mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02: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,7 +1,7 @@
|
||||
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
|
||||
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
|
||||
import { pluginResponses, type PluginPackage, type PluginSettings } from "../../../src/shared/plugins.js";
|
||||
import { pluginResponses, type PluginPackage, type PluginSettingsInput } from "../../../src/shared/plugins.js";
|
||||
|
||||
export class AdminApiError extends Error {
|
||||
constructor(readonly code: string, readonly status = 0, message = code) {
|
||||
@@ -103,9 +103,12 @@ export function createAdminApi(options: AdminApiOptions) {
|
||||
invalidate() { generation++; for (const controller of pending) controller.abort(); },
|
||||
plugins: (signal?: AbortSignal) => request("/plugins", pluginResponses.installed, "GET", undefined, true, signal),
|
||||
pluginStore: (signal?: AbortSignal) => request("/plugins/store", pluginResponses.catalog, "GET", undefined, true, signal),
|
||||
pluginRuntime: (signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "GET", undefined, true, signal),
|
||||
configurePluginRuntime: (publicOrigin: string, revision: string, signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "PUT", { publicOrigin, revision }, true, signal),
|
||||
restartPlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/restart`, pluginResponses.saved, "POST", { revision }, true, signal),
|
||||
installPlugin: (body: { id: string; revision: string; installedRevision: string | null }, signal?: AbortSignal) => request("/plugins/store/install", pluginResponses.saved, "POST", body, true, signal),
|
||||
uploadPlugin: (pack: PluginPackage, installedRevision: string | null, signal?: AbortSignal) => request("/plugins/upload", pluginResponses.saved, "POST", { package: pack, installedRevision }, true, signal),
|
||||
configurePlugin: (id: string, revision: string, settings: PluginSettings, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
|
||||
configurePlugin: (id: string, revision: string, settings: PluginSettingsInput, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
|
||||
removePlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}`, adminResponses.ok, "DELETE", { revision }, true, signal),
|
||||
session: (signal?: AbortSignal) => request("/session", adminResponses.session, "GET", undefined, true, signal),
|
||||
login: (username: string, password: string, signal?: AbortSignal) => request("/login", adminResponses.login, "POST", { username, password }, false, signal),
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import appPackage from "../../../package.json";
|
||||
|
||||
// Available before the public config request completes, including on the demo page.
|
||||
export const APP_VERSION = appPackage.version;
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createInstanceAuthorization, INSTANCE_AUTHORIZATION_KEY, canUseSkin, setInstanceAuthorization } from './instance-authorization.js';
|
||||
|
||||
function storage() {
|
||||
const values = new Map<string, string>();
|
||||
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
|
||||
}
|
||||
test('new instances require an explicit decision; legacy package approvals do not imply consent', () => {
|
||||
const data = storage(); data.values.set('webspeak:skin-plugin-approvals', '{"grants":{"old":true}}');
|
||||
const state = createInstanceAuthorization(data);
|
||||
assert.equal(state.decision.value, null); assert.equal(state.allowed.value, false);
|
||||
state.set(false); assert.equal(createInstanceAuthorization(data).decision.value, false);
|
||||
state.set(true); assert.equal(createInstanceAuthorization(data).allowed.value, true);
|
||||
assert.deepEqual([...data.values.keys()].sort(), [INSTANCE_AUTHORIZATION_KEY, 'webspeak:skin-plugin-approvals'].sort());
|
||||
});
|
||||
test('separate instance storage stays independent; revocation and clearing propagate on reload', () => {
|
||||
const first = storage(), second = storage(), tab = createInstanceAuthorization(first), otherTab = createInstanceAuthorization(first);
|
||||
tab.set(true); otherTab.reload(); assert.equal(otherTab.allowed.value, true);
|
||||
assert.equal(createInstanceAuthorization(second).decision.value, null);
|
||||
tab.set(false); otherTab.reload(); assert.equal(otherTab.allowed.value, false);
|
||||
first.values.clear(); otherTab.reload(); assert.equal(otherTab.decision.value, null);
|
||||
});
|
||||
test('malformed or inaccessible storage never grants access; explicit choices survive in memory', () => {
|
||||
const data = storage();
|
||||
for (const value of ['true', '{}', '{"schemaVersion":1,"allowed":"true"}', '{"schemaVersion":2,"allowed":true}', 'broken']) {
|
||||
data.setItem(INSTANCE_AUTHORIZATION_KEY, value); assert.equal(createInstanceAuthorization(data).allowed.value, false);
|
||||
}
|
||||
const unavailable = createInstanceAuthorization({ getItem() { throw Error(); }, setItem() { throw Error(); } });
|
||||
assert.equal(unavailable.allowed.value, false); unavailable.set(true); assert.equal(unavailable.allowed.value, true);
|
||||
unavailable.set(false); assert.equal(unavailable.allowed.value, false);
|
||||
});
|
||||
test('only the three official IDs bypass consent, including when KAAK is shipped as built-in', () => {
|
||||
setInstanceAuthorization(false);
|
||||
for (const id of ['builtin.light', 'builtin.dark', 'community.illusia-voice']) assert.equal(canUseSkin(id), true);
|
||||
for (const id of ['community.kaak-voice', 'community.discord-voice', 'builtin.other']) assert.equal(canUseSkin(id), false);
|
||||
setInstanceAuthorization(true); assert.equal(canUseSkin('community.kaak-voice'), true);
|
||||
setInstanceAuthorization(false);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { computed, readonly, ref } from 'vue';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
|
||||
export const INSTANCE_AUTHORIZATION_KEY = 'webspeak:instance-authorization:v1';
|
||||
export const OFFICIAL_SKIN_IDS = new Set(['builtin.light', 'builtin.dark', 'community.illusia-voice']);
|
||||
type AuthorizationStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
|
||||
/** A decision belongs to this browser origin, never to a skin package or a TS account. */
|
||||
export function createInstanceAuthorization(storage: AuthorizationStorage) {
|
||||
function read(): boolean | null {
|
||||
try {
|
||||
const value = JSON.parse(storage.getItem(INSTANCE_AUTHORIZATION_KEY) ?? 'null');
|
||||
return value?.schemaVersion === 1 && typeof value.allowed === 'boolean' ? value.allowed : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
const decision = ref<boolean | null>(read());
|
||||
return {
|
||||
decision: readonly(decision),
|
||||
allowed: computed(() => decision.value === true),
|
||||
set(allowed: boolean) {
|
||||
// Notify consumers synchronously so revocation also retires in-flight loads.
|
||||
decision.value = allowed;
|
||||
try { storage.setItem(INSTANCE_AUTHORIZATION_KEY, JSON.stringify({ schemaVersion: 1, allowed })); } catch { /* Keep this page's explicit decision when storage is unavailable. */ }
|
||||
},
|
||||
reload() { decision.value = read(); },
|
||||
};
|
||||
}
|
||||
|
||||
const store = createInstanceAuthorization({
|
||||
getItem: key => typeof window === 'undefined' ? null : window.localStorage.getItem(key),
|
||||
setItem: (key, value) => { if (typeof window !== 'undefined') window.localStorage.setItem(key, value); },
|
||||
});
|
||||
export const authorizationDecision = store.decision;
|
||||
export const thirdPartyAllowed = store.allowed;
|
||||
export const authorizationRequested = ref(false);
|
||||
export const authorizationLanguage = ref<SiteLanguage>('zh');
|
||||
export const setInstanceAuthorization = store.set;
|
||||
export const canUseSkin = (id: string) => OFFICIAL_SKIN_IDS.has(id) || thirdPartyAllowed.value;
|
||||
export function openInstanceAuthorization() { authorizationRequested.value = true; }
|
||||
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') window.addEventListener('storage', event => {
|
||||
if (event.key === INSTANCE_AUTHORIZATION_KEY || event.key === null) store.reload();
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPluginAppClient } from './plugin-app-client.js';
|
||||
const token='a'.repeat(43),id='b'.repeat(43);
|
||||
const manifest={apiVersion:2,id:'test.app',name:'Test',version:'1.0.0',author:'Test',license:'MIT',description:'App',scopes:['instance'],client:{entry:'client/index.html'}};
|
||||
test('plugin control uses the connected gateway origin and never sends its voice query or cookies',async()=>{
|
||||
const seen:Array<{url:string;init:RequestInit|undefined}>=[];
|
||||
const client=createPluginAppClient('wss://relay.example/voice?credential=private',token,async(url,init)=>{seen.push({url:String(url),init});return Response.json({plugins:[{manifest,scope:'instance',runtime:{state:'client'}}]});});
|
||||
assert.equal((await client.list())[0].manifest.id,'test.app');assert.equal(seen[0].url,'https://relay.example/api/plugins');assert.equal(seen[0].init?.credentials,'omit');assert.equal(new Headers(seen[0].init?.headers).get('authorization'),'Bearer '+token);
|
||||
assert.throws(()=>createPluginAppClient('https://x','invalid'));assert.throws(()=>createPluginAppClient('https://user:secret@example.com',token));
|
||||
});
|
||||
test('launch validation rejects mismatched IDs, unsafe URLs and invalid runtime responses',async()=>{
|
||||
for(const value of [{id,url:`https://apps.example/apps/${id}/client/index.html`,manifest:{...manifest,id:'another.app'}},{id,url:`https://user:secret@apps.example/apps/${id}/client/index.html`,manifest},{id,url:'javascript:alert(1)',manifest},{id,url:`https://apps.example/apps/${id}/client/index.html?ticket=x`,manifest}]){
|
||||
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json(value));await assert.rejects(client.open('test.app',{openId:'operation-123',theme:'light',language:'en'}));
|
||||
}
|
||||
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json({plugins:[{manifest,scope:'anything',runtime:{state:'unknown'}}]}));await assert.rejects(client.list());
|
||||
});
|
||||
test('control requests time out through response body parsing and support caller cancellation',async()=>{
|
||||
const slow:typeof fetch=async(_url,init)=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))));
|
||||
const client=createPluginAppClient('http://localhost:3040',token,slow,15);await assert.rejects(client.list(),/PLUGIN_TIMEOUT/);
|
||||
const controller=new AbortController(),request=client.list(controller.signal);controller.abort();await assert.rejects(request,/PLUGIN_REQUEST_CANCELLED/);
|
||||
const body:typeof fetch=async(_url,init)=>({ok:true,json:()=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))))}) as Response;
|
||||
await assert.rejects(createPluginAppClient('http://localhost:3040',token,body,15).list(),/PLUGIN_TIMEOUT/);
|
||||
});
|
||||
test('pending open cancellation remains a separate operation and status errors are bounded codes',async()=>{
|
||||
const requests:string[]=[];const client=createPluginAppClient('http://localhost:3040',token,async(url,init)=>{requests.push(`${init?.method} ${url}`);return Response.json({ok:true});});
|
||||
await client.cancelOpen('operation-123');assert.match(requests[0],/^DELETE .*\/opening\/operation-123$/);
|
||||
await assert.rejects(createPluginAppClient('http://localhost:3040',token,async()=>Response.json({code:'<secret error body>'},{status:500})).list(),/PLUGIN_RUNTIME_FAILED/);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { parsePluginManifest, pluginAssert, pluginRecord, type PluginManifest, type PluginAppLaunch, type PluginScope, type PluginRuntimeStatus } from '../../../src/shared/plugins.js';
|
||||
|
||||
export interface AvailablePluginApp { manifest: PluginManifest; scope: PluginScope; runtime: PluginRuntimeStatus }
|
||||
export function createPluginAppClient(gatewayUrl:string,token:string,fetcher:typeof fetch=fetch,timeoutMs=15000){
|
||||
pluginAssert(/^[A-Za-z0-9_-]{43}$/.test(token),'PLUGIN_NOT_CONNECTED');
|
||||
const gateway=new URL(gatewayUrl);pluginAssert(['ws:','wss:','http:','https:'].includes(gateway.protocol)&&!gateway.username&&!gateway.password);
|
||||
gateway.protocol=gateway.protocol==='wss:'||gateway.protocol==='https:'?'https:':'http:';
|
||||
const base=gateway.origin+'/api/plugins';
|
||||
async function request(route:string,method='GET',body?:unknown,signal?:AbortSignal):Promise<unknown>{
|
||||
const controller=new AbortController();let timedOut=false;
|
||||
const abort=()=>controller.abort();if(signal?.aborted)abort();else signal?.addEventListener('abort',abort,{once:true});
|
||||
const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeoutMs);
|
||||
try{
|
||||
const response=await fetcher(base+route,{method,headers:{authorization:'Bearer '+token,...(body===undefined?{}:{'content-type':'application/json'})},credentials:'omit',redirect:'error',signal:controller.signal,...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
const value:unknown=await response.json();
|
||||
if(!response.ok)throw new Error(pluginRecord(value)&&typeof value.code==='string'&&/^[A-Z0-9_]{1,80}$/.test(value.code)?value.code:'PLUGIN_RUNTIME_FAILED');
|
||||
return value;
|
||||
}catch(error){if(timedOut)throw new Error('PLUGIN_TIMEOUT');if(signal?.aborted)throw new Error('PLUGIN_REQUEST_CANCELLED');throw error;}
|
||||
finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);}
|
||||
}
|
||||
return {
|
||||
async list(signal?:AbortSignal):Promise<AvailablePluginApp[]>{
|
||||
const value=await request('','GET',undefined,signal);pluginAssert(pluginRecord(value)&&Array.isArray(value.plugins)&&value.plugins.length<=50,'PLUGIN_INVALID_RESPONSE');
|
||||
return value.plugins.map(entry=>{
|
||||
pluginAssert(pluginRecord(entry)&&(entry.scope==='server'||entry.scope==='instance')&&pluginRecord(entry.runtime)&&['disabled','client','stopped','starting','running','failed'].includes(String(entry.runtime.state)),'PLUGIN_INVALID_RESPONSE');
|
||||
return {manifest:parsePluginManifest(entry.manifest),scope:entry.scope,runtime:{state:entry.runtime.state as PluginRuntimeStatus['state'],...(typeof entry.runtime.error==='string'?{error:entry.runtime.error}:{})}};
|
||||
});
|
||||
},
|
||||
async open(id:string,options:{openId:string;theme:'light'|'dark';language:string},signal?:AbortSignal):Promise<PluginAppLaunch>{
|
||||
const value=await request('/'+encodeURIComponent(id)+'/open','POST',options,signal);
|
||||
pluginAssert(pluginRecord(value)&&typeof value.id==='string'&&/^[A-Za-z0-9_-]{43}$/.test(value.id)&&typeof value.url==='string','PLUGIN_INVALID_RESPONSE');
|
||||
const manifest=parsePluginManifest(value.manifest),url=new URL(value.url);
|
||||
pluginAssert(manifest.id===id&&['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&url.pathname==='/apps/'+value.id+'/'+manifest.client.entry&&!url.hash&&!url.search,'PLUGIN_INVALID_RESPONSE');
|
||||
return {id:value.id,url:url.href,manifest};
|
||||
},
|
||||
cancelOpen:(openId:string)=>request('/opening/'+encodeURIComponent(openId),'DELETE'),
|
||||
appearance:(id:string,theme:'light'|'dark',language:string)=>request('/apps/'+encodeURIComponent(id),'PATCH',{theme,language}),
|
||||
};
|
||||
}
|
||||
export type PluginAppClient=ReturnType<typeof createPluginAppClient>;
|
||||
@@ -1,32 +0,0 @@
|
||||
import { type PluginPackage } from "../../../src/shared/plugins.js";
|
||||
|
||||
/** The SDK never receives a voice socket, TS identity, cookie, or admin API. */
|
||||
export function pluginFrameDocument(pack: PluginPackage, channel: string): string {
|
||||
const escape = (source: string, tag: string) => source.replace(new RegExp(`</${tag}`, "gi"), `<\\/${tag}`);
|
||||
const bootstrap = `(() => {
|
||||
const channel = ${JSON.stringify(channel)};
|
||||
const pending = new Map(), listeners = new Set(); let sequence = 0, context;
|
||||
const send = value => parent.postMessage({channel,...value}, '*');
|
||||
const ready = new Promise(resolve => window.addEventListener('message', function receive(event) {
|
||||
if(event.source !== parent || event.data?.channel !== channel) return;
|
||||
const m = event.data;
|
||||
if(m.type === 'context') { context=m.context; document.documentElement.dataset.theme=context.theme;
|
||||
document.getElementById('plugin-light').media=context.theme==='dark'?'not all':'all';
|
||||
document.getElementById('plugin-dark').media=context.theme==='dark'?'all':'not all'; resolve(context); }
|
||||
if(m.type === 'snapshot') for(const fn of listeners) { try {fn(m.snapshot);} catch {} }
|
||||
if(m.type === 'reply') { const task=pending.get(m.id); if(task) {pending.delete(m.id); clearTimeout(task.timer); m.error?task.reject(new Error(m.error)):task.resolve(m.result);} }
|
||||
}));
|
||||
const request = (method,args) => new Promise((resolve,reject) => {
|
||||
if(pending.size>=16) return reject(new Error('PLUGIN_RATE_LIMITED'));
|
||||
const id=++sequence, timer=setTimeout(()=>{pending.delete(id);reject(new Error('PLUGIN_TIMEOUT'));},12000);
|
||||
pending.set(id,{resolve,reject,timer}); send({type:'request',id,method,args});
|
||||
});
|
||||
window.webspeak = Object.freeze({apiVersion:1,ready,
|
||||
room:Object.freeze({snapshot:()=>request('room.snapshot'),update:(revision,state)=>request('room.update',{revision,state}),
|
||||
subscribe(fn){listeners.add(fn); return ()=>listeners.delete(fn);}})});
|
||||
send({type:'ready'});
|
||||
})();`;
|
||||
// Opaque origin + no same-origin, popups, forms, navigation, fetch, or nested frames.
|
||||
const csp = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src https: data:; media-src https: http: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="${csp}"><script>${escape(bootstrap,"script")}</script><style>html,body{margin:0;min-height:100%;font:15px system-ui}*{box-sizing:border-box}body{padding:20px}html[data-theme="dark"]{color-scheme:dark}</style><style id="plugin-light">${escape(pack.styles.light,"style")}</style><style id="plugin-dark" media="not all">${escape(pack.styles.dark,"style")}</style></head><body>${pack.html}<script>${escape(pack.script,"script")}</script></body></html>`;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPluginTransport } from './plugin-transport.js';
|
||||
|
||||
test('plugin requests correlate replies, reset pending work and release subscribers independently',async () => {
|
||||
const sent:any[]=[];const socket={readyState:1,send:(v:string)=>sent.push(JSON.parse(v))} as unknown as WebSocket;
|
||||
const transport=createPluginTransport(()=>socket,()=>true);
|
||||
const result=transport.request('list');assert.equal(sent[0].type,'pluginRequest');
|
||||
transport.receive({type:'pluginReply',requestId:sent[0].requestId,ok:true,result:[{id:'a'}]});
|
||||
assert.deepEqual(await result,[{id:'a'}]);
|
||||
const events:any[]=[];const off=transport.subscribe(m=>events.push(m));
|
||||
transport.receive({type:'pluginEvent',pluginId:'a',snapshot:null});assert.equal(events.length,1);
|
||||
const pending=transport.request('open',{pluginId:'a'});transport.reset();await assert.rejects(pending,/PLUGIN_NOT_CONNECTED/);
|
||||
transport.receive({type:'pluginReply',requestId:sent[1].requestId,ok:true,result:{old:true}});assert.equal(events.at(-1).type,'pluginReset');
|
||||
off();transport.reset();assert.equal(events.length,2);
|
||||
});
|
||||
test('server errors, disconnected sockets and request quotas do not leak promises',async () => {
|
||||
const sent:any[]=[];let connected=false;const socket={readyState:1,send:(v:string)=>sent.push(JSON.parse(v))} as unknown as WebSocket;
|
||||
const transport=createPluginTransport(()=>socket,()=>connected);
|
||||
await assert.rejects(transport.request('list'),/PLUGIN_NOT_CONNECTED/);connected=true;
|
||||
const failed=transport.request('snapshot',{pluginId:'a'});
|
||||
transport.receive({type:'pluginReply',requestId:sent[0].requestId,ok:false,code:'PLUGIN_NOT_OPEN'});await assert.rejects(failed,/PLUGIN_NOT_OPEN/);
|
||||
const pending=Array.from({length:16},()=>transport.request('list').catch(e=>e.message));
|
||||
await assert.rejects(transport.request('list'),/PLUGIN_RATE_LIMITED/);transport.reset();
|
||||
assert.ok((await Promise.all(pending)).every(v=>v==='PLUGIN_NOT_CONNECTED'));
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
import { pluginRecord, type PluginRequest, type PluginMessage } from "../../../src/shared/plugins.js";
|
||||
|
||||
/** Owns requests and event subscribers for one voice connection. */
|
||||
export function createPluginTransport(socket: () => WebSocket | null, connected: () => boolean) {
|
||||
let sequence = 0;
|
||||
const pending = new Map<string, { finish(value?: unknown, error?: Error): void }>();
|
||||
const listeners = new Set<(message: PluginMessage | { type: "pluginReset" }) => void>();
|
||||
function emit(message: PluginMessage | { type: "pluginReset" }): void { for (const listener of [...listeners]) { try { listener(message); } catch { /* isolate presentation */ } } }
|
||||
return {
|
||||
request(action: PluginRequest["action"], fields: { pluginId?: string; revision?: number; state?: unknown } = {}): Promise<unknown> {
|
||||
const ws = socket();
|
||||
if (!connected() || ws?.readyState !== 1) return Promise.reject(new Error("PLUGIN_NOT_CONNECTED"));
|
||||
if (pending.size >= 16) return Promise.reject(new Error("PLUGIN_RATE_LIMITED"));
|
||||
const requestId = `plugin-${Date.now().toString(36)}-${++sequence}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => finish(undefined, new Error("PLUGIN_TIMEOUT")), 15_000);
|
||||
const finish = (value?: unknown, error?: Error) => { if (!pending.delete(requestId)) return; clearTimeout(timer); error ? reject(error) : resolve(value); };
|
||||
pending.set(requestId, { finish });
|
||||
try { ws.send(JSON.stringify({ type: "pluginRequest", requestId, action, ...fields })); }
|
||||
catch { finish(undefined, new Error("PLUGIN_NOT_CONNECTED")); }
|
||||
});
|
||||
},
|
||||
receive(value: unknown): boolean {
|
||||
if (!pluginRecord(value)) return false;
|
||||
if (value.type === "pluginReply") {
|
||||
if (typeof value.requestId === "string" && typeof value.ok === "boolean") pending.get(value.requestId)?.finish(value.result,
|
||||
value.ok ? undefined : new Error(typeof value.code === "string" ? value.code.slice(0, 80) : "PLUGIN_FAILED"));
|
||||
return true;
|
||||
}
|
||||
if (value.type === "pluginEvent" && typeof value.pluginId === "string" && (value.snapshot === null || pluginRecord(value.snapshot))) {
|
||||
emit(value as unknown as PluginMessage); return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
subscribe(listener: (message: PluginMessage | { type: "pluginReset" }) => void): () => void { listeners.add(listener); return () => listeners.delete(listener); },
|
||||
reset(): void { for (const item of [...pending.values()]) item.finish(undefined, new Error("PLUGIN_NOT_CONNECTED")); emit({ type: "pluginReset" }); },
|
||||
};
|
||||
}
|
||||
export type PluginTransport = ReturnType<typeof createPluginTransport>;
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import test, { beforeEach } from "node:test";
|
||||
import { setInstanceAuthorization } from './instance-authorization.js';
|
||||
import { createRenderer, createSSRApp, defineComponent, h, nextTick, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
SkinExtensionUiOutputError,
|
||||
} from "../../../src/shared/skin-extension-ui.js";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
beforeEach(() => setInstanceAuthorization(true));
|
||||
|
||||
function outputDocument(componentId = "runtime-ui", root?: Record<string, unknown>, permissions: string[] = [], actions: Record<string, unknown> = {}, state?: Record<string, unknown>): string {
|
||||
return JSON.stringify({
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
/** Temporary development policy. Re-enable consent before public skin distribution. */
|
||||
/** Per-package dialogs are replaced by the explicit, revocable instance authorization.
|
||||
* Hosts must check canUseSkin before issuing/using internal manifest-bound grants. */
|
||||
export const PROMPT_FOR_SKIN_PERMISSIONS = false;
|
||||
@@ -51,7 +51,7 @@ export function getSkinRuntimePluginApproval(
|
||||
return grant && isSkinRuntimePluginApproved(grant, skinId, skinVersion, plugin, digest) ? grant : null;
|
||||
}
|
||||
|
||||
/** Called only by the host consent UI after a user explicitly approves this exact package. */
|
||||
/** Internal digest-bound record. The host must first allow this skin through instance authorization. */
|
||||
export function approveSkinRuntimePlugin(
|
||||
skinId: string,
|
||||
skinVersion: string,
|
||||
|
||||
@@ -35,6 +35,19 @@ async function approvedFiles(source = createSkinExtensionWasmPrefixByteImmediate
|
||||
return { files, digest, approval: createSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest) };
|
||||
}
|
||||
|
||||
test('revocation while package bytes are being verified prevents worker startup', async () => {
|
||||
const { files, approval } = await approvedFiles();
|
||||
const controller = new AbortController(), original = files[plugin.entry];
|
||||
class RevokedBlob extends Blob {
|
||||
override async arrayBuffer(): Promise<ArrayBuffer> { controller.abort(); return super.arrayBuffer(); }
|
||||
}
|
||||
await assert.rejects(createSkinRuntimePluginWasmSandbox({
|
||||
skinId: 'community.sample', skinVersion: '2.0.0', plugin, approval,
|
||||
files: { [plugin.entry]: new RevokedBlob([original]) }, signal: controller.signal,
|
||||
readSessionStatus: async () => ({ connected: true, channelName: 'Test', memberCount: 1 }),
|
||||
}), { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test("Wasm plugin startup rechecks the exact digest approval before creating a Worker", async () => {
|
||||
const { files, approval } = await approvedFiles();
|
||||
const staleApproval = { ...approval, digest: "0".repeat(64) };
|
||||
|
||||
@@ -26,6 +26,7 @@ export class SkinRuntimePluginWasmError extends Error {
|
||||
}
|
||||
|
||||
export interface SkinRuntimePluginWasmOptions {
|
||||
signal?: AbortSignal;
|
||||
skinId: string;
|
||||
skinVersion: string;
|
||||
plugin: SkinRuntimePlugin;
|
||||
@@ -43,6 +44,7 @@ const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSI
|
||||
export async function createSkinRuntimePluginWasmSandbox(
|
||||
options: SkinRuntimePluginWasmOptions,
|
||||
): Promise<SkinExtensionWasmSandboxHandle> {
|
||||
options.signal?.throwIfAborted();
|
||||
const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [options.plugin] }).plugins[0];
|
||||
if (plugin.runtime !== "wasm") throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "Only a Wasm plugin entry can use the bounded Wasm runner.");
|
||||
|
||||
@@ -52,6 +54,7 @@ export async function createSkinRuntimePluginWasmSandbox(
|
||||
}
|
||||
|
||||
const digest = await computeSkinRuntimePluginDigest(plugin, options.files);
|
||||
options.signal?.throwIfAborted();
|
||||
let approval: SkinRuntimePluginApproval;
|
||||
try { approval = parseSkinRuntimePluginApproval(options.approval); }
|
||||
catch { throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_APPROVAL_INVALID", "The Wasm plugin does not have a valid local approval."); }
|
||||
@@ -62,6 +65,7 @@ export async function createSkinRuntimePluginWasmSandbox(
|
||||
const entry = options.files[plugin.entry];
|
||||
if (!(entry instanceof Blob)) throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "The approved Wasm entry is unavailable.");
|
||||
const wasmBytes = new Uint8Array(await entry.arrayBuffer());
|
||||
options.signal?.throwIfAborted();
|
||||
const baseInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
|
||||
const uiInput = parseSkinExtensionUiInput({
|
||||
...baseInput,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
|
||||
import { APP_VERSION } from "./app-version.js";
|
||||
import type { InstalledSkin } from "./skin-pack.js";
|
||||
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
|
||||
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
|
||||
import { setSkinLayoutPackage } from "./skin-layout-runtime.js";
|
||||
import { canUseSkin } from './instance-authorization.js';
|
||||
|
||||
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
|
||||
export const BUILTIN_LIGHT_SKIN = "builtin.light";
|
||||
@@ -34,7 +36,7 @@ export async function activateStoredSkin(): Promise<InstalledSkin | null> {
|
||||
return activateSkin(selectedId);
|
||||
}
|
||||
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.7", options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = APP_VERSION, options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
|
||||
// An already retired page must not cancel a newer page's activation.
|
||||
options.signal?.throwIfAborted();
|
||||
pendingActivation?.cancel();
|
||||
@@ -51,6 +53,7 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
|
||||
async function prepareAndActivate(id: string, expectedVersion: string | undefined, appVersion: string,
|
||||
operation: ReturnType<typeof createSkinOperation>): Promise<InstalledSkin | null> {
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) return fallBackToBuiltin();
|
||||
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
|
||||
removeCustomSkinStyle();
|
||||
setSkinLayoutPackage(id, null);
|
||||
@@ -92,6 +95,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
|
||||
candidateUrls = compiled.objectUrls;
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) { candidateUrls.forEach(url => URL.revokeObjectURL(url)); return fallBackToBuiltin(); }
|
||||
// A community skin is a complete appearance choice, not an overlay on the
|
||||
// previously selected day/night skin. Keep the document theme (used by the
|
||||
// independent admin appearance) but give unstyled public parts a light,
|
||||
|
||||
Reference in new issue
Block a user