feat(skin): add bounded UI output bridge

This commit is contained in:
illusia committed 2026-10-10 15:53:49 +08:00
1 parent 849eb1a6d9
commit 7047d71678
12 files changed
+266 -19

No files matched your search

@@ -18,7 +18,7 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, a built-in
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
- Follow the schema-specific CSS rules: v1/v2 reject layout changes; v3 allows layout, placement, size, typography, and visibility changes within the skin root. Keep CSS package-local, scoped to public hooks, and free of external resources or executable values.
- v3 can replace or obscure normal page controls. A surface must request `ui.surface.replace` and stays disabled until the user approves it. Custom interfaces can use their own declarative nodes and CSS; embed optional host widgets only when a trusted WebSpeak control is useful. Available widget IDs are registered in `src/shared/skin-plugin.ts`; each stateful host widget may appear once per page. Preserve usable microphone, disconnect, device-settings, screen-share and recovery paths at desktop and mobile sizes. Verify both the return-to-built-in-UI and restore-built-in-skin buttons. The host recovery and permission UI render outside the skin root. Keep `/admin/**` unskinned.
- components.json schema v1 is legacy; v2 adds `mode: "surface"` and optional allowlisted host-widget nodes; v3 expands bounded declarative composition, events and permission-gated voice actions. Never add script, Wasm, HTML strings, direct network/storage, or private host objects. Request only the component-level permissions needed; surfaces require `ui.surface.replace`. Bind voice actions only to explicit trusted activations; passive focus/blur/hover/drag-start/over events may update local UI state only, and input/change must not trigger host actions. Keep server-list labels and opaque identifiers separate from addresses and credentials. Use `servers.quickList` plus `quickServers.switch` when a custom UI should show favorites and recent servers together. Host widgets execute in WebSpeak and do not grant author code access to their private state.
- components.json schema v1 is legacy; v2 adds `mode: "surface"` and optional allowlisted host-widget nodes; v3 expands bounded declarative composition, events and permission-gated voice actions. Keep script/Wasm execution disabled in production until sandbox review and host rendering/action validation are complete. The development Wasm prototype may return one untrusted `ui_emit_json` string up to 16 KiB; do not render it until strict JSON/schema validation maps it to safe declarative nodes. Never execute HTML strings or expose direct network/storage or private host objects. Request only the component-level permissions needed; surfaces require `ui.surface.replace`. Bind voice actions only to explicit trusted activations; passive focus/blur/hover/drag-start/over events may update local UI state only, and input/change must not trigger host actions. Keep server-list labels and opaque identifiers separate from addresses and credentials. Use `servers.quickList` plus `quickServers.switch` when a custom UI should show favorites and recent servers together. Host widgets execute in WebSpeak and do not grant author code access to their private state.
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
+7 -1
View File
@@ -32,6 +32,12 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖
- 被动 focus/blur/hover/drag-start/drag-over 只能更新本地 UI 状态;触发宿主动作需要明确用户操作,输入/change 仍不能触发连接、切房或消息发送。
- 完成统一批次验证后,再以真实授权语音房间完善 KAAK 参考实现;授权房间在当前浏览器仍不可读取时,保持未完成状态,不猜测视觉细节。
### R3.2:受限作者逻辑运行时(原型,生产关闭)
- 现有 JavaScript Worker 因缺少硬内存配额继续关闭;Wasmi 原型用独立 Worker、解释器内存上限、扩展燃料上限和超时终止运行非可信 Wasm。
- 当前增量加入 `env.ui_emit_json`:单次运行最多输出一次、不超过 16 KiB 的 UTF-8 UI 数据。宿主只接收有界字符串,不执行 HTML/JS,也不允许通过该接口触发 TeamSpeak 动作。
- 下一步先实现严格 JSON/schema 校验,再将结果映射到安全声明式节点;宿主动作必须另走现有权限、可信用户事件与逐次参数校验。验证完整之前继续保持生产开关关闭。
### R4:整页皮肤界面和宿主控件组合(进行中)
- components.json schema v2 引入、schema v3 继续支持 `mode: "surface"`,允许替换首页或语音工作区的完整可见页面;旧 schema v1/v2 继续兼容。
@@ -50,7 +56,7 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖
- surface 的“恢复内置皮肤”按钮误接到仅用于皮肤加载错误的回退函数,正常皮肤下点击无效。已改为明确切换到当前主题对应的内置皮肤,并增加授权/撤销回归。
- 初版自定义服务器栏只有收藏数据,缺少最近连接项。新增 `servers.quickList` 和宿主切换动作,使用不透明令牌,不下放目标地址或凭据。
- 收藏名/最近连接显示名有时会直接等于服务器地址;投影数据前增加地址匹配与泛化标签,避免通过“显示名”字段间接暴露连接目标。
- KOOK 已授权范围是“比奇堡恶人帮”相关的前两个语音房间;用户明确排除陪玩店、活动通知等运营页面。新建 IAB 标签可以读取频道页的大致布局结构,但现有页面绑定、截图和语音频道点击均超时,无法确认是否真正进入语音房或取得视觉截图。尚未保存频道 ID、成员名单或历史消息;房间视觉复刻与交互验收仍未完成,不以推广内容、历史消息、搜索摘要或不相关页面替代参考。
- KOOK 已授权范围是“比奇堡恶人帮”相关的前两个语音房间;用户明确排除陪玩店、活动通知等运营页面。当前能读到服务器页的无障碍结构,包括语音分组、频道列表、主内容区、成员栏和底部语音控件;进入频道的点击与截图读取仍超时,无法确认已加入房间或完成视觉采集。未保存频道标识、成员名单或历史消息;房间视觉复刻与交互验收仍未完成,不以推广内容、历史消息、搜索摘要或不相关页面替代参考。
## 下一阶段
+2 -1
View File
@@ -75,5 +75,6 @@ v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦
- 扩展数据字段或宿主动作时,增加精确 schema、权限、明确用户事件约束和宿主侧运行时验证,不暴露内部 SDK 对象。新增宿主控件也必须登记固定 ID、明确页面和确认只在宿主内处理其私有状态;自定义声明式 UI 不应被限制为只能拼装这组控件。
- 对恶意输入、路径别名、拒绝授权、撤销、更新和皮肤切换增加测试;高敏能力必须单独设计。
- 不把当前声明式包描述为可执行代码沙箱。现有 JavaScript Worker 与 Wasm 原型均未启用;浏览器 Worker 没有硬内存配额,原型也没有完整的页面渲染、控件与动作审查流程。若未来考虑作者代码,应另行开展威胁建模、资源耗尽测试、浏览器隔离评估与独立安全审查。
- 当前 JavaScript Worker 与 Wasm 扩展运行时都保持生产关闭。JavaScript Worker 缺少硬内存配额;Wasmi 解释器目前只是受限原型:解释器容器上限 64 MiB,扩展线性内存最多 4 MiB,燃料上限 10,000,000,外层 Worker 在 100 ms 后可终止执行。
- Wasm 原型新增 `env.ui_emit_json`,每次运行最多提交一次、最多 16 KiB 的 UTF-8 字符串。该结果仍是不可信输入;它不会被当成 HTML 或脚本执行,也不授予网络、存储或宿主动作权限。完成严格 JSON/schema 校验、只用安全节点渲染、动作可信事件校验、授权/撤销流程、资源耗尽测试和独立安全审查之前,不得接入生产渲染或启用运行开关。
- 商城发布、签名、下架、更新和撤销设计与管理员面板重做一起验收,且保持零新增服务费用为默认约束。
Binary file not shown.
+81 -3
View File
@@ -5,6 +5,7 @@ use wasmi::{
const SOURCE_LIMIT: usize = 256 * 1024;
const STATUS_LIMIT: usize = 512;
const UI_OUTPUT_LIMIT: usize = 16 * 1024;
const MEMORY_LIMIT_BYTES: usize = 64 * 64 * 1024;
const STATUS_READ_LIMIT: u32 = 10;
const FUEL_LIMIT: u64 = 10_000_000;
@@ -20,10 +21,13 @@ const ERROR_STATUS_LINK: u32 = 8;
const ERROR_INSTANTIATION: u32 = 9;
const ERROR_IMPORT: u32 = 10;
const ERROR_PERMISSION: u32 = 11;
const ERROR_UI_OUTPUT: u32 = 12;
static mut LAST_ERROR_CODE: u32 = ERROR_NONE;
static mut LAST_STATUS_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;
static mut LAST_DIAGNOSTIC: [u8; 256] = [0; 256];
static mut LAST_DIAGNOSTIC_LENGTH: u32 = 0;
@@ -31,6 +35,9 @@ struct HostState {
limits: StoreLimits,
status: Vec<u8>,
status_read_count: u32,
ui_output: Vec<u8>,
ui_output_emitted: bool,
ui_output_invalid: bool,
}
#[unsafe(no_mangle)]
@@ -60,6 +67,7 @@ pub unsafe extern "C" fn run(
fuel: u64,
) -> i64 {
clear_diagnostic();
clear_ui_output();
set_report(ERROR_NONE, 0, 0);
if module_pointer == 0
|| module_length == 0
@@ -83,7 +91,8 @@ pub unsafe extern "C" fn run(
};
match execute(module_bytes, status, status_permission_granted == 1, memory_maximum_pages, fuel) {
Ok((result, status_reads, guest_memory_bytes)) => {
Ok((result, status_reads, guest_memory_bytes, ui_output)) => {
set_ui_output(&ui_output);
set_report(ERROR_NONE, status_reads, guest_memory_bytes);
result as i64
}
@@ -109,6 +118,16 @@ pub extern "C" fn last_guest_memory_bytes() -> u32 {
unsafe { LAST_GUEST_MEMORY_BYTES }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_ui_output_pointer() -> u32 {
core::ptr::addr_of!(LAST_UI_OUTPUT) as usize as u32
}
#[unsafe(no_mangle)]
pub extern "C" fn last_ui_output_length() -> u32 {
unsafe { LAST_UI_OUTPUT_LENGTH }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_diagnostic_pointer() -> u32 {
core::ptr::addr_of!(LAST_DIAGNOSTIC) as usize as u32
@@ -142,13 +161,26 @@ fn set_report(error: u32, status_reads: u32, guest_memory_bytes: u32) {
}
}
fn clear_ui_output() {
unsafe { LAST_UI_OUTPUT_LENGTH = 0; }
}
fn set_ui_output(output: &[u8]) {
let length = output.len().min(UI_OUTPUT_LIMIT);
unsafe {
let destination = core::ptr::addr_of_mut!(LAST_UI_OUTPUT).cast::<u8>();
core::ptr::copy_nonoverlapping(output.as_ptr(), destination, length);
LAST_UI_OUTPUT_LENGTH = length as u32;
}
}
fn execute(
module_bytes: &[u8],
status: Vec<u8>,
status_permission_granted: bool,
memory_maximum_pages: u32,
fuel: u64,
) -> Result<(i32, u32, u32), (u32, u32, u32)> {
) -> Result<(i32, u32, u32, Vec<u8>), (u32, u32, u32)> {
let mut config = Config::default();
config
.consume_fuel(true)
@@ -165,6 +197,7 @@ fn execute(
.map_err(|_| (ERROR_MODULE, 0, 0))?;
let mut saw_memory = false;
let mut saw_status = false;
let mut saw_ui_output = false;
for import in module.imports() {
match (import.module(), import.name(), import.ty()) {
("env", "memory", wasmi::ExternType::Memory(memory_type))
@@ -183,6 +216,9 @@ fn execute(
("env", "session_status_read", wasmi::ExternType::Func(_)) => {
return Err((ERROR_PERMISSION, 0, 0));
}
("env", "ui_emit_json", wasmi::ExternType::Func(_)) if !saw_ui_output => {
saw_ui_output = true;
}
_ => return Err((ERROR_IMPORT, 0, 0)),
}
}
@@ -210,7 +246,14 @@ fn execute(
.tables(0)
.trap_on_grow_failure(true)
.build();
let mut store = Store::new(&engine, HostState { limits, status, status_read_count: 0 });
let mut store = Store::new(&engine, HostState {
limits,
status,
status_read_count: 0,
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))?;
@@ -256,6 +299,36 @@ fn execute(
.map_err(|_| (ERROR_STATUS_LINK, 0, 0))?;
}
let output_memory = memory;
linker
.func_wrap(
"env",
"ui_emit_json",
move |mut caller: Caller<'_, HostState>, pointer: i32, length: i32| -> i32 {
if pointer < 0 || length <= 0 || length as usize > UI_OUTPUT_LIMIT {
caller.data_mut().ui_output_invalid = true;
return -1;
}
let offset = pointer as usize;
let length = length as usize;
let memory_bytes = output_memory.data(&caller);
if offset > memory_bytes.len() || length > memory_bytes.len() - offset {
caller.data_mut().ui_output_invalid = true;
return -1;
}
let output = memory_bytes[offset..offset + length].to_vec();
if core::str::from_utf8(&output).is_err() || caller.data().ui_output_emitted {
caller.data_mut().ui_output_invalid = true;
return -1;
}
let state = caller.data_mut();
state.ui_output = output;
state.ui_output_emitted = true;
length as i32
},
)
.map_err(|_| (ERROR_IMPORT, 0, 0))?;
let instance = match linker.instantiate_and_start(&mut store, &module) {
Ok(instance) => instance,
Err(error) => {
@@ -270,9 +343,14 @@ fn execute(
.call(&mut store, ())
.map_err(|_| (ERROR_EXECUTION, store.data().status_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));
}
Ok((
result,
store.data().status_read_count,
memory.data(&store).len() as u32,
store.data().ui_output.clone(),
))
}
@@ -20,11 +20,12 @@ import {
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmStatusProbe,
createSkinExtensionWasmTooManyFunctionsProbe,
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, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
assert.deepEqual(metadata, { usesSessionStatus: false, usesUiOutput: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
});
test("Wasm policy rejects module-defined memory or tables that bypass host limits", () => {
@@ -83,9 +84,15 @@ test("Wasm import parsing reads the bounded permission contract without native c
});
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(status, ["session.status.read"]), {
usesSessionStatus: true,
usesUiOutput: false,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
assert.equal(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmCappedRunProbe()).usesSessionStatus, false);
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmUiOutputProbe()), {
usesSessionStatus: false,
usesUiOutput: true,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
});
test("Wasm instruction scanning distinguishes extension prefixes from signed integer bytes", () => {
@@ -93,6 +100,7 @@ test("Wasm instruction scanning distinguishes extension prefixes from signed int
assert.doesNotThrow(() => validateSkinExtensionWasmBytes(bytes));
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(bytes), {
usesSessionStatus: false,
usesUiOutput: false,
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
});
});
+13 -7
View File
@@ -3,9 +3,10 @@ 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_MESSAGE_LIMIT = 32 * 1024;
export const SKIN_EXTENSION_WASM_STATUS_READ_LIMIT = 10;
export const SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT = 512;
export const SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES = 16 * 1024;
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;
@@ -19,7 +20,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, 2], // memory and one optional capability import
[2, 3], // memory, one optional capability import, and one optional UI output import
[3, SKIN_EXTENSION_WASM_FUNCTION_LIMIT],
[6, 128], // globals
[7, 64], // exports; the runner later requires exactly run
@@ -310,6 +311,7 @@ export function validateSkinExtensionWasmBytes(source: Uint8Array): void {
export interface SkinExtensionWasmModuleMetadata {
usesSessionStatus: boolean;
usesUiOutput: boolean;
memoryMaximumPages: number;
}
@@ -360,6 +362,7 @@ export function validateSkinExtensionWasmImportsAndExports(
let memoryMaximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
let hasMemory = false;
let usesSessionStatus = false;
let usesUiOutput = false;
let hasExports = false;
while (offset < bytes.byteLength) {
@@ -371,8 +374,8 @@ export function validateSkinExtensionWasmImportsAndExports(
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.");
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.");
}
let cursor = count.next;
for (let index = 0; index < count.value; index += 1) {
@@ -386,10 +389,13 @@ export function validateSkinExtensionWasmImportsAndExports(
if (kind === 0) {
const typeIndex = readU32(bytes, cursor, end);
cursor = typeIndex.next;
if (fieldName.value !== "session_status_read" || usesSessionStatus) {
if (fieldName.value === "session_status_read" && !usesSessionStatus) {
usesSessionStatus = true;
} else if (fieldName.value === "ui_emit_json" && !usesUiOutput) {
usesUiOutput = true;
} else {
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.");
@@ -433,5 +439,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, memoryMaximumPages };
return { usesSessionStatus, usesUiOutput, memoryMaximumPages };
}
@@ -13,6 +13,7 @@ import {
SKIN_EXTENSION_WASM_SOURCE_LIMIT,
SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS,
SKIN_EXTENSION_WASM_STATUS_READ_LIMIT,
SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES,
validateSkinExtensionWasmBytes,
} from "./skin-extension-wasm-policy.js";
@@ -29,6 +30,7 @@ export interface SkinExtensionWasmSandboxResult {
result: number | string;
linearMemoryBytes: number;
statusReadCount: number;
uiOutput: string | null;
sessionSnapshot?: SkinExtensionSessionStatus;
}
@@ -173,10 +175,13 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
return;
}
if (message.type === "complete") {
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount"];
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount", "uiOutput"];
if (Object.keys(message).length !== expectedKeys.length
|| Object.keys(message).some((key) => !expectedKeys.includes(key))
|| (typeof message.result !== "number" && typeof message.result !== "string")
|| (message.uiOutput !== null && typeof message.uiOutput !== "string")
|| (typeof message.uiOutput === "string"
&& new TextEncoder().encode(message.uiOutput).byteLength > SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES)
|| !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
@@ -185,7 +190,8 @@ export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWa
return;
}
complete({ result: message.result as number | string, linearMemoryBytes: message.linearMemoryBytes as number,
statusReadCount: message.statusReadCount as number, ...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) });
statusReadCount: message.statusReadCount as number, uiOutput: message.uiOutput as string | null,
...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) });
return;
}
if (message.type === "error" && Object.keys(message).length === 3
+31 -2
View File
@@ -8,6 +8,7 @@ import {
SKIN_EXTENSION_WASM_MESSAGE_LIMIT,
SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT,
SKIN_EXTENSION_WASM_STATUS_READ_LIMIT,
SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES,
validateSkinExtensionWasmImportsAndExports,
} from "./skin-extension-wasm-policy.js";
@@ -32,6 +33,8 @@ interface WasmiInterpreterExports extends WebAssembly.Exports {
last_error_code: () => number;
last_status_read_count: () => number;
last_guest_memory_bytes: () => number;
last_ui_output_pointer: () => number;
last_ui_output_length: () => number;
}
const scope = self as unknown as {
@@ -111,7 +114,8 @@ async function run(job: RunMessage): Promise<void> {
: 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";
: errorCode === 12 ? "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID"
: "SKIN_EXTENSION_WASM_INTERPRETER_FAILED";
sendError(code, "The extension was rejected or stopped inside the bounded Wasmi interpreter.");
return;
}
@@ -119,6 +123,8 @@ async function run(job: RunMessage): Promise<void> {
const result = Number(rawResult);
const statusReadCount = interpreter.last_status_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)
|| linearMemoryBytes < 0 || linearMemoryBytes > metadata.memoryMaximumPages * 64 * 1024
@@ -126,11 +132,33 @@ async function run(job: RunMessage): Promise<void> {
sendError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The interpreter returned a value outside the allowed resource policy.");
return;
}
if (!Number.isSafeInteger(uiOutputPointer) || uiOutputPointer < 0 || !Number.isSafeInteger(uiOutputLength)
|| uiOutputLength < 0 || uiOutputLength > SKIN_EXTENSION_WASM_UI_OUTPUT_LIMIT_BYTES
|| (uiOutputLength > 0 && !metadata.usesUiOutput)
|| uiOutputPointer > interpreter.memory.buffer.byteLength
|| uiOutputLength > interpreter.memory.buffer.byteLength - uiOutputPointer) {
sendError("SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID", "The interpreter returned UI output outside its bounded memory range.");
return;
}
let uiOutput: string | null = null;
if (uiOutputLength > 0) {
try {
const decodedOutput = new TextDecoder("utf-8", { fatal: true }).decode(
new Uint8Array(interpreter.memory.buffer, uiOutputPointer, uiOutputLength),
);
JSON.parse(decodedOutput);
uiOutput = decodedOutput;
} catch {
sendError("SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID", "The extension returned malformed UTF-8 or JSON UI output.");
return;
}
}
const message = {
type: "complete",
result,
linearMemoryBytes,
statusReadCount,
uiOutput,
};
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.");
@@ -160,7 +188,8 @@ async function loadWasmiInterpreter(): Promise<WasmiInterpreterExports> {
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") {
|| typeof exports.last_status_read_count !== "function" || typeof exports.last_guest_memory_bytes !== "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.");
}
return exports;
+24 -1
View File
@@ -5,6 +5,7 @@ import {
createSkinExtensionWasmCappedRunProbe,
createSkinExtensionWasmInfiniteRunProbe,
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmUiOutputProbe,
} from "../../test/skin-extension-wasm-fixture.js";
interface WasmiInterpreterExports extends WebAssembly.Exports {
@@ -14,6 +15,8 @@ interface WasmiInterpreterExports extends WebAssembly.Exports {
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
last_error_code: () => number;
last_guest_memory_bytes: () => number;
last_ui_output_pointer: () => number;
last_ui_output_length: () => number;
}
test("the fixed Wasmi artifact caps its own memory and stops guest execution at fuel", async () => {
@@ -21,7 +24,7 @@ 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 } {
function run(module: Uint8Array): { result: number; error: number; guestMemoryBytes: number; uiOutput: string | null } {
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);
@@ -30,6 +33,13 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
result: Number(result),
error: runtime.last_error_code(),
guestMemoryBytes: runtime.last_guest_memory_bytes(),
uiOutput: runtime.last_ui_output_length() === 0
? null
: new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(
runtime.memory.buffer,
runtime.last_ui_output_pointer(),
runtime.last_ui_output_length(),
)),
};
}
@@ -37,14 +47,27 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
result: 123,
error: 0,
guestMemoryBytes: 64 * 1024,
uiOutput: null,
});
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,
uiOutput: null,
});
assert.deepEqual(run(createSkinExtensionWasmUiOutputProbe()), {
result: 7,
error: 0,
guestMemoryBytes: 64 * 1024,
uiOutput: '{"type":"root"}',
});
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,
"the interpreter must reject more than one UI payload per execution");
const memory = runtime.memory;
const currentPages = memory.buffer.byteLength / (64 * 1024);
memory.grow(1024 - currentPages);
@@ -19,6 +19,7 @@ import {
createSkinExtensionWasmInfiniteRunProbe,
createSkinExtensionWasmStatusMutationProbe,
createSkinExtensionWasmStatusProbe,
createSkinExtensionWasmUiOutputProbe,
createSkinExtensionWasmGcAllocationProbe,
createSkinExtensionWasmOversizedFunctionBodyProbe,
createSkinExtensionWasmOversizedElementVectorProbe,
@@ -246,6 +247,48 @@ await test("the development Wasm prototype bounds linear memory at 64 pages", as
}
});
await test("Wasm can return one bounded UTF-8 UI payload to the host", async () => {
const { sandbox } = wasmExtension(createSkinExtensionWasmUiOutputProbe());
try {
await sandbox.ready;
const result = await sandbox.result;
equal(result.uiOutput, '{"type":"root"}', "the host should receive the exact bounded UI payload");
equal(result.result, 7, "the ordinary scalar return value should remain available");
} finally {
sandbox.close("test-complete");
await sandbox.stopped;
}
});
await test("Wasm UI output is rejected when it exceeds the host byte limit", async () => {
const { sandbox } = wasmExtension(createSkinExtensionWasmUiOutputProbe("x".repeat(16 * 1024 + 1)));
try {
await sandbox.ready;
await rejects(sandbox.result, "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID", "oversized UI output must fail closed");
await sandbox.stopped;
} finally {
sandbox.close("test-complete");
await sandbox.stopped;
}
});
await test("Wasm UI output rejects malformed JSON and repeated emissions", async () => {
for (const bytes of [
createSkinExtensionWasmUiOutputProbe("not-json"),
createSkinExtensionWasmUiOutputProbe('{"type":"root"}', true),
]) {
const { sandbox } = wasmExtension(bytes);
try {
await sandbox.ready;
await rejects(sandbox.result, "SKIN_EXTENSION_WASM_UI_OUTPUT_INVALID", "invalid UI output must fail closed");
await sandbox.stopped;
} finally {
sandbox.close("test-complete");
await sandbox.stopped;
}
}
});
await test("Wasm complexity limits reject too many functions and oversized bodies before Worker creation", async () => {
throws(() => wasmExtension(createSkinExtensionWasmTooManyFunctionsProbe()), "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
"the host must reject an excessive function count before starting a Worker");
+47
View File
@@ -13,6 +13,21 @@ function unsignedLeb128(value: number): number[] {
return bytes;
}
function signedLeb128(value: number): number[] {
const bytes: number[] = [];
let remaining = value | 0;
let more = true;
while (more) {
let byte = remaining & 0x7f;
remaining >>= 7;
const signBitSet = (byte & 0x40) !== 0;
more = !((remaining === 0 && !signBitSet) || (remaining === -1 && signBitSet));
if (more) byte |= 0x80;
bytes.push(byte);
}
return bytes;
}
function name(value: string): number[] {
const bytes = Array.from(value, (character) => character.charCodeAt(0));
return [bytes.length, ...bytes];
@@ -49,6 +64,38 @@ export function createSkinExtensionWasmStatusProbe(): Uint8Array {
return singleRunModule([0, 0x41, 0x00, 0x41, 0x80, 0x02, 0x10, 0x00, 0x0b], true);
}
/** Emits one bounded UTF-8 JSON string through the host-owned UI output bridge. */
export function createSkinExtensionWasmUiOutputProbe(output = '{"type":"root"}', emitTwice = false): Uint8Array {
const outputBytes = Array.from(new TextEncoder().encode(output));
const outputPointer = 16;
const emitOutput = [
0x41, ...signedLeb128(outputPointer),
0x41, ...signedLeb128(outputBytes.length),
0x10, 0,
0x1a,
];
const body = [
0,
...emitOutput,
...(emitTwice ? emitOutput : []),
0x41, 0x07,
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, [
2,
...name("env"), ...name("memory"), 0x02, 0x01, 1, 64,
...name("env"), ...name("ui_emit_json"), 0x00, 0,
]),
...section(3, [1, 1]),
...section(7, [1, ...name("run"), 0, 1]),
...section(10, [1, body.length, ...body]),
...section(11, [1, 0, 0x41, outputPointer, 0x0b, ...unsignedLeb128(outputBytes.length), ...outputBytes]),
]);
}
/** 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,