mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat(skin): add bounded plugin runtime and Harbor voice sample
This commit is contained in:
1 parent
8f097ec597
commit
96c29394f3
30 files changed
+1540
-185
No files matched your search
@@ -222,7 +222,7 @@ test("generated UI callbacks reject unsupported events, malformed IDs, and passw
|
||||
expectOutputError(generatedOutput("runtime-ui", { tag: "button", events: { click: "run" } }), "SKIN_EXTENSION_UI_OUTPUT_SCHEMA");
|
||||
});
|
||||
|
||||
test("SkinPluginOutlet emits callback data only for a trusted user event", async () => {
|
||||
test("SkinPluginOutlet emits only trusted callbacks and gates user-entered values by permission", async () => {
|
||||
interface HostNode {
|
||||
type: string;
|
||||
props: Record<string, unknown>;
|
||||
@@ -265,43 +265,77 @@ test("SkinPluginOutlet emits callback data only for a trusted user event", async
|
||||
id: "base", name: "Base", page: "voice", accessibleName: "Base", permissions: [], actions: {}, root: { tag: "p", children: [{ text: "Base" }] },
|
||||
}],
|
||||
};
|
||||
const emitted: unknown[] = [];
|
||||
const host = createHostNode("root");
|
||||
const app = renderer.createApp(SkinPluginOutlet, {
|
||||
skinId: "community.test",
|
||||
skinVersion: "1.0.0",
|
||||
document,
|
||||
extensionOutput: JSON.stringify({
|
||||
schemaVersion: 5,
|
||||
components: [{
|
||||
id: "server-rail", name: "Server rail", page: "voice", accessibleName: "Saved voice servers",
|
||||
state: { expanded: false },
|
||||
root: { tag: "button", attributes: { type: "button" }, events: { click: "select-server" }, children: [{ text: "Home" }] },
|
||||
}],
|
||||
}),
|
||||
page: "voice",
|
||||
data: {},
|
||||
assets: {},
|
||||
actions: {},
|
||||
"onExtension-event": (payload: unknown) => emitted.push(payload),
|
||||
const output = JSON.stringify({
|
||||
schemaVersion: 5,
|
||||
components: [{
|
||||
id: "server-rail", name: "Server rail", page: "voice", accessibleName: "Saved voice servers",
|
||||
state: { expanded: false },
|
||||
root: { tag: "div", children: [
|
||||
{ tag: "button", attributes: { type: "button" }, events: { click: "select-server" }, children: [{ text: "Home" }] },
|
||||
{ tag: "input", attributes: { type: "text" }, events: { input: "search" } },
|
||||
] },
|
||||
}],
|
||||
});
|
||||
app.mount(host);
|
||||
await nextTick();
|
||||
const findButton = (node: HostNode): HostNode | undefined => node.type === "button" ? node : node.children.map(findButton).find(Boolean);
|
||||
const button = findButton(host);
|
||||
const describe = (node: HostNode): string => `${node.type}[${node.text}](${node.children.map(describe).join(",")})`;
|
||||
assert.ok(button, describe(host));
|
||||
const onClick = button.props.onClick as (event: Event) => void;
|
||||
onClick({ isTrusted: false, target: null } as unknown as Event);
|
||||
assert.equal(emitted.length, 0, "script-created events must not reach extension logic");
|
||||
onClick({ isTrusted: true, target: null } as unknown as Event);
|
||||
assert.equal(emitted.length, 1);
|
||||
const payload = emitted[0] as { skinId: string; componentId: string; input: { state: Record<string, unknown>; event: Record<string, unknown> } };
|
||||
assert.equal(payload.skinId, "community.test");
|
||||
assert.equal(payload.componentId, "server-rail");
|
||||
assert.deepEqual({ ...payload.input.state }, { expanded: false });
|
||||
assert.deepEqual(payload.input.event, { componentId: "server-rail", handlerId: "select-server", eventName: "click" });
|
||||
app.unmount();
|
||||
class MockInputElement {
|
||||
type = "text";
|
||||
value = "private search text";
|
||||
checked = false;
|
||||
}
|
||||
const previousInputConstructor = Object.getOwnPropertyDescriptor(globalThis, "HTMLInputElement");
|
||||
Object.defineProperty(globalThis, "HTMLInputElement", { configurable: true, value: MockInputElement });
|
||||
const find = (node: HostNode, type: string): HostNode | undefined => node.type === type ? node : node.children.map((child) => find(child, type)).find(Boolean);
|
||||
const runInput = async (permissions: string[]) => {
|
||||
const emitted: unknown[] = [];
|
||||
const host = createHostNode("root");
|
||||
const app = renderer.createApp(SkinPluginOutlet, {
|
||||
skinId: "community.test", skinVersion: "1.0.0", document, extensionOutput: output,
|
||||
extensionPermissions: permissions, page: "voice", data: {}, assets: {}, actions: {},
|
||||
"onExtension-event": (payload: unknown) => emitted.push(payload),
|
||||
});
|
||||
app.mount(host);
|
||||
await nextTick();
|
||||
const input = find(host, "input");
|
||||
assert.ok(input);
|
||||
(input.props.onInput as (event: Event) => void)({ isTrusted: true, target: new MockInputElement() } as unknown as Event);
|
||||
app.unmount();
|
||||
return emitted[0] as { input: { event: Record<string, unknown> } };
|
||||
};
|
||||
try {
|
||||
const deniedHost = createHostNode("root");
|
||||
const deniedEvents: unknown[] = [];
|
||||
const deniedApp = renderer.createApp(SkinPluginOutlet, {
|
||||
skinId: "community.test", skinVersion: "1.0.0", document, extensionOutput: output,
|
||||
page: "voice", data: {}, assets: {}, actions: {},
|
||||
"onExtension-event": (payload: unknown) => deniedEvents.push(payload),
|
||||
});
|
||||
deniedApp.mount(deniedHost);
|
||||
await nextTick();
|
||||
const button = find(deniedHost, "button");
|
||||
const input = find(deniedHost, "input");
|
||||
assert.ok(button && input);
|
||||
const onClick = button.props.onClick as (event: Event) => void;
|
||||
onClick({ isTrusted: false, target: null } as unknown as Event);
|
||||
assert.equal(deniedEvents.length, 0, "script-created events must not reach extension logic");
|
||||
onClick({ isTrusted: true, target: null } as unknown as Event);
|
||||
const deniedValueEvent = input.props.onInput as (event: Event) => void;
|
||||
deniedValueEvent({ isTrusted: true, target: new MockInputElement() } as unknown as Event);
|
||||
const clickPayload = deniedEvents[0] as { skinId: string; componentId: string; input: { state: Record<string, unknown>; event: Record<string, unknown> } };
|
||||
assert.equal(clickPayload.skinId, "community.test");
|
||||
assert.equal(clickPayload.componentId, "server-rail");
|
||||
assert.deepEqual({ ...clickPayload.input.state }, { expanded: false });
|
||||
assert.deepEqual(clickPayload.input.event, { componentId: "server-rail", handlerId: "select-server", eventName: "click" });
|
||||
const deniedValuePayload = deniedEvents[1] as { input: { event: Record<string, unknown> } };
|
||||
assert.deepEqual(deniedValuePayload.input.event, { componentId: "server-rail", handlerId: "search", eventName: "input" });
|
||||
deniedApp.unmount();
|
||||
|
||||
const approvedValuePayload = await runInput(["ui.input.read"]);
|
||||
assert.deepEqual(approvedValuePayload.input.event, {
|
||||
componentId: "server-rail", handlerId: "search", eventName: "input", value: "private search text",
|
||||
});
|
||||
} finally {
|
||||
if (previousInputConstructor) Object.defineProperty(globalThis, "HTMLInputElement", previousInputConstructor);
|
||||
else Reflect.deleteProperty(globalThis, "HTMLInputElement");
|
||||
}
|
||||
});
|
||||
|
||||
test("generated UI rejects executable elements, event handlers, and network/navigation sinks", () => {
|
||||
|
||||
@@ -65,7 +65,7 @@ function skipSignedLeb128(bytes: Uint8Array, offset: number, end: number, maxByt
|
||||
function requireScalarValueType(bytes: Uint8Array, offset: number, end: number): number {
|
||||
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains a truncated value type.");
|
||||
if (!SCALAR_VALUE_TYPES.has(bytes[offset])) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts numeric scalar types only; reference, vector, and GC types are disabled.");
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm runtime accepts numeric scalar types only; reference, vector, and GC types are disabled.");
|
||||
}
|
||||
return offset + 1;
|
||||
}
|
||||
@@ -76,7 +76,7 @@ function validateTypeSection(bytes: Uint8Array, start: number, end: number): voi
|
||||
for (let typeIndex = 0; typeIndex < cursor.value; typeIndex += 1) {
|
||||
if (cursor.next >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension type section is truncated.");
|
||||
if (bytes[cursor.next++] !== 0x60) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts function types only; GC and recursive types are disabled.");
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm runtime accepts function types only; GC and recursive types are disabled.");
|
||||
}
|
||||
const parameters = readU32(bytes, cursor.next, end);
|
||||
cursor.next = parameters.next;
|
||||
@@ -100,7 +100,7 @@ function readBlockType(bytes: Uint8Array, offset: number, end: number): number {
|
||||
const valueType = bytes[offset];
|
||||
if (valueType === 0x40 || SCALAR_VALUE_TYPES.has(valueType)) return offset + 1;
|
||||
if (valueType === 0x6f || valueType === 0x70 || valueType === 0x7b || valueType === 0x63 || valueType === 0x64) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Reference and vector block types are disabled in the Wasm prototype.");
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Reference and vector block types are disabled in the Wasm runtime.");
|
||||
}
|
||||
return skipSignedLeb128(bytes, offset, end, 5);
|
||||
}
|
||||
@@ -210,7 +210,7 @@ function scanFunctionBody(bytes: Uint8Array, start: number, end: number): number
|
||||
}
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Table, GC, SIMD, thread, and unknown Wasm extension instructions are disabled.");
|
||||
}
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts scalar core instructions only; reference, GC, SIMD, thread, and unknown extension instructions are disabled.");
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm runtime accepts scalar core instructions only; reference, GC, SIMD, thread, and unknown extension instructions are disabled.");
|
||||
}
|
||||
return localCount;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createSkinExtensionApproval, parseSkinExtensionManifest } from "../../../src/shared/skin-extension.js";
|
||||
import {
|
||||
createSkinExtensionWasmSandboxPrototype,
|
||||
createSkinExtensionWasmSandbox,
|
||||
SKIN_EXTENSION_WASM_RUNTIME_ENABLED,
|
||||
} from "./skin-extension-wasm-sandbox.js";
|
||||
import { SKIN_EXTENSION_WASM_SOURCE_LIMIT } from "./skin-extension-wasm-policy.js";
|
||||
@@ -18,14 +18,13 @@ const manifest = parseSkinExtensionManifest({
|
||||
permissions: [],
|
||||
});
|
||||
|
||||
test("production Wasm execution remains disabled while the bounded runner is prototype-only", () => {
|
||||
assert.equal(SKIN_EXTENSION_WASM_RUNTIME_ENABLED, false);
|
||||
assert.throws(() => createSkinExtensionWasmSandboxPrototype({
|
||||
test("production Wasm runtime is enabled behind the bounded approval and ABI checks", () => {
|
||||
assert.equal(SKIN_EXTENSION_WASM_RUNTIME_ENABLED, true);
|
||||
assert.throws(() => createSkinExtensionWasmSandbox({
|
||||
manifest,
|
||||
approval: createSkinExtensionApproval(manifest),
|
||||
wasmBytes: new Uint8Array(SKIN_EXTENSION_WASM_SOURCE_LIMIT + 1),
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
}), { code: "SKIN_EXTENSION_WASM_SIZE" });
|
||||
});
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES,
|
||||
} from "../../../src/shared/skin-extension-ui-input.js";
|
||||
|
||||
export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = false as const;
|
||||
export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = true as const;
|
||||
|
||||
export class SkinExtensionWasmSandboxError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
@@ -46,8 +46,6 @@ export interface SkinExtensionWasmSandboxOptions {
|
||||
/** Bounded local component state and optional safe fields from a trusted UI event. */
|
||||
uiInput?: unknown;
|
||||
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
|
||||
/** This prototype is available only to the development security harness. */
|
||||
prototypeOnly: true;
|
||||
}
|
||||
|
||||
export interface SkinExtensionWasmSandboxHandle {
|
||||
@@ -72,9 +70,8 @@ function messageSize(value: unknown): number {
|
||||
catch { return SKIN_EXTENSION_WASM_MESSAGE_LIMIT + 1; }
|
||||
}
|
||||
|
||||
/** Development-only Wasm runner: no author JavaScript is evaluated and every job owns one terminable Worker. */
|
||||
export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWasmSandboxOptions): SkinExtensionWasmSandboxHandle {
|
||||
if (options.prototypeOnly !== true) throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_PROTOTYPE_ONLY", "The Wasm runner is a development-only security prototype.");
|
||||
/** Runs one approved Wasm module in a disposable worker with bounded memory and execution. */
|
||||
export function createSkinExtensionWasmSandbox(options: SkinExtensionWasmSandboxOptions): SkinExtensionWasmSandboxHandle {
|
||||
if (!(options.wasmBytes instanceof Uint8Array) || !options.wasmBytes.byteLength || options.wasmBytes.byteLength > SKIN_EXTENSION_WASM_SOURCE_LIMIT) {
|
||||
throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_SIZE", "The extension module is empty or exceeds its source limit.");
|
||||
}
|
||||
@@ -92,7 +89,7 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
|
||||
const wasmBytes = options.wasmBytes.slice();
|
||||
const worker = new Worker(new URL("./skin-extension-wasm-worker.ts", import.meta.url), {
|
||||
type: "module",
|
||||
name: "webspeak-skin-extension-wasm-prototype",
|
||||
name: "webspeak-skin-extension-wasm",
|
||||
});
|
||||
|
||||
let active = true;
|
||||
|
||||
@@ -4,7 +4,7 @@ import test from "node:test";
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import type { SkinPluginDocument, SkinPluginNode } from "../../../src/shared/skin-plugin.js";
|
||||
import { createSkinExtensionWasmPrefixByteImmediateProbe } from "../../test/skin-extension-wasm-fixture.js";
|
||||
|
||||
const manifest = {
|
||||
@@ -513,6 +513,37 @@ test("the full voice surface example packages home, voice, and host-owned contro
|
||||
assert.ok(skin.css.includes("@media (max-width: 800px)"));
|
||||
});
|
||||
|
||||
test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspace", async () => {
|
||||
const archive = await readFile(new URL("../../../docs/examples/harbor-voice.wskin", import.meta.url));
|
||||
const file = new File([archive], "harbor-voice.wskin", { type: "application/octet-stream" });
|
||||
const skin = await importSkinPack(file);
|
||||
assert.equal(skin.id, "community.harbor-voice");
|
||||
assert.equal(skin.pluginData?.schemaVersion, 3);
|
||||
assert.deepEqual(skin.pluginData?.components.map((component) => [component.page, component.mode]), [
|
||||
["home", "surface"], ["voice", "surface"],
|
||||
]);
|
||||
const voiceSurface = skin.pluginData?.components.find((component) => component.page === "voice");
|
||||
assert.ok(voiceSurface?.permissions.includes("session.channel.join"));
|
||||
assert.ok(voiceSurface?.permissions.includes("servers.quickList.switch"));
|
||||
assert.ok(voiceSurface?.permissions.includes("session.members.read"));
|
||||
function findPart(node: SkinPluginNode | undefined, part: string): SkinPluginNode | undefined {
|
||||
if (!node) return undefined;
|
||||
if (node.part === part) return node;
|
||||
for (const child of node.children ?? []) {
|
||||
const found = findPart(child, part);
|
||||
if (found) return found;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const channelRow = findPart(voiceSurface?.root, "channel-row");
|
||||
assert.equal(channelRow?.events?.dblclick, "join-channel", "channel switching follows TeamSpeak's double-click join behavior");
|
||||
const channelVoiceMembers = findPart(voiceSurface?.root, "channel-voice-members");
|
||||
assert.equal(channelVoiceMembers?.when?.path, "channel.current");
|
||||
assert.equal(findPart(channelVoiceMembers, "channel-voice-member")?.repeat?.path, "channel.members");
|
||||
assert.ok(skin.css.includes("@media (max-width: 820px)"));
|
||||
assert.ok(!skin.css.includes("https://"), "the skin uses no remote artwork or font resources");
|
||||
});
|
||||
|
||||
function makeSkinV2(layout: unknown, manifestChanges: Record<string, unknown> = {}): File {
|
||||
const packageFiles: Record<string, Uint8Array> = {
|
||||
"manifest.json": strToU8(JSON.stringify({
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createSkinRuntimePluginWasmGovernor, SkinRuntimePluginWasmGovernorError } from "./skin-runtime-plugin-wasm-governor.js";
|
||||
|
||||
test("Wasm worker governor grants slots FIFO and releases each slot once", async () => {
|
||||
const governor = createSkinRuntimePluginWasmGovernor({ maxConcurrentRuns: 1, maxPendingRuns: 2, queueTimeoutMs: 100 });
|
||||
const first = await governor.acquire(new AbortController().signal);
|
||||
const order: number[] = [];
|
||||
const second = governor.acquire(new AbortController().signal).then((release) => { order.push(2); return release; });
|
||||
const third = governor.acquire(new AbortController().signal).then((release) => { order.push(3); return release; });
|
||||
assert.equal(governor.activeRuns, 1);
|
||||
assert.equal(governor.pendingRuns, 2);
|
||||
first();
|
||||
first();
|
||||
const secondRelease = await second;
|
||||
assert.deepEqual(order, [2]);
|
||||
secondRelease();
|
||||
const thirdRelease = await third;
|
||||
assert.deepEqual(order, [2, 3]);
|
||||
thirdRelease();
|
||||
assert.equal(governor.activeRuns, 0);
|
||||
});
|
||||
|
||||
test("Wasm worker governor bounds its queue and removes cancelled waiters", async () => {
|
||||
const governor = createSkinRuntimePluginWasmGovernor({ maxConcurrentRuns: 1, maxPendingRuns: 1, queueTimeoutMs: 100 });
|
||||
const release = await governor.acquire(new AbortController().signal);
|
||||
const cancelled = new AbortController();
|
||||
const waiting = governor.acquire(cancelled.signal);
|
||||
assert.equal(governor.pendingRuns, 1);
|
||||
await assert.rejects(governor.acquire(new AbortController().signal), (error: unknown) =>
|
||||
error instanceof SkinRuntimePluginWasmGovernorError && error.code === "SKIN_EXTENSION_WASM_QUEUE_FULL");
|
||||
cancelled.abort();
|
||||
await assert.rejects(waiting, (error: unknown) =>
|
||||
error instanceof SkinRuntimePluginWasmGovernorError && error.code === "SKIN_EXTENSION_WASM_QUEUE_CANCELLED");
|
||||
assert.equal(governor.pendingRuns, 0);
|
||||
release();
|
||||
assert.equal(governor.activeRuns, 0);
|
||||
});
|
||||
|
||||
test("Wasm worker governor rejects queued work after the bounded wait", async () => {
|
||||
const governor = createSkinRuntimePluginWasmGovernor({ maxConcurrentRuns: 1, maxPendingRuns: 1, queueTimeoutMs: 5 });
|
||||
const release = await governor.acquire(new AbortController().signal);
|
||||
await assert.rejects(governor.acquire(new AbortController().signal), (error: unknown) =>
|
||||
error instanceof SkinRuntimePluginWasmGovernorError && error.code === "SKIN_EXTENSION_WASM_QUEUE_TIMEOUT");
|
||||
assert.equal(governor.pendingRuns, 0);
|
||||
release();
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
export const SKIN_RUNTIME_PLUGIN_WASM_MAX_CONCURRENT_RUNS = 2;
|
||||
export const SKIN_RUNTIME_PLUGIN_WASM_MAX_PENDING_RUNS = 64;
|
||||
export const SKIN_RUNTIME_PLUGIN_WASM_QUEUE_TIMEOUT_MS = 120_000;
|
||||
|
||||
export class SkinRuntimePluginWasmGovernorError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "SkinRuntimePluginWasmGovernorError";
|
||||
}
|
||||
}
|
||||
|
||||
interface Waiter {
|
||||
signal: AbortSignal;
|
||||
resolve(release: () => void): void;
|
||||
reject(error: Error): void;
|
||||
onAbort: () => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
export interface SkinRuntimePluginWasmGovernorOptions {
|
||||
maxConcurrentRuns: number;
|
||||
maxPendingRuns: number;
|
||||
queueTimeoutMs: number;
|
||||
}
|
||||
|
||||
/** Fairly limits guest workers across all runtime plugins in this WebClient. */
|
||||
export function createSkinRuntimePluginWasmGovernor(options: SkinRuntimePluginWasmGovernorOptions) {
|
||||
if (!Number.isSafeInteger(options.maxConcurrentRuns) || options.maxConcurrentRuns < 1
|
||||
|| !Number.isSafeInteger(options.maxPendingRuns) || options.maxPendingRuns < 0
|
||||
|| !Number.isSafeInteger(options.queueTimeoutMs) || options.queueTimeoutMs < 1) {
|
||||
throw new RangeError("The Wasm worker governor requires positive integer limits.");
|
||||
}
|
||||
|
||||
let activeRuns = 0;
|
||||
const waiters: Waiter[] = [];
|
||||
|
||||
function removeWaiter(waiter: Waiter): void {
|
||||
const index = waiters.indexOf(waiter);
|
||||
if (index >= 0) waiters.splice(index, 1);
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
||||
}
|
||||
|
||||
function lease(): () => void {
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
activeRuns -= 1;
|
||||
drain();
|
||||
};
|
||||
}
|
||||
|
||||
function drain(): void {
|
||||
while (activeRuns < options.maxConcurrentRuns && waiters.length > 0) {
|
||||
const waiter = waiters.shift()!;
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
||||
if (waiter.signal.aborted) {
|
||||
waiter.reject(new SkinRuntimePluginWasmGovernorError("SKIN_EXTENSION_WASM_QUEUE_CANCELLED", "The plugin run was cancelled while waiting for an execution slot."));
|
||||
continue;
|
||||
}
|
||||
activeRuns += 1;
|
||||
waiter.resolve(lease());
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get activeRuns() { return activeRuns; },
|
||||
get pendingRuns() { return waiters.length; },
|
||||
acquire(signal: AbortSignal): Promise<() => void> {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(new SkinRuntimePluginWasmGovernorError("SKIN_EXTENSION_WASM_QUEUE_CANCELLED", "The plugin run was cancelled before acquiring an execution slot."));
|
||||
}
|
||||
if (activeRuns < options.maxConcurrentRuns && waiters.length === 0) {
|
||||
activeRuns += 1;
|
||||
return Promise.resolve(lease());
|
||||
}
|
||||
if (waiters.length >= options.maxPendingRuns) {
|
||||
return Promise.reject(new SkinRuntimePluginWasmGovernorError("SKIN_EXTENSION_WASM_QUEUE_FULL", "Too many skin plugin runs are waiting for an execution slot."));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let waiter!: Waiter;
|
||||
const onAbort = () => {
|
||||
removeWaiter(waiter);
|
||||
reject(new SkinRuntimePluginWasmGovernorError("SKIN_EXTENSION_WASM_QUEUE_CANCELLED", "The plugin run was cancelled while waiting for an execution slot."));
|
||||
drain();
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
removeWaiter(waiter);
|
||||
reject(new SkinRuntimePluginWasmGovernorError("SKIN_EXTENSION_WASM_QUEUE_TIMEOUT", "The plugin run waited too long for an execution slot."));
|
||||
drain();
|
||||
}, options.queueTimeoutMs);
|
||||
waiter = { signal, resolve, reject, onAbort, timer };
|
||||
waiters.push(waiter);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const skinRuntimePluginWasmGovernor = createSkinRuntimePluginWasmGovernor({
|
||||
maxConcurrentRuns: SKIN_RUNTIME_PLUGIN_WASM_MAX_CONCURRENT_RUNS,
|
||||
maxPendingRuns: SKIN_RUNTIME_PLUGIN_WASM_MAX_PENDING_RUNS,
|
||||
queueTimeoutMs: SKIN_RUNTIME_PLUGIN_WASM_QUEUE_TIMEOUT_MS,
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import "./skin-runtime-plugin-session.test.js";
|
||||
import "./skin-runtime-plugin-wasm-governor.test.js";
|
||||
import {
|
||||
computeSkinRuntimePluginDigest,
|
||||
createSkinRuntimePluginApproval,
|
||||
@@ -8,7 +9,7 @@ import {
|
||||
import { parseSkinRuntimePluginDocument } from "../../../src/shared/skin-runtime-plugins.js";
|
||||
import { createSkinExtensionWasmPrefixByteImmediateProbe } from "../../test/skin-extension-wasm-fixture.js";
|
||||
import {
|
||||
createSkinRuntimePluginWasmSandboxPrototype,
|
||||
createSkinRuntimePluginWasmSandbox,
|
||||
SkinRuntimePluginWasmError,
|
||||
} from "./skin-runtime-plugin-wasm.js";
|
||||
|
||||
@@ -37,14 +38,13 @@ async function approvedFiles(source = createSkinExtensionWasmPrefixByteImmediate
|
||||
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) };
|
||||
await assert.rejects(createSkinRuntimePluginWasmSandboxPrototype({
|
||||
await assert.rejects(createSkinRuntimePluginWasmSandbox({
|
||||
skinId: "community.sample",
|
||||
skinVersion: "2.0.0",
|
||||
plugin,
|
||||
approval: staleApproval,
|
||||
files,
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
}), (error: unknown) => error instanceof SkinRuntimePluginWasmError && error.code === "SKIN_EXTENSION_WASM_APPROVAL_INVALID");
|
||||
});
|
||||
|
||||
@@ -75,14 +75,13 @@ test("Wasm prototype accepts a host-mediated channel join permission", async ()
|
||||
Object.defineProperty(globalThis, "Worker", { configurable: true, value: FakeWorker });
|
||||
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
|
||||
try {
|
||||
const handle = await createSkinRuntimePluginWasmSandboxPrototype({
|
||||
const handle = await createSkinRuntimePluginWasmSandbox({
|
||||
skinId: "community.sample",
|
||||
skinVersion: "2.0.0",
|
||||
plugin: writePlugin,
|
||||
approval,
|
||||
files,
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
});
|
||||
assert.equal((await handle.result).uiOutput, null);
|
||||
} finally {
|
||||
@@ -122,7 +121,7 @@ test("approved read permissions project only their public fields into each Wasm
|
||||
Object.defineProperty(globalThis, "Worker", { configurable: true, value: FakeWorker });
|
||||
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
|
||||
try {
|
||||
const handle = await createSkinRuntimePluginWasmSandboxPrototype({
|
||||
const handle = await createSkinRuntimePluginWasmSandbox({
|
||||
skinId: "community.sample",
|
||||
skinVersion: "2.0.0",
|
||||
plugin: readPlugin,
|
||||
@@ -136,7 +135,6 @@ test("approved read permissions project only their public fields into each Wasm
|
||||
favorites: { items: [{ id: "favorite-1", label: "Saved", address: "another-private.example:9987" }] },
|
||||
},
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
});
|
||||
await handle.result;
|
||||
const parsedInput = JSON.parse(inputJson) as { data: unknown };
|
||||
@@ -176,14 +174,13 @@ test("approved Wasm entries run as disposable workers with bounded interpreter o
|
||||
Object.defineProperty(globalThis, "Worker", { configurable: true, value: FakeWorker });
|
||||
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
|
||||
try {
|
||||
const handle = await createSkinRuntimePluginWasmSandboxPrototype({
|
||||
const handle = await createSkinRuntimePluginWasmSandbox({
|
||||
skinId: "community.sample",
|
||||
skinVersion: "2.0.0",
|
||||
plugin,
|
||||
approval,
|
||||
files,
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
});
|
||||
assert.deepEqual(await handle.result, {
|
||||
result: 7,
|
||||
|
||||
@@ -14,7 +14,7 @@ import { SKIN_PLUGIN_ACTION_PERMISSIONS } from "../../../src/shared/skin-plugin.
|
||||
import { projectSkinRuntimePluginContext, SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-runtime-plugin-context.js";
|
||||
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
import {
|
||||
createSkinExtensionWasmSandboxPrototype,
|
||||
createSkinExtensionWasmSandbox,
|
||||
type SkinExtensionWasmSandboxHandle,
|
||||
} from "./skin-extension-wasm-sandbox.js";
|
||||
|
||||
@@ -35,22 +35,20 @@ export interface SkinRuntimePluginWasmOptions {
|
||||
/** Trusted WebClient snapshot; it is projected using the plugin's declared read permissions. */
|
||||
context?: unknown;
|
||||
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
|
||||
prototypeOnly: true;
|
||||
}
|
||||
|
||||
const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, ...SKIN_PLUGIN_ACTION_PERMISSIONS, "ui.surface.replace"]);
|
||||
const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, ...SKIN_PLUGIN_ACTION_PERMISSIONS, "ui.surface.replace", "ui.input.read"]);
|
||||
|
||||
/** Starts a Wasm entry only after rechecking the exact package digest and local approval. */
|
||||
export async function createSkinRuntimePluginWasmSandboxPrototype(
|
||||
export async function createSkinRuntimePluginWasmSandbox(
|
||||
options: SkinRuntimePluginWasmOptions,
|
||||
): Promise<SkinExtensionWasmSandboxHandle> {
|
||||
if (options.prototypeOnly !== true) throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_PROTOTYPE_ONLY", "The Wasm runner is a development-only security prototype.");
|
||||
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.");
|
||||
|
||||
const unsupportedPermission = plugin.permissions.find((permission) => !WASM_PROTOTYPE_PERMISSIONS.has(permission));
|
||||
if (unsupportedPermission) {
|
||||
throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_PERMISSION_UNSUPPORTED", `The Wasm prototype does not implement ${unsupportedPermission}.`);
|
||||
throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_PERMISSION_UNSUPPORTED", `The Wasm runtime does not implement ${unsupportedPermission}.`);
|
||||
}
|
||||
|
||||
const digest = await computeSkinRuntimePluginDigest(plugin, options.files);
|
||||
@@ -80,12 +78,11 @@ export async function createSkinRuntimePluginWasmSandboxPrototype(
|
||||
});
|
||||
|
||||
// This legacy approval object is created only after the v4 digest-bound host approval above.
|
||||
return createSkinExtensionWasmSandboxPrototype({
|
||||
return createSkinExtensionWasmSandbox({
|
||||
manifest,
|
||||
approval: createSkinExtensionApproval(manifest),
|
||||
wasmBytes,
|
||||
uiInput,
|
||||
readSessionStatus: options.readSessionStatus,
|
||||
prototypeOnly: true,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user