feat(skin): project bounded read data into Wasm plugins

This commit is contained in:
illusia committed 2026-10-10 15:53:50 +08:00
1 parent 7650bd650b
commit 1aa29158ef
17 files changed
+450 -42

No files matched your search

@@ -39,6 +39,23 @@ test("Wasm UI input preserves bounded local state and safe event data", () => {
assert.deepEqual(parsed.event, { componentId: "server-rail", handlerId: "select-server", eventName: "click" });
});
test("Wasm UI input sanitizes host-projected public data before it enters the guest", () => {
const parsed = parseSkinExtensionUiInput({
schemaVersion: 1,
state: {},
event: null,
data: {
session: {
channels: [{ id: "lobby", name: "Lobby", address: "private.example:9987", members: [{ name: "not a projected field" }] }],
},
private: { token: "must not cross the guest boundary" },
},
});
assert.deepEqual(JSON.parse(JSON.stringify(parsed.data)), {
session: { channels: [{ id: "lobby", name: "Lobby" }] },
});
});
test("Wasm UI input rejects unsupported fields, oversized text, and mismatched event values", () => {
assert.throws(() => parseSkinExtensionUiInput({ schemaVersion: 1, state: {}, event: null, trusted: true }), {
code: "SKIN_EXTENSION_UI_INPUT_INVALID",
@@ -57,6 +57,25 @@ test("Wasm UI callback reruns receive only declared component state and replace
loop.close();
});
test("runtime data refresh reruns the guest without fabricating a user event", async () => {
const jobs: SkinExtensionUiInput[] = [];
const loop = createSkinExtensionWasmUiLoopPrototype({
createRun(input) {
jobs.push(input);
const count = input.event ? Number(input.state.count) + 1 : Number(input.state.count ?? 0);
return { result: Promise.resolve({ uiOutput: uiOutput(count) }), close: () => undefined };
},
});
assert.equal(await loop.start(), true);
assert.equal(await loop.dispatch(clickInput(3)), true);
assert.equal(await loop.refresh(), true);
assert.equal(jobs.length, 3);
assert.equal(jobs[2].event, null);
assert.deepEqual({ ...jobs[2].state }, { count: 3 });
loop.close();
});
test("Wasm UI callback queue is bounded and close cancels active and waiting work", async () => {
let rejectActive!: (error: Error) => void;
let held = false;
@@ -56,8 +56,9 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
let running = false;
let output: string | null = null;
let document: SkinPluginDocument | null = null;
let lastState: Record<string, string | number | boolean> = Object.create(null) as Record<string, string | number | boolean>;
let activeRun: SkinExtensionWasmUiLoopRunHandle | null = null;
const queue: Array<{ input: SkinExtensionUiInput; resolve: (ran: boolean) => void }> = [];
const queue: Array<{ input: SkinExtensionUiInput; kind: "event" | "refresh"; resolve: Array<(ran: boolean) => void> }> = [];
function report(error: unknown): void {
try { options.onError?.(error instanceof Error ? error : new Error("The bounded Wasm UI callback failed.")); }
@@ -71,6 +72,7 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
activeRun = run;
const result = await run.result;
if (closed || activeRun !== run) return false;
lastState = { ...input.state };
if (result.uiOutput !== null) {
const nextDocument = parseSkinExtensionUiOutput(result.uiOutput);
output = result.uiOutput;
@@ -92,11 +94,15 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
try {
while (queue.length && !closed) {
const pending = queue.shift()!;
if (!acceptsEvent(document, pending.input)) {
pending.resolve(false);
const accepted = pending.kind === "refresh"
? pending.input.event === null
: acceptsEvent(document, pending.input);
if (!accepted) {
pending.resolve.forEach((resolve) => resolve(false));
continue;
}
pending.resolve(await execute(pending.input));
const ran = await execute(pending.input);
pending.resolve.forEach((resolve) => resolve(ran));
}
} finally {
running = false;
@@ -106,7 +112,7 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
return {
get output() { return output; },
get pendingEventCount() { return queue.length; },
get pendingEventCount() { return queue.filter((item) => item.kind === "event").length; },
get running() { return running || activeRun !== null; },
get closed() { return closed; },
async start(): Promise<boolean> {
@@ -121,14 +127,27 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
try { input = parseSkinExtensionUiInput(inputValue); }
catch { return Promise.resolve(false); }
if (!acceptsEvent(document, input) || queue.length >= SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT) return Promise.resolve(false);
const result = new Promise<boolean>((resolve) => queue.push({ input, resolve }));
const result = new Promise<boolean>((resolve) => queue.push({ input, kind: "event", resolve: [resolve] }));
void drain();
return result;
},
refresh(): Promise<boolean> {
if (!started || closed) return Promise.resolve(false);
const input = parseSkinExtensionUiInput({ schemaVersion: 1, state: { ...lastState }, event: null });
const queued = queue.find((item) => item.kind === "refresh");
if (queued) {
queued.input = input;
return new Promise<boolean>((resolve) => queued.resolve.push(resolve));
}
if (queue.length >= SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT) return Promise.resolve(false);
const result = new Promise<boolean>((resolve) => queue.push({ input, kind: "refresh", resolve: [resolve] }));
void drain();
return result;
},
close(reason = "closed"): void {
if (closed) return;
closed = true;
queue.splice(0).forEach((pending) => pending.resolve(false));
queue.splice(0).forEach((pending) => pending.resolve.forEach((resolve) => resolve(false)));
activeRun?.close(reason);
activeRun = null;
},
@@ -44,6 +44,7 @@ export function createSkinRuntimePluginSession(options: SkinRuntimePluginSession
get running() { return loop.running; },
start: () => loop.start(),
dispatch: (input: unknown) => loop.dispatch(input),
refresh: () => loop.refresh(),
close: (reason?: string) => loop.close(reason),
};
}
@@ -48,18 +48,18 @@ test("Wasm plugin startup rechecks the exact digest approval before creating a W
}), (error: unknown) => error instanceof SkinRuntimePluginWasmError && error.code === "SKIN_EXTENSION_WASM_APPROVAL_INVALID");
});
test("Wasm prototype refuses v4 capabilities it does not implement", async () => {
const channelPlugin = parseSkinRuntimePluginDocument({
test("Wasm prototype refuses write permissions that have no host action bridge", async () => {
const writePlugin = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{ ...plugin, permissions: ["session.channels.read"] }],
plugins: [{ ...plugin, permissions: ["session.channel.join"] }],
}).plugins[0];
const files = { [channelPlugin.entry]: new Blob([createSkinExtensionWasmPrefixByteImmediateProbe()]) };
const digest = await computeSkinRuntimePluginDigest(channelPlugin, files);
const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", channelPlugin, digest);
const files = { [writePlugin.entry]: new Blob([createSkinExtensionWasmPrefixByteImmediateProbe()]) };
const digest = await computeSkinRuntimePluginDigest(writePlugin, files);
const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", writePlugin, digest);
await assert.rejects(createSkinRuntimePluginWasmSandboxPrototype({
skinId: "community.sample",
skinVersion: "2.0.0",
plugin: channelPlugin,
plugin: writePlugin,
approval,
files,
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
@@ -68,6 +68,67 @@ test("Wasm prototype refuses v4 capabilities it does not implement", async () =>
&& error.code === "SKIN_EXTENSION_WASM_PERMISSION_UNSUPPORTED");
});
test("approved read permissions project only their public fields into each Wasm job", async () => {
const readPlugin = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{ ...plugin, permissions: ["session.channels.read"] }],
}).plugins[0];
const files = { [readPlugin.entry]: new Blob([createSkinExtensionWasmPrefixByteImmediateProbe()]) };
const digest = await computeSkinRuntimePluginDigest(readPlugin, files);
const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", readPlugin, digest);
const previousWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker");
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
let inputJson = "";
class FakeWorker {
onmessage: ((event: MessageEvent<unknown>) => void) | null = null;
onmessageerror: (() => void) | null = null;
onerror: (() => void) | null = null;
postMessage(message: unknown): void {
if (message && typeof message === "object" && "input" in message && typeof message.input === "string") inputJson = message.input;
queueMicrotask(() => {
this.onmessage?.({ data: { type: "running" } } as MessageEvent<unknown>);
this.onmessage?.({ data: {
type: "complete", result: 1, linearMemoryBytes: 65_536, statusReadCount: 0, uiInputReadCount: 0, uiOutput: null,
} } as MessageEvent<unknown>);
});
}
terminate(): void { /* The test worker has no external resources. */ }
}
Object.defineProperty(globalThis, "Worker", { configurable: true, value: FakeWorker });
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
try {
const handle = await createSkinRuntimePluginWasmSandboxPrototype({
skinId: "community.sample",
skinVersion: "2.0.0",
plugin: readPlugin,
approval,
files,
context: {
session: {
status: { connected: true, serverLabel: "private.example:9987" },
channels: [{ id: "lobby", name: "Lobby", depth: 0, memberCount: 1, current: true, address: "voice.internal.example:9987" }],
},
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 };
assert.deepEqual(JSON.parse(JSON.stringify(parsedInput.data)), {
session: { channels: [{ id: "lobby", name: "Lobby", depth: 0, memberCount: 1, current: true }] },
});
assert.equal(inputJson.includes("private.example"), false);
assert.equal(inputJson.includes("voice.internal.example"), false);
assert.equal(inputJson.includes("favorite-1"), false);
} finally {
if (previousWorker) Object.defineProperty(globalThis, "Worker", previousWorker);
else Reflect.deleteProperty(globalThis, "Worker");
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
test("approved Wasm entries run as disposable workers with bounded interpreter output", async () => {
const { files, approval } = await approvedFiles();
const previousWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker");
+11 -2
View File
@@ -10,6 +10,8 @@ import {
type SkinRuntimePluginApproval,
} from "../../../src/shared/skin-runtime-plugin-approval.js";
import { parseSkinRuntimePluginDocument, type SkinRuntimePlugin } from "../../../src/shared/skin-runtime-plugins.js";
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,
type SkinExtensionWasmSandboxHandle,
@@ -29,11 +31,13 @@ export interface SkinRuntimePluginWasmOptions {
approval: unknown;
files: Readonly<Record<string, Blob>>;
uiInput?: unknown;
/** 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(["session.status.read", "ui.surface.replace"]);
const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, "ui.surface.replace"]);
/** Starts a Wasm entry only after rechecking the exact package digest and local approval. */
export async function createSkinRuntimePluginWasmSandboxPrototype(
@@ -59,6 +63,11 @@ export async function createSkinRuntimePluginWasmSandboxPrototype(
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());
const baseInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
const uiInput = parseSkinExtensionUiInput({
...baseInput,
data: projectSkinRuntimePluginContext(plugin.permissions, options.context),
});
const manifest = parseSkinExtensionManifest({
schemaVersion: 1,
packageType: "extension",
@@ -74,7 +83,7 @@ export async function createSkinRuntimePluginWasmSandboxPrototype(
manifest,
approval: createSkinExtensionApproval(manifest),
wasmBytes,
uiInput: options.uiInput,
uiInput,
readSessionStatus: options.readSessionStatus,
prototypeOnly: true,
});