mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
feat: add plugin application runtime and unified instance authorization
This commit is contained in:
1 parent
8bca848c21
commit
3430a8a753
80 files changed
+2133
-1004
No files matched your search
@@ -1,10 +1,11 @@
|
||||
import { Router, type RequestHandler } from "express";
|
||||
import express, { Router, type RequestHandler } from "express";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PluginStore } from "./store.js";
|
||||
import type { PluginRuntime } from "./runtime.js";
|
||||
import { pluginAssert, pluginRecord, PluginError, parsePluginPackage } from "../shared/plugins.js";
|
||||
|
||||
export function createPluginAdminRouter(options: {
|
||||
registry?: PluginRegistry; store?: PluginStore; protect: RequestHandler[];
|
||||
registry?: PluginRegistry; store?: PluginStore; runtime?: PluginRuntime; protect: RequestHandler[];
|
||||
audit(event: string, data: { id: string; version?: string }): void;
|
||||
}) {
|
||||
const router = Router(), store = options.store ?? new PluginStore();
|
||||
@@ -14,13 +15,21 @@ export function createPluginAdminRouter(options: {
|
||||
// Reuse the admin session's same-origin and CSRF rules for every write.
|
||||
writeGuard(request, response, next);
|
||||
});
|
||||
// The parent authenticates before parsing a potentially large application bundle.
|
||||
router.use(express.json({limit:"50mb"}));
|
||||
const registry = () => { pluginAssert(options.registry, "PLUGIN_STORAGE_UNAVAILABLE"); return options.registry; };
|
||||
router.get("/", (_request, response) => response.json({ plugins: registry().list() }));
|
||||
const project=(plugin:ReturnType<PluginRegistry["list"]>[number])=>({...plugin,runtime:options.runtime?.status(plugin.manifest.id)??{state:plugin.settings.enabled?(plugin.manifest.server?"stopped":"client"):"disabled"}});
|
||||
router.get("/", (_request, response) => response.json({ plugins: registry().list().map(project) }));
|
||||
router.get("/runtime",(_request,response)=>{pluginAssert(options.runtime,"PLUGIN_RUNTIME_UNAVAILABLE");response.json({runtime:options.runtime.settings()});});
|
||||
router.put("/runtime",async(request,response)=>{
|
||||
pluginAssert(options.runtime&&pluginRecord(request.body));const runtime=await options.runtime.configureOrigin(request.body.publicOrigin,request.body.revision);
|
||||
options.audit("ADMIN_PLUGIN_RUNTIME_CONFIGURED",{id:"runtime"});response.json({runtime});
|
||||
});
|
||||
router.get("/store", async (_request, response) => { response.json(await store.list()); });
|
||||
router.post("/store/install", async (request, response) => {
|
||||
const plugin = await store.install(registry(), request.body);
|
||||
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
|
||||
response.status(201).json({ plugin });
|
||||
response.status(201).json({ plugin:project(plugin) });
|
||||
});
|
||||
router.post("/upload", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body));
|
||||
@@ -28,22 +37,30 @@ export function createPluginAdminRouter(options: {
|
||||
pluginAssert(expected === null || typeof expected === "string");
|
||||
const plugin = await registry().install(parsePluginPackage(request.body.package), expected);
|
||||
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
|
||||
response.status(201).json({ plugin });
|
||||
response.status(201).json({ plugin:project(plugin) });
|
||||
});
|
||||
router.put("/:id/settings", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
|
||||
const plugin = await registry().configure(String(request.params.id), request.body.settings, request.body.revision);
|
||||
await options.runtime?.synchronize(plugin.manifest.id);
|
||||
options.audit("ADMIN_PLUGIN_CONFIGURED", { id: plugin.manifest.id });
|
||||
response.json({ plugin });
|
||||
response.json({ plugin:project(plugin) });
|
||||
});
|
||||
router.post("/:id/restart",async(request,response)=>{
|
||||
pluginAssert(options.runtime&&pluginRecord(request.body));const id=String(request.params.id),plugin=registry().policy(id);
|
||||
pluginAssert(plugin,"PLUGIN_NOT_FOUND");pluginAssert(plugin.revision===request.body.revision,"PLUGIN_CHANGED");pluginAssert(plugin.settings.enabled&&plugin.settings.trusted,"PLUGIN_DISABLED");
|
||||
await options.runtime.restart(id);options.audit("ADMIN_PLUGIN_RESTARTED",{id});response.json({plugin:project(plugin)});
|
||||
});
|
||||
router.delete("/:id", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
|
||||
await registry().remove(String(request.params.id), request.body.revision);
|
||||
await options.runtime?.synchronize(String(request.params.id));
|
||||
options.audit("ADMIN_PLUGIN_REMOVED", { id: String(request.params.id) }); response.json({ ok: true });
|
||||
});
|
||||
router.use((error: unknown, _request: unknown, response: import("express").Response, _next: unknown) => {
|
||||
const code = error instanceof PluginError ? error.code : "PLUGIN_FAILED";
|
||||
response.status(code === "PLUGIN_STORE_UNAVAILABLE" ? 502 : code === "PLUGIN_NOT_FOUND" ? 404 : code === "PLUGIN_CHANGED" ? 409 : 400).json({ ok: false, code });
|
||||
const tooLarge=pluginRecord(error)&&error.type==="entity.too.large";
|
||||
const code = tooLarge?"PLUGIN_TOO_LARGE":error instanceof PluginError ? error.code : "PLUGIN_FAILED";
|
||||
response.status(tooLarge?413:code === "PLUGIN_STORE_UNAVAILABLE" ? 502 : code === "PLUGIN_NOT_FOUND" ? 404 : code === "PLUGIN_CHANGED" ? 409 : 400).json({ ok: false, code });
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { parsePluginRequest, pluginAssert, PluginError, type PluginMessage, type JsonValue, type PluginRequest, type PluginRoomSnapshot } from "../shared/plugins.js";
|
||||
|
||||
export interface PluginParticipant {
|
||||
id: string; nickname: string; target: TeamSpeakTarget;
|
||||
session: { state: string };
|
||||
tsClient: { getChannelId(): bigint; isConnected(): boolean };
|
||||
}
|
||||
interface Membership { room: string; packageRevision: string }
|
||||
interface Room { id: string; state: JsonValue; revision: number; members: Set<string>; writeWindow: number; writes: number }
|
||||
/** Generic bounded JSON rooms. No package code or video-specific behavior runs on the server. */
|
||||
export class PluginCoordinator {
|
||||
private readonly rooms = new Map<string, Room>();
|
||||
private readonly memberships = new Map<string, Map<string, Membership>>();
|
||||
private readonly limits = new Map<string, { time: number; count: number }>();
|
||||
private readonly changed = (id: string) => {
|
||||
for (const [entryId, memberships] of [...this.memberships]) if (memberships.has(id)) this.leave(entryId, id, "PLUGIN_CHANGED");
|
||||
};
|
||||
constructor(private readonly registry: PluginRegistry | undefined, private readonly entries: ReadonlyMap<string, PluginParticipant>,
|
||||
private readonly send: (entryId: string, message: PluginMessage) => void) { registry?.listeners.add(this.changed); }
|
||||
private key(entry: PluginParticipant, id: string): string {
|
||||
const plugin = this.registry?.policy(id); pluginAssert(plugin?.settings.enabled, "PLUGIN_DISABLED");
|
||||
pluginAssert(entry.session.state === "connected" && entry.tsClient.isConnected(), "PLUGIN_NOT_CONNECTED");
|
||||
if (plugin.settings.scope === "instance") return `${id}\u0000instance`;
|
||||
const target = teamSpeakTargetKey(entry.target);
|
||||
pluginAssert(plugin.settings.targets.includes(target), "PLUGIN_NOT_ALLOWED");
|
||||
return `${id}\u0000${target}\u0000${entry.tsClient.getChannelId()}`;
|
||||
}
|
||||
private snapshot(room: Room): PluginRoomSnapshot {
|
||||
return { roomId: room.id, revision: room.revision, state: structuredClone(room.state), serverTime: Date.now(),
|
||||
participants: [...room.members].flatMap(id => { const e = this.entries.get(id); return e ? [{ id, nickname: e.nickname }] : []; }) };
|
||||
}
|
||||
private broadcast(key: string, id: string): void {
|
||||
const room = this.rooms.get(key); if (!room) return;
|
||||
for (const entryId of [...room.members]) {
|
||||
const entry = this.entries.get(entryId); let valid = false;
|
||||
try { valid = !!entry && this.key(entry, id) === key; } catch { /* stale scope */ }
|
||||
if (!valid) this.leave(entryId, id, "PLUGIN_CONTEXT_CHANGED", false);
|
||||
}
|
||||
const snapshot = this.snapshot(room);
|
||||
if (this.registry?.policy(id)?.manifest.permissions.includes("room.read"))
|
||||
for (const entryId of room.members) this.send(entryId, { type: "pluginEvent", pluginId: id, snapshot });
|
||||
}
|
||||
handle(entry: PluginParticipant, value: unknown): void {
|
||||
let request: PluginRequest;
|
||||
try { request = parsePluginRequest(value); }
|
||||
catch { return; }
|
||||
const reply = (ok: boolean, result?: unknown, code?: string) => this.send(entry.id, { type: "pluginReply", requestId: request.requestId, ok, ...(ok ? { result } : { code }) });
|
||||
try {
|
||||
const limit = this.limits.get(entry.id), now = Date.now();
|
||||
if (!limit || now - limit.time > 1000) this.limits.set(entry.id, { time: now, count: 1 });
|
||||
else if (request.action !== "close") pluginAssert(++limit.count <= 20, "PLUGIN_RATE_LIMITED");
|
||||
pluginAssert(entry.session.state === "connected" && entry.tsClient.isConnected(), "PLUGIN_NOT_CONNECTED");
|
||||
if (request.action === "list") {
|
||||
const plugins = (this.registry?.list() ?? []).filter(p => { try { this.key(entry, p.manifest.id); return true; } catch { return false; } });
|
||||
reply(true, plugins.map(p => ({ manifest: p.manifest, revision: p.revision, scope: p.settings.scope }))); return;
|
||||
}
|
||||
const id = request.pluginId!;
|
||||
if (request.action === "close") { this.leave(entry.id, id); reply(true, null); return; }
|
||||
const key = this.key(entry, id), plugin = this.registry!.policy(id)!;
|
||||
const memberships = this.memberships.get(entry.id) ?? new Map<string, Membership>();
|
||||
const previous = memberships.get(id);
|
||||
if (previous && (previous.room !== key || previous.packageRevision !== plugin.revision)) this.leave(entry.id, id, "PLUGIN_CONTEXT_CHANGED");
|
||||
if (request.action === "open") {
|
||||
pluginAssert(memberships.size < 8 || memberships.has(id), "PLUGIN_LIMIT");
|
||||
let room = this.rooms.get(key);
|
||||
if (!room) { pluginAssert(this.rooms.size < 800, "PLUGIN_LIMIT"); room = { id: randomUUID(), state: null, revision: 0, members: new Set(), writeWindow: 0, writes: 0 }; this.rooms.set(key, room); }
|
||||
const current = this.memberships.get(entry.id) ?? new Map<string, Membership>();
|
||||
current.set(id, { room: key, packageRevision: plugin.revision }); this.memberships.set(entry.id, current); room.members.add(entry.id);
|
||||
const snapshot = plugin.manifest.permissions.includes("room.read") ? this.snapshot(room)
|
||||
: { roomId: room.id, revision: 0, state: null, serverTime: Date.now(), participants: [] };
|
||||
reply(true, { package: this.registry!.get(id)!.package, config: plugin.settings.config, self: { id: entry.id, nickname: entry.nickname }, scope: plugin.settings.scope, snapshot });
|
||||
this.broadcast(key, id); return;
|
||||
}
|
||||
const membership = this.memberships.get(entry.id)?.get(id);
|
||||
pluginAssert(membership?.room === key && membership.packageRevision === plugin.revision, "PLUGIN_NOT_OPEN");
|
||||
const room = this.rooms.get(key)!;
|
||||
pluginAssert(plugin.manifest.permissions.includes("room.read"), "PLUGIN_PERMISSION_DENIED");
|
||||
if (request.action === "update") {
|
||||
pluginAssert(plugin.manifest.permissions.includes("room.write"), "PLUGIN_PERMISSION_DENIED");
|
||||
pluginAssert(request.revision === room.revision, "PLUGIN_REVISION_CONFLICT");
|
||||
if (now - room.writeWindow >= 1000) { room.writeWindow = now; room.writes = 0; }
|
||||
pluginAssert(++room.writes <= 10, "PLUGIN_RATE_LIMITED");
|
||||
room.state = request.state!; room.revision++;
|
||||
}
|
||||
reply(true, this.snapshot(room)); if (request.action === "update") this.broadcast(key, id);
|
||||
} catch (error) { reply(false, undefined, error instanceof PluginError ? error.code : "PLUGIN_FAILED"); }
|
||||
}
|
||||
private leave(entryId: string, id: string, code?: string, broadcast = true): void {
|
||||
const memberships = this.memberships.get(entryId), membership = memberships?.get(id); if (!membership) return;
|
||||
memberships!.delete(id); if (!memberships!.size) this.memberships.delete(entryId);
|
||||
const room = this.rooms.get(membership.room); room?.members.delete(entryId);
|
||||
if (!room?.members.size) this.rooms.delete(membership.room);
|
||||
if (code) this.send(entryId, { type: "pluginEvent", pluginId: id, snapshot: null, code });
|
||||
if (broadcast) this.broadcast(membership.room, id);
|
||||
}
|
||||
remove(entryId: string): void { for (const id of [...(this.memberships.get(entryId)?.keys() ?? [])]) this.leave(entryId, id, "PLUGIN_CONTEXT_CHANGED"); this.limits.delete(entryId); }
|
||||
reconcile(entry: PluginParticipant): void {
|
||||
for (const [id, membership] of [...(this.memberships.get(entry.id) ?? [])]) {
|
||||
try { if (this.key(entry, id) !== membership.room) this.leave(entry.id, id, "PLUGIN_CONTEXT_CHANGED"); }
|
||||
catch { this.leave(entry.id, id, "PLUGIN_CONTEXT_CHANGED"); }
|
||||
}
|
||||
}
|
||||
dispose(): void { this.registry?.listeners.delete(this.changed); this.memberships.clear(); this.rooms.clear(); this.limits.clear(); }
|
||||
}
|
||||
+52
-102
@@ -3,113 +3,63 @@ import test from 'node:test';
|
||||
import { mkdtemp, rm, readFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { PluginRegistry } from './registry.js';
|
||||
import { PluginCoordinator, type PluginParticipant } from './coordinator.js';
|
||||
import { PluginStore } from './store.js';
|
||||
import { parsePluginPackage, parsePluginJson, parsePluginRequest, PLUGIN_STORE_INDEX, type PluginMessage } from '../shared/plugins.js';
|
||||
import { PluginProcess } from './process.js';
|
||||
import { parsePluginPackage, parsePluginJson, pluginPath, pluginFileBytes, type PluginPackage, type PluginAppContext } from '../shared/plugins.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
|
||||
const example = () => readFile(new URL('../../docs/examples/watch-together.wplugin',import.meta.url),'utf8').then(t => parsePluginPackage(JSON.parse(t)));
|
||||
async function registry(t: test.TestContext) {
|
||||
const directory = await mkdtemp(path.join(tmpdir(),'webspeak-plugins-'));
|
||||
t.after(async () => { assert.equal(path.dirname(directory), tmpdir()); await rm(directory,{recursive:true,force:true}); });
|
||||
const value = new PluginRegistry(directory); await value.initialize(); return { value, directory };
|
||||
}
|
||||
function participant(id: string, host='one.example', channel=1n): PluginParticipant {
|
||||
return {id,nickname:id,target:{host,port:9987},session:{state:'connected'},tsClient:{getChannelId:()=>channel,isConnected:()=>true}};
|
||||
}
|
||||
test('package and state validators reject unsupported APIs, capabilities, prototype keys and excessive nesting',async () => {
|
||||
const pack = await example(); assert.equal(pack.manifest.apiVersion,1);
|
||||
assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,apiVersion:2}}));
|
||||
assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,permissions:['admin.query']}}));
|
||||
assert.throws(()=>parsePluginPackage({...pack,styles:{light:'x',dark:''}}));
|
||||
assert.throws(()=>parsePluginJson(JSON.parse('{"__proto__":{"x":1}}')));
|
||||
assert.throws(()=>parsePluginJson(Array.from({length:5000},()=>1)));
|
||||
assert.throws(()=>parsePluginJson({number:Infinity}));
|
||||
assert.throws(()=>parsePluginRequest({type:'pluginRequest',requestId:'a',action:'update',pluginId:'a',revision:-1,state:null}));
|
||||
export const fixturePackage = (server?:string):PluginPackage => parsePluginPackage({manifest:{apiVersion:2,id:'test.application',name:'Application',version:'1.0.0',author:'Tests',license:'MIT',description:'Independent application fixture',scopes:['server','instance'],client:{entry:'client/index.html'},...(server?{server:{entry:'server/main.mjs'}}:{})},files:{'client/index.html':{encoding:'utf8',data:'<!doctype html><html><head></head><body><script type="module" src="./app.js"></script></body></html>'},'client/app.js':{encoding:'utf8',data:'document.body.dataset.ready="yes"'},...(server?{'server/main.mjs':{encoding:'utf8',data:server}}:{})}});
|
||||
async function registry(t:test.TestContext){const directory=await mkdtemp(path.join(tmpdir(),'webspeak-app-v2-'));const cleanup:Array<()=>Promise<unknown>>=[];t.after(async()=>{for(const dispose of cleanup)await dispose();assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});const value=new PluginRegistry(directory,Buffer.alloc(32,7));await value.initialize();return {value,directory,cleanup};}
|
||||
|
||||
test('v2 accepts ordinary application assets and rejects the obsolete room protocol',()=>{
|
||||
const pack=fixturePackage();assert.equal(pack.manifest.apiVersion,2);assert.ok(pack.files['client/app.js']);
|
||||
assert.throws(()=>parsePluginPackage({manifest:{...pack.manifest,apiVersion:1},html:'x',script:'x',styles:{light:'x',dark:'x'}}),/PLUGIN_API_UNSUPPORTED/);
|
||||
assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,permissions:['room.read']}}),/PLUGIN_API_UNSUPPORTED/);
|
||||
const binary=parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'AAEC/w=='}}});assert.deepEqual([...pluginFileBytes(binary.files['client/asset.bin'])],[0,1,2,255]);
|
||||
assert.throws(()=>parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'!notbase64'}}}));
|
||||
});
|
||||
test('atomic persistence retains settings, requires CAS and disables code updates until reviewed',async t => {
|
||||
const {value:r,directory} = await registry(t); const pack=await example();
|
||||
const first=await r.install(pack,null); assert.equal(first.settings.enabled,false);
|
||||
const enabled=await r.configure(pack.manifest.id,{enabled:true,scope:'server',targets:['ONE.example#9987'],config:{title:'Public'}},first.revision);
|
||||
assert.deepEqual(enabled.settings.targets,['one.example:9987']);
|
||||
await assert.rejects(r.configure(pack.manifest.id,enabled.settings,first.revision),/PLUGIN_CHANGED/);
|
||||
const reload=new PluginRegistry(directory); await reload.initialize(); assert.deepEqual(reload.list(),r.list());
|
||||
const updated=await r.install({...pack,script:'throw new Error("must never run on server")'},enabled.revision);
|
||||
assert.equal(updated.settings.enabled,false); assert.deepEqual(updated.settings.config,{title:'Public'});
|
||||
await assert.rejects(r.remove(pack.manifest.id,enabled.revision),/PLUGIN_CHANGED/);
|
||||
await r.remove(pack.manifest.id,updated.revision); assert.equal(r.list().length,0);
|
||||
await assert.rejects(r.install({...pack,manifest:{...pack.manifest,id:'../../escape'}},null));
|
||||
test('package paths reject traversal, Windows special names, case collisions and file-directory aliases',()=>{
|
||||
for(const name of ['../a','client/../a','client/a\\b','client/CON.txt','client/aux','client/a.','/client/a'])assert.equal(pluginPath(name),false,name);
|
||||
const pack=fixturePackage();
|
||||
for(const files of [{...pack.files,'client/APP.js':{encoding:'utf8',data:'x'}},{...pack.files,'client/folder':{encoding:'utf8',data:'x'},'client/folder/file.js':{encoding:'utf8',data:'x'}}])assert.throws(()=>parsePluginPackage({...pack,files}));
|
||||
assert.throws(()=>parsePluginJson(JSON.parse('{"__proto__":{"value":1}}')));assert.throws(()=>parsePluginJson({n:Infinity}));
|
||||
});
|
||||
test('server rooms synchronize state with CAS, isolate target/channel, expire on moves and revoke on disable',async t => {
|
||||
const {value:r}=await registry(t), pack=await example(), p=await r.install(pack,null);
|
||||
const enabled=await r.configure(pack.manifest.id,{enabled:true,scope:'server',targets:['one.example:9987','two.example:9987'],config:{}},p.revision);
|
||||
const entries=new Map([participant('a'),participant('b'),participant('c','one.example',2n),participant('d','two.example')].map(e=>[e.id,e]));
|
||||
const messages:{id:string;message:PluginMessage}[]=[];
|
||||
const c=new PluginCoordinator(r,entries,(id,message)=>messages.push({id,message})); t.after(()=>c.dispose());
|
||||
let seq=0; const send=(id:string,action:string,fields={})=>{c.handle(entries.get(id)!,{type:'pluginRequest',requestId:`r-${++seq}`,action,pluginId:pack.manifest.id,...fields}); return messages.filter(v=>v.id===id&&v.message.type==='pluginReply').at(-1)!.message as Extract<PluginMessage,{type:'pluginReply'}>;};
|
||||
const a=send('a','open').result as any, b=send('b','open').result as any;
|
||||
assert.equal(a.snapshot.roomId,b.snapshot.roomId); assert.notEqual((send('c','open').result as any).snapshot.roomId,a.snapshot.roomId);
|
||||
assert.notEqual((send('d','open').result as any).snapshot.roomId,a.snapshot.roomId);
|
||||
const state={url:'https://video.example/a.mp4',position:5,playing:true,updatedAt:Date.now()};
|
||||
assert.equal(send('a','update',{revision:0,state}).ok,true);
|
||||
assert.equal(send('b','update',{revision:0,state:{position:9}}).code,'PLUGIN_REVISION_CONFLICT');
|
||||
assert.deepEqual((send('b','snapshot').result as any).state,state);
|
||||
assert.equal(messages.some(v=>v.id==='c'&&v.message.type==='pluginEvent'&&v.message.snapshot?.state && (v.message.snapshot.state as any).url),false);
|
||||
entries.get('a')!.tsClient.getChannelId=()=>2n; c.reconcile(entries.get('a')!);
|
||||
assert.equal(send('a','snapshot').code,'PLUGIN_NOT_OPEN');
|
||||
assert.equal((send('b','snapshot').result as any).participants.length,1);
|
||||
await r.configure(pack.manifest.id,{...enabled.settings,enabled:false},enabled.revision);
|
||||
assert.equal(send('b','open').code,'PLUGIN_DISABLED');
|
||||
assert.ok(messages.some(v=>v.id==='b'&&v.message.type==='pluginEvent'&&v.message.snapshot===null));
|
||||
test('install and update require explicit trust, encrypt private config and preserve CAS/persistence',async t=>{
|
||||
const {value:r,directory}=await registry(t),pack=fixturePackage();const first=await r.install(pack,null);
|
||||
assert.equal(first.settings.enabled,false);assert.equal(first.settings.trusted,false);
|
||||
await assert.rejects(r.configure(pack.manifest.id,{enabled:true,trusted:false,scope:'instance',targets:[],config:{}},first.revision),/PLUGIN_TRUST_REQUIRED/);
|
||||
const enabled=await r.configure(pack.manifest.id,{enabled:true,trusted:true,scope:'server',targets:['EXAMPLE.com#9987'],config:{public:'value'},serverConfigAction:'replace',serverConfig:{secret:'private-fixture-value'}},first.revision);
|
||||
assert.deepEqual(enabled.settings.targets,['example.com:9987']);assert.equal(enabled.settings.hasServerConfig,true);assert.equal(JSON.stringify(enabled).includes('private-fixture-value'),false);
|
||||
const record=await readFile(path.join(directory,'installed',pack.manifest.id+'.json'),'utf8');assert.equal(record.includes('private-fixture-value'),false);assert.deepEqual(r.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
|
||||
await assert.rejects(r.configure(pack.manifest.id,enabled.settings,first.revision),/PLUGIN_CHANGED/);
|
||||
const reloaded=new PluginRegistry(directory,Buffer.alloc(32,7));await reloaded.initialize();assert.deepEqual(reloaded.list(),r.list());assert.deepEqual(reloaded.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
|
||||
const update=await r.install({...pack,manifest:{...pack.manifest,version:'1.1.0'}},enabled.revision);assert.equal(update.settings.enabled,false);assert.equal(update.settings.trusted,false);assert.equal(update.settings.hasServerConfig,true);
|
||||
const cleared=await r.configure(pack.manifest.id,{...update.settings,serverConfigAction:'remove'},update.revision);assert.equal(cleared.settings.hasServerConfig,false);
|
||||
await r.remove(pack.manifest.id,cleared.revision);assert.equal(r.list().length,0);
|
||||
});
|
||||
test('instance rooms span targets but session readiness, write permission, quotas and teardown are enforced',async t => {
|
||||
const {value:r}=await registry(t), pack=await example(), p=await r.install(pack,null);
|
||||
const enabled=await r.configure(pack.manifest.id,{enabled:true,scope:'instance',targets:[],config:{}},p.revision);
|
||||
const a=participant('a'),b=participant('b','another.example',5n), entries=new Map([[a.id,a],[b.id,b]]);
|
||||
const messages:PluginMessage[]=[];const c=new PluginCoordinator(r,entries,(_id,m)=>messages.push(m));t.after(()=>c.dispose());
|
||||
let sequence=0;function send(e:PluginParticipant,action:string,fields={}){c.handle(e,{type:'pluginRequest',requestId:`r-${++sequence}`,pluginId:pack.manifest.id,action,...fields});return messages.filter(m=>m.type==='pluginReply').at(-1) as Extract<PluginMessage,{type:'pluginReply'}>;}
|
||||
const first=send(a,'open').result as any;assert.equal((send(b,'open').result as any).snapshot.roomId,first.snapshot.roomId);
|
||||
send(a,'update',{revision:0,state:{progress:30}});c.remove(a.id);
|
||||
assert.deepEqual((send(b,'snapshot').result as any).state,{progress:30}); c.remove(b.id);
|
||||
assert.equal((send(a,'open').result as any).snapshot.state,null);
|
||||
a.session.state='reconnecting';assert.equal(send(a,'update',{revision:0,state:0}).code,'PLUGIN_NOT_CONNECTED');a.session.state='connected';
|
||||
const next=await r.install({...pack,manifest:{...pack.manifest,permissions:['room.read']}},enabled.revision);
|
||||
await r.configure(pack.manifest.id,{...next.settings,enabled:true},next.revision);send(a,'open');assert.equal(send(a,'update',{revision:0,state:0}).code,'PLUGIN_PERMISSION_DENIED');
|
||||
for(let i=0;i<30;i++)send(a,'list');assert.equal((messages.filter(m=>m.type==='pluginReply').at(-1) as any).code,'PLUGIN_RATE_LIMITED');
|
||||
});
|
||||
test('GitHub distribution checks package hashes and reviewed metadata; redirects/arbitrary sources are rejected',async t => {
|
||||
const {value:r}=await registry(t), pack=await example(), bytes=Buffer.from(JSON.stringify(pack));
|
||||
const repository='https://github.com/Huddle-Up-Forge/webspeak-plugin';let corrupt=false;
|
||||
const metadata={manifest:pack.manifest,package:{ref:'main',path:'watch-together.wplugin',sha256:createHash('sha256').update(bytes).digest('hex')}};
|
||||
const visited:string[]=[];
|
||||
const store=new PluginStore(async(input,init)=>{
|
||||
const url=String(input);visited.push(url);assert.equal(init?.redirect,'error');assert.equal(init?.credentials,'omit');
|
||||
if(url===PLUGIN_STORE_INDEX)return Response.json({schemaVersion:1,plugins:[{id:pack.manifest.id,repository}]});
|
||||
if(url.endsWith('/HEAD/plugin.json'))return Response.json(metadata);
|
||||
return new Response(corrupt?'{}':bytes);
|
||||
});
|
||||
const entry=(await store.list()).entries[0];assert.equal(entry.error,null);
|
||||
const installed=await store.install(r,{id:entry.id,revision:entry.revision,installedRevision:null});assert.equal(installed.settings.enabled,false);
|
||||
corrupt=true;await assert.rejects(store.install(r,{id:entry.id,revision:entry.revision,installedRevision:installed.revision}),/PLUGIN_CHECKSUM/);
|
||||
await assert.rejects(store.install(r,{id:entry.id,revision:'a'.repeat(64),installedRevision:installed.revision}),/PLUGIN_CHANGED/);
|
||||
const bad=new PluginStore(async()=>Response.json({schemaVersion:1,plugins:[{id:'evil',repository:'http://127.0.0.1:3040'}]}));
|
||||
await assert.rejects(bad.list(),/PLUGIN_INVALID/);assert.ok(visited.every(u=>u.startsWith('https://raw.githubusercontent.com/')));
|
||||
test('materialized applications contain their own files and package integrity is checked',async t=>{
|
||||
const {value:r}=await registry(t),pack=fixturePackage();const installed=await r.install(pack,null);const directory=await r.materialize(pack.manifest.id,installed.revision);
|
||||
assert.match(await readFile(path.join(directory,'client/index.html'),'utf8'),/type="module"/);
|
||||
await assert.rejects(r.releaseCode(path.resolve(directory,'../../../../unrelated')),/PLUGIN_INVALID/);
|
||||
await r.releaseCode(directory);await assert.rejects(readFile(path.join(directory,'client/index.html')));
|
||||
});
|
||||
|
||||
test('a UI-only plugin opens without shared data access, and read snapshots never broadcast to others',async t=>{
|
||||
const {value:r}=await registry(t),examplePack=await example();
|
||||
const pack={...examplePack,manifest:{...examplePack.manifest,permissions:[]}};
|
||||
const p=await r.install(pack,null);await r.configure(pack.manifest.id,{enabled:true,scope:'instance',targets:[],config:{}},p.revision);
|
||||
const a=participant('a'),b=participant('b'),entries=new Map([[a.id,a],[b.id,b]]);const messages:{id:string;message:PluginMessage}[]=[];
|
||||
const c=new PluginCoordinator(r,entries,(id,message)=>messages.push({id,message}));t.after(()=>c.dispose());
|
||||
let seq=0;const send=(id:string,action:string,fields={})=>{c.handle(entries.get(id)!,{type:'pluginRequest',requestId:`r-${++seq}`,pluginId:pack.manifest.id,action,...fields});return messages.filter(m=>m.id===id&&m.message.type==='pluginReply').at(-1)!.message as Extract<PluginMessage,{type:'pluginReply'}>;};
|
||||
const open=send('a','open');assert.equal(open.ok,true);assert.deepEqual((open.result as any).snapshot.participants,[]);
|
||||
assert.equal(send('a','snapshot').code,'PLUGIN_PERMISSION_DENIED');assert.equal(send('a','update',{revision:0,state:1}).code,'PLUGIN_PERMISSION_DENIED');
|
||||
const updated=await r.install(examplePack,r.list()[0].revision);await r.configure(pack.manifest.id,{...updated.settings,enabled:true},updated.revision);
|
||||
send('a','open');send('b','open');const before=messages.length;send('a','snapshot');assert.equal(messages.length,before+1);
|
||||
for(let revision=0;revision<10;revision++)assert.equal(send('a','update',{revision,state:revision}).ok,true);
|
||||
assert.equal(send('b','update',{revision:10,state:11}).code,'PLUGIN_RATE_LIMITED');
|
||||
for(let i=0;i<20;i++)send('a','list');assert.equal(send('a','close').ok,true);
|
||||
assert.equal((send('b','snapshot').result as any).participants.length,1);
|
||||
test('a backend runs native Node filesystem and arbitrary HTTP handlers in an independent process',async t=>{
|
||||
const {value:r,cleanup}=await registry(t);
|
||||
const source=`import {writeFile,readFile} from 'node:fs/promises';import path from 'node:path';export default async ({dataDir,config})=>{let count=Number(await readFile(path.join(dataDir,'counter.txt'),'utf8').catch(()=>0));return {handle:async(req,res)=>{count++;await writeFile(path.join(dataDir,'counter.txt'),String(count));res.setHeader('content-type','application/json');res.end(JSON.stringify({path:req.url,user:req.webspeak.self.id,configured:config.secret==='private',count,pid:process.pid}));}};};`;
|
||||
const pack=fixturePackage(source),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision),data=await r.dataDirectory(pack.manifest.id);
|
||||
const processes:PluginProcess[]=[];cleanup.push(async()=>{await Promise.all(processes.map(p=>p.close()));});
|
||||
const run=()=>{const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:data,config:{secret:'private'},publicConfig:{},logger:createLogger(),onExit:()=>{}});processes.push(child);return child;};
|
||||
const child=run();await child.ready;assert.ok(child.child.pid&&child.child.pid!==process.pid);
|
||||
const context={apiVersion:2,self:{id:'participant-a'},scope:{key:'instance'}} as PluginAppContext;
|
||||
const request=()=>fetch(`http://127.0.0.1:${child.port}/author-defined/path`,{headers:{'x-webspeak-runtime':child.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});
|
||||
assert.equal((await fetch(`http://127.0.0.1:${child.port}/author-defined/path`)).status,403);
|
||||
const value=await(await request()).json();assert.equal(value.path,'/author-defined/path');assert.equal(value.user,'participant-a');assert.equal(value.configured,true);assert.equal(value.count,1);
|
||||
await child.close();const replacement=run();await replacement.ready;
|
||||
const next=await fetch(`http://127.0.0.1:${replacement.port}/another-route`,{headers:{'x-webspeak-runtime':replacement.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});assert.equal((await next.json()).count,2);
|
||||
});
|
||||
test('a failed or hung plugin activation is bounded and does not execute in the gateway process',async t=>{
|
||||
const {value:r,cleanup}=await registry(t),pack=fixturePackage('export default async()=>new Promise(()=>{});'),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision);
|
||||
const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:await r.dataDirectory(pack.manifest.id),config:{},publicConfig:{},logger:createLogger(),onExit:()=>{},startupMs:1000});
|
||||
cleanup.push(()=>child.close());await assert.rejects(child.ready,/PLUGIN_START_TIMEOUT/);await child.close();assert.notEqual(child.child.exitCode,null);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { PluginError, pluginRecord, type JsonValue } from "../shared/plugins.js";
|
||||
|
||||
export class PluginProcess {
|
||||
readonly token = randomBytes(32).toString("base64url");
|
||||
readonly child: ChildProcess;
|
||||
readonly ready: Promise<number>;
|
||||
readonly exited: Promise<void>;
|
||||
port = 0;
|
||||
private stopping = false;
|
||||
private finished = false;
|
||||
private closePromise?: Promise<void>;
|
||||
constructor(options: {
|
||||
entry: string; codeDirectory: string; dataDirectory: string; config: JsonValue; publicConfig: JsonValue;
|
||||
logger: Logger; onExit(): void; startupMs?: number;
|
||||
}) {
|
||||
const typescript = import.meta.url.endsWith(".ts");
|
||||
const worker = fileURLToPath(new URL(typescript ? "./worker.ts" : "./worker.js", import.meta.url));
|
||||
const execArgv = [...(typescript ? ["--import", import.meta.resolve("tsx")] : []), "--max-old-space-size=256"];
|
||||
// Separate process and reduced environment; reviewed backend code still has the OS user's permissions.
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const key of ["PATH", "Path", "SystemRoot", "WINDIR", "TEMP", "TMP", "LANG", "NODE_EXTRA_CA_CERTS"]) if (process.env[key]) env[key] = process.env[key];
|
||||
this.child = spawn(process.execPath, [...execArgv, worker], { cwd: options.codeDirectory, env, windowsHide: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
|
||||
let resolveExit!: () => void;
|
||||
this.exited = new Promise(resolve => { resolveExit = resolve; });
|
||||
let resolveReady!: (port: number) => void, rejectReady!: (error: Error) => void;
|
||||
this.ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const timer = setTimeout(() => { rejectReady(new PluginError("PLUGIN_START_TIMEOUT")); void this.close(); }, options.startupMs ?? 10000);
|
||||
let logWindow = Date.now(), logs = 0;
|
||||
this.child.on("message", value => {
|
||||
if (!pluginRecord(value) || this.stopping) return;
|
||||
if (value.type === "ready" && Number.isInteger(value.port) && Number(value.port) > 0 && Number(value.port) <= 65535) {
|
||||
clearTimeout(timer); this.port = Number(value.port); resolveReady(this.port);
|
||||
} else if (value.type === "failed") {
|
||||
clearTimeout(timer); rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close();
|
||||
} else if (value.type === "log" && typeof value.message === "string") {
|
||||
if (Date.now() - logWindow > 1000) { logWindow = Date.now(); logs = 0; }
|
||||
if (++logs <= 20) options.logger.debug({ message: value.message.slice(0, 1000) }, "Plugin application log");
|
||||
}
|
||||
});
|
||||
const finish = () => {
|
||||
if (this.finished) return; this.finished = true; clearTimeout(timer);
|
||||
rejectReady(new PluginError(this.stopping ? "PLUGIN_STOPPED" : "PLUGIN_PROCESS_EXITED"));
|
||||
resolveExit(); if (!this.stopping) options.onExit();
|
||||
};
|
||||
this.child.once("error", finish); this.child.once("exit", finish);
|
||||
this.child.send({ type: "initialize", entry: options.entry, dataDir: options.dataDirectory, config: options.config, publicConfig: options.publicConfig, token: this.token }, error => {
|
||||
if (error) { rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close(); }
|
||||
});
|
||||
}
|
||||
event(name: string, payload: unknown): void {
|
||||
if (this.stopping || this.finished || !this.child.connected) return;
|
||||
try { this.child.send({ type: "event", name, payload }, () => undefined); } catch { /* Retired worker. */ }
|
||||
}
|
||||
close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.stopping = true;
|
||||
this.closePromise = (async () => {
|
||||
if (this.finished) return;
|
||||
if (this.child.connected) { try { this.child.send({ type: "stop" }, () => undefined); } catch {} }
|
||||
const killer = setTimeout(() => this.child.kill("SIGKILL"), 2000);
|
||||
try { await this.exited; } finally { clearTimeout(killer); }
|
||||
})();
|
||||
return this.closePromise;
|
||||
}
|
||||
}
|
||||
+80
-66
@@ -1,84 +1,98 @@
|
||||
import { mkdir, readFile, readdir, writeFile, rename, unlink } from "node:fs/promises";
|
||||
import { mkdir, readFile, readdir, writeFile, rename, unlink, mkdtemp, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
|
||||
import { parsePluginPackage, parsePluginJson, pluginAssert, pluginId, pluginRecord, PluginError, PLUGIN_LIMIT_BYTES,
|
||||
type InstalledPlugin, type PluginPackage, type PluginSettings } from "../shared/plugins.js";
|
||||
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
|
||||
import { loadOrCreateMasterSecret } from "../security/master-secret.js";
|
||||
import { parsePluginPackage, parsePluginManifest, parsePluginJson, pluginAssert, pluginId, pluginRecord, pluginFileBytes, PluginError, PLUGIN_LIMIT_BYTES,
|
||||
type InstalledPlugin, type PluginPackage, type PluginSettings, type JsonValue } from "../shared/plugins.js";
|
||||
|
||||
interface StoredPlugin extends InstalledPlugin { package: PluginPackage }
|
||||
interface StoredPlugin extends InstalledPlugin { schemaVersion: 2; packageDigest: string; serverConfigCiphertext: string }
|
||||
export class PluginRegistry {
|
||||
private records = new Map<string, StoredPlugin>();
|
||||
private readonly records = new Map<string, StoredPlugin>();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private readonly masterKey: Buffer;
|
||||
readonly listeners = new Set<(id: string) => void>();
|
||||
constructor(private readonly directory: string) {}
|
||||
readonly directory: string;
|
||||
constructor(directory: string, masterKey?: Buffer) {
|
||||
this.directory = path.resolve(directory);
|
||||
this.masterKey = masterKey ?? loadOrCreateMasterSecret(path.join(this.directory,"master.key"));
|
||||
}
|
||||
async initialize(): Promise<void> {
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
for (const file of await readdir(this.directory)) {
|
||||
if (!file.endsWith(".json")) continue;
|
||||
await mkdir(path.join(this.directory,"installed"),{recursive:true});
|
||||
for (const file of await readdir(path.join(this.directory,"installed"))) {
|
||||
if (!file.endsWith('.json')) continue;
|
||||
try {
|
||||
const raw = await readFile(path.join(this.directory, file));
|
||||
pluginAssert(raw.length <= PLUGIN_LIMIT_BYTES + 32 * 1024);
|
||||
const value = JSON.parse(raw.toString("utf8"));
|
||||
const pack = parsePluginPackage(value.package);
|
||||
pluginAssert(file === `${pack.manifest.id}.json` && typeof value.installedAt === "number");
|
||||
const settings = this.settings(value.settings, pack);
|
||||
this.records.set(pack.manifest.id, { package: pack, manifest: pack.manifest, settings, installedAt: value.installedAt, revision: this.hash(pack, settings) });
|
||||
} catch { /* An invalid package is never executed or exposed. */ }
|
||||
const bytes=await readFile(path.join(this.directory,"installed",file)); pluginAssert(bytes.length<=256*1024);
|
||||
const v:unknown=JSON.parse(bytes.toString('utf8'));pluginAssert(pluginRecord(v)&&v.schemaVersion===2);
|
||||
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
|
||||
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
|
||||
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
|
||||
this.readSecret(record);record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
|
||||
} catch { /* Invalid or obsolete packages are never executed. */ }
|
||||
}
|
||||
}
|
||||
list(): InstalledPlugin[] { return [...this.records.values()].map(({ package: _, ...value }) => structuredClone(value)); }
|
||||
get(id: string): StoredPlugin | undefined { const r = this.records.get(id); return r ? structuredClone(r) : undefined; }
|
||||
policy(id: string): InstalledPlugin | undefined {
|
||||
const record = this.records.get(id); if (!record) return undefined;
|
||||
const { package: _, ...policy } = record; return structuredClone(policy);
|
||||
private public(record: StoredPlugin): InstalledPlugin {
|
||||
return structuredClone({manifest:record.manifest,settings:record.settings,revision:record.revision,installedAt:record.installedAt});
|
||||
}
|
||||
private hash(pack: PluginPackage, settings: PluginSettings): string { return createHash("sha256").update(JSON.stringify({ pack, settings })).digest("hex"); }
|
||||
private settings(value: unknown, pack: PluginPackage): PluginSettings {
|
||||
pluginAssert(pluginRecord(value) && typeof value.enabled === "boolean" && pack.manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(Array.isArray(value.targets) && value.targets.length <= 50 && value.targets.every(t => typeof t === "string" && t.length <= 300));
|
||||
let targets: string[];
|
||||
try { targets = [...new Set(value.targets.map(t => teamSpeakTargetKey(parseTeamSpeakTarget(t))))]; }
|
||||
catch { throw new PluginError("PLUGIN_TARGET_INVALID"); }
|
||||
pluginAssert(value.scope !== "server" || !value.enabled || targets.length > 0, "PLUGIN_TARGET_REQUIRED");
|
||||
return { enabled: value.enabled, scope: value.scope as PluginSettings["scope"], targets, config: parsePluginJson(value.config, 8192) };
|
||||
list(): InstalledPlugin[] { return [...this.records.values()].map(record=>this.public(record)); }
|
||||
policy(id: string): InstalledPlugin | undefined { const record=this.records.get(id);return record?this.public(record):undefined; }
|
||||
private hash(record: Omit<StoredPlugin,'revision'> | StoredPlugin): string {
|
||||
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
|
||||
}
|
||||
private mutate<T>(run: () => Promise<T>): Promise<T> { const next = this.queue.then(run, run); this.queue = next.catch(() => undefined); return next; }
|
||||
private async commit(record: StoredPlugin): Promise<InstalledPlugin> {
|
||||
const temporary = path.join(this.directory, `.${randomUUID()}.tmp`);
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(record), { flag: "wx", mode: 0o600 });
|
||||
await rename(temporary, path.join(this.directory, `${record.manifest.id}.json`));
|
||||
} finally { await unlink(temporary).catch(() => undefined); }
|
||||
this.records.set(record.manifest.id, record);
|
||||
for (const listener of this.listeners) { try { listener(record.manifest.id); } catch { /* Commit already succeeded. */ } }
|
||||
const { package: _, ...result } = record; return structuredClone(result);
|
||||
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
|
||||
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
|
||||
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
|
||||
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
|
||||
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
|
||||
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
|
||||
}
|
||||
install(pack: PluginPackage, expectedRevision: string | null): Promise<InstalledPlugin> {
|
||||
return this.mutate(async () => {
|
||||
pack = parsePluginPackage(pack);
|
||||
const previous = this.records.get(pack.manifest.id);
|
||||
pluginAssert((previous?.revision ?? null) === expectedRevision, "PLUGIN_CHANGED");
|
||||
pluginAssert(previous || this.records.size < 50, "PLUGIN_LIMIT");
|
||||
// Updates require an explicit enable/review of the new permission set.
|
||||
const settings = { ...(previous?.settings ?? { scope: pack.manifest.scopes[0], targets: [], config: {} }), enabled: false };
|
||||
if (!pack.manifest.scopes.includes(settings.scope)) settings.scope = pack.manifest.scopes[0];
|
||||
return this.commit({ package: pack, manifest: pack.manifest, settings, revision: this.hash(pack, settings), installedAt: previous?.installedAt ?? Date.now() });
|
||||
});
|
||||
private readSecret(record: StoredPlugin): JsonValue {
|
||||
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
|
||||
return text?parsePluginJson(JSON.parse(text)):null;
|
||||
}
|
||||
configure(id: string, input: unknown, revision: string): Promise<InstalledPlugin> {
|
||||
return this.mutate(async () => {
|
||||
const record = this.records.get(id); pluginAssert(record, "PLUGIN_NOT_FOUND");
|
||||
pluginAssert(record.revision === revision, "PLUGIN_CHANGED");
|
||||
const settings = this.settings(input, record.package);
|
||||
return this.commit({ ...record, settings, revision: this.hash(record.package, settings) });
|
||||
});
|
||||
serverConfig(id: string): JsonValue { const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');return this.readSecret(record); }
|
||||
private mutate<T>(run:()=>Promise<T>):Promise<T>{const next=this.queue.then(run,run);this.queue=next.catch(()=>undefined);return next;}
|
||||
private async commit(record:StoredPlugin):Promise<InstalledPlugin>{
|
||||
record.revision=this.hash(record);const directory=path.join(this.directory,'installed'),temporary=path.join(directory,`.${randomUUID()}.tmp`);
|
||||
try{await writeFile(temporary,JSON.stringify(record),{flag:'wx',mode:0o600});await rename(temporary,path.join(directory,`${record.manifest.id}.json`));}finally{await unlink(temporary).catch(()=>undefined);}
|
||||
this.records.set(record.manifest.id,record);for(const listener of this.listeners){try{listener(record.manifest.id);}catch{}}
|
||||
return this.public(record);
|
||||
}
|
||||
remove(id: string, revision: string): Promise<void> {
|
||||
return this.mutate(async () => {
|
||||
pluginAssert(pluginId(id)); const record = this.records.get(id); pluginAssert(record, "PLUGIN_NOT_FOUND");
|
||||
pluginAssert(record.revision === revision, "PLUGIN_CHANGED");
|
||||
await unlink(path.join(this.directory, `${id}.json`)); this.records.delete(id);
|
||||
for (const listener of this.listeners) { try { listener(id); } catch { /* Removal already succeeded. */ } }
|
||||
});
|
||||
install(input:PluginPackage,expectedRevision:string|null):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
const pack=parsePluginPackage(input),previous=this.records.get(pack.manifest.id);pluginAssert((previous?.revision??null)===expectedRevision,'PLUGIN_CHANGED');pluginAssert(previous||this.records.size<50,'PLUGIN_LIMIT');
|
||||
const bytes=JSON.stringify(pack),digest=createHash('sha256').update(bytes).digest('hex'),directory=path.join(this.directory,'packages',pack.manifest.id);
|
||||
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
|
||||
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
|
||||
const old=previous?.settings;
|
||||
const settings={enabled:false,trusted:false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
|
||||
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
|
||||
});}
|
||||
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');pluginAssert(pluginRecord(input));
|
||||
let secret=record.serverConfigCiphertext;const action=input.serverConfigAction??'keep';pluginAssert(['keep','replace','remove'].includes(String(action)));
|
||||
if(action==='remove')secret='';else if(action==='replace')secret=encryptSecret(JSON.stringify(parsePluginJson(input.serverConfig)),this.masterKey,`webspeak:plugin-config:v2:${id}`);
|
||||
const settings=this.settings(input,record.manifest,!!secret);return this.commit({...record,settings,serverConfigCiphertext:secret});
|
||||
});}
|
||||
async getPackage(id:string):Promise<PluginPackage>{
|
||||
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');
|
||||
const bytes=await readFile(path.join(this.directory,'packages',id,`${record.packageDigest}.wplugin`));pluginAssert(bytes.length<=PLUGIN_LIMIT_BYTES,'PLUGIN_TOO_LARGE');
|
||||
pluginAssert(createHash('sha256').update(bytes).digest('hex')===record.packageDigest,'PLUGIN_CHECKSUM');
|
||||
const pack=parsePluginPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes)));pluginAssert(JSON.stringify(pack.manifest)===JSON.stringify(record.manifest),'PLUGIN_PACKAGE_MISMATCH');return pack;
|
||||
}
|
||||
async materialize(id:string,revision:string):Promise<string>{
|
||||
const record=this.records.get(id);pluginAssert(record?.revision===revision,'PLUGIN_CHANGED');const pack=await this.getPackage(id);pluginAssert(this.records.get(id)?.revision===revision,'PLUGIN_CHANGED');
|
||||
const parent=path.join(this.directory,'code',id);await mkdir(parent,{recursive:true});const root=await mkdtemp(path.join(parent,'run-'));
|
||||
try{for(const [name,file]of Object.entries(pack.files)){const target=path.resolve(root,name);pluginAssert(target.startsWith(root+path.sep));await mkdir(path.dirname(target),{recursive:true});await writeFile(target,pluginFileBytes(file),{flag:'wx',mode:0o600});}return root;}
|
||||
catch(error){await this.releaseCode(root);throw error;}
|
||||
}
|
||||
async releaseCode(directory:string):Promise<void>{
|
||||
const root=path.resolve(this.directory,'code');pluginAssert(path.resolve(directory).startsWith(root+path.sep));await rm(directory,{recursive:true,force:true});
|
||||
}
|
||||
async dataDirectory(id:string):Promise<string>{pluginAssert(pluginId(id));const directory=path.join(this.directory,'data',id);await mkdir(directory,{recursive:true});return directory;}
|
||||
remove(id:string,revision:string):Promise<void>{return this.mutate(async()=>{
|
||||
pluginAssert(pluginId(id));const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');
|
||||
await unlink(path.join(this.directory,'installed',`${id}.json`));this.records.delete(id);for(const listener of this.listeners){try{listener(id);}catch{}}
|
||||
});}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Router } from "express";
|
||||
import { PluginRuntime } from "./runtime.js";
|
||||
import { pluginAssert, PluginError, pluginRecord } from "../shared/plugins.js";
|
||||
|
||||
/** Control plane only. Application HTTP/WebSocket traffic lives on the independent origin. */
|
||||
export function createPluginRuntimeRouter(runtime?: PluginRuntime) {
|
||||
const router=Router();
|
||||
router.use((_request,response,next)=>{
|
||||
response.setHeader("access-control-allow-origin","*");
|
||||
response.setHeader("access-control-allow-headers","authorization, content-type");
|
||||
response.setHeader("access-control-allow-methods","GET, POST, PATCH, DELETE, OPTIONS");
|
||||
response.setHeader("cache-control","no-store");next();
|
||||
});
|
||||
router.options(/.*/,(_request,response)=>{response.sendStatus(204);});
|
||||
const token=(authorization:string|undefined)=>{pluginAssert(typeof authorization==="string"&&authorization.startsWith("Bearer "),"PLUGIN_NOT_CONNECTED");return authorization.slice(7);};
|
||||
const service=()=>{pluginAssert(runtime,"PLUGIN_RUNTIME_UNAVAILABLE");return runtime;};
|
||||
router.get("/",(request,response)=>{response.json({plugins:service().directory(token(request.header("authorization")))});});
|
||||
router.post("/:id/open",async(request,response)=>{
|
||||
const origin=request.header("origin")??`${request.protocol}://${request.header("host")}`;
|
||||
response.status(201).json(await service().open(token(request.header("authorization")),String(request.params.id),request.body,origin));
|
||||
});
|
||||
router.delete("/opening/:id",(request,response)=>{service().cancelOpen(token(request.header("authorization")),String(request.params.id));response.json({ok:true});});
|
||||
router.patch("/apps/:id",(request,response)=>{
|
||||
pluginAssert(pluginRecord(request.body));service().appearance(String(request.params.id),token(request.header("authorization")),request.body);response.json({ok:true});
|
||||
});
|
||||
router.delete("/apps/:id",(request,response)=>{
|
||||
const instance=service(),id=String(request.params.id);pluginAssert(instance.authorizeApp(id,token(request.header("authorization"))),"PLUGIN_NOT_OPEN");instance.closeApp(id);response.json({ok:true});
|
||||
});
|
||||
router.use((error:unknown,_request:unknown,response:import("express").Response,_next:unknown)=>{
|
||||
const code=error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED";
|
||||
response.status(code==="PLUGIN_NOT_CONNECTED"?401:code==="PLUGIN_NOT_FOUND"?404:code==="PLUGIN_RUNTIME_UNAVAILABLE"?503:403).json({ok:false,code});
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse, type Server } from "node:http";
|
||||
import { createServer as createHttpsServer, type ServerOptions } from "node:https";
|
||||
import { readFile, writeFile, rename } from "node:fs/promises";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Socket } from "node:net";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PluginProcess } from "./process.js";
|
||||
import { PluginError, pluginAssert, pluginPath, pluginRecord, type InstalledPlugin, type PluginAppContext, type PluginAppLaunch, type PluginParticipant, type PluginRequestContext, type PluginRuntimeStatus } from "../shared/plugins.js";
|
||||
|
||||
interface ApplicationEntry { policy: InstalledPlugin; directory: string; assets: Set<string>; process?: PluginProcess; status: PluginRuntimeStatus; stale: boolean }
|
||||
interface AppSession {
|
||||
id: string; publicId: string; participantId: string; openKey: string; pluginId: string; revision: string; voiceToken: string; scopeKey: string;
|
||||
theme: "light" | "dark"; language: PluginAppContext["language"]; origin: string; lastActivity: number; lastContext: string;
|
||||
streams: Set<ServerResponse>; connections: Set<() => void>;
|
||||
}
|
||||
interface RuntimeOptions {
|
||||
registry: PluginRegistry; participant(token: string): PluginParticipant | null; logger: Logger;
|
||||
port?: number; host?: string; publicOrigin?: string; tls?: ServerOptions; maxWorkers?: number;
|
||||
}
|
||||
const contentTypes: Record<string, string> = { ".html":"text/html; charset=utf-8", ".js":"text/javascript; charset=utf-8", ".mjs":"text/javascript; charset=utf-8", ".css":"text/css; charset=utf-8", ".json":"application/json; charset=utf-8", ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".jpeg":"image/jpeg", ".webp":"image/webp", ".gif":"image/gif", ".ico":"image/x-icon", ".woff":"font/woff", ".woff2":"font/woff2", ".wasm":"application/wasm", ".mp4":"video/mp4", ".webm":"video/webm" };
|
||||
|
||||
/** App traffic uses its own HTTP origin and child processes, never the voice WebSocket. */
|
||||
export class PluginRuntime {
|
||||
private readonly entries = new Map<string, ApplicationEntry>();
|
||||
private readonly queues = new Map<string, Promise<unknown>>();
|
||||
private readonly sessions = new Map<string, AppSession>();
|
||||
private readonly openings = new Map<string, {cancelled:boolean; expires:number; appId?:string}>();
|
||||
private readonly server: Server | ReturnType<typeof createHttpsServer>;
|
||||
private readonly sockets = new Set<Socket>();
|
||||
private timer?: ReturnType<typeof setInterval>;
|
||||
private origin = "";
|
||||
private listening = false;
|
||||
private closed = false;
|
||||
private configQueue: Promise<unknown> = Promise.resolve();
|
||||
private readonly changed = (id: string) => {
|
||||
this.revokePlugin(id, "PLUGIN_CHANGED");
|
||||
const entry = this.entries.get(id); if (entry) { entry.stale = true; void entry.process?.close(); }
|
||||
void this.synchronize(id).catch(() => undefined);
|
||||
};
|
||||
constructor(private readonly options: RuntimeOptions) {
|
||||
this.server = options.tls ? createHttpsServer(options.tls, (req,res) => void this.handle(req,res)) : createServer((req,res) => void this.handle(req,res));
|
||||
this.server.on("connection", socket => { this.sockets.add(socket); socket.once("close", () => this.sockets.delete(socket)); });
|
||||
this.server.on("upgrade", (req,socket,head) => void this.upgrade(req,socket as Socket,head));
|
||||
options.registry.listeners.add(this.changed);
|
||||
}
|
||||
get port(): number { const address=this.server.address(); return address&&typeof address!=="string"?address.port:0; }
|
||||
settings() { return { publicOrigin:this.origin, port:this.port, available:this.listening, revision:createHash("sha256").update(this.origin).digest("hex") }; }
|
||||
async configureOrigin(input: unknown, revision: unknown): Promise<ReturnType<PluginRuntime["settings"]>> {
|
||||
const next=this.configQueue.then(async()=>{
|
||||
pluginAssert(typeof input==="string"&&input.length<=300&&typeof revision==="string");
|
||||
pluginAssert(revision===this.settings().revision,"PLUGIN_CHANGED");
|
||||
const origin=normalizeOrigin(input);
|
||||
const directory=this.options.registry.directory, temporary=path.join(directory,`.runtime-${randomUUID()}.tmp`);
|
||||
await writeFile(temporary,JSON.stringify({publicOrigin:origin}),{flag:"wx",mode:0o600}); await rename(temporary,path.join(directory,"runtime.json"));
|
||||
this.origin=origin;for(const app of [...this.sessions.values()])this.closeApp(app.id,"PLUGIN_CHANGED");return this.settings();
|
||||
});this.configQueue=next.catch(()=>undefined);return next;
|
||||
}
|
||||
async start(): Promise<void> {
|
||||
try { const value=JSON.parse(await readFile(path.join(this.options.registry.directory,"runtime.json"),"utf8"));this.origin=normalizeOrigin(value.publicOrigin); }
|
||||
catch { this.origin=normalizeOrigin(this.options.publicOrigin??""); }
|
||||
await new Promise<void>((resolve,reject)=>{
|
||||
const failed=(error:Error)=>{this.server.off("listening",ready);reject(error);};
|
||||
const ready=()=>{this.server.off("error",failed);this.listening=true;resolve();};
|
||||
this.server.once("error",failed);this.server.once("listening",ready);this.server.listen(this.options.port??3042,this.options.host??"0.0.0.0");
|
||||
});
|
||||
this.timer=setInterval(()=>this.reconcileSessions(),1000);
|
||||
// Applications may provide background integrations even without an open browser panel.
|
||||
await Promise.allSettled(this.options.registry.list().filter(p=>p.settings.enabled).map(p=>this.synchronize(p.manifest.id)));
|
||||
}
|
||||
status(id: string): PluginRuntimeStatus {
|
||||
const policy=this.options.registry.policy(id);if(!policy?.settings.enabled)return {state:"disabled"};
|
||||
return this.entries.get(id)?.status??{state:policy.manifest.server?"stopped":"client"};
|
||||
}
|
||||
private async stopEntry(entry: ApplicationEntry): Promise<void> {
|
||||
await entry.process?.close();if(entry.directory){await this.options.registry.releaseCode(entry.directory);entry.directory="";}
|
||||
}
|
||||
synchronize(id: string): Promise<void> {
|
||||
const next=(this.queues.get(id)??Promise.resolve()).then(async()=>{
|
||||
const policy=this.options.registry.policy(id),previous=this.entries.get(id);
|
||||
if(previous&&!previous.stale&&previous.policy.revision===policy?.revision)return;
|
||||
if(previous){await this.stopEntry(previous);this.entries.delete(id);}
|
||||
if(this.closed||!policy?.settings.enabled||!policy.settings.trusted)return;
|
||||
const entry:ApplicationEntry={policy,directory:"",assets:new Set(),status:{state:"starting"},stale:false};this.entries.set(id,entry);
|
||||
try {
|
||||
if(policy.manifest.server)pluginAssert([...this.entries.values()].filter(p=>p.policy.manifest.server&&["starting","running"].includes(p.status.state)).length<=(this.options.maxWorkers??8),"PLUGIN_WORKER_LIMIT");
|
||||
entry.assets=new Set(Object.keys((await this.options.registry.getPackage(id)).files).filter(name=>name.startsWith("client/")));
|
||||
entry.directory=await this.options.registry.materialize(id,policy.revision);
|
||||
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
|
||||
if(policy.manifest.server){
|
||||
entry.process=new PluginProcess({entry:path.join(entry.directory,policy.manifest.server.entry),codeDirectory:entry.directory,dataDirectory:await this.options.registry.dataDirectory(id),config:this.options.registry.serverConfig(id),publicConfig:policy.settings.config,logger:this.options.logger.child({pluginId:id}),onExit:()=>{
|
||||
if(this.entries.get(id)===entry&&!entry.stale&&!this.closed){entry.status={state:"failed",error:"PLUGIN_PROCESS_EXITED"};this.revokePlugin(id,"PLUGIN_PROCESS_EXITED");}
|
||||
}});await entry.process.ready;
|
||||
}
|
||||
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
|
||||
entry.status={state:policy.manifest.server?"running":"client"};
|
||||
} catch(error) {
|
||||
entry.status={state:"failed",error:error instanceof PluginError?error.code:"PLUGIN_START_FAILED"};
|
||||
await this.stopEntry(entry);this.options.logger.warn({pluginId:id,code:entry.status.error},"Plugin application failed to start");
|
||||
}
|
||||
});this.queues.set(id,next.catch(()=>undefined));return next;
|
||||
}
|
||||
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
|
||||
directory(voiceToken:string) {
|
||||
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
|
||||
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,runtime:this.status(policy.manifest.id)}));
|
||||
}
|
||||
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
|
||||
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
|
||||
if(policy.settings.scope==="instance")return "instance";
|
||||
pluginAssert(policy.settings.targets.includes(participant.target),"PLUGIN_NOT_ALLOWED");return `${participant.target}#${participant.channelId}`;
|
||||
}
|
||||
private appOrigin(mainOrigin:string):string{
|
||||
pluginAssert(this.listening,"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
if(this.origin){pluginAssert(this.origin!==new URL(mainOrigin).origin,"PLUGIN_SEPARATE_ORIGIN_REQUIRED");return this.origin;}
|
||||
const source=new URL(mainOrigin);pluginAssert(["127.0.0.1","localhost","[::1]"].includes(source.hostname),"PLUGIN_PUBLIC_ORIGIN_REQUIRED");
|
||||
source.hostname=source.hostname==="localhost"?"127.0.0.1":"localhost";source.port=String(this.port);source.protocol=this.options.tls?"https:":"http:";return source.origin;
|
||||
}
|
||||
async open(voiceToken:string,id:string,input:unknown,mainOrigin:string):Promise<PluginAppLaunch>{
|
||||
const participant=this.options.participant(voiceToken),policy=this.options.registry.policy(id);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");pluginAssert(policy,"PLUGIN_NOT_FOUND");
|
||||
const preferences=pluginRecord(input)?input:{},openId=preferences.openId??randomUUID();
|
||||
pluginAssert(typeof openId==="string"&&/^[a-zA-Z0-9-]{8,80}$/.test(openId));const openKey=voiceToken+":"+openId,previous=this.openings.get(openKey);
|
||||
if(previous?.appId){const app=this.sessions.get(previous.appId);if(app&&this.validate(app)){pluginAssert(app.pluginId===id,"PLUGIN_OPEN_CONFLICT");return {id:app.id,url:`${app.origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};}}
|
||||
pluginAssert(!previous,previous?.cancelled?"PLUGIN_CANCELLED":"PLUGIN_OPEN_PENDING");
|
||||
pluginAssert([...this.openings.keys()].filter(key=>key.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
|
||||
const operation={cancelled:false,expires:Date.now()+90000,appId:undefined as string|undefined};this.openings.set(openKey,operation);
|
||||
const scopeKey=this.scopeKey(policy,participant),origin=this.appOrigin(mainOrigin);
|
||||
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
|
||||
await this.synchronize(id);const entry=this.entries.get(id);pluginAssert(entry&&["running","client"].includes(entry.status.state),entry?.status.error??"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
pluginAssert(!operation.cancelled,"PLUGIN_CANCELLED");
|
||||
const current=this.options.participant(voiceToken);pluginAssert(current&&this.options.registry.policy(id)?.revision===policy.revision&&this.scopeKey(policy,current)===scopeKey,"PLUGIN_CONTEXT_CHANGED");
|
||||
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
|
||||
const app:AppSession={id:randomBytes(32).toString("base64url"),publicId:randomUUID(),participantId:current.id,openKey,pluginId:id,revision:policy.revision,voiceToken,scopeKey,origin,theme:preferences.theme==="dark"?"dark":"light",language:["zh","en","de","ru","ja"].includes(String(preferences.language))?preferences.language as PluginAppContext["language"]:"en",lastActivity:Date.now(),lastContext:"",streams:new Set(),connections:new Set()};
|
||||
operation.appId=app.id;
|
||||
this.sessions.set(app.id,app);entry.process?.event("participantJoined",this.requestContext(app,current));
|
||||
return {id:app.id,url:`${origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};
|
||||
}
|
||||
authorizeApp(id:string,voiceToken:string):boolean{return this.sessions.get(id)?.voiceToken===voiceToken;}
|
||||
cancelOpen(voiceToken:string,openId:string):void{
|
||||
pluginAssert(/^[a-zA-Z0-9-]{8,80}$/.test(openId));const key=voiceToken+":"+openId,operation=this.openings.get(key);
|
||||
if(operation){operation.cancelled=true;if(operation.appId)this.closeApp(operation.appId);return;}
|
||||
pluginAssert(this.options.participant(voiceToken),"PLUGIN_NOT_CONNECTED");
|
||||
pluginAssert([...this.openings.keys()].filter(item=>item.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
|
||||
this.openings.set(key,{cancelled:true,expires:Date.now()+90000});
|
||||
}
|
||||
appearance(id:string,voiceToken:string,input:unknown):void{
|
||||
pluginAssert(this.authorizeApp(id,voiceToken)&&pluginRecord(input),"PLUGIN_NOT_OPEN");const app=this.sessions.get(id)!;
|
||||
if(input.theme==="light"||input.theme==="dark")app.theme=input.theme;
|
||||
if(["zh","en","de","ru","ja"].includes(String(input.language)))app.language=input.language as PluginAppContext["language"];
|
||||
this.publishContext(app);
|
||||
}
|
||||
closeApp(id:string,code="PLUGIN_CLOSED"):void{
|
||||
const app=this.sessions.get(id);if(!app)return;this.sessions.delete(id);
|
||||
const opening=this.openings.get(app.openKey);if(opening){opening.cancelled=true;opening.appId=undefined;opening.expires=Date.now()+90000;}
|
||||
for(const response of app.streams){if(!response.destroyed)response.end(`event: closed\ndata: ${JSON.stringify({code})}\n\n`);}
|
||||
for(const close of app.connections){try{close();}catch{}}
|
||||
this.entries.get(app.pluginId)?.process?.event("participantLeft",{appId:app.publicId,selfId:app.participantId,scopeKey:app.scopeKey});
|
||||
}
|
||||
private revokePlugin(id:string,code:string):void{for(const app of [...this.sessions.values()])if(app.pluginId===id)this.closeApp(app.id,code);}
|
||||
private context(app:AppSession,participant:PluginParticipant):PluginAppContext{
|
||||
const policy=this.options.registry.policy(app.pluginId)!;
|
||||
const base=`${app.origin}/apps/${app.id}`;
|
||||
return {...this.requestContext(app,participant),plugin:policy.manifest,connection:{target:participant.target,channelId:participant.channelId,members:participant.members},config:policy.settings.config,theme:app.theme,language:app.language,
|
||||
serverUrl:policy.manifest.server?`${base}/server`:null,socketUrl:policy.manifest.server?`${base.replace(/^http/,"ws")}/server`:null,contextUrl:`${base}/_runtime/context`};
|
||||
}
|
||||
private requestContext(app:AppSession,participant:PluginParticipant):PluginRequestContext{
|
||||
return {apiVersion:2,appId:app.publicId,self:{id:participant.id,nickname:participant.nickname,...(participant.uid?{uid:participant.uid}:{})},connection:{target:participant.target,channelId:participant.channelId},scope:{type:this.options.registry.policy(app.pluginId)!.settings.scope,key:app.scopeKey}};
|
||||
}
|
||||
private validate(app:AppSession):PluginParticipant|null{
|
||||
const policy=this.options.registry.policy(app.pluginId),participant=this.options.participant(app.voiceToken);
|
||||
try{return policy&&policy.revision===app.revision&&participant&&this.scopeKey(policy,participant)===app.scopeKey?participant:null;}catch{return null;}
|
||||
}
|
||||
private publishContext(app:AppSession):void{
|
||||
const participant=this.validate(app);if(!participant){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");return;}
|
||||
const context=this.context(app,participant),json=JSON.stringify(context);
|
||||
if(json!==app.lastContext){app.lastContext=json;for(const response of app.streams)if(!response.destroyed)response.write(`event: context\ndata: ${json}\n\n`);this.entries.get(app.pluginId)?.process?.event("contextChanged",{...this.requestContext(app,participant),connection:context.connection});}
|
||||
}
|
||||
private reconcileSessions():void{
|
||||
for(const [key,operation]of this.openings)if(!operation.appId&&operation.expires<Date.now())this.openings.delete(key);
|
||||
for(const app of [...this.sessions.values()]){
|
||||
if(!this.validate(app)||(!app.streams.size&&Date.now()-app.lastActivity>90000)){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");continue;}
|
||||
this.publishContext(app);for(const response of app.streams){if(response.destroyed)app.streams.delete(response);else if(response.writableLength>256*1024){response.destroy();app.streams.delete(response);}else response.write(": keepalive\n\n");}
|
||||
}
|
||||
}
|
||||
private locate(request:IncomingMessage):{app:AppSession;route:string;query:string;participant:PluginParticipant}{
|
||||
const url=new URL(request.url??"/","http://runtime.invalid"),match=/^\/apps\/([A-Za-z0-9_-]{43})\/(.*)$/.exec(url.pathname);
|
||||
pluginAssert(match,"PLUGIN_NOT_OPEN");const app=this.sessions.get(match[1]);pluginAssert(app,"PLUGIN_NOT_OPEN");
|
||||
const participant=this.validate(app);pluginAssert(participant,"PLUGIN_CONTEXT_CHANGED");app.lastActivity=Date.now();
|
||||
return {app,route:decodeURIComponent(match[2]),query:url.search,participant};
|
||||
}
|
||||
private async handle(request:IncomingMessage,response:ServerResponse):Promise<void>{
|
||||
response.setHeader("referrer-policy","no-referrer");response.setHeader("x-content-type-options","nosniff");response.setHeader("cache-control","no-store");
|
||||
try{
|
||||
const {app,route,query,participant}=this.locate(request),entry=this.entries.get(app.pluginId);pluginAssert(entry?.directory,"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
if(route.startsWith("server/")||route==="server"){this.proxy(request,response,app,participant,"/"+route.slice(7)+query);return;}
|
||||
pluginAssert(request.method==="GET"||request.method==="HEAD","PLUGIN_METHOD_NOT_ALLOWED");
|
||||
if(route==="_runtime/context"){response.setHeader("content-type","application/json");response.end(JSON.stringify(this.context(app,participant)));return;}
|
||||
if(route==="_runtime/events"){
|
||||
pluginAssert(app.streams.size<4,"PLUGIN_LIMIT");response.writeHead(200,{"content-type":"text/event-stream","x-accel-buffering":"no"});response.flushHeaders();app.streams.add(response);
|
||||
response.write(`event: context\ndata: ${JSON.stringify(this.context(app,participant))}\n\n`);response.once("close",()=>app.streams.delete(response));return;
|
||||
}
|
||||
if(route==="_runtime/sdk.js"){response.setHeader("content-type","text/javascript; charset=utf-8");response.end(applicationSdk(this.context(app,participant),`${app.origin}/apps/${app.id}/_runtime/events`,app.id));return;}
|
||||
pluginAssert(route.startsWith("client/")&&pluginPath(route),"PLUGIN_ASSET_NOT_FOUND");
|
||||
pluginAssert(this.validate(app)&&entry.assets.has(route),"PLUGIN_ASSET_NOT_FOUND");
|
||||
const file=path.resolve(entry.directory,route);pluginAssert(file.startsWith(entry.directory+path.sep),"PLUGIN_ASSET_NOT_FOUND");
|
||||
response.setHeader("content-type",contentTypes[path.extname(route)]??"application/octet-stream");
|
||||
if(route===entry.policy.manifest.client.entry){
|
||||
let html=await readFile(file,"utf8");pluginAssert(this.validate(app),"PLUGIN_CONTEXT_CHANGED");
|
||||
const script=`<script src="/apps/${app.id}/_runtime/sdk.js"></script>`;
|
||||
if(/<head(?:\s[^>]*)?>/i.test(html))html=html.replace(/<head(?:\s[^>]*)?>/i,head=>head+script);
|
||||
else if(/<!doctype[^>]*>/i.test(html))html=html.replace(/<!doctype[^>]*>/i,doctype=>doctype+script);
|
||||
else html=script+html;
|
||||
response.end(request.method==="HEAD"?undefined:html);return;
|
||||
}
|
||||
if(request.method==="HEAD"){response.end();return;}
|
||||
const stream=createReadStream(file);stream.once("error",()=>{if(!response.headersSent)response.writeHead(404);response.end();});response.once("close",()=>stream.destroy());stream.pipe(response);
|
||||
}catch(error){if(!response.headersSent)response.writeHead(error instanceof PluginError&&error.code==="PLUGIN_ASSET_NOT_FOUND"?404:403,{"content-type":"application/json"});response.end(JSON.stringify({error:error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED"}));}
|
||||
}
|
||||
private headers(request:IncomingMessage,app:AppSession,participant:PluginParticipant):Record<string,string|string[]>{
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");
|
||||
const headers:Record<string,string|string[]>={};
|
||||
for(const [key,value]of Object.entries(request.headers))if(value!==undefined&&!['cookie','authorization','host','connection','proxy-authorization'].includes(key)&&!key.startsWith('x-webspeak-'))headers[key]=value;
|
||||
const context=this.requestContext(app,participant);
|
||||
headers['x-webspeak-runtime']=worker.token;headers['x-webspeak-context']=Buffer.from(JSON.stringify(context),'utf8').toString('base64url');return headers;
|
||||
}
|
||||
private proxy(request:IncomingMessage,response:ServerResponse,app:AppSession,participant:PluginParticipant,route:string):void{
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");pluginAssert(app.connections.size<32,"PLUGIN_BUSY");
|
||||
const upstream=httpRequest({hostname:"127.0.0.1",port:worker.port,path:route,method:request.method,headers:this.headers(request,app,participant)},incoming=>{
|
||||
if(response.destroyed||!this.sessions.has(app.id)){incoming.destroy();return;}
|
||||
const headers={...incoming.headers};delete headers['set-cookie'];response.writeHead(incoming.statusCode??502,headers);incoming.once('error',()=>response.destroy());incoming.pipe(response);
|
||||
});
|
||||
const close=()=>{upstream.destroy();if(!response.writableFinished)response.destroy();};app.connections.add(close);
|
||||
upstream.setTimeout(120000,()=>upstream.destroy());upstream.once('error',()=>{if(!response.headersSent)response.writeHead(502,{'content-type':'application/json'});response.end('{"error":"PLUGIN_BACKEND_UNAVAILABLE"}');});
|
||||
response.once('close',()=>{app.connections.delete(close);upstream.destroy();});request.once('aborted',close);request.pipe(upstream);
|
||||
}
|
||||
private async upgrade(request:IncomingMessage,socket:Socket,head:Buffer):Promise<void>{
|
||||
try{
|
||||
const {app,route,query,participant}=this.locate(request);pluginAssert(route==='server'||route.startsWith('server/'),"PLUGIN_NOT_ALLOWED");
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port&&app.connections.size<32,"PLUGIN_BACKEND_UNAVAILABLE");
|
||||
const headers=this.headers(request,app,participant);headers.connection='Upgrade';headers.upgrade=String(request.headers.upgrade??'websocket');
|
||||
const upstream=httpRequest({hostname:'127.0.0.1',port:worker.port,path:'/'+route.slice(7)+query,headers});
|
||||
const close=()=>{upstream.destroy();socket.destroy();};app.connections.add(close);socket.once('close',()=>{app.connections.delete(close);upstream.destroy();});
|
||||
upstream.once('upgrade',(response,peer,upstreamHead)=>{
|
||||
socket.write(`HTTP/1.1 ${response.statusCode??101} Switching Protocols\r\n`);for(const [key,value]of Object.entries(response.headers))if(value!==undefined&&key!=='set-cookie')socket.write(`${key}: ${Array.isArray(value)?value.join(', '):value}\r\n`);socket.write('\r\n');
|
||||
if(head.length)peer.write(head);if(upstreamHead.length)socket.write(upstreamHead);peer.pipe(socket);socket.pipe(peer);peer.once('error',()=>socket.destroy());socket.once('error',()=>peer.destroy());
|
||||
app.connections.delete(close);const closePeer=()=>{peer.destroy();socket.destroy();};app.connections.add(closePeer);socket.once('close',()=>{app.connections.delete(closePeer);peer.destroy();});peer.once('close',()=>socket.destroy());
|
||||
});
|
||||
upstream.once('error',close);upstream.once('response',()=>close());upstream.end();
|
||||
}catch{socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');}
|
||||
}
|
||||
async close():Promise<void>{
|
||||
if(this.closed)return;this.closed=true;this.listening=false;clearInterval(this.timer);this.options.registry.listeners.delete(this.changed);
|
||||
for(const app of [...this.sessions.values()])this.closeApp(app.id);
|
||||
this.openings.clear();
|
||||
await Promise.allSettled([...this.entries.values()].map(entry=>entry.process?.close()));
|
||||
await Promise.allSettled(this.queues.values());await Promise.allSettled([...this.entries.values()].map(entry=>this.stopEntry(entry)));this.entries.clear();
|
||||
for(const socket of this.sockets)socket.destroy();await new Promise<void>(resolve=>this.server.close(()=>resolve()));
|
||||
}
|
||||
}
|
||||
function normalizeOrigin(value:unknown):string{
|
||||
pluginAssert(typeof value==='string'&&value.length<=300);if(!value.trim())return '';
|
||||
const url=new URL(value.trim());pluginAssert(['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash&&url.pathname==='/');
|
||||
pluginAssert(url.protocol==='https:'||['localhost','127.0.0.1','[::1]'].includes(url.hostname),'PLUGIN_HTTPS_REQUIRED');return url.origin;
|
||||
}
|
||||
function applicationSdk(context:PluginAppContext,eventsUrl:string,id:string):string{
|
||||
// No expression evaluator, business RPC, shared rooms, dependency loader, or network allowlist.
|
||||
return `(()=>{let context=${JSON.stringify(context).replace(/</g,'\\u003c')};const listeners=new Set(),closed=new AbortController();document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;
|
||||
const events=new EventSource(${JSON.stringify(eventsUrl)});events.addEventListener('context',event=>{try{context=JSON.parse(event.data);document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;for(const fn of listeners){try{fn(context)}catch{}}}catch{}});
|
||||
events.addEventListener('closed',()=>{closed.abort();events.close();parent.postMessage({type:'webspeak-app-closed',id:${JSON.stringify(id)}},'*')});
|
||||
window.webspeak=Object.freeze({apiVersion:2,ready:Promise.resolve(context),getContext:()=>context,onContextChange(fn){listeners.add(fn);return()=>listeners.delete(fn)},signal:closed.signal});
|
||||
addEventListener('pagehide',()=>{closed.abort();events.close();listeners.clear()},{once:true});})();`;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export class PluginStore {
|
||||
}
|
||||
private async sources() {
|
||||
const root = await this.json(PLUGIN_STORE_INDEX);
|
||||
pluginAssert(pluginRecord(root) && root.schemaVersion === 1 && Array.isArray(root.plugins) && root.plugins.length <= 50);
|
||||
pluginAssert(pluginRecord(root) && root.schemaVersion === 2 && Array.isArray(root.plugins) && root.plugins.length <= 50,"PLUGIN_CATALOG_UNSUPPORTED");
|
||||
const seen = new Set<string>();
|
||||
return root.plugins.map(item => {
|
||||
pluginAssert(pluginRecord(item) && pluginId(item.id) && !seen.has(item.id)); seen.add(item.id);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/** Child-process entrypoint. Reviewed applications run normal Node.js, not a JS sandbox. */
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { type Socket } from "node:net";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import type { JsonValue, PluginRequestContext } from "../shared/plugins.js";
|
||||
|
||||
interface RequestContext extends IncomingMessage { webspeak?: PluginRequestContext }
|
||||
interface Application {
|
||||
handle(request: RequestContext, response: ServerResponse): unknown;
|
||||
upgrade?(request: RequestContext, socket: Socket, head: Buffer): unknown;
|
||||
stop?(): unknown;
|
||||
}
|
||||
interface Initialization { type: "initialize"; entry: string; dataDir: string; config: JsonValue; publicConfig: JsonValue; token: string }
|
||||
const events = new EventEmitter(), abort = new AbortController(), sockets = new Set<Socket>();
|
||||
let application: Application | undefined, initialized = false, stopping = false, secret = "";
|
||||
const server = createServer((request: RequestContext, response) => {
|
||||
if (!authorize(request)) { response.writeHead(403).end(); return; }
|
||||
Promise.resolve().then(() => application!.handle(request, response)).catch(() => {
|
||||
if (!response.headersSent) response.writeHead(500, { "content-type": "application/json" });
|
||||
if (!response.destroyed) response.end('{"error":"PLUGIN_HANDLER_FAILED"}');
|
||||
});
|
||||
});
|
||||
function authorize(request: RequestContext): boolean {
|
||||
if (!secret || request.headers["x-webspeak-runtime"] !== secret) return false;
|
||||
delete request.headers["x-webspeak-runtime"];
|
||||
try {
|
||||
const context = JSON.parse(Buffer.from(String(request.headers["x-webspeak-context"]), "base64url").toString("utf8"));
|
||||
if (context?.apiVersion !== 2 || !context.self?.id || !context.scope?.key) return false;
|
||||
request.webspeak = context;
|
||||
delete request.headers["x-webspeak-context"];
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); });
|
||||
server.on("upgrade", (request: RequestContext, socket: Socket, head) => {
|
||||
if (!authorize(request) || !application?.upgrade) { socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); return; }
|
||||
Promise.resolve().then(() => application!.upgrade!(request, socket, head)).catch(() => socket.destroy());
|
||||
});
|
||||
server.on("error", () => { process.send?.({ type: "failed", code: "PLUGIN_LISTEN_FAILED" }); void stop(); });
|
||||
async function initialize(value: Initialization): Promise<void> {
|
||||
if (initialized) return;
|
||||
initialized = true; secret = value.token;
|
||||
try {
|
||||
const module = await import(pathToFileURL(value.entry).href);
|
||||
if (typeof module.default !== "function") throw new Error("Expected a default activation function");
|
||||
const result = await module.default({
|
||||
dataDir: value.dataDir, config: value.config, publicConfig: value.publicConfig, events, signal: abort.signal,
|
||||
log(level: string, message: unknown) { process.send?.({ type: "log", level, message: String(message).slice(0, 1000) }); },
|
||||
});
|
||||
if (stopping) return;
|
||||
application = typeof result === "function" ? { handle: result } : result;
|
||||
if (!application || typeof application.handle !== "function") throw new Error("Expected a Node HTTP request handler");
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (address && typeof address !== "string") process.send?.({ type: "ready", port: address.port });
|
||||
});
|
||||
} catch { process.send?.({ type: "failed", code: "PLUGIN_START_FAILED" }); await stop(); }
|
||||
}
|
||||
async function stop(): Promise<void> {
|
||||
if (stopping) return;
|
||||
stopping = true; abort.abort();
|
||||
for (const socket of sockets) socket.destroy();
|
||||
server.close();
|
||||
try { await application?.stop?.(); } catch { /* Disposal cannot keep the worker alive. */ }
|
||||
events.removeAllListeners();
|
||||
if (process.connected) process.disconnect();
|
||||
process.exit(0);
|
||||
}
|
||||
process.on("message", (value: unknown) => {
|
||||
if (!value || typeof value !== "object" || !("type" in value)) return;
|
||||
if (value.type === "initialize") void initialize(value as Initialization);
|
||||
else if (value.type === "stop") void stop();
|
||||
else if (value.type === "event" && "name" in value && typeof value.name === "string" && !stopping) {
|
||||
try { events.emit(value.name, "payload" in value ? value.payload : undefined); } catch { /* App event failure is local to this worker. */ }
|
||||
}
|
||||
});
|
||||
process.once("disconnect", () => void stop());
|
||||
process.once("SIGTERM", () => void stop());
|
||||
process.once("SIGINT", () => void stop());
|
||||
Reference in new issue
Block a user