feat(skin): prototype bounded UI callback inputs

This commit is contained in:
illusia committed 2026-10-10 15:53:49 +08:00
1 parent c3810a177a
commit 54c77bcb27
17 files changed
+567 -62

No files matched your search

Binary file not shown.
+101 -25
View File
@@ -5,6 +5,7 @@ use wasmi::{
const SOURCE_LIMIT: usize = 256 * 1024;
const STATUS_LIMIT: usize = 512;
const UI_INPUT_LIMIT: usize = 8 * 1024;
const UI_OUTPUT_LIMIT: usize = 16 * 1024;
const MEMORY_LIMIT_BYTES: usize = 64 * 64 * 1024;
const STATUS_READ_LIMIT: u32 = 10;
@@ -22,9 +23,11 @@ const ERROR_INSTANTIATION: u32 = 9;
const ERROR_IMPORT: u32 = 10;
const ERROR_PERMISSION: u32 = 11;
const ERROR_UI_OUTPUT: u32 = 12;
const ERROR_UI_INPUT: u32 = 13;
static mut LAST_ERROR_CODE: u32 = ERROR_NONE;
static mut LAST_STATUS_READ_COUNT: u32 = 0;
static mut LAST_UI_INPUT_READ_COUNT: u32 = 0;
static mut LAST_GUEST_MEMORY_BYTES: u32 = 0;
static mut LAST_UI_OUTPUT: [u8; UI_OUTPUT_LIMIT] = [0; UI_OUTPUT_LIMIT];
static mut LAST_UI_OUTPUT_LENGTH: u32 = 0;
@@ -35,6 +38,9 @@ struct HostState {
limits: StoreLimits,
status: Vec<u8>,
status_read_count: u32,
ui_input: Vec<u8>,
ui_input_read_count: u32,
ui_input_invalid: bool,
ui_output: Vec<u8>,
ui_output_emitted: bool,
ui_output_invalid: bool,
@@ -42,7 +48,7 @@ struct HostState {
#[unsafe(no_mangle)]
pub extern "C" fn alloc(size: u32) -> u32 {
if size == 0 || size as usize > SOURCE_LIMIT + STATUS_LIMIT {
if size == 0 || size as usize > SOURCE_LIMIT + STATUS_LIMIT + UI_INPUT_LIMIT {
return 0;
}
let allocation = Vec::<u8>::with_capacity(size as usize);
@@ -62,24 +68,33 @@ pub unsafe extern "C" fn run(
module_length: u32,
status_pointer: u32,
status_length: u32,
ui_input_pointer: u32,
ui_input_length: u32,
status_permission_granted: u32,
memory_maximum_pages: u32,
fuel: u64,
) -> i64 {
clear_diagnostic();
clear_ui_output();
set_report(ERROR_NONE, 0, 0);
set_report(ERROR_NONE, 0, 0, 0);
let interpreter_memory_bytes = core::arch::wasm32::memory_size(0) as usize * 64 * 1024;
if module_pointer == 0
|| module_length == 0
|| module_length as usize > SOURCE_LIMIT
|| status_length as usize > STATUS_LIMIT
|| (status_length != 0 && status_pointer == 0)
|| (status_length != 0 && status_permission_granted != 1)
|| ui_input_length == 0
|| ui_input_length as usize > UI_INPUT_LIMIT
|| ui_input_pointer == 0
|| !valid_range(module_pointer, module_length, interpreter_memory_bytes)
|| (status_length > 0 && !valid_range(status_pointer, status_length, interpreter_memory_bytes))
|| !valid_range(ui_input_pointer, ui_input_length, interpreter_memory_bytes)
|| !(1..=64).contains(&memory_maximum_pages)
|| fuel == 0
|| fuel > FUEL_LIMIT
{
set_report(ERROR_INPUT, 0, 0);
set_report(ERROR_INPUT, 0, 0, 0);
return 0;
}
@@ -89,15 +104,16 @@ pub unsafe extern "C" fn run(
} else {
core::slice::from_raw_parts(status_pointer as usize as *const u8, status_length as usize).to_vec()
};
let ui_input = core::slice::from_raw_parts(ui_input_pointer as usize as *const u8, ui_input_length as usize).to_vec();
match execute(module_bytes, status, status_permission_granted == 1, memory_maximum_pages, fuel) {
Ok((result, status_reads, guest_memory_bytes, ui_output)) => {
match execute(module_bytes, status, ui_input, status_permission_granted == 1, memory_maximum_pages, fuel) {
Ok((result, status_reads, ui_input_reads, guest_memory_bytes, ui_output)) => {
set_ui_output(&ui_output);
set_report(ERROR_NONE, status_reads, guest_memory_bytes);
set_report(ERROR_NONE, status_reads, ui_input_reads, guest_memory_bytes);
result as i64
}
Err((error, status_reads, guest_memory_bytes)) => {
set_report(error, status_reads, guest_memory_bytes);
Err((error, status_reads, ui_input_reads, guest_memory_bytes)) => {
set_report(error, status_reads, ui_input_reads, guest_memory_bytes);
0
}
}
@@ -113,6 +129,11 @@ pub extern "C" fn last_status_read_count() -> u32 {
unsafe { LAST_STATUS_READ_COUNT }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_ui_input_read_count() -> u32 {
unsafe { LAST_UI_INPUT_READ_COUNT }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_guest_memory_bytes() -> u32 {
unsafe { LAST_GUEST_MEMORY_BYTES }
@@ -152,11 +173,12 @@ fn set_diagnostic(message: &str) {
}
}
fn set_report(error: u32, status_reads: u32, guest_memory_bytes: u32) {
fn set_report(error: u32, status_reads: u32, ui_input_reads: u32, guest_memory_bytes: u32) {
// Each interpreter instance runs in a dedicated Worker and accepts one job.
unsafe {
LAST_ERROR_CODE = error;
LAST_STATUS_READ_COUNT = status_reads;
LAST_UI_INPUT_READ_COUNT = ui_input_reads;
LAST_GUEST_MEMORY_BYTES = guest_memory_bytes;
}
}
@@ -174,13 +196,20 @@ fn set_ui_output(output: &[u8]) {
}
}
fn valid_range(pointer: u32, length: u32, memory_bytes: usize) -> bool {
let start = pointer as usize;
let length = length as usize;
pointer != 0 && start <= memory_bytes && length <= memory_bytes.saturating_sub(start)
}
fn execute(
module_bytes: &[u8],
status: Vec<u8>,
ui_input: Vec<u8>,
status_permission_granted: bool,
memory_maximum_pages: u32,
fuel: u64,
) -> Result<(i32, u32, u32, Vec<u8>), (u32, u32, u32)> {
) -> Result<(i32, u32, u32, u32, Vec<u8>), (u32, u32, u32, u32)> {
let mut config = Config::default();
config
.consume_fuel(true)
@@ -194,10 +223,11 @@ fn execute(
.enforced_limits(EnforcedLimits::strict());
let engine = Engine::new(&config);
let module = Module::new(&engine, &mut &module_bytes[..])
.map_err(|_| (ERROR_MODULE, 0, 0))?;
.map_err(|_| (ERROR_MODULE, 0, 0, 0))?;
let mut saw_memory = false;
let mut saw_status = false;
let mut saw_ui_output = false;
let mut saw_ui_input = false;
for import in module.imports() {
match (import.module(), import.name(), import.ty()) {
("env", "memory", wasmi::ExternType::Memory(memory_type))
@@ -214,26 +244,29 @@ fn execute(
saw_status = true;
}
("env", "session_status_read", wasmi::ExternType::Func(_)) => {
return Err((ERROR_PERMISSION, 0, 0));
return Err((ERROR_PERMISSION, 0, 0, 0));
}
("env", "ui_emit_json", wasmi::ExternType::Func(_)) if !saw_ui_output => {
saw_ui_output = true;
}
_ => return Err((ERROR_IMPORT, 0, 0)),
("env", "ui_input_read", wasmi::ExternType::Func(_)) if !saw_ui_input => {
saw_ui_input = true;
}
_ => return Err((ERROR_IMPORT, 0, 0, 0)),
}
}
if !saw_memory {
return Err((ERROR_IMPORT, 0, 0));
return Err((ERROR_IMPORT, 0, 0, 0));
}
let mut exports = module.exports();
let Some(entry) = exports.next() else {
return Err((ERROR_EXPORT, 0, 0));
return Err((ERROR_EXPORT, 0, 0, 0));
};
if entry.name() != "run"
|| !matches!(entry.ty(), wasmi::ExternType::Func(_))
|| exports.next().is_some()
{
return Err((ERROR_EXPORT, 0, 0));
return Err((ERROR_EXPORT, 0, 0, 0));
}
let limits = StoreLimitsBuilder::new()
@@ -250,20 +283,23 @@ fn execute(
limits,
status,
status_read_count: 0,
ui_input,
ui_input_read_count: 0,
ui_input_invalid: false,
ui_output: Vec::new(),
ui_output_emitted: false,
ui_output_invalid: false,
});
store.limiter(|state| &mut state.limits);
store.set_fuel(fuel).map_err(|_| (ERROR_EXECUTION, 0, 0))?;
store.set_fuel(fuel).map_err(|_| (ERROR_EXECUTION, 0, 0, 0))?;
let memory_type = MemoryType::new(1, Some(memory_maximum_pages));
let memory = Memory::new(&mut store, memory_type)
.map_err(|_| (ERROR_HOST_MEMORY, 0, 0))?;
.map_err(|_| (ERROR_HOST_MEMORY, 0, 0, 0))?;
let mut linker = Linker::<HostState>::new(&engine);
linker
.define("env", "memory", memory)
.map_err(|_| (ERROR_MEMORY_LINK, 0, 0))?;
.map_err(|_| (ERROR_MEMORY_LINK, 0, 0, 0))?;
if status_permission_granted {
let status_memory = memory;
@@ -296,7 +332,7 @@ fn execute(
status_size as i32
},
)
.map_err(|_| (ERROR_STATUS_LINK, 0, 0))?;
.map_err(|_| (ERROR_STATUS_LINK, 0, 0, 0))?;
}
let output_memory = memory;
@@ -327,29 +363,69 @@ fn execute(
length as i32
},
)
.map_err(|_| (ERROR_IMPORT, 0, 0))?;
.map_err(|_| (ERROR_IMPORT, 0, 0, 0))?;
let input_memory = memory;
linker
.func_wrap(
"env",
"ui_input_read",
move |mut caller: Caller<'_, HostState>, pointer: i32, capacity: i32| -> i32 {
if pointer < 0 || capacity < 0 {
caller.data_mut().ui_input_invalid = true;
return -1;
}
let offset = pointer as usize;
let capacity = capacity as usize;
let (input_size, reads, memory_size) = {
let state = caller.data();
(state.ui_input.len(), state.ui_input_read_count, input_memory.data(&caller).len())
};
if input_size == 0
|| input_size > UI_INPUT_LIMIT
|| reads >= 1
|| capacity < input_size
|| offset > memory_size.saturating_sub(capacity)
{
caller.data_mut().ui_input_invalid = true;
return -1;
}
let input = caller.data().ui_input.clone();
if input_memory.write(&mut caller, offset, &input).is_err() {
caller.data_mut().ui_input_invalid = true;
return -1;
}
caller.data_mut().ui_input_read_count += 1;
input_size as i32
},
)
.map_err(|_| (ERROR_IMPORT, 0, 0, 0))?;
let instance = match linker.instantiate_and_start(&mut store, &module) {
Ok(instance) => instance,
Err(error) => {
set_diagnostic(&error.to_string());
return Err((ERROR_INSTANTIATION, store.data().status_read_count, memory.data(&store).len() as u32));
return Err((ERROR_INSTANTIATION, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32));
}
};
let function = instance
.get_typed_func::<(), i32>(&store, "run")
.map_err(|_| (ERROR_EXPORT, store.data().status_read_count, memory.data(&store).len() as u32))?;
.map_err(|_| (ERROR_EXPORT, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32))?;
let result = function
.call(&mut store, ())
.map_err(|_| (ERROR_EXECUTION, store.data().status_read_count, memory.data(&store).len() as u32))?;
.map_err(|_| (ERROR_EXECUTION, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32))?;
if store.data().ui_output_invalid {
return Err((ERROR_UI_OUTPUT, store.data().status_read_count, memory.data(&store).len() as u32));
return Err((ERROR_UI_OUTPUT, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32));
}
if store.data().ui_input_invalid {
return Err((ERROR_UI_INPUT, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32));
}
Ok((
result,
store.data().status_read_count,
store.data().ui_input_read_count,
memory.data(&store).len() as u32,
store.data().ui_output.clone(),
))
+27 -2
View File
@@ -11,6 +11,7 @@ import {
type SkinPluginNode,
} from "../../../src/shared/skin-plugin.js";
import { parseSkinExtensionUiOutput } from "../../../src/shared/skin-extension-ui.js";
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js";
type Scalar = string | number | boolean;
@@ -40,6 +41,7 @@ export default defineComponent({
emits: {
"surface-change": (_active: boolean) => typeof _active === "boolean",
"restore-skin": () => true,
"extension-event": (_payload: unknown) => true,
},
setup(props, { emit }) {
const denied = ref(false);
@@ -146,6 +148,28 @@ export default defineComponent({
if (handler) void Promise.resolve(handler(args, component)).catch(() => undefined);
}
function dispatchRuntimeCallback(component: SkinPluginComponent, handlerId: string, eventName: string, event: Event, state: Record<string, Scalar>): void {
if (!component.runtimeCallbacks) return;
const callbackEvent: Record<string, unknown> = { componentId: component.id, handlerId, eventName };
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) callbackEvent.key = event.key;
if ((eventName === "input" || eventName === "change") && event.target instanceof HTMLInputElement) {
if (["password", "file", "hidden"].includes(event.target.type)) return;
if (event.target.type === "checkbox") callbackEvent.checked = event.target.checked;
else if (event.target.value.length <= 2_048) callbackEvent.value = event.target.value;
} else if ((eventName === "input" || eventName === "change") && event.target instanceof HTMLTextAreaElement) {
if (event.target.value.length <= 2_048) callbackEvent.value = event.target.value;
} else if ((eventName === "input" || eventName === "change") && event.target instanceof HTMLSelectElement
&& event.target.value.length <= 2_048) {
callbackEvent.value = event.target.value;
}
try {
const input = parseSkinExtensionUiInput({ schemaVersion: 1, state: { ...state }, event: callbackEvent });
emit("extension-event", { skinId: props.skinId, componentId: component.id, input });
} catch {
// Overlarge or malformed local state stays local and is not passed to the extension guest.
}
}
function assetUrl(path: string): string | undefined {
const current = props.assets[path];
if (!(current instanceof Blob)) return undefined;
@@ -217,7 +241,7 @@ export default defineComponent({
if (!propName) continue;
attrs[propName] = (event: Event) => {
if (!event.isTrusted) return;
if ((eventName === "keydown" || eventName === "keyup") && event instanceof KeyboardEvent
if (!component.runtimeCallbacks && (eventName === "keydown" || eventName === "keyup") && event instanceof KeyboardEvent
&& event.key !== "Enter" && event.key !== " " && event.key !== "Escape") return;
if (eventName === "contextmenu" || eventName === "dragover") event.preventDefault();
if (node.bindValue && eventName === "input" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)) {
@@ -226,7 +250,8 @@ export default defineComponent({
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
}
if (eventName === "submit") event.preventDefault();
dispatch(component, actionId, context, state);
if (component.runtimeCallbacks) dispatchRuntimeCallback(component, actionId, eventName, event, state);
else dispatch(component, actionId, context, state);
};
}
if (node.bindValue && !node.events?.input && !node.events?.change) {
+121 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createSSRApp } from "vue";
import { createRenderer, createSSRApp, nextTick } from "vue";
import { renderToString } from "@vue/server-renderer";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
@@ -79,6 +79,126 @@ test("generated UI supports broad safe markup, ARIA/data attributes, and inert c
assert.equal(document.components[0].root.children?.[1].tag, "button");
});
test("generated UI schema 5 carries bounded state and named callbacks for a trusted host event loop", () => {
const source = JSON.stringify({
schemaVersion: 5,
components: [{
id: "server-rail",
name: "Server rail",
page: "voice",
accessibleName: "Saved voice servers",
state: { expanded: false, selected: "home" },
root: {
tag: "nav",
children: [{
tag: "button",
attributes: { type: "button", "aria-pressed": false },
events: { click: "select-server" },
children: [{ text: "Home" }],
}],
},
}],
});
const document = parseSkinExtensionUiOutput(source);
const component = document.components[0];
assert.equal(component.runtimeCallbacks, true);
assert.deepEqual({ ...component.state }, { expanded: false, selected: "home" });
assert.equal(component.root.children?.[0].events?.click, "select-server");
});
test("generated UI callbacks reject unsupported events, malformed IDs, and password inputs", () => {
const schema5 = (root: Record<string, unknown>) => JSON.stringify({
schemaVersion: 5,
components: [{ id: "runtime-ui", name: "Runtime UI", page: "voice", accessibleName: "Runtime UI", root }],
});
expectOutputError(schema5({ tag: "button", events: { animationstart: "run" } }), "SKIN_EXTENSION_UI_OUTPUT_SCHEMA");
expectOutputError(schema5({ tag: "button", events: { click: "../run" } }), "SKIN_EXTENSION_UI_OUTPUT_SCHEMA");
expectOutputError(schema5({ tag: "input", attributes: { type: "password" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
expectOutputError(generatedOutput("runtime-ui", { tag: "button", events: { click: "run" } }), "SKIN_EXTENSION_UI_OUTPUT_SCHEMA");
});
test("SkinPluginOutlet emits callback data only for a trusted user event", async () => {
interface HostNode {
type: string;
props: Record<string, unknown>;
text: string;
children: HostNode[];
parent?: HostNode;
}
const createHostNode = (type: string, text = ""): HostNode => ({ type, props: {}, text, children: [] });
const renderer = createRenderer<HostNode, HostNode>({
patchProp(node, key, _previous, next) { node.props[key] = next; },
insert(node, parent, anchor) {
node.parent = parent;
const oldIndex = parent.children.indexOf(node);
if (oldIndex >= 0) parent.children.splice(oldIndex, 1);
const anchorIndex = anchor ? parent.children.indexOf(anchor) : -1;
parent.children.splice(anchorIndex >= 0 ? anchorIndex : parent.children.length, 0, node);
},
remove(node) {
const parent = node.parent;
if (!parent) return;
const index = parent.children.indexOf(node);
if (index >= 0) parent.children.splice(index, 1);
node.parent = undefined;
},
createElement: (type) => createHostNode(type),
createText: (text) => createHostNode("#text", text),
createComment: (text) => createHostNode("#comment", text),
setText(node, text) { node.text = text; },
setElementText(node, text) { node.children = []; node.text = text; },
parentNode: (node) => node.parent ?? null,
nextSibling(node) {
if (!node.parent) return null;
const index = node.parent.children.indexOf(node);
return node.parent.children[index + 1] ?? null;
},
});
const document: SkinPluginDocument = {
schemaVersion: 3,
components: [{
id: "base", name: "Base", page: "voice", accessibleName: "Base", permissions: [], actions: {}, root: { tag: "p", children: [{ text: "Base" }] },
}],
};
const emitted: unknown[] = [];
const host = createHostNode("root");
const app = renderer.createApp(SkinPluginOutlet, {
skinId: "community.test",
skinVersion: "1.0.0",
document,
extensionOutput: JSON.stringify({
schemaVersion: 5,
components: [{
id: "server-rail", name: "Server rail", page: "voice", accessibleName: "Saved voice servers",
state: { expanded: false },
root: { tag: "button", attributes: { type: "button" }, events: { click: "select-server" }, children: [{ text: "Home" }] },
}],
}),
page: "voice",
data: {},
assets: {},
actions: {},
"onExtension-event": (payload: unknown) => emitted.push(payload),
});
app.mount(host);
await nextTick();
const findButton = (node: HostNode): HostNode | undefined => node.type === "button" ? node : node.children.map(findButton).find(Boolean);
const button = findButton(host);
const describe = (node: HostNode): string => `${node.type}[${node.text}](${node.children.map(describe).join(",")})`;
assert.ok(button, describe(host));
const onClick = button.props.onClick as (event: Event) => void;
onClick({ isTrusted: false, target: null } as unknown as Event);
assert.equal(emitted.length, 0, "script-created events must not reach extension logic");
onClick({ isTrusted: true, target: null } as unknown as Event);
assert.equal(emitted.length, 1);
const payload = emitted[0] as { skinId: string; componentId: string; input: { state: Record<string, unknown>; event: Record<string, unknown> } };
assert.equal(payload.skinId, "community.test");
assert.equal(payload.componentId, "server-rail");
assert.deepEqual({ ...payload.input.state }, { expanded: false });
assert.deepEqual(payload.input.event, { componentId: "server-rail", handlerId: "select-server", eventName: "click" });
app.unmount();
});
test("generated UI rejects executable elements, event handlers, and network/navigation sinks", () => {
expectOutputError(generatedOutput("runtime-ui", { tag: "script" }), "SKIN_EXTENSION_UI_ELEMENT_INVALID");
expectOutputError(generatedOutput("runtime-ui", { tag: "iframe" }), "SKIN_EXTENSION_UI_ELEMENT_INVALID");
@@ -20,12 +20,13 @@ import {
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmStatusProbe,
createSkinExtensionWasmTooManyFunctionsProbe,
createSkinExtensionWasmUiInputProbe,
createSkinExtensionWasmUiOutputProbe,
} from "../../test/skin-extension-wasm-fixture.js";
test("Wasm metadata policy accepts only a single run export and one bounded host memory", () => {
const metadata = validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmPrefixByteImmediateProbe());
assert.deepEqual(metadata, { usesSessionStatus: false, usesUiOutput: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
assert.deepEqual(metadata, { usesSessionStatus: false, usesUiInput: false, usesUiOutput: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
});
test("Wasm policy rejects module-defined memory or tables that bypass host limits", () => {
@@ -84,12 +85,20 @@ test("Wasm import parsing reads the bounded permission contract without native c
});
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(status, ["session.status.read"]), {
usesSessionStatus: true,
usesUiInput: false,
usesUiOutput: false,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
assert.equal(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmCappedRunProbe()).usesSessionStatus, false);
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmUiOutputProbe()), {
usesSessionStatus: false,
usesUiInput: false,
usesUiOutput: true,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmUiInputProbe()), {
usesSessionStatus: false,
usesUiInput: true,
usesUiOutput: true,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
@@ -100,6 +109,7 @@ test("Wasm instruction scanning distinguishes extension prefixes from signed int
assert.doesNotThrow(() => validateSkinExtensionWasmBytes(bytes));
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(bytes), {
usesSessionStatus: false,
usesUiInput: false,
usesUiOutput: false,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
@@ -22,7 +22,7 @@ const WASM_HEADER = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00] as const;
const SCALAR_VALUE_TYPES = new Set([0x7f, 0x7e, 0x7d, 0x7c]);
const BOUNDED_VECTOR_COUNTS = new Map<number, number>([
[1, 128], // types
[2, 3], // memory, one optional capability import, and one optional UI output import
[2, 4], // memory, one optional capability, one UI input, and one UI output import
[3, SKIN_EXTENSION_WASM_FUNCTION_LIMIT],
[6, 128], // globals
[7, 64], // exports; the runner later requires exactly run
@@ -313,6 +313,7 @@ export function validateSkinExtensionWasmBytes(source: Uint8Array): void {
export interface SkinExtensionWasmModuleMetadata {
usesSessionStatus: boolean;
usesUiInput: boolean;
usesUiOutput: boolean;
memoryMaximumPages: number;
}
@@ -364,6 +365,7 @@ export function validateSkinExtensionWasmImportsAndExports(
let memoryMaximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
let hasMemory = false;
let usesSessionStatus = false;
let usesUiInput = false;
let usesUiOutput = false;
let hasExports = false;
@@ -376,8 +378,8 @@ export function validateSkinExtensionWasmImportsAndExports(
if (sectionId === 2) {
const count = readU32(bytes, offset, end);
if (count.value < 1 || count.value > 3) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and may import one capability and one UI output function.");
if (count.value < 1 || count.value > 4) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and may import the bounded status, UI input, and UI output functions.");
}
let cursor = count.next;
for (let index = 0; index < count.value; index += 1) {
@@ -393,6 +395,8 @@ export function validateSkinExtensionWasmImportsAndExports(
cursor = typeIndex.next;
if (fieldName.value === "session_status_read" && !usesSessionStatus) {
usesSessionStatus = true;
} else if (fieldName.value === "ui_input_read" && !usesUiInput) {
usesUiInput = true;
} else if (fieldName.value === "ui_emit_json" && !usesUiOutput) {
usesUiOutput = true;
} else {
@@ -441,5 +445,5 @@ export function validateSkinExtensionWasmImportsAndExports(
if (usesSessionStatus && !grantedPermissions.includes("session.status.read")) {
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The module imports session status without an approved session.status.read capability.");
}
return { usesSessionStatus, usesUiOutput, memoryMaximumPages };
return { usesSessionStatus, usesUiInput, usesUiOutput, memoryMaximumPages };
}
@@ -6,6 +6,7 @@ import {
SKIN_EXTENSION_WASM_RUNTIME_ENABLED,
} from "./skin-extension-wasm-sandbox.js";
import { SKIN_EXTENSION_WASM_SOURCE_LIMIT } from "./skin-extension-wasm-policy.js";
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
const manifest = parseSkinExtensionManifest({
schemaVersion: 1,
@@ -27,3 +28,27 @@ test("production Wasm execution remains disabled while the bounded runner is pro
prototypeOnly: true,
}), { code: "SKIN_EXTENSION_WASM_SIZE" });
});
test("Wasm UI input preserves bounded local state and safe event data", () => {
const parsed = parseSkinExtensionUiInput({
schemaVersion: 1,
state: { open: true, query: "team", count: 2 },
event: { componentId: "server-rail", handlerId: "select-server", eventName: "click" },
});
assert.deepEqual({ ...parsed.state }, { open: true, query: "team", count: 2 });
assert.deepEqual(parsed.event, { componentId: "server-rail", handlerId: "select-server", eventName: "click" });
});
test("Wasm UI input rejects unsupported fields, oversized text, and mismatched event values", () => {
assert.throws(() => parseSkinExtensionUiInput({ schemaVersion: 1, state: {}, event: null, trusted: true }), {
code: "SKIN_EXTENSION_UI_INPUT_INVALID",
});
assert.throws(() => parseSkinExtensionUiInput({ schemaVersion: 1, state: {}, event: {
componentId: "server-rail", handlerId: "select-server", eventName: "click", value: "forged",
} }), { code: "SKIN_EXTENSION_UI_INPUT_INVALID" });
assert.throws(() => parseSkinExtensionUiInput({
schemaVersion: 1,
state: { query: "x".repeat(1_025) },
event: null,
}), { code: "SKIN_EXTENSION_UI_INPUT_INVALID" });
});
@@ -16,6 +16,10 @@ import {
SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES,
validateSkinExtensionWasmBytes,
} from "./skin-extension-wasm-policy.js";
import {
parseSkinExtensionUiInput,
SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES,
} from "../../../src/shared/skin-extension-ui-input.js";
export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = false as const;
@@ -30,6 +34,7 @@ export interface SkinExtensionWasmSandboxResult {
result: number | string;
linearMemoryBytes: number;
statusReadCount: number;
uiInputReadCount: number;
uiOutput: string | null;
sessionSnapshot?: SkinExtensionSessionStatus;
}
@@ -38,6 +43,8 @@ export interface SkinExtensionWasmSandboxOptions {
manifest: unknown;
approval: unknown;
wasmBytes: Uint8Array;
/** Bounded local component state and optional safe fields from a trusted UI event. */
uiInput?: unknown;
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
/** This prototype is available only to the development security harness. */
prototypeOnly: true;
@@ -77,6 +84,11 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
validateSkinExtensionWasmBytes(options.wasmBytes);
const grantedPermissions = manifest.permissions.filter((permission) =>
isSkinExtensionPermissionApproved(approval, manifest.id, permission));
const uiInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
const uiInputJson = JSON.stringify(uiInput);
if (new TextEncoder().encode(uiInputJson).byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) {
throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_UI_INPUT_INVALID", "The local UI input exceeds its bounded size.");
}
const wasmBytes = options.wasmBytes.slice();
const worker = new Worker(new URL("./skin-extension-wasm-worker.ts", import.meta.url), {
type: "module",
@@ -175,7 +187,7 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
return;
}
if (message.type === "complete") {
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount", "uiOutput"];
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount", "uiInputReadCount", "uiOutput"];
if (Object.keys(message).length !== expectedKeys.length
|| Object.keys(message).some((key) => !expectedKeys.includes(key))
|| (typeof message.result !== "number" && typeof message.result !== "string")
@@ -185,12 +197,15 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
|| !Number.isSafeInteger(message.linearMemoryBytes) || (message.linearMemoryBytes as number) < 0
|| (message.linearMemoryBytes as number) > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024
|| !Number.isSafeInteger(message.statusReadCount) || (message.statusReadCount as number) < 0
|| (message.statusReadCount as number) > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT) {
|| (message.statusReadCount as number) > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT
|| !Number.isSafeInteger(message.uiInputReadCount) || (message.uiInputReadCount as number) < 0
|| (message.uiInputReadCount as number) > 1) {
finish("invalid-result", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The Wasm worker returned a result outside its allowed shape."));
return;
}
complete({ result: message.result as number | string, linearMemoryBytes: message.linearMemoryBytes as number,
statusReadCount: message.statusReadCount as number, uiOutput: message.uiOutput as string | null,
statusReadCount: message.statusReadCount as number, uiInputReadCount: message.uiInputReadCount as number,
uiOutput: message.uiOutput as string | null,
...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) });
return;
}
@@ -206,7 +221,7 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
startupTimer = window.setTimeout(() => finish("startup-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_STARTUP_TIMEOUT", "The Wasm worker did not finish initialization in time.")), SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS);
const bytes = wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength) as ArrayBuffer;
worker.postMessage({ type: "run", bytes, approvedPermissions: grantedPermissions }, [bytes]);
worker.postMessage({ type: "run", bytes, approvedPermissions: grantedPermissions, input: uiInputJson }, [bytes]);
return {
ready,
+29 -6
View File
@@ -11,11 +11,16 @@ import {
SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES,
validateSkinExtensionWasmImportsAndExports,
} from "./skin-extension-wasm-policy.js";
import {
parseSkinExtensionUiInput,
SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES,
} from "../../../src/shared/skin-extension-ui-input.js";
interface RunMessage {
type: "run";
bytes: ArrayBuffer;
approvedPermissions: string[];
input: string;
}
interface CapabilityResponse {
@@ -29,9 +34,11 @@ interface WasmiInterpreterExports extends WebAssembly.Exports {
memory: WebAssembly.Memory;
alloc: (size: number) => number;
run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number,
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
uiInputPointer: number, uiInputLength: number, statusPermissionGranted: number,
memoryMaximumPages: number, fuel: bigint) => bigint;
last_error_code: () => number;
last_status_read_count: () => number;
last_ui_input_read_count: () => number;
last_guest_memory_bytes: () => number;
last_ui_output_pointer: () => number;
last_ui_output_length: () => number;
@@ -64,8 +71,9 @@ scope.addEventListener("message", (event: MessageEvent<unknown>) => {
return;
}
if (started || !isPlainRecord(value) || value.type !== "run" || !(value.bytes instanceof ArrayBuffer)
|| typeof value.input !== "string"
|| !Array.isArray(value.approvedPermissions) || value.approvedPermissions.some((permission) => typeof permission !== "string")
|| Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions"].includes(key))) {
|| Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions", "input"].includes(key))) {
sendError("SKIN_EXTENSION_WASM_JOB_INVALID", "The isolated Wasm job message is invalid.");
return;
}
@@ -86,6 +94,12 @@ async function requestSessionStatus(): Promise<SkinExtensionSessionStatus> {
async function run(job: RunMessage): Promise<void> {
try {
const bytes = new Uint8Array(job.bytes);
const input = parseSkinExtensionUiInput(job.input);
const inputBytes = new TextEncoder().encode(JSON.stringify(input));
if (inputBytes.byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) {
sendError("SKIN_EXTENSION_UI_INPUT_INVALID", "The local UI input exceeds its bounded size.");
return;
}
const metadata = validateSkinExtensionWasmImportsAndExports(bytes, job.approvedPermissions);
const interpreter = await loadWasmiInterpreter();
const status = metadata.usesSessionStatus ? await requestSessionStatus() : null;
@@ -95,7 +109,7 @@ async function run(job: RunMessage): Promise<void> {
return;
}
const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0);
const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0) + inputBytes.byteLength;
const pointer = interpreter.alloc(payloadLength);
if (!pointer) {
sendError("SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT", "The extension input exceeds the interpreter's bounded memory.");
@@ -104,29 +118,36 @@ async function run(job: RunMessage): Promise<void> {
new Uint8Array(interpreter.memory.buffer, pointer, bytes.byteLength).set(bytes);
const statusPointer = statusBytes ? pointer + bytes.byteLength : 0;
if (statusBytes) new Uint8Array(interpreter.memory.buffer, statusPointer, statusBytes.byteLength).set(statusBytes);
const uiInputPointer = pointer + bytes.byteLength + (statusBytes?.byteLength ?? 0);
new Uint8Array(interpreter.memory.buffer, uiInputPointer, inputBytes.byteLength).set(inputBytes);
scope.postMessage({ type: "running" });
const rawResult = interpreter.run(pointer, bytes.byteLength, statusPointer, statusBytes?.byteLength ?? 0,
metadata.usesSessionStatus ? 1 : 0, metadata.memoryMaximumPages, SKIN_EXTENSION_WASM_FUEL_LIMIT);
uiInputPointer, inputBytes.byteLength, metadata.usesSessionStatus ? 1 : 0,
metadata.memoryMaximumPages, SKIN_EXTENSION_WASM_FUEL_LIMIT);
const errorCode = interpreter.last_error_code();
if (errorCode !== 0) {
const code = errorCode === 5 ? "SKIN_EXTENSION_WASM_EXECUTION_LIMIT"
: errorCode === 6 ? "SKIN_EXTENSION_WASM_MEMORY_LIMIT"
: errorCode === 10 ? "SKIN_EXTENSION_WASM_IMPORT_INVALID"
: errorCode === 11 ? "SKIN_EXTENSION_WASM_PERMISSION_INVALID"
: errorCode === 12 ? "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID"
: "SKIN_EXTENSION_WASM_INTERPRETER_FAILED";
: errorCode === 12 ? "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID"
: errorCode === 13 ? "SKIN_EXTENSION_WASM_UI_INPUT_INVALID"
: "SKIN_EXTENSION_WASM_INTERPRETER_FAILED";
sendError(code, "The extension was rejected or stopped inside the bounded Wasmi interpreter.");
return;
}
const result = Number(rawResult);
const statusReadCount = interpreter.last_status_read_count();
const uiInputReadCount = interpreter.last_ui_input_read_count();
const linearMemoryBytes = interpreter.last_guest_memory_bytes();
const uiOutputPointer = interpreter.last_ui_output_pointer();
const uiOutputLength = interpreter.last_ui_output_length();
if (!Number.isSafeInteger(result) || !Number.isSafeInteger(statusReadCount) || statusReadCount < 0
|| statusReadCount > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT || !Number.isSafeInteger(linearMemoryBytes)
|| !Number.isSafeInteger(uiInputReadCount) || uiInputReadCount < 0 || uiInputReadCount > 1
|| (uiInputReadCount > 0 && !metadata.usesUiInput)
|| linearMemoryBytes < 0 || linearMemoryBytes > metadata.memoryMaximumPages * 64 * 1024
|| linearMemoryBytes > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024) {
sendError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The interpreter returned a value outside the allowed resource policy.");
@@ -158,6 +179,7 @@ async function run(job: RunMessage): Promise<void> {
result,
linearMemoryBytes,
statusReadCount,
uiInputReadCount,
uiOutput,
};
if (new TextEncoder().encode(JSON.stringify(message)).byteLength > SKIN_EXTENSION_WASM_MESSAGE_LIMIT) {
@@ -189,6 +211,7 @@ async function loadWasmiInterpreter(): Promise<WasmiInterpreterExports> {
if (!(exports.memory instanceof WebAssembly.Memory) || typeof exports.alloc !== "function"
|| typeof exports.run !== "function" || typeof exports.last_error_code !== "function"
|| typeof exports.last_status_read_count !== "function" || typeof exports.last_guest_memory_bytes !== "function"
|| typeof exports.last_ui_input_read_count !== "function"
|| typeof exports.last_ui_output_pointer !== "function" || typeof exports.last_ui_output_length !== "function") {
throw new Error("The bounded Wasmi interpreter exposes an incompatible runtime interface.");
}
+25 -4
View File
@@ -5,6 +5,7 @@ import {
createSkinExtensionWasmCappedRunProbe,
createSkinExtensionWasmInfiniteRunProbe,
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmUiInputProbe,
createSkinExtensionWasmUiOutputProbe,
} from "../../test/skin-extension-wasm-fixture.js";
@@ -12,8 +13,10 @@ interface WasmiInterpreterExports extends WebAssembly.Exports {
memory: WebAssembly.Memory;
alloc: (size: number) => number;
run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number,
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
uiInputPointer: number, uiInputLength: number, statusPermissionGranted: number,
memoryMaximumPages: number, fuel: bigint) => bigint;
last_error_code: () => number;
last_ui_input_read_count: () => number;
last_guest_memory_bytes: () => number;
last_ui_output_pointer: () => number;
last_ui_output_length: () => number;
@@ -24,15 +27,20 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
const { instance } = await WebAssembly.instantiate(artifact);
const runtime = instance.exports as unknown as WasmiInterpreterExports;
function run(module: Uint8Array): { result: number; error: number; guestMemoryBytes: number; uiOutput: string | null } {
const pointer = runtime.alloc(module.byteLength);
function run(module: Uint8Array, input = '{"schemaVersion":1,"state":{},"event":null}'):
{ result: number; error: number; guestMemoryBytes: number; uiInputReadCount: number; uiOutput: string | null } {
const inputBytes = new TextEncoder().encode(input);
const pointer = runtime.alloc(module.byteLength + inputBytes.byteLength);
assert.notEqual(pointer, 0, "the bounded interpreter should accept the small fixture");
new Uint8Array(runtime.memory.buffer, pointer, module.byteLength).set(module);
const result = runtime.run(pointer, module.byteLength, 0, 0, 0, 64, 10_000_000n);
const inputPointer = pointer + module.byteLength;
new Uint8Array(runtime.memory.buffer, inputPointer, inputBytes.byteLength).set(inputBytes);
const result = runtime.run(pointer, module.byteLength, 0, 0, inputPointer, inputBytes.byteLength, 0, 64, 10_000_000n);
return {
result: Number(result),
error: runtime.last_error_code(),
guestMemoryBytes: runtime.last_guest_memory_bytes(),
uiInputReadCount: runtime.last_ui_input_read_count(),
uiOutput: runtime.last_ui_output_length() === 0
? null
: new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(
@@ -47,6 +55,7 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
result: 123,
error: 0,
guestMemoryBytes: 64 * 1024,
uiInputReadCount: 0,
uiOutput: null,
});
assert.equal(run(createSkinExtensionWasmInfiniteRunProbe()).error, 5, "the fuel budget must trap a non-returning module");
@@ -54,6 +63,7 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
result: -1,
error: 0,
guestMemoryBytes: 4 * 1024 * 1024,
uiInputReadCount: 0,
uiOutput: null,
});
@@ -61,8 +71,19 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
result: 7,
error: 0,
guestMemoryBytes: 64 * 1024,
uiInputReadCount: 0,
uiOutput: '{"type":"root"}',
});
const uiInput = '{"schemaVersion":1,"state":{"open":true},"event":{"componentId":"rail","handlerId":"toggle","eventName":"click"}}';
assert.deepEqual(run(createSkinExtensionWasmUiInputProbe(), uiInput), {
result: 7,
error: 0,
guestMemoryBytes: 64 * 1024,
uiInputReadCount: 1,
uiOutput: uiInput,
});
assert.equal(run(createSkinExtensionWasmUiInputProbe(true), uiInput).error, 13,
"the host must reject a second UI input read in one guest invocation");
assert.equal(run(createSkinExtensionWasmUiOutputProbe("x".repeat(16 * 1024 + 1))).error, 12,
"the interpreter must reject a UI payload above its byte cap");
assert.equal(run(createSkinExtensionWasmUiOutputProbe('{"type":"root"}', true)).error, 12,
+34
View File
@@ -96,6 +96,40 @@ export function createSkinExtensionWasmUiOutputProbe(output = '{"type":"root"}',
]);
}
/** Reads the host-provided bounded local state/event JSON once and echoes it through UI output. */
export function createSkinExtensionWasmUiInputProbe(readTwice = false): Uint8Array {
const readInput = [
0x41, 0,
0x41, ...signedLeb128(8 * 1024),
0x10, 0,
];
const body = [
1, 1, 0x7f, // one i32 local for input length
...readInput,
0x21, 0, // local.set 0
...(readTwice ? [...readInput, 0x1a] : []),
0x41, 0,
0x20, 0,
0x10, 1, // ui_emit_json(0, input_length)
0x1a,
0x41, 7,
0x0b,
];
return Uint8Array.from([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
...section(1, [2, 0x60, 2, 0x7f, 0x7f, 1, 0x7f, 0x60, 0, 1, 0x7f]),
...section(2, [
3,
...name("env"), ...name("memory"), 0x02, 0x01, 1, 64,
...name("env"), ...name("ui_input_read"), 0x00, 0,
...name("env"), ...name("ui_emit_json"), 0x00, 0,
]),
...section(3, [1, 1]),
...section(7, [1, ...name("run"), 0, 2]),
...section(10, [1, body.length, ...body]),
]);
}
/** Tries to alter the copied snapshot before returning; host results must remain host-owned. */
export function createSkinExtensionWasmStatusMutationProbe(): Uint8Array {
return singleRunModule([1, 1, 0x7f, 0x41, 0x00, 0x41, 0x80, 0x02, 0x10, 0x00,