feat(plugins): add GitHub store and scoped collaborative panels

This commit is contained in:
illusia committed 2026-10-25 01:42:41 +08:00
1 parent b9fccb8757
commit ce681f749d
40 files changed
+1370 -5

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
import { Router, type RequestHandler } from "express";
import { PluginRegistry } from "./registry.js";
import { PluginStore } from "./store.js";
import { pluginAssert, pluginRecord, PluginError, parsePluginPackage } from "../shared/plugins.js";
export function createPluginAdminRouter(options: {
registry?: PluginRegistry; store?: PluginStore; protect: RequestHandler[];
audit(event: string, data: { id: string; version?: string }): void;
}) {
const router = Router(), store = options.store ?? new PluginStore();
const writeGuard = Router(); writeGuard.use(...options.protect);
router.use((request, response, next) => {
if (request.method === "GET") return next();
// Reuse the admin session's same-origin and CSRF rules for every write.
writeGuard(request, response, next);
});
const registry = () => { pluginAssert(options.registry, "PLUGIN_STORAGE_UNAVAILABLE"); return options.registry; };
router.get("/", (_request, response) => response.json({ plugins: registry().list() }));
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 });
});
router.post("/upload", async (request, response) => {
pluginAssert(pluginRecord(request.body));
const expected = request.body.installedRevision;
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 });
});
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);
options.audit("ADMIN_PLUGIN_CONFIGURED", { id: plugin.manifest.id });
response.json({ 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);
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 });
});
return router;
}
+107
View File
@@ -0,0 +1,107 @@
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(); }
}
+115
View File
@@ -0,0 +1,115 @@
import assert from 'node:assert/strict';
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';
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}));
});
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('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('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('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);
});
+84
View File
@@ -0,0 +1,84 @@
import { mkdir, readFile, readdir, writeFile, rename, unlink } 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";
interface StoredPlugin extends InstalledPlugin { package: PluginPackage }
export class PluginRegistry {
private records = new Map<string, StoredPlugin>();
private queue: Promise<unknown> = Promise.resolve();
readonly listeners = new Set<(id: string) => void>();
constructor(private readonly directory: string) {}
async initialize(): Promise<void> {
await mkdir(this.directory, { recursive: true });
for (const file of await readdir(this.directory)) {
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. */ }
}
}
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 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) };
}
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);
}
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() });
});
}
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) });
});
}
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. */ } }
});
}
}
+78
View File
@@ -0,0 +1,78 @@
import { createHash } from "node:crypto";
import { PluginRegistry } from "./registry.js";
import { PLUGIN_STORE_INDEX, PLUGIN_STORE_REPOSITORY, PLUGIN_LIMIT_BYTES, pluginAssert, pluginId, pluginRecord,
parsePluginManifest, parsePluginPackage, PluginError, type PluginCatalog, type PluginStoreEntry } from "../shared/plugins.js";
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
const SHA = /^[a-f0-9]{64}$/;
export class PluginStore {
constructor(private readonly fetcher: typeof fetch = fetch) {}
private async read(url: string, limit: number): Promise<Buffer> {
pluginAssert(new URL(url).origin === "https://raw.githubusercontent.com");
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000);
try {
const response = await this.fetcher(url, { signal: controller.signal, redirect: "error", credentials: "omit" });
pluginAssert(response.ok && response.body, "PLUGIN_STORE_UNAVAILABLE");
const reader = response.body.getReader(), chunks: Uint8Array[] = []; let size = 0;
try {
while (true) {
const part = await reader.read(); if (part.done) break;
size += part.value.byteLength;
if (size > limit) { await reader.cancel(); throw new PluginError("PLUGIN_TOO_LARGE"); }
chunks.push(part.value);
}
} finally { reader.releaseLock(); }
return Buffer.concat(chunks, size);
} catch (error) { if (error instanceof PluginError) throw error; throw new PluginError("PLUGIN_STORE_UNAVAILABLE"); }
finally { clearTimeout(timer); }
}
private async json(url: string): Promise<unknown> {
try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await this.read(url, 128 * 1024))); }
catch (e) { if (e instanceof PluginError) throw e; throw new PluginError("PLUGIN_INVALID"); }
}
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);
const seen = new Set<string>();
return root.plugins.map(item => {
pluginAssert(pluginRecord(item) && pluginId(item.id) && !seen.has(item.id)); seen.add(item.id);
pluginAssert(typeof item.repository === "string" && /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,99}$/.test(item.repository) && !item.repository.endsWith(".git"));
const metadataPath = item.metadataPath ?? "plugin.json";
pluginAssert(typeof metadataPath === "string" && /^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.json$/.test(metadataPath) && metadataPath.length <= 160);
return { id: item.id, repository: item.repository, metadataPath };
});
}
private async metadata(source: { id: string; repository: string; metadataPath: string }) {
const rawBase = source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/");
const value = await this.json(`${rawBase}/HEAD/${source.metadataPath}`);
pluginAssert(pluginRecord(value) && pluginRecord(value.package));
const manifest = parsePluginManifest(value.manifest), pack = value.package;
pluginAssert(manifest.id === source.id && typeof pack.ref === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/.test(pack.ref));
pluginAssert(typeof pack.path === "string" && /^(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+\.wplugin$/.test(pack.path) && pack.path.length <= 160);
pluginAssert(typeof pack.sha256 === "string" && SHA.test(pack.sha256));
const descriptor = { ref: pack.ref, path: pack.path, sha256: pack.sha256 };
return { manifest, descriptor, revision: hash({ source, manifest, package: descriptor }), url: `${rawBase}/${pack.ref}/${pack.path}` };
}
async list(): Promise<PluginCatalog> {
const sources = await this.sources(), entries = new Array<PluginStoreEntry>(sources.length); let cursor = 0;
await Promise.all(Array.from({ length: Math.min(4, sources.length) }, async () => {
while (cursor < sources.length) { const i = cursor++, source = sources[i];
try { const meta = await this.metadata(source); entries[i] = { ...source, manifest: meta.manifest, revision: meta.revision, error: null }; }
catch (e) { entries[i] = { ...source, manifest: null, revision: "", error: e instanceof PluginError ? e.code : "PLUGIN_STORE_UNAVAILABLE" }; }
}
}));
return { repository: PLUGIN_STORE_REPOSITORY, entries };
}
async install(registry: PluginRegistry, input: unknown) {
pluginAssert(pluginRecord(input) && pluginId(input.id) && typeof input.revision === "string" && SHA.test(input.revision));
pluginAssert(input.installedRevision === null || typeof input.installedRevision === "string" && SHA.test(input.installedRevision));
const source = (await this.sources()).find(s => s.id === input.id); pluginAssert(source, "PLUGIN_NOT_FOUND");
const metadata = await this.metadata(source); pluginAssert(metadata.revision === input.revision, "PLUGIN_CHANGED");
const bytes = await this.read(metadata.url, PLUGIN_LIMIT_BYTES);
pluginAssert(createHash("sha256").update(bytes).digest("hex") === metadata.descriptor.sha256, "PLUGIN_CHECKSUM");
let value: unknown;
try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { throw new PluginError("PLUGIN_INVALID"); }
const pack = parsePluginPackage(value); pluginAssert(JSON.stringify(pack.manifest) === JSON.stringify(metadata.manifest), "PLUGIN_PACKAGE_MISMATCH");
return registry.install(pack, input.installedRevision as string | null);
}
}