diff --git a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md index 827dfcb..7ebebc1 100644 --- a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md @@ -39,8 +39,10 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 - 现有 JavaScript Worker 因缺少硬内存配额继续关闭;Wasmi 原型用独立 Worker、解释器内存上限、扩展燃料上限和超时终止运行非可信 Wasm。 - 当前增量加入 `env.ui_emit_json`:单次运行最多输出一次、不超过 16 KiB 的 UTF-8 UI 数据。宿主只接收有界字符串,不执行 HTML/JS,也不允许通过该接口触发 TeamSpeak 动作。 -- 已实现严格 UTF-8 大小、JSON 与 schema v3/v4 输出校验,以及供 `SkinPluginOutlet` 使用的合并入口;v4 输出可以组合较完整的安全 HTML/SVG 节点、ARIA/data 属性与包内图片引用。自定义标签会由宿主渲染为惰性占位 `div`,不实例化页面中可能注册的 Web Component。输出仍不能定义事件、读取数据、请求皮肤权限、替换页面、嵌入宿主控件或调用 TeamSpeak 动作;目前只有单元/SSR 测试经过该入口,尚无生产客户端把 Wasm 结果接到该属性。 -- 这一步只拓宽可生成的界面结构,不是完整插件运行时,也不是“万物皆插件”目标的替代品。后续还要为 Wasm 作者逻辑设计有界状态、用户事件协议、受权限控制的数据投影/宿主动作和完整插件生命周期,并接入实际客户端。 +- 已实现严格 UTF-8 大小、JSON 与 schema v3/v4/v5 输出校验,以及供 `SkinPluginOutlet` 使用的合并入口;schema v4 可生成安全 HTML/SVG、ARIA/data 属性与包内图片,schema v5 额外携带有界标量状态和命名事件回调。自定义标签渲染为惰性占位 `div`,不实例化页面中可能注册的 Web Component。 +- Wasm 有界输入协议新增 `env.ui_input_read`:每次运行最多读取一次、最多 8 KiB 的 JSON,包含插件本地标量状态和单个安全事件。UI 事件只在浏览器 `isTrusted` 事件触发时由宿主组件发出;DOM/Event 对象不跨边界,只传事件名、组件/处理器 ID,以及受限的键盘或输入值字段。生成的密码、文件和隐藏输入会拒绝;输入值与状态还会二次限长验证。协议不含“trusted”自报字段,作者代码不能把字段伪装成宿主授权。 +- 当前只完成到 `SkinPluginOutlet` 发出 `extension-event`,并没有 WebClient 监听器把事件重新送入 Wasm,也没有把输出、状态更新、授权撤销或受权限 TeamSpeak 操作接成完整循环。Wasm 仍为单次 Worker 原型,生产开关关闭。它尚不能读取 TeamSpeak 数据、请求权限、替换页面、嵌入宿主控件或调用 TeamSpeak 动作。 +- 这一步把事件输入/输出合同做成可测试的安全原型,不是完整插件运行时,也不是“万物皆插件”完成态。后续需完成持久生命周期与重跑策略、权限/摘要绑定、脱敏数据投影、宿主动作桥、插件布局与安装管理,并接入实际客户端。 - 这是一次性输出的受限原型,不构成完整插件运行时。生产开关关闭;后续须更换为有版本、权限、事件、生命周期和资源治理的插件协议,并做端到端与独立安全审查。 ### R3.3:完整自定义插件运行时(未完成,优先阶段) @@ -54,7 +56,7 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 - 插件对 TeamSpeak 的读取和操作经明确列举的权限、脱敏投影和宿主能力桥接;命令总由宿主校验参数、当前会话和权限。双击等事件只改变插件化界面的触发方式,不更改 TeamSpeak 协议,也不影响未启用该插件的其他皮肤。 - 沙箱架构还未选定。opaque-origin iframe 可以隔离父页面 DOM 和存储,但不等于网络隔离:浏览器仍允许 frame 自己导航,`sandbox` 主要阻止顶层导航;CSP `navigate-to` 也不能作为跨浏览器阻断保证。若 iframe 同时持有获批的会话数据,插件可尝试把数据编码进自己的导航 URL。详见 R3.3 问题记录。不得因此把任意 JS 放进有浏览 DOM 的 iframe。 - 已有安全原型把作者 JavaScript 放在没有 DOM/导航上下文的 data Worker 中,由 opaque-origin iframe 只负责消息桥;Worker CSP 可限制常规网络请求,但没有硬内存上限,仍保持生产关闭。下一版运行时必须同时保留完整自定义 UI 能力和确定的计算/内存边界:优先评估有界解释器 + 宿主创建的通用自定义节点树/CSS;不能以牺牲 DOM/事件自定义为理由退回固定原生控件目录。 -- 新增一次 Wasm 生成 UI 的安全结构试验:输出 schema v4 提供常见安全 HTML/SVG、任意 `data-*`/`aria-*` 和惰性自定义元素占位,再由宿主渲染;节点/组件/属性/文本仍有硬上限,危险加载、导航、脚本和事件属性会被拒绝。它保留完整结构方向,但现在没有事件回调和宿主能力桥,且 Wasm 仍未接入生产生命周期。 +- 新增 Wasm UI 输出 schema v4/v5 原型:v4 提供常见安全 HTML/SVG、`data-*`/`aria-*` 和惰性自定义元素占位;v5 增加安全事件名到作者处理器 ID 的映射与本地状态。节点/组件/属性/文本仍有硬上限,危险加载、导航、脚本和事件属性会被拒绝。前端只发出剥离 DOM 对象的 `extension-event`,当前还没有接回 Wasm 或宿主能力桥,且未接入生产插件生命周期。 - 插件生命周期包括批准前不加载、逐插件/逐权限批准、版本变化重新确认、撤销立即销毁上下文、超时/输出限额/崩溃隔离、旧包兼容和宿主恢复 UI。完整威胁模型、资源耗尽与跨浏览器测试未完成前不启用生产运行开关。 - 复核零新增预算约束:插件及本地素材随皮肤包分发,不依赖 CDN、外部脚本托管或付费沙箱服务。 @@ -62,6 +64,7 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 - 首个 v4 沙箱候选把 opaque-origin iframe 当成了“无网络”边界。复核浏览器规则发现沙箱 frame 仍有自己的文档和 URL 导航能力,`allow-top-navigation` 仅控制顶层页面;当前 MDN browser-compat-data 也没有 `navigate-to` 指令条目。因而 `connect-src 'none'`、禁用表单/弹窗和 CSP 元标签不足以证明获批数据不会通过 frame 导航外传。否决 iframe 直接执行作者 JS 的方案;保留现有只运行于无 DOM Worker 的原型,但 JS 内存无硬上限,继续关闭生产执行。下一步必须通过可计量执行环境承载作者逻辑,并由可信宿主创建/校验通用自定义 UI 树与 CSS,再验证事件到 TeamSpeak 能力的桥接。 - Wasm UI 输出原先经过扩展校验后又送入 v3 固定标签/属性解析器,导致打开节点协议时整份扩展 UI 被悄悄丢弃。现改为分别校验基础皮肤和生成输出,只在组件 ID 不冲突且合并数量有界时组合,并额外把自定义标签渲染为惰性 `div`。目前仍缺用户事件和能力授权桥接,不代表完整运行时已完成。 +- 一次性 Wasm 运行先前没有宿主发回本地界面状态或交互事件的入口。现增加每次调用只读一次、8 KiB 封顶的 `ui_input_read`,并让输出 schema v5 声明命名回调;宿主事件只传安全字段,不信任作者可伪造的“用户手势”标记。现阶段事件只会从 UI outlet 发给组件父级,还未形成重新运行 Wasm 的闭环,不能让插件执行 TeamSpeak 动作,也不能据此打开生产开关。 ### R3.4:声明式自定义节点布局编辑(已实施) @@ -80,7 +83,7 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 - 页面权限确认、撤销入口和“返回标准界面”控件在皮肤 CSS 作用域之外。页面替换被拒绝或退出时,原生首页/语音工作区重新显示。 - 补充导入、旧包兼容、页面替换、权限拒绝/撤销、宿主控件及皮肤切换回归。 - 已提供 v3 首页/语音工作区 surface 样例及 KAAK 语音外观样例;它们验证现有格式,不代表插件系统目标已完成。KAAK 不引入发现、广告、陪玩、活动或商城页面。 -- KOOK 参考皮肤只实现语音客户端体验;不复制运营、广告、陪玩、活动和商城页面。只有能实际查看的公开/授权界面才作为视觉依据。 +- KOOK 参考皮肤只实现语音客户端体验;不复制运营、广告、陪玩、活动和商城页面。当前发现页确实把陪玩匹配、店铺卡片和推荐内容放在独立发现工作流中,这些都不纳入客户端复刻。只有能实际查看的公开/授权界面才作为视觉依据。 #### R4 问题记录 diff --git a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md index 6412327..4964d41 100644 --- a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md @@ -98,5 +98,5 @@ v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦 - 扩展数据字段或宿主动作时,增加精确 schema、权限、明确用户事件约束和宿主侧运行时验证,不暴露内部 SDK 对象。新增宿主控件也必须登记固定 ID、明确页面和确认只在宿主内处理其私有状态;自定义声明式 UI 不应被限制为只能拼装这组控件。 - 对恶意输入、路径别名、拒绝授权、撤销、更新和皮肤切换增加测试;高敏能力必须单独设计。 - 当前 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 字符串。输出 schema v3 仍可使用原有声明式节点;schema v4 允许较完整的安全 HTML/SVG 节点、ARIA/data 属性及包内图片引用。宿主独立校验后创建节点,不把输出当成 HTML 字符串执行;自定义标签映射为惰性宿主 `div`,避免触发页面已注册 Web Component。脚本/框架、事件属性、外部资源和导航目标会被拒绝,非法 JSON/schema、重名组件或超限输出会被丢弃并保留包内 UI。当前 v4 输出仍不能定义事件回调、读取数据、请求皮肤权限、替换页面、嵌入宿主控件或调用 TeamSpeak 动作。Wasm 执行仍未连接到生产客户端;它只是扩宽结构的安全试验,并非完整插件能力。完成有界事件与宿主能力桥、扩展级授权/撤销衔接、资源耗尽测试、端到端验证和独立安全审查之前,不得启用运行开关。 +- Wasm 原型的 `env.ui_emit_json` 每次运行最多提交一次、最多 16 KiB 的 UTF-8 字符串。动态 UI 输出 schema v3 可用原声明式节点;v4 允许较完整的安全 HTML/SVG、ARIA/data 属性与包内图片;v5 再增加本地标量状态和节点事件到处理器 ID 的映射。宿主独立校验后创建节点,不把输出当 HTML 执行;自定义标签映射为惰性宿主 `div`,避免触发页面已注册 Web Component。脚本/框架、事件属性、密码/文件/隐藏输入、外部资源和导航目标会被拒绝。另有 `env.ui_input_read`,每次 Wasm 调用最多读取一次、最多 8 KiB 的状态/事件 JSON;宿主不传 DOM/Event 对象或自报的可信标记。当前 `SkinPluginOutlet` 只把受信用户事件投影成 `extension-event` 发给父组件,生产 WebClient 尚未把它接回 Wasm,也没有权限化宿主动作桥、扩展生命周期或授权/撤销连接。Wasm 仍是生产关闭的安全原型。完成重入闭环、宿主票据/动作校验、权限绑定、资源耗尽测试、端到端验证和独立安全审查之前,不得启用运行开关。 - 商城发布、签名、下架、更新和撤销设计与管理员面板重做一起验收,且保持零新增服务费用为默认约束。 diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index ac1c8ce..7af924f 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -147,7 +147,7 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s 示例包见 [KAAK voice 示例](./examples/KAAK-VOICE.md),其 components.json 展示了公开频道列表和在线成员侧栏;[Open Voice Surface](./examples/OPEN-VOICE-SURFACE.md) 展示了完整首页和语音工作区 surface,是格式验证脚手架。KAAK 的语音视觉参考来自用户授权进入的前两个语音房间;只记录布局,不保留服务器/房间标识、成员名或聊天内容。当前数据权限和宿主动作以[开放皮肤规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)中的清单为准。组件按本地用户授权后才渲染;权限对每个皮肤版本、页面和组件分别保存,可在宿主权限入口撤销。页面替换时,宿主会额外显示“返回标准界面”和“恢复内置皮肤”入口;拒绝授权或离开 surface 后,普通页面可立即恢复。 -组件树有硬上限:components.json 256 KiB。schema v1/v2 上限为 32 个组件、每组件 256 个模板节点、16 层深度和 100 条重复记录;schema v3 上限为 128 个组件、每组件 2048 个模板节点、32 层深度和 250 条重复记录,并允许 64 个本地标量状态与 64 个动作。当前 Wasm 输出的 schema v4 另有 16 KiB 总输出上限、最多 64 个组件、每个节点最多 64 个属性和 256 个子节点,并沿用每组件节点/深度限制;它可使用更广的安全 HTML/SVG 结构、ARIA/data 属性和包内图片。任意自定义元素名称会映射为惰性 `div` 占位,不触发宿主页定义的 Web Component。外部 URL、脚本/框架、事件属性和导航目标会拒绝。该 v4 仅扩大 UI 结构,暂不提供事件回调、数据读取或 TeamSpeak 动作,也未连接生产插件生命周期,不能当作完整插件运行时。 +组件树有硬上限:components.json 256 KiB。schema v1/v2 上限为 32 个组件、每组件 256 个模板节点、16 层深度和 100 条重复记录;schema v3 上限为 128 个组件、每组件 2048 个模板节点、32 层深度和 250 条重复记录,并允许 64 个本地标量状态与 64 个动作。Wasmi 原型动态 UI 输出的 schema v4 有 16 KiB 总输出上限、最多 64 个组件、每个节点最多 64 个属性和 256 个子节点,并沿用每组件节点/深度限制;它可使用更广的安全 HTML/SVG 结构、ARIA/data 属性和包内图片。动态输出 schema v5 再增加本地标量状态及事件名到作者处理器 ID 的映射。宿主只通过 `isTrusted` 用户事件发出剥离 DOM/Event 对象后的 `extension-event`,Wasm 侧只能经 `env.ui_input_read` 一次读取最多 8 KiB 的 JSON。输入字段限长;生成界面中的 password/file/hidden 类型输入会拒绝。自定义元素名称映射为惰性 `div`,外部 URL、脚本/框架、事件属性和导航目标会拒绝。当前事件尚未接回 Wasm 重跑或 TeamSpeak 宿主动作,生产开关仍关闭,不能当作完整插件运行时。 图片资源只能从包内引用,CSS 不能读取外部 URL、脚本或浏览器存储。宿主动作需显式权限,并只能绑定可信的用户事件;输入或 change 事件不能触发宿主动作。focus/blur、hover 和 drag-start/over 等被动事件只可改动组件本地状态,不能触发语音操作。 diff --git a/src/shared/skin-extension-ui-input.ts b/src/shared/skin-extension-ui-input.ts new file mode 100644 index 0000000..b99a952 --- /dev/null +++ b/src/shared/skin-extension-ui-input.ts @@ -0,0 +1,120 @@ +export const SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION = 1 as const; +export const SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES = 8 * 1024; +export const SKIN_EXTENSION_UI_STATE_KEY_LIMIT = 64; +export const SKIN_EXTENSION_UI_EVENT_NAMES = Object.freeze([ + "click", "dblclick", "change", "input", "submit", "keydown", "keyup", "contextmenu", "focus", "blur", + "pointerdown", "pointerup", "pointerenter", "pointerleave", "dragstart", "dragover", "drop", +] as const); + +export type SkinExtensionUiEventName = typeof SKIN_EXTENSION_UI_EVENT_NAMES[number]; +export type SkinExtensionUiScalar = string | number | boolean; + +export interface SkinExtensionUiEventInput { + componentId: string; + handlerId: string; + eventName: SkinExtensionUiEventName; + key?: string; + value?: string; + checked?: boolean; +} + +export interface SkinExtensionUiInput { + schemaVersion: typeof SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION; + state: Record; + event: SkinExtensionUiEventInput | null; +} + +export class SkinExtensionUiInputError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinExtensionUiInputError"; + } +} + +function fail(message: string): never { + throw new SkinExtensionUiInputError("SKIN_EXTENSION_UI_INPUT_INVALID", message); +} + +function isRecord(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function cleanState(value: unknown): Record { + if (!isRecord(value) || Object.keys(value).length > SKIN_EXTENSION_UI_STATE_KEY_LIMIT) { + return fail("UI state must be a bounded scalar object."); + } + const state: Record = Object.create(null) as Record; + for (const [key, entry] of Object.entries(value)) { + if (!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(key) + || (typeof entry !== "string" && typeof entry !== "number" && typeof entry !== "boolean") + || (typeof entry === "string" && entry.length > 1_024) + || (typeof entry === "number" && (!Number.isFinite(entry) || Math.abs(entry) > 1_000_000_000))) { + return fail("UI state contains an invalid key or scalar value."); + } + state[key] = entry; + } + return state; +} + +function cleanEvent(value: unknown): SkinExtensionUiEventInput | null { + if (value === null) return null; + if (!isRecord(value)) return fail("A UI event must be an object or null."); + const allowed = ["componentId", "handlerId", "eventName", "key", "value", "checked"]; + if (Object.keys(value).some((key) => !allowed.includes(key))) return fail("A UI event contains an unsupported field."); + const slug = (entry: unknown): entry is string => typeof entry === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(entry); + if (!slug(value.componentId) || !slug(value.handlerId) + || typeof value.eventName !== "string" + || !(SKIN_EXTENSION_UI_EVENT_NAMES as readonly string[]).includes(value.eventName)) { + return fail("A UI event has an invalid component, handler, or event name."); + } + const event: SkinExtensionUiEventInput = { + componentId: value.componentId, + handlerId: value.handlerId, + eventName: value.eventName as SkinExtensionUiEventName, + }; + if (value.key !== undefined) { + if (typeof value.key !== "string" || !value.key || value.key.length > 32 || /[\u0000-\u001f]/.test(value.key)) { + return fail("A UI event key is invalid."); + } + if (event.eventName !== "keydown" && event.eventName !== "keyup") return fail("Only keyboard events may carry a key."); + event.key = value.key; + } + if (value.value !== undefined) { + if (typeof value.value !== "string" || value.value.length > 2_048) return fail("A UI event value exceeds its limit."); + if (event.eventName !== "input" && event.eventName !== "change") return fail("Only input and change events may carry a value."); + event.value = value.value; + } + if (value.checked !== undefined) { + if (typeof value.checked !== "boolean") return fail("A UI event checked value must be boolean."); + if (event.eventName !== "input" && event.eventName !== "change") return fail("Only input and change events may carry a checked value."); + event.checked = value.checked; + } + return event; +} + +/** Validates bounded local UI state and a single event before it enters the Wasm guest. */ +export function parseSkinExtensionUiInput(input: unknown): SkinExtensionUiInput { + let value = input; + if (typeof input === "string") { + if (new TextEncoder().encode(input).byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) { + return fail("UI input exceeds its 8 KiB limit."); + } + try { value = JSON.parse(input); } + catch { return fail("UI input must be valid JSON."); } + } + if (!isRecord(value) || Object.keys(value).some((key) => !["schemaVersion", "state", "event"].includes(key)) + || value.schemaVersion !== SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION) { + return fail("UI input uses an unsupported schema or contains unsupported fields."); + } + const parsed = { + schemaVersion: SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION, + state: cleanState(value.state), + event: cleanEvent(value.event), + } satisfies SkinExtensionUiInput; + if (new TextEncoder().encode(JSON.stringify(parsed)).byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) { + return fail("UI input exceeds its 8 KiB limit."); + } + return parsed; +} diff --git a/src/shared/skin-extension-ui.ts b/src/shared/skin-extension-ui.ts index 975ef65..644e0e9 100644 --- a/src/shared/skin-extension-ui.ts +++ b/src/shared/skin-extension-ui.ts @@ -7,6 +7,7 @@ import { type SkinPluginDocument, type SkinPluginNode, } from "./skin-plugin.js"; +import { parseSkinExtensionUiInput, SKIN_EXTENSION_UI_EVENT_NAMES } from "./skin-extension-ui-input.js"; export const SKIN_EXTENSION_UI_OUTPUT_LIMIT_BYTES = 16 * 1024; @@ -77,12 +78,12 @@ function onlyKeys(value: Record, allowed: readonly string[], co if (Object.keys(value).some((key) => !allowed.includes(key))) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", `${context} has an unsupported field.`); } -function generatedNode(input: unknown, depth: number, count: { value: number }): SkinPluginNode { +function generatedNode(input: unknown, depth: number, count: { value: number }, allowEvents: boolean): SkinPluginNode { count.value += 1; if (count.value > SKIN_PLUGIN_NODE_LIMIT || depth > SKIN_PLUGIN_TREE_DEPTH_LIMIT || !isRecord(input)) { fail("SKIN_EXTENSION_UI_COMPLEXITY_LIMIT", "The generated UI tree exceeds its node or depth limit."); } - onlyKeys(input, ["tag", "text", "part", "className", "attributes", "asset", "children"], "A generated UI node"); + onlyKeys(input, ["tag", "text", "part", "className", "attributes", "asset", "children", ...(allowEvents ? ["events"] : [])], "A generated UI node"); const hasTag = input.tag !== undefined; const hasText = input.text !== undefined; if (Number(hasTag) + Number(hasText) !== 1) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated node must contain either a tag or text."); @@ -137,6 +138,10 @@ function generatedNode(input: unknown, depth: number, count: { value: number }): attributes[key] = value; } node.attributes = attributes; + if (node.tag === "input" && typeof attributes.type === "string" + && ["password", "file", "hidden"].includes(attributes.type.toLowerCase())) { + fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "Generated input controls cannot collect password, file, or hidden values."); + } } if (input.asset !== undefined) { const asset = boundedText(input.asset, 120, "SKIN_EXTENSION_UI_ASSET_INVALID", "node.asset"); @@ -145,6 +150,20 @@ function generatedNode(input: unknown, depth: number, count: { value: number }): } node.asset = asset; } + if (input.events !== undefined) { + if (!allowEvents || !isRecord(input.events) || Object.keys(input.events).length > SKIN_EXTENSION_UI_EVENT_NAMES.length) { + fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated event callbacks are supported only by UI output schema 5."); + } + const events: NonNullable = {}; + for (const [eventName, handlerId] of Object.entries(input.events)) { + if (!(SKIN_EXTENSION_UI_EVENT_NAMES as readonly string[]).includes(eventName) + || typeof handlerId !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(handlerId)) { + fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated callback uses an unsupported event or handler ID."); + } + events[eventName as keyof typeof events] = handlerId; + } + node.events = events; + } if (input.children !== undefined) { if (!Array.isArray(input.children) || input.children.length > GENERATED_CHILD_LIMIT) { fail("SKIN_EXTENSION_UI_COMPLEXITY_LIMIT", "A generated node has too many children."); @@ -152,12 +171,12 @@ function generatedNode(input: unknown, depth: number, count: { value: number }): if (node.tag && GENERATED_VOID_ELEMENTS.has(node.tag) && input.children.length > 0) { fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Void generated elements cannot contain children."); } - node.children = input.children.map((child) => generatedNode(child, depth + 1, count)); + node.children = input.children.map((child) => generatedNode(child, depth + 1, count, allowEvents)); } return node; } -function parseGeneratedDocument(input: Record): SkinPluginDocument { +function parseGeneratedDocument(input: Record, allowEvents: boolean): SkinPluginDocument { onlyKeys(input, ["schemaVersion", "components"], "Generated UI document"); if (!Array.isArray(input.components) || input.components.length < 1 || input.components.length > GENERATED_COMPONENT_LIMIT) { fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "The generated document has an unsupported component count."); @@ -165,21 +184,28 @@ function parseGeneratedDocument(input: Record): SkinPluginDocum const ids = new Set(); const components: SkinPluginComponent[] = input.components.map((raw, index) => { if (!isRecord(raw)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", `Generated component ${index} must be an object.`); - onlyKeys(raw, ["id", "name", "page", "accessibleName", "root"], "Generated component"); + onlyKeys(raw, ["id", "name", "page", "accessibleName", "root", ...(allowEvents ? ["state"] : [])], "Generated component"); const id = boundedText(raw.id, 64, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "component.id"); if (!/^[a-z][a-z0-9-]*$/.test(id) || ids.has(id)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated component IDs must be unique lowercase slugs."); ids.add(id); const name = boundedText(raw.name, 80, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "component.name"); const accessibleName = boundedText(raw.accessibleName, 120, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "component.accessibleName"); if (raw.page !== "home" && raw.page !== "voice") fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated components may target only the public home or voice page."); - const root = generatedNode(raw.root, 1, { value: 0 }); + const root = generatedNode(raw.root, 1, { value: 0 }, allowEvents); if (!root.tag) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated component root must be an element."); - return { id, name, page: raw.page, accessibleName, permissions: [], actions: Object.create(null) as Record, root }; + const state = allowEvents + ? parseSkinExtensionUiInput({ schemaVersion: 1, state: raw.state ?? {}, event: null }).state + : undefined; + return { + id, name, page: raw.page, accessibleName, permissions: [], actions: Object.create(null) as Record, root, + ...(state ? { state } : {}), + ...(allowEvents ? { runtimeCallbacks: true } : {}), + }; }); return { schemaVersion: 3, components }; } -/** Parses bounded Wasm output. Schema 4 supports broad safe HTML/SVG, data/ARIA attributes, and inert custom-element placeholders. */ +/** Parses bounded Wasm output. Schema 5 adds trusted UI event callbacks and local scalar state. */ export function parseSkinExtensionUiOutput(source: string): SkinPluginDocument { if (typeof source !== "string" || !source.length) { fail("SKIN_EXTENSION_UI_OUTPUT_INVALID", "Extension UI output must be a non-empty JSON string."); @@ -193,7 +219,8 @@ export function parseSkinExtensionUiOutput(source: string): SkinPluginDocument { catch { fail("SKIN_EXTENSION_UI_OUTPUT_JSON", "Extension UI output must contain valid JSON."); } if (!isRecord(input)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Extension UI output must be an object."); - if (input.schemaVersion === 4) return parseGeneratedDocument(input); + if (input.schemaVersion === 4) return parseGeneratedDocument(input, false); + if (input.schemaVersion === 5) return parseGeneratedDocument(input, true); let document: SkinPluginDocument; try { document = parseSkinPluginDocument(input); } diff --git a/src/shared/skin-plugin.ts b/src/shared/skin-plugin.ts index 3db97f9..89a7bf1 100644 --- a/src/shared/skin-plugin.ts +++ b/src/shared/skin-plugin.ts @@ -91,6 +91,8 @@ export interface SkinPluginComponent { accessibleName: string; permissions: SkinPluginPermission[]; state?: Record; + /** Internal marker used only for generated Wasm views; rejected by package JSON validation. */ + runtimeCallbacks?: boolean; actions: Record; root: SkinPluginNode; } diff --git a/web/public/skin-wasm-interpreter.wasm b/web/public/skin-wasm-interpreter.wasm index 66190bc..2bd488f 100644 Binary files a/web/public/skin-wasm-interpreter.wasm and b/web/public/skin-wasm-interpreter.wasm differ diff --git a/web/skin-wasm-interpreter/src/lib.rs b/web/skin-wasm-interpreter/src/lib.rs index 15caf43..b9c890d 100644 --- a/web/skin-wasm-interpreter/src/lib.rs +++ b/web/skin-wasm-interpreter/src/lib.rs @@ -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, status_read_count: u32, + ui_input: Vec, + ui_input_read_count: u32, + ui_input_invalid: bool, ui_output: Vec, 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::::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, + ui_input: Vec, status_permission_granted: bool, memory_maximum_pages: u32, fuel: u64, -) -> Result<(i32, u32, u32, Vec), (u32, u32, u32)> { +) -> Result<(i32, u32, u32, u32, Vec), (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::::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(), )) diff --git a/web/src/components/SkinPluginOutlet.ts b/web/src/components/SkinPluginOutlet.ts index 70d0b4f..fccbc6b 100644 --- a/web/src/components/SkinPluginOutlet.ts +++ b/web/src/components/SkinPluginOutlet.ts @@ -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): void { + if (!component.runtimeCallbacks) return; + const callbackEvent: Record = { 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) { diff --git a/web/src/services/skin-extension-ui.test.ts b/web/src/services/skin-extension-ui.test.ts index 6bd88c1..6a7425e 100644 --- a/web/src/services/skin-extension-ui.test.ts +++ b/web/src/services/skin-extension-ui.test.ts @@ -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) => 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; + text: string; + children: HostNode[]; + parent?: HostNode; + } + const createHostNode = (type: string, text = ""): HostNode => ({ type, props: {}, text, children: [] }); + const renderer = createRenderer({ + 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; event: Record } }; + 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"); diff --git a/web/src/services/skin-extension-wasm-policy.test.ts b/web/src/services/skin-extension-wasm-policy.test.ts index df42653..727c8ea 100644 --- a/web/src/services/skin-extension-wasm-policy.test.ts +++ b/web/src/services/skin-extension-wasm-policy.test.ts @@ -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, }); diff --git a/web/src/services/skin-extension-wasm-policy.ts b/web/src/services/skin-extension-wasm-policy.ts index f9f64cd..4d9f615 100644 --- a/web/src/services/skin-extension-wasm-policy.ts +++ b/web/src/services/skin-extension-wasm-policy.ts @@ -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([ [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 }; } diff --git a/web/src/services/skin-extension-wasm-sandbox.test.ts b/web/src/services/skin-extension-wasm-sandbox.test.ts index 9222a43..e8831a6 100644 --- a/web/src/services/skin-extension-wasm-sandbox.test.ts +++ b/web/src/services/skin-extension-wasm-sandbox.test.ts @@ -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" }); +}); diff --git a/web/src/services/skin-extension-wasm-sandbox.ts b/web/src/services/skin-extension-wasm-sandbox.ts index 7dd4e2b..76b286d 100644 --- a/web/src/services/skin-extension-wasm-sandbox.ts +++ b/web/src/services/skin-extension-wasm-sandbox.ts @@ -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; /** 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, diff --git a/web/src/services/skin-extension-wasm-worker.ts b/web/src/services/skin-extension-wasm-worker.ts index 36d9eba..022045c 100644 --- a/web/src/services/skin-extension-wasm-worker.ts +++ b/web/src/services/skin-extension-wasm-worker.ts @@ -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) => { 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 { async function run(job: RunMessage): Promise { 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 { 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 { 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 { 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 { 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."); } diff --git a/web/src/services/skin-wasm-interpreter.test.ts b/web/src/services/skin-wasm-interpreter.test.ts index afae9de..7dd1ae9 100644 --- a/web/src/services/skin-wasm-interpreter.test.ts +++ b/web/src/services/skin-wasm-interpreter.test.ts @@ -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, diff --git a/web/test/skin-extension-wasm-fixture.ts b/web/test/skin-extension-wasm-fixture.ts index 53ab6d7..780ce54 100644 --- a/web/test/skin-extension-wasm-fixture.ts +++ b/web/test/skin-extension-wasm-fixture.ts @@ -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,