From 81c35356b424a85e0c973069426f0f44c85c01a0 Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:36:07 +0800 Subject: [PATCH] feat(skin): validate v4 plugin packages --- .../skills/webspeak-skin-development/SKILL.md | 7 +- docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md | 7 +- docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md | 20 +- docs/SKIN_DEVELOPMENT.md | 33 +++- package.json | 2 +- src/admin/skin-registry.test.ts | 71 +++++++ src/admin/skin-registry.ts | 67 ++++++- src/shared/skin-runtime-plugins.test.ts | 93 +++++++++ src/shared/skin-runtime-plugins.ts | 181 ++++++++++++++++++ web/src/services/skin-pack.test.ts | 70 +++++++ web/src/services/skin-pack.ts | 83 ++++++-- 11 files changed, 595 insertions(+), 39 deletions(-) create mode 100644 src/shared/skin-runtime-plugins.test.ts create mode 100644 src/shared/skin-runtime-plugins.ts diff --git a/.agents/skills/webspeak-skin-development/SKILL.md b/.agents/skills/webspeak-skin-development/SKILL.md index 2f9c0f5..ba21af4 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 v1 visual, v2 layout, and v3 open skins, including custom declarative public interfaces, full-page surfaces, and permission-gated TeamSpeak interactions. +description: Create, refine, package, and verify WebSpeak v1 visual, v2 layout, v3 open skins, and the v4 plugin package envelope, including declarative public interfaces, full-page surfaces, and permission-gated TeamSpeak interactions. --- # WebSpeak skin development -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 freely compose bounded declarative UI from its own nodes, rearrange public UI, and replace the visible home/voice page with a validated surface. Optional host widgets are reusable trusted primitives, not the limit of custom UI. WebSpeak owns host behavior and the administrator console is 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 freely compose bounded declarative UI from its own nodes, rearrange public UI, and replace the visible home/voice page with a validated surface. v4 currently adds only a validated plugin descriptor and cached code/style/assets; it does not execute author code. Optional host widgets are reusable trusted primitives, not the limit of custom UI. WebSpeak owns host behavior and the administrator console is outside the skin scope. ## Before editing @@ -19,6 +19,7 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, a built-in - 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. Do not describe v3's fixed element, attribute, data, and action registries as complete customization; the target is a versioned, isolated plugin runtime with author-owned UI structure, CSS, and local logic. - v3 can replace or obscure normal page controls. A surface must request `ui.surface.replace` and stays disabled until the user approves it. Custom interfaces can use their own declarative nodes and CSS; embed optional host widgets only when a trusted WebSpeak control is useful. Available widget IDs are registered in `src/shared/skin-plugin.ts`; each stateful host widget may appear once per page. Preserve usable microphone, disconnect, device-settings, screen-share and recovery paths at desktop and mobile sizes. Verify both the return-to-built-in-UI and restore-built-in-skin buttons. The host recovery and permission UI render outside the skin root. Keep `/admin/**` unskinned. - components.json schema v1 is legacy; v2 adds `mode: "surface"` and optional allowlisted host-widget nodes; v3 expands bounded declarative composition, events and permission-gated voice actions. Keep author-code runtime disabled in production until the versioned plugin protocol, sandbox, message bridge, host action checks, and recovery lifecycle are reviewed and tested. The current Wasm prototype may return one untrusted `ui_emit_json` string up to 16 KiB; `parseSkinExtensionUiOutput` accepts only schema v3 display nodes, no widgets, surfaces, permissions, or non-local actions. The outlet adapter has tests but no production Wasm caller; do not describe this as a functioning plugin runtime. For the target plugin runtime, author UI runs isolated from the host and gets only approved data/actions; host actions must originate from captured trusted events, never a plugin-supplied trust flag. Never expose direct network/storage or private host objects. Keep server-list labels and opaque identifiers separate from addresses and credentials. Use `servers.quickList` plus `quickServers.switch` when a custom UI should show favorites and recent servers together. Host widgets execute in WebSpeak and do not grant author code access to their private state. +- The current v4 package parser is shared by client import and server registration. It accepts `plugins.json` schema v1 with local `plugins//` JS/CSS/assets, a 256 KiB descriptor cap, 256 KiB JS cap, 512 KiB CSS cap and 32 assets per plugin. These files are validated and cached separately; no loader or executor is connected. The descriptor still lacks widget mounting, ordering, visibility and user layout data. Keep v1–v3 unable to reference executable files, and keep the v4 sandbox and lifecycle disabled until their own security milestone is complete. - 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. @@ -37,5 +38,5 @@ The shipped default day, default night, and ILLUSIA skins are protected built-in - A full-page surface is a separate user-approved capability (`ui.surface.replace`); package installation alone must leave the built-in page visible. - The “restore built-in skin” control must use an unconditional selection function, not the skin-load-error-only recovery handler. - Custom quick-server layouts should use the unified favorites/recent collection and opaque host tokens. Labels that match the underlying address are redacted before projection; never expose target addresses or credentials to skin data bindings. -- KOOK voice-only visual reference: the first two user-authorized rooms were accessible in the in-app browser. Observed the server rail, channel tree, voice membership rows, central chat area, right member list, and lower-left voice controls. Microphone remained off and the client was disconnected after inspection. No server/room identifiers, member names, or chat content were retained. Keep discovery, events, companion shop, ads, and operator/admin surfaces out of this skin. +- KOOK voice-only visual reference: the first two user-authorized rooms were accessible in the in-app browser. Observed voice membership nested under the channel tree, the lower-left connection card with screen-share and audio controls, and the persistent central chat/right member panes. Microphone remained off and the client was disconnected after inspection. No server/room identifiers, member names, or chat content were retained. Keep discovery, events, companion shop, ads, and operator/admin surfaces out of this skin. - Report the exact system constraints discovered during implementation in both the roadmap and this skill. Keep each step reversible: preserve a clean tested checkpoint before changing package/runtime protocol versions, do not rewrite or push history without an explicit request, and keep v1/v2/v3 behavior isolated from new plugin capabilities. diff --git a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md index 5c824c3..9437cca 100644 --- a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md @@ -32,7 +32,8 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 - 新增自己的麦克风/扬声器、音量、离开状态、悄悄话、断开连接和屏幕共享等宿主动作及逐项权限;皮肤只调用现有 WebSpeak 流程。 - 新增音频、悄悄话和屏幕共享的公开状态数据,不向组件提供私有 SDK 对象、地址、原始音频或屏幕流。 - 被动 focus/blur/hover/drag-start/drag-over 只能更新本地 UI 状态;触发宿主动作需要明确用户操作,输入/change 仍不能触发连接、切房或消息发送。 -- 已获准并实际查看指定服务器前两个语音频道;麦克风全程关闭。将频道列表、频道成员、中心聊天区、右侧成员栏和左下语音控制卡作为 KAAK 布局参考,不记录房间标识、成员名单或聊天内容。 +- 已获准并实际查看指定服务器前两个语音频道;麦克风全程关闭。将频道列表、频道成员、中心聊天区、右侧成员栏和左下语音控制卡作为 KOOK 语音工作区参考,不记录房间标识、成员名单或聊天内容。 +- 补充观察到语音成员缩进挂在频道行下;加入频道后,自己的成员行留在频道树中,左下角出现独立连接控制卡,屏幕分享与音频控件集中放置,中心聊天和右侧成员区保持可见。观察后已断开,语音人数恢复为 0。 ### R3.2:受限作者逻辑运行时(原型,生产关闭) @@ -43,8 +44,10 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 ### R3.3:完整自定义插件运行时(未完成,优先阶段) -- 新增 opt-in 的皮肤包/schema 版本,不给旧 v1/v2/v3 包追溯增加代码执行能力;同一皮肤可将界面分成多个独立、可排序、可显示/隐藏、可单独授权和回退的插件。 +- v4 包格式的首个节点已落地:客户端和服务端共用 `plugins.json` 描述校验器,校验插件 ID、版本、页面、模式、权限、入口/样式/素材路径与重复 surface;客户端分开缓存插件文件,服务端验证文件存在、UTF-8 和大小。此节点不执行 JS/CSS,不能作为完整运行时完成态。 +- 继续新增 opt-in 的插件协议,不给旧 v1/v2/v3 包追溯增加代码执行能力;同一皮肤可将界面分成多个独立、可排序、可显示/隐藏、可单独授权和回退的插件。 - 插件可自定义公开界面的 DOM 结构、CSS、组件状态和普通 UI 事件,不局限于当前标签、属性、数据字段和固定动作表。宿主控件目录变成可选的兼容原生组件。 +- 尚待定义 widget 插件在宿主页面中的挂载、排序、显隐和用户自定义几何布局;当前 v4 描述只有页面与 widget/surface 模式,没有挂载或实例布局字段。应把用户布局保存在本地宿主状态,并让 CSS/插件沙箱边界保持独立。 - 插件对 TeamSpeak 的读取和操作经明确列举的权限、脱敏投影和宿主能力桥接;命令总由宿主校验参数、当前会话和权限。双击等事件只改变插件化界面的触发方式,不更改 TeamSpeak 协议,也不影响未启用该插件的其他皮肤。 - 安全设计候选为每个插件独立的沙箱化 opaque-origin iframe:仅开放脚本执行,不授予同源、表单、弹窗、顶层导航或下载权限;CSP 默认拒绝网络/外部资源,只提供包内素材;宿主通过专用 `MessageChannel` 发送脱敏数据并接收有限命令。桥接需由宿主可信 bootstrap 捕获 `isTrusted` 用户事件,插件不能直接调用宿主 API。需要验证所有目标浏览器的事件、CSP、资源与进程隔离行为后才能决定生产启用。 - 插件生命周期包括批准前不加载、逐插件/逐权限批准、版本变化重新确认、撤销立即销毁上下文、超时/输出限额/崩溃隔离、旧包兼容和宿主恢复 UI。完整威胁模型、资源耗尽与跨浏览器测试未完成前不启用生产运行开关。 diff --git a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md index ae0e2d2..584cc89 100644 --- a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md @@ -1,28 +1,32 @@ # 更开放的皮肤系统规格 -状态:现有 v1/v2/v3 是兼容实现,不是“万物皆插件”目标的完成态。components.json v3 仍限制元素/属性、数据字段、重复集合和宿主动作;Wasm UI 输出仍未接入生产客户端。完整插件运行时尚在设计与实现中,不能把当前系统描述为完全自定义。阶段记录和问题节点见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md),当前包格式见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。 +状态:v1/v2/v3 是兼容实现,不是“万物皆插件”目标的完成态。v4 的插件描述和包文件校验已接入客户端导入及服务端登记,但 JS/CSS 只被缓存,不会执行;components.json v3 仍限制元素/属性、数据字段、重复集合和宿主动作,Wasm UI 输出也仍未接入生产客户端。完整插件运行时尚未实现,不能把当前系统描述为完全自定义。阶段记录和问题节点见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md),当前包格式见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。 ## 1. 目标与范围 完整目标中,皮肤作者可以用自己的插件组件、DOM、CSS 和本地逻辑排列、替换、隐藏或重做公开客户端界面中的任何视觉元素,也可以重建首页和完整语音工作区。连接、频道、聊天、音频、收藏/历史、共享等基础能力始终由 WebSpeak/TeamSpeak 宿主保留;皮肤能替换其展示和交互入口,但不能删除或篡改底层业务能力。宿主恢复入口、权限管理和安全提示位于皮肤之外,任何插件失效、拒绝授权或撤销后都能回到原生可用界面。 -当前 v1/v2/v3 只能达到该目标的一部分:v3 组件依赖有限标签、属性、数据和动作白名单;完整作者逻辑与插件生命周期仍待 v4 协议实现。本规格区分已实现行为与目标行为,不以当前限制重新定义完成态。 +当前 v1/v2/v3 只能达到该目标的一部分:v3 组件依赖有限标签、属性、数据和动作白名单;v4 包协议已开始实现,但作者逻辑、沙箱执行与插件生命周期仍待接入。本规格区分已实现行为与目标行为,不以当前限制重新定义完成态。 适用页面为连接首页、语音工作区和公开演示页。管理员面板及其数据、管理 API 明确排除,不读取皮肤包。语音服务的运营、广告、陪玩、活动和商店等页面不属于语音客户端皮肤范围。 ## 2. 包格式与执行模型 -皮肤格式按版本区分:v1 保持视觉皮肤兼容;v2 提供有界布局 JSON;v3 使用 open-skin 清单、受控 CSS 和可选的 components.json。v1/v2 的 CSS 继续拒绝布局类声明,既有用户包不会因升级而获得新权限。v3 才允许 CSS 控制公开页面中的布局、位置、尺寸、顺序、文字排版和显隐。 +皮肤格式按版本区分:v1 保持视觉皮肤兼容;v2 提供有界布局 JSON;v3 使用 open-skin 清单、受控 CSS 和声明式 components.json;v4 在 open-skin 包中增加必需的 plugins.json 和插件专属 JS/CSS/素材路径。客户端与服务端共用 v4 插件描述校验器,并检查引用文件、UTF-8 和大小;当前不执行或加载这些代码。v1/v2 的 CSS 继续拒绝布局类声明,旧包不会因升级而获得新权限;v3/v4 才允许 CSS 控制公开页面中的布局、位置、尺寸、顺序、文字排版和显隐。 v3 自定义组件不是脚本插件。components.json schema v1 是既有格式;schema v2 增加 `mode: "surface"` 与宿主控件节点;schema v3 扩大自定义节点、嵌套、重复列表和声明式交互的边界,并增加映射到现有语音功能的动作。宿主仍解析固定元素/属性白名单、固定数据集合、简单绑定与有限动作,再由 Vue 创建节点。作者不必使用固定宿主控件目录,但 v3 仍不足以表达任意自定义 UI 逻辑和完整插件生命周期。管理员面板和演示页不能被 surface 替换。 宿主控件通过固定 ID 嵌入,始终由 WebSpeak 代码运行。当前可选注册表包括 `home.connection-form`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls` 和 `voice.disconnect-control`。每个控件在同一页面最多出现一次;未知 ID 或重复的有状态控件会拒绝导入。作者可以不用这些控件,自行绘制界面并将点击、双击等事件绑定到公开数据与受权限保护的动作。 -包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAssembly、远程脚本、任意 URL、表单导航、浏览器存储访问或网络调用。未知字段、元素、动作、数据路径、控件和权限一律拒绝。 +v1-v3 包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAssembly、远程脚本、任意 URL、表单导航、浏览器存储访问或网络调用。v4 可携带本地 JS/CSS 供后续沙箱运行时使用,但当前只校验和缓存,不会执行。未知字段、元素、动作、数据路径、控件和权限一律拒绝。 -### 2.1 完整插件目标协议(v4,尚未实现) +### 2.1 完整插件目标协议(v4,运行时尚未实现) -完成态不把标签、属性、CSS 布局、普通 UI 状态或插件自身交互限制在 v3 固定表中。v4 插件应能在自定义内容区域构建完整 DOM/CSS/本地交互,并允许将任意公开客户端区域拆成可排序、显隐、独立授权和可回退的插件。现有宿主控件只是可选的原生能力组件;连接/频道/聊天/音频等基础业务能力仍由 WebSpeak 保留、可由插件重新呈现,且始终能通过宿主恢复界面回到可信基础 UI。旧 v1/v2/v3 包继续按原验证与能力运行,不获得追溯性代码权限。 +已实现的 v4 包描述为 `plugins.json` schema v1:每包 1–64 个插件,每个插件指定唯一小写 ID、语义版本、API 版本 1、`home`/`voice` 页面、`widget`/`surface` 模式、`plugins//` 下入口 JS/可选 CSS、该目录中的图片/woff2 素材和现有权限表中的权限。每页至多一个 surface,且必须申请 `ui.surface.replace`。清单最多 256 KiB、插件入口最多 256 KiB、插件样式最多 512 KiB、每插件最多 32 个素材;引用文件必须存在且路径不重复。客户端与服务端复用同一解析器。此协议节点只做识别、验证和缓存,尚不加载或执行作者代码。 + +当前 descriptor 没有定义 widget 的宿主挂载位置、实例顺序、显隐或几何配置。完整运行时需决定这些默认值随皮肤包分发还是由用户本地覆盖;用户布局应与作者文件分开存储,且沙箱内代码不能改动其他插件的宿主容器或恢复控件。 + +完整运行时目标是不把标签、属性、CSS 布局、普通 UI 状态或插件自身交互限制在 v3 固定表中。插件应能在自定义内容区域构建完整 DOM/CSS/本地交互,并允许将任意公开客户端区域拆成可排序、显隐、独立授权和可回退的插件。现有宿主控件只是可选的原生能力组件;连接/频道/聊天/音频等基础业务能力仍由 WebSpeak 保留、可由插件重新呈现,且始终能通过宿主恢复界面回到可信基础 UI。旧 v1/v2/v3 包继续按原验证与能力运行,不获得追溯性代码权限。 沙箱架构候选:每个插件单独装入 `sandbox="allow-scripts"`、不带 `allow-same-origin` 的 iframe,使插件文档采用 opaque origin;不授予 forms、popups、top navigation、downloads、storage-access 或同源访问。由服务端运行时文档响应头强制 CSP,默认拒绝所有资源与连接,仅允许插件包内脚本、CSS 和素材,显式阻断 `connect-src`、外部字体/图片/媒体、frame、object 和 worker。不能只依赖可被插件文档修改的元标签。该 frame 本身不提供 CPU/内存硬配额,也不能假定每个浏览器都把它放到独立进程;无限循环、巨大 DOM 和高频渲染仍是生产门槛,需专门压测/回收或改选有确定资源计量的执行模型。可复用的浏览器边界参考:[MDN iframe sandbox](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe)、[MDN CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy) 和 [WHATWG HTML iframe sandbox](https://html.spec.whatwg.org/multipage/iframe-embed-object.html)。 @@ -71,7 +75,7 @@ v4 插件应独立声明读取投影和宿主动作权限,授权键至少包 ## 4. CSS 与基础组件 -v1-v3 CSS 被重写到当前公开皮肤根节点;v4 插件的 DOM 和 CSS 运行在独立沙箱文档中,不得越出自己的插件 frame。两种路径都不允许影响 `/admin/**`。页面权限提示、皮肤组件权限入口和“返回标准界面”控件由宿主放在皮肤插件/皮肤 CSS 之外,不能被作者样式隐藏。 +v1-v3 CSS 被重写到当前公开皮肤根节点;未来启用 v4 时,插件的 DOM 和 CSS 必须运行在独立沙箱文档中,不得越出自己的插件 frame。当前 v4 代码尚未渲染。两种路径都不允许影响 `/admin/**`。页面权限提示、皮肤组件权限入口和“返回标准界面”控件由宿主放在皮肤插件/皮肤 CSS 之外,不能被作者样式隐藏。 v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦克风、退出、共享等控件的可见位置。宿主提供的“返回标准界面”和“恢复内置皮肤”控件以及组件权限确认和撤销入口在皮肤根节点之外;用户可立即退回 WebSpeak 页面,再用原生皮肤选择器切换皮肤。作者仍应在桌面和移动布局中保留语音操作的可达路径。 @@ -79,7 +83,7 @@ v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦 ## 5. 校验与回退 -客户端导入和服务端登记都会校验 manifest、ZIP 路径、组件协议、所引用素材和文件限额。运行时会再次解析持久化的组件文档;无效组件不执行。权限界面和恢复控件由宿主代码渲染。v3 CSS 的结构限制可降低跨应用影响,但 CSS 不是针对恶意脚本的沙箱。 +客户端导入和服务端登记都会校验 manifest、ZIP 路径、组件协议、所引用素材和文件限额;v4 插件描述由共享解析器验证,JS/CSS 目前只作 UTF-8 和尺寸校验并缓存,不执行。现有组件运行时会再次解析持久化的组件文档;无效组件不执行。权限界面和恢复控件由宿主代码渲染。v3/v4 CSS 的作用域能降低跨应用影响,但 CSS 不是针对恶意脚本的沙箱。 皮肤载入错误不得清除用户布局或 TeamSpeak 会话。组件树为空、权限被拒绝或皮肤无效时,宿主本身和既有功能仍可由用户恢复。v4 每个插件需有独立错误边界;单个 iframe 崩溃不能拖垮语音会话或其余插件,撤销必须立即销毁该插件运行环境。管理员后台仍沿用自己的样式和服务端管理流程。 diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 2bf4c0d..fdfcb2b 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -1,8 +1,8 @@ # WebSpeak 皮肤开发规范 -本文说明仍受支持的 v1 视觉皮肤、v2 声明式布局皮肤和 v3 开放皮肤。v1/v2 保持固定 CSS 几何边界;v3 可重排公开 UI、用自定义声明式节点构建界面,并用 components.json schema v2/v3 替换首页/语音工作区的整页可见界面。自定义界面不依赖固定宿主控件目录;交互通过逐项授权的宿主动作实现。路线和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。 +本文说明 v1 视觉皮肤、v2 声明式布局皮肤、v3 开放皮肤以及正在接入的 v4 插件包格式。v1/v2 保持固定 CSS 几何边界;v3 可重排公开 UI、用自定义声明式节点构建界面,并用 components.json schema v2/v3 替换首页/语音工作区的整页可见界面。v4 已加入插件清单、插件文件校验和本地缓存,但作者代码尚未执行。路线和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。 -当前 v3 仍限制 HTML 标签、属性、可绑定数据集合和宿主动作,不能称为“完全自定义”或“万物皆插件”。v4 插件运行时是目标阶段,尚未实现或获安全批准;它必须支持作者自定义 DOM/CSS/本地逻辑,同时保持 TeamSpeak 功能经宿主能力桥接、皮肤后台之外可恢复。不要把 v3 的示例包或 Wasm 输出原型描述成已完成的全量插件系统。 +当前 v3 仍限制 HTML 标签、属性、可绑定数据集合和宿主动作,不能称为“完全自定义”或“万物皆插件”。v4 插件运行时尚未实现或获安全批准;当前实现只校验并缓存清单、JS/CSS 和包内素材,不执行作者代码。完整运行时仍须支持作者自定义 DOM/CSS/本地逻辑,同时保持 TeamSpeak 功能经宿主能力桥接、皮肤后台之外可恢复。不要把 v4 包格式、v3 示例包或 Wasm 输出原型描述成已完成的全量插件系统。 `.wskin` 包可为公开页面定制艺术表现。v1 提供 CSS 与美术资源;v2 另外携带受校验的布局 JSON;v3 可自由安排公开组件,并用 components.json 声明由宿主渲染的安全组件。所有版本均由 WebSpeak 保留基础组件的业务逻辑和 TeamSpeak 行为。 @@ -28,6 +28,10 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可 assets/background.webp # 可选:页面艺术素材 assets/brand.woff2 # 可选:自带字体 components.json # v3 可选:声明式组件或完整页面 surface +plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件 +plugins//index.js # v4 插件代码,目前只校验和缓存 +plugins//style.css # v4 可选:插件样式,目前只校验和缓存 +plugins//assets/ # v4 插件专属的本地图片或字体素材 ``` 所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。 @@ -147,6 +151,31 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s 注意:v3 CSS 和 surface 可以隐藏或遮挡普通语音控件。权限和返回标准界面提示由宿主在皮肤根之外绘制;其他界面控件仍受皮肤排版影响。测试时务必确保麦克风、设置、退出语音、屏幕共享操作和移动端导航仍有可达路径。组件演示页 /demo 使用合成数据,加入频道和聊天动作只更新演示状态;它不支持宿主控件或整页替换。 +### schemaVersion 4:插件包描述(运行时尚未启用) + +v4 在 open-skin 包中增加必需的 `plugins` 路径。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。JS、CSS 和素材均不会被此阶段的 WebSpeak 运行时加载或执行,因此 v4 当前只是可验证的包协议,不能作为可运行插件发布。 + +```json +{ + "schemaVersion": 4, + "packageType": "open-skin", + "id": "community.example-plugin-skin", + "name": "Example plugin skin", + "version": "1.0.0", + "author": "Example author", + "license": "MIT", + "entry": "skin.css", + "plugins": "plugins.json", + "minAppVersion": "0.2.7-preview" +} +``` + +`plugins.json` 顶层 `schemaVersion` 当前为 `1`,并包含 1–64 个插件。每个插件声明 `id`、`name`、`version`、`apiVersion: 1`、`page`(`home` 或 `voice`)、`mode`(`widget` 或 `surface`)、必需的 `entry`、可选的 `style`、素材路径数组 `assets` 和 `permissions`。入口及样式必须位于 `plugins//`;素材必须位于该插件自己的 `assets/` 子目录,只能是本地图片或 woff2 字体。插件不能共享文件;同一公开页面最多有一个 `surface`,且必须申请 `ui.surface.replace`。其余权限只能从 `src/shared/skin-plugin.ts` 的现有权限表中选择。 + +`plugins.json` 不超过 256 KiB;每个入口 JS 不超过 256 KiB,每个样式 CSS 不超过 512 KiB;每个插件最多声明 32 个素材。皮肤包整体仍受通用 ZIP 文件数、展开大小、图像和字体限额约束。v1–v3 不接受插件代码。沙箱 iframe、可信事件捕获、MessageChannel 能力桥、逐插件授权、撤销和生命周期隔离仍未完成;不得通过增加识别格式而提前开启脚本执行。 + +当前描述还没有 widget 挂载点、排序、显隐或实例布局字段,完整运行时阶段需要明确这些由皮肤作者还是本地用户管理;不能让一个插件越过其 iframe 去调整其他插件或宿主恢复控件。 + ## 首页内容和文案 `content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例: diff --git a/package.json b/package.json index 2869661..0aab9a1 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-wasm-interpreter.test.ts", + "test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-wasm-interpreter.test.ts", "verify": "npm test && npm run build && npm run web:build", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", diff --git a/src/admin/skin-registry.test.ts b/src/admin/skin-registry.test.ts index de894ab..29ec6d3 100644 --- a/src/admin/skin-registry.test.ts +++ b/src/admin/skin-registry.test.ts @@ -177,6 +177,77 @@ test("server accepts v3 declarative components and rejects unapproved capability await assert.rejects(registry.save(unsafeArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PLUGIN_INVALID"); }); +test("server accepts a v3 open visual skin without a components document", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v3-visual-only-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const archive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify({ ...manifest, schemaVersion: 3, packageType: "open-skin", content: undefined, preview: undefined }))], + ["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')], + ]); + const saved = await registry.save(archive, "sample-skin"); + assert.equal(saved.id, "sample-skin"); + assert.deepEqual(await registry.readArchive("sample-skin"), archive); +}); + +test("server validates v4 plugin manifests and package files without executing author code", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v4-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const manifestV4 = { + ...manifest, + schemaVersion: 4, + packageType: "open-skin", + content: undefined, + preview: undefined, + plugins: "plugins.json", + }; + const plugins = { + schemaVersion: 1, + plugins: [{ + id: "voice-toolbar", + name: "Voice toolbar", + version: "1.0.0", + apiVersion: 1, + page: "voice", + mode: "widget", + entry: "plugins/voice-toolbar/index.js", + style: "plugins/voice-toolbar/style.css", + assets: ["plugins/voice-toolbar/assets/icon.png"], + permissions: ["session.channels.read"], + }], + }; + const archive = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV4))], + ["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')], + ["plugins.json", Buffer.from(JSON.stringify(plugins))], + ["plugins/voice-toolbar/index.js", Buffer.from("export const render = () => document.createElement('button');")], + ["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")], + ["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])], + ]); + const saved = await registry.save(archive, "sample-skin"); + assert.equal(saved.id, "sample-skin"); + assert.deepEqual(await registry.readArchive("sample-skin"), archive); + + const missingEntry = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV4))], + ["skin.css", Buffer.from("[data-ws-part=app] { color: teal; }")], + ["plugins.json", Buffer.from(JSON.stringify(plugins))], + ]); + await assert.rejects(registry.save(missingEntry, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_RUNTIME_PLUGIN_FILE_MISSING"); + + const unlistedScript = createZip([ + ["manifest.json", Buffer.from(JSON.stringify(manifestV4))], + ["skin.css", Buffer.from("[data-ws-part=app] { color: teal; }")], + ["plugins.json", Buffer.from(JSON.stringify(plugins))], + ["plugins/voice-toolbar/index.js", Buffer.from("export {};")], + ["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")], + ["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])], + ["plugins/other/rogue.js", Buffer.from("export {};")], + ]); + await assert.rejects(registry.save(unlistedScript, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_FILE_UNSUPPORTED"); +}); + 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 c9a7e86..1dbaa33 100644 --- a/src/admin/skin-registry.ts +++ b/src/admin/skin-registry.ts @@ -1,6 +1,14 @@ 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 { + listSkinRuntimePluginFilePaths, + parseSkinRuntimePluginJson, + SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES, + SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES, + SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES, + type SkinRuntimePluginDocument, +} from "../shared/skin-runtime-plugins.js"; import { randomBytes } from "node:crypto"; import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -42,12 +50,13 @@ interface SkinArchiveEntry { } type ParsedSkinManifest = Omit & { - schemaVersion: 1 | 2 | 3; + schemaVersion: 1 | 2 | 3 | 4; packageType?: "layout-skin" | "open-skin"; entry: string; layout?: string; content?: string; components?: string; + plugins?: string; preview?: string; }; @@ -225,10 +234,45 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE"); decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8."); + let runtimePlugins: SkinRuntimePluginDocument | undefined; + if (manifest.plugins) { + const pluginsBytes = fileBytes.get(manifest.plugins); + if (!pluginsBytes || pluginsBytes.byteLength > SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES) { + throw new SkinRegistryError("plugins.json is missing or exceeds 256 KiB.", "SKIN_RUNTIME_PLUGIN_SIZE"); + } + try { runtimePlugins = parseSkinRuntimePluginJson(decodeUtf8(pluginsBytes, "plugins.json is not valid UTF-8.")); } + catch (error) { throw new SkinRegistryError("plugins.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_RUNTIME_PLUGIN_INVALID"); } + } + const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : []; + const runtimePluginPathSet = new Set(runtimePluginPaths.map((packagePath) => packagePath.toLowerCase())); + const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview] + .filter((packagePath): packagePath is string => Boolean(packagePath)).map((packagePath) => packagePath.toLowerCase()); + if (runtimePluginPaths.some((packagePath) => manifestPathSet.includes(packagePath))) { + throw new SkinRegistryError("Plugin files cannot reuse skin manifest, CSS, content, component, or preview paths.", "SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE"); + } + for (const pluginPath of runtimePluginPaths) { + const data = fileBytes.get(pluginPath); + if (!data) throw new SkinRegistryError(`A declared plugin file is missing: ${pluginPath}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING"); + const lowerPath = pluginPath.toLowerCase(); + if (lowerPath.endsWith(".js")) { + if (data.byteLength > SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES) throw new SkinRegistryError("Plugin entry files must be smaller than 256 KiB.", "SKIN_RUNTIME_PLUGIN_SOURCE_SIZE"); + decodeUtf8(data, "Plugin entry files must contain valid UTF-8."); + } else if (lowerPath.endsWith(".css")) { + if (data.byteLength > SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES) throw new SkinRegistryError("Plugin style files must be smaller than 512 KiB.", "SKIN_RUNTIME_PLUGIN_STYLE_SIZE"); + decodeUtf8(data, "Plugin style files must contain valid UTF-8."); + } else { + const mimeType = imageMime(pluginPath) ?? (lowerPath.endsWith(".woff2") ? "font/woff2" : null); + if (!mimeType) throw new SkinRegistryError(`Unsupported plugin asset: ${pluginPath}`, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"); + if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Plugin images must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE"); + if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Plugin fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE"); + } + } + let previewBytes: Buffer | undefined; let previewMime: string | undefined; for (const [packagePath, data] of fileBytes) { - if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.preview].includes(packagePath)) continue; + if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview].includes(packagePath) + || runtimePluginPathSet.has(packagePath.toLowerCase())) 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"); @@ -389,10 +433,11 @@ 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 && schemaVersion !== 3) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) 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"); } + if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); } + if (schemaVersion === 4) fields.add("plugins"); 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"); } @@ -407,7 +452,8 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { throw new SkinRegistryError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID"); } 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)) { + if (schemaVersion === 4 && value.packageType !== "open-skin") throw new SkinRegistryError("Version 4 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 || value.plugins !== undefined)) { throw new SkinRegistryError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION"); } const version = read("version", 32); @@ -417,14 +463,15 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max); 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 components = schemaVersion >= 3 && value.components != null ? read("components", 120) : undefined; + const plugins = schemaVersion === 4 ? read("plugins", 120) : undefined; const preview = readOptional("preview", 120); - 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()); + for (const candidate of [entry, layout, content, components, plugins, 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")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(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 } : 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 } : {}) }; + 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 } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) }; } function singleRootPrefix(paths: string[]): string { diff --git a/src/shared/skin-runtime-plugins.test.ts b/src/shared/skin-runtime-plugins.test.ts new file mode 100644 index 0000000..89105bd --- /dev/null +++ b/src/shared/skin-runtime-plugins.test.ts @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + listSkinRuntimePluginFilePaths, + parseSkinRuntimePluginDocument, + parseSkinRuntimePluginJson, + SkinRuntimePluginValidationError, + SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES, +} from "./skin-runtime-plugins.js"; + +const plugin = { + id: "voice-toolbar", + name: "Voice toolbar", + version: "1.2.3", + apiVersion: 1, + page: "voice", + mode: "widget", + entry: "plugins/voice-toolbar/index.js", + style: "plugins/voice-toolbar/style.css", + assets: ["plugins/voice-toolbar/assets/icon.png"], + permissions: ["session.channels.read"], +}; + +function document(plugins: unknown[] = [plugin]): unknown { + return { schemaVersion: 1, plugins }; +} + +test("v4 plugin descriptors accept bounded local files and freeze their parsed data", () => { + const parsed = parseSkinRuntimePluginDocument(document() as never); + assert.deepEqual(listSkinRuntimePluginFilePaths(parsed), [ + "plugins/voice-toolbar/index.js", + "plugins/voice-toolbar/style.css", + "plugins/voice-toolbar/assets/icon.png", + ]); + assert.equal(parsed.plugins[0].permissions[0], "session.channels.read"); + assert.ok(Object.isFrozen(parsed) && Object.isFrozen(parsed.plugins) && Object.isFrozen(parsed.plugins[0])); + assert.ok(Object.isFrozen(parsed.plugins[0].assets) && Object.isFrozen(parsed.plugins[0].permissions)); +}); + +test("surface replacement is an explicit page-scoped plugin capability", () => { + const surface = { ...plugin, mode: "surface", permissions: ["ui.surface.replace"] }; + const parsed = parseSkinRuntimePluginDocument(document([surface]) as never); + assert.equal(parsed.plugins[0].mode, "surface"); + assert.throws( + () => parseSkinRuntimePluginDocument(document([{ ...surface, permissions: [] }]) as never), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_PERMISSION_MISSING", + ); + assert.throws( + () => parseSkinRuntimePluginDocument(document([surface, { ...surface, id: "other-surface", entry: "plugins/other-surface/index.js", style: "plugins/other-surface/style.css", assets: ["plugins/other-surface/assets/icon.png"] }]) as never), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_SURFACE_DUPLICATE", + ); +}); + +test("v4 plugin descriptors reject unknown fields, path escape, wrong ownership, and executable assets", () => { + const cases: Array<[unknown, string]> = [ + [{ ...plugin, arbitraryCodeHook: "run" }, "SKIN_RUNTIME_PLUGIN_FIELD_INVALID"], + [{ ...plugin, entry: "plugins/voice-toolbar/../other.js" }, "SKIN_RUNTIME_PLUGIN_PATH_INVALID"], + [{ ...plugin, entry: "plugins/other/index.js" }, "SKIN_RUNTIME_PLUGIN_PATH_INVALID"], + [{ ...plugin, assets: ["plugins/voice-toolbar/assets/plugin.js"] }, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"], + [{ ...plugin, assets: ["plugins/another/assets/icon.png"] }, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"], + [{ ...plugin, permissions: ["network.fetch"] }, "SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID"], + [{ ...plugin, assets: [plugin.assets[0], plugin.assets[0]] }, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"], + ]; + for (const [value, code] of cases) { + assert.throws( + () => parseSkinRuntimePluginDocument(document([value]) as never), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === code, + ); + } + assert.throws( + () => parseSkinRuntimePluginDocument(document([plugin, { ...plugin }]) as never), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_ID_INVALID", + ); +}); + +test("v4 plugin documents enforce schema, counts, and UTF-8 byte limits", () => { + assert.throws( + () => parseSkinRuntimePluginDocument({ schemaVersion: 2, plugins: [plugin] } as never), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", + ); + assert.throws( + () => parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [] } as never), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", + ); + assert.throws( + () => parseSkinRuntimePluginJson(" ".repeat(SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES + 1)), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_SIZE", + ); + assert.throws( + () => parseSkinRuntimePluginJson("{"), + (error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", + ); +}); diff --git a/src/shared/skin-runtime-plugins.ts b/src/shared/skin-runtime-plugins.ts new file mode 100644 index 0000000..b431b8e --- /dev/null +++ b/src/shared/skin-runtime-plugins.ts @@ -0,0 +1,181 @@ +import { SKIN_PLUGIN_PERMISSIONS, type SkinPluginPermission } from "./skin-plugin.js"; + +export const SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION = 1 as const; +export const SKIN_RUNTIME_PLUGIN_LIMIT = 64; +export const SKIN_RUNTIME_PLUGIN_ASSET_LIMIT = 32; +export const SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES = 256 * 1024; +export const SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES = 256 * 1024; +export const SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES = 512 * 1024; + +export type SkinRuntimePluginPage = "home" | "voice"; +export type SkinRuntimePluginMode = "widget" | "surface"; + +export interface SkinRuntimePlugin { + id: string; + name: string; + version: string; + apiVersion: 1; + page: SkinRuntimePluginPage; + mode: SkinRuntimePluginMode; + entry: string; + style?: string; + assets: readonly string[]; + permissions: readonly SkinPluginPermission[]; +} + +export interface SkinRuntimePluginDocument { + schemaVersion: typeof SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION; + plugins: readonly SkinRuntimePlugin[]; +} + +export class SkinRuntimePluginValidationError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinRuntimePluginValidationError"; + } +} + +const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/; +const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; +const PERMISSIONS = new Set(Object.keys(SKIN_PLUGIN_PERMISSIONS)); +const ASSET_PATH = /^plugins\/([a-z][a-z0-9-]{0,63})\/assets\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.(?:png|jpe?g|webp|avif|gif|woff2)$/i; + +function invalid(code: string, message: string): never { + throw new SkinRuntimePluginValidationError(code, message); +} + +function isRecord(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function onlyKeys(value: Record, allowed: readonly string[], context: string): void { + if (Object.keys(value).some((key) => !allowed.includes(key))) { + invalid("SKIN_RUNTIME_PLUGIN_FIELD_INVALID", `${context} contains an unsupported field.`); + } +} + +function text(value: unknown, field: string, maximum: number): string { + if (typeof value !== "string" || !value.trim() || value.length > maximum || value.trim() !== value) { + invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", `${field} must be bounded non-empty text.`); + } + return value; +} + +function packageFile(value: unknown, field: string, pluginId: string, suffix: ".js" | ".css"): string { + const result = text(value, field, 160); + if (result.includes("\\") || result.startsWith("/") || result.split("/").some((part) => !part || part === "." || part === "..") + || !result.startsWith(`plugins/${pluginId}/`) || !result.toLowerCase().endsWith(suffix)) { + invalid("SKIN_RUNTIME_PLUGIN_PATH_INVALID", `${field} must be a safe ${suffix} file inside its plugin directory.`); + } + return result; +} + +/** Parses the v4 author-plugin descriptor. It never evaluates plugin code. */ +export function parseSkinRuntimePluginDocument(input: unknown): SkinRuntimePluginDocument { + if (!isRecord(input)) invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", "plugins.json must contain an object."); + onlyKeys(input, ["schemaVersion", "plugins"], "plugins.json"); + if (input.schemaVersion !== SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION || !Array.isArray(input.plugins) + || input.plugins.length < 1 || input.plugins.length > SKIN_RUNTIME_PLUGIN_LIMIT) { + invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", "plugins.json uses an unsupported version or plugin count."); + } + + const ids = new Set(); + const files = new Set(); + const plugins: SkinRuntimePlugin[] = []; + for (const raw of input.plugins) { + if (!isRecord(raw)) invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "A plugin definition must be an object."); + onlyKeys(raw, ["id", "name", "version", "apiVersion", "page", "mode", "entry", "style", "assets", "permissions"], "Plugin definition"); + + const id = text(raw.id, "plugin.id", 64); + if (!PLUGIN_ID.test(id) || ids.has(id)) invalid("SKIN_RUNTIME_PLUGIN_ID_INVALID", "Plugin IDs must be unique lowercase slugs."); + ids.add(id); + const name = text(raw.name, "plugin.name", 80); + const version = text(raw.version, "plugin.version", 32); + if (!SEMVER.test(version)) invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "Plugin versions must use semantic version syntax."); + if (raw.apiVersion !== 1) invalid("SKIN_RUNTIME_PLUGIN_API_UNSUPPORTED", "The plugin API version is not supported."); + if (raw.page !== "home" && raw.page !== "voice") invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "Plugins may target only the public home or voice page."); + if (raw.mode !== "widget" && raw.mode !== "surface") invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "Plugin mode must be widget or surface."); + + const entry = packageFile(raw.entry, "plugin.entry", id, ".js"); + const style = raw.style === undefined ? undefined : packageFile(raw.style, "plugin.style", id, ".css"); + if (!Array.isArray(raw.assets) || raw.assets.length > SKIN_RUNTIME_PLUGIN_ASSET_LIMIT) { + invalid("SKIN_RUNTIME_PLUGIN_ASSET_INVALID", "A plugin must declare a bounded asset list."); + } + const assets: string[] = []; + for (const rawPath of raw.assets) { + const assetPath = text(rawPath, "plugin.asset", 180); + const match = ASSET_PATH.exec(assetPath); + if (!match || match[1] !== id) invalid("SKIN_RUNTIME_PLUGIN_ASSET_INVALID", "Plugin assets must be safe local image or font files inside that plugin's assets directory."); + assets.push(assetPath); + } + if (new Set(assets.map((path) => path.toLowerCase())).size !== assets.length) { + invalid("SKIN_RUNTIME_PLUGIN_ASSET_INVALID", "A plugin asset path is duplicated."); + } + + if (!Array.isArray(raw.permissions) || raw.permissions.length > 32) { + invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID", "Plugin permissions must be a bounded array."); + } + const permissions: SkinPluginPermission[] = []; + for (const permission of raw.permissions) { + if (typeof permission !== "string" || !PERMISSIONS.has(permission)) { + invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID", "The plugin requests an unsupported permission."); + } + if (permissions.includes(permission as SkinPluginPermission)) { + invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_DUPLICATE", "A plugin permission is duplicated."); + } + permissions.push(permission as SkinPluginPermission); + } + if (raw.mode === "surface" && !permissions.includes("ui.surface.replace")) { + invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_MISSING", "A surface plugin requires ui.surface.replace."); + } + + for (const path of [entry, ...(style ? [style] : []), ...assets]) { + const normalized = path.toLowerCase(); + if (files.has(normalized)) invalid("SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE", "Plugin files cannot be shared between definitions."); + files.add(normalized); + } + plugins.push({ + id, + name, + version, + apiVersion: 1, + page: raw.page, + mode: raw.mode, + entry, + ...(style ? { style } : {}), + assets, + permissions, + }); + } + + const surfacePages = new Set(); + for (const plugin of plugins) { + if (plugin.mode !== "surface") continue; + if (surfacePages.has(plugin.page)) invalid("SKIN_RUNTIME_PLUGIN_SURFACE_DUPLICATE", "Only one surface plugin may replace each public page."); + surfacePages.add(plugin.page); + } + + const immutablePlugins = plugins.map((plugin) => Object.freeze({ + ...plugin, + assets: Object.freeze([...plugin.assets]), + permissions: Object.freeze([...plugin.permissions]), + })); + return Object.freeze({ schemaVersion: SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION, plugins: Object.freeze(immutablePlugins) }); +} + +export function parseSkinRuntimePluginJson(source: string): SkinRuntimePluginDocument { + if (typeof source !== "string" || !source.length + || new TextEncoder().encode(source).byteLength > SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES) { + invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_SIZE", "plugins.json is empty or exceeds 256 KiB."); + } + let input: unknown; + try { input = JSON.parse(source); } + catch { invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", "plugins.json must contain valid JSON."); } + return parseSkinRuntimePluginDocument(input); +} + +export function listSkinRuntimePluginFilePaths(document: SkinRuntimePluginDocument): string[] { + return document.plugins.flatMap((plugin) => [plugin.entry, ...(plugin.style ? [plugin.style] : []), ...plugin.assets]); +} diff --git a/web/src/services/skin-pack.test.ts b/web/src/services/skin-pack.test.ts index e7f6884..b4a4c48 100644 --- a/web/src/services/skin-pack.test.ts +++ b/web/src/services/skin-pack.test.ts @@ -331,6 +331,17 @@ test("schema version 3 supports arbitrary public layouts and validated declarati await assert.rejects(importSkinPack(makeSkinV3(missingAsset, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_ASSET_INVALID"); }); +test("schema version 3 permits an open visual skin without a components document", async () => { + const bytes = zipSync({ + "manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 3, packageType: "open-skin" })), + "skin.css": strToU8('[data-ws-part="app"] { position: fixed; }'), + }); + const skin = await importSkinPack(new File([bytes.slice().buffer as ArrayBuffer], "v3-visual-only.wskin")); + assert.equal(skin.schemaVersion, 3); + assert.equal(skin.pluginData, undefined); + assert.match(skin.css, /position: fixed/); +}); + test("schema version 3 accepts a schema v2 full-page surface with host widgets", async () => { const components = { schemaVersion: 2, @@ -362,6 +373,34 @@ test("schema version 3 accepts a schema v2 full-page surface with host widgets", ]); }); +test("schema version 4 validates and caches isolated plugin package files without executing them", async () => { + const skin = await importSkinPack(makeSkinV4()); + const entry = "plugins/voice-toolbar/index.js"; + const style = "plugins/voice-toolbar/style.css"; + const icon = "plugins/voice-toolbar/assets/icon.png"; + assert.equal(skin.schemaVersion, 4); + assert.equal(skin.packageType, "open-skin"); + assert.equal(skin.runtimePlugins?.plugins[0].id, "voice-toolbar"); + assert.equal(await skin.runtimePluginFiles?.[entry].text(), "export const render = () => document.createElement('button');"); + assert.equal(await skin.runtimePluginFiles?.[style].text(), ".toolbar { color: teal; }"); + assert.equal(skin.runtimePluginFiles?.[icon].type, "image/png"); + assert.equal(skin.assets[icon], undefined, "plugin assets stay in the isolated plugin file set"); + assert.match(skin.css, /position: fixed/); + + await assert.rejects( + importSkinPack(makeSkinV4(undefined, { includeEntry: false })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_RUNTIME_PLUGIN_FILE_MISSING", + ); + await assert.rejects( + importSkinPack(makeSkinV4(undefined, { extra: { "plugins/unlisted/rogue.js": strToU8("export {};") } })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_FILE_UNSUPPORTED", + ); + await assert.rejects( + importSkinPack(makeSkinV4(undefined, { entryBytes: new Uint8Array(256 * 1024 + 1) })), + (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_RUNTIME_PLUGIN_SOURCE_SIZE", + ); +}); + 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" }); @@ -419,3 +458,34 @@ function makeSkinV3(components: unknown, css: string, assets: Record } = {}, +): File { + const packageFiles: Record = { + "manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json" })), + "skin.css": strToU8('[data-ws-part="app"] { position: fixed; color: teal; }'), + "plugins.json": strToU8(JSON.stringify(pluginDocument)), + "plugins/voice-toolbar/style.css": strToU8(".toolbar { color: teal; }"), + "plugins/voice-toolbar/assets/icon.png": new Uint8Array([1, 2, 3, 4]), + ...options.extra, + }; + if (options.includeEntry !== false) packageFiles["plugins/voice-toolbar/index.js"] = options.entryBytes ?? strToU8("export const render = () => document.createElement('button');"); + const bytes = zipSync(packageFiles); + return new File([bytes.slice().buffer as ArrayBuffer], "skin-v4.wskin", { type: "application/octet-stream" }); +} diff --git a/web/src/services/skin-pack.ts b/web/src/services/skin-pack.ts index 7268968..9552ae5 100644 --- a/web/src/services/skin-pack.ts +++ b/web/src/services/skin-pack.ts @@ -4,6 +4,14 @@ 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"; +import { + listSkinRuntimePluginFilePaths, + parseSkinRuntimePluginJson, + SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES, + SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES, + SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES, + type SkinRuntimePluginDocument, +} from "../../../src/shared/skin-runtime-plugins.js"; const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024; const MAX_EXPANDED_BYTES = 50 * 1024 * 1024; @@ -53,7 +61,7 @@ const ZIP_EOCD = 0x06054b50; const ZIP_CENTRAL_FILE = 0x02014b50; export interface SkinManifest { - schemaVersion: 1 | 2 | 3; + schemaVersion: 1 | 2 | 3 | 4; packageType?: "layout-skin" | "open-skin"; id: string; name: string; @@ -66,6 +74,7 @@ export interface SkinManifest { permissions?: []; content?: string; components?: string; + plugins?: string; minAppVersion: string; preview?: string; } @@ -97,6 +106,8 @@ export interface InstalledSkin extends SkinManifest { contentData?: SkinContent; layoutData?: SkinLayoutDocument; pluginData?: SkinPluginDocument; + runtimePlugins?: SkinRuntimePluginDocument; + runtimePluginFiles?: Record; previewBlob?: Blob; warnings: string[]; installedAt: number; @@ -154,9 +165,49 @@ export async function importSkinPack(file: File): Promise { const cssBytes = files.get(manifest.entry); if (!cssBytes || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE"); + let runtimePlugins: SkinRuntimePluginDocument | undefined; + if (manifest.plugins) { + const pluginsBytes = files.get(manifest.plugins); + if (!pluginsBytes || pluginsBytes.byteLength > SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES) { + throw new SkinPackError("plugins.json is missing or exceeds 256 KiB.", "SKIN_RUNTIME_PLUGIN_SIZE"); + } + try { runtimePlugins = parseSkinRuntimePluginJson(decoder.decode(pluginsBytes)); } + catch (error) { throw new SkinPackError("plugins.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_RUNTIME_PLUGIN_INVALID"); } + } + + const runtimePluginFiles: Record = Object.create(null) as Record; + const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : []; + const runtimePluginPathSet = new Set(runtimePluginPaths.map((path) => path.toLowerCase())); + const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview] + .filter((path): path is string => Boolean(path)).map((path) => path.toLowerCase()); + if (runtimePluginPaths.some((path) => manifestPathSet.includes(path))) { + throw new SkinPackError("Plugin files cannot reuse skin manifest, CSS, content, component, or preview paths.", "SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE"); + } + for (const pluginPath of runtimePluginPaths) { + const bytes = files.get(pluginPath); + if (!bytes) throw new SkinPackError(`A declared plugin file is missing: ${pluginPath}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING"); + const lowerPath = pluginPath.toLowerCase(); + if (lowerPath.endsWith(".js")) { + if (bytes.byteLength > SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES) throw new SkinPackError("Plugin entry files must be smaller than 256 KiB.", "SKIN_RUNTIME_PLUGIN_SOURCE_SIZE"); + try { decoder.decode(bytes); } catch { throw new SkinPackError("Plugin entry files must contain valid UTF-8.", "SKIN_RUNTIME_PLUGIN_ENCODING_INVALID"); } + runtimePluginFiles[pluginPath] = new Blob([bytes], { type: "text/javascript" }); + } else if (lowerPath.endsWith(".css")) { + if (bytes.byteLength > SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES) throw new SkinPackError("Plugin style files must be smaller than 512 KiB.", "SKIN_RUNTIME_PLUGIN_STYLE_SIZE"); + try { decoder.decode(bytes); } catch { throw new SkinPackError("Plugin style files must contain valid UTF-8.", "SKIN_RUNTIME_PLUGIN_ENCODING_INVALID"); } + runtimePluginFiles[pluginPath] = new Blob([bytes], { type: "text/css" }); + } else { + const mimeType = assetMimeType(pluginPath); + if (!mimeType) throw new SkinPackError(`Unsupported plugin asset: ${pluginPath}`, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"); + if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Plugin fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE"); + if (mimeType.startsWith("image/") && bytes.byteLength > MAX_IMAGE_BYTES) throw new SkinPackError("Plugin images must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE"); + runtimePluginFiles[pluginPath] = new Blob([bytes], { type: mimeType }); + } + } + const assets: Record = Object.create(null) as Record; for (const [path, bytes] of files) { - if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components].includes(path)) continue; + if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins].includes(path) + || runtimePluginPathSet.has(path.toLowerCase())) 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"); @@ -201,7 +252,7 @@ export async function importSkinPack(file: File): Promise { } 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() }; + return { ...manifest, css: compiled.css, assets, contentData, layoutData, pluginData, runtimePlugins, runtimePluginFiles, previewBlob, warnings: compiled.warnings, installedAt: Date.now() }; } export function resolveSkinCssAssets(css: string, assets: Record): { css: string; objectUrls: string[] } { @@ -347,10 +398,11 @@ 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 && schemaVersion !== 3) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION"); + if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) 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"); } + if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); } + if (schemaVersion === 4) fields.add("plugins"); 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"); } @@ -366,29 +418,33 @@ function parseManifest(bytes: Uint8Array): SkinManifest { 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)) { + if (schemaVersion === 4 && raw.packageType !== "open-skin") { + throw new SkinPackError("Version 4 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 || raw.plugins !== 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, schemaVersion === 2)! : undefined; - const components = schemaVersion === 3 ? stringField("components", 120)! : undefined; + const components = schemaVersion >= 3 ? stringField("components", 120, false) : undefined; + const plugins = schemaVersion === 4 ? stringField("plugins", 120)! : undefined; const content = stringField("content", 120, false); const preview = stringField("preview", 120, false); - for (const path of [entry, layout, content, components, preview].filter((item): item is string => Boolean(item))) { + for (const path of [entry, layout, content, components, plugins, 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")) || (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 (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(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 === 3 ? { packageType: "open-skin" as const } : {}), + ...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: stringField("name", 80)!, version, @@ -399,6 +455,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest { layout, content, components, + plugins, minAppVersion, preview, }; @@ -506,7 +563,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, 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 (!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) => { @@ -590,7 +647,7 @@ function compileSkinCss(source: string, id: string, assets: Record 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 (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) => {