diff --git a/.gitignore b/.gitignore index b93b382..a0738c4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ node_modules/ dist/ web/dist/ +web/skin-wasm-interpreter/target/ mobile/node_modules/ web/android/.gradle/ web/android/build/ diff --git a/README.md b/README.md index 8f2cf7e..a25f777 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,8 @@ - [Русский](./docs/README.ru.md) - [日本語](./docs/README.ja.md) - [皮肤开发规范 / Skin Development Guide](./docs/SKIN_DEVELOPMENT.md) +- [更开放的皮肤系统路线图](./docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md) +- [更开放的皮肤系统规格与权限沙箱](./docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md) - [皮肤开发 Agent Skill / Skin Development Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md) ## 社区 · Community diff --git a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md new file mode 100644 index 0000000..f543f35 --- /dev/null +++ b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md @@ -0,0 +1,85 @@ +# 更开放的皮肤系统路线图 + +状态:R0–R2 已在 `skilV2` 分支实现并验收;R3 的 JavaScript / Wasm 安全原型已在本机 Chrome、Edge 和 Codex 内置浏览器通过 19 项测试。Wasm 原型改由固定 Wasmi 解释器处理作者二进制,并为解释器内存与执行 fuel 设置硬上限;生产扩展仍保持关闭,等待产品接入和独立安全评审。浏览器不提供整个进程 RSS 配额,因此不宣称进程级 RSS 上限。商城与管理员面板改造依照用户决定留待后续管理员面板重做。 + +本文与[更开放的皮肤系统规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)配套。商城目录和管理员界面改造暂不在本阶段实现,计划在管理员面板重做时一起交付。 + +## 目标 + +让公开客户端的页面组件可以由用户选择、摆放、缩放、设定样式和显隐;基础组件继续由 WebSpeak 提供,任何皮肤都不能替换其行为或永久移除它。长期允许第三方扩展提供自定义组件,但扩展必须通过明确的权限边界与沙箱运行。 + +本路线以安全和可维护为约束: + +- 管理后台 /admin/** 不属于皮肤范围。 +- 第一阶段只执行受验证的声明式布局和视觉配置,不执行皮肤作者提供的 JavaScript。 +- 不因本功能增加付费服务、域名、存储或服务器费用。商城和分发后续优先复用公开仓库及现有免费能力;若免费方案不满足规模要求,不能自动改用付费服务。 +- 继续识别当前 schemaVersion 为 1 的 .wskin 包;升级格式时必须有兼容和回退路径。 + +## 当前基线 + +当前 .wskin 是 ZIP 包,含 manifest.json、CSS、可选文案和包内素材。运行时校验包大小、路径、CSS 选择器、布局相关属性及资源 URL,再将样式限制在公开皮肤根节点。当前格式不提供组件排列和尺寸控制,不允许运行皮肤脚本;管理员面板使用独立样式。 + +CSS 作用域与校验可以降低意外影响,但样式仍运行在应用页面中,不能视为抵御恶意代码的完整安全沙箱。下一版布局能力应由宿主解析声明式数据并创建宿主组件,不通过放宽 CSS 黑名单来实现。 + +当前实例皮肤目录由 WebSpeak 服务端提供,管理员皮肤界面管理实例包。公共商城是独立的目录与发布问题,留到管理员面板重做时确定。 + +现行格式、控件钩子和限额见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。 + +## 阶段 + +### R0:边界与威胁模型(已完成) + +- 定义组件注册表、必要组件、可信宿主 UI、布局格式和插件权限。 +- 明确声明式皮肤和可执行扩展是两类不同能力。 +- 记录管理员后台排除项、零新增预算约束和 v1 兼容策略。 + +**完成条件:** 规格文档评审完成;任何实现任务都能明确指出影响的组件、权限和回退行为。 + +### R1:稳定的公开组件注册表(已完成) + +- 为公开页面组件分配稳定 ID,并验证所有公开 `data-ws-part` 均已登记;管理员页面不进入注册表。 +- 将必要组件、可选组件、可信安全 UI 分开登记。 +- 明确组件的键盘操作、焦点顺序、屏幕阅读器名称和窄屏最小尺寸。 +- 把目前分散的 data-ws-part 逐步映射到注册表;现有 CSS 钩子在迁移期保持有效。 + +**已实现并验证:** 226 个公开组件 ID 均有可读名称、用途、分类、页面根容器、可编辑能力、数据敏感级别、键盘/焦点/无障碍策略、窄屏策略、尺寸与触控范围、样式令牌元数据。可信组件的布局模式、样式令牌和容器权限为空;可信祖先中的通用控件也不能绕过保护。模板扫描验证所有公开 `data-ws-part` 均登记,并检查带原生交互语义、键盘操作或拖放能力的钩子具备至少 44px 的触控尺寸和 1 倍最小缩放。布局运行时现在对所有可编辑交互组件始终执行注册表的 44px 最小命中区域,不要求用户先保存布局覆盖。演示页语音卡片已补键盘操作和可见焦点环。服务端与客户端共用相同注册表校验。 + +### R2:声明式布局与本地自定义(已完成) + +- 引入新版本布局清单,以注册表中的组件 ID 描述位置、尺寸、缩放、颜色、显隐和响应式配置。 +- 为桌面、平板和手机提供独立布局配置;坐标由宿主限制在有界数值内。 +- 提供本地布局编辑、撤销/重做和恢复默认布局的能力。 +- 位置、尺寸、显隐由布局配置表达,继续拒绝皮肤 CSS 覆盖几何和交互区域。 +- 个人编辑保存在浏览器本地,和皮肤包作者的默认布局分开;支持导入、导出与版本迁移。 + +**已实现并验证:** schema v2 声明式布局、桌面/平板/手机独立配置、直接拖动和属性编辑、本地撤销/重做、恢复默认、导入/导出;编辑器恢复入口和皮肤加载错误恢复提示都由宿主在皮肤根节点外渲染;v1 视觉皮肤继续受支持。坐标滑块和拖动都按页面根容器边界限制;触控控件不能缩到 44px 以下;编辑器可提示碰撞/溢出,并允许仅对当前布局忽略提示。新增焦点辅助预览:按浏览器顺序编号可布局的键盘控件,叠加实际命中区域并明确标出小于 44×44px 的目标;尺寸由布局运行时在默认状态和自定义布局下共同保证。失败的自定义皮肤会自动回退,并提供可信的一键切换到内置皮肤且记住选择的入口。本地演示页已确认焦点列表与覆盖层正常;测试覆盖焦点顺序算法、默认触控尺寸与 trusted-chrome 排除、皮肤加载失败回退和内置皮肤恢复。布局存储测试覆盖 v1 到当前存储格式迁移、无效项恢复导出、旧键备份及未来格式保护。ILLUSIA 已转换为 v2 布局皮肤并在浏览器中验证样式和包内素材正常加载。 + +### R3:扩展 API 与权限代理(仅在 R2 稳定后) + +- 首先发布无代码的布局和样式能力,不因用户期待插件化而提前执行任意脚本。 +- 若要允许扩展代码,先实现隔离运行时、能力权限账本、宿主 API 代理、权限撤销和资源配额。 +- 扩展通过版本化消息协议请求能力;宿主逐次校验,而不是把 DOM、浏览器存储、网络或媒体对象直接交给扩展。 +- 先以只读、低敏的会话状态能力做原型。私聊、身份、网络、麦克风、屏幕共享和命令执行须独立评审,不随一般 UI 权限自动开放。 + +**完成条件:** 隔离原型通过针对 DOM 访问、同源访问、未授权网络、消息伪造、恶意高频请求、权限撤销和升级增权的安全测试;不满足时保持禁用可执行扩展。 + +**当前原型与验收:** JavaScript 原型验证不透明 sandbox iframe、Worker 隔离、精确 `WindowProxy` / `null` origin / 随机 nonce 握手、独占 MessagePort、权限代理、撤权和消息配额。另有 Wasm-only 一次性运行原型:源码最多 256 KiB,预检最多 128 个函数、每个函数体最多 32 KiB、代码段最多 192 KiB、自定义段最多 8 个;函数签名每类值最多 64 个,整个模块的局部值最多 4096 个、每个函数最多 256 组;仅接受数字标量类型和受支持的核心指令,预检拒绝 GC / 引用 / SIMD / 线程类型与指令、start 函数、表元素段及未知扩展指令,以防越过线性内存限制或在执行前造成无界初始化。作者 Wasm 字节不会交给浏览器原生 Wasm 编译器,而是在 Worker 中交给固定版本 Wasmi 解释器解析和执行;解释器自身线性内存最多 64 MiB,获批扩展的宿主 `env.memory` 最多 64 页 / 4 MiB,每次执行最多 10,000,000 fuel。解释器采用 portable-dispatch,避免 wasm32 默认递归分发随每条指令耗尽调用栈。运行时只接受可选的获批状态读取导入,只允许单一 `run` 导出;3 秒期限覆盖 Worker 和解释器初始化,100 毫秒宿主看门狗作为 fuel 之外的后备保护。宿主保留脱敏快照副本,Wasm 无法通过改写线性内存伪造宿主返回值。浏览器安全页的 19 项用例已在 Chrome for Testing 155.0.8059.39、Edge 和 Codex 内置浏览器全部通过,涵盖 DOM/存储/同源/网络/导航隔离、伪造握手、未授权能力、撤权及取消待处理读取、高频请求、4 MiB 内存、fuel 死循环、GC 分配、超大签名/局部/元素向量、状态篡改和 start 函数拒绝。生产运行时仍关闭;原型尚无 UI 渲染 API、授权界面或产品接入。 + +**完成状态与边界:** R3 的开发原型已满足本阶段完成条件:三种浏览器中的 19 项安全页测试均通过,作者 Wasm 的解析与执行、guest memory、fuel、权限代理和可终止 Worker 均有明确限制。它不构成浏览器进程 RSS 配额,也不覆盖浏览器引擎漏洞;生产扩展保持关闭,直到产品 API、授权 UI、故障恢复流程完成接入并经过独立安全评审。此阶段不引入付费基础设施。 + +### R4:皮肤商城与管理员面板重做时交付 + +- 目录、包分发和运行时安装使用平台无关的清单协议。 +- 先以人工审查和版本化公开目录发布;支持兼容版本、来源、许可证、校验值、信任标签、下架和撤销记录。 +- 商城配置和管理随管理员面板重做设计,但管理后台本身仍不可被皮肤化。 +- 默认使用现有公开 GitHub 仓库或经确认的免费静态能力;皮肤包优先作为版本化 Release 附件。不得把内部服务器地址、密钥、测试节点或其他私密配置放入公共目录。 +- 暂不承诺评分、评论、自动付款、付费托管或第三方账号接入。 + +**完成条件:** 用户能查看来源和权限、安装/更新/卸载/回退;管理员能处理下架和撤销;离线或目录不可用时,已安装皮肤可安全回退。 + +## 迁移与发布策略 + +- v1 .wskin 继续作为视觉皮肤兼容格式;不得把原有 CSS 静默解释成新的布局权限。 +- 新格式使用单独的 schema 版本。未知版本、未知组件、未知权限和超出限额的包必须失败关闭,并提供可理解的错误。 +- 新包加载失败、兼容性不符或插件崩溃时,回退到宿主默认布局;用户数据和 TeamSpeak 会话状态不得因皮肤故障丢失。 +- 每个阶段单独验收,相关变更合并后统一运行验证;皮肤系统之外的语音、服务器管理或 Android 功能不借此扩展。 diff --git a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md new file mode 100644 index 0000000..449fe44 --- /dev/null +++ b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md @@ -0,0 +1,195 @@ +# 更开放的皮肤系统规格 + +状态:实现规格 0.2;R0–R2 的 schema v2 声明式布局已实现,R3 扩展沙箱仍为默认关闭的开发原型。配套阶段与未完成项见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)。 + +## 1. 范围 + +本规格针对 WebSpeak 公开客户端页面:连接首页、语音工作区及公开演示页面。管理员后台 /admin/** 明确排除,不读取皮肤布局、样式或插件配置。 + +目标是让页面组件可以自由组合和个性化,同时保留 WebSpeak 对基础组件、状态和行为的所有权。长期目标可以支持第三方扩展组件,但组件扩展必须处于受限沙箱中。 + +当前实现范围: + +- 为公开页面登记稳定组件 ID,并在服务端和客户端共同校验布局数据。 +- 支持不运行作者代码的皮肤布局能力和本地用户覆盖。 +- 保留 v1 视觉皮肤兼容;v2 只接受 `layout-skin` 且 `permissions` 必须为空。 +- 为后续扩展 API 和商城定义安全前提。 + +明确不在本轮范围: + +- 皮肤商城、公共目录运营和管理员面板重做;它们在后续阶段一起规划交付。 +- 将管理员面板开放给皮肤。 +- 在公开页面执行任意 HTML、Vue 模板、JavaScript、WebAssembly 或远程脚本。 +- 允许皮肤读取或控制 TeamSpeak 私钥、凭据、服务器配置、管理 API、原始音频流或屏幕流。 +- 引入付费托管、CDN、域名或新的服务器费用。 + +## 2. 核心术语与不变量 + +**宿主**指 WebSpeak 本身,包括组件注册表、页面结构、状态管理、权限判断和受信任的系统控件。 + +**基础组件**指 WebSpeak 提供并负责维护的组件。它们始终存在于应用组件注册表中,不能被皮肤删除、替换成作者代码或改写行为。皮肤可提供默认布局,用户可调整其显示、位置、尺寸和样式。即使用户把基础组件从当前布局隐藏,也必须能从不受皮肤控制的恢复入口重新显示或恢复默认布局。 + +**布局皮肤**指由清单、布局 JSON、受限样式和本地素材组成的声明式包。它不运行作者脚本,不因安装而取得应用数据权限。 + +**扩展插件**指未来可能提供自定义展示或能力的独立代码包。插件与布局皮肤分开授权、分开运行;安装一个布局皮肤不能隐式安装或启用插件代码。 + +以下不变量必须成立: + +1. 皮肤故障不能断开语音、改变 TeamSpeak 权限、启动麦克风或屏幕共享,也不能绕过宿主确认流程。 +2. 组件的业务逻辑、事件监听和 TeamSpeak 命令始终由 WebSpeak 实现。布局只能请求显示宿主注册组件,不能提供一套替代逻辑。 +3. 用户始终能退出当前布局、恢复默认布局和撤销插件权限;这些恢复控件不受皮肤布局和样式控制。 +4. 权限提示、身份/私钥安全提示、连接安全状态和管理员入口属于宿主可信 UI,不由皮肤绘制、覆盖或拦截。 +5. 新格式按未知即拒绝处理;只有宿主版本支持的组件、布局节点、令牌和权限才能生效。 + +## 3. 组件注册表 + +每个公开组件由宿主登记稳定 ID 和受控元数据,至少包含: + +- id、用户可读名称、所属页面和用途。 +- 分类:core、optional 或 trusted-chrome。 +- 可用父容器/插槽、允许的布局模式和尺寸范围。 +- 可公开调整的外观令牌及其值类型/范围。 +- 可展示的数据字段及其敏感级别。 +- 键盘操作、焦点规则、无障碍名称和窄屏约束。 +- 可触发的宿主动作标识;布局不能任意调用命令。 + +布局引用 ID,不引用 Vue class、私有 DOM 结构或内部服务名称。未知、已移除或不兼容的 ID 在校验时拒绝,不能降级为任意 HTML。旧 data-ws-part 在迁移期保持为 CSS 兼容钩子,并逐步对应注册表 ID。 + +trusted-chrome 不属于可布局组件。恢复布局、权限审批、安全提示和管理员导航由宿主独立渲染。基础组件可在用户布局中隐藏,但不从注册表和编辑器中删除;每次应用重启后,宿主仍能通过固定恢复入口找回。 + +## 4. 布局与外观模型 + +### 4.1 声明式布局 + +布局由宿主解释为组件树。节点仅允许引用注册组件和受支持的容器类型,例如 stack、grid、dock、overlay;不允许嵌入 HTML 字符串、事件代码、表达式求值或动态模块。 + +布局可以为每个组件指定: + +- visible:默认是否显示。 +- order、group:排列和分组。 +- placement:所在区域或相对于父容器的位置。 +- size:受组件约束的宽高或尺寸等级。 +- style:注册表允许的外观令牌。 + +为实现自由摆放,可提供容器相对的锚点/比例坐标以及可选重叠层;不能让作者直接注入 position: fixed 等任意 CSS 几何规则。编辑器应展示碰撞、越界、文字遮挡和小屏溢出检查,并允许用户选择忽略非关键提示。 + +### 4.2 响应式布局 + +布局包可为桌面、平板、手机声明不同配置,并可指定合理的宿主断点。小屏布局不能仅靠缩放桌面坐标推导。组件移动、尺寸与显隐设置按当前布局配置保存;切换设备宽度不得清除用户配置。 + +布局坐标必须相对于明确容器,并由宿主限制在可用视区内。用户可以有意重叠组件,但必须能从编辑器或恢复入口解除遮挡。恢复入口和可信系统控件不参加用户坐标变换。 + +### 4.3 用户配置与作者默认值 + +皮肤包只提供作者默认布局。用户编辑产生本地覆盖层,按皮肤 ID、布局 schema 版本、页面和设备配置隔离保存。加载作者新版时,不得静默覆盖用户布局;只迁移仍匹配的组件与属性,并保留可恢复的旧配置或提示迁移失败。 + +用户配置应能导出/导入为数据文件。导入时重新验证组件、坐标、尺寸、样式令牌和限制,不能因为文件来自本地就跳过校验。 + +### 4.4 样式 + +几何布局、显隐和排序以结构化布局字段表达;颜色、背景、字体、圆角、阴影和受限动效以注册令牌或作用域 CSS 表达。优先使用组件令牌,避免让所有皮肤依赖实现细节选择器。 + +视觉 CSS 继续限制在公开皮肤根节点和稳定钩子内;只能引用包内素材。解析器应逐步采用属性/值白名单、函数与选择器限制、复杂度配额,而不是依赖不断扩大的黑名单。布局引擎负责位置和命中区域,因此样式 CSS 不能覆盖布局几何、焦点、可交互区域或可信 UI。 + +## 5. 包格式与兼容 + +新包必须使用独立 schema 版本,并声明包类型。布局皮肤与扩展插件必须可分别验证和安装。字段示意如下,最终字段名由 R1/R2 实现评审固定: + + { + "schemaVersion": 2, + "packageType": "layout-skin", + "id": "author.example-layout", + "version": "1.0.0", + "minAppVersion": "0.2.7", + "entry": "skin.css", + "layout": "layout.json", + "permissions": [] + } + +布局皮肤不得声明可执行权限;其 `permissions` 必须为空。当前 v2 清单拒绝未定义字段,以免未来能力字段被旧客户端静默忽略。未来插件必须使用独立包类型、API 版本和逐项权限审批,不得复用布局皮肤的信任模型。 + +当前 schemaVersion 为 1 的 .wskin 保持可安装和可运行。v1 CSS 不会因此取得几何布局权限;迁移到新布局包是显式操作,预览后由用户确认。新包校验失败、最低客户端版本不符或激活超时,保留用户最后可用配置并回退到宿主默认外观。 + +继续沿用当前归档安全要求:限制压缩包和解压大小、文件数、路径长度与 CSS 复杂度;拒绝路径穿越、重复路径、符号链接、超出白名单的文件类型、远程资源和可执行 CSS。具体上限按当前皮肤开发规范维护并在版本发布时测试。 + +## 6. 权限与沙箱 + +### 6.1 权限级别 + +| 能力 | 布局皮肤 | 未来扩展插件 | 原则 | +| --- | --- | --- | --- | +| 组件摆放、尺寸、显示/隐藏和外观 | 允许 | 允许 | 只能操作注册组件和 schema 允许的令牌;基础组件仍可恢复 | +| 读取静态、非敏感的页面状态 | 无运行代码 | 逐项申请 | 只通过宿主 API;只提供完成该组件所需的最小字段 | +| 频道成员、当前频道、发言状态 | 不适用 | 默认拒绝,按能力单独授权 | 绑定当前会话,断开后立即失效 | +| 频道聊天、私聊、身份资料 | 不适用 | 默认拒绝,分别授权 | 私聊和身份视为高敏数据;不得批量导出 | +| 网络请求 | 仅包内素材 | 默认拒绝 | 需要时由宿主代理并按精确来源授权,不允许插件自行访问任意 URL | +| 插件本地存储 | 无 | 默认关闭或严格配额 | 按插件 ID 隔离;不能读取网页 localStorage、Cookie、IndexedDB 或其他插件数据 | +| 调用宿主动作/TeamSpeak 命令 | 不允许 | 默认拒绝 | 插件只能提交意图;宿主在用户操作和自身策略下决定是否执行 | +| 麦克风、音频轨道、屏幕采集 | 不允许 | 不向插件暴露原始对象 | 延续浏览器和宿主的用户授权;插件不能静默开始、旁听或共享 | +| 私钥、访问令牌、Cookie、管理 API、文件系统 | 不允许 | 永久禁止 | 这些数据和接口不属于插件能力模型 | +| 管理后台和管理数据 | 不允许 | 永久禁止 | /admin/** 与管理 API 不进入插件运行环境 | + +能力名称必须精确、可审计,禁止通配符授权。任何权限都默认拒绝;包作者只能声明请求,不能自行授予。用户拒绝某项权限后,插件必须仍能提供不依赖该能力的功能,或清楚说明该功能不可用。 + +建议的首批权限 ID 为 session.status.read、session.members.read、chat.channel.read、chat.private.read、identity.profile.read、network.fetch 和 storage.private。权限 ID 及其数据字段范围必须由宿主版本化登记;network.fetch 还必须绑定明确来源。不得提供通用的 admin、filesystem、credentials、media.raw 或 teamspeak.command 权限。即使未来存在网络权限,也不得默认把私聊、身份或凭据数据交给网络请求;跨越这两类能力需要单独的风险提示和明确批准。 + +基础动作组件仍由宿主渲染和处理。用户点击一个宿主提供的麦克风、离开或频道按钮,不等于把对应动作 API 授给皮肤;扩展不能在后台直接调用同一动作。 + +### 6.2 可信边界 + +当前皮肤 CSS 在应用文档中加载。根节点作用域、CSS 解析器和路径校验是输入限制,不是浏览器安全沙箱;恶意视觉规则仍可能误导用户或妨碍操作。因此: + +- 第一阶段不执行第三方 JavaScript、WebAssembly 或 HTML 模板。 +- 权限提示、恢复入口、可信状态和管理 UI 必须脱离可皮肤化根节点渲染。 +- 对布局几何、隐显和交互命中区域的控制由宿主布局引擎实现,避免依赖主页面 CSS。 +- CSS、文案和图片均视为不可信输入,分别经过 schema、解析器和资源校验。 + +当前只有开发安全原型,尚未接入皮肤安装流程或公开页面运行时。JavaScript 原型使用不透明源的 sandbox iframe 作为**受信任引导壳**,只授予 `allow-scripts`,不授予 `allow-same-origin`、顶层导航、弹窗、表单提交、下载或媒体权限。作者 JavaScript 在独立 Worker 中执行;Worker 没有 DOM、`window`、网页存储或应用全局对象。Worker 侧隐藏网络、子 Worker、IndexedDB、Cache Storage 和 WebAssembly 等全局,CSP 作为纵深防御拒绝网络、远程脚本、图片、媒体和子框架。此前实测发现目标浏览器没有按预期执行 `navigate-to 'none'`,因此隔离不依赖该指令:不可信代码位于 Worker,不能自行导航壳页面。宿主绑定精确 iframe `WindowProxy`、opaque `null` origin、一次性 nonce 和单一转移端口后改用独占 `MessageChannel`;壳只转发固定格式的能力请求,不接收任意 HTML 或代码作为渲染指令。撤权和关闭会通知壳调用 `Worker.terminate()`,并在短超时后由宿主移除 iframe。这个 JavaScript 原型用于验证隔离与消息协议,因普通 Worker 没有硬内存配额,不可用于生产。 + +另有一个 Wasm-only 运行原型:扩展包仅提供最多 256 KiB 的 Wasm 二进制,不执行作者 JavaScript。Worker 先做有界预检,最多接受 128 个函数、单个函数体 32 KiB、代码段总计 192 KiB 和 8 个自定义段;类型只接受函数签名和数字标量,每个签名最多 64 个参数/结果值,整个模块最多 4096 个局部值、每个函数最多 256 组。指令扫描拒绝 GC / 引用 / SIMD / 线程类型与指令、start 函数、表元素段和未知扩展指令。作者二进制不会交给浏览器的原生 Wasm 编译器,而由固定版本的 Wasmi 解释器解析与执行;解释器容器本身的 Wasm 线性内存上限为 64 MiB,guest 只能使用一块宿主提供的 `env.memory`,上限 64 页(4 MiB)。运行时只接受可选且经 `session.status.read` 授权的状态读取导入,并只允许一个 `run` 函数导出。Worker 和受信解释器初始化期限为 3 秒;开始运行后,Wasmi 每次最多消耗 10,000,000 fuel,宿主另以 100 毫秒 Worker 看门狗兜底。跨 Worker 消息最多 8 KiB,状态快照最多 512 字节、最多读取 10 次。授权快照由宿主持有,Wasm 只能收到拷贝,不能通过篡改线性内存改写宿主返回值。该原型仍是一次性安全演示,没有 UI 渲染 API、授权界面或产品接入。 + +解释器容器的 64 MiB Wasm 上限与 guest 的 4 MiB 线性内存上限,能限制作者模块解析和执行期间由 Wasmi 分配的内存;作者字节不会触发浏览器对不可信模块的原生编译开销。浏览器仍没有普通 Worker 的进程级 RSS 配额,因此这不等于限制整个浏览器进程的 RSS,也不能抵御浏览器引擎或受信解释器本身的漏洞。10,000,000 fuel 是执行指令预算;100 毫秒墙钟看门狗是额外的 Worker 终止保护。生产扩展运行时仍保持关闭,直到产品 API、授权 UI、故障恢复流程完成接入并通过独立安全评审。安全页的 19 项用例已在 Chrome for Testing 155.0.8059.39、Edge 和 Codex 内置浏览器通过;这仅确认本机版本,不代表不同操作系统或未来版本均已验收。浏览器用例通过不等于安全审计。 + +插件不得直接访问宿主 DOM、Vue 实例、全局变量、Cookie、浏览器持久化区、应用请求客户端或 TeamSpeak SDK。宿主通过专用消息通道提供版本化、带 schema 的能力 API。每次请求均按插件 ID、当前会话、已批准能力和用户操作重新判断;校验调用方窗口/消息源、请求大小、频率和数据范围。初始化握手须绑定该 iframe 的 window source 和单次随机 nonce,成功后转交独占的 MessageChannel;不能只依赖 opaque iframe 的 origin 值,也不能通过通配 postMessage、共享对象引用或未校验事件回调授权。 + +### 6.3 授权生命周期 + +1. 安装/启用时展示发布者、来源、包版本、完整权限清单和风险级别。 +2. 仅声明权限不等于获准。对高敏权限,应在首次使用前单独解释其用途并取得明确同意。 +3. 插件版本升级后若权限增加或权限含义变化,必须重新征求同意;用户已有的无关授权不能扩大。 +4. 用户撤销权限时,宿主立即拒绝后续调用、停止插件执行并丢弃该权限下的临时数据。 +5. 卸载时停止计时器、消息订阅和 UI,删除该插件命名空间内的存储;不改动其他皮肤、插件或 WebSpeak 数据。 +6. 权限决定保存在本地;不得为了商城分析而上传用户身份、会话或权限记录。 + +### 6.4 资源与滥用控制 + +布局和样式包沿用当前皮肤包体积限制,并为新格式增加节点数、嵌套深度、属性数、动画数和素材总量上限。插件执行环境需设置消息频率、单次消息大小、启动期限和停用/重启上限。 + +JavaScript 隔离原型限制源码为 64 KiB、单条消息为 8 KiB、最多 10 条 API 请求/秒和 10,000 条总请求;Worker 最多保留 16 条未完成请求。该 JavaScript 执行原型仍因没有硬内存配额而保持关闭。Wasm-only 原型限制二进制为 256 KiB、函数最多 128 个、单函数体最多 32 KiB、代码段最多 192 KiB、自定义段最多 8 个、签名每类值最多 64 个、模块局部值最多 4096 个、每函数最多 256 组;解释器容器最多 64 MiB,guest 线性内存最多 4 MiB,每次运行最多 10,000,000 fuel,并有 3 秒初始化期限和 100 毫秒 Worker 看门狗。跨 Worker 消息最多 8 KiB,状态快照最多 512 字节、最多读取 10 次。预检只接受数字标量和受支持核心指令,拒绝 GC / 引用 / SIMD / 线程、start 函数、表元素段和未知扩展指令。浏览器不提供普通 Worker 的进程级 RSS 配额,因此规格只承诺上述解释器和 guest 边界,不声称能限制浏览器进程 RSS。Wasm 仍为开发原型,接入前须完成独立安全评审和产品生命周期设计。安全测试覆盖高频消息、解释器与 guest 内存边界、fuel 死循环、GC/超大向量声明、函数数量与函数体复杂度、数据范围、伪造握手、未授权能力和撤权终止。 + +### 6.5 发布者与包信任 + +包校验值只能说明下载字节与目录记录一致,不能证明作者可信或代码安全。未来商城至少应显示来源、版本、许可证、权限和校验状态;签名可用于验证发布来源,但不能替代沙箱和权限审核。下架或撤销应记录包 ID 与受影响版本,并让客户端在下次可联网时停止建议/更新该版本;离线运行时仍须允许用户卸载或回退。 + +## 7. 失效、恢复与无障碍 + +- 布局 JSON 无效、组件不存在、加载超时或插件崩溃时,回退到宿主默认布局;不得阻断连接页或会话恢复。 +- 恢复入口始终可通过键盘和触屏操作,提供明确名称、焦点样式和屏幕阅读器标签。 +- 布局编辑器必须显示当前焦点顺序与触屏命中区域预览;不能只检查视觉坐标。 +- 用户可保存桌面和移动布局;窄屏状态下关键操作至少存在可访问路径。 +- reduced-motion 偏好、语言变化、文本扩展和浏览器缩放不能导致安全/恢复 UI 消失。 +- 皮肤/插件错误只显示在宿主可信提示区域,并允许一键停用对应包。 + +当前编辑器的焦点辅助预览按浏览器顺序列出公开页面中可布局的键盘目标,并在宿主层叠加实际命中矩形;小于 44×44 CSS px 的目标以红色显示。注册表约束在默认布局和个人覆盖下都执行。编辑器面板不使用动效,语言随页面 `lang` 变化,焦点列表支持长文本换行,固定恢复入口位于皮肤根节点之外。自定义皮肤加载失败时页面自动回退,并在宿主可信提示层提供记住内置皮肤选择的一键操作;此操作停用当前选择,不会在服务端目录中禁用或删除皮肤包。 + +## 8. 安全验收清单 + +每次开放新的布局或权限能力前,至少验证: + +- 不存在读取 /admin/**、管理 API、DOM 外部根节点、Cookie、localStorage 或 TeamSpeak 凭据的路径。 +- 未授权插件不能联网、读取聊天/身份数据、接收原始音频或启动屏幕采集。 +- 权限增加、拒绝、撤销、卸载和更新竞态不留下旧订阅或迟到回调。 +- 恢复入口、权限提示、身份安全提示、焦点可见性和基础组件可恢复。 +- 未知 schema、权限、组件、文件类型、路径穿越、压缩炸弹、极端嵌套和超大消息均安全失败。 +- 布局在五种产品语言、键盘导航、窄屏、触屏和浏览器缩放下仍能使用。 +- 新布局能力没有扩大管理员页面或语音服务端的工作范围。 diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index 0025424..1717cea 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -4,6 +4,8 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。 +当前皮肤包的实现规则见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。声明式布局已实现;扩展插件权限沙箱仍为默认关闭的开发原型,阶段状态和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。 + ## 在线 Demo 地址: diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index ceeb300..f7ed99d 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -1,6 +1,8 @@ # WebSpeak 皮肤开发规范 -本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。 +本文说明仍受支持的 v1 视觉皮肤包,以及已实现的 v2 声明式布局皮肤。v1 继续保持固定组件布局;v2 可调整公开组件的位置、尺寸、显隐和外观,但不执行作者代码。路线和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。 + +`.wskin` 包可为公开页面定制艺术表现。v1 保持 WebSpeak 的固定布局;v2 另外携带受校验的布局 JSON,并可由用户在浏览器本地继续调整。两种格式均不允许皮肤替换宿主组件或改变 TeamSpeak 行为。 页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。** @@ -32,11 +34,11 @@ assets/brand.woff2 # 可选:自带字体 ```json { "schemaVersion": 1, - "id": "community.illusia-voice", - "name": "ILLUSIA风", - "version": "1.0.28", - "author": "WebSpeak Project", - "license": "All rights reserved", + "id": "community.example-skin", + "name": "Example skin", + "version": "1.0.0", + "author": "Example author", + "license": "CC-BY-4.0", "description": "A visual-only art skin using the WebSpeak interface translations.", "entry": "skin.css", "preview": "assets/background-composite.webp", @@ -57,6 +59,50 @@ assets/brand.woff2 # 可选:自带字体 清单不得重复声明同一个文件为 CSS、内容或预览入口。 +### schemaVersion 2:声明式布局皮肤 + +v2 为 v1 增加一个必需布局文件。清单和布局 JSON 会在导入端及服务端分别验证;未知清单字段、权限、组件、布局字段及越界数值都会导致包被拒绝。v2 不支持 HTML、JavaScript、WebAssembly、远程资源或扩展插件代码。皮肤 CSS 仍使用当前解析器规则,不能控制几何布局和交互区域。 + +```json +{ + "schemaVersion": 2, + "packageType": "layout-skin", + "id": "community.example-layout", + "name": "Example layout", + "version": "1.0.0", + "author": "Example author", + "license": "CC-BY-4.0", + "entry": "skin.css", + "layout": "layout.json", + "permissions": [], + "minAppVersion": "0.2.7" +} +``` + +布局只引用 WebSpeak 登记的稳定组件 ID。当前支持 `home`、`voice`、`demo` 页面及 `desktop`、`tablet`、`mobile` 三种设备配置。组件位置使用有界的水平/垂直偏移,尺寸使用缩放、宽、高,外观字段只接受六位十六进制颜色和受限圆角;`visible` 控制显示状态。`home.security-note`、身份安全提示、连接状态与屏幕共享错误属于可信宿主 UI,不允许布局隐藏或改写。 + +示例 `layout.json`: + +```json +{ + "schemaVersion": 1, + "pages": { + "home": { + "desktop": { + "home.header": { "x": 12, "y": 8, "scale": 1.05 }, + "home.features": { "visible": false } + }, + "tablet": { "home.join-card": { "width": 680 } }, + "mobile": { "home.header": { "x": 0, "y": 4 } } + } + } +} +``` + +作者包中的布局是初始默认值。用户编辑内容单独存放在本地浏览器,覆盖作者默认值;支持撤销/重做、单个组件重置、整套布局恢复、导入和导出。更换设备宽度会选择对应设备配置,不会删除其他设备的值。恢复入口由宿主在皮肤根节点之外绘制,即使用户隐藏了页面组件,也能再次打开编辑器并恢复默认值。 + +v1 和 v2 都只支持公开页面。`/admin/**` 不加载布局、用户覆盖和皮肤组件编辑器。布局包没有数据/API 权限;后续插件必须另行设计独立沙箱与授权协议,不能通过增加 v2 清单字段取得能力。 + ## 首页内容和文案 `content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例: @@ -185,11 +231,11 @@ assets/brand.woff2 # 可选:自带字体 ### 固定布局与交互边界 -皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。 +以下规则针对 `skin.css`:校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。v2 的位置和尺寸只从经过 schema 校验的 `layout.json` 生效,不会放宽 CSS 规则。 -因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。 +因此,皮肤 CSS 可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材;v1 不能移动播放器或改变成员卡片尺寸。v2 布局可移动和缩放宿主注册组件,但 CSS 仍不能把锚定浮层改成模态弹窗或挪动按钮点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。 -外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。 +v1 外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。v2 应在布局数据中分别设置桌面、平板和手机配置。上线前仍需预览各设备尺寸、所有五种语言、键盘焦点、减少动效偏好,并确认必要控件可用、文字未被裁切。 ## 安全边界和限制 @@ -246,9 +292,10 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删 ```powershell Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force Rename-Item .\illusia-voice.zip illusia-voice.wskin + Copy-Item .\illusia-voice.wskin .\web\public\skins\illusia-voice.wskin -Force ``` -5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。 +5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置。v1 检查固定布局无回归;v2 还要检查作者默认布局与用户本地覆盖。 6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。 当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。 diff --git a/docs/examples/ILLUSIA-VOICE.md b/docs/examples/ILLUSIA-VOICE.md index 7ccac38..c4b01e0 100644 --- a/docs/examples/ILLUSIA-VOICE.md +++ b/docs/examples/ILLUSIA-VOICE.md @@ -1,14 +1,15 @@ # ILLUSIA风 -ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls. The shared quick-server list styles home history and favorite controls, the desktop rail, mobile strip, active-server marker, switch status, and quick-connect dialog with a coordinated light-glass treatment to check compatibility across desktop and mobile layouts. +ILLUSIA风 is a schema v2 `.wskin` example built from the local artwork in `illusia-voice/assets/`. Version 1.0.29 adds the required `layout.json` while preserving the existing CSS composition. The layout file starts empty, so WebSpeak's responsive defaults remain intact until a user customizes the layout locally. The package declares no permissions and contains no executable skin code. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls. The shared quick-server list styles home history and favorite controls, the desktop rail, mobile strip, active-server marker, switch status, and quick-connect dialog with a coordinated light-glass treatment to check compatibility across desktop and mobile layouts. -This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element. +This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. CSS remains visual-only; the new layout editor changes only registered host components and stores user overrides in the browser. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element. The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root: ```powershell Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force +Copy-Item .\docs\examples\illusia-voice.wskin .\web\public\skins\illusia-voice.wskin -Force ``` Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances. diff --git a/docs/examples/illusia-voice.wskin b/docs/examples/illusia-voice.wskin index 65042d6..d8544f8 100644 Binary files a/docs/examples/illusia-voice.wskin and b/docs/examples/illusia-voice.wskin differ diff --git a/docs/examples/illusia-voice/layout.json b/docs/examples/illusia-voice/layout.json new file mode 100644 index 0000000..96c5260 --- /dev/null +++ b/docs/examples/illusia-voice/layout.json @@ -0,0 +1,4 @@ +{ + "schemaVersion": 1, + "pages": {} +} diff --git a/docs/examples/illusia-voice/manifest.json b/docs/examples/illusia-voice/manifest.json index 6f771fe..cc897f0 100644 --- a/docs/examples/illusia-voice/manifest.json +++ b/docs/examples/illusia-voice/manifest.json @@ -1,12 +1,15 @@ { - "schemaVersion": 1, + "schemaVersion": 2, + "packageType": "layout-skin", "id": "community.illusia-voice", "name": "ILLUSIA风", - "version": "1.0.28", + "version": "1.0.29", "author": "WebSpeak Project", "license": "All rights reserved", "description": "A bright original-character art skin for the home, voice room, and demo pages.", "entry": "skin.css", + "layout": "layout.json", + "permissions": [], "preview": "assets/background-composite.webp", "minAppVersion": "0.2.7-preview" } diff --git a/package.json b/package.json index 2ea4c12..f0ae042 100644 --- a/package.json +++ b/package.json @@ -11,11 +11,12 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts", + "test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-wasm-interpreter.test.ts", "verify": "npm test && npm run build && npm run web:build", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", "web:build": "npm --prefix web run build", + "skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs", "android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs", "android:sync": "npm run android:prepare && cd web && npx cap sync android", "prepare:sdk": "node scripts/prepare-sdk.mjs", diff --git a/scripts/build-skin-wasm-interpreter.mjs b/scripts/build-skin-wasm-interpreter.mjs new file mode 100644 index 0000000..9b2ca0c --- /dev/null +++ b/scripts/build-skin-wasm-interpreter.mjs @@ -0,0 +1,32 @@ +import { copyFile, mkdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const interpreterRoot = path.join(repositoryRoot, "web", "skin-wasm-interpreter"); +const sourceArtifact = path.join(interpreterRoot, "target", "wasm32-unknown-unknown", "release", "webspeak_skin_wasm_interpreter.wasm"); +const publicDirectory = path.join(repositoryRoot, "web", "public"); +const publicArtifact = path.join(publicDirectory, "skin-wasm-interpreter.wasm"); +const rustFlags = "-C link-arg=--max-memory=67108864 -C panic=abort"; + +const result = spawnSync("cargo", ["build", "--locked", "--release", "--target", "wasm32-unknown-unknown"], { + cwd: interpreterRoot, + env: { ...process.env, RUSTFLAGS: rustFlags }, + stdio: "inherit", +}); +if (result.error) throw result.error; +if (result.status !== 0) process.exit(result.status ?? 1); + +const artifactInfo = await stat(sourceArtifact); +if (artifactInfo.size < 8 || artifactInfo.size > 8 * 1024 * 1024) { + throw new Error(`The Wasmi interpreter artifact has an unexpected size: ${artifactInfo.size} bytes.`); +} +const header = await readFile(sourceArtifact, { encoding: null, flag: "r" }); +if (header[0] !== 0 || header[1] !== 0x61 || header[2] !== 0x73 || header[3] !== 0x6d) { + throw new Error("The Wasmi interpreter build did not produce a WebAssembly module."); +} + +await mkdir(publicDirectory, { recursive: true }); +await copyFile(sourceArtifact, publicArtifact); +console.log(`Built bounded Wasmi interpreter (${artifactInfo.size} bytes) at web/public/skin-wasm-interpreter.wasm.`); diff --git a/src/admin/skin-registry.test.ts b/src/admin/skin-registry.test.ts index 9e7862e..b9c4c3a 100644 --- a/src/admin/skin-registry.test.ts +++ b/src/admin/skin-registry.test.ts @@ -5,7 +5,7 @@ import path from "node:path"; import test from "node:test"; import { SkinRegistry, SkinRegistryError } from "./skin-registry.js"; -const manifest = { + const manifest = { schemaVersion: 1, id: "sample-skin", name: "Sample skin", @@ -87,6 +87,53 @@ test("custom skins can be enabled, disabled, and selected as the instance defaul assert.equal(await registry.getDefaultSkinId(), "builtin.light"); }); +test("server accepts validated declarative v2 layouts and rejects permissions or unregistered components", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v2-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const manifestV2 = { + ...manifest, + schemaVersion: 2, + packageType: "layout-skin", + permissions: [], + layout: "layout.json", + content: undefined, + preview: undefined, + }; + const layout = { + schemaVersion: 1, + pages: { home: { desktop: { "home.header": { x: 24, visible: true, background: "#123456" } } } }, + }; + const archive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV2))], + ["skin.css", Buffer.from('[data-ws-part="home.header"] { color: teal; }')], + ["layout.json", Buffer.from(JSON.stringify(layout))], + ]); + const saved = await registry.save(archive, "sample-skin"); + assert.equal(saved.id, "sample-skin"); + assert.deepEqual(await registry.readArchive("sample-skin"), archive); + + const permissionsArchive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify({ ...manifestV2, permissions: ["network.fetch"] }))], + ["skin.css", Buffer.from("")], + ["layout.json", Buffer.from(JSON.stringify(layout))], + ]); + await assert.rejects(registry.save(permissionsArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PERMISSION_INVALID"); + const unknownManifestField = createZip([ + ["manifest.json", Buffer.from(JSON.stringify({ ...manifestV2, capabilities: ["network.fetch"] }))], + ["skin.css", Buffer.from('[data-ws-part="home.header"] { color: teal; }')], + ["layout.json", Buffer.from(JSON.stringify({ schemaVersion: 1, pages: {} }))], + ]); + await assert.rejects(registry.save(unknownManifestField, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_MANIFEST_INVALID"); + + const unknownComponentArchive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV2))], + ["skin.css", Buffer.from(".voice-card { color: teal; }")], + ["layout.json", Buffer.from(JSON.stringify({ schemaVersion: 1, pages: { home: { desktop: { "home.unknown": { x: 1 } } } } }))], + ]); + await assert.rejects(registry.save(unknownComponentArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_LAYOUT_INVALID"); +}); + test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => { const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-")); context.after(() => rm(directory, { recursive: true, force: true })); diff --git a/src/admin/skin-registry.ts b/src/admin/skin-registry.ts index ded65d6..c541200 100644 --- a/src/admin/skin-registry.ts +++ b/src/admin/skin-registry.ts @@ -1,4 +1,5 @@ import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js"; +import { parseSkinLayoutJson } from "../shared/skin-layout.js"; import { randomBytes } from "node:crypto"; import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -40,7 +41,10 @@ interface SkinArchiveEntry { } type ParsedSkinManifest = Omit & { + schemaVersion: 1 | 2; + packageType?: "layout-skin"; entry: string; + layout?: string; content?: string; preview?: string; }; @@ -222,7 +226,7 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa let previewBytes: Buffer | undefined; let previewMime: string | undefined; for (const [packagePath, data] of fileBytes) { - if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue; + if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.preview].includes(packagePath)) continue; const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null); if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED"); if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE"); @@ -235,6 +239,12 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa try { JSON.parse(content.toString("utf8")); } catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); } } + if (manifest.layout) { + const layout = fileBytes.get(manifest.layout); + if (!layout || layout.byteLength > 128 * 1024) throw new SkinRegistryError("layout.json is missing or exceeds 128 KiB.", "SKIN_LAYOUT_SIZE"); + try { parseSkinLayoutJson(decodeUtf8(layout, "layout.json is not valid UTF-8.")); } + catch (error) { throw new SkinRegistryError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); } + } if (manifest.preview) { previewBytes = fileBytes.get(manifest.preview); previewMime = imageMime(manifest.preview) ?? undefined; @@ -366,25 +376,40 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); } if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID"); const value = raw as Record; + const schemaVersion = value.schemaVersion; + if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion === 2) { + const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]); + const unknown = Object.keys(value).find((key) => !fields.has(key)); + if (unknown) throw new SkinRegistryError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID"); + } const read = (key: string, max: number): string => { const item = value[key]; if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID"); return item.trim(); }; const id = read("id", 80); - if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION"); + if (!isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion === 2 && (value.packageType !== "layout-skin" || !Array.isArray(value.permissions) || value.permissions.length !== 0)) { + throw new SkinRegistryError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID"); + } + if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined)) { + throw new SkinRegistryError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION"); + } const version = read("version", 32); const minAppVersion = read("minAppVersion", 32); if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID"); const entry = read("entry", 120); const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max); + const layout = schemaVersion === 2 ? read("layout", 120) : undefined; const content = readOptional("content", 120); const preview = readOptional("preview", 120); - for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID"); - if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID"); - if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID"); + for (const candidate of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID"); + if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); + if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID"); const description = readOptional("description", 400); - return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) }; + return { schemaVersion, ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) }; } function singleRootPrefix(paths: string[]): string { diff --git a/src/shared/skin-extension.ts b/src/shared/skin-extension.ts new file mode 100644 index 0000000..7499e53 --- /dev/null +++ b/src/shared/skin-extension.ts @@ -0,0 +1,245 @@ +export const SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION = 1 as const; +export const SKIN_EXTENSION_API_VERSION = 1 as const; +export const SKIN_EXTENSION_MESSAGE_CHANNEL = "webspeak.skin-extension" as const; + +export const SKIN_EXTENSION_PERMISSION_DEFINITIONS = Object.freeze({ + "session.status.read": Object.freeze({ + policyVersion: 1, + risk: "low", + description: "Read a minimal snapshot of the current voice session status.", + }), +} as const); + +export type SkinExtensionPermissionId = keyof typeof SKIN_EXTENSION_PERMISSION_DEFINITIONS; + +export interface SkinExtensionManifest { + schemaVersion: typeof SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION; + packageType: "extension"; + id: string; + name: string; + version: string; + apiVersion: typeof SKIN_EXTENSION_API_VERSION; + permissions: readonly SkinExtensionPermissionId[]; +} + +export type SkinExtensionPermissionVersions = Readonly>>; + +/** A host-created approval record. Package contents can request permissions but cannot create this record. */ +export interface SkinExtensionApproval { + pluginId: string; + apiVersion: number; + permissions: SkinExtensionPermissionVersions; +} + +export interface SkinExtensionUpgradeConsentDelta { + addedPermissions: SkinExtensionPermissionId[]; + changedMeaningPermissions: SkinExtensionPermissionId[]; + removedPermissions: SkinExtensionPermissionId[]; + apiVersionChanged: boolean; + requiresConsent: boolean; +} + +export interface SkinExtensionSessionStatus { + connected: boolean; + channelName: string | null; + memberCount: number; +} + +export interface SkinExtensionRequestMessage { + channel: typeof SKIN_EXTENSION_MESSAGE_CHANNEL; + apiVersion: typeof SKIN_EXTENSION_API_VERSION; + nonce: string; + id: string; + type: "request"; + permission: SkinExtensionPermissionId; + payload: Record; +} + +export class SkinExtensionValidationError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinExtensionValidationError"; + } +} + +const MANIFEST_FIELDS = new Set(["schemaVersion", "packageType", "id", "name", "version", "apiVersion", "permissions"]); +const PLUGIN_ID_PATTERN = /^[a-z0-9]+(?:[.-][a-z0-9]+)*$/; +const SEMVER_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; +const KNOWN_PERMISSIONS = new Set(Object.keys(SKIN_EXTENSION_PERMISSION_DEFINITIONS)); + +function isPlainRecord(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 boundedString(value: unknown, field: string, maximumLength: number): string { + if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || value.trim() !== value) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", `Invalid ${field}.`); + } + return value; +} + +export function parseSkinExtensionManifest(input: unknown): SkinExtensionManifest { + if (!isPlainRecord(input)) throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension manifest must be an object."); + if (Object.keys(input).some((key) => !MANIFEST_FIELDS.has(key))) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_UNKNOWN_FIELD", "The extension manifest contains an unsupported field."); + } + if (input.schemaVersion !== SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION || input.packageType !== "extension") { + throw new SkinExtensionValidationError("SKIN_EXTENSION_SCHEMA_UNSUPPORTED", "The extension package schema is not supported."); + } + + const id = boundedString(input.id, "id", 100); + if (!PLUGIN_ID_PATTERN.test(id)) throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension id must use lowercase letters, numbers, dots, or hyphens."); + const name = boundedString(input.name, "name", 120); + const version = boundedString(input.version, "version", 64); + if (!SEMVER_PATTERN.test(version)) throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension version must use semantic version syntax."); + if (input.apiVersion !== SKIN_EXTENSION_API_VERSION) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_API_UNSUPPORTED", "The extension API version is not supported."); + } + if (!Array.isArray(input.permissions) || input.permissions.length > 8) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension permissions must be a small array."); + } + + const permissions: SkinExtensionPermissionId[] = []; + for (const permission of input.permissions) { + if (typeof permission !== "string" || !KNOWN_PERMISSIONS.has(permission)) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_PERMISSION_UNKNOWN", "The extension requests an unsupported permission."); + } + if (permissions.includes(permission as SkinExtensionPermissionId)) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_PERMISSION_DUPLICATE", "The extension requests a permission more than once."); + } + permissions.push(permission as SkinExtensionPermissionId); + } + + return Object.freeze({ + schemaVersion: SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION, + packageType: "extension", + id, + name, + version, + apiVersion: SKIN_EXTENSION_API_VERSION, + permissions: Object.freeze(permissions), + }); +} + +/** Called only by a future host approval flow after the user approves the exact capabilities. */ +export function createSkinExtensionApproval(manifest: SkinExtensionManifest): SkinExtensionApproval { + const permissions: Partial> = {}; + for (const permission of manifest.permissions) { + permissions[permission] = SKIN_EXTENSION_PERMISSION_DEFINITIONS[permission].policyVersion; + } + return Object.freeze({ + pluginId: manifest.id, + apiVersion: manifest.apiVersion, + permissions: Object.freeze(permissions), + }); +} + +export function parseSkinExtensionApproval(input: unknown): SkinExtensionApproval { + if (!isPlainRecord(input) || Object.keys(input).some((key) => !["pluginId", "apiVersion", "permissions"].includes(key))) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_APPROVAL_INVALID", "The extension approval record is invalid."); + } + const pluginId = boundedString(input.pluginId, "approval.pluginId", 100); + if (!PLUGIN_ID_PATTERN.test(pluginId) || input.apiVersion !== SKIN_EXTENSION_API_VERSION || !isPlainRecord(input.permissions)) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_APPROVAL_INVALID", "The extension approval record is invalid."); + } + const permissions: Partial> = {}; + for (const [permission, policyVersion] of Object.entries(input.permissions)) { + if (!KNOWN_PERMISSIONS.has(permission) || !Number.isSafeInteger(policyVersion) || (policyVersion as number) < 1) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_APPROVAL_INVALID", "The extension approval record contains an unsupported grant."); + } + permissions[permission as SkinExtensionPermissionId] = policyVersion as number; + } + return Object.freeze({ + pluginId, + apiVersion: SKIN_EXTENSION_API_VERSION, + permissions: Object.freeze(permissions), + }); +} + +export function getSkinExtensionUpgradeConsentDelta( + previousApproval: SkinExtensionApproval, + nextManifest: SkinExtensionManifest, +): SkinExtensionUpgradeConsentDelta { + if (previousApproval.pluginId !== nextManifest.id) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_ID_CHANGED", "An approval cannot be reused for a different extension id."); + } + + const addedPermissions = nextManifest.permissions.filter((permission) => previousApproval.permissions[permission] === undefined); + const changedMeaningPermissions = nextManifest.permissions.filter((permission) => { + const grantedPolicyVersion = previousApproval.permissions[permission]; + return grantedPolicyVersion !== undefined + && grantedPolicyVersion !== SKIN_EXTENSION_PERMISSION_DEFINITIONS[permission].policyVersion; + }); + const removedPermissions = Object.keys(previousApproval.permissions) + .filter((permission): permission is SkinExtensionPermissionId => KNOWN_PERMISSIONS.has(permission)) + .filter((permission) => !nextManifest.permissions.includes(permission)); + const apiVersionChanged = previousApproval.apiVersion !== nextManifest.apiVersion; + + return { + addedPermissions, + changedMeaningPermissions, + removedPermissions, + apiVersionChanged, + requiresConsent: addedPermissions.length > 0 || changedMeaningPermissions.length > 0 || apiVersionChanged, + }; +} + +export function isSkinExtensionPermissionApproved( + approval: SkinExtensionApproval, + pluginId: string, + permission: SkinExtensionPermissionId, +): boolean { + return approval.pluginId === pluginId + && approval.permissions[permission] === SKIN_EXTENSION_PERMISSION_DEFINITIONS[permission].policyVersion; +} + +export function isSkinExtensionBootstrapHello( + event: { source: unknown; origin: string; data: unknown; ports: readonly unknown[] }, + expectedSource: unknown, + expectedNonce: string, +): boolean { + if (event.source !== expectedSource || event.origin !== "null" || event.ports.length !== 1 || !isPlainRecord(event.data)) return false; + const data = event.data; + return Object.keys(data).length === 4 + && data.channel === SKIN_EXTENSION_MESSAGE_CHANNEL + && data.type === "hello" + && data.apiVersion === SKIN_EXTENSION_API_VERSION + && data.nonce === expectedNonce; +} + +export function parseSkinExtensionRequestMessage(value: unknown, expectedNonce: string): SkinExtensionRequestMessage | null { + if (!isPlainRecord(value) || !isPlainRecord(value.payload)) return null; + const expectedFields = ["channel", "apiVersion", "nonce", "id", "type", "permission", "payload"]; + if (Object.keys(value).length !== expectedFields.length || expectedFields.some((field) => !(field in value))) return null; + if (Object.keys(value.payload).length !== 0) return null; + if (value.channel !== SKIN_EXTENSION_MESSAGE_CHANNEL || value.apiVersion !== SKIN_EXTENSION_API_VERSION + || value.nonce !== expectedNonce || value.type !== "request") return null; + if (typeof value.id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(value.id)) return null; + if (typeof value.permission !== "string" || !KNOWN_PERMISSIONS.has(value.permission)) return null; + return value as unknown as SkinExtensionRequestMessage; +} + +/** Copies only the low-sensitivity fields registered for the prototype capability. */ +export function sanitizeSkinExtensionSessionStatus(value: unknown): SkinExtensionSessionStatus { + if (!isPlainRecord(value) || typeof value.connected !== "boolean") { + throw new SkinExtensionValidationError("SKIN_EXTENSION_STATUS_INVALID", "The host session status is invalid."); + } + const channelName = value.channelName; + const memberCount = value.memberCount; + if (channelName !== null && typeof channelName !== "string") { + throw new SkinExtensionValidationError("SKIN_EXTENSION_STATUS_INVALID", "The host session status is invalid."); + } + if (!Number.isSafeInteger(memberCount) || (memberCount as number) < 0 || (memberCount as number) > 10000) { + throw new SkinExtensionValidationError("SKIN_EXTENSION_STATUS_INVALID", "The host session status is invalid."); + } + const safeChannelName = typeof channelName === "string" + ? channelName.slice(0, 120).replace(/[\u0000-\u001f\u007f]/g, " ") + : null; + return Object.freeze({ + connected: value.connected, + channelName: safeChannelName, + memberCount: memberCount as number, + }); +} diff --git a/src/shared/skin-layout.test.ts b/src/shared/skin-layout.test.ts new file mode 100644 index 0000000..7b6d9a4 --- /dev/null +++ b/src/shared/skin-layout.test.ts @@ -0,0 +1,149 @@ +import assert from "node:assert/strict"; +import { readFile, readdir } from "node:fs/promises"; +import test from "node:test"; +import { + getSkinLayoutComponents, + parseSkinLayoutJson, + SKIN_LAYOUT_COMPONENTS, + validateSkinLayout, + canEditSkinLayoutComponent, +} from "./skin-layout.js"; + +async function vueSources(directory: URL): Promise { + const files = (await readdir(directory, { recursive: true })).filter((file) => file.endsWith(".vue")); + return Promise.all(files.map((file) => readFile(new URL(file.replaceAll("\\", "/"), directory), "utf8"))); +} + +test("the stable layout registry covers public skin hooks and excludes the admin console", async () => { + const [webClient, demo, sharedComponents, skinSwitcher, languageSwitcher, admin, adminComponents] = await Promise.all([ + readFile(new URL("../../web/src/views/WebClient.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/views/DemoView.vue", import.meta.url), "utf8"), + vueSources(new URL("../../web/src/components/web-client/", import.meta.url)), + readFile(new URL("../../web/src/components/SkinSwitcher.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/components/LanguageSwitcher.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/views/AdminView.vue", import.meta.url), "utf8"), + vueSources(new URL("../../web/src/components/admin/", import.meta.url)), + ]); + const publicSource = [webClient, demo, ...sharedComponents, skinSwitcher, languageSwitcher].join("\n"); + const publicParts = new Set([...publicSource.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1])); + const interactiveParts = new Set(); + for (const match of publicSource.matchAll(/<[A-Za-z][\w.-]*\b[^>]*>/gs)) { + const attributes = match[0]; + const part = attributes.match(/\bdata-ws-part="([^"]+)"/)?.[1]; + if (!part) continue; + const isNativeControl = /^<(?:button|a|input|select|textarea)\b/i.test(attributes); + const hasButtonRole = /\brole="button"/.test(attributes); + const keyboardAction = /@keydown\.(?:enter|space)\b/.test(attributes); + const dragAction = /@(?:dragstart|dragover|dragleave|drop)\b|:draggable=/.test(attributes); + if (isNativeControl || hasButtonRole || keyboardAction || dragAction) interactiveParts.add(part); + } + const registered = new Set(SKIN_LAYOUT_COMPONENTS.map((component) => component.selectorPart)); + for (const part of publicParts) assert.ok(registered.has(part), "Unregistered public layout hook: " + part); + for (const part of interactiveParts) { + const component = SKIN_LAYOUT_COMPONENTS.find((entry) => entry.id === part); + assert.ok(component, "Interactive public hook must have its own component metadata: " + part); + assert.ok(component.minTouchTarget >= 44, "Interactive public hook needs a 44px touch target: " + part); + assert.ok(component.minWidth >= 44 && component.minHeight >= 44, "Interactive public hook needs bounded minimum dimensions: " + part); + assert.ok(component.minScale >= 1, "Interactive public hook must not scale below its natural hit target: " + part); + } + assert.match(publicSource, /data-ws-part="demo\.voice-card"[\s\S]*?role="button"[\s\S]*?tabindex="0"[\s\S]*?@keydown\.enter[\s\S]*?@keydown\.space/); + assert.doesNotMatch([admin, ...adminComponents].join("\n"), /ws-skin-root|data-ws-page=/); + assert.ok(SKIN_LAYOUT_COMPONENTS.every((component) => !component.id.startsWith("admin."))); +}); + +test("valid layouts accept only bounded positions and safe visual tokens", () => { + const layout = validateSkinLayout({ + schemaVersion: 1, + pages: { + home: { + desktop: { + "home.header": { x: -120, y: 40, scale: 1.25, visible: true, foreground: "#aabbcc", radius: 16 }, + "control.button": { background: "#010203", border: "#ffffff" }, + }, + mobile: { "home.join-card": { x: 8, scale: 0.9 } }, + tablet: { "home.join-card": { width: 720, height: 460 } }, + }, + }, + }); + assert.equal(layout.pages.home?.desktop?.["home.header"]?.x, -120); + assert.equal(layout.pages.home?.desktop?.["home.header"]?.foreground, "#aabbcc"); + assert.equal(layout.pages.home?.tablet?.["home.join-card"]?.width, 720); + assert.equal(getSkinLayoutComponents("home").some((component) => component.id === "home.join-card"), true); + assert.equal(getSkinLayoutComponents("voice").some((component) => component.id === "home.join-card"), false); +}); + +test("layout validation fails closed for unknown pages, components, trusted notices, fields, and values", () => { + const invalidValues: unknown[] = [ + { schemaVersion: 2, pages: {} }, + { schemaVersion: 1, pages: { admin: { desktop: {} } } }, + { schemaVersion: 1, pages: { home: { desktop: { "home.not-registered": { x: 0 } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { "home.security-note": { visible: false } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { app: { visible: false } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { "home.header": { position: "fixed" } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { "home.header": { x: 2001 } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { "home.header": { width: 8 } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { "voice.connection-status": { visible: false } } } } }, + { schemaVersion: 1, pages: { home: { desktop: { "home.header": { background: "url(https://example.invalid)" } } } } }, + ]; + for (const invalid of invalidValues) assert.throws(() => validateSkinLayout(invalid)); +}); + +test("registered components carry accessibility, responsive, purpose, and data-scope metadata", () => { + assert.ok(SKIN_LAYOUT_COMPONENTS.length > 100); + for (const component of SKIN_LAYOUT_COMPONENTS) { + assert.ok(component.name.length > 0); + assert.notEqual(component.name, component.id, "registry names must be readable metadata rather than the ID repeated"); + assert.ok(component.purpose.length > 0); + assert.ok(["core", "optional", "trusted-chrome"].includes(component.category)); + if (component.editable) { + assert.deepEqual(component.allowedContainers, ["app"]); + assert.deepEqual(component.layoutModes, ["position", "size", "visibility", "appearance"]); + assert.ok(component.minWidth > 0 && component.maxWidth >= component.minWidth); + assert.ok(component.minHeight > 0 && component.maxHeight >= component.minHeight); + assert.ok(component.minScale > 0 && component.maxScale >= component.minScale); + assert.ok(component.allowedStyleTokens.length > 0); + } else { + assert.deepEqual(component.allowedContainers, []); + assert.deepEqual(component.layoutModes, []); + assert.deepEqual(component.allowedStyleTokens, []); + } + assert.equal(component.keyboardBehavior, "host-native"); + assert.equal(component.focusOrder, "host-dom"); + assert.equal(component.accessibleNamePolicy, "preserve-host-name"); + assert.ok(component.narrowScreenBehavior.length > 0); + assert.ok(component.dataSensitivity.length > 0); + } + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.connect")?.minTouchTarget, 44); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.feature")?.category, "optional"); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.security-note")?.category, "trusted-chrome"); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.identity-import.security")?.dataSensitivity, "identity"); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "demo.voice-card")?.minTouchTarget, 44); +}); + +test("trusted host components cannot be changed through a nested generic control", () => { + assert.equal(canEditSkinLayoutComponent("control.button", "home", ["home.form"]), true); + assert.equal(canEditSkinLayoutComponent("control.button", "home", ["home.identity-import.security"]), false); + assert.equal(canEditSkinLayoutComponent("control.button", "voice", ["voice.screen-share-error"]), false); + assert.equal(canEditSkinLayoutComponent("home.security-note", "home"), false); +}); + +test("touch controls cannot be shrunk below their registered hit-target bounds", () => { + assert.throws(() => validateSkinLayout({ + schemaVersion: 1, + pages: { home: { desktop: { "home.connect": { scale: 0.75 } } } }, + })); + assert.throws(() => validateSkinLayout({ + schemaVersion: 1, + pages: { home: { desktop: { "control.button": { width: 20 } } } }, + })); + assert.equal(validateSkinLayout({ + schemaVersion: 1, + pages: { home: { desktop: { "home.feature": { width: 20, scale: 0.5 } } } }, + }).pages.home?.desktop?.["home.feature"]?.width, 20); +}); + +test("layout JSON parsing rejects malformed and oversized documents", () => { + assert.throws(() => parseSkinLayoutJson("{")); + assert.throws(() => parseSkinLayoutJson(" ".repeat(128 * 1024 + 1))); + assert.deepEqual(parseSkinLayoutJson('{"schemaVersion":1,"pages":{}}'), { schemaVersion: 1, pages: {} }); +}); diff --git a/src/shared/skin-layout.ts b/src/shared/skin-layout.ts new file mode 100644 index 0000000..bd81ddb --- /dev/null +++ b/src/shared/skin-layout.ts @@ -0,0 +1,559 @@ +export type SkinLayoutPage = "home" | "voice" | "demo"; +export type SkinLayoutProfile = "desktop" | "tablet" | "mobile"; + +export interface SkinLayoutPlacement { + visible?: boolean; + x?: number; + y?: number; + scale?: number; + width?: number; + height?: number; + foreground?: string; + background?: string; + border?: string; + radius?: number; +} + +export interface SkinLayoutDocument { + schemaVersion: 1; + pages: Partial>>>>; +} + +export interface SkinLayoutComponent { + id: string; + page: SkinLayoutPage | "common"; + selectorPart: string; + controlKind?: string; + name: string; + purpose: "host-shell" | "host-action" | "session-content" | "identity-content" | "page-content" | "decoration" | "trusted-status"; + category: "core" | "optional" | "trusted-chrome"; + allowedContainers: readonly string[]; + layoutModes: readonly ("position" | "size" | "visibility" | "appearance")[]; + dataSensitivity: "none" | "public" | "session" | "identity"; + keyboardBehavior: "host-native"; + focusOrder: "host-dom"; + accessibleNamePolicy: "preserve-host-name"; + narrowScreenBehavior: "host-responsive" | "decorative" | "trusted-fixed"; + minWidth: number; + minHeight: number; + maxWidth: number; + maxHeight: number; + minScale: number; + maxScale: number; + minTouchTarget: number; + allowedStyleTokens: readonly ("foreground" | "background" | "border" | "radius")[]; + editable: boolean; +} + +const PUBLIC_PART_IDS = new Set([ + "app", + "app.toast", + "control", + "demo.action.poke", + "demo.action.reconnect", + "demo.action.speaking", + "demo.actions", + "demo.actions.heading", + "demo.avatar", + "demo.badge", + "demo.brand", + "demo.channel", + "demo.channel.members", + "demo.channel.select", + "demo.channels", + "demo.channels.heading", + "demo.chat.composer", + "demo.chat.empty", + "demo.chat.heading", + "demo.chat.input", + "demo.chat.message", + "demo.chat.messages", + "demo.chat.send", + "demo.chat.tab", + "demo.chat.tabs", + "demo.header", + "demo.header-tools", + "demo.hero", + "demo.hero.description", + "demo.hero.online", + "demo.hero.title", + "demo.home-link", + "demo.language-switcher", + "demo.layout", + "demo.live", + "demo.main", + "demo.member-name", + "demo.member-status", + "demo.note", + "demo.poke-notification", + "demo.poke.dismiss", + "demo.reconnect", + "demo.reconnect.restore", + "demo.skin-switcher", + "demo.user", + "demo.voice-card", + "demo.voice-grid", + "demo.voice-heading", + "demo.wave", + "home", + "home.brand", + "home.community-dialog", + "home.connect", + "home.content", + "home.favorite-toggle", + "home.feature", + "home.features", + "home.field", + "home.field-label", + "home.footer", + "home.form", + "home.gateway-status", + "home.header", + "home.header-tools", + "home.hero", + "home.hero.description", + "home.hero.eyebrow", + "home.hero.title", + "home.identity", + "home.identity-actions", + "home.identity-export.button", + "home.identity-import-dialog", + "home.identity-import.cancel", + "home.identity-import.close", + "home.identity-import.drop-zone", + "home.identity-import.error", + "home.identity-import.file-button", + "home.identity-import.footer", + "home.identity-import.header", + "home.identity-import.open", + "home.identity-import.security", + "home.identity-import.submit", + "home.identity-import.textarea", + "home.join-card", + "home.join-card.sonar", + "home.join-card.waveform", + "home.join-description", + "home.join-title", + "home.notice", + "home.relay-choice", + "home.relay-choice.copy", + "home.security-note", + "home.server-history", + "home.server-history.favorite-toggle", + "home.server-history.group", + "home.server-history.item", + "home.server-history.select", + "home.server-target", + "home.visitors", + "language.menu", + "language.option", + "language.trigger", + "skin.menu", + "skin.option", + "skin.trigger", + "voice.activity", + "voice.activity-heading", + "voice.activity.artwork", + "voice.audio-dock", + "voice.audio-dock.microphone", + "voice.audio-dock.microphone-panel", + "voice.audio-dock.output", + "voice.audio-dock.output-panel", + "voice.audio-settings", + "voice.audio-status", + "voice.breadcrumbs", + "voice.channel-group", + "voice.channel-group.heading", + "voice.channel-group.members", + "voice.chat", + "voice.chat.composer", + "voice.chat.empty", + "voice.chat.event", + "voice.chat.heading", + "voice.chat.message", + "voice.chat.message-avatar", + "voice.chat.message-body", + "voice.chat.message-bubble", + "voice.chat.messages", + "voice.chat.status", + "voice.chat.tab", + "voice.chat.tabs", + "voice.connection-status", + "voice.content", + "voice.context-menu", + "voice.context-menu-backdrop", + "voice.context-menu.header", + "voice.context-menu.move-submenu", + "voice.favorite-servers.add", + "voice.favorite-servers.avatar", + "voice.favorite-servers.current-toggle", + "voice.favorite-servers.dialog", + "voice.favorite-servers.dialog-backdrop", + "voice.favorite-servers.dialog.actions", + "voice.favorite-servers.dialog.cancel", + "voice.favorite-servers.dialog.close", + "voice.favorite-servers.dialog.field", + "voice.favorite-servers.dialog.form", + "voice.favorite-servers.dialog.header", + "voice.favorite-servers.dialog.hint", + "voice.favorite-servers.dialog.input", + "voice.favorite-servers.dialog.submit", + "voice.favorite-servers.dialog.target", + "voice.favorite-servers.favorite-toggle", + "voice.favorite-servers.rail", + "voice.favorite-servers.rail.item", + "voice.favorite-servers.rail.list", + "voice.favorite-servers.server", + "voice.favorite-servers.strip", + "voice.favorite-servers.strip.add", + "voice.favorite-servers.strip.favorite-toggle", + "voice.favorite-servers.strip.item", + "voice.favorite-servers.strip.server", + "voice.favorite-servers.switch-status", + "voice.favorite-servers.tooltip", + "voice.header", + "voice.header-actions", + "voice.member", + "voice.member-panel", + "voice.member-panel.channels", + "voice.member-panel.heading", + "voice.member-panel.search", + "voice.member-row", + "voice.member-row.avatar", + "voice.member-row.copy", + "voice.member-row.flags", + "voice.member-row.volume", + "voice.member.avatar", + "voice.member.avatar-wrap", + "voice.member.live-indicator", + "voice.member.name", + "voice.member.share-actions", + "voice.member.status", + "voice.member.stop-share", + "voice.members", + "voice.members.empty", + "voice.mobile-more", + "voice.mobile-nav", + "voice.performance", + "voice.performance.metrics", + "voice.performance.panel", + "voice.performance.route", + "voice.performance.status", + "voice.performance.webrtc-stats", + "voice.poke", + "voice.screen-player", + "voice.screen-player.controls", + "voice.screen-player.exit", + "voice.screen-player.fullscreen", + "voice.screen-player.live", + "voice.screen-player.placeholder", + "voice.screen-player.source", + "voice.screen-player.stage", + "voice.screen-player.video", + "voice.screen-player.viewer-avatar", + "voice.screen-player.viewers", + "voice.screen-player.volume", + "voice.screen-share-error", + "voice.screen-share-settings", + "voice.screen-share-settings.actions", + "voice.screen-share-settings.fields", + "voice.screen-share-settings.heading", + "voice.screen-share-settings.note", + "voice.scroll", + "voice.shell", + "voice.whisper-strip", + "voice.workspace", +]); + +const CONTROL_KINDS = ["button", "link", "input", "checkbox", "range", "select", "textarea", "menuitem", "draggable"] as const; +const TRUSTED_PART_IDS = new Set([ + "app", + "app.toast", + "home.security-note", + "home.identity-import.security", + "voice.connection-status", + "voice.screen-share-error", +]); +const DECORATIVE_PART_IDS = new Set([ + "demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave", + "home.feature", "home.features", "home.footer", "home.hero.eyebrow", "home.join-card.sonar", + "home.join-card.waveform", "home.visitors", "voice.activity.artwork", "voice.member.avatar-wrap", + "voice.member.live-indicator", "voice.performance.metrics", "voice.performance.webrtc-stats", + "voice.screen-player.viewer-avatar", +]); +const SHELL_PART_IDS = new Set([ + "app", "home", "home.content", "home.form", "home.header", "voice.shell", "voice.workspace", + "voice.content", "demo.layout", "demo.main", +]); +const ACTION_PART_IDS = new Set([ + "control", "home.connect", "home.favorite-toggle", "home.identity-actions", "home.identity-export.button", + "home.identity-import.cancel", "home.identity-import.close", "home.identity-import.file-button", + "home.identity-import.open", "home.identity-import.submit", "home.relay-choice.copy", + "home.server-history.favorite-toggle", "home.server-history.select", "language.trigger", "language.menu", + "language.option", "skin.trigger", "skin.menu", "skin.option", "voice.audio-dock.microphone", + "voice.audio-dock.output", "voice.context-menu", "voice.favorite-servers.add", + "voice.favorite-servers.current-toggle", "voice.favorite-servers.dialog.cancel", + "voice.favorite-servers.dialog.close", "voice.favorite-servers.dialog.submit", + "voice.favorite-servers.favorite-toggle", "voice.favorite-servers.strip.add", + "voice.favorite-servers.strip.favorite-toggle", "voice.member-row.copy", "voice.member-row.volume", + "voice.member.share-actions", "voice.member.stop-share", "voice.member.stop-share", + "voice.mobile-more", "voice.mobile-nav", "voice.poke", "voice.screen-player.controls", + "voice.screen-player.exit", "voice.screen-player.fullscreen", "voice.screen-player.volume", + "demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select", + "demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss", "demo.reconnect.restore", + "voice.channel-group.heading", "voice.chat.tab", "voice.favorite-servers.server", + "voice.favorite-servers.strip.server", "demo.voice-card", "home.identity-import.drop-zone", + "voice.channel-group", "voice.member-row", "demo.skin-switcher", "demo.language-switcher", +]); +const INTERACTIVE_PART_IDS = new Set([ + "demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select", + "demo.chat.input", "demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss", + "demo.reconnect.restore", "home.connect", "home.favorite-toggle", "home.identity-export.button", + "home.identity-import.cancel", "home.identity-import.close", "home.identity-import.file-button", + "home.identity-import.open", "home.identity-import.submit", "home.identity-import.textarea", + "home.server-history.favorite-toggle", "home.server-history.select", "language.option", + "language.trigger", "skin.option", "skin.trigger", "voice.channel-group.heading", "voice.chat.tab", + "voice.favorite-servers.add", "voice.favorite-servers.current-toggle", "voice.favorite-servers.dialog.cancel", + "voice.favorite-servers.dialog.close", "voice.favorite-servers.dialog.input", "voice.favorite-servers.dialog.submit", + "voice.favorite-servers.favorite-toggle", "voice.favorite-servers.server", "voice.favorite-servers.strip.add", + "voice.favorite-servers.strip.favorite-toggle", "voice.favorite-servers.strip.server", "voice.member.stop-share", + "voice.screen-player.exit", "voice.screen-player.fullscreen", "demo.voice-card", + "home.identity-import.drop-zone", "voice.channel-group", "voice.member-row", "demo.skin-switcher", + "demo.language-switcher", +]); +const IDENTITY_PART_IDS = new Set([ + "home.identity", "home.identity-actions", "home.identity-export.button", "home.identity-import-dialog", + "home.identity-import.cancel", "home.identity-import.close", "home.identity-import.drop-zone", + "home.identity-import.error", "home.identity-import.file-button", "home.identity-import.footer", + "home.identity-import.header", "home.identity-import.open", "home.identity-import.submit", + "home.identity-import.textarea", "home.identity-import.security", +]); +const COMMON_PART_IDS = new Set([ + "app", "app.toast", "control", "skin.trigger", "skin.menu", "skin.option", + "language.trigger", "language.menu", "language.option", +]); + +function pageOfPart(id: string): SkinLayoutPage | "common" | null { + if (COMMON_PART_IDS.has(id)) return "common"; + if (id === "home" || id.startsWith("home.")) return "home"; + if (id.startsWith("voice.")) return "voice"; + if (id.startsWith("demo.")) return "demo"; + return null; +} + +const LAYOUT_MODES = ["position", "size", "visibility", "appearance"] as const; +const STYLE_TOKENS = ["foreground", "background", "border", "radius"] as const; +const COMPONENT_NAME_PARTS: Record = { + action: "Action", actions: "Actions", activity: "Activity", add: "Add", app: "Application", artwork: "Artwork", + audio: "Audio", avatar: "Avatar", backdrop: "Backdrop", badge: "Badge", body: "Body", brand: "Brand", + breadcrumbs: "Breadcrumbs", bubble: "Bubble", button: "Button", cancel: "Cancel", card: "Card", + channel: "Channel", channels: "Channels", chat: "Chat", checkbox: "Checkbox", choice: "Choice", close: "Close", + community: "Community", composer: "Composer", connect: "Connect", connection: "Connection", content: "Content", + context: "Context", control: "Control", controls: "Controls", copy: "Copy", current: "Current", demo: "Demo", + description: "Description", dialog: "Dialog", dismiss: "Dismiss", dock: "Dock", draggable: "Draggable", + drop: "Drop", empty: "Empty state", error: "Error", event: "Event", exit: "Exit", export: "Export", + eyebrow: "Eyebrow", favorite: "Favorite", feature: "Feature", features: "Features", field: "Field", fields: "Fields", + file: "File", flags: "Flags", footer: "Footer", form: "Form", fullscreen: "Fullscreen", gateway: "Gateway", + grid: "Grid", group: "Group", header: "Header", heading: "Heading", hero: "Hero", hint: "Hint", history: "History", + home: "Home page", identity: "Identity", import: "Import", indicator: "Indicator", input: "Input", item: "Item", + join: "Join", label: "Label", language: "Language", layout: "Layout", link: "Link", list: "List", live: "Live status", + main: "Main content", member: "Member", members: "Members", menu: "Menu", menuitem: "Menu item", message: "Message", + messages: "Messages", metrics: "Metrics", microphone: "Microphone", mobile: "Mobile", more: "More", move: "Move", + name: "Name", nav: "Navigation", note: "Note", notice: "Notice", notification: "Notification", online: "Online status", + open: "Open", option: "Option", output: "Output", panel: "Panel", performance: "Performance", placeholder: "Placeholder", + player: "Player", poke: "Poke", rail: "Rail", range: "Range", reconnect: "Reconnect", relay: "Relay", restore: "Restore", + route: "Route", row: "Row", screen: "Screen", scroll: "Scrollable area", search: "Search", security: "Security", + select: "Select", send: "Send", server: "Server", servers: "Servers", settings: "Settings", share: "Share", + shell: "Application shell", skin: "Skin", sonar: "Sonar effect", source: "Source", speaking: "Speaking status", + stage: "Stage", stats: "Statistics", status: "Status", stop: "Stop", strip: "Strip", submenu: "Submenu", + submit: "Submit", switch: "Switch", switcher: "Switcher", tab: "Tab", tabs: "Tabs", target: "Target", textarea: "Text area", + title: "Title", toast: "Notifications", toggle: "Toggle", tools: "Tools", tooltip: "Tooltip", trigger: "Trigger", + user: "User", video: "Video", viewer: "Viewer", viewers: "Viewers", visitors: "Visitors", voice: "Voice", + volume: "Volume", wave: "Wave", waveform: "Waveform", webrtc: "WebRTC", whisper: "Whisper", workspace: "Workspace", + wrap: "Wrapper", zone: "Drop zone", +}; + +function componentName(id: string): string { + return id.split(".").map((part) => part.split("-").map((word) => COMPONENT_NAME_PARTS[word] + ?? (word.charAt(0).toUpperCase() + word.slice(1))).join(" ")).join(" · "); +} + +function describeComponent(id: string, page: SkinLayoutPage | "common", controlKind?: string): SkinLayoutComponent { + const category: SkinLayoutComponent["category"] = TRUSTED_PART_IDS.has(id) ? "trusted-chrome" + : DECORATIVE_PART_IDS.has(id) ? "optional" : "core"; + const purpose: SkinLayoutComponent["purpose"] = TRUSTED_PART_IDS.has(id) ? "trusted-status" + : SHELL_PART_IDS.has(id) ? "host-shell" + : ACTION_PART_IDS.has(id) || Boolean(controlKind) ? "host-action" + : IDENTITY_PART_IDS.has(id) ? "identity-content" + : DECORATIVE_PART_IDS.has(id) ? "decoration" + : page === "voice" ? "session-content" : "page-content"; + const allowedContainers = category === "trusted-chrome" ? [] : ["app"]; + const editable = category !== "trusted-chrome"; + const isControl = editable && (Boolean(controlKind) || id === "control" || purpose === "host-action" || INTERACTIVE_PART_IDS.has(id)); + return { + id, + page, + selectorPart: id.startsWith("control.") ? "control" : id, + ...(controlKind ? { controlKind } : {}), + name: componentName(id), + purpose, + category, + allowedContainers, + layoutModes: editable ? LAYOUT_MODES : [], + dataSensitivity: IDENTITY_PART_IDS.has(id) ? "identity" : page === "voice" ? "session" : purpose === "decoration" ? "none" : "public", + keyboardBehavior: "host-native", + focusOrder: "host-dom", + accessibleNamePolicy: "preserve-host-name", + narrowScreenBehavior: category === "trusted-chrome" ? "trusted-fixed" : category === "optional" ? "decorative" : "host-responsive", + minWidth: editable ? isControl ? 44 : 12 : 0, + minHeight: editable ? isControl ? 44 : 12 : 0, + maxWidth: editable ? isControl ? 1600 : 2400 : 0, + maxHeight: editable ? isControl ? 1200 : 2400 : 0, + minScale: editable ? isControl ? 1 : 0.5 : 1, + maxScale: editable ? isControl ? 3 : 4 : 1, + minTouchTarget: isControl ? 44 : 0, + allowedStyleTokens: editable ? STYLE_TOKENS : [], + editable, + }; +} + +const regularComponents: SkinLayoutComponent[] = [...PUBLIC_PART_IDS].flatMap((id) => { + const page = pageOfPart(id); + return page ? [describeComponent(id, page)] : []; +}); +const virtualControls: SkinLayoutComponent[] = CONTROL_KINDS.map((kind) => ({ + ...describeComponent("control." + kind, "common", kind), +})); + +export const SKIN_LAYOUT_COMPONENTS: readonly SkinLayoutComponent[] = [ + ...regularComponents, + ...virtualControls, +]; + +const componentById = new Map(SKIN_LAYOUT_COMPONENTS.map((component) => [component.id, component])); + +export function getSkinLayoutComponents(page: SkinLayoutPage): SkinLayoutComponent[] { + return SKIN_LAYOUT_COMPONENTS.filter((component) => component.page === "common" || component.page === page); +} + +export function getSkinLayoutComponent(id: string, page?: SkinLayoutPage): SkinLayoutComponent | undefined { + const component = componentById.get(id); + if (!component || (page && component.page !== "common" && component.page !== page)) return undefined; + return component; +} + +export function canEditSkinLayoutComponent(id: string, page: SkinLayoutPage, ancestorIds: readonly string[] = []): boolean { + const component = getSkinLayoutComponent(id, page); + if (!component?.editable) return false; + return ancestorIds.every((ancestorId) => getSkinLayoutComponent(ancestorId, page)?.category !== "trusted-chrome"); +} + +export function getSkinLayoutComponentId(part: string | undefined, controlKind?: string): string | null { + if (!part) return null; + if (part === "control" && controlKind) return "control." + controlKind; + return part; +} + +const ALLOWED_PLACEMENT_FIELDS = new Set([ + "visible", "x", "y", "scale", "width", "height", "foreground", "background", "border", "radius", +]); + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function assertOnlyKeys(value: Record, allowed: ReadonlySet, context: string): void { + for (const key of Object.keys(value)) { + if (!allowed.has(key)) throw new Error(context + " contains an unknown field: " + key); + } +} + +function readNumber(value: unknown, key: string, minimum: number, maximum: number): number | undefined { + if (value === undefined) return undefined; + if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) { + throw new Error("Skin layout field " + key + " is outside its allowed range."); + } + return value; +} + +function readColor(value: unknown, key: string): string | undefined { + if (value === undefined) return undefined; + if (typeof value !== "string" || !/^#[0-9a-f]{6}$/i.test(value)) throw new Error("Skin layout field " + key + " must be a six-digit hex color."); + return value.toLowerCase(); +} + +export function validateSkinLayout(value: unknown): SkinLayoutDocument { + if (!isRecord(value) || value.schemaVersion !== 1 || !isRecord(value.pages)) { + throw new Error("Skin layout must use schemaVersion 1 and contain a pages object."); + } + assertOnlyKeys(value, new Set(["schemaVersion", "pages"]), "Skin layout"); + const pages: SkinLayoutDocument["pages"] = {}; + let placementCount = 0; + + for (const [pageKey, pageValue] of Object.entries(value.pages)) { + if (!(["home", "voice", "demo"] as string[]).includes(pageKey) || !isRecord(pageValue)) { + throw new Error("Skin layout contains an unsupported page."); + } + assertOnlyKeys(pageValue, new Set(["desktop", "tablet", "mobile"]), "Skin layout page"); + const profiles: Partial>> = {}; + for (const profile of ["desktop", "tablet", "mobile"] as const) { + const profileValue = pageValue[profile]; + if (profileValue === undefined) continue; + if (!isRecord(profileValue)) throw new Error("Skin layout profile must be a component map."); + const placements: Record = {}; + for (const [id, rawPlacement] of Object.entries(profileValue)) { + placementCount += 1; + if (placementCount > 512) throw new Error("Skin layout contains too many component placements."); + const component = getSkinLayoutComponent(id, pageKey as SkinLayoutPage); + if (!component) throw new Error("Skin layout references an unknown component: " + id); + if (!component.editable) throw new Error("Skin layout cannot change trusted component: " + id); + if (!isRecord(rawPlacement)) throw new Error("Skin component placement must be an object."); + assertOnlyKeys(rawPlacement, ALLOWED_PLACEMENT_FIELDS, "Skin component placement"); + const supportedFields = new Set(); + if (component.layoutModes.includes("visibility")) supportedFields.add("visible"); + if (component.layoutModes.includes("position")) { supportedFields.add("x"); supportedFields.add("y"); } + if (component.layoutModes.includes("size")) { supportedFields.add("scale"); supportedFields.add("width"); supportedFields.add("height"); } + if (component.layoutModes.includes("appearance")) component.allowedStyleTokens.forEach((token) => supportedFields.add(token)); + assertOnlyKeys(rawPlacement, supportedFields, "Skin component placement"); + const placement: SkinLayoutPlacement = {}; + if (rawPlacement.visible !== undefined) { + if (typeof rawPlacement.visible !== "boolean") throw new Error("Skin layout visible must be a boolean."); + placement.visible = rawPlacement.visible; + } + const x = readNumber(rawPlacement.x, "x", -2000, 2000); + const y = readNumber(rawPlacement.y, "y", -2000, 2000); + const scale = readNumber(rawPlacement.scale, "scale", component.minScale, component.maxScale); + const width = readNumber(rawPlacement.width, "width", component.minWidth, component.maxWidth); + const height = readNumber(rawPlacement.height, "height", component.minHeight, component.maxHeight); + const radius = readNumber(rawPlacement.radius, "radius", 0, 64); + if (x !== undefined) placement.x = x; + if (y !== undefined) placement.y = y; + if (scale !== undefined) placement.scale = scale; + if (width !== undefined) placement.width = width; + if (height !== undefined) placement.height = height; + if (radius !== undefined) placement.radius = radius; + const foreground = readColor(rawPlacement.foreground, "foreground"); + const background = readColor(rawPlacement.background, "background"); + const border = readColor(rawPlacement.border, "border"); + if (foreground !== undefined) placement.foreground = foreground; + if (background !== undefined) placement.background = background; + if (border !== undefined) placement.border = border; + placements[id] = placement; + } + profiles[profile] = placements; + } + pages[pageKey as SkinLayoutPage] = profiles; + } + + return { schemaVersion: 1, pages }; +} + +export function parseSkinLayoutJson(source: string): SkinLayoutDocument { + if (!source || new TextEncoder().encode(source).byteLength > 128 * 1024) { + throw new Error("Skin layout must be smaller than 128 KiB."); + } + let value: unknown; + try { value = JSON.parse(source); } + catch { throw new Error("Skin layout is not valid JSON."); } + return validateSkinLayout(value); +} diff --git a/web/public/skin-wasm-interpreter.wasm b/web/public/skin-wasm-interpreter.wasm new file mode 100644 index 0000000..5c8bb2d Binary files /dev/null and b/web/public/skin-wasm-interpreter.wasm differ diff --git a/web/public/skins/illusia-voice.wskin b/web/public/skins/illusia-voice.wskin index 65042d6..d8544f8 100644 Binary files a/web/public/skins/illusia-voice.wskin and b/web/public/skins/illusia-voice.wskin differ diff --git a/web/skin-wasm-interpreter/Cargo.lock b/web/skin-wasm-interpreter/Cargo.lock new file mode 100644 index 0000000..7263e6a --- /dev/null +++ b/web/skin-wasm-interpreter/Cargo.lock @@ -0,0 +1,189 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "string-interner" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0" +dependencies = [ + "hashbrown 0.15.5", + "serde", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "wasmi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27" +dependencies = [ + "spin", + "wasmi_collections", + "wasmi_core", + "wasmi_ir", + "wasmparser", +] + +[[package]] +name = "wasmi_collections" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557" +dependencies = [ + "string-interner", +] + +[[package]] +name = "wasmi_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa" +dependencies = [ + "libm", +] + +[[package]] +name = "wasmi_ir" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6" +dependencies = [ + "wasmi_core", +] + +[[package]] +name = "wasmparser" +version = "0.228.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3" +dependencies = [ + "bitflags", + "indexmap", +] + +[[package]] +name = "webspeak-skin-wasm-interpreter" +version = "0.1.0" +dependencies = [ + "wasmi", +] diff --git a/web/skin-wasm-interpreter/Cargo.toml b/web/skin-wasm-interpreter/Cargo.toml new file mode 100644 index 0000000..6d982f4 --- /dev/null +++ b/web/skin-wasm-interpreter/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "webspeak-skin-wasm-interpreter" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +# On wasm32, the portable loop dispatcher prevents one native Wasm stack frame per guest instruction. +wasmi = { version = "=2.0.0", default-features = false, features = ["std", "validate", "portable-dispatch"] } diff --git a/web/skin-wasm-interpreter/NOTICE.md b/web/skin-wasm-interpreter/NOTICE.md new file mode 100644 index 0000000..6407e0c --- /dev/null +++ b/web/skin-wasm-interpreter/NOTICE.md @@ -0,0 +1,6 @@ +The browser interpreter artifact is built from `wasmi` 2.0.0, licensed under either MIT or Apache-2.0. See the upstream license texts at: + +- https://github.com/wasmi-labs/wasmi/blob/v2.0.0/LICENSE-MIT +- https://github.com/wasmi-labs/wasmi/blob/v2.0.0/LICENSE-APACHE + +The checked-in `.wasm` artifact is generated from the source in this directory and is not a remotely downloaded runtime. diff --git a/web/skin-wasm-interpreter/rust-toolchain.toml b/web/skin-wasm-interpreter/rust-toolchain.toml new file mode 100644 index 0000000..4aff397 --- /dev/null +++ b/web/skin-wasm-interpreter/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.99.0" +profile = "minimal" +targets = ["wasm32-unknown-unknown"] diff --git a/web/skin-wasm-interpreter/src/lib.rs b/web/skin-wasm-interpreter/src/lib.rs new file mode 100644 index 0000000..89f6fad --- /dev/null +++ b/web/skin-wasm-interpreter/src/lib.rs @@ -0,0 +1,278 @@ +use wasmi::{ + Caller, Config, Engine, EnforcedLimits, Linker, Memory, MemoryType, Module, Store, + StoreLimits, StoreLimitsBuilder, +}; + +const SOURCE_LIMIT: usize = 256 * 1024; +const STATUS_LIMIT: usize = 512; +const MEMORY_LIMIT_BYTES: usize = 64 * 64 * 1024; +const STATUS_READ_LIMIT: u32 = 10; +const FUEL_LIMIT: u64 = 10_000_000; + +const ERROR_NONE: u32 = 0; +const ERROR_INPUT: u32 = 1; +const ERROR_MODULE: u32 = 2; +const ERROR_EXPORT: u32 = 4; +const ERROR_EXECUTION: u32 = 5; +const ERROR_HOST_MEMORY: u32 = 6; +const ERROR_MEMORY_LINK: u32 = 7; +const ERROR_STATUS_LINK: u32 = 8; +const ERROR_INSTANTIATION: u32 = 9; +const ERROR_IMPORT: u32 = 10; +const ERROR_PERMISSION: u32 = 11; + +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_DIAGNOSTIC: [u8; 256] = [0; 256]; +static mut LAST_DIAGNOSTIC_LENGTH: u32 = 0; + +struct HostState { + limits: StoreLimits, + status: Vec, + status_read_count: u32, +} + +#[unsafe(no_mangle)] +pub extern "C" fn alloc(size: u32) -> u32 { + if size == 0 || size as usize > SOURCE_LIMIT + STATUS_LIMIT { + return 0; + } + let allocation = Vec::::with_capacity(size as usize); + let pointer = allocation.as_ptr() as usize as u32; + core::mem::forget(allocation); + pointer +} + +/// Runs one untrusted module inside Wasmi, whose entire allocator is bounded by +/// the fixed maximum memory of this outer Wasm artifact. +/// +/// The web worker validates the byte ranges and permission grant before calling +/// this ABI. Every invocation gets a new Store, module, memory, and linker. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn run( + module_pointer: u32, + module_length: u32, + status_pointer: u32, + status_length: u32, + status_permission_granted: u32, + memory_maximum_pages: u32, + fuel: u64, +) -> i64 { + clear_diagnostic(); + set_report(ERROR_NONE, 0, 0); + 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) + || !(1..=64).contains(&memory_maximum_pages) + || fuel == 0 + || fuel > FUEL_LIMIT + { + set_report(ERROR_INPUT, 0, 0); + return 0; + } + + let module_bytes = core::slice::from_raw_parts(module_pointer as usize as *const u8, module_length as usize); + let status = if status_length == 0 { + Vec::new() + } else { + core::slice::from_raw_parts(status_pointer as usize as *const u8, status_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)) => { + set_report(ERROR_NONE, status_reads, guest_memory_bytes); + result as i64 + } + Err((error, status_reads, guest_memory_bytes)) => { + set_report(error, status_reads, guest_memory_bytes); + 0 + } + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_error_code() -> u32 { + unsafe { LAST_ERROR_CODE } +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_status_read_count() -> u32 { + unsafe { LAST_STATUS_READ_COUNT } +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_guest_memory_bytes() -> u32 { + unsafe { LAST_GUEST_MEMORY_BYTES } +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_diagnostic_pointer() -> u32 { + core::ptr::addr_of!(LAST_DIAGNOSTIC) as usize as u32 +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_diagnostic_length() -> u32 { + unsafe { LAST_DIAGNOSTIC_LENGTH } +} + +fn clear_diagnostic() { + unsafe { LAST_DIAGNOSTIC_LENGTH = 0; } +} + +fn set_diagnostic(message: &str) { + let bytes = message.as_bytes(); + let length = bytes.len().min(255); + unsafe { + let destination = core::ptr::addr_of_mut!(LAST_DIAGNOSTIC).cast::(); + core::ptr::copy_nonoverlapping(bytes.as_ptr(), destination, length); + LAST_DIAGNOSTIC_LENGTH = length as u32; + } +} + +fn set_report(error: u32, status_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_GUEST_MEMORY_BYTES = guest_memory_bytes; + } +} + +fn execute( + module_bytes: &[u8], + status: Vec, + status_permission_granted: bool, + memory_maximum_pages: u32, + fuel: u64, +) -> Result<(i32, u32, u32), (u32, u32, u32)> { + let mut config = Config::default(); + config + .consume_fuel(true) + .allow_start_fn(false) + .wasm_reference_types(false) + .wasm_multi_memory(false) + .wasm_bulk_memory(true) + .set_max_recursion_depth(128) + .set_max_stack_height(64 * 1024) + .set_max_cached_stacks(0) + .enforced_limits(EnforcedLimits::strict()); + let engine = Engine::new(&config); + let module = Module::new(&engine, &mut &module_bytes[..]) + .map_err(|_| (ERROR_MODULE, 0, 0))?; + let mut saw_memory = false; + let mut saw_status = false; + for import in module.imports() { + match (import.module(), import.name(), import.ty()) { + ("env", "memory", wasmi::ExternType::Memory(memory_type)) + if !saw_memory + && memory_type.minimum() <= 1 + && memory_type.maximum().unwrap_or(64) == memory_maximum_pages as u64 + && memory_type.maximum().unwrap_or(64) <= 64 => + { + saw_memory = true; + } + ("env", "session_status_read", wasmi::ExternType::Func(_)) + if !saw_status && status_permission_granted => + { + saw_status = true; + } + ("env", "session_status_read", wasmi::ExternType::Func(_)) => { + return Err((ERROR_PERMISSION, 0, 0)); + } + _ => return Err((ERROR_IMPORT, 0, 0)), + } + } + if !saw_memory { + return Err((ERROR_IMPORT, 0, 0)); + } + let mut exports = module.exports(); + let Some(entry) = exports.next() else { + return Err((ERROR_EXPORT, 0, 0)); + }; + if entry.name() != "run" + || !matches!(entry.ty(), wasmi::ExternType::Func(_)) + || exports.next().is_some() + { + return Err((ERROR_EXPORT, 0, 0)); + } + + let limits = StoreLimitsBuilder::new() + .memory_size(MEMORY_LIMIT_BYTES) + .table_elements(0) + .instances(1) + // Wasmi counts the host-created import and the instantiated module's + // view of that import independently inside one Store. + .memories(2) + .tables(0) + .trap_on_grow_failure(true) + .build(); + let mut store = Store::new(&engine, HostState { limits, status, status_read_count: 0 }); + store.limiter(|state| &mut state.limits); + store.set_fuel(fuel).map_err(|_| (ERROR_EXECUTION, 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))?; + let mut linker = Linker::::new(&engine); + linker + .define("env", "memory", memory) + .map_err(|_| (ERROR_MEMORY_LINK, 0, 0))?; + + if status_permission_granted { + let status_memory = memory; + linker + .func_wrap( + "env", + "session_status_read", + move |mut caller: Caller<'_, HostState>, pointer: i32, capacity: i32| -> i32 { + if pointer < 0 || capacity < 0 { + return -1; + } + let offset = pointer as usize; + let capacity = capacity as usize; + let (status_size, reads, memory_size) = { + let state = caller.data(); + (state.status.len(), state.status_read_count, status_memory.data(&caller).len()) + }; + if status_size == 0 + || reads >= STATUS_READ_LIMIT + || capacity < status_size + || offset > memory_size.saturating_sub(capacity) + { + return -1; + } + let status = caller.data().status.clone(); + if status_memory.write(&mut caller, offset, &status).is_err() { + return -1; + } + caller.data_mut().status_read_count += 1; + status_size as i32 + }, + ) + .map_err(|_| (ERROR_STATUS_LINK, 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)); + } + }; + let function = instance + .get_typed_func::<(), i32>(&store, "run") + .map_err(|_| (ERROR_EXPORT, store.data().status_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))?; + + Ok(( + result, + store.data().status_read_count, + memory.data(&store).len() as u32, + )) +} diff --git a/web/src/App.vue b/web/src/App.vue index b3572ea..f976612 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -1,7 +1,12 @@ + + diff --git a/web/src/components/SkinLoadRecoveryNotice.vue b/web/src/components/SkinLoadRecoveryNotice.vue new file mode 100644 index 0000000..95248dc --- /dev/null +++ b/web/src/components/SkinLoadRecoveryNotice.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/web/src/composables/usePublicSkin.ts b/web/src/composables/usePublicSkin.ts index 8eae77c..a24dcf4 100644 --- a/web/src/composables/usePublicSkin.ts +++ b/web/src/composables/usePublicSkin.ts @@ -22,6 +22,7 @@ export function usePublicSkin(options: PublicSkinOptions = {}) { const stored = getStoredSkinId(); const activeSkinId = ref(stored ?? fallbackId()); const skinReady = ref(Boolean(stored && builtin(stored))); + const skinLoadError = shallowRef<{ skinId: string } | null>(null); const installedSkins = ref([]); const catalogSkins = ref([...BUILTIN_SKIN_CATALOG]); let current: ReturnType | undefined; @@ -34,34 +35,38 @@ export function usePublicSkin(options: PublicSkinOptions = {}) { } onScopeDispose(() => { disposed = true; cancel(); }); - async function apply(id: string, operation: ReturnType, persist = true, updateTheme = false) { + async function apply(id: string, operation: ReturnType, persist = true, updateTheme = false, clearLoadError = true) { operation.check(); const entry = catalogSkins.value.find(skin => skin.id === id); const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal })); if (!owns(operation)) return; + if (!builtin(id) && !skin) throw new Error("The selected skin could not be activated."); activeSkin.value = skin; activeSkinId.value = skin?.id ?? (builtin(id) ? id : fallbackId()); + if (clearLoadError) skinLoadError.value = null; const mode = activeSkinId.value === BUILTIN_LIGHT_SKIN ? "light" : activeSkinId.value === BUILTIN_DARK_SKIN ? "dark" : isDarkTheme(getStoredTheme()) ? "dark" : "light"; if (options.themeMode && updateTheme) { options.themeMode.value = mode; - saveTheme(mode); + saveTheme(mode, { preserveCustomSkins: !builtin(activeSkinId.value) }); } if (persist) void saveLocalPreferences({ schemaVersion: 1, skinId: activeSkinId.value, ...(options.themeMode && updateTheme ? { theme: mode } : {}) }, operation.signal).catch(() => undefined); } - async function recover(error: unknown, operation: ReturnType) { + async function recover(error: unknown, operation: ReturnType, failedSkinId: string) { if (!owns(operation) || (error as { name?: string })?.name === "AbortError") return; + if (!builtin(failedSkinId)) skinLoadError.value = { skinId: failedSkinId }; // Retire every stage of the old operation before installing a fallback. operation.cancel(); const fallback = begin(); - try { await apply(fallbackId(), fallback, false); } + try { await apply(fallbackId(), fallback, false, false, false); } catch { /* A newer selection or page can retire the fallback as well. */ } finally { if (owns(fallback)) skinReady.value = true; fallback.finish(); } } async function initialize() { if (disposed) return; const operation = begin(); + let requestedSkinId = fallbackId(); try { const [preferences, installed, available] = await operation.wait(Promise.all([ loadLocalPreferences(), listInstalledSkins(), listPublicSkins({ signal: operation.signal }), @@ -74,8 +79,9 @@ export function usePublicSkin(options: PublicSkinOptions = {}) { } // Only an explicit user choice overrides the instance default. const choice = readChoice(); - await apply(choice && isPublicSkinEnabled(choice) ? choice : getPublicDefaultSkinId(), operation); - } catch (error) { await recover(error, operation); } + requestedSkinId = choice && isPublicSkinEnabled(choice) ? choice : getPublicDefaultSkinId(); + await apply(requestedSkinId, operation); + } catch (error) { await recover(error, operation, requestedSkinId); } finally { if (owns(operation)) skinReady.value = true; operation.finish(); } } async function select(id: string) { @@ -84,12 +90,13 @@ export function usePublicSkin(options: PublicSkinOptions = {}) { try { try { localStorage.setItem("webspeak:skin-choice", id); } catch { /* Optional storage. */ } await apply(id, operation, true, true); - } catch (error) { await recover(error, operation); } + } catch (error) { await recover(error, operation, id); } finally { if (owns(operation)) skinReady.value = true; operation.finish(); } } async function reset() { if (disposed) return; const operation = begin(); + skinLoadError.value = null; clearCustomSkinStyle(); activeSkin.value = null; installedSkins.value = []; @@ -104,5 +111,10 @@ export function usePublicSkin(options: PublicSkinOptions = {}) { catch { /* Reset remains usable even if refreshing the optional catalog fails. */ } finally { operation.finish(); } } - return { activeSkin, activeSkinId, skinReady, installedSkins, catalogSkins, initialize, select, cancel, reset }; + async function switchToBuiltInAfterLoadError(): Promise { + if (!skinLoadError.value) return; + await select(fallbackId()); + } + + return { activeSkin, activeSkinId, skinReady, skinLoadError, installedSkins, catalogSkins, initialize, select, cancel, reset, switchToBuiltInAfterLoadError }; } diff --git a/web/src/composables/useSkinLayoutEditor.ts b/web/src/composables/useSkinLayoutEditor.ts new file mode 100644 index 0000000..b81d9d6 --- /dev/null +++ b/web/src/composables/useSkinLayoutEditor.ts @@ -0,0 +1,657 @@ +import { computed, nextTick, onMounted, onUnmounted, ref, shallowRef } from "vue"; +import { + canEditSkinLayoutComponent, + getSkinLayoutComponentId, + getSkinLayoutComponent, + getSkinLayoutComponents, + type SkinLayoutDocument, + type SkinLayoutPlacement, +} from "../../../src/shared/skin-layout.js"; +import { analyzeSkinLayoutGeometry, clampSkinLayoutOffset, getSkinLayoutOffsetBounds } from "../services/skin-layout-geometry.js"; +import type { SkinLayoutOffsetBounds } from "../services/skin-layout-geometry.js"; +import { orderSequentialFocusTargets } from "../services/skin-layout-focus.js"; +import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js"; +import { + clearActiveSkinLayoutOverrides, + getActiveSkinLayoutContext, + getActiveSkinLayoutOverride, + getActiveSkinLayoutOverrides, + getEffectiveSkinLayoutPlacement, + initializeSkinLayoutRuntime, + previewActiveSkinLayoutPlacement, + refreshSkinLayout, + replaceActiveSkinLayoutOverrides, + saveActiveSkinLayoutPlacement, + setSkinLayoutEditorState, + type ActiveSkinLayoutContext, +} from "../services/skin-layout-runtime.js"; +import { + exportSkinLayout, + exportSkinLayoutMigrationRecovery, + getSkinLayoutMigrationRecovery, + importSkinLayout, +} from "../services/skin-layout-storage.js"; + +interface DragState { + pointerId: number; + componentId: string; + startX: number; + startY: number; + originX: number; + originY: number; + placement: SkinLayoutPlacement; + changed: boolean; +} + +interface FocusPreviewTarget { + key: string; + tabIndex: number; + componentName: string; + accessibleName: string; + left: number; + top: number; + width: number; + height: number; + meetsTouchTarget: boolean; + order?: number; +} + +function componentIdForElement(element: HTMLElement): string | null { + return getSkinLayoutComponentId(element.dataset.wsPart, element.dataset.wsControlKind); +} + +export function useSkinLayoutEditor() { + const isOpen = ref(false); + const isEditing = ref(false); + const canUndo = ref(false); + const canRedo = ref(false); + const focusPreviewEnabled = ref(false); + const filter = ref(""); + const selectedComponentId = ref(""); + const statusMessage = ref(""); + const ignoredWarningKey = ref(""); + const context = shallowRef(null); + const revision = ref(0); + let contextKey = ""; + let observer: MutationObserver | null = null; + let drag: DragState | null = null; + let viewportRefreshFrame = 0; + let geometryRefreshFrame = 0; + let geometryRefreshQueued = false; + let history: SkinLayoutDocument[] = []; + let historyIndex = -1; + let lastHistoryChangeAt = 0; + + const labels = computed(() => skinLayoutLabels[context.value?.root.lang ? resolveSkinLayoutLanguage(context.value.root.lang) : "zh"]); + const available = computed(() => Boolean(context.value)); + const components = computed(() => { + revision.value; + const page = context.value?.page; + return page ? getSkinLayoutComponents(page).filter((component) => component.editable) : []; + }); + const filteredComponents = computed(() => { + const search = filter.value.trim().toLowerCase(); + return components.value.filter((component) => !search || component.id.toLowerCase().includes(search) + || component.name.toLowerCase().includes(search)); + }); + const selectedPlacement = computed(() => { + revision.value; + return selectedComponentId.value ? getEffectiveSkinLayoutPlacement(selectedComponentId.value) ?? {} : {}; + }); + const selectedVisible = computed(() => selectedPlacement.value.visible !== false); + const selectedScale = computed(() => selectedPlacement.value.scale ?? 1); + const selectedWidth = computed(() => selectedPlacement.value.width ?? 320); + const selectedHeight = computed(() => selectedPlacement.value.height ?? 160); + const selectedX = computed(() => selectedPlacement.value.x ?? 0); + const selectedY = computed(() => selectedPlacement.value.y ?? 0); + const selectedForeground = computed(() => selectedPlacement.value.foreground ?? "#ffffff"); + const selectedBackground = computed(() => selectedPlacement.value.background ?? "#ffffff"); + const selectedBorder = computed(() => selectedPlacement.value.border ?? "#ffffff"); + const selectedRadius = computed(() => selectedPlacement.value.radius ?? 0); + const selectedComponent = computed(() => context.value && selectedComponentId.value + ? getSkinLayoutComponent(selectedComponentId.value, context.value.page) : undefined); + const focusPreviewTargets = computed(() => { + revision.value; + const active = context.value; + if (!active || !focusPreviewEnabled.value) return []; + const candidates: FocusPreviewTarget[] = []; + const selector = "a[href], area[href], button, input, select, textarea, iframe, summary, [tabindex], [contenteditable]:not([contenteditable='false']), audio[controls], video[controls]"; + const focusable = [...active.root.querySelectorAll(selector)]; + const isVisibleFocusTarget = (element: HTMLElement) => { + if (element.tabIndex < 0 || element.matches(":disabled") || element.closest("[hidden], [inert]")) return false; + if (!element.getClientRects().length) return false; + const style = window.getComputedStyle(element); + return style.visibility !== "hidden" && style.visibility !== "collapse"; + }; + const radioGroups = new Map>(); + for (const element of active.root.querySelectorAll('input[type="radio"][name]')) { + const owner = element.form ?? element.getRootNode() as object; + let groups = radioGroups.get(owner); + if (!groups) radioGroups.set(owner, groups = new Map()); + const group = groups.get(element.name) ?? []; + group.push(element); + groups.set(element.name, group); + } + for (const element of focusable) { + if (!isVisibleFocusTarget(element)) continue; + if (element instanceof HTMLInputElement && element.type === "radio" && element.name) { + const owner = element.form ?? element.getRootNode() as object; + const group = radioGroups.get(owner)?.get(element.name) ?? [element]; + const activeRadio = group.find((radio) => radio.checked && isVisibleFocusTarget(radio)) + ?? group.find(isVisibleFocusTarget); + if (activeRadio !== element) continue; + } + const owner = element.closest("[data-ws-part]"); + if (!owner || !active.root.contains(owner)) continue; + const id = componentIdForElement(owner); + const component = id ? getSkinLayoutComponent(id, active.page) : undefined; + if (!id || !component || component.category === "trusted-chrome" + || !canEditSkinLayoutComponent(id, active.page, ancestorComponentIds(owner, active.root))) continue; + const rect = element.getBoundingClientRect(); + const labelledBy = element.getAttribute("aria-labelledby")?.split(/\s+/) + .map((labelId) => document.getElementById(labelId)?.textContent ?? "").filter(Boolean).join(" "); + const nativeLabels = "labels" in element + ? [...((element as HTMLInputElement).labels ?? [])].map((label) => label.textContent ?? "").join(" ") : ""; + const accessibleName = (labelledBy || element.getAttribute("aria-label") || nativeLabels + || element.getAttribute("alt") || element.getAttribute("title") || element.getAttribute("placeholder") + || element.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100); + candidates.push({ + key: `${id}:${candidates.length}`, + tabIndex: element.tabIndex, + componentName: component.name, + accessibleName, + left: rect.left, + top: rect.top, + width: rect.width, + height: rect.height, + meetsTouchTarget: rect.width >= 44 && rect.height >= 44, + }); + } + return orderSequentialFocusTargets(candidates).map((target, index) => ({ ...target, order: index + 1 })); + }); + const selectedSizeBounds = computed(() => selectedComponent.value ?? { + minWidth: 44, maxWidth: 2400, minHeight: 44, maxHeight: 2400, minScale: 0.25, maxScale: 4, + }); + const migrationRecovery = computed(() => { + revision.value; + return context.value ? getSkinLayoutMigrationRecovery(context.value.skinId) : null; + }); + const migrationRecoveryCount = computed(() => migrationRecovery.value + ? migrationRecovery.value.items.length + migrationRecovery.value.omittedCount : 0); + function ancestorComponentIds(element: HTMLElement, root: HTMLElement): string[] { + const ids: string[] = []; + let ancestor = element.parentElement; + while (ancestor && ancestor !== root) { + const id = componentIdForElement(ancestor); + if (id) ids.push(id); + ancestor = ancestor.parentElement; + } + return ids; + } + + function componentTargets(active: ActiveSkinLayoutContext, id: string): HTMLElement[] { + const component = getSkinLayoutComponent(id, active.page); + if (!component) return []; + return [...active.root.querySelectorAll(`[data-ws-part="${component.selectorPart}"]`)].filter((element) => { + if (component.controlKind && element.dataset.wsControlKind !== component.controlKind) return false; + if (!canEditSkinLayoutComponent(id, active.page, ancestorComponentIds(element, active.root))) return false; + return Boolean(element.getClientRects().length) && element.dataset.wsLayoutHidden !== "true"; + }); + } + + function offsetBounds(axis: "x" | "y"): SkinLayoutOffsetBounds | null { + const active = context.value; + const id = selectedComponentId.value; + if (!active || !id) return null; + const targets = componentTargets(active, id).map((element) => element.getBoundingClientRect()); + if (!targets.length) return null; + const currentOffset = selectedPlacement.value[axis] ?? 0; + return getSkinLayoutOffsetBounds(targets, active.root.getBoundingClientRect(), currentOffset, axis) + ?? { minimum: 0, maximum: 0 }; + } + + const positionBoundsX = computed(() => { + revision.value; + return offsetBounds("x") ?? { minimum: -2000, maximum: 2000 }; + }); + const positionBoundsY = computed(() => { + revision.value; + return offsetBounds("y") ?? { minimum: -2000, maximum: 2000 }; + }); + + const detectedLayoutWarnings = computed(() => { + revision.value; + const active = context.value; + const id = selectedComponentId.value; + const placement = selectedPlacement.value; + if (!active || !id || placement.visible === false + || ![placement.x, placement.y, placement.width, placement.height, placement.scale].some((value) => value !== undefined)) return []; + const targets = componentTargets(active, id); + if (!targets.length) return []; + const targetSet = new Set(targets); + const peers = [...active.root.querySelectorAll("[data-ws-part]")].filter((peer) => { + if (targetSet.has(peer) || !peer.getClientRects().length) return false; + const peerId = componentIdForElement(peer); + if (!peerId) return false; + return targets.every((target) => !peer.contains(target) && !target.contains(peer)); + }).map((peer) => peer.getBoundingClientRect()); + const issues = analyzeSkinLayoutGeometry( + targets.map((element) => element.getBoundingClientRect()), + active.root.getBoundingClientRect(), + peers, + ); + const warnings: string[] = []; + if (issues.overflow) warnings.push(labels.value.overflowWarning); + if (issues.overlap) warnings.push(labels.value.overlapWarning); + return warnings; + }); + + function currentWarningKey(): string { + const active = context.value; + return active ? [active.skinId, active.page, active.profile, selectedComponentId.value, JSON.stringify(selectedPlacement.value)].join(":") : ""; + } + + const layoutWarnings = computed(() => ignoredWarningKey.value === currentWarningKey() ? [] : detectedLayoutWarnings.value); + + function ignoreLayoutWarnings(): void { + if (layoutWarnings.value.length) ignoredWarningKey.value = currentWarningKey(); + } + + function reviseLayout(): void { + revision.value += 1; + if (typeof window === "undefined" || geometryRefreshQueued) return; + geometryRefreshQueued = true; + void nextTick(() => { + if (!geometryRefreshQueued) return; + geometryRefreshFrame = window.requestAnimationFrame(() => { + geometryRefreshFrame = 0; + geometryRefreshQueued = false; + revision.value += 1; + }); + }); + } + + function syncContext(): void { + const next = getActiveSkinLayoutContext(); + const key = next ? [next.skinId, next.page, next.profile, next.root.lang].join(":") : ""; + if (key === contextKey) return; + contextKey = key; + context.value = next; + history = next ? [getActiveSkinLayoutOverrides()] : []; + historyIndex = history.length ? 0 : -1; + lastHistoryChangeAt = 0; + updateHistoryControls(); + const first = next ? getSkinLayoutComponents(next.page).find((component) => component.editable)?.id ?? "" : ""; + if (!next || !getSkinLayoutComponent(selectedComponentId.value, next.page)?.editable) selectedComponentId.value = first; + reviseLayout(); + setSkinLayoutEditorState(isEditing.value, selectedComponentId.value || null); + } + + function scheduleViewportRefresh(): void { + if (viewportRefreshFrame) window.cancelAnimationFrame(viewportRefreshFrame); + viewportRefreshFrame = window.requestAnimationFrame(() => { + viewportRefreshFrame = 0; + const previousRevision = revision.value; + syncContext(); + if (revision.value === previousRevision) revision.value += 1; + }); + } + + function selectComponent(id: string): void { + if (!context.value || !getSkinLayoutComponent(id, context.value.page)?.editable) return; + selectedComponentId.value = id; + reviseLayout(); + setSkinLayoutEditorState(isEditing.value, id); + } + + function setEditing(value: boolean): void { + isEditing.value = value; + setSkinLayoutEditorState(value, value ? selectedComponentId.value || null : null); + } + + function setFocusPreview(value: boolean): void { + focusPreviewEnabled.value = value; + reviseLayout(); + } + + function setOpen(value: boolean): void { + isOpen.value = value; + statusMessage.value = ""; + if (!value) setEditing(false); + } + + function updateSelected(field: keyof SkinLayoutPlacement, value: boolean | number | string): void { + if (!selectedComponentId.value) return; + ignoredWarningKey.value = ""; + const local = getActiveSkinLayoutOverride(selectedComponentId.value) ?? {}; + const next = { ...local, [field]: value } as SkinLayoutPlacement; + try { + saveActiveSkinLayoutPlacement(selectedComponentId.value, next); + recordHistory(); + statusMessage.value = ""; + } catch { + statusMessage.value = labels.value.saveFailed; + return; + } + reviseLayout(); + } + + function setVisible(value: boolean): void { updateSelected("visible", value); } + function setX(value: number): void { updateSelected("x", clampSkinLayoutOffset(value, offsetBounds("x") ?? { minimum: -2000, maximum: 2000 })); } + function setY(value: number): void { updateSelected("y", clampSkinLayoutOffset(value, offsetBounds("y") ?? { minimum: -2000, maximum: 2000 })); } + function setScale(value: number): void { updateSelected("scale", Math.max(selectedSizeBounds.value.minScale, Math.min(selectedSizeBounds.value.maxScale, value))); } + function setWidth(value: number): void { updateSelected("width", Math.max(selectedSizeBounds.value.minWidth, Math.min(selectedSizeBounds.value.maxWidth, Math.round(value)))); } + function setHeight(value: number): void { updateSelected("height", Math.max(selectedSizeBounds.value.minHeight, Math.min(selectedSizeBounds.value.maxHeight, Math.round(value)))); } + function setForeground(value: string): void { updateSelected("foreground", value); } + function setBackground(value: string): void { updateSelected("background", value); } + function setBorder(value: string): void { updateSelected("border", value); } + function setRadius(value: number): void { updateSelected("radius", Math.max(0, Math.min(64, value))); } + + function resetComponent(): void { + if (!selectedComponentId.value) return; + try { + saveActiveSkinLayoutPlacement(selectedComponentId.value, null); + recordHistory(true); + statusMessage.value = ""; + } catch { + statusMessage.value = labels.value.saveFailed; + return; + } + reviseLayout(); + } + + function resetAll(): void { + try { + clearActiveSkinLayoutOverrides(); + statusMessage.value = ""; + recordHistory(true); + } catch { statusMessage.value = labels.value.saveFailed; } + reviseLayout(); + } + + function updateHistoryControls(): void { + canUndo.value = historyIndex > 0; + canRedo.value = historyIndex >= 0 && historyIndex < history.length - 1; + } + + function copyLayout(layout: SkinLayoutDocument): SkinLayoutDocument { + return JSON.parse(JSON.stringify(layout)) as SkinLayoutDocument; + } + + function recordHistory(forceNew = false): void { + if (!context.value) return; + const next = copyLayout(getActiveSkinLayoutOverrides()); + const now = Date.now(); + if (historyIndex < 0) { + history = [next]; + historyIndex = 0; + } else { + history = history.slice(0, historyIndex + 1); + if (!forceNew && historyIndex > 0 && now - lastHistoryChangeAt < 500) history[historyIndex] = next; + else { + history.push(next); + historyIndex += 1; + } + if (history.length > 50) { + history.shift(); + historyIndex -= 1; + } + } + lastHistoryChangeAt = now; + updateHistoryControls(); + } + + function undo(): void { + if (historyIndex <= 0) return; + const targetIndex = historyIndex - 1; + try { + replaceActiveSkinLayoutOverrides(copyLayout(history[targetIndex])); + historyIndex = targetIndex; + lastHistoryChangeAt = 0; + statusMessage.value = ""; + reviseLayout(); + } catch { statusMessage.value = labels.value.saveFailed; } + updateHistoryControls(); + } + + function redo(): void { + if (historyIndex < 0 || historyIndex >= history.length - 1) return; + const targetIndex = historyIndex + 1; + try { + replaceActiveSkinLayoutOverrides(copyLayout(history[targetIndex])); + historyIndex = targetIndex; + lastHistoryChangeAt = 0; + statusMessage.value = ""; + reviseLayout(); + } catch { statusMessage.value = labels.value.saveFailed; } + updateHistoryControls(); + } + + function exportCurrent(): void { + if (!context.value) return; + const blob = new Blob([exportSkinLayout(getActiveSkinLayoutOverrides())], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = "webspeak-layout-" + context.value.skinId.replace(/[^a-z0-9.-]/g, "-") + ".json"; + anchor.click(); + window.setTimeout(() => URL.revokeObjectURL(url), 30_000); + } + + function exportRecovery(): void { + const skinId = context.value?.skinId; + if (!skinId || !migrationRecovery.value) return; + const blob = new Blob([exportSkinLayoutMigrationRecovery(skinId)], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = "webspeak-layout-recovery-" + skinId.replace(/[^a-z0-9.-]/g, "-") + ".json"; + anchor.click(); + window.setTimeout(() => URL.revokeObjectURL(url), 30_000); + } + + async function importFile(file: File | undefined): Promise { + if (!file) return; + if (file.size > 128 * 1024) { + statusMessage.value = labels.value.importFailed; + return; + } + try { + replaceActiveSkinLayoutOverrides(importSkinLayout(await file.text())); + recordHistory(true); + statusMessage.value = labels.value.imported; + reviseLayout(); + } catch { + statusMessage.value = labels.value.importFailed; + } + } + + function startDrag(event: PointerEvent): void { + if (!isEditing.value || !context.value || !(event.target instanceof Element)) return; + if (event.target.closest("[data-ws-layout-editor]")) return; + const root = event.target.closest(".ws-skin-root[data-ws-page]"); + if (!root || root !== context.value.root) return; + const element = event.target.closest("[data-ws-part]"); + if (!element || !root.contains(element)) return; + const id = componentIdForElement(element); + const ancestors: string[] = []; + let ancestor = element.parentElement; + while (ancestor && ancestor !== root) { + const ancestorId = componentIdForElement(ancestor); + if (ancestorId) ancestors.push(ancestorId); + ancestor = ancestor.parentElement; + } + if (!id || !canEditSkinLayoutComponent(id, context.value.page, ancestors)) return; + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + selectComponent(id); + const placement = getEffectiveSkinLayoutPlacement(id) ?? {}; + drag = { + pointerId: event.pointerId, + componentId: id, + startX: event.clientX, + startY: event.clientY, + originX: placement.x ?? 0, + originY: placement.y ?? 0, + placement, + changed: false, + }; + } + + function moveDrag(event: PointerEvent): void { + if (!drag || event.pointerId !== drag.pointerId) return; + ignoredWarningKey.value = ""; + const xBounds = offsetBounds("x"); + const yBounds = offsetBounds("y"); + const x = clampSkinLayoutOffset(drag.originX + event.clientX - drag.startX, xBounds ?? { minimum: -2000, maximum: 2000 }); + const y = clampSkinLayoutOffset(drag.originY + event.clientY - drag.startY, yBounds ?? { minimum: -2000, maximum: 2000 }); + if (x === drag.originX && y === drag.originY) return; + drag.changed = true; + drag.placement = { ...drag.placement, x, y }; + previewActiveSkinLayoutPlacement(drag.componentId, drag.placement); + reviseLayout(); + } + + function endDrag(event: PointerEvent): void { + if (!drag || event.pointerId !== drag.pointerId) return; + const finished = drag; + drag = null; + if (finished.changed) { + const local = getActiveSkinLayoutOverride(finished.componentId) ?? {}; + try { + saveActiveSkinLayoutPlacement(finished.componentId, { + ...local, + x: finished.placement.x, + y: finished.placement.y, + }); + recordHistory(true); + } catch { + statusMessage.value = labels.value.saveFailed; + previewActiveSkinLayoutPlacement(finished.componentId, null); + } + } else { + previewActiveSkinLayoutPlacement(finished.componentId, null); + } + reviseLayout(); + } + + function cancelDrag(): void { + if (!drag) return; + previewActiveSkinLayoutPlacement(drag.componentId, null); + drag = null; + refreshSkinLayout(); + reviseLayout(); + } + + function onKeydown(event: KeyboardEvent): void { + if (!isOpen.value || !isEditing.value || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "z") return; + if (event.target instanceof HTMLElement && /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName)) return; + event.preventDefault(); + if (event.shiftKey) redo(); + else undo(); + } + + onMounted(() => { + initializeSkinLayoutRuntime(); + syncContext(); + observer = new MutationObserver(() => { + syncContext(); + if (focusPreviewEnabled.value) revision.value += 1; + }); + observer.observe(document.body, { + childList: true, + subtree: true, + characterData: true, + attributes: true, + attributeFilter: ["data-ws-page", "data-ws-skin", "lang", "tabindex", "disabled", "href", "aria-label", "aria-labelledby", "title", "placeholder", "hidden", "inert", "aria-hidden", "class", "style"], + }); + document.addEventListener("pointerdown", startDrag, true); + document.addEventListener("pointermove", moveDrag, true); + document.addEventListener("pointerup", endDrag, true); + document.addEventListener("pointercancel", endDrag, true); + document.addEventListener("keydown", onKeydown); + document.addEventListener("change", onFocusStateChange, true); + document.addEventListener("input", onFocusStateChange, true); + window.addEventListener("blur", cancelDrag); + window.addEventListener("resize", scheduleViewportRefresh, { passive: true }); + window.addEventListener("scroll", scheduleViewportRefresh, { capture: true, passive: true }); + }); + + function onFocusStateChange(): void { + if (focusPreviewEnabled.value) revision.value += 1; + } + + onUnmounted(() => { + observer?.disconnect(); + document.removeEventListener("pointerdown", startDrag, true); + document.removeEventListener("pointermove", moveDrag, true); + document.removeEventListener("pointerup", endDrag, true); + document.removeEventListener("pointercancel", endDrag, true); + document.removeEventListener("keydown", onKeydown); + document.removeEventListener("change", onFocusStateChange, true); + document.removeEventListener("input", onFocusStateChange, true); + window.removeEventListener("blur", cancelDrag); + window.removeEventListener("resize", scheduleViewportRefresh); + window.removeEventListener("scroll", scheduleViewportRefresh, true); + if (viewportRefreshFrame) window.cancelAnimationFrame(viewportRefreshFrame); + if (geometryRefreshFrame) window.cancelAnimationFrame(geometryRefreshFrame); + geometryRefreshQueued = false; + setSkinLayoutEditorState(false, null); + }); + + return { + isOpen, + isEditing, + available, + context, + labels, + filter, + filteredComponents, + selectedComponentId, + selectedPlacement, + selectedVisible, + selectedScale, + selectedWidth, + selectedHeight, + canUndo, + canRedo, + focusPreviewEnabled, + focusPreviewTargets, + selectedX, + selectedY, + selectedForeground, + selectedBackground, + selectedBorder, + selectedRadius, + selectedSizeBounds, + positionBoundsX, + positionBoundsY, + statusMessage, + layoutWarnings, + ignoreLayoutWarnings, + migrationRecovery, + migrationRecoveryCount, + setOpen, + setEditing, + setFocusPreview, + selectComponent, + setVisible, + setX, + setY, + setScale, + setWidth, + setHeight, + setForeground, + setBackground, + setBorder, + setRadius, + resetComponent, + resetAll, + undo, + redo, + exportCurrent, + exportRecovery, + importFile, + }; +} diff --git a/web/src/i18n/skin-layout.ts b/web/src/i18n/skin-layout.ts new file mode 100644 index 0000000..7d7289e --- /dev/null +++ b/web/src/i18n/skin-layout.ts @@ -0,0 +1,255 @@ +import type { Language } from "./web-client.js"; + +type SkinLayoutLabels = { + editButton: string; + title: string; + hint: string; + component: string; + filter: string; + visible: string; + positionX: string; + positionY: string; + size: string; + width: string; + height: string; + foreground: string; + background: string; + border: string; + radius: string; + resetItem: string; + resetAll: string; + export: string; + import: string; + close: string; + editMode: string; + focusPreview: string; + focusPreviewEmpty: string; + focusPreviewUnnamed: string; + focusPreviewTargetSize: string; + focusPreviewTargetAdequate: string; + focusPreviewTargetSmall: string; + skinLoadError: (skinId: string) => string; + skinUseBuiltIn: string; + undo: string; + redo: string; + saveFailed: string; + overlapWarning: string; + overflowWarning: string; + ignoreWarnings: string; + imported: string; + importFailed: string; + migrationWarning: (count: number) => string; + exportRecovery: string; +}; + +export const skinLayoutLabels: Record = { + zh: { + editButton: "布局", + title: "自定义页面布局", + hint: "打开编辑模式后,直接拖动页面组件调整位置。布局只保存在此浏览器。", + component: "当前组件", + filter: "搜索组件 ID", + visible: "显示此组件", + positionX: "水平偏移", + positionY: "垂直偏移", + size: "缩放", + width: "宽度", + height: "高度", + foreground: "文字颜色", + background: "背景颜色", + border: "边框颜色", + radius: "圆角", + resetItem: "重置此组件", + resetAll: "重置当前皮肤布局", + export: "导出", + import: "导入", + close: "关闭", + editMode: "拖动组件", + focusPreview: "预览键盘顺序与触屏命中范围", + focusPreviewEmpty: "当前页面没有可见的键盘焦点控件。", + focusPreviewUnnamed: "未命名控件", + focusPreviewTargetSize: "实际区域 {width} × {height} px", + focusPreviewTargetAdequate: "触控范围符合 44 × 44 px", + focusPreviewTargetSmall: "触控范围小于 44 × 44 px", + skinLoadError: (skinId) => `皮肤“${skinId}”加载失败,已返回默认界面。你可以停用此选择并记住内置皮肤。`, + skinUseBuiltIn: "停用此选择并记住内置皮肤", + undo: "撤销", + redo: "重做", + saveFailed: "浏览器存储不可用,布局更改未保存", + overlapWarning: "此位置可能与其他组件重叠。", + overflowWarning: "此组件超出页面布局区域。", + ignoreWarnings: "忽略当前提示", + imported: "布局已导入", + importFailed: "布局文件无效或与当前组件不兼容", + migrationWarning: (count) => `已升级旧布局;${count} 项无法自动应用,旧数据已保留供恢复。`, + exportRecovery: "导出旧布局数据", + }, + en: { + editButton: "Layout", + title: "Customize page layout", + hint: "Enable editing and drag page components to reposition them. Changes stay in this browser.", + component: "Selected component", + filter: "Search component ID", + visible: "Show this component", + positionX: "Horizontal offset", + positionY: "Vertical offset", + size: "Scale", + width: "Width", + height: "Height", + foreground: "Text color", + background: "Background", + border: "Border color", + radius: "Corner radius", + resetItem: "Reset component", + resetAll: "Reset this skin layout", + export: "Export", + import: "Import", + close: "Close", + editMode: "Move components", + focusPreview: "Preview keyboard order and touch targets", + focusPreviewEmpty: "No visible keyboard-focusable controls on this page.", + focusPreviewUnnamed: "Unnamed control", + focusPreviewTargetSize: "Actual area {width} × {height} px", + focusPreviewTargetAdequate: "Touch target meets 44 × 44 px", + focusPreviewTargetSmall: "Touch target is smaller than 44 × 44 px", + skinLoadError: (skinId) => `Skin “${skinId}” failed to load and the built-in interface was restored. You can stop selecting it and remember a built-in skin.`, + skinUseBuiltIn: "Stop selecting this skin and remember a built-in skin", + undo: "Undo", + redo: "Redo", + saveFailed: "Browser storage is unavailable; the layout change was not saved", + overlapWarning: "This position may overlap another component.", + overflowWarning: "This component extends beyond the page layout area.", + ignoreWarnings: "Ignore these hints for this layout", + imported: "Layout imported", + importFailed: "The layout file is invalid or incompatible with this client", + migrationWarning: (count) => `The old layout was upgraded; ${count} item(s) could not be applied and were kept for recovery.`, + exportRecovery: "Export old layout data", + }, + de: { + editButton: "Layout", + title: "Seitenlayout anpassen", + hint: "Aktiviere den Bearbeitungsmodus und ziehe Komponenten an ihre neue Position. Änderungen bleiben in diesem Browser.", + component: "Ausgewählte Komponente", + filter: "Komponenten-ID suchen", + visible: "Komponente anzeigen", + positionX: "Horizontaler Versatz", + positionY: "Vertikaler Versatz", + size: "Skalierung", + width: "Breite", + height: "Höhe", + foreground: "Textfarbe", + background: "Hintergrund", + border: "Rahmenfarbe", + radius: "Eckenradius", + resetItem: "Komponente zurücksetzen", + resetAll: "Skin-Layout zurücksetzen", + export: "Exportieren", + import: "Importieren", + close: "Schließen", + editMode: "Komponenten verschieben", + focusPreview: "Tastaturreihenfolge und Touch-Ziele anzeigen", + focusPreviewEmpty: "Auf dieser Seite sind keine sichtbaren Tastaturziele.", + focusPreviewUnnamed: "Unbenanntes Steuerelement", + focusPreviewTargetSize: "Tatsächliche Fläche {width} × {height} px", + focusPreviewTargetAdequate: "Touch-Ziel erfüllt 44 × 44 px", + focusPreviewTargetSmall: "Touch-Ziel kleiner als 44 × 44 px", + skinLoadError: (skinId) => `Skin „${skinId}“ konnte nicht geladen werden; die integrierte Oberfläche wurde wiederhergestellt. Du kannst diese Auswahl beenden und einen integrierten Skin speichern.`, + skinUseBuiltIn: "Diesen Skin nicht mehr auswählen", + undo: "Rückgängig", + redo: "Wiederholen", + saveFailed: "Der Browserspeicher ist nicht verfügbar; die Änderung wurde nicht gespeichert", + overlapWarning: "Diese Position kann eine andere Komponente überdecken.", + overflowWarning: "Diese Komponente liegt außerhalb des Seitenlayouts.", + ignoreWarnings: "Diese Hinweise für dieses Layout ausblenden", + imported: "Layout importiert", + importFailed: "Die Layoutdatei ist ungültig oder inkompatibel", + migrationWarning: (count) => `Das alte Layout wurde aktualisiert; ${count} Einträge konnten nicht übernommen werden und bleiben zur Wiederherstellung erhalten.`, + exportRecovery: "Alte Layoutdaten exportieren", + }, + ru: { + editButton: "Макет", + title: "Настройка макета", + hint: "Включите режим редактирования и перетаскивайте компоненты. Изменения сохраняются в этом браузере.", + component: "Выбранный компонент", + filter: "Поиск ID компонента", + visible: "Показывать компонент", + positionX: "Смещение по горизонтали", + positionY: "Смещение по вертикали", + size: "Масштаб", + width: "Ширина", + height: "Высота", + foreground: "Цвет текста", + background: "Фон", + border: "Цвет границы", + radius: "Радиус угла", + resetItem: "Сбросить компонент", + resetAll: "Сбросить макет скина", + export: "Экспорт", + import: "Импорт", + close: "Закрыть", + editMode: "Перемещать компоненты", + focusPreview: "Показать порядок клавиатуры и сенсорные цели", + focusPreviewEmpty: "На странице нет видимых элементов клавиатурной навигации.", + focusPreviewUnnamed: "Элемент без названия", + focusPreviewTargetSize: "Фактическая область {width} × {height} px", + focusPreviewTargetAdequate: "Сенсорная цель соответствует 44 × 44 px", + focusPreviewTargetSmall: "Сенсорная цель меньше 44 × 44 px", + skinLoadError: (skinId) => `Не удалось загрузить тему «${skinId}»; восстановлен встроенный интерфейс. Можно отказаться от неё и сохранить встроенную тему.`, + skinUseBuiltIn: "Больше не выбирать эту тему", + undo: "Отменить", + redo: "Повторить", + saveFailed: "Хранилище браузера недоступно; изменение не сохранено", + overlapWarning: "Компонент может перекрывать другой компонент.", + overflowWarning: "Компонент выходит за пределы области страницы.", + ignoreWarnings: "Скрыть эти подсказки для этой раскладки", + imported: "Макет импортирован", + importFailed: "Файл макета недействителен или несовместим", + migrationWarning: (count) => `Старая раскладка обновлена; ${count} элементов не применено, исходные данные сохранены для восстановления.`, + exportRecovery: "Экспортировать старые данные", + }, + ja: { + editButton: "レイアウト", + title: "ページレイアウトをカスタマイズ", + hint: "編集を有効にして、コンポーネントをドラッグして配置します。設定はこのブラウザーに保存されます。", + component: "選択中のコンポーネント", + filter: "コンポーネント ID を検索", + visible: "このコンポーネントを表示", + positionX: "横方向の移動", + positionY: "縦方向の移動", + size: "拡大縮小", + width: "幅", + height: "高さ", + foreground: "文字色", + background: "背景色", + border: "枠線の色", + radius: "角丸", + resetItem: "コンポーネントをリセット", + resetAll: "このスキンのレイアウトをリセット", + export: "エクスポート", + import: "インポート", + close: "閉じる", + editMode: "コンポーネントを移動", + focusPreview: "キーボード順序とタッチ領域を表示", + focusPreviewEmpty: "このページに表示中のキーボード操作対象はありません。", + focusPreviewUnnamed: "名前のないコントロール", + focusPreviewTargetSize: "実際の領域 {width} × {height} px", + focusPreviewTargetAdequate: "タッチ領域は 44 × 44 px 以上です", + focusPreviewTargetSmall: "タッチ領域が 44 × 44 px 未満です", + skinLoadError: (skinId) => `スキン「${skinId}」を読み込めず、標準の画面に戻しました。このスキンを使わず、標準スキンを保存できます。`, + skinUseBuiltIn: "このスキンを使わず標準スキンを保存", + undo: "元に戻す", + redo: "やり直す", + saveFailed: "ブラウザーのストレージを利用できないため、変更を保存できませんでした", + overlapWarning: "この位置では、ほかのコンポーネントと重なる可能性があります。", + overflowWarning: "コンポーネントがページ領域からはみ出しています。", + ignoreWarnings: "このレイアウトのヒントを無視", + imported: "レイアウトをインポートしました", + importFailed: "レイアウトファイルが無効か、このクライアントと互換性がありません", + migrationWarning: (count) => `旧レイアウトを更新しました。${count} 件は適用できず、復元用にデータを保存しました。`, + exportRecovery: "旧レイアウトデータをエクスポート", + }, +}; + +export function resolveSkinLayoutLanguage(value: string | undefined): Language { + return value === "en" || value === "de" || value === "ru" || value === "ja" ? value : "zh"; +} diff --git a/web/src/services/skin-catalog.ts b/web/src/services/skin-catalog.ts index 0a06191..f460420 100644 --- a/web/src/services/skin-catalog.ts +++ b/web/src/services/skin-catalog.ts @@ -32,7 +32,7 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [ { id: BUILTIN_ILLUSIA_SKIN_ID, name: "ILLUSIA风", - version: "1.0.28", + version: "1.0.29", author: "WebSpeak Project", license: "All rights reserved", description: "A bright original-character art skin for the home, voice room, and demo pages.", diff --git a/web/src/services/skin-extension-sandbox.test.ts b/web/src/services/skin-extension-sandbox.test.ts new file mode 100644 index 0000000..7fe7fe4 --- /dev/null +++ b/web/src/services/skin-extension-sandbox.test.ts @@ -0,0 +1,143 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + createSkinExtensionApproval, + getSkinExtensionUpgradeConsentDelta, + isSkinExtensionBootstrapHello, + isSkinExtensionPermissionApproved, + parseSkinExtensionApproval, + parseSkinExtensionManifest, + parseSkinExtensionRequestMessage, + sanitizeSkinExtensionSessionStatus, + SKIN_EXTENSION_MESSAGE_CHANNEL, + type SkinExtensionManifest, +} from "../../../src/shared/skin-extension.js"; +import { + createSkinExtensionSandboxPrototype, + SKIN_EXTENSION_RUNTIME_ENABLED, + SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT, + SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND, + SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT, + SkinExtensionSandboxError, +} from "./skin-extension-sandbox.js"; + +function manifest(overrides: Record = {}) { + return parseSkinExtensionManifest({ + schemaVersion: 1, + packageType: "extension", + id: "community.status-card", + name: "Status card", + version: "1.0.0", + apiVersion: 1, + permissions: ["session.status.read"], + ...overrides, + }); +} + +test("extension manifests use a separate strict schema and reject unknown capabilities", () => { + const parsed = manifest(); + assert.equal(parsed.packageType, "extension"); + assert.deepEqual(parsed.permissions, ["session.status.read"]); + assert.throws(() => manifest({ unexpected: true }), { code: "SKIN_EXTENSION_UNKNOWN_FIELD" }); + assert.throws(() => manifest({ permissions: ["filesystem.read"] }), { code: "SKIN_EXTENSION_PERMISSION_UNKNOWN" }); + assert.throws(() => manifest({ permissions: ["session.status.read", "session.status.read"] }), { code: "SKIN_EXTENSION_PERMISSION_DUPLICATE" }); + assert.throws(() => manifest({ version: "latest" }), { code: "SKIN_EXTENSION_MANIFEST_INVALID" }); + assert.throws(() => manifest({ apiVersion: 2 }), { code: "SKIN_EXTENSION_API_UNSUPPORTED" }); +}); + +test("approval is host-shaped, permission-specific, and cannot be reused for another extension", () => { + const parsed = manifest(); + const approval = createSkinExtensionApproval(parsed); + assert.equal(isSkinExtensionPermissionApproved(approval, parsed.id, "session.status.read"), true); + assert.equal(isSkinExtensionPermissionApproved(approval, "other.extension", "session.status.read"), false); + assert.deepEqual(parseSkinExtensionApproval(approval), approval); + assert.throws(() => parseSkinExtensionApproval({ ...approval, permissions: { "filesystem.read": 1 } }), { code: "SKIN_EXTENSION_APPROVAL_INVALID" }); + assert.throws(() => getSkinExtensionUpgradeConsentDelta(approval, manifest({ id: "other.extension" })), { code: "SKIN_EXTENSION_ID_CHANGED" }); +}); + +test("an extension upgrade needs new consent when it adds or changes a capability", () => { + const approval = createSkinExtensionApproval(manifest()); + const unchanged = getSkinExtensionUpgradeConsentDelta(approval, manifest({ version: "2.0.0" })); + assert.equal(unchanged.requiresConsent, false, "a version change alone does not silently change permission meaning"); + + const approvalWithoutPermissions = createSkinExtensionApproval(manifest({ permissions: [] })); + const added = getSkinExtensionUpgradeConsentDelta(approvalWithoutPermissions, manifest({ version: "2.0.0" })); + assert.deepEqual(added.addedPermissions, ["session.status.read"]); + assert.equal(added.requiresConsent, true); + + const removed = getSkinExtensionUpgradeConsentDelta(approval, manifest({ version: "2.0.0", permissions: [] })); + assert.deepEqual(removed.removedPermissions, ["session.status.read"]); + assert.equal(removed.requiresConsent, false, "removing a capability cannot expand an existing approval"); + + const outdatedApproval = { ...approval, permissions: { "session.status.read": 2 } }; + const changedMeaning = getSkinExtensionUpgradeConsentDelta(outdatedApproval, manifest({ version: "2.0.0" })); + assert.deepEqual(changedMeaning.changedMeaningPermissions, ["session.status.read"]); + assert.equal(changedMeaning.requiresConsent, true); + + const changedApi = getSkinExtensionUpgradeConsentDelta({ ...approval, apiVersion: 2 }, manifest({ version: "2.0.0" }) as SkinExtensionManifest); + assert.equal(changedApi.apiVersionChanged, true); + assert.equal(changedApi.requiresConsent, true); +}); + +test("bootstrap accepts only the exact opaque iframe source, nonce, origin, and transferred port", () => { + const expectedSource = {}; + const valid = { + source: expectedSource, + origin: "null", + data: { channel: SKIN_EXTENSION_MESSAGE_CHANNEL, type: "hello", apiVersion: 1, nonce: "secret" }, + ports: [{}], + }; + assert.equal(isSkinExtensionBootstrapHello(valid, expectedSource, "secret"), true); + assert.equal(isSkinExtensionBootstrapHello({ ...valid, source: {} }, expectedSource, "secret"), false); + assert.equal(isSkinExtensionBootstrapHello({ ...valid, origin: "https://example.invalid" }, expectedSource, "secret"), false); + assert.equal(isSkinExtensionBootstrapHello({ ...valid, data: { ...valid.data, nonce: "wrong" } }, expectedSource, "secret"), false); + assert.equal(isSkinExtensionBootstrapHello({ ...valid, ports: [] }, expectedSource, "secret"), false); + assert.equal(isSkinExtensionBootstrapHello({ ...valid, data: { ...valid.data, extra: true } }, expectedSource, "secret"), false); +}); + +test("capability requests have a fixed envelope and empty, bounded payload", () => { + const message = { + channel: SKIN_EXTENSION_MESSAGE_CHANNEL, + apiVersion: 1, + nonce: "secret", + id: "r1", + type: "request", + permission: "session.status.read", + payload: {}, + }; + assert.deepEqual(parseSkinExtensionRequestMessage(message, "secret"), message); + assert.equal(parseSkinExtensionRequestMessage({ ...message, nonce: "wrong" }, "secret"), null); + assert.equal(parseSkinExtensionRequestMessage({ ...message, payload: { includePrivateChat: true } }, "secret"), null); + assert.equal(parseSkinExtensionRequestMessage({ ...message, extra: true }, "secret"), null); + assert.equal(parseSkinExtensionRequestMessage({ ...message, permission: "chat.private.read" }, "secret"), null); + assert.equal(parseSkinExtensionRequestMessage({ ...message, id: "a".repeat(65) }, "secret"), null); +}); + +test("session status copies only low-sensitivity fields and rejects invalid values", () => { + const safe = sanitizeSkinExtensionSessionStatus({ connected: true, channelName: "Lounge\n", memberCount: 3, token: "must not escape" }); + assert.deepEqual(safe, { connected: true, channelName: "Lounge ", memberCount: 3 }); + assert.equal("token" in safe, false); + assert.throws(() => sanitizeSkinExtensionSessionStatus({ connected: true, channelName: null, memberCount: -1 })); + assert.throws(() => sanitizeSkinExtensionSessionStatus({ connected: "yes", channelName: null, memberCount: 0 })); +}); + +test("JavaScript extensions stay disabled because Workers have no hard memory quota", () => { + assert.equal(SKIN_EXTENSION_RUNTIME_ENABLED, false); + assert.ok(SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT <= 64 * 1024); + assert.ok(SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT <= 8 * 1024); + assert.ok(SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND <= 10); + assert.ok(new SkinExtensionSandboxError("DISABLED", "disabled") instanceof Error); +}); + +test("the prototype rejects source beyond its fixed startup budget before creating a frame", () => { + const parsed = manifest(); + const approval = createSkinExtensionApproval(parsed); + assert.throws(() => createSkinExtensionSandboxPrototype({ + container: {} as HTMLElement, + manifest: parsed, + approval, + source: "x".repeat(SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT + 1), + readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }), + prototypeOnly: true, + }), { code: "SKIN_EXTENSION_SOURCE_TOO_LARGE" }); +}); diff --git a/web/src/services/skin-extension-sandbox.ts b/web/src/services/skin-extension-sandbox.ts new file mode 100644 index 0000000..8eaa50f --- /dev/null +++ b/web/src/services/skin-extension-sandbox.ts @@ -0,0 +1,501 @@ +import { + isSkinExtensionBootstrapHello, + isSkinExtensionPermissionApproved, + parseSkinExtensionApproval, + parseSkinExtensionManifest, + parseSkinExtensionRequestMessage, + sanitizeSkinExtensionSessionStatus, + SKIN_EXTENSION_API_VERSION, + SKIN_EXTENSION_MESSAGE_CHANNEL, + type SkinExtensionApproval, + type SkinExtensionManifest, + type SkinExtensionPermissionId, + type SkinExtensionSessionStatus, +} from "../../../src/shared/skin-extension.js"; + +export const SKIN_EXTENSION_RUNTIME_ENABLED = false as const; +export const SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT = 64 * 1024; +export const SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT = 8 * 1024; +export const SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND = 10; +export const SKIN_EXTENSION_SANDBOX_MAX_REQUESTS = 10_000; + +const HANDSHAKE_TIMEOUT_MS = 3_000; +const SHUTDOWN_TIMEOUT_MS = 100; +const MESSAGE_CHANNEL = SKIN_EXTENSION_MESSAGE_CHANNEL; + +export class SkinExtensionSandboxError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinExtensionSandboxError"; + } +} + +export interface SkinExtensionSandboxOptions { + container: HTMLElement; + manifest: unknown; + approval: unknown; + source: string; + readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise; + /** The only entry point is explicitly marked as a development prototype and is not wired into the application. */ + prototypeOnly: true; +} + +export interface SkinExtensionSandboxHandle { + readonly frame: HTMLIFrameElement; + readonly manifest: SkinExtensionManifest; + readonly approval: SkinExtensionApproval; + readonly ready: Promise; + readonly stopped: Promise; + readonly closed: boolean; + readonly closeReason: string | null; + readonly acceptedRequests: number; + readonly rejectedRequests: number; + revokePermission(permission: SkinExtensionPermissionId): void; + close(reason?: string): void; +} + +function isPlainRecord(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function randomNonce(view: Window): string { + const bytes = new Uint8Array(32); + view.crypto.getRandomValues(bytes); + return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join(""); +} + +function toBase64(source: string): string { + const bytes = new TextEncoder().encode(source); + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + } + return btoa(binary); +} + +function createWorkerDataUrl(source: string): string { + const pluginModuleUrl = `data:text/javascript;base64,${toBase64(source)}`; + const workerBootstrap = ` +const __wsPluginModuleUrl = ${JSON.stringify(pluginModuleUrl)}; +const __wsApiVersion = ${SKIN_EXTENSION_API_VERSION}; +const __wsDeniedGlobals = ["Worker", "SharedWorker", "fetch", "XMLHttpRequest", "WebSocket", "EventSource", "WebTransport", "importScripts", "indexedDB", "caches", "WebAssembly"]; +for (const __wsName of __wsDeniedGlobals) { + try { Object.defineProperty(globalThis, __wsName, { value: undefined, writable: false, configurable: false }); } catch {} + if (globalThis[__wsName] !== undefined) throw new Error("The worker cannot disable a restricted global."); +} +let __wsPort = null; +let __wsSequence = 0; +const __wsPending = new Map(); +self.addEventListener("message", async function __wsInitialize(event) { + if (__wsPort || event.data?.type !== "initialize" || event.ports.length !== 1 || Object.keys(event.data).length !== 1) return; + __wsPort = event.ports[0]; + __wsPort.onmessage = (portEvent) => { + const response = portEvent.data; + if (!response || typeof response !== "object" || response.type !== "response" || typeof response.id !== "string") return; + const pending = __wsPending.get(response.id); + if (!pending) return; + __wsPending.delete(response.id); + if (response.ok === true) pending.resolve(response.data); + else pending.reject(new Error(typeof response.error?.message === "string" ? response.error.message : "Extension request denied.")); + }; + __wsPort.start(); + const api = Object.freeze({ + apiVersion: __wsApiVersion, + request(permission, payload = {}) { + if (!__wsPort) return Promise.reject(new Error("Extension runtime is closed.")); + if (typeof permission !== "string" || !payload || typeof payload !== "object" || Array.isArray(payload) || Object.keys(payload).length !== 0) return Promise.reject(new Error("Invalid extension request.")); + if (__wsPending.size >= 16) return Promise.reject(new Error("Too many pending extension requests.")); + const id = "r" + (++__wsSequence).toString(36); + return new Promise((resolve, reject) => { + __wsPending.set(id, { resolve, reject }); + __wsPort.postMessage({ type: "request", id, permission, payload: {} }); + }); + }, + }); + Object.defineProperty(globalThis, "WebSpeakExtension", { value: api, writable: false, configurable: false }); + __wsPort.postMessage({ type: "worker-ready" }); + try { await import(__wsPluginModuleUrl); } + catch { __wsPort.postMessage({ type: "plugin-error" }); } +});`; + return `data:text/javascript;base64,${toBase64(workerBootstrap)}`; +} + +function createSandboxDocument(workerUrl: string, nonce: string): string { + const policy = [ + "default-src 'none'", + `script-src 'nonce-${nonce}' data:`, + "style-src 'unsafe-inline'", + "connect-src 'none'", + "img-src 'none'", + "media-src 'none'", + "font-src 'none'", + "object-src 'none'", + "frame-src 'none'", + "child-src 'none'", + "worker-src data:", + "manifest-src 'none'", + "form-action 'none'", + "base-uri 'none'", + "navigate-to 'none'", + ].join("; "); + + return ` + + +Isolated WebSpeak extension +
+`; +} + +function serializedMessageBytes(value: unknown): number { + try { + const serialized = JSON.stringify(value); + return serialized === undefined ? Number.POSITIVE_INFINITY : new TextEncoder().encode(serialized).byteLength; + } catch { + return Number.POSITIVE_INFINITY; + } +} + +function isReadyMessage(value: unknown, nonce: string): boolean { + return isPlainRecord(value) + && Object.keys(value).length === 4 + && value.channel === MESSAGE_CHANNEL + && value.apiVersion === SKIN_EXTENSION_API_VERSION + && value.nonce === nonce + && value.type === "client-ready"; +} + +export function createSkinExtensionSandboxPrototype(options: SkinExtensionSandboxOptions): SkinExtensionSandboxHandle { + if (options.prototypeOnly !== true) { + throw new SkinExtensionSandboxError("SKIN_EXTENSION_RUNTIME_DISABLED", "Executable extensions are disabled."); + } + if (!options.container || typeof options.source !== "string") { + throw new SkinExtensionSandboxError("SKIN_EXTENSION_INPUT_INVALID", "The extension runtime input is invalid."); + } + + const manifest = parseSkinExtensionManifest(options.manifest); + const approval = parseSkinExtensionApproval(options.approval); + if (approval.pluginId !== manifest.id || approval.apiVersion !== manifest.apiVersion) { + throw new SkinExtensionSandboxError("SKIN_EXTENSION_RECONSENT_REQUIRED", "The extension must be reviewed and approved again."); + } + for (const permission of manifest.permissions) { + if (!isSkinExtensionPermissionApproved(approval, manifest.id, permission)) { + throw new SkinExtensionSandboxError("SKIN_EXTENSION_RECONSENT_REQUIRED", "A requested extension permission has not been approved."); + } + } + if (new TextEncoder().encode(options.source).byteLength > SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT) { + throw new SkinExtensionSandboxError("SKIN_EXTENSION_SOURCE_TOO_LARGE", "The extension source exceeds the prototype size limit."); + } + + const document = options.container.ownerDocument; + const view = document.defaultView; + if (!view || !view.crypto?.getRandomValues || typeof MessageChannel === "undefined") { + throw new SkinExtensionSandboxError("SKIN_EXTENSION_BROWSER_UNSUPPORTED", "This browser cannot create the isolated extension prototype."); + } + const hostWindow = view; + const nonce = randomNonce(hostWindow); + const workerUrl = createWorkerDataUrl(options.source); + const frame = document.createElement("iframe"); + frame.setAttribute("sandbox", "allow-scripts"); + frame.setAttribute("allow", "camera 'none'; microphone 'none'; display-capture 'none'; geolocation 'none'"); + frame.setAttribute("referrerpolicy", "no-referrer"); + frame.setAttribute("title", `${manifest.name} isolated component`); + frame.tabIndex = 0; + frame.style.display = "block"; + frame.style.width = "100%"; + frame.style.height = "100%"; + frame.style.border = "0"; + frame.style.background = "transparent"; + frame.srcdoc = createSandboxDocument(workerUrl, nonce); + + let active = true; + let closeReason: string | null = null; + let port: MessagePort | null = null; + let readySettled = false; + let stopTimer: number | undefined; + let stoppedSettled = false; + let loadCount = 0; + let invalidMessages = 0; + let totalRequests = 0; + let acceptedRequests = 0; + let rejectedRequests = 0; + const requestTimes: number[] = []; + const recentRequestIds = new Set(); + const recentRequestIdOrder: string[] = []; + const pendingHostRequests = new Map(); + let resolveReady!: () => void; + let rejectReady!: (reason: Error) => void; + const ready = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + let resolveStopped!: () => void; + const stopped = new Promise((resolve) => { resolveStopped = resolve; }); + const timer = hostWindow.setTimeout(() => close("handshake-timeout", new SkinExtensionSandboxError("SKIN_EXTENSION_HANDSHAKE_TIMEOUT", "The extension did not complete its isolated handshake.")), HANDSHAKE_TIMEOUT_MS); + + function finalizeStop(): void { + if (stoppedSettled) return; + stoppedSettled = true; + if (stopTimer !== undefined) hostWindow.clearTimeout(stopTimer); + if (port) { + port.onmessage = null; + port.onmessageerror = null; + port.close(); + port = null; + } + frame.remove(); + resolveStopped(); + } + + function close(reason = "closed", error?: Error): void { + if (!active) return; + active = false; + closeReason = reason; + hostWindow.clearTimeout(timer); + hostWindow.removeEventListener("message", onWindowMessage); + frame.removeEventListener("load", onFrameLoad); + frame.removeEventListener("error", onFrameError); + for (const controller of pendingHostRequests.values()) controller.abort(); + pendingHostRequests.clear(); + requestTimes.length = 0; + recentRequestIds.clear(); + recentRequestIdOrder.length = 0; + if (!readySettled) { + readySettled = true; + rejectReady(error ?? new SkinExtensionSandboxError("SKIN_EXTENSION_RUNTIME_CLOSED", "The extension runtime closed before it was ready.")); + } + if (port) { + try { + port.postMessage({ channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, type: "shutdown" }); + stopTimer = hostWindow.setTimeout(finalizeStop, SHUTDOWN_TIMEOUT_MS); + } catch { + finalizeStop(); + } + } else finalizeStop(); + } + + function failInvalidMessage(): void { + invalidMessages += 1; + if (invalidMessages >= 3) close("invalid-protocol"); + } + + function sendResponse(id: string, ok: true, data: SkinExtensionSessionStatus): void; + function sendResponse(id: string, ok: false, code: string, message: string): void; + function sendResponse(id: string, ok: boolean, dataOrCode: SkinExtensionSessionStatus | string, message?: string): void { + if (!active || !port) return; + const response = ok + ? { channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, id, type: "response", ok: true, data: dataOrCode } + : { channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, id, type: "response", ok: false, error: { code: dataOrCode, message } }; + try { port.postMessage(response); } + catch { close("response-failed"); } + } + + function consumeRequestRate(now: number): boolean { + while (requestTimes.length > 0 && now - requestTimes[0] >= 1000) requestTimes.shift(); + if (requestTimes.length >= SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND) return false; + requestTimes.push(now); + return true; + } + + async function handleRequest(value: unknown): Promise { + if (!active || !port) return; + if (serializedMessageBytes(value) > SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT) { + close("message-too-large"); + return; + } + if (!consumeRequestRate(hostWindow.performance.now())) { + close("message-rate-exceeded"); + return; + } + const request = parseSkinExtensionRequestMessage(value, nonce); + if (!request) { + failInvalidMessage(); + return; + } + if (recentRequestIds.has(request.id) || pendingHostRequests.has(request.id)) { + close("duplicate-request-id"); + return; + } + recentRequestIds.add(request.id); + recentRequestIdOrder.push(request.id); + if (recentRequestIdOrder.length > 256) recentRequestIds.delete(recentRequestIdOrder.shift()!); + totalRequests += 1; + if (totalRequests > SKIN_EXTENSION_SANDBOX_MAX_REQUESTS) { + close("request-budget-exceeded"); + return; + } + if (!manifest.permissions.includes(request.permission) + || !isSkinExtensionPermissionApproved(approval, manifest.id, request.permission)) { + rejectedRequests += 1; + sendResponse(request.id, false, "CAPABILITY_NOT_APPROVED", "The extension capability is not approved."); + return; + } + if (request.permission !== "session.status.read") { + rejectedRequests += 1; + sendResponse(request.id, false, "CAPABILITY_UNAVAILABLE", "The extension capability is unavailable in this prototype."); + return; + } + + acceptedRequests += 1; + const controller = new AbortController(); + pendingHostRequests.set(request.id, controller); + try { + const status = sanitizeSkinExtensionSessionStatus(await options.readSessionStatus(controller.signal)); + if (active && pendingHostRequests.get(request.id) === controller) { + pendingHostRequests.delete(request.id); + sendResponse(request.id, true, status); + } + } catch { + if (pendingHostRequests.get(request.id) === controller) pendingHostRequests.delete(request.id); + if (active) sendResponse(request.id, false, "HOST_DATA_UNAVAILABLE", "The requested session status is unavailable."); + } + } + + function onPortMessage(event: MessageEvent): void { + if (!active) { + const value = event.data; + if (isPlainRecord(value) && Object.keys(value).length === 4 + && value.channel === MESSAGE_CHANNEL && value.apiVersion === SKIN_EXTENSION_API_VERSION + && value.nonce === nonce && value.type === "shutdown-complete") finalizeStop(); + return; + } + if (serializedMessageBytes(event.data) > SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT) { + close("message-too-large"); + return; + } + if (isPlainRecord(event.data) && Object.keys(event.data).length === 4 + && event.data.channel === MESSAGE_CHANNEL && event.data.apiVersion === SKIN_EXTENSION_API_VERSION + && event.data.nonce === nonce && event.data.type === "runtime-error") { + close("worker-error", new SkinExtensionSandboxError("SKIN_EXTENSION_WORKER_FAILED", "The isolated extension worker failed.")); + return; + } + if (!readySettled) { + if (!isReadyMessage(event.data, nonce)) { + close("invalid-handshake", new SkinExtensionSandboxError("SKIN_EXTENSION_HANDSHAKE_INVALID", "The isolated extension handshake was invalid.")); + return; + } + readySettled = true; + hostWindow.clearTimeout(timer); + resolveReady(); + return; + } + void handleRequest(event.data); + } + + function onWindowMessage(event: MessageEvent): void { + if (!active || port) { + for (const transferredPort of event.ports) transferredPort.close(); + return; + } + const validHello = isSkinExtensionBootstrapHello({ source: event.source, origin: event.origin, data: event.data, ports: event.ports }, frame.contentWindow, nonce); + if (!validHello) { + for (const transferredPort of event.ports) transferredPort.close(); + return; + } + port = event.ports[0]; + port.onmessage = onPortMessage; + port.onmessageerror = () => close("message-deserialization-failed"); + port.start(); + hostWindow.removeEventListener("message", onWindowMessage); + port.postMessage({ channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, type: "host-ready" }); + } + + function onFrameLoad(): void { + loadCount += 1; + if (loadCount > 1) close("frame-navigation"); + } + + function onFrameError(): void { close("frame-error"); } + + hostWindow.addEventListener("message", onWindowMessage); + frame.addEventListener("load", onFrameLoad); + frame.addEventListener("error", onFrameError); + options.container.append(frame); + + return { + frame, + manifest, + approval, + ready, + stopped, + get closed() { return !active; }, + get closeReason() { return closeReason; }, + get acceptedRequests() { return acceptedRequests; }, + get rejectedRequests() { return rejectedRequests; }, + revokePermission(permission) { + if (manifest.permissions.includes(permission)) close(`permission-revoked:${permission}`); + }, + close, + }; +} diff --git a/web/src/services/skin-extension-wasm-policy.test.ts b/web/src/services/skin-extension-wasm-policy.test.ts new file mode 100644 index 0000000..682aab2 --- /dev/null +++ b/web/src/services/skin-extension-wasm-policy.test.ts @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES, + SKIN_EXTENSION_WASM_SOURCE_LIMIT, + SkinExtensionWasmPolicyError, + validateSkinExtensionWasmBytes, + validateSkinExtensionWasmImportsAndExports, +} from "./skin-extension-wasm-policy.js"; +import { + createSkinExtensionWasmCappedRunProbe, + createSkinExtensionWasmGcAllocationProbe, + createSkinExtensionWasmInfiniteStartProbe, + createSkinExtensionWasmInternalMemoryProbe, + createSkinExtensionWasmInternalTableProbe, + createSkinExtensionWasmOversizedElementVectorProbe, + createSkinExtensionWasmOversizedFunctionBodyProbe, + createSkinExtensionWasmOversizedLocalProbe, + createSkinExtensionWasmOversizedSignatureProbe, + createSkinExtensionWasmPrefixByteImmediateProbe, + createSkinExtensionWasmStatusProbe, + createSkinExtensionWasmTooManyFunctionsProbe, +} from "../../test/skin-extension-wasm-fixture.js"; + +test("Wasm metadata policy accepts only a single run export and one bounded host memory", () => { + const metadata = validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmPrefixByteImmediateProbe()); + assert.deepEqual(metadata, { usesSessionStatus: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES }); +}); + +test("Wasm policy rejects module-defined memory or tables that bypass host limits", () => { + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInternalMemoryProbe()), { + code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", + }); + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInternalTableProbe()), { + code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", + }); +}); + +test("Wasm metadata parser rejects missing import memory, malformed sections, and oversized modules", () => { + assert.throws(() => validateSkinExtensionWasmImportsAndExports(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])), { + code: "SKIN_EXTENSION_WASM_IMPORT_INVALID", + }); + assert.throws(() => validateSkinExtensionWasmBytes(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 127])), { + code: "SKIN_EXTENSION_WASM_INVALID", + }); + assert.throws(() => validateSkinExtensionWasmBytes(new Uint8Array(SKIN_EXTENSION_WASM_SOURCE_LIMIT + 1)), { + code: "SKIN_EXTENSION_WASM_SIZE", + }); + assert.ok(new SkinExtensionWasmPolicyError("test", "test") instanceof Error); +}); + +test("Wasm preflight caps function count and body size before the interpreter sees a module", () => { + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmTooManyFunctionsProbe()), { + code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", + }); + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedFunctionBodyProbe()), { + code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", + }); + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInfiniteStartProbe()), { + code: "SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", + }); +}); + +test("Wasm preflight rejects GC allocation and bounds nested vectors before interpretation", () => { + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmGcAllocationProbe()), { + code: "SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", + }); + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedSignatureProbe()), { + code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", + }); + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedLocalProbe()), { + code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", + }); + assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedElementVectorProbe()), { + code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", + }); +}); + +test("Wasm import parsing reads the bounded permission contract without native compilation", () => { + const status = createSkinExtensionWasmStatusProbe(); + assert.throws(() => validateSkinExtensionWasmImportsAndExports(status), { + code: "SKIN_EXTENSION_WASM_PERMISSION_INVALID", + }); + assert.deepEqual(validateSkinExtensionWasmImportsAndExports(status, ["session.status.read"]), { + usesSessionStatus: true, + memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES, + }); + assert.equal(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmCappedRunProbe()).usesSessionStatus, false); +}); + +test("Wasm instruction scanning distinguishes extension prefixes from signed integer bytes", () => { + const bytes = createSkinExtensionWasmPrefixByteImmediateProbe(); + assert.doesNotThrow(() => validateSkinExtensionWasmBytes(bytes)); + assert.deepEqual(validateSkinExtensionWasmImportsAndExports(bytes), { + usesSessionStatus: false, + memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES, + }); +}); diff --git a/web/src/services/skin-extension-wasm-policy.ts b/web/src/services/skin-extension-wasm-policy.ts new file mode 100644 index 0000000..a419bbe --- /dev/null +++ b/web/src/services/skin-extension-wasm-policy.ts @@ -0,0 +1,437 @@ +export const SKIN_EXTENSION_WASM_SOURCE_LIMIT = 256 * 1024; +export const SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES = 64; +export const SKIN_EXTENSION_WASM_PAGE_BYTES = 64 * 1024; +export const SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS = 3_000; +export const SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS = 100; +export const SKIN_EXTENSION_WASM_MESSAGE_LIMIT = 8 * 1024; +export const SKIN_EXTENSION_WASM_STATUS_READ_LIMIT = 10; +export const SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT = 512; +export const SKIN_EXTENSION_WASM_FUEL_LIMIT = 10_000_000n; +export const SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024; +export const SKIN_EXTENSION_WASM_FUNCTION_LIMIT = 128; +export const SKIN_EXTENSION_WASM_FUNCTION_BODY_LIMIT = 32 * 1024; +export const SKIN_EXTENSION_WASM_CODE_BYTES_LIMIT = 192 * 1024; +const SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT = 64; +const SKIN_EXTENSION_WASM_LOCAL_GROUP_LIMIT = 256; +const SKIN_EXTENSION_WASM_LOCAL_LIMIT = 4_096; + +const WASM_HEADER = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00] as const; +const SCALAR_VALUE_TYPES = new Set([0x7f, 0x7e, 0x7d, 0x7c]); +const BOUNDED_VECTOR_COUNTS = new Map([ + [1, 128], // types + [2, 2], // memory and one optional capability import + [3, SKIN_EXTENSION_WASM_FUNCTION_LIMIT], + [6, 128], // globals + [7, 64], // exports; the runner later requires exactly run + [9, 64], // element segments + [11, 64], // data segments + [12, 64], // data segments referenced by bulk-memory operations +]); + +export class SkinExtensionWasmPolicyError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinExtensionWasmPolicyError"; + } +} + +function readU32(bytes: Uint8Array, offset: number, end: number): { value: number; next: number } { + let value = 0; + let shift = 0; + for (let index = 0; index < 5; index += 1) { + if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section length."); + const byte = bytes[offset++]; + if (index === 4 && (byte & 0xf0) !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has an overflowing section length."); + value |= (byte & 0x7f) << shift; + if ((byte & 0x80) === 0) return { value: value >>> 0, next: offset }; + shift += 7; + } + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has an invalid section length."); +} + +function skipSignedLeb128(bytes: Uint8Array, offset: number, end: number, maxBytes: number): number { + for (let index = 0; index < maxBytes; index += 1) { + if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated integer immediate."); + if ((bytes[offset++] & 0x80) === 0) return offset; + } + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains an oversized integer immediate."); +} + +function requireScalarValueType(bytes: Uint8Array, offset: number, end: number): number { + if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains a truncated value type."); + if (!SCALAR_VALUE_TYPES.has(bytes[offset])) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts numeric scalar types only; reference, vector, and GC types are disabled."); + } + return offset + 1; +} + +function validateTypeSection(bytes: Uint8Array, start: number, end: number): void { + let cursor = readU32(bytes, start, end); + if (cursor.value > 128) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many function types."); + for (let typeIndex = 0; typeIndex < cursor.value; typeIndex += 1) { + if (cursor.next >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension type section is truncated."); + if (bytes[cursor.next++] !== 0x60) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts function types only; GC and recursive types are disabled."); + } + const parameters = readU32(bytes, cursor.next, end); + cursor.next = parameters.next; + if (parameters.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function signature contains too many parameters."); + } + for (let index = 0; index < parameters.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end); + + const results = readU32(bytes, cursor.next, end); + cursor.next = results.next; + if (results.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function signature contains too many results."); + } + for (let index = 0; index < results.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end); + } + if (cursor.next !== end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension type section contains trailing bytes."); +} + +function readBlockType(bytes: Uint8Array, offset: number, end: number): number { + if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated block type."); + const valueType = bytes[offset]; + if (valueType === 0x40 || SCALAR_VALUE_TYPES.has(valueType)) return offset + 1; + if (valueType === 0x6f || valueType === 0x70 || valueType === 0x7b || valueType === 0x63 || valueType === 0x64) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Reference and vector block types are disabled in the Wasm prototype."); + } + return skipSignedLeb128(bytes, offset, end, 5); +} + +function scanFunctionBody(bytes: Uint8Array, start: number, end: number): number { + let cursor = readU32(bytes, start, end); + if (cursor.value > SKIN_EXTENSION_WASM_LOCAL_GROUP_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function contains too many local groups."); + } + const localGroupCount = cursor.value; + let localCount = 0; + for (let index = 0; index < localGroupCount; index += 1) { + const group = readU32(bytes, cursor.next, end); + cursor.next = group.next; + localCount += group.value; + if (localCount > SKIN_EXTENSION_WASM_LOCAL_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension module declares too many local values."); + } + cursor.next = requireScalarValueType(bytes, cursor.next, end); + } + + while (cursor.next < end) { + const opcode = bytes[cursor.next++]; + if ((opcode >= 0x45 && opcode <= 0xc4) + || opcode === 0x00 || opcode === 0x01 || opcode === 0x05 || opcode === 0x0b + || opcode === 0x0f || opcode === 0x1a || opcode === 0x1b) continue; + + if (opcode === 0x02 || opcode === 0x03 || opcode === 0x04) { + cursor.next = readBlockType(bytes, cursor.next, end); + continue; + } + if (opcode === 0x0c || opcode === 0x0d || opcode === 0x10 + || (opcode >= 0x20 && opcode <= 0x24)) { + cursor = readU32(bytes, cursor.next, end); + continue; + } + if (opcode === 0x0e) { + const labels = readU32(bytes, cursor.next, end); + cursor.next = labels.next; + if (labels.value > end - cursor.next) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension branch table is truncated."); + for (let index = 0; index <= labels.value; index += 1) cursor = readU32(bytes, cursor.next, end); + continue; + } + if (opcode === 0x11) { + cursor = readU32(bytes, cursor.next, end); + const table = readU32(bytes, cursor.next, end); + if (table.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported table."); + cursor.next = table.next; + continue; + } + if (opcode === 0x1c) { + const selected = readU32(bytes, cursor.next, end); + cursor.next = selected.next; + if (selected.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "A typed selection contains too many values."); + } + for (let index = 0; index < selected.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end); + continue; + } + if (opcode >= 0x28 && opcode <= 0x3e) { + const alignment = readU32(bytes, cursor.next, end); + cursor.next = alignment.next; + if (alignment.value > 3) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Multi-memory and over-aligned memory operations are disabled."); + cursor = readU32(bytes, cursor.next, end); + continue; + } + if (opcode === 0x3f || opcode === 0x40) { + const memory = readU32(bytes, cursor.next, end); + if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory."); + cursor.next = memory.next; + continue; + } + if (opcode === 0x41 || opcode === 0x42) { + cursor.next = skipSignedLeb128(bytes, cursor.next, end, opcode === 0x41 ? 5 : 10); + continue; + } + if (opcode === 0x43 || opcode === 0x44) { + const immediateBytes = opcode === 0x43 ? 4 : 8; + if (cursor.next + immediateBytes > end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated floating-point immediate."); + cursor.next += immediateBytes; + continue; + } + if (opcode === 0xfc) { + const operation = readU32(bytes, cursor.next, end); + cursor.next = operation.next; + if (operation.value <= 7) continue; // Saturating numeric conversions. + if (operation.value === 8) { + cursor = readU32(bytes, cursor.next, end); // data index + const memory = readU32(bytes, cursor.next, end); + if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory."); + cursor.next = memory.next; + continue; + } + if (operation.value === 9) { cursor = readU32(bytes, cursor.next, end); continue; } // data.drop + if (operation.value === 10) { + const firstMemory = readU32(bytes, cursor.next, end); + const secondMemory = readU32(bytes, firstMemory.next, end); + if (firstMemory.value !== 0 || secondMemory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory."); + cursor.next = secondMemory.next; + continue; + } + if (operation.value === 11) { + const memory = readU32(bytes, cursor.next, end); + if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory."); + cursor.next = memory.next; + continue; + } + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Table, GC, SIMD, thread, and unknown Wasm extension instructions are disabled."); + } + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts scalar core instructions only; reference, GC, SIMD, thread, and unknown extension instructions are disabled."); + } + return localCount; +} + +/** + * Resource-policy preflight before the fixed Wasmi interpreter parses an extension. + * It bounds the binary work up front; Wasmi still performs full module validation. + */ +export function validateSkinExtensionWasmBytes(source: Uint8Array): void { + if (!(source instanceof Uint8Array) || source.byteLength < WASM_HEADER.length || source.byteLength > SKIN_EXTENSION_WASM_SOURCE_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_SIZE", "The extension module is empty, invalid, or exceeds its size limit."); + } + if (WASM_HEADER.some((byte, index) => source[index] !== byte)) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module header or version is unsupported."); + } + + let offset: number = WASM_HEADER.length; + let previousSectionRank = 0; + let customSectionCount = 0; + const seenSections = new Set(); + let definedFunctionCount: number | undefined; + let codeFunctionCount: number | undefined; + let codeBytes = 0; + let totalLocalCount = 0; + while (offset < source.byteLength) { + const sectionId = source[offset++]; + if (sectionId > 12) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains an unknown section."); + if (sectionId === 0) { + customSectionCount += 1; + if (customSectionCount > 8) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many custom sections."); + } else { + if (seenSections.has(sectionId)) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains a duplicate section."); + seenSections.add(sectionId); + // The data-count section (12) is ordered immediately before code (10) by the Wasm binary format. + const rank = sectionId === 12 ? 9.5 : sectionId; + if (rank <= previousSectionRank) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module sections are out of order."); + previousSectionRank = rank; + } + if (sectionId === 8) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Module start functions are disabled; extensions may enter only through the exported run function."); + } + const sectionLength = readU32(source, offset, source.byteLength); + offset = sectionLength.next; + const sectionEnd = offset + sectionLength.value; + if (sectionEnd > source.byteLength) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section."); + + if (sectionId === 1) validateTypeSection(source, offset, sectionEnd); + + const vectorLimit = BOUNDED_VECTOR_COUNTS.get(sectionId); + if (vectorLimit !== undefined) { + const count = readU32(source, offset, sectionEnd); + if (count.value > vectorLimit) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module exceeds a structural item limit."); + if (sectionId === 3) definedFunctionCount = count.value; + } + + // This model permits exactly one host-provided bounded linear memory and no tables. + // Module-defined memories, tables, and element segments would bypass that resource model. + if (sectionId === 4 || sectionId === 5) { + const count = readU32(source, offset, sectionEnd).value; + if (count !== 0) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Extension modules must import bounded memory and cannot define memory or tables."); + } + } + if (sectionId === 9 && readU32(source, offset, sectionEnd).value !== 0) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Extension modules cannot declare element segments or tables."); + } + + if (sectionId === 10) { + let cursor = offset; + const count = readU32(source, cursor, sectionEnd); + cursor = count.next; + if (count.value > SKIN_EXTENSION_WASM_FUNCTION_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many function bodies."); + } + codeFunctionCount = count.value; + for (let index = 0; index < count.value; index += 1) { + const body = readU32(source, cursor, sectionEnd); + cursor = body.next; + if (!body.value || body.value > SKIN_EXTENSION_WASM_FUNCTION_BODY_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function body exceeds its size limit."); + } + codeBytes += body.value; + if (codeBytes > SKIN_EXTENSION_WASM_CODE_BYTES_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension code section exceeds its total size limit."); + } + const bodyEnd = cursor + body.value; + if (bodyEnd > sectionEnd) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "An extension function body is truncated."); + totalLocalCount += scanFunctionBody(source, cursor, bodyEnd); + if (totalLocalCount > SKIN_EXTENSION_WASM_LOCAL_LIMIT) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module declares too many local values."); + } + cursor = bodyEnd; + } + if (cursor !== sectionEnd) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension code section contains trailing bytes."); + } + offset = sectionEnd; + } + if (definedFunctionCount !== undefined && codeFunctionCount !== undefined && definedFunctionCount !== codeFunctionCount) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function and code counts do not match."); + } +} + +export interface SkinExtensionWasmModuleMetadata { + usesSessionStatus: boolean; + memoryMaximumPages: number; +} + +function readWasmName(bytes: Uint8Array, offset: number, end: number): { value: string; next: number } { + const length = readU32(bytes, offset, end); + if (length.value > 80 || length.next + length.value > end) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module contains an invalid import or export name."); + } + try { + return { + value: new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(length.next, length.next + length.value)), + next: length.next + length.value, + }; + } catch { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module contains an invalid UTF-8 import or export name."); + } +} + +function readImportedMemoryMaximum(bytes: Uint8Array, offset: number, end: number): { maximumPages: number; next: number } { + const flags = readU32(bytes, offset, end); + if (flags.value !== 0 && flags.value !== 1) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Shared and memory64 imports are not supported."); + } + const minimum = readU32(bytes, flags.next, end); + let next = minimum.next; + let maximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES; + if (flags.value === 1) { + const maximum = readU32(bytes, next, end); + next = maximum.next; + maximumPages = maximum.value; + if (maximumPages < 1 || maximumPages > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES || maximumPages < minimum.value) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The imported memory limit is outside the host's allowed range."); + } + } + if (minimum.value > 1 || minimum.value > maximumPages) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The module requests more initial memory than the host provides."); + } + return { maximumPages, next }; +} + +/** Parses only bounded imports/exports; author bytes never reach the browser's native Wasm compiler. */ +export function validateSkinExtensionWasmImportsAndExports( + bytes: Uint8Array, + grantedPermissions: readonly string[] = [], +): SkinExtensionWasmModuleMetadata { + validateSkinExtensionWasmBytes(bytes); + let offset: number = WASM_HEADER.length; + let memoryMaximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES; + let hasMemory = false; + let usesSessionStatus = false; + let hasExports = false; + + while (offset < bytes.byteLength) { + const sectionId = bytes[offset++]; + const sectionLength = readU32(bytes, offset, bytes.byteLength); + offset = sectionLength.next; + const end = offset + sectionLength.value; + if (end > bytes.byteLength) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section."); + + if (sectionId === 2) { + const count = readU32(bytes, offset, end); + if (count.value < 1 || count.value > 2) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and at most one approved capability."); + } + let cursor = count.next; + for (let index = 0; index < count.value; index += 1) { + const moduleName = readWasmName(bytes, cursor, end); + const fieldName = readWasmName(bytes, moduleName.next, end); + cursor = fieldName.next; + if (cursor >= end || moduleName.value !== "env") { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module may import only the host's env memory and approved capability."); + } + const kind = bytes[cursor++]; + if (kind === 0) { + const typeIndex = readU32(bytes, cursor, end); + cursor = typeIndex.next; + if (fieldName.value !== "session_status_read" || usesSessionStatus) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module requested an unsupported or duplicate function import."); + } + usesSessionStatus = true; + } else if (kind === 2) { + if (fieldName.value !== "memory" || hasMemory) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import exactly one env.memory value."); + } + const memory = readImportedMemoryMaximum(bytes, cursor, end); + cursor = memory.next; + memoryMaximumPages = memory.maximumPages; + hasMemory = true; + } else { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "Tables, globals, tags, and unknown imports are not supported."); + } + } + if (cursor !== end || !hasMemory) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import exactly one env.memory value."); + } + } + + if (sectionId === 7) { + const count = readU32(bytes, offset, end); + if (count.value !== 1) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module must export only one run function."); + } + let cursor = count.next; + const name = readWasmName(bytes, cursor, end); + cursor = name.next; + if (cursor >= end || name.value !== "run" || bytes[cursor++] !== 0) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module must export one function named run."); + } + const functionIndex = readU32(bytes, cursor, end); + cursor = functionIndex.next; + if (cursor !== end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module has trailing export data."); + hasExports = true; + } + + offset = end; + } + + if (!hasMemory || !hasExports) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import bounded env.memory and export a run function."); + } + if (usesSessionStatus && !grantedPermissions.includes("session.status.read")) { + throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The module imports session status without an approved session.status.read capability."); + } + return { usesSessionStatus, memoryMaximumPages }; +} diff --git a/web/src/services/skin-extension-wasm-sandbox.test.ts b/web/src/services/skin-extension-wasm-sandbox.test.ts new file mode 100644 index 0000000..9222a43 --- /dev/null +++ b/web/src/services/skin-extension-wasm-sandbox.test.ts @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createSkinExtensionApproval, parseSkinExtensionManifest } from "../../../src/shared/skin-extension.js"; +import { + createSkinExtensionWasmSandboxPrototype, + SKIN_EXTENSION_WASM_RUNTIME_ENABLED, +} from "./skin-extension-wasm-sandbox.js"; +import { SKIN_EXTENSION_WASM_SOURCE_LIMIT } from "./skin-extension-wasm-policy.js"; + +const manifest = parseSkinExtensionManifest({ + schemaVersion: 1, + packageType: "extension", + id: "test.wasm-extension", + name: "Wasm extension", + version: "1.0.0", + apiVersion: 1, + permissions: [], +}); + +test("production Wasm execution remains disabled while the bounded runner is prototype-only", () => { + assert.equal(SKIN_EXTENSION_WASM_RUNTIME_ENABLED, false); + assert.throws(() => createSkinExtensionWasmSandboxPrototype({ + manifest, + approval: createSkinExtensionApproval(manifest), + wasmBytes: new Uint8Array(SKIN_EXTENSION_WASM_SOURCE_LIMIT + 1), + readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }), + prototypeOnly: true, + }), { code: "SKIN_EXTENSION_WASM_SIZE" }); +}); diff --git a/web/src/services/skin-extension-wasm-sandbox.ts b/web/src/services/skin-extension-wasm-sandbox.ts new file mode 100644 index 0000000..7bd1b09 --- /dev/null +++ b/web/src/services/skin-extension-wasm-sandbox.ts @@ -0,0 +1,217 @@ +import { + isSkinExtensionPermissionApproved, + parseSkinExtensionApproval, + parseSkinExtensionManifest, + sanitizeSkinExtensionSessionStatus, + type SkinExtensionPermissionId, + type SkinExtensionSessionStatus, +} from "../../../src/shared/skin-extension.js"; +import { + SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS, + SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES, + SKIN_EXTENSION_WASM_MESSAGE_LIMIT, + SKIN_EXTENSION_WASM_SOURCE_LIMIT, + SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS, + SKIN_EXTENSION_WASM_STATUS_READ_LIMIT, + validateSkinExtensionWasmBytes, +} from "./skin-extension-wasm-policy.js"; + +export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = false as const; + +export class SkinExtensionWasmSandboxError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinExtensionWasmSandboxError"; + } +} + +export interface SkinExtensionWasmSandboxResult { + result: number | string; + linearMemoryBytes: number; + statusReadCount: number; + sessionSnapshot?: SkinExtensionSessionStatus; +} + +export interface SkinExtensionWasmSandboxOptions { + manifest: unknown; + approval: unknown; + wasmBytes: Uint8Array; + readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise; + /** This prototype is available only to the development security harness. */ + prototypeOnly: true; +} + +export interface SkinExtensionWasmSandboxHandle { + readonly ready: Promise; + readonly result: Promise; + readonly stopped: Promise; + readonly closed: boolean; + readonly closeReason: string | null; + readonly capabilityRequests: number; + revokePermission(permission: SkinExtensionPermissionId): void; + close(reason?: string): void; +} + +function isPlainRecord(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function messageSize(value: unknown): number { + try { return new TextEncoder().encode(JSON.stringify(value)).byteLength; } + catch { return SKIN_EXTENSION_WASM_MESSAGE_LIMIT + 1; } +} + +/** Development-only Wasm runner: no author JavaScript is evaluated and every job owns one terminable Worker. */ +export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWasmSandboxOptions): SkinExtensionWasmSandboxHandle { + if (options.prototypeOnly !== true) throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_PROTOTYPE_ONLY", "The Wasm runner is a development-only security prototype."); + if (!(options.wasmBytes instanceof Uint8Array) || !options.wasmBytes.byteLength || options.wasmBytes.byteLength > SKIN_EXTENSION_WASM_SOURCE_LIMIT) { + throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_SIZE", "The extension module is empty or exceeds its source limit."); + } + + const manifest = parseSkinExtensionManifest(options.manifest); + const approval = parseSkinExtensionApproval(options.approval); + validateSkinExtensionWasmBytes(options.wasmBytes); + const grantedPermissions = manifest.permissions.filter((permission) => + isSkinExtensionPermissionApproved(approval, manifest.id, permission)); + const wasmBytes = options.wasmBytes.slice(); + const worker = new Worker(new URL("./skin-extension-wasm-worker.ts", import.meta.url), { + type: "module", + name: "webspeak-skin-extension-wasm-prototype", + }); + + let active = true; + let closeReason: string | null = null; + const hostAbortController = new AbortController(); + let readySettled = false; + let resultSettled = false; + let capabilityRequests = 0; + let approvedSessionStatus: SkinExtensionSessionStatus | undefined; + let startupTimer: number | undefined; + let executionTimer: number | undefined; + let resolveReady!: () => void; + let rejectReady!: (error: Error) => void; + let resolveResult!: (value: SkinExtensionWasmSandboxResult) => void; + let rejectResult!: (error: Error) => void; + let resolveStopped!: () => void; + const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; }); + const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; }); + const stopped = new Promise((resolve) => { resolveStopped = resolve; }); + void ready.catch(() => undefined); + void result.catch(() => undefined); + + function finish(reason: string, error?: Error): void { + if (!active) return; + active = false; + closeReason = reason; + approvedSessionStatus = undefined; + hostAbortController.abort(); + if (startupTimer !== undefined) clearTimeout(startupTimer); + if (executionTimer !== undefined) clearTimeout(executionTimer); + worker.onmessage = null; + worker.onmessageerror = null; + worker.onerror = null; + worker.terminate(); + if (!readySettled) { + readySettled = true; + rejectReady(error ?? new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_CLOSED", "The Wasm extension stopped before execution began.")); + } + if (!resultSettled) { + resultSettled = true; + rejectResult(error ?? new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_CLOSED", "The Wasm extension stopped before returning a result.")); + } + resolveStopped(); + } + + function complete(value: SkinExtensionWasmSandboxResult): void { + if (!active) return; + active = false; + closeReason = "completed"; + if (startupTimer !== undefined) clearTimeout(startupTimer); + if (executionTimer !== undefined) clearTimeout(executionTimer); + worker.onmessage = null; + worker.onmessageerror = null; + worker.onerror = null; + worker.terminate(); + if (!readySettled) { readySettled = true; resolveReady(); } + if (!resultSettled) { resultSettled = true; resolveResult(value); } + resolveStopped(); + } + + worker.onmessage = (event: MessageEvent) => { + if (!active || messageSize(event.data) > SKIN_EXTENSION_WASM_MESSAGE_LIMIT || !isPlainRecord(event.data)) { + finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker returned an invalid or oversized message.")); + return; + } + const message = event.data; + if (message.type === "capability-request") { + if (Object.keys(message).length !== 3 || message.requestId !== "session-status-1" || message.permission !== "session.status.read" + || capabilityRequests !== 0 || !grantedPermissions.includes("session.status.read")) { + finish("capability-denied", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The Wasm worker requested an unapproved capability.")); + return; + } + capabilityRequests += 1; + Promise.resolve().then(() => options.readSessionStatus(hostAbortController.signal)).then(sanitizeSkinExtensionSessionStatus).then((status) => { + if (!active) return; + approvedSessionStatus = status; + worker.postMessage({ type: "capability-response", requestId: message.requestId, approved: true, status }); + }).catch(() => { + if (active) worker.postMessage({ type: "capability-response", requestId: message.requestId, approved: false }); + }); + return; + } + if (message.type === "running" && Object.keys(message).length === 1) { + if (readySettled) { + finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker sent an unexpected execution-start message.")); + return; + } + readySettled = true; + if (startupTimer !== undefined) clearTimeout(startupTimer); + resolveReady(); + executionTimer = window.setTimeout(() => finish("execution-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_EXECUTION_TIMEOUT", "The Wasm extension exceeded its execution time limit.")), SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS); + return; + } + if (message.type === "complete") { + const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount"]; + if (Object.keys(message).length !== expectedKeys.length + || Object.keys(message).some((key) => !expectedKeys.includes(key)) + || (typeof message.result !== "number" && typeof message.result !== "string") + || !Number.isSafeInteger(message.linearMemoryBytes) || (message.linearMemoryBytes as number) < 0 + || (message.linearMemoryBytes as number) > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024 + || !Number.isSafeInteger(message.statusReadCount) || (message.statusReadCount as number) < 0 + || (message.statusReadCount as number) > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT) { + finish("invalid-result", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The Wasm worker returned a result outside its allowed shape.")); + return; + } + complete({ result: message.result as number | string, linearMemoryBytes: message.linearMemoryBytes as number, + statusReadCount: message.statusReadCount as number, ...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) }); + return; + } + if (message.type === "error" && Object.keys(message).length === 3 + && typeof message.code === "string" && typeof message.message === "string") { + finish("worker-error", new SkinExtensionWasmSandboxError(message.code, message.message)); + return; + } + finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker returned an unsupported message.")); + }; + worker.onmessageerror = () => finish("message-deserialization-failed", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker message could not be decoded.")); + worker.onerror = () => finish("worker-error", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_WORKER_FAILED", "The isolated Wasm worker failed.")); + startupTimer = window.setTimeout(() => finish("startup-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_STARTUP_TIMEOUT", "The Wasm worker did not finish initialization in time.")), SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS); + + const bytes = wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength) as ArrayBuffer; + worker.postMessage({ type: "run", bytes, approvedPermissions: grantedPermissions }, [bytes]); + + return { + ready, + result, + stopped, + get closed() { return !active; }, + get closeReason() { return closeReason; }, + get capabilityRequests() { return capabilityRequests; }, + revokePermission(permission) { + if (manifest.permissions.includes(permission)) finish(`permission-revoked:${permission}`); + }, + close(reason = "closed") { finish(reason); }, + }; +} diff --git a/web/src/services/skin-extension-wasm-worker.ts b/web/src/services/skin-extension-wasm-worker.ts new file mode 100644 index 0000000..a01138c --- /dev/null +++ b/web/src/services/skin-extension-wasm-worker.ts @@ -0,0 +1,167 @@ +import { + sanitizeSkinExtensionSessionStatus, + type SkinExtensionSessionStatus, +} from "../../../src/shared/skin-extension.js"; +import { + SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES, + SKIN_EXTENSION_WASM_FUEL_LIMIT, + SKIN_EXTENSION_WASM_MESSAGE_LIMIT, + SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT, + SKIN_EXTENSION_WASM_STATUS_READ_LIMIT, + validateSkinExtensionWasmImportsAndExports, +} from "./skin-extension-wasm-policy.js"; + +interface RunMessage { + type: "run"; + bytes: ArrayBuffer; + approvedPermissions: string[]; +} + +interface CapabilityResponse { + type: "capability-response"; + requestId: string; + approved: boolean; + status?: unknown; +} + +interface WasmiInterpreterExports extends WebAssembly.Exports { + memory: WebAssembly.Memory; + alloc: (size: number) => number; + run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number, + statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint; + last_error_code: () => number; + last_status_read_count: () => number; + last_guest_memory_bytes: () => number; +} + +const scope = self as unknown as { + addEventListener(type: string, listener: (event: MessageEvent) => void): void; + postMessage(message: unknown): void; +}; +let started = false; +let pendingCapability: { requestId: string; resolve: (message: CapabilityResponse) => void } | null = null; + +function isPlainRecord(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function sendError(code: string, message: string): void { + scope.postMessage({ type: "error", code, message }); +} + +scope.addEventListener("message", (event: MessageEvent) => { + const value = event.data; + if (isPlainRecord(value) && value.type === "capability-response" && pendingCapability + && value.requestId === pendingCapability.requestId && typeof value.approved === "boolean") { + const resolve = pendingCapability.resolve; + pendingCapability = null; + resolve(value as unknown as CapabilityResponse); + return; + } + if (started || !isPlainRecord(value) || value.type !== "run" || !(value.bytes instanceof ArrayBuffer) + || !Array.isArray(value.approvedPermissions) || value.approvedPermissions.some((permission) => typeof permission !== "string") + || Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions"].includes(key))) { + sendError("SKIN_EXTENSION_WASM_JOB_INVALID", "The isolated Wasm job message is invalid."); + return; + } + started = true; + void run(value as unknown as RunMessage); +}); + +async function requestSessionStatus(): Promise { + const requestId = "session-status-1"; + const response = await new Promise((resolve) => { + pendingCapability = { requestId, resolve }; + scope.postMessage({ type: "capability-request", requestId, permission: "session.status.read" }); + }); + if (!response.approved) throw new Error("The host denied session.status.read."); + return sanitizeSkinExtensionSessionStatus(response.status); +} + +async function run(job: RunMessage): Promise { + try { + const bytes = new Uint8Array(job.bytes); + const metadata = validateSkinExtensionWasmImportsAndExports(bytes, job.approvedPermissions); + const interpreter = await loadWasmiInterpreter(); + const status = metadata.usesSessionStatus ? await requestSessionStatus() : null; + const statusBytes = status ? new TextEncoder().encode(JSON.stringify(status)) : null; + if (statusBytes && statusBytes.byteLength > SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT) { + sendError("SKIN_EXTENSION_WASM_STATUS_SIZE", "The approved session snapshot exceeds its size limit."); + return; + } + + const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0); + const pointer = interpreter.alloc(payloadLength); + if (!pointer) { + sendError("SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT", "The extension input exceeds the interpreter's bounded memory."); + return; + } + new Uint8Array(interpreter.memory.buffer, pointer, bytes.byteLength).set(bytes); + const statusPointer = statusBytes ? pointer + bytes.byteLength : 0; + if (statusBytes) new Uint8Array(interpreter.memory.buffer, statusPointer, statusBytes.byteLength).set(statusBytes); + + scope.postMessage({ type: "running" }); + const rawResult = interpreter.run(pointer, bytes.byteLength, statusPointer, statusBytes?.byteLength ?? 0, + metadata.usesSessionStatus ? 1 : 0, metadata.memoryMaximumPages, SKIN_EXTENSION_WASM_FUEL_LIMIT); + const errorCode = interpreter.last_error_code(); + if (errorCode !== 0) { + const code = errorCode === 5 ? "SKIN_EXTENSION_WASM_EXECUTION_LIMIT" + : errorCode === 6 ? "SKIN_EXTENSION_WASM_MEMORY_LIMIT" + : errorCode === 10 ? "SKIN_EXTENSION_WASM_IMPORT_INVALID" + : errorCode === 11 ? "SKIN_EXTENSION_WASM_PERMISSION_INVALID" + : "SKIN_EXTENSION_WASM_INTERPRETER_FAILED"; + sendError(code, "The extension was rejected or stopped inside the bounded Wasmi interpreter."); + return; + } + + const result = Number(rawResult); + const statusReadCount = interpreter.last_status_read_count(); + const linearMemoryBytes = interpreter.last_guest_memory_bytes(); + if (!Number.isSafeInteger(result) || !Number.isSafeInteger(statusReadCount) || statusReadCount < 0 + || statusReadCount > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT || !Number.isSafeInteger(linearMemoryBytes) + || linearMemoryBytes < 0 || linearMemoryBytes > metadata.memoryMaximumPages * 64 * 1024 + || linearMemoryBytes > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024) { + sendError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The interpreter returned a value outside the allowed resource policy."); + return; + } + const message = { + type: "complete", + result, + linearMemoryBytes, + statusReadCount, + }; + if (new TextEncoder().encode(JSON.stringify(message)).byteLength > SKIN_EXTENSION_WASM_MESSAGE_LIMIT) { + sendError("SKIN_EXTENSION_WASM_MESSAGE_SIZE", "The module result exceeds its message limit."); + return; + } + scope.postMessage(message); + } catch (error) { + const candidate = error as { code?: unknown; message?: unknown }; + const code = typeof candidate?.code === "string" ? candidate.code : "SKIN_EXTENSION_WASM_FAILED"; + const detail = typeof candidate?.message === "string" ? ` ${candidate.message.slice(0, 240)}` : ""; + sendError(code, `The bounded Wasm extension failed validation or execution.${detail}`); + } +} + +async function loadWasmiInterpreter(): Promise { + const response = await fetch(new URL("/skin-wasm-interpreter.wasm", self.location.origin), { cache: "force-cache" }); + if (!response.ok) throw new Error("The bounded Wasmi interpreter asset could not be loaded."); + const contentLength = Number(response.headers.get("content-length")); + if (Number.isFinite(contentLength) && (contentLength < 8 || contentLength > 8 * 1024 * 1024)) { + throw new Error("The bounded Wasmi interpreter asset has an invalid size."); + } + const artifact = await response.arrayBuffer(); + if (artifact.byteLength < 8 || artifact.byteLength > 8 * 1024 * 1024) { + throw new Error("The bounded Wasmi interpreter asset has an invalid size."); + } + const { instance } = await WebAssembly.instantiate(artifact); + const exports = instance.exports as unknown as WasmiInterpreterExports; + if (!(exports.memory instanceof WebAssembly.Memory) || typeof exports.alloc !== "function" + || typeof exports.run !== "function" || typeof exports.last_error_code !== "function" + || typeof exports.last_status_read_count !== "function" || typeof exports.last_guest_memory_bytes !== "function") { + throw new Error("The bounded Wasmi interpreter exposes an incompatible runtime interface."); + } + return exports; +} diff --git a/web/src/services/skin-layout-focus.test.ts b/web/src/services/skin-layout-focus.test.ts new file mode 100644 index 0000000..6f700bd --- /dev/null +++ b/web/src/services/skin-layout-focus.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { orderSequentialFocusTargets } from "./skin-layout-focus.js"; + +test("focus preview follows browser order: positive tabindex first, then DOM order, excluding negative targets", () => { + const targets = [ + { id: "first-dom", tabIndex: 0 }, + { id: "second-positive", tabIndex: 2 }, + { id: "first-positive", tabIndex: 1 }, + { id: "programmatic-only", tabIndex: -1 }, + { id: "second-dom", tabIndex: 0 }, + { id: "same-positive", tabIndex: 1 }, + ]; + + assert.deepEqual(orderSequentialFocusTargets(targets).map((target) => target.id), [ + "first-positive", "same-positive", "second-positive", "first-dom", "second-dom", + ]); +}); diff --git a/web/src/services/skin-layout-focus.ts b/web/src/services/skin-layout-focus.ts new file mode 100644 index 0000000..22eafbf --- /dev/null +++ b/web/src/services/skin-layout-focus.ts @@ -0,0 +1,18 @@ +export interface SequentialFocusTarget { + tabIndex: number; +} + +/** Mirrors browser sequential focus order for a DOM-ordered list of focusable controls. */ +export function orderSequentialFocusTargets(targets: readonly T[]): T[] { + return targets + .map((target, domOrder) => ({ target, domOrder })) + .filter(({ target }) => Number.isInteger(target.tabIndex) && target.tabIndex >= 0) + .sort((left, right) => { + const leftBucket = left.target.tabIndex > 0 ? 0 : 1; + const rightBucket = right.target.tabIndex > 0 ? 0 : 1; + return leftBucket - rightBucket + || (leftBucket === 0 ? left.target.tabIndex - right.target.tabIndex : 0) + || left.domOrder - right.domOrder; + }) + .map(({ target }) => target); +} diff --git a/web/src/services/skin-layout-geometry.test.ts b/web/src/services/skin-layout-geometry.test.ts new file mode 100644 index 0000000..b0c6ec6 --- /dev/null +++ b/web/src/services/skin-layout-geometry.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + analyzeSkinLayoutGeometry, + clampSkinLayoutOffset, + getSkinLayoutOffsetBounds, +} from "./skin-layout-geometry.js"; + +const page = { left: 0, top: 0, right: 800, bottom: 600 }; + +test("layout diagnostics detect collision and overflow only when bounds actually intersect", () => { + const target = { left: 700, top: 520, right: 840, bottom: 660 }; + const issues = analyzeSkinLayoutGeometry([target], page, [{ left: 720, top: 540, right: 780, bottom: 580 }]); + assert.deepEqual(issues, { overflow: true, overlap: true }); + assert.deepEqual(analyzeSkinLayoutGeometry( + [{ left: 0, top: 0, right: 40, bottom: 40 }], page, + [{ left: 48, top: 0, right: 90, bottom: 40 }], + ), { overflow: false, overlap: false }); + assert.deepEqual(analyzeSkinLayoutGeometry([ + { left: 0, top: 0, right: 140, bottom: 80 }, + { left: 100, top: 0, right: 240, bottom: 80 }, + ], page, []), { overflow: false, overlap: true }); +}); + +test("position controls clamp every matching instance inside the available layout container", () => { + const bounds = getSkinLayoutOffsetBounds([ + { left: 100, top: 80, right: 220, bottom: 160 }, + { left: 300, top: 300, right: 420, bottom: 380 }, + ], page, 0, "x"); + assert.deepEqual(bounds, { minimum: -100, maximum: 380 }); + assert.equal(clampSkinLayoutOffset(-500, bounds), -100); + assert.equal(clampSkinLayoutOffset(500, bounds), 380); + assert.equal(getSkinLayoutOffsetBounds([{ left: -40, top: 20, right: 860, bottom: 50 }], page, 0, "x"), null); +}); diff --git a/web/src/services/skin-layout-geometry.ts b/web/src/services/skin-layout-geometry.ts new file mode 100644 index 0000000..9ffa666 --- /dev/null +++ b/web/src/services/skin-layout-geometry.ts @@ -0,0 +1,62 @@ +export interface SkinLayoutRect { + left: number; + top: number; + right: number; + bottom: number; +} + +export interface SkinLayoutOffsetBounds { + minimum: number; + maximum: number; +} + +export interface SkinLayoutGeometryIssues { + overflow: boolean; + overlap: boolean; +} + +export function analyzeSkinLayoutGeometry( + targets: readonly SkinLayoutRect[], + container: SkinLayoutRect, + peers: readonly SkinLayoutRect[], + overlapThreshold = 8, +): SkinLayoutGeometryIssues { + const intersects = (first: SkinLayoutRect, second: SkinLayoutRect) => { + const width = Math.min(first.right, second.right) - Math.max(first.left, second.left); + const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top); + return width > overlapThreshold && height > overlapThreshold; + }; + const overflow = targets.some((target) => target.left < container.left - 1 || target.top < container.top - 1 + || target.right > container.right + 1 || target.bottom > container.bottom + 1); + const overlap = targets.some((target, index) => peers.some((peer) => intersects(target, peer)) + || targets.slice(index + 1).some((peer) => intersects(target, peer))); + return { overflow, overlap }; +} + +export function getSkinLayoutOffsetBounds( + targets: readonly SkinLayoutRect[], + container: SkinLayoutRect, + currentOffset: number, + axis: "x" | "y", + absoluteLimit = 2000, +): SkinLayoutOffsetBounds | null { + if (!targets.length || !Number.isFinite(currentOffset)) return null; + const containerStart = axis === "x" ? container.left : container.top; + const containerEnd = axis === "x" ? container.right : container.bottom; + let minimum = -absoluteLimit; + let maximum = absoluteLimit; + for (const target of targets) { + const start = axis === "x" ? target.left : target.top; + const end = axis === "x" ? target.right : target.bottom; + const baseStart = start - currentOffset; + const baseEnd = end - currentOffset; + minimum = Math.max(minimum, containerStart - baseStart); + maximum = Math.min(maximum, containerEnd - baseEnd); + } + return minimum <= maximum ? { minimum: Math.ceil(minimum), maximum: Math.floor(maximum) } : null; +} + +export function clampSkinLayoutOffset(value: number, bounds: SkinLayoutOffsetBounds | null): number { + if (!bounds || !Number.isFinite(value)) return 0; + return Math.max(bounds.minimum, Math.min(bounds.maximum, Math.round(value))); +} diff --git a/web/src/services/skin-layout-runtime.ts b/web/src/services/skin-layout-runtime.ts new file mode 100644 index 0000000..8af96b6 --- /dev/null +++ b/web/src/services/skin-layout-runtime.ts @@ -0,0 +1,261 @@ +import layoutRuntimeCss from "../skins/layout-runtime.css?inline"; +import { + canEditSkinLayoutComponent, + getSkinLayoutComponentId, + getSkinLayoutComponent, + type SkinLayoutDocument, + type SkinLayoutPage, + type SkinLayoutPlacement, + type SkinLayoutProfile, +} from "../../../src/shared/skin-layout.js"; +import { + clearSkinLayoutOverrides, + loadSkinLayoutOverrides, + saveSkinLayoutOverrides, + updateSkinLayoutOverride, +} from "./skin-layout-storage.js"; + +const STYLE_ID = "webspeak-layout-runtime"; +const MOBILE_QUERY = "(max-width: 740px)"; +const TABLET_QUERY = "(min-width: 741px) and (max-width: 1100px)"; + +export interface ActiveSkinLayoutContext { + root: HTMLElement; + skinId: string; + page: SkinLayoutPage; + profile: SkinLayoutProfile; +} + +let activePackageSkinId: string | null = null; +let activePackageLayout: SkinLayoutDocument | null = null; +let observer: MutationObserver | null = null; +let refreshFrame = 0; +let editorEnabled = false; +let selectedComponentId: string | null = null; +let previewComponentId: string | null = null; +let previewPlacement: SkinLayoutPlacement | null = null; +let previewScope = ""; + +function isLayoutPage(value: string | undefined): value is SkinLayoutPage { + return value === "home" || value === "voice" || value === "demo"; +} + +function currentProfile(): SkinLayoutProfile { + if (typeof window === "undefined") return "desktop"; + if (window.matchMedia(MOBILE_QUERY).matches) return "mobile"; + return window.matchMedia(TABLET_QUERY).matches ? "tablet" : "desktop"; +} + +function activeRoots(): HTMLElement[] { + if (typeof document === "undefined") return []; + return [...document.querySelectorAll(".ws-skin-root[data-ws-page]")]; +} + +export function getActiveSkinLayoutContext(): ActiveSkinLayoutContext | null { + const root = activeRoots()[0]; + if (!root || !isLayoutPage(root.dataset.wsPage)) return null; + return { + root, + skinId: root.dataset.wsSkin || activePackageSkinId || "builtin.light", + page: root.dataset.wsPage, + profile: currentProfile(), + }; +} + +function effectivePlacements(context: ActiveSkinLayoutContext): Record { + const packageEntries = activePackageSkinId === context.skinId + ? activePackageLayout?.pages[context.page]?.[context.profile] ?? {} + : {}; + const userEntries = loadSkinLayoutOverrides(context.skinId).pages[context.page]?.[context.profile] ?? {}; + const result: Record = {}; + for (const [id, placement] of Object.entries(packageEntries)) result[id] = { ...placement }; + for (const [id, placement] of Object.entries(userEntries)) result[id] = { ...result[id], ...placement }; + const scope = context.skinId + ":" + context.page + ":" + context.profile; + if (previewComponentId && previewPlacement && previewScope === scope) { + result[previewComponentId] = { ...result[previewComponentId], ...previewPlacement }; + } + return result; +} + +function setVariable(element: HTMLElement, dataFlag: string, variable: string, value: string | undefined): void { + if (value === undefined) { + delete element.dataset[dataFlag]; + element.style.removeProperty(variable); + } else { + element.dataset[dataFlag] = "true"; + element.style.setProperty(variable, value); + } +} + +function clearLayoutAttributes(element: HTMLElement): void { + for (const key of ["wsLayoutActive", "wsLayoutHidden", "wsLayoutSelected", "wsLayoutForeground", "wsLayoutBackground", "wsLayoutBorder", "wsLayoutRadius", "wsLayoutWidth", "wsLayoutHeight", "wsLayoutTouchTarget"]) { + delete element.dataset[key]; + } + for (const key of ["--ws-layout-x", "--ws-layout-y", "--ws-layout-scale", "--ws-layout-width", "--ws-layout-height", "--ws-layout-foreground", "--ws-layout-background", "--ws-layout-border", "--ws-layout-radius"]) { + element.style.removeProperty(key); + } +} + +function componentId(element: HTMLElement): string | null { + return getSkinLayoutComponentId(element.dataset.wsPart, element.dataset.wsControlKind); +} + +function trustedAncestorIds(element: HTMLElement, root: HTMLElement): string[] { + const ids: string[] = []; + let ancestor = element.parentElement; + while (ancestor && ancestor !== root) { + const id = componentId(ancestor); + if (id) ids.push(id); + ancestor = ancestor.parentElement; + } + return ids; +} + +function applyRoot(root: HTMLElement): void { + const pageValue = root.dataset.wsPage; + if (!isLayoutPage(pageValue)) return; + const skinId = root.dataset.wsSkin || activePackageSkinId || "builtin.light"; + const context: ActiveSkinLayoutContext = { root, skinId, page: pageValue, profile: currentProfile() }; + const placements = effectivePlacements(context); + const nodes = [ + ...(root.matches("[data-ws-part]") ? [root] : []), + ...root.querySelectorAll("[data-ws-part]"), + ]; + for (const element of nodes) { + const id = componentId(element); + const component = id ? getSkinLayoutComponent(id, context.page) : undefined; + if (!component || !canEditSkinLayoutComponent(id!, context.page, trustedAncestorIds(element, root))) { + clearLayoutAttributes(element); + continue; + } + const placement = placements[id!]; + if (!placement || !Object.keys(placement).length) { + clearLayoutAttributes(element); + // Registered touch controls keep their minimum hit area even before a + // user applies a layout override; editing must never be required for safety. + if (component.minTouchTarget) element.dataset.wsLayoutTouchTarget = String(component.minTouchTarget); + continue; + } + element.dataset.wsLayoutActive = "true"; + if (component.minTouchTarget) element.dataset.wsLayoutTouchTarget = String(component.minTouchTarget); + else delete element.dataset.wsLayoutTouchTarget; + if (placement.visible === false) element.dataset.wsLayoutHidden = "true"; + else delete element.dataset.wsLayoutHidden; + if (placement.x !== undefined) element.style.setProperty("--ws-layout-x", placement.x + "px"); + else element.style.removeProperty("--ws-layout-x"); + if (placement.y !== undefined) element.style.setProperty("--ws-layout-y", placement.y + "px"); + else element.style.removeProperty("--ws-layout-y"); + if (placement.scale !== undefined) element.style.setProperty("--ws-layout-scale", String(placement.scale)); + else element.style.removeProperty("--ws-layout-scale"); + setVariable(element, "wsLayoutWidth", "--ws-layout-width", placement.width === undefined ? undefined : placement.width + "px"); + setVariable(element, "wsLayoutHeight", "--ws-layout-height", placement.height === undefined ? undefined : placement.height + "px"); + setVariable(element, "wsLayoutForeground", "--ws-layout-foreground", placement.foreground); + setVariable(element, "wsLayoutBackground", "--ws-layout-background", placement.background); + setVariable(element, "wsLayoutBorder", "--ws-layout-border", placement.border); + setVariable(element, "wsLayoutRadius", "--ws-layout-radius", placement.radius === undefined ? undefined : placement.radius + "px"); + if (editorEnabled && selectedComponentId === id) element.dataset.wsLayoutSelected = "true"; + else delete element.dataset.wsLayoutSelected; + } + root.dataset.wsLayoutEditing = editorEnabled ? "true" : "false"; +} + +export function refreshSkinLayout(): void { + if (typeof document === "undefined") return; + for (const root of activeRoots()) applyRoot(root); +} + +function scheduleRefresh(): void { + if (typeof window === "undefined" || refreshFrame) return; + refreshFrame = window.requestAnimationFrame(() => { + refreshFrame = 0; + refreshSkinLayout(); + }); +} + +export function initializeSkinLayoutRuntime(): void { + if (typeof document === "undefined") return; + if (!document.getElementById(STYLE_ID)) { + const style = document.createElement("style"); + style.id = STYLE_ID; + style.textContent = layoutRuntimeCss; + document.head.append(style); + } + if (!observer) { + observer = new MutationObserver(scheduleRefresh); + observer.observe(document.body, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ["data-ws-page", "data-ws-skin", "data-ws-part", "data-ws-control-kind"], + }); + window.addEventListener("resize", scheduleRefresh, { passive: true }); + } + scheduleRefresh(); +} + +export function setSkinLayoutPackage(skinId: string, layout: SkinLayoutDocument | null): void { + activePackageSkinId = skinId; + activePackageLayout = layout; + previewComponentId = null; + previewPlacement = null; + previewScope = ""; + scheduleRefresh(); +} + +export function setSkinLayoutEditorState(enabled: boolean, selectedId: string | null = selectedComponentId): void { + editorEnabled = enabled; + selectedComponentId = enabled ? selectedId : null; + scheduleRefresh(); +} + +export function getEffectiveSkinLayoutPlacement(componentIdValue: string): SkinLayoutPlacement | undefined { + const context = getActiveSkinLayoutContext(); + if (!context || !getSkinLayoutComponent(componentIdValue, context.page)?.editable) return undefined; + return effectivePlacements(context)[componentIdValue]; +} + +export function getActiveSkinLayoutOverride(componentIdValue: string): SkinLayoutPlacement | undefined { + const context = getActiveSkinLayoutContext(); + if (!context || !getSkinLayoutComponent(componentIdValue, context.page)?.editable) return undefined; + return loadSkinLayoutOverrides(context.skinId).pages[context.page]?.[context.profile]?.[componentIdValue]; +} + +export function previewActiveSkinLayoutPlacement(componentIdValue: string, placement: SkinLayoutPlacement | null): void { + const context = getActiveSkinLayoutContext(); + previewComponentId = context && placement ? componentIdValue : null; + previewPlacement = context ? placement : null; + previewScope = context ? context.skinId + ":" + context.page + ":" + context.profile : ""; + scheduleRefresh(); +} + +export function saveActiveSkinLayoutPlacement(componentIdValue: string, placement: SkinLayoutPlacement | null): void { + const context = getActiveSkinLayoutContext(); + if (!context) throw new Error("There is no active public skin layout."); + previewComponentId = null; + previewPlacement = null; + previewScope = ""; + updateSkinLayoutOverride(context.skinId, context.page, context.profile, componentIdValue, placement); + scheduleRefresh(); +} + +export function getActiveSkinLayoutOverrides(): SkinLayoutDocument { + const context = getActiveSkinLayoutContext(); + return context ? loadSkinLayoutOverrides(context.skinId) : { schemaVersion: 1, pages: {} }; +} + +export function replaceActiveSkinLayoutOverrides(layout: SkinLayoutDocument): void { + const context = getActiveSkinLayoutContext(); + if (!context) throw new Error("There is no active public skin layout."); + saveSkinLayoutOverrides(context.skinId, layout); + scheduleRefresh(); +} + +export function clearActiveSkinLayoutOverrides(): void { + const context = getActiveSkinLayoutContext(); + if (!context) return; + previewComponentId = null; + previewPlacement = null; + previewScope = ""; + clearSkinLayoutOverrides(context.skinId); + scheduleRefresh(); +} diff --git a/web/src/services/skin-layout-storage.test.ts b/web/src/services/skin-layout-storage.test.ts new file mode 100644 index 0000000..9017317 --- /dev/null +++ b/web/src/services/skin-layout-storage.test.ts @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + clearSkinLayoutOverrides, + exportSkinLayoutMigrationRecovery, + getSkinLayoutMigrationRecovery, + LEGACY_SKIN_LAYOUT_STORAGE_KEY, + loadSkinLayoutOverrides, + saveSkinLayoutOverrides, + SKIN_LAYOUT_STORAGE_KEY, +} from "./skin-layout-storage.js"; + +class MemoryStorage { + private readonly values = new Map(); + getItem(key: string): string | null { return this.values.get(key) ?? null; } + setItem(key: string, value: string): void { this.values.set(key, value); } +} + +function withLocalStorage(run: (storage: MemoryStorage) => T): T { + const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); + const storage = new MemoryStorage(); + Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage }); + try { return run(storage); } + finally { + if (previous) Object.defineProperty(globalThis, "localStorage", previous); + else Reflect.deleteProperty(globalThis, "localStorage"); + } +} + +test("legacy local layouts migrate matching entries and keep incompatible entries recoverable", () => { + withLocalStorage((storage) => { + const legacy = JSON.stringify({ + schemaVersion: 1, + skins: { + "community.illusia-voice": { + schemaVersion: 1, + pages: { home: { desktop: { + "home.header": { x: 32 }, + "home.retired-component": { x: 80 }, + "home.security-note": { visible: false }, + "home.connect": { scale: 0.5 }, + } } }, + }, + }, + }); + storage.setItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY, legacy); + + const migrated = loadSkinLayoutOverrides("community.illusia-voice"); + assert.deepEqual(migrated.pages.home?.desktop, { "home.header": { x: 32 } }); + assert.deepEqual(JSON.parse(storage.getItem(SKIN_LAYOUT_STORAGE_KEY) ?? "null").schemaVersion, 2); + assert.equal(storage.getItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY), legacy, "the source config remains intact as a backup"); + + const recovery = getSkinLayoutMigrationRecovery("community.illusia-voice"); + assert.equal(recovery?.sourceVersion, 1); + assert.equal(recovery?.items.length, 3); + assert.equal(recovery?.omittedCount, 0); + const exported = JSON.parse(exportSkinLayoutMigrationRecovery("community.illusia-voice")); + assert.equal(exported.skinId, "community.illusia-voice"); + assert.equal(exported.items.length, 3); + }); +}); + +test("version 2 layout overrides can be saved, loaded, and cleared per skin", () => { + withLocalStorage((storage) => { + saveSkinLayoutOverrides("community.illusia-voice", { + schemaVersion: 1, + pages: { home: { mobile: { "home.header": { x: 8, visible: true } } } }, + }); + assert.equal(loadSkinLayoutOverrides("community.illusia-voice").pages.home?.mobile?.["home.header"]?.x, 8); + clearSkinLayoutOverrides("community.illusia-voice"); + assert.deepEqual(loadSkinLayoutOverrides("community.illusia-voice"), { schemaVersion: 1, pages: {} }); + assert.equal(JSON.parse(storage.getItem(SKIN_LAYOUT_STORAGE_KEY) ?? "null").schemaVersion, 2); + }); +}); + +test("an unknown newer local storage version is preserved instead of overwritten", () => { + withLocalStorage((storage) => { + const future = JSON.stringify({ schemaVersion: 99, skins: { "community.illusia-voice": { retained: true } } }); + storage.setItem(SKIN_LAYOUT_STORAGE_KEY, future); + assert.throws(() => saveSkinLayoutOverrides("community.illusia-voice", { schemaVersion: 1, pages: {} })); + assert.equal(storage.getItem(SKIN_LAYOUT_STORAGE_KEY), future); + }); +}); diff --git a/web/src/services/skin-layout-storage.ts b/web/src/services/skin-layout-storage.ts new file mode 100644 index 0000000..45c5867 --- /dev/null +++ b/web/src/services/skin-layout-storage.ts @@ -0,0 +1,266 @@ +import { + getSkinLayoutComponent, + parseSkinLayoutJson, + validateSkinLayout, + type SkinLayoutDocument, + type SkinLayoutPage, + type SkinLayoutPlacement, + type SkinLayoutProfile, +} from "../../../src/shared/skin-layout.js"; + +export const SKIN_LAYOUT_STORAGE_KEY = "webspeak:skin-layouts:v2"; +export const LEGACY_SKIN_LAYOUT_STORAGE_KEY = "webspeak:skin-layouts:v1"; +const MAX_STORAGE_BYTES = 1024 * 1024; +const MAX_RECOVERY_BYTES = 128 * 1024; + +interface SkinLayoutCollection { + schemaVersion: 2; + skins: Record; + recoveries: Record; +} + +export interface SkinLayoutMigrationRecovery { + sourceVersion: number; + items: Array<{ page: string; profile: string; componentId: string; placement: unknown }>; + omittedCount: number; + backupKey: string; +} + +interface StorageLike { + getItem(key: string): string | null; + setItem(key: string, value: string): void; +} + +function emptyDocument(): SkinLayoutDocument { + return { schemaVersion: 1, pages: {} }; +} + +function emptyCollection(): SkinLayoutCollection { + return { schemaVersion: 2, skins: {}, recoveries: {} }; +} + +function isSkinId(value: string): boolean { + return value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value); +} + +function getBrowserStorage(): StorageLike | null { + try { + return typeof localStorage === "undefined" ? null : localStorage; + } catch { + return null; + } +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function serializedBytes(value: unknown): number { + return new TextEncoder().encode(JSON.stringify(value)).byteLength; +} + +function parseCollection(source: string | null): SkinLayoutCollection { + if (!source) return emptyCollection(); + if (new TextEncoder().encode(source).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit."); + let raw: unknown; + try { raw = JSON.parse(source); } + catch { throw new Error("Saved skin layouts are not valid JSON."); } + if (!isRecord(raw) || raw.schemaVersion !== 2 || !isRecord(raw.skins) || !isRecord(raw.recoveries)) { + throw new Error("Saved skin layouts use an unsupported storage version."); + } + const skins: Record = {}; + for (const [id, layout] of Object.entries(raw.skins)) { + if (!isSkinId(id)) throw new Error("Saved skin layouts contain an invalid skin ID."); + skins[id] = validateSkinLayout(layout); + } + const recoveries: Record = {}; + for (const [id, recovery] of Object.entries(raw.recoveries)) { + if (!isSkinId(id) || !isRecord(recovery) || !Array.isArray(recovery.items) + || typeof recovery.sourceVersion !== "number" || !Number.isInteger(recovery.sourceVersion) + || typeof recovery.omittedCount !== "number" || !Number.isInteger(recovery.omittedCount) + || recovery.items.length > 1024) throw new Error("Saved skin layout recovery data is invalid."); + recoveries[id] = { + sourceVersion: recovery.sourceVersion, + items: recovery.items.filter(isRecord).map((item) => ({ + page: typeof item.page === "string" ? item.page.slice(0, 80) : "", + profile: typeof item.profile === "string" ? item.profile.slice(0, 20) : "", + componentId: typeof item.componentId === "string" ? item.componentId.slice(0, 120) : "", + placement: item.placement, + })), + omittedCount: Math.max(0, recovery.omittedCount), + backupKey: LEGACY_SKIN_LAYOUT_STORAGE_KEY, + }; + } + return { schemaVersion: 2, skins, recoveries }; +} + +function recoverLegacyLayout(layout: unknown): { layout: SkinLayoutDocument; items: SkinLayoutMigrationRecovery["items"] } { + const items: SkinLayoutMigrationRecovery["items"] = []; + const pages: SkinLayoutDocument["pages"] = {}; + const remember = (page: string, profile: string, componentId: string, placement: unknown) => { + if (items.length < 1024) items.push({ page: page.slice(0, 80), profile: profile.slice(0, 20), componentId: componentId.slice(0, 120), placement }); + }; + if (!isRecord(layout) || layout.schemaVersion !== 1 || !isRecord(layout.pages)) { + remember("", "", "__document__", layout); + return { layout: emptyDocument(), items }; + } + for (const [pageKey, rawPage] of Object.entries(layout.pages)) { + if (!(pageKey === "home" || pageKey === "voice" || pageKey === "demo") || !isRecord(rawPage)) { + remember(pageKey, "", "__page__", rawPage); + continue; + } + const profiles: NonNullable = {}; + for (const [profileKey, rawProfile] of Object.entries(rawPage)) { + if (!(profileKey === "desktop" || profileKey === "tablet" || profileKey === "mobile") || !isRecord(rawProfile)) { + remember(pageKey, profileKey, "__profile__", rawProfile); + continue; + } + const placements: Record = {}; + for (const [id, placement] of Object.entries(rawProfile)) { + const component = getSkinLayoutComponent(id, pageKey); + try { + if (!component?.editable) throw new Error("Component no longer exists or is not editable."); + const verified = validateSkinLayout({ schemaVersion: 1, pages: { [pageKey]: { [profileKey]: { [id]: placement } } } }); + const normalized = verified.pages[pageKey]?.[profileKey]?.[id]; + if (!normalized) throw new Error("Placement could not be migrated."); + placements[id] = normalized; + } catch { + remember(pageKey, profileKey, id, placement); + } + } + if (Object.keys(placements).length) profiles[profileKey] = placements; + } + if (Object.keys(profiles).length) pages[pageKey] = profiles; + } + return { layout: validateSkinLayout({ schemaVersion: 1, pages }), items }; +} + +function migrateLegacyCollection(source: string): SkinLayoutCollection { + if (new TextEncoder().encode(source).byteLength > MAX_STORAGE_BYTES) throw new Error("Legacy skin layouts exceed the local storage limit."); + let raw: unknown; + try { raw = JSON.parse(source); } + catch { throw new Error("Legacy skin layouts are not valid JSON."); } + if (!isRecord(raw) || raw.schemaVersion !== 1 || !isRecord(raw.skins)) { + throw new Error("Legacy skin layouts use an unsupported storage version."); + } + const collection = emptyCollection(); + for (const [id, storedLayout] of Object.entries(raw.skins)) { + if (!isSkinId(id)) continue; + const recovered = recoverLegacyLayout(storedLayout); + collection.skins[id] = recovered.layout; + if (recovered.items.length) { + const recovery: SkinLayoutMigrationRecovery = { + sourceVersion: 1, + items: [], + omittedCount: recovered.items.length, + backupKey: LEGACY_SKIN_LAYOUT_STORAGE_KEY, + }; + for (const item of recovered.items) { + recovery.items.push(item); + recovery.omittedCount -= 1; + if (serializedBytes(recovery) > MAX_RECOVERY_BYTES) { + recovery.items.pop(); + recovery.omittedCount += 1; + break; + } + } + collection.recoveries[id] = recovery; + } + } + return collection; +} + +function readCollection(storage: StorageLike): SkinLayoutCollection { + const current = storage.getItem(SKIN_LAYOUT_STORAGE_KEY); + if (current !== null) return parseCollection(current); + const legacy = storage.getItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY); + if (legacy === null) return emptyCollection(); + const migrated = migrateLegacyCollection(legacy); + try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, JSON.stringify(migrated)); } + catch { /* Keep the legacy key untouched and allow this page to use the migrated copy in memory. */ } + return migrated; +} + +export function loadSkinLayoutOverrides(skinId: string): SkinLayoutDocument { + if (!isSkinId(skinId)) return emptyDocument(); + const storage = getBrowserStorage(); + if (!storage) return emptyDocument(); + try { return readCollection(storage).skins[skinId] ?? emptyDocument(); } + catch { return emptyDocument(); } +} + +export function getSkinLayoutMigrationRecovery(skinId: string): SkinLayoutMigrationRecovery | null { + if (!isSkinId(skinId)) return null; + const storage = getBrowserStorage(); + if (!storage) return null; + try { return readCollection(storage).recoveries[skinId] ?? null; } + catch { return null; } +} + +export function exportSkinLayoutMigrationRecovery(skinId: string): string { + const recovery = getSkinLayoutMigrationRecovery(skinId); + if (!recovery) throw new Error("There is no recovered legacy layout data."); + return JSON.stringify({ schemaVersion: 1, skinId, ...recovery }, null, 2); +} + +export function saveSkinLayoutOverrides(skinId: string, layout: SkinLayoutDocument): void { + if (!isSkinId(skinId)) throw new Error("Skin ID is invalid."); + const validated = validateSkinLayout(layout); + const storage = getBrowserStorage(); + if (!storage) throw new Error("Local browser storage is unavailable."); + let collection: SkinLayoutCollection; + try { collection = readCollection(storage); } + catch { throw new Error("Local browser storage could not be read."); } + collection.skins[skinId] = validated; + const serialized = JSON.stringify(collection); + if (new TextEncoder().encode(serialized).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit."); + try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, serialized); } + catch { throw new Error("Local browser storage could not be written."); } +} + +export function updateSkinLayoutOverride( + skinId: string, + page: SkinLayoutPage, + profile: SkinLayoutProfile, + componentId: string, + placement: SkinLayoutPlacement | null, +): SkinLayoutDocument { + const component = getSkinLayoutComponent(componentId, page); + if (!component?.editable) throw new Error("This skin component cannot be customized."); + const layout = loadSkinLayoutOverrides(skinId); + const pages = { ...layout.pages }; + const pageLayout = { ...(pages[page] ?? {}) }; + const profileLayout = { ...(pageLayout[profile] ?? {}) }; + if (placement === null || Object.keys(placement).length === 0) delete profileLayout[componentId]; + else profileLayout[componentId] = placement; + if (Object.keys(profileLayout).length) pageLayout[profile] = profileLayout; + else delete pageLayout[profile]; + if (Object.keys(pageLayout).length) pages[page] = pageLayout; + else delete pages[page]; + const validated = validateSkinLayout({ schemaVersion: 1, pages }); + saveSkinLayoutOverrides(skinId, validated); + return validated; +} + +export function clearSkinLayoutOverrides(skinId: string): void { + if (!isSkinId(skinId)) return; + const storage = getBrowserStorage(); + if (!storage) throw new Error("Local browser storage is unavailable."); + let collection: SkinLayoutCollection; + try { collection = readCollection(storage); } + catch { throw new Error("Local browser storage could not be read."); } + delete collection.skins[skinId]; + delete collection.recoveries[skinId]; + const serialized = JSON.stringify(collection); + if (new TextEncoder().encode(serialized).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit."); + try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, serialized); } + catch { throw new Error("Local browser storage could not be written."); } +} + +export function exportSkinLayout(layout: SkinLayoutDocument): string { + return JSON.stringify(validateSkinLayout(layout), null, 2); +} + +export function importSkinLayout(source: string): SkinLayoutDocument { + return parseSkinLayoutJson(source); +} diff --git a/web/src/services/skin-pack.test.ts b/web/src/services/skin-pack.test.ts index 6932442..1b1e2f6 100644 --- a/web/src/services/skin-pack.test.ts +++ b/web/src/services/skin-pack.test.ts @@ -127,12 +127,18 @@ test("skin content supports localized interface message overrides and includes t assert.ok(skin.assets["assets/preview.png"]); }); -test("the ILLUSIA visual-only example imports without replacing WebSpeak's base translations", async () => { - const bytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url)); - const skin = await importSkinPack(new File([bytes], "illusia-voice.wskin", { type: "application/octet-stream" })); +test("the ILLUSIA v2 example and bundled package import without replacing WebSpeak's base translations", async () => { + const exampleBytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url)); + const bundledBytes = await readFile(new URL("../../public/skins/illusia-voice.wskin", import.meta.url)); + assert.deepEqual(bundledBytes, exampleBytes); + const skin = await importSkinPack(new File([exampleBytes], "illusia-voice.wskin", { type: "application/octet-stream" })); assert.equal(skin.id, "community.illusia-voice"); assert.equal(skin.name, "ILLUSIA风"); - assert.equal(skin.version, "1.0.28"); + assert.equal(skin.version, "1.0.29"); + assert.equal(skin.schemaVersion, 2); + assert.equal(skin.packageType, "layout-skin"); + assert.deepEqual(skin.permissions, []); + assert.deepEqual(skin.layoutData, { schemaVersion: 1, pages: {} }); assert.equal(skin.minAppVersion, "0.2.7-preview"); assert.equal(skin.contentData, undefined); assert.equal(skin.previewBlob?.type, "image/webp"); @@ -250,3 +256,52 @@ function makeSkin(css: string, content?: unknown): File { const bytes = zipSync(packageFiles); return new File([bytes.slice().buffer as ArrayBuffer], "skin.wskin", { type: "application/octet-stream" }); } + +test("schema version 2 skin packages load only validated declarative layouts with no permissions", async () => { + const layout = { + schemaVersion: 1, + pages: { + home: { desktop: { "home.header": { x: 48, y: -12, scale: 1.1, background: "#123456" } } }, + }, + }; + const skin = await importSkinPack(makeSkinV2(layout)); + assert.equal(skin.schemaVersion, 2); + assert.equal(skin.packageType, "layout-skin"); + assert.deepEqual(skin.permissions, []); + assert.equal(skin.layoutData?.pages.home?.desktop?.["home.header"]?.x, 48); + assert.equal(skin.layoutData?.pages.home?.desktop?.["home.header"]?.background, "#123456"); + + await assert.rejects( + importSkinPack(makeSkinV2(layout, { permissions: ["network.fetch"] })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PERMISSION_INVALID", + ); + await assert.rejects( + importSkinPack(makeSkinV2(layout, { capabilities: ["network.fetch"] })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_MANIFEST_INVALID", + ); + await assert.rejects( + importSkinPack(makeSkinV2({ schemaVersion: 1, pages: { home: { desktop: { "home.unknown": { x: 4 } } } } })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_LAYOUT_INVALID", + ); + await assert.rejects( + importSkinPack(makeSkinV2({ schemaVersion: 1, pages: { home: { desktop: { "home.security-note": { visible: false } } } } })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_LAYOUT_INVALID", + ); +}); + +function makeSkinV2(layout: unknown, manifestChanges: Record = {}): File { + const packageFiles: Record = { + "manifest.json": strToU8(JSON.stringify({ + ...manifest, + schemaVersion: 2, + packageType: "layout-skin", + layout: "layout.json", + permissions: [], + ...manifestChanges, + })), + "skin.css": strToU8('[data-ws-part="home.header"] { color: #123456; }'), + "layout.json": strToU8(JSON.stringify(layout)), + }; + const bytes = zipSync(packageFiles); + return new File([bytes.slice().buffer as ArrayBuffer], "skin-v2.wskin", { type: "application/octet-stream" }); +} diff --git a/web/src/services/skin-pack.ts b/web/src/services/skin-pack.ts index 93ca9ed..3d4a669 100644 --- a/web/src/services/skin-pack.ts +++ b/web/src/services/skin-pack.ts @@ -2,6 +2,7 @@ import postcss, { type AtRule, type Declaration, type Node, type Rule } from "po import selectorParser from "postcss-selector-parser"; import valueParser from "postcss-value-parser"; import { unzipSync } from "fflate"; +import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js"; const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024; const MAX_EXPANDED_BYTES = 50 * 1024 * 1024; @@ -51,7 +52,8 @@ const ZIP_EOCD = 0x06054b50; const ZIP_CENTRAL_FILE = 0x02014b50; export interface SkinManifest { - schemaVersion: 1; + schemaVersion: 1 | 2; + packageType?: "layout-skin"; id: string; name: string; version: string; @@ -59,6 +61,8 @@ export interface SkinManifest { license: string; description?: string; entry: string; + layout?: string; + permissions?: []; content?: string; minAppVersion: string; preview?: string; @@ -89,6 +93,7 @@ export interface InstalledSkin extends SkinManifest { css: string; assets: Record; contentData?: SkinContent; + layoutData?: SkinLayoutDocument; previewBlob?: Blob; warnings: string[]; installedAt: number; @@ -148,7 +153,7 @@ export async function importSkinPack(file: File): Promise { const assets: Record = Object.create(null) as Record; for (const [path, bytes] of files) { - if (["manifest.json", manifest.entry, manifest.content].includes(path)) continue; + if (["manifest.json", manifest.entry, manifest.layout, manifest.content].includes(path)) continue; const mimeType = assetMimeType(path); if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED"); if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE"); @@ -163,6 +168,14 @@ export async function importSkinPack(file: File): Promise { contentData = parseContent(contentBytes); } + let layoutData: SkinLayoutDocument | undefined; + if (manifest.layout) { + const layoutBytes = files.get(manifest.layout); + if (!layoutBytes) throw new SkinPackError("layout.json is missing from the package.", "SKIN_LAYOUT_MISSING"); + try { layoutData = parseSkinLayoutJson(decoder.decode(layoutBytes)); } + catch (error) { throw new SkinPackError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); } + } + let previewBlob: Blob | undefined; if (manifest.preview) { const previewBytes = files.get(manifest.preview); @@ -174,7 +187,7 @@ export async function importSkinPack(file: File): Promise { } const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets); - return { ...manifest, css: compiled.css, assets, contentData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() }; + return { ...manifest, css: compiled.css, assets, contentData, layoutData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() }; } export function resolveSkinCssAssets(css: string, assets: Record): { css: string; objectUrls: string[] } { @@ -319,30 +332,44 @@ function parseManifest(bytes: Uint8Array): SkinManifest { catch { throw new SkinPackError("manifest.json must contain valid UTF-8 JSON.", "SKIN_MANIFEST_INVALID"); } if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID"); const raw = value as Record; + const schemaVersion = raw.schemaVersion; + if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion === 2) { + const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]); + const unknown = Object.keys(raw).find((key) => !fields.has(key)); + if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID"); + } const stringField = (key: string, max: number, required = true): string | undefined => { const field = raw[key]; if (field == null && !required) return undefined; if (typeof field !== "string" || !field.trim() || field.length > max) throw new SkinPackError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID"); return field.trim(); }; - if (raw.schemaVersion !== 1) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion === 2 && (raw.packageType !== "layout-skin" || !Array.isArray(raw.permissions) || raw.permissions.length !== 0)) { + throw new SkinPackError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID"); + } + if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined)) { + throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION"); + } const id = stringField("id", 80)!; if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID"); const entry = stringField("entry", 120)!; + const layout = schemaVersion === 2 ? stringField("layout", 120)! : undefined; const content = stringField("content", 120, false); const preview = stringField("preview", 120, false); - for (const path of [entry, content, preview].filter((item): item is string => Boolean(item))) { + for (const path of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) { if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID"); } const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; const version = stringField("version", 32)!; const minAppVersion = stringField("minAppVersion", 32)!; if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID"); - if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID"); - const declaredFiles = ["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); + if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID"); return { - schemaVersion: 1, + schemaVersion, + ...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : {}), id, name: stringField("name", 80)!, version, @@ -350,6 +377,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest { license: stringField("license", 80)!, description: stringField("description", 400, false), entry, + layout, content, minAppVersion, preview, diff --git a/web/src/services/skin-runtime.ts b/web/src/services/skin-runtime.ts index 0dff0a0..fb71a98 100644 --- a/web/src/services/skin-runtime.ts +++ b/web/src/services/skin-runtime.ts @@ -4,6 +4,7 @@ import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./th import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js"; import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js"; import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js"; +import { setSkinLayoutPackage } from "./skin-layout-runtime.js"; export const ACTIVE_SKIN_KEY = "webspeak:active-skin"; export const BUILTIN_LIGHT_SKIN = "builtin.light"; @@ -52,6 +53,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine operation.check(); if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) { removeCustomSkinStyle(); + setSkinLayoutPackage(id, null); applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light"); markCoreControls(); storeSkinId(id); @@ -120,6 +122,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine activeAssetUrls = compiled.objectUrls; candidateUrls = []; previousAssetUrls.forEach((url) => URL.revokeObjectURL(url)); + setSkinLayoutPackage(skin.id, skin.layoutData ?? null); storeSkinId(id); return skin; } catch { @@ -132,6 +135,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine function fallBackToBuiltin(): null { const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN; removeCustomSkinStyle(); + setSkinLayoutPackage(fallback, null); applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light"); storeSkinId(fallback); return null; @@ -141,6 +145,7 @@ export function clearCustomSkinStyle(): void { pendingActivation?.cancel(); pendingActivation = null; removeCustomSkinStyle(); + setSkinLayoutPackage(getStoredSkinId() ?? BUILTIN_LIGHT_SKIN, null); } function removeCustomSkinStyle(): void { diff --git a/web/src/services/skin-wasm-interpreter.test.ts b/web/src/services/skin-wasm-interpreter.test.ts new file mode 100644 index 0000000..aa90348 --- /dev/null +++ b/web/src/services/skin-wasm-interpreter.test.ts @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; +import { + createSkinExtensionWasmCappedRunProbe, + createSkinExtensionWasmInfiniteRunProbe, + createSkinExtensionWasmPrefixByteImmediateProbe, +} from "../../test/skin-extension-wasm-fixture.js"; + +interface WasmiInterpreterExports extends WebAssembly.Exports { + memory: WebAssembly.Memory; + alloc: (size: number) => number; + run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number, + statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint; + last_error_code: () => number; + last_guest_memory_bytes: () => number; +} + +test("the fixed Wasmi artifact caps its own memory and stops guest execution at fuel", async () => { + const artifact = await readFile(new URL("../../public/skin-wasm-interpreter.wasm", import.meta.url)); + const { instance } = await WebAssembly.instantiate(artifact); + const runtime = instance.exports as unknown as WasmiInterpreterExports; + + function run(module: Uint8Array): { result: number; error: number; guestMemoryBytes: number } { + const pointer = runtime.alloc(module.byteLength); + assert.notEqual(pointer, 0, "the bounded interpreter should accept the small fixture"); + new Uint8Array(runtime.memory.buffer, pointer, module.byteLength).set(module); + const result = runtime.run(pointer, module.byteLength, 0, 0, 0, 64, 10_000_000n); + return { + result: Number(result), + error: runtime.last_error_code(), + guestMemoryBytes: runtime.last_guest_memory_bytes(), + }; + } + + assert.deepEqual(run(createSkinExtensionWasmPrefixByteImmediateProbe()), { + result: 123, + error: 0, + guestMemoryBytes: 64 * 1024, + }); + assert.equal(run(createSkinExtensionWasmInfiniteRunProbe()).error, 5, "the fuel budget must trap a non-returning module"); + assert.deepEqual(run(createSkinExtensionWasmCappedRunProbe()), { + result: -1, + error: 0, + guestMemoryBytes: 4 * 1024 * 1024, + }); + + const memory = runtime.memory; + const currentPages = memory.buffer.byteLength / (64 * 1024); + memory.grow(1024 - currentPages); + assert.equal(memory.buffer.byteLength, 64 * 1024 * 1024, "the interpreter container should reach its 64 MiB cap"); + assert.throws(() => memory.grow(1), RangeError, "the interpreter container must not grow beyond its cap"); +}); diff --git a/web/src/services/theme.ts b/web/src/services/theme.ts index 2b0135b..72afe01 100644 --- a/web/src/services/theme.ts +++ b/web/src/services/theme.ts @@ -65,9 +65,9 @@ export function applyTheme(theme: ThemeMode, options: { preserveCustomSkins?: bo style.textContent = activeSkin.css; } -export function saveTheme(theme: ThemeMode): void { +export function saveTheme(theme: ThemeMode, options: { preserveCustomSkins?: boolean } = {}): void { if (typeof localStorage !== "undefined") localStorage.setItem(THEME_KEY, theme); - applyTheme(theme); + applyTheme(theme, options); } export function isDarkTheme(theme: ThemeMode): boolean { diff --git a/web/src/skins/layout-runtime.css b/web/src/skins/layout-runtime.css new file mode 100644 index 0000000..48d4731 --- /dev/null +++ b/web/src/skins/layout-runtime.css @@ -0,0 +1,44 @@ +.ws-skin-root[data-ws-layout-hidden="true"], +.ws-skin-root [data-ws-layout-hidden="true"] { + display: none !important; +} + +.ws-skin-root [data-ws-layout-active="true"] { + translate: var(--ws-layout-x, 0px) var(--ws-layout-y, 0px) !important; + scale: var(--ws-layout-scale, 1) !important; +} + +.ws-skin-root [data-ws-layout-width="true"] { + width: var(--ws-layout-width) !important; +} + +.ws-skin-root [data-ws-layout-height="true"] { + height: var(--ws-layout-height) !important; +} + +.ws-skin-root [data-ws-layout-touch-target="44"] { + min-width: 44px !important; + min-height: 44px !important; +} + +.ws-skin-root [data-ws-layout-foreground="true"] { + color: var(--ws-layout-foreground) !important; +} + +.ws-skin-root [data-ws-layout-background="true"] { + background-color: var(--ws-layout-background) !important; +} + +.ws-skin-root [data-ws-layout-border="true"] { + border-color: var(--ws-layout-border) !important; +} + +.ws-skin-root [data-ws-layout-radius="true"] { + border-radius: var(--ws-layout-radius) !important; +} + +.ws-skin-root[data-ws-layout-editing="true"] [data-ws-layout-selected="true"] { + outline: 2px solid #4f46e5 !important; + outline-offset: 2px !important; + cursor: move !important; +} diff --git a/web/src/views/DemoView.vue b/web/src/views/DemoView.vue index a52c765..07e7e5e 100644 --- a/web/src/views/DemoView.vue +++ b/web/src/views/DemoView.vue @@ -1,5 +1,5 @@ + + diff --git a/web/test/skin-extension-sandbox.harness.ts b/web/test/skin-extension-sandbox.harness.ts new file mode 100644 index 0000000..922dc34 --- /dev/null +++ b/web/test/skin-extension-sandbox.harness.ts @@ -0,0 +1,511 @@ +import { + createSkinExtensionApproval, + parseSkinExtensionManifest, + type SkinExtensionSessionStatus, +} from "../../src/shared/skin-extension.js"; +import { + createSkinExtensionSandboxPrototype, + SKIN_EXTENSION_RUNTIME_ENABLED, + type SkinExtensionSandboxHandle, +} from "../src/services/skin-extension-sandbox.js"; +import { + createSkinExtensionWasmSandboxPrototype, + SKIN_EXTENSION_WASM_RUNTIME_ENABLED, + type SkinExtensionWasmSandboxHandle, +} from "../src/services/skin-extension-wasm-sandbox.js"; +import { + createSkinExtensionWasmCappedRunProbe, + createSkinExtensionWasmInfiniteStartProbe, + createSkinExtensionWasmInfiniteRunProbe, + createSkinExtensionWasmStatusMutationProbe, + createSkinExtensionWasmStatusProbe, + createSkinExtensionWasmGcAllocationProbe, + createSkinExtensionWasmOversizedFunctionBodyProbe, + createSkinExtensionWasmOversizedElementVectorProbe, + createSkinExtensionWasmOversizedLocalProbe, + createSkinExtensionWasmOversizedSignatureProbe, + createSkinExtensionWasmPrefixByteImmediateProbe, + createSkinExtensionWasmTooManyFunctionsProbe, +} from "./skin-extension-wasm-fixture.js"; + +const results = document.querySelector("#results")!; +const host = document.querySelector("#sandbox-host")!; +const bufferedMessages = new WeakMap>(); +const messageWaiters = new WeakMap void>>(); + +window.addEventListener("message", (event) => { + if (event.origin !== "null" || !event.source || !event.data || typeof event.data !== "object") return; + const source = event.source as object; + const key = (event.data as Record).__skinHarness; + if (typeof key !== "string") return; + const waiter = messageWaiters.get(source)?.get(key); + if (waiter) { + messageWaiters.get(source)?.delete(key); + waiter(event.data); + return; + } + const buffered = bufferedMessages.get(source) ?? new Map(); + buffered.set(key, event.data); + bufferedMessages.set(source, buffered); +}); + +function extension( + permissions: string[], + source: string, + container: HTMLElement = host, + readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise = () => ({ connected: true, channelName: "Quiet Zone", memberCount: 2 }), +) { + const manifest = parseSkinExtensionManifest({ + schemaVersion: 1, + packageType: "extension", + id: "test.sandbox-check", + name: "Sandbox check", + version: "1.0.0", + apiVersion: 1, + permissions, + }); + let statusReads = 0; + const sandbox = createSkinExtensionSandboxPrototype({ + container, + manifest, + approval: createSkinExtensionApproval(manifest), + source, + readSessionStatus: (signal) => { + statusReads += 1; + return readSessionStatus(signal); + }, + prototypeOnly: true, + }); + return { sandbox, get statusReads() { return statusReads; } }; +} + +function wasmExtension( + wasmBytes: Uint8Array, + permissions: string[] = [], + readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise = () => ({ connected: true, channelName: "Quiet Zone", memberCount: 2 }), +) { + const manifest = parseSkinExtensionManifest({ + schemaVersion: 1, + packageType: "extension", + id: "test.wasm-check", + name: "Wasm check", + version: "1.0.0", + apiVersion: 1, + permissions, + }); + let statusReads = 0; + const sandbox = createSkinExtensionWasmSandboxPrototype({ + manifest, + approval: createSkinExtensionApproval(manifest), + wasmBytes, + readSessionStatus: (signal) => { + statusReads += 1; + return readSessionStatus(signal); + }, + prototypeOnly: true, + }); + return { sandbox, get statusReads() { return statusReads; } }; +} + +function waitForSourceMessage(source: object, key: string, timeoutMs = 1500): Promise { + const buffered = bufferedMessages.get(source)?.get(key); + if (buffered !== undefined) { + bufferedMessages.get(source)?.delete(key); + return Promise.resolve(buffered); + } + return new Promise((resolve, reject) => { + const waiters = messageWaiters.get(source) ?? new Map void>(); + const timer = window.setTimeout(() => { + waiters.delete(key); + reject(new Error(`Timed out waiting for ${key}.`)); + }, timeoutMs); + waiters.set(key, (value) => { + window.clearTimeout(timer); + resolve(value); + }); + messageWaiters.set(source, waiters); + }); +} + +function waitForWindowMessage(predicate: (event: MessageEvent) => boolean, timeoutMs = 1500): Promise { + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + window.removeEventListener("message", onMessage); + reject(new Error("Timed out waiting for the window message.")); + }, timeoutMs); + const onMessage = (event: MessageEvent) => { + if (!predicate(event)) return; + window.clearTimeout(timer); + window.removeEventListener("message", onMessage); + resolve(event); + }; + window.addEventListener("message", onMessage); + }); +} + +function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise { + return new Promise((resolve, reject) => { + const started = performance.now(); + const check = () => { + if (predicate()) resolve(); + else if (performance.now() - started >= timeoutMs) reject(new Error("Timed out waiting for the sandbox state.")); + else window.setTimeout(check, 20); + }; + check(); + }); +} + +function assert(condition: unknown, message: string): asserts condition { + if (!condition) throw new Error(message); +} + +function equal(actual: unknown, expected: unknown, message: string): void { + assert(Object.is(actual, expected), `${message} (expected ${String(expected)}, got ${String(actual)})`); +} + +function throws(operation: () => unknown, code: string, message: string): void { + let error: unknown; + try { operation(); } catch (reason) { error = reason; } + assert(error !== undefined && typeof error === "object" && "code" in error && error.code === code, message); +} + +function deepEqual(actual: unknown, expected: unknown, message: string): void { + assert(JSON.stringify(actual) === JSON.stringify(expected), message); +} + +async function rejects(promise: Promise, code: string, message: string): Promise { + const error = await promise.then(() => null, (reason: unknown) => reason); + assert(error !== null && typeof error === "object" && "code" in error && error.code === code, message); +} + +async function test(name: string, run: () => Promise): Promise { + const item = document.createElement("li"); + try { + await run(); + item.className = "pass"; + item.textContent = `PASS — ${name}`; + } catch (error) { + item.className = "fail"; + const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? ` [${error.code}]` : ""; + item.textContent = `FAIL — ${name}${code}: ${error instanceof Error ? error.message : String(error)}`; + } + results.append(item); +} + +async function closeSandbox(sandbox: SkinExtensionSandboxHandle): Promise { + sandbox.close("harness-complete"); + await sandbox.stopped; +} + +async function waitForReady(sandbox: SkinExtensionSandboxHandle): Promise { + try { await sandbox.ready; } + catch (error) { + throw new Error(`${error instanceof Error ? error.message : String(error)} (reason: ${sandbox.closeReason ?? "unknown"})`); + } +} + +await test("production extension runtime remains disabled", async () => { + assert(SKIN_EXTENSION_RUNTIME_ENABLED === false, "Executable extensions must remain disabled."); + assert(SKIN_EXTENSION_WASM_RUNTIME_ENABLED === false, "The Wasm prototype must remain disabled in production."); +}); + +await test("a data worker inherits network CSP and can be terminated while its owner stays responsive", async () => { + await fetch("http://127.0.0.1:5176/reset"); + const frame = document.createElement("iframe"); + frame.setAttribute("sandbox", "allow-scripts"); + frame.srcdoc = ` + `; + document.body.append(rogue); + + try { + const event = await observed; + assert(event.ports.length === 1, "The spoof did not include the transferable port it was trying to claim."); + assert(!sandbox.closed, "A wrong-source hello closed the legitimate extension runtime."); + host.append(staging); + await waitForReady(sandbox); + await waitFor(() => instance.statusReads === 1); + assert(!sandbox.closed && instance.statusReads === 1, "The legitimate iframe could not complete the handshake after the spoof attempt."); + await closeSandbox(sandbox); + } finally { + rogue.remove(); + staging.remove(); + if (!sandbox.closed) await closeSandbox(sandbox); + } +}); + +await test("undeclared capabilities are denied without reaching the host provider", async () => { + const instance = extension([], ` + await globalThis.WebSpeakExtension.request("session.status.read").catch(() => {}); + `); + const { sandbox } = instance; + await waitForReady(sandbox); + await waitFor(() => sandbox.rejectedRequests === 1); + assert(instance.statusReads === 0, "The unapproved capability reached the host provider."); + await closeSandbox(sandbox); +}); + +await test("revoking an approved capability terminates the worker and closes the channel", async () => { + const instance = extension(["session.status.read"], ` + setInterval(() => globalThis.WebSpeakExtension.request("session.status.read").catch(() => {}), 100); + `); + const { sandbox } = instance; + await waitForReady(sandbox); + await waitFor(() => instance.statusReads > 0); + sandbox.revokePermission("session.status.read"); + await sandbox.stopped; + assert(sandbox.closed && !sandbox.frame.isConnected, "Revocation did not remove the running frame."); + assert(sandbox.closeReason === "permission-revoked:session.status.read", "Revocation did not record the reason."); + const statusReadsAtRevoke = instance.statusReads; + await new Promise((resolve) => window.setTimeout(resolve, 250)); + assert(instance.statusReads === statusReadsAtRevoke, "Host calls continued after permission revocation."); +}); + +await test("revoking an approved capability aborts pending host status work", async () => { + const provider = { signal: null as AbortSignal | null }; + const pendingStatus = (signal: AbortSignal) => new Promise((_resolve, reject) => { + provider.signal = signal; + signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true }); + }); + const instance = extension(["session.status.read"], ` + await globalThis.WebSpeakExtension.request("session.status.read").catch(() => {}); + `, host, pendingStatus); + const { sandbox } = instance; + try { + await waitForReady(sandbox); + await waitFor(() => provider.signal !== null); + sandbox.revokePermission("session.status.read"); + await sandbox.stopped; + assert(provider.signal?.aborted === true, "revocation did not abort the pending host data provider"); + assert(sandbox.closeReason === "permission-revoked:session.status.read", "revocation should stop the pending host request"); + } finally { + if (!sandbox.closed) await closeSandbox(sandbox); + } +}); + +await test("a burst of API calls terminates the extension", async () => { + const instance = extension(["session.status.read"], ` + for (let index = 0; index < 20; index += 1) { + globalThis.WebSpeakExtension.request("session.status.read").catch(() => {}); + } + `); + const { sandbox } = instance; + await waitForReady(sandbox); + await waitFor(() => sandbox.closed); + await sandbox.stopped; + assert(sandbox.closeReason === "message-rate-exceeded", "The rate limiter did not terminate a flooding extension."); +}); + +await test("the host can terminate a worker stuck in an infinite loop", async () => { + const instance = extension(["session.status.read"], ` + void globalThis.WebSpeakExtension.request("session.status.read").catch(() => {}); + while (true) {} + `); + const { sandbox } = instance; + await waitForReady(sandbox); + await waitFor(() => instance.statusReads === 1); + sandbox.close("cpu-abuse-probe"); + await sandbox.stopped; + assert(sandbox.closed && !sandbox.frame.isConnected, "The host could not stop the busy worker and remove its shell."); +}); diff --git a/web/test/skin-extension-wasm-fixture.ts b/web/test/skin-extension-wasm-fixture.ts new file mode 100644 index 0000000..449ea22 --- /dev/null +++ b/web/test/skin-extension-wasm-fixture.ts @@ -0,0 +1,148 @@ +function section(id: number, payload: number[]): number[] { + return [id, ...unsignedLeb128(payload.length), ...payload]; +} + +function unsignedLeb128(value: number): number[] { + const bytes: number[] = []; + do { + let byte = value & 0x7f; + value >>>= 7; + if (value) byte |= 0x80; + bytes.push(byte); + } while (value); + return bytes; +} + +function name(value: string): number[] { + const bytes = Array.from(value, (character) => character.charCodeAt(0)); + return [bytes.length, ...bytes]; +} + +function singleRunModule(body: number[], withStatusImport = false): Uint8Array { + const functionTypes = withStatusImport + ? [2, 0x60, 2, 0x7f, 0x7f, 1, 0x7f, 0x60, 0, 1, 0x7f] + : [1, 0x60, 0, 1, 0x7f]; + const imports = [ + 1 + Number(withStatusImport), + ...name("env"), ...name("memory"), 0x02, 0x01, 1, 64, + ...(withStatusImport ? [...name("env"), ...name("session_status_read"), 0x00, 0] : []), + ]; + const runType = withStatusImport ? 1 : 0; + const runFunctionIndex = withStatusImport ? 1 : 0; + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, functionTypes), + ...section(2, imports), + ...section(3, [1, runType]), + ...section(7, [1, ...name("run"), 0, runFunctionIndex]), + ...section(10, [1, body.length, ...body]), + ]); +} + +/** Grows the host-provided memory to 64 pages, then proves the next page is denied. */ +export function createSkinExtensionWasmCappedRunProbe(): Uint8Array { + return singleRunModule([0, 0x41, 0x3f, 0x40, 0x00, 0x1a, 0x41, 0x01, 0x40, 0x00, 0x0b]); +} + +/** Reads the permission-gated status snapshot into bounded linear memory and returns its byte length. */ +export function createSkinExtensionWasmStatusProbe(): Uint8Array { + return singleRunModule([0, 0x41, 0x00, 0x41, 0x80, 0x02, 0x10, 0x00, 0x0b], true); +} + +/** 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, + 0x21, 0x00, 0x41, 0x00, 0x41, 0x00, 0x3a, 0x00, 0x00, 0x20, 0x00, 0x0b], true); +} + +/** Runs forever after the trusted worker has announced that execution began. */ +export function createSkinExtensionWasmInfiniteRunProbe(): Uint8Array { + // Mark the path after the endless loop unreachable so the i32-returning + // function remains valid without adding a reachable fallthrough value. + return singleRunModule([0, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x00, 0x0b]); +} + +/** Hangs inside the Wasm start section, before the worker can announce run readiness. */ +export function createSkinExtensionWasmInfiniteStartProbe(): Uint8Array { + const runBody = [0, 0x41, 0x00, 0x0b]; + const startBody = [0, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x0b]; + const imports = [1, ...name("env"), ...name("memory"), 0x02, 0x01, 1, 64]; + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, [2, 0x60, 0, 1, 0x7f, 0x60, 0, 0]), + ...section(2, imports), + ...section(3, [2, 0, 1]), + ...section(7, [1, ...name("run"), 0, 0]), + ...section(8, [1]), + ...section(10, [2, runBody.length, ...runBody, startBody.length, ...startBody]), + ]); +} + +/** Imports only env.memory; the exports fill the cap, exceed it, and spin forever. */ +export function createSkinExtensionWasmResourceProbe(): Uint8Array { + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, [2, 0x60, 0, 1, 0x7f, 0x60, 0, 0]), + ...section(2, [1, ...name("env"), ...name("memory"), 0x02, 0x01, 1, 64]), + ...section(3, [3, 0, 0, 1]), + ...section(7, [3, ...name("fill"), 0, 0, ...name("grow"), 0, 1, ...name("spin"), 0, 2]), + ...section(10, [3, 6, 0, 0x41, 0x3f, 0x40, 0, 0x0b, 7, 0, 0x41, 0xc0, 0, 0x40, 0, 0x0b, 7, 0, 0x03, 0x40, 0x0c, 0, 0x0b, 0x0b]), + ]); +} + +/** A valid-looking module that defines its own unbounded linear memory. */ +export function createSkinExtensionWasmInternalMemoryProbe(): Uint8Array { + return Uint8Array.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, ...section(5, [1, 0, 1])]); +} + +export function createSkinExtensionWasmInternalTableProbe(): Uint8Array { + return Uint8Array.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, ...section(4, [1, 0x70, 0, 0])]); +} + +export function createSkinExtensionWasmTooManyFunctionsProbe(): Uint8Array { + return Uint8Array.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, ...section(3, [0x81, 0x01])]); +} + +export function createSkinExtensionWasmOversizedFunctionBodyProbe(): Uint8Array { + const body = new Array(32 * 1024 + 1).fill(0); + return Uint8Array.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, ...section(10, [1, ...unsignedLeb128(body.length), ...body])]); +} + +/** A valid Wasm GC module whose struct allocation is outside the linear-memory cap. */ +export function createSkinExtensionWasmGcAllocationProbe(): Uint8Array { + const imports = [1, ...name("env"), ...name("memory"), 0x02, 0x01, 1, 64]; + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, [2, 0x5f, 0, 0x60, 0, 0]), // empty struct type, then () -> () + ...section(2, imports), + ...section(3, [1, 1]), + ...section(7, [1, ...name("run"), 0, 0]), + ...section(10, [1, 6, 0, 0xfb, 0, 0, 0x1a, 0x0b]), // struct.new 0; drop; end + ]); +} + +/** Encodes an impossible signature parameter count in a small binary. */ +export function createSkinExtensionWasmOversizedSignatureProbe(): Uint8Array { + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, [1, 0x60, ...unsignedLeb128(0x10000000), 0, 0]), + ]); +} + +/** Encodes an impossible local count that must be rejected before Wasm compilation. */ +export function createSkinExtensionWasmOversizedLocalProbe(): Uint8Array { + return singleRunModule([1, ...unsignedLeb128(0x10000000), 0x7f, 0x41, 0, 0x0b]); +} + +/** Encodes a huge passive element vector; element segments are unsupported because tables are disabled. */ +export function createSkinExtensionWasmOversizedElementVectorProbe(): Uint8Array { + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(9, [1, 3, 0, ...unsignedLeb128(0x10000000)]), + ]); +} + +/** A legal signed LEB immediate contains byte 0xfb and must not look like an instruction prefix. */ +export function createSkinExtensionWasmPrefixByteImmediateProbe(): Uint8Array { + return singleRunModule([0, 0x41, 0xfb, 0x00, 0x0b]); // i32.const 123 +} diff --git a/web/test/skin-layout-runtime.test.mjs b/web/test/skin-layout-runtime.test.mjs new file mode 100644 index 0000000..5d0591b --- /dev/null +++ b/web/test/skin-layout-runtime.test.mjs @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; +import { after, before, test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { createServer } from "vite"; + +let vite; +let runtime; +const savedGlobals = new Map(); + +function setGlobal(name, value) { + if (!savedGlobals.has(name)) savedGlobals.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + Object.defineProperty(globalThis, name, { configurable: true, writable: true, value }); +} + +class FakeElement { + dataset = {}; + style = { + values: new Map(), + setProperty(name, value) { this.values.set(name, value); }, + removeProperty(name) { this.values.delete(name); }, + }; + parentElement = null; + children = []; + + matches(selector) { return selector === "[data-ws-part]" && typeof this.dataset.wsPart === "string"; } + querySelectorAll(selector) { + if (selector !== "[data-ws-part]") return []; + return this.children.flatMap((child) => [child, ...child.querySelectorAll(selector)]); + } + contains(element) { return element === this || this.children.some((child) => child.contains(element)); } +} + +function append(parent, child) { + child.parentElement = parent; + parent.children.push(child); + return child; +} + +before(async () => { + vite = await createServer({ + configFile: false, + root: fileURLToPath(new URL("../", import.meta.url)), + server: { middlewareMode: true, hmr: false, ws: false, watch: null }, + optimizeDeps: { noDiscovery: true, include: [] }, + appType: "custom", + }); + runtime = await vite.ssrLoadModule("/src/services/skin-layout-runtime.ts"); +}); + +after(async () => { + await vite?.close(); + for (const [name, descriptor] of savedGlobals) { + if (descriptor) Object.defineProperty(globalThis, name, descriptor); + else Reflect.deleteProperty(globalThis, name); + } +}); + +test("registered interactive controls retain their minimum hit target without a layout override", () => { + const root = new FakeElement(); + root.dataset.wsPage = "home"; + root.dataset.wsSkin = "test.skin"; + const connect = append(root, new FakeElement()); + connect.dataset.wsPart = "home.connect"; + const trusted = append(root, new FakeElement()); + trusted.dataset.wsPart = "home.security-note"; + const trustedControl = append(trusted, new FakeElement()); + trustedControl.dataset.wsPart = "control"; + trustedControl.dataset.wsControlKind = "button"; + const unknown = append(root, new FakeElement()); + unknown.dataset.wsPart = "home.unknown"; + + setGlobal("document", { querySelectorAll: () => [root] }); + setGlobal("window", { matchMedia: () => ({ matches: false }) }); + runtime.refreshSkinLayout(); + + assert.equal(connect.dataset.wsLayoutTouchTarget, "44", "a visible registered control must retain its 44px hit area by default"); + assert.equal(connect.dataset.wsLayoutActive, undefined, "the default hit-area rule must not create a user layout override"); + assert.equal(trustedControl.dataset.wsLayoutTouchTarget, undefined, "trusted host UI must remain outside the editable layout runtime"); + assert.equal(unknown.dataset.wsLayoutTouchTarget, undefined, "unregistered markup must not inherit layout control styles"); +}); diff --git a/web/test/skin-lifecycle.test.mjs b/web/test/skin-lifecycle.test.mjs index 744a75b..d54cda8 100644 --- a/web/test/skin-lifecycle.test.mjs +++ b/web/test/skin-lifecycle.test.mjs @@ -212,6 +212,23 @@ test("reset prevents outstanding choices from restoring cleared state", async () assert.deepEqual(writes, []); }); +test("a failed skin choice falls back, exposes recovery, and remembers the built-in selection", async () => { + handler = async url => url === "/api/skins" + ? json({ skins: [{ ...skin("sample.a"), author: "test", license: "MIT" }] }) + : { ok: false, status: 503 }; + await catalog.listPublicSkins(); + const view = page(); + + await view.select("sample.a"); + assert.equal(view.activeSkinId.value, "builtin.light"); + assert.deepEqual(view.skinLoadError.value, { skinId: "sample.a" }); + + await view.switchToBuiltInAfterLoadError(); + assert.equal(view.skinLoadError.value, null); + assert.equal(storage.get("webspeak:skin-choice"), "builtin.light"); + assert.equal(runtime.getStoredSkinId(), "builtin.light"); +}); + test("an already aborted caller cannot cancel the next page's activation", async () => { const read = deferred(); globalThis.skinStorage.get = () => read.promise; const current = runtime.activateSkin("sample.b");