From eabc78f36aae815dd120b0619ab80a779576a4f5 Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:26:30 +0800 Subject: [PATCH] feat(skin): add v3 declarative plugin components --- .../skills/webspeak-skin-development/SKILL.md | 13 +- docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md | 95 +- docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md | 204 +--- docs/SKIN_DEVELOPMENT.md | 33 +- docs/examples/ILLUSIA-VOICE.md | 12 +- docs/examples/KAAK-VOICE.md | 24 + docs/examples/illusia-voice.wskin | Bin 3544212 -> 3545012 bytes docs/examples/illusia-voice/components.json | 31 + docs/examples/illusia-voice/layout.json | 4 - docs/examples/illusia-voice/manifest.json | 11 +- docs/examples/illusia-voice/skin.css | 51 + docs/examples/kaak-voice.wskin | Bin 0 -> 5805 bytes docs/examples/kaak-voice/components.json | 124 +++ docs/examples/kaak-voice/content.json | 10 + docs/examples/kaak-voice/manifest.json | 14 + docs/examples/kaak-voice/skin.css | 969 ++++++++++++++++++ package.json | 2 +- src/admin/skin-registry.test.ts | 43 + src/admin/skin-registry.ts | 37 +- src/shared/skin-plugin.test.ts | 122 +++ src/shared/skin-plugin.ts | 364 +++++++ web/public/skins/illusia-voice.wskin | Bin 3544212 -> 3545012 bytes web/src/components/SkinPluginOutlet.ts | 236 +++++ web/src/services/skin-catalog.ts | 4 +- web/src/services/skin-pack.test.ts | 77 +- web/src/services/skin-pack.ts | 65 +- web/src/services/skin-plugin-approval.ts | 59 ++ web/src/styles/skin-plugin.css | 57 ++ web/src/views/DemoView.vue | 41 + web/src/views/WebClient.vue | 89 ++ 30 files changed, 2483 insertions(+), 308 deletions(-) create mode 100644 docs/examples/KAAK-VOICE.md create mode 100644 docs/examples/illusia-voice/components.json delete mode 100644 docs/examples/illusia-voice/layout.json create mode 100644 docs/examples/kaak-voice.wskin create mode 100644 docs/examples/kaak-voice/components.json create mode 100644 docs/examples/kaak-voice/content.json create mode 100644 docs/examples/kaak-voice/manifest.json create mode 100644 docs/examples/kaak-voice/skin.css create mode 100644 src/shared/skin-plugin.test.ts create mode 100644 src/shared/skin-plugin.ts create mode 100644 web/src/components/SkinPluginOutlet.ts create mode 100644 web/src/services/skin-plugin-approval.ts create mode 100644 web/src/styles/skin-plugin.css diff --git a/.agents/skills/webspeak-skin-development/SKILL.md b/.agents/skills/webspeak-skin-development/SKILL.md index 4272077..678043a 100644 --- a/.agents/skills/webspeak-skin-development/SKILL.md +++ b/.agents/skills/webspeak-skin-development/SKILL.md @@ -1,11 +1,11 @@ --- name: webspeak-skin-development -description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions. +description: Create, refine, package, and verify WebSpeak v1 visual, v2 layout, and v3 open skins while preserving host-owned behavior and access boundaries. --- # WebSpeak skin development -Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope. +Use this skill when editing or authoring a WebSpeak `.wskin` package, a built-in skin, or skin-facing UI hooks. v1/v2 packages are visual/layout data; v3 may rearrange public UI and add bounded declarative components. WebSpeak owns host behavior and the administrator console is outside the skin scope. ## Before editing @@ -16,8 +16,9 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSI ## Preserve the interface - Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork. -- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation. -- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned. +- Follow the schema-specific CSS rules: v1/v2 reject layout changes; v3 allows layout, placement, size, typography, and visibility changes within the skin root. Keep CSS package-local, scoped to public hooks, and free of external resources or executable values. +- v3 can obscure normal page controls. Preserve usable microphone, disconnect, device-settings, screen-share and recovery paths at desktop and mobile sizes. Skin CSS cannot reach host permission and recovery chrome rendered outside the skin root. Keep `/admin/**` unskinned. +- v3 component trees are declarative JSON rendered by the host. Never add script, Wasm, HTML strings, direct network/storage, or private host objects. Request only the component-level permissions needed; keep labels and favorite identifiers opaque and never bind server addresses or credentials. - Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry. - Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states. - Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights. @@ -26,7 +27,7 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSI 1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap. 2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged. -3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails. +3. Run the relevant skin-package tests and application build after a related batch of changes. Fix validation failures rather than weakening the v1/v2 boundaries or v3 permission checks. 4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session. -The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them. +The shipped default day, default night, and ILLUSIA skins are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them. A permission request is not a grant; verify the deny and revoke paths. Do not claim a skin was visually verified against an external reference unless that page was actually accessible. diff --git a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md index f543f35..573b909 100644 --- a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md @@ -1,85 +1,52 @@ # 更开放的皮肤系统路线图 -状态:R0–R2 已在 `skilV2` 分支实现并验收;R3 的 JavaScript / Wasm 安全原型已在本机 Chrome、Edge 和 Codex 内置浏览器通过 19 项测试。Wasm 原型改由固定 Wasmi 解释器处理作者二进制,并为解释器内存与执行 fuel 设置硬上限;生产扩展仍保持关闭,等待产品接入和独立安全评审。浏览器不提供整个进程 RSS 配额,因此不宣称进程级 RSS 上限。商城与管理员面板改造依照用户决定留待后续管理员面板重做。 +当前路线把皮肤能力限定在 WebSpeak 的公开连接首页、语音工作区和演示页。目标是让基础组件能自由安排、设定样式与显隐,并允许作者用声明式组件补充界面。管理员面板、管理 API 和语音服务运营页面都不纳入皮肤范围。 -本文与[更开放的皮肤系统规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)配套。商城目录和管理员界面改造暂不在本阶段实现,计划在管理员面板重做时一起交付。 +零新增预算是持续约束:不因皮肤系统引入付费托管、CDN、域名或存储。商城与管理员面板重做由后续阶段共同规划;优先复用公开 GitHub 仓库、版本化 Release 附件和现有免费能力,不能把隐私配置发布到公共目录。 -## 目标 +## 已完成 -让公开客户端的页面组件可以由用户选择、摆放、缩放、设定样式和显隐;基础组件继续由 WebSpeak 提供,任何皮肤都不能替换其行为或永久移除它。长期允许第三方扩展提供自定义组件,但扩展必须通过明确的权限边界与沙箱运行。 +### R0:边界与威胁模型 -本路线以安全和可维护为约束: +已明确基础组件由宿主维护、管理后台排除、作者代码默认不执行、用户能够恢复内置皮肤,以及新增数据能力必须经过宿主授权。 -- 管理后台 /admin/** 不属于皮肤范围。 -- 第一阶段只执行受验证的声明式布局和视觉配置,不执行皮肤作者提供的 JavaScript。 -- 不因本功能增加付费服务、域名、存储或服务器费用。商城和分发后续优先复用公开仓库及现有免费能力;若免费方案不满足规模要求,不能自动改用付费服务。 -- 继续识别当前 schemaVersion 为 1 的 .wskin 包;升级格式时必须有兼容和回退路径。 +### R1:公开组件和恢复入口 -## 当前基线 +公开页面稳定钩子与组件注册表已建立。恢复布局、皮肤加载错误处理和权限管理由宿主可信界面提供,位于皮肤样式作用域之外。 -当前 .wskin 是 ZIP 包,含 manifest.json、CSS、可选文案和包内素材。运行时校验包大小、路径、CSS 选择器、布局相关属性及资源 URL,再将样式限制在公开皮肤根节点。当前格式不提供组件排列和尺寸控制,不允许运行皮肤脚本;管理员面板使用独立样式。 +### R2:声明式布局 -CSS 作用域与校验可以降低意外影响,但样式仍运行在应用页面中,不能视为抵御恶意代码的完整安全沙箱。下一版布局能力应由宿主解析声明式数据并创建宿主组件,不通过放宽 CSS 黑名单来实现。 +schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖、撤销/重做、导入导出及错误恢复。schema v1 视觉皮肤继续兼容。 -当前实例皮肤目录由 WebSpeak 服务端提供,管理员皮肤界面管理实例包。公共商城是独立的目录与发布问题,留到管理员面板重做时确定。 +### R3:开放皮肤与受控组件 -现行格式、控件钩子和限额见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。 +schema v3 的客户端和服务端包校验、CSS 布局能力、声明式组件渲染、按组件权限审批与撤销、公开数据代理及有限宿主动作已接入。自定义组件使用受限 JSON 节点,不运行作者 JavaScript 或 WebAssembly。只有经用户启用的组件才可读取明确列出的公开会话数据或提出宿主动作;宿主对每次动作重新校验。 -## 阶段 +当前白名单包括连接摘要、公开频道、可见成员、当前公开频道消息和脱敏收藏名称。宿主动作覆盖公开频道加入、已有收藏切换、当前频道聊天发送和组件本地状态更新。收藏服务器地址、密码、身份密钥、私聊、原始音频、屏幕流、管理 API、任意网络和浏览器存储均不提供。 -### R0:边界与威胁模型(已完成) +CSS v3 可以完全改变公开页面布局、尺寸、排版和显隐,所以皮肤可能遮挡普通界面。宿主权限和恢复控件不受其 CSS 控制;实际皮肤仍要检查触屏、键盘、移动端及语音操作可达性。CSS 隔离不是恶意代码沙箱。 -- 定义组件注册表、必要组件、可信宿主 UI、布局格式和插件权限。 -- 明确声明式皮肤和可执行扩展是两类不同能力。 -- 记录管理员后台排除项、零新增预算约束和 v1 兼容策略。 +## 下一步 -**完成条件:** 规格文档评审完成;任何实现任务都能明确指出影响的组件、权限和回退行为。 +### R4:作者体验与兼容性 -### R1:稳定的公开组件注册表(已完成) +- 完成 Illusia 和 KAAK 示例的 v3 迁移,提供真实可导入的 .wskin 包和清楚的权限清单。 +- 为组件数据绑定、重复列表、动作校验、用户拒绝与撤销补足自动化回归。 +- 改善权限说明和皮肤开发文档;注明视觉预览限制、CSS 可隐藏普通 UI 的风险及恢复方式。 +- 汇总公开语音界面的预览问题并修复;不扩展到无关业务代码。 -- 为公开页面组件分配稳定 ID,并验证所有公开 `data-ws-part` 均已登记;管理员页面不进入注册表。 -- 将必要组件、可选组件、可信安全 UI 分开登记。 -- 明确组件的键盘操作、焦点顺序、屏幕阅读器名称和窄屏最小尺寸。 -- 把目前分散的 data-ws-part 逐步映射到注册表;现有 CSS 钩子在迁移期保持有效。 +### R5:皮肤商城与管理员面板重做时交付 -**已实现并验证:** 226 个公开组件 ID 均有可读名称、用途、分类、页面根容器、可编辑能力、数据敏感级别、键盘/焦点/无障碍策略、窄屏策略、尺寸与触控范围、样式令牌元数据。可信组件的布局模式、样式令牌和容器权限为空;可信祖先中的通用控件也不能绕过保护。模板扫描验证所有公开 `data-ws-part` 均登记,并检查带原生交互语义、键盘操作或拖放能力的钩子具备至少 44px 的触控尺寸和 1 倍最小缩放。布局运行时现在对所有可编辑交互组件始终执行注册表的 44px 最小命中区域,不要求用户先保存布局覆盖。演示页语音卡片已补键盘操作和可见焦点环。服务端与客户端共用相同注册表校验。 +- 商城目录、发现、安装、更新、回退、下架与撤销同管理员面板改造一起设计;后台本身保持不可皮肤化。 +- 首选人工审查的静态清单和 Release 附件,列出来源、版本、许可证、包校验值和组件权限。 +- 对目录不可用、版本冲突、撤销及离线场景提供可靠回退。 +- 维持零新增服务费用;任何无法在现有免费资源内解决的规模问题,重新确认预算后再处理。 +- 不默认加入评分、评论、付款、付费托管或第三方账号接入。 -### R2:声明式布局与本地自定义(已完成) +## 迁移和验收 -- 引入新版本布局清单,以注册表中的组件 ID 描述位置、尺寸、缩放、颜色、显隐和响应式配置。 -- 为桌面、平板和手机提供独立布局配置;坐标由宿主限制在有界数值内。 -- 提供本地布局编辑、撤销/重做和恢复默认布局的能力。 -- 位置、尺寸、显隐由布局配置表达,继续拒绝皮肤 CSS 覆盖几何和交互区域。 -- 个人编辑保存在浏览器本地,和皮肤包作者的默认布局分开;支持导入、导出与版本迁移。 - -**已实现并验证:** schema v2 声明式布局、桌面/平板/手机独立配置、直接拖动和属性编辑、本地撤销/重做、恢复默认、导入/导出;编辑器恢复入口和皮肤加载错误恢复提示都由宿主在皮肤根节点外渲染;v1 视觉皮肤继续受支持。坐标滑块和拖动都按页面根容器边界限制;触控控件不能缩到 44px 以下;编辑器可提示碰撞/溢出,并允许仅对当前布局忽略提示。新增焦点辅助预览:按浏览器顺序编号可布局的键盘控件,叠加实际命中区域并明确标出小于 44×44px 的目标;尺寸由布局运行时在默认状态和自定义布局下共同保证。失败的自定义皮肤会自动回退,并提供可信的一键切换到内置皮肤且记住选择的入口。本地演示页已确认焦点列表与覆盖层正常;测试覆盖焦点顺序算法、默认触控尺寸与 trusted-chrome 排除、皮肤加载失败回退和内置皮肤恢复。布局存储测试覆盖 v1 到当前存储格式迁移、无效项恢复导出、旧键备份及未来格式保护。ILLUSIA 已转换为 v2 布局皮肤并在浏览器中验证样式和包内素材正常加载。 - -### R3:扩展 API 与权限代理(仅在 R2 稳定后) - -- 首先发布无代码的布局和样式能力,不因用户期待插件化而提前执行任意脚本。 -- 若要允许扩展代码,先实现隔离运行时、能力权限账本、宿主 API 代理、权限撤销和资源配额。 -- 扩展通过版本化消息协议请求能力;宿主逐次校验,而不是把 DOM、浏览器存储、网络或媒体对象直接交给扩展。 -- 先以只读、低敏的会话状态能力做原型。私聊、身份、网络、麦克风、屏幕共享和命令执行须独立评审,不随一般 UI 权限自动开放。 - -**完成条件:** 隔离原型通过针对 DOM 访问、同源访问、未授权网络、消息伪造、恶意高频请求、权限撤销和升级增权的安全测试;不满足时保持禁用可执行扩展。 - -**当前原型与验收:** JavaScript 原型验证不透明 sandbox iframe、Worker 隔离、精确 `WindowProxy` / `null` origin / 随机 nonce 握手、独占 MessagePort、权限代理、撤权和消息配额。另有 Wasm-only 一次性运行原型:源码最多 256 KiB,预检最多 128 个函数、每个函数体最多 32 KiB、代码段最多 192 KiB、自定义段最多 8 个;函数签名每类值最多 64 个,整个模块的局部值最多 4096 个、每个函数最多 256 组;仅接受数字标量类型和受支持的核心指令,预检拒绝 GC / 引用 / SIMD / 线程类型与指令、start 函数、表元素段及未知扩展指令,以防越过线性内存限制或在执行前造成无界初始化。作者 Wasm 字节不会交给浏览器原生 Wasm 编译器,而是在 Worker 中交给固定版本 Wasmi 解释器解析和执行;解释器自身线性内存最多 64 MiB,获批扩展的宿主 `env.memory` 最多 64 页 / 4 MiB,每次执行最多 10,000,000 fuel。解释器采用 portable-dispatch,避免 wasm32 默认递归分发随每条指令耗尽调用栈。运行时只接受可选的获批状态读取导入,只允许单一 `run` 导出;3 秒期限覆盖 Worker 和解释器初始化,100 毫秒宿主看门狗作为 fuel 之外的后备保护。宿主保留脱敏快照副本,Wasm 无法通过改写线性内存伪造宿主返回值。浏览器安全页的 19 项用例已在 Chrome for Testing 155.0.8059.39、Edge 和 Codex 内置浏览器全部通过,涵盖 DOM/存储/同源/网络/导航隔离、伪造握手、未授权能力、撤权及取消待处理读取、高频请求、4 MiB 内存、fuel 死循环、GC 分配、超大签名/局部/元素向量、状态篡改和 start 函数拒绝。生产运行时仍关闭;原型尚无 UI 渲染 API、授权界面或产品接入。 - -**完成状态与边界:** R3 的开发原型已满足本阶段完成条件:三种浏览器中的 19 项安全页测试均通过,作者 Wasm 的解析与执行、guest memory、fuel、权限代理和可终止 Worker 均有明确限制。它不构成浏览器进程 RSS 配额,也不覆盖浏览器引擎漏洞;生产扩展保持关闭,直到产品 API、授权 UI、故障恢复流程完成接入并经过独立安全评审。此阶段不引入付费基础设施。 - -### R4:皮肤商城与管理员面板重做时交付 - -- 目录、包分发和运行时安装使用平台无关的清单协议。 -- 先以人工审查和版本化公开目录发布;支持兼容版本、来源、许可证、校验值、信任标签、下架和撤销记录。 -- 商城配置和管理随管理员面板重做设计,但管理后台本身仍不可被皮肤化。 -- 默认使用现有公开 GitHub 仓库或经确认的免费静态能力;皮肤包优先作为版本化 Release 附件。不得把内部服务器地址、密钥、测试节点或其他私密配置放入公共目录。 -- 暂不承诺评分、评论、自动付款、付费托管或第三方账号接入。 - -**完成条件:** 用户能查看来源和权限、安装/更新/卸载/回退;管理员能处理下架和撤销;离线或目录不可用时,已安装皮肤可安全回退。 - -## 迁移与发布策略 - -- v1 .wskin 继续作为视觉皮肤兼容格式;不得把原有 CSS 静默解释成新的布局权限。 -- 新格式使用单独的 schema 版本。未知版本、未知组件、未知权限和超出限额的包必须失败关闭,并提供可理解的错误。 -- 新包加载失败、兼容性不符或插件崩溃时,回退到宿主默认布局;用户数据和 TeamSpeak 会话状态不得因皮肤故障丢失。 -- 每个阶段单独验收,相关变更合并后统一运行验证;皮肤系统之外的语音、服务器管理或 Android 功能不借此扩展。 +- v1、v2 包继续按原有规则校验;只有明确声明 open-skin 的 v3 包才有 v3 CSS 与组件能力。 +- 未知版本、字段、权限、节点、数据路径、动作和素材类型都拒绝导入。 +- 每次将相关修改合并成一批统一运行验证,避免每个小节点重复跑全套构建。 +- 验收桌面与移动视口、产品支持语言、键盘与触屏、焦点状态、语音/静音/退出和皮肤恢复路径。 +- 管理端、运营页面、Android 计划及语音业务逻辑不因开放皮肤系统而扩展。 diff --git a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md index 449fe44..006d46f 100644 --- a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md @@ -1,195 +1,65 @@ # 更开放的皮肤系统规格 -状态:实现规格 0.2;R0–R2 的 schema v2 声明式布局已实现,R3 扩展沙箱仍为默认关闭的开发原型。配套阶段与未完成项见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)。 +状态:schema v3 声明式开放皮肤已接入公开客户端、浏览器导入和服务端包校验。当前实现的是受限组件树与宿主能力桥,不执行皮肤作者提供的 JavaScript 或 WebAssembly。阶段记录见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md),创作者操作见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。 -## 1. 范围 +## 1. 目标与范围 -本规格针对 WebSpeak 公开客户端页面:连接首页、语音工作区及公开演示页面。管理员后台 /admin/** 明确排除,不读取皮肤布局、样式或插件配置。 +皮肤可以重新排列、设置样式和显隐公开客户端中的元素,并可提供由宿主安全渲染的自定义声明式组件。基础组件始终由 WebSpeak 提供和维护;皮肤可以隐藏当前布局中的基础组件,但不能删除其注册、替换其业务行为或令其永久不可恢复。编辑器恢复入口、权限管理和系统安全提示由宿主放在皮肤作用域之外。 -目标是让页面组件可以自由组合和个性化,同时保留 WebSpeak 对基础组件、状态和行为的所有权。长期目标可以支持第三方扩展组件,但组件扩展必须处于受限沙箱中。 +适用页面为连接首页、语音工作区和公开演示页。管理员面板及其数据、管理 API 明确排除,不读取皮肤包。语音服务的运营、广告、陪玩、活动和商店等页面不属于语音客户端皮肤范围。 -当前实现范围: +## 2. 包格式与执行模型 -- 为公开页面登记稳定组件 ID,并在服务端和客户端共同校验布局数据。 -- 支持不运行作者代码的皮肤布局能力和本地用户覆盖。 -- 保留 v1 视觉皮肤兼容;v2 只接受 `layout-skin` 且 `permissions` 必须为空。 -- 为后续扩展 API 和商城定义安全前提。 +皮肤格式按版本区分:v1 保持视觉皮肤兼容;v2 提供有界布局 JSON;v3 使用 open-skin 清单、受控 CSS 和可选的 components.json。v1/v2 的 CSS 继续拒绝布局类声明,既有用户包不会因升级而获得新权限。v3 才允许 CSS 控制公开页面中的布局、位置、尺寸、顺序、文字排版和显隐。 -明确不在本轮范围: +v3 自定义组件不是脚本插件。宿主解析 JSON 中的元素白名单、受限属性、数据绑定、重复列表、条件和事件声明,再由 Vue 创建安全节点。包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAssembly、远程脚本、任意 URL、表单导航、浏览器存储访问或网络调用。未知字段、元素、动作、数据路径和权限一律拒绝。 -- 皮肤商城、公共目录运营和管理员面板重做;它们在后续阶段一起规划交付。 -- 将管理员面板开放给皮肤。 -- 在公开页面执行任意 HTML、Vue 模板、JavaScript、WebAssembly 或远程脚本。 -- 允许皮肤读取或控制 TeamSpeak 私钥、凭据、服务器配置、管理 API、原始音频流或屏幕流。 -- 引入付费托管、CDN、域名或新的服务器费用。 +每个组件只能声明 home、voice 或 demo 页面中的一个页面、一个有界的树和精确权限清单。components.json 全文不超过 256 KiB;最多 32 个组件;每组件最多 256 个节点、16 层深度、100 个重复行、32 个本地状态值和 24 个宿主动作。图片仅可通过包内 image 资源引用。 -## 2. 核心术语与不变量 +## 3. 可读数据和权限 -**宿主**指 WebSpeak 本身,包括组件注册表、页面结构、状态管理、权限判断和受信任的系统控件。 +组件权限按组件单独请求,用户在宿主确认界面查看用途后才启用。授权按皮肤 ID、版本、页面、组件和权限策略版本保存;换版本或策略含义变化会重新询问。皮肤设置中的独立入口可查看和撤销授权;拒绝或撤销后对应组件不渲染、不触发动作。 -**基础组件**指 WebSpeak 提供并负责维护的组件。它们始终存在于应用组件注册表中,不能被皮肤删除、替换成作者代码或改写行为。皮肤可提供默认布局,用户可调整其显示、位置、尺寸和样式。即使用户把基础组件从当前布局隐藏,也必须能从不受皮肤控制的恢复入口重新显示或恢复默认布局。 +当前公开只读能力如下: -**布局皮肤**指由清单、布局 JSON、受限样式和本地素材组成的声明式包。它不运行作者脚本,不因安装而取得应用数据权限。 +- session.status.read:连接状态、当前频道和显示名称。 +- session.channels.read:公开频道树、频道名称、层级、人数和当前频道标志。 +- session.members.read:可见成员名称、所在频道、在线状态、说话状态及本人标志。 +- chat.channel.read:当前公开文字频道中可见的消息。 +- favorites.read:收藏项名称、类型、是否当前项和随机不透明本地令牌;不提供地址或凭据。 -**扩展插件**指未来可能提供自定义展示或能力的独立代码包。插件与布局皮肤分开授权、分开运行;安装一个布局皮肤不能隐式安装或启用插件代码。 +当前宿主动作如下: -以下不变量必须成立: +- voice.joinChannel 需要 session.channel.join,只能请求加入当前页面公开可见的 TeamSpeak 频道,仍经过宿主和原有密码、权限流程。 +- favorites.switch 需要 favorites.switch,只能让宿主按不透明令牌选择本机已有收藏并走原连接流程。 +- chat.sendMessage 需要 chat.channel.send,只能发送到当前公开文字频道;不包括私聊。 +- ui.setState 只修改该组件短暂的本地标量状态,不需要会话权限。 -1. 皮肤故障不能断开语音、改变 TeamSpeak 权限、启动麦克风或屏幕共享,也不能绕过宿主确认流程。 -2. 组件的业务逻辑、事件监听和 TeamSpeak 命令始终由 WebSpeak 实现。布局只能请求显示宿主注册组件,不能提供一套替代逻辑。 -3. 用户始终能退出当前布局、恢复默认布局和撤销插件权限;这些恢复控件不受皮肤布局和样式控制。 -4. 权限提示、身份/私钥安全提示、连接安全状态和管理员入口属于宿主可信 UI,不由皮肤绘制、覆盖或拦截。 -5. 新格式按未知即拒绝处理;只有宿主版本支持的组件、布局节点、令牌和权限才能生效。 +动作仅能绑定到真实可信用户事件。输入和 change 事件不能调用宿主动作;键盘动作仅响应 Enter 或 Space。宿主再次检查当前频道、令牌及动作参数。皮肤不能控制麦克风、音频设备、屏幕采集、身份密钥或 TeamSpeak 管理命令。 -## 3. 组件注册表 +数据授权不是数据上传授权:组件没有任意联网或持久化 API,权限决定保存在本机。渲染进程不会把服务器地址、密码、身份私钥、访问令牌、Cookie、私聊、原始音频或屏幕流交给皮肤。 -每个公开组件由宿主登记稳定 ID 和受控元数据,至少包含: +## 4. CSS 与基础组件 -- id、用户可读名称、所属页面和用途。 -- 分类:core、optional 或 trusted-chrome。 -- 可用父容器/插槽、允许的布局模式和尺寸范围。 -- 可公开调整的外观令牌及其值类型/范围。 -- 可展示的数据字段及其敏感级别。 -- 键盘操作、焦点规则、无障碍名称和窄屏约束。 -- 可触发的宿主动作标识;布局不能任意调用命令。 +全部 CSS 被重写到当前公开皮肤根节点。选择器必须锚定 :root、data-ws-page、data-ws-part 或 v3 的 data-ws-plugin-part;v3 可在这些锚点之外使用皮肤自己的 class 和 ID。禁止全局逃逸、@import、脚本化 CSS 值和外部资源;图片和字体必须打包。不同 skin CSS 变量使用 --skin- 前缀。 -布局引用 ID,不引用 Vue class、私有 DOM 结构或内部服务名称。未知、已移除或不兼容的 ID 在校验时拒绝,不能降级为任意 HTML。旧 data-ws-part 在迁移期保持为 CSS 兼容钩子,并逐步对应注册表 ID。 +v3 CSS 可排列和重设公开 UI,因此可能遮挡麦克风、退出、共享或恢复入口。导入器会对隐藏界面发出提示,但这不是安全边界,也不能证明皮肤布局可用。可信的皮肤选择、恢复入口、组件权限确认和撤销控件在皮肤根节点之外;作者必须在桌面和移动布局中保留必要语音操作的可达路径。用户始终可切回内置皮肤。 -trusted-chrome 不属于可布局组件。恢复布局、权限审批、安全提示和管理员导航由宿主独立渲染。基础组件可在用户布局中隐藏,但不从注册表和编辑器中删除;每次应用重启后,宿主仍能通过固定恢复入口找回。 +皮肤与 /admin/** 完全分离。不得将后台页面标记为公开皮肤页面,也不得通过资源、选择器或组件数据间接读取管理员内容。 -## 4. 布局与外观模型 +## 5. 校验与回退 -### 4.1 声明式布局 +客户端导入和服务端登记都会校验 manifest、ZIP 路径、组件协议、所引用素材和文件限额。运行时会再次解析持久化的组件文档;无效组件不执行。权限界面和恢复控件由宿主代码渲染。v3 CSS 的结构限制可降低跨应用影响,但 CSS 不是针对恶意脚本的沙箱。 -布局由宿主解释为组件树。节点仅允许引用注册组件和受支持的容器类型,例如 stack、grid、dock、overlay;不允许嵌入 HTML 字符串、事件代码、表达式求值或动态模块。 +皮肤载入错误不得清除用户布局或 TeamSpeak 会话。组件树为空、权限被拒绝或皮肤无效时,宿主本身和既有功能仍可由用户恢复。管理员后台仍沿用自己的样式和服务端管理流程。 -布局可以为每个组件指定: +## 6. 商城和预算约束 -- visible:默认是否显示。 -- order、group:排列和分组。 -- placement:所在区域或相对于父容器的位置。 -- size:受组件约束的宽高或尺寸等级。 -- style:注册表允许的外观令牌。 +皮肤商城、公共目录和管理员面板重做不属于本轮实现,按路线图后续规划。未来优先使用公开 GitHub 仓库和 Release 附件等现有免费能力;若免费方案不能满足需求,需重新评估范围,不自动新增托管、CDN、域名或其他费用。公共目录不得包含内部服务器地址、密钥、测试节点或其他隐私数据。 -为实现自由摆放,可提供容器相对的锚点/比例坐标以及可选重叠层;不能让作者直接注入 position: fixed 等任意 CSS 几何规则。编辑器应展示碰撞、越界、文字遮挡和小屏溢出检查,并允许用户选择忽略非关键提示。 +## 7. 后续安全工作 -### 4.2 响应式布局 - -布局包可为桌面、平板、手机声明不同配置,并可指定合理的宿主断点。小屏布局不能仅靠缩放桌面坐标推导。组件移动、尺寸与显隐设置按当前布局配置保存;切换设备宽度不得清除用户配置。 - -布局坐标必须相对于明确容器,并由宿主限制在可用视区内。用户可以有意重叠组件,但必须能从编辑器或恢复入口解除遮挡。恢复入口和可信系统控件不参加用户坐标变换。 - -### 4.3 用户配置与作者默认值 - -皮肤包只提供作者默认布局。用户编辑产生本地覆盖层,按皮肤 ID、布局 schema 版本、页面和设备配置隔离保存。加载作者新版时,不得静默覆盖用户布局;只迁移仍匹配的组件与属性,并保留可恢复的旧配置或提示迁移失败。 - -用户配置应能导出/导入为数据文件。导入时重新验证组件、坐标、尺寸、样式令牌和限制,不能因为文件来自本地就跳过校验。 - -### 4.4 样式 - -几何布局、显隐和排序以结构化布局字段表达;颜色、背景、字体、圆角、阴影和受限动效以注册令牌或作用域 CSS 表达。优先使用组件令牌,避免让所有皮肤依赖实现细节选择器。 - -视觉 CSS 继续限制在公开皮肤根节点和稳定钩子内;只能引用包内素材。解析器应逐步采用属性/值白名单、函数与选择器限制、复杂度配额,而不是依赖不断扩大的黑名单。布局引擎负责位置和命中区域,因此样式 CSS 不能覆盖布局几何、焦点、可交互区域或可信 UI。 - -## 5. 包格式与兼容 - -新包必须使用独立 schema 版本,并声明包类型。布局皮肤与扩展插件必须可分别验证和安装。字段示意如下,最终字段名由 R1/R2 实现评审固定: - - { - "schemaVersion": 2, - "packageType": "layout-skin", - "id": "author.example-layout", - "version": "1.0.0", - "minAppVersion": "0.2.7", - "entry": "skin.css", - "layout": "layout.json", - "permissions": [] - } - -布局皮肤不得声明可执行权限;其 `permissions` 必须为空。当前 v2 清单拒绝未定义字段,以免未来能力字段被旧客户端静默忽略。未来插件必须使用独立包类型、API 版本和逐项权限审批,不得复用布局皮肤的信任模型。 - -当前 schemaVersion 为 1 的 .wskin 保持可安装和可运行。v1 CSS 不会因此取得几何布局权限;迁移到新布局包是显式操作,预览后由用户确认。新包校验失败、最低客户端版本不符或激活超时,保留用户最后可用配置并回退到宿主默认外观。 - -继续沿用当前归档安全要求:限制压缩包和解压大小、文件数、路径长度与 CSS 复杂度;拒绝路径穿越、重复路径、符号链接、超出白名单的文件类型、远程资源和可执行 CSS。具体上限按当前皮肤开发规范维护并在版本发布时测试。 - -## 6. 权限与沙箱 - -### 6.1 权限级别 - -| 能力 | 布局皮肤 | 未来扩展插件 | 原则 | -| --- | --- | --- | --- | -| 组件摆放、尺寸、显示/隐藏和外观 | 允许 | 允许 | 只能操作注册组件和 schema 允许的令牌;基础组件仍可恢复 | -| 读取静态、非敏感的页面状态 | 无运行代码 | 逐项申请 | 只通过宿主 API;只提供完成该组件所需的最小字段 | -| 频道成员、当前频道、发言状态 | 不适用 | 默认拒绝,按能力单独授权 | 绑定当前会话,断开后立即失效 | -| 频道聊天、私聊、身份资料 | 不适用 | 默认拒绝,分别授权 | 私聊和身份视为高敏数据;不得批量导出 | -| 网络请求 | 仅包内素材 | 默认拒绝 | 需要时由宿主代理并按精确来源授权,不允许插件自行访问任意 URL | -| 插件本地存储 | 无 | 默认关闭或严格配额 | 按插件 ID 隔离;不能读取网页 localStorage、Cookie、IndexedDB 或其他插件数据 | -| 调用宿主动作/TeamSpeak 命令 | 不允许 | 默认拒绝 | 插件只能提交意图;宿主在用户操作和自身策略下决定是否执行 | -| 麦克风、音频轨道、屏幕采集 | 不允许 | 不向插件暴露原始对象 | 延续浏览器和宿主的用户授权;插件不能静默开始、旁听或共享 | -| 私钥、访问令牌、Cookie、管理 API、文件系统 | 不允许 | 永久禁止 | 这些数据和接口不属于插件能力模型 | -| 管理后台和管理数据 | 不允许 | 永久禁止 | /admin/** 与管理 API 不进入插件运行环境 | - -能力名称必须精确、可审计,禁止通配符授权。任何权限都默认拒绝;包作者只能声明请求,不能自行授予。用户拒绝某项权限后,插件必须仍能提供不依赖该能力的功能,或清楚说明该功能不可用。 - -建议的首批权限 ID 为 session.status.read、session.members.read、chat.channel.read、chat.private.read、identity.profile.read、network.fetch 和 storage.private。权限 ID 及其数据字段范围必须由宿主版本化登记;network.fetch 还必须绑定明确来源。不得提供通用的 admin、filesystem、credentials、media.raw 或 teamspeak.command 权限。即使未来存在网络权限,也不得默认把私聊、身份或凭据数据交给网络请求;跨越这两类能力需要单独的风险提示和明确批准。 - -基础动作组件仍由宿主渲染和处理。用户点击一个宿主提供的麦克风、离开或频道按钮,不等于把对应动作 API 授给皮肤;扩展不能在后台直接调用同一动作。 - -### 6.2 可信边界 - -当前皮肤 CSS 在应用文档中加载。根节点作用域、CSS 解析器和路径校验是输入限制,不是浏览器安全沙箱;恶意视觉规则仍可能误导用户或妨碍操作。因此: - -- 第一阶段不执行第三方 JavaScript、WebAssembly 或 HTML 模板。 -- 权限提示、恢复入口、可信状态和管理 UI 必须脱离可皮肤化根节点渲染。 -- 对布局几何、隐显和交互命中区域的控制由宿主布局引擎实现,避免依赖主页面 CSS。 -- CSS、文案和图片均视为不可信输入,分别经过 schema、解析器和资源校验。 - -当前只有开发安全原型,尚未接入皮肤安装流程或公开页面运行时。JavaScript 原型使用不透明源的 sandbox iframe 作为**受信任引导壳**,只授予 `allow-scripts`,不授予 `allow-same-origin`、顶层导航、弹窗、表单提交、下载或媒体权限。作者 JavaScript 在独立 Worker 中执行;Worker 没有 DOM、`window`、网页存储或应用全局对象。Worker 侧隐藏网络、子 Worker、IndexedDB、Cache Storage 和 WebAssembly 等全局,CSP 作为纵深防御拒绝网络、远程脚本、图片、媒体和子框架。此前实测发现目标浏览器没有按预期执行 `navigate-to 'none'`,因此隔离不依赖该指令:不可信代码位于 Worker,不能自行导航壳页面。宿主绑定精确 iframe `WindowProxy`、opaque `null` origin、一次性 nonce 和单一转移端口后改用独占 `MessageChannel`;壳只转发固定格式的能力请求,不接收任意 HTML 或代码作为渲染指令。撤权和关闭会通知壳调用 `Worker.terminate()`,并在短超时后由宿主移除 iframe。这个 JavaScript 原型用于验证隔离与消息协议,因普通 Worker 没有硬内存配额,不可用于生产。 - -另有一个 Wasm-only 运行原型:扩展包仅提供最多 256 KiB 的 Wasm 二进制,不执行作者 JavaScript。Worker 先做有界预检,最多接受 128 个函数、单个函数体 32 KiB、代码段总计 192 KiB 和 8 个自定义段;类型只接受函数签名和数字标量,每个签名最多 64 个参数/结果值,整个模块最多 4096 个局部值、每个函数最多 256 组。指令扫描拒绝 GC / 引用 / SIMD / 线程类型与指令、start 函数、表元素段和未知扩展指令。作者二进制不会交给浏览器的原生 Wasm 编译器,而由固定版本的 Wasmi 解释器解析与执行;解释器容器本身的 Wasm 线性内存上限为 64 MiB,guest 只能使用一块宿主提供的 `env.memory`,上限 64 页(4 MiB)。运行时只接受可选且经 `session.status.read` 授权的状态读取导入,并只允许一个 `run` 函数导出。Worker 和受信解释器初始化期限为 3 秒;开始运行后,Wasmi 每次最多消耗 10,000,000 fuel,宿主另以 100 毫秒 Worker 看门狗兜底。跨 Worker 消息最多 8 KiB,状态快照最多 512 字节、最多读取 10 次。授权快照由宿主持有,Wasm 只能收到拷贝,不能通过篡改线性内存改写宿主返回值。该原型仍是一次性安全演示,没有 UI 渲染 API、授权界面或产品接入。 - -解释器容器的 64 MiB Wasm 上限与 guest 的 4 MiB 线性内存上限,能限制作者模块解析和执行期间由 Wasmi 分配的内存;作者字节不会触发浏览器对不可信模块的原生编译开销。浏览器仍没有普通 Worker 的进程级 RSS 配额,因此这不等于限制整个浏览器进程的 RSS,也不能抵御浏览器引擎或受信解释器本身的漏洞。10,000,000 fuel 是执行指令预算;100 毫秒墙钟看门狗是额外的 Worker 终止保护。生产扩展运行时仍保持关闭,直到产品 API、授权 UI、故障恢复流程完成接入并通过独立安全评审。安全页的 19 项用例已在 Chrome for Testing 155.0.8059.39、Edge 和 Codex 内置浏览器通过;这仅确认本机版本,不代表不同操作系统或未来版本均已验收。浏览器用例通过不等于安全审计。 - -插件不得直接访问宿主 DOM、Vue 实例、全局变量、Cookie、浏览器持久化区、应用请求客户端或 TeamSpeak SDK。宿主通过专用消息通道提供版本化、带 schema 的能力 API。每次请求均按插件 ID、当前会话、已批准能力和用户操作重新判断;校验调用方窗口/消息源、请求大小、频率和数据范围。初始化握手须绑定该 iframe 的 window source 和单次随机 nonce,成功后转交独占的 MessageChannel;不能只依赖 opaque iframe 的 origin 值,也不能通过通配 postMessage、共享对象引用或未校验事件回调授权。 - -### 6.3 授权生命周期 - -1. 安装/启用时展示发布者、来源、包版本、完整权限清单和风险级别。 -2. 仅声明权限不等于获准。对高敏权限,应在首次使用前单独解释其用途并取得明确同意。 -3. 插件版本升级后若权限增加或权限含义变化,必须重新征求同意;用户已有的无关授权不能扩大。 -4. 用户撤销权限时,宿主立即拒绝后续调用、停止插件执行并丢弃该权限下的临时数据。 -5. 卸载时停止计时器、消息订阅和 UI,删除该插件命名空间内的存储;不改动其他皮肤、插件或 WebSpeak 数据。 -6. 权限决定保存在本地;不得为了商城分析而上传用户身份、会话或权限记录。 - -### 6.4 资源与滥用控制 - -布局和样式包沿用当前皮肤包体积限制,并为新格式增加节点数、嵌套深度、属性数、动画数和素材总量上限。插件执行环境需设置消息频率、单次消息大小、启动期限和停用/重启上限。 - -JavaScript 隔离原型限制源码为 64 KiB、单条消息为 8 KiB、最多 10 条 API 请求/秒和 10,000 条总请求;Worker 最多保留 16 条未完成请求。该 JavaScript 执行原型仍因没有硬内存配额而保持关闭。Wasm-only 原型限制二进制为 256 KiB、函数最多 128 个、单函数体最多 32 KiB、代码段最多 192 KiB、自定义段最多 8 个、签名每类值最多 64 个、模块局部值最多 4096 个、每函数最多 256 组;解释器容器最多 64 MiB,guest 线性内存最多 4 MiB,每次运行最多 10,000,000 fuel,并有 3 秒初始化期限和 100 毫秒 Worker 看门狗。跨 Worker 消息最多 8 KiB,状态快照最多 512 字节、最多读取 10 次。预检只接受数字标量和受支持核心指令,拒绝 GC / 引用 / SIMD / 线程、start 函数、表元素段和未知扩展指令。浏览器不提供普通 Worker 的进程级 RSS 配额,因此规格只承诺上述解释器和 guest 边界,不声称能限制浏览器进程 RSS。Wasm 仍为开发原型,接入前须完成独立安全评审和产品生命周期设计。安全测试覆盖高频消息、解释器与 guest 内存边界、fuel 死循环、GC/超大向量声明、函数数量与函数体复杂度、数据范围、伪造握手、未授权能力和撤权终止。 - -### 6.5 发布者与包信任 - -包校验值只能说明下载字节与目录记录一致,不能证明作者可信或代码安全。未来商城至少应显示来源、版本、许可证、权限和校验状态;签名可用于验证发布来源,但不能替代沙箱和权限审核。下架或撤销应记录包 ID 与受影响版本,并让客户端在下次可联网时停止建议/更新该版本;离线运行时仍须允许用户卸载或回退。 - -## 7. 失效、恢复与无障碍 - -- 布局 JSON 无效、组件不存在、加载超时或插件崩溃时,回退到宿主默认布局;不得阻断连接页或会话恢复。 -- 恢复入口始终可通过键盘和触屏操作,提供明确名称、焦点样式和屏幕阅读器标签。 -- 布局编辑器必须显示当前焦点顺序与触屏命中区域预览;不能只检查视觉坐标。 -- 用户可保存桌面和移动布局;窄屏状态下关键操作至少存在可访问路径。 -- reduced-motion 偏好、语言变化、文本扩展和浏览器缩放不能导致安全/恢复 UI 消失。 -- 皮肤/插件错误只显示在宿主可信提示区域,并允许一键停用对应包。 - -当前编辑器的焦点辅助预览按浏览器顺序列出公开页面中可布局的键盘目标,并在宿主层叠加实际命中矩形;小于 44×44 CSS px 的目标以红色显示。注册表约束在默认布局和个人覆盖下都执行。编辑器面板不使用动效,语言随页面 `lang` 变化,焦点列表支持长文本换行,固定恢复入口位于皮肤根节点之外。自定义皮肤加载失败时页面自动回退,并在宿主可信提示层提供记住内置皮肤选择的一键操作;此操作停用当前选择,不会在服务端目录中禁用或删除皮肤包。 - -## 8. 安全验收清单 - -每次开放新的布局或权限能力前,至少验证: - -- 不存在读取 /admin/**、管理 API、DOM 外部根节点、Cookie、localStorage 或 TeamSpeak 凭据的路径。 -- 未授权插件不能联网、读取聊天/身份数据、接收原始音频或启动屏幕采集。 -- 权限增加、拒绝、撤销、卸载和更新竞态不留下旧订阅或迟到回调。 -- 恢复入口、权限提示、身份安全提示、焦点可见性和基础组件可恢复。 -- 未知 schema、权限、组件、文件类型、路径穿越、压缩炸弹、极端嵌套和超大消息均安全失败。 -- 布局在五种产品语言、键盘导航、窄屏、触屏和浏览器缩放下仍能使用。 -- 新布局能力没有扩大管理员页面或语音服务端的工作范围。 +- 扩展数据字段或宿主动作时,增加精确 schema、权限和宿主侧运行时验证,不暴露内部 SDK 对象。 +- 对恶意输入、路径别名、拒绝授权、撤销、更新和皮肤切换增加测试;高敏能力必须单独设计。 +- 不把当前 v3 声明式包描述为可执行代码沙箱。若未来考虑代码扩展,应另行开展威胁建模、浏览器隔离评估与独立安全审查。 +- 商城发布、签名、下架、更新和撤销设计与管理员面板重做一起验收,且保持零新增服务费用为默认约束。 diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index f7ed99d..bec7538 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -1,8 +1,8 @@ # WebSpeak 皮肤开发规范 -本文说明仍受支持的 v1 视觉皮肤包,以及已实现的 v2 声明式布局皮肤。v1 继续保持固定组件布局;v2 可调整公开组件的位置、尺寸、显隐和外观,但不执行作者代码。路线和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。 +本文说明仍受支持的 v1 视觉皮肤、v2 声明式布局皮肤和 v3 开放皮肤。v1/v2 保持固定 CSS 几何边界;v3 可重排公开 UI 并携带受限声明式组件,但不执行作者代码。路线和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。 -`.wskin` 包可为公开页面定制艺术表现。v1 保持 WebSpeak 的固定布局;v2 另外携带受校验的布局 JSON,并可由用户在浏览器本地继续调整。两种格式均不允许皮肤替换宿主组件或改变 TeamSpeak 行为。 +`.wskin` 包可为公开页面定制艺术表现。v1 提供 CSS 与美术资源;v2 另外携带受校验的布局 JSON;v3 可自由安排公开组件,并用 components.json 声明由宿主渲染的安全组件。所有版本均由 WebSpeak 保留基础组件的业务逻辑和 TeamSpeak 行为。 页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。** @@ -25,6 +25,7 @@ content.json # 可选:首页内容与多语言界面文案 assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用 assets/background.webp # 可选:页面艺术素材 assets/brand.woff2 # 可选:自带字体 +components.json # v3 可选:声明式扩展组件 ``` 所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。 @@ -103,6 +104,18 @@ v2 为 v1 增加一个必需布局文件。清单和布局 JSON 会在导入端 v1 和 v2 都只支持公开页面。`/admin/**` 不加载布局、用户覆盖和皮肤组件编辑器。布局包没有数据/API 权限;后续插件必须另行设计独立沙箱与授权协议,不能通过增加 v2 清单字段取得能力。 +### schemaVersion 3:开放皮肤和声明式组件 + +v3 清单的 packageType 固定为 open-skin,entry 指向 CSS,components 指向 components.json;不含 v2 的 layout 或 permissions 字段。组件文件可以省略。仅 v3 开放公开页面的 CSS 排版能力,v1/v2 仍按旧 CSS 规则校验。客户端导入和服务端登记使用同一共享组件 schema 与权限白名单。 + +components.json 顶层为 schemaVersion 1 和 components 数组。每个组件需声明 id、name、page、accessibleName、permissions、actions 和 root,可选 state。page 只接受 home、voice、demo。root 使用白名单 HTML/SVG 元素。节点可包含 text、part、className、受限 attributes、包内图片 asset、bindValue、本地 repeat/when、events 和 children。文本与属性支持简单的双大括号数据路径;不支持表达式、HTML 字符串或脚本。 + +示例包见 [KAAK voice 示例](./examples/KAAK-VOICE.md),其 components.json 展示了公开频道列表和双击加入频道。当前数据权限和宿主动作以[开放皮肤规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)中的清单为准。组件按本地用户授权后才渲染;权限对每个皮肤版本、页面和组件分别保存,可在宿主浮动的权限入口撤销。用户拒绝时组件保持关闭。 + +组件树有硬上限:components.json 256 KiB,最多 32 个组件,每组件最多 256 个模板节点、16 层深度、100 条重复记录、32 个本地标量状态和 24 个动作。图片资源只能从包内引用,CSS 不能读取外部 URL、脚本或浏览器存储。宿主动作需显式权限,并只能绑定可信的用户事件;输入或 change 事件不能连接、切房或发消息。 + +注意:v3 CSS 可以隐藏或遮挡语音控件。权限和恢复提示由宿主在皮肤根之外绘制,但其他界面控件仍受皮肤排版影响。测试时务必确保麦克风、设置、退出语音、屏幕共享操作和移动端导航仍有可达路径。组件演示页 /demo 使用合成数据,加入频道和聊天动作只更新演示状态。 + ## 首页内容和文案 `content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例: @@ -231,11 +244,11 @@ v1 和 v2 都只支持公开页面。`/admin/**` 不加载布局、用户覆盖 ### 固定布局与交互边界 -以下规则针对 `skin.css`:校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。v2 的位置和尺寸只从经过 schema 校验的 `layout.json` 生效,不会放宽 CSS 规则。 +以下 CSS 限制适用于 v1 和 v2:校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的声明,包括 display、position、inset、z-index、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件和字号等。v2 的位置和尺寸只从经过 schema 校验的 layout.json 生效。v3 为支持自由布局而允许这些声明,但仍限制皮肤根作用域、公开钩子、危险值和外部资源;只通过 CSS 隔离不能阻止皮肤作者遮挡控件。 -因此,皮肤 CSS 可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材;v1 不能移动播放器或改变成员卡片尺寸。v2 布局可移动和缩放宿主注册组件,但 CSS 仍不能把锚定浮层改成模态弹窗或挪动按钮点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。 +因此,v1/v2 CSS 可以更换艺术素材、颜色和表面风格,但不能重排组件。v3 可以用 CSS 重新安排界面和组件盒子,也能隐藏普通界面部分;基础组件由宿主继续创建,宿主的恢复和权限 UI 位于皮肤作用域外。所有版本都应确保焦点、文字、键盘和触屏操作可用。 -v1 外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。v2 应在布局数据中分别设置桌面、平板和手机配置。上线前仍需预览各设备尺寸、所有五种语言、键盘焦点、减少动效偏好,并确认必要控件可用、文字未被裁切。 +v1/v2 外观可以因窄屏而更换图片裁切或装饰,但 @media 规则也受固定布局限制。v2 应在布局数据中分别设置桌面、平板和手机配置;v3 可用媒体查询构建响应式 CSS。上线前仍需预览各设备尺寸、所有五种语言、键盘焦点、减少动效偏好,并确认必要控件可用、文字未被裁切。 ## 安全边界和限制 @@ -247,7 +260,7 @@ v1 外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也 | 解压总大小 | 50 MiB | | ZIP 条目数 | 128 | | 单个 CSS 文件 | 512 KiB | -| `content.json` | 256 KiB | +| `content.json` / `components.json` | 256 KiB | | 单张图片(包括预览) | 16 MiB | | 单个 WOFF2 字体 | 4 MiB | | 每实例皮肤数 | 50 | @@ -255,7 +268,7 @@ v1 外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也 压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。 -必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出: +v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显示状态,因此皮肤开发者必须保留语音操作路径;授权界面、皮肤选择和恢复入口由宿主在皮肤作用域之外提供。以下选择器是旧格式对可选装饰部件的透明度白名单: ```css [data-ws-part="home.hero.eyebrow"] @@ -278,7 +291,7 @@ v1 外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也 上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 -皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。 +皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。 @@ -286,7 +299,7 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删 1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。 2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。 -3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。 +3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`;需要自定义安全组件时使用 v3 的 `components.json`。 4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例: ```powershell @@ -295,7 +308,7 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删 Copy-Item .\illusia-voice.wskin .\web\public\skins\illusia-voice.wskin -Force ``` -5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置。v1 检查固定布局无回归;v2 还要检查作者默认布局与用户本地覆盖。 +5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置。v1/v2 检查固定布局无回归;v2 还要检查作者默认布局与用户本地覆盖;v3 检查授权拒绝与撤销、公开数据边界和自定义组件失效恢复。 6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。 当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。 diff --git a/docs/examples/ILLUSIA-VOICE.md b/docs/examples/ILLUSIA-VOICE.md index c4b01e0..2763840 100644 --- a/docs/examples/ILLUSIA-VOICE.md +++ b/docs/examples/ILLUSIA-VOICE.md @@ -1,15 +1,11 @@ # ILLUSIA风 -ILLUSIA风 is a schema v2 `.wskin` example built from the local artwork in `illusia-voice/assets/`. Version 1.0.29 adds the required `layout.json` while preserving the existing CSS composition. The layout file starts empty, so WebSpeak's responsive defaults remain intact until a user customizes the layout locally. The package declares no permissions and contains no executable skin code. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls. The shared quick-server list styles home history and favorite controls, the desktop rail, mobile strip, active-server marker, switch status, and quick-connect dialog with a coordinated light-glass treatment to check compatibility across desktop and mobile layouts. +ILLUSIA 风格 is a schema v3 open-skin example built from the local artwork in [illusia-voice/assets](./illusia-voice/assets/). Version 2.0.0 keeps its existing light-glass CSS and adds a small declarative current-channel card to exercise the new component renderer. The package still uses WebSpeak's base translations and contains no executable skin code. -This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. CSS remains visual-only; the new layout editor changes only registered host components and stores user overrides in the browser. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element. +The new voice-page component is defined in [components.json](./illusia-voice/components.json). It reads only the current public channel name through session.status.read and uses a local mascot image for a compact, non-interactive glass badge. The component needs the user's local approval before it renders; that approval is scoped to this skin version and can be revoked from the host access control. It cannot switch channels, read favorites, access a server address, or control audio. -The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root: +The CSS continues to style the WebSpeak home page, voice workspace, screen-share player and /demo with cyan accents and original art. The homepage includes translucent navigation and selectors, animated mascot details, feature tiles, a visitor badge, a join action and a curved footer. The voice workspace includes the shared quick-server list, channel/member views, chat empty state, screen-share art and audio controls. The mobile view keeps WebSpeak's responsive host navigation while applying ILLUSIA colors and artwork. -```powershell -Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force -Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force -Copy-Item .\docs\examples\illusia-voice.wskin .\web\public\skins\illusia-voice.wskin -Force -``` +The distributable package and the copy served from web/public/skins are built from the source folder. After changing source files, recreate docs/examples/illusia-voice.wskin from that folder and copy the resulting package to web/public/skins/illusia-voice.wskin. Run the package import test to confirm both copies stay byte-identical and valid. Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances. diff --git a/docs/examples/KAAK-VOICE.md b/docs/examples/KAAK-VOICE.md new file mode 100644 index 0000000..8ab9aee --- /dev/null +++ b/docs/examples/KAAK-VOICE.md @@ -0,0 +1,24 @@ +# KAAK voice skin + +KAAK is a schema v3 open-skin package for WebSpeak's public connection page and voice workspace. It keeps TeamSpeak connection, channel, member, chat, favorite-server, audio, and screen-sharing behavior in the host. On desktop, its declarative channel/member sidebar replaces the host's channel tree; on narrow screens, WebSpeak's native responsive channel/member UI remains in use. + +The design target is the voice-client portion of KOOK, as requested by the project owner. This skin does not include discovery, advertising, companion/party, event, store, administrator, or other service-operator pages. It does not add a KOOK account flow, direct messages, server administration, or channels absent from the connected TeamSpeak server. + +## Reference access note + +The owner authorized inspection of two specified voice rooms. The current browser bridge exposes the KOOK tab in its inventory but times out when reading its page, and direct page access is unavailable. Therefore this revision is a v3 architecture and styling migration based on the existing KAAK draft and the owner's voice-client scope; it is not a verified pixel-for-pixel reproduction of either live room. No room contents or member details are asserted here. + +## Components and permissions + +The voice sidebar is defined in [components.json](./kaak-voice/components.json). It reads the public channel tree and visible member names/speaking state. A real user double-click or Enter/Space key action can ask the host to join a listed channel; the host rechecks that the channel is visible and applies the existing TeamSpeak password and permission flow. Permission approval is local to this skin version and can be revoked from the host access control. + +The favorite-server rail and main audio/chat controls remain WebSpeak components. The plugin does not receive server addresses, passwords, identity keys, microphone controls, raw audio, private messages, or arbitrary network/storage APIs. The /demo page uses synthetic data and does not connect to TeamSpeak. + +## Files + +- Source package: [kaak-voice](./kaak-voice/) +- Component schema: [components.json](./kaak-voice/components.json) +- Distributable archive: [kaak-voice.wskin](./kaak-voice.wskin) +- Shared format and safety rules: [SKIN_DEVELOPMENT.md](../SKIN_DEVELOPMENT.md) + +The package is a ZIP archive with manifest.json at its root. Rebuild the archive from the contents of kaak-voice after any source change, then import the .wskin in a visitor browser and verify the consent, approval, denial, revoke, desktop, and narrow-screen paths. diff --git a/docs/examples/illusia-voice.wskin b/docs/examples/illusia-voice.wskin index d8544f876ba46db52faddf913ac90e8f3dc8a176..12641f277aff1d98d36b6ffbdcccbd6fbeb07a4e 100644 GIT binary patch delta 8562 zcmZviWlSAF_vV3%yHlLv?pmaHad)`5Q(TK(`v8s#l-`z|deAFaQh-h6BTc5x|IGBrq}<1&j(t1EYg6z?fhx zFg6$mj0?sCrUTQ18NiHSCNMLY z1j zIz%UQEA_Ku4m}GEj=HK3tf6semW>4jK)X9-soRa#GUZ5==A%ZTqLyF;48(l;l&0gA zD)+z=m(?8&72hi-vhDYg)qQ{kMO8bHWRy>1!%f_K+f&~6i>W|W&=f?~5(5QwR|CVI zUW3J6sv(^)yjHQFyhmJ0@LeUS+HQRe}^Uza69opvCv;sw%SB`#_sE*=U36~8E z?uHQ@-t)}Uvat?pNjp%~z1$;O4~dZ%nG&Z>U_bSe_FD`${s!%)VjjP$@R$+7sX%7E zOSS+i{gz5dQ$mK=>?2SvS!Y4f@^F67Bc9=~tTT&@*TKnQvaNelm;&MGhF4>m1Jw1L zn4Jym^%~1fbC3Em(%mOuhkmsiP!++8-o5%4^S*xLvmY1 z9srB`Pk%(H|F~j#k&90G&y}InntL8RP`sc+KRYVq8LAbKC!iJWMjtn67Jv#jH>@yT zF{zURtLlM?+bPaAJO79u^1Ye#@vDgH!n+3`cfgH%2Sv){dI9>%Qy0zJ`}^rBz6`18 zt7uhRc2)+^q0ag@dsNK4Vtr!)JAR^-ge{*dDZ1;U*B9ZO*v04NV_OA~c4;Ro$i0=q zSs^P{*SGME1kuMU>O-8il4l%}IWaP(7q;OcOOc?GS)wa}79LJAH&&gS?YcwNd@+Mx z)E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LlBPGmH2AN=!k;q{3;|F+no^l7XDQrvQEtRWHgeZdS>q^z>DZmCk)Mz?LYD&VVa~%*S61fd z%MjA;D-5uak`%@!5FUE;^b-;n@{4CI)3BEFTo9Hk)-6W8ge;8sQ;NXeS3^PfpuCC_ z9Fq-^FPiweUF)kFf&TSay#~qC{E%Npsk4C~qWjZRU7%S$?S`HIw6z2pYgcgf*g%iD z`l&w7#FNi2)?GCZkBkbSR(PD)W-rMr9jduCmC3;v^6S;6OUu@L`*SSnYNA5w1YRTU zoHD=0&w~4;Ya~v2a67C;W`AB;_mV`k^3`IF1w4C3_Jscwk#Ud8oYCoB(n(uZBKWxj zjMneC3=~K(vYkE!G~BHxua1B{&TW7fwI@bClDmyV_FX)VE??)Mn+n@KjKmOG!o!EB z1Y2TwjQIn1M{;SWg<-4J7UQ)b{kavtvzCY9P}^iTO+yEuvf?JaX6q?!ulnpuHBazT z`cp32t~M2Uk*uD%fC$h31Ip9zpT5P zdU=$bJbOVS_a7Z>t3&$6Qt=)H@o9wH(9H=yP8z3At#eJ@n614bHG1F)M8N6)PZaeZ zo%`P=f5rd*GF5dY7+8GJ|DTrrpE3|A^(tAPP=Hk8eC-^&-*XQ_{B^B diff --git a/docs/examples/illusia-voice/components.json b/docs/examples/illusia-voice/components.json new file mode 100644 index 0000000..2c417b6 --- /dev/null +++ b/docs/examples/illusia-voice/components.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "components": [ + { + "id": "illusia-now-playing", + "name": "ILLUSIA 当前频道 / current channel", + "page": "voice", + "accessibleName": "当前语音频道 / Current voice channel", + "permissions": ["session.status.read"], + "actions": {}, + "root": { + "tag": "aside", + "part": "room-card", + "className": "illusia-now-playing", + "attributes": { "role": "status" }, + "children": [ + { + "tag": "small", + "part": "eyebrow", + "children": [{ "text": "ILLUSIA · 当前频道 / NOW IN" }] + }, + { + "tag": "strong", + "part": "channel-name", + "children": [{ "text": "{{session.status.channelName}}" }] + } + ] + } + } + ] +} diff --git a/docs/examples/illusia-voice/layout.json b/docs/examples/illusia-voice/layout.json deleted file mode 100644 index 96c5260..0000000 --- a/docs/examples/illusia-voice/layout.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "pages": {} -} diff --git a/docs/examples/illusia-voice/manifest.json b/docs/examples/illusia-voice/manifest.json index cc897f0..86070a5 100644 --- a/docs/examples/illusia-voice/manifest.json +++ b/docs/examples/illusia-voice/manifest.json @@ -1,15 +1,14 @@ { - "schemaVersion": 2, - "packageType": "layout-skin", + "schemaVersion": 3, + "packageType": "open-skin", "id": "community.illusia-voice", "name": "ILLUSIA风", - "version": "1.0.29", + "version": "2.0.0", "author": "WebSpeak Project", "license": "All rights reserved", - "description": "A bright original-character art skin for the home, voice room, and demo pages.", + "description": "A bright original-character art skin with a safe declarative live-channel badge.", "entry": "skin.css", - "layout": "layout.json", - "permissions": [], + "components": "components.json", "preview": "assets/background-composite.webp", "minAppVersion": "0.2.7-preview" } diff --git a/docs/examples/illusia-voice/skin.css b/docs/examples/illusia-voice/skin.css index b913b3f..20d044b 100644 --- a/docs/examples/illusia-voice/skin.css +++ b/docs/examples/illusia-voice/skin.css @@ -271,6 +271,57 @@ } } +/* Open-skin compatibility sample: a small, non-interactive live-channel card. */ +[data-ws-page="voice"] .ws-plugin-component[data-ws-plugin-part="illusia-now-playing"] { + position: fixed; + z-index: 5; + top: 66px; + right: 18px; + display: grid; + gap: 3px; + width: min(236px, calc(100vw - 36px)); + min-height: 58px; + padding: 10px 56px 10px 14px; + overflow: hidden; + color: #15545b; + border: 1px solid rgba(71, 201, 212, .52); + border-radius: 17px; + background-image: linear-gradient(110deg, rgba(255, 255, 255, .95), rgba(219, 249, 250, .8)), url("assets/banner-mascot-blob.webp"); + background-repeat: no-repeat; + background-position: center, right 8px center; + background-size: auto, 42px 42px; + box-shadow: 0 12px 30px rgba(7, 55, 65, .16), inset 0 1px rgba(255, 255, 255, .9); + backdrop-filter: blur(12px); + pointer-events: none; +} + +[data-ws-page="voice"] [data-ws-plugin-part="illusia-now-playing.eyebrow"] { + color: #168f99; + font-size: 9px; + font-weight: 800; + letter-spacing: .08em; +} + +[data-ws-page="voice"] [data-ws-plugin-part="illusia-now-playing.channel-name"] { + overflow: hidden; + color: #173f48; + font-size: 13px; + font-weight: 750; + text-overflow: ellipsis; + white-space: nowrap; +} + +@media (max-width: 740px) { + [data-ws-page="voice"] .ws-plugin-component[data-ws-plugin-part="illusia-now-playing"] { + top: 62px; + right: 10px; + width: min(218px, calc(100vw - 20px)); + min-height: 52px; + padding-block: 8px; + border-radius: 14px; + } +} + [data-ws-part="home.join-title"] { color: var(--skin-illusia-ink); } diff --git a/docs/examples/kaak-voice.wskin b/docs/examples/kaak-voice.wskin new file mode 100644 index 0000000000000000000000000000000000000000..f3ae659aff6d96511f4586ab5ee434a3652c5d6d GIT binary patch literal 5805 zcmZ{oWl$WH=ez&&ncK_(=?mE?{-mdfhcvR%kF`lEKpkSl$qRAPuG)-1!qNAV`5u>0G{XI2v zgg7}mSU9-4ytQ?4bm-NRw_B7Y?)Y8J>e~3h9J!t848=C7!+Z8Ah=`*!ZSQrd{=$-3 zHMh_vF{#9_U<0VEtgH?!`pg6!M|U>#frF;{fiuOSVR?T%Mlym>V!x_i`;(^jzSGUs+}6^Ll|Nj}{~V)_SP94MrKAiS6Ir2ar%l8Z4~}FK>>2lRqgG|t z?|2GMv3ulJ?m3n+#c!j|m+sIZQtaq}x-^~;j4vpm6<(l3l~Tz{G+rt-pEdi5^)H!d zV2%ALj0*5h$Ge&vV99XZ!d-(?(xu@T&Z>>-%Kkfdln-u6TJQ)0MGb##Hew0KoT~`UU5<6D4rR;MWTqu+{-q; zIE-3p+pn|gp6^YnUi}RC7-Ez1Zs>aG z{@Pn}*GRI%htDoM&ki4J+g-YY?ct^!2Nt)IOQDKitG`7#M;6{UPmanQe_gYH8{tz0 z5A#A-3)%%lk9-S~^12N2OVtdkldidO6uNvUN?1~>pV$+R_w+c0Li<{!mGqv-cOx1> zNK|C$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7n(^@X*U8r>*@Hzi*vK3YJvq{VtUy2F<)c#D;J9b79>eD}n_z}>s+ zBJF|(;qVYn8?T_5 z-Ojo}@Y`z1a@w+DAf_36tNCOmCLS|u#2zZsMRHFKqXfK_FMa^n_Cnh?p+bO8QywD_ z2D8Abua=*e6|sVfXSOJWsEm}KBBrS&=#bz+qs19?p$P$IubsOE)HSu*eY-$2<1tiB zr)(6ttX;(ZK}~YYD>`qXp6Xb<4TXXM(p` zPwG!9BDG1~qmVf1d*v*^2jymgyq3Of6Tbq%`hdMeyR;+W2IzSV6vK8lir@LkuZ?g49 z(~d0f;@m_a(!|S?`awJA-4GL->U}4h$ky9rMlvjn7>2g4^`CWmz|Yk!Y^dQ=KekuP zw37PrycD5}wd4gH%?zBzD~9{19Y3N9g4H0Q(gT>Qs$6;`$W_RZvzKM}VLb&>&=fP^qBNl@!I4-@qw1u)CewP^ z4p{&hT{Ar(*k4VbcAw$#oNm;3edq`rnT_^m33iFh>{1RL)@U-+f70p69{g~tBEP)n zh-rgnbni{z*&Y~xBvCb1p1s)#_y0>(P|=>F{QtoAFE#kL@qh5`zl;A9CHhDC>n{T~ zbNq)H{k!r%;hcYzx)}cl?) error instanceof SkinRegistryError && error.code === "SKIN_LAYOUT_INVALID"); }); +test("server accepts v3 declarative components and rejects unapproved capability declarations", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v3-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const manifestV3 = { + ...manifest, + schemaVersion: 3, + packageType: "open-skin", + content: undefined, + preview: undefined, + components: "components.json", + }; + const components = { + schemaVersion: 1, + components: [{ + id: "channels", + name: "Channels", + page: "voice", + accessibleName: "TeamSpeak channels", + permissions: ["session.channels.read", "session.channel.join"], + actions: { join: { type: "voice.joinChannel", args: { channelId: "{{channel.id}}" } } }, + root: { tag: "nav", repeat: { path: "session.channels", as: "channel" }, children: [{ tag: "button", events: { dblclick: "join" }, children: [{ text: "{{channel.name}}" }] }] }, + }], + }; + const archive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV3))], + ["skin.css", Buffer.from('[data-ws-part="voice.channel-group"] { display: none; }')], + ["components.json", Buffer.from(JSON.stringify(components))], + ]); + const saved = await registry.save(archive, "sample-skin"); + assert.equal(saved.id, "sample-skin"); + assert.deepEqual(await registry.readArchive("sample-skin"), archive); + + const unapproved = structuredClone(components) as typeof components; + unapproved.components[0].permissions = ["network.fetch"]; + const unsafeArchive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV3))], + ["skin.css", Buffer.from("[data-ws-part=app] { color: red; }")], + ["components.json", Buffer.from(JSON.stringify(unapproved))], + ]); + await assert.rejects(registry.save(unsafeArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PLUGIN_INVALID"); +}); + test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => { const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-")); context.after(() => rm(directory, { recursive: true, force: true })); diff --git a/src/admin/skin-registry.ts b/src/admin/skin-registry.ts index c541200..c9a7e86 100644 --- a/src/admin/skin-registry.ts +++ b/src/admin/skin-registry.ts @@ -1,5 +1,6 @@ import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js"; import { parseSkinLayoutJson } from "../shared/skin-layout.js"; +import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../shared/skin-plugin.js"; import { randomBytes } from "node:crypto"; import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -41,11 +42,12 @@ interface SkinArchiveEntry { } type ParsedSkinManifest = Omit & { - schemaVersion: 1 | 2; - packageType?: "layout-skin"; + schemaVersion: 1 | 2 | 3; + packageType?: "layout-skin" | "open-skin"; entry: string; layout?: string; content?: string; + components?: string; preview?: string; }; @@ -226,7 +228,7 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa let previewBytes: Buffer | undefined; let previewMime: string | undefined; for (const [packagePath, data] of fileBytes) { - if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.preview].includes(packagePath)) continue; + if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.preview].includes(packagePath)) continue; const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null); if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED"); if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE"); @@ -245,6 +247,16 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa try { parseSkinLayoutJson(decodeUtf8(layout, "layout.json is not valid UTF-8.")); } catch (error) { throw new SkinRegistryError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); } } + if (manifest.components) { + const components = fileBytes.get(manifest.components); + if (!components || components.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("components.json is missing or exceeds 256 KiB.", "SKIN_PLUGIN_SIZE"); + let document: SkinPluginDocument; + try { document = parseSkinPluginJson(decodeUtf8(components, "components.json is not valid UTF-8.")); } + catch (error) { throw new SkinRegistryError("components.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_PLUGIN_INVALID"); } + for (const assetPath of listSkinPluginAssetPaths(document)) { + if (!fileBytes.has(assetPath) || !imageMime(assetPath)) throw new SkinRegistryError(`Component image asset is missing or unsupported: ${assetPath}`, "SKIN_PLUGIN_ASSET_INVALID"); + } + } if (manifest.preview) { previewBytes = fileBytes.get(manifest.preview); previewMime = imageMime(manifest.preview) ?? undefined; @@ -377,9 +389,10 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID"); const value = raw as Record; const schemaVersion = value.schemaVersion; - if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION"); - if (schemaVersion === 2) { + if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion >= 2) { const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]); + if (schemaVersion === 3) { fields.delete("permissions"); fields.add("components"); } const unknown = Object.keys(value).find((key) => !fields.has(key)); if (unknown) throw new SkinRegistryError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID"); } @@ -393,7 +406,8 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { if (schemaVersion === 2 && (value.packageType !== "layout-skin" || !Array.isArray(value.permissions) || value.permissions.length !== 0)) { throw new SkinRegistryError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID"); } - if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined)) { + if (schemaVersion === 3 && value.packageType !== "open-skin") throw new SkinRegistryError("Version 3 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID"); + if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined || value.components !== undefined)) { throw new SkinRegistryError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION"); } const version = read("version", 32); @@ -401,15 +415,16 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID"); const entry = read("entry", 120); const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max); - const layout = schemaVersion === 2 ? read("layout", 120) : undefined; + const layout = schemaVersion === 2 ? read("layout", 120) : schemaVersion === 3 && value.layout != null ? read("layout", 120) : undefined; const content = readOptional("content", 120); + const components = schemaVersion === 3 ? read("components", 120) : undefined; const preview = readOptional("preview", 120); - for (const candidate of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID"); - if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); - const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); + for (const candidate of [entry, layout, content, components, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID"); + if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, plugin components, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID"); const description = readOptional("description", 400); - return { schemaVersion, ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) }; + return { schemaVersion, ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion === 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) }; } function singleRootPrefix(paths: string[]): string { diff --git a/src/shared/skin-plugin.test.ts b/src/shared/skin-plugin.test.ts new file mode 100644 index 0000000..1fb9bc0 --- /dev/null +++ b/src/shared/skin-plugin.test.ts @@ -0,0 +1,122 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; +import { + parseSkinPluginDocument, + parseSkinPluginJson, + type SkinPluginDocument, + type SkinPluginNode, +} from "./skin-plugin.js"; + +function validDocument(): SkinPluginDocument { + return { + schemaVersion: 1, + components: [{ + id: "channel-list", + name: "Channel list", + page: "voice", + accessibleName: "TeamSpeak channels", + permissions: ["session.channels.read", "session.channel.join"], + actions: { + join: { type: "voice.joinChannel", args: { channelId: "{{channel.id}}" } }, + }, + root: { + tag: "nav", + repeat: { path: "session.channels", as: "channel" }, + children: [{ + tag: "button", + attributes: { type: "button", "aria-label": "{{channel.name}}" }, + events: { dblclick: "join" }, + children: [{ text: "{{channel.name}}" }], + }], + }, + }], + }; +} + +function errorCode(run: () => unknown, expected: string): void { + assert.throws(run, (error: unknown) => error instanceof Error + && "code" in error && error.code === expected); +} + +test("skin plugin accepts a bounded channel list with a double-click host action", () => { + const parsed = parseSkinPluginDocument(validDocument()); + assert.equal(parsed.components[0].root.repeat?.path, "session.channels"); + assert.equal(parsed.components[0].root.children?.[0].events?.dblclick, "join"); +}); + +test("KAAK v3 example uses only validated public session data and an explicit join action", async () => { + const source = await readFile(new URL("../../docs/examples/kaak-voice/components.json", import.meta.url), "utf8"); + const parsed = parseSkinPluginJson(source); + const sidebar = parsed.components[0]; + assert.equal(sidebar.id, "kaak-room-sidebar"); + assert.deepEqual(sidebar.permissions, ["session.channels.read", "session.members.read", "session.channel.join"]); + assert.equal(sidebar.actions["join-channel"].type, "voice.joinChannel"); + assert.equal(sidebar.root.children?.[1].children?.[0].repeat?.path, "session.channels"); +}); + +test("skin plugin binds form controls only to declared local state", () => { + const document = validDocument(); + document.components[0].state = { search: "" }; + document.components[0].root.children = [{ + tag: "input", + bindValue: "search", + events: { input: "filter" }, + }]; + document.components[0].actions.filter = { type: "ui.setState", args: { key: "search", value: "{{state.search}}" } }; + assert.equal(parseSkinPluginDocument(document).components[0].state?.search, ""); +}); + +test("skin plugin rejects undeclared permissions, arbitrary paths, and executable markup", () => { + const missingPermission = validDocument(); + missingPermission.components[0].permissions = ["session.channel.join"]; + errorCode(() => parseSkinPluginDocument(missingPermission), "SKIN_PLUGIN_PERMISSION_MISSING"); + + const hiddenPath = validDocument(); + hiddenPath.components[0].root.children![0].children = [{ text: "{{session.credentials.privateKey}}" }]; + errorCode(() => parseSkinPluginDocument(hiddenPath), "SKIN_PLUGIN_BINDING_INVALID"); + + const executable = validDocument(); + executable.components[0].root.children![0].attributes = { onclick: "alert(1)" }; + errorCode(() => parseSkinPluginDocument(executable), "SKIN_PLUGIN_ATTRIBUTE_INVALID"); + + const unsafeTag = validDocument(); + unsafeTag.components[0].root.children![0].tag = "iframe"; + errorCode(() => parseSkinPluginDocument(unsafeTag), "SKIN_PLUGIN_ELEMENT_INVALID"); + + 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"); +}); + +test("skin plugin restricts repeated fields to the selected collection", () => { + const document = validDocument(); + document.components[0].root.repeat = { path: "session.channels", as: "channel" }; + document.components[0].root.children = [{ text: "{{channel.author}}" }]; + errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_BINDING_INVALID"); +}); + +test("skin plugin never dispatches host actions from typing or selection changes", () => { + const document = validDocument(); + document.components[0].root.children![0].events = { change: "join" }; + errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_EVENT_INVALID"); +}); + +test("skin plugin JSON parser enforces a bounded document size and valid JSON", () => { + assert.throws(() => parseSkinPluginJson("{")); + assert.throws(() => parseSkinPluginJson(" ".repeat(256 * 1024 + 1))); + assert.equal(parseSkinPluginJson(JSON.stringify(validDocument())).components.length, 1); +}); + +test("skin plugin enforces each component's node and nesting limits", () => { + const broad = validDocument(); + broad.components[0].root.children = Array.from({ length: 101 }, () => ({ text: "item" })); + errorCode(() => parseSkinPluginDocument(broad), "SKIN_PLUGIN_TREE_INVALID"); + + const tooMany = validDocument(); + const branch = (depth: number): SkinPluginNode => depth === 0 + ? { tag: "span", children: [{ text: "item" }] } + : { tag: "span", children: Array.from({ length: 3 }, () => branch(depth - 1)) }; + tooMany.components[0].root.children = Array.from({ length: 3 }, () => branch(5)); + errorCode(() => parseSkinPluginDocument(tooMany), "SKIN_PLUGIN_COMPLEXITY_LIMIT"); +}); diff --git a/src/shared/skin-plugin.ts b/src/shared/skin-plugin.ts new file mode 100644 index 0000000..873f95d --- /dev/null +++ b/src/shared/skin-plugin.ts @@ -0,0 +1,364 @@ +/** Safe, declarative UI extensions shipped inside a v3 skin package. + * Extension authors provide a bounded component tree and action declarations, + * never executable HTML, JavaScript, or browser APIs. + */ +export const SKIN_PLUGIN_SCHEMA_VERSION = 1 as const; +export const SKIN_PLUGIN_DOCUMENT_LIMIT_BYTES = 256 * 1024; +export const SKIN_PLUGIN_COMPONENT_LIMIT = 32; +export const SKIN_PLUGIN_NODE_LIMIT = 256; +export const SKIN_PLUGIN_TREE_DEPTH_LIMIT = 16; +export const SKIN_PLUGIN_REPEAT_LIMIT = 100; + +export const SKIN_PLUGIN_PERMISSIONS = Object.freeze({ + "session.status.read": Object.freeze({ policyVersion: 1, description: "Read the current connection and channel summary." }), + "session.channels.read": Object.freeze({ policyVersion: 1, description: "Read the public TeamSpeak channel tree; the demo page uses synthetic sample data." }), + "session.members.read": Object.freeze({ policyVersion: 1, description: "Read visible member names and speaking states; the demo page uses synthetic sample data." }), + "chat.channel.read": Object.freeze({ policyVersion: 1, description: "Read the current public text channel; the demo page uses synthetic sample data." }), + "chat.channel.send": Object.freeze({ policyVersion: 1, description: "Send to the current public text channel; the demo page only simulates this action." }), + "favorites.read": Object.freeze({ policyVersion: 1, description: "Read favorite labels and opaque local identifiers, without server addresses or credentials." }), + "favorites.switch": Object.freeze({ policyVersion: 1, description: "Select a saved TeamSpeak server using the host's connection flow." }), + "session.channel.join": Object.freeze({ policyVersion: 1, description: "Request joining a visible TeamSpeak channel through the host; the demo page only changes simulated state." }), +} as const); + +export type SkinPluginPermission = keyof typeof SKIN_PLUGIN_PERMISSIONS; +export type SkinPluginPage = "home" | "voice" | "demo"; +export type SkinPluginEvent = "click" | "dblclick" | "change" | "input" | "submit" | "keydown"; +export type SkinPluginAction = "ui.setState" | "voice.joinChannel" | "favorites.switch" | "chat.sendMessage"; + +export interface SkinPluginActionDefinition { + type: SkinPluginAction; + args: Record; +} + +export interface SkinPluginNode { + tag?: string; + text?: string; + part?: string; + className?: string; + attributes?: Record; + asset?: string; + bindValue?: string; + repeat?: { path: string; as: string }; + when?: { path: string; equals?: string | number | boolean }; + events?: Partial>; + children?: SkinPluginNode[]; +} + +export interface SkinPluginComponent { + id: string; + name: string; + page: SkinPluginPage; + accessibleName: string; + permissions: SkinPluginPermission[]; + state?: Record; + actions: Record; + root: SkinPluginNode; +} + +export interface SkinPluginDocument { + schemaVersion: typeof SKIN_PLUGIN_SCHEMA_VERSION; + components: SkinPluginComponent[]; +} + +export interface SkinPluginApproval { + pluginId: string; + policyVersions: Partial>; +} + +export class SkinPluginValidationError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinPluginValidationError"; + } +} + +const ELEMENTS = new Set([ + "article", "aside", "button", "circle", "code", "dd", "details", "div", "dl", "dt", "em", "figcaption", "figure", "footer", "form", + "g", "h1", "h2", "h3", "h4", "header", "hr", "img", "input", "label", "li", "line", "main", "nav", "ol", "option", + "output", "p", "path", "polyline", "rect", "section", "select", "small", "span", "strong", "summary", "svg", "textarea", "time", "ul", +]); +const VOID_ELEMENTS = new Set(["circle", "hr", "img", "input", "line", "path", "polyline", "rect"]); +const ATTRIBUTES = new Set([ + "alt", "aria-current", "aria-expanded", "aria-hidden", "aria-label", "aria-pressed", "aria-selected", "class", "colspan", "fill", + "height", "max", "min", "name", "placeholder", "role", "rowspan", "stroke", "stroke-linecap", "stroke-linejoin", "stroke-width", + "tabindex", "title", "type", "value", "viewbox", "width", "x", "x1", "x2", "y", "y1", "y2", +]); +const EVENTS = new Set(["click", "dblclick", "change", "input", "submit", "keydown"]); +const ACTIONS = new Set(["ui.setState", "voice.joinChannel", "favorites.switch", "chat.sendMessage"]); +const PERMISSIONS = new Set(Object.keys(SKIN_PLUGIN_PERMISSIONS)); +const ACTION_ARGS: Record> = { + "ui.setState": new Set(["key", "value"]), + "voice.joinChannel": new Set(["channelId"]), + "favorites.switch": new Set(["favoriteId"]), + "chat.sendMessage": new Set(["text"]), +}; +const ACTION_PERMISSION: Record = { + "ui.setState": null, + "voice.joinChannel": "session.channel.join", + "favorites.switch": "favorites.switch", + "chat.sendMessage": "chat.channel.send", +}; +const COLLECTION_PERMISSION: Record = { + "session.channels": "session.channels.read", + "session.members": "session.members.read", + "favorites.items": "favorites.read", + "chat.messages": "chat.channel.read", +}; +const COLLECTION_FIELDS: Record> = { + "session.channels": new Set(["id", "name", "parentId", "depth", "memberCount", "current"]), + "session.members": new Set(["id", "name", "channelId", "status", "speaking", "self"]), + "favorites.items": new Set(["id", "label", "current", "kind"]), + "chat.messages": new Set(["id", "author", "text", "time", "kind", "channelId"]), +}; +const SESSION_STATUS_FIELDS = new Set(["connected", "connecting", "serverLabel", "channelId", "channelName", "userName"]); + +function fail(code: string, message: string): never { throw new SkinPluginValidationError(code, message); } +function isRecord(value: unknown): value is Record { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } +function onlyKeys(value: Record, allowed: ReadonlySet, context: string): void { + const unknown = Object.keys(value).find((key) => !allowed.has(key)); + if (unknown) fail("SKIN_PLUGIN_FIELD_INVALID", `${context} contains an unsupported field: ${unknown}.`); +} +function boundedText(value: unknown, field: string, max = 160): string { + if (typeof value !== "string" || !value.trim() || value.length > max || value !== value.trim()) fail("SKIN_PLUGIN_FIELD_INVALID", `${field} must be a non-empty bounded string.`); + return value; +} +function identifier(value: unknown, field: string): string { + const result = boundedText(value, field, 64); + if (!/^[a-z][a-z0-9-]*$/.test(result)) fail("SKIN_PLUGIN_FIELD_INVALID", `${field} must use a lowercase identifier.`); + return result; +} +function bindingPermissions(value: string, aliases: ReadonlyMap, stateKeys: ReadonlySet): SkinPluginPermission[] { + const found = new Set(); + for (const match of value.matchAll(/\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g)) { + const path = match[1].split("."); + if (path[0] === "state") { + if (path.length !== 2 || !stateKeys.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A state binding must reference a declared local state key."); + continue; + } + const aliasCollection = aliases.get(path[0]); + if (aliasCollection) { + if (path.length !== 2 || !COLLECTION_FIELDS[aliasCollection]?.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A repeated item binding references an unsupported public field."); + continue; + } + if (path[0] === "session" && path.length === 3 && path[1] === "status" && SESSION_STATUS_FIELDS.has(path[2])) { + found.add("session.status.read"); + continue; + } + const collectionPath = path.slice(0, 2).join("."); + const permission = COLLECTION_PERMISSION[collectionPath]; + if (permission && (path.length === 2 || (path.length === 3 && COLLECTION_FIELDS[collectionPath].has(path[2])))) { + found.add(permission); + continue; + } + fail("SKIN_PLUGIN_BINDING_INVALID", `The data path ${match[1]} is not available to skin components.`); + } + if (/\{\{[^}]*\}\}/.test(value.replace(/\{\{\s*[a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5}\s*\}\}/g, ""))) { + fail("SKIN_PLUGIN_BINDING_INVALID", "A component binding must use a simple registered data path."); + } + return [...found]; +} + +export function parseSkinPluginDocument(input: unknown): SkinPluginDocument { + if (!isRecord(input)) fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json must contain an object."); + onlyKeys(input, new Set(["schemaVersion", "components"]), "components.json"); + if (input.schemaVersion !== SKIN_PLUGIN_SCHEMA_VERSION || !Array.isArray(input.components) + || !input.components.length || input.components.length > SKIN_PLUGIN_COMPONENT_LIMIT) { + fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json uses an unsupported schema or component count."); + } + const ids = new Set(); + const components = input.components.map((rawComponent, componentIndex): SkinPluginComponent => { + if (!isRecord(rawComponent)) fail("SKIN_PLUGIN_COMPONENT_INVALID", `Component ${componentIndex} must be an object.`); + onlyKeys(rawComponent, new Set(["id", "name", "page", "accessibleName", "permissions", "actions", "state", "root"]), "Skin plugin component"); + const id = identifier(rawComponent.id, "component.id"); + if (ids.has(id)) fail("SKIN_PLUGIN_COMPONENT_DUPLICATE", "Component IDs must be unique within the skin."); + ids.add(id); + if (!(rawComponent.page === "home" || rawComponent.page === "voice" || rawComponent.page === "demo")) fail("SKIN_PLUGIN_COMPONENT_INVALID", "A plugin component must target a public page."); + const page = rawComponent.page as SkinPluginPage; + const name = boundedText(rawComponent.name, "component.name", 80); + const accessibleName = boundedText(rawComponent.accessibleName, "component.accessibleName", 120); + if (!Array.isArray(rawComponent.permissions) || rawComponent.permissions.length > 8) fail("SKIN_PLUGIN_PERMISSION_INVALID", "Each component may request at most eight explicit permissions."); + const permissions: SkinPluginPermission[] = []; + for (const permission of rawComponent.permissions) { + if (typeof permission !== "string" || !PERMISSIONS.has(permission)) fail("SKIN_PLUGIN_PERMISSION_UNKNOWN", "The component requests an unsupported permission."); + if (permissions.includes(permission as SkinPluginPermission)) fail("SKIN_PLUGIN_PERMISSION_DUPLICATE", "A component permission is duplicated."); + permissions.push(permission as SkinPluginPermission); + } + const state: Record = Object.create(null) as Record; + if (rawComponent.state !== undefined) { + if (!isRecord(rawComponent.state) || Object.keys(rawComponent.state).length > 32) fail("SKIN_PLUGIN_STATE_INVALID", "A component may declare up to 32 local state values."); + for (const [key, value] of Object.entries(rawComponent.state)) { + identifier(key, "state.key"); + if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_STATE_INVALID", "Component state values must be scalar."); + if (typeof value === "string" && value.length > 512) fail("SKIN_PLUGIN_STATE_INVALID", "A component state string exceeds its limit."); + state[key] = value; + } + } + const stateKeys = new Set(Object.keys(state)); + if (!isRecord(rawComponent.actions)) fail("SKIN_PLUGIN_ACTION_INVALID", "A component must declare an action map."); + const actionEntries = Object.entries(rawComponent.actions); + if (actionEntries.length > 24) fail("SKIN_PLUGIN_ACTION_INVALID", "A component declares too many actions."); + const actions: Record = Object.create(null) as Record; + for (const [actionId, rawAction] of actionEntries) { + identifier(actionId, "action.id"); + if (!isRecord(rawAction)) fail("SKIN_PLUGIN_ACTION_INVALID", "An action must be an object."); + onlyKeys(rawAction, new Set(["type", "args"]), "Component action"); + if (typeof rawAction.type !== "string" || !ACTIONS.has(rawAction.type)) fail("SKIN_PLUGIN_ACTION_UNKNOWN", "An action type is not supported by the host."); + if (!isRecord(rawAction.args)) fail("SKIN_PLUGIN_ACTION_INVALID", "An action must define an argument object."); + const requiredPermission = ACTION_PERMISSION[rawAction.type as SkinPluginAction]; + if (requiredPermission && !permissions.includes(requiredPermission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawAction.type} action requires ${requiredPermission}.`); + if (Object.keys(rawAction.args).length > 8) fail("SKIN_PLUGIN_ACTION_INVALID", "An action has too many arguments."); + const args: Record = Object.create(null) as Record; + for (const [key, value] of Object.entries(rawAction.args)) { + if (!/^[a-z][a-zA-Z0-9]{0,31}$/.test(key) || !ACTION_ARGS[rawAction.type as SkinPluginAction].has(key)) fail("SKIN_PLUGIN_ACTION_INVALID", "An action uses an unsupported argument name."); + if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_ACTION_INVALID", "Action arguments must be static scalars or simple data bindings."); + if (typeof value === "string") { + if (value.length > 512) fail("SKIN_PLUGIN_ACTION_INVALID", "An action argument exceeds its length limit."); + } + args[key] = value; + } + if (rawAction.type === "ui.setState" && (typeof args.key !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(args.key) || !stateKeys.has(args.key) || !("value" in args))) { + fail("SKIN_PLUGIN_ACTION_INVALID", "ui.setState requires a local state key and value."); + } + if (rawAction.type === "voice.joinChannel" && typeof args.channelId !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "voice.joinChannel requires a channelId binding."); + if (rawAction.type === "favorites.switch" && typeof args.favoriteId !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "favorites.switch requires a favoriteId binding."); + if (rawAction.type === "chat.sendMessage" && typeof args.text !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "chat.sendMessage requires a text binding."); + actions[actionId] = { type: rawAction.type as SkinPluginAction, args }; + } + let componentNodes = 0; + const walk = (rawNode: unknown, depth: number, aliases: ReadonlyMap = new Map()): SkinPluginNode => { + componentNodes += 1; + if (componentNodes > SKIN_PLUGIN_NODE_LIMIT) fail("SKIN_PLUGIN_COMPLEXITY_LIMIT", "A component contains too many template nodes."); + if (depth > SKIN_PLUGIN_TREE_DEPTH_LIMIT || !isRecord(rawNode)) fail("SKIN_PLUGIN_TREE_INVALID", "A component tree is too deep or contains an invalid node."); + onlyKeys(rawNode, new Set(["tag", "text", "part", "className", "attributes", "asset", "bindValue", "repeat", "when", "events", "children"]), "Component node"); + if ((rawNode.tag === undefined) === (rawNode.text === undefined)) fail("SKIN_PLUGIN_TREE_INVALID", "Each component node must define either a tag or text, but not both."); + const node: SkinPluginNode = {}; + if (rawNode.tag !== undefined) { + if (typeof rawNode.tag !== "string" || !ELEMENTS.has(rawNode.tag)) fail("SKIN_PLUGIN_ELEMENT_INVALID", "The component uses an unsupported HTML element."); + node.tag = rawNode.tag; + } + if (rawNode.text !== undefined) { + node.text = boundedText(rawNode.text, "node.text", 2048); + for (const permission of bindingPermissions(node.text, aliases, stateKeys)) { + if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The component data requires ${permission}.`); + } + } + if (rawNode.part !== undefined) node.part = identifier(rawNode.part, "node.part"); + if (rawNode.className !== undefined) { + if (typeof rawNode.className !== "string" || rawNode.className.length > 160 || /[<>]/.test(rawNode.className)) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component class names must be bounded plain text."); + node.className = rawNode.className; + } + if (rawNode.attributes !== undefined) { + if (!isRecord(rawNode.attributes) || Object.keys(rawNode.attributes).length > 24) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component attributes must be a small object."); + const attrs: Record = Object.create(null) as Record; + for (const [key, value] of Object.entries(rawNode.attributes)) { + const lowerKey = key.toLowerCase(); + if (!ATTRIBUTES.has(lowerKey) || lowerKey.startsWith("on") || key !== lowerKey) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "The component uses an unsupported or executable attribute."); + if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component attributes must be scalar values."); + if (typeof value === "string" && ["fill", "stroke"].includes(lowerKey) && /\burl\s*\(|javascript\s*:/i.test(value)) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "SVG paint attributes cannot load external or executable resources."); + if (typeof value === "string") { + for (const permission of bindingPermissions(value, aliases, stateKeys)) { + if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The component data requires ${permission}.`); + } + if (value.length > 512) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "A component attribute exceeds its length limit."); + } + attrs[key] = value; + } + node.attributes = attrs; + } + if (rawNode.asset !== undefined) { + const asset = boundedText(rawNode.asset, "node.asset", 120); + if (node.tag !== "img") fail("SKIN_PLUGIN_ASSET_INVALID", "Package image assets can only be attached to img elements."); + if (!/^assets\/[a-zA-Z0-9._/-]+$/.test(asset) || asset.split("/").some((part) => !part || part === "." || part === "..")) fail("SKIN_PLUGIN_ASSET_INVALID", "Component assets must use safe package-relative paths."); + node.asset = asset; + } + if (rawNode.bindValue !== undefined) { + const key = identifier(rawNode.bindValue, "node.bindValue"); + if (node.tag !== "input" && node.tag !== "select" && node.tag !== "textarea") fail("SKIN_PLUGIN_BINDING_INVALID", "Only input, select, and textarea elements can bind local state."); + if (!stateKeys.has(key)) fail("SKIN_PLUGIN_BINDING_INVALID", "A bound form control must reference a declared local state key."); + node.bindValue = key; + } + if (rawNode.repeat !== undefined) { + if (!isRecord(rawNode.repeat)) fail("SKIN_PLUGIN_REPEAT_INVALID", "A repeat declaration must be an object."); + onlyKeys(rawNode.repeat, new Set(["path", "as"]), "Repeat declaration"); + const path = boundedText(rawNode.repeat.path, "repeat.path", 120); + if (!(path === "session.channels" || path === "session.members" || path === "favorites.items" || path === "chat.messages")) fail("SKIN_PLUGIN_REPEAT_INVALID", "A component may repeat only a registered public collection."); + const permission = COLLECTION_PERMISSION[path]; + if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `Repeating ${path} requires ${permission}.`); + const alias = identifier(rawNode.repeat.as, "repeat.as"); + if (aliases.has(alias)) fail("SKIN_PLUGIN_REPEAT_INVALID", "Repeat aliases cannot shadow an existing alias."); + node.repeat = { path, as: alias }; + } + if (rawNode.when !== undefined) { + if (!isRecord(rawNode.when)) fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition must be an object."); + onlyKeys(rawNode.when, new Set(["path", "equals"]), "Component condition"); + const path = boundedText(rawNode.when.path, "condition.path", 120); + for (const permission of bindingPermissions(`{{${path}}}`, aliases, stateKeys)) { + if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition data requires ${permission}.`); + } + const equals = rawNode.when.equals; + if (equals !== undefined && typeof equals !== "string" && typeof equals !== "number" && typeof equals !== "boolean") fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition comparison must be scalar."); + node.when = { path, ...(equals === undefined ? {} : { equals }) }; + } + if (rawNode.events !== undefined) { + if (!isRecord(rawNode.events) || Object.keys(rawNode.events).length > 6) fail("SKIN_PLUGIN_EVENT_INVALID", "Component events must be a small object."); + const events: Partial> = {}; + for (const [event, actionIdValue] of Object.entries(rawNode.events)) { + if (!EVENTS.has(event) || typeof actionIdValue !== "string" || !actions[actionIdValue]) fail("SKIN_PLUGIN_EVENT_INVALID", "Each component event must refer to a declared host action."); + const action = actions[actionIdValue]; + if (action.type !== "ui.setState" && (event === "input" || event === "change")) fail("SKIN_PLUGIN_EVENT_INVALID", "Host actions cannot run while a form value is being typed or changed."); + for (const argument of Object.values(action.args)) { + if (typeof argument !== "string") continue; + for (const permission of bindingPermissions(argument, aliases, stateKeys)) { + if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The event data requires ${permission}.`); + } + } + events[event as SkinPluginEvent] = actionIdValue; + } + node.events = events; + } + if (rawNode.children !== undefined) { + if (!Array.isArray(rawNode.children) || rawNode.children.length > 100) fail("SKIN_PLUGIN_TREE_INVALID", "A component node contains too many children."); + if (node.tag && VOID_ELEMENTS.has(node.tag) && rawNode.children.length) fail("SKIN_PLUGIN_TREE_INVALID", "A void element cannot contain child nodes."); + const childAliases = new Map(aliases); + if (node.repeat) childAliases.set(node.repeat.as, node.repeat.path); + node.children = rawNode.children.map((child) => walk(child, depth + 1, childAliases)); + } + return node; + }; + const root = walk(rawComponent.root, 1); + if (!root.tag) fail("SKIN_PLUGIN_TREE_INVALID", "A plugin component root must be an element."); + return { id, name, page, accessibleName, permissions, actions, ...(Object.keys(state).length ? { state } : {}), root }; + }); + return { schemaVersion: SKIN_PLUGIN_SCHEMA_VERSION, components }; +} + +export function parseSkinPluginJson(source: string): SkinPluginDocument { + if (!source || new TextEncoder().encode(source).byteLength > SKIN_PLUGIN_DOCUMENT_LIMIT_BYTES) fail("SKIN_PLUGIN_DOCUMENT_SIZE", "components.json exceeds the 256 KiB limit."); + let input: unknown; + try { input = JSON.parse(source); } catch { fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json must contain valid JSON."); } + return parseSkinPluginDocument(input); +} + +export function listSkinPluginAssetPaths(document: SkinPluginDocument): string[] { + const paths = new Set(); + const visit = (node: SkinPluginNode) => { + if (node.asset) paths.add(node.asset); + node.children?.forEach(visit); + }; + document.components.forEach((component) => visit(component.root)); + return [...paths]; +} + +export function createSkinPluginApproval(pluginId: string, permissions: readonly SkinPluginPermission[]): SkinPluginApproval { + const policyVersions: Partial> = {}; + for (const permission of permissions) policyVersions[permission] = SKIN_PLUGIN_PERMISSIONS[permission].policyVersion; + return { pluginId, policyVersions }; +} + +export function isSkinPluginPermissionApproved(approval: SkinPluginApproval | null | undefined, pluginId: string, permission: SkinPluginPermission): boolean { + return approval?.pluginId === pluginId && approval.policyVersions[permission] === SKIN_PLUGIN_PERMISSIONS[permission].policyVersion; +} + +export function skinPluginActionPermission(action: SkinPluginAction): SkinPluginPermission | null { + return ACTION_PERMISSION[action]; +} diff --git a/web/public/skins/illusia-voice.wskin b/web/public/skins/illusia-voice.wskin index d8544f876ba46db52faddf913ac90e8f3dc8a176..12641f277aff1d98d36b6ffbdcccbd6fbeb07a4e 100644 GIT binary patch delta 8562 zcmZviWlSAF_vV3%yHlLv?pmaHad)`5Q(TK(`v8s#l-`z|deAFaQh-h6BTc5x|IGBrq}<1&j(t1EYg6z?fhx zFg6$mj0?sCrUTQ18NiHSCNMLY z1j zIz%UQEA_Ku4m}GEj=HK3tf6semW>4jK)X9-soRa#GUZ5==A%ZTqLyF;48(l;l&0gA zD)+z=m(?8&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azT z`cp32t~M2Uk*uD%fC$h31Ip9zpT5P zdU=$bJbOVS_a7Z>t3&$6Qt=)H@o9wH(9H=yP8z3At#eJ@n614bHG1F)M8N6)PZaeZ zo%`P=f5rd*GF5dY7+8GJ|DTrrpE3|A^(tAPP=Hk8eC-^&-*XQ_{B^B diff --git a/web/src/components/SkinPluginOutlet.ts b/web/src/components/SkinPluginOutlet.ts new file mode 100644 index 0000000..56a708d --- /dev/null +++ b/web/src/components/SkinPluginOutlet.ts @@ -0,0 +1,236 @@ +import { computed, defineComponent, Fragment, h, onUnmounted, reactive, ref, Teleport, watch, type PropType, type VNodeChild } from "vue"; +import { + SKIN_PLUGIN_PERMISSIONS, + parseSkinPluginDocument, + type SkinPluginActionDefinition, + type SkinPluginComponent, + type SkinPluginDocument, + type SkinPluginNode, +} from "../../../src/shared/skin-plugin.js"; +import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js"; + +type Scalar = string | number | boolean; +type SafeContext = Record; +type HostAction = (args: Record, component: SkinPluginComponent) => void | Promise; + +const eventProps: Record = { + click: "onClick", dblclick: "onDblclick", change: "onChange", input: "onInput", submit: "onSubmit", keydown: "onKeydown", +}; + +export default defineComponent({ + name: "SkinPluginOutlet", + props: { + skinId: { type: String, required: true }, + skinVersion: { type: String, required: true }, + document: { type: Object as PropType, required: true }, + page: { type: String as PropType<"home" | "voice" | "demo">, required: true }, + data: { type: Object as PropType, required: true }, + assets: { type: Object as PropType>, required: true }, + actions: { type: Object as PropType>, required: true }, + }, + setup(props) { + const denied = ref(false); + const manageOpen = ref(false); + const refresh = ref(0); + const stateByComponent = reactive>>({}); + const objectUrls = new Map(); + const validatedDocument = computed(() => { + try { return parseSkinPluginDocument(props.document); } + catch { return { schemaVersion: 1 as const, components: [] }; } + }); + const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page)); + const pendingApproval = computed(() => { + refresh.value; + return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value }); + }); + const accessComponents = computed(() => pendingApproval.value.length + ? pendingApproval.value + : matchingComponents.value.filter((component) => component.permissions.length > 0)); + const activeComponents = computed(() => { + refresh.value; + return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)); + }); + + watch(() => [props.skinId, props.skinVersion, props.document, props.page], () => { denied.value = false; refresh.value += 1; }, { immediate: true }); + + function localState(component: SkinPluginComponent): Record { + const key = `${props.skinId}/${component.id}`; + if (!stateByComponent[key]) stateByComponent[key] = { ...(component.state ?? {}) }; + return stateByComponent[key]; + } + + function permissionLabel(permission: string): string { + return SKIN_PLUGIN_PERMISSIONS[permission as keyof typeof SKIN_PLUGIN_PERMISSIONS]?.description ?? permission; + } + + function resolvePath(path: string, context: SafeContext, state: Record): unknown { + const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, ""); + const parts = normalized.split("."); + let value: unknown = parts[0] === "state" ? state : context; + const start = parts[0] === "state" ? 1 : 0; + for (let index = start; index < parts.length; index += 1) { + if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, parts[index])) return undefined; + value = (value as Record)[parts[index]]; + } + return value; + } + + function interpolate(value: string, context: SafeContext, state: Record): string { + return value.replace(/\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g, (_match, path: string) => { + const resolved = resolvePath(path, context, state); + return typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" ? String(resolved) : ""; + }); + } + + function resolveActionArgs(definition: SkinPluginActionDefinition, context: SafeContext, state: Record): Record { + const args: Record = {}; + for (const [key, value] of Object.entries(definition.args)) { + if (typeof value !== "string") { args[key] = value; continue; } + const exact = /^\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}$/.exec(value); + const resolved = exact ? resolvePath(exact[1], context, state) : interpolate(value, context, state); + if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean") args[key] = resolved; + } + return args; + } + + function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record): void { + const definition = component.actions[actionId]; + if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return; + const args = resolveActionArgs(definition, context, state); + if (definition.type === "ui.setState") { + if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) state[args.key] = args.value; + return; + } + const handler = props.actions[definition.type]; + if (handler) void Promise.resolve(handler(args, component)).catch(() => undefined); + } + + function assetUrl(path: string): string | undefined { + const current = props.assets[path]; + if (!(current instanceof Blob)) return undefined; + let url = objectUrls.get(path); + if (!url) { url = URL.createObjectURL(current); objectUrls.set(path, url); } + return url; + } + + function renderNode(component: SkinPluginComponent, node: SkinPluginNode, context: SafeContext, state: Record, skipRepeat = false): VNodeChild { + if (!node.tag) return interpolate(node.text ?? "", context, state); + if (!skipRepeat && node.repeat) { + const values = resolvePath(node.repeat.path, context, state); + if (!Array.isArray(values)) return null; + return h(Fragment, null, values.slice(0, 100).map((value) => renderNode(component, node, { ...context, [node.repeat!.as]: value }, state, true))); + } + if (node.when) { + const value = resolvePath(node.when.path, context, state); + if (node.when.equals !== undefined ? value !== node.when.equals : !value) return null; + } + const attrs: Record = {}; + for (const [key, value] of Object.entries(node.attributes ?? {})) { + attrs[key === "viewbox" ? "viewBox" : key] = typeof value === "string" ? interpolate(value, context, state) : value; + } + if (node.asset) { + const url = assetUrl(node.asset); + if (url) attrs.src = url; + } + if (node.className || attrs.class) { + attrs.class = ["ws-plugin-node", node.className, attrs.class].filter(Boolean).join(" "); + } else attrs.class = "ws-plugin-node"; + attrs["data-ws-plugin-part"] = node.part ? `${component.id}.${node.part}` : component.id; + if (node.bindValue) attrs.value = state[node.bindValue]; + + for (const [eventName, actionId] of Object.entries(node.events ?? {})) { + const propName = eventProps[eventName]; + if (!propName) continue; + attrs[propName] = (event: Event) => { + if (!event.isTrusted) return; + if (eventName === "keydown" && event instanceof KeyboardEvent && event.key !== "Enter" && event.key !== " ") return; + if (node.bindValue && eventName === "input" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)) { + state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value; + } else if (node.bindValue && eventName === "change" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLSelectElement || event.target instanceof HTMLTextAreaElement)) { + state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value; + } + if (eventName === "submit") event.preventDefault(); + dispatch(component, actionId, context, state); + }; + } + if (node.bindValue && !node.events?.input && !node.events?.change) { + attrs[node.tag === "input" ? "onInput" : "onChange"] = (event: Event) => { + if (!event.isTrusted) return; + const target = event.target; + if (target instanceof HTMLInputElement) state[node.bindValue!] = target.type === "checkbox" ? target.checked : target.value; + else if (target instanceof HTMLTextAreaElement) state[node.bindValue!] = target.value; + else if (target instanceof HTMLSelectElement) state[node.bindValue!] = target.value; + }; + } + if (node.tag === "form" && !node.events?.submit) attrs.onSubmit = (event: Event) => event.preventDefault(); + const children = (node.children ?? []).map((child) => renderNode(component, child, context, state)); + return h(node.tag, attrs, children); + } + + function accept(): void { + approveSkinPluginComponents(props.skinId, props.skinVersion, pendingApproval.value); + denied.value = false; + manageOpen.value = false; + refresh.value += 1; + } + + function openAccessManager(): void { + denied.value = false; + manageOpen.value = true; + } + + function closeOrDisable(): void { + if (pendingApproval.value.length) denied.value = true; + manageOpen.value = false; + } + + function revokeAll(): void { + revokeSkinPluginApprovals(props.skinId); + denied.value = true; + manageOpen.value = false; + refresh.value += 1; + } + + onUnmounted(() => { objectUrls.forEach((url) => URL.revokeObjectURL(url)); objectUrls.clear(); }); + + return () => { + const nodes: VNodeChild[] = activeComponents.value.map((component) => h("div", { + key: `${props.skinId}:${component.id}`, + class: "ws-plugin-component", + "data-ws-plugin-component": component.id, + "data-ws-plugin-name": component.name, + "data-ws-plugin-part": component.id, + "aria-label": component.accessibleName, + }, [renderNode(component, component.root, props.data, localState(component))])); + const hasPermissions = matchingComponents.value.some((component) => component.permissions.length > 0); + const showConsent = pendingApproval.value.length > 0 || manageOpen.value; + const accessToggle = hasPermissions ? h(Teleport, { to: "body" }, [h("button", { + type: "button", + class: "ws-plugin-access-toggle", + "aria-label": "管理皮肤组件权限 / Manage skin component access", + onClick: openAccessManager, + }, "权限 / Access")]) : null; + if (!showConsent) return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : [])]); + + const requested = accessComponents.value; + const hasMissing = pendingApproval.value.length > 0; + const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-plugin-consent": "true" }, [ + h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-plugin-consent-title" }, [ + h("h2", { id: "ws-plugin-consent-title" }, "皮肤组件权限 / Skin component access"), + h("p", null, "此皮肤包含会读取公开语音界面数据或请求宿主动作的组件。只有你批准的组件才会启用。/ This skin requests limited access for its components. Only approved components will run."), + ...requested.map((component) => h("div", { class: "ws-plugin-consent-item", key: component.id }, [ + h("strong", null, component.name), + h("ul", null, component.permissions.map((permission) => h("li", { key: permission }, permissionLabel(permission)))), + ])), + h("p", { class: "ws-plugin-consent-note" }, "组件不能运行脚本、访问浏览器存储、读取连接地址/密码或控制麦克风。/ Components cannot run code, access storage or credentials, or control the microphone."), + h("div", { class: "ws-plugin-consent-actions" }, [ + ...(hasMissing ? [h("button", { type: "button", class: "secondary", onClick: closeOrDisable }, "暂不启用 / Keep disabled")] + : [h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access")]), + h("button", { type: "button", class: "primary", onClick: hasMissing ? accept : () => { manageOpen.value = false; } }, hasMissing ? "批准所列权限 / Approve listed access" : "关闭 / Close"), + ]), + ]), + ])]); + return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : []), consent]); + }; + }, +}); diff --git a/web/src/services/skin-catalog.ts b/web/src/services/skin-catalog.ts index f460420..a5933b5 100644 --- a/web/src/services/skin-catalog.ts +++ b/web/src/services/skin-catalog.ts @@ -32,10 +32,10 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [ { id: BUILTIN_ILLUSIA_SKIN_ID, name: "ILLUSIA风", - version: "1.0.29", + version: "2.0.0", author: "WebSpeak Project", license: "All rights reserved", - description: "A bright original-character art skin for the home, voice room, and demo pages.", + description: "A bright original-character art skin with a safe declarative live-channel badge.", minAppVersion: "0.2.7-preview", previewUrl: "/skins/illusia-voice-preview.webp", installedAt: 0, diff --git a/web/src/services/skin-pack.test.ts b/web/src/services/skin-pack.test.ts index 1b1e2f6..0e69232 100644 --- a/web/src/services/skin-pack.test.ts +++ b/web/src/services/skin-pack.test.ts @@ -4,6 +4,7 @@ import test from "node:test"; import { strToU8, zipSync } from "fflate"; import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js"; import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js"; +import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js"; const manifest = { schemaVersion: 1, @@ -127,18 +128,19 @@ test("skin content supports localized interface message overrides and includes t assert.ok(skin.assets["assets/preview.png"]); }); -test("the ILLUSIA v2 example and bundled package import without replacing WebSpeak's base translations", async () => { +test("the ILLUSIA v3 example and bundled package import without replacing WebSpeak's base translations", async () => { const exampleBytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url)); const bundledBytes = await readFile(new URL("../../public/skins/illusia-voice.wskin", import.meta.url)); assert.deepEqual(bundledBytes, exampleBytes); const skin = await importSkinPack(new File([exampleBytes], "illusia-voice.wskin", { type: "application/octet-stream" })); assert.equal(skin.id, "community.illusia-voice"); assert.equal(skin.name, "ILLUSIA风"); - assert.equal(skin.version, "1.0.29"); - assert.equal(skin.schemaVersion, 2); - assert.equal(skin.packageType, "layout-skin"); - assert.deepEqual(skin.permissions, []); - assert.deepEqual(skin.layoutData, { schemaVersion: 1, pages: {} }); + assert.equal(skin.version, "2.0.0"); + assert.equal(skin.schemaVersion, 3); + assert.equal(skin.packageType, "open-skin"); + assert.equal(skin.layoutData, undefined); + assert.equal(skin.pluginData?.components[0].id, "illusia-now-playing"); + assert.deepEqual(skin.pluginData?.components[0].permissions, ["session.status.read"]); assert.equal(skin.minAppVersion, "0.2.7-preview"); assert.equal(skin.contentData, undefined); assert.equal(skin.previewBlob?.type, "image/webp"); @@ -160,6 +162,7 @@ test("the ILLUSIA v2 example and bundled package import without replacing WebSpe assert.match(skin.css, /language\.option/); assert.match(skin.css, /data-ws-skin-id="community\.illusia-voice"/); assert.match(skin.css, /data-ws-part="voice\.favorite-servers\.rail"/); + assert.match(skin.css, /data-ws-plugin-part="illusia-now-playing\.channel-name"/); assert.match(skin.css, /data-ws-part="home\.server-history\.item"/); assert.match(skin.css, /data-ws-part="home\.server-history\.favorite-toggle"\]\[data-ws-state="saved"\]/); assert.match(skin.css, /data-ws-part="voice\.favorite-servers\.favorite-toggle"\]\[data-ws-state="saved"\]/); @@ -191,7 +194,8 @@ test("the ILLUSIA v2 example and bundled package import without replacing WebSpe assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*\{[^}]*background-position:\s*0 0, right 8px center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s); assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s); assert.doesNotMatch(skin.css, /data-ws-state="messages-empty"[^{}]*\{[^}]*color: transparent/s); - assert.doesNotMatch(skin.css, /(?:^|[;{\s])(?:position|inset|top|right|bottom|left|width|height|min-height|padding|z-index|transform)\s*:/); + assert.match(skin.css, /illusia-now-playing[^{}]*\{[^}]*position:\s*fixed/); + assert.match(skin.css, /illusia-now-playing[^{}]*\{[^}]*background-image:[^;]*assets%2Fbanner-mascot-blob\.webp/); assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{[^}]*animation:/); assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{\s*animation: none;/); assert.match(skin.css, /home\.footer[\s\S]*?footer-wave\.png/); @@ -289,6 +293,54 @@ test("schema version 2 skin packages load only validated declarative layouts wit ); }); +test("schema version 3 supports arbitrary public layouts and validated declarative plugin components", async () => { + const components = { + schemaVersion: 1, + components: [{ + id: "channel-list", + name: "Channel list", + page: "voice", + accessibleName: "TeamSpeak channels", + permissions: ["session.channels.read", "session.channel.join"], + actions: { join: { type: "voice.joinChannel", args: { channelId: "{{channel.id}}" } } }, + root: { + tag: "nav", + repeat: { path: "session.channels", as: "channel" }, + children: [{ tag: "button", part: "row", events: { dblclick: "join" }, children: [{ text: "{{channel.name}}" }] }], + }, + }], + }; + const skin = await importSkinPack(makeSkinV3(components, ` + [data-ws-part="voice.channel-group"] { display: none; } + .channel-row[data-ws-plugin-part="channel-list.row"] { position: fixed; inset: 10px; width: 240px; order: 1; } + `)); + assert.equal(skin.schemaVersion, 3); + assert.equal(skin.packageType, "open-skin"); + assert.equal(skin.pluginData?.components[0].id, "channel-list"); + assert.equal(skin.pluginData?.components[0].root.children?.[0].events?.dblclick, "join"); + assert.match(skin.css, /position: fixed/); + assert.match(skin.css, /display: none/); + assert.ok(skin.warnings.some((warning) => warning.includes("hides an interface part"))); + + const unsafe = structuredClone(components) as typeof components; + unsafe.components[0].permissions = ["network.fetch"]; + await assert.rejects(importSkinPack(makeSkinV3(unsafe, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_INVALID"); + await assert.rejects(importSkinPack(makeSkinV3({ schemaVersion: 1, components: [] }, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_INVALID"); + const missingAsset = structuredClone(components) as unknown as SkinPluginDocument; + missingAsset.components[0].root = { tag: "img", asset: "assets/missing.webp" }; + await assert.rejects(importSkinPack(makeSkinV3(missingAsset, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_ASSET_INVALID"); +}); + +test("the distributable KAAK v3 package validates end to end", async () => { + const archive = await readFile(new URL("../../../docs/examples/kaak-voice.wskin", import.meta.url)); + const file = new File([archive], "kaak-voice.wskin", { type: "application/octet-stream" }); + const skin = await importSkinPack(file); + assert.equal(skin.id, "community.kaak-voice"); + assert.equal(skin.schemaVersion, 3); + assert.equal(skin.pluginData?.components[0].id, "kaak-room-sidebar"); + assert.ok(skin.css.includes('data-ws-plugin-part="kaak-room-sidebar.channel-row"')); +}); + function makeSkinV2(layout: unknown, manifestChanges: Record = {}): File { const packageFiles: Record = { "manifest.json": strToU8(JSON.stringify({ @@ -305,3 +357,14 @@ function makeSkinV2(layout: unknown, manifestChanges: Record = const bytes = zipSync(packageFiles); return new File([bytes.slice().buffer as ArrayBuffer], "skin-v2.wskin", { type: "application/octet-stream" }); } + +function makeSkinV3(components: unknown, css: string, assets: Record = {}): File { + const packageFiles: Record = { + "manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 3, packageType: "open-skin", components: "components.json" })), + "skin.css": strToU8(css), + "components.json": strToU8(JSON.stringify(components)), + ...assets, + }; + const bytes = zipSync(packageFiles); + return new File([bytes.slice().buffer as ArrayBuffer], "skin-v3.wskin", { type: "application/octet-stream" }); +} diff --git a/web/src/services/skin-pack.ts b/web/src/services/skin-pack.ts index 3d4a669..7268968 100644 --- a/web/src/services/skin-pack.ts +++ b/web/src/services/skin-pack.ts @@ -3,6 +3,7 @@ import selectorParser from "postcss-selector-parser"; import valueParser from "postcss-value-parser"; import { unzipSync } from "fflate"; import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js"; +import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js"; const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024; const MAX_EXPANDED_BYTES = 50 * 1024 * 1024; @@ -52,8 +53,8 @@ const ZIP_EOCD = 0x06054b50; const ZIP_CENTRAL_FILE = 0x02014b50; export interface SkinManifest { - schemaVersion: 1 | 2; - packageType?: "layout-skin"; + schemaVersion: 1 | 2 | 3; + packageType?: "layout-skin" | "open-skin"; id: string; name: string; version: string; @@ -64,6 +65,7 @@ export interface SkinManifest { layout?: string; permissions?: []; content?: string; + components?: string; minAppVersion: string; preview?: string; } @@ -94,6 +96,7 @@ export interface InstalledSkin extends SkinManifest { assets: Record; contentData?: SkinContent; layoutData?: SkinLayoutDocument; + pluginData?: SkinPluginDocument; previewBlob?: Blob; warnings: string[]; installedAt: number; @@ -153,7 +156,7 @@ export async function importSkinPack(file: File): Promise { const assets: Record = Object.create(null) as Record; for (const [path, bytes] of files) { - if (["manifest.json", manifest.entry, manifest.layout, manifest.content].includes(path)) continue; + if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components].includes(path)) continue; const mimeType = assetMimeType(path); if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED"); if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE"); @@ -168,6 +171,17 @@ export async function importSkinPack(file: File): Promise { contentData = parseContent(contentBytes); } + let pluginData: SkinPluginDocument | undefined; + if (manifest.components) { + const componentsBytes = files.get(manifest.components); + if (!componentsBytes || componentsBytes.byteLength > MAX_CONTENT_BYTES) throw new SkinPackError("components.json is missing or exceeds 256 KiB.", "SKIN_PLUGIN_SIZE"); + try { pluginData = parseSkinPluginJson(decoder.decode(componentsBytes)); } + catch (error) { throw new SkinPackError("components.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_PLUGIN_INVALID"); } + for (const assetPath of listSkinPluginAssetPaths(pluginData)) { + if (!assets[assetPath]?.type.startsWith("image/")) throw new SkinPackError(`Component image asset is missing or unsupported: ${assetPath}`, "SKIN_PLUGIN_ASSET_INVALID"); + } + } + let layoutData: SkinLayoutDocument | undefined; if (manifest.layout) { const layoutBytes = files.get(manifest.layout); @@ -186,8 +200,8 @@ export async function importSkinPack(file: File): Promise { previewBlob = new Blob([previewBytes], { type: previewMime }); } - const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets); - return { ...manifest, css: compiled.css, assets, contentData, layoutData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() }; + const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets, manifest.schemaVersion); + return { ...manifest, css: compiled.css, assets, contentData, layoutData, pluginData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() }; } export function resolveSkinCssAssets(css: string, assets: Record): { css: string; objectUrls: string[] } { @@ -333,9 +347,10 @@ function parseManifest(bytes: Uint8Array): SkinManifest { if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID"); const raw = value as Record; const schemaVersion = raw.schemaVersion; - if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION"); - if (schemaVersion === 2) { + if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion >= 2) { const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]); + if (schemaVersion === 3) { fields.delete("permissions"); fields.add("components"); } const unknown = Object.keys(raw).find((key) => !fields.has(key)); if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID"); } @@ -348,28 +363,32 @@ function parseManifest(bytes: Uint8Array): SkinManifest { if (schemaVersion === 2 && (raw.packageType !== "layout-skin" || !Array.isArray(raw.permissions) || raw.permissions.length !== 0)) { throw new SkinPackError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID"); } - if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined)) { + if (schemaVersion === 3 && raw.packageType !== "open-skin") { + throw new SkinPackError("Version 3 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID"); + } + if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined || raw.components !== undefined)) { throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION"); } const id = stringField("id", 80)!; if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID"); const entry = stringField("entry", 120)!; - const layout = schemaVersion === 2 ? stringField("layout", 120)! : undefined; + const layout = schemaVersion >= 2 ? stringField("layout", 120, schemaVersion === 2)! : undefined; + const components = schemaVersion === 3 ? stringField("components", 120)! : undefined; const content = stringField("content", 120, false); const preview = stringField("preview", 120, false); - for (const path of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) { + for (const path of [entry, layout, content, components, preview].filter((item): item is string => Boolean(item))) { if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID"); } const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; const version = stringField("version", 32)!; const minAppVersion = stringField("minAppVersion", 32)!; if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID"); - if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); - const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); + if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or plugin components path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID"); return { schemaVersion, - ...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : {}), + ...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : schemaVersion === 3 ? { packageType: "open-skin" as const } : {}), id, name: stringField("name", 80)!, version, @@ -379,6 +398,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest { entry, layout, content, + components, minAppVersion, preview, }; @@ -438,7 +458,7 @@ function parseContent(bytes: Uint8Array): SkinContent { return { defaultLocale: root.defaultLocale, locales }; } -function compileSkinCss(source: string, id: string, assets: Record): { css: string; warnings: string[] } { +function compileSkinCss(source: string, id: string, assets: Record, schemaVersion: SkinManifest["schemaVersion"]): { 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; @@ -486,7 +506,7 @@ function compileSkinCss(source: string, id: string, assets: Record 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 (!selectorUsesPublicHook(rule.selector)) throw rule.error("Skin selectors must use :root, [data-ws-page], or [data-ws-part] so they stay attached to WebSpeak's stable visual interface."); + if (!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) => { @@ -543,7 +563,7 @@ function compileSkinCss(source: string, id: string, assets: Record if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)) { throw declaration.error("Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens."); } - if (isLayoutAffectingProperty(property)) { + 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."); @@ -551,7 +571,7 @@ function compileSkinCss(source: string, id: string, assets: Record 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 (["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) { + 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" @@ -561,15 +581,16 @@ function compileSkinCss(source: string, id: string, assets: Record || (property === "pointer-events" && compactValue === "none") || (property === "clip-path" && /inset\(\s*50%/.test(compactValue)) || (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue)); - if (removesVisual && !canHideTarget) { + 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) { + 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) => { @@ -597,16 +618,16 @@ function targetsOnlyOptionalVisualParts(selector: string): boolean { } } -function selectorUsesPublicHook(selector: string): boolean { +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"].includes(node.attribute.toLowerCase())) scoped = true; + 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 (node.type === "class" || node.type === "id") usesPrivateName = true; + if (!allowCustomClasses && (node.type === "class" || node.type === "id")) usesPrivateName = true; }); return scoped && !usesPrivateName; }); diff --git a/web/src/services/skin-plugin-approval.ts b/web/src/services/skin-plugin-approval.ts new file mode 100644 index 0000000..498ac66 --- /dev/null +++ b/web/src/services/skin-plugin-approval.ts @@ -0,0 +1,59 @@ +import { + createSkinPluginApproval, + isSkinPluginPermissionApproved, + type SkinPluginApproval, + type SkinPluginComponent, + type SkinPluginDocument, +} from "../../../src/shared/skin-plugin.js"; + +const STORAGE_KEY = "webspeak:skin-plugin-approvals"; +interface ApprovalStore { schemaVersion: 1; grants: Record } + +function approvalKey(skinId: string, skinVersion: string, component: SkinPluginComponent): string { + return `${skinId}@${skinVersion}/${component.page}/${component.id}`; +} + +function readStore(): ApprovalStore { + try { + const raw: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null"); + if (!raw || typeof raw !== "object" || (raw as Record).schemaVersion !== 1 + || !(raw as Record).grants || typeof (raw as Record).grants !== "object") { + return { schemaVersion: 1, grants: {} }; + } + return raw as ApprovalStore; + } catch { + return { schemaVersion: 1, grants: {} }; + } +} + +function writeStore(store: ApprovalStore): void { + try { localStorage.setItem(STORAGE_KEY, JSON.stringify(store)); } catch { /* Approval persistence is optional. */ } +} + +export function getMissingSkinPluginApprovals(skinId: string, skinVersion: string, document: SkinPluginDocument): SkinPluginComponent[] { + const grants = readStore().grants; + return document.components.filter((component) => component.permissions.some((permission) => + !isSkinPluginPermissionApproved(grants[approvalKey(skinId, skinVersion, component)], approvalKey(skinId, skinVersion, component), permission))); +} + +export function isSkinPluginComponentApproved(skinId: string, skinVersion: string, component: SkinPluginComponent): boolean { + if (!component.permissions.length) return true; + const pluginId = approvalKey(skinId, skinVersion, component); + const grant = readStore().grants[pluginId]; + return component.permissions.every((permission) => isSkinPluginPermissionApproved(grant, pluginId, permission)); +} + +export function approveSkinPluginComponents(skinId: string, skinVersion: string, components: readonly SkinPluginComponent[]): void { + const store = readStore(); + for (const component of components) { + const pluginId = approvalKey(skinId, skinVersion, component); + store.grants[pluginId] = createSkinPluginApproval(pluginId, component.permissions); + } + writeStore(store); +} + +export function revokeSkinPluginApprovals(skinId: string): void { + const store = readStore(); + for (const key of Object.keys(store.grants)) if (key.startsWith(`${skinId}@`)) delete store.grants[key]; + writeStore(store); +} diff --git a/web/src/styles/skin-plugin.css b/web/src/styles/skin-plugin.css new file mode 100644 index 0000000..284b2ed --- /dev/null +++ b/web/src/styles/skin-plugin.css @@ -0,0 +1,57 @@ +.ws-plugin-consent-backdrop { + position: fixed; + inset: 0; + z-index: 2147483647; + display: grid; + place-items: center; + padding: 20px; + background: rgba(8, 12, 18, .76); + color: #f7fbff; + font: 14px/1.55 Inter, ui-sans-serif, system-ui, sans-serif; + backdrop-filter: blur(8px); +} + +.ws-plugin-access-toggle { + position: fixed; + right: 12px; + bottom: 12px; + z-index: 2147483000; + min-height: 34px; + padding: 0 12px; + border: 1px solid #8197ac; + border-radius: 999px; + color: #f7fbff; + background: #182331eF; + box-shadow: 0 4px 18px #0006; + font: 12px/1.2 Inter, ui-sans-serif, system-ui, sans-serif; + cursor: pointer; +} +.ws-plugin-access-toggle:focus-visible { outline: 3px solid #fbbf24; outline-offset: 3px; } + +.ws-plugin-consent { + width: min(640px, 100%); + max-height: min(86vh, 800px); + overflow-y: auto; + padding: 24px; + border: 1px solid rgba(165, 196, 220, .38); + border-radius: 16px; + background: #151d28; + box-shadow: 0 28px 90px #0009; +} + +.ws-plugin-consent h2 { margin: 0 0 10px; font-size: 20px; } +.ws-plugin-consent p { margin: 0 0 16px; color: #c0ccd8; } +.ws-plugin-consent-item { margin: 12px 0; padding: 12px 14px; border-radius: 10px; background: #202c39; } +.ws-plugin-consent-item ul { margin: 7px 0 0; padding-left: 20px; color: #c7d5e1; } +.ws-plugin-consent-note { margin-top: 18px !important; font-size: 12px; } +.ws-plugin-consent-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; } +.ws-plugin-consent-actions button { min-height: 40px; padding: 0 14px; border-radius: 8px; font: inherit; cursor: pointer; } +.ws-plugin-consent-actions .secondary { color: #e3eaf1; background: #303c49; } +.ws-plugin-consent-actions .primary { color: #fff; background: #2563eb; font-weight: 700; } +.ws-plugin-consent-actions button:focus-visible { outline: 3px solid #fbbf24; outline-offset: 3px; } + +@media (max-width: 520px) { + .ws-plugin-consent { padding: 18px; } + .ws-plugin-consent-actions { flex-direction: column-reverse; } + .ws-plugin-consent-actions button { width: 100%; } +} diff --git a/web/src/views/DemoView.vue b/web/src/views/DemoView.vue index 07e7e5e..8b11c77 100644 --- a/web/src/views/DemoView.vue +++ b/web/src/views/DemoView.vue @@ -1,5 +1,15 @@