mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
feat(skin): prototype bounded UI callback inputs
This commit is contained in:
1 parent
c3810a177a
commit
54c77bcb27
17 files changed
+567
-62
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createSSRApp } from "vue";
|
||||
import { createRenderer, createSSRApp, nextTick } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import {
|
||||
@@ -79,6 +79,126 @@ test("generated UI supports broad safe markup, ARIA/data attributes, and inert c
|
||||
assert.equal(document.components[0].root.children?.[1].tag, "button");
|
||||
});
|
||||
|
||||
test("generated UI schema 5 carries bounded state and named callbacks for a trusted host event loop", () => {
|
||||
const source = JSON.stringify({
|
||||
schemaVersion: 5,
|
||||
components: [{
|
||||
id: "server-rail",
|
||||
name: "Server rail",
|
||||
page: "voice",
|
||||
accessibleName: "Saved voice servers",
|
||||
state: { expanded: false, selected: "home" },
|
||||
root: {
|
||||
tag: "nav",
|
||||
children: [{
|
||||
tag: "button",
|
||||
attributes: { type: "button", "aria-pressed": false },
|
||||
events: { click: "select-server" },
|
||||
children: [{ text: "Home" }],
|
||||
}],
|
||||
},
|
||||
}],
|
||||
});
|
||||
const document = parseSkinExtensionUiOutput(source);
|
||||
const component = document.components[0];
|
||||
assert.equal(component.runtimeCallbacks, true);
|
||||
assert.deepEqual({ ...component.state }, { expanded: false, selected: "home" });
|
||||
assert.equal(component.root.children?.[0].events?.click, "select-server");
|
||||
});
|
||||
|
||||
test("generated UI callbacks reject unsupported events, malformed IDs, and password inputs", () => {
|
||||
const schema5 = (root: Record<string, unknown>) => JSON.stringify({
|
||||
schemaVersion: 5,
|
||||
components: [{ id: "runtime-ui", name: "Runtime UI", page: "voice", accessibleName: "Runtime UI", root }],
|
||||
});
|
||||
expectOutputError(schema5({ tag: "button", events: { animationstart: "run" } }), "SKIN_EXTENSION_UI_OUTPUT_SCHEMA");
|
||||
expectOutputError(schema5({ tag: "button", events: { click: "../run" } }), "SKIN_EXTENSION_UI_OUTPUT_SCHEMA");
|
||||
expectOutputError(schema5({ tag: "input", attributes: { type: "password" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
|
||||
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 () => {
|
||||
interface HostNode {
|
||||
type: string;
|
||||
props: Record<string, unknown>;
|
||||
text: string;
|
||||
children: HostNode[];
|
||||
parent?: HostNode;
|
||||
}
|
||||
const createHostNode = (type: string, text = ""): HostNode => ({ type, props: {}, text, children: [] });
|
||||
const renderer = createRenderer<HostNode, HostNode>({
|
||||
patchProp(node, key, _previous, next) { node.props[key] = next; },
|
||||
insert(node, parent, anchor) {
|
||||
node.parent = parent;
|
||||
const oldIndex = parent.children.indexOf(node);
|
||||
if (oldIndex >= 0) parent.children.splice(oldIndex, 1);
|
||||
const anchorIndex = anchor ? parent.children.indexOf(anchor) : -1;
|
||||
parent.children.splice(anchorIndex >= 0 ? anchorIndex : parent.children.length, 0, node);
|
||||
},
|
||||
remove(node) {
|
||||
const parent = node.parent;
|
||||
if (!parent) return;
|
||||
const index = parent.children.indexOf(node);
|
||||
if (index >= 0) parent.children.splice(index, 1);
|
||||
node.parent = undefined;
|
||||
},
|
||||
createElement: (type) => createHostNode(type),
|
||||
createText: (text) => createHostNode("#text", text),
|
||||
createComment: (text) => createHostNode("#comment", text),
|
||||
setText(node, text) { node.text = text; },
|
||||
setElementText(node, text) { node.children = []; node.text = text; },
|
||||
parentNode: (node) => node.parent ?? null,
|
||||
nextSibling(node) {
|
||||
if (!node.parent) return null;
|
||||
const index = node.parent.children.indexOf(node);
|
||||
return node.parent.children[index + 1] ?? null;
|
||||
},
|
||||
});
|
||||
const document: SkinPluginDocument = {
|
||||
schemaVersion: 3,
|
||||
components: [{
|
||||
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),
|
||||
});
|
||||
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();
|
||||
});
|
||||
|
||||
test("generated UI rejects executable elements, event handlers, and network/navigation sinks", () => {
|
||||
expectOutputError(generatedOutput("runtime-ui", { tag: "script" }), "SKIN_EXTENSION_UI_ELEMENT_INVALID");
|
||||
expectOutputError(generatedOutput("runtime-ui", { tag: "iframe" }), "SKIN_EXTENSION_UI_ELEMENT_INVALID");
|
||||
|
||||
@@ -20,12 +20,13 @@ import {
|
||||
createSkinExtensionWasmPrefixByteImmediateProbe,
|
||||
createSkinExtensionWasmStatusProbe,
|
||||
createSkinExtensionWasmTooManyFunctionsProbe,
|
||||
createSkinExtensionWasmUiInputProbe,
|
||||
createSkinExtensionWasmUiOutputProbe,
|
||||
} from "../../test/skin-extension-wasm-fixture.js";
|
||||
|
||||
test("Wasm metadata policy accepts only a single run export and one bounded host memory", () => {
|
||||
const metadata = validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmPrefixByteImmediateProbe());
|
||||
assert.deepEqual(metadata, { usesSessionStatus: false, usesUiOutput: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
|
||||
assert.deepEqual(metadata, { usesSessionStatus: false, usesUiInput: false, usesUiOutput: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
|
||||
});
|
||||
|
||||
test("Wasm policy rejects module-defined memory or tables that bypass host limits", () => {
|
||||
@@ -84,12 +85,20 @@ test("Wasm import parsing reads the bounded permission contract without native c
|
||||
});
|
||||
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(status, ["session.status.read"]), {
|
||||
usesSessionStatus: true,
|
||||
usesUiInput: false,
|
||||
usesUiOutput: false,
|
||||
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
});
|
||||
assert.equal(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmCappedRunProbe()).usesSessionStatus, false);
|
||||
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmUiOutputProbe()), {
|
||||
usesSessionStatus: false,
|
||||
usesUiInput: false,
|
||||
usesUiOutput: true,
|
||||
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
});
|
||||
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmUiInputProbe()), {
|
||||
usesSessionStatus: false,
|
||||
usesUiInput: true,
|
||||
usesUiOutput: true,
|
||||
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
});
|
||||
@@ -100,6 +109,7 @@ test("Wasm instruction scanning distinguishes extension prefixes from signed int
|
||||
assert.doesNotThrow(() => validateSkinExtensionWasmBytes(bytes));
|
||||
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(bytes), {
|
||||
usesSessionStatus: false,
|
||||
usesUiInput: false,
|
||||
usesUiOutput: false,
|
||||
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ const WASM_HEADER = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00] as const;
|
||||
const SCALAR_VALUE_TYPES = new Set([0x7f, 0x7e, 0x7d, 0x7c]);
|
||||
const BOUNDED_VECTOR_COUNTS = new Map<number, number>([
|
||||
[1, 128], // types
|
||||
[2, 3], // memory, one optional capability import, and one optional UI output import
|
||||
[2, 4], // memory, one optional capability, one UI input, and one UI output import
|
||||
[3, SKIN_EXTENSION_WASM_FUNCTION_LIMIT],
|
||||
[6, 128], // globals
|
||||
[7, 64], // exports; the runner later requires exactly run
|
||||
@@ -313,6 +313,7 @@ export function validateSkinExtensionWasmBytes(source: Uint8Array): void {
|
||||
|
||||
export interface SkinExtensionWasmModuleMetadata {
|
||||
usesSessionStatus: boolean;
|
||||
usesUiInput: boolean;
|
||||
usesUiOutput: boolean;
|
||||
memoryMaximumPages: number;
|
||||
}
|
||||
@@ -364,6 +365,7 @@ export function validateSkinExtensionWasmImportsAndExports(
|
||||
let memoryMaximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
|
||||
let hasMemory = false;
|
||||
let usesSessionStatus = false;
|
||||
let usesUiInput = false;
|
||||
let usesUiOutput = false;
|
||||
let hasExports = false;
|
||||
|
||||
@@ -376,8 +378,8 @@ export function validateSkinExtensionWasmImportsAndExports(
|
||||
|
||||
if (sectionId === 2) {
|
||||
const count = readU32(bytes, offset, end);
|
||||
if (count.value < 1 || count.value > 3) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and may import one capability and one UI output function.");
|
||||
if (count.value < 1 || count.value > 4) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and may import the bounded status, UI input, and UI output functions.");
|
||||
}
|
||||
let cursor = count.next;
|
||||
for (let index = 0; index < count.value; index += 1) {
|
||||
@@ -393,6 +395,8 @@ export function validateSkinExtensionWasmImportsAndExports(
|
||||
cursor = typeIndex.next;
|
||||
if (fieldName.value === "session_status_read" && !usesSessionStatus) {
|
||||
usesSessionStatus = true;
|
||||
} else if (fieldName.value === "ui_input_read" && !usesUiInput) {
|
||||
usesUiInput = true;
|
||||
} else if (fieldName.value === "ui_emit_json" && !usesUiOutput) {
|
||||
usesUiOutput = true;
|
||||
} else {
|
||||
@@ -441,5 +445,5 @@ export function validateSkinExtensionWasmImportsAndExports(
|
||||
if (usesSessionStatus && !grantedPermissions.includes("session.status.read")) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The module imports session status without an approved session.status.read capability.");
|
||||
}
|
||||
return { usesSessionStatus, usesUiOutput, memoryMaximumPages };
|
||||
return { usesSessionStatus, usesUiInput, usesUiOutput, memoryMaximumPages };
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
SKIN_EXTENSION_WASM_RUNTIME_ENABLED,
|
||||
} from "./skin-extension-wasm-sandbox.js";
|
||||
import { SKIN_EXTENSION_WASM_SOURCE_LIMIT } from "./skin-extension-wasm-policy.js";
|
||||
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
|
||||
const manifest = parseSkinExtensionManifest({
|
||||
schemaVersion: 1,
|
||||
@@ -27,3 +28,27 @@ test("production Wasm execution remains disabled while the bounded runner is pro
|
||||
prototypeOnly: true,
|
||||
}), { code: "SKIN_EXTENSION_WASM_SIZE" });
|
||||
});
|
||||
|
||||
test("Wasm UI input preserves bounded local state and safe event data", () => {
|
||||
const parsed = parseSkinExtensionUiInput({
|
||||
schemaVersion: 1,
|
||||
state: { open: true, query: "team", count: 2 },
|
||||
event: { componentId: "server-rail", handlerId: "select-server", eventName: "click" },
|
||||
});
|
||||
assert.deepEqual({ ...parsed.state }, { open: true, query: "team", count: 2 });
|
||||
assert.deepEqual(parsed.event, { componentId: "server-rail", handlerId: "select-server", eventName: "click" });
|
||||
});
|
||||
|
||||
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",
|
||||
});
|
||||
assert.throws(() => parseSkinExtensionUiInput({ schemaVersion: 1, state: {}, event: {
|
||||
componentId: "server-rail", handlerId: "select-server", eventName: "click", value: "forged",
|
||||
} }), { code: "SKIN_EXTENSION_UI_INPUT_INVALID" });
|
||||
assert.throws(() => parseSkinExtensionUiInput({
|
||||
schemaVersion: 1,
|
||||
state: { query: "x".repeat(1_025) },
|
||||
event: null,
|
||||
}), { code: "SKIN_EXTENSION_UI_INPUT_INVALID" });
|
||||
});
|
||||
@@ -16,6 +16,10 @@ import {
|
||||
SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES,
|
||||
validateSkinExtensionWasmBytes,
|
||||
} from "./skin-extension-wasm-policy.js";
|
||||
import {
|
||||
parseSkinExtensionUiInput,
|
||||
SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES,
|
||||
} from "../../../src/shared/skin-extension-ui-input.js";
|
||||
|
||||
export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = false as const;
|
||||
|
||||
@@ -30,6 +34,7 @@ export interface SkinExtensionWasmSandboxResult {
|
||||
result: number | string;
|
||||
linearMemoryBytes: number;
|
||||
statusReadCount: number;
|
||||
uiInputReadCount: number;
|
||||
uiOutput: string | null;
|
||||
sessionSnapshot?: SkinExtensionSessionStatus;
|
||||
}
|
||||
@@ -38,6 +43,8 @@ export interface SkinExtensionWasmSandboxOptions {
|
||||
manifest: unknown;
|
||||
approval: unknown;
|
||||
wasmBytes: Uint8Array;
|
||||
/** 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;
|
||||
@@ -77,6 +84,11 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
|
||||
validateSkinExtensionWasmBytes(options.wasmBytes);
|
||||
const grantedPermissions = manifest.permissions.filter((permission) =>
|
||||
isSkinExtensionPermissionApproved(approval, manifest.id, permission));
|
||||
const uiInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
|
||||
const uiInputJson = JSON.stringify(uiInput);
|
||||
if (new TextEncoder().encode(uiInputJson).byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) {
|
||||
throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_UI_INPUT_INVALID", "The local UI input exceeds its bounded size.");
|
||||
}
|
||||
const wasmBytes = options.wasmBytes.slice();
|
||||
const worker = new Worker(new URL("./skin-extension-wasm-worker.ts", import.meta.url), {
|
||||
type: "module",
|
||||
@@ -175,7 +187,7 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
|
||||
return;
|
||||
}
|
||||
if (message.type === "complete") {
|
||||
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount", "uiOutput"];
|
||||
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount", "uiInputReadCount", "uiOutput"];
|
||||
if (Object.keys(message).length !== expectedKeys.length
|
||||
|| Object.keys(message).some((key) => !expectedKeys.includes(key))
|
||||
|| (typeof message.result !== "number" && typeof message.result !== "string")
|
||||
@@ -185,12 +197,15 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
|
||||
|| !Number.isSafeInteger(message.linearMemoryBytes) || (message.linearMemoryBytes as number) < 0
|
||||
|| (message.linearMemoryBytes as number) > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024
|
||||
|| !Number.isSafeInteger(message.statusReadCount) || (message.statusReadCount as number) < 0
|
||||
|| (message.statusReadCount as number) > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT) {
|
||||
|| (message.statusReadCount as number) > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT
|
||||
|| !Number.isSafeInteger(message.uiInputReadCount) || (message.uiInputReadCount as number) < 0
|
||||
|| (message.uiInputReadCount as number) > 1) {
|
||||
finish("invalid-result", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The Wasm worker returned a result outside its allowed shape."));
|
||||
return;
|
||||
}
|
||||
complete({ result: message.result as number | string, linearMemoryBytes: message.linearMemoryBytes as number,
|
||||
statusReadCount: message.statusReadCount as number, uiOutput: message.uiOutput as string | null,
|
||||
statusReadCount: message.statusReadCount as number, uiInputReadCount: message.uiInputReadCount as number,
|
||||
uiOutput: message.uiOutput as string | null,
|
||||
...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) });
|
||||
return;
|
||||
}
|
||||
@@ -206,7 +221,7 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
|
||||
startupTimer = window.setTimeout(() => finish("startup-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_STARTUP_TIMEOUT", "The Wasm worker did not finish initialization in time.")), SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS);
|
||||
|
||||
const bytes = wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength) as ArrayBuffer;
|
||||
worker.postMessage({ type: "run", bytes, approvedPermissions: grantedPermissions }, [bytes]);
|
||||
worker.postMessage({ type: "run", bytes, approvedPermissions: grantedPermissions, input: uiInputJson }, [bytes]);
|
||||
|
||||
return {
|
||||
ready,
|
||||
|
||||
@@ -11,11 +11,16 @@ import {
|
||||
SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES,
|
||||
validateSkinExtensionWasmImportsAndExports,
|
||||
} from "./skin-extension-wasm-policy.js";
|
||||
import {
|
||||
parseSkinExtensionUiInput,
|
||||
SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES,
|
||||
} from "../../../src/shared/skin-extension-ui-input.js";
|
||||
|
||||
interface RunMessage {
|
||||
type: "run";
|
||||
bytes: ArrayBuffer;
|
||||
approvedPermissions: string[];
|
||||
input: string;
|
||||
}
|
||||
|
||||
interface CapabilityResponse {
|
||||
@@ -29,9 +34,11 @@ interface WasmiInterpreterExports extends WebAssembly.Exports {
|
||||
memory: WebAssembly.Memory;
|
||||
alloc: (size: number) => number;
|
||||
run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number,
|
||||
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
|
||||
uiInputPointer: number, uiInputLength: number, statusPermissionGranted: number,
|
||||
memoryMaximumPages: number, fuel: bigint) => bigint;
|
||||
last_error_code: () => number;
|
||||
last_status_read_count: () => number;
|
||||
last_ui_input_read_count: () => number;
|
||||
last_guest_memory_bytes: () => number;
|
||||
last_ui_output_pointer: () => number;
|
||||
last_ui_output_length: () => number;
|
||||
@@ -64,8 +71,9 @@ scope.addEventListener("message", (event: MessageEvent<unknown>) => {
|
||||
return;
|
||||
}
|
||||
if (started || !isPlainRecord(value) || value.type !== "run" || !(value.bytes instanceof ArrayBuffer)
|
||||
|| typeof value.input !== "string"
|
||||
|| !Array.isArray(value.approvedPermissions) || value.approvedPermissions.some((permission) => typeof permission !== "string")
|
||||
|| Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions"].includes(key))) {
|
||||
|| Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions", "input"].includes(key))) {
|
||||
sendError("SKIN_EXTENSION_WASM_JOB_INVALID", "The isolated Wasm job message is invalid.");
|
||||
return;
|
||||
}
|
||||
@@ -86,6 +94,12 @@ async function requestSessionStatus(): Promise<SkinExtensionSessionStatus> {
|
||||
async function run(job: RunMessage): Promise<void> {
|
||||
try {
|
||||
const bytes = new Uint8Array(job.bytes);
|
||||
const input = parseSkinExtensionUiInput(job.input);
|
||||
const inputBytes = new TextEncoder().encode(JSON.stringify(input));
|
||||
if (inputBytes.byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) {
|
||||
sendError("SKIN_EXTENSION_UI_INPUT_INVALID", "The local UI input exceeds its bounded size.");
|
||||
return;
|
||||
}
|
||||
const metadata = validateSkinExtensionWasmImportsAndExports(bytes, job.approvedPermissions);
|
||||
const interpreter = await loadWasmiInterpreter();
|
||||
const status = metadata.usesSessionStatus ? await requestSessionStatus() : null;
|
||||
@@ -95,7 +109,7 @@ async function run(job: RunMessage): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0);
|
||||
const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0) + inputBytes.byteLength;
|
||||
const pointer = interpreter.alloc(payloadLength);
|
||||
if (!pointer) {
|
||||
sendError("SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT", "The extension input exceeds the interpreter's bounded memory.");
|
||||
@@ -104,29 +118,36 @@ async function run(job: RunMessage): Promise<void> {
|
||||
new Uint8Array(interpreter.memory.buffer, pointer, bytes.byteLength).set(bytes);
|
||||
const statusPointer = statusBytes ? pointer + bytes.byteLength : 0;
|
||||
if (statusBytes) new Uint8Array(interpreter.memory.buffer, statusPointer, statusBytes.byteLength).set(statusBytes);
|
||||
const uiInputPointer = pointer + bytes.byteLength + (statusBytes?.byteLength ?? 0);
|
||||
new Uint8Array(interpreter.memory.buffer, uiInputPointer, inputBytes.byteLength).set(inputBytes);
|
||||
|
||||
scope.postMessage({ type: "running" });
|
||||
const rawResult = interpreter.run(pointer, bytes.byteLength, statusPointer, statusBytes?.byteLength ?? 0,
|
||||
metadata.usesSessionStatus ? 1 : 0, metadata.memoryMaximumPages, SKIN_EXTENSION_WASM_FUEL_LIMIT);
|
||||
uiInputPointer, inputBytes.byteLength, metadata.usesSessionStatus ? 1 : 0,
|
||||
metadata.memoryMaximumPages, SKIN_EXTENSION_WASM_FUEL_LIMIT);
|
||||
const errorCode = interpreter.last_error_code();
|
||||
if (errorCode !== 0) {
|
||||
const code = errorCode === 5 ? "SKIN_EXTENSION_WASM_EXECUTION_LIMIT"
|
||||
: errorCode === 6 ? "SKIN_EXTENSION_WASM_MEMORY_LIMIT"
|
||||
: errorCode === 10 ? "SKIN_EXTENSION_WASM_IMPORT_INVALID"
|
||||
: errorCode === 11 ? "SKIN_EXTENSION_WASM_PERMISSION_INVALID"
|
||||
: errorCode === 12 ? "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID"
|
||||
: "SKIN_EXTENSION_WASM_INTERPRETER_FAILED";
|
||||
: errorCode === 12 ? "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID"
|
||||
: errorCode === 13 ? "SKIN_EXTENSION_WASM_UI_INPUT_INVALID"
|
||||
: "SKIN_EXTENSION_WASM_INTERPRETER_FAILED";
|
||||
sendError(code, "The extension was rejected or stopped inside the bounded Wasmi interpreter.");
|
||||
return;
|
||||
}
|
||||
|
||||
const result = Number(rawResult);
|
||||
const statusReadCount = interpreter.last_status_read_count();
|
||||
const uiInputReadCount = interpreter.last_ui_input_read_count();
|
||||
const linearMemoryBytes = interpreter.last_guest_memory_bytes();
|
||||
const uiOutputPointer = interpreter.last_ui_output_pointer();
|
||||
const uiOutputLength = interpreter.last_ui_output_length();
|
||||
if (!Number.isSafeInteger(result) || !Number.isSafeInteger(statusReadCount) || statusReadCount < 0
|
||||
|| statusReadCount > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT || !Number.isSafeInteger(linearMemoryBytes)
|
||||
|| !Number.isSafeInteger(uiInputReadCount) || uiInputReadCount < 0 || uiInputReadCount > 1
|
||||
|| (uiInputReadCount > 0 && !metadata.usesUiInput)
|
||||
|| linearMemoryBytes < 0 || linearMemoryBytes > metadata.memoryMaximumPages * 64 * 1024
|
||||
|| linearMemoryBytes > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024) {
|
||||
sendError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The interpreter returned a value outside the allowed resource policy.");
|
||||
@@ -158,6 +179,7 @@ async function run(job: RunMessage): Promise<void> {
|
||||
result,
|
||||
linearMemoryBytes,
|
||||
statusReadCount,
|
||||
uiInputReadCount,
|
||||
uiOutput,
|
||||
};
|
||||
if (new TextEncoder().encode(JSON.stringify(message)).byteLength > SKIN_EXTENSION_WASM_MESSAGE_LIMIT) {
|
||||
@@ -189,6 +211,7 @@ async function loadWasmiInterpreter(): Promise<WasmiInterpreterExports> {
|
||||
if (!(exports.memory instanceof WebAssembly.Memory) || typeof exports.alloc !== "function"
|
||||
|| typeof exports.run !== "function" || typeof exports.last_error_code !== "function"
|
||||
|| typeof exports.last_status_read_count !== "function" || typeof exports.last_guest_memory_bytes !== "function"
|
||||
|| typeof exports.last_ui_input_read_count !== "function"
|
||||
|| typeof exports.last_ui_output_pointer !== "function" || typeof exports.last_ui_output_length !== "function") {
|
||||
throw new Error("The bounded Wasmi interpreter exposes an incompatible runtime interface.");
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createSkinExtensionWasmCappedRunProbe,
|
||||
createSkinExtensionWasmInfiniteRunProbe,
|
||||
createSkinExtensionWasmPrefixByteImmediateProbe,
|
||||
createSkinExtensionWasmUiInputProbe,
|
||||
createSkinExtensionWasmUiOutputProbe,
|
||||
} from "../../test/skin-extension-wasm-fixture.js";
|
||||
|
||||
@@ -12,8 +13,10 @@ interface WasmiInterpreterExports extends WebAssembly.Exports {
|
||||
memory: WebAssembly.Memory;
|
||||
alloc: (size: number) => number;
|
||||
run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number,
|
||||
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
|
||||
uiInputPointer: number, uiInputLength: number, statusPermissionGranted: number,
|
||||
memoryMaximumPages: number, fuel: bigint) => bigint;
|
||||
last_error_code: () => number;
|
||||
last_ui_input_read_count: () => number;
|
||||
last_guest_memory_bytes: () => number;
|
||||
last_ui_output_pointer: () => number;
|
||||
last_ui_output_length: () => number;
|
||||
@@ -24,15 +27,20 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
|
||||
const { instance } = await WebAssembly.instantiate(artifact);
|
||||
const runtime = instance.exports as unknown as WasmiInterpreterExports;
|
||||
|
||||
function run(module: Uint8Array): { result: number; error: number; guestMemoryBytes: number; uiOutput: string | null } {
|
||||
const pointer = runtime.alloc(module.byteLength);
|
||||
function run(module: Uint8Array, input = '{"schemaVersion":1,"state":{},"event":null}'):
|
||||
{ result: number; error: number; guestMemoryBytes: number; uiInputReadCount: number; uiOutput: string | null } {
|
||||
const inputBytes = new TextEncoder().encode(input);
|
||||
const pointer = runtime.alloc(module.byteLength + inputBytes.byteLength);
|
||||
assert.notEqual(pointer, 0, "the bounded interpreter should accept the small fixture");
|
||||
new Uint8Array(runtime.memory.buffer, pointer, module.byteLength).set(module);
|
||||
const result = runtime.run(pointer, module.byteLength, 0, 0, 0, 64, 10_000_000n);
|
||||
const inputPointer = pointer + module.byteLength;
|
||||
new Uint8Array(runtime.memory.buffer, inputPointer, inputBytes.byteLength).set(inputBytes);
|
||||
const result = runtime.run(pointer, module.byteLength, 0, 0, inputPointer, inputBytes.byteLength, 0, 64, 10_000_000n);
|
||||
return {
|
||||
result: Number(result),
|
||||
error: runtime.last_error_code(),
|
||||
guestMemoryBytes: runtime.last_guest_memory_bytes(),
|
||||
uiInputReadCount: runtime.last_ui_input_read_count(),
|
||||
uiOutput: runtime.last_ui_output_length() === 0
|
||||
? null
|
||||
: new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(
|
||||
@@ -47,6 +55,7 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
|
||||
result: 123,
|
||||
error: 0,
|
||||
guestMemoryBytes: 64 * 1024,
|
||||
uiInputReadCount: 0,
|
||||
uiOutput: null,
|
||||
});
|
||||
assert.equal(run(createSkinExtensionWasmInfiniteRunProbe()).error, 5, "the fuel budget must trap a non-returning module");
|
||||
@@ -54,6 +63,7 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
|
||||
result: -1,
|
||||
error: 0,
|
||||
guestMemoryBytes: 4 * 1024 * 1024,
|
||||
uiInputReadCount: 0,
|
||||
uiOutput: null,
|
||||
});
|
||||
|
||||
@@ -61,8 +71,19 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
|
||||
result: 7,
|
||||
error: 0,
|
||||
guestMemoryBytes: 64 * 1024,
|
||||
uiInputReadCount: 0,
|
||||
uiOutput: '{"type":"root"}',
|
||||
});
|
||||
const uiInput = '{"schemaVersion":1,"state":{"open":true},"event":{"componentId":"rail","handlerId":"toggle","eventName":"click"}}';
|
||||
assert.deepEqual(run(createSkinExtensionWasmUiInputProbe(), uiInput), {
|
||||
result: 7,
|
||||
error: 0,
|
||||
guestMemoryBytes: 64 * 1024,
|
||||
uiInputReadCount: 1,
|
||||
uiOutput: uiInput,
|
||||
});
|
||||
assert.equal(run(createSkinExtensionWasmUiInputProbe(true), uiInput).error, 13,
|
||||
"the host must reject a second UI input read in one guest invocation");
|
||||
assert.equal(run(createSkinExtensionWasmUiOutputProbe("x".repeat(16 * 1024 + 1))).error, 12,
|
||||
"the interpreter must reject a UI payload above its byte cap");
|
||||
assert.equal(run(createSkinExtensionWasmUiOutputProbe('{"type":"root"}', true)).error, 12,
|
||||
|
||||
Reference in new issue
Block a user