mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-11-30 18:42:49 +08:00
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.
This commit is contained in:
1 parent
33ba062686
commit
f8d61d22ef
45 files changed
+3535
-558
No files matched your search
+122
-9
@@ -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/<plugin-id>/index.js # v4 插件代码,目前只校验和缓存
|
||||
plugins/<plugin-id>/index.wasm # v4 有界 Wasm 插件入口
|
||||
@@ -130,6 +132,7 @@ plugins/<plugin-id>/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"`,授权对话框是 `<dialog>` + `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` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
|
||||
Binary file not shown.
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Binary file not shown.
+2
-1
@@ -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",
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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<SkinCatalogEntry, "installedAt" | "previewUrl" |
|
||||
content?: string;
|
||||
components?: string;
|
||||
plugins?: string;
|
||||
chrome?: string;
|
||||
workspace?: SkinWorkspacePolicy;
|
||||
preview?: string;
|
||||
};
|
||||
@@ -248,7 +255,7 @@ export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manif
|
||||
}
|
||||
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
|
||||
const runtimePluginPathSet = new Set(runtimePluginPaths.map((packagePath) => packagePath.toLowerCase()));
|
||||
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
|
||||
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 {
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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<string> = 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<string, string>;
|
||||
}
|
||||
|
||||
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<string, unknown> {
|
||||
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<string, string> = Object.create(null) as Record<string, string>;
|
||||
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<string> {
|
||||
const hidden = new Set<string>(instanceHiddenParts.filter((part) => DECORATIVE_PART_IDS.has(part)));
|
||||
const visible = new Set<string>(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" : "";
|
||||
}
|
||||
@@ -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<string>();
|
||||
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"));
|
||||
});
|
||||
+290
-24
@@ -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<Record<string, unknown>> | Map<string, unknown> | Set<string>;
|
||||
@@ -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<string>();
|
||||
@@ -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") {
|
||||
|
||||
@@ -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<string[]> {
|
||||
const files = (await readdir(directory, { recursive: true })).filter((file) => file.endsWith(".vue"));
|
||||
@@ -16,16 +20,20 @@ async function vueSources(directory: URL): Promise<string[]> {
|
||||
}
|
||||
|
||||
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<string>();
|
||||
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");
|
||||
|
||||
+26
-33
@@ -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<string>([
|
||||
"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<string>([
|
||||
"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<string, string> = {
|
||||
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 {
|
||||
|
||||
@@ -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<string> = 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<string> = new Set([
|
||||
"host.recovery",
|
||||
"host.permission",
|
||||
]);
|
||||
|
||||
/** All host-owned parts (used by the part registry and documentation). */
|
||||
export const HOST_PART_IDS: ReadonlySet<string> = 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<string> = 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<string> = 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<string> = 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<string> = 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";
|
||||
Binary file not shown.
@@ -0,0 +1,210 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-ws-route="webclient" data-ws-page="voice">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>WebSpeak · Host chrome preview</title>
|
||||
<link rel="stylesheet" href="/src/styles/plugin-overlay.css" />
|
||||
<style id="skin-style"></style>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; font: 12px/1.5 Tahoma, "Segoe UI", sans-serif; color: #1b2825; background: #eef2f1; }
|
||||
.ws-skin-root { min-height: 100dvh; display: flex; flex-direction: column; }
|
||||
.ws-header { height: 44px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 12px; border-bottom: 1px solid #d5dedc; background: #f7faf9; }
|
||||
.ws-brand { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 14px; color: #006a64; }
|
||||
.ws-brand i { width: 22px; height: 22px; border-radius: 5px; background: linear-gradient(135deg,#006a64,#32cdb7); }
|
||||
.ws-toolbar { display: flex; align-items: center; gap: 6px; margin-left: auto; }
|
||||
.ws-trigger, .ws-icon-button { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 4px 9px; border: 1px solid #cfd9d7; border-radius: 5px; background: #fff; color: #35514d; cursor: pointer; font: inherit; }
|
||||
.ws-icon-button { width: 30px; padding: 4px; justify-content: center; }
|
||||
.ws-icon-slot { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; }
|
||||
.ws-icon-slot svg { display: block; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; }
|
||||
.ws-columns { flex: 1; display: grid; grid-template-columns: 230px 1fr 280px; min-height: 0; }
|
||||
.ws-tree, .ws-info { border-right: 1px solid #d5dedc; background: #fff; padding: 10px; }
|
||||
.ws-info { border-right: 0; border-left: 1px solid #d5dedc; }
|
||||
.ws-main { padding: 14px; overflow: auto; }
|
||||
.ws-card { padding: 12px; margin-bottom: 10px; border: 1px solid #dde5e3; border-radius: 6px; background: #fff; }
|
||||
.ws-card h3 { margin: 0 0 6px; font-size: 12px; text-transform: uppercase; letter-spacing: .1em; color: #6e8a86; }
|
||||
.ws-status { display: flex; align-items: center; gap: 8px; padding: 8px 10px; margin-bottom: 10px; border: 1px solid #bfd8d3; border-radius: 5px; background: #f0faf7; color: #225b53; }
|
||||
.ws-dock { flex: none; display: flex; align-items: center; gap: 12px; min-height: 60px; padding: 8px 14px; border-top: 1px solid #d5dedc; background: #f7faf9; }
|
||||
.ws-dock strong { display: block; font-size: 12px; }
|
||||
.ws-dock small { color: #6b8480; }
|
||||
.ws-dock-actions { margin-left: auto; display: flex; gap: 8px; }
|
||||
.ws-footer { flex: none; padding: 6px 14px; border-top: 1px solid #d5dedc; background: #f2f6f5; color: #6b8480; font-size: 11px; }
|
||||
.ws-footer span { margin-right: 6px; }
|
||||
/* Teleported host chrome */
|
||||
.ws-host-chrome { position: fixed; inset: 0; z-index: 1; overflow: hidden; pointer-events: none; }
|
||||
.ws-host-watermark { position: absolute; top: 64px; right: 56px; color: #8ab9cf; font: 800 clamp(40px,7vw,104px)/1 ui-sans-serif,system-ui,sans-serif; letter-spacing: -.06em; opacity: .14; }
|
||||
.ws-host-hint { position: absolute; bottom: 10px; left: 14px; margin: 0; max-width: 50vw; color: #6d8b88; font-size: 11px; opacity: .8; }
|
||||
.ws-host-voice-status-decoration { position: absolute; top: 0; right: 0; display: flex; align-items: center; gap: 8px; width: 280px; height: 28px; padding: 0 12px; opacity: .28; }
|
||||
.ws-host-voice-status-decoration span { display: block; height: 6px; border-radius: 3px; background: #95b6b1; }
|
||||
.ws-host-voice-status-decoration span:first-child { width: 64px; }
|
||||
.ws-host-voice-status-decoration span:last-child { flex: 1; opacity: .6; }
|
||||
.ws-host-recovery { position: fixed; inset: auto auto 38px 12px; margin: 0; align-items: center; gap: 6px; padding: 4px 6px 4px 10px; border: 1px solid #9db6b2; border-radius: 999px; background: #fff; color: #31524f; font: inherit; pointer-events: auto; }
|
||||
.ws-host-recovery:popover-open { display: flex; }
|
||||
.ws-host-recovery button { display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 5px 10px; border: 1px solid #9db6b2; border-radius: 999px; background: #fff; color: #31524f; font: inherit; cursor: pointer; }
|
||||
.ws-host-recovery button:hover, .ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; }
|
||||
.ws-host-recovery-layer { position: fixed; inset: 0; z-index: 2147483647; overflow: visible; pointer-events: none; }
|
||||
.ws-plugin-overlay { font-family: inherit; }
|
||||
/* Preview-only legend */
|
||||
.ws-legend { position: fixed; z-index: 12000; top: 56px; left: 12px; width: 320px; padding: 10px 12px; border: 1px solid #b9cfcb; border-radius: 8px; background: #fffffff2; box-shadow: 0 8px 24px #0f2a2633; font-size: 11px; }
|
||||
.ws-legend h2 { margin: 0 0 6px; font-size: 12px; color: #006a64; }
|
||||
.ws-legend p { margin: 0 0 4px; }
|
||||
.ws-legend code { background: #eef4f2; padding: 0 3px; border-radius: 3px; }
|
||||
.ws-legend .ws-ok { color: #0a7a2f; font-weight: 700; }
|
||||
.ws-legend .ws-hidden { color: #a33; font-weight: 700; }
|
||||
.ws-entry-marker { outline: 3px solid #d2600a !important; outline-offset: 3px !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ws-skin-root" data-ws-page="voice" data-ws-part="app">
|
||||
<header class="ws-header" data-ws-part="voice.header">
|
||||
<div class="ws-brand" data-ws-part="home.brand"><i></i><span>WebSpeak</span></div>
|
||||
<div class="ws-toolbar" data-ws-part="voice.header-actions">
|
||||
<button type="button" class="ws-trigger" data-ws-part="language.trigger"><span class="ws-icon-slot" data-ws-icon-slot="language.trigger"><svg viewBox="0 0 24 24"><path d="M4 5h9M8 5v2c0 5-2 8-4 10M6 10c1 3 4 5 7 6M13 19l4-10 4 10M14.5 16h5"/></svg></span><span>EN</span></button>
|
||||
<button type="button" class="ws-trigger" data-ws-part="skin.trigger"><span class="ws-icon-slot" data-ws-icon-slot="skin.trigger"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="m15.5 8.5-2.2 4.8-4.8 2.2 2.2-4.8z"/></svg></span><span>Skin</span></button>
|
||||
<button type="button" class="ws-icon-button" title="Settings" data-ws-part="home.toolbar.settings"><span class="ws-icon-slot" data-ws-icon-slot="home.toolbar.settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M12 2v3m0 14v3M2 12h3m14 0h3M5 5l2 2m10 10 2 2M19 5l-2 2M7 17l-2 2"/></svg></span></button>
|
||||
<button type="button" class="ws-icon-button" title="Voice status" data-ws-part="voice.performance"><span class="ws-icon-slot" data-ws-icon-slot="voice.performance"><svg viewBox="0 0 24 24"><path d="M3 12h4l2-7 4 14 2-7h6"/></svg></span></button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="ws-columns">
|
||||
<aside class="ws-tree"><strong>demo.example</strong><p>◈ Lobby</p><p> 👤 Demo User</p><p> ♫ Demo Bot</p></aside>
|
||||
<main class="ws-main">
|
||||
<div class="ws-status" data-ws-part="voice.connection-status" role="status">Connected · Demo User · 17 ms</div>
|
||||
<div class="ws-card"><h3>Server information</h3><p>Address: demo.example · Channel: Lobby · Skin: host chrome demo</p></div>
|
||||
<div class="ws-card"><h3>Server log</h3><p>Conversation and session events appear below.</p></div>
|
||||
</main>
|
||||
<aside class="ws-info"><strong>Voice status</strong><p>Connection transport: WebSockets</p><p>Ping: 17 ms</p></aside>
|
||||
</div>
|
||||
|
||||
<div class="ws-dock" data-ws-part="voice.audio-dock" role="toolbar" aria-label="Audio controls">
|
||||
<div><strong>Audio controls</strong><small>Microphone and output remain available</small></div>
|
||||
<div class="ws-dock-actions">
|
||||
<button type="button" class="ws-trigger" data-ws-part="voice.audio-dock.microphone">🎤 Microphone</button>
|
||||
<button type="button" class="ws-trigger" data-ws-part="voice.audio-dock.output">🔊 Output</button>
|
||||
<button type="button" class="ws-trigger" data-ws-part="voice.connection-status.reconnect">Reconnect</button>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="ws-footer" data-ws-part="home.footer"><span data-ws-part="home.footer.decoration">WebSpeak · TeamSpeak Client</span><button type="button" data-ws-part="home.footer.clear">Clear local data</button><span data-ws-part="home.footer.decoration">Browser support</span></footer>
|
||||
</div>
|
||||
|
||||
<!-- Teleported host chrome, outside .ws-skin-root -->
|
||||
<div class="ws-host-chrome" data-ws-host-chrome>
|
||||
<div class="ws-host-watermark" data-ws-part="host.watermark" aria-hidden="true">WebSpeak</div>
|
||||
<p class="ws-host-hint" data-ws-part="host.hint">Audio controls remain available in the toolbar and voice workspace.</p>
|
||||
<div class="ws-host-voice-status-decoration" data-ws-part="host.voice-status-decoration" aria-hidden="true"><span></span><span></span></div>
|
||||
</div>
|
||||
<!-- Recovery is displayed only when the launcher is hidden/unreachable, mirroring
|
||||
the client's closed-shadow top-layer entry rather than a watermark sibling.
|
||||
The node deliberately has no data-ws-part: there is no skin hook for it. -->
|
||||
<div class="ws-host-recovery-layer" data-ws-host-recovery-layer>
|
||||
<div class="ws-host-recovery" id="recovery-popover" popover="manual"><span aria-hidden="true">◈</span><button type="button" id="recovery-entry">Use built-in skin (recovery)</button></div>
|
||||
</div>
|
||||
|
||||
<div class="ws-plugin-overlay" data-plugin-theme="light">
|
||||
<button type="button" id="plugin-launcher" class="ws-plugin-launcher" data-ws-part="host.plugins.launcher">
|
||||
<svg viewBox="0 0 24 24" data-ws-icon-slot="host.plugins.launcher" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z"/></svg>
|
||||
<span>Plugins</span>
|
||||
</button>
|
||||
<section id="plugin-window" class="ws-plugin-window" data-ws-part="host.plugins.overlay" role="dialog" aria-label="Application library" style="display:none;left:50%;top:16%;transform:translateX(-50%);width:min(720px,80vw);height:min(420px,60vh)">
|
||||
<header class="ws-plugin-titlebar"><span class="ws-plugin-mark" aria-hidden="true">◈</span><div class="ws-plugin-window-title"><strong>Application library</strong><small>WebSpeak</small></div></header>
|
||||
<nav class="ws-plugin-navigation"><button type="button" class="active">Application library</button></nav>
|
||||
<div class="ws-plugin-library"><div class="ws-plugin-library-heading"><div><h2>Application library</h2><span>1 available</span></div></div>
|
||||
<div class="ws-plugin-grid"><article class="ws-plugin-entry"><div class="ws-plugin-app-mark">D</div><div class="ws-plugin-entry-copy"><h3>Demo application</h3><small>v1.0.0 · instance</small><p>Local demo entry used to verify the recovery path.</p></div><button type="button">Open ↗</button></article></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="ws-legend" id="legend"><h2>Host chrome preview</h2><p id="status">Loading skin…</p></div>
|
||||
|
||||
<script type="module">
|
||||
const params = new URLSearchParams(location.search);
|
||||
const skinUrl = params.get("skin") || "/host-chrome-themed.wskin";
|
||||
const state = params.get("state") || "themed";
|
||||
const legend = document.getElementById("legend");
|
||||
const status = document.getElementById("status");
|
||||
const launcher = document.getElementById("plugin-launcher");
|
||||
const libraryWindow = document.getElementById("plugin-window");
|
||||
const recovery = document.getElementById("recovery-entry");
|
||||
const recoveryPopover = document.getElementById("recovery-popover");
|
||||
const recoveryLayer = document.querySelector("[data-ws-host-recovery-layer]");
|
||||
const decorations = ["host.watermark", "host.hint", "host.voice-status-decoration"];
|
||||
|
||||
function setLibraryOpen(open) {
|
||||
libraryWindow.style.display = open ? "flex" : "none";
|
||||
}
|
||||
launcher.addEventListener("click", () => setLibraryOpen(libraryWindow.style.display === "none"));
|
||||
recovery.addEventListener("click", () => { setLibraryOpen(true); recovery.classList.add("ws-entry-marker"); });
|
||||
|
||||
try {
|
||||
const { resolveHiddenHostParts, isHostPartReachable } = await import("/src/services/host-chrome-preview.ts");
|
||||
let chromeData;
|
||||
if (skinUrl !== "none") {
|
||||
const { importSkinPack, resolveSkinCssAssets } = await import("/src/services/skin-pack.ts");
|
||||
const response = await fetch(skinUrl);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const blob = await response.blob();
|
||||
const name = skinUrl.split("/").pop() || "skin.wskin";
|
||||
const skin = await importSkinPack(new File([blob], name, { type: "application/octet-stream" }));
|
||||
const resolved = resolveSkinCssAssets(skin.css, skin.assets);
|
||||
document.getElementById("skin-style").textContent = resolved.css;
|
||||
document.documentElement.setAttribute("data-ws-host-skin", skin.id);
|
||||
document.querySelector(".ws-skin-root").setAttribute("data-ws-skin", skin.id);
|
||||
chromeData = skin.chromeData;
|
||||
status.innerHTML = `Active skin: <code>${skin.id}</code> v${skin.version}<br>hiddenParts: <code>${JSON.stringify(skin.chromeData?.hiddenParts ?? [])}</code><br>visibleParts: <code>${JSON.stringify(skin.chromeData?.visibleParts ?? [])}</code><br>icon overrides: <code>${Object.keys(skin.chromeData?.icons ?? {}).length}</code>`;
|
||||
} else {
|
||||
status.textContent = "Baseline: no skin active.";
|
||||
}
|
||||
|
||||
// Decorations follow the client's opt-in rule: only visibleParts keeps them
|
||||
// in the DOM. hiddenParts-only and icon-only chrome.json stay clean, and
|
||||
// skin=none behaves like a built-in skin.
|
||||
const hiddenParts = resolveHiddenHostParts(chromeData, []);
|
||||
const decorationVisible = Object.fromEntries(decorations.map((part) => {
|
||||
const element = document.querySelector(`[data-ws-part="${part}"]`);
|
||||
const visible = Boolean(element) && !hiddenParts.has(part);
|
||||
if (!visible) element?.remove();
|
||||
return [part, visible];
|
||||
}));
|
||||
|
||||
// Recovery follows the same reachability rule as the client, with
|
||||
// ?state=recovery kept as an explicit demo override.
|
||||
const launcherStyle = getComputedStyle(launcher);
|
||||
const rect = launcher.getBoundingClientRect();
|
||||
const launcherReachable = isHostPartReachable({
|
||||
display: launcherStyle.display,
|
||||
visibility: launcherStyle.visibility,
|
||||
opacity: launcherStyle.opacity,
|
||||
pointerEvents: launcherStyle.pointerEvents,
|
||||
clipPath: launcherStyle.clipPath,
|
||||
clip: launcherStyle.clip,
|
||||
rect: { width: rect.width, height: rect.height, left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom },
|
||||
viewport: { width: window.innerWidth, height: window.innerHeight },
|
||||
});
|
||||
if (state !== "recovery" && launcherReachable) recoveryLayer.remove();
|
||||
else recoveryPopover.showPopover?.();
|
||||
|
||||
const line = document.createElement("p");
|
||||
line.innerHTML = `<span class="${decorationVisible["host.watermark"] ? "ws-ok" : "ws-hidden"}">watermark ${decorationVisible["host.watermark"] ? "visible" : "hidden"}</span> · <span class="${decorationVisible["host.hint"] ? "ws-ok" : "ws-hidden"}">hint ${decorationVisible["host.hint"] ? "visible" : "hidden"}</span> · <span class="${launcherReachable ? "ws-ok" : "ws-hidden"}">launcher ${launcherReachable ? "themed" : "hidden"}</span>`;
|
||||
legend.append(line);
|
||||
const note = document.createElement("p");
|
||||
note.innerHTML = '<span class="ws-ok">✓</span> authorization / recovery / audio dock still present';
|
||||
legend.append(note);
|
||||
|
||||
if (state === "recovery") {
|
||||
setLibraryOpen(true);
|
||||
recovery.classList.add("ws-entry-marker");
|
||||
}
|
||||
if (state === "icons") {
|
||||
document.querySelectorAll('[data-ws-icon-slot]').forEach((slot) => slot.closest("button")?.classList.add("ws-entry-marker"));
|
||||
}
|
||||
window.__previewReady = true;
|
||||
} catch (error) {
|
||||
status.textContent = `Error: ${error instanceof Error ? error.message : String(error)}`;
|
||||
status.className = "ws-hidden";
|
||||
window.__previewError = String(error);
|
||||
window.__previewReady = true;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
@@ -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.`);
|
||||
@@ -0,0 +1,251 @@
|
||||
<template>
|
||||
<!-- Host chrome is intentionally outside .ws-skin-root so a v3 surface
|
||||
replacement cannot delete the recovery path or the authorization UI. -->
|
||||
<Teleport to="body">
|
||||
<div class="ws-host-chrome" data-ws-host-chrome>
|
||||
<div
|
||||
v-if="!isHostPartHidden('host.watermark')"
|
||||
class="ws-host-watermark"
|
||||
data-ws-part="host.watermark"
|
||||
aria-hidden="true"
|
||||
>WebSpeak</div>
|
||||
|
||||
<p
|
||||
v-if="!isHostPartHidden('host.hint')"
|
||||
class="ws-host-hint"
|
||||
data-ws-part="host.hint"
|
||||
>{{ copy.hint }}</p>
|
||||
|
||||
<div
|
||||
v-if="!isHostPartHidden('host.voice-status-decoration')"
|
||||
class="ws-host-voice-status-decoration"
|
||||
data-ws-part="host.voice-status-decoration"
|
||||
aria-hidden="true"
|
||||
><span></span><span></span></div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- Trusted recovery entry. It lives in a closed shadow root and a manual
|
||||
popover, so no compiled skin selector can target it (shadow boundary)
|
||||
and no normal stacking context can cover it (top layer). It carries no
|
||||
`data-ws-part`: there is intentionally no skin hook for this control. -->
|
||||
<Teleport v-if="layer" :to="layer.container">
|
||||
<div
|
||||
ref="recoveryPopover"
|
||||
popover="manual"
|
||||
class="ws-host-recovery"
|
||||
data-ws-host-recovery
|
||||
role="region"
|
||||
:aria-label="copy.recovery"
|
||||
>
|
||||
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
|
||||
<button
|
||||
type="button"
|
||||
data-ws-recovery-action="built-in"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>{{ copy.useBuiltIn }}</button>
|
||||
<button
|
||||
type="button"
|
||||
data-ws-recovery-action="library"
|
||||
:title="copy.library"
|
||||
@click="openLibrary"
|
||||
>{{ copy.library }}</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
import { hostChromeCopy } from "../i18n/host-chrome.js";
|
||||
import {
|
||||
isHostPartHidden,
|
||||
isHostPartVisuallyReachable,
|
||||
isRecoveryShortcut,
|
||||
isThirdPartySkinActive,
|
||||
openPluginLibrary,
|
||||
requestBuiltInSkin,
|
||||
} from "../services/host-chrome.js";
|
||||
import {
|
||||
createHostOwnedLayer,
|
||||
syncRecoveryPopover,
|
||||
type HostOwnedLayer,
|
||||
} from "../services/host-owned-layer.js";
|
||||
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
|
||||
import { thirdPartyAllowed } from "../services/instance-authorization.js";
|
||||
|
||||
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean }>(), { connected: false });
|
||||
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
|
||||
|
||||
// Styles live inside the closed shadow root: the component's scoped stylesheet
|
||||
// in <head> cannot cross the shadow boundary.
|
||||
const RECOVERY_LAYER_CSS = `
|
||||
:host { font: 11px/1.2 ui-sans-serif, system-ui, sans-serif; }
|
||||
.ws-host-recovery {
|
||||
position: fixed;
|
||||
inset: auto auto calc(38px + env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
|
||||
margin: 0;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
max-width: calc(100vw - 24px);
|
||||
padding: 4px 5px 4px 9px;
|
||||
border: 1px solid #9db6b2;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, #ffffff 92%, transparent);
|
||||
color: #31524f;
|
||||
box-shadow: 0 6px 18px #0f2a2626;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.ws-host-recovery:popover-open { display: flex; }
|
||||
.ws-host-recovery-mark { font-size: 12px; line-height: 1; }
|
||||
.ws-host-recovery button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
padding: 4px 9px;
|
||||
border: 1px solid #9db6b2;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #31524f;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
|
||||
border-color: #b45309;
|
||||
background: #fff7ed;
|
||||
color: #7c2d12;
|
||||
}
|
||||
.ws-host-recovery button:hover { filter: brightness(.96); }
|
||||
.ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) { .ws-host-recovery button { transition: none; } }
|
||||
`;
|
||||
|
||||
const layer: HostOwnedLayer | null = createHostOwnedLayer("recovery", RECOVERY_LAYER_CSS);
|
||||
|
||||
// CSS-only hiding is invisible to `isHostPartHidden`, so sample the launcher's
|
||||
// live geometry. A one-second interval is enough for a recovery fallback and
|
||||
// stays cheaper than a MutationObserver on the whole document. While a
|
||||
// third-party skin is active the entry is persistent and this sample only
|
||||
// matters for the official-skin fallback.
|
||||
const launcherReachable = ref(true);
|
||||
const showRecovery = computed(() => shouldShowRecovery({
|
||||
connected: props.connected,
|
||||
thirdPartyAllowed: thirdPartyAllowed.value,
|
||||
thirdPartySkinActive: isThirdPartySkinActive(),
|
||||
launcherHiddenByConfig: isHostPartHidden("host.plugins.launcher"),
|
||||
launcherReachable: launcherReachable.value,
|
||||
}));
|
||||
|
||||
// The documented shortcut can summon the same host-owned entry even while a
|
||||
// bundled skin is active (for example after a broken third-party skin was
|
||||
// already reset). It never renders decoration on its own.
|
||||
const shortcutOpen = ref(false);
|
||||
const recoveryPopover = ref<HTMLElement | null>(null);
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
|
||||
function syncPopover() {
|
||||
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
|
||||
}
|
||||
|
||||
function useBuiltInSkin() {
|
||||
shortcutOpen.value = false;
|
||||
requestBuiltInSkin();
|
||||
}
|
||||
|
||||
function openLibrary() {
|
||||
shortcutOpen.value = false;
|
||||
openPluginLibrary();
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.defaultPrevented || event.repeat || !thirdPartyAllowed.value) return;
|
||||
if (isRecoveryShortcut(event)) {
|
||||
event.preventDefault();
|
||||
shortcutOpen.value = true;
|
||||
void nextTick(() => recoveryPopover.value?.querySelector("button")?.focus());
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape" && shortcutOpen.value) shortcutOpen.value = false;
|
||||
}
|
||||
|
||||
let reachabilityTimer: ReturnType<typeof setInterval> | undefined;
|
||||
function refreshLauncherReachability() {
|
||||
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
|
||||
}
|
||||
|
||||
watch([recoveryVisible, recoveryPopover], () => { void nextTick(syncPopover); }, { flush: "post" });
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
|
||||
|
||||
onMounted(() => {
|
||||
refreshLauncherReachability();
|
||||
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
|
||||
window.addEventListener("resize", refreshLauncherReachability);
|
||||
window.addEventListener("keydown", onKeydown);
|
||||
void nextTick(syncPopover);
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
if (reachabilityTimer) clearInterval(reachabilityTimer);
|
||||
window.removeEventListener("resize", refreshLauncherReachability);
|
||||
window.removeEventListener("keydown", onKeydown);
|
||||
layer?.dispose();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.ws-host-chrome {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
.ws-host-watermark {
|
||||
position: absolute;
|
||||
top: clamp(8px, 6vh, 64px);
|
||||
right: clamp(12px, 3vw, 64px);
|
||||
color: #8ab9cf;
|
||||
font: 800 clamp(40px, 7vw, 104px)/1 ui-sans-serif, system-ui, sans-serif;
|
||||
letter-spacing: -.06em;
|
||||
opacity: .14;
|
||||
user-select: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ws-host-hint {
|
||||
position: absolute;
|
||||
bottom: calc(10px + env(safe-area-inset-bottom));
|
||||
left: 14px;
|
||||
max-width: min(46vw, 420px);
|
||||
margin: 0;
|
||||
color: #6d8b88;
|
||||
font: 11px/1.4 ui-sans-serif, system-ui, sans-serif;
|
||||
opacity: .8;
|
||||
user-select: none;
|
||||
}
|
||||
.ws-host-voice-status-decoration {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: min(28vw, 320px);
|
||||
height: 28px;
|
||||
padding: 0 12px;
|
||||
opacity: .28;
|
||||
}
|
||||
.ws-host-voice-status-decoration span {
|
||||
display: block;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: #95b6b1;
|
||||
}
|
||||
.ws-host-voice-status-decoration span:first-child { width: 64px; }
|
||||
.ws-host-voice-status-decoration span:last-child { flex: 1; opacity: .6; }
|
||||
@media (max-width: 640px) {
|
||||
.ws-host-hint { max-width: 62vw; }
|
||||
.ws-host-voice-status-decoration { display: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,5 +1,9 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<!-- The authorization dialog is host-owned trusted UI: it is rendered in a
|
||||
closed shadow root and promoted with showModal(), so compiled skin CSS
|
||||
cannot select, restyle, cover or disable it. It deliberately carries no
|
||||
`data-ws-part`; there is no skin hook for this dialog. -->
|
||||
<Teleport v-if="layer" :to="layer.container">
|
||||
<dialog ref="dialog" class="ws-instance-authorization" @cancel.prevent="cancel" @close="authorizationRequested = false">
|
||||
<form @submit.prevent="save">
|
||||
<div class="ws-authorization-mark" aria-hidden="true">◈</div>
|
||||
@@ -20,6 +24,18 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
import { createHostOwnedLayer, type HostOwnedLayer } from '../services/host-owned-layer.js';
|
||||
|
||||
const AUTHORIZATION_LAYER_CSS = `
|
||||
:host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:inherit;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
|
||||
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
|
||||
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
|
||||
`;
|
||||
|
||||
const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHORIZATION_LAYER_CSS);
|
||||
const props = defineProps<{ language: SiteLanguage }>();
|
||||
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
|
||||
const copy = computed(() => instanceAuthorizationCopy[props.language]);
|
||||
@@ -34,12 +50,5 @@ function finish() { authorizationRequested.value = false; dialog.value?.close();
|
||||
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
|
||||
function decline() { setInstanceAuthorization(false); finish(); }
|
||||
function cancel() { if (firstVisit.value) decline(); else finish(); }
|
||||
onBeforeUnmount(() => dialog.value?.close());
|
||||
onBeforeUnmount(() => { dialog.value?.close(); layer?.dispose(); });
|
||||
</script>
|
||||
<style>
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:14px/1.75 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto}
|
||||
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
|
||||
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
|
||||
</style>
|
||||
@@ -11,7 +11,7 @@
|
||||
:aria-controls="menuId"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<Icon class="language-current-icon" name="translate" :size="24" />
|
||||
<Icon class="language-current-icon" name="translate" :size="24" data-ws-icon-slot="language.trigger" />
|
||||
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
|
||||
<span class="language-current-code">{{ currentLanguage.code }}</span>
|
||||
<Icon name="chevron-down" :size="13" />
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
|
||||
<button ref="launcher" class="ws-plugin-launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="ws-plugin-launcher" data-ws-part="host.plugins.launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" data-ws-icon-slot="host.plugins.launcher" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<span>{{ tr('title') }}</span><i v-if="current" />
|
||||
</button>
|
||||
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
|
||||
<section v-show="visible" ref="windowElement" class="ws-plugin-window" data-ws-part="host.plugins.overlay" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
|
||||
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
|
||||
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
|
||||
<div class="ws-plugin-window-title"><strong>{{ current && appView ? current.manifest.name : tr('title') }}</strong><small>WebSpeak</small></div>
|
||||
@@ -50,6 +50,7 @@ import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
|
||||
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { isHostPartHidden, pluginLibraryRequests } from '../services/host-chrome.js';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage }>();
|
||||
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
|
||||
const ui = computed(() => pluginWindowTranslations[props.language]);
|
||||
@@ -154,9 +155,19 @@ watch(windowElement, element => { resizeObserver?.disconnect(); if (element) { r
|
||||
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, close);
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) close(); }, { flush: 'sync' });
|
||||
watch(() => props.language, appearance); watch(theme, appearance);
|
||||
// Trusted recovery entry (host chrome / skin menu) keeps the application
|
||||
// library reachable when a skin hides the floating launcher.
|
||||
watch(pluginLibraryRequests, () => {
|
||||
if (!thirdPartyAllowed.value || !props.connected || !props.sessionToken) return;
|
||||
detectTheme();
|
||||
visible.value = true;
|
||||
appView.value = false;
|
||||
if (!current.value) void refresh();
|
||||
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
|
||||
});
|
||||
onMounted(() => {
|
||||
detectTheme(); window.addEventListener('message', message); window.addEventListener('resize', fitWindow); window.addEventListener('pointermove', moveDrag); window.addEventListener('pointerup', endDrag); window.addEventListener('pointercancel', endDrag); window.addEventListener('blur', endDrag);
|
||||
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
|
||||
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-ws-host-skin', 'data-theme'] });
|
||||
});
|
||||
onBeforeUnmount(() => { stop(); endDrag(); observer?.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('message', message); window.removeEventListener('resize', fitWindow); window.removeEventListener('pointermove', moveDrag); window.removeEventListener('pointerup', endDrag); window.removeEventListener('pointercancel', endDrag); window.removeEventListener('blur', endDrag); });
|
||||
</script>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<section v-if="error" class="skin-load-recovery" role="alert">
|
||||
<section v-if="error" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
|
||||
<p>{{ labels.skinLoadError(error.skinId) }}</p>
|
||||
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
|
||||
</section>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
:aria-controls="menuId"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<Icon :name="selectedOption.icon || 'compass'" :size="15" />
|
||||
<Icon :name="selectedOption.icon || 'compass'" :size="15" data-ws-icon-slot="skin.trigger" />
|
||||
<span>{{ menuLabel }}</span>
|
||||
<Icon name="chevron-down" :size="12" />
|
||||
</button>
|
||||
@@ -38,6 +38,9 @@
|
||||
<button type="button" class="skin-option skin-authorization" role="option" :aria-selected="false" @click="authorization">
|
||||
<Icon name="shield" :size="16" /><span>{{ authorizationCopy.menu }}</span><small>{{ thirdPartyAllowed ? authorizationCopy.enabled : authorizationCopy.disabled }}</small>
|
||||
</button>
|
||||
<button v-if="thirdPartyAllowed" type="button" class="skin-option skin-library" data-ws-part="skin.library" role="option" :aria-selected="false" @click="openLibrary">
|
||||
<Icon name="grid" :size="16" /><span>{{ libraryLabel }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -47,6 +50,8 @@ import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
import { authorizationLanguage, canUseSkin, openInstanceAuthorization, thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
import { hostChromeCopy } from '../i18n/host-chrome.js';
|
||||
import { openPluginLibrary } from '../services/host-chrome.js';
|
||||
|
||||
export interface SkinOption {
|
||||
value: string;
|
||||
@@ -67,7 +72,9 @@ const emit = defineEmits<{
|
||||
|
||||
const options = computed(() => props.options.filter(option => canUseSkin(option.value)));
|
||||
const authorizationCopy = computed(() => instanceAuthorizationCopy[authorizationLanguage.value]);
|
||||
const libraryLabel = computed(() => hostChromeCopy[authorizationLanguage.value]?.library ?? hostChromeCopy.en.library);
|
||||
function authorization() { close(); openInstanceAuthorization(); }
|
||||
function openLibrary() { close(); openPluginLibrary(); }
|
||||
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0] ?? {
|
||||
value: props.modelValue,
|
||||
label: props.menuLabel,
|
||||
@@ -101,6 +108,7 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
|
||||
}
|
||||
.skin-authorization{margin-top:6px;border-top:1px solid #8bdad8!important}
|
||||
.skin-authorization small{margin-left:auto;font-size:10px;opacity:.75}
|
||||
.skin-library{opacity:.9}
|
||||
|
||||
.skin-trigger {
|
||||
display: inline-flex;
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
@click.stop="togglePerformancePanel"
|
||||
><Icon
|
||||
name="activity"
|
||||
:size="16" /><span class="performance-trigger-label">{{ t("voiceStatus") }}</span
|
||||
:size="16"
|
||||
data-ws-icon-slot="voice.performance" /><span class="performance-trigger-label">{{ t("voiceStatus") }}</span
|
||||
><small v-if="performanceStats.ready">{{ voiceTransportLabel }}</small
|
||||
><Icon
|
||||
name="chevron-down"
|
||||
|
||||
@@ -92,6 +92,7 @@
|
||||
<Icon
|
||||
name="settings"
|
||||
:size="15"
|
||||
data-ws-icon-slot="home.toolbar.settings"
|
||||
/><span>{{ t("adminConsole") }}</span>
|
||||
</a>
|
||||
<SkinSwitcher
|
||||
|
||||
@@ -4,6 +4,7 @@ import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "
|
||||
import { BUILTIN_SKIN_CATALOG, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
|
||||
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
|
||||
import { createSkinOperation } from "../services/skin-operation.js";
|
||||
import { setSkinHostChromeParts, setHostChromeActiveSkin, hostBuiltInSkinRequests } from "../services/host-chrome.js";
|
||||
import { getStoredTheme, isDarkTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import type { InstalledSkin } from "../services/skin-pack.js";
|
||||
|
||||
@@ -36,6 +37,14 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
return current = createSkinOperation({ timeoutMs: options.timeoutMs });
|
||||
}
|
||||
onScopeDispose(() => { disposed = true; cancel(); });
|
||||
// Host decorations depend on the active skin's chrome.json opt-in. Built-in
|
||||
// skins leave `activeSkin` empty, which keeps host chrome hidden by default.
|
||||
// Only `visibleParts` opts in: chrome.json hiddenParts/icons generate host
|
||||
// CSS containing `data-ws-part="host.…"`, so inspecting the combined stylesheet
|
||||
// would wrongly treat every hiddenParts-only pack as host-chrome themed.
|
||||
watch(activeSkin, (skin) => setSkinHostChromeParts(skin?.chromeData), { immediate: true, flush: "sync" });
|
||||
// The recovery affordance is persistent while a non-bundled skin is applied.
|
||||
watch(activeSkinId, (id) => setHostChromeActiveSkin(id), { immediate: true, flush: "sync" });
|
||||
|
||||
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false, clearLoadError = true) {
|
||||
operation.check();
|
||||
@@ -133,6 +142,10 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
skinReady.value = true;
|
||||
void select(fallbackId());
|
||||
}, { flush: 'sync' });
|
||||
// Host-owned recovery's guaranteed action: reset to the built-in skin. It is
|
||||
// independent of the skinnable plugin overlay, so it also works when that
|
||||
// overlay is hidden with `display: none`.
|
||||
watch(hostBuiltInSkinRequests, () => { if (!disposed) void switchToBuiltIn(); }, { flush: 'sync' });
|
||||
return { activeSkin, activeSkinId, skinReady, skinLoadError,
|
||||
installedSkins: computed(() => installedSkins.value.filter(skin => canUseSkin(skin.id))),
|
||||
catalogSkins: computed(() => catalogSkins.value.filter(skin => canUseSkin(skin.id))),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { computed, reactive, ref, type Ref } from "vue";
|
||||
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { APP_VERSION } from "../services/app-version.js";
|
||||
import { setInstanceHiddenParts } from "../services/host-chrome.js";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
|
||||
interface RelayOption {
|
||||
@@ -58,7 +59,11 @@ export function useWebClientPublicConfig({
|
||||
visitorNumber?: unknown;
|
||||
visitorTotal?: unknown;
|
||||
accelerationRelays?: unknown;
|
||||
hiddenHostParts?: unknown;
|
||||
};
|
||||
if (Array.isArray(config.hiddenHostParts)) {
|
||||
setInstanceHiddenParts(config.hiddenHostParts.filter((part): part is string => typeof part === "string"));
|
||||
}
|
||||
if (typeof config.version === "string" && config.version.trim()) appVersion.value = config.version.trim();
|
||||
visitorNumber.value = Number.isSafeInteger(config.visitorNumber) && Number(config.visitorNumber) > 0 ? Number(config.visitorNumber) : null;
|
||||
visitorTotal.value = Number.isSafeInteger(config.visitorTotal) && Number(config.visitorTotal) > 0 ? Number(config.visitorTotal) : null;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
|
||||
/** All five public languages implement the same host chrome labels. */
|
||||
const en = {
|
||||
hint: "Audio controls remain available in the toolbar and voice workspace.",
|
||||
library: "Application library",
|
||||
recovery: "Restore application library",
|
||||
useBuiltIn: "Use built-in skin",
|
||||
shortcut: "Restore the built-in skin (Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS)",
|
||||
};
|
||||
export const hostChromeCopy: Record<SiteLanguage, typeof en> = {
|
||||
en,
|
||||
zh: {
|
||||
hint: "音频控制始终保留在工具栏和语音工作区中。",
|
||||
library: "应用库",
|
||||
recovery: "恢复应用库",
|
||||
useBuiltIn: "使用内置皮肤",
|
||||
shortcut: "恢复内置皮肤(Ctrl+Alt+Shift+R,macOS 为 ⌘+⌥+⇧+R)",
|
||||
},
|
||||
de: {
|
||||
hint: "Audiosteuerung bleibt in der Werkzeugleiste und im Sprachbereich verfügbar.",
|
||||
library: "Anwendungsbibliothek",
|
||||
recovery: "Anwendungsbibliothek wiederherstellen",
|
||||
useBuiltIn: "Integrierten Skin verwenden",
|
||||
shortcut: "Integrierten Skin wiederherstellen (Strg+Alt+Umschalt+R, unter macOS ⌘+⌥+⇧+R)",
|
||||
},
|
||||
ru: {
|
||||
hint: "Управление звуком остаётся доступным на панели инструментов и в голосовой области.",
|
||||
library: "Библиотека приложений",
|
||||
recovery: "Восстановить библиотеку приложений",
|
||||
useBuiltIn: "Использовать встроенную тему",
|
||||
shortcut: "Восстановить встроенную тему (Ctrl+Alt+Shift+R, в macOS ⌘+⌥+⇧+R)",
|
||||
},
|
||||
ja: {
|
||||
hint: "音声コントロールはツールバーと音声ワークスペースで常に利用できます。",
|
||||
library: "アプリライブラリ",
|
||||
recovery: "アプリライブラリを復元",
|
||||
useBuiltIn: "組み込みスキンを使用",
|
||||
shortcut: "組み込みスキンを復元(Ctrl+Alt+Shift+R、macOS は ⌘+⌥+⇧+R)",
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Browser-facing re-exports for the static host chrome preview page.
|
||||
*
|
||||
* Vite serves modules below `web/`, while the host-chrome policy lives in the
|
||||
* repository-level `src/shared` tree. Keeping the bridge here lets the preview
|
||||
* use exactly the same opt-in and reachability rules as the Vue client.
|
||||
*/
|
||||
export {
|
||||
DEFAULT_HIDDEN_HOST_PARTS,
|
||||
resolveHiddenHostParts,
|
||||
} from "../../../src/shared/skin-chrome.js";
|
||||
export type { SkinChromeDocument } from "../../../src/shared/skin-chrome.js";
|
||||
export { isHostPartReachable, shouldShowRecovery } from "./host-chrome-visibility.js";
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isBundledSkin } from "./host-chrome.js";
|
||||
import { isHostPartReachable, shouldShowRecovery, type HostPartVisibilitySnapshot } from "./host-chrome-visibility.js";
|
||||
|
||||
const snapshot = (overrides: Partial<HostPartVisibilitySnapshot> = {}): HostPartVisibilitySnapshot => ({
|
||||
display: "inline-flex",
|
||||
visibility: "visible",
|
||||
opacity: "1",
|
||||
pointerEvents: "auto",
|
||||
rect: { width: 120, height: 40, left: 600, top: 700, right: 720, bottom: 740 },
|
||||
viewport: { width: 1280, height: 800 },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test("a rendered, on-screen host part is reachable", () => {
|
||||
assert.equal(isHostPartReachable(snapshot()), true);
|
||||
// Partially off-screen is still usable.
|
||||
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: -40, top: 700, right: 80, bottom: 740 } })), true);
|
||||
});
|
||||
|
||||
test("CSS-only hiding makes a host part unreachable", () => {
|
||||
for (const hidden of [
|
||||
snapshot({ display: "none" }),
|
||||
snapshot({ visibility: "hidden" }),
|
||||
snapshot({ visibility: "collapse" }),
|
||||
snapshot({ opacity: "0" }),
|
||||
snapshot({ pointerEvents: "none" }),
|
||||
snapshot({ clipPath: "inset(50%)" }),
|
||||
snapshot({ clipPath: "circle(0px)" }),
|
||||
snapshot({ clip: "rect(0px, 0px, 0px, 0px)" }),
|
||||
snapshot({ rect: { width: 0, height: 0, left: 0, top: 0, right: 0, bottom: 0 } }),
|
||||
]) {
|
||||
assert.equal(isHostPartReachable(hidden), false);
|
||||
}
|
||||
// Decorative clipping that leaves a usable area does not trigger recovery.
|
||||
assert.equal(isHostPartReachable(snapshot({ clipPath: "inset(2px)" })), true);
|
||||
assert.equal(isHostPartReachable(snapshot({ clipPath: "none" })), true);
|
||||
});
|
||||
|
||||
test("a host part moved entirely outside the viewport is unreachable", () => {
|
||||
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: -9999, top: 700, right: -9879, bottom: 740 } })), false);
|
||||
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: 600, top: 900, right: 720, bottom: 940 } })), false);
|
||||
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: 1400, top: 700, right: 1520, bottom: 740 } })), false);
|
||||
});
|
||||
|
||||
test("bundled and third-party skins are classified for the recovery affordance", () => {
|
||||
// Official Day/Night and the bundled ILLUSIA/KAAK packs stay quiet.
|
||||
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
|
||||
assert.equal(isBundledSkin(id), true, String(id));
|
||||
}
|
||||
for (const id of ["community.hostile-fixture", "community.some-open-skin", "builtin.future"]) {
|
||||
// `builtin.*` is reserved for future host packs; everything else is third-party.
|
||||
assert.equal(isBundledSkin(id), id.startsWith("builtin."), id);
|
||||
}
|
||||
});
|
||||
|
||||
test("the recovery entry is persistent for third-party skins only", () => {
|
||||
const base = {
|
||||
connected: true,
|
||||
thirdPartyAllowed: true,
|
||||
thirdPartySkinActive: false,
|
||||
launcherHiddenByConfig: false,
|
||||
launcherReachable: true,
|
||||
};
|
||||
assert.equal(shouldShowRecovery(base), false);
|
||||
// A non-bundled skin keeps a small host-owned affordance visible even when
|
||||
// the launcher is reachable: if the skin hides/covers it, recovery is there.
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartySkinActive: true }), true);
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartySkinActive: true, connected: false }), true);
|
||||
// Bundled/official skins never gain the affordance while the launcher works.
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartySkinActive: false, launcherReachable: false, connected: false }), false);
|
||||
// Declarative hiding (chrome.json / instance setting) on a bundled skin.
|
||||
assert.equal(shouldShowRecovery({ ...base, launcherHiddenByConfig: true }), true);
|
||||
// CSS-only hiding discovered at runtime.
|
||||
assert.equal(shouldShowRecovery({ ...base, launcherReachable: false }), true);
|
||||
// Never show a recovery entry without authorization.
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, thirdPartySkinActive: true }), false);
|
||||
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Pure visibility decisions used by the host chrome recovery entry.
|
||||
*
|
||||
* The actual DOM reads live in `host-chrome.ts`; keeping the predicates here
|
||||
* makes them testable without a browser and keeps the preview page and the Vue
|
||||
* client on the same rules.
|
||||
*/
|
||||
|
||||
export interface HostPartRect {
|
||||
width: number;
|
||||
height: number;
|
||||
left: number;
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
export interface HostPartVisibilitySnapshot {
|
||||
display: string;
|
||||
visibility: string;
|
||||
opacity: string;
|
||||
pointerEvents: string;
|
||||
/** Optional: computed `clip-path`; strong clipping makes a control unusable. */
|
||||
clipPath?: string;
|
||||
/** Optional: legacy computed `clip` (for example `rect(0 0 0 0)`). */
|
||||
clip?: string;
|
||||
rect: HostPartRect;
|
||||
viewport: { width: number; height: number };
|
||||
}
|
||||
|
||||
function isClippedAway(clipPath: string, clip: string): boolean {
|
||||
const path = clipPath.toLowerCase();
|
||||
// `inset(50%)` collapses both axes; a three-digit/100 percentage does too.
|
||||
if (/inset\(\s*(?:[5-9]\d|100)%/.test(path)) return true;
|
||||
// Large pixel insets are the unit-based variant of the same escape.
|
||||
if (/inset\(\s*\d{3,}px/.test(path)) return true;
|
||||
if (/(?:circle|ellipse)\(\s*0(?:px)?\s*[,)]/.test(path)) return true;
|
||||
const legacy = clip.toLowerCase();
|
||||
return /rect\(\s*0(?:px)?[\s,]+0(?:px)?[\s,]+0(?:px)?[\s,]+0(?:px)?\s*\)/.test(legacy);
|
||||
}
|
||||
|
||||
/**
|
||||
* A host part is reachable when it is rendered, visible, interactive and at
|
||||
* least partially inside the viewport. CSS-only hiding (display, visibility,
|
||||
* opacity, pointer-events, clipping, off-screen margins/transforms) therefore
|
||||
* counts as unavailable even when no chrome.json declared the part hidden.
|
||||
*/
|
||||
export function isHostPartReachable(snapshot: HostPartVisibilitySnapshot): boolean {
|
||||
if (snapshot.display === "none") return false;
|
||||
if (snapshot.visibility === "hidden" || snapshot.visibility === "collapse") return false;
|
||||
const opacity = Number.parseFloat(snapshot.opacity);
|
||||
if (Number.isFinite(opacity) && opacity <= 0.01) return false;
|
||||
if (snapshot.pointerEvents === "none") return false;
|
||||
if (isClippedAway(snapshot.clipPath ?? "none", snapshot.clip ?? "auto")) return false;
|
||||
const { rect, viewport } = snapshot;
|
||||
if (!(rect.width > 0) || !(rect.height > 0)) return false;
|
||||
if (rect.right <= 0 || rect.bottom <= 0) return false;
|
||||
if (rect.left >= viewport.width || rect.top >= viewport.height) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface RecoveryVisibilityInput {
|
||||
connected: boolean;
|
||||
thirdPartyAllowed: boolean;
|
||||
/** A non-bundled skin is applied, so the recovery affordance is persistent. */
|
||||
thirdPartySkinActive: boolean;
|
||||
/** The part is hidden declaratively (chrome.json hiddenParts / instance setting). */
|
||||
launcherHiddenByConfig: boolean;
|
||||
/** The launcher element is currently rendered and reachable in the DOM. */
|
||||
launcherReachable: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The recovery entry is a small, persistent host-owned affordance while a
|
||||
* third-party skin is active, so a hostile skin can never remove the only way
|
||||
* back. Official/built-in skins (Day, Night, ILLUSIA, KAAK) never grow it
|
||||
* automatically: for them it remains a fallback that only appears when the
|
||||
* normal launcher is declared or observed unavailable while connected.
|
||||
*/
|
||||
export function shouldShowRecovery(input: RecoveryVisibilityInput): boolean {
|
||||
if (!input.thirdPartyAllowed) return false;
|
||||
if (input.thirdPartySkinActive) return true;
|
||||
return input.connected && (input.launcherHiddenByConfig || !input.launcherReachable);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { computed, readonly, ref, shallowRef } from "vue";
|
||||
import { DECORATIVE_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
|
||||
import { resolveHiddenHostParts, type SkinChromeDocument } from "../../../src/shared/skin-chrome.js";
|
||||
import { isHostPartReachable } from "./host-chrome-visibility.js";
|
||||
|
||||
/**
|
||||
* Host-owned state shared by Teleported host chrome components. Skin CSS can
|
||||
* never mutate this state: it is only written by the host from a validated
|
||||
* instance setting or a validated chrome.json document.
|
||||
*/
|
||||
|
||||
const instanceHiddenParts = ref<ReadonlySet<string>>(new Set());
|
||||
const skinChrome = shallowRef<SkinChromeDocument | undefined>(undefined);
|
||||
const activeSkin = ref<string | undefined>(undefined);
|
||||
|
||||
/**
|
||||
* Skins bundled with WebSpeak. They are never treated as "third-party" for the
|
||||
* recovery affordance, so official Day/Night/ILLUSIA/KAAK stay decoration-free
|
||||
* and gain no extra host chrome.
|
||||
*/
|
||||
const BUNDLED_SKIN_IDS: ReadonlySet<string> = new Set([
|
||||
"builtin.light",
|
||||
"builtin.dark",
|
||||
"community.illusia-voice",
|
||||
"community.kaak-voice",
|
||||
]);
|
||||
|
||||
/** The id of the skin currently applied by `usePublicSkin`. */
|
||||
export function setHostChromeActiveSkin(id: string | undefined): void {
|
||||
activeSkin.value = id;
|
||||
}
|
||||
|
||||
export function isBundledSkin(id: string | undefined): boolean {
|
||||
return !id || id.startsWith("builtin.") || BUNDLED_SKIN_IDS.has(id);
|
||||
}
|
||||
|
||||
/** True while a non-bundled (open / third-party) skin is applied. */
|
||||
export function isThirdPartySkinActive(): boolean {
|
||||
return !isBundledSkin(activeSkin.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorations (`host.watermark`, `host.hint`, `host.voice-status-decoration`)
|
||||
* are hidden unless the active skin opts in with `chrome.json#visibleParts`,
|
||||
* so official and built-in skins stay identical to production.
|
||||
*/
|
||||
const hiddenParts = computed(() => resolveHiddenHostParts(skinChrome.value, [...instanceHiddenParts.value]));
|
||||
|
||||
/** Instance-level default, supplied by /api/public-config. */
|
||||
export function setInstanceHiddenParts(parts: readonly string[]): void {
|
||||
instanceHiddenParts.value = new Set(parts.filter((part) => DECORATIVE_PART_IDS.has(part)));
|
||||
}
|
||||
|
||||
/** The active skin's validated chrome.json (or undefined for built-in skins). */
|
||||
export function setSkinHostChromeParts(document: SkinChromeDocument | undefined): void {
|
||||
skinChrome.value = document;
|
||||
}
|
||||
|
||||
export function isHostPartHidden(part: string): boolean {
|
||||
return hiddenParts.value.has(part);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the live DOM to find out whether a host part can actually be used.
|
||||
* Declarative hiding (`v-if`) removes the element entirely; CSS-only hiding
|
||||
* leaves it in place, so this also checks computed style and on-screen bounds.
|
||||
*/
|
||||
export function isHostPartVisuallyReachable(part: string): boolean {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") return true;
|
||||
const element = document.querySelector(`[data-ws-part="${part}"]`);
|
||||
if (!element) return false;
|
||||
const style = window.getComputedStyle(element);
|
||||
const rect = element.getBoundingClientRect();
|
||||
return isHostPartReachable({
|
||||
display: style.display,
|
||||
visibility: style.visibility,
|
||||
opacity: style.opacity,
|
||||
pointerEvents: style.pointerEvents,
|
||||
clipPath: style.clipPath,
|
||||
clip: style.clip,
|
||||
rect: { width: rect.width, height: rect.height, left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom },
|
||||
viewport: { width: window.innerWidth, height: window.innerHeight },
|
||||
});
|
||||
}
|
||||
|
||||
/** A monotonically increasing request counter; PluginPanel watches it. */
|
||||
const libraryRequests = ref(0);
|
||||
export const pluginLibraryRequests = readonly(libraryRequests);
|
||||
|
||||
export function openPluginLibrary(): void {
|
||||
libraryRequests.value += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recovery's guaranteed escape hatch: reset to the built-in Day/Night skin.
|
||||
* `usePublicSkin` watches this counter, so it works even when the skinnable
|
||||
* plugin overlay is `display: none`.
|
||||
*/
|
||||
const builtInSkinRequests = ref(0);
|
||||
export const hostBuiltInSkinRequests = readonly(builtInSkinRequests);
|
||||
|
||||
export function requestBuiltInSkin(): void {
|
||||
builtInSkinRequests.value += 1;
|
||||
}
|
||||
|
||||
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key">;
|
||||
|
||||
/**
|
||||
* The documented recovery shortcut: Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS.
|
||||
* The letter is matched case-insensitively, but every modifier is required so
|
||||
* ordinary app shortcuts (Ctrl+R, Alt+R, Ctrl+Shift+R) keep their meaning.
|
||||
*/
|
||||
export function isRecoveryShortcut(event: RecoveryShortcutEvent): boolean {
|
||||
return (event.ctrlKey || event.metaKey)
|
||||
&& event.altKey
|
||||
&& event.shiftKey
|
||||
&& event.key.toLowerCase() === "r";
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Closed-shadow, top-layer rendering layer for trusted host UI.
|
||||
*
|
||||
* Skin CSS is compiled to two scopes: `.ws-skin-root[data-ws-skin="…"] …` and
|
||||
* `:root[data-ws-host-skin="…"] [data-ws-part="host.…"] …`. Content rendered in
|
||||
* this layer satisfies neither:
|
||||
*
|
||||
* - it lives inside a closed shadow root, so no author selector can reach its
|
||||
* internals (open or closed, author CSS never crosses a shadow boundary);
|
||||
* - its host element carries no `data-ws-part`, so it never matches the
|
||||
* document-level host-chrome scope either;
|
||||
* - whichever of its children is promoted to the top layer (`<dialog>`
|
||||
* `showModal()` / a `popover="manual"` element) paints above every normal
|
||||
* stacking context, including `z-index: 2147483647`.
|
||||
*
|
||||
* The host element is also a fixed, pointer-transparent wrapper so a browser
|
||||
* without the Popover API still shows the UI above ordinary content.
|
||||
*/
|
||||
|
||||
export type HostOwnedLayerName = "recovery" | "authorization";
|
||||
|
||||
/**
|
||||
* The CSS 32-bit maximum stacking value. A compiled skin may legitimately use
|
||||
* `z-index: 2147483647` on a fullscreen part, so the pre-Popover fallback must
|
||||
* not sit below it. At equal maximum stacking the host layer still paints on
|
||||
* top: it is appended to `document.body` after `#app`, and later siblings win
|
||||
* when the stacking level ties. The top-layer paths (`showPopover()` /
|
||||
* `showModal()`) still outrank both.
|
||||
*/
|
||||
export const HOST_OWNED_LAYER_Z_INDEX = 2147483647;
|
||||
|
||||
export interface HostOwnedLayer {
|
||||
readonly name: HostOwnedLayerName;
|
||||
readonly host: HTMLElement;
|
||||
/** Closed shadow root; only the host that created the layer holds this. */
|
||||
readonly shadow: ShadowRoot;
|
||||
/** Teleport target for the layer's Vue subtree. */
|
||||
readonly container: HTMLElement;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const layers = new Set<HostOwnedLayer>();
|
||||
|
||||
/** Diagnostics / tests: enumerate live host-owned layers in this realm. */
|
||||
export function hostOwnedLayers(): readonly HostOwnedLayer[] {
|
||||
return [...layers];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a detached-from-skin-DOM host with a closed shadow root and inject the
|
||||
* layer's stylesheet inside it. Returns `null` in a non-DOM environment.
|
||||
*/
|
||||
export function createHostOwnedLayer(name: HostOwnedLayerName, css: string): HostOwnedLayer | null {
|
||||
if (typeof document === "undefined" || !document.body) return null;
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.setAttribute("data-ws-host-layer", name);
|
||||
// The wrapper itself must never intercept clicks meant for the page; the
|
||||
// promoted child re-enables pointer events for its own controls.
|
||||
host.style.cssText = `position:fixed;inset:0;z-index:${HOST_OWNED_LAYER_Z_INDEX};pointer-events:none;overflow:visible;`;
|
||||
|
||||
const shadow = host.attachShadow({ mode: "closed" });
|
||||
const style = document.createElement("style");
|
||||
style.textContent = css;
|
||||
const container = document.createElement("div");
|
||||
container.setAttribute("data-ws-host-layer-content", name);
|
||||
shadow.append(style, container);
|
||||
document.body.append(host);
|
||||
|
||||
const layer: HostOwnedLayer = {
|
||||
name,
|
||||
host,
|
||||
shadow,
|
||||
container,
|
||||
dispose() {
|
||||
layers.delete(layer);
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
layers.add(layer);
|
||||
return layer;
|
||||
}
|
||||
|
||||
type PopoverCapableElement = HTMLElement & {
|
||||
showPopover?: () => void;
|
||||
hidePopover?: () => void;
|
||||
matches?: (selector: string) => boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Elements that already used the display fallback must never flap back to the
|
||||
* Popover API: re-entering it could re-apply the UA `[popover] { display: none
|
||||
* !important }` rule and hide the capsule again.
|
||||
*/
|
||||
const popoverFallbacks = new WeakSet<HTMLElement>();
|
||||
|
||||
/**
|
||||
* Show or hide a manual recovery popover, with a display-based fallback.
|
||||
*
|
||||
* A closed `[popover]` is `display: none !important` in the UA stylesheet and
|
||||
* has no `:popover-open` box, so simply setting `style.display` leaves it
|
||||
* invisible. The fallback therefore removes the `popover` attribute before
|
||||
* assigning `display`. The same path is used when the Popover API is missing
|
||||
* or when top-layer promotion throws (for example in a constrained embed).
|
||||
*/
|
||||
export function syncRecoveryPopover(element: HTMLElement | null | undefined, visible: boolean): void {
|
||||
if (!element) return;
|
||||
|
||||
const enterFallback = (): void => {
|
||||
popoverFallbacks.add(element);
|
||||
element.removeAttribute("popover");
|
||||
element.style.display = visible ? "flex" : "none";
|
||||
};
|
||||
|
||||
if (popoverFallbacks.has(element)) {
|
||||
element.style.display = visible ? "flex" : "none";
|
||||
return;
|
||||
}
|
||||
|
||||
const candidate = element as PopoverCapableElement;
|
||||
if (typeof candidate.showPopover !== "function") {
|
||||
// Pre-Popover browsers: the fixed host layer is the only fallback.
|
||||
enterFallback();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const open = candidate.matches?.(":popover-open") ?? false;
|
||||
if (visible && !open) candidate.showPopover();
|
||||
else if (!visible && open) candidate.hidePopover?.();
|
||||
} catch {
|
||||
// Constrained embeds may reject top-layer promotion. The fixed host layer
|
||||
// is still there, but only the display fallback can actually reveal it.
|
||||
enterFallback();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isRecoveryShortcut } from "./host-chrome.js";
|
||||
import { HOST_OWNED_LAYER_Z_INDEX, syncRecoveryPopover } from "./host-owned-layer.js";
|
||||
|
||||
type ShortcutEvent = {
|
||||
ctrlKey: boolean;
|
||||
metaKey: boolean;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
key: string;
|
||||
};
|
||||
|
||||
const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
key: "",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test("the recovery shortcut requires the full Ctrl/Cmd+Alt+Shift+R chord", () => {
|
||||
assert.equal(isRecoveryShortcut(shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "r" })), true);
|
||||
// macOS uses the Meta/Command key in place of Ctrl.
|
||||
assert.equal(isRecoveryShortcut(shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "R" })), true);
|
||||
|
||||
for (const rejected of [
|
||||
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "x" }),
|
||||
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "Enter" }),
|
||||
// Ordinary app/browser shortcuts must stay available.
|
||||
shortcut({ ctrlKey: true, key: "r" }),
|
||||
shortcut({ altKey: true, key: "r" }),
|
||||
shortcut({ ctrlKey: true, shiftKey: true, key: "r" }),
|
||||
shortcut({ ctrlKey: true, altKey: true, key: "r" }),
|
||||
shortcut({ ctrlKey: false, altKey: true, shiftKey: true, key: "r" }),
|
||||
]) {
|
||||
assert.equal(isRecoveryShortcut(rejected), false, JSON.stringify(rejected));
|
||||
}
|
||||
});
|
||||
|
||||
interface FakePopover {
|
||||
style: { display: string };
|
||||
showPopover?: () => void;
|
||||
hidePopover?: () => void;
|
||||
matches?: (selector: string) => boolean;
|
||||
removedAttributes: string[];
|
||||
removeAttribute(name: string): void;
|
||||
}
|
||||
|
||||
const fakePopover = (overrides: Partial<FakePopover> = {}): FakePopover => {
|
||||
const element: FakePopover = {
|
||||
style: { display: "" },
|
||||
removedAttributes: [],
|
||||
removeAttribute(name: string) {
|
||||
element.removedAttributes.push(name);
|
||||
},
|
||||
matches: () => false,
|
||||
...overrides,
|
||||
};
|
||||
return element;
|
||||
};
|
||||
|
||||
const asElement = (element: FakePopover) => element as unknown as HTMLElement;
|
||||
|
||||
test("a missing showPopover uses the display fallback, visible and hidden", () => {
|
||||
const element = fakePopover();
|
||||
syncRecoveryPopover(asElement(element), true);
|
||||
assert.equal(element.style.display, "flex", "the capsule must be laid out without the Popover API");
|
||||
syncRecoveryPopover(asElement(element), false);
|
||||
assert.equal(element.style.display, "none");
|
||||
syncRecoveryPopover(asElement(element), true);
|
||||
assert.equal(element.style.display, "flex");
|
||||
});
|
||||
|
||||
test("a throwing showPopover drops the popover attribute and shows the capsule", () => {
|
||||
let calls = 0;
|
||||
const element = fakePopover({
|
||||
showPopover() {
|
||||
calls += 1;
|
||||
throw new Error("top-layer promotion rejected");
|
||||
},
|
||||
});
|
||||
|
||||
syncRecoveryPopover(asElement(element), true);
|
||||
assert.deepEqual(element.removedAttributes, ["popover"], "the UA display:none rule must be removed");
|
||||
assert.equal(element.style.display, "flex");
|
||||
assert.notEqual(element.style.display, "none");
|
||||
assert.equal(calls, 1);
|
||||
|
||||
// Once fallback is in use the element must not flap back to showPopover().
|
||||
syncRecoveryPopover(asElement(element), false);
|
||||
assert.equal(element.style.display, "none");
|
||||
syncRecoveryPopover(asElement(element), true);
|
||||
assert.equal(element.style.display, "flex");
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test("a working showPopover/hidePopover keeps the top-layer path", () => {
|
||||
let open = false;
|
||||
let shown = 0;
|
||||
let hidden = 0;
|
||||
const element = fakePopover({
|
||||
showPopover() {
|
||||
shown += 1;
|
||||
open = true;
|
||||
},
|
||||
hidePopover() {
|
||||
hidden += 1;
|
||||
open = false;
|
||||
},
|
||||
matches: (selector) => selector === ":popover-open" && open,
|
||||
});
|
||||
|
||||
syncRecoveryPopover(asElement(element), true);
|
||||
assert.equal(shown, 1);
|
||||
assert.equal(element.style.display, "", "the top-layer path must not force display");
|
||||
syncRecoveryPopover(asElement(element), true);
|
||||
assert.equal(shown, 1, "an already-open popover is not reopened");
|
||||
|
||||
syncRecoveryPopover(asElement(element), false);
|
||||
assert.equal(hidden, 1);
|
||||
assert.deepEqual(element.removedAttributes, [], "a working popover keeps its attribute");
|
||||
});
|
||||
|
||||
test("the pre-Popover host layer uses the CSS 32-bit maximum z-index", () => {
|
||||
assert.equal(HOST_OWNED_LAYER_Z_INDEX, 2147483647);
|
||||
});
|
||||
+511
-437
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,14 @@
|
||||
import { parseSkinWorkspacePolicy, type SkinWorkspacePolicy } from "../../../src/shared/skin-workspace.js";
|
||||
import { unzipSync } from "fflate";
|
||||
import { compileSkinCss as compileSharedSkinCss, rewriteSkinCssAssets, SkinCssValidationError } from "../../../src/shared/skin-css.js";
|
||||
import {
|
||||
compileSkinChromeCss,
|
||||
parseSkinChromeDocument,
|
||||
SKIN_CHROME_MAX_BYTES,
|
||||
SkinChromeError,
|
||||
validateSkinChromeAssets,
|
||||
type SkinChromeDocument,
|
||||
} from "../../../src/shared/skin-chrome.js";
|
||||
|
||||
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
|
||||
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
@@ -39,6 +47,7 @@ export interface SkinManifest {
|
||||
content?: string;
|
||||
components?: string;
|
||||
plugins?: string;
|
||||
chrome?: string;
|
||||
workspace?: SkinWorkspacePolicy;
|
||||
minAppVersion: string;
|
||||
preview?: string;
|
||||
@@ -75,6 +84,7 @@ export interface InstalledSkin extends SkinManifest {
|
||||
runtimePluginFiles?: Record<string, Blob>;
|
||||
runtimePluginStyles?: Record<string, string>;
|
||||
previewBlob?: Blob;
|
||||
chromeData?: SkinChromeDocument;
|
||||
warnings: string[];
|
||||
installedAt: number;
|
||||
}
|
||||
@@ -145,7 +155,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
|
||||
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
|
||||
const runtimePluginPathSet = new Set(runtimePluginPaths.map((path) => path.toLowerCase()));
|
||||
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
|
||||
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome, manifest.preview]
|
||||
.filter((path): path is string => Boolean(path)).map((path) => path.toLowerCase());
|
||||
if (runtimePluginPaths.some((path) => manifestPathSet.includes(path))) {
|
||||
throw new SkinPackError("Plugin files cannot reuse skin manifest, CSS, content, component, or preview paths.", "SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE");
|
||||
@@ -184,7 +194,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
}
|
||||
|
||||
for (const [path, bytes] of files) {
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins].includes(path)
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome].includes(path)
|
||||
|| runtimePluginPathSet.has(path.toLowerCase())) continue;
|
||||
const mimeType = assetMimeType(path);
|
||||
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
|
||||
@@ -233,6 +243,26 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
catch (error) { throw new SkinPackError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); }
|
||||
}
|
||||
|
||||
let chromeData: SkinChromeDocument | undefined;
|
||||
if (manifest.chrome) {
|
||||
const chromeBytes = files.get(manifest.chrome);
|
||||
if (!chromeBytes || chromeBytes.byteLength > SKIN_CHROME_MAX_BYTES) {
|
||||
throw new SkinPackError("chrome.json is missing or exceeds 32 KiB.", "SKIN_CHROME_SIZE");
|
||||
}
|
||||
try {
|
||||
chromeData = parseSkinChromeDocument(decoder.decode(chromeBytes));
|
||||
validateSkinChromeAssets(chromeData, (path) => {
|
||||
const asset = assets[path];
|
||||
return asset ? { bytes: asset.size, mime: asset.type } : undefined;
|
||||
});
|
||||
} catch (error) {
|
||||
const chromeError = error instanceof SkinChromeError
|
||||
? error
|
||||
: new SkinChromeError(error instanceof Error ? error.message : "Invalid chrome.json.", "SKIN_CHROME_INVALID");
|
||||
throw new SkinPackError(chromeError.message, chromeError.code);
|
||||
}
|
||||
}
|
||||
|
||||
let previewBlob: Blob | undefined;
|
||||
if (manifest.preview) {
|
||||
const previewBytes = files.get(manifest.preview);
|
||||
@@ -248,9 +278,12 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
&& runtimePlugins?.plugins.some((plugin) => plugin.mode === "surface" && plugin.page === component.page));
|
||||
if (hasConflictingSurface) throw new SkinPackError("A page cannot declare both a v3 and v4 surface.", "SKIN_PLUGIN_SURFACE_DUPLICATE");
|
||||
|
||||
// Host-owned additions are appended after author CSS so they win ties, and
|
||||
// use wskin-asset markers resolved by resolveSkinCssAssets at activation.
|
||||
const chromeCss = chromeData ? compileSkinChromeCss(chromeData, manifest.id) : "";
|
||||
return {
|
||||
...manifest,
|
||||
css: compiled.css,
|
||||
css: chromeCss ? `${compiled.css}\n${chromeCss}` : compiled.css,
|
||||
assets,
|
||||
contentData,
|
||||
layoutData,
|
||||
@@ -259,6 +292,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
runtimePluginFiles,
|
||||
runtimePluginStyles,
|
||||
previewBlob,
|
||||
...(chromeData ? { chromeData } : {}),
|
||||
warnings: [...compiled.warnings, ...runtimePluginWarnings],
|
||||
installedAt: Date.now(),
|
||||
};
|
||||
@@ -407,7 +441,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion >= 2) {
|
||||
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
|
||||
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); 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(raw).find((key) => !fields.has(key));
|
||||
if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
|
||||
@@ -427,8 +461,8 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
if (schemaVersion === 4 && raw.packageType !== "open-skin") {
|
||||
throw new SkinPackError("Version 4 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
|
||||
}
|
||||
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined || raw.components !== undefined || raw.plugins !== undefined)) {
|
||||
throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined || raw.components !== undefined || raw.plugins !== undefined || raw.chrome !== undefined)) {
|
||||
throw new SkinPackError("Version 1 skin packages cannot declare layout, chrome or plugin fields.", "SKIN_SCHEMA_VERSION");
|
||||
}
|
||||
let workspace: SkinWorkspacePolicy | undefined;
|
||||
try { workspace = parseSkinWorkspacePolicy(raw.workspace, schemaVersion); }
|
||||
@@ -439,17 +473,18 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
const layout = schemaVersion >= 2 ? stringField("layout", 120, schemaVersion === 2)! : undefined;
|
||||
const components = schemaVersion >= 3 ? stringField("components", 120, false) : undefined;
|
||||
const plugins = schemaVersion === 4 ? stringField("plugins", 120)! : undefined;
|
||||
const chrome = schemaVersion >= 3 ? stringField("chrome", 120, false) : undefined;
|
||||
const content = stringField("content", 120, false);
|
||||
const preview = stringField("preview", 120, false);
|
||||
for (const path of [entry, layout, content, components, plugins, preview].filter((item): item is string => Boolean(item))) {
|
||||
for (const path of [entry, layout, content, components, plugins, chrome, preview].filter((item): item is string => Boolean(item))) {
|
||||
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
|
||||
}
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
const version = stringField("version", 32)!;
|
||||
const minAppVersion = stringField("minAppVersion", 32)!;
|
||||
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (!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 && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("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 SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
return {
|
||||
schemaVersion,
|
||||
@@ -465,6 +500,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
content,
|
||||
components,
|
||||
plugins,
|
||||
chrome,
|
||||
minAppVersion,
|
||||
...(workspace ? { workspace } : {}),
|
||||
preview,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js
|
||||
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
|
||||
import { setSkinLayoutPackage } from "./skin-layout-runtime.js";
|
||||
import { canUseSkin } from './instance-authorization.js';
|
||||
import { HOST_SKIN_ATTRIBUTE } from '../../../src/shared/skin-visual-parts.js';
|
||||
|
||||
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
|
||||
export const BUILTIN_LIGHT_SKIN = "builtin.light";
|
||||
@@ -112,6 +113,10 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
|
||||
clientRoot.dataset.wsSkin = skin!.id;
|
||||
});
|
||||
// Host chrome lives outside `.ws-skin-root` (Teleport to body). A
|
||||
// document-level marker lets compiled host rules reach it, but only while
|
||||
// this exact skin is active; removing the skin removes the marker.
|
||||
document.documentElement.setAttribute(HOST_SKIN_ATTRIBUTE, skin!.id);
|
||||
markCoreControls();
|
||||
|
||||
let style = document.getElementById(CUSTOM_STYLE_ID) as HTMLStyleElement | null;
|
||||
@@ -155,6 +160,7 @@ export function clearCustomSkinStyle(): void {
|
||||
function removeCustomSkinStyle(): void {
|
||||
document.getElementById(CUSTOM_STYLE_ID)?.remove();
|
||||
document.getElementById(CUSTOM_BASE_STYLE_ID)?.remove();
|
||||
document.documentElement.removeAttribute(HOST_SKIN_ATTRIBUTE);
|
||||
activeAssetUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
activeAssetUrls = [];
|
||||
}
|
||||
|
||||
@@ -59,12 +59,14 @@
|
||||
</div>
|
||||
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
|
||||
<InstanceAuthorization :language="language" />
|
||||
<HostChrome :language="language" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
|
||||
import HostChrome from '../components/HostChrome.vue';
|
||||
import "../styles/skin-plugin.css";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
|
||||
@@ -259,15 +259,16 @@
|
||||
data-ws-part="home.footer"
|
||||
>
|
||||
<div class="ws-skin-mount-slot" data-ws-skin-mount="home.footer.before"></div>
|
||||
<span>WebSpeak</span><span class="footer-separator">·</span
|
||||
><span>{{ t("teamSpeakClient") }}</span
|
||||
<span data-ws-part="home.footer.decoration">WebSpeak</span><span class="footer-separator" data-ws-part="home.footer.decoration">·</span
|
||||
><span data-ws-part="home.footer.decoration">{{ t("teamSpeakClient") }}</span
|
||||
><span class="footer-spacer"></span
|
||||
><button
|
||||
type="button"
|
||||
class="clear-local-button"
|
||||
data-ws-part="home.footer.clear"
|
||||
@click="clearBrowserData"
|
||||
>{{ t("clearLocalData") }}</button
|
||||
><span class="footer-separator">·</span><span>{{ t("browserSupport") }}</span>
|
||||
><span class="footer-separator" data-ws-part="home.footer.decoration">·</span><span data-ws-part="home.footer.decoration">{{ t("browserSupport") }}</span>
|
||||
</footer>
|
||||
|
||||
<!-- QQ community modal -->
|
||||
@@ -871,6 +872,7 @@
|
||||
</div>
|
||||
|
||||
<PluginPanel :session-token="pluginSession" :gateway-url="pluginVoiceSocket?.url ?? ''" :connected="voiceState.connected" :language="language" />
|
||||
<HostChrome :language="language" :connected="voiceState.connected" />
|
||||
<IdentityImportDialog
|
||||
v-if="identityImportOpen"
|
||||
v-model="identityImportText"
|
||||
@@ -1004,6 +1006,7 @@ import { useWebClientChannels, type TreeChannel } from "../composables/useWebCli
|
||||
import { useWebClientConnection } from "../composables/useWebClientConnection.js";
|
||||
import { useWebClientMembers } from "../composables/useWebClientMembers.js";
|
||||
import PluginPanel from "../components/PluginPanel.vue";
|
||||
import HostChrome from "../components/HostChrome.vue";
|
||||
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
|
||||
import { useVoiceWebSocket, type ChannelMember, type ChatMessage } from "../composables/useVoiceWebSocket.js";
|
||||
import { useWebClientScreenShare } from "../composables/useWebClientScreenShare.js";
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-ws-route="webclient" data-ws-page="voice" data-ws-host-skin="community.hostile-fixture">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Host chrome recovery fixture</title>
|
||||
<script>
|
||||
// Authorize third-party skins before instance-authorization.ts is evaluated.
|
||||
try { localStorage.setItem("webspeak:instance-authorization:v1", JSON.stringify({ schemaVersion: 1, allowed: true })); } catch {}
|
||||
</script>
|
||||
<style>
|
||||
html, body { margin: 0; min-height: 100%; font: 12px/1.5 system-ui, sans-serif; }
|
||||
.ws-skin-root { min-height: 100vh; }
|
||||
#dock { display: flex; gap: 8px; padding: 12px; background: #eef4f2; }
|
||||
#overlay { width: 320px; height: 180px; margin: 12px; background: #fff; border: 1px solid #ccd; }
|
||||
#app { position: absolute; left: 0; top: 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- A minimal public-skin surface so compiled hostile rules have real targets. -->
|
||||
<div class="ws-skin-root" data-ws-skin="community.hostile-fixture" data-ws-page="voice" data-ws-part="app">
|
||||
<div id="dock" data-ws-part="voice.audio-dock">
|
||||
<button type="button" data-ws-part="voice.audio-dock.microphone">Mic</button>
|
||||
<button type="button" data-ws-part="voice.audio-dock.output">Output</button>
|
||||
</div>
|
||||
<div id="overlay" data-ws-part="host.plugins.overlay">Application library</div>
|
||||
<button type="button" id="launcher" data-ws-part="host.plugins.launcher">Plugins</button>
|
||||
</div>
|
||||
<div id="app"></div>
|
||||
<div id="auth-app"></div>
|
||||
<pre id="result" style="position:relative;z-index:5;background:#fff">pending</pre>
|
||||
<script type="module">
|
||||
import { createApp, h } from "vue";
|
||||
import HostChrome from "/src/components/HostChrome.vue";
|
||||
import InstanceAuthorization from "/src/components/InstanceAuthorization.vue";
|
||||
import { hostBuiltInSkinRequests, setHostChromeActiveSkin } from "/src/services/host-chrome.ts";
|
||||
import { hostOwnedLayers, syncRecoveryPopover } from "/src/services/host-owned-layer.ts";
|
||||
|
||||
const output = document.getElementById("result");
|
||||
const scenarios = JSON.parse(decodeURIComponent(location.hash.slice(1) || "[]"));
|
||||
const style = document.createElement("style");
|
||||
style.id = "hostile-skin";
|
||||
document.head.append(style);
|
||||
|
||||
setHostChromeActiveSkin("community.hostile-fixture");
|
||||
createApp({ render: () => h(HostChrome, { language: "en", connected: true }) }).mount("#app");
|
||||
createApp({ render: () => h(InstanceAuthorization, { language: "en" }) }).mount("#auth-app");
|
||||
|
||||
const layer = hostOwnedLayers().find((entry) => entry.name === "recovery");
|
||||
const results = [];
|
||||
|
||||
if (!layer) {
|
||||
output.textContent = JSON.stringify({ error: "recovery layer was not created" });
|
||||
} else {
|
||||
const popover = layer.container.querySelector("[data-ws-host-recovery]");
|
||||
// The component promotes the popover on the next microtask; do it here so
|
||||
// the whole fixture runs synchronously and the result is ready before load.
|
||||
if (!popover.matches(":popover-open")) popover.showPopover();
|
||||
for (const scenario of scenarios) {
|
||||
style.textContent = scenario.css;
|
||||
const button = layer.container.querySelector('[data-ws-recovery-action="built-in"]');
|
||||
// Reading geometry forces a synchronous style/layout pass, so the hostile
|
||||
// stylesheet is fully applied before the hit test.
|
||||
const rect = button.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
|
||||
const computed = getComputedStyle(button);
|
||||
const dock = document.getElementById("dock");
|
||||
const before = hostBuiltInSkinRequests.value;
|
||||
if (hit === button || button.contains(hit)) {
|
||||
hit.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, composed: true }));
|
||||
} else {
|
||||
button.click();
|
||||
}
|
||||
results.push({
|
||||
name: scenario.name,
|
||||
popoverOpen: popover.matches(":popover-open"),
|
||||
// elementFromPoint retargets nodes inside a closed shadow root to its
|
||||
// host, so either the inner button or the host proves the top layer won.
|
||||
topLayerHit: hit === layer.host || hit === button || layer.container.contains(hit),
|
||||
hostileCovered: hit === dock,
|
||||
visible: computed.display !== "none" && computed.visibility !== "hidden"
|
||||
&& Number(computed.opacity) > 0.01 && computed.pointerEvents !== "none",
|
||||
clicked: hostBuiltInSkinRequests.value === before + 1,
|
||||
layerOutsideSkinRoot: layer.host.closest(".ws-skin-root") === null,
|
||||
buttonRect: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
|
||||
});
|
||||
}
|
||||
// Authorization: the real dialog is teleported into its own closed shadow
|
||||
// root. showModal() must place it above the same hostile fullscreen layer.
|
||||
style.textContent = scenarios[0]?.css ?? "";
|
||||
const authLayer = hostOwnedLayers().find((entry) => entry.name === "authorization");
|
||||
const authDialog = authLayer?.container.querySelector("dialog");
|
||||
let authorization = null;
|
||||
if (authLayer && authDialog) {
|
||||
authDialog.showModal();
|
||||
const rect = authDialog.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2);
|
||||
authorization = {
|
||||
modalOpen: authDialog.matches(":modal"),
|
||||
topLayerHit: hit === authLayer.host || authDialog === hit || authLayer.container.contains(hit),
|
||||
hostileCovered: hit === document.getElementById("dock"),
|
||||
layerOutsideSkinRoot: authLayer.host.closest(".ws-skin-root") === null,
|
||||
sized: rect.width > 0 && rect.height > 0,
|
||||
};
|
||||
authDialog.close();
|
||||
}
|
||||
// Verify the rejected-promotion fallback really lays the capsule out. A
|
||||
// closed [popover] is `display:none !important` until the attribute is gone.
|
||||
const fallback = document.createElement("div");
|
||||
fallback.setAttribute("popover", "manual");
|
||||
fallback.textContent = "fallback";
|
||||
fallback.style.cssText = "position:fixed;left:0;top:0;width:80px;height:24px;";
|
||||
Object.defineProperty(fallback, "showPopover", {
|
||||
configurable: true,
|
||||
value: () => { throw new Error("top-layer promotion rejected"); },
|
||||
});
|
||||
document.body.append(fallback);
|
||||
syncRecoveryPopover(fallback, true);
|
||||
const fallbackStyle = getComputedStyle(fallback);
|
||||
const fallbackRect = fallback.getBoundingClientRect();
|
||||
const popoverFallback = {
|
||||
display: fallbackStyle.display,
|
||||
popoverAttribute: fallback.hasAttribute("popover"),
|
||||
visible: fallbackStyle.display !== "none" && fallbackRect.width > 0 && fallbackRect.height > 0,
|
||||
};
|
||||
fallback.remove();
|
||||
output.textContent = JSON.stringify({ results, authorization, popoverFallback });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,201 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { compileSkinCss } from "../../src/shared/skin-css.ts";
|
||||
|
||||
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
|
||||
const webRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const CHROME = ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"].find((candidate) => existsSync(candidate));
|
||||
|
||||
const compileHostile = (css) => compileSkinCss(css, "community.hostile-fixture", {}, 3).css;
|
||||
|
||||
/**
|
||||
* Hostile rules that the compiler still accepts (they are legitimate page /
|
||||
* themable-host styling) but that must not be able to hide, cover, or disable
|
||||
* the recovery entry. `fullscreen-audio-dock` is the case the previous review
|
||||
* reproduced: a public part promoted to a `z-index: 2147483647` fullscreen layer.
|
||||
*/
|
||||
const scenarios = [
|
||||
{
|
||||
name: "fullscreen-audio-dock",
|
||||
css: compileHostile('[data-ws-part="voice.audio-dock"] { position: fixed; inset: 0; z-index: 2147483647; }'),
|
||||
},
|
||||
{
|
||||
name: "opacity-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { opacity: 0; }'),
|
||||
},
|
||||
{
|
||||
name: "filter-launcher",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"] { filter: opacity(0); }'),
|
||||
},
|
||||
{
|
||||
name: "display-none-overlay",
|
||||
css: compileHostile('[data-ws-part="host.plugins.overlay"] { display: none !important; }'),
|
||||
},
|
||||
{
|
||||
name: "pointer-events-none",
|
||||
css: compileHostile('[data-ws-part="host.plugins.launcher"], [data-ws-part="host.plugins.overlay"] { pointer-events: none !important; }'),
|
||||
},
|
||||
];
|
||||
|
||||
test("host chrome renders recovery and authorization in a closed-shadow top layer", async () => {
|
||||
const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin] = await Promise.all([
|
||||
read("../src/components/HostChrome.vue"),
|
||||
read("../src/components/InstanceAuthorization.vue"),
|
||||
read("../src/services/host-owned-layer.ts"),
|
||||
read("../src/services/host-chrome.ts"),
|
||||
read("../src/composables/usePublicSkin.ts"),
|
||||
]);
|
||||
|
||||
// Recovery: closed shadow root + manual popover + no skin hook.
|
||||
assert.match(hostChrome, /createHostOwnedLayer\("recovery"/);
|
||||
assert.match(hostChrome, /popover="manual"/);
|
||||
assert.match(hostChrome, /data-ws-recovery-action="built-in"/);
|
||||
assert.match(hostChrome, /requestBuiltInSkin/);
|
||||
assert.match(hostChrome, /isThirdPartySkinActive/);
|
||||
assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/);
|
||||
|
||||
// Authorization: showModal() inside the same host-owned mechanism.
|
||||
assert.match(authorization, /createHostOwnedLayer\('authorization'/);
|
||||
assert.match(authorization, /showModal\(\)/);
|
||||
assert.doesNotMatch(authorization, /data-ws-part="host\.permission"/);
|
||||
|
||||
// The layer itself: closed shadow root, no data-ws-part, fixed fallback.
|
||||
assert.match(ownedLayer, /attachShadow\(\{ mode: "closed" \}\)/);
|
||||
assert.match(ownedLayer, /data-ws-host-layer/);
|
||||
assert.doesNotMatch(ownedLayer, /setAttribute\("data-ws-part"/);
|
||||
|
||||
// The reset path is independent of the skinnable plugin overlay.
|
||||
assert.match(hostChromeService, /requestBuiltInSkin/);
|
||||
assert.match(hostChromeService, /isThirdPartySkinActive/);
|
||||
assert.match(publicSkin, /hostBuiltInSkinRequests/);
|
||||
assert.match(publicSkin, /switchToBuiltIn/);
|
||||
|
||||
// Defense in depth: there is still no compiler route to a "host.recovery"
|
||||
// selector, even if a node ever regressed to carrying that attribute.
|
||||
for (const selector of ['[data-ws-part="host.recovery"]', '[data-ws-part="host.permission"]']) {
|
||||
assert.throws(() => compileSkinCss(`${selector} { display: none; }`, "community.evil", {}, 3), /Trusted or unknown host part/);
|
||||
}
|
||||
|
||||
// A leading `:root` must not reach body-level siblings (the host layer in the
|
||||
// preview/fixture topology) through `+` / `~`.
|
||||
for (const selector of [
|
||||
":root ~ [data-ws-host-layer]",
|
||||
":root ~ *",
|
||||
":root + [data-ws-host-layer]",
|
||||
":root:hover ~ *",
|
||||
]) {
|
||||
assert.throws(
|
||||
() => compileSkinCss(`${selector} { display: none !important; }`, "community.evil", {}, 3),
|
||||
/sibling combinator after :root/,
|
||||
selector,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("the themed preview keeps recovery in its own hookless top layer", async () => {
|
||||
const [preview, bridge] = await Promise.all([
|
||||
read("../public/host-chrome-preview.html"),
|
||||
read("../src/services/host-chrome-preview.ts"),
|
||||
]);
|
||||
assert.match(bridge, /resolveHiddenHostParts/);
|
||||
assert.match(preview, /host-chrome-preview\.ts/);
|
||||
assert.match(preview, /resolveHiddenHostParts\(chromeData, \[\]\)/);
|
||||
assert.match(preview, /hiddenParts\.has\(part\)/);
|
||||
assert.match(preview, /isHostPartReachable\(/);
|
||||
assert.match(preview, /launcherReachable/);
|
||||
assert.match(preview, /recoveryLayer\.remove\(\)/);
|
||||
assert.match(preview, /popover="manual"/);
|
||||
assert.doesNotMatch(preview, /data-ws-part="host\.recovery"/);
|
||||
assert.doesNotMatch(preview, /const watermarkHidden = getComputedStyle/);
|
||||
});
|
||||
|
||||
test("the public-skin composable opts in only through chrome.json#visibleParts", async () => {
|
||||
const usePublicSkin = await read("../src/composables/usePublicSkin.ts");
|
||||
assert.match(usePublicSkin, /setSkinHostChromeParts\(skin\?\.chromeData\)/);
|
||||
// Sniffing the combined stylesheet would match the importer-generated
|
||||
// hiddenParts/icon CSS and leak decorations for hiddenParts-only packs.
|
||||
assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/);
|
||||
});
|
||||
|
||||
async function dumpDom(url) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(CHROME, [
|
||||
"--headless=new",
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--hide-scrollbars",
|
||||
"--dump-dom",
|
||||
url,
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
reject(new Error(`Headless Chrome timed out.\n${stderr.slice(-2000)}`));
|
||||
}, 60000);
|
||||
child.on("error", (error) => { clearTimeout(timer); reject(error); });
|
||||
child.on("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
if (!stdout.includes('id="result"')) {
|
||||
reject(new Error(`Headless Chrome exited ${code} without a result.\n${stderr.slice(-2000)}`));
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("recovery stays visible and clickable under hostile compiled skins", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
|
||||
const server = await createServer({
|
||||
root: webRoot,
|
||||
configFile: path.join(webRoot, "vite.config.ts"),
|
||||
logLevel: "silent",
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
await server.listen();
|
||||
const address = server.httpServer?.address();
|
||||
const port = address && typeof address === "object" ? address.port : 0;
|
||||
assert.ok(port, "Vite did not expose a listening port");
|
||||
|
||||
const hash = encodeURIComponent(JSON.stringify(scenarios));
|
||||
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-chrome-recovery.html#${hash}`);
|
||||
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
|
||||
assert.ok(match, "the fixture did not emit a result block");
|
||||
const payload = JSON.parse(match[1]);
|
||||
assert.equal(payload.error, undefined, payload.error);
|
||||
assert.equal(payload.results.length, scenarios.length);
|
||||
|
||||
assert.ok(payload.authorization, "the authorization dialog was not mounted");
|
||||
assert.equal(payload.authorization.modalOpen, true, "the authorization dialog is not modal / in the top layer");
|
||||
assert.equal(payload.authorization.topLayerHit, true, "the hostile layer covers the authorization dialog");
|
||||
assert.equal(payload.authorization.hostileCovered, false, "the hostile layer received the authorization hit test");
|
||||
assert.equal(payload.authorization.layerOutsideSkinRoot, true, "the authorization dialog was rendered inside .ws-skin-root");
|
||||
assert.equal(payload.authorization.sized, true, "the authorization dialog has no layout box");
|
||||
|
||||
// The pre-Popover / rejected-promotion fallback must actually lay the capsule
|
||||
// out: a closed [popover] is display:none !important until the attribute goes.
|
||||
assert.ok(payload.popoverFallback, "the fixture did not exercise the popover fallback");
|
||||
assert.equal(payload.popoverFallback.display, "flex", "the fallback capsule is not displayed");
|
||||
assert.equal(payload.popoverFallback.popoverAttribute, false, "the popover attribute still forces display:none");
|
||||
assert.equal(payload.popoverFallback.visible, true, "the fallback capsule has no layout box");
|
||||
|
||||
for (const result of payload.results) {
|
||||
assert.equal(result.popoverOpen, true, `${result.name}: recovery popover is not in the top layer`);
|
||||
assert.equal(result.topLayerHit, true, `${result.name}: recovery is covered by the hostile layer`);
|
||||
assert.equal(result.hostileCovered, false, `${result.name}: the hostile layer received the hit test`);
|
||||
assert.equal(result.visible, true, `${result.name}: recovery is visually hidden or non-interactive`);
|
||||
assert.equal(result.clicked, true, `${result.name}: clicking "use built-in skin" did not reach the handler`);
|
||||
assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`);
|
||||
}
|
||||
});
|
||||
@@ -22,7 +22,11 @@ const skin = id => ({ id, name: id, version: "1.0.0", minAppVersion: "0.2.6",
|
||||
css: `[data-ws-skin="${id}"] { --skin-test: blue; }`, assets: {}, installedAt: 1 });
|
||||
const json = body => new Response(JSON.stringify(body));
|
||||
class Element {
|
||||
dataset = {}; textContent = ""; id = "";
|
||||
dataset = {}; textContent = ""; id = ""; attributes = new Map();
|
||||
setAttribute(name, value) { this.attributes.set(String(name), String(value)); }
|
||||
getAttribute(name) { return this.attributes.get(String(name)) ?? null; }
|
||||
hasAttribute(name) { return this.attributes.has(String(name)); }
|
||||
removeAttribute(name) { this.attributes.delete(String(name)); }
|
||||
append(el) { elements.set(el.id, el); }
|
||||
remove() { elements.delete(this.id); }
|
||||
matches() { return false; }
|
||||
|
||||
Reference in new issue
Block a user