feat(web): implement open skin layouts and migrate Illusia

This commit is contained in:
illusia committed 2026-10-10 15:53:38 +08:00
1 parent 58559cf839
commit 02441410a0
60 files changed
+6511 -50

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
{
id: BUILTIN_ILLUSIA_SKIN_ID,
name: "ILLUSIA风",
version: "1.0.28",
version: "1.0.29",
author: "WebSpeak Project",
license: "All rights reserved",
description: "A bright original-character art skin for the home, voice room, and demo pages.",
@@ -0,0 +1,143 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
createSkinExtensionApproval,
getSkinExtensionUpgradeConsentDelta,
isSkinExtensionBootstrapHello,
isSkinExtensionPermissionApproved,
parseSkinExtensionApproval,
parseSkinExtensionManifest,
parseSkinExtensionRequestMessage,
sanitizeSkinExtensionSessionStatus,
SKIN_EXTENSION_MESSAGE_CHANNEL,
type SkinExtensionManifest,
} from "../../../src/shared/skin-extension.js";
import {
createSkinExtensionSandboxPrototype,
SKIN_EXTENSION_RUNTIME_ENABLED,
SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT,
SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND,
SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT,
SkinExtensionSandboxError,
} from "./skin-extension-sandbox.js";
function manifest(overrides: Record<string, unknown> = {}) {
return parseSkinExtensionManifest({
schemaVersion: 1,
packageType: "extension",
id: "community.status-card",
name: "Status card",
version: "1.0.0",
apiVersion: 1,
permissions: ["session.status.read"],
...overrides,
});
}
test("extension manifests use a separate strict schema and reject unknown capabilities", () => {
const parsed = manifest();
assert.equal(parsed.packageType, "extension");
assert.deepEqual(parsed.permissions, ["session.status.read"]);
assert.throws(() => manifest({ unexpected: true }), { code: "SKIN_EXTENSION_UNKNOWN_FIELD" });
assert.throws(() => manifest({ permissions: ["filesystem.read"] }), { code: "SKIN_EXTENSION_PERMISSION_UNKNOWN" });
assert.throws(() => manifest({ permissions: ["session.status.read", "session.status.read"] }), { code: "SKIN_EXTENSION_PERMISSION_DUPLICATE" });
assert.throws(() => manifest({ version: "latest" }), { code: "SKIN_EXTENSION_MANIFEST_INVALID" });
assert.throws(() => manifest({ apiVersion: 2 }), { code: "SKIN_EXTENSION_API_UNSUPPORTED" });
});
test("approval is host-shaped, permission-specific, and cannot be reused for another extension", () => {
const parsed = manifest();
const approval = createSkinExtensionApproval(parsed);
assert.equal(isSkinExtensionPermissionApproved(approval, parsed.id, "session.status.read"), true);
assert.equal(isSkinExtensionPermissionApproved(approval, "other.extension", "session.status.read"), false);
assert.deepEqual(parseSkinExtensionApproval(approval), approval);
assert.throws(() => parseSkinExtensionApproval({ ...approval, permissions: { "filesystem.read": 1 } }), { code: "SKIN_EXTENSION_APPROVAL_INVALID" });
assert.throws(() => getSkinExtensionUpgradeConsentDelta(approval, manifest({ id: "other.extension" })), { code: "SKIN_EXTENSION_ID_CHANGED" });
});
test("an extension upgrade needs new consent when it adds or changes a capability", () => {
const approval = createSkinExtensionApproval(manifest());
const unchanged = getSkinExtensionUpgradeConsentDelta(approval, manifest({ version: "2.0.0" }));
assert.equal(unchanged.requiresConsent, false, "a version change alone does not silently change permission meaning");
const approvalWithoutPermissions = createSkinExtensionApproval(manifest({ permissions: [] }));
const added = getSkinExtensionUpgradeConsentDelta(approvalWithoutPermissions, manifest({ version: "2.0.0" }));
assert.deepEqual(added.addedPermissions, ["session.status.read"]);
assert.equal(added.requiresConsent, true);
const removed = getSkinExtensionUpgradeConsentDelta(approval, manifest({ version: "2.0.0", permissions: [] }));
assert.deepEqual(removed.removedPermissions, ["session.status.read"]);
assert.equal(removed.requiresConsent, false, "removing a capability cannot expand an existing approval");
const outdatedApproval = { ...approval, permissions: { "session.status.read": 2 } };
const changedMeaning = getSkinExtensionUpgradeConsentDelta(outdatedApproval, manifest({ version: "2.0.0" }));
assert.deepEqual(changedMeaning.changedMeaningPermissions, ["session.status.read"]);
assert.equal(changedMeaning.requiresConsent, true);
const changedApi = getSkinExtensionUpgradeConsentDelta({ ...approval, apiVersion: 2 }, manifest({ version: "2.0.0" }) as SkinExtensionManifest);
assert.equal(changedApi.apiVersionChanged, true);
assert.equal(changedApi.requiresConsent, true);
});
test("bootstrap accepts only the exact opaque iframe source, nonce, origin, and transferred port", () => {
const expectedSource = {};
const valid = {
source: expectedSource,
origin: "null",
data: { channel: SKIN_EXTENSION_MESSAGE_CHANNEL, type: "hello", apiVersion: 1, nonce: "secret" },
ports: [{}],
};
assert.equal(isSkinExtensionBootstrapHello(valid, expectedSource, "secret"), true);
assert.equal(isSkinExtensionBootstrapHello({ ...valid, source: {} }, expectedSource, "secret"), false);
assert.equal(isSkinExtensionBootstrapHello({ ...valid, origin: "https://example.invalid" }, expectedSource, "secret"), false);
assert.equal(isSkinExtensionBootstrapHello({ ...valid, data: { ...valid.data, nonce: "wrong" } }, expectedSource, "secret"), false);
assert.equal(isSkinExtensionBootstrapHello({ ...valid, ports: [] }, expectedSource, "secret"), false);
assert.equal(isSkinExtensionBootstrapHello({ ...valid, data: { ...valid.data, extra: true } }, expectedSource, "secret"), false);
});
test("capability requests have a fixed envelope and empty, bounded payload", () => {
const message = {
channel: SKIN_EXTENSION_MESSAGE_CHANNEL,
apiVersion: 1,
nonce: "secret",
id: "r1",
type: "request",
permission: "session.status.read",
payload: {},
};
assert.deepEqual(parseSkinExtensionRequestMessage(message, "secret"), message);
assert.equal(parseSkinExtensionRequestMessage({ ...message, nonce: "wrong" }, "secret"), null);
assert.equal(parseSkinExtensionRequestMessage({ ...message, payload: { includePrivateChat: true } }, "secret"), null);
assert.equal(parseSkinExtensionRequestMessage({ ...message, extra: true }, "secret"), null);
assert.equal(parseSkinExtensionRequestMessage({ ...message, permission: "chat.private.read" }, "secret"), null);
assert.equal(parseSkinExtensionRequestMessage({ ...message, id: "a".repeat(65) }, "secret"), null);
});
test("session status copies only low-sensitivity fields and rejects invalid values", () => {
const safe = sanitizeSkinExtensionSessionStatus({ connected: true, channelName: "Lounge\n", memberCount: 3, token: "must not escape" });
assert.deepEqual(safe, { connected: true, channelName: "Lounge ", memberCount: 3 });
assert.equal("token" in safe, false);
assert.throws(() => sanitizeSkinExtensionSessionStatus({ connected: true, channelName: null, memberCount: -1 }));
assert.throws(() => sanitizeSkinExtensionSessionStatus({ connected: "yes", channelName: null, memberCount: 0 }));
});
test("JavaScript extensions stay disabled because Workers have no hard memory quota", () => {
assert.equal(SKIN_EXTENSION_RUNTIME_ENABLED, false);
assert.ok(SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT <= 64 * 1024);
assert.ok(SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT <= 8 * 1024);
assert.ok(SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND <= 10);
assert.ok(new SkinExtensionSandboxError("DISABLED", "disabled") instanceof Error);
});
test("the prototype rejects source beyond its fixed startup budget before creating a frame", () => {
const parsed = manifest();
const approval = createSkinExtensionApproval(parsed);
assert.throws(() => createSkinExtensionSandboxPrototype({
container: {} as HTMLElement,
manifest: parsed,
approval,
source: "x".repeat(SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT + 1),
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
prototypeOnly: true,
}), { code: "SKIN_EXTENSION_SOURCE_TOO_LARGE" });
});
+501
View File
@@ -0,0 +1,501 @@
import {
isSkinExtensionBootstrapHello,
isSkinExtensionPermissionApproved,
parseSkinExtensionApproval,
parseSkinExtensionManifest,
parseSkinExtensionRequestMessage,
sanitizeSkinExtensionSessionStatus,
SKIN_EXTENSION_API_VERSION,
SKIN_EXTENSION_MESSAGE_CHANNEL,
type SkinExtensionApproval,
type SkinExtensionManifest,
type SkinExtensionPermissionId,
type SkinExtensionSessionStatus,
} from "../../../src/shared/skin-extension.js";
export const SKIN_EXTENSION_RUNTIME_ENABLED = false as const;
export const SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT = 64 * 1024;
export const SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT = 8 * 1024;
export const SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND = 10;
export const SKIN_EXTENSION_SANDBOX_MAX_REQUESTS = 10_000;
const HANDSHAKE_TIMEOUT_MS = 3_000;
const SHUTDOWN_TIMEOUT_MS = 100;
const MESSAGE_CHANNEL = SKIN_EXTENSION_MESSAGE_CHANNEL;
export class SkinExtensionSandboxError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinExtensionSandboxError";
}
}
export interface SkinExtensionSandboxOptions {
container: HTMLElement;
manifest: unknown;
approval: unknown;
source: string;
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
/** The only entry point is explicitly marked as a development prototype and is not wired into the application. */
prototypeOnly: true;
}
export interface SkinExtensionSandboxHandle {
readonly frame: HTMLIFrameElement;
readonly manifest: SkinExtensionManifest;
readonly approval: SkinExtensionApproval;
readonly ready: Promise<void>;
readonly stopped: Promise<void>;
readonly closed: boolean;
readonly closeReason: string | null;
readonly acceptedRequests: number;
readonly rejectedRequests: number;
revokePermission(permission: SkinExtensionPermissionId): void;
close(reason?: string): void;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function randomNonce(view: Window): string {
const bytes = new Uint8Array(32);
view.crypto.getRandomValues(bytes);
return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
}
function toBase64(source: string): string {
const bytes = new TextEncoder().encode(source);
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
}
return btoa(binary);
}
function createWorkerDataUrl(source: string): string {
const pluginModuleUrl = `data:text/javascript;base64,${toBase64(source)}`;
const workerBootstrap = `
const __wsPluginModuleUrl = ${JSON.stringify(pluginModuleUrl)};
const __wsApiVersion = ${SKIN_EXTENSION_API_VERSION};
const __wsDeniedGlobals = ["Worker", "SharedWorker", "fetch", "XMLHttpRequest", "WebSocket", "EventSource", "WebTransport", "importScripts", "indexedDB", "caches", "WebAssembly"];
for (const __wsName of __wsDeniedGlobals) {
try { Object.defineProperty(globalThis, __wsName, { value: undefined, writable: false, configurable: false }); } catch {}
if (globalThis[__wsName] !== undefined) throw new Error("The worker cannot disable a restricted global.");
}
let __wsPort = null;
let __wsSequence = 0;
const __wsPending = new Map();
self.addEventListener("message", async function __wsInitialize(event) {
if (__wsPort || event.data?.type !== "initialize" || event.ports.length !== 1 || Object.keys(event.data).length !== 1) return;
__wsPort = event.ports[0];
__wsPort.onmessage = (portEvent) => {
const response = portEvent.data;
if (!response || typeof response !== "object" || response.type !== "response" || typeof response.id !== "string") return;
const pending = __wsPending.get(response.id);
if (!pending) return;
__wsPending.delete(response.id);
if (response.ok === true) pending.resolve(response.data);
else pending.reject(new Error(typeof response.error?.message === "string" ? response.error.message : "Extension request denied."));
};
__wsPort.start();
const api = Object.freeze({
apiVersion: __wsApiVersion,
request(permission, payload = {}) {
if (!__wsPort) return Promise.reject(new Error("Extension runtime is closed."));
if (typeof permission !== "string" || !payload || typeof payload !== "object" || Array.isArray(payload) || Object.keys(payload).length !== 0) return Promise.reject(new Error("Invalid extension request."));
if (__wsPending.size >= 16) return Promise.reject(new Error("Too many pending extension requests."));
const id = "r" + (++__wsSequence).toString(36);
return new Promise((resolve, reject) => {
__wsPending.set(id, { resolve, reject });
__wsPort.postMessage({ type: "request", id, permission, payload: {} });
});
},
});
Object.defineProperty(globalThis, "WebSpeakExtension", { value: api, writable: false, configurable: false });
__wsPort.postMessage({ type: "worker-ready" });
try { await import(__wsPluginModuleUrl); }
catch { __wsPort.postMessage({ type: "plugin-error" }); }
});`;
return `data:text/javascript;base64,${toBase64(workerBootstrap)}`;
}
function createSandboxDocument(workerUrl: string, nonce: string): string {
const policy = [
"default-src 'none'",
`script-src 'nonce-${nonce}' data:`,
"style-src 'unsafe-inline'",
"connect-src 'none'",
"img-src 'none'",
"media-src 'none'",
"font-src 'none'",
"object-src 'none'",
"frame-src 'none'",
"child-src 'none'",
"worker-src data:",
"manifest-src 'none'",
"form-action 'none'",
"base-uri 'none'",
"navigate-to 'none'",
].join("; ");
return `<!doctype html>
<html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer">
<meta http-equiv="Content-Security-Policy" content="${policy}">
<title>Isolated WebSpeak extension</title></head>
<body><main id="extension-root" aria-label="Extension component"></main>
<script nonce="${nonce}">
(() => {
"use strict";
const channelName = ${JSON.stringify(MESSAGE_CHANNEL)};
const apiVersion = ${SKIN_EXTENSION_API_VERSION};
const nonce = ${JSON.stringify(nonce)};
const workerUrl = ${JSON.stringify(workerUrl)};
const parentChannel = new MessageChannel();
const parentPort = parentChannel.port1;
const workerChannel = new MessageChannel();
let worker = null;
let workerPort = workerChannel.port1;
let started = false;
let stopped = false;
function stopWorker() {
if (stopped) return;
stopped = true;
if (worker) worker.terminate();
if (workerPort) { workerPort.onmessage = null; workerPort.close(); }
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "shutdown-complete" });
}
function validHostEnvelope(data) {
return !!data && typeof data === "object" && !Array.isArray(data)
&& data.channel === channelName && data.apiVersion === apiVersion && data.nonce === nonce;
}
parentPort.onmessage = (event) => {
const data = event.data;
if (!validHostEnvelope(data)) return;
if (data.type === "shutdown" && Object.keys(data).length === 4) { stopWorker(); return; }
if (data.type === "host-ready" && Object.keys(data).length === 4 && !started) {
started = true;
try {
worker = new Worker(workerUrl, { type: "module", name: "webspeak-skin-extension" });
worker.onerror = () => parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "runtime-error" });
workerPort.onmessage = (workerEvent) => {
const message = workerEvent.data;
if (!message || typeof message !== "object" || Array.isArray(message)) return;
if (message.type === "worker-ready" && Object.keys(message).length === 1) {
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "client-ready" });
return;
}
if (message.type === "plugin-error" && Object.keys(message).length === 1) {
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "runtime-error" });
return;
}
const keys = Object.keys(message).sort().join(",");
if (message.type !== "request" || keys !== "id,payload,permission,type" || !/^r[A-Za-z0-9_-]{0,63}$/.test(message.id)
|| typeof message.permission !== "string" || !message.payload || typeof message.payload !== "object"
|| Array.isArray(message.payload) || Object.keys(message.payload).length !== 0) return;
parentPort.postMessage({ channel: channelName, apiVersion, nonce, id: message.id, type: "request", permission: message.permission, payload: {} });
};
workerPort.start();
worker.postMessage({ type: "initialize" }, [workerChannel.port2]);
} catch {
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "runtime-error" });
}
return;
}
if (data.type === "response" && typeof data.id === "string") {
try { workerPort.postMessage(data); } catch { stopWorker(); }
}
};
parentPort.onmessageerror = stopWorker;
parentPort.start();
parent.postMessage({ channel: channelName, apiVersion, nonce, type: "hello" }, "*", [parentChannel.port2]);
})();
</script></body></html>`;
}
function serializedMessageBytes(value: unknown): number {
try {
const serialized = JSON.stringify(value);
return serialized === undefined ? Number.POSITIVE_INFINITY : new TextEncoder().encode(serialized).byteLength;
} catch {
return Number.POSITIVE_INFINITY;
}
}
function isReadyMessage(value: unknown, nonce: string): boolean {
return isPlainRecord(value)
&& Object.keys(value).length === 4
&& value.channel === MESSAGE_CHANNEL
&& value.apiVersion === SKIN_EXTENSION_API_VERSION
&& value.nonce === nonce
&& value.type === "client-ready";
}
export function createSkinExtensionSandboxPrototype(options: SkinExtensionSandboxOptions): SkinExtensionSandboxHandle {
if (options.prototypeOnly !== true) {
throw new SkinExtensionSandboxError("SKIN_EXTENSION_RUNTIME_DISABLED", "Executable extensions are disabled.");
}
if (!options.container || typeof options.source !== "string") {
throw new SkinExtensionSandboxError("SKIN_EXTENSION_INPUT_INVALID", "The extension runtime input is invalid.");
}
const manifest = parseSkinExtensionManifest(options.manifest);
const approval = parseSkinExtensionApproval(options.approval);
if (approval.pluginId !== manifest.id || approval.apiVersion !== manifest.apiVersion) {
throw new SkinExtensionSandboxError("SKIN_EXTENSION_RECONSENT_REQUIRED", "The extension must be reviewed and approved again.");
}
for (const permission of manifest.permissions) {
if (!isSkinExtensionPermissionApproved(approval, manifest.id, permission)) {
throw new SkinExtensionSandboxError("SKIN_EXTENSION_RECONSENT_REQUIRED", "A requested extension permission has not been approved.");
}
}
if (new TextEncoder().encode(options.source).byteLength > SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT) {
throw new SkinExtensionSandboxError("SKIN_EXTENSION_SOURCE_TOO_LARGE", "The extension source exceeds the prototype size limit.");
}
const document = options.container.ownerDocument;
const view = document.defaultView;
if (!view || !view.crypto?.getRandomValues || typeof MessageChannel === "undefined") {
throw new SkinExtensionSandboxError("SKIN_EXTENSION_BROWSER_UNSUPPORTED", "This browser cannot create the isolated extension prototype.");
}
const hostWindow = view;
const nonce = randomNonce(hostWindow);
const workerUrl = createWorkerDataUrl(options.source);
const frame = document.createElement("iframe");
frame.setAttribute("sandbox", "allow-scripts");
frame.setAttribute("allow", "camera 'none'; microphone 'none'; display-capture 'none'; geolocation 'none'");
frame.setAttribute("referrerpolicy", "no-referrer");
frame.setAttribute("title", `${manifest.name} isolated component`);
frame.tabIndex = 0;
frame.style.display = "block";
frame.style.width = "100%";
frame.style.height = "100%";
frame.style.border = "0";
frame.style.background = "transparent";
frame.srcdoc = createSandboxDocument(workerUrl, nonce);
let active = true;
let closeReason: string | null = null;
let port: MessagePort | null = null;
let readySettled = false;
let stopTimer: number | undefined;
let stoppedSettled = false;
let loadCount = 0;
let invalidMessages = 0;
let totalRequests = 0;
let acceptedRequests = 0;
let rejectedRequests = 0;
const requestTimes: number[] = [];
const recentRequestIds = new Set<string>();
const recentRequestIdOrder: string[] = [];
const pendingHostRequests = new Map<string, AbortController>();
let resolveReady!: () => void;
let rejectReady!: (reason: Error) => void;
const ready = new Promise<void>((resolve, reject) => {
resolveReady = resolve;
rejectReady = reject;
});
let resolveStopped!: () => void;
const stopped = new Promise<void>((resolve) => { resolveStopped = resolve; });
const timer = hostWindow.setTimeout(() => close("handshake-timeout", new SkinExtensionSandboxError("SKIN_EXTENSION_HANDSHAKE_TIMEOUT", "The extension did not complete its isolated handshake.")), HANDSHAKE_TIMEOUT_MS);
function finalizeStop(): void {
if (stoppedSettled) return;
stoppedSettled = true;
if (stopTimer !== undefined) hostWindow.clearTimeout(stopTimer);
if (port) {
port.onmessage = null;
port.onmessageerror = null;
port.close();
port = null;
}
frame.remove();
resolveStopped();
}
function close(reason = "closed", error?: Error): void {
if (!active) return;
active = false;
closeReason = reason;
hostWindow.clearTimeout(timer);
hostWindow.removeEventListener("message", onWindowMessage);
frame.removeEventListener("load", onFrameLoad);
frame.removeEventListener("error", onFrameError);
for (const controller of pendingHostRequests.values()) controller.abort();
pendingHostRequests.clear();
requestTimes.length = 0;
recentRequestIds.clear();
recentRequestIdOrder.length = 0;
if (!readySettled) {
readySettled = true;
rejectReady(error ?? new SkinExtensionSandboxError("SKIN_EXTENSION_RUNTIME_CLOSED", "The extension runtime closed before it was ready."));
}
if (port) {
try {
port.postMessage({ channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, type: "shutdown" });
stopTimer = hostWindow.setTimeout(finalizeStop, SHUTDOWN_TIMEOUT_MS);
} catch {
finalizeStop();
}
} else finalizeStop();
}
function failInvalidMessage(): void {
invalidMessages += 1;
if (invalidMessages >= 3) close("invalid-protocol");
}
function sendResponse(id: string, ok: true, data: SkinExtensionSessionStatus): void;
function sendResponse(id: string, ok: false, code: string, message: string): void;
function sendResponse(id: string, ok: boolean, dataOrCode: SkinExtensionSessionStatus | string, message?: string): void {
if (!active || !port) return;
const response = ok
? { channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, id, type: "response", ok: true, data: dataOrCode }
: { channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, id, type: "response", ok: false, error: { code: dataOrCode, message } };
try { port.postMessage(response); }
catch { close("response-failed"); }
}
function consumeRequestRate(now: number): boolean {
while (requestTimes.length > 0 && now - requestTimes[0] >= 1000) requestTimes.shift();
if (requestTimes.length >= SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND) return false;
requestTimes.push(now);
return true;
}
async function handleRequest(value: unknown): Promise<void> {
if (!active || !port) return;
if (serializedMessageBytes(value) > SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT) {
close("message-too-large");
return;
}
if (!consumeRequestRate(hostWindow.performance.now())) {
close("message-rate-exceeded");
return;
}
const request = parseSkinExtensionRequestMessage(value, nonce);
if (!request) {
failInvalidMessage();
return;
}
if (recentRequestIds.has(request.id) || pendingHostRequests.has(request.id)) {
close("duplicate-request-id");
return;
}
recentRequestIds.add(request.id);
recentRequestIdOrder.push(request.id);
if (recentRequestIdOrder.length > 256) recentRequestIds.delete(recentRequestIdOrder.shift()!);
totalRequests += 1;
if (totalRequests > SKIN_EXTENSION_SANDBOX_MAX_REQUESTS) {
close("request-budget-exceeded");
return;
}
if (!manifest.permissions.includes(request.permission)
|| !isSkinExtensionPermissionApproved(approval, manifest.id, request.permission)) {
rejectedRequests += 1;
sendResponse(request.id, false, "CAPABILITY_NOT_APPROVED", "The extension capability is not approved.");
return;
}
if (request.permission !== "session.status.read") {
rejectedRequests += 1;
sendResponse(request.id, false, "CAPABILITY_UNAVAILABLE", "The extension capability is unavailable in this prototype.");
return;
}
acceptedRequests += 1;
const controller = new AbortController();
pendingHostRequests.set(request.id, controller);
try {
const status = sanitizeSkinExtensionSessionStatus(await options.readSessionStatus(controller.signal));
if (active && pendingHostRequests.get(request.id) === controller) {
pendingHostRequests.delete(request.id);
sendResponse(request.id, true, status);
}
} catch {
if (pendingHostRequests.get(request.id) === controller) pendingHostRequests.delete(request.id);
if (active) sendResponse(request.id, false, "HOST_DATA_UNAVAILABLE", "The requested session status is unavailable.");
}
}
function onPortMessage(event: MessageEvent): void {
if (!active) {
const value = event.data;
if (isPlainRecord(value) && Object.keys(value).length === 4
&& value.channel === MESSAGE_CHANNEL && value.apiVersion === SKIN_EXTENSION_API_VERSION
&& value.nonce === nonce && value.type === "shutdown-complete") finalizeStop();
return;
}
if (serializedMessageBytes(event.data) > SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT) {
close("message-too-large");
return;
}
if (isPlainRecord(event.data) && Object.keys(event.data).length === 4
&& event.data.channel === MESSAGE_CHANNEL && event.data.apiVersion === SKIN_EXTENSION_API_VERSION
&& event.data.nonce === nonce && event.data.type === "runtime-error") {
close("worker-error", new SkinExtensionSandboxError("SKIN_EXTENSION_WORKER_FAILED", "The isolated extension worker failed."));
return;
}
if (!readySettled) {
if (!isReadyMessage(event.data, nonce)) {
close("invalid-handshake", new SkinExtensionSandboxError("SKIN_EXTENSION_HANDSHAKE_INVALID", "The isolated extension handshake was invalid."));
return;
}
readySettled = true;
hostWindow.clearTimeout(timer);
resolveReady();
return;
}
void handleRequest(event.data);
}
function onWindowMessage(event: MessageEvent): void {
if (!active || port) {
for (const transferredPort of event.ports) transferredPort.close();
return;
}
const validHello = isSkinExtensionBootstrapHello({ source: event.source, origin: event.origin, data: event.data, ports: event.ports }, frame.contentWindow, nonce);
if (!validHello) {
for (const transferredPort of event.ports) transferredPort.close();
return;
}
port = event.ports[0];
port.onmessage = onPortMessage;
port.onmessageerror = () => close("message-deserialization-failed");
port.start();
hostWindow.removeEventListener("message", onWindowMessage);
port.postMessage({ channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, type: "host-ready" });
}
function onFrameLoad(): void {
loadCount += 1;
if (loadCount > 1) close("frame-navigation");
}
function onFrameError(): void { close("frame-error"); }
hostWindow.addEventListener("message", onWindowMessage);
frame.addEventListener("load", onFrameLoad);
frame.addEventListener("error", onFrameError);
options.container.append(frame);
return {
frame,
manifest,
approval,
ready,
stopped,
get closed() { return !active; },
get closeReason() { return closeReason; },
get acceptedRequests() { return acceptedRequests; },
get rejectedRequests() { return rejectedRequests; },
revokePermission(permission) {
if (manifest.permissions.includes(permission)) close(`permission-revoked:${permission}`);
},
close,
};
}
@@ -0,0 +1,98 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
SKIN_EXTENSION_WASM_SOURCE_LIMIT,
SkinExtensionWasmPolicyError,
validateSkinExtensionWasmBytes,
validateSkinExtensionWasmImportsAndExports,
} from "./skin-extension-wasm-policy.js";
import {
createSkinExtensionWasmCappedRunProbe,
createSkinExtensionWasmGcAllocationProbe,
createSkinExtensionWasmInfiniteStartProbe,
createSkinExtensionWasmInternalMemoryProbe,
createSkinExtensionWasmInternalTableProbe,
createSkinExtensionWasmOversizedElementVectorProbe,
createSkinExtensionWasmOversizedFunctionBodyProbe,
createSkinExtensionWasmOversizedLocalProbe,
createSkinExtensionWasmOversizedSignatureProbe,
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmStatusProbe,
createSkinExtensionWasmTooManyFunctionsProbe,
} 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, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
});
test("Wasm policy rejects module-defined memory or tables that bypass host limits", () => {
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInternalMemoryProbe()), {
code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION",
});
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInternalTableProbe()), {
code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION",
});
});
test("Wasm metadata parser rejects missing import memory, malformed sections, and oversized modules", () => {
assert.throws(() => validateSkinExtensionWasmImportsAndExports(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])), {
code: "SKIN_EXTENSION_WASM_IMPORT_INVALID",
});
assert.throws(() => validateSkinExtensionWasmBytes(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 127])), {
code: "SKIN_EXTENSION_WASM_INVALID",
});
assert.throws(() => validateSkinExtensionWasmBytes(new Uint8Array(SKIN_EXTENSION_WASM_SOURCE_LIMIT + 1)), {
code: "SKIN_EXTENSION_WASM_SIZE",
});
assert.ok(new SkinExtensionWasmPolicyError("test", "test") instanceof Error);
});
test("Wasm preflight caps function count and body size before the interpreter sees a module", () => {
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmTooManyFunctionsProbe()), {
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
});
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedFunctionBodyProbe()), {
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
});
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInfiniteStartProbe()), {
code: "SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE",
});
});
test("Wasm preflight rejects GC allocation and bounds nested vectors before interpretation", () => {
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmGcAllocationProbe()), {
code: "SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE",
});
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedSignatureProbe()), {
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
});
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedLocalProbe()), {
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
});
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedElementVectorProbe()), {
code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION",
});
});
test("Wasm import parsing reads the bounded permission contract without native compilation", () => {
const status = createSkinExtensionWasmStatusProbe();
assert.throws(() => validateSkinExtensionWasmImportsAndExports(status), {
code: "SKIN_EXTENSION_WASM_PERMISSION_INVALID",
});
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(status, ["session.status.read"]), {
usesSessionStatus: true,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
assert.equal(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmCappedRunProbe()).usesSessionStatus, false);
});
test("Wasm instruction scanning distinguishes extension prefixes from signed integer bytes", () => {
const bytes = createSkinExtensionWasmPrefixByteImmediateProbe();
assert.doesNotThrow(() => validateSkinExtensionWasmBytes(bytes));
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(bytes), {
usesSessionStatus: false,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
});
@@ -0,0 +1,437 @@
export const SKIN_EXTENSION_WASM_SOURCE_LIMIT = 256 * 1024;
export const SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES = 64;
export const SKIN_EXTENSION_WASM_PAGE_BYTES = 64 * 1024;
export const SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS = 3_000;
export const SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS = 100;
export const SKIN_EXTENSION_WASM_MESSAGE_LIMIT = 8 * 1024;
export const SKIN_EXTENSION_WASM_STATUS_READ_LIMIT = 10;
export const SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT = 512;
export const SKIN_EXTENSION_WASM_FUEL_LIMIT = 10_000_000n;
export const SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
export const SKIN_EXTENSION_WASM_FUNCTION_LIMIT = 128;
export const SKIN_EXTENSION_WASM_FUNCTION_BODY_LIMIT = 32 * 1024;
export const SKIN_EXTENSION_WASM_CODE_BYTES_LIMIT = 192 * 1024;
const SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT = 64;
const SKIN_EXTENSION_WASM_LOCAL_GROUP_LIMIT = 256;
const SKIN_EXTENSION_WASM_LOCAL_LIMIT = 4_096;
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, 2], // memory and one optional capability import
[3, SKIN_EXTENSION_WASM_FUNCTION_LIMIT],
[6, 128], // globals
[7, 64], // exports; the runner later requires exactly run
[9, 64], // element segments
[11, 64], // data segments
[12, 64], // data segments referenced by bulk-memory operations
]);
export class SkinExtensionWasmPolicyError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinExtensionWasmPolicyError";
}
}
function readU32(bytes: Uint8Array, offset: number, end: number): { value: number; next: number } {
let value = 0;
let shift = 0;
for (let index = 0; index < 5; index += 1) {
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section length.");
const byte = bytes[offset++];
if (index === 4 && (byte & 0xf0) !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has an overflowing section length.");
value |= (byte & 0x7f) << shift;
if ((byte & 0x80) === 0) return { value: value >>> 0, next: offset };
shift += 7;
}
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has an invalid section length.");
}
function skipSignedLeb128(bytes: Uint8Array, offset: number, end: number, maxBytes: number): number {
for (let index = 0; index < maxBytes; index += 1) {
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated integer immediate.");
if ((bytes[offset++] & 0x80) === 0) return offset;
}
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains an oversized integer immediate.");
}
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.");
}
return offset + 1;
}
function validateTypeSection(bytes: Uint8Array, start: number, end: number): void {
let cursor = readU32(bytes, start, end);
if (cursor.value > 128) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many function types.");
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.");
}
const parameters = readU32(bytes, cursor.next, end);
cursor.next = parameters.next;
if (parameters.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function signature contains too many parameters.");
}
for (let index = 0; index < parameters.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end);
const results = readU32(bytes, cursor.next, end);
cursor.next = results.next;
if (results.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function signature contains too many results.");
}
for (let index = 0; index < results.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end);
}
if (cursor.next !== end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension type section contains trailing bytes.");
}
function readBlockType(bytes: Uint8Array, offset: number, end: number): number {
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated block type.");
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.");
}
return skipSignedLeb128(bytes, offset, end, 5);
}
function scanFunctionBody(bytes: Uint8Array, start: number, end: number): number {
let cursor = readU32(bytes, start, end);
if (cursor.value > SKIN_EXTENSION_WASM_LOCAL_GROUP_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function contains too many local groups.");
}
const localGroupCount = cursor.value;
let localCount = 0;
for (let index = 0; index < localGroupCount; index += 1) {
const group = readU32(bytes, cursor.next, end);
cursor.next = group.next;
localCount += group.value;
if (localCount > SKIN_EXTENSION_WASM_LOCAL_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension module declares too many local values.");
}
cursor.next = requireScalarValueType(bytes, cursor.next, end);
}
while (cursor.next < end) {
const opcode = bytes[cursor.next++];
if ((opcode >= 0x45 && opcode <= 0xc4)
|| opcode === 0x00 || opcode === 0x01 || opcode === 0x05 || opcode === 0x0b
|| opcode === 0x0f || opcode === 0x1a || opcode === 0x1b) continue;
if (opcode === 0x02 || opcode === 0x03 || opcode === 0x04) {
cursor.next = readBlockType(bytes, cursor.next, end);
continue;
}
if (opcode === 0x0c || opcode === 0x0d || opcode === 0x10
|| (opcode >= 0x20 && opcode <= 0x24)) {
cursor = readU32(bytes, cursor.next, end);
continue;
}
if (opcode === 0x0e) {
const labels = readU32(bytes, cursor.next, end);
cursor.next = labels.next;
if (labels.value > end - cursor.next) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension branch table is truncated.");
for (let index = 0; index <= labels.value; index += 1) cursor = readU32(bytes, cursor.next, end);
continue;
}
if (opcode === 0x11) {
cursor = readU32(bytes, cursor.next, end);
const table = readU32(bytes, cursor.next, end);
if (table.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported table.");
cursor.next = table.next;
continue;
}
if (opcode === 0x1c) {
const selected = readU32(bytes, cursor.next, end);
cursor.next = selected.next;
if (selected.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "A typed selection contains too many values.");
}
for (let index = 0; index < selected.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end);
continue;
}
if (opcode >= 0x28 && opcode <= 0x3e) {
const alignment = readU32(bytes, cursor.next, end);
cursor.next = alignment.next;
if (alignment.value > 3) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Multi-memory and over-aligned memory operations are disabled.");
cursor = readU32(bytes, cursor.next, end);
continue;
}
if (opcode === 0x3f || opcode === 0x40) {
const memory = readU32(bytes, cursor.next, end);
if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
cursor.next = memory.next;
continue;
}
if (opcode === 0x41 || opcode === 0x42) {
cursor.next = skipSignedLeb128(bytes, cursor.next, end, opcode === 0x41 ? 5 : 10);
continue;
}
if (opcode === 0x43 || opcode === 0x44) {
const immediateBytes = opcode === 0x43 ? 4 : 8;
if (cursor.next + immediateBytes > end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated floating-point immediate.");
cursor.next += immediateBytes;
continue;
}
if (opcode === 0xfc) {
const operation = readU32(bytes, cursor.next, end);
cursor.next = operation.next;
if (operation.value <= 7) continue; // Saturating numeric conversions.
if (operation.value === 8) {
cursor = readU32(bytes, cursor.next, end); // data index
const memory = readU32(bytes, cursor.next, end);
if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
cursor.next = memory.next;
continue;
}
if (operation.value === 9) { cursor = readU32(bytes, cursor.next, end); continue; } // data.drop
if (operation.value === 10) {
const firstMemory = readU32(bytes, cursor.next, end);
const secondMemory = readU32(bytes, firstMemory.next, end);
if (firstMemory.value !== 0 || secondMemory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
cursor.next = secondMemory.next;
continue;
}
if (operation.value === 11) {
const memory = readU32(bytes, cursor.next, end);
if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
cursor.next = memory.next;
continue;
}
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.");
}
return localCount;
}
/**
* Resource-policy preflight before the fixed Wasmi interpreter parses an extension.
* It bounds the binary work up front; Wasmi still performs full module validation.
*/
export function validateSkinExtensionWasmBytes(source: Uint8Array): void {
if (!(source instanceof Uint8Array) || source.byteLength < WASM_HEADER.length || source.byteLength > SKIN_EXTENSION_WASM_SOURCE_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_SIZE", "The extension module is empty, invalid, or exceeds its size limit.");
}
if (WASM_HEADER.some((byte, index) => source[index] !== byte)) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module header or version is unsupported.");
}
let offset: number = WASM_HEADER.length;
let previousSectionRank = 0;
let customSectionCount = 0;
const seenSections = new Set<number>();
let definedFunctionCount: number | undefined;
let codeFunctionCount: number | undefined;
let codeBytes = 0;
let totalLocalCount = 0;
while (offset < source.byteLength) {
const sectionId = source[offset++];
if (sectionId > 12) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains an unknown section.");
if (sectionId === 0) {
customSectionCount += 1;
if (customSectionCount > 8) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many custom sections.");
} else {
if (seenSections.has(sectionId)) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains a duplicate section.");
seenSections.add(sectionId);
// The data-count section (12) is ordered immediately before code (10) by the Wasm binary format.
const rank = sectionId === 12 ? 9.5 : sectionId;
if (rank <= previousSectionRank) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module sections are out of order.");
previousSectionRank = rank;
}
if (sectionId === 8) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Module start functions are disabled; extensions may enter only through the exported run function.");
}
const sectionLength = readU32(source, offset, source.byteLength);
offset = sectionLength.next;
const sectionEnd = offset + sectionLength.value;
if (sectionEnd > source.byteLength) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section.");
if (sectionId === 1) validateTypeSection(source, offset, sectionEnd);
const vectorLimit = BOUNDED_VECTOR_COUNTS.get(sectionId);
if (vectorLimit !== undefined) {
const count = readU32(source, offset, sectionEnd);
if (count.value > vectorLimit) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module exceeds a structural item limit.");
if (sectionId === 3) definedFunctionCount = count.value;
}
// This model permits exactly one host-provided bounded linear memory and no tables.
// Module-defined memories, tables, and element segments would bypass that resource model.
if (sectionId === 4 || sectionId === 5) {
const count = readU32(source, offset, sectionEnd).value;
if (count !== 0) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Extension modules must import bounded memory and cannot define memory or tables.");
}
}
if (sectionId === 9 && readU32(source, offset, sectionEnd).value !== 0) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Extension modules cannot declare element segments or tables.");
}
if (sectionId === 10) {
let cursor = offset;
const count = readU32(source, cursor, sectionEnd);
cursor = count.next;
if (count.value > SKIN_EXTENSION_WASM_FUNCTION_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many function bodies.");
}
codeFunctionCount = count.value;
for (let index = 0; index < count.value; index += 1) {
const body = readU32(source, cursor, sectionEnd);
cursor = body.next;
if (!body.value || body.value > SKIN_EXTENSION_WASM_FUNCTION_BODY_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function body exceeds its size limit.");
}
codeBytes += body.value;
if (codeBytes > SKIN_EXTENSION_WASM_CODE_BYTES_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension code section exceeds its total size limit.");
}
const bodyEnd = cursor + body.value;
if (bodyEnd > sectionEnd) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "An extension function body is truncated.");
totalLocalCount += scanFunctionBody(source, cursor, bodyEnd);
if (totalLocalCount > SKIN_EXTENSION_WASM_LOCAL_LIMIT) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module declares too many local values.");
}
cursor = bodyEnd;
}
if (cursor !== sectionEnd) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension code section contains trailing bytes.");
}
offset = sectionEnd;
}
if (definedFunctionCount !== undefined && codeFunctionCount !== undefined && definedFunctionCount !== codeFunctionCount) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function and code counts do not match.");
}
}
export interface SkinExtensionWasmModuleMetadata {
usesSessionStatus: boolean;
memoryMaximumPages: number;
}
function readWasmName(bytes: Uint8Array, offset: number, end: number): { value: string; next: number } {
const length = readU32(bytes, offset, end);
if (length.value > 80 || length.next + length.value > end) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module contains an invalid import or export name.");
}
try {
return {
value: new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(length.next, length.next + length.value)),
next: length.next + length.value,
};
} catch {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module contains an invalid UTF-8 import or export name.");
}
}
function readImportedMemoryMaximum(bytes: Uint8Array, offset: number, end: number): { maximumPages: number; next: number } {
const flags = readU32(bytes, offset, end);
if (flags.value !== 0 && flags.value !== 1) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Shared and memory64 imports are not supported.");
}
const minimum = readU32(bytes, flags.next, end);
let next = minimum.next;
let maximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
if (flags.value === 1) {
const maximum = readU32(bytes, next, end);
next = maximum.next;
maximumPages = maximum.value;
if (maximumPages < 1 || maximumPages > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES || maximumPages < minimum.value) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The imported memory limit is outside the host's allowed range.");
}
}
if (minimum.value > 1 || minimum.value > maximumPages) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The module requests more initial memory than the host provides.");
}
return { maximumPages, next };
}
/** Parses only bounded imports/exports; author bytes never reach the browser's native Wasm compiler. */
export function validateSkinExtensionWasmImportsAndExports(
bytes: Uint8Array,
grantedPermissions: readonly string[] = [],
): SkinExtensionWasmModuleMetadata {
validateSkinExtensionWasmBytes(bytes);
let offset: number = WASM_HEADER.length;
let memoryMaximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
let hasMemory = false;
let usesSessionStatus = false;
let hasExports = false;
while (offset < bytes.byteLength) {
const sectionId = bytes[offset++];
const sectionLength = readU32(bytes, offset, bytes.byteLength);
offset = sectionLength.next;
const end = offset + sectionLength.value;
if (end > bytes.byteLength) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section.");
if (sectionId === 2) {
const count = readU32(bytes, offset, end);
if (count.value < 1 || count.value > 2) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and at most one approved capability.");
}
let cursor = count.next;
for (let index = 0; index < count.value; index += 1) {
const moduleName = readWasmName(bytes, cursor, end);
const fieldName = readWasmName(bytes, moduleName.next, end);
cursor = fieldName.next;
if (cursor >= end || moduleName.value !== "env") {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module may import only the host's env memory and approved capability.");
}
const kind = bytes[cursor++];
if (kind === 0) {
const typeIndex = readU32(bytes, cursor, end);
cursor = typeIndex.next;
if (fieldName.value !== "session_status_read" || usesSessionStatus) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module requested an unsupported or duplicate function import.");
}
usesSessionStatus = true;
} else if (kind === 2) {
if (fieldName.value !== "memory" || hasMemory) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import exactly one env.memory value.");
}
const memory = readImportedMemoryMaximum(bytes, cursor, end);
cursor = memory.next;
memoryMaximumPages = memory.maximumPages;
hasMemory = true;
} else {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "Tables, globals, tags, and unknown imports are not supported.");
}
}
if (cursor !== end || !hasMemory) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import exactly one env.memory value.");
}
}
if (sectionId === 7) {
const count = readU32(bytes, offset, end);
if (count.value !== 1) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module must export only one run function.");
}
let cursor = count.next;
const name = readWasmName(bytes, cursor, end);
cursor = name.next;
if (cursor >= end || name.value !== "run" || bytes[cursor++] !== 0) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module must export one function named run.");
}
const functionIndex = readU32(bytes, cursor, end);
cursor = functionIndex.next;
if (cursor !== end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module has trailing export data.");
hasExports = true;
}
offset = end;
}
if (!hasMemory || !hasExports) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import bounded env.memory and export a run function.");
}
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, memoryMaximumPages };
}
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createSkinExtensionApproval, parseSkinExtensionManifest } from "../../../src/shared/skin-extension.js";
import {
createSkinExtensionWasmSandboxPrototype,
SKIN_EXTENSION_WASM_RUNTIME_ENABLED,
} from "./skin-extension-wasm-sandbox.js";
import { SKIN_EXTENSION_WASM_SOURCE_LIMIT } from "./skin-extension-wasm-policy.js";
const manifest = parseSkinExtensionManifest({
schemaVersion: 1,
packageType: "extension",
id: "test.wasm-extension",
name: "Wasm extension",
version: "1.0.0",
apiVersion: 1,
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({
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" });
});
@@ -0,0 +1,217 @@
import {
isSkinExtensionPermissionApproved,
parseSkinExtensionApproval,
parseSkinExtensionManifest,
sanitizeSkinExtensionSessionStatus,
type SkinExtensionPermissionId,
type SkinExtensionSessionStatus,
} from "../../../src/shared/skin-extension.js";
import {
SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS,
SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
SKIN_EXTENSION_WASM_MESSAGE_LIMIT,
SKIN_EXTENSION_WASM_SOURCE_LIMIT,
SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS,
SKIN_EXTENSION_WASM_STATUS_READ_LIMIT,
validateSkinExtensionWasmBytes,
} from "./skin-extension-wasm-policy.js";
export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = false as const;
export class SkinExtensionWasmSandboxError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinExtensionWasmSandboxError";
}
}
export interface SkinExtensionWasmSandboxResult {
result: number | string;
linearMemoryBytes: number;
statusReadCount: number;
sessionSnapshot?: SkinExtensionSessionStatus;
}
export interface SkinExtensionWasmSandboxOptions {
manifest: unknown;
approval: unknown;
wasmBytes: Uint8Array;
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
/** This prototype is available only to the development security harness. */
prototypeOnly: true;
}
export interface SkinExtensionWasmSandboxHandle {
readonly ready: Promise<void>;
readonly result: Promise<SkinExtensionWasmSandboxResult>;
readonly stopped: Promise<void>;
readonly closed: boolean;
readonly closeReason: string | null;
readonly capabilityRequests: number;
revokePermission(permission: SkinExtensionPermissionId): void;
close(reason?: string): void;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function messageSize(value: unknown): number {
try { return new TextEncoder().encode(JSON.stringify(value)).byteLength; }
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.");
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.");
}
const manifest = parseSkinExtensionManifest(options.manifest);
const approval = parseSkinExtensionApproval(options.approval);
validateSkinExtensionWasmBytes(options.wasmBytes);
const grantedPermissions = manifest.permissions.filter((permission) =>
isSkinExtensionPermissionApproved(approval, manifest.id, permission));
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",
});
let active = true;
let closeReason: string | null = null;
const hostAbortController = new AbortController();
let readySettled = false;
let resultSettled = false;
let capabilityRequests = 0;
let approvedSessionStatus: SkinExtensionSessionStatus | undefined;
let startupTimer: number | undefined;
let executionTimer: number | undefined;
let resolveReady!: () => void;
let rejectReady!: (error: Error) => void;
let resolveResult!: (value: SkinExtensionWasmSandboxResult) => void;
let rejectResult!: (error: Error) => void;
let resolveStopped!: () => void;
const ready = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
const result = new Promise<SkinExtensionWasmSandboxResult>((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });
const stopped = new Promise<void>((resolve) => { resolveStopped = resolve; });
void ready.catch(() => undefined);
void result.catch(() => undefined);
function finish(reason: string, error?: Error): void {
if (!active) return;
active = false;
closeReason = reason;
approvedSessionStatus = undefined;
hostAbortController.abort();
if (startupTimer !== undefined) clearTimeout(startupTimer);
if (executionTimer !== undefined) clearTimeout(executionTimer);
worker.onmessage = null;
worker.onmessageerror = null;
worker.onerror = null;
worker.terminate();
if (!readySettled) {
readySettled = true;
rejectReady(error ?? new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_CLOSED", "The Wasm extension stopped before execution began."));
}
if (!resultSettled) {
resultSettled = true;
rejectResult(error ?? new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_CLOSED", "The Wasm extension stopped before returning a result."));
}
resolveStopped();
}
function complete(value: SkinExtensionWasmSandboxResult): void {
if (!active) return;
active = false;
closeReason = "completed";
if (startupTimer !== undefined) clearTimeout(startupTimer);
if (executionTimer !== undefined) clearTimeout(executionTimer);
worker.onmessage = null;
worker.onmessageerror = null;
worker.onerror = null;
worker.terminate();
if (!readySettled) { readySettled = true; resolveReady(); }
if (!resultSettled) { resultSettled = true; resolveResult(value); }
resolveStopped();
}
worker.onmessage = (event: MessageEvent<unknown>) => {
if (!active || messageSize(event.data) > SKIN_EXTENSION_WASM_MESSAGE_LIMIT || !isPlainRecord(event.data)) {
finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker returned an invalid or oversized message."));
return;
}
const message = event.data;
if (message.type === "capability-request") {
if (Object.keys(message).length !== 3 || message.requestId !== "session-status-1" || message.permission !== "session.status.read"
|| capabilityRequests !== 0 || !grantedPermissions.includes("session.status.read")) {
finish("capability-denied", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The Wasm worker requested an unapproved capability."));
return;
}
capabilityRequests += 1;
Promise.resolve().then(() => options.readSessionStatus(hostAbortController.signal)).then(sanitizeSkinExtensionSessionStatus).then((status) => {
if (!active) return;
approvedSessionStatus = status;
worker.postMessage({ type: "capability-response", requestId: message.requestId, approved: true, status });
}).catch(() => {
if (active) worker.postMessage({ type: "capability-response", requestId: message.requestId, approved: false });
});
return;
}
if (message.type === "running" && Object.keys(message).length === 1) {
if (readySettled) {
finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker sent an unexpected execution-start message."));
return;
}
readySettled = true;
if (startupTimer !== undefined) clearTimeout(startupTimer);
resolveReady();
executionTimer = window.setTimeout(() => finish("execution-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_EXECUTION_TIMEOUT", "The Wasm extension exceeded its execution time limit.")), SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS);
return;
}
if (message.type === "complete") {
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount"];
if (Object.keys(message).length !== expectedKeys.length
|| Object.keys(message).some((key) => !expectedKeys.includes(key))
|| (typeof message.result !== "number" && typeof message.result !== "string")
|| !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) {
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, ...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) });
return;
}
if (message.type === "error" && Object.keys(message).length === 3
&& typeof message.code === "string" && typeof message.message === "string") {
finish("worker-error", new SkinExtensionWasmSandboxError(message.code, message.message));
return;
}
finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker returned an unsupported message."));
};
worker.onmessageerror = () => finish("message-deserialization-failed", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker message could not be decoded."));
worker.onerror = () => finish("worker-error", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_WORKER_FAILED", "The isolated Wasm worker failed."));
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]);
return {
ready,
result,
stopped,
get closed() { return !active; },
get closeReason() { return closeReason; },
get capabilityRequests() { return capabilityRequests; },
revokePermission(permission) {
if (manifest.permissions.includes(permission)) finish(`permission-revoked:${permission}`);
},
close(reason = "closed") { finish(reason); },
};
}
@@ -0,0 +1,167 @@
import {
sanitizeSkinExtensionSessionStatus,
type SkinExtensionSessionStatus,
} from "../../../src/shared/skin-extension.js";
import {
SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
SKIN_EXTENSION_WASM_FUEL_LIMIT,
SKIN_EXTENSION_WASM_MESSAGE_LIMIT,
SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT,
SKIN_EXTENSION_WASM_STATUS_READ_LIMIT,
validateSkinExtensionWasmImportsAndExports,
} from "./skin-extension-wasm-policy.js";
interface RunMessage {
type: "run";
bytes: ArrayBuffer;
approvedPermissions: string[];
}
interface CapabilityResponse {
type: "capability-response";
requestId: string;
approved: boolean;
status?: unknown;
}
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;
last_error_code: () => number;
last_status_read_count: () => number;
last_guest_memory_bytes: () => number;
}
const scope = self as unknown as {
addEventListener(type: string, listener: (event: MessageEvent<unknown>) => void): void;
postMessage(message: unknown): void;
};
let started = false;
let pendingCapability: { requestId: string; resolve: (message: CapabilityResponse) => void } | null = null;
function isPlainRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function sendError(code: string, message: string): void {
scope.postMessage({ type: "error", code, message });
}
scope.addEventListener("message", (event: MessageEvent<unknown>) => {
const value = event.data;
if (isPlainRecord(value) && value.type === "capability-response" && pendingCapability
&& value.requestId === pendingCapability.requestId && typeof value.approved === "boolean") {
const resolve = pendingCapability.resolve;
pendingCapability = null;
resolve(value as unknown as CapabilityResponse);
return;
}
if (started || !isPlainRecord(value) || value.type !== "run" || !(value.bytes instanceof ArrayBuffer)
|| !Array.isArray(value.approvedPermissions) || value.approvedPermissions.some((permission) => typeof permission !== "string")
|| Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions"].includes(key))) {
sendError("SKIN_EXTENSION_WASM_JOB_INVALID", "The isolated Wasm job message is invalid.");
return;
}
started = true;
void run(value as unknown as RunMessage);
});
async function requestSessionStatus(): Promise<SkinExtensionSessionStatus> {
const requestId = "session-status-1";
const response = await new Promise<CapabilityResponse>((resolve) => {
pendingCapability = { requestId, resolve };
scope.postMessage({ type: "capability-request", requestId, permission: "session.status.read" });
});
if (!response.approved) throw new Error("The host denied session.status.read.");
return sanitizeSkinExtensionSessionStatus(response.status);
}
async function run(job: RunMessage): Promise<void> {
try {
const bytes = new Uint8Array(job.bytes);
const metadata = validateSkinExtensionWasmImportsAndExports(bytes, job.approvedPermissions);
const interpreter = await loadWasmiInterpreter();
const status = metadata.usesSessionStatus ? await requestSessionStatus() : null;
const statusBytes = status ? new TextEncoder().encode(JSON.stringify(status)) : null;
if (statusBytes && statusBytes.byteLength > SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT) {
sendError("SKIN_EXTENSION_WASM_STATUS_SIZE", "The approved session snapshot exceeds its size limit.");
return;
}
const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0);
const pointer = interpreter.alloc(payloadLength);
if (!pointer) {
sendError("SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT", "The extension input exceeds the interpreter's bounded memory.");
return;
}
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);
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);
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"
: "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 linearMemoryBytes = interpreter.last_guest_memory_bytes();
if (!Number.isSafeInteger(result) || !Number.isSafeInteger(statusReadCount) || statusReadCount < 0
|| statusReadCount > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT || !Number.isSafeInteger(linearMemoryBytes)
|| 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.");
return;
}
const message = {
type: "complete",
result,
linearMemoryBytes,
statusReadCount,
};
if (new TextEncoder().encode(JSON.stringify(message)).byteLength > SKIN_EXTENSION_WASM_MESSAGE_LIMIT) {
sendError("SKIN_EXTENSION_WASM_MESSAGE_SIZE", "The module result exceeds its message limit.");
return;
}
scope.postMessage(message);
} catch (error) {
const candidate = error as { code?: unknown; message?: unknown };
const code = typeof candidate?.code === "string" ? candidate.code : "SKIN_EXTENSION_WASM_FAILED";
const detail = typeof candidate?.message === "string" ? ` ${candidate.message.slice(0, 240)}` : "";
sendError(code, `The bounded Wasm extension failed validation or execution.${detail}`);
}
}
async function loadWasmiInterpreter(): Promise<WasmiInterpreterExports> {
const response = await fetch(new URL("/skin-wasm-interpreter.wasm", self.location.origin), { cache: "force-cache" });
if (!response.ok) throw new Error("The bounded Wasmi interpreter asset could not be loaded.");
const contentLength = Number(response.headers.get("content-length"));
if (Number.isFinite(contentLength) && (contentLength < 8 || contentLength > 8 * 1024 * 1024)) {
throw new Error("The bounded Wasmi interpreter asset has an invalid size.");
}
const artifact = await response.arrayBuffer();
if (artifact.byteLength < 8 || artifact.byteLength > 8 * 1024 * 1024) {
throw new Error("The bounded Wasmi interpreter asset has an invalid size.");
}
const { instance } = await WebAssembly.instantiate(artifact);
const exports = instance.exports as unknown as 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") {
throw new Error("The bounded Wasmi interpreter exposes an incompatible runtime interface.");
}
return exports;
}
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { orderSequentialFocusTargets } from "./skin-layout-focus.js";
test("focus preview follows browser order: positive tabindex first, then DOM order, excluding negative targets", () => {
const targets = [
{ id: "first-dom", tabIndex: 0 },
{ id: "second-positive", tabIndex: 2 },
{ id: "first-positive", tabIndex: 1 },
{ id: "programmatic-only", tabIndex: -1 },
{ id: "second-dom", tabIndex: 0 },
{ id: "same-positive", tabIndex: 1 },
];
assert.deepEqual(orderSequentialFocusTargets(targets).map((target) => target.id), [
"first-positive", "same-positive", "second-positive", "first-dom", "second-dom",
]);
});
+18
View File
@@ -0,0 +1,18 @@
export interface SequentialFocusTarget {
tabIndex: number;
}
/** Mirrors browser sequential focus order for a DOM-ordered list of focusable controls. */
export function orderSequentialFocusTargets<T extends SequentialFocusTarget>(targets: readonly T[]): T[] {
return targets
.map((target, domOrder) => ({ target, domOrder }))
.filter(({ target }) => Number.isInteger(target.tabIndex) && target.tabIndex >= 0)
.sort((left, right) => {
const leftBucket = left.target.tabIndex > 0 ? 0 : 1;
const rightBucket = right.target.tabIndex > 0 ? 0 : 1;
return leftBucket - rightBucket
|| (leftBucket === 0 ? left.target.tabIndex - right.target.tabIndex : 0)
|| left.domOrder - right.domOrder;
})
.map(({ target }) => target);
}
@@ -0,0 +1,34 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
analyzeSkinLayoutGeometry,
clampSkinLayoutOffset,
getSkinLayoutOffsetBounds,
} from "./skin-layout-geometry.js";
const page = { left: 0, top: 0, right: 800, bottom: 600 };
test("layout diagnostics detect collision and overflow only when bounds actually intersect", () => {
const target = { left: 700, top: 520, right: 840, bottom: 660 };
const issues = analyzeSkinLayoutGeometry([target], page, [{ left: 720, top: 540, right: 780, bottom: 580 }]);
assert.deepEqual(issues, { overflow: true, overlap: true });
assert.deepEqual(analyzeSkinLayoutGeometry(
[{ left: 0, top: 0, right: 40, bottom: 40 }], page,
[{ left: 48, top: 0, right: 90, bottom: 40 }],
), { overflow: false, overlap: false });
assert.deepEqual(analyzeSkinLayoutGeometry([
{ left: 0, top: 0, right: 140, bottom: 80 },
{ left: 100, top: 0, right: 240, bottom: 80 },
], page, []), { overflow: false, overlap: true });
});
test("position controls clamp every matching instance inside the available layout container", () => {
const bounds = getSkinLayoutOffsetBounds([
{ left: 100, top: 80, right: 220, bottom: 160 },
{ left: 300, top: 300, right: 420, bottom: 380 },
], page, 0, "x");
assert.deepEqual(bounds, { minimum: -100, maximum: 380 });
assert.equal(clampSkinLayoutOffset(-500, bounds), -100);
assert.equal(clampSkinLayoutOffset(500, bounds), 380);
assert.equal(getSkinLayoutOffsetBounds([{ left: -40, top: 20, right: 860, bottom: 50 }], page, 0, "x"), null);
});
+62
View File
@@ -0,0 +1,62 @@
export interface SkinLayoutRect {
left: number;
top: number;
right: number;
bottom: number;
}
export interface SkinLayoutOffsetBounds {
minimum: number;
maximum: number;
}
export interface SkinLayoutGeometryIssues {
overflow: boolean;
overlap: boolean;
}
export function analyzeSkinLayoutGeometry(
targets: readonly SkinLayoutRect[],
container: SkinLayoutRect,
peers: readonly SkinLayoutRect[],
overlapThreshold = 8,
): SkinLayoutGeometryIssues {
const intersects = (first: SkinLayoutRect, second: SkinLayoutRect) => {
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top);
return width > overlapThreshold && height > overlapThreshold;
};
const overflow = targets.some((target) => target.left < container.left - 1 || target.top < container.top - 1
|| target.right > container.right + 1 || target.bottom > container.bottom + 1);
const overlap = targets.some((target, index) => peers.some((peer) => intersects(target, peer))
|| targets.slice(index + 1).some((peer) => intersects(target, peer)));
return { overflow, overlap };
}
export function getSkinLayoutOffsetBounds(
targets: readonly SkinLayoutRect[],
container: SkinLayoutRect,
currentOffset: number,
axis: "x" | "y",
absoluteLimit = 2000,
): SkinLayoutOffsetBounds | null {
if (!targets.length || !Number.isFinite(currentOffset)) return null;
const containerStart = axis === "x" ? container.left : container.top;
const containerEnd = axis === "x" ? container.right : container.bottom;
let minimum = -absoluteLimit;
let maximum = absoluteLimit;
for (const target of targets) {
const start = axis === "x" ? target.left : target.top;
const end = axis === "x" ? target.right : target.bottom;
const baseStart = start - currentOffset;
const baseEnd = end - currentOffset;
minimum = Math.max(minimum, containerStart - baseStart);
maximum = Math.min(maximum, containerEnd - baseEnd);
}
return minimum <= maximum ? { minimum: Math.ceil(minimum), maximum: Math.floor(maximum) } : null;
}
export function clampSkinLayoutOffset(value: number, bounds: SkinLayoutOffsetBounds | null): number {
if (!bounds || !Number.isFinite(value)) return 0;
return Math.max(bounds.minimum, Math.min(bounds.maximum, Math.round(value)));
}
+261
View File
@@ -0,0 +1,261 @@
import layoutRuntimeCss from "../skins/layout-runtime.css?inline";
import {
canEditSkinLayoutComponent,
getSkinLayoutComponentId,
getSkinLayoutComponent,
type SkinLayoutDocument,
type SkinLayoutPage,
type SkinLayoutPlacement,
type SkinLayoutProfile,
} from "../../../src/shared/skin-layout.js";
import {
clearSkinLayoutOverrides,
loadSkinLayoutOverrides,
saveSkinLayoutOverrides,
updateSkinLayoutOverride,
} from "./skin-layout-storage.js";
const STYLE_ID = "webspeak-layout-runtime";
const MOBILE_QUERY = "(max-width: 740px)";
const TABLET_QUERY = "(min-width: 741px) and (max-width: 1100px)";
export interface ActiveSkinLayoutContext {
root: HTMLElement;
skinId: string;
page: SkinLayoutPage;
profile: SkinLayoutProfile;
}
let activePackageSkinId: string | null = null;
let activePackageLayout: SkinLayoutDocument | null = null;
let observer: MutationObserver | null = null;
let refreshFrame = 0;
let editorEnabled = false;
let selectedComponentId: string | null = null;
let previewComponentId: string | null = null;
let previewPlacement: SkinLayoutPlacement | null = null;
let previewScope = "";
function isLayoutPage(value: string | undefined): value is SkinLayoutPage {
return value === "home" || value === "voice" || value === "demo";
}
function currentProfile(): SkinLayoutProfile {
if (typeof window === "undefined") return "desktop";
if (window.matchMedia(MOBILE_QUERY).matches) return "mobile";
return window.matchMedia(TABLET_QUERY).matches ? "tablet" : "desktop";
}
function activeRoots(): HTMLElement[] {
if (typeof document === "undefined") return [];
return [...document.querySelectorAll<HTMLElement>(".ws-skin-root[data-ws-page]")];
}
export function getActiveSkinLayoutContext(): ActiveSkinLayoutContext | null {
const root = activeRoots()[0];
if (!root || !isLayoutPage(root.dataset.wsPage)) return null;
return {
root,
skinId: root.dataset.wsSkin || activePackageSkinId || "builtin.light",
page: root.dataset.wsPage,
profile: currentProfile(),
};
}
function effectivePlacements(context: ActiveSkinLayoutContext): Record<string, SkinLayoutPlacement> {
const packageEntries = activePackageSkinId === context.skinId
? activePackageLayout?.pages[context.page]?.[context.profile] ?? {}
: {};
const userEntries = loadSkinLayoutOverrides(context.skinId).pages[context.page]?.[context.profile] ?? {};
const result: Record<string, SkinLayoutPlacement> = {};
for (const [id, placement] of Object.entries(packageEntries)) result[id] = { ...placement };
for (const [id, placement] of Object.entries(userEntries)) result[id] = { ...result[id], ...placement };
const scope = context.skinId + ":" + context.page + ":" + context.profile;
if (previewComponentId && previewPlacement && previewScope === scope) {
result[previewComponentId] = { ...result[previewComponentId], ...previewPlacement };
}
return result;
}
function setVariable(element: HTMLElement, dataFlag: string, variable: string, value: string | undefined): void {
if (value === undefined) {
delete element.dataset[dataFlag];
element.style.removeProperty(variable);
} else {
element.dataset[dataFlag] = "true";
element.style.setProperty(variable, value);
}
}
function clearLayoutAttributes(element: HTMLElement): void {
for (const key of ["wsLayoutActive", "wsLayoutHidden", "wsLayoutSelected", "wsLayoutForeground", "wsLayoutBackground", "wsLayoutBorder", "wsLayoutRadius", "wsLayoutWidth", "wsLayoutHeight", "wsLayoutTouchTarget"]) {
delete element.dataset[key];
}
for (const key of ["--ws-layout-x", "--ws-layout-y", "--ws-layout-scale", "--ws-layout-width", "--ws-layout-height", "--ws-layout-foreground", "--ws-layout-background", "--ws-layout-border", "--ws-layout-radius"]) {
element.style.removeProperty(key);
}
}
function componentId(element: HTMLElement): string | null {
return getSkinLayoutComponentId(element.dataset.wsPart, element.dataset.wsControlKind);
}
function trustedAncestorIds(element: HTMLElement, root: HTMLElement): string[] {
const ids: string[] = [];
let ancestor = element.parentElement;
while (ancestor && ancestor !== root) {
const id = componentId(ancestor);
if (id) ids.push(id);
ancestor = ancestor.parentElement;
}
return ids;
}
function applyRoot(root: HTMLElement): void {
const pageValue = root.dataset.wsPage;
if (!isLayoutPage(pageValue)) return;
const skinId = root.dataset.wsSkin || activePackageSkinId || "builtin.light";
const context: ActiveSkinLayoutContext = { root, skinId, page: pageValue, profile: currentProfile() };
const placements = effectivePlacements(context);
const nodes = [
...(root.matches("[data-ws-part]") ? [root] : []),
...root.querySelectorAll<HTMLElement>("[data-ws-part]"),
];
for (const element of nodes) {
const id = componentId(element);
const component = id ? getSkinLayoutComponent(id, context.page) : undefined;
if (!component || !canEditSkinLayoutComponent(id!, context.page, trustedAncestorIds(element, root))) {
clearLayoutAttributes(element);
continue;
}
const placement = placements[id!];
if (!placement || !Object.keys(placement).length) {
clearLayoutAttributes(element);
// Registered touch controls keep their minimum hit area even before a
// user applies a layout override; editing must never be required for safety.
if (component.minTouchTarget) element.dataset.wsLayoutTouchTarget = String(component.minTouchTarget);
continue;
}
element.dataset.wsLayoutActive = "true";
if (component.minTouchTarget) element.dataset.wsLayoutTouchTarget = String(component.minTouchTarget);
else delete element.dataset.wsLayoutTouchTarget;
if (placement.visible === false) element.dataset.wsLayoutHidden = "true";
else delete element.dataset.wsLayoutHidden;
if (placement.x !== undefined) element.style.setProperty("--ws-layout-x", placement.x + "px");
else element.style.removeProperty("--ws-layout-x");
if (placement.y !== undefined) element.style.setProperty("--ws-layout-y", placement.y + "px");
else element.style.removeProperty("--ws-layout-y");
if (placement.scale !== undefined) element.style.setProperty("--ws-layout-scale", String(placement.scale));
else element.style.removeProperty("--ws-layout-scale");
setVariable(element, "wsLayoutWidth", "--ws-layout-width", placement.width === undefined ? undefined : placement.width + "px");
setVariable(element, "wsLayoutHeight", "--ws-layout-height", placement.height === undefined ? undefined : placement.height + "px");
setVariable(element, "wsLayoutForeground", "--ws-layout-foreground", placement.foreground);
setVariable(element, "wsLayoutBackground", "--ws-layout-background", placement.background);
setVariable(element, "wsLayoutBorder", "--ws-layout-border", placement.border);
setVariable(element, "wsLayoutRadius", "--ws-layout-radius", placement.radius === undefined ? undefined : placement.radius + "px");
if (editorEnabled && selectedComponentId === id) element.dataset.wsLayoutSelected = "true";
else delete element.dataset.wsLayoutSelected;
}
root.dataset.wsLayoutEditing = editorEnabled ? "true" : "false";
}
export function refreshSkinLayout(): void {
if (typeof document === "undefined") return;
for (const root of activeRoots()) applyRoot(root);
}
function scheduleRefresh(): void {
if (typeof window === "undefined" || refreshFrame) return;
refreshFrame = window.requestAnimationFrame(() => {
refreshFrame = 0;
refreshSkinLayout();
});
}
export function initializeSkinLayoutRuntime(): void {
if (typeof document === "undefined") return;
if (!document.getElementById(STYLE_ID)) {
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = layoutRuntimeCss;
document.head.append(style);
}
if (!observer) {
observer = new MutationObserver(scheduleRefresh);
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["data-ws-page", "data-ws-skin", "data-ws-part", "data-ws-control-kind"],
});
window.addEventListener("resize", scheduleRefresh, { passive: true });
}
scheduleRefresh();
}
export function setSkinLayoutPackage(skinId: string, layout: SkinLayoutDocument | null): void {
activePackageSkinId = skinId;
activePackageLayout = layout;
previewComponentId = null;
previewPlacement = null;
previewScope = "";
scheduleRefresh();
}
export function setSkinLayoutEditorState(enabled: boolean, selectedId: string | null = selectedComponentId): void {
editorEnabled = enabled;
selectedComponentId = enabled ? selectedId : null;
scheduleRefresh();
}
export function getEffectiveSkinLayoutPlacement(componentIdValue: string): SkinLayoutPlacement | undefined {
const context = getActiveSkinLayoutContext();
if (!context || !getSkinLayoutComponent(componentIdValue, context.page)?.editable) return undefined;
return effectivePlacements(context)[componentIdValue];
}
export function getActiveSkinLayoutOverride(componentIdValue: string): SkinLayoutPlacement | undefined {
const context = getActiveSkinLayoutContext();
if (!context || !getSkinLayoutComponent(componentIdValue, context.page)?.editable) return undefined;
return loadSkinLayoutOverrides(context.skinId).pages[context.page]?.[context.profile]?.[componentIdValue];
}
export function previewActiveSkinLayoutPlacement(componentIdValue: string, placement: SkinLayoutPlacement | null): void {
const context = getActiveSkinLayoutContext();
previewComponentId = context && placement ? componentIdValue : null;
previewPlacement = context ? placement : null;
previewScope = context ? context.skinId + ":" + context.page + ":" + context.profile : "";
scheduleRefresh();
}
export function saveActiveSkinLayoutPlacement(componentIdValue: string, placement: SkinLayoutPlacement | null): void {
const context = getActiveSkinLayoutContext();
if (!context) throw new Error("There is no active public skin layout.");
previewComponentId = null;
previewPlacement = null;
previewScope = "";
updateSkinLayoutOverride(context.skinId, context.page, context.profile, componentIdValue, placement);
scheduleRefresh();
}
export function getActiveSkinLayoutOverrides(): SkinLayoutDocument {
const context = getActiveSkinLayoutContext();
return context ? loadSkinLayoutOverrides(context.skinId) : { schemaVersion: 1, pages: {} };
}
export function replaceActiveSkinLayoutOverrides(layout: SkinLayoutDocument): void {
const context = getActiveSkinLayoutContext();
if (!context) throw new Error("There is no active public skin layout.");
saveSkinLayoutOverrides(context.skinId, layout);
scheduleRefresh();
}
export function clearActiveSkinLayoutOverrides(): void {
const context = getActiveSkinLayoutContext();
if (!context) return;
previewComponentId = null;
previewPlacement = null;
previewScope = "";
clearSkinLayoutOverrides(context.skinId);
scheduleRefresh();
}
@@ -0,0 +1,83 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
clearSkinLayoutOverrides,
exportSkinLayoutMigrationRecovery,
getSkinLayoutMigrationRecovery,
LEGACY_SKIN_LAYOUT_STORAGE_KEY,
loadSkinLayoutOverrides,
saveSkinLayoutOverrides,
SKIN_LAYOUT_STORAGE_KEY,
} from "./skin-layout-storage.js";
class MemoryStorage {
private readonly values = new Map<string, string>();
getItem(key: string): string | null { return this.values.get(key) ?? null; }
setItem(key: string, value: string): void { this.values.set(key, value); }
}
function withLocalStorage<T>(run: (storage: MemoryStorage) => T): T {
const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const storage = new MemoryStorage();
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
try { return run(storage); }
finally {
if (previous) Object.defineProperty(globalThis, "localStorage", previous);
else Reflect.deleteProperty(globalThis, "localStorage");
}
}
test("legacy local layouts migrate matching entries and keep incompatible entries recoverable", () => {
withLocalStorage((storage) => {
const legacy = JSON.stringify({
schemaVersion: 1,
skins: {
"community.illusia-voice": {
schemaVersion: 1,
pages: { home: { desktop: {
"home.header": { x: 32 },
"home.retired-component": { x: 80 },
"home.security-note": { visible: false },
"home.connect": { scale: 0.5 },
} } },
},
},
});
storage.setItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY, legacy);
const migrated = loadSkinLayoutOverrides("community.illusia-voice");
assert.deepEqual(migrated.pages.home?.desktop, { "home.header": { x: 32 } });
assert.deepEqual(JSON.parse(storage.getItem(SKIN_LAYOUT_STORAGE_KEY) ?? "null").schemaVersion, 2);
assert.equal(storage.getItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY), legacy, "the source config remains intact as a backup");
const recovery = getSkinLayoutMigrationRecovery("community.illusia-voice");
assert.equal(recovery?.sourceVersion, 1);
assert.equal(recovery?.items.length, 3);
assert.equal(recovery?.omittedCount, 0);
const exported = JSON.parse(exportSkinLayoutMigrationRecovery("community.illusia-voice"));
assert.equal(exported.skinId, "community.illusia-voice");
assert.equal(exported.items.length, 3);
});
});
test("version 2 layout overrides can be saved, loaded, and cleared per skin", () => {
withLocalStorage((storage) => {
saveSkinLayoutOverrides("community.illusia-voice", {
schemaVersion: 1,
pages: { home: { mobile: { "home.header": { x: 8, visible: true } } } },
});
assert.equal(loadSkinLayoutOverrides("community.illusia-voice").pages.home?.mobile?.["home.header"]?.x, 8);
clearSkinLayoutOverrides("community.illusia-voice");
assert.deepEqual(loadSkinLayoutOverrides("community.illusia-voice"), { schemaVersion: 1, pages: {} });
assert.equal(JSON.parse(storage.getItem(SKIN_LAYOUT_STORAGE_KEY) ?? "null").schemaVersion, 2);
});
});
test("an unknown newer local storage version is preserved instead of overwritten", () => {
withLocalStorage((storage) => {
const future = JSON.stringify({ schemaVersion: 99, skins: { "community.illusia-voice": { retained: true } } });
storage.setItem(SKIN_LAYOUT_STORAGE_KEY, future);
assert.throws(() => saveSkinLayoutOverrides("community.illusia-voice", { schemaVersion: 1, pages: {} }));
assert.equal(storage.getItem(SKIN_LAYOUT_STORAGE_KEY), future);
});
});
+266
View File
@@ -0,0 +1,266 @@
import {
getSkinLayoutComponent,
parseSkinLayoutJson,
validateSkinLayout,
type SkinLayoutDocument,
type SkinLayoutPage,
type SkinLayoutPlacement,
type SkinLayoutProfile,
} from "../../../src/shared/skin-layout.js";
export const SKIN_LAYOUT_STORAGE_KEY = "webspeak:skin-layouts:v2";
export const LEGACY_SKIN_LAYOUT_STORAGE_KEY = "webspeak:skin-layouts:v1";
const MAX_STORAGE_BYTES = 1024 * 1024;
const MAX_RECOVERY_BYTES = 128 * 1024;
interface SkinLayoutCollection {
schemaVersion: 2;
skins: Record<string, SkinLayoutDocument>;
recoveries: Record<string, SkinLayoutMigrationRecovery>;
}
export interface SkinLayoutMigrationRecovery {
sourceVersion: number;
items: Array<{ page: string; profile: string; componentId: string; placement: unknown }>;
omittedCount: number;
backupKey: string;
}
interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
}
function emptyDocument(): SkinLayoutDocument {
return { schemaVersion: 1, pages: {} };
}
function emptyCollection(): SkinLayoutCollection {
return { schemaVersion: 2, skins: {}, recoveries: {} };
}
function isSkinId(value: string): boolean {
return value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value);
}
function getBrowserStorage(): StorageLike | null {
try {
return typeof localStorage === "undefined" ? null : localStorage;
} catch {
return null;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function serializedBytes(value: unknown): number {
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
}
function parseCollection(source: string | null): SkinLayoutCollection {
if (!source) return emptyCollection();
if (new TextEncoder().encode(source).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit.");
let raw: unknown;
try { raw = JSON.parse(source); }
catch { throw new Error("Saved skin layouts are not valid JSON."); }
if (!isRecord(raw) || raw.schemaVersion !== 2 || !isRecord(raw.skins) || !isRecord(raw.recoveries)) {
throw new Error("Saved skin layouts use an unsupported storage version.");
}
const skins: Record<string, SkinLayoutDocument> = {};
for (const [id, layout] of Object.entries(raw.skins)) {
if (!isSkinId(id)) throw new Error("Saved skin layouts contain an invalid skin ID.");
skins[id] = validateSkinLayout(layout);
}
const recoveries: Record<string, SkinLayoutMigrationRecovery> = {};
for (const [id, recovery] of Object.entries(raw.recoveries)) {
if (!isSkinId(id) || !isRecord(recovery) || !Array.isArray(recovery.items)
|| typeof recovery.sourceVersion !== "number" || !Number.isInteger(recovery.sourceVersion)
|| typeof recovery.omittedCount !== "number" || !Number.isInteger(recovery.omittedCount)
|| recovery.items.length > 1024) throw new Error("Saved skin layout recovery data is invalid.");
recoveries[id] = {
sourceVersion: recovery.sourceVersion,
items: recovery.items.filter(isRecord).map((item) => ({
page: typeof item.page === "string" ? item.page.slice(0, 80) : "",
profile: typeof item.profile === "string" ? item.profile.slice(0, 20) : "",
componentId: typeof item.componentId === "string" ? item.componentId.slice(0, 120) : "",
placement: item.placement,
})),
omittedCount: Math.max(0, recovery.omittedCount),
backupKey: LEGACY_SKIN_LAYOUT_STORAGE_KEY,
};
}
return { schemaVersion: 2, skins, recoveries };
}
function recoverLegacyLayout(layout: unknown): { layout: SkinLayoutDocument; items: SkinLayoutMigrationRecovery["items"] } {
const items: SkinLayoutMigrationRecovery["items"] = [];
const pages: SkinLayoutDocument["pages"] = {};
const remember = (page: string, profile: string, componentId: string, placement: unknown) => {
if (items.length < 1024) items.push({ page: page.slice(0, 80), profile: profile.slice(0, 20), componentId: componentId.slice(0, 120), placement });
};
if (!isRecord(layout) || layout.schemaVersion !== 1 || !isRecord(layout.pages)) {
remember("", "", "__document__", layout);
return { layout: emptyDocument(), items };
}
for (const [pageKey, rawPage] of Object.entries(layout.pages)) {
if (!(pageKey === "home" || pageKey === "voice" || pageKey === "demo") || !isRecord(rawPage)) {
remember(pageKey, "", "__page__", rawPage);
continue;
}
const profiles: NonNullable<SkinLayoutDocument["pages"][SkinLayoutPage]> = {};
for (const [profileKey, rawProfile] of Object.entries(rawPage)) {
if (!(profileKey === "desktop" || profileKey === "tablet" || profileKey === "mobile") || !isRecord(rawProfile)) {
remember(pageKey, profileKey, "__profile__", rawProfile);
continue;
}
const placements: Record<string, SkinLayoutPlacement> = {};
for (const [id, placement] of Object.entries(rawProfile)) {
const component = getSkinLayoutComponent(id, pageKey);
try {
if (!component?.editable) throw new Error("Component no longer exists or is not editable.");
const verified = validateSkinLayout({ schemaVersion: 1, pages: { [pageKey]: { [profileKey]: { [id]: placement } } } });
const normalized = verified.pages[pageKey]?.[profileKey]?.[id];
if (!normalized) throw new Error("Placement could not be migrated.");
placements[id] = normalized;
} catch {
remember(pageKey, profileKey, id, placement);
}
}
if (Object.keys(placements).length) profiles[profileKey] = placements;
}
if (Object.keys(profiles).length) pages[pageKey] = profiles;
}
return { layout: validateSkinLayout({ schemaVersion: 1, pages }), items };
}
function migrateLegacyCollection(source: string): SkinLayoutCollection {
if (new TextEncoder().encode(source).byteLength > MAX_STORAGE_BYTES) throw new Error("Legacy skin layouts exceed the local storage limit.");
let raw: unknown;
try { raw = JSON.parse(source); }
catch { throw new Error("Legacy skin layouts are not valid JSON."); }
if (!isRecord(raw) || raw.schemaVersion !== 1 || !isRecord(raw.skins)) {
throw new Error("Legacy skin layouts use an unsupported storage version.");
}
const collection = emptyCollection();
for (const [id, storedLayout] of Object.entries(raw.skins)) {
if (!isSkinId(id)) continue;
const recovered = recoverLegacyLayout(storedLayout);
collection.skins[id] = recovered.layout;
if (recovered.items.length) {
const recovery: SkinLayoutMigrationRecovery = {
sourceVersion: 1,
items: [],
omittedCount: recovered.items.length,
backupKey: LEGACY_SKIN_LAYOUT_STORAGE_KEY,
};
for (const item of recovered.items) {
recovery.items.push(item);
recovery.omittedCount -= 1;
if (serializedBytes(recovery) > MAX_RECOVERY_BYTES) {
recovery.items.pop();
recovery.omittedCount += 1;
break;
}
}
collection.recoveries[id] = recovery;
}
}
return collection;
}
function readCollection(storage: StorageLike): SkinLayoutCollection {
const current = storage.getItem(SKIN_LAYOUT_STORAGE_KEY);
if (current !== null) return parseCollection(current);
const legacy = storage.getItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY);
if (legacy === null) return emptyCollection();
const migrated = migrateLegacyCollection(legacy);
try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, JSON.stringify(migrated)); }
catch { /* Keep the legacy key untouched and allow this page to use the migrated copy in memory. */ }
return migrated;
}
export function loadSkinLayoutOverrides(skinId: string): SkinLayoutDocument {
if (!isSkinId(skinId)) return emptyDocument();
const storage = getBrowserStorage();
if (!storage) return emptyDocument();
try { return readCollection(storage).skins[skinId] ?? emptyDocument(); }
catch { return emptyDocument(); }
}
export function getSkinLayoutMigrationRecovery(skinId: string): SkinLayoutMigrationRecovery | null {
if (!isSkinId(skinId)) return null;
const storage = getBrowserStorage();
if (!storage) return null;
try { return readCollection(storage).recoveries[skinId] ?? null; }
catch { return null; }
}
export function exportSkinLayoutMigrationRecovery(skinId: string): string {
const recovery = getSkinLayoutMigrationRecovery(skinId);
if (!recovery) throw new Error("There is no recovered legacy layout data.");
return JSON.stringify({ schemaVersion: 1, skinId, ...recovery }, null, 2);
}
export function saveSkinLayoutOverrides(skinId: string, layout: SkinLayoutDocument): void {
if (!isSkinId(skinId)) throw new Error("Skin ID is invalid.");
const validated = validateSkinLayout(layout);
const storage = getBrowserStorage();
if (!storage) throw new Error("Local browser storage is unavailable.");
let collection: SkinLayoutCollection;
try { collection = readCollection(storage); }
catch { throw new Error("Local browser storage could not be read."); }
collection.skins[skinId] = validated;
const serialized = JSON.stringify(collection);
if (new TextEncoder().encode(serialized).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit.");
try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, serialized); }
catch { throw new Error("Local browser storage could not be written."); }
}
export function updateSkinLayoutOverride(
skinId: string,
page: SkinLayoutPage,
profile: SkinLayoutProfile,
componentId: string,
placement: SkinLayoutPlacement | null,
): SkinLayoutDocument {
const component = getSkinLayoutComponent(componentId, page);
if (!component?.editable) throw new Error("This skin component cannot be customized.");
const layout = loadSkinLayoutOverrides(skinId);
const pages = { ...layout.pages };
const pageLayout = { ...(pages[page] ?? {}) };
const profileLayout = { ...(pageLayout[profile] ?? {}) };
if (placement === null || Object.keys(placement).length === 0) delete profileLayout[componentId];
else profileLayout[componentId] = placement;
if (Object.keys(profileLayout).length) pageLayout[profile] = profileLayout;
else delete pageLayout[profile];
if (Object.keys(pageLayout).length) pages[page] = pageLayout;
else delete pages[page];
const validated = validateSkinLayout({ schemaVersion: 1, pages });
saveSkinLayoutOverrides(skinId, validated);
return validated;
}
export function clearSkinLayoutOverrides(skinId: string): void {
if (!isSkinId(skinId)) return;
const storage = getBrowserStorage();
if (!storage) throw new Error("Local browser storage is unavailable.");
let collection: SkinLayoutCollection;
try { collection = readCollection(storage); }
catch { throw new Error("Local browser storage could not be read."); }
delete collection.skins[skinId];
delete collection.recoveries[skinId];
const serialized = JSON.stringify(collection);
if (new TextEncoder().encode(serialized).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit.");
try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, serialized); }
catch { throw new Error("Local browser storage could not be written."); }
}
export function exportSkinLayout(layout: SkinLayoutDocument): string {
return JSON.stringify(validateSkinLayout(layout), null, 2);
}
export function importSkinLayout(source: string): SkinLayoutDocument {
return parseSkinLayoutJson(source);
}
+59 -4
View File
@@ -127,12 +127,18 @@ test("skin content supports localized interface message overrides and includes t
assert.ok(skin.assets["assets/preview.png"]);
});
test("the ILLUSIA visual-only example imports without replacing WebSpeak's base translations", async () => {
const bytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
const skin = await importSkinPack(new File([bytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
test("the ILLUSIA v2 example and bundled package import without replacing WebSpeak's base translations", async () => {
const exampleBytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
const bundledBytes = await readFile(new URL("../../public/skins/illusia-voice.wskin", import.meta.url));
assert.deepEqual(bundledBytes, exampleBytes);
const skin = await importSkinPack(new File([exampleBytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
assert.equal(skin.id, "community.illusia-voice");
assert.equal(skin.name, "ILLUSIA风");
assert.equal(skin.version, "1.0.28");
assert.equal(skin.version, "1.0.29");
assert.equal(skin.schemaVersion, 2);
assert.equal(skin.packageType, "layout-skin");
assert.deepEqual(skin.permissions, []);
assert.deepEqual(skin.layoutData, { schemaVersion: 1, pages: {} });
assert.equal(skin.minAppVersion, "0.2.7-preview");
assert.equal(skin.contentData, undefined);
assert.equal(skin.previewBlob?.type, "image/webp");
@@ -250,3 +256,52 @@ function makeSkin(css: string, content?: unknown): File {
const bytes = zipSync(packageFiles);
return new File([bytes.slice().buffer as ArrayBuffer], "skin.wskin", { type: "application/octet-stream" });
}
test("schema version 2 skin packages load only validated declarative layouts with no permissions", async () => {
const layout = {
schemaVersion: 1,
pages: {
home: { desktop: { "home.header": { x: 48, y: -12, scale: 1.1, background: "#123456" } } },
},
};
const skin = await importSkinPack(makeSkinV2(layout));
assert.equal(skin.schemaVersion, 2);
assert.equal(skin.packageType, "layout-skin");
assert.deepEqual(skin.permissions, []);
assert.equal(skin.layoutData?.pages.home?.desktop?.["home.header"]?.x, 48);
assert.equal(skin.layoutData?.pages.home?.desktop?.["home.header"]?.background, "#123456");
await assert.rejects(
importSkinPack(makeSkinV2(layout, { permissions: ["network.fetch"] })),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PERMISSION_INVALID",
);
await assert.rejects(
importSkinPack(makeSkinV2(layout, { capabilities: ["network.fetch"] })),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_MANIFEST_INVALID",
);
await assert.rejects(
importSkinPack(makeSkinV2({ schemaVersion: 1, pages: { home: { desktop: { "home.unknown": { x: 4 } } } } })),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_LAYOUT_INVALID",
);
await assert.rejects(
importSkinPack(makeSkinV2({ schemaVersion: 1, pages: { home: { desktop: { "home.security-note": { visible: false } } } } })),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_LAYOUT_INVALID",
);
});
function makeSkinV2(layout: unknown, manifestChanges: Record<string, unknown> = {}): File {
const packageFiles: Record<string, Uint8Array> = {
"manifest.json": strToU8(JSON.stringify({
...manifest,
schemaVersion: 2,
packageType: "layout-skin",
layout: "layout.json",
permissions: [],
...manifestChanges,
})),
"skin.css": strToU8('[data-ws-part="home.header"] { color: #123456; }'),
"layout.json": strToU8(JSON.stringify(layout)),
};
const bytes = zipSync(packageFiles);
return new File([bytes.slice().buffer as ArrayBuffer], "skin-v2.wskin", { type: "application/octet-stream" });
}
+36 -8
View File
@@ -2,6 +2,7 @@ import postcss, { type AtRule, type Declaration, type Node, type Rule } from "po
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import { unzipSync } from "fflate";
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
@@ -51,7 +52,8 @@ const ZIP_EOCD = 0x06054b50;
const ZIP_CENTRAL_FILE = 0x02014b50;
export interface SkinManifest {
schemaVersion: 1;
schemaVersion: 1 | 2;
packageType?: "layout-skin";
id: string;
name: string;
version: string;
@@ -59,6 +61,8 @@ export interface SkinManifest {
license: string;
description?: string;
entry: string;
layout?: string;
permissions?: [];
content?: string;
minAppVersion: string;
preview?: string;
@@ -89,6 +93,7 @@ export interface InstalledSkin extends SkinManifest {
css: string;
assets: Record<string, Blob>;
contentData?: SkinContent;
layoutData?: SkinLayoutDocument;
previewBlob?: Blob;
warnings: string[];
installedAt: number;
@@ -148,7 +153,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
for (const [path, bytes] of files) {
if (["manifest.json", manifest.entry, manifest.content].includes(path)) continue;
if (["manifest.json", manifest.entry, manifest.layout, manifest.content].includes(path)) continue;
const mimeType = assetMimeType(path);
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
@@ -163,6 +168,14 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
contentData = parseContent(contentBytes);
}
let layoutData: SkinLayoutDocument | undefined;
if (manifest.layout) {
const layoutBytes = files.get(manifest.layout);
if (!layoutBytes) throw new SkinPackError("layout.json is missing from the package.", "SKIN_LAYOUT_MISSING");
try { layoutData = parseSkinLayoutJson(decoder.decode(layoutBytes)); }
catch (error) { throw new SkinPackError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); }
}
let previewBlob: Blob | undefined;
if (manifest.preview) {
const previewBytes = files.get(manifest.preview);
@@ -174,7 +187,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
}
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets);
return { ...manifest, css: compiled.css, assets, contentData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
return { ...manifest, css: compiled.css, assets, contentData, layoutData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
}
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
@@ -319,30 +332,44 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
catch { throw new SkinPackError("manifest.json must contain valid UTF-8 JSON.", "SKIN_MANIFEST_INVALID"); }
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
const raw = value as Record<string, unknown>;
const schemaVersion = raw.schemaVersion;
if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion === 2) {
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
const unknown = Object.keys(raw).find((key) => !fields.has(key));
if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
}
const stringField = (key: string, max: number, required = true): string | undefined => {
const field = raw[key];
if (field == null && !required) return undefined;
if (typeof field !== "string" || !field.trim() || field.length > max) throw new SkinPackError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
return field.trim();
};
if (raw.schemaVersion !== 1) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion === 2 && (raw.packageType !== "layout-skin" || !Array.isArray(raw.permissions) || raw.permissions.length !== 0)) {
throw new SkinPackError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID");
}
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined)) {
throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
}
const id = stringField("id", 80)!;
if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID");
const entry = stringField("entry", 120)!;
const layout = schemaVersion === 2 ? stringField("layout", 120)! : undefined;
const content = stringField("content", 120, false);
const preview = stringField("preview", 120, false);
for (const path of [entry, content, preview].filter((item): item is string => Boolean(item))) {
for (const path of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) {
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
}
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
const version = stringField("version", 32)!;
const minAppVersion = stringField("minAppVersion", 32)!;
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
const declaredFiles = ["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
return {
schemaVersion: 1,
schemaVersion,
...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : {}),
id,
name: stringField("name", 80)!,
version,
@@ -350,6 +377,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
license: stringField("license", 80)!,
description: stringField("description", 400, false),
entry,
layout,
content,
minAppVersion,
preview,
+5
View File
@@ -4,6 +4,7 @@ import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./th
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";
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
export const BUILTIN_LIGHT_SKIN = "builtin.light";
@@ -52,6 +53,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
operation.check();
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
removeCustomSkinStyle();
setSkinLayoutPackage(id, null);
applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light");
markCoreControls();
storeSkinId(id);
@@ -120,6 +122,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
activeAssetUrls = compiled.objectUrls;
candidateUrls = [];
previousAssetUrls.forEach((url) => URL.revokeObjectURL(url));
setSkinLayoutPackage(skin.id, skin.layoutData ?? null);
storeSkinId(id);
return skin;
} catch {
@@ -132,6 +135,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
function fallBackToBuiltin(): null {
const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
removeCustomSkinStyle();
setSkinLayoutPackage(fallback, null);
applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light");
storeSkinId(fallback);
return null;
@@ -141,6 +145,7 @@ export function clearCustomSkinStyle(): void {
pendingActivation?.cancel();
pendingActivation = null;
removeCustomSkinStyle();
setSkinLayoutPackage(getStoredSkinId() ?? BUILTIN_LIGHT_SKIN, null);
}
function removeCustomSkinStyle(): void {
@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import {
createSkinExtensionWasmCappedRunProbe,
createSkinExtensionWasmInfiniteRunProbe,
createSkinExtensionWasmPrefixByteImmediateProbe,
} from "../../test/skin-extension-wasm-fixture.js";
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;
last_error_code: () => number;
last_guest_memory_bytes: () => number;
}
test("the fixed Wasmi artifact caps its own memory and stops guest execution at fuel", async () => {
const artifact = await readFile(new URL("../../public/skin-wasm-interpreter.wasm", import.meta.url));
const { instance } = await WebAssembly.instantiate(artifact);
const runtime = instance.exports as unknown as WasmiInterpreterExports;
function run(module: Uint8Array): { result: number; error: number; guestMemoryBytes: number } {
const pointer = runtime.alloc(module.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);
return {
result: Number(result),
error: runtime.last_error_code(),
guestMemoryBytes: runtime.last_guest_memory_bytes(),
};
}
assert.deepEqual(run(createSkinExtensionWasmPrefixByteImmediateProbe()), {
result: 123,
error: 0,
guestMemoryBytes: 64 * 1024,
});
assert.equal(run(createSkinExtensionWasmInfiniteRunProbe()).error, 5, "the fuel budget must trap a non-returning module");
assert.deepEqual(run(createSkinExtensionWasmCappedRunProbe()), {
result: -1,
error: 0,
guestMemoryBytes: 4 * 1024 * 1024,
});
const memory = runtime.memory;
const currentPages = memory.buffer.byteLength / (64 * 1024);
memory.grow(1024 - currentPages);
assert.equal(memory.buffer.byteLength, 64 * 1024 * 1024, "the interpreter container should reach its 64 MiB cap");
assert.throws(() => memory.grow(1), RangeError, "the interpreter container must not grow beyond its cap");
});
+2 -2
View File
@@ -65,9 +65,9 @@ export function applyTheme(theme: ThemeMode, options: { preserveCustomSkins?: bo
style.textContent = activeSkin.css;
}
export function saveTheme(theme: ThemeMode): void {
export function saveTheme(theme: ThemeMode, options: { preserveCustomSkins?: boolean } = {}): void {
if (typeof localStorage !== "undefined") localStorage.setItem(THEME_KEY, theme);
applyTheme(theme);
applyTheme(theme, options);
}
export function isDarkTheme(theme: ThemeMode): boolean {