From f8d61d22efcac34bb161bc4ec8fc7c397931ed3e Mon Sep 17 00:00:00 2001 From: OddTurtleHead <2396299126@qq.com> Date: Wed, 11 Nov 2026 18:06:20 +0800 Subject: [PATCH] feat: add host chrome theming and a skin-proof recovery layer Allow skins to theme host chrome through a second scope and explicit visibleParts. Official and built-in skins stay decoration-free by default. Harden the CSS compiler so skins cannot hide the document root, push protected controls off-screen, or target the host layer with sibling selectors. Move recovery and authorization UI into a closed Shadow DOM on the top layer, so a third-party skin cannot block the built-in skin reset. --- docs/SKIN_DEVELOPMENT.md | 131 ++- docs/examples/host-chrome-demo.wskin | Bin 0 -> 2622 bytes docs/examples/host-chrome-demo/chrome.json | 12 + docs/examples/host-chrome-demo/manifest.json | 13 + docs/examples/host-chrome-demo/skin.css | 71 ++ docs/examples/host-chrome-themed.wskin | Bin 0 -> 2585 bytes package.json | 3 +- src/admin/skin-registry.test.ts | 52 + src/admin/skin-registry.ts | 47 +- src/server/server.ts | 4 + src/shared/skin-chrome.ts | 242 +++++ src/shared/skin-css.test.ts | 341 +++++++ src/shared/skin-css.ts | 314 +++++- src/shared/skin-layout.test.ts | 46 +- src/shared/skin-layout.ts | 59 +- src/shared/skin-visual-parts.ts | 155 +++ web/public/host-chrome-demo.wskin | Bin 0 -> 2622 bytes web/public/host-chrome-preview.html | 210 ++++ web/public/host-chrome-themed.wskin | Bin 0 -> 2585 bytes web/scripts/build-host-chrome-demo-skin.mjs | 104 ++ web/src/components/HostChrome.vue | 251 +++++ web/src/components/InstanceAuthorization.vue | 27 +- web/src/components/LanguageSwitcher.vue | 2 +- web/src/components/PluginPanel.vue | 19 +- web/src/components/SkinLoadRecoveryNotice.vue | 2 +- web/src/components/SkinSwitcher.vue | 10 +- .../web-client/VoicePerformancePanel.vue | 3 +- .../components/web-client/WebClientHeader.vue | 1 + web/src/composables/usePublicSkin.ts | 13 + .../composables/useWebClientPublicConfig.ts | 5 + web/src/i18n/host-chrome.ts | 41 + web/src/services/host-chrome-preview.ts | 13 + .../services/host-chrome-visibility.test.ts | 80 ++ web/src/services/host-chrome-visibility.ts | 84 ++ web/src/services/host-chrome.ts | 118 +++ web/src/services/host-owned-layer.ts | 135 +++ .../services/host-recovery-helpers.test.ts | 128 +++ web/src/services/skin-pack.test.ts | 948 ++++++++++-------- web/src/services/skin-pack.ts | 54 +- web/src/services/skin-runtime.ts | 6 + web/src/views/DemoView.vue | 2 + web/src/views/WebClient.vue | 9 +- web/test/fixtures/host-chrome-recovery.html | 131 +++ web/test/host-chrome-recovery.test.mjs | 201 ++++ web/test/skin-lifecycle.test.mjs | 6 +- 45 files changed, 3535 insertions(+), 558 deletions(-) create mode 100644 docs/examples/host-chrome-demo.wskin create mode 100644 docs/examples/host-chrome-demo/chrome.json create mode 100644 docs/examples/host-chrome-demo/manifest.json create mode 100644 docs/examples/host-chrome-demo/skin.css create mode 100644 docs/examples/host-chrome-themed.wskin create mode 100644 src/shared/skin-chrome.ts create mode 100644 src/shared/skin-css.test.ts create mode 100644 src/shared/skin-visual-parts.ts create mode 100644 web/public/host-chrome-demo.wskin create mode 100644 web/public/host-chrome-preview.html create mode 100644 web/public/host-chrome-themed.wskin create mode 100644 web/scripts/build-host-chrome-demo-skin.mjs create mode 100644 web/src/components/HostChrome.vue create mode 100644 web/src/i18n/host-chrome.ts create mode 100644 web/src/services/host-chrome-preview.ts create mode 100644 web/src/services/host-chrome-visibility.test.ts create mode 100644 web/src/services/host-chrome-visibility.ts create mode 100644 web/src/services/host-chrome.ts create mode 100644 web/src/services/host-owned-layer.ts create mode 100644 web/src/services/host-recovery-helpers.test.ts create mode 100644 web/test/fixtures/host-chrome-recovery.html create mode 100644 web/test/host-chrome-recovery.test.mjs diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 14c8906..fc2de5f 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -96,6 +96,8 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可 assets/background.webp # 可选:页面艺术素材 assets/brand.woff2 # 可选:自带字体 components.json # v3 可选:声明式组件或完整页面 surface +chrome.json # v3/v4 可选:宿主装饰隐藏与图标位图覆盖(见「chrome.json」章节) +assets/icons/language.png # v3/v4 可选:工具栏图标位图覆盖素材 plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件 plugins//index.js # v4 插件代码,目前只校验和缓存 plugins//index.wasm # v4 有界 Wasm 插件入口 @@ -130,6 +132,7 @@ plugins//assets/ # v4 插件专属的本地图片或字体素材 | `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 | | `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 | | `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 | +| `chrome` | v3/v4 可选,包内 `chrome.json` 路径,最多 120 个字符;v1/v2 声明该字段会被拒绝。 | | `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 | | `description` | 可选,最多 400 个字符。 | @@ -393,6 +396,8 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 | 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` | | 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` | | `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` | +| 宿主外壳(皮肤根之外 / 宿主固定绘制) | `host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`、`app.skin-load-recovery`、`skin.library`;`host.recovery` / `host.permission` 仅为概念标识(闭合 Shadow DOM + 顶层,无 CSS 钩子,见下文) | +| 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) | `voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。 @@ -414,6 +419,100 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 } ``` +### 宿主外壳主题化(v3 / v4 开放皮肤) + +Plugins 悬浮钮、应用库窗口、大淡品牌水印、非关键提示与空状态装饰由宿主编排,并通过 `Teleport to="body"` 绘制在 `.ws-skin-root` **之外**。为保证拖动与叠层不被破坏,宿主不会把它们搬进皮肤根,而是提供第二个文档级作用域: + +- 皮肤激活时,宿主在 `documentElement` 上设置 `data-ws-host-skin="<皮肤 ID>"`;停用或回退到内置皮肤时立即移除。 +- 编译 `skin.css` 时,**只**命中下列宿主部件的单个选择器会被限定到 `:root[data-ws-host-skin="<皮肤 ID>"] …`,其余规则仍限定到 `.ws-skin-root[data-ws-skin="…"]`。宿主部件的选择器必须**以可主题化的 `[data-ws-part="host.…"]` 开头**,不能把 `:root`、`html`、`body` 或 `*:has(…)` 作为规则主体;`:root:has([data-ws-part="host.watermark"])` 一类写法会被拒绝。皮肤作者不能自己写 `html`、`body`、`data-ws-host-skin`、`data-ws-route`、`data-theme` 或 `data-ws-skin` 选择器,也不能在同一选择器里混用宿主部件与页面部件;宿主部件只对 schema v3/v4 开放皮肤生效。 +- 宿主外壳的布局与层级由 WebSpeak 拥有:皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform` 等把 `host.plugins.overlay` 之类控件变成全屏遮罩。 +- 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。 +- 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。 +- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。 +- 无 Popover API 或顶层提升被拒绝时,恢复胶囊会退回固定宿主层并使用 32 位最大 `z-index: 2147483647`。宿主层在 `#app` 之后追加到 `document.body`;与树内皮肤层同为最大层级时,后绘制的宿主层仍在上面。顶层(top layer)路径的 `showPopover()` / `showModal()` 仍高于两者。 + +可主题化的宿主部件: + +| 部件 | 内容 | +| --- | --- | +| `host.plugins.launcher` | 右下角 Plugins 悬浮按钮(颜色、尺寸、圆角、背景图均可改;也可声明式隐藏) | +| `host.plugins.overlay` | 应用库浮层窗口外壳;**不含**权限对话框里的批准/拒绝(`host.permission`) | +| `host.watermark` | 页面大淡 WebSpeak 品牌水印 | +| `host.hint` | 非关键提示文案(「音频控制始终保留…」一类) | +| `host.voice-status-decoration` | 右栏空的 Voice status 装饰条;与必要状态 `voice.connection-status`、`voice.audio-status` 完全分开 | + +### 恢复入口与授权对话框:结构上不可被皮肤触及 + +`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或主题化的 CSS 钩子:当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们: + +1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。 +2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。 +3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。 + +**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。 + +**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。 + +`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅使用独立部件 `app.skin-load-recovery`(「切换到内置皮肤」),与恢复胶囊不是同一个钩子。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。 + +恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。 + +`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。 + +示例(v3 `skin.css`): + +```css +/* 只命中宿主部件,编译后进入文档级宿主作用域 */ +[data-ws-part="host.plugins.launcher"] { + background: #1d4f9c; + color: #fff; + border-radius: 4px; + padding: 8px 12px; + font-size: 12px; +} +[data-ws-part="host.watermark"] { color: #dbe8f7; opacity: .08; } +[data-ws-part="host.hint"] { display: none; } +``` + +宿主图标槽用 `data-ws-icon-slot` 标记,槽名即部件名,可在 CSS 中直接换背景位图;也可用下面的 `chrome.json` 声明式覆盖。可用槽名: + +| 槽名 | 位置 | +| --- | --- | +| `host.plugins.launcher` | Plugins 悬浮按钮图标 | +| `language.trigger` | 语言下拉触发器图标 | +| `skin.trigger` | 皮肤下拉触发器图标 | +| `home.toolbar.settings` | 首页工具栏设置图标 | +| `voice.performance` | 语音页 Voice status / 性能触发器图标 | + +### `chrome.json`:声明式显示 / 隐藏与图标位图覆盖 + +v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB: + +```json +{ + "schemaVersion": 1, + "visibleParts": ["host.watermark", "host.hint", "host.voice-status-decoration"], + "hiddenParts": ["home.footer.decoration"], + "icons": { + "language.trigger": "assets/icons/language.png", + "skin.trigger": "assets/icons/skin.png", + "host.plugins.launcher": "assets/icons/apps.png" + } +} +``` + +| 字段 | 规则 | +| --- | --- | +| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 | +| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 | +| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 | + +图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。 + +实例级默认值:启动网关时设置环境变量 `WEBSPEAK_HOST_CHROME_HIDDEN_PARTS`(逗号或空格分隔,例如 `host.watermark,host.hint`)。`/api/public-config` 会返回校验后的 `hiddenHostParts`,宿主据此默认折叠这些非关键装饰;未知或受保护的名字会被忽略。宿主的三个装饰部件默认就是隐藏的;皮肤通过 `chrome.json` 的 `visibleParts` 开启,实例默认值与皮肤 `hiddenParts` 取并集并优先于 `visibleParts`。 + +`home.footer` 是容器,包含必要的「清除本地数据」链接 `home.footer.clear`,因此**不在**可隐藏列表;纯装饰文案被拆分为 `home.footer.decoration`,只隐藏它不会破坏恢复路径。 + ### 令牌、字体、动效和图片 皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则: @@ -476,28 +575,42 @@ v1/v2 外观可以因窄屏而更换图片裁切或装饰,但 @media 规则也 v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显示状态,因此皮肤开发者必须保留语音操作路径;授权界面、皮肤选择和恢复入口由宿主在皮肤作用域之外提供。以下选择器是旧格式对可选装饰部件的透明度白名单: +下面这份清单是**唯一**的可隐藏装饰部件白名单,由 `src/shared/skin-visual-parts.ts` 的 `DECORATIVE_PART_IDS` 定义;CSS 校验器(`OPTIONAL_VISUAL_PARTS`)、布局编辑器(`DECORATIVE_PART_IDS`)与 `chrome.json` 的 `hiddenParts` 共用它,三者永远一致: + ```css +[data-ws-part="demo.avatar"] +[data-ws-part="demo.badge"] +[data-ws-part="demo.note"] +[data-ws-part="demo.poke-notification"] +[data-ws-part="demo.wave"] +[data-ws-part="demo.member-status"] +[data-ws-part="home.feature"] +[data-ws-part="home.features"] +[data-ws-part="home.footer.decoration"] [data-ws-part="home.hero.eyebrow"] [data-ws-part="home.gateway-status"] -[data-ws-part="home.features"] -[data-ws-part="home.feature"] +[data-ws-part="home.join-card.sonar"] +[data-ws-part="home.join-card.waveform"] [data-ws-part="home.visitors"] +[data-ws-part="voice.activity.artwork"] [data-ws-part="voice.activity-heading"] [data-ws-part="voice.member.avatar"] +[data-ws-part="voice.member.avatar-wrap"] [data-ws-part="voice.member.live-indicator"] [data-ws-part="voice.member-row.avatar"] +[data-ws-part="voice.performance.metrics"] +[data-ws-part="voice.performance.webrtc-stats"] [data-ws-part="voice.screen-player.viewer-avatar"] [data-ws-part="voice.screen-player.live"] -[data-ws-part="demo.badge"] -[data-ws-part="demo.wave"] -[data-ws-part="demo.avatar"] -[data-ws-part="demo.member-status"] -[data-ws-part="demo.note"] +[data-ws-part="host.watermark"] +[data-ws-part="host.hint"] +[data-ws-part="host.voice-status-decoration"] +[data-ws-part="host.plugins.launcher"] ``` -上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 +上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 -皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 +皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。 diff --git a/docs/examples/host-chrome-demo.wskin b/docs/examples/host-chrome-demo.wskin new file mode 100644 index 0000000000000000000000000000000000000000..94ce2d7766725a26be36d1b475ca1434dab76397 GIT binary patch literal 2622 zcmb7Gc{r5&9v^Ea93E@Up|R9-CTmB?lCC|*GKkU~H6!jA%UEVcLL7vHOx7Gm*&C^3 z3AvclILO{mN=7)8vBX%9IEFj*Tvy(nd!NqxKELPpynlQ@@8|t|Ki~KBLn8S2r9dE% z5U3gL#J zmU!yzwJOWhla(&8hqK|2LYLrc!HFZ7(}l}wt!)F(*{!izGtIMan})w1NI$f~I7{eF zzp1n}{)b9_HU`Q8`{B1tWb_6q8|pZgzYUnOuewqU+^bSeXg!?6FszJtDEB^Tr6YLnUwle08{7?6lZx784LrtJ|7bfD|Wn#QVSyAm$Htpg=^Q_mS>e| zT(ge7f1$)%ws~U8o8c)rz`1e`xkscnebAkLt~iglA_;T%%U(hLex9EtBBdP1b0spr zlGn`0{b4G{i8$j(M0>cvl$@f^P)$=CvK*5XNR-rfk$HKWa&3K9zXnFhJ}}9C8yG%R zGjH?a`lg6;Yv?0>M2uHK1r!{B!GQH@h z4+v8)dY*6hpK4ST=2QpsfsA?>r=p+9IV=ctX!xQ->iDNH9pcqC}-kF25L^d?Lz{O}4lu7;(I`G{)putj^(p z{(%@`ad};;br3He4Zn_b=5RJ~H1nKwh%pOX@QYbhX zB{OTCU(U+FB5lT!x=T~kyhbK6#Azei>)X{1WWy33S{Ld>0*1&^n0o0Y}iE9#tSA1Nfd&lKyZPTUw&E2l^64xN#AI9-MAzk~2k{ zU9xsIeQa<__0~O^W~}22Lmq^T7;_R$x3UlHFqG8L6MWdIjWFevCOskN6cH1n{qQ1z zHyOP^TqU@&G8p^-j?xK-rgu0>137*k#&6~a4Ilo<9R2G?jNV$R zE5(IaKWqI%f-O1-Mc**RCQz*-GmKvuM~Q+_Hn++>Nh30y?P#AGM~tnVDU=~3Xn*c> z7Re553*gtOf?M$YkA`3I!vq8nzFj{p9mB0@_O&*8E{dIC@eTSh(%uctbOgmqd-2Cm z@8@;tQ?J7S^yWhPAv^MY)nab9i8ws=Z%`B!*&neHmKUhWva{B&DeQ7PXJX~co6g+- z3aXDVblxZusrqie@0mgODx%u`Wg(=)89UU&f*!10KW*wPM1 z*{@nm#1Kh;gP|S_vbFNrgiRmrBJ#h%gcs(unH;?^7rwnF literal 0 HcmV?d00001 diff --git a/docs/examples/host-chrome-demo/chrome.json b/docs/examples/host-chrome-demo/chrome.json new file mode 100644 index 0000000..c22b887 --- /dev/null +++ b/docs/examples/host-chrome-demo/chrome.json @@ -0,0 +1,12 @@ +{ + "schemaVersion": 1, + "hiddenParts": ["host.plugins.launcher"], + "visibleParts": ["host.watermark", "host.hint", "host.voice-status-decoration"], + "icons": { + "language.trigger": "assets/icons/language.png", + "skin.trigger": "assets/icons/skin.png", + "host.plugins.launcher": "assets/icons/apps.png", + "home.toolbar.settings": "assets/icons/settings.png", + "voice.performance": "assets/icons/status.png" + } +} diff --git a/docs/examples/host-chrome-demo/manifest.json b/docs/examples/host-chrome-demo/manifest.json new file mode 100644 index 0000000..bb5372f --- /dev/null +++ b/docs/examples/host-chrome-demo/manifest.json @@ -0,0 +1,13 @@ +{ + "schemaVersion": 3, + "packageType": "open-skin", + "id": "community.host-chrome-demo", + "name": "Host Chrome Demo", + "version": "1.0.0", + "author": "WebSpeak Project", + "license": "AGPL-3.0-only", + "description": "Minimal open skin demonstrating host chrome theming, declarative hiding and bitmap icon overrides.", + "entry": "skin.css", + "chrome": "chrome.json", + "minAppVersion": "0.3.0" +} diff --git a/docs/examples/host-chrome-demo/skin.css b/docs/examples/host-chrome-demo/skin.css new file mode 100644 index 0000000..96c17a0 --- /dev/null +++ b/docs/examples/host-chrome-demo/skin.css @@ -0,0 +1,71 @@ +/* Host chrome demo — v3 open skin (schemaVersion 3). + Every selector uses :root, [data-ws-page] or [data-ws-part]. + Host-only selectors are compiled into :root[data-ws-host-skin="…"]. */ + +:root { + --skin-accent: #1d4f9c; + --skin-panel: #ffffff; + --skin-border: #c9c9c9; + --skin-text: #141414; +} + +[data-ws-page] { + color-scheme: light; + font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif; + font-size: 12px; + color: #141414; +} + +[data-ws-part="home.header"] , +[data-ws-part="voice.header"] { + background: linear-gradient(180deg, #fbfbfb, #e9e9e9); + border-bottom: 1px solid var(--skin-border); +} + +[data-ws-part="voice.audio-dock"] { + border-top: 1px solid var(--skin-border); + background: #f7f9fb; +} + +/* --- Host chrome (outside .ws-skin-root) --- */ +[data-ws-part="host.plugins.launcher"] { + background: #1d4f9c; + color: #ffffff; + border: 1px solid #163c78; + border-radius: 3px; + padding: 7px 12px; + font-size: 12px; + font-weight: 600; + letter-spacing: .02em; + box-shadow: none; +} + +[data-ws-part="host.plugins.launcher"]:hover { + background: #2a63bb; +} + +[data-ws-part="host.plugins.overlay"] { + border: 2px solid #1d4f9c; + border-radius: 4px; +} + +[data-ws-part="host.watermark"] { + color: #1d4f9c; + opacity: .12; + font-family: Tahoma, sans-serif; +} + +[data-ws-part="host.hint"] { + color: #1d4f9c; + border-left: 2px solid #1d4f9c; + padding-left: 6px; +} + +[data-ws-part="host.voice-status-decoration"] { + opacity: .45; +} + +/* Icon slots can also be addressed directly from CSS. */ +[data-ws-part="host.plugins.launcher"] [data-ws-icon-slot="host.plugins.launcher"] { + background-color: transparent; +} diff --git a/docs/examples/host-chrome-themed.wskin b/docs/examples/host-chrome-themed.wskin new file mode 100644 index 0000000000000000000000000000000000000000..29e1ccac38e30696d2ed3df68f7e474aed0908cd GIT binary patch literal 2585 zcmb7GdpMN&9v_U!xEwuc$TW7`vd1Y*5$k^B7K25xG0}|JnL%#vjHZN8StgTQ(lM-c zYo@krvXK^RN@83>ZVeerj7zRzP&l(a$C0<^oTq)C=lA@c_mA)A{ro=P&-eZOT(J_+ z-4F;w3i1RW(nl3zfSKv}Rq+k3vGFssnMc=@kRJ0Q#ot5pg z&%)~IC4>UyO{)a(I)iq!P5&omJ4`{YrP9 z)(g1hw30S-i+ikE@R|Mn)2`dJ$wjMtC>LqsF49Iuw4WwLgq{ibs0=mLoFRTt_VUco zc`06`OKF$kerW}#di7zO@*UE3ui<~NAnjgD0)g-XjIPkKY#(?MTAwGz2(D^bpijVt zEuEg3<+M2vJ0)a=^>srpR!@A>!9_)vb}{_i7MQ&6Aq?AWuJR#AZ;V^mNXAhD)Ig(x zYTy0Kxy(+=RPDUnRGDe_i=HY?MHyu!GTDN5x6AiKKPn@wf}O9{nwDK{v}V6i`ts#v z$H#h861&C|W;mwNl_$lvA5WX@bFf@o)NEC@?S%#2B{i3I|N-XVqEE(RVNT zqmSeSN-1{Hu$Y5vcEXW=TsG7U>*z|L6qQt5clT~KPVMHq;E%Wz4*!6B_D})-h@B4$ z_c4kwLh5npNr;g*Hun^?Qki5$bsI;+AC4<(#X1ero7t&4q=Dg#oizi8S2oJr7-q#{ zHBC5!s*&QwCx!ZltC1XL-c{aICjF6zz=YdynW-hTzWyxm4j-Mq;XTO{ENbh;?2+X zIAtC8FP4KlPY|4mNl5kw^c#!C^o2tz#pxyrIGj`|apu^acq3$f3p6liET?Q0wRb!- z+2Yrxs%+$BU*+8czfY@GN1iN?$-Ylr`Swl%t3Bucqb)ZroOULUey=CWcj%?;FK)9PIihercL+ zB*Z@GT-EuBW}I~`N{Ix8jl)%20OE@XHo1T{;0rpqiQ-XvsF* z4ajzHH=tjypAmUFOth3mivR!t6hM!BIy3~(3nqjRsRUwxZdeF$Qg#*)jHC_u;qilu z3t@2aj$NwF9GE6Lqi-GJKKi3BLk&@pCaFu?m=#(K<6Cp*h377kVl(3C4Dq0EA;QF? z*BZZyz$ug%XltRG8y1pBLz=u=>SpIA%RTH(nSAjS{48Y=@DgOSK|vf5Nned`azubR zejLUx=7+w}zud=ve>K5ac-@QXNvWK4{Cko!J_5&CwI(L99Ah)Ax~<~m;5ernB>~g{ zMQ#H==%G8o*~J>&CI$QUJIgGp3)~sRkGr2d8~h&)KjTLT3j@AfKYc^9_3@eLdQJ{* zCduv#^lM9d!<%S~NJNmJ39O&kA)ESpD`E_NOl}q4)IRzBS`0 zPl@d&6cgVK`QJAH5zSAYZTA6J?DkS{KyKBcM3MPPT!IV1(X&yE(gJHmPw*?a=34+<2LNEk)G`1l2io$f;&t`K_zz|^jZb3W-LwssxFbvpXTQI&m bKum!D`pp$9Df-5rsV@bQ5ZwSi#y{lW8nhM2 literal 0 HcmV?d00001 diff --git a/package.json b/package.json index df847b6..291d7ee 100644 --- a/package.json +++ b/package.json @@ -11,10 +11,11 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.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 scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.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/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts 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-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts", + "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.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 scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.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/channel-capacity.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-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts 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-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/test/host-chrome-recovery.test.mjs", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", + "skin:host-chrome:build": "node web/scripts/build-host-chrome-demo-skin.mjs", "skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs", "skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs", "start": "node dist/index.js", diff --git a/src/admin/skin-registry.test.ts b/src/admin/skin-registry.test.ts index 0112a54..04d2bcf 100644 --- a/src/admin/skin-registry.test.ts +++ b/src/admin/skin-registry.test.ts @@ -449,3 +449,55 @@ function crc32(bytes: Buffer): number { } return (crc ^ 0xffffffff) >>> 0; } + +test("the registry validates chrome.json hidden parts and icon bitmaps without executing skin code", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-chrome-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const chromeManifest = { + ...manifest, + schemaVersion: 3, + packageType: "open-skin", + content: undefined, + preview: undefined, + chrome: "chrome.json", + }; + const chrome = (hiddenParts: string[], iconPath = "assets/icons/language.png") => JSON.stringify({ + schemaVersion: 1, + hiddenParts, + icons: { "language.trigger": iconPath }, + }); + const goodFiles: Array<[string, Buffer]> = [ + ["manifest.json", Buffer.from(JSON.stringify(chromeManifest))], + ["skin.css", Buffer.from('[data-ws-part="host.plugins.launcher"] { color: teal; }')], + ["chrome.json", Buffer.from(chrome(["host.watermark", "host.hint"]))], + ["assets/icons/language.png", Buffer.from([137, 80, 78, 71, 1, 2, 3])], + ]; + const saved = await registry.save(createZip(goodFiles), "sample-skin"); + assert.equal((saved as unknown as { chrome?: string }).chrome, "chrome.json"); + + const protectedChrome = [...goodFiles]; + protectedChrome[2] = ["chrome.json", Buffer.from(chrome(["voice.audio-dock"]))]; + await assert.rejects(registry.save(createZip(protectedChrome), "sample-skin"), + (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_CHROME_HIDDEN_INVALID"); + + const missingIcon = goodFiles.filter(([name]) => name !== "assets/icons/language.png"); + await assert.rejects(registry.save(createZip(missingIcon), "sample-skin"), + (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ICON_MISSING"); + + const badIconPath = [...goodFiles]; + badIconPath[2] = ["chrome.json", Buffer.from(chrome(["host.hint"], "../../escape.png"))]; + await assert.rejects(registry.save(createZip(badIconPath), "sample-skin"), + (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ICON_PATH"); + + const oversizedIcon = [...goodFiles]; + oversizedIcon[3] = ["assets/icons/language.png", Buffer.alloc(64 * 1024 + 1)]; + await assert.rejects(registry.save(createZip(oversizedIcon), "sample-skin"), + (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ICON_SIZE"); + + // v1/v2 packages cannot declare host chrome options. + const legacy = [...goodFiles]; + legacy[0] = ["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined, chrome: "chrome.json" }))]; + await assert.rejects(registry.save(createZip(legacy), "sample-skin"), + (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_SCHEMA_VERSION"); +}); diff --git a/src/admin/skin-registry.ts b/src/admin/skin-registry.ts index 1241fe2..2c16551 100644 --- a/src/admin/skin-registry.ts +++ b/src/admin/skin-registry.ts @@ -2,6 +2,12 @@ import { parseSkinWorkspacePolicy, type SkinWorkspacePolicy } from "../shared/sk import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js"; import { compileSkinCss, SkinCssValidationError, type SkinCssSchemaVersion } from "../shared/skin-css.js"; import { parseSkinLayoutJson } from "../shared/skin-layout.js"; +import { + parseSkinChromeDocument, + SKIN_CHROME_MAX_BYTES, + SkinChromeError, + validateSkinChromeAssets, +} from "../shared/skin-chrome.js"; import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../shared/skin-plugin.js"; import { listSkinRuntimePluginFilePaths, @@ -59,6 +65,7 @@ type ParsedSkinManifest = Omit packagePath.toLowerCase())); - const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview] + const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome, 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"); @@ -276,7 +283,7 @@ export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manif 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.plugins, manifest.preview].includes(packagePath) + if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome, 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"); @@ -286,6 +293,27 @@ export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manif const cssAssets = new Set([...fileBytes.keys()].filter((packagePath) => imageMime(packagePath) !== null || packagePath.toLowerCase().endsWith(".woff2"))); validateSkinCss(cssSource, manifest.id, cssAssets, manifest.schemaVersion); + if (manifest.chrome) { + const chromeBytes = fileBytes.get(manifest.chrome); + if (!chromeBytes || !chromeBytes.byteLength || chromeBytes.byteLength > SKIN_CHROME_MAX_BYTES) { + throw new SkinRegistryError("chrome.json is missing or exceeds 32 KiB.", "SKIN_CHROME_SIZE"); + } + try { + const chrome = parseSkinChromeDocument(decodeUtf8(chromeBytes, "chrome.json is not valid UTF-8.")); + // The registry only stores the archive; CSS is compiled by the browser + // importer from the same bytes. Verify every referenced bitmap here too + // so an incomplete package can never be enabled on an instance. + validateSkinChromeAssets(chrome, (packagePath) => { + const data = fileBytes.get(packagePath); + return data ? { bytes: data.byteLength, mime: imageMime(packagePath) ?? "" } : undefined; + }); + } catch (error) { + const chromeError = error instanceof SkinChromeError + ? error + : new SkinChromeError(error instanceof Error ? error.message : "Invalid chrome.json.", "SKIN_CHROME_INVALID"); + throw new SkinRegistryError(chromeError.message, chromeError.code); + } + } for (const plugin of runtimePlugins?.plugins ?? []) { if (!plugin.style) continue; const styleBytes = fileBytes.get(plugin.style); @@ -474,7 +502,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { 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"); fields.add("workspace"); } + if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); fields.add("chrome"); } 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"); @@ -494,8 +522,8 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { } 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 === 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"); + if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined || value.components !== undefined || value.plugins !== undefined || value.chrome !== undefined)) { + throw new SkinRegistryError("Version 1 skin packages cannot declare layout, chrome or plugin fields.", "SKIN_SCHEMA_VERSION"); } const version = read("version", 32); const minAppVersion = read("minAppVersion", 32); @@ -506,13 +534,14 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest { const content = readOptional("content", 120); const components = schemaVersion >= 3 && value.components != null ? read("components", 120) : undefined; const plugins = schemaVersion === 4 ? read("plugins", 120) : undefined; + const chrome = schemaVersion >= 3 && value.chrome != null ? read("chrome", 120) : undefined; const preview = readOptional("preview", 120); - 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()); + for (const candidate of [entry, layout, content, components, plugins, chrome, 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")) || (chrome && !chrome.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, chrome, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(chrome ? [chrome] : []), ...(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, ...(workspace ? { workspace } : {}), ...(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 } : {}) }; + return { schemaVersion, ...(workspace ? { workspace } : {}), ...(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 } : {}), ...(chrome ? { chrome } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) }; } function singleRootPrefix(paths: string[]): string { diff --git a/src/server/server.ts b/src/server/server.ts index d29a356..0506bb3 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -21,6 +21,7 @@ import { resolveVisitorTotal } from "./visitor-count.js"; import type { PluginRegistry } from "../plugins/registry.js"; import { PluginRuntime } from "../plugins/runtime.js"; import { createPluginRuntimeRouter } from "../plugins/runtime-router.js"; +import { parseHiddenHostParts } from "../shared/skin-chrome.js"; export interface WebServerOptions { port: number; @@ -123,6 +124,9 @@ export function createWebServer(options: WebServerOptions): WebServer { ...(visitorTotal === null ? {} : { visitorTotal }), accelerationAvailable: acceleration.length > 0, accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })), + // Instance-level default for non-critical host decorations. Unknown or + // protected names are ignored by the shared validator. + hiddenHostParts: parseHiddenHostParts(process.env.WEBSPEAK_HOST_CHROME_HIDDEN_PARTS), }); }); diff --git a/src/shared/skin-chrome.ts b/src/shared/skin-chrome.ts new file mode 100644 index 0000000..ed626d9 --- /dev/null +++ b/src/shared/skin-chrome.ts @@ -0,0 +1,242 @@ +import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js"; + +/** + * `chrome.json` is an optional, declarative companion to an open skin. + * + * It describes two host-chrome capabilities that CSS alone cannot express + * safely: + * - `visibleParts`: decorations the skin asks the host to render. This is the + * only opt-in; official and built-in skins stay clean. + * - `hiddenParts`: non-critical decorations the skin wants collapsed by + * default. Only explicitly optional parts are accepted. + * - `icons`: bitmap overrides for stable icon slots, keyed by part name. + * + * Both the browser importer and the server-side registry parse the exact same + * document, so a package accepted by one is accepted by the other. + */ + +export const SKIN_CHROME_MAX_BYTES = 32 * 1024; +export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32; +export const SKIN_CHROME_MAX_ICONS = 16; +export const SKIN_ICON_MAX_BYTES = 64 * 1024; +export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024; +export const SKIN_ICON_DIRECTORY = "assets/icons/"; + +const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]); + +/** + * Decorative host chrome that is hidden unless a skin explicitly opts in. + * Official and built-in skins ship no `chrome.json`, so they stay identical to + * production; a host-chrome pack opts in with `chrome.json#visibleParts`. + */ +export const DEFAULT_HIDDEN_HOST_PARTS: ReadonlySet = new Set([ + "host.watermark", + "host.hint", + "host.voice-status-decoration", +]); + +export interface SkinChromeDocument { + schemaVersion: 1; + hiddenParts: string[]; + /** + * Parts from `DEFAULT_HIDDEN_HOST_PARTS` (or other decorative parts) that a + * skin asks the host to render. This is the only opt-in for decorations; a + * chrome.json that omits it keeps the same clean chrome as built-in skins. + */ + visibleParts?: string[]; + icons: Record; +} + +export interface SkinChromeAssetInfo { + bytes: number; + mime: string; +} + +export class SkinChromeError extends Error { + constructor(message: string, readonly code: string) { + super(message); + this.name = "SkinChromeError"; + } +} + +function reject(message: string, code: string): never { + throw new SkinChromeError(message, code); +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +/** Validate and normalize an icon asset path. Only package-local bitmaps under assets/icons/ are allowed. */ +export function normalizeSkinIconPath(raw: unknown): string { + if (typeof raw !== "string" || !raw || raw.length > 160) { + return reject("An icon path must be a short, non-empty string.", "SKIN_ICON_PATH"); + } + const path = raw.split(/[?#]/, 1)[0]; + if (!path.startsWith(SKIN_ICON_DIRECTORY)) { + return reject(`Icon bitmaps must live in ${SKIN_ICON_DIRECTORY}.`, "SKIN_ICON_PATH"); + } + const segments = path.split("/"); + if (segments.length !== 3 || segments.some((segment) => !segment || segment === "." || segment === "..")) { + return reject("An icon path must be a single file inside assets/icons/.", "SKIN_ICON_PATH"); + } + const filename = segments[2]; + const extension = filename.split(".").pop()?.toLowerCase() ?? ""; + if (!SUPPORTED_ICON_EXTENSIONS.has(extension)) { + return reject("Icon bitmaps must be PNG, JPEG, WebP, AVIF or GIF files (SVG is not allowed).", "SKIN_ICON_PATH"); + } + if (/[\\:\0%\s]/.test(path) || /^[a-z]:/i.test(path) || path.startsWith("/") || path.includes("//")) { + return reject("An icon path must be a safe, package-relative path.", "SKIN_ICON_PATH"); + } + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(filename)) { + return reject("An icon filename contains unsupported characters.", "SKIN_ICON_PATH"); + } + return path; +} + +export function parseSkinChromeDocument(source: string): SkinChromeDocument { + const bytes = new TextEncoder().encode(source).byteLength; + if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) { + return reject("chrome.json must be between 1 byte and 32 KiB.", "SKIN_CHROME_SIZE"); + } + let raw: unknown; + try { raw = JSON.parse(source); } + catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); } + if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID"); + for (const key of Object.keys(raw)) { + if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") { + return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID"); + } + } + if (raw.schemaVersion !== 1) return reject("chrome.json must use schemaVersion 1.", "SKIN_CHROME_INVALID"); + + const hiddenParts: string[] = []; + if (raw.hiddenParts !== undefined) { + if (!Array.isArray(raw.hiddenParts) || raw.hiddenParts.length > SKIN_CHROME_MAX_HIDDEN_PARTS) { + return reject("hiddenParts must be an array of at most 32 part names.", "SKIN_CHROME_HIDDEN_INVALID"); + } + for (const entry of raw.hiddenParts) { + if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) { + return reject(`Only explicitly optional decorative parts may be hidden: ${String(entry)}.`, "SKIN_CHROME_HIDDEN_INVALID"); + } + if (!hiddenParts.includes(entry)) hiddenParts.push(entry); + } + } + + let visibleParts: string[] | undefined; + if (raw.visibleParts !== undefined) { + if (!Array.isArray(raw.visibleParts) || raw.visibleParts.length > SKIN_CHROME_MAX_HIDDEN_PARTS) { + return reject("visibleParts must be an array of at most 32 part names.", "SKIN_CHROME_VISIBLE_INVALID"); + } + visibleParts = []; + for (const entry of raw.visibleParts) { + if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) { + return reject(`Only explicitly optional decorative parts may be shown: ${String(entry)}.`, "SKIN_CHROME_VISIBLE_INVALID"); + } + if (!visibleParts.includes(entry)) visibleParts.push(entry); + } + } + + const icons: Record = Object.create(null) as Record; + if (raw.icons !== undefined) { + if (!isRecord(raw.icons)) return reject("icons must be an object mapping slot names to asset paths.", "SKIN_ICON_INVALID"); + const entries = Object.entries(raw.icons); + if (entries.length > SKIN_CHROME_MAX_ICONS) { + return reject(`A skin may override at most ${SKIN_CHROME_MAX_ICONS} icons.`, "SKIN_ICON_INVALID"); + } + for (const [slot, path] of entries) { + if (!SKIN_ICON_SLOT_IDS.has(slot)) { + return reject(`Unknown icon slot: ${slot}.`, "SKIN_ICON_INVALID"); + } + icons[slot] = normalizeSkinIconPath(path); + } + } + return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons }; +} + +/** + * Merge the instance default, the skin's explicit opt-ins and its hidden list + * into the set of optional host parts the host must not render. + * + * Decorations are hidden by default so official/built-in skins match + * production. A pack opts in with `visibleParts`; a pack that ships a + * chrome.json without that field (icons-only or hiddenParts-only) stays hidden, + * and `hiddenParts` still wins over both. + * + * The decision is intentionally independent of the generated host CSS: the + * importer appends `compileSkinChromeCss()` output after the author CSS, so + * sniffing the combined string for `data-ws-part="host.…"` would treat every + * hiddenParts entry as a declaration that the skin themes host chrome. + */ +export function resolveHiddenHostParts( + document: SkinChromeDocument | undefined, + instanceHiddenParts: readonly string[], +): ReadonlySet { + const hidden = new Set(instanceHiddenParts.filter((part) => DECORATIVE_PART_IDS.has(part))); + const visible = new Set(document?.visibleParts ?? []); + for (const part of DEFAULT_HIDDEN_HOST_PARTS) { + if (!visible.has(part)) hidden.add(part); + } + for (const part of document?.hiddenParts ?? []) hidden.add(part); + return hidden; +} + +/** Compile-time path and size validation against the actual package contents. */ +export function validateSkinChromeAssets( + document: SkinChromeDocument, + lookup: (path: string) => SkinChromeAssetInfo | undefined, +): void { + let total = 0; + for (const [slot, path] of Object.entries(document.icons)) { + const asset = lookup(path); + if (!asset) return reject(`Icon bitmap is missing from the package: ${path}`, "SKIN_ICON_MISSING"); + if (!asset.mime.startsWith("image/") || asset.mime === "image/svg+xml") { + return reject(`Icon bitmap is not a supported raster image: ${path}`, "SKIN_ICON_INVALID"); + } + if (!asset.bytes || asset.bytes > SKIN_ICON_MAX_BYTES) { + return reject(`Icon bitmap ${path} exceeds ${SKIN_ICON_MAX_BYTES / 1024} KiB.`, "SKIN_ICON_SIZE"); + } + total += asset.bytes; + if (total > SKIN_ICONS_MAX_TOTAL_BYTES) { + return reject(`All icon bitmaps together exceed ${SKIN_ICONS_MAX_TOTAL_BYTES / 1024} KiB.`, "SKIN_ICON_SIZE"); + } + void slot; + } +} + +/** Instance-level default: comma/space separated optional part names, or a JSON array. */ +export function parseHiddenHostParts(value: unknown): string[] { + const entries = typeof value === "string" + ? value.split(/[\s,]+/) + : Array.isArray(value) ? value : []; + const result: string[] = []; + for (const entry of entries) { + if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) continue; + if (!result.includes(entry) && result.length < SKIN_CHROME_MAX_HIDDEN_PARTS) result.push(entry); + } + return result; +} + +function cssString(value: string): string { + return value.replace(/["\\\n\r]/g, (character) => `\\${character}`); +} + +/** + * Generate host-owned CSS. It is appended to the compiled skin CSS by the + * importer, so `wskin-asset:` markers are resolved together with author CSS. + * The document-level scope reaches both the skin root and Teleported host + * chrome, while never selecting arbitrary html/body content. + */ +export function compileSkinChromeCss(document: SkinChromeDocument, skinId: string): string { + const scope = `:root[${HOST_SKIN_ATTRIBUTE}="${cssString(skinId)}"]`; + const rules: string[] = []; + for (const part of document.hiddenParts) { + rules.push(`${scope} [data-ws-part="${cssString(part)}"] { display: none !important; }`); + } + for (const [slot, path] of Object.entries(document.icons)) { + const target = `${scope} [data-ws-icon-slot="${cssString(slot)}"]`; + rules.push(`${target} { background-image: url("wskin-asset:${encodeURIComponent(path)}") !important; background-position: center !important; background-repeat: no-repeat !important; background-size: contain !important; }`); + rules.push(`${target} > * { visibility: hidden !important; }`); + } + return rules.length ? rules.join("\n") + "\n" : ""; +} diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts new file mode 100644 index 0000000..3cb73db --- /dev/null +++ b/src/shared/skin-css.test.ts @@ -0,0 +1,341 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js"; +import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js"; +import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js"; +import { + compileSkinChromeCss, + DEFAULT_HIDDEN_HOST_PARTS, + parseHiddenHostParts, + parseSkinChromeDocument, + resolveHiddenHostParts, + SKIN_ICON_MAX_BYTES, + validateSkinChromeAssets, +} from "./skin-chrome.js"; + +const assets = new Set(); +const compile = (css: string, version: 1 | 2 | 3 | 4 = 3, id = "demo-skin") => + compileSkinCss(css, id, assets, version); + +test("the CSS hide whitelist and the layout decorative registry are one shared set", () => { + assert.deepEqual([...OPTIONAL_VISUAL_PARTS].sort(), [...DECORATIVE_PART_IDS].sort()); + assert.deepEqual([...LAYOUT_DECORATIVE].sort(), [...DECORATIVE_PART_IDS].sort()); + for (const part of ["host.watermark", "host.hint", "host.voice-status-decoration", "home.footer.decoration"]) { + assert.ok(OPTIONAL_VISUAL_PARTS.has(part), `${part} must be hideable`); + } + // home.footer contains the necessary "clear local data" link: only its + // decorative children may be hidden, never the container. + assert.equal(OPTIONAL_VISUAL_PARTS.has("home.footer"), false); + assert.ok(PROTECTED_PART_IDS.has("home.footer"), "the footer container must not be hidden"); + assert.ok(PROTECTED_PART_IDS.has("home.footer.clear")); + // Decorative password-dialog children stay hideable: existing skins rely on it. + for (const part of ["auth.password.decoration", "auth.password.eyebrow", "auth.password.lead", "auth.password.label", "auth.password.field-icon"]) { + assert.equal(PROTECTED_PART_IDS.has(part), false, `${part} must stay hideable`); + } + for (const part of ["auth.password.dialog", "auth.password.form", "auth.password.field", "auth.password.error", "auth.password.actions"]) { + assert.ok(PROTECTED_PART_IDS.has(part), `${part} must be protected`); + } + // A screen-share exit button is a control but not part of the essential audio + // path; v3 skins may still hide it, so it is not in the protected set. + assert.equal(PROTECTED_PART_IDS.has("voice.screen-player.exit"), false); + // The load-failure banner and the library recovery entry are distinct parts. + assert.ok(PROTECTED_PART_IDS.has("app.skin-load-recovery")); + assert.ok(PROTECTED_PART_IDS.has("host.recovery")); +}); + +test("host chrome selectors compile into the document-level host scope", () => { + const themed = compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }'); + assert.match(themed.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/); + assert.doesNotMatch(themed.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/); + + const scoped = compile('[data-ws-part="host.plugins.launcher"]:hover { color: white; }'); + assert.match(scoped.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]:hover/); + + const overlay = compile('[data-ws-part="host.plugins.overlay"] { border-color: red; }'); + assert.match(overlay.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.overlay"\]/); + + // Ordinary page parts keep the original skin-root scope. + const page = compile('[data-ws-part="home.header"] { color: teal; }'); + assert.match(page.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="home\.header"\]/); + assert.doesNotMatch(page.css, /data-ws-host-skin/); +}); + +test("the extended scope cannot escape to html/body or host internals", () => { + const rejected: Array<[string, RegExp]> = [ + ['html [data-ws-part="host.watermark"] { color: red; }', /cannot target html or body/], + ['body [data-ws-part="host.watermark"] { color: red; }', /cannot target html or body/], + ['[data-ws-host-skin] [data-ws-part="host.watermark"] { color: red; }', /host attribute/], + ['[data-ws-route="webclient"] [data-ws-part="host.watermark"] { color: red; }', /host attribute/], + ['[data-ws-part="home.header"] [data-ws-part="host.watermark"] { color: red; }', /cannot be mixed/], + ['[data-ws-part="host.recovery"] { display: none; }', /Trusted or unknown host part/], + ['[data-ws-part="host.permission"] { display: none; }', /Trusted or unknown host part/], + ['[data-ws-part="host.unknown"] { color: red; }', /Trusted or unknown host part/], + [':root { --ws-internal-token: red; }', /--skin- prefix/], + ['[data-ws-part="host.hint"] { behavior: url(x.htc); }', /Executable CSS/], + ['[data-ws-part="host.hint"] { background: url("https://example.invalid/x.png"); }', /Only relative paths/], + ]; + for (const [css, message] of rejected) { + assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css); + } + assert.throws(() => compile('[data-ws-part="host.watermark"] { color: red; }', 1), /requires an open/); + assert.throws(() => compile('[data-ws-part="host.watermark"] { color: red; }', 2), /requires an open/); +}); + +test("a leading :root cannot escape the skin root through a sibling combinator", () => { + // `:root` is rewritten in place, so these become `.ws-skin-root … ~ …` and + // would select the body-level host layer in the preview/fixture topology. + for (const css of [ + ':root ~ [data-ws-host-layer] { display: none !important; }', + ':root ~ * { display: none !important; }', + ':root ~ div { pointer-events: none !important; }', + ':root + [data-ws-host-layer] { display: none; }', + ':root + * { visibility: hidden; }', + ':root:hover ~ * { display: none !important; }', + ':ROOT ~ * { display: none !important; }', + ]) { + assert.throws(() => compile(css), /sibling combinator after :root/, css); + } + + // Descendant scoping (the documented form) still compiles into the skin root. + const descendant = compile(':root [data-ws-part="home.header"] { color: teal; }'); + assert.match(descendant.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="home\.header"\]/); + // `>` and the descendant combinator are not sibling escapes. + assert.doesNotThrow(() => compile(':root > [data-ws-part="home.header"] { color: teal; }')); + assert.doesNotThrow(() => compile(':root { --skin-accent: #4c8f88; }')); +}); + +test("host-owned layer attributes are not skin hooks", () => { + for (const attribute of [ + "data-ws-host-layer", + "data-ws-host-recovery", + "data-ws-host-layer-content", + "data-ws-recovery-action", + ]) { + // A public hook in the same selector gets past the "must use a public hook" + // check, so the attribute-name rejection is what stops the selector. + assert.throws(() => compile(`:root [${attribute}] { display: none; }`), /host attribute/, attribute); + assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute); + assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}="x"] { color: red; }`), /host attribute/, attribute); + } + // Normal descendant theming of a public part remains accepted. + assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }')); +}); + +test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => { + for (const part of [ + "voice.audio-dock", + "voice.audio-dock.microphone", + "voice.audio-dock.output", + "voice.connection-status", + "voice.audio-status", + "voice.connection-status.reconnect", + "home.security-note", + "home.footer", + "home.footer.clear", + "app.toast", + ]) { + const mustNameSubject = (error: unknown) => error instanceof Error + && error.message.includes(`"${part}"`) + && /must remain available/.test(error.message); + assert.throws(() => compile(`[data-ws-part="${part}"] { display: none; }`), mustNameSubject, part); + assert.throws(() => compile(`[data-ws-part="${part}"] { opacity: 0; }`), mustNameSubject, part); + } + // Existing skins legitimately hide a decorative child *inside* the audio + // dock; only the dock/control subject itself is protected. + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }')); + // Hiding the screen-share exit button is a visual choice, not an essential + // audio/recovery path: v3 skins may still do it. Legacy v1/v2 skins keep the + // layout guard, so this cannot be used as a positioning attack. + assert.doesNotThrow(() => compile('[data-ws-part="voice.screen-player.exit"] { display: none; }')); + assert.throws(() => compile('[data-ws-part="voice.screen-player.exit"] { display: none; }', 1), /must not change layout/); + // Explicitly optional decorations remain hideable. + assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { display: none; }')); + assert.doesNotThrow(() => compile('[data-ws-part="home.footer.decoration"] { visibility: hidden; }')); +}); + +test("chrome.json declares hidden parts and icon bitmaps, with path and size validation", () => { + const valid = parseSkinChromeDocument(JSON.stringify({ + schemaVersion: 1, + hiddenParts: ["host.watermark", "host.hint", "host.watermark"], + icons: { "language.trigger": "assets/icons/language.png", "host.plugins.launcher": "assets/icons/apps.png" }, + })); + assert.deepEqual(valid.hiddenParts, ["host.watermark", "host.hint"]); + assert.equal(valid.icons["language.trigger"], "assets/icons/language.png"); + assert.equal(valid.visibleParts, undefined); + + const optedIn = parseSkinChromeDocument(JSON.stringify({ + schemaVersion: 1, + visibleParts: ["host.watermark", "host.hint", "host.watermark"], + })); + assert.deepEqual(optedIn.visibleParts, ["host.watermark", "host.hint"]); + + const lookup = (path: string) => path.endsWith(".png") ? { bytes: 128, mime: "image/png" } : undefined; + assert.doesNotThrow(() => validateSkinChromeAssets(valid, lookup)); + const generated = compileSkinChromeCss(valid, "demo-skin"); + assert.match(generated, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.watermark"\] \{ display: none !important; \}/); + assert.match(generated, /\[data-ws-icon-slot="language\.trigger"\] \{ background-image: url\("wskin-asset:assets%2Ficons%2Flanguage\.png"\)/); + assert.match(generated, /\[data-ws-icon-slot="language\.trigger"\] > \* \{ visibility: hidden/); + + const invalidDocuments: Array<[unknown, RegExp]> = [ + [{ schemaVersion: 2, hiddenParts: [] }, /schemaVersion 1/], + [{ schemaVersion: 1, hiddenParts: ["voice.audio-dock"] }, /explicitly optional/], + [{ schemaVersion: 1, hiddenParts: ["host.recovery"] }, /explicitly optional/], + [{ schemaVersion: 1, hiddenParts: ["home.footer"] }, /explicitly optional/], + [{ schemaVersion: 1, visibleParts: ["voice.audio-dock"] }, /explicitly optional/], + [{ schemaVersion: 1, icons: { "unknown.slot": "assets/icons/x.png" } }, /Unknown icon slot/], + [{ schemaVersion: 1, icons: { "language.trigger": "../escape.png" } }, /assets\/icons/], + [{ schemaVersion: 1, icons: { "language.trigger": "assets/icons/x.svg" } }, /SVG is not allowed/], + [{ schemaVersion: 1, icons: { "language.trigger": "https://example.invalid/x.png" } }, /assets\/icons/], + [{ schemaVersion: 1, extra: true }, /unsupported field/], + ]; + for (const [value, message] of invalidDocuments) { + assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value)); + } + assert.throws(() => validateSkinChromeAssets(valid, () => undefined), /missing from the package/); + assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: SKIN_ICON_MAX_BYTES + 1, mime: "image/png" })), /exceeds/); + assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/); +}); + +test("instance-level hidden parts ignore unknown and protected names", () => { + assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]); + assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]); + assert.deepEqual(parseHiddenHostParts(undefined), []); +}); + +test("host-scope CSS cannot make the document root the subject of a hiding rule", () => { + for (const css of [ + // The verified escape: the root is promoted to the host scope but still the subject. + ':root:has([data-ws-part="host.watermark"]) { display: none; }', + ':root:has([data-ws-part="host.hint"]) { visibility: hidden; }', + '[data-ws-part="host.watermark"] :root { display: none; }', + '*:has([data-ws-part="host.watermark"]) { display: none; }', + 'html:has([data-ws-part="host.watermark"]) { display: none; }', + 'body:has([data-ws-part="host.watermark"]) { display: none; }', + '[data-ws-part="host.watermark"] + body { display: none; }', + ]) { + assert.throws(() => compile(css), /must start from a themeable|document root|cannot target html or body/, css); + } + + // Legitimate host-part theming still compiles into the document-level scope. + const launcher = compile('[data-ws-part="host.plugins.launcher"] { color: white; }'); + assert.match(launcher.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/); + assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"]:has(span) { color: red; }')); + assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] [data-ws-icon-slot="host.plugins.launcher"] { opacity: .5; }')); +}); + +test("protected controls cannot be hidden through variables or moved off-screen", () => { + assert.throws( + () => compile(':root { --skin-hide: none; } [data-ws-part="voice.audio-dock"] { display: var(--skin-hide); }'), + /cannot use indirect values/, + ); + assert.throws( + () => compile('[data-ws-part="voice.audio-dock"] { position: fixed; left: -9999px; }'), + /must remain on screen/, + ); + assert.throws( + () => compile('[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }'), + /must remain on screen/, + ); + assert.throws( + () => compile('[data-ws-part="voice.audio-dock"] { inset: 0 0 0 -120vw; }'), + /must remain on screen/, + ); + + // Large negative margins are the same escape as an inset: reject the pattern + // generically, including longhands, shorthand, relative units and calc(). + for (const css of [ + '[data-ws-part="voice.audio-dock"] { margin-left: -9999px; }', + '[data-ws-part="voice.audio-dock"] { margin-inline: -9999px; }', + '[data-ws-part="voice.audio-dock"] { margin-block-start: -1200px; }', + '[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }', + '[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }', + '[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }', + '[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }', + ]) { + assert.throws(() => compile(css), /must remain on screen/, css); + } + assert.throws( + () => compile(':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock"] { margin-left: var(--skin-pull); }'), + /cannot use indirect values/, + ); + + // Ordinary appearance tokens and optional decorations keep working. + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { background: var(--skin-panel); }')); + assert.doesNotThrow(() => compile(':root { --skin-hide: none; } [data-ws-part="host.watermark"] { display: var(--skin-hide); }')); + // A small margin on a protected control and a decorative dock child are still + // legitimate v3 theming. + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }')); + // The off-screen guard only protects the subject, not decorative or + // non-protected parts. + assert.doesNotThrow(() => compile('[data-ws-part="home.header"] { margin-left: -9999px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }')); +}); + +test("host chrome cannot be restyled into a viewport-sized overlay", () => { + assert.throws( + () => compile('[data-ws-part="host.plugins.overlay"] { position: fixed; inset: 0; z-index: 2147483647; }'), + /layout is owned by WebSpeak/, + ); + assert.throws(() => compile('[data-ws-part="host.watermark"] { position: fixed; }'), /layout is owned by WebSpeak/); + assert.throws(() => compile('[data-ws-part="host.plugins.overlay"] { width: 100vw; height: 100vh; }'), /fullscreen overlay/); + + // Descendant rules are the same escape: `*` can turn the library contents + // into a viewport mask even when the shell itself is frozen. + for (const css of [ + '[data-ws-part="host.plugins.overlay"] * { position: fixed; inset: 0; z-index: 2147483647; }', + '[data-ws-part="host.plugins.overlay"] * { width: 100vw; height: 100vh; }', + '[data-ws-part="host.plugins.overlay"] .ws-plugin-library { position: fixed; top: 0; left: 0; }', + '[data-ws-part="host.watermark"] * { z-index: 2147483647; }', + ]) { + assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); + } + // zoom (and any comparable scaling) must not blow the shell up either. + for (const css of [ + '[data-ws-part="host.plugins.overlay"] { zoom: 10; }', + '[data-ws-part="host.plugins.overlay"] * { zoom: 10; }', + '[data-ws-part="host.plugins.overlay"] { transform: scale(10); }', + ]) { + assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); + } + + // Colors, borders, radius, shadows and artwork stay available, including on + // descendants of the overlay. + const themed = compile('[data-ws-part="host.plugins.overlay"] { border: 2px solid #1d4f9c; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px #0003; }'); + assert.match(themed.css, /data-ws-part="host\.plugins\.overlay"/); + assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { color: #fff; border-color: #1d4f9c; border-radius: 6px; }')); + assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }')); +}); + +test("official and built-in skins hide host decorations unless the active skin opts in", () => { + const decorations = ["host.watermark", "host.hint", "host.voice-status-decoration"]; + assert.deepEqual([...DEFAULT_HIDDEN_HOST_PARTS].sort(), [...decorations].sort()); + + // Built-in skins ship no chrome.json: decorations are hidden, launcher stays. + const builtin = resolveHiddenHostParts(undefined, []); + for (const part of decorations) assert.ok(builtin.has(part), `${part} must be hidden for built-in skins`); + assert.equal(builtin.has("host.plugins.launcher"), false); + + // An explicit opt-in shows them again; hiddenParts still wins. + const optedIn = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], visibleParts: decorations, icons: {} }, []); + for (const part of decorations) assert.equal(optedIn.has(part), false, `${part} must be visible after opting in`); + const explicitlyHidden = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.hint"], visibleParts: decorations, icons: {} }, []); + assert.ok(explicitlyHidden.has("host.hint")); + + // hiddenParts-only chrome.json is not an opt-in: decorations stay hidden. + // This is the production path that previously reported a false positive + // because the appended chrome CSS itself contained `data-ws-part="host.…"`. + const hiddenOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.plugins.launcher"], icons: {} }, []); + for (const part of decorations) assert.ok(hiddenOnly.has(part), `${part} must stay hidden for a hiddenParts-only pack`); + assert.ok(hiddenOnly.has("host.plugins.launcher")); + const watermarkOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.watermark"], icons: {} }, []); + for (const part of decorations) assert.ok(watermarkOnly.has(part), `${part} must stay hidden when only watermark is declared`); + + // chrome.json alone (for example an icon-only override) is not an opt-in. + const iconOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], icons: {} }, []); + for (const part of decorations) assert.ok(iconOnly.has(part), `${part} must stay hidden without visibleParts`); + + // Instance defaults cannot be re-enabled by a skin. + const instanceHidden = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], visibleParts: decorations, icons: {} }, ["host.watermark"]); + assert.ok(instanceHidden.has("host.watermark")); +}); diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts index 4784940..543d340 100644 --- a/src/shared/skin-css.ts +++ b/src/shared/skin-css.ts @@ -1,6 +1,14 @@ import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss"; import selectorParser from "postcss-selector-parser"; import valueParser from "postcss-value-parser"; +import { + DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS, + HOST_CHROME_PART_IDS, + HOST_SKIN_ATTRIBUTE, + PROTECTED_PART_IDS, +} from "./skin-visual-parts.js"; + +export { OPTIONAL_VISUAL_PARTS }; export type SkinCssSchemaVersion = 1 | 2 | 3 | 4; export type SkinCssAssets = Readonly> | Map | Set; @@ -36,25 +44,55 @@ const LAYOUT_AFFECTING_PROPERTIES = new Set([ "writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content", "position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope", ]); -const OPTIONAL_VISUAL_PARTS = new Set([ - "home.hero.eyebrow", - "home.gateway-status", - "home.features", - "home.feature", - "home.visitors", - "home.join-card.waveform", - "home.join-card.sonar", - "voice.activity-heading", - "voice.member.avatar", - "voice.member.live-indicator", - "voice.member-row.avatar", - "voice.screen-player.viewer-avatar", - "voice.screen-player.live", - "demo.badge", - "demo.wave", - "demo.avatar", - "demo.member-status", - "demo.note", +/** + * Properties that let a skin move a host-chrome part into a viewport-sized + * overlay or out from under the host's own layout. Appearance properties + * (colors, borders, radius, shadows, artwork) stay available. + */ +const HOST_CHROME_LOCKED_PROPERTIES = new Set([ + "all", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline", + "inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end", + "z-index", "transform", "translate", "scale", "rotate", "zoom", "float", "clear", + "clip", "clip-path", "mask", "mask-image", "perspective", "contain", +]); +/** + * The plugin library shell additionally owns its footprint: without a locked + * size a skin could still stretch it over the recovery entry even though + * `position`/`inset`/`z-index` are frozen. + */ +const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([ + ...HOST_CHROME_LOCKED_PROPERTIES, + "width", "height", "min-width", "min-height", "max-width", "max-height", + "inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size", + "aspect-ratio", "margin", "margin-block", "margin-inline", "margin-block-start", "margin-block-end", + "margin-inline-start", "margin-inline-end", +]); +/** Properties whose indirect values could smuggle a hidden or moved control past the static checks. */ +const INDIRECT_VALUE_PROPERTIES = new Set([ + "all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image", + "position", "top", "right", "bottom", "left", "inset", + "inset-block", "inset-inline", "inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end", + "transform", "translate", "scale", "rotate", "zoom", + // Margins move a subject just like insets do; a variable could resolve to a + // viewport-sized negative value, so protected controls may not use them. + "margin", "margin-top", "margin-right", "margin-bottom", "margin-left", + "margin-block", "margin-block-start", "margin-block-end", + "margin-inline", "margin-inline-start", "margin-inline-end", +]); +/** Attributes a skin author must never use to reach outside the public hooks. */ +const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([ + HOST_SKIN_ATTRIBUTE, + "data-ws-skin", + "data-ws-route", + "data-theme", + "data-ws-hidden-host-parts", + // Host-owned recovery layer internals. They are deliberately not skin hooks, + // and naming them keeps `:root [data-ws-host-layer]` / mixed selectors from + // opting into the element by attribute. + "data-ws-host-layer", + "data-ws-host-recovery", + "data-ws-host-layer-content", + "data-ws-recovery-action", ]); export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } { const size = new TextEncoder().encode(source).byteLength; @@ -67,6 +105,12 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const scope = pluginId ? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]` : skinScope; + // Host chrome is Teleported outside `.ws-skin-root`. Rules that target only + // registered host parts use a second, document-level scope anchored to an + // attribute the host sets while this exact skin is active. Author CSS never + // names html/body: the host generates the scope itself. + const hostSkinScope = `:root[${HOST_SKIN_ATTRIBUTE}="${id}"]`; + const hostScopeNodes = selectorParser().astSync(hostSkinScope).first!.nodes.map((node) => node.clone()); const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`; const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone()); const warnings = new Set(); @@ -117,12 +161,15 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const text = selector.toString().trim(); if (!text) throw new SkinCssValidationError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR"); if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinCssValidationError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR"); + const hostScope = assertHostChromeSelector(text, schemaVersion, Boolean(pluginId)); + const activeScope = hostScope ? hostSkinScope : scope; + const activeNodes = hostScope ? hostScopeNodes : scopeNodes; if (/^:root\b/.test(text)) { - selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone()); + selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, activeScope)).first!.clone()); return; } selector.prepend(selectorParser.combinator({ value: " " })); - for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone()); + for (let index = activeNodes.length - 1; index >= 0; index -= 1) selector.prepend(activeNodes[index].clone()); }); }).processSync(rule.selector); } catch (error) { @@ -157,6 +204,7 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets root.walkDecls((declaration: Declaration) => { const property = decodeCssEscapes(declaration.prop).toLowerCase(); + const unprefixedProperty = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); const value = declaration.value.trim(); const decodedValue = decodeCssEscapes(value); const owningRule = findOwningRule(declaration); @@ -164,6 +212,16 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const canHideTarget = owningRule ? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim())) : false; + // Trusted UI and essential audio/recovery controls stay available even for + // open skins. The host also draws authorization and recovery UI outside the + // skin root, so a container-level hide cannot remove them either. + const protectedTarget = owningRule && !keyframesRule ? selectorSubjectProtectedPart(owningRule.selector) : null; + // Every themeable host part referenced anywhere in the selector. A rule may + // target a descendant of the overlay (for example with `*`), so the subject + // alone is not enough to decide whether host chrome layout is at stake. + const hostChromeParts = owningRule && !keyframesRule ? selectorHostChromeParts(owningRule.selector) : []; + const inHostChromeScope = hostChromeParts.length > 0; + const inOverlayScope = hostChromeParts.includes("host.plugins.overlay"); if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property) && !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) { throw declaration.error(pluginId @@ -173,13 +231,26 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets 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."); } + // Host chrome lives outside the skin root and owns its own placement. A + // skin may repaint it (colors, borders, radius, artwork) but must not turn + // it — or any of its descendants — into a viewport-sized overlay above + // authorization/recovery UI. + if (inHostChromeScope && HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) { + throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls."); + } + if (inOverlayScope && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) { + throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead."); + } if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing."); if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) { throw declaration.error("Executable CSS values are not allowed."); } const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase(); - if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) { - if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts."); + if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) { + if (protectedTarget) { + throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`); + } + if (!canHideTarget && schemaVersion < 3) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts."); } const removesVisual = property === "all" || (property === "display" && compactValue === "none") @@ -188,16 +259,25 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets || (property === "pointer-events" && compactValue === "none") || (property === "clip-path" && /inset\(\s*50%/.test(compactValue)) || (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue)); + if (removesVisual && protectedTarget) { + throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`); + } if (removesVisual && !canHideTarget && schemaVersion < 3) { throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available."); } const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue)) || (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue)) || (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue)); + if (visuallyRemoves && protectedTarget) { + throw declaration.error(`The required control "${protectedTarget}" must remain visible.`); + } 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 (protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) { + throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`); + } + if (schemaVersion >= 3 && removesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls."); if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile."); const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames); declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => { @@ -250,6 +330,136 @@ function selectorUsesPublicHook(selector: string, allowCustomClasses = false): b } } +/** + * A leading `:root` is rewritten in place to `.ws-skin-root[data-ws-skin=…]`. + * With a sibling combinator (`+` / `~`) that would select siblings of the + * skin root — for example the host-owned layer, which is a body child and a + * sibling of the skin root in the preview fixture. Skin scope must only apply + * to the root's own subtree, so reject that shape structurally. A leading + * `:root` followed by a descendant combinator (`:root [data-ws-part="…"]`) + * remains valid. + */ +function assertNoRootSiblingEscape(parsed: selectorParser.Root): void { + for (const item of parsed.nodes) { + const first = item.nodes[0]; + if (!first || first.type !== "pseudo" || first.value.toLowerCase() !== ":root") continue; + const combinator = item.nodes.find((node) => node.type === "combinator"); + if (combinator && (combinator.value === "+" || combinator.value === "~")) { + throw new SkinCssValidationError( + "Skin selectors cannot use a sibling combinator after :root; the scope must stay inside the skin root.", + "SKIN_CSS_SELECTOR", + ); + } + } +} + +/** + * Decide whether one selector of an author rule targets host chrome, and + * enforce the boundary around the extended document-level scope. + * + * Returns true when the compiled rule must use `:root[data-ws-host-skin=…]`. + * Author CSS can never name html/body or the host marker attribute itself; the + * host generates that anchor. Host parts are only available to open (v3/v4) + * skins and may not be mixed with page parts in the same selector. + */ +function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchemaVersion, isPluginStyle: boolean): boolean { + let parsed: selectorParser.Root; + try { parsed = selectorParser().astSync(selector); } + catch { throw new SkinCssValidationError("A CSS selector is invalid.", "SKIN_CSS_SELECTOR"); } + assertNoRootSiblingEscape(parsed); + const partNames: string[] = []; + parsed.walk((node) => { + if (node.type === "tag" && ["html", "body"].includes(node.value.toLowerCase())) { + throw new SkinCssValidationError("Skin selectors cannot target html or body elements.", "SKIN_CSS_SELECTOR"); + } + if (node.type === "attribute" && FORBIDDEN_SCOPE_ATTRIBUTES.has(node.attribute.toLowerCase())) { + throw new SkinCssValidationError(`Skin selectors cannot reference the host attribute ${node.attribute}.`, "SKIN_CSS_SELECTOR"); + } + if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) { + partNames.push(node.value.replace(/^['"]|['"]$/g, "")); + } + }); + const hostParts = partNames.filter((part) => HOST_CHROME_PART_IDS.has(part)); + const unknownHostParts = partNames.filter((part) => part.startsWith("host.") && !HOST_CHROME_PART_IDS.has(part)); + if (unknownHostParts.length) { + throw new SkinCssValidationError(`Trusted or unknown host part cannot be styled: ${unknownHostParts[0]}.`, "SKIN_CSS_SELECTOR"); + } + if (!hostParts.length) return false; + if (hostParts.length !== partNames.length) { + throw new SkinCssValidationError("Host chrome parts cannot be mixed with page parts in one selector.", "SKIN_CSS_SELECTOR"); + } + if (isPluginStyle) throw new SkinCssValidationError("Plugin styles cannot target host chrome parts.", "SKIN_CSS_SELECTOR"); + if (schemaVersion < 3) throw new SkinCssValidationError("Host chrome theming requires an open (schemaVersion 3 or 4) skin.", "SKIN_CSS_SELECTOR"); + assertHostChromeSubject(parsed); + return true; +} + +/** + * A host-scope rule is promoted to the document root. To keep that promotion + * from turning the root/html/body (or an arbitrary ancestor) into the rule's + * subject, every host-scope selector must be anchored on a themeable host part + * in its first compound and must never end in `:root`. + */ +function assertHostChromeSubject(parsed: selectorParser.Root): void { + for (const item of parsed.nodes) { + if (!item.nodes.length) continue; + const firstCombinator = item.nodes.findIndex((node) => node.type === "combinator"); + if (firstCombinator === 0) { + throw new SkinCssValidationError("Host chrome rules must start from a themeable host part.", "SKIN_CSS_SELECTOR"); + } + const firstCompound = firstCombinator === -1 ? item.nodes : item.nodes.slice(0, firstCombinator); + const anchored = firstCompound.some((node) => node.type === "attribute" + && node.attribute.toLowerCase() === "data-ws-part" + && HOST_CHROME_PART_IDS.has((node.value ?? "").replace(/^['"]|['"]$/g, ""))); + if (!anchored) { + throw new SkinCssValidationError("Host chrome rules must start from a themeable [data-ws-part=\"host.…\"] selector; the document root cannot be themed or hidden.", "SKIN_CSS_SELECTOR"); + } + let subjectStart = 0; + for (let index = item.nodes.length - 1; index >= 0; index -= 1) { + if (item.nodes[index].type === "combinator") { subjectStart = index + 1; break; } + } + for (let index = subjectStart; index < item.nodes.length; index += 1) { + const node = item.nodes[index]; + if (node.type === "pseudo" && node.value.toLowerCase() === ":root") { + throw new SkinCssValidationError("Host chrome rules cannot make the document root the subject of a rule.", "SKIN_CSS_SELECTOR"); + } + } + } +} + +/** Find a protected part in the subject (last compound) of any selector in a rule. */ +function selectorSubjectProtectedPart(selector: string): string | null { + try { + const parsed = selectorParser().astSync(selector); + for (const item of parsed.nodes) { + let start = 0; + for (let index = item.nodes.length - 1; index >= 0; index -= 1) { + if (item.nodes[index].type === "combinator") { start = index + 1; break; } + } + for (let index = start; index < item.nodes.length; index += 1) { + const node = item.nodes[index]; + if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) continue; + const part = node.value.replace(/^['"]|['"]$/g, ""); + if (PROTECTED_PART_IDS.has(part)) return part; + } + } + } catch { /* A malformed selector is rejected elsewhere. */ } + return null; +} + +/** Find every themeable host part referenced by a selector, in any compound. */ +function selectorHostChromeParts(selector: string): string[] { + const parts: string[] = []; + try { + selectorParser().astSync(selector).walk((node) => { + if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) return; + const part = node.value.replace(/^['"]|['"]$/g, ""); + if (HOST_CHROME_PART_IDS.has(part) && !parts.includes(part)) parts.push(part); + }); + } catch { /* A malformed selector is rejected elsewhere. */ } + return parts; +} + function isLayoutAffectingProperty(property: string): boolean { const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true; @@ -259,6 +469,62 @@ function isLayoutAffectingProperty(property: string): boolean { return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed); } +/** + * True when a positioning/margin/transform value can push a protected control + * off-screen. Thresholds are deliberately low: a protected control has a + * minimum 44 px hit target, so an offset of a hundred pixels is already enough + * to make it unreachable. Percentages and viewport units are compared against a + * full viewport/containing block. + */ +const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform|scale|rotate)(?:-|$)/; +const ABSOLUTE_OFFSET_LIMIT_PX = 100; +const RELATIVE_OFFSET_LIMIT = 100; + +function absoluteLengthToPixels(magnitude: number, unit: string): number | null { + switch (unit) { + case "px": return magnitude; + case "rem": case "em": return magnitude * 16; + case "ex": case "rex": case "ch": return magnitude * 8; + case "cm": return magnitude * 37.8; + case "mm": return magnitude * 3.78; + case "q": return magnitude * 0.945; + case "in": return magnitude * 96; + case "pt": return magnitude * 1.333; + case "pc": return magnitude * 16; + default: return null; + } +} + +function valueMovesOffscreen(property: string, value: string): boolean { + if (!OFFSET_PROPERTY_PATTERN.test(property)) return false; + let offscreen = false; + valueParser(value).walk((node) => { + if (node.type !== "word") return; + const match = /^(-?(?:\d+|\d*\.\d+))(px|rem|em|r?ex|ch|%|cm|mm|q|in|pt|pc|(?:s|l|d)?v(?:w|h|min|max)|cq(?:w|h|min|max|i|b))$/i.exec(node.value); + if (!match) return; + const magnitude = Math.abs(Number(match[1])); + const unit = match[2].toLowerCase(); + if (unit === "%" || /^(?:s|l|d)?v(?:w|h|min|max)$/.test(unit) || /^cq(?:w|h|min|max|i|b)$/.test(unit)) { + if (magnitude >= RELATIVE_OFFSET_LIMIT) offscreen = true; + return; + } + const pixels = absoluteLengthToPixels(magnitude, unit); + if (pixels !== null && pixels >= ABSOLUTE_OFFSET_LIMIT_PX) offscreen = true; + }); + // A matrix transform can smuggle a large translation in unitless numbers. + if (property === "transform") { + valueParser(value).walk((node) => { + if (node.type !== "function") return; + const name = node.value.toLowerCase(); + if (name !== "matrix" && name !== "matrix3d") return; + const numbers = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim())); + const translations = name === "matrix" ? [numbers[4], numbers[5]] : [numbers[12], numbers[13]]; + if (translations.some((translation) => Number.isFinite(translation) && Math.abs(translation) >= ABSOLUTE_OFFSET_LIMIT_PX)) offscreen = true; + }); + } + return offscreen; +} + function findOwningRule(node: Node): Rule | null { let parent = node.parent; while (parent && parent.type !== "root") { diff --git a/src/shared/skin-layout.test.ts b/src/shared/skin-layout.test.ts index 0714ed7..f2a369e 100644 --- a/src/shared/skin-layout.test.ts +++ b/src/shared/skin-layout.test.ts @@ -8,7 +8,11 @@ import { SKIN_LAYOUT_COMPONENTS, validateSkinLayout, canEditSkinLayoutComponent, + DECORATIVE_PART_IDS, + HOST_PART_IDS, } from "./skin-layout.js"; +import { HOST_TRUSTED_PART_IDS } from "./skin-visual-parts.js"; +import { OPTIONAL_VISUAL_PARTS } from "./skin-css.js"; async function vueSources(directory: URL): Promise { const files = (await readdir(directory, { recursive: true })).filter((file) => file.endsWith(".vue")); @@ -16,16 +20,20 @@ async function vueSources(directory: URL): Promise { } test("the stable layout registry covers public skin hooks and excludes the admin console", async () => { - const [webClient, demo, sharedComponents, skinSwitcher, languageSwitcher, admin, adminComponents] = await Promise.all([ + const [webClient, demo, sharedComponents, skinSwitcher, languageSwitcher, hostChrome, pluginPanel, authorization, recoveryNotice, admin, adminComponents] = await Promise.all([ readFile(new URL("../../web/src/views/WebClient.vue", import.meta.url), "utf8"), readFile(new URL("../../web/src/views/DemoView.vue", import.meta.url), "utf8"), vueSources(new URL("../../web/src/components/web-client/", import.meta.url)), readFile(new URL("../../web/src/components/SkinSwitcher.vue", import.meta.url), "utf8"), readFile(new URL("../../web/src/components/LanguageSwitcher.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/components/HostChrome.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/components/PluginPanel.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/components/InstanceAuthorization.vue", import.meta.url), "utf8"), + readFile(new URL("../../web/src/components/SkinLoadRecoveryNotice.vue", import.meta.url), "utf8"), readFile(new URL("../../web/src/views/AdminView.vue", import.meta.url), "utf8"), vueSources(new URL("../../web/src/components/admin/", import.meta.url)), ]); - const publicSource = [webClient, demo, ...sharedComponents, skinSwitcher, languageSwitcher].join("\n"); + const publicSource = [webClient, demo, ...sharedComponents, skinSwitcher, languageSwitcher, hostChrome, pluginPanel, authorization, recoveryNotice].join("\n"); const publicParts = new Set([...publicSource.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1])); const interactiveParts = new Set(); for (const match of publicSource.matchAll(/<[A-Za-z][\w.-]*\b[^>]*>/gs)) { @@ -35,17 +43,25 @@ test("the stable layout registry covers public skin hooks and excludes the admin const isNativeControl = /^<(?:button|a|input|select|textarea)\b/i.test(attributes); const hasButtonRole = /\brole="button"/.test(attributes); const keyboardAction = /@keydown\.(?:enter|space)\b/.test(attributes); - // Native HTML drag gestures are desktop-only and do not make a row a 44px touch control. - if (isNativeControl || hasButtonRole || keyboardAction) interactiveParts.add(part); + // Native HTML drag gestures are desktop-only and do not make a row a 44px touch control. + if (isNativeControl || hasButtonRole || keyboardAction) interactiveParts.add(part); } - const registered = new Set(SKIN_LAYOUT_COMPONENTS.map((component) => component.selectorPart)); - for (const part of publicParts) assert.ok(registered.has(part), "Unregistered public layout hook: " + part); - const micStatus = getSkinLayoutComponent("voice.member.mic-status", "voice"); - assert.equal(micStatus?.category, "core"); - assert.equal(micStatus?.editable, true); - assert.ok(micStatus?.layoutModes.includes("visibility")); - assert.equal(getSkinLayoutComponent("voice.server-banner", "voice")?.editable, true); - for (const part of interactiveParts) { + const registered = new Set(SKIN_LAYOUT_COMPONENTS.map((component) => component.selectorPart)); + for (const part of publicParts) assert.ok(registered.has(part), "Unregistered public layout hook: " + part); + for (const part of HOST_PART_IDS) assert.ok(registered.has(part), "Unregistered host chrome hook: " + part); + // The layout registry and the CSS hiding whitelist must never drift apart. + assert.deepEqual([...DECORATIVE_PART_IDS].sort(), [...OPTIONAL_VISUAL_PARTS].sort()); + for (const part of HOST_TRUSTED_PART_IDS) { + const component = getSkinLayoutComponent(part, "voice"); + assert.equal(component?.category, "trusted-chrome", "Trusted host entry must not be layout-editable: " + part); + assert.equal(component?.editable, false); + } + const micStatus = getSkinLayoutComponent("voice.member.mic-status", "voice"); + assert.equal(micStatus?.category, "core"); + assert.equal(micStatus?.editable, true); + assert.ok(micStatus?.layoutModes.includes("visibility")); + assert.equal(getSkinLayoutComponent("voice.server-banner", "voice")?.editable, true); + for (const part of interactiveParts) { const component = SKIN_LAYOUT_COMPONENTS.find((entry) => entry.id === part); assert.ok(component, "Interactive public hook must have its own component metadata: " + part); assert.ok(component.minTouchTarget >= 44, "Interactive public hook needs a 44px touch target: " + part); @@ -174,9 +190,9 @@ test("registered components carry accessibility, responsive, purpose, and data-s assert.ok(component.narrowScreenBehavior.length > 0); assert.ok(component.dataSensitivity.length > 0); } - assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.connect")?.minTouchTarget, 44); - assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.range")?.minTouchTarget, 44); - assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.checkbox")?.minTouchTarget, 44); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.connect")?.minTouchTarget, 44); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.range")?.minTouchTarget, 44); + assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.checkbox")?.minTouchTarget, 44); assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.feature")?.category, "optional"); assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.security-note")?.category, "trusted-chrome"); assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.identity-import.security")?.dataSensitivity, "identity"); diff --git a/src/shared/skin-layout.ts b/src/shared/skin-layout.ts index 4505a0f..5acf1e1 100644 --- a/src/shared/skin-layout.ts +++ b/src/shared/skin-layout.ts @@ -1,3 +1,13 @@ +import { + AUTH_PASSWORD_PART_IDS, + DECORATIVE_PART_IDS, + HOST_PART_IDS, + PROTECTED_PART_IDS, + TRUSTED_PART_IDS, +} from "./skin-visual-parts.js"; + +export { AUTH_PASSWORD_PART_IDS, DECORATIVE_PART_IDS, TRUSTED_PART_IDS, PROTECTED_PART_IDS, HOST_PART_IDS }; + export type SkinLayoutPage = "home" | "voice" | "demo"; export type SkinLayoutProfile = "desktop" | "tablet" | "mobile"; @@ -46,24 +56,10 @@ export interface SkinLayoutComponent { editable: boolean; } -const AUTH_PASSWORD_PART_IDS = [ - "auth.password.backdrop", - "auth.password.dialog", - "auth.password.decoration", - "auth.password.eyebrow", - "auth.password.title", - "auth.password.lead", - "auth.password.form", - "auth.password.label", - "auth.password.field", - "auth.password.field-icon", - "auth.password.error", - "auth.password.actions", -] as const; - const PUBLIC_PART_IDS = new Set([ "app", "app.toast", + "app.skin-load-recovery", ...AUTH_PASSWORD_PART_IDS, "control", "demo.action.poke", @@ -330,25 +326,16 @@ const PUBLIC_PART_IDS = new Set([ "voice.shell", "voice.whisper-strip", "voice.workspace", + // Host chrome is rendered outside the skin root. It stays in the public + // part registry so contract tests and the layout catalogue describe it, + // even though the layout editor only moves elements inside the root. + ...HOST_PART_IDS, + "home.footer.decoration", + "home.footer.clear", + "skin.library", ]); const CONTROL_KINDS = ["button", "link", "input", "checkbox", "range", "select", "textarea", "menuitem", "draggable"] as const; -const TRUSTED_PART_IDS = new Set([ - ...AUTH_PASSWORD_PART_IDS, - "app", - "app.toast", - "home.security-note", - "home.identity-import.security", - "voice.connection-status", - "voice.screen-share-error", -]); -const DECORATIVE_PART_IDS = new Set([ - "demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave", - "home.feature", "home.features", "home.footer", "home.hero.eyebrow", "home.join-card.sonar", - "home.join-card.waveform", "home.visitors", "voice.activity.artwork", "voice.member.avatar-wrap", - "voice.member.live-indicator", "voice.performance.metrics", "voice.performance.webrtc-stats", - "voice.screen-player.viewer-avatar", -]); const SHELL_PART_IDS = new Set([ "app", "home", "home.content", "home.form", "home.header", "voice.shell", "voice.workspace", "voice.content", "demo.layout", "demo.main", @@ -373,6 +360,7 @@ const ACTION_PART_IDS = new Set([ "voice.favorite-servers.strip.server", "demo.voice-card", "home.identity-import.drop-zone", "voice.channel-group", "voice.member-row", "voice.server-switcher.trigger", "voice.server-switcher.item", "voice.channel-tree.expander", "voice.channel-tree.row", "demo.skin-switcher", "demo.language-switcher", + "skin.library", "home.footer.clear", "host.plugins.launcher", ]); const INTERACTIVE_PART_IDS = new Set([ "voice.connection-status.nickname.input", "voice.connection-status.reconnect", @@ -392,6 +380,7 @@ const INTERACTIVE_PART_IDS = new Set([ "voice.screen-player.exit", "voice.screen-player.fullscreen", "demo.voice-card", "home.identity-import.drop-zone", "voice.channel-group", "voice.member-row", "demo.skin-switcher", "demo.language-switcher", + "skin.library", "home.footer.clear", "host.plugins.launcher", ]); const IDENTITY_PART_IDS = new Set([ "home.identity", "home.identity-actions", "home.identity-export.button", "home.identity-import-dialog", @@ -402,8 +391,9 @@ const IDENTITY_PART_IDS = new Set([ ]); const COMMON_PART_IDS = new Set([ ...AUTH_PASSWORD_PART_IDS, - "app", "app.toast", "control", "skin.trigger", "skin.menu", "skin.option", - "language.trigger", "language.menu", "language.option", + ...HOST_PART_IDS, + "app", "app.toast", "app.skin-load-recovery", "control", "skin.trigger", "skin.menu", "skin.option", + "skin.library", "language.trigger", "language.menu", "language.option", ]); function pageOfPart(id: string): SkinLayoutPage | "common" | null { @@ -444,6 +434,9 @@ const COMPONENT_NAME_PARTS: Record = { user: "User", video: "Video", viewer: "Viewer", viewers: "Viewers", visitors: "Visitors", voice: "Voice", volume: "Volume", wave: "Wave", waveform: "Waveform", webrtc: "WebRTC", whisper: "Whisper", workspace: "Workspace", wrap: "Wrapper", zone: "Drop zone", + host: "Host", plugins: "Plugins", launcher: "Launcher", overlay: "Overlay", watermark: "Watermark", + decoration: "Decoration", recovery: "Recovery", permission: "Permission", library: "Library", + clear: "Clear", }; function componentName(id: string): string { diff --git a/src/shared/skin-visual-parts.ts b/src/shared/skin-visual-parts.ts new file mode 100644 index 0000000..76301a1 --- /dev/null +++ b/src/shared/skin-visual-parts.ts @@ -0,0 +1,155 @@ +/** + * Single source of truth for the public skin part policy. + * + * `skin-css.ts` (CSS hiding whitelist), `skin-layout.ts` (layout editor + * metadata) and `skin-chrome.ts` (declarative host chrome document) all read + * these sets so a part can never be "hideable" in one layer and protected in + * another. Adding a part here is the only way to make it explicitly optional. + */ + +/** Password dialog parts are trusted in both the CSS and layout layers. */ +export const AUTH_PASSWORD_PART_IDS = [ + "auth.password.backdrop", + "auth.password.dialog", + "auth.password.decoration", + "auth.password.eyebrow", + "auth.password.title", + "auth.password.lead", + "auth.password.form", + "auth.password.label", + "auth.password.field", + "auth.password.field-icon", + "auth.password.error", + "auth.password.actions", +] as const; + +/** + * Host chrome is drawn by WebSpeak outside `.ws-skin-root` (Teleport to body) + * or is painted by the host with fixed artwork. A skin may theme these parts, + * but only through the dedicated document-level host scope, never with a + * global `html` / `body` selector. + */ +export const HOST_CHROME_PART_IDS: ReadonlySet = new Set([ + "host.plugins.launcher", + "host.plugins.overlay", + "host.watermark", + "host.hint", + "host.voice-status-decoration", +]); + +/** Host parts that must stay reachable and can never be hidden or themed. */ +export const HOST_TRUSTED_PART_IDS: ReadonlySet = new Set([ + "host.recovery", + "host.permission", +]); + +/** All host-owned parts (used by the part registry and documentation). */ +export const HOST_PART_IDS: ReadonlySet = new Set([ + ...HOST_CHROME_PART_IDS, + ...HOST_TRUSTED_PART_IDS, +]); + +/** + * Explicitly optional (decorative) visual parts. Both `OPTIONAL_VISUAL_PARTS` + * in the CSS compiler and `DECORATIVE_PART_IDS` in the layout registry are + * aliases of this set. + * + * `home.footer` is deliberately absent: the footer contains the necessary + * "clear local data" recovery link. The purely decorative text is split into + * `home.footer.decoration`, which is the part that may be hidden. + */ +export const DECORATIVE_PART_IDS: ReadonlySet = new Set([ + "demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave", + "demo.member-status", + "home.feature", "home.features", "home.footer.decoration", "home.hero.eyebrow", + "home.gateway-status", "home.join-card.sonar", "home.join-card.waveform", "home.visitors", + "voice.activity.artwork", "voice.activity-heading", "voice.member.avatar", + "voice.member.avatar-wrap", "voice.member.live-indicator", "voice.member-row.avatar", + "voice.performance.metrics", "voice.performance.webrtc-stats", + "voice.screen-player.viewer-avatar", "voice.screen-player.live", + "host.watermark", "host.hint", "host.voice-status-decoration", "host.plugins.launcher", +]); + +/** Trusted host UI: authorization, connection status, identity and recovery. */ +export const TRUSTED_PART_IDS: ReadonlySet = new Set([ + ...AUTH_PASSWORD_PART_IDS, + ...HOST_TRUSTED_PART_IDS, + "app", + "app.toast", + "app.skin-load-recovery", + "home.security-note", + "home.identity-import.security", + "voice.connection-status", + "voice.screen-share-error", +]); + +/** + * Parts that even an open (v3/v4) skin must never visually remove: the + * permission/recovery entries and the essential audio operation path. + * + * This is deliberately narrower than `TRUSTED_PART_IDS`: trusted metadata also + * covers decorative children of the password dialog (`auth.password.decoration`, + * `auth.password.eyebrow`, `auth.password.lead`, `auth.password.label`, + * `auth.password.field-icon`), which existing skins legitimately hide. Only the + * dialog shell, form, field, error and action row are protected. + */ +export const PROTECTED_PART_IDS: ReadonlySet = new Set([ + "app", + "app.toast", + "app.skin-load-recovery", + "home.security-note", + "home.identity-import.security", + // The footer container holds the necessary "clear local data" recovery + // link; only its decorative children may be hidden. + "home.footer", + "home.footer.clear", + "voice.connection-status", + "voice.connection-status.reconnect", + "voice.connection-status.nickname.input", + "voice.audio-status", + "voice.audio-dock", + "voice.audio-dock.microphone", + "voice.audio-dock.output", + "voice.audio-dock.microphone-panel", + "voice.audio-dock.output-panel", + "voice.audio-settings", + "voice.screen-share-error", + "voice.mobile-nav", + "voice.mobile-more", + "demo.reconnect.restore", + "auth.password.dialog", + "auth.password.form", + "auth.password.field", + "auth.password.error", + "auth.password.actions", + "host.recovery", + "host.permission", +]); + +/** Stable icon bitmap slots. `chrome.json` may only reference these names. */ +export const SKIN_ICON_SLOT_IDS: ReadonlySet = new Set([ + "host.plugins.launcher", + "language.trigger", + "skin.trigger", + "voice.performance", + "home.toolbar.settings", +]); + +export function isHostChromePart(part: string): boolean { + return HOST_CHROME_PART_IDS.has(part); +} + +export function isHostPart(part: string): boolean { + return HOST_PART_IDS.has(part) || part.startsWith("host."); +} + +export function isDecorativePart(part: string): boolean { + return DECORATIVE_PART_IDS.has(part); +} + +export function isProtectedPart(part: string): boolean { + return PROTECTED_PART_IDS.has(part); +} + +/** Document-level marker set by the host while a custom skin is active. */ +export const HOST_SKIN_ATTRIBUTE = "data-ws-host-skin"; diff --git a/web/public/host-chrome-demo.wskin b/web/public/host-chrome-demo.wskin new file mode 100644 index 0000000000000000000000000000000000000000..94ce2d7766725a26be36d1b475ca1434dab76397 GIT binary patch literal 2622 zcmb7Gc{r5&9v^Ea93E@Up|R9-CTmB?lCC|*GKkU~H6!jA%UEVcLL7vHOx7Gm*&C^3 z3AvclILO{mN=7)8vBX%9IEFj*Tvy(nd!NqxKELPpynlQ@@8|t|Ki~KBLn8S2r9dE% z5U3gL#J zmU!yzwJOWhla(&8hqK|2LYLrc!HFZ7(}l}wt!)F(*{!izGtIMan})w1NI$f~I7{eF zzp1n}{)b9_HU`Q8`{B1tWb_6q8|pZgzYUnOuewqU+^bSeXg!?6FszJtDEB^Tr6YLnUwle08{7?6lZx784LrtJ|7bfD|Wn#QVSyAm$Htpg=^Q_mS>e| zT(ge7f1$)%ws~U8o8c)rz`1e`xkscnebAkLt~iglA_;T%%U(hLex9EtBBdP1b0spr zlGn`0{b4G{i8$j(M0>cvl$@f^P)$=CvK*5XNR-rfk$HKWa&3K9zXnFhJ}}9C8yG%R zGjH?a`lg6;Yv?0>M2uHK1r!{B!GQH@h z4+v8)dY*6hpK4ST=2QpsfsA?>r=p+9IV=ctX!xQ->iDNH9pcqC}-kF25L^d?Lz{O}4lu7;(I`G{)putj^(p z{(%@`ad};;br3He4Zn_b=5RJ~H1nKwh%pOX@QYbhX zB{OTCU(U+FB5lT!x=T~kyhbK6#Azei>)X{1WWy33S{Ld>0*1&^n0o0Y}iE9#tSA1Nfd&lKyZPTUw&E2l^64xN#AI9-MAzk~2k{ zU9xsIeQa<__0~O^W~}22Lmq^T7;_R$x3UlHFqG8L6MWdIjWFevCOskN6cH1n{qQ1z zHyOP^TqU@&G8p^-j?xK-rgu0>137*k#&6~a4Ilo<9R2G?jNV$R zE5(IaKWqI%f-O1-Mc**RCQz*-GmKvuM~Q+_Hn++>Nh30y?P#AGM~tnVDU=~3Xn*c> z7Re553*gtOf?M$YkA`3I!vq8nzFj{p9mB0@_O&*8E{dIC@eTSh(%uctbOgmqd-2Cm z@8@;tQ?J7S^yWhPAv^MY)nab9i8ws=Z%`B!*&neHmKUhWva{B&DeQ7PXJX~co6g+- z3aXDVblxZusrqie@0mgODx%u`Wg(=)89UU&f*!10KW*wPM1 z*{@nm#1Kh;gP|S_vbFNrgiRmrBJ#h%gcs(unH;?^7rwnF literal 0 HcmV?d00001 diff --git a/web/public/host-chrome-preview.html b/web/public/host-chrome-preview.html new file mode 100644 index 0000000..d2b0b3f --- /dev/null +++ b/web/public/host-chrome-preview.html @@ -0,0 +1,210 @@ + + + + + +WebSpeak · Host chrome preview + + + + + +
+
+
WebSpeak
+
+ + + + +
+
+ +
+ +
+
Connected · Demo User · 17 ms
+

Server information

Address: demo.example · Channel: Lobby · Skin: host chrome demo

+

Server log

Conversation and session events appear below.

+
+ +
+ + +
WebSpeak · TeamSpeak ClientBrowser support
+
+ + +
+ +

Audio controls remain available in the toolbar and voice workspace.

+ +
+ +
+
+
+ +
+ + +
+ +

Host chrome preview

Loading skin…

+ + + + diff --git a/web/public/host-chrome-themed.wskin b/web/public/host-chrome-themed.wskin new file mode 100644 index 0000000000000000000000000000000000000000..29e1ccac38e30696d2ed3df68f7e474aed0908cd GIT binary patch literal 2585 zcmb7GdpMN&9v_U!xEwuc$TW7`vd1Y*5$k^B7K25xG0}|JnL%#vjHZN8StgTQ(lM-c zYo@krvXK^RN@83>ZVeerj7zRzP&l(a$C0<^oTq)C=lA@c_mA)A{ro=P&-eZOT(J_+ z-4F;w3i1RW(nl3zfSKv}Rq+k3vGFssnMc=@kRJ0Q#ot5pg z&%)~IC4>UyO{)a(I)iq!P5&omJ4`{YrP9 z)(g1hw30S-i+ikE@R|Mn)2`dJ$wjMtC>LqsF49Iuw4WwLgq{ibs0=mLoFRTt_VUco zc`06`OKF$kerW}#di7zO@*UE3ui<~NAnjgD0)g-XjIPkKY#(?MTAwGz2(D^bpijVt zEuEg3<+M2vJ0)a=^>srpR!@A>!9_)vb}{_i7MQ&6Aq?AWuJR#AZ;V^mNXAhD)Ig(x zYTy0Kxy(+=RPDUnRGDe_i=HY?MHyu!GTDN5x6AiKKPn@wf}O9{nwDK{v}V6i`ts#v z$H#h861&C|W;mwNl_$lvA5WX@bFf@o)NEC@?S%#2B{i3I|N-XVqEE(RVNT zqmSeSN-1{Hu$Y5vcEXW=TsG7U>*z|L6qQt5clT~KPVMHq;E%Wz4*!6B_D})-h@B4$ z_c4kwLh5npNr;g*Hun^?Qki5$bsI;+AC4<(#X1ero7t&4q=Dg#oizi8S2oJr7-q#{ zHBC5!s*&QwCx!ZltC1XL-c{aICjF6zz=YdynW-hTzWyxm4j-Mq;XTO{ENbh;?2+X zIAtC8FP4KlPY|4mNl5kw^c#!C^o2tz#pxyrIGj`|apu^acq3$f3p6liET?Q0wRb!- z+2Yrxs%+$BU*+8czfY@GN1iN?$-Ylr`Swl%t3Bucqb)ZroOULUey=CWcj%?;FK)9PIihercL+ zB*Z@GT-EuBW}I~`N{Ix8jl)%20OE@XHo1T{;0rpqiQ-XvsF* z4ajzHH=tjypAmUFOth3mivR!t6hM!BIy3~(3nqjRsRUwxZdeF$Qg#*)jHC_u;qilu z3t@2aj$NwF9GE6Lqi-GJKKi3BLk&@pCaFu?m=#(K<6Cp*h377kVl(3C4Dq0EA;QF? z*BZZyz$ug%XltRG8y1pBLz=u=>SpIA%RTH(nSAjS{48Y=@DgOSK|vf5Nned`azubR zejLUx=7+w}zud=ve>K5ac-@QXNvWK4{Cko!J_5&CwI(L99Ah)Ax~<~m;5ernB>~g{ zMQ#H==%G8o*~J>&CI$QUJIgGp3)~sRkGr2d8~h&)KjTLT3j@AfKYc^9_3@eLdQJ{* zCduv#^lM9d!<%S~NJNmJ39O&kA)ESpD`E_NOl}q4)IRzBS`0 zPl@d&6cgVK`QJAH5zSAYZTA6J?DkS{KyKBcM3MPPT!IV1(X&yE(gJHmPw*?a=34+<2LNEk)G`1l2io$f;&t`K_zz|^jZb3W-LwssxFbvpXTQI&m bKum!D`pp$9Df-5rsV@bQ5ZwSi#y{lW8nhM2 literal 0 HcmV?d00001 diff --git a/web/scripts/build-host-chrome-demo-skin.mjs b/web/scripts/build-host-chrome-demo-skin.mjs new file mode 100644 index 0000000..f9c1135 --- /dev/null +++ b/web/scripts/build-host-chrome-demo-skin.mjs @@ -0,0 +1,104 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { deflateSync } from "node:zlib"; +import { zipSync, strToU8 } from "fflate"; + +const source = new URL("../../docs/examples/host-chrome-demo/", import.meta.url); +const examples = new URL("../../docs/examples/", import.meta.url); +const publicDir = new URL("../public/", import.meta.url); + +const crcTable = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n += 1) { + let c = n; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(bytes) { + let c = 0xffffffff; + for (const byte of bytes) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function chunk(type, data) { + const out = Buffer.alloc(data.length + 12); + out.writeUInt32BE(data.length, 0); + out.write(type, 4, "ascii"); + data.copy(out, 8); + out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length); + return out; +} + +/** Build a tiny 24x24 RGBA PNG without any native image dependency. */ +function iconPng(base, accent) { + const size = 24; + const stride = size * 4 + 1; + const raw = Buffer.alloc(stride * size); + for (let y = 0; y < size; y += 1) { + raw[y * stride] = 0; + for (let x = 0; x < size; x += 1) { + const border = x < 2 || y < 2 || x > size - 3 || y > size - 3; + const glyph = (x > 6 && x < 18 && y > 6 && y < 10) || (x > 10 && x < 14 && y > 6 && y < 18); + const color = border ? accent : glyph ? [255, 255, 255] : base; + const offset = y * stride + 1 + x * 4; + raw[offset] = color[0]; raw[offset + 1] = color[1]; raw[offset + 2] = color[2]; raw[offset + 3] = 255; + } + } + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; + return Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", ihdr), + chunk("IDAT", deflateSync(raw, { level: 9 })), + chunk("IEND", Buffer.alloc(0)), + ]); +} + +const icons = { + "assets/icons/language.png": iconPng([29, 79, 156], [16, 46, 96]), + "assets/icons/skin.png": iconPng([22, 130, 106], [12, 76, 62]), + "assets/icons/apps.png": iconPng([208, 108, 32], [128, 62, 12]), + "assets/icons/settings.png": iconPng([92, 92, 118], [48, 48, 68]), + "assets/icons/status.png": iconPng([150, 60, 90], [84, 28, 52]), +}; + +const [manifestText, cssText, chromeText] = await Promise.all([ + readFile(new URL("manifest.json", source), "utf8"), + readFile(new URL("skin.css", source)), + readFile(new URL("chrome.json", source), "utf8"), +]); + +const chrome = JSON.parse(chromeText); +const sharedFiles = { + "skin.css": new Uint8Array(cssText), + ...Object.fromEntries(Object.entries(icons).map(([path, bytes]) => [path, new Uint8Array(bytes)])), +}; + +// Variant A: theming + bitmap icons only (watermark / hints / launcher visible). +const themedManifest = JSON.stringify({ ...JSON.parse(manifestText), id: "community.host-chrome-themed", name: "Host Chrome Themed" }); +const themedChrome = JSON.stringify({ schemaVersion: 1, visibleParts: chrome.visibleParts, icons: chrome.icons }); +const themed = zipSync({ + "manifest.json": strToU8(themedManifest), + "chrome.json": strToU8(themedChrome), + ...sharedFiles, +}, { level: 9 }); + +// Variant B: the same package plus declarative hiding of non-critical chrome. +const hidden = zipSync({ + "manifest.json": strToU8(manifestText), + "chrome.json": strToU8(chromeText), + ...sharedFiles, +}, { level: 9 }); + +await Promise.all([ + writeFile(new URL("host-chrome-themed.wskin", examples), themed), + writeFile(new URL("host-chrome-demo.wskin", examples), hidden), + writeFile(new URL("host-chrome-themed.wskin", publicDir), themed), + writeFile(new URL("host-chrome-demo.wskin", publicDir), hidden), +]); + +console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} bytes) into docs/examples and web/public.`); diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue new file mode 100644 index 0000000..8c8ed79 --- /dev/null +++ b/web/src/components/HostChrome.vue @@ -0,0 +1,251 @@ + + + + + diff --git a/web/src/components/InstanceAuthorization.vue b/web/src/components/InstanceAuthorization.vue index 52bcd33..f0c83c9 100644 --- a/web/src/components/InstanceAuthorization.vue +++ b/web/src/components/InstanceAuthorization.vue @@ -1,5 +1,9 @@