From f2e5695bb6ea199ca4d9285911b5e373cc8c6b1a Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:04:36 +0800 Subject: [PATCH] feat(skins): complete visual component CRUD authoring --- docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md | 13 +- docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md | 8 +- package-lock.json | 95 +++ package.json | 5 +- src/admin/skin-registry.test.ts | 60 +- src/admin/skin-registry.ts | 36 +- src/shared/skin-css.ts | 380 +++++++++ src/shared/skin-extension-ui.ts | 2 +- src/shared/skin-plugin-editor.ts | 20 +- src/shared/skin-plugin.test.ts | 8 + src/shared/skin-plugin.ts | 5 +- web/src/components/SkinLayoutEditor.vue | 47 +- web/src/components/SkinPluginEditor.vue | 202 +++-- web/src/components/SkinPluginOutlet.ts | 30 +- .../services/host-editor-top-layer.test.ts | 40 + web/src/services/host-editor-top-layer.ts | 15 + web/src/services/skin-extension-ui.test.ts | 6 + .../skin-extension-wasm-ui-loop.test.ts | 28 +- .../services/skin-extension-wasm-ui-loop.ts | 4 +- web/src/services/skin-pack.test.ts | 4 + web/src/services/skin-pack.ts | 352 +-------- .../services/skin-plugin-asset-urls.test.ts | 30 + web/src/services/skin-plugin-asset-urls.ts | 4 + .../services/skin-plugin-authoring.test.ts | 42 +- .../skin-runtime-plugin-wasm-governor.test.ts | 48 ++ .../services/skin-runtime-plugin-wasm.test.ts | 40 + .../services/skin-wasm-interpreter.test.ts | 8 + web/test/skin-extension-wasm-fixture.ts | 63 ++ web/test/skin-layout-runtime.test.mjs | 38 + web/test/skin-plugin-editor.test.mjs | 736 ++++++++++++++++-- 30 files changed, 1858 insertions(+), 511 deletions(-) create mode 100644 src/shared/skin-css.ts create mode 100644 web/src/services/host-editor-top-layer.test.ts create mode 100644 web/src/services/host-editor-top-layer.ts diff --git a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md index ea0a5d1..4cf4d5d 100644 --- a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md @@ -138,12 +138,17 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 - 当前已接入本地组件编辑器首批能力:新建/复制/删除/排序组件,选中组件树节点,添加/复制/删除/排序节点,编辑完整组件或节点 JSON,撤销/重做,以及按皮肤 ID 和版本本地保存、导入导出 components.json。没有组件文件的皮肤也可以从空 schema v3 文档开始;复制节点时会重新生成稳定布局标识,避免两个节点共用同一编辑目标。 - 编辑器导入、每次保存和运行时渲染统一复用 components.json schema 校验。危险标签/属性、未注册数据路径、未声明权限、越权动作、重复状态型宿主控件、超深或超大的树都必须拒绝;本地编辑不能赋予包外权限,也不能访问管理员页面、服务器地址、口令或身份材料。 - 存储现按皮肤 ID 和版本分键;单份损坏数据可以单独清除并恢复原包,不影响其他皮肤。宿主保留的 data-ws-* 属性不会由作者节点写入渲染 DOM。 -- 编辑器操作按钮和选择器现在保留至少 44 px 触控高度,支持 Escape 关闭并在打开/关闭时移动焦点;继续打磨窄屏布局和可理解的校验提示。组件新增权限仍由宿主按既有权限机制要求批准;删除整页 surface 后应自然回到 WebSpeak 页面和宿主恢复控件。 +- 编辑器操作按钮和选择器现在保留至少 44 px 触控高度,支持 Escape 关闭并在打开/关闭时移动焦点。窄屏面板已改用安全区锚点,并在支持时依据动态视口高度限制面板,降低虚拟键盘遮挡编辑区的概率;仍需在真实 Android/iOS 浏览器键盘弹出场景验收。两个宿主作者编辑器均 Teleport 到 body,并共用顶层提升逻辑;支持 Popover API 的浏览器中,宿主编辑器进入浏览器顶层,皮肤组件不能创建或触发 popover 来覆盖它。旧浏览器保留普通固定定位和最高层级回退,仍需实际浏览器矩阵验收。权限确认与恢复入口也位于皮肤 CSS 作用域之外。组件新增权限仍由宿主按既有权限机制要求批准;删除整页 surface 后应自然回到 WebSpeak 页面和宿主恢复控件。 - 稳定门禁至少覆盖:组件/节点完整 CRUD 与撤销重做;导入导出往返;空组件文档;旧 schema v1/v2 只读兼容并在首次编辑时安全升到 v3;存储按皮肤版本隔离且坏数据可独立恢复;非法或越权文档不保存、不渲染;页面切换、皮肤切换及恢复入口不丢失。 -- 2026-10-10 的统一验证通过:622 项测试通过,服务端 TypeScript 构建、前端类型检查与 Vite 生产构建通过。编辑器到渲染出口的集成回归已证明新增、修改、删除会即时更新页面预览;删除最后一个已授权 surface 也会自动恢复宿主页面;运行时插件的屏幕采集动作会被异步桥拒绝并要求使用可信宿主控件。这仍不代表真实窄屏作者体验、跨浏览器行为或插件安全边界已经验收。 -- 当前补查发现客户端曾接受 v4 包级 `layout.json`,服务端却未读取该字段,造成同一个包本地可导入但服务端拒绝;已为校验一致性修复补充回归用例。后续只在整批修改后统一验证。 +- 2026-10-10 的统一验证通过:645 项测试通过,服务端 TypeScript 构建、前端类型检查与 Vite 生产构建通过。作者数据层测试已纳入根测试门禁,并补充连续复制时的布局 ID 冲突检查;门禁发现根节点复制 API 可返回无法插入树的孤立节点,现已在共享 CRUD 函数中拒绝。编辑器到渲染出口的集成回归已证明组件和节点的新增、复制、排序、修改、删除能即时更新页面预览;拒绝授权、增加组件权限后的重新同意、撤销授权或删除最后一个已授权 surface 都会安全恢复宿主页面,未批准的 surface 不会显示。删除树中最后一个图片引用节点后资源 URL 会及时释放,重新添加节点和 outlet 销毁也有集成回归。随后补查发现宿主作者编辑器可能被皮肤 CSS 的高层级覆盖,现已将组件编辑器和布局编辑器都 Teleport 到 body,并在支持 Popover API 时提升到浏览器顶层;v3/v4 皮肤组件都不能声明或触发 popover 或 popovertarget。回归覆盖编辑器位于皮肤根外、无 Popover API 时的固定定位回退、损坏数据的界面恢复、v1/v2 包首次编辑升级到 v3,以及组件文件导入后经界面导出的往返。根皮肤 CSS 与 v4 插件 CSS 现在共用前后端同一校验器,覆盖选择器作用域、转义后的 url()/local()、远程资源和包内素材路径;服务端会在保存皮肤包前执行相同规则。随后验证宿主拒绝 Wasm 输出时不会提交未展示的组件树,并以 2,000 个并发请求压力检查全局 Wasm 调度器的 2 个运行槽、64 个排队槽、溢出拒绝、FIFO 排空及队列计数最终归零;另有回归确认执行超过期限的 Worker 会被宿主终止并释放句柄。真实 Wasmi 解释器还接受了 240 KiB JSON 输出,并在复制前拒绝 256 KiB + 1 字节的输出。更新后的全量 645 项测试、服务端 TypeScript 构建、前端类型检查与 Vite 生产构建再次通过。这仍不代表真实窄屏作者体验、跨浏览器行为或独立安全复核已经验收。 +- 随后补查发现节点树把根节点路径与“组件级编辑”都编码为空字符串,导致根节点虽可通过组件 JSON 间接修改,却无法从树中选中并用节点编辑器直接更新。现用独立 `root` 选择键区分两种状态,并补了界面回归,证明根节点可以选中和替换;组件/子节点操作不变。编辑器与共享 CRUD 定向测试 18 项通过;随后统一验证 645 项测试、服务端 TypeScript 构建、Vue 类型检查和 Vite 生产构建全部通过。 +- 后续检查发现“添加子节点/同级节点”仍固定生成 `div/span`,其他元素只能手写 JSON,降低了任意组件的直接编辑能力。新增节点类型选择器,复用 schema 导出的安全 HTML/SVG 元素清单,也可直接插入文本节点;每次保存仍经过同一组件 schema、权限与属性校验。组件树回归覆盖根替换、直接插入 `button` 和文本节点,并逐项验证选择器列出的所有安全元素从新增、保存、实时预览、稳定布局目标到删除都能走通;同时确认节点排序及撤销/重做会同步更新组件文档与预览顺序。SVG 根和分组节点也使用合理的初始结构。随后补充布局运行时回归,验证任意组件子节点的本地位置、尺寸、显隐覆盖生效,交互节点仍保留 44 px 最小触控目标。最新统一验证为 647 项测试全部通过,服务端 TypeScript 构建、Vue 类型检查和 Vite 生产构建均通过。 +- 曾怀疑客户端接受 v4 包级 `layout.json` 而服务端未读取。重新对照后确认服务端与客户端都解析并校验该字段,服务端测试也已覆盖有效布局、缺失文件和未注册布局 ID;该疑点已排除,无需代码修复。此后新增的布局集成回归专门覆盖任意组件子节点,避免把根节点支持误当成完整节点布局支持。 - 组件渲染器原先只按素材路径缓存 Blob URL,切换皮肤后同名图片可能沿用旧皮肤素材,旧 URL 也会一直留到卸载;现改为同时绑定 Blob,并在资源替换、皮肤切换或组件卸载时释放。对应缺失素材和换包回归已加入自动化验证。 -- R5 完成门槛包括:编辑器能完整管理组件和节点;更新后页面即时预览;导入、导出、版本隔离、坏数据恢复及旧格式迁移可靠;客户端与服务端对每种包格式采用一致校验;键盘与窄屏作者流程可用;授权拒绝/撤销、恢复原生页面、插件销毁与资源回收通过针对性验证;跨浏览器动作和资源边界完成独立复核。 +- 真实浏览器实测完成 ILLUSIA v1 样例作者流程:修复旧 schema 解析时自动补入的 `mode: widget` 被首次编辑升级器再次拒绝的问题;组件编辑器现可挂载,并已在 390 px 窄屏实际新增/删除组件和节点。组件与布局编辑器在内置 Chromium 中均检查了 44 px 触控目标、Escape 关闭和焦点返回;组件编辑器另在 390×500 的键盘高度模拟视口确认面板仍可滚动、关闭控件可见且无横向溢出。测试编辑已清除。合并本轮改动后的全量验证通过:647 项测试、服务端构建、前端类型检查和 Vite 生产构建通过。该浏览器检查只覆盖当前内置 Chromium;Android/iOS 真实虚拟键盘、Edge/Firefox/Safari 矩阵及独立安全复核仍未完成。 +- 随后发现声明式组件本地状态只按皮肤 ID 和组件 ID 缓存,会在切换皮肤版本时串用,也可能在组件删除或撤权后被后续重新启用恢复。现按皮肤 ID、版本、组件命名空间和组件 ID 隔离,并在组件退出当前授权渲染集合时清理;状态键删除或类型变化也会清除/重置,类型不变的用户值保留。集成回归覆盖版本切换、删除后重建、状态 schema 修改、权限扩展重新同意和撤权后再批准。最新统一验证为 648 项测试通过,服务端 TypeScript 构建、Vue 类型检查与 Vite 生产构建通过;`git diff --check` 通过。浏览器验收按用户确认采用侧栏内置 Chromium,不要求多机或跨浏览器矩阵;独立安全复核仍作为更广泛插件安全工作的单独事项记录。 +- 随后在隔离的内置 Chromium 本地应用实例中端到端操作编辑器:从 ILLUSIA 当前包新增组件,组件立即进入首页预览;修改组件名称、根节点为 `article` 并添加 `button`,再把子节点改为 `strong`,树视图与预览同步更新;删除子节点和组件后,首页回到宿主页面。最后使用“清除本地修改”确认 ILLUSIA 包数据已恢复,临时测试覆盖已清空。用户确认这项侧栏浏览器验收可作为通过标准,不要求多机或 Edge/Firefox/Safari 矩阵;本目标的 CRUD 浏览器验收已通过。 +- R5 完成门槛包括:编辑器能完整管理组件和节点;更新后页面即时预览;导入、导出、版本隔离、坏数据恢复及旧格式迁移可靠;客户端与服务端对每种包格式采用一致校验;键盘与窄屏作者流程可用;授权拒绝/撤销、恢复原生页面、插件销毁与资源回收通过针对性验证;浏览器行为和资源边界在侧栏浏览器中验收,独立安全复核单独记录,不要求多机矩阵。 - R5 门槛通过前暂停新增参考皮肤功能和视觉扩展。R6 现有样例作为回归材料保留,之后只因明确的样例阻塞做小范围系统修补,不再反复重做通用架构或重新采集参考页面。 ### R6:KOOK 语音客户端体验复刻(等待 R5 通过) diff --git a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md index 6c0046d..096fb07 100644 --- a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md @@ -36,13 +36,13 @@ v4 当前运行路径已不使用 v3 固定标签/属性/状态/动作表来构 每个插件有稳定 ID、版本、入口文件、资源清单、页面/挂载点和细粒度 permission manifest。安装本身不运行代码;用户批准插件及权限后才加载;升级更改插件字节或权限后重新确认。撤销必须终止该插件的执行环境、关闭消息端口、清除临时数据和对象 URL;恢复按钮在插件宿主节点和皮肤 CSS 外。运行中断、加载失败、超时和更新均自动回到宿主基础界面。包内资源随 `.wskin` 本地分发,不要求新增 CDN、域名、账号或付费托管。 -当前有界解释器 + 宿主 UI 桥接已在生产构建开放,但尚未通过独立安全审查。直接在 iframe 执行 JS 的候选已因自导航外传路径被否决。生产运行仍须验证 Chrome/Edge/Firefox/Safari 的事件信任、瞬时用户激活、焦点/键盘、资源加载和销毁语义;还需测试恶意节点树、消息伪造/重放、CPU/内存耗尽、打包路径与浏览器崩溃恢复。若浏览器无法保证必要的动作来源校验,则必须由宿主渲染对应交互控件或设计其他可信用户确认,不得退化为信任插件 JS。 +当前有界解释器 + 宿主 UI 桥接已在生产构建开放,但尚未通过独立安全审查。直接在 iframe 执行 JS 的候选已因自导航外传路径被否决。按用户确认,浏览器端到端验收以侧栏内置浏览器为准,不要求多机或跨浏览器矩阵;仍需测试恶意节点树、消息伪造/重放、CPU/内存耗尽、打包路径与浏览器崩溃恢复,并完成独立安全审查后再宣称更广泛的不可信插件安全边界通过。若浏览器无法保证必要的动作来源校验,则必须由宿主渲染对应交互控件或设计其他可信用户确认,不得退化为信任插件 JS。 每个组件只能声明 home、voice 或 demo 页面中的一个页面、一个有界的树和精确权限清单。components.json 全文不超过 256 KiB。schema v1/v2 保留旧上限(32 个组件、每组件 256 个节点、16 层深度、100 个重复行);schema v3 上限为 128 个组件、每组件 2048 个节点、32 层深度、250 个重复行、64 个本地状态值和 64 个动作。图片仅可通过包内 image 资源引用。文档字节上限仍优先生效,因此实际可用数量取决于包内容。 ## 3. 可读数据和权限 -现有 v3 组件权限按组件单独请求,用户在宿主确认界面查看用途后才启用。整页 surface 必须申请 `ui.surface.replace`,所以页面替换不会因皮肤包已安装而静默启用。授权按皮肤 ID、版本、页面、组件和权限策略版本保存;换版本或策略含义变化会重新询问。皮肤设置中的独立入口可查看和撤销授权;拒绝或撤销后对应组件不渲染、不触发动作。 +现有 v3 组件权限按组件单独请求,用户在宿主确认界面查看用途后才启用。整页 surface 必须申请 `ui.surface.replace`,所以页面替换不会因皮肤包已安装而静默启用。授权按皮肤 ID、版本、页面、组件和权限策略版本保存;换版本或策略含义变化会重新询问。皮肤设置中的独立入口可查看和撤销授权;拒绝或撤销后对应组件不渲染、不触发动作。组件运行时本地状态按皮肤 ID、版本、命名空间和组件 ID 隔离,组件因删除、页面切换或权限不再满足而退出运行时后清除;修改状态定义时,已删除的键和类型变化的键清除或重置为新默认值,类型未变的现有值保留。 当前公开只读能力如下: @@ -85,7 +85,7 @@ v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦 ## 5. 校验与回退 -客户端导入和服务端登记都会校验 manifest、ZIP 路径、组件协议、所引用素材和文件限额;v4 插件描述由共享解析器验证,JS 只作 UTF-8 和尺寸校验并缓存、不执行;Wasm 入口另行校验固定 ABI。生产构建中的 Wasm 生命周期有摘要授权 UI、可终止运行、动态输出解析、全局并发上限和插件样式清理。现有组件运行时会再次解析持久化的组件文档;无效输出不渲染。权限界面和恢复控件由宿主代码渲染。v3/v4 CSS 的作用域能降低跨应用影响,但 CSS 不是针对恶意脚本的沙箱。 +客户端导入和服务端登记都会校验 manifest、ZIP 路径、组件协议、所引用素材和文件限额;根皮肤 CSS 与 v4 插件 CSS 共用 CSS 编译器,校验语法、选择器作用域、包内素材路径和复杂度,并按 CSS 转义语义检查资源函数;v4 插件描述由共享解析器验证,JS 只作 UTF-8 和尺寸校验并缓存、不执行;Wasm 入口另行校验固定 ABI。生产构建中的 Wasm 生命周期有摘要授权 UI、可终止运行、动态输出解析、全局并发上限和插件样式清理。现有组件运行时会再次解析持久化的组件文档;无效输出不渲染。权限界面和恢复控件由宿主代码渲染。v3/v4 CSS 的作用域能降低跨应用影响,但 CSS 不是针对恶意脚本的沙箱。 皮肤载入错误不得清除用户布局或 TeamSpeak 会话。组件树为空、权限被拒绝或皮肤无效时,宿主本身和既有功能仍可由用户恢复。v4 每个插件需有独立错误边界;单个插件崩溃不能拖垮语音会话或其余插件,撤销必须立即销毁该插件运行环境。管理员后台仍沿用自己的样式和服务端管理流程。 @@ -98,5 +98,5 @@ v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦 - 扩展数据字段或宿主动作时,增加精确 schema、权限、明确用户事件约束和宿主侧运行时验证,不暴露内部 SDK 对象。新增宿主控件也必须登记固定 ID、明确页面和确认只在宿主内处理其私有状态;自定义声明式 UI 不应被限制为只能拼装这组控件。 - 对恶意输入、路径别名、拒绝授权、撤销、更新和皮肤切换增加测试;高敏能力必须单独设计。 - JavaScript Worker 运行时在生产构建保持关闭,因为它缺少硬内存配额。Wasm 解释器使用 64 MiB 容器上限、最多 4 MiB 扩展线性内存、10,000,000 燃料上限,外层 Worker 在 100 ms 后可终止执行;单个 WebClient 页面实例最多并发 2 个 Wasm worker,最多排队 64 个任务。 -- Wasm 的 `env.ui_emit_json` 每次运行最多提交一次、最多 256 KiB 的 UTF-8 JSON。动态 UI 输出 schema v3 可用原声明式节点;v4 支持标准 HTML/SVG 节点、普通属性、隔离插件 CSS 和包内图片;v5 增加本地标量状态与事件名到处理器 ID 的映射;v6 可在可信 UI 事件触发的同一轮输出中提出一个宿主动作。生产 WebClient 经摘要授权后由宿主解析并创建节点,不把输出当 HTML 执行;自定义元素映射为惰性宿主 `div`,避免触发页面中注册的 Web Component。脚本、嵌入浏览器、外部资源/导航属性、事件属性和行内 CSS 会拒绝;作者样式通过包内隔离 CSS 提供。`env.ui_input_read` 每次 Wasm 调用最多读取一次、最多 64 KiB;本地状态和事件字段仍受限,公开数据快照最多 48 KiB,并经宿主读取权限映射与字段白名单投影。数据只存在于当前调用的输入中,不传 DOM/Event 对象或自报的可信标记。UI 循环可将可信事件或数据变化作为下一次有界 Wasm 调用输入,最多串行排队 8 项,并重新验证回调 ID 与组件状态归属。异步 Wasm 动作继续受插件声明权限和会话校验约束;`voice.startScreenShare` 必须走可信宿主控件,不能由异步动作桥调用。仍需完成其余动作的跨浏览器、资源耗尽测试和独立安全审查。 +- Wasm 的 `env.ui_emit_json` 每次运行最多提交一次、最多 256 KiB 的 UTF-8 JSON。动态 UI 输出 schema v3 可用原声明式节点;v4 支持标准 HTML/SVG 节点、普通属性、隔离插件 CSS 和包内图片;v5 增加本地标量状态与事件名到处理器 ID 的映射;v6 可在可信 UI 事件触发的同一轮输出中提出一个宿主动作。生产 WebClient 经摘要授权后由宿主解析并创建节点,不把输出当 HTML 执行;自定义元素映射为惰性宿主 `div`,避免触发页面中注册的 Web Component。脚本、嵌入浏览器、外部资源/导航属性、事件属性、行内 CSS,以及可创建或触发浏览器顶层 Popover 的 `popover`、`popovertarget` 和 `popovertargetaction` 属性均会拒绝;作者样式通过包内隔离 CSS 提供。`env.ui_input_read` 每次 Wasm 调用最多读取一次、最多 64 KiB;本地状态和事件字段仍受限,公开数据快照最多 48 KiB,并经宿主读取权限映射与字段白名单投影。数据只存在于当前调用的输入中,不传 DOM/Event 对象或自报的可信标记。UI 循环可将可信事件或数据变化作为下一次有界 Wasm 调用输入,最多串行排队 8 项,并重新验证回调 ID 与组件状态归属。异步 Wasm 动作继续受插件声明权限和会话校验约束;`voice.startScreenShare` 必须走可信宿主控件,不能由异步动作桥调用。仍需完成其余动作的跨浏览器、资源耗尽测试和独立安全审查。 - 商城发布、签名、下架、更新和撤销设计与管理员面板重做一起验收,且保持零新增服务费用为默认约束。 diff --git a/package-lock.json b/package-lock.json index 1a1e295..a6156ec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,9 @@ "@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811", "express": "^5.2.1", "pino": "^10.3.1", + "postcss": "^8.5.29", + "postcss-selector-parser": "^7.1.6", + "postcss-value-parser": "^4.2.0", "werift": "0.24.4", "ws": "^8.20.0" }, @@ -1198,6 +1201,18 @@ "node": ">=6.6.0" } }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1901,6 +1916,24 @@ "multicast-dns": "cli.js" } }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "node_modules/negotiator": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", @@ -2046,6 +2079,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, "node_modules/pino": { "version": "10.3.1", "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", @@ -2083,6 +2122,53 @@ "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", "license": "MIT" }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "license": "MIT" + }, "node_modules/process-warning": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", @@ -2427,6 +2513,15 @@ "atomic-sleep": "^1.0.0" } }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", diff --git a/package.json b/package.json index 5288add..c8ba08f 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "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/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.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/skin-plugin-runtime.test.ts web/src/services/skin-extension-ui.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-runtime-plugin-approval.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/test/skin-plugin-editor.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-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.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/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.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/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.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-runtime-plugin-approval.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/test/skin-plugin-editor.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-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "start": "node dist/index.js", @@ -31,6 +31,9 @@ "@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811", "express": "^5.2.1", "pino": "^10.3.1", + "postcss": "^8.5.29", + "postcss-selector-parser": "^7.1.6", + "postcss-value-parser": "^4.2.0", "werift": "0.24.4", "ws": "^8.20.0" }, diff --git a/src/admin/skin-registry.test.ts b/src/admin/skin-registry.test.ts index 0ec489b..a0f502a 100644 --- a/src/admin/skin-registry.test.ts +++ b/src/admin/skin-registry.test.ts @@ -26,7 +26,7 @@ test("skin registry validates, lists, replaces, serves, and removes packages", a assert.equal(await registry.readArchive("sample-skin"), null); const firstArchive = createZip([ ["manifest.json", Buffer.from(JSON.stringify(manifest))], - ["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")], + ["skin.css", Buffer.from('[data-ws-part="voice.member"] { background: url(assets/background.png); }')], ["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))], ["assets/background.png", Buffer.from([1, 2, 3, 4])], ["assets/preview.png", Buffer.from([5, 6, 7, 8])], @@ -45,7 +45,7 @@ test("skin registry validates, lists, replaces, serves, and removes packages", a const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined }; const secondArchive = createZip([ ["manifest.json", Buffer.from(JSON.stringify(replacement))], - ["skin.css", Buffer.from(".voice-card { border-radius: 0; }")], + ["skin.css", Buffer.from('[data-ws-part="voice.member"] { border-radius: 0; }')], ]); const second = await registry.save(secondArchive, "sample-skin"); assert.equal(second.version, "2.0.0"); @@ -128,7 +128,7 @@ test("server accepts validated declarative v2 layouts and rejects permissions or const unknownComponentArchive = createZip([ ["manifest.json", Buffer.from(JSON.stringify(manifestV2))], - ["skin.css", Buffer.from(".voice-card { color: teal; }")], + ["skin.css", Buffer.from('[data-ws-part="voice.member"] { 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"); @@ -190,6 +190,58 @@ test("server accepts a v3 open visual skin without a components document", async assert.deepEqual(await registry.readArchive("sample-skin"), archive); }); +test("server applies the browser CSS scope and package-only resource policy to every stylesheet", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-css-policy-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const unsafeLegacySelector = createZip([ + ["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))], + ["skin.css", Buffer.from(".private-class { color: teal; }")], + ]); + await assert.rejects(registry.save(unsafeLegacySelector, "sample-skin"), (error: unknown) => + error instanceof SkinRegistryError && error.code === "SKIN_CSS_SELECTOR"); + + const remoteSkinCss = createZip([ + ["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))], + ["skin.css", Buffer.from('[data-ws-part="app"] { background-image: url("https://example.invalid/track.png"); }')], + ]); + await assert.rejects(registry.save(remoteSkinCss, "sample-skin"), (error: unknown) => + error instanceof SkinRegistryError && error.code === "SKIN_EXTERNAL_RESOURCE"); + + const manifestV4 = { + ...manifest, + schemaVersion: 4, + packageType: "open-skin", + content: undefined, + preview: undefined, + plugins: "plugins.json", + }; + const plugins = { + schemaVersion: 1, + plugins: [{ + id: "voice-toolbar", + name: "Voice toolbar", + version: "1.0.0", + apiVersion: 1, + page: "voice", + mode: "widget", + entry: "plugins/voice-toolbar/index.js", + style: "plugins/voice-toolbar/style.css", + assets: [], + permissions: [], + }], + }; + const remotePluginCss = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV4))], + ["skin.css", Buffer.from('[data-ws-part="app"] { color: teal; }')], + ["plugins.json", Buffer.from(JSON.stringify(plugins))], + ["plugins/voice-toolbar/index.js", Buffer.from("export {}; ")], + ["plugins/voice-toolbar/style.css", Buffer.from('.toolbar { background-image: u\\72l("https://example.invalid/track.png"); }')], + ]); + await assert.rejects(registry.save(remotePluginCss, "sample-skin"), (error: unknown) => + error instanceof SkinRegistryError && error.code === "SKIN_EXTERNAL_RESOURCE"); +}); + test("server validates v4 plugin manifests and package files without executing author code", async (context) => { const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v4-")); context.after(() => rm(directory, { recursive: true, force: true })); @@ -308,7 +360,7 @@ test("skin registry rejects path traversal and mismatched local ZIP headers", as const registry = new SkinRegistry(directory); const goodFiles: Array<[string, Buffer]> = [ ["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))], - ["skin.css", Buffer.from(".voice-card { color: teal; }")], + ["skin.css", Buffer.from('[data-ws-part="voice.member"] { color: teal; }')], ]; await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID"); diff --git a/src/admin/skin-registry.ts b/src/admin/skin-registry.ts index 8e18e9e..3077d45 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 { compileSkinCss, SkinCssValidationError, type SkinCssSchemaVersion } from "../shared/skin-css.js"; import { parseSkinLayoutJson } from "../shared/skin-layout.js"; import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../shared/skin-plugin.js"; import { @@ -232,7 +233,7 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH"); const cssBytes = fileBytes.get(manifest.entry); if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE"); - decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8."); + const cssSource = decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8."); let runtimePlugins: SkinRuntimePluginDocument | undefined; if (manifest.plugins) { @@ -280,6 +281,23 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE"); if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE"); } + const cssAssets = new Set([...fileBytes.keys()].filter((packagePath) => + imageMime(packagePath) !== null || packagePath.toLowerCase().endsWith(".woff2"))); + validateSkinCss(cssSource, manifest.id, cssAssets, manifest.schemaVersion); + for (const plugin of runtimePlugins?.plugins ?? []) { + if (!plugin.style) continue; + const styleBytes = fileBytes.get(plugin.style); + if (!styleBytes) throw new SkinRegistryError(`A declared plugin style is missing: ${plugin.style}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING"); + const pluginCssAssets = new Set([...cssAssets].filter((packagePath) => + packagePath.startsWith("assets/") || packagePath.startsWith(`plugins/${plugin.id}/assets/`))); + validateSkinCss( + decodeUtf8(styleBytes, "Plugin style files must contain valid UTF-8."), + manifest.id, + pluginCssAssets, + manifest.schemaVersion, + plugin.id, + ); + } if (manifest.content) { const content = fileBytes.get(manifest.content); if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE"); @@ -311,6 +329,22 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) }; } +function validateSkinCss( + source: string, + skinId: string, + assets: Set, + schemaVersion: SkinCssSchemaVersion, + pluginId?: string, +): void { + try { compileSkinCss(source, skinId, assets, schemaVersion, pluginId); } + catch (error) { + const cssError = error instanceof SkinCssValidationError + ? error + : new SkinCssValidationError(error instanceof Error ? error.message : "The CSS file is invalid.", "SKIN_CSS_INVALID"); + throw new SkinRegistryError(cssError.message, cssError.code); + } +} + function inspectArchive(bytes: Buffer): SkinArchiveEntry[] { if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE"); const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff); diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts new file mode 100644 index 0000000..4784940 --- /dev/null +++ b/src/shared/skin-css.ts @@ -0,0 +1,380 @@ +import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss"; +import selectorParser from "postcss-selector-parser"; +import valueParser from "postcss-value-parser"; + +export type SkinCssSchemaVersion = 1 | 2 | 3 | 4; +export type SkinCssAssets = Readonly> | Map | Set; +const MAX_CSS_BYTES = 512 * 1024; + +export class SkinCssValidationError extends Error { + constructor(message: string, readonly code: string) { + super(message); + this.name = "SkinCssValidationError"; + } +} + +function hasSkinCssAsset(assets: SkinCssAssets, path: string): boolean { + if (assets instanceof Set) return assets.has(path); + if (assets instanceof Map) return assets.has(path); + return Object.prototype.hasOwnProperty.call(assets, path) && Boolean(assets[path]); +} + +const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]); +const LAYOUT_AFFECTING_PROPERTIES = new Set([ + "all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline", + "width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size", + "min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing", + "gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x", + "overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility", + "pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate", + "perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name", + "container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font", + "font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap", + "text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim", + "line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift", + "box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing", + "writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content", + "position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope", +]); +const OPTIONAL_VISUAL_PARTS = new Set([ + "home.hero.eyebrow", + "home.gateway-status", + "home.features", + "home.feature", + "home.visitors", + "home.join-card.waveform", + "home.join-card.sonar", + "voice.activity-heading", + "voice.member.avatar", + "voice.member.live-indicator", + "voice.member-row.avatar", + "voice.screen-player.viewer-avatar", + "voice.screen-player.live", + "demo.badge", + "demo.wave", + "demo.avatar", + "demo.member-status", + "demo.note", +]); +export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } { + const size = new TextEncoder().encode(source).byteLength; + if (!size || size > MAX_CSS_BYTES) throw new SkinCssValidationError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE"); + let root: postcss.Root; + try { root = postcss.parse(source, { from: undefined }); } + catch (error) { throw new SkinCssValidationError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); } + + const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`; + const scope = pluginId + ? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]` + : skinScope; + const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`; + const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone()); + const warnings = new Set(); + const keyframeNames = new Map(); + const fontFamilyNames = new Map(); + const hideableRules = new WeakSet(); + let nodeCount = 0; + root.walk((node) => { + nodeCount += 1; + if (nodeCount > 12000) throw new SkinCssValidationError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY"); + }); + + root.walkAtRules((rule: AtRule) => { + const name = rule.name.toLowerCase(); + if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`); + if (name.endsWith("keyframes")) { + const keyframeName = rule.params.trim(); + if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers."); + keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`); + rule.params = `${namespace}-${keyframeName}`; + } else if (name === "layer") { + const layers = rule.params.split(",").map((layer) => layer.trim()); + if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) { + throw rule.error("Skin CSS must use named @layer values so layer names can be isolated."); + } + rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", "); + } else if (name === "font-face") { + if (/\blocal\s*\(/i.test(decodeCssEscapes(rule.toString()))) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package."); + const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family"); + if (!family) throw rule.error("Each @font-face rule must declare font-family."); + const originalFamily = parseSingleFontFamily(family.value); + const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`; + fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily); + family.value = `"${scopedFamily}"`; + } + }); + + root.walkRules((rule: Rule) => { + if (hasKeyframesAncestor(rule)) return; + if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors."); + if (!pluginId && !selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) { + throw new SkinCssValidationError(rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.").message, "SKIN_CSS_SELECTOR"); + } + if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule); + try { + rule.selector = selectorParser((selectors) => { + selectors.each((selector) => { + const text = selector.toString().trim(); + if (!text) throw new SkinCssValidationError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR"); + if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinCssValidationError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR"); + if (/^:root\b/.test(text)) { + selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone()); + return; + } + selector.prepend(selectorParser.combinator({ value: " " })); + for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone()); + }); + }).processSync(rule.selector); + } catch (error) { + if (error instanceof SkinCssValidationError) throw error; + throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`); + } + }); + + const referencedKeyframes = new Set(); + const nonOptionalKeyframes = new Set(); + root.walkRules((rule: Rule) => { + if (hasKeyframesAncestor(rule)) return; + const optionalTarget = hideableRules.has(rule); + rule.walkDecls((declaration: Declaration) => { + const property = declaration.prop.toLowerCase(); + if (property !== "animation" && property !== "animation-name") return; + const value = declaration.value; + if (/\b(?:var|attr)\s*\(|\\/i.test(value)) { + keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name)); + return; + } + for (const name of keyframeNames.keys()) { + if (!referencesCssIdentifier(value, name)) continue; + referencedKeyframes.add(name); + if (!optionalTarget) nonOptionalKeyframes.add(name); + } + }); + }); + const optionalOnlyKeyframes = new Set([...referencedKeyframes] + .filter((name) => !nonOptionalKeyframes.has(name)) + .map((name) => keyframeNames.get(name)!)); + + root.walkDecls((declaration: Declaration) => { + const property = decodeCssEscapes(declaration.prop).toLowerCase(); + const value = declaration.value.trim(); + const decodedValue = decodeCssEscapes(value); + const owningRule = findOwningRule(declaration); + const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null; + const canHideTarget = owningRule + ? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim())) + : false; + if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property) + && !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) { + throw declaration.error(pluginId + ? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.` + : "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens."); + } + if (schemaVersion < 3 && isLayoutAffectingProperty(property)) { + throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry."); + } + if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing."); + if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) { + throw declaration.error("Executable CSS values are not allowed."); + } + const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase(); + if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) { + if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts."); + } + const removesVisual = property === "all" + || (property === "display" && compactValue === "none") + || (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue)) + || (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue)) + || (property === "pointer-events" && compactValue === "none") + || (property === "clip-path" && /inset\(\s*50%/.test(compactValue)) + || (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue)); + if (removesVisual && !canHideTarget && schemaVersion < 3) { + throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available."); + } + const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue)) + || (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue)) + || (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue)); + if (visuallyRemoves && !canHideTarget && schemaVersion < 3) { + throw declaration.error("Only explicitly optional visual parts may be visually removed."); + } + if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls."); + if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile."); + const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames); + declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => { + if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`); + return `wskin-asset:${encodeURIComponent(assetPath)}`; + }); + }); + + return { css: root.toString(), warnings: [...warnings] }; +} + +export function rewriteSkinCssAssets(css: string, resolve: (path: string) => string): string { + const root = postcss.parse(css, { from: undefined }); + root.walkDecls((declaration) => { + declaration.value = rewriteAssetUrls(declaration.value, resolve); + }); + return root.toString(); +} + +function targetsOnlyOptionalVisualParts(selector: string): boolean { + try { + const parsed = selectorParser().astSync(selector); + return parsed.nodes.length > 0 && parsed.nodes.every((item) => { + if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false; + const attribute = item.nodes[0]; + if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false; + const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, ""); + return OPTIONAL_VISUAL_PARTS.has(part); + }); + } catch { + return false; + } +} + +function selectorUsesPublicHook(selector: string, allowCustomClasses = false): boolean { + try { + const parsed = selectorParser().astSync(selector); + return parsed.nodes.length > 0 && parsed.nodes.every((item) => { + let scoped = false; + let usesPrivateName = false; + item.walk((node) => { + if (node.type === "attribute" && ["data-ws-part", "data-ws-page", ...(allowCustomClasses ? ["data-ws-plugin-part"] : [])].includes(node.attribute.toLowerCase())) scoped = true; + if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true; + if (!allowCustomClasses && (node.type === "class" || node.type === "id")) usesPrivateName = true; + }); + return scoped && !usesPrivateName; + }); + } catch { + return false; + } +} + +function isLayoutAffectingProperty(property: string): boolean { + const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); + if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true; + if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true; + if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true; + if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true; + return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed); +} + +function findOwningRule(node: Node): Rule | null { + let parent = node.parent; + while (parent && parent.type !== "root") { + if (parent.type === "rule") return parent as Rule; + parent = parent.parent; + } + return null; +} + +function findKeyframesRule(rule: Rule): AtRule | null { + let parent = rule.parent; + while (parent && parent.type !== "root") { + if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule; + parent = parent.parent; + } + return null; +} + +function referencesCssIdentifier(value: string, identifier: string): boolean { + const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value); +} + +export function rewriteAssetUrls(value: string, resolve: (path: string) => string): string { + const parsed = valueParser(value); + const resolvePackageAsset = (rawValue: string): string => { + const raw = decodeCssEscapes(rawValue.trim()); + if (!raw || raw.startsWith("#")) throw new SkinCssValidationError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE"); + const isInternalMarker = raw.startsWith("wskin-asset:"); + if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinCssValidationError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE"); + let path: string; + try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); } + catch { throw new SkinCssValidationError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); } + return resolve(path); + }; + const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => { + for (const node of nodes) { + const functionName = node.type === "function" ? decodeCssEscapes(node.value).toLowerCase() : ""; + if (node.type === "function" && functionName === "url") { + const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim(); + node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }]; + node.before = ""; + node.after = ""; + continue; + } + if (node.type === "function" && (functionName === "image-set" || functionName === "-webkit-image-set")) { + for (const child of node.nodes) { + if (child.type === "string") child.value = resolvePackageAsset(child.value); + else if (child.type === "function") visit([child]); + } + continue; + } + if (node.type === "function") visit(node.nodes, inImageSet); + else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value); + } + }; + visit(parsed.nodes); + return parsed.toString(); +} + +function decodeCssEscapes(value: string): string { + return value.replace(/\\([\da-f]{1,6})(?:[\t\n\f\r ]|\r\n)?|\\([^\da-f\r\n\f])/gi, (match, hexadecimal: string | undefined, escaped: string | undefined) => { + if (hexadecimal) { + const codePoint = Number.parseInt(hexadecimal, 16); + if (!codePoint || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) return "\ufffd"; + return String.fromCodePoint(codePoint); + } + return escaped ?? match; + }); +} + +function parseSingleFontFamily(value: string): string { + const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment"); + if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) { + throw new SkinCssValidationError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY"); + } + return parsed[0].value.trim(); +} + +function rewriteScopedNames(value: string, property: string, keyframes: Map, fontFamilies: Map): string { + const parsed = valueParser(value); + if (["animation", "animation-name", "font", "font-family"].includes(property)) { + parsed.walk((node) => { + if (node.type !== "word" && node.type !== "string") return; + const keyframe = keyframes.get(node.value); + if (keyframe) node.value = keyframe; + const family = fontFamilies.get(node.value.toLowerCase()); + if (family) node.value = family; + }); + } + return parsed.toString(); +} + +function normalizeAssetPath(raw: string): string { + let path = raw.split(/[?#]/, 1)[0]; + try { path = decodeURIComponent(path); } catch { throw new SkinCssValidationError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); } + if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinCssValidationError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH"); + const segments: string[] = []; + for (const segment of path.split("/")) { + if (!segment || segment === ".") continue; + if (segment === "..") { + if (!segments.length) throw new SkinCssValidationError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH"); + segments.pop(); + } else { + segments.push(segment); + } + } + if (!segments.length) throw new SkinCssValidationError("An asset URL must point to a package file.", "SKIN_ASSET_PATH"); + return segments.join("/"); +} + +function hasKeyframesAncestor(rule: Rule): boolean { + let parent = rule.parent; + while (parent && parent.type !== "root") { + if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true; + parent = parent.parent; + } + return false; +} diff --git a/src/shared/skin-extension-ui.ts b/src/shared/skin-extension-ui.ts index 44739c6..8274c2e 100644 --- a/src/shared/skin-extension-ui.ts +++ b/src/shared/skin-extension-ui.ts @@ -33,7 +33,7 @@ const GENERATED_VOID_ELEMENTS = new Set([ const GENERATED_BLOCKED_ATTRIBUTES = new Set([ "action", "archive", "background", "code", "codebase", "data", "download", "form", "formaction", "formmethod", "formenctype", "formtarget", "is", "manifest", "ping", "poster", "profile", "src", "srcdoc", "srcset", "style", "target", "xlink:href", - "autofocus", "autoplay", "command", "commandfor", "http-equiv", "nonce", "slot", "xml:base", + "autofocus", "autoplay", "command", "commandfor", "http-equiv", "nonce", "popover", "popovertarget", "popovertargetaction", "slot", "xml:base", ]); export class SkinExtensionUiOutputError extends Error { diff --git a/src/shared/skin-plugin-editor.ts b/src/shared/skin-plugin-editor.ts index 795e241..2fb4ede 100644 --- a/src/shared/skin-plugin-editor.ts +++ b/src/shared/skin-plugin-editor.ts @@ -8,7 +8,24 @@ import { /** Normalize an older declarative package before editing while preserving its validated data. */ export function editableSkinPluginDocument(input: unknown): SkinPluginDocument { - const parsed = parseSkinPluginDocument(input); + // The package parser materializes the schema-v1 default `mode: "widget"` in + // its normalized object. Remove that derived field before validating the + // normalized document again, since schema v1 itself does not declare mode. + const source = input && typeof input === "object" && !Array.isArray(input) + && (input as { schemaVersion?: unknown }).schemaVersion === 1 + && Array.isArray((input as { components?: unknown }).components) + ? { + ...(input as Record), + components: ((input as { components: unknown[] }).components).map((component) => { + if (!component || typeof component !== "object" || Array.isArray(component) + || (component as { mode?: unknown }).mode !== "widget") return component; + const withoutDefaultMode = { ...(component as Record) }; + delete withoutDefaultMode.mode; + return withoutDefaultMode; + }), + } + : input; + const parsed = parseSkinPluginDocument(source); if (parsed.schemaVersion === 3) return parsed; const components = parsed.components.map((component) => { const permissions = new Set(component.permissions); @@ -197,6 +214,7 @@ export function getSkinPluginNode(input: SkinPluginDocument, componentId: string /** Give a duplicated subtree fresh stable layout parts so it cannot alias its source nodes. */ export function duplicateSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode { + if (!path.length) throw new Error("A component root cannot be duplicated."); const document = editableSkinPluginDocument(input); const component = document.components[componentIndex(document, componentId)]; const source = nodeAt(component, path); diff --git a/src/shared/skin-plugin.test.ts b/src/shared/skin-plugin.test.ts index c4e6332..2bcf4b4 100644 --- a/src/shared/skin-plugin.test.ts +++ b/src/shared/skin-plugin.test.ts @@ -213,6 +213,14 @@ test("skin plugin rejects undeclared permissions, arbitrary paths, and executabl const externalSvgPaint = validDocument(); externalSvgPaint.components[0].root.children![0].attributes = { fill: "url(https://example.invalid/payload.svg#paint)" }; errorCode(() => parseSkinPluginDocument(externalSvgPaint), "SKIN_PLUGIN_ATTRIBUTE_INVALID"); + + const skinOwnedPopover = validDocument(); + skinOwnedPopover.components[0].root.children![0].attributes = { popover: "manual" }; + errorCode(() => parseSkinPluginDocument(skinOwnedPopover), "SKIN_PLUGIN_ATTRIBUTE_INVALID"); + + const skinOwnedPopoverTrigger = validDocument(); + skinOwnedPopoverTrigger.components[0].root.children![0].attributes = { popovertarget: "host-editor" }; + errorCode(() => parseSkinPluginDocument(skinOwnedPopoverTrigger), "SKIN_PLUGIN_ATTRIBUTE_INVALID"); }); test("skin plugin restricts repeated fields to the selected collection", () => { diff --git a/src/shared/skin-plugin.ts b/src/shared/skin-plugin.ts index a5e50ae..a86448a 100644 --- a/src/shared/skin-plugin.ts +++ b/src/shared/skin-plugin.ts @@ -134,13 +134,14 @@ export class SkinPluginValidationError extends Error { } } -const ELEMENTS = new Set([ +export const SKIN_PLUGIN_ALLOWED_ELEMENTS = Object.freeze([ "article", "aside", "b", "blockquote", "br", "button", "caption", "circle", "cite", "code", "dd", "del", "details", "div", "dl", "dt", "em", "fieldset", "figcaption", "figure", "footer", "form", "g", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "i", "img", "input", "kbd", "label", "legend", "li", "line", "main", "mark", "nav", "ol", "option", "output", "p", "path", "polyline", "pre", "progress", "q", "rect", "s", "section", "select", "small", "span", "strong", "sub", "summary", "sup", "svg", "table", "tbody", "td", "textarea", "th", "thead", "time", "tr", "u", "ul", "wbr", -]); +] as const); +const ELEMENTS = new Set(SKIN_PLUGIN_ALLOWED_ELEMENTS); const VOID_ELEMENTS = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]); const ATTRIBUTES = new Set([ "alt", "aria-current", "aria-expanded", "aria-hidden", "aria-label", "aria-pressed", "aria-selected", "autocomplete", "checked", "class", "colspan", "disabled", "draggable", "fill", "height", "inputmode", "max", "maxlength", "min", diff --git a/web/src/components/SkinLayoutEditor.vue b/web/src/components/SkinLayoutEditor.vue index 429ce25..3f15e01 100644 --- a/web/src/components/SkinLayoutEditor.vue +++ b/web/src/components/SkinLayoutEditor.vue @@ -1,7 +1,8 @@ diff --git a/web/src/components/SkinPluginOutlet.ts b/web/src/components/SkinPluginOutlet.ts index 34c007c..b6ecec9 100644 --- a/web/src/components/SkinPluginOutlet.ts +++ b/web/src/components/SkinPluginOutlet.ts @@ -4,6 +4,7 @@ import { SKIN_PLUGIN_PERMISSIONS, SKIN_PLUGIN_RENDER_NODE_LIMIT, SKIN_PLUGIN_REPEAT_LIMIT, + listSkinPluginAssetPaths, parseSkinPluginDocument, type SkinPluginActionDefinition, type SkinPluginComponent, @@ -120,12 +121,35 @@ export default defineComponent({ refresh.value += 1; }, { immediate: true }); watch(() => [props.skinId, props.skinVersion, props.assets] as const, () => assetUrls.clear()); + watch(renderedComponents, (components) => { + assetUrls.retain(listSkinPluginAssetPaths({ schemaVersion: 3, components })); + const activeStateKeys = new Set(components.map(componentStateKey)); + for (const key of Object.keys(stateByComponent)) { + if (!activeStateKeys.has(key)) delete stateByComponent[key]; + } + }, { immediate: true }); watch(activeSurface, (surface) => emit("surface-change", Boolean(surface)), { immediate: true, flush: "sync" }); + function componentStateKey(component: SkinPluginComponent): string { + return JSON.stringify([props.skinId, props.skinVersion, props.componentNamespace, component.id]); + } + function localState(component: SkinPluginComponent): Record { - const key = `${props.skinId}/${component.id}`; - if (!stateByComponent[key]) stateByComponent[key] = { ...(component.state ?? {}) }; - return stateByComponent[key]; + const key = componentStateKey(component); + const defaults = component.state ?? {}; + let state = stateByComponent[key]; + if (!state) { + state = { ...defaults }; + stateByComponent[key] = state; + return state; + } + for (const stateKey of Object.keys(state)) { + if (!Object.hasOwn(defaults, stateKey)) delete state[stateKey]; + } + for (const [stateKey, value] of Object.entries(defaults)) { + if (!Object.hasOwn(state, stateKey) || typeof state[stateKey] !== typeof value) state[stateKey] = value; + } + return state; } function permissionLabel(permission: string): string { diff --git a/web/src/services/host-editor-top-layer.test.ts b/web/src/services/host-editor-top-layer.test.ts new file mode 100644 index 0000000..1097163 --- /dev/null +++ b/web/src/services/host-editor-top-layer.test.ts @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { promoteHostEditorToTopLayer } from "./host-editor-top-layer.js"; + +test("host editors use Popover API top layer when it is available", () => { + const attributes = new Map(); + let showCount = 0; + const element = { + showPopover() { showCount += 1; }, + matches(selector: string) { return selector === ":popover-open" && showCount > 0; }, + setAttribute(name: string, value: string) { attributes.set(name, value); }, + removeAttribute(name: string) { attributes.delete(name); }, + } as unknown as HTMLElement; + + promoteHostEditorToTopLayer(element); + promoteHostEditorToTopLayer(element); + + assert.equal(attributes.get("popover"), "manual"); + assert.equal(showCount, 1, "repeated ref notifications do not reopen an already visible popover"); +}); + +test("host editors keep their ordinary positioning when Popover API is unavailable or fails", () => { + let showCount = 0; + const unsupported = { + setAttribute() { throw new Error("must not add unsupported popover attributes"); }, + } as unknown as HTMLElement; + const failingAttributes = new Map(); + const failing = { + showPopover() { showCount += 1; throw new Error("browser denied popover"); }, + setAttribute(name: string, value: string) { failingAttributes.set(name, value); }, + removeAttribute(name: string) { failingAttributes.delete(name); }, + } as unknown as HTMLElement; + + promoteHostEditorToTopLayer(unsupported); + promoteHostEditorToTopLayer(null); + promoteHostEditorToTopLayer(failing); + + assert.equal(showCount, 1); + assert.equal(failingAttributes.has("popover"), false, "a failed top-layer promotion leaves the CSS fallback visible"); +}); diff --git a/web/src/services/host-editor-top-layer.ts b/web/src/services/host-editor-top-layer.ts new file mode 100644 index 0000000..da6f537 --- /dev/null +++ b/web/src/services/host-editor-top-layer.ts @@ -0,0 +1,15 @@ +export function promoteHostEditorToTopLayer(element: HTMLElement | null): void { + const popover = element as (HTMLElement & { + showPopover?: () => void; + matches?: (selectors: string) => boolean; + }) | null; + if (!popover || typeof popover.showPopover !== "function") return; + + try { + if (popover.matches?.(":popover-open")) return; + popover.setAttribute("popover", "manual"); + popover.showPopover(); + } catch { + popover.removeAttribute("popover"); + } +} diff --git a/web/src/services/skin-extension-ui.test.ts b/web/src/services/skin-extension-ui.test.ts index d223c5b..a1c05d5 100644 --- a/web/src/services/skin-extension-ui.test.ts +++ b/web/src/services/skin-extension-ui.test.ts @@ -350,6 +350,12 @@ test("generated UI rejects executable elements, event handlers, and network/navi expectOutputError(generatedOutput("runtime-ui", { tag: "div", attributes: { "data-ws-part": "spoofed" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID"); }); +test("generated UI cannot create browser top-layer popovers that cover host controls", () => { + expectOutputError(generatedOutput("runtime-ui", { tag: "div", attributes: { popover: "manual" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID"); + expectOutputError(generatedOutput("runtime-ui", { tag: "button", attributes: { popovertarget: "host-editor" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID"); + expectOutputError(generatedOutput("runtime-ui", { tag: "button", attributes: { popovertargetaction: "show" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID"); +}); + test("generated UI enforces component and per-node child limits", () => { const tooManyComponents = JSON.stringify({ schemaVersion: 4, diff --git a/web/src/services/skin-extension-wasm-ui-loop.test.ts b/web/src/services/skin-extension-wasm-ui-loop.test.ts index 3dcff22..3d4f9f7 100644 --- a/web/src/services/skin-extension-wasm-ui-loop.test.ts +++ b/web/src/services/skin-extension-wasm-ui-loop.test.ts @@ -6,7 +6,7 @@ import { } from "./skin-extension-wasm-ui-loop.js"; import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js"; -function uiOutput(count: number): string { +function uiOutput(count: number, handlerId = "increment"): string { return JSON.stringify({ schemaVersion: 5, components: [{ @@ -15,7 +15,7 @@ function uiOutput(count: number): string { page: "voice", accessibleName: "Local counter", state: { count }, - root: { tag: "button", events: { click: "increment" }, children: [{ text: String(count) }] }, + root: { tag: "button", events: { click: handlerId }, children: [{ text: String(count) }] }, }], }); } @@ -76,6 +76,30 @@ test("runtime data refresh reruns the guest without fabricating a user event", a loop.close(); }); +test("host-rejected UI output does not replace the callback document", async () => { + const jobs: SkinExtensionUiInput[] = []; + const rejectedOutput = uiOutput(1, "unaccepted"); + const loop = createSkinExtensionWasmUiLoopPrototype({ + createRun(input) { + jobs.push(input); + return { + result: Promise.resolve({ uiOutput: input.event ? rejectedOutput : uiOutput(0) }), + close: () => undefined, + }; + }, + onOutput(output) { + if (output === rejectedOutput) throw new Error("Host rejected the generated document."); + }, + }); + + assert.equal(await loop.start(), true); + assert.equal(await loop.dispatch(clickInput(0)), false); + assert.equal(loop.output, uiOutput(0)); + assert.equal(await loop.dispatch(clickInput(1, "unaccepted")), false); + assert.equal(jobs.length, 2, "callbacks from a host-rejected document must not be accepted"); + loop.close(); +}); + test("Wasm UI callback queue is bounded and close cancels active and waiting work", async () => { let rejectActive!: (error: Error) => void; let held = false; diff --git a/web/src/services/skin-extension-wasm-ui-loop.ts b/web/src/services/skin-extension-wasm-ui-loop.ts index b9503a7..35c3b4a 100644 --- a/web/src/services/skin-extension-wasm-ui-loop.ts +++ b/web/src/services/skin-extension-wasm-ui-loop.ts @@ -74,13 +74,13 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas activeRun = run; const result = await run.result; if (closed || activeRun !== run) return false; - lastState = { ...input.state }; if (result.uiOutput !== null) { const nextDocument = options.parseOutput?.(result.uiOutput) ?? parseSkinExtensionUiOutput(result.uiOutput); + await options.onOutput?.(result.uiOutput, nextDocument, input); output = result.uiOutput; document = nextDocument; - await options.onOutput?.(output, nextDocument, input); } + lastState = { ...input.state }; return true; } catch (error) { if (!closed) report(error); diff --git a/web/src/services/skin-pack.test.ts b/web/src/services/skin-pack.test.ts index 1928cb7..5a8fe3d 100644 --- a/web/src/services/skin-pack.test.ts +++ b/web/src/services/skin-pack.test.ts @@ -48,6 +48,7 @@ test("skin CSS permits visual decoration but prevents layout, text-flow, and con assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/); await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout")); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { d\\69splay: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout")); await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { position: fixed; inset: 0; z-index: 99999; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout")); await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.member"] { padding: 30px; transform: scale(1.2); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout")); await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { font-size: 3rem; line-height: 1; white-space: nowrap; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout")); @@ -62,6 +63,9 @@ test("skin CSS permits visual decoration but prevents layout, text-flow, and con await assert.rejects(importSkinPack(makeSkin(".internal-class { color: red; }")), (error: unknown) => error instanceof Error && error.message.includes("must use :root")); await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.voice-card"].private-component { color: red; }')), (error: unknown) => error instanceof Error && error.message.includes("must use :root")); await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: image-set("https://example.invalid/remote.png" 1x); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE"); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: u\\72l("https://example.invalid/escaped.png"); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE"); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: u\\72l(h\\74 tps\\3a //example.invalid/escaped-scheme.png); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE"); + await assert.rejects(importSkinPack(makeSkin('@font-face { font-family: "Local Font"; src: l\\6f cal("Arial"); } [data-ws-part="home"] { color: teal; }')), (error: unknown) => error instanceof Error && error.message.includes("local() is not allowed")); }); test("custom skins can override theme appearance without !important or private class selectors", () => { diff --git a/web/src/services/skin-pack.ts b/web/src/services/skin-pack.ts index 9166a18..f082c54 100644 --- a/web/src/services/skin-pack.ts +++ b/web/src/services/skin-pack.ts @@ -1,7 +1,6 @@ -import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss"; -import selectorParser from "postcss-selector-parser"; -import valueParser from "postcss-value-parser"; import { unzipSync } from "fflate"; +import { compileSkinCss as compileSharedSkinCss, rewriteSkinCssAssets, SkinCssValidationError } from "../../../src/shared/skin-css.js"; + import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js"; import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js"; import { validateSkinExtensionWasmBytes, validateSkinExtensionWasmImportsAndExports } from "./skin-extension-wasm-policy.js"; @@ -21,43 +20,6 @@ const MAX_CSS_BYTES = 512 * 1024; const MAX_CONTENT_BYTES = 256 * 1024; const MAX_IMAGE_BYTES = 16 * 1024 * 1024; const MAX_FONT_BYTES = 4 * 1024 * 1024; -const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]); -const LAYOUT_AFFECTING_PROPERTIES = new Set([ - "all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline", - "width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size", - "min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing", - "gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x", - "overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility", - "pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate", - "perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name", - "container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font", - "font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap", - "text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim", - "line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift", - "box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing", - "writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content", - "position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope", -]); -const OPTIONAL_VISUAL_PARTS = new Set([ - "home.hero.eyebrow", - "home.gateway-status", - "home.features", - "home.feature", - "home.visitors", - "home.join-card.waveform", - "home.join-card.sonar", - "voice.activity-heading", - "voice.member.avatar", - "voice.member.live-indicator", - "voice.member-row.avatar", - "voice.screen-player.viewer-avatar", - "voice.screen-player.live", - "demo.badge", - "demo.wave", - "demo.avatar", - "demo.member-status", - "demo.note", -]); const ZIP_EOCD = 0x06054b50; const ZIP_CENTRAL_FILE = 0x02014b50; @@ -303,17 +265,14 @@ export async function importSkinPack(file: File): Promise { export function resolveSkinCssAssets(css: string, assets: Record): { css: string; objectUrls: string[] } { const objectUrls: string[] = []; try { - const root = postcss.parse(css, { from: undefined }); - root.walkDecls((declaration) => { - declaration.value = rewriteAssetUrls(declaration.value, (assetPath) => { + const rewritten = rewriteSkinCssAssets(css, (assetPath) => { const blob = assets[assetPath]; if (!blob) throw new SkinPackError(`Skin asset is missing: ${assetPath}`, "SKIN_ASSET_MISSING"); const url = URL.createObjectURL(blob); objectUrls.push(url); return url; - }); }); - return { css: root.toString(), objectUrls }; + return { css: rewritten, objectUrls }; } catch (error) { objectUrls.forEach((url) => URL.revokeObjectURL(url)); throw error; @@ -561,306 +520,15 @@ function parseContent(bytes: Uint8Array): SkinContent { } function compileSkinCss(source: string, id: string, assets: Record, schemaVersion: SkinManifest["schemaVersion"], pluginId?: string): { css: string; warnings: string[] } { - const size = new TextEncoder().encode(source).byteLength; - if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE"); - let root: postcss.Root; - try { root = postcss.parse(source, { from: undefined }); } - catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); } - - const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`; - const scope = pluginId - ? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]` - : skinScope; - const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`; - const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone()); - const warnings = new Set(); - const keyframeNames = new Map(); - const fontFamilyNames = new Map(); - const hideableRules = new WeakSet(); - let nodeCount = 0; - root.walk((node) => { - nodeCount += 1; - if (nodeCount > 12000) throw new SkinPackError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY"); - }); - - root.walkAtRules((rule: AtRule) => { - const name = rule.name.toLowerCase(); - if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`); - if (name.endsWith("keyframes")) { - const keyframeName = rule.params.trim(); - if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers."); - keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`); - rule.params = `${namespace}-${keyframeName}`; - } else if (name === "layer") { - const layers = rule.params.split(",").map((layer) => layer.trim()); - if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) { - throw rule.error("Skin CSS must use named @layer values so layer names can be isolated."); - } - rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", "); - } else if (name === "font-face") { - if (/\blocal\s*\(/i.test(rule.toString())) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package."); - const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family"); - if (!family) throw rule.error("Each @font-face rule must declare font-family."); - const originalFamily = parseSingleFontFamily(family.value); - const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`; - fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily); - family.value = `"${scopedFamily}"`; - } - }); - - root.walkRules((rule: Rule) => { - if (hasKeyframesAncestor(rule)) return; - if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors."); - if (!pluginId && !selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface."); - if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule); - try { - rule.selector = selectorParser((selectors) => { - selectors.each((selector) => { - const text = selector.toString().trim(); - if (!text) throw new SkinPackError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR"); - if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinPackError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR"); - if (/^:root\b/.test(text)) { - selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone()); - return; - } - selector.prepend(selectorParser.combinator({ value: " " })); - for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone()); - }); - }).processSync(rule.selector); - } catch (error) { - if (error instanceof SkinPackError) throw error; - throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`); - } - }); - - const referencedKeyframes = new Set(); - const nonOptionalKeyframes = new Set(); - root.walkRules((rule: Rule) => { - if (hasKeyframesAncestor(rule)) return; - const optionalTarget = hideableRules.has(rule); - rule.walkDecls((declaration: Declaration) => { - const property = declaration.prop.toLowerCase(); - if (property !== "animation" && property !== "animation-name") return; - const value = declaration.value; - if (/\b(?:var|attr)\s*\(|\\/i.test(value)) { - keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name)); - return; - } - for (const name of keyframeNames.keys()) { - if (!referencesCssIdentifier(value, name)) continue; - referencedKeyframes.add(name); - if (!optionalTarget) nonOptionalKeyframes.add(name); - } - }); - }); - const optionalOnlyKeyframes = new Set([...referencedKeyframes] - .filter((name) => !nonOptionalKeyframes.has(name)) - .map((name) => keyframeNames.get(name)!)); - - root.walkDecls((declaration: Declaration) => { - const property = declaration.prop.toLowerCase(); - const value = declaration.value.trim(); - const owningRule = findOwningRule(declaration); - const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null; - const canHideTarget = owningRule - ? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim())) - : false; - if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property) - && !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) { - throw declaration.error(pluginId - ? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.` - : "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens."); - } - if (schemaVersion < 3 && isLayoutAffectingProperty(property)) { - throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry."); - } - if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing."); - if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) { - throw declaration.error("Executable CSS values are not allowed."); - } - const compactValue = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("").toLowerCase(); - if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) { - if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts."); - } - const removesVisual = property === "all" - || (property === "display" && compactValue === "none") - || (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue)) - || (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue)) - || (property === "pointer-events" && compactValue === "none") - || (property === "clip-path" && /inset\(\s*50%/.test(compactValue)) - || (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue)); - if (removesVisual && !canHideTarget && schemaVersion < 3) { - throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available."); - } - const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(value)) - || (property === "clip-path" && /inset\(\s*50%/i.test(value)) - || (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(value)); - if (visuallyRemoves && !canHideTarget && schemaVersion < 3) { - throw declaration.error("Only explicitly optional visual parts may be visually removed."); - } - if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls."); - if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${value}`) || (property === "position" && value === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile."); - const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames); - declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => { - const blob = assets[assetPath]; - if (!blob) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`); - return `wskin-asset:${encodeURIComponent(assetPath)}`; - }); - }); - - return { css: root.toString(), warnings: [...warnings] }; -} - -function targetsOnlyOptionalVisualParts(selector: string): boolean { - try { - const parsed = selectorParser().astSync(selector); - return parsed.nodes.length > 0 && parsed.nodes.every((item) => { - if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false; - const attribute = item.nodes[0]; - if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false; - const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, ""); - return OPTIONAL_VISUAL_PARTS.has(part); - }); - } catch { - return false; + try { return compileSharedSkinCss(source, id, assets, schemaVersion, pluginId); } + catch (error) { + const cssError = error instanceof SkinCssValidationError + ? error + : new SkinCssValidationError(error instanceof Error ? error.message : "The CSS file is invalid.", "SKIN_CSS_INVALID"); + throw new SkinPackError(cssError.message, cssError.code); } } -function selectorUsesPublicHook(selector: string, allowCustomClasses = false): boolean { - try { - const parsed = selectorParser().astSync(selector); - return parsed.nodes.length > 0 && parsed.nodes.every((item) => { - let scoped = false; - let usesPrivateName = false; - item.walk((node) => { - if (node.type === "attribute" && ["data-ws-part", "data-ws-page", ...(allowCustomClasses ? ["data-ws-plugin-part"] : [])].includes(node.attribute.toLowerCase())) scoped = true; - if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true; - if (!allowCustomClasses && (node.type === "class" || node.type === "id")) usesPrivateName = true; - }); - return scoped && !usesPrivateName; - }); - } catch { - return false; - } -} - -function isLayoutAffectingProperty(property: string): boolean { - const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); - if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true; - if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true; - if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true; - if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true; - return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed); -} - -function findOwningRule(node: Node): Rule | null { - let parent = node.parent; - while (parent && parent.type !== "root") { - if (parent.type === "rule") return parent as Rule; - parent = parent.parent; - } - return null; -} - -function findKeyframesRule(rule: Rule): AtRule | null { - let parent = rule.parent; - while (parent && parent.type !== "root") { - if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule; - parent = parent.parent; - } - return null; -} - -function referencesCssIdentifier(value: string, identifier: string): boolean { - const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value); -} - -function rewriteAssetUrls(value: string, resolve: (path: string) => string): string { - const parsed = valueParser(value); - const resolvePackageAsset = (rawValue: string): string => { - const raw = rawValue.trim(); - if (!raw || raw.startsWith("#")) throw new SkinPackError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE"); - const isInternalMarker = raw.startsWith("wskin-asset:"); - if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinPackError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE"); - let path: string; - try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); } - catch { throw new SkinPackError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); } - return resolve(path); - }; - const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => { - for (const node of nodes) { - if (node.type === "function" && node.value.toLowerCase() === "url") { - const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim(); - node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }]; - node.before = ""; - node.after = ""; - continue; - } - if (node.type === "function" && (node.value.toLowerCase() === "image-set" || node.value.toLowerCase() === "-webkit-image-set")) { - for (const child of node.nodes) { - if (child.type === "string") child.value = resolvePackageAsset(child.value); - else if (child.type === "function") visit([child]); - } - continue; - } - if (node.type === "function") visit(node.nodes, inImageSet); - else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value); - } - }; - visit(parsed.nodes); - return parsed.toString(); -} - -function parseSingleFontFamily(value: string): string { - const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment"); - if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) { - throw new SkinPackError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY"); - } - return parsed[0].value.trim(); -} - -function rewriteScopedNames(value: string, property: string, keyframes: Map, fontFamilies: Map): string { - const parsed = valueParser(value); - if (["animation", "animation-name", "font", "font-family"].includes(property)) { - parsed.walk((node) => { - if (node.type !== "word" && node.type !== "string") return; - const keyframe = keyframes.get(node.value); - if (keyframe) node.value = keyframe; - const family = fontFamilies.get(node.value.toLowerCase()); - if (family) node.value = family; - }); - } - return parsed.toString(); -} - -function normalizeAssetPath(raw: string): string { - let path = raw.split(/[?#]/, 1)[0]; - try { path = decodeURIComponent(path); } catch { throw new SkinPackError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); } - if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinPackError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH"); - const segments: string[] = []; - for (const segment of path.split("/")) { - if (!segment || segment === ".") continue; - if (segment === "..") { - if (!segments.length) throw new SkinPackError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH"); - segments.pop(); - } else { - segments.push(segment); - } - } - if (!segments.length) throw new SkinPackError("An asset URL must point to a package file.", "SKIN_ASSET_PATH"); - return segments.join("/"); -} - -function hasKeyframesAncestor(rule: Rule): boolean { - let parent = rule.parent; - while (parent && parent.type !== "root") { - if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true; - parent = parent.parent; - } - return false; -} - function assetMimeType(path: string): string | null { const extension = path.split(".").at(-1)?.toLowerCase(); switch (extension) { diff --git a/web/src/services/skin-plugin-asset-urls.test.ts b/web/src/services/skin-plugin-asset-urls.test.ts index 677f13d..5275727 100644 --- a/web/src/services/skin-plugin-asset-urls.test.ts +++ b/web/src/services/skin-plugin-asset-urls.test.ts @@ -58,3 +58,33 @@ test("a missing plugin asset releases a cached URL instead of returning stale ar URL.revokeObjectURL = originalRevoke; } }); + +test("plugin asset URLs are released when their final component reference is removed", () => { + const originalCreate = URL.createObjectURL; + const originalRevoke = URL.revokeObjectURL; + const created: string[] = []; + const revoked: string[] = []; + URL.createObjectURL = () => { + const url = `blob:skin-retain-${created.length + 1}`; + created.push(url); + return url; + }; + URL.revokeObjectURL = (url) => { revoked.push(url); }; + + try { + const cache = createSkinPluginAssetUrlCache(); + cache.resolve("assets/used.png", { "assets/used.png": new Blob(["used"]) }); + cache.resolve("assets/removed.png", { "assets/removed.png": new Blob(["removed"]) }); + + cache.retain(["assets/used.png"]); + assert.deepEqual(revoked, ["blob:skin-retain-2"]); + assert.equal(cache.size, 1); + + cache.retain([]); + assert.deepEqual(revoked, ["blob:skin-retain-2", "blob:skin-retain-1"]); + assert.equal(cache.size, 0); + } finally { + URL.createObjectURL = originalCreate; + URL.revokeObjectURL = originalRevoke; + } +}); diff --git a/web/src/services/skin-plugin-asset-urls.ts b/web/src/services/skin-plugin-asset-urls.ts index e08bd10..e56d895 100644 --- a/web/src/services/skin-plugin-asset-urls.ts +++ b/web/src/services/skin-plugin-asset-urls.ts @@ -26,6 +26,10 @@ export function createSkinPluginAssetUrlCache() { clear(): void { for (const path of urls.keys()) release(path); }, + retain(paths: Iterable): void { + const retained = new Set(paths); + for (const path of urls.keys()) if (!retained.has(path)) release(path); + }, get size(): number { return urls.size; }, }; } diff --git a/web/src/services/skin-plugin-authoring.test.ts b/web/src/services/skin-plugin-authoring.test.ts index a4681a8..ea1f8a5 100644 --- a/web/src/services/skin-plugin-authoring.test.ts +++ b/web/src/services/skin-plugin-authoring.test.ts @@ -13,7 +13,7 @@ import { removeSkinPluginNode, replaceSkinPluginNode, } from "../../../src/shared/skin-plugin-editor.js"; -import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js"; +import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js"; import { clearSkinPluginAuthoringDocument, exportSkinPluginAuthoringDocument, @@ -101,7 +101,7 @@ test("component order is editable and stays within the selected skin document", test("duplicating a nested component node gives copied layout parts unique stable IDs", () => { const source = document(); source.components[0].root.children![0] = { - tag: "div", part: "message", children: [{ tag: "span", part: "author", text: "Author" }], + tag: "div", part: "message", children: [{ tag: "span", part: "author", children: [{ text: "Author" }] }], }; const copy = duplicateSkinPluginNode(source, "voice-panel", [0]); assert.equal(copy.part, "message-copy"); @@ -109,6 +109,24 @@ test("duplicating a nested component node gives copied layout parts unique stabl assert.throws(() => duplicateSkinPluginNode(source, "voice-panel", []), /root cannot be duplicated/i); }); +test("repeated node duplication skips existing layout part IDs", () => { + const source = document(); + source.components[0].root.children = [ + { tag: "div", part: "message", children: [{ tag: "span", part: "author" }] }, + { tag: "div", part: "message-copy", children: [{ tag: "span", part: "author-copy" }] }, + { tag: "div", part: "message-copy-2", children: [{ tag: "span", part: "author-copy-2" }] }, + ]; + + const first = duplicateSkinPluginNode(source, "voice-panel", [0]); + assert.equal(first.part, "message-copy-3"); + assert.equal(first.children?.[0].part, "author-copy-3"); + + const withFirstCopy = addSkinPluginNodeSibling(source, "voice-panel", [0], first); + const second = duplicateSkinPluginNode(withFirstCopy, "voice-panel", [0]); + assert.equal(second.part, "message-copy-4"); + assert.equal(second.children?.[0].part, "author-copy-4"); +}); + test("component editor rejects unsafe markup and invalid permission/action combinations", () => { assert.throws(() => addSkinPluginNode(document(), "voice-panel", [], { tag: "script" }), /unsupported HTML element/i); assert.throws(() => replaceSkinPluginNode(document(), "voice-panel", [0], { @@ -124,11 +142,23 @@ test("component editor rejects unsafe markup and invalid permission/action combi }); test("older package trees upgrade to editable schema v3 without losing their component", () => { - const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument; - const editable = editableSkinPluginDocument(legacy); - assert.equal(editable.schemaVersion, 3); - assert.equal(editable.components[0].root.tag, "section"); + for (const schemaVersion of [1, 2]) { + const legacy = { ...document(), schemaVersion } as unknown as SkinPluginDocument; + const editable = editableSkinPluginDocument(legacy); + assert.equal(editable.schemaVersion, 3); + assert.equal(editable.components[0].root.tag, "section"); + } + const normalizedV1 = parseSkinPluginDocument({ ...document(), schemaVersion: 1 }); + assert.equal(normalizedV1.components[0].mode, "widget", "the package parser materializes the schema-v1 default mode"); + assert.equal(editableSkinPluginDocument(normalizedV1).schemaVersion, 3, + "revalidating a normalized legacy package must safely strip the parser-generated default before migration"); + assert.throws(() => parseSkinPluginDocument({ + ...document(), schemaVersion: 1, + components: [{ ...document().components[0], mode: "surface" }], + }), /Page surfaces require components schema version 2/i); + + const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument; const legacyWithWidget = structuredClone(legacy); legacyWithWidget.components[0].permissions = []; legacyWithWidget.components[0].root = { tag: "section", children: [{ widget: "voice.audio-controls" }] }; diff --git a/web/src/services/skin-runtime-plugin-wasm-governor.test.ts b/web/src/services/skin-runtime-plugin-wasm-governor.test.ts index d9cc380..0a33e5e 100644 --- a/web/src/services/skin-runtime-plugin-wasm-governor.test.ts +++ b/web/src/services/skin-runtime-plugin-wasm-governor.test.ts @@ -45,3 +45,51 @@ test("Wasm worker governor rejects queued work after the bounded wait", async () assert.equal(governor.pendingRuns, 0); release(); }); + +test("Wasm worker governor stays bounded and drains a saturated burst in FIFO order", async () => { + const maxConcurrentRuns = 2; + const maxPendingRuns = 64; + const burstSize = 2_000; + const governor = createSkinRuntimePluginWasmGovernor({ + maxConcurrentRuns, + maxPendingRuns, + queueTimeoutMs: 10_000, + }); + const started: number[] = []; + let active = 0; + let peakActive = 0; + const acquisitions = Array.from({ length: burstSize }, (_, index) => governor.acquire(new AbortController().signal) + .then((release) => { + active += 1; + peakActive = Math.max(peakActive, active); + started.push(index); + return { + index, + release: () => { + active -= 1; + release(); + }, + }; + }, (error: unknown) => ({ index, error }))); + + assert.equal(governor.activeRuns, maxConcurrentRuns); + assert.equal(governor.pendingRuns, maxPendingRuns); + const overflow = await Promise.all(acquisitions.slice(maxConcurrentRuns + maxPendingRuns)); + assert.equal(overflow.length, burstSize - maxConcurrentRuns - maxPendingRuns); + assert.ok(overflow.every((item) => "error" in item + && item.error instanceof SkinRuntimePluginWasmGovernorError + && item.error.code === "SKIN_EXTENSION_WASM_QUEUE_FULL")); + + for (let index = 0; index < maxConcurrentRuns + maxPendingRuns; index += maxConcurrentRuns) { + const batch = await Promise.all(acquisitions.slice(index, index + maxConcurrentRuns)); + assert.ok(batch.every((item) => "release" in item)); + batch.forEach((item) => { + if ("release" in item) item.release(); + }); + } + + assert.deepEqual(started, Array.from({ length: maxConcurrentRuns + maxPendingRuns }, (_, index) => index)); + assert.equal(peakActive, maxConcurrentRuns); + assert.equal(governor.activeRuns, 0); + assert.equal(governor.pendingRuns, 0); +}); diff --git a/web/src/services/skin-runtime-plugin-wasm.test.ts b/web/src/services/skin-runtime-plugin-wasm.test.ts index 018ed64..347ba22 100644 --- a/web/src/services/skin-runtime-plugin-wasm.test.ts +++ b/web/src/services/skin-runtime-plugin-wasm.test.ts @@ -198,3 +198,43 @@ test("approved Wasm entries run as disposable workers with bounded interpreter o else Reflect.deleteProperty(globalThis, "window"); } }); + +test("a worker that exceeds the execution deadline is terminated and releases its handle", async () => { + const { files, approval } = await approvedFiles(); + const previousWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker"); + const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window"); + let terminated = 0; + class HangingWorker { + onmessage: ((event: MessageEvent) => void) | null = null; + onmessageerror: (() => void) | null = null; + onerror: (() => void) | null = null; + postMessage(): void { + queueMicrotask(() => this.onmessage?.({ data: { type: "running" } } as MessageEvent)); + } + terminate(): void { terminated += 1; } + } + Object.defineProperty(globalThis, "Worker", { configurable: true, value: HangingWorker }); + Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } }); + try { + const handle = await createSkinRuntimePluginWasmSandbox({ + skinId: "community.sample", + skinVersion: "2.0.0", + plugin, + approval, + files, + readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }), + }); + await handle.ready; + await assert.rejects(handle.result, (error: unknown) => + error instanceof Error && "code" in error && error.code === "SKIN_EXTENSION_WASM_EXECUTION_TIMEOUT"); + await handle.stopped; + assert.equal(handle.closeReason, "execution-timeout"); + assert.equal(handle.closed, true); + assert.equal(terminated, 1, "the host must terminate the worker when its execution deadline expires"); + } finally { + if (previousWorker) Object.defineProperty(globalThis, "Worker", previousWorker); + else Reflect.deleteProperty(globalThis, "Worker"); + if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow); + else Reflect.deleteProperty(globalThis, "window"); + } +}); diff --git a/web/src/services/skin-wasm-interpreter.test.ts b/web/src/services/skin-wasm-interpreter.test.ts index 583292d..b8c65f2 100644 --- a/web/src/services/skin-wasm-interpreter.test.ts +++ b/web/src/services/skin-wasm-interpreter.test.ts @@ -4,6 +4,8 @@ import test from "node:test"; import { createSkinExtensionWasmCappedRunProbe, createSkinExtensionWasmInfiniteRunProbe, + createSkinExtensionWasmLargeUiOutputProbe, + createSkinExtensionWasmOversizedUiOutputProbe, createSkinExtensionWasmPrefixByteImmediateProbe, createSkinExtensionWasmUiInputProbe, createSkinExtensionWasmUiOutputProbe, @@ -88,6 +90,12 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at "the interpreter must accept payloads larger than the previous 16 KiB cap"); assert.equal(run(createSkinExtensionWasmUiOutputProbe('{"type":"root"}', true)).error, 12, "the interpreter must reject more than one UI payload per execution"); + const largeUiOutput = `{"text":"${"x".repeat(240 * 1024)}"}`; + const largeUiResult = run(createSkinExtensionWasmLargeUiOutputProbe(240 * 1024)); + assert.equal(largeUiResult.error, 0, "the interpreter must accept a large payload that remains under the output limit"); + assert.equal(largeUiResult.uiOutput, largeUiOutput); + assert.equal(run(createSkinExtensionWasmOversizedUiOutputProbe()).error, 12, + "the interpreter must reject UI output beyond its 256 KiB cap before copying it"); const memory = runtime.memory; const currentPages = memory.buffer.byteLength / (64 * 1024); diff --git a/web/test/skin-extension-wasm-fixture.ts b/web/test/skin-extension-wasm-fixture.ts index 780ce54..98ddedc 100644 --- a/web/test/skin-extension-wasm-fixture.ts +++ b/web/test/skin-extension-wasm-fixture.ts @@ -96,6 +96,69 @@ export function createSkinExtensionWasmUiOutputProbe(output = '{"type":"root"}', ]); } +/** Calls the UI bridge with a payload length just beyond its 256 KiB output cap. */ +export function createSkinExtensionWasmOversizedUiOutputProbe(): Uint8Array { + const oversizedLength = 256 * 1024 + 1; + const body = [ + 0, + 0x41, 0x00, + 0x41, ...signedLeb128(oversizedLength), + 0x10, 0x00, + 0x1a, + 0x41, 0x07, + 0x0b, + ]; + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, [2, 0x60, 2, 0x7f, 0x7f, 1, 0x7f, 0x60, 0, 1, 0x7f]), + ...section(2, [ + 2, + ...name("env"), ...name("memory"), 0x02, 0x01, 1, 64, + ...name("env"), ...name("ui_emit_json"), 0x00, 0, + ]), + ...section(3, [1, 1]), + ...section(7, [1, ...name("run"), 0, 1]), + ...section(10, [1, body.length, ...body]), + ]); +} + +/** Grows bounded guest memory, fills a large JSON payload, and emits it through the host bridge. */ +export function createSkinExtensionWasmLargeUiOutputProbe(fillerLength: number): Uint8Array { + const outputPointer = 16; + const prefix = Array.from(new TextEncoder().encode('{"text":"')); + const fillerPointer = outputPointer + prefix.length; + const suffixPointer = fillerPointer + fillerLength; + const outputLength = prefix.length + fillerLength + 2; + const body = [ + 0, + 0x41, 0x03, 0x40, 0x00, 0x1a, + 0x41, ...signedLeb128(fillerPointer), + 0x41, ...signedLeb128(0x78), + 0x41, ...signedLeb128(fillerLength), + 0xfc, 0x0b, 0x00, + 0x41, ...signedLeb128(suffixPointer), 0x41, ...signedLeb128(0x22), 0x3a, 0x00, 0x00, + 0x41, ...signedLeb128(suffixPointer + 1), 0x41, ...signedLeb128(0x7d), 0x3a, 0x00, 0x00, + 0x41, ...signedLeb128(outputPointer), + 0x41, ...signedLeb128(outputLength), + 0x10, 0x00, 0x1a, + 0x41, 0x07, + 0x0b, + ]; + return Uint8Array.from([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, + ...section(1, [2, 0x60, 2, 0x7f, 0x7f, 1, 0x7f, 0x60, 0, 1, 0x7f]), + ...section(2, [ + 2, + ...name("env"), ...name("memory"), 0x02, 0x01, 1, 64, + ...name("env"), ...name("ui_emit_json"), 0x00, 0, + ]), + ...section(3, [1, 1]), + ...section(7, [1, ...name("run"), 0, 1]), + ...section(10, [1, body.length, ...body]), + ...section(11, [1, 0, 0x41, outputPointer, 0x0b, ...unsignedLeb128(prefix.length), ...prefix]), + ]); +} + /** Reads the host-provided bounded local state/event JSON once and echoes it through UI output. */ export function createSkinExtensionWasmUiInputProbe(readTwice = false): Uint8Array { const readInput = [ diff --git a/web/test/skin-layout-runtime.test.mjs b/web/test/skin-layout-runtime.test.mjs index abcb272..081defe 100644 --- a/web/test/skin-layout-runtime.test.mjs +++ b/web/test/skin-layout-runtime.test.mjs @@ -115,3 +115,41 @@ test("a local order override is applied only to the registered element", () => { assert.equal(pluginRoot.dataset.wsLayoutOrder, "true"); assert.equal(pluginRoot.style.values.get("--ws-layout-order"), "3"); }); + +test("arbitrary component nodes accept local layout edits while interactive nodes keep a 44px target", () => { + const root = new FakeElement(); + root.dataset.wsPage = "home"; + root.dataset.wsSkin = "test.skin"; + const content = append(root, new FakeElement()); + content.dataset.wsPart = "skin.home.demo-banner.node-root-0"; + const button = append(root, new FakeElement()); + button.dataset.wsPart = "skin.home.demo-banner.control-node-root-1"; + + const collection = JSON.stringify({ + schemaVersion: 2, + skins: { + "test.skin": { + schemaVersion: 1, + pages: { home: { desktop: { + "skin.home.demo-banner.node-root-0": { x: 24, y: 36, width: 280, height: 96, visible: false }, + "skin.home.demo-banner.control-node-root-1": { order: 5 }, + } } }, + }, + }, + recoveries: {}, + }); + setGlobal("localStorage", { getItem: () => collection, setItem: () => undefined }); + setGlobal("document", { querySelectorAll: () => [root] }); + setGlobal("window", { matchMedia: () => ({ matches: false }) }); + + runtime.refreshSkinLayout(); + + assert.equal(content.dataset.wsLayoutActive, "true"); + assert.equal(content.dataset.wsLayoutHidden, "true"); + assert.equal(content.style.values.get("--ws-layout-x"), "24px"); + assert.equal(content.style.values.get("--ws-layout-y"), "36px"); + assert.equal(content.style.values.get("--ws-layout-width"), "280px"); + assert.equal(content.style.values.get("--ws-layout-height"), "96px"); + assert.equal(button.style.values.get("--ws-layout-order"), "5"); + assert.equal(button.dataset.wsLayoutTouchTarget, "44"); +}); diff --git a/web/test/skin-plugin-editor.test.mjs b/web/test/skin-plugin-editor.test.mjs index 91cfb0d..85cabaf 100644 --- a/web/test/skin-plugin-editor.test.mjs +++ b/web/test/skin-plugin-editor.test.mjs @@ -8,6 +8,7 @@ import { createRenderer, nextTick, ssrContextKey, createSSRApp } from "vue"; import { renderToString } from "@vue/server-renderer"; import { createServer } from "vite"; import vuePlugin from "@vitejs/plugin-vue"; +import { SKIN_PLUGIN_ALLOWED_ELEMENTS } from "../../src/shared/skin-plugin.js"; let vite; let SkinPluginEditor; @@ -15,6 +16,7 @@ let SkinPluginOutlet; let authoring; let approvals; let focusedNode; +let supportsPopoverApi = true; const localStorageDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); class MemoryStorage { @@ -24,18 +26,25 @@ class MemoryStorage { removeItem(key) { this.values.delete(key); } } -const hostNode = (tag, type = "element") => ({ - tag, type, props: {}, text: "", children: [], parent: null, value: "", listeners: new Map(), focus() { focusedNode = this; }, - addEventListener(name, listener) { - const listeners = this.listeners.get(name) ?? []; - listeners.push(listener); - this.listeners.set(name, listeners); - }, - removeEventListener(name, listener) { - this.listeners.set(name, (this.listeners.get(name) ?? []).filter(candidate => candidate !== listener)); - }, - dispatchEvent(event) { for (const listener of this.listeners.get(event.type) ?? []) listener(event); }, -}); +const hostNode = (tag, type = "element") => { + const node = { + tag, type, props: {}, text: "", children: [], parent: null, value: "", listeners: new Map(), popoverOpen: false, + focus() { focusedNode = this; }, + setAttribute(name, value) { this.props[name] = value; }, + removeAttribute(name) { delete this.props[name]; }, + addEventListener(name, listener) { + const listeners = this.listeners.get(name) ?? []; + listeners.push(listener); + this.listeners.set(name, listeners); + }, + removeEventListener(name, listener) { + this.listeners.set(name, (this.listeners.get(name) ?? []).filter(candidate => candidate !== listener)); + }, + dispatchEvent(event) { for (const listener of this.listeners.get(event.type) ?? []) listener(event); }, + }; + if (supportsPopoverApi) node.showPopover = function () { this.popoverOpen = true; }; + return node; +}; const teleportRoot = hostNode("teleport-root"); function insert(child, parent, anchor = null) { if (child.parent) { @@ -184,88 +193,146 @@ test("component editor creates, changes, and deletes a skin component tree throu page: "voice", lang: "zh", }; - const html = await renderToString(createSSRApp(SkinPluginEditor, props)); - assert.match(html, /组件结构/); + const ssrContext = {}; + const html = await renderToString(createSSRApp(SkinPluginEditor, props), ssrContext); + assert.doesNotMatch(html, /组件结构/); + assert.match(ssrContext.teleports.body, /组件结构/, + "the editor controls are teleported outside the skin-rendered DOM tree"); const root = hostNode("root"); - const app = renderer.createApp(SkinPluginEditor, props); + const hostView = Vue.defineComponent({ + setup() { + return () => Vue.h("main", { class: "ws-skin-root", "data-ws-skin": props.skinId }, [ + Vue.h(SkinPluginEditor, props), + ]); + }, + }); + const app = renderer.createApp(hostView); app.provide(ssrContextKey, { modules: new Set() }); app.mount(root); try { - clickButton(root, "组件结构"); + assert.equal(visit(root, node => node.props["data-ws-plugin-editor"] !== undefined), null, + "skin CSS cannot target the host-owned component editor"); + const teleportedEditor = visit(teleportRoot, node => node.props["data-ws-plugin-editor"] !== undefined); + assert.ok(teleportedEditor); + await nextTick(); + assert.equal(teleportedEditor.popoverOpen, true, + "browsers with the Popover API keep the host editor above skin-authored stacking layers"); + clickButton(teleportRoot, "组件结构"); await nextTick(); await nextTick(); - assert.equal(app._instance.setupState.open, true, "the trigger opens the editor"); assert.equal(focusedNode?.props["aria-label"], "关闭", "opening moves keyboard focus to the close control"); - assert.equal(visit(root, node => node.tag === "button" && nodeText(node).trim() === "组件结构")?.props["aria-expanded"], true); - clickButton(root, "新增组件"); + assert.equal(visit(teleportRoot, node => node.tag === "button" && nodeText(node).trim() === "组件结构")?.props["aria-expanded"], true); + clickButton(teleportRoot, "新增组件"); await nextTick(); const key = authoring.getSkinPluginAuthoringStorageKey("community.example", "1.0.0"); let edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.equal(edited.components.length, 2); assert.equal(edited.components[1].id, "custom-component-1"); - clickButton(root, "组件上移"); + changeSelect(teleportRoot, 1, "root"); + await nextTick(); + assert.match(nodeText(teleportRoot), /节点定义/, "the root node has a distinct selectable entry in the tree"); + editTextarea(teleportRoot, JSON.stringify({ tag: "article", children: [{ text: "新建组件" }] }, null, 2)); + await nextTick(); + clickButton(teleportRoot, "应用定义"); + await nextTick(); + edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); + assert.equal(edited.components[1].root.tag, "article", + "selecting the root lets authors replace it through the ordinary node editor"); + + changeSelect(teleportRoot, 2, "button"); + await nextTick(); + const nodeTypeOptions = visit(teleportRoot, node => node.tag === "select" && node.props["aria-label"] === "新增节点类型"); + assert.ok(nodeTypeOptions.children.some(option => option.props.value === "svg"), + "the node type picker exposes the shared safe element set, including SVG"); + + clickButton(teleportRoot, "组件上移"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.deepEqual(edited.components.map(component => component.id), ["custom-component-1", "base-panel"]); - clickButton(root, "添加子节点"); + clickButton(teleportRoot, "添加子节点"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.equal(edited.components[0].root.children.length, 2); + assert.equal(edited.components[0].root.children[1].tag, "button", + "authors can add a selected safe element directly instead of hand-writing its node JSON"); assert.ok(localStorage.getItem(key)); - changeSelect(root, 1, "0"); + clickButton(teleportRoot, "复制节点"); await nextTick(); - editTextarea(root, JSON.stringify({ text: "Edited in the component editor" }, null, 2)); + edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); + assert.equal(edited.components[0].root.children.length, 3, "the editor duplicates the selected node as a sibling"); + clickButton(teleportRoot, "节点上移"); await nextTick(); - clickButton(root, "应用定义"); + edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); + assert.equal(edited.components[0].root.children[1].tag, "button", "the selected node moves within its parent"); + clickButton(teleportRoot, "节点下移"); + await nextTick(); + changeSelect(teleportRoot, 2, "text"); + await nextTick(); + clickButton(teleportRoot, "添加同级节点"); + await nextTick(); + edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); + assert.equal(edited.components[0].root.children.length, 4, "the editor adds a sibling beside the selected node"); + assert.equal(edited.components[0].root.children[3].text, "新建内容", + "text nodes are available through the same authoring flow"); + clickButton(teleportRoot, "删除节点"); + await nextTick(); + edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); + assert.equal(edited.components[0].root.children.length, 3, "the editor deletes the selected node without deleting its parent"); + + changeSelect(teleportRoot, 1, "0"); + await nextTick(); + editTextarea(teleportRoot, JSON.stringify({ text: "Edited in the component editor" }, null, 2)); + await nextTick(); + clickButton(teleportRoot, "应用定义"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.equal(edited.components[0].root.children[0].text, "Edited in the component editor"); - clickButton(root, "撤销"); + clickButton(teleportRoot, "撤销"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.equal(edited.components[0].root.children[0].text, "新建组件"); - clickButton(root, "重做"); + clickButton(teleportRoot, "重做"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.equal(edited.components[0].root.children[0].text, "Edited in the component editor"); - clickButton(root, "删除组件"); + clickButton(teleportRoot, "删除组件"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.deepEqual(edited.components.map(component => component.id), ["base-panel"]); - changeSelect(root, 0, "base-panel"); + changeSelect(teleportRoot, 0, "base-panel"); await nextTick(); - clickButton(root, "复制组件"); + clickButton(teleportRoot, "复制组件"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.deepEqual(edited.components.map(component => component.id), ["base-panel", "base-panel-2"]); - changeSelect(root, 0, "base-panel"); + changeSelect(teleportRoot, 0, "base-panel"); await nextTick(); - changeSelect(root, 1, "0"); + changeSelect(teleportRoot, 1, "0"); await nextTick(); - clickButton(root, "删除组件"); + clickButton(teleportRoot, "删除组件"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.deepEqual(edited.components.map(component => component.id), ["base-panel-2"]); - clickButton(root, "新增组件"); + clickButton(teleportRoot, "新增组件"); await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.equal(edited.components[1].id, "custom-component-1"); - assert.match(nodeText(root), /组件定义/, "creating after deleting a component from node mode selects the component definition"); - assert.match(visit(root, node => node.tag === "textarea").value, /"id": "custom-component-1"/); + assert.match(nodeText(teleportRoot), /组件定义/, "creating after deleting a component from node mode selects the component definition"); + assert.match(visit(teleportRoot, node => node.tag === "textarea").value, /"id": "custom-component-1"/); - changeSelect(root, 1, "0"); + changeSelect(teleportRoot, 1, "0"); await nextTick(); - const importInput = visit(root, node => node.tag === "input"); + const importInput = visit(teleportRoot, node => node.tag === "input"); assert.ok(importInput); const importedDocument = { schemaVersion: 3, @@ -278,16 +345,47 @@ test("component editor creates, changes, and deletes a skin component tree throu await nextTick(); edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0"); assert.deepEqual(edited.components.map(component => component.id), ["imported-panel"]); - assert.match(visit(root, node => node.tag === "textarea").value, /"id": "imported-panel"/, + assert.match(visit(teleportRoot, node => node.tag === "textarea").value, /"id": "imported-panel"/, "importing from node mode selects the imported component definition"); - const panel = visit(root, node => node.tag === "section" && node.props.role === "dialog"); + const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window"); + const previousCreateObjectURL = Object.getOwnPropertyDescriptor(URL, "createObjectURL"); + const previousRevokeObjectURL = Object.getOwnPropertyDescriptor(URL, "revokeObjectURL"); + let exportedBlob; + let downloadedUrl; + const downloadAnchor = { href: "", download: "", click() { downloadedUrl = this.href; } }; + Object.defineProperty(globalThis, "window", { + configurable: true, + value: { + document: { createElement: tag => { assert.equal(tag, "a"); return downloadAnchor; } }, + setTimeout: callback => { callback(); return 0; }, + }, + }); + Object.defineProperty(URL, "createObjectURL", { configurable: true, value: blob => { exportedBlob = blob; return "blob:skin-export"; } }); + Object.defineProperty(URL, "revokeObjectURL", { configurable: true, value: url => { assert.equal(url, "blob:skin-export"); } }); + try { + clickButton(teleportRoot, "导出 components.json"); + assert.equal(downloadAnchor.download, "community.example-components.json"); + assert.equal(downloadedUrl, "blob:skin-export", "the editor starts a local file download"); + assert.ok(exportedBlob instanceof Blob); + assert.deepEqual(authoring.importSkinPluginAuthoringDocument(await exportedBlob.text()), edited, + "the exported editor file round-trips through the same package validator"); + } finally { + if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow); + else Reflect.deleteProperty(globalThis, "window"); + if (previousCreateObjectURL) Object.defineProperty(URL, "createObjectURL", previousCreateObjectURL); + else Reflect.deleteProperty(URL, "createObjectURL"); + if (previousRevokeObjectURL) Object.defineProperty(URL, "revokeObjectURL", previousRevokeObjectURL); + else Reflect.deleteProperty(URL, "revokeObjectURL"); + } + + const panel = visit(teleportRoot, node => node.tag === "section" && node.props.role === "dialog"); assert.ok(panel); assert.equal(panel.props["aria-modal"], "false"); panel.props.onKeydown({ key: "Escape", preventDefault() {}, stopPropagation() {} }); await nextTick(); await nextTick(); - assert.equal(visit(root, node => node.tag === "section" && node.props.role === "dialog"), null, + assert.equal(visit(teleportRoot, node => node.tag === "section" && node.props.role === "dialog"), null, "Escape closes the editor dialog"); assert.equal(nodeText(focusedNode), "组件结构", "closing returns keyboard focus to the trigger"); } finally { @@ -295,6 +393,308 @@ test("component editor creates, changes, and deletes a skin component tree throu } }); +test("the node picker can create and delete every schema-safe element and text node", async () => { + Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() }); + const skinId = "community.node-picker"; + const skinVersion = "1.0.0"; + const baseDocument = { schemaVersion: 3, components: [] }; + const revision = Vue.ref(0); + const editorProps = { + skinId, + skinVersion, + page: "voice", + lang: "zh", + baseDocument, + }; + const view = Vue.defineComponent({ + setup() { + const currentDocument = () => { + revision.value; + return authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion) ?? baseDocument; + }; + return () => Vue.h("main", null, [ + Vue.h(SkinPluginOutlet, { + skinId, + skinVersion, + document: currentDocument(), + page: "voice", + data: {}, + assets: {}, + actions: {}, + }), + Vue.h(SkinPluginEditor, { ...editorProps, onUpdated: () => { revision.value += 1; } }), + ]); + }, + }); + const root = hostNode("root"); + const app = renderer.createApp(view); + app.provide(ssrContextKey, { modules: new Set() }); + app.mount(root); + + try { + clickButton(teleportRoot, "组件结构"); + await nextTick(); + await nextTick(); + clickButton(teleportRoot, "新增组件"); + await nextTick(); + + const picker = visit(teleportRoot, node => node.tag === "select" && node.props["aria-label"] === "新增节点类型"); + assert.ok(picker); + const choices = picker.children.filter(option => option.tag === "option").map(option => option.props.value); + assert.deepEqual(choices, ["text", ...SKIN_PLUGIN_ALLOWED_ELEMENTS], + "the editor picker stays in sync with the single schema allowlist"); + const renderedComponent = () => visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); + const countRendered = (node, predicate) => (predicate(node) ? 1 : 0) + node.children.reduce((count, child) => count + countRendered(child, predicate), 0); + + for (const type of choices) { + changeSelect(teleportRoot, 1, "root"); + await nextTick(); + changeSelect(teleportRoot, 2, type); + await nextTick(); + const initialComponentView = renderedComponent(); + assert.ok(initialComponentView); + const initialRoot = initialComponentView.children[0]; + const isNewText = node => node.type === "text" && node.text === "新建内容"; + const isSelectedTag = node => node.tag === type; + const initialCount = countRendered(initialRoot, type === "text" ? isNewText : isSelectedTag); + clickButton(teleportRoot, "添加子节点"); + await nextTick(); + + let edited = authoring.loadSkinPluginAuthoringDocument(skinId, "1.0.0"); + const added = edited.components[0].root.children.at(-1); + if (type === "text") assert.deepEqual(added, { text: "新建内容" }); + else assert.equal(added.tag, type, `the picker creates <${type}>`); + if (type === "img") assert.equal(added.attributes.alt, "皮肤图片"); + + const componentView = renderedComponent(); + assert.ok(componentView, "the edited component remains mounted in the page preview"); + const componentRoot = componentView.children[0]; + assert.equal(countRendered(componentRoot, type === "text" ? isNewText : isSelectedTag), initialCount + 1, + `adding ${type} updates the live preview`); + if (type === "text") { + assert.ok(visit(componentRoot, isNewText), "the authored text node is visible in the live preview"); + } else { + assert.ok(visit(componentRoot, node => node.tag === type && node.props["data-ws-part"]?.endsWith("node-root-1")), + `<${type}> receives a stable host layout target in the live preview`); + } + + clickButton(teleportRoot, "删除节点"); + await nextTick(); + edited = authoring.loadSkinPluginAuthoringDocument(skinId, "1.0.0"); + assert.equal(edited.components[0].root.children.length, 1, `the created ${type} node can be deleted`); + const afterDelete = renderedComponent()?.children[0]; + assert.equal(countRendered(afterDelete, type === "text" ? isNewText : isSelectedTag), initialCount, + `deleting ${type} restores the previous live preview`); + } + } finally { + app.unmount(); + } +}); + +test("corrupt local component edits can be cleared from the editor to restore package CRUD", async () => { + Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() }); + const skinId = "community.corrupt-edits"; + const skinVersion = "1.0.0"; + const key = authoring.getSkinPluginAuthoringStorageKey(skinId, skinVersion); + localStorage.setItem(key, "{not valid JSON"); + const props = { + skinId, + skinVersion, + page: "voice", + lang: "zh", + baseDocument: { + schemaVersion: 3, + components: [{ + id: "package-component", + name: "Package component", + page: "voice", + accessibleName: "Package component", + permissions: [], + actions: {}, + root: { tag: "section", children: [{ text: "Package content" }] }, + }], + }, + }; + const root = hostNode("root"); + const app = renderer.createApp(SkinPluginEditor, props); + app.provide(ssrContextKey, { modules: new Set() }); + app.mount(root); + + try { + clickButton(teleportRoot, "组件结构"); + await nextTick(); + await nextTick(); + assert.match(nodeText(teleportRoot), /本地修改无法通过校验/, + "the editor explains that this skin version has invalid saved edits"); + const resetButton = visit(teleportRoot, node => node.tag === "button" && nodeText(node).trim() === "清除本地修改"); + assert.ok(resetButton); + assert.equal(resetButton.props.disabled, false, "recovery remains enabled for corrupt saved edits"); + + clickButton(teleportRoot, "清除本地修改"); + await nextTick(); + assert.equal(localStorage.getItem(key), null, "recovery clears only this skin version's saved edits"); + assert.match(nodeText(teleportRoot), /本地修改已清除/); + + clickButton(teleportRoot, "新增组件"); + await nextTick(); + const recovered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion); + assert.deepEqual(recovered.components.map(component => component.id), ["package-component", "custom-component-1"], + "the package document is restored and normal component editing works again"); + } finally { + app.unmount(); + } +}); + +test("the first edit upgrades legacy v1 and v2 component packages to v3", async () => { + Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() }); + + for (const schemaVersion of [1, 2]) { + const skinId = `community.legacy-v${schemaVersion}`; + const baseDocument = { + schemaVersion, + components: [{ + id: `legacy-component-v${schemaVersion}`, + name: `Legacy v${schemaVersion} component`, + page: "voice", + accessibleName: `Legacy v${schemaVersion} component`, + permissions: [], + actions: {}, + root: { tag: "section", children: [{ text: `Original schema v${schemaVersion}` }] }, + }], + }; + const app = renderer.createApp(SkinPluginEditor, { + skinId, + skinVersion: "1.0.0", + page: "voice", + baseDocument, + }); + app.provide(ssrContextKey, { modules: new Set() }); + app.mount(hostNode("root")); + + try { + clickButton(teleportRoot, "组件结构"); + await nextTick(); + await nextTick(); + clickButton(teleportRoot, "新增组件"); + await nextTick(); + + const saved = authoring.loadSkinPluginAuthoringDocument(skinId, "1.0.0"); + assert.equal(saved.schemaVersion, 3, `the first v${schemaVersion} edit is persisted as schema v3`); + assert.deepEqual(saved.components.map(component => component.id), [ + `legacy-component-v${schemaVersion}`, + "custom-component-1", + ]); + assert.equal(saved.components[0].root.children[0].text, `Original schema v${schemaVersion}`); + assert.equal(baseDocument.schemaVersion, schemaVersion, "the package object stays unchanged while local edits migrate"); + } finally { + app.unmount(); + } + } +}); + +test("component editor stays visible in browsers without the Popover API", async () => { + const previousSupport = supportsPopoverApi; + supportsPopoverApi = false; + const root = hostNode("root"); + const app = renderer.createApp(SkinPluginEditor, { + skinId: "community.legacy-browser", + skinVersion: "1.0.0", + page: "voice", + baseDocument: { schemaVersion: 3, components: [] }, + }); + app.provide(ssrContextKey, { modules: new Set() }); + app.mount(root); + + try { + await nextTick(); + const editor = visit(teleportRoot, node => node.props["data-ws-plugin-editor"] !== undefined); + assert.ok(editor); + assert.equal(editor.props.popover, undefined, + "unsupported browsers use the ordinary fixed-position fallback instead of leaving an undisplayed popover"); + } finally { + app.unmount(); + supportsPopoverApi = previousSupport; + } +}); + +test("component runtime state is isolated by skin version and reset after deletion or schema changes", async () => { + const skinId = "community.runtime-state-isolation"; + const component = { + id: "stateful-panel", + name: "Stateful panel", + page: "voice", + accessibleName: "Stateful panel", + permissions: [], + actions: { toggle: { type: "ui.toggleState", args: { key: "enabled" } } }, + state: { enabled: false }, + root: { tag: "section", children: [ + { tag: "button", events: { click: "toggle" }, children: [{ text: "Toggle" }] }, + { tag: "span", children: [{ text: "{{state.enabled}}" }] }, + ] }, + }; + const version = Vue.ref("1.0.0"); + const document = Vue.ref({ schemaVersion: 3, components: [component] }); + const hostView = Vue.defineComponent({ + setup() { + return () => Vue.h(SkinPluginOutlet, { + skinId, + skinVersion: version.value, + document: document.value, + page: "voice", + data: {}, + assets: {}, + actions: {}, + }); + }, + }); + const root = hostNode("root"); + const app = renderer.createApp(hostView); + app.mount(root); + + const renderedComponent = () => visit(root, node => node.props["data-ws-plugin-component"] === component.id); + const toggle = () => { + const button = visit(renderedComponent(), node => node.tag === "button"); + assert.ok(button?.props.onClick, "the component's local toggle action is rendered"); + button.props.onClick({ type: "click", target: button, isTrusted: true }); + }; + + try { + await nextTick(); + assert.match(nodeText(renderedComponent()), /false/); + toggle(); + await nextTick(); + assert.match(nodeText(renderedComponent()), /true/); + + version.value = "2.0.0"; + await nextTick(); + assert.match(nodeText(renderedComponent()), /false/, + "a new skin version starts from its own declared component state"); + + toggle(); + await nextTick(); + assert.match(nodeText(renderedComponent()), /true/); + document.value = { schemaVersion: 3, components: [] }; + await nextTick(); + assert.equal(renderedComponent(), null, "deleting a component removes it from the active runtime"); + document.value = { schemaVersion: 3, components: [component] }; + await nextTick(); + assert.match(nodeText(renderedComponent()), /false/, + "re-adding a deleted component does not revive its previous local state"); + + document.value = { schemaVersion: 3, components: [{ + ...component, + actions: {}, + state: { enabled: "closed" }, + root: { tag: "span", children: [{ text: "{{state.enabled}}" }] }, + }] }; + await nextTick(); + assert.match(nodeText(renderedComponent()), /closed/, + "editing a state key's declared type applies the new default in the live preview"); + } finally { + app.unmount(); + } +}); + test("component create, update, and delete immediately change the rendered skin preview", async () => { Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() }); const skinId = "community.preview"; @@ -328,33 +728,71 @@ test("component create, update, and delete immediately change the rendered skin app.mount(root); try { - clickButton(root, "组件结构"); + clickButton(teleportRoot, "组件结构"); await nextTick(); await nextTick(); - clickButton(root, "新增组件"); + clickButton(teleportRoot, "新增组件"); await nextTick(); let rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); assert.ok(rendered, "the newly created component is rendered in the page preview"); assert.match(nodeText(rendered), /新建组件/); + changeSelect(teleportRoot, 1, "root"); + await nextTick(); + editTextarea(teleportRoot, JSON.stringify({ tag: "article", children: [{ text: "根节点已更新" }] }, null, 2)); + await nextTick(); + clickButton(teleportRoot, "应用定义"); + await nextTick(); + rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); + assert.equal(rendered.children[0].tag, "article", "editing the selected root replaces the live preview root"); + assert.match(nodeText(rendered), /根节点已更新/); + const saved = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion); const updated = { ...saved.components[0], name: "Preview component", accessibleName: "Preview component", - root: { tag: "section", children: [{ text: "预览已更新" }] }, + root: { tag: "section", children: [{ text: "预览已更新" }, { tag: "span", children: [{ text: "尾部" }] }] }, }; - editTextarea(root, JSON.stringify(updated, null, 2)); + changeSelect(teleportRoot, 1, ""); await nextTick(); - clickButton(root, "应用定义"); + editTextarea(teleportRoot, JSON.stringify(updated, null, 2)); + await nextTick(); + clickButton(teleportRoot, "应用定义"); await nextTick(); rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); assert.ok(rendered); assert.match(nodeText(rendered), /预览已更新/, "applying a component definition updates the rendered preview immediately"); - clickButton(root, "删除组件"); + changeSelect(teleportRoot, 1, "0"); + await nextTick(); + clickButton(teleportRoot, "节点下移"); + await nextTick(); + let reordered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion); + assert.deepEqual(reordered.components[0].root.children.map(node => node.text ?? node.tag), ["span", "预览已更新"]); + rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); + assert.ok(nodeText(rendered).indexOf("尾部") < nodeText(rendered).indexOf("预览已更新"), + "reordering nodes also changes their actual preview order"); + + clickButton(teleportRoot, "撤销"); + await nextTick(); + reordered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion); + assert.deepEqual(reordered.components[0].root.children.map(node => node.text ?? node.tag), ["预览已更新", "span"]); + rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); + assert.ok(nodeText(rendered).indexOf("预览已更新") < nodeText(rendered).indexOf("尾部"), + "undo restores both the saved component tree and its preview"); + + clickButton(teleportRoot, "重做"); + await nextTick(); + reordered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion); + assert.deepEqual(reordered.components[0].root.children.map(node => node.text ?? node.tag), ["span", "预览已更新"]); + rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"); + assert.ok(nodeText(rendered).indexOf("尾部") < nodeText(rendered).indexOf("预览已更新"), + "redo restores both the reordered tree and its preview"); + + clickButton(teleportRoot, "删除组件"); await nextTick(); assert.equal(visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"), null, "deleting the component removes it from the rendered page preview"); @@ -363,6 +801,75 @@ test("component create, update, and delete immediately change the rendered skin } }); +test("deleting the final image node releases its URL and outlet teardown releases remaining assets", async () => { + const originalCreate = URL.createObjectURL; + const originalRevoke = URL.revokeObjectURL; + const created = []; + const revoked = []; + URL.createObjectURL = () => { + const url = `blob:skin-outlet-${created.length + 1}`; + created.push(url); + return url; + }; + URL.revokeObjectURL = (url) => { revoked.push(url); }; + + const skinId = "community.asset-cleanup"; + const skinVersion = "1.0.0"; + const image = { + id: "image-panel", + name: "Image panel", + page: "voice", + accessibleName: "Image panel", + permissions: [], + actions: {}, + root: { tag: "section", children: [{ tag: "img", asset: "assets/icon.png" }] }, + }; + const document = Vue.ref({ schemaVersion: 3, components: [image] }); + const assets = { "assets/icon.png": new Blob(["icon"]) }; + const view = Vue.defineComponent({ + setup() { + return () => Vue.h(SkinPluginOutlet, { + skinId, + skinVersion, + document: document.value, + page: "voice", + data: {}, + assets, + actions: {}, + }); + }, + }); + const root = hostNode("root"); + const app = renderer.createApp(view); + app.provide(ssrContextKey, { modules: new Set() }); + + try { + app.mount(root); + await nextTick(); + const firstImage = visit(root, node => node.tag === "img"); + assert.equal(firstImage?.props.src, "blob:skin-outlet-1"); + + document.value = { schemaVersion: 3, components: [{ ...image, root: { tag: "section" } }] }; + await nextTick(); + assert.deepEqual(revoked, ["blob:skin-outlet-1"], + "removing the final node reference releases the asset URL while keeping its component mounted"); + assert.ok(visit(root, node => node.props["data-ws-plugin-component"] === "image-panel")); + assert.equal(visit(root, node => node.tag === "img"), null); + + document.value = { schemaVersion: 3, components: [image] }; + await nextTick(); + assert.equal(visit(root, node => node.tag === "img")?.props.src, "blob:skin-outlet-2", + "re-adding the component receives a fresh object URL"); + + app.unmount(); + assert.deepEqual(revoked, ["blob:skin-outlet-1", "blob:skin-outlet-2"], + "outlet teardown releases every remaining asset URL"); + } finally { + URL.createObjectURL = originalCreate; + URL.revokeObjectURL = originalRevoke; + } +}); + test("deleting the last surface component immediately restores the host page", async () => { Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() }); const skinId = "community.surface"; @@ -417,10 +924,10 @@ test("deleting the last surface component immediately restores the host page", a assert.equal(surfaceActive.value, true, "the approved surface replaces the host page"); assert.equal(visit(root, node => node.props["data-native-host"] === "true"), null); - clickButton(root, "组件结构"); + clickButton(teleportRoot, "组件结构"); await nextTick(); await nextTick(); - clickButton(root, "删除组件"); + clickButton(teleportRoot, "删除组件"); await nextTick(); await nextTick(); @@ -431,3 +938,136 @@ test("deleting the last surface component immediately restores the host page", a app.unmount(); } }); + +test("surface access can be refused, approved, and revoked from the host UI", async () => { + Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() }); + const skinId = "community.access-lifecycle"; + const skinVersion = "1.0.0"; + const surface = { + id: "protected-surface", + name: "Protected surface", + page: "voice", + mode: "surface", + accessibleName: "Protected voice page", + permissions: ["ui.surface.replace"], + actions: { toggle: { type: "ui.toggleState", args: { key: "enabled" } } }, + state: { enabled: false }, + root: { tag: "main", children: [ + { text: "Protected custom page" }, + { tag: "button", events: { click: "toggle" }, children: [{ text: "Toggle state" }] }, + { tag: "span", children: [{ text: "{{state.enabled}}" }] }, + ] }, + }; + const baseDocument = { schemaVersion: 3, components: [surface] }; + const props = { skinId, skinVersion, baseDocument, page: "voice", lang: "zh" }; + const hostView = Vue.defineComponent({ + setup() { + const surfaceActive = Vue.ref(false); + const revision = Vue.ref(0); + const currentDocument = () => { + revision.value; + return authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion) ?? baseDocument; + }; + return () => Vue.h("main", null, [ + surfaceActive.value ? null : Vue.h("section", { "data-native-host": "true" }, "WebSpeak host page"), + Vue.h(SkinPluginOutlet, { + skinId, + skinVersion, + document: currentDocument(), + page: "voice", + data: {}, + assets: {}, + actions: {}, + onSurfaceChange: (active) => { surfaceActive.value = active; }, + }), + Vue.h(SkinPluginEditor, { ...props, onUpdated: () => { revision.value += 1; } }), + ]); + }, + }); + const root = hostNode("root"); + const app = renderer.createApp(hostView); + app.provide(ssrContextKey, { modules: new Set() }); + app.mount(root); + + try { + await nextTick(); + assert.match(nodeText(teleportRoot), /Replace the built-in public page/, + "the host asks for approval before showing the surface permission"); + assert.equal(visit(root, node => node.props["data-native-host"] === "true")?.text, "WebSpeak host page", + "the built-in page remains visible before consent"); + assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null); + + clickButton(teleportRoot, "暂不启用 / Keep disabled"); + await nextTick(); + assert.equal(visit(teleportRoot, node => node.props["data-ws-plugin-consent"] === "true"), null, + "refusal closes the consent prompt"); + assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null, + "a refused surface does not render"); + assert.ok(visit(root, node => node.props["data-native-host"] === "true"), + "refusal leaves the built-in page usable"); + + clickButton(teleportRoot, "管理皮肤组件权限 / Manage skin component access"); + await nextTick(); + clickButton(teleportRoot, "批准所列权限 / Approve listed access"); + await nextTick(); + const activeSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice"); + assert.ok(activeSurface, "the surface activates only after explicit approval"); + assert.match(nodeText(activeSurface), /Protected custom page/); + assert.equal(visit(root, node => node.props["data-native-host"] === "true"), null); + let stateToggle = visit(activeSurface, node => node.tag === "button"); + stateToggle.props.onClick({ type: "click", target: stateToggle, isTrusted: true }); + await nextTick(); + assert.match(nodeText(activeSurface), /true/, "approved UI interactions update component-local state"); + + clickButton(teleportRoot, "组件结构"); + await nextTick(); + await nextTick(); + const original = baseDocument.components[0]; + const expanded = { ...original, permissions: [...original.permissions, "session.status.read"] }; + changeSelect(teleportRoot, 0, surface.id); + await nextTick(); + editTextarea(teleportRoot, JSON.stringify(expanded, null, 2)); + await nextTick(); + clickButton(teleportRoot, "应用定义"); + await nextTick(); + await nextTick(); + assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null, + "editing a component to request another permission disables its old approval"); + assert.ok(visit(root, node => node.props["data-native-host"] === "true"), + "the host page returns while the changed permission request awaits consent"); + assert.equal(approvals.isSkinPluginComponentApproved(skinId, skinVersion, expanded), false); + assert.ok(visit(teleportRoot, node => node.props["data-ws-plugin-consent"] === "true"), + "the changed component is presented for renewed approval"); + clickButton(teleportRoot, "批准所列权限 / Approve listed access"); + await nextTick(); + let reapprovedSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice"); + assert.ok(reapprovedSurface, + "the updated surface activates after its expanded permission set is approved"); + assert.match(nodeText(reapprovedSurface), /false/, "a component awaiting new permissions does not retain its previous state"); + + stateToggle = visit(reapprovedSurface, node => node.tag === "button"); + stateToggle.props.onClick({ type: "click", target: stateToggle, isTrusted: true }); + await nextTick(); + assert.match(nodeText(reapprovedSurface), /true/); + clickButton(teleportRoot, "管理皮肤组件权限 / Manage skin component access"); + await nextTick(); + clickButton(teleportRoot, "撤销全部授权 / Revoke all access"); + await nextTick(); + assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null, + "revocation removes the active surface immediately"); + assert.ok(visit(root, node => node.props["data-native-host"] === "true"), + "revocation restores the built-in page"); + assert.equal(approvals.isSkinPluginComponentApproved(skinId, skinVersion, surface), false, + "revocation also removes the persisted component grant"); + + clickButton(teleportRoot, "管理皮肤组件权限 / Manage skin component access"); + await nextTick(); + clickButton(teleportRoot, "批准所列权限 / Approve listed access"); + await nextTick(); + reapprovedSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice"); + assert.ok(reapprovedSurface); + assert.match(nodeText(reapprovedSurface), /false/, "revocation clears component-local state before the next approval"); + } finally { + app.unmount(); + } +});