Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eddc098d29 | ||
|
|
6273185afa | ||
|
|
0bc2e6cec8 | ||
|
|
34cee80302 | ||
|
|
82b58dbd61 | ||
|
|
699e606da5 | ||
|
|
eb6c4ba857 | ||
|
|
2de2e23fd3 | ||
|
|
ae6788a796 | ||
|
|
9812a28e5f | ||
|
|
cc36bc4c64 | ||
|
|
8ca33fd77d | ||
|
|
99d7b86d09 | ||
|
|
2b019d82ff | ||
|
|
e46d7a0eb7 | ||
|
|
0df25e4892 | ||
|
|
a353c32892 | ||
|
|
c1187d12d2 | ||
|
|
93d221c3ef | ||
|
|
aefa0bc163 | ||
|
|
fa720bf260 | ||
|
|
a4ae4de82f | ||
|
|
a84f66b47d | ||
|
|
af1d1f8a88 | ||
|
|
2cb8b8d161 | ||
|
|
12a37fc26f | ||
|
|
f20a372f4b | ||
|
|
15ca32b7a8 | ||
|
|
274bd81dc3 | ||
|
|
6a35d9be3d | ||
|
|
ed752a5a6f | ||
|
|
f8d61d22ef |
No files matched your search
@@ -21,10 +21,20 @@ Verify import, trust, enable, update, failure/restart, custom routes, persistenc
|
||||
|
||||
After completing development and verification, automatically finish the distribution workflow below; do not stop at a local archive or ask the user to submit it later. Honor explicit local-only/no-push instructions. Review-only, inspection and planning tasks do not trigger publishing. This workflow does not authorize deployment or automatic merging.
|
||||
|
||||
## Administrator configuration
|
||||
|
||||
- Document each supported field in the plugin repository with its key, input type, required status, default and accepted range or choices. Provide a copyable `config.example.json` with separate `config` (public) and `serverConfig` (private) objects. Mark placeholder credentials and explain where administrators obtain them. Use defaults for optional keys and validate the actual values in the plugin.
|
||||
- The 0.3.2 admin console has a generic typed editor for objects, lists and primitive values. P2P File Transfer, Watch Together and TSMusicBot have dedicated forms in the admin frontend. A repository example is documentation and does not register a custom form automatically. Keep app-specific form behavior out of the runtime, registry and package validation.
|
||||
- Verify setting, saving and reloading a configuration in `/admin/plugins`. Test that secret values are masked in inputs and omitted from admin reads, and that keeping a saved secret does not require re-entry. P2P File Transfer exposes `maxFileMiB` and optional `iceServers`. TURN credentials sent to authorized browsers must be client credentials. Watch Together exposes `control` (`everyone` or `host`) and has no private settings.
|
||||
|
||||
## Public runtime deployment
|
||||
|
||||
A public gateway needs a separate HTTPS origin for apps. Set it in **Plugins → Application runtime** (persisted setting takes precedence) or with `WEBSPEAK_PLUGIN_PUBLIC_ORIGIN`. Proxy that origin to the plugin listener (port `3042` by default), preserving WebSocket upgrades and unbuffered SSE. Loopback development can use the built-in alternate host. If every app reports `PLUGIN_PUBLIC_ORIGIN_REQUIRED`, check the gateway origin setting, DNS, certificate and proxy before rebuilding packages. Verify by opening a real app in a connected voice room and checking that the iframe loads from the configured origin. A bare GET to the origin can return `PLUGIN_NOT_OPEN`; opening an app creates the scoped URL.
|
||||
|
||||
## Automatic distribution PR
|
||||
|
||||
1. Read the current [application catalog](https://github.com/Huddle-Up-Forge/webspeak-plugin), its default branch, contribution rules, `index.json`, JSON schema, validators and any PR template. Follow the actual repository contract.
|
||||
2. Maintain source, license, dependencies, build instructions, tests and `.wplugin` in an independent public application repository. Use the task's selected destination; ask only for a genuinely missing owner/name when it cannot be discovered. Commit and push the final package first, then generate and publish default-branch `plugin.json` with the complete API v2 `manifest` and `package.ref/path/sha256`. The catalog requires a full 40-character package commit SHA, not a branch, mutable label, future commit or self-reference. Hash the raw package bytes; metadata must match its manifest.
|
||||
2. Maintain source, license, dependencies, build instructions, tests and `.wplugin` in an independent public application repository. Use the task's selected destination; ask only for a genuinely missing owner/name when it cannot be discovered. Commit and push the final package first, then generate and publish default-branch `plugin.json` with the complete API v2 `manifest` and `package.ref/path/sha256`. The catalog requires a full 40-character package commit SHA, not a branch, mutable label, future commit or self-reference. Hash the raw package bytes and follow the catalog's manifest checks. WebSpeak 0.3.2 compares the ID, version, scope set and entry points after API v2 and package validation. Display name, description, author and license may differ at install time. Keep that information accurate and run the catalog's own checks before submission.
|
||||
3. Fetch the public metadata and pinned package, check identity/manifest/hash and real import, then run the catalog's current checks (currently `npm run verify` and `npm run verify:remote`). Fix failures before marking the submission ready. Bundle audited dependencies in the application package. Never copy business code, archives, secrets or diagnostics into the catalog.
|
||||
4. For a new listing, add one `{ "id": "<plugin-id>", "repository": "https://github.com/<owner>/<repo>", "metadataPath": "plugin.json" }` under `plugins` in schema 2 `index.json`. Update an existing ID when catalog fields change; never duplicate it or edit unrelated entries. Version-only releases already discoverable through the listed metadata need no empty index PR; report their published metadata and existing listing instead.
|
||||
5. Open the PR automatically from a focused branch against the actual default branch, or from a fork if needed. Reuse an existing open PR for this contribution. Titles: `feat(plugins): add <plugin-id> v<version>` or `chore(plugins): update <plugin-id> v<version>`. Apply any existing PR template.
|
||||
@@ -33,9 +43,9 @@ Use the catalog's PR template, or `Summary`, `Package`, `Validation` and `Previe
|
||||
|
||||
Return and attach the real PR URL when supported, with validation results. Do not auto-merge. If authentication or repository policy blocks submission, retain the reviewable branch/diff, identify the precise blocker and request only what is missing; do not substitute a generic permission question or claim success without a submitted PR.
|
||||
|
||||
## Floating host workspace
|
||||
## Host launcher and application window
|
||||
|
||||
The host owns a skin-independent draggable launcher, application library and non-modal app window. Do not add launch controls to a particular skin or inspect its DOM. Apps render their responsive light/dark UI inside the supplied iframe; the host supplies dragging, minimize/maximize/restore and close controls. The host window uses the standard `color-scheme` for its light/dark fallback without inheriting skin component styles. Do not duplicate host window chrome or block the workspace with a page-wide modal backdrop.
|
||||
WebSpeak owns the launcher, library, pinning and non-modal app window. In 0.3.2 a skin can place the host launcher in a toolbar or sidebar with `voice.plugin-launcher`. The host falls back to its library entry for layouts without a usable slot. The app uses the same iframe and lifecycle contract in all layouts. Apps render their responsive light/dark UI inside the supplied iframe; the host supplies dragging, minimize/maximize/restore and close controls. The host window uses the standard `color-scheme` for its light/dark fallback without inheriting skin component styles. Do not duplicate host window chrome or block the workspace with a page-wide modal backdrop.
|
||||
|
||||
Minimizing or switching to the library retains the same iframe and app session. Transfers and playback must survive those actions. Closing the window, replacing the active app or host context revocation ends that session; only one frontend app is currently hosted at a time. Do not equate a hidden iframe with app exit. Verify resize, narrow screens, theme changes, minimize/resume without reload and close/revocation cleanup. Keep the user-facing window focused on functionality and actionable status; omit repeated runtime/permission disclaimers. Administrator trust and security review remain part of enablement.
|
||||
|
||||
|
||||
@@ -20,12 +20,19 @@ When a WebSpeak checkout is unavailable, read the [published skin guide](https:/
|
||||
5. Build the `.wskin` from its source directory while including only files declared by the manifest. Validate the finished archive with the repository importer and keep any distributable built-in archive synchronized with its example source. An example README or other undeclared file belongs beside the package, not inside it.
|
||||
6. Verify the package at the scope of the change: run the skin package and component-schema tests; run the relevant type/build checks; import the exact archive in a compatible WebSpeak runtime. Check desktop and narrow layouts, all supported interface languages, long text, keyboard focus, reduced motion, contrast, and every interaction the skin replaces. For a portability claim, install the same archive (compare its SHA-256) in two instances with the same compatible runtime/API version; do not treat a successful build alone as proof.
|
||||
|
||||
## WebSpeak 0.3.2 host controls
|
||||
|
||||
- Use component schema v3 and set `minAppVersion` to at least `0.3.2` when using `voice.plugin-launcher`. Place it once in the voice surface, inside a visible slot. Set `options.pluginPresentation` to `drawer-side` for a sidebar, `drawer-below` for a header button, or `dialog` for the default library. The built-in Day, Night and ILLUSIA skins use the header drawer. The KAAK and Discord examples use the sidebar drawer.
|
||||
- Style `voice.plugin-launcher`, `voice.plugin-drawer` and `voice.plugin-drawer.app` through the published parts. WebSpeak owns app availability, pinning, authorization and the app window. Layouts without a usable mount can fall back to the host library. In a connected, authorized voice session verify that the launcher mounts in the intended slot, that the drawer stays within desktop and narrow viewports, and that both pinned and unpinned apps open. For KAAK, verify the rail itself and check the package version served by the instance if the launcher still floats.
|
||||
- For a compact rail, `home.social-links` accepts `options.communityLinks: false` to keep the admin entry and hide community links. The admin console uses host styling. Use `chrome.json#visibleParts` only for documented host decorations. Confirm that the host-owned recovery action remains usable after applying the skin.
|
||||
- Test changes to the public home and voice surfaces with the same released archive. Check cold load for a theme flash, long translations for clipping, and live/shared media for artwork layering. Use a real voice session for interaction claims.
|
||||
|
||||
## Automatic distribution PR
|
||||
|
||||
After completing a skin development or update task and its verification, automatically finish the contribution workflow below; do not wait for another instruction to submit the validated contribution. Honor explicit local-only/no-push instructions. Review-only, inspection and planning tasks do not trigger publishing. This workflow does not authorize deployment or automatic merging.
|
||||
|
||||
1. Read the current [skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins), its default branch, `index.json`, contribution rules, and any PR template or checks that exist. Follow the actual catalog contract rather than inventing fields.
|
||||
2. Keep source, license, build instructions and the validated `.wskin` in an independent public skin repository. Use the destination selected for the task; ask only for a genuinely missing owner/name when it cannot be discovered. Commit and push the package first. Then publish default-branch `skin.json` pointing to its existing full package commit SHA/path with the SHA-256 of the exact archive bytes. Keep ID, version, license and `minAppVersion` consistent. Do not move a published package tag or make metadata reference its own not-yet-created commit.
|
||||
2. Keep source, license, build instructions and the validated `.wskin` in an independent public skin repository. Use the destination selected for the task; ask only for a genuinely missing owner/name when it cannot be discovered. Commit and push the package first. Then publish default-branch `skin.json` pointing to its existing full package commit SHA/path with the SHA-256 of the exact archive bytes. Match the package ID, version and `minAppVersion` to the catalog. Keep names, author credits and licenses accurate in both places. WebSpeak 0.3.2 permits display metadata to differ, and catalog publication checks may impose additional requirements. Do not move a published package tag or make metadata reference its own not-yet-created commit.
|
||||
3. Fetch public metadata and the pinned package as the store would; verify hash, identity, version, compatibility and actual import, and run catalog checks when supplied. The catalog contains an index, not skin source or archives. Exclude credentials, captures, diagnostic reports and unrelated development documents.
|
||||
4. For a new listing, add exactly one `{ "id": "<skin-id>", "repository": "https://github.com/<owner>/<repo>" }` under `skins` in schema 1 `index.json`. Update an existing ID rather than duplicating it. Under the catalog's current policy, a version-only update is discovered through the skin repository's metadata; if there is no real catalog diff, report the published update and existing listing instead of creating an empty PR.
|
||||
5. Create a focused branch against the catalog's actual default branch, using a fork if necessary, and open the PR automatically. Reuse an existing open PR for the same contribution. Titles: `feat(skins): add <skin-id> v<version>` or `chore(skins): update <skin-id> v<version>`. Follow the repository's PR template when present.
|
||||
@@ -45,6 +52,7 @@ Return the actual PR URL and validation outcome, and attach the PR to the chat w
|
||||
|
||||
- `docs/SKIN_DEVELOPMENT.md` — the single current reference for skin formats, runtime APIs, permissions, data, actions, CSS hooks, security, and QA.
|
||||
- `docs/examples/ILLUSIA-VOICE.md` and `docs/examples/OPEN-VOICE-SURFACE.md` — full skin and surface examples.
|
||||
- `docs/examples/KAAK-VOICE.md` and `docs/examples/DISCORD-VOICE.md` — complete layouts with a sidebar app library.
|
||||
|
||||
## Instance authorization
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.3.1
|
||||
default: 0.3.2
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -182,12 +182,9 @@ jobs:
|
||||
cp "$runtime_root/bin/node" "$package_root/runtime/node"
|
||||
cp "$runtime_root/LICENSE" "$package_root/runtime/NODE-LICENSE"
|
||||
chmod 0755 "$package_root/runtime/node"
|
||||
cat > "$package_root/start-webspeak.sh" <<'LAUNCHER'
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
cd -- "$(dirname -- "$0")"
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
LAUNCHER
|
||||
# Ship the exact launcher the self-update installer and recovery
|
||||
# tests use; never maintain a second launcher body in the workflow.
|
||||
cp "$GITHUB_WORKSPACE/scripts/start-webspeak.sh" "$package_root/start-webspeak.sh"
|
||||
chmod 0755 "$package_root/start-webspeak.sh"
|
||||
|
||||
smoke_root="$RUNNER_TEMP/${package_name}-smoke"
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
当前版本 / Current version: **[v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
|
||||
当前版本 / Current version: **[v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
|
||||
|
||||
dev 实验功能 / dev experiment: [锁屏通话 / Lock-screen calls](./docs/EXPERIMENTAL_BACKGROUND_CALLS.md)(默认关闭,尚未通过真机锁屏验收 / off by default; physical-device validation pending)。
|
||||
|
||||
## 关于 WebSpeak · Overview
|
||||
|
||||
@@ -52,6 +54,8 @@ Join voice channels, chat and share your screen from a browser. Deploy your own
|
||||
|
||||
- [简体中文](./docs/README.zh-CN.md#screenshots) · [English](./docs/README.en.md#screenshots) · [Deutsch](./docs/README.de.md#screenshots) · [Русский](./docs/README.ru.md#screenshots) · [日本語](./docs/README.ja.md#screenshots)
|
||||
|
||||
以下皮肤截图拍摄于已连接的 TeamSpeak 语音房间。 / The skin screenshots below were captured in a connected TeamSpeak voice room.
|
||||
|
||||
| 日间 · Day | 夜间 · Night |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
@@ -81,9 +85,9 @@ docker compose up -d
|
||||
2. 配置 TeamSpeak 目标和访问模式;公网使用 HTTPS。Set the TeamSpeak target and access mode; use HTTPS for public access.
|
||||
3. 启用 WebRTC 时放行配置的 UDP 范围,默认 `40000–40099`。Allow the configured UDP range when enabling WebRTC.
|
||||
|
||||
数据保存在 `webspeak-data` volume,升级时保留它。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
|
||||
数据保存在 `webspeak-data` volume,升级时保留它。Docker 控制台只能检查版本;升级请在宿主机执行 `docker compose pull && docker compose up -d`,且不要执行 `docker compose down -v`。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
|
||||
|
||||
Data persists in the `webspeak-data` volume. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
|
||||
Data persists in the `webspeak-data` volume. On Docker, the console only checks versions; upgrade on the host with `docker compose pull && docker compose up -d` and never run `docker compose down -v`. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
|
||||
|
||||
<a id="documentation"></a>
|
||||
|
||||
@@ -104,9 +108,9 @@ Data persists in the `webspeak-data` volume. The Compose file uses host networki
|
||||
| 皮肤包 · Skin packages | [皮肤索引 · Catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) |
|
||||
| 功能插件 · Functional plugins | [应用目录与开发起点 · Catalog & application starter](https://github.com/Huddle-Up-Forge/webspeak-plugin) · [开发指南 · Guide](./docs/PLUGIN_DEVELOPMENT.md) · [Agent Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) |
|
||||
|
||||
皮肤包负责界面、布局及其附属小组件;功能插件使用标准浏览器环境和可选 Node 后端,自行实现业务功能。功能插件 API v2 已包含在 v0.3.1 中,提供独立于皮肤的工具栏入口。
|
||||
皮肤包负责界面、布局及其附属小组件;功能插件使用标准浏览器环境和可选 Node 后端,自行实现业务功能。功能插件 API v2 已包含在 v0.3.1 中,从语音工作区的应用库启动,支持工具栏和皮肤侧栏入口。
|
||||
|
||||
Skins own appearance, layout and attached widgets. Functional plugin API v2 is included in v0.3.1 with a skin-independent toolbar entry for the application workspace.
|
||||
Skins own appearance, layout and attached widgets. Functional plugin API v2 is included in v0.3.1 and opens applications from the voice workspace library, available in the toolbar or a skin sidebar.
|
||||
|
||||
### 开发与收录 · Develop & contribute
|
||||
|
||||
@@ -142,11 +146,14 @@ The skills complete the contribution workflow automatically: publish validated s
|
||||
<summary>查看贡献说明 · View contribution credits</summary>
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
|
||||
- [ph1gros](https://github.com/ph1gros) — 在 [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 中报告并提供公开目标 IPv6 校验、管理员认证与会话、代理限流和 PCM 上行边界的安全审查、补丁及回归测试;相关问题由项目在 `dev` 分支重新实现并修复。Security findings, proposed fixes and regression tests; reimplemented on `dev`.
|
||||
- [ph1gros](https://github.com/ph1gros) — 在 [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 中报告并提供公开目标 IPv6 校验、管理员认证与会话、代理限流和 PCM 上行边界的安全审查、补丁及回归测试;相关问题由项目在 `dev` 分支重新实现并修复。[PR #46](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/46) 提供 TS3 版本识别修复及兼容性文档建议。Security findings, proposed fixes and regression tests; reimplemented on `dev`.
|
||||
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
|
||||
|
||||
- [Jh_Harry](https://github.com/JhHarry) — [Persona 3](https://github.com/JhHarry/webspeak-skin-persona3)、[Persona 4](https://github.com/JhHarry/webspeak-skin-persona4) 和 [Persona 5](https://github.com/JhHarry/webspeak-skin-persona5) 的皮肤样式、构建脚本与打包。Theme styles, build scripts, and packaging for the three Persona skins.
|
||||
- [OddTurtleHead](https://github.com/OddTurtleHead) — [PR #57](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/57) 为皮肤开放宿主装饰的定制接口,完善独立皮肤恢复入口,并提供两套示例皮肤。Host chrome theming, a protected skin recovery control, and two example skins.
|
||||
|
||||
</details>
|
||||
|
||||
## 许可证 · License
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# 锁屏通话实验 / Experimental lock-screen calls
|
||||
|
||||
此功能目前只用于 dev 分支实验,默认关闭。它改善浏览器的音频路径,不能保证浏览器或操作系统允许锁屏后一直录音、联网或播放。尚未完成 Android/iOS 真机锁屏验收。
|
||||
|
||||
## 使用
|
||||
|
||||
在音频配置中开启“锁屏通话(实验性)”,然后断开并重新进入语音房间。设置只在下次连接生效,通话中修改不会突然更换麦克风路径。需要网关及浏览器支持 WebRTC。没有 WebRTC 或协商失败时,回退到原有兼容传输,音频配置中的原生模式提示会消失。
|
||||
|
||||
原生模式直接发送系统麦克风音轨,并用浏览器原生 `<audio srcObject>` 接收。浏览器的回声消除、标准降噪仍可使用;RNNoise 强降噪、软件输入增益、客户端音量计、语音阈值和伴奏不参与这条路径。非零输入增益不会缩放声音,0% 仍禁止发送。此模式持续发送未静音的麦克风,请在不需要说话时静音。静音同时控制音轨与网关的麦克风状态。关闭实验选项并重新连接可恢复普通处理。
|
||||
|
||||
支持的浏览器会显示系统媒体控制。Pause 同时静音麦克风及接收声音;Play 只恢复接收,不解除麦克风静音。麦克风切换需要明确操作,Stop/Hang up 会结束连接并释放采集。在支持 Audio Session API 的平台上声明 `play-and-record`,离开时恢复之前的类型。系统暂停或结束音轨时,音频配置会显示中断提示。
|
||||
|
||||
## 实现与边界
|
||||
|
||||
- 普通模式保留现有 Web Audio、WebRTC 与 PCM 回退。原生模式不创建麦克风的 AudioContext、AudioWorklet、分析器或混音节点。
|
||||
- 远端原生音频的 `play()` 不再等待采集 AudioContext 的 `resume()`;未完成的恢复请求不会连带阻塞收听。
|
||||
- 返回前台和系统 Play 只重试当前会话的播放。它们不会重新申请麦克风、取消静音或重新建立已结束的通话。
|
||||
- Media Session 是系统控制接口,不是后台保活权限。PWA、Service Worker、屏幕常亮都不能绕过系统限制;不播放静音文件或伪造音乐来保活。
|
||||
- WebSocket 兼容模式仍依赖 JavaScript 解码与 Web Audio,不作锁屏持续通话保证。真实语音需要持续网络连接,不能像音乐文件那样提前缓冲。
|
||||
- Android APK 目前仍为 WebView 与嵌入式网关。这次未添加原生前台音频服务,也未完成 APK 后台双向语音验收。
|
||||
|
||||
## 验证
|
||||
|
||||
自动化测试覆盖原始音轨发送、静音、权限请求取消、WebRTC 失败/缺失后的回退、系统 API 缺失/部分支持、旧系统动作隔离、采集恢复不阻塞播放,以及前台恢复不自动开麦。
|
||||
|
||||
2026-11-24 本地验证:`npm run verify` 的 1023 项测试全部通过,前后端构建成功。Windows Edge 使用模拟麦克风、两个真实浏览器 RTCPeerConnection 做回环,确认原生轨道收发 RTP、播放不等待采集恢复、静音切换及资源释放;1440px 与 390px 视口检查了全部五种语言的设置界面。该回环未连接 TeamSpeak,移动视口也不是手机系统锁屏测试。
|
||||
|
||||
真机验收应连接真实 TeamSpeak 房间,用第二个独立客户端双向监听,并分别记录:
|
||||
|
||||
1. Android Chrome、iPhone Safari、已安装 PWA 和 APK 的版本、系统版本、网络与省电设置。
|
||||
2. 普通模式与实验模式下,前台、切应用、锁屏各 1/5/15 分钟的收听和发送;每次恢复说话前后都检查第二端实际听感及媒体收发计数。
|
||||
3. 开麦/静音/输入音量 0%、系统 Play/Pause/麦克风控制、蓝牙切换、电话打断、网络切换和网关重连。
|
||||
4. 断开或撤销权限后系统录音指示消失;旧权限请求或系统按钮不能重新启动采集。关闭实验并重连后强降噪、伴奏和普通音量控制恢复。
|
||||
|
||||
桌面模拟移动视口、无头浏览器和单元测试不代表通过真机锁屏验收。
|
||||
|
||||
## References
|
||||
|
||||
- HollyMusic [`useAudioPlayer.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/hooks/useAudioPlayer.ts) and [`audio-analysis.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/lib/client/audio-analysis.ts): native playback separated from optional Web Audio processing. This implementation uses the same architectural idea; no HollyMusic source was copied.
|
||||
- [Media Session API](https://web.dev/articles/media-session) and [Audio Session draft](https://www.w3.org/TR/audio-session/).
|
||||
- [Android foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types).
|
||||
|
||||
The experiment is off by default and applies on the next connection. It uses native WebRTC microphone tracks and native remote playback, while keeping mute, hangup and compatibility fallback. Optional Web Audio processing and accompaniment are unavailable in the native route. OS playback controls never unmute the microphone implicitly. Browser/OS restrictions still apply; physical-device background calling and native Android foreground audio services remain unverified/unimplemented respectively.
|
||||
@@ -135,13 +135,15 @@ export default async function activate({ dataDir, config, publicConfig, events,
|
||||
|
||||
## 分发与验证
|
||||
|
||||
[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含同一 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。宿主限制 GitHub 内容来源、核验哈希与 manifest;目录或安装修订改变会拒绝覆盖,需重新加载。空目录不默认安装插件。
|
||||
[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。实例安装时校验包哈希、API 版本、插件 ID、版本、作用域集合与前后端入口。商店展示 `plugin.json` 里的名称、描述、作者和许可证,实例安装后展示包内清单里的值。目录或安装修订改变时需重新加载。空目录不默认安装插件。
|
||||
|
||||
需要后台配置的插件应在仓库 README 写明公开与私密字段的用途、必填项、默认值、取值范围和凭据获取方式,并提供含占位符的 `config.example.json`。管理员可从已安装插件打开仓库,并使用后台的通用字段编辑器。P2P 文件传输、视频同看和 TSMusicBot 有专用表单,由管理前端提供。仓库示例文件供管理员参考,当前运行时没有自动注册表单的接口。
|
||||
|
||||
验证实际构建包的导入、审核、启用、自定义 HTTP/WS、依赖加载、持久化和关闭/断线/禁用/更新撤销;检查明暗、语言、窄屏。协作另测两位真实参与者及并发/离开/重连。区分模拟身份、真实 TS、浏览器交互与跨网络证据。宿主回归:`npm run verify`。
|
||||
|
||||
## 悬浮应用窗口 / Floating application workspace
|
||||
## 插件入口与应用窗口 / Plugin launcher and application window
|
||||
|
||||
功能插件入口由宿主的独立悬浮层提供,不属于默认主题或任何皮肤插槽。入口可拖动,避免遮挡工作台控件。应用库和应用内容使用非模态窗口:打开后仍可操作工作台;标题栏可拖动,支持最小化、最大化、还原和关闭,小屏幕自动限制在可视区域内。宿主窗口优先读取标准 `color-scheme` 来选择日间/夜间配色,不继承皮肤组件样式。
|
||||
插件入口由宿主管理。WebSpeak 0.3.2 起,完整语音皮肤可以把 `voice.plugin-launcher` 放到工具栏或侧栏,并选择抽屉或对话框。布局缺少可用插槽时会显示宿主的应用库入口。应用库和应用内容使用非模态窗口:打开后仍可操作工作台;标题栏可拖动,支持最小化、最大化、还原和关闭,小屏幕自动限制在可视区域内。宿主窗口优先读取标准 `color-scheme` 来选择日间/夜间配色,不继承皮肤组件样式。
|
||||
|
||||
最小化、切换到应用库、再返回当前应用均保留同一个 iframe 与会话,传输、播放等任务不会因收起窗口而重置。关闭窗口、切换至另一个应用或语音会话撤销时,宿主结束当前应用会话。当前同时承载一个前端应用;不要把窗口最小化当成退出事件。
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Browserclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer verwenden Sprache, Chat und Bildschirmfreigabe im Browser; Betreiber verwalten Zielserver, Zugriff und Daten über die Webkonsole.
|
||||
|
||||
Stabile Version: [Hinweise zu v0.3.1](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Audiowiedergabe und Diagnose, Rauschunterdrückung, Plugin-Kurzbefehle und private Einladungen.
|
||||
Stabile Version: [Hinweise zu v0.3.2](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin-Wiederherstellung, App-Bibliothek und Plugin-Formulare.
|
||||
|
||||
|
||||
|
||||
@@ -341,6 +341,14 @@ Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und opti
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- Drittanbieter-Skins können Host-Dekorationen gestalten. Der Host verwaltet Wiederherstellung und Freigabe, damit Nutzer zu einem integrierten Skin zurückkehren können. Danke an ph1gros für die TS3-Erkennung und Kompatibilitätshinweise (#46) und an OddTurtleHead für Host-Design und Skin-Wiederherstellung (#57).
|
||||
- Tag, Nacht und ILLUSIA öffnen die App-Bibliothek über die obere Leiste. KAAK 3.1.134 platziert den Button in der linken Symbolleiste und gleicht ihn den Nachbarbuttons an. Angeheftete Apps stehen oben.
|
||||
- Die Plugin-Verwaltung bietet einen Feldeditor, Formulare für P2P-Dateitransfer, gemeinsames Ansehen und TSMusicBot sowie Links zu den Repositories.
|
||||
- Die Stores tolerieren Unterschiede bei Anzeigedaten und prüfen SHA-256, Paketformat und für Installation oder Ausführung nötige Felder.
|
||||
- Die Entwicklungsleitfäden und Agent Skills erklären die Platzierung des App-Buttons, die Konfigurationsfelder und den separaten HTTPS-Ursprung für öffentliche Plugins.
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- Die WebSocket-Wiedergabe berücksichtigt jetzt die Opus-Kanalzahl und die tatsächliche Paketdauer. Der WebRTC-Downlink-Mix erhält Stereo. Siehe #54.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors join voice, chat and screen sharing in a browser; operators manage target servers, access policy and data through the administration console.
|
||||
|
||||
Stable release: [v0.3.1 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Voice playback and diagnostics, noise suppression levels, plugin shortcuts and private invites.
|
||||
Stable release: [v0.3.2 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin recovery, app library layouts, and plugin settings forms.
|
||||
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
Upgrade from the host. The administration console can check for newer stable releases on Docker, but it cannot replace the container image from inside the container:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
@@ -111,12 +111,16 @@ docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database and administrator settings.
|
||||
Do not run `docker compose down -v`; it removes the `webspeak-data` volume, including the database and administrator settings.
|
||||
|
||||
### Release package
|
||||
|
||||
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
|
||||
|
||||
Linux x64 release packages that match the official `build-release.yml` layout can be upgraded from the administration console. It checks the official GitHub Releases, refuses a package without a matching `SHA256SUMS.txt` entry, replaces only application code and restarts the process. `SHA256SUMS.txt` is an integrity checksum only, not a digital signature. `data/`, `config.json`, `certs/`, installed skins and plugins are preserved. Export a backup before starting. Windows release packages can check for versions, but console apply is disabled until it is verified on a real Windows install; download the new package and replace it manually. Linux arm64 packages can be checked, but console apply is disabled because the in-place swap has not been verified on real arm64 hardware; download the new package and replace it manually. Docker and source deployments cannot apply an update from the console.
|
||||
|
||||
Console installation is limited to foreground Linux x64 packages. Instances managed by systemd, PM2 or Supervisor can still check releases and open release notes, but cannot apply them in the console. Stop the service, replace application files from the new package, and start the service again; preserve `data/`, `config.json` and `certs/`. A detached updater is not independent of the service manager.
|
||||
|
||||
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
|
||||
|
||||
### From source
|
||||
@@ -134,6 +138,8 @@ npm start
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
|
||||
The administration console can check for newer stable versions when running from source, but one-click apply is unavailable because the tree has no bundled Node.js runtime. Pull the source and rebuild after reviewing the release notes. The console never downloads or swaps source-tree files.
|
||||
|
||||
### First-time setup
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
@@ -341,6 +347,14 @@ Functional plugins are independent applications using standard browser capabilit
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- Third-party skins can style host decorations. The host manages recovery and authorization so users can switch back to a built-in skin. Thanks to ph1gros for the TS3 detection and compatibility work (#46), and OddTurtleHead for host theming and skin recovery (#57).
|
||||
- Day, Night and ILLUSIA open the app library from the top toolbar. KAAK 3.1.134 puts it in the leftmost icon rail and aligns its button with neighboring controls. Pinned apps appear first.
|
||||
- The plugin console adds a field editor, forms for P2P File Transfer, Watch Together and TSMusicBot, and links to plugin repositories.
|
||||
- Skin and plugin stores accept differences in display metadata while checking SHA-256, package format, and fields required for installation or execution.
|
||||
- Updated the skin and plugin development guides and Agent Skills for launcher layouts, configuration fields, and the separate HTTPS origin required for public plugin hosting.
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- Fixed lost Opus channel information and fixed 20 ms packet durations in WebSocket playback. WebRTC downlink mixing now preserves stereo. See #54.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
|
||||
|
||||
安定版:[v0.3.1 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 音声再生と診断、ノイズ抑制、プラグインのショートカット、非公開招待を改善。
|
||||
安定版:[v0.3.2 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · スキンの復元、アプリライブラリの配置、プラグイン設定フォーム。
|
||||
|
||||
|
||||
|
||||
@@ -276,6 +276,14 @@ relay.example.com {
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- サードパーティースキンでホストの装飾を変更できます。復元と許可の操作は WebSpeak が管理し、組み込みスキンに戻せます。TS3 判定と互換性情報の ph1gros(#46)、ホスト装飾と復元機能の OddTurtleHead(#57)に感謝します。
|
||||
- 日間、夜間、ILLUSIA では上部バーからアプリライブラリを開けます。KAAK 3.1.134 では左端のアイコン列に移動し、隣のボタンとサイズを揃えました。固定したアプリは先頭に表示されます。
|
||||
- 管理画面にフィールドエディター、P2P ファイル転送・動画の同時視聴・TSMusicBot の設定フォーム、各リポジトリへのリンクを追加しました。
|
||||
- ストアでは表示情報の差異を許容し、SHA-256、パッケージ形式、インストールや実行に必要な項目を検証します。
|
||||
- 開発ガイドと Agent Skill に、アプリ入口の配置、設定項目、公開プラグインに必要な独立した HTTPS オリジンを記載しました。
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- WebSocket 再生で Opus のチャンネル情報と実際のパケット長を扱うよう修正しました。WebRTC の下りミックスでもステレオを維持します。関連 #54。
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
|
||||
|
||||
Стабильный выпуск: [изменения v0.3.1](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Воспроизведение и диагностика звука, уровни шумоподавления, ярлыки плагинов и личные приглашения.
|
||||
Стабильный выпуск: [изменения v0.3.2](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Восстановление темы, библиотека приложений и формы настройки плагинов.
|
||||
|
||||
|
||||
|
||||
@@ -276,6 +276,14 @@ relay.example.com {
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- Сторонние темы могут оформлять декоративные элементы. WebSpeak управляет восстановлением и разрешениями, чтобы пользователи могли вернуться к встроенной теме. Спасибо ph1gros за определение TS3 и сведения о совместимости (#46), а OddTurtleHead за оформление интерфейса и восстановление темы (#57).
|
||||
- Дневная, ночная и ILLUSIA открывают библиотеку из верхней панели. В KAAK 3.1.134 кнопка расположена на крайней левой панели и совпадает по размеру с соседними. Закреплённые приложения отображаются первыми.
|
||||
- В управлении плагинами появились редактор полей, формы для передачи файлов P2P, совместного просмотра и TSMusicBot, а также ссылки на репозитории.
|
||||
- Магазины допускают различия в отображаемых данных. SHA-256, формат пакета и поля, необходимые для установки или запуска, проверяются.
|
||||
- Руководства и Agent Skills обновлены с учётом размещения кнопки, полей настройки и отдельного HTTPS-адреса для публичных плагинов.
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- При воспроизведении через WebSocket учитываются каналы Opus и фактическая длительность пакета. Микшер WebRTC сохраняет стерео. См. #54.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
|
||||
|
||||
稳定版:[v0.3.1 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 语音播放与诊断、降噪选项、插件快捷入口和私密邀请。
|
||||
稳定版:[v0.3.2 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 皮肤恢复入口、应用库布局和插件配置表单。
|
||||
|
||||
|
||||
|
||||
@@ -78,6 +78,8 @@ WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语
|
||||
<details>
|
||||
<summary>展开日间、夜间、ILLUSIA、KAAK 与 Discord Voice 皮肤预览</summary>
|
||||
|
||||
以下截图拍摄于已连接的 TeamSpeak 语音房间。
|
||||
|
||||
| 日间 | 夜间 |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
@@ -118,7 +120,7 @@ docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
升级在宿主机执行。管理控制台在 Docker 部署中只能检查新版本,不能从容器内部替换镜像:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
@@ -126,12 +128,16 @@ docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
|
||||
不要执行 `docker compose down -v`,否则会删除 `webspeak-data` volume,包括数据库和管理员设置。
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
|
||||
|
||||
Linux x64 发布包(已按官方 `build-release.yml` 产物形态验证)可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`SHA256SUMS.txt` 只是 SHA-256 校验和,不是数字签名。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Windows 发布包可以检查版本,但控制台应用更新尚未经真实 Windows 环境验证,因此已禁用,请下载新包后手动替换。Linux arm64 发布包可以检查版本,但由于原地替换尚未在真实 arm64 硬件验证,控制台应用已禁用;请下载新版发布包后手动替换。Docker 和源码运行不能在控制台应用更新。
|
||||
|
||||
控制台安装仅限前台运行的 Linux x64 发布包。通过 systemd、PM2 或 Supervisor 托管的实例仍可检查版本和查看发行说明,但不能在控制台直接安装。请停止服务,替换新发布包中的程序文件后再启动,并保留 `data/`、`config.json` 和 `certs/`。升级助手即使以独立子进程启动,也仍受服务管理器控制。
|
||||
|
||||
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
|
||||
|
||||
### 源码运行
|
||||
@@ -149,6 +155,8 @@ npm start
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
源码运行时,管理控制台可以检查新的正式版本,但目录中没有捆绑的 Node.js 运行时,因此不能一键应用更新。请查看发行说明后拉取源码并重新构建;控制台不会下载或替换源码目录中的文件。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
@@ -362,6 +370,14 @@ relay.example.com {
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- 第三方皮肤可以为宿主装饰添加样式。恢复入口和授权弹窗由宿主管理,应用皮肤后仍能切回内置皮肤。感谢 ph1gros 对 TS3 版本识别及兼容性文档的贡献(#46),以及 OddTurtleHead 对宿主装饰和皮肤恢复的贡献(#57)。
|
||||
- 日间、夜间和 ILLUSIA 的应用库在顶部工具栏展开。KAAK 3.1.134 将应用库放入最左侧图标栏,按钮与相邻控件对齐。固定应用排在列表前面。
|
||||
- 插件后台提供字段编辑器,以及 P2P 文件传输、视频同看和 TSMusicBot 的配置表单。插件页面可以打开对应仓库。
|
||||
- 皮肤和插件商店允许目录与包内的展示信息有所不同,继续校验 SHA-256、包格式和影响安装或运行的字段。
|
||||
- 更新皮肤及插件开发指南和 Agent Skill,说明入口布局、配置字段和公网插件所需的独立 HTTPS 地址。
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- 修复 WebSocket 播放丢失 Opus 声道信息、固定按 20 毫秒处理音频包的问题,并保留 WebRTC 下行混音的立体声。关联 #54。
|
||||
|
||||
@@ -68,7 +68,7 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
|
||||
}
|
||||
```
|
||||
|
||||
`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、名称、版本、作者、许可证和最低应用版本一致。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。
|
||||
`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、版本和最低应用版本一致。商店展示 `skin.json` 中的名称、作者和许可证,安装后的实例皮肤展示归档清单中的值。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。
|
||||
|
||||
发布步骤:先构建并用客户端和服务端导入器验证最终归档;计算 SHA-256;提交源码、归档、许可证和 `skin.json`;为这个提交创建版本 tag;最后提交中央索引条目。后续更新只需在皮肤仓库发布新版本并更新默认分支的 `skin.json`,无需同步修改中央索引。安装时服务端重新检查索引及元数据,核对摘要并运行普通 `.wskin` 校验;校验失败不替换实例皮肤。同 ID 已安装且版本相同或更新时,不提供覆盖或降级操作。多个管理员同时修改实例皮肤时,过期的安装请求会被拒绝,需刷新后重试。
|
||||
|
||||
@@ -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 个字符。 |
|
||||
|
||||
@@ -218,7 +221,16 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s
|
||||
}
|
||||
```
|
||||
|
||||
当前可选宿主控件 ID:`home.connection-form`、`home.connection-status`、`home.visitor-count`、`home.server-announcement`、`home.social-links`、`home.identity-provider`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`、`voice.server-header`、`voice.server-banner`、`voice.server-switcher`、`voice.channel-tree`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。`home.identity-provider` 是通用身份提供方入口,需用 `options.identityProviderId` 和 `options.identityProviderLabel` 指定稳定提供方标识与显示名;宿主会把点击转交给应用代码的 `registerIdentityProviderAdapter` 分发接口,皮肤只能发起请求、不能注册适配器。当前没有 MyTS 适配器,所以 MyTS 入口仍提示开发中;这不代表已经实现登录认证。schema v3 会检查受保护控件所需权限:音频控件需 `audio.status.read`、`audio.microphone.control` 和 `audio.output.control`;聊天需 `chat.channel.read` 与 `chat.channel.send`;成员卡片始终需 `session.members.read` 和 `session.memberAvatars.read`;schema v3 可为成员卡片设置 `options.memberActions: true`,在非本人卡片上显示可信宿主成员操作入口(包含现有个人音量控件);也可为 `voice.channel-tree` 设置该选项,在非本人频道树成员行上启用右键菜单;菜单仍由 WebSpeak 宿主处理,皮肤不获得额外动作或数据接口。频道树还可单独设置 `options.memberDragDrop: true`,将非本人成员拖到另一频道行时复用 WebSpeak 现有移动成员操作;悬停和拖入高亮由皮肤样式控制,此选项默认关闭且只适用于频道树。成员卡片或性能卡片可设置 `options.screenShare: false`,同时隐藏共享 UI/指标并免除成员卡片所需的屏幕共享权限;默认成员共享操作仍需屏幕共享读取/控制权限;头像只在可信宿主控件内显示,不暴露给皮肤代码;屏幕共享播放器需 `voice.screenShare.read` 与 `voice.screenShare.control`;悄悄话控件需对应状态读取和控制权限;断开/连接控件需 `voice.disconnect`。既有 v2 包维持旧校验行为,`voice.screen-share-start` 仍像此前一样要求 `voice.screenShare.control`。该控件仅能放在语音页;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、噪声抑制、伴奏、离开状态、悄悄话、断开连接和屏幕共享动作;噪声抑制使用 `audio.toggleNoiseSuppression` 与 `audio.microphone.control`,伴奏使用 `audio.toggleAccompaniment` 与 `audio.output.control`。它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
|
||||
当前可选宿主控件 ID:`home.connection-form`、`home.connection-status`、`home.visitor-count`、`home.server-announcement`、`home.social-links`、`home.identity-provider`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`、`voice.plugin-launcher`、`voice.server-header`、`voice.server-banner`、`voice.server-switcher`、`voice.channel-tree`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。`home.identity-provider` 是通用身份提供方入口,需用 `options.identityProviderId` 和 `options.identityProviderLabel` 指定稳定提供方标识与显示名;宿主会把点击转交给应用代码的 `registerIdentityProviderAdapter` 分发接口,皮肤只能发起请求、不能注册适配器。当前没有 MyTS 适配器,所以 MyTS 入口仍提示开发中;这不代表已经实现登录认证。schema v3 会检查受保护控件所需权限:音频控件需 `audio.status.read`、`audio.microphone.control` 和 `audio.output.control`;聊天需 `chat.channel.read` 与 `chat.channel.send`;成员卡片始终需 `session.members.read` 和 `session.memberAvatars.read`;schema v3 可为成员卡片设置 `options.memberActions: true`,在非本人卡片上显示可信宿主成员操作入口(包含现有个人音量控件);也可为 `voice.channel-tree` 设置该选项,在非本人频道树成员行上启用右键菜单;菜单仍由 WebSpeak 宿主处理,皮肤不获得额外动作或数据接口。频道树还可单独设置 `options.memberDragDrop: true`,将非本人成员拖到另一频道行时复用 WebSpeak 现有移动成员操作;悬停和拖入高亮由皮肤样式控制,此选项默认关闭且只适用于频道树。成员卡片或性能卡片可设置 `options.screenShare: false`,同时隐藏共享 UI/指标并免除成员卡片所需的屏幕共享权限;默认成员共享操作仍需屏幕共享读取/控制权限;头像只在可信宿主控件内显示,不暴露给皮肤代码;屏幕共享播放器需 `voice.screenShare.read` 与 `voice.screenShare.control`;悄悄话控件需对应状态读取和控制权限;断开/连接控件需 `voice.disconnect`。既有 v2 包维持旧校验行为,`voice.screen-share-start` 仍像此前一样要求 `voice.screenShare.control`。该控件仅能放在语音页;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、噪声抑制、伴奏、离开状态、悄悄话、断开连接和屏幕共享动作;噪声抑制使用 `audio.toggleNoiseSuppression` 与 `audio.microphone.control`,伴奏使用 `audio.toggleAccompaniment` 与 `audio.output.control`。它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
|
||||
|
||||
从 WebSpeak 0.3.2 起,完整语音布局可以放置宿主小组件 `voice.plugin-launcher`。组件 schema v3 支持 `options.pluginPresentation`,省略时使用 `dialog`。可选 `drawer-below` 在按钮下方展开,或用 `drawer-side` 在侧栏内展开。固定应用排在列表前面,未固定的可用应用仍可搜索。WebSpeak 管理插件授权、可用性与应用窗口,皮肤只声明入口的位置和呈现方式。
|
||||
|
||||
```json
|
||||
{ "widget": "voice.plugin-launcher", "part": "plugin-launcher", "options": { "pluginPresentation": "drawer-side" } }
|
||||
```
|
||||
|
||||
皮肤可用 `voice.plugin-launcher`、`voice.plugin-drawer` 和 `voice.plugin-drawer.app` 调整外观。没有放置此组件的完整语音布局会获得默认应用库入口。可为 `home.social-links` 设置 `options.communityLinks: false`,只保留管理控制台入口。
|
||||
|
||||
|
||||
首页访客统计使用公开宿主控件 `home.visitor-count`:它展示当前访客序号与累计访客数,文本跟随当前界面语言,并在统计数据尚不可用时隐藏;不需声明权限。该控件复用 WebSpeak 日间首页的同一结构与基础样式,皮肤通过包内 CSS 定位,不需要自建统计逻辑。组件节点可用稳定的 `part` 名称(例如 `visitor-stats`)控制位置;内部 `home.visitors`、`home.visitors.orbit`、`home.visitors.icon`、`home.visitors.label`、`home.visitors.divider`、`home.visitors.total` 和 `home.visitors.spark` 是稳定样式部件。控件只能放在 `home` 页面。
|
||||
|
||||
@@ -388,12 +400,14 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| --- | --- |
|
||||
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
|
||||
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.visitors.orbit`、`home.visitors.icon`、`home.visitors.label`、`home.visitors.divider`、`home.visitors.total`、`home.visitors.spark`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.server-history.item`、`home.server-history.select`、`home.server-history.favorite-toggle`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-provider.button`、`home.identity-provider.label`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.server-announcement`、`home.server-announcement.title`、`home.server-announcement.body`、`home.social-links`、`home.connection-status`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.plugin-toolbar`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.plugin-toolbar`、`voice.plugin-launcher`、`voice.plugin-drawer`、`voice.plugin-drawer.app`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| KOOK 频道树与服务器切换 | `voice.server-switcher`、`voice.server-switcher.trigger`、`voice.server-switcher.menu`、`voice.server-switcher.item`、`voice.server-switcher.icon`、`voice.server-switcher.label`、`voice.server-switcher.current`、`voice.server-switcher.empty`、`voice.channel-tree.list`、`voice.channel-tree.empty`、`voice.channel-tree.node`、`voice.channel-tree.line`、`voice.channel-tree.expander`、`voice.channel-tree.row`、`voice.channel-tree.icon`、`voice.channel-tree.join-hint`、`voice.channel-tree.name`、`voice.channel-tree.count`、`voice.channel-tree.branch`、`voice.channel-tree.member`、`voice.channel-tree.avatar`、`voice.channel-tree.member-name`、`voice.channel-tree.member-muted`、`voice.channel-tree.member-screen-share`、`voice.channel-tree.member-speaking`、`voice.channel-tree.member-away` |
|
||||
| 快速服务器 | `voice.favorite-servers.rail`、`voice.favorite-servers.rail.list`、`voice.favorite-servers.rail.item`、`voice.favorite-servers.server`、`voice.favorite-servers.avatar`、`voice.favorite-servers.tooltip`、`voice.favorite-servers.favorite-toggle`、`voice.favorite-servers.add`、`voice.favorite-servers.strip`、`voice.favorite-servers.strip.item`、`voice.favorite-servers.strip.server`、`voice.favorite-servers.strip.favorite-toggle`、`voice.favorite-servers.strip.add`、`voice.favorite-servers.switch-status`、`voice.favorite-servers.current-toggle`、`voice.favorite-servers.dialog-backdrop`、`voice.favorite-servers.dialog`、`voice.favorite-servers.dialog.header`、`voice.favorite-servers.dialog.close`、`voice.favorite-servers.dialog.form`、`voice.favorite-servers.dialog.field`、`voice.favorite-servers.dialog.input`、`voice.favorite-servers.dialog.target`、`voice.favorite-servers.dialog.hint`、`voice.favorite-servers.dialog.actions`、`voice.favorite-servers.dialog.cancel`、`voice.favorite-servers.dialog.submit` |
|
||||
| 聊天与菜单 | `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`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
|
||||
| 首页页脚拆分 | `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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
|
||||
@@ -415,6 +429,213 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
}
|
||||
```
|
||||
|
||||
### 宿主外壳主题化(v3 / v4 开放皮肤)
|
||||
|
||||
应用库窗口、水印、非关键提示与空状态装饰绘制在皮肤根之外;插件入口保留在语音工作区顶部工具栏。宿主提供第二个文档级作用域来主题化这些部件:
|
||||
|
||||
- 皮肤激活时,宿主在 `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 开放皮肤生效。
|
||||
- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。
|
||||
- 自定义变量仍必须使用 `--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` | 语音工作区顶部的插件按钮(颜色、尺寸、圆角、背景图均可改;也可声明式隐藏) |
|
||||
| `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 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
|
||||
|
||||
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`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
|
||||
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
|
||||
|
||||
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
|
||||
|
||||
恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
|
||||
|
||||
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
|
||||
|
||||
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
|
||||
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
|
||||
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 |
|
||||
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
|
||||
|
||||
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
|
||||
|
||||
- v3 `components.json` 组件根:`skin.<page>.<componentId>`。
|
||||
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
|
||||
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
|
||||
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;同一页面内,当前位置不遮挡时不会为了回到默认角落而移动(默认角落“看起来空”可能只是被模态对话框的遮罩或提示条暂时挡住);进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,并在默认角落和当前位置都空闲(鼠标也不在那里)时回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
|
||||
|
||||
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
| --- | --- |
|
||||
| `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 |
|
||||
| `--skin-recovery-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 |
|
||||
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
|
||||
| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
|
||||
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
|
||||
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 |
|
||||
| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
|
||||
|
||||
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
|
||||
|
||||
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停、键盘聚焦或点按/轻触 ◈ 时展开为完整按钮;点按展开会保持到焦点离开胶囊、在胶囊外按下指针或按 Escape。新皮肤激活后、胶囊首次成功停靠起的约 5 秒内始终显示完整胶囊(从停靠时刻开始计时,皮肤加载慢也不会提前收起),避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
#### 受保护控件的主题化
|
||||
|
||||
28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
|
||||
|
||||
**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`(字面值)、`outline` 等纯视觉属性都可以写:
|
||||
|
||||
```css
|
||||
[data-ws-part="voice.audio-dock.microphone"],
|
||||
[data-ws-part="auth.password.dialog"],
|
||||
[data-ws-part="home.footer.clear"] {
|
||||
color: var(--skin-ink);
|
||||
background: linear-gradient(135deg, #0f172a, #1e3a5f);
|
||||
border: 2px solid var(--skin-accent);
|
||||
border-radius: 16px;
|
||||
font: 600 14px/1.4 Tahoma, "Segoe UI", sans-serif;
|
||||
padding: 10px 16px;
|
||||
min-width: 56px;
|
||||
min-height: 56px;
|
||||
box-shadow: 0 8px 24px #0006;
|
||||
}
|
||||
```
|
||||
|
||||
以下规则仍会被拒绝,因为它们会隐藏、禁用或把控件移出视口:`display:none`、`visibility:hidden/collapse`、`opacity:0`、`pointer-events:none`、使 `clip`/`clip-path`/`mask` 完全裁掉内容、`transform`/`scale` 缩到 0、`inset`/`top`/`left`/`margin` 等把控件推到视口外,以及在这些隐藏/移动属性上使用 `var()`/`attr()`。`margin` 仍算移动属性,所以 `margin: var(--skin-gap)` 会被拒绝;普通的小 `margin` 数值可以写。自定义变量仍然只能使用 `--skin-` 前缀。
|
||||
|
||||
个别受保护部件的子元素(例如音频面板和音频设置里的 `<input type="range">`)由 Vue 写入内联 `style`;要给滑轨本身换肤,用视觉属性的 `!important` 覆盖即可,受保护的外壳不受影响。
|
||||
|
||||
**宿主自有的受保护控件。** `host.recovery`、`app.skin-load-recovery` 横幅和授权对话框在闭合 Shadow DOM 内,皮肤 CSS 不能命中。宿主提供一组统一的令牌;皮肤把变量写在活动皮肤根(`:root`,编译后就是皮肤根)上即可,恢复胶囊也接受写在锚点或其祖先上的值:
|
||||
|
||||
| 控件 | 每部件前缀 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 |
|
||||
| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠。令牌取自横幅出现时的**活动**皮肤:加载失败后宿主会退回内置皮肤(内置皮肤不声明令牌),所以失败皮肤自己的值通常不会作用在自己的横幅上,横幅保持默认琥珀色 |
|
||||
| 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 |
|
||||
|
||||
每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-accent: #47dcc4;
|
||||
--skin-host-background: #0b1418;
|
||||
--skin-host-foreground: #edf8f5;
|
||||
--skin-host-border: #2a5a54;
|
||||
--skin-host-radius: 10px;
|
||||
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-size: medium;
|
||||
|
||||
/* 只覆盖恢复胶囊,其他宿主控件继续使用全局值 */
|
||||
--skin-recovery-background: #102030;
|
||||
}
|
||||
```
|
||||
|
||||
宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式、窗口尺寸变化让 `@media` 里的令牌生效时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
|
||||
|
||||
- 背景强制不透明(alpha 视为 1)。
|
||||
- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
|
||||
- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
|
||||
- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
|
||||
- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`,或带有编译器给皮肤字体加的 `ws-` 作用域前缀(包括放在暂未生效的 `@media` 里的字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
|
||||
- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
|
||||
- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白;如果黑白两种文字在强调色上都达不到 4.5,这组颜色同样整体回退到宿主默认。
|
||||
- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
|
||||
|
||||
`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。
|
||||
|
||||
`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` | 顶部工具栏插件按钮图标 |
|
||||
| `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"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `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/<文件名>` 的位图相对路径。 |
|
||||
| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 |
|
||||
|
||||
图标文件约定:仅 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`,只隐藏它不会破坏恢复路径。
|
||||
|
||||
### 令牌、字体、动效和图片
|
||||
|
||||
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
|
||||
@@ -477,28 +698,44 @@ 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` 才是它们的开启开关。
|
||||
|
||||
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
|
||||
关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名;受保护控件上的 `filter` / `-webkit-filter`、`clip` 与 `content-visibility` 同样只接受字面值,不能用 `var()` / `attr()`(否则变量可以绕过上面的隐藏检查),其他部件不受影响。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
This example turns the Discord-inspired voice interface into a portable WebSpeak `open-skin` v3 package. Its page structure is declared in `components.json`; its palette and layout are in `skin.css`; localized skin copy lives in `content.json`.
|
||||
|
||||
The independent distribution repository is [Huddle-Up-Forge/webspeak-skin-discord-voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice). It is the first entry in the [WebSpeak skin store index](https://github.com/Huddle-Up-Forge/webspeak-skins). Administrators can install it from **Skins → Skin store**, then manage availability and the instance default under **Instance skins**. Version 1.0.11 requires WebSpeak 0.2.8 with the current public skin API.
|
||||
The independent distribution repository is [Huddle-Up-Forge/webspeak-skin-discord-voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice). It is the first entry in the [WebSpeak skin store index](https://github.com/Huddle-Up-Forge/webspeak-skins). Administrators can install it from **Skins → Skin store**, then manage availability and the instance default under **Instance skins**. Version 1.0.12 requires WebSpeak 0.3.2 with the current public skin API.
|
||||
|
||||
The package uses WebSpeak's public TeamSpeak widgets for channel navigation, member cards, chat, audio controls, screen sharing, performance status, server switching and invite links. That keeps connection logic and trusted actions in WebSpeak while the skin controls the visible layout. The Discord visual language and color palette are retained, while host-owned controls keep their supported behavior and accessibility.
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ The owner authorized inspection of the first two voice rooms in the KOOK server.
|
||||
|
||||
## Returning to the workspace
|
||||
|
||||
KAAK 3.1.131 uses the normal connection home on every visit. It no longer opts into persistent workspace entry. The connection-status and explicit reconnect controls remain available inside the voice workspace.
|
||||
KAAK 3.1.132 uses the normal connection home on every visit. It no longer opts into persistent workspace entry. The connection-status and explicit reconnect controls remain available inside the voice workspace.
|
||||
|
||||
The permission-gated `voice.connection-status` host widget provides the connection state, nickname and explicit reconnect button beside server navigation at desktop and narrow widths. Open-mode server switching and adding servers reuse the host connection flow, including saved-password lookup and trusted password prompts; fixed mode retains its restrictions. All KAAK layout and styling remain in the package.
|
||||
|
||||
@@ -52,3 +52,5 @@ Member cards are rendered by WebSpeak's trusted `voice.member-cards` widget. It
|
||||
- Shared format and safety rules: [SKIN_DEVELOPMENT.md](../SKIN_DEVELOPMENT.md)
|
||||
|
||||
KAAK is included in the public skin selector and its `.wskin` archive is also available as a standalone package. After changing the source, run `npm run skin:kaak:build` to rebuild both copies, then run the package tests and verify the connection page, approval, denial, revoke, desktop, and narrow-screen paths in the local browser. The connected voice surface can be verified when a TeamSpeak session is available.
|
||||
|
||||
KAAK 3.1.133 places the application library icon in the server rail, alongside the skin and language controls. It opens the drawer beside the rail.
|
||||
@@ -263,6 +263,7 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{"widget":"voice.plugin-launcher","part":"plugin-launcher","options":{"pluginPresentation":"drawer-side"}},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-sidebar-scroll",
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.discord-voice",
|
||||
"name": "Discord Voice",
|
||||
"version": "1.0.11",
|
||||
"version": "1.0.12",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A Discord-inspired dark voice workspace built with WebSpeak's portable open-skin interface.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"minAppVersion": "0.2.8"
|
||||
"minAppVersion": "0.3.2"
|
||||
}
|
||||
@@ -2149,3 +2149,20 @@
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] {
|
||||
flex: 0 0 auto;
|
||||
padding: 4px 8px;
|
||||
--skin-plugin-app-accent: #c9cdfc;
|
||||
}
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"] > button {
|
||||
color: var(--skin-plugin-app-accent);
|
||||
}
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer"] {
|
||||
background: #242529;
|
||||
color: #e8e9ed;
|
||||
border-color: #3f4148;
|
||||
}
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer.app"]:hover {
|
||||
background: #383a44;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"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"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
@@ -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, protected-control theming, declarative hiding and bitmap icon overrides.",
|
||||
"entry": "skin.css",
|
||||
"chrome": "chrome.json",
|
||||
"minAppVersion": "0.3.2"
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/* 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;
|
||||
|
||||
/* Host-owned protected controls: one global set, per-part overrides below. */
|
||||
--skin-host-accent: #1d4f9c;
|
||||
--skin-host-background: #ffffff;
|
||||
--skin-host-foreground: #141414;
|
||||
--skin-host-border: #9db6b2;
|
||||
--skin-host-radius: 10px;
|
||||
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-size: medium;
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-border: #9db6b2;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-load-recovery-accent: #b45309;
|
||||
--skin-load-recovery-background: #fff7ed;
|
||||
--skin-load-recovery-foreground: #7c2d12;
|
||||
--skin-permission-accent: #1d4f9c;
|
||||
--skin-permission-background: #ffffff;
|
||||
--skin-permission-foreground: #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;
|
||||
/* Fold the trusted recovery capsule into the audio dock (chrome.json#slots). */
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-recovery-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-recovery-size: small;
|
||||
}
|
||||
|
||||
/* --- Protected app-DOM controls: purely visual theming is allowed --- */
|
||||
[data-ws-part="voice.audio-dock.microphone"] button,
|
||||
[data-ws-part="voice.audio-dock.output"] button,
|
||||
[data-ws-part="voice.connection-status.reconnect"],
|
||||
[data-ws-part="home.footer.clear"] {
|
||||
color: #141414;
|
||||
background: linear-gradient(180deg, #ffffff, #eef3fa);
|
||||
border: 1px solid var(--skin-accent);
|
||||
border-radius: 8px;
|
||||
font-family: Tahoma, "Segoe UI", sans-serif;
|
||||
font-size: 12px;
|
||||
padding: 8px 12px;
|
||||
min-height: 44px;
|
||||
box-shadow: 0 2px 6px #1d4f9c22;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone"] button:hover,
|
||||
[data-ws-part="voice.audio-dock.output"] button:hover,
|
||||
[data-ws-part="voice.connection-status.reconnect"]:hover,
|
||||
[data-ws-part="home.footer.clear"]:hover {
|
||||
background: #e7eefb;
|
||||
}
|
||||
|
||||
[data-ws-part="auth.password.dialog"],
|
||||
[data-ws-part="voice.audio-settings"] {
|
||||
background: #ffffff;
|
||||
border: 2px solid var(--skin-accent);
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 18px 48px #1d4f9c33;
|
||||
}
|
||||
|
||||
[data-ws-part="auth.password.dialog"] h2,
|
||||
[data-ws-part="voice.audio-settings"] h2 {
|
||||
color: var(--skin-accent);
|
||||
letter-spacing: .01em;
|
||||
}
|
||||
|
||||
/* --- 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;
|
||||
}
|
||||
@@ -582,9 +582,11 @@
|
||||
"widget": "app.language-switcher",
|
||||
"part": "rail-language"
|
||||
},
|
||||
{"widget":"voice.plugin-launcher","part":"plugin-launcher","options":{"pluginPresentation":"drawer-side"}},
|
||||
{
|
||||
"widget": "home.social-links",
|
||||
"part": "rail-links"
|
||||
"part": "rail-links",
|
||||
"options": { "communityLinks": false }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.kaak-voice",
|
||||
"name": "KAAK",
|
||||
"version": "3.1.131",
|
||||
"version": "3.1.134",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"minAppVersion": "0.2.8"
|
||||
"minAppVersion": "0.3.2"
|
||||
}
|
||||
@@ -4700,7 +4700,7 @@
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-switcher,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-trigger,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-switcher,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-trigger { width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-trigger { width: 44px; min-width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a { transition: none; }
|
||||
@@ -4715,3 +4715,53 @@
|
||||
height: auto;
|
||||
max-height: calc(100dvh - 32px);
|
||||
}
|
||||
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] {
|
||||
order: 6;
|
||||
flex: 0 0 var(--skin-kaak-app-button-size);
|
||||
width: var(--skin-kaak-app-button-size);
|
||||
--skin-kaak-app-button-size: 58px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
width: var(--skin-kaak-app-button-size);
|
||||
height: var(--skin-kaak-app-button-size);
|
||||
border: 1px solid #3d4048;
|
||||
border-radius: 18px;
|
||||
color: #d1d5dc;
|
||||
background: var(--skin-kaak-rail-item-bg);
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button svg {
|
||||
flex: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button > span {
|
||||
display: none;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button:is(:hover, :focus-visible, [aria-expanded="true"]) {
|
||||
border-color: #699b32;
|
||||
color: #a8ed50;
|
||||
background: #2b3524;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer"] {
|
||||
position: fixed;
|
||||
inset: auto auto max(76px, env(safe-area-inset-bottom)) 86px;
|
||||
box-sizing: border-box;
|
||||
width: min(280px, calc(100vw - 98px));
|
||||
background: #24272a;
|
||||
color: #e8e9ed;
|
||||
border-color: #3d4048;
|
||||
box-shadow: 0 12px 32px #0006;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer.app"]:is(:hover, :focus-visible) {
|
||||
background: #2b3524;
|
||||
}
|
||||
@media (max-height: 620px) {
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] { --skin-kaak-app-button-size: 44px; }
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button { border-radius: 14px; }
|
||||
}
|
||||
|
Before Width: | Height: | Size: 171 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 161 KiB After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 261 KiB After Width: | Height: | Size: 1.6 MiB |
|
Before Width: | Height: | Size: 171 KiB After Width: | Height: | Size: 63 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 65 KiB |
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.2",
|
||||
"dependencies": {
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^4.21.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.2",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.2",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -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/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.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-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/call-media-session.test.ts",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env sh
|
||||
# WebSpeak official release launcher.
|
||||
#
|
||||
# This file is the single source of truth for the launcher shipped in release
|
||||
# packages: .github/workflows/build-release.yml copies it verbatim, and the
|
||||
# self-update pre-swap installer copies the same file from the staged package.
|
||||
# Keep it a plain POSIX shell script: it must be able to repair an interrupted
|
||||
# code swap before Node (dist/index.js) is available at all.
|
||||
set -eu
|
||||
|
||||
cd -- "$(dirname -- "$0")"
|
||||
|
||||
# Mirrors src/index.ts: a custom data directory is the only supported override.
|
||||
data_dir="${WEBSPEAK_DATA_DIR:-$PWD/data}"
|
||||
backups="$data_dir/updates/backups"
|
||||
|
||||
# Only executable code is swapped by the updater. data/, config.json, certs/,
|
||||
# identities, skins and plugins are deliberately never listed here.
|
||||
code_entries="dist web/dist node_modules runtime package.json package-lock.json README.md LICENSE config.example.json start-webspeak.cmd"
|
||||
required_entries="dist/index.js web/dist/index.html node_modules package.json runtime/node"
|
||||
|
||||
code_missing() {
|
||||
for entry in $required_entries; do
|
||||
if [ ! -e "$entry" ]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A backup can only repair an install if it recorded a swap and still holds
|
||||
# every entry needed to boot. Partial/legacy backups must be skipped.
|
||||
backup_is_complete() {
|
||||
[ -f "$1/.webspeak-swap.json" ] || return 1
|
||||
for entry in $required_entries; do
|
||||
[ -e "$1/$entry" ] || return 1
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
# During the first phase of a swap, only some old entries have been moved.
|
||||
# The rest still live at the install root. The current task can be recovered
|
||||
# from that union, including a kill between rename and manifest persistence.
|
||||
# Never combine a stale task's partial backup with this install.
|
||||
task_backup_can_repair() {
|
||||
[ -f "$1/.webspeak-swap.json" ] || return 1
|
||||
for entry in $required_entries; do
|
||||
if [ ! -e "$1/$entry" ] && [ ! -e "$entry" ]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
restore_from_backup() {
|
||||
backup="$1"
|
||||
# Move whatever partial new code the interrupted swap left in the install
|
||||
# root aside, so a later restore never mistakes it for the old tree.
|
||||
for entry in $code_entries; do
|
||||
if [ -e "$entry" ] && [ -e "$backup/$entry" ]; then
|
||||
rejected="$backup/rejected/$entry"
|
||||
rejected_parent="${rejected%/*}"
|
||||
mkdir -p "$rejected_parent"
|
||||
if [ -e "$rejected" ]; then
|
||||
rm -rf -- "$entry"
|
||||
else
|
||||
mv -- "$entry" "$rejected"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
# Put back every complete entry recorded by the swap manifest.
|
||||
for entry in $code_entries; do
|
||||
if [ ! -e "$entry" ] && [ -e "$backup/$entry" ]; then
|
||||
parent="${entry%/*}"
|
||||
if [ "$parent" != "$entry" ]; then
|
||||
mkdir -p "$parent"
|
||||
fi
|
||||
mv -- "$backup/$entry" "$entry"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
if code_missing; then
|
||||
restore_backup=""
|
||||
|
||||
# The interrupted task is the source of truth: backups/<task.id> holds the
|
||||
# exact version that was running before the swap. A successful earlier
|
||||
# update leaves its backup behind (M1 does not clean it up), so picking the
|
||||
# first or alphabetically smallest backup can resurrect a much older build.
|
||||
state_file="$data_dir/updates/state.json"
|
||||
task_id=""
|
||||
if [ -f "$state_file" ]; then
|
||||
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
fi
|
||||
# Task ids are generated as upd_<base36>_<hex>. Reject anything else so a
|
||||
# tampered state.json cannot become a path traversal or a glob pattern.
|
||||
case "$task_id" in
|
||||
""|*[!A-Za-z0-9_-]*) task_id="" ;;
|
||||
esac
|
||||
if [ -n "$task_id" ]; then
|
||||
candidate="$backups/$task_id"
|
||||
if task_backup_can_repair "$candidate"; then
|
||||
restore_backup="$candidate"
|
||||
fi
|
||||
fi
|
||||
|
||||
# No usable task backup (e.g. state.json was lost): use the most recently
|
||||
# modified complete backup rather than whichever name happens to sort first.
|
||||
if [ -z "$restore_backup" ]; then
|
||||
for manifest in "$backups"/*/.webspeak-swap.json; do
|
||||
[ -f "$manifest" ] || continue
|
||||
backup="${manifest%/.webspeak-swap.json}"
|
||||
backup_is_complete "$backup" || continue
|
||||
if [ -z "$restore_backup" ] || [ "$backup" -nt "$restore_backup" ]; then
|
||||
restore_backup="$backup"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [ -z "$restore_backup" ]; then
|
||||
echo "WebSpeak update was interrupted and automatic recovery from $backups failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
restore_from_backup "$restore_backup"
|
||||
if code_missing; then
|
||||
echo "WebSpeak update was interrupted and automatic recovery from $restore_backup failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
@@ -12,6 +12,7 @@ import { createPluginAdminRouter } from "../plugins/admin-router.js";
|
||||
import type { PluginRegistry } from "../plugins/registry.js";
|
||||
import type { PluginStore } from "../plugins/store.js";
|
||||
import type { PluginRuntime } from "../plugins/runtime.js";
|
||||
import { UpdateError, type UpdateService } from "../updater/update-service.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
@@ -45,6 +46,9 @@ export interface AdminRouterOptions {
|
||||
pluginRegistry?: PluginRegistry;
|
||||
pluginStore?: PluginStore;
|
||||
pluginRuntime?: PluginRuntime;
|
||||
updateService?: UpdateService;
|
||||
/** Stops the current process after the update response has been flushed. */
|
||||
restartAfterUpdate?: () => void;
|
||||
startedAt: number;
|
||||
clientIp?: (request: Request) => string;
|
||||
}
|
||||
@@ -414,6 +418,63 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/update", (_request, response) => {
|
||||
if (!options.updateService) {
|
||||
response.json({
|
||||
currentVersion: options.version ?? "0.0.0",
|
||||
deployment: {
|
||||
mode: "source",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
applyAllowed: false,
|
||||
reasonCode: "UPDATE_UNAVAILABLE",
|
||||
upgradePath: "source",
|
||||
},
|
||||
task: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
response.json(options.updateService.getStatus());
|
||||
});
|
||||
|
||||
router.post("/update/check", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
|
||||
if (!options.updateService) {
|
||||
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
response.json(await options.updateService.checkForUpdates());
|
||||
} catch (error: unknown) {
|
||||
sendUpdateError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/update/apply", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
if (!options.updateService) {
|
||||
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
if (!options.restartAfterUpdate) {
|
||||
response.status(503).json({ ok: false, code: "UPDATE_RESTART_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
const version = readString(body, "version", 32);
|
||||
const confirmVersion = readString(body, "confirmVersion", 32);
|
||||
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
|
||||
const task = await options.updateService.applyUpdate(version, confirmVersion);
|
||||
options.service.database.addAudit("ADMIN_UPDATE_STARTED", { version });
|
||||
response.status(202).json({ ok: true, task });
|
||||
// Do not wait for the response to finish: a reverse proxy or a client
|
||||
// that disconnects early must not leave the restart runner waiting for
|
||||
// this process until its timeout expires.
|
||||
setTimeout(() => options.restartAfterUpdate?.(), 250).unref();
|
||||
} catch (error: unknown) {
|
||||
sendUpdateError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
|
||||
@@ -814,3 +875,15 @@ function sendAdminError(response: Response, error: unknown): void {
|
||||
}
|
||||
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
|
||||
}
|
||||
|
||||
function sendUpdateError(response: Response, error: unknown): void {
|
||||
if (error instanceof UpdateError) {
|
||||
response.status(error.statusCode).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
if (error instanceof AdminInputError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
response.status(500).json({ ok: false, code: "UPDATE_FAILED" });
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -134,8 +134,8 @@ export class SkinStore {
|
||||
const bytes = await this.download(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/${metadata.package.ref}/${metadata.package.path}`, MAX_PACK_BYTES);
|
||||
if (createHash("sha256").update(bytes).digest("hex") !== metadata.package.sha256) return fail("SKIN_STORE_CHECKSUM");
|
||||
const { manifest } = validateSkinArchive(bytes, input.id);
|
||||
for (const key of ["id", "name", "version", "author", "license", "minAppVersion"] as const) {
|
||||
if (manifest[key] !== metadata[key]) return fail("SKIN_STORE_PACKAGE_MISMATCH");
|
||||
if (manifest.version !== metadata.version || manifest.minAppVersion !== metadata.minAppVersion) {
|
||||
return fail("SKIN_STORE_PACKAGE_MISMATCH");
|
||||
}
|
||||
return registry.save(bytes, input.id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import express from "express";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminService } from "./admin-service.js";
|
||||
import { AdminSessionStore } from "./admin-session.js";
|
||||
import { createAdminRouter } from "./admin-router.js";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { UpdateError, type UpdateService } from "../updater/update-service.js";
|
||||
import type { UpdateCheckView, UpdateStatusView, UpdateTaskView } from "../shared/update.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
const statusView: UpdateStatusView = {
|
||||
currentVersion: "0.3.2",
|
||||
deployment: {
|
||||
mode: "release-package", platform: "linux", architecture: "x64",
|
||||
applyAllowed: true, reasonCode: null, upgradePath: "release-package",
|
||||
},
|
||||
task: null,
|
||||
};
|
||||
|
||||
const taskView: UpdateTaskView = {
|
||||
id: "upd_route_test", status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
};
|
||||
|
||||
const checkView: UpdateCheckView = {
|
||||
currentVersion: "0.3.2",
|
||||
releases: [{
|
||||
version: "0.4.0", tag: "v0.4.0", publishedAt: "2026-01-01T00:00:00.000Z",
|
||||
releaseUrl: "https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.4.0",
|
||||
assetName: "webspeak-webclient-v0.4.0-linux-x64.tar.gz", assetSize: 10,
|
||||
assetAvailable: true, hasChecksums: true, digest: null, canApply: true, blockedReason: null,
|
||||
}],
|
||||
};
|
||||
|
||||
interface Fixture {
|
||||
origin: string;
|
||||
service: AdminService;
|
||||
database: WebSpeakDatabase;
|
||||
applyCalls: Array<[string, string]>;
|
||||
restarted: () => boolean;
|
||||
login(): Promise<{ cookie: string; csrf: string }>;
|
||||
post(route: string, body: unknown, headers?: Record<string, string>): Promise<Response>;
|
||||
}
|
||||
|
||||
async function fixture(t: TestContext, options: { updateService?: boolean } = {}): Promise<Fixture> {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-routes-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "test.db"));
|
||||
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"), undefined, "0.3.2");
|
||||
await service.initialize();
|
||||
await service.changePassword("test-only-admin-password");
|
||||
const applyCalls: Array<[string, string]> = [];
|
||||
let restarted = false;
|
||||
const updateService = {
|
||||
getStatus: () => statusView,
|
||||
checkForUpdates: async () => checkView,
|
||||
applyUpdate: async (version: string, confirmVersion: string) => {
|
||||
applyCalls.push([version, confirmVersion]);
|
||||
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "confirmation mismatch");
|
||||
return taskView;
|
||||
},
|
||||
} as unknown as UpdateService;
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({
|
||||
service, sessions: new AdminSessionStore(), logger,
|
||||
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now(), version: "0.3.2",
|
||||
...(options.updateService === false ? {} : { updateService, restartAfterUpdate: () => { restarted = true; } }),
|
||||
}));
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise<void>((resolve) => server.once("listening", resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
t.after(async () => {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
database.close();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
const post = (route: string, body: unknown, headers: Record<string, string> = {}) => fetch(`${origin}/api/admin${route}`, {
|
||||
method: "POST", headers: { origin, "content-type": "application/json", ...headers }, body: JSON.stringify(body),
|
||||
});
|
||||
const login = async () => {
|
||||
const response = await post("/login", { username: "admin", password: "test-only-admin-password" });
|
||||
assert.equal(response.status, 200);
|
||||
const body = await response.json() as { csrfToken: string };
|
||||
return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
|
||||
};
|
||||
return { origin, service, database, applyCalls, restarted: () => restarted, login, post };
|
||||
}
|
||||
|
||||
test("update routes require an authenticated session", async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await fetch(`${f.origin}/api/admin/update`)).status, 401);
|
||||
assert.equal((await f.post("/update/check", {})).status, 401);
|
||||
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" })).status, 401);
|
||||
});
|
||||
|
||||
test("update routes reject missing CSRF tokens and cross-origin requests", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const noCsrf = await f.post("/update/check", {}, { cookie });
|
||||
assert.equal(noCsrf.status, 403);
|
||||
assert.equal((await noCsrf.json() as { code: string }).code, "CSRF_REJECTED");
|
||||
const crossOrigin = await fetch(`${f.origin}/api/admin/update/apply`, {
|
||||
method: "POST",
|
||||
headers: { origin: "https://evil.example", cookie, "x-csrf-token": csrf, "content-type": "application/json" },
|
||||
body: JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" }),
|
||||
});
|
||||
assert.equal(crossOrigin.status, 403);
|
||||
assert.equal((await crossOrigin.json() as { code: string }).code, "ORIGIN_REJECTED");
|
||||
const wrongType = await fetch(`${f.origin}/api/admin/update/check`, {
|
||||
method: "POST",
|
||||
headers: { origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "text/plain" },
|
||||
body: "{}",
|
||||
});
|
||||
assert.equal(wrongType.status, 415);
|
||||
assert.equal((await wrongType.json() as { code: string }).code, "JSON_REQUIRED");
|
||||
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 200);
|
||||
});
|
||||
|
||||
test("apply requires version and confirmVersion to match before touching the service", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.1" }, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(response.status, 400);
|
||||
assert.equal((await response.json() as { code: string }).code, "UPDATE_CONFIRMATION_REQUIRED");
|
||||
assert.deepEqual(f.applyCalls, []);
|
||||
const missing = await f.post("/update/apply", { version: "0.4.0" }, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(missing.status, 400);
|
||||
assert.deepEqual(f.applyCalls, []);
|
||||
});
|
||||
|
||||
test("a confirmed apply returns the task and stops the process after the response", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(response.status, 202);
|
||||
const body = await response.json() as { ok: boolean; task: UpdateTaskView };
|
||||
assert.equal(body.ok, true);
|
||||
assert.equal(body.task.id, "upd_route_test");
|
||||
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
|
||||
assert.ok(f.database.recentAudit(10).some((event) => event.event === "ADMIN_UPDATE_STARTED"));
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 400));
|
||||
assert.equal(f.restarted(), true);
|
||||
});
|
||||
|
||||
test("a client that disconnects before the response still schedules the restart", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const body = JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" });
|
||||
const url = new URL(`${f.origin}/api/admin/update/apply`);
|
||||
const request = http.request({
|
||||
hostname: url.hostname, port: url.port, path: url.pathname, method: "POST",
|
||||
headers: {
|
||||
origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "application/json",
|
||||
"content-length": Buffer.byteLength(body),
|
||||
},
|
||||
});
|
||||
request.on("error", () => { /* Expected once the socket is destroyed. */ });
|
||||
request.end(body);
|
||||
const deadline = Date.now() + 2_000;
|
||||
while (f.applyCalls.length === 0 && Date.now() < deadline) await new Promise<void>((resolve) => setTimeout(resolve, 20));
|
||||
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
|
||||
// Close the connection without consuming the response. The restart must not
|
||||
// depend on the response finish event.
|
||||
request.destroy();
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 700));
|
||||
assert.equal(f.restarted(), true);
|
||||
});
|
||||
|
||||
test("update status and check return the service projections", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
|
||||
assert.equal(status.status, 200);
|
||||
assert.deepEqual(await status.json(), statusView);
|
||||
const check = await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(check.status, 200);
|
||||
assert.deepEqual(await check.json(), checkView);
|
||||
});
|
||||
|
||||
test("deployments without an update service expose a read-only source status", async t => {
|
||||
const f = await fixture(t, { updateService: false });
|
||||
const { cookie, csrf } = await f.login();
|
||||
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
|
||||
assert.equal(status.status, 200);
|
||||
const body = await status.json() as UpdateStatusView;
|
||||
assert.equal(body.deployment.mode, "source");
|
||||
assert.equal(body.deployment.applyAllowed, false);
|
||||
assert.equal(body.deployment.reasonCode, "UPDATE_UNAVAILABLE");
|
||||
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 503);
|
||||
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf })).status, 503);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
|
||||
import { SkinRegistry } from "./admin/skin-registry.js";
|
||||
import { PluginRegistry } from "./plugins/registry.js";
|
||||
import { UpdateService } from "./updater/update-service.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -52,13 +53,42 @@ async function main() {
|
||||
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
|
||||
|
||||
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
|
||||
const updateService = new UpdateService({
|
||||
rootDir: ROOT_DIR,
|
||||
dataDir: DATA_DIR,
|
||||
currentVersion: APP_VERSION,
|
||||
logger,
|
||||
port: APP_PORT,
|
||||
https: hasCert,
|
||||
});
|
||||
updateService.initialize();
|
||||
|
||||
const webServer = createWebServer({
|
||||
let webServer: ReturnType<typeof createWebServer> | undefined;
|
||||
webServer = createWebServer({
|
||||
port: APP_PORT,
|
||||
version: APP_VERSION,
|
||||
logFile: path.join(LOG_DIR, "webspeak.log"),
|
||||
staticDir: STATIC_DIR,
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
updateService,
|
||||
restartAfterUpdate: () => {
|
||||
void (async () => {
|
||||
if (!updateService.runnerStillHealthy()) {
|
||||
// 202 already promised a restart, but the helper died before this
|
||||
// process left. Stay up and reconcile instead of reporting success
|
||||
// and silently abandoning the update.
|
||||
logger.warn("The restart runner is no longer healthy; keeping this process and reconciling the update state");
|
||||
try { updateService.initialize(); }
|
||||
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Update state could not be reconciled"); }
|
||||
return;
|
||||
}
|
||||
logger.info("Stopping for scheduled update");
|
||||
try { await webServer?.stop(); }
|
||||
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); }
|
||||
database.close();
|
||||
process.exit(0);
|
||||
})();
|
||||
},
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
|
||||
|
||||
@@ -72,7 +72,12 @@ export class PluginStore {
|
||||
pluginAssert(createHash("sha256").update(bytes).digest("hex") === metadata.descriptor.sha256, "PLUGIN_CHECKSUM");
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { throw new PluginError("PLUGIN_INVALID"); }
|
||||
const pack = parsePluginPackage(value); pluginAssert(JSON.stringify(pack.manifest) === JSON.stringify(metadata.manifest), "PLUGIN_PACKAGE_MISMATCH");
|
||||
const pack = parsePluginPackage(value);
|
||||
const actual = pack.manifest, listed = metadata.manifest;
|
||||
pluginAssert(actual.id === listed.id && actual.version === listed.version
|
||||
&& actual.client.entry === listed.client.entry && actual.server?.entry === listed.server?.entry
|
||||
&& actual.scopes.length === listed.scopes.length && actual.scopes.every(scope => listed.scopes.includes(scope)),
|
||||
"PLUGIN_PACKAGE_MISMATCH");
|
||||
return registry.install(pack, input.installedRevision as string | null);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ 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";
|
||||
import type { UpdateService } from "../updater/update-service.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -36,6 +38,8 @@ export interface WebServerOptions {
|
||||
logger: Logger;
|
||||
nextVisitorNumber?: () => number;
|
||||
visitorCount?: () => number;
|
||||
updateService?: UpdateService;
|
||||
restartAfterUpdate?: () => void;
|
||||
}
|
||||
|
||||
export interface WebServer {
|
||||
@@ -123,6 +127,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),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -297,6 +304,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
skinRegistry: options.skinRegistry,
|
||||
pluginRegistry: options.pluginRegistry,
|
||||
pluginRuntime,
|
||||
updateService: options.updateService,
|
||||
restartAfterUpdate: options.restartAfterUpdate,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
|
||||
@@ -93,6 +93,52 @@ const tsAdminOverview = object({
|
||||
});
|
||||
const savedTsAdminSettings = object({ ok: choice(true), settings: tsAdminSettings });
|
||||
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
|
||||
const updateStep = object({
|
||||
name: text,
|
||||
status: choice("running", "succeeded", "failed"),
|
||||
at: text,
|
||||
detail: optional(text),
|
||||
});
|
||||
const updateTask = object({
|
||||
id: text,
|
||||
status: choice("downloading", "verifying", "extracting", "staging", "restarting", "succeeded", "failed"),
|
||||
fromVersion: text,
|
||||
targetVersion: text,
|
||||
startedAt: text,
|
||||
updatedAt: text,
|
||||
finishedAt: nullable(text),
|
||||
errorCode: nullable(text),
|
||||
errorMessage: nullable(text),
|
||||
rolledBack: boolean,
|
||||
steps: array(updateStep),
|
||||
});
|
||||
const updateDeployment = object({
|
||||
mode: choice("docker", "release-package", "source"),
|
||||
platform: text,
|
||||
architecture: text,
|
||||
applyAllowed: boolean,
|
||||
reasonCode: nullable(text),
|
||||
upgradePath: choice("docker-compose", "release-package", "source"),
|
||||
});
|
||||
const updateStatus = object({
|
||||
currentVersion: text,
|
||||
deployment: updateDeployment,
|
||||
task: nullable(updateTask),
|
||||
});
|
||||
const updateRelease = object({
|
||||
version: text,
|
||||
tag: text,
|
||||
publishedAt: text,
|
||||
releaseUrl: text,
|
||||
assetName: text,
|
||||
assetSize: number,
|
||||
assetAvailable: boolean,
|
||||
hasChecksums: boolean,
|
||||
digest: nullable(text),
|
||||
canApply: boolean,
|
||||
blockedReason: nullable(text),
|
||||
});
|
||||
const updateCheck = object({ currentVersion: text, releases: array(updateRelease) });
|
||||
|
||||
export const adminResponses = {
|
||||
session(value: unknown) {
|
||||
@@ -127,6 +173,9 @@ export const adminResponses = {
|
||||
latencyMs: number, serverName: nullable(text), requiresPassword: boolean,
|
||||
packetLossPercent: optional(number), attempts: optional(number), successfulAttempts: optional(number), errorCode: optional(text),
|
||||
}),
|
||||
updateStatus,
|
||||
updateCheck,
|
||||
updateApplied: object({ ok: choice(true), task: updateTask }),
|
||||
};
|
||||
|
||||
export type AdminSettings = ReturnType<typeof settings>;
|
||||
@@ -135,3 +184,7 @@ export type AdminSession = ReturnType<typeof session>;
|
||||
export type ManagedInvite = ReturnType<typeof invite>;
|
||||
export type AdminLog = ReturnType<typeof logEntry>;
|
||||
export type AdminConnectionRecord = ReturnType<typeof connection>;
|
||||
export type AdminUpdateTask = ReturnType<typeof updateTask>;
|
||||
export type AdminUpdateStatus = ReturnType<typeof updateStatus>;
|
||||
export type AdminUpdateCheck = ReturnType<typeof updateCheck>;
|
||||
export type AdminUpdateRelease = ReturnType<typeof updateRelease>;
|
||||
@@ -0,0 +1,340 @@
|
||||
import {
|
||||
DECORATIVE_PART_IDS,
|
||||
HOST_SKIN_ATTRIBUTE,
|
||||
HOST_SLOTTABLE_PART_IDS,
|
||||
SKIN_ICON_SLOT_IDS,
|
||||
TRUSTED_PART_IDS,
|
||||
isHostPart,
|
||||
} from "./skin-visual-parts.js";
|
||||
|
||||
/**
|
||||
* `chrome.json` is an optional, declarative companion to an open skin.
|
||||
*
|
||||
* It describes 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.
|
||||
* - `slots`: declarative anchors for trusted host controls. A skin never
|
||||
* receives the control; it only names a part it already renders so the
|
||||
* host can position its own top-layer capsule there and fall back to the
|
||||
* default corner when the anchor stops being usable.
|
||||
*
|
||||
* 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_CHROME_MAX_SLOTS = 8;
|
||||
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
|
||||
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
|
||||
export const SKIN_ICON_DIRECTORY = "assets/icons/";
|
||||
|
||||
/**
|
||||
* Anchor names are `data-ws-part` values, including host-rendered v3 component
|
||||
* parts (`skin.<page>.<component>.part-<name>`) and v4 runtime plugin parts
|
||||
* (`skin.<page>.runtime_plugin_<plugin>__<component>.part-<name>`). Each
|
||||
* dot-separated segment follows the same identifier grammar as other part
|
||||
* names; the generous overall limit covers a namespaced runtime plugin.
|
||||
*/
|
||||
export const SKIN_SLOT_ANCHOR_MAX_LENGTH = 240;
|
||||
const PART_NAME_SEGMENT = /^[-_a-z][-_a-z0-9]*$/i;
|
||||
|
||||
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>;
|
||||
/** Protected host controls folded into skin-owned layout anchors. */
|
||||
slots?: Partial<Record<string, SkinChromeSlot>>;
|
||||
}
|
||||
|
||||
export type SkinChromeSlotAlign = "start" | "center" | "end";
|
||||
|
||||
export interface SkinChromeSlot {
|
||||
/** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */
|
||||
anchor: string;
|
||||
/** Horizontal alignment inside the anchor; the control is vertically centred. */
|
||||
align: SkinChromeSlotAlign;
|
||||
/** Collapse to the mark only until hovered or focused. */
|
||||
compact: boolean;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slot anchor is an existing part name, never host-owned UI: a skin must not
|
||||
* be able to park a protected control on the launcher, the authorization
|
||||
* dialog or another trusted element it could then cover or remove.
|
||||
*/
|
||||
function normalizeSlotAnchor(raw: unknown): string {
|
||||
if (typeof raw !== "string" || !raw || raw.length > SKIN_SLOT_ANCHOR_MAX_LENGTH) {
|
||||
return reject(`A slot anchor must be a part name of at most ${SKIN_SLOT_ANCHOR_MAX_LENGTH} characters.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const segments = raw.split(".");
|
||||
if (segments.some((segment) => !PART_NAME_SEGMENT.test(segment))) {
|
||||
return reject(`A slot anchor is not a valid part name: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (isHostPart(raw) || TRUSTED_PART_IDS.has(raw)) {
|
||||
return reject(`A slot anchor cannot point at trusted host UI: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function isSlotAlign(value: unknown): value is SkinChromeSlotAlign {
|
||||
return value === "start" || value === "center" || value === "end";
|
||||
}
|
||||
|
||||
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" && key !== "slots") {
|
||||
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);
|
||||
}
|
||||
}
|
||||
let slots: Partial<Record<string, SkinChromeSlot>> | undefined;
|
||||
if (raw.slots !== undefined) {
|
||||
if (!isRecord(raw.slots)) {
|
||||
return reject("slots must be an object mapping protected part names to anchors.", "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const entries = Object.entries(raw.slots);
|
||||
if (entries.length > SKIN_CHROME_MAX_SLOTS) {
|
||||
return reject(`A skin may declare at most ${SKIN_CHROME_MAX_SLOTS} slots.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots = Object.create(null) as Partial<Record<string, SkinChromeSlot>>;
|
||||
for (const [part, value] of entries) {
|
||||
if (!HOST_SLOTTABLE_PART_IDS.has(part)) {
|
||||
return reject(`Unknown slottable host part: ${part}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
for (const key of Object.keys(value)) {
|
||||
if (key !== "anchor" && key !== "align" && key !== "compact") {
|
||||
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
}
|
||||
const anchor = normalizeSlotAnchor(value.anchor);
|
||||
const align = value.align === undefined ? "end" : value.align;
|
||||
if (!isSlotAlign(align)) {
|
||||
return reject(`Slot ${part} has an invalid align value: ${String(align)}.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
const compact = value.compact === undefined ? false : value.compact;
|
||||
if (typeof compact !== "boolean") {
|
||||
return reject(`Slot ${part} compact must be a boolean.`, "SKIN_CHROME_SLOT_INVALID");
|
||||
}
|
||||
slots[part] = { anchor, align, compact };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
hiddenParts,
|
||||
...(visibleParts ? { visibleParts } : {}),
|
||||
icons,
|
||||
...(slots ? { slots } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,763 @@
|
||||
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, HOST_SLOTTABLE_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("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
|
||||
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]);
|
||||
|
||||
const explicit = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(explicit.slots?.["host.recovery"], {
|
||||
anchor: "voice.audio-dock",
|
||||
align: "start",
|
||||
compact: true,
|
||||
});
|
||||
|
||||
// Defaults: align "end", compact off. Component and runtime-plugin parts are
|
||||
// ordinary anchors; only host/trusted parts are off limits.
|
||||
const defaults = parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: {
|
||||
"host.recovery": { anchor: "skin.voice.harbor-dock.part-anchor" },
|
||||
},
|
||||
}));
|
||||
assert.deepEqual(defaults.slots?.["host.recovery"], {
|
||||
anchor: "skin.voice.harbor-dock.part-anchor",
|
||||
align: "end",
|
||||
compact: false,
|
||||
});
|
||||
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
slots: { "host.recovery": { anchor: "skin.voice.runtime_plugin_voice-surface__dock.part-anchor" } },
|
||||
})));
|
||||
|
||||
// Slot declarations are runtime input, not compiled CSS: the generated host
|
||||
// stylesheet must stay exactly as empty as before.
|
||||
assert.equal(compileSkinChromeCss(explicit, "demo-skin"), "");
|
||||
|
||||
const invalidDocuments: Array<[unknown, RegExp]> = [
|
||||
[{ schemaVersion: 1, slots: [] }, /must be an object/],
|
||||
[{ schemaVersion: 1, slots: { "host.permission": { anchor: "voice.audio-dock" } } }, /Unknown slottable host part/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": "voice.audio-dock" } }, /must be an object/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "host.plugins.launcher" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.connection-status" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "app" } } }, /trusted host UI/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", align: "left" } } }, /invalid align/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", compact: "yes" } } }, /compact must be a boolean/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", extra: true } } }, /unsupported field/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/],
|
||||
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/],
|
||||
];
|
||||
for (const [value, message] of invalidDocuments) {
|
||||
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
|
||||
}
|
||||
});
|
||||
|
||||
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 -1000px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 5000px); }',
|
||||
'[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }',
|
||||
'[data-ws-part="voice.audio-dock"] { margin-left: -1e4px; }',
|
||||
'[data-ws-part="voice.audio-dock"] { transform: translateX(calc(2px*-1000)); }',
|
||||
]) {
|
||||
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. Ordinary placement is no longer mistaken for a
|
||||
// yeet: only values clearly beyond a viewport are rejected.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-top: 120px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 auto 120px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { top: 100%; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { scale: 100%; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { rotate: 4deg; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { transform: rotate(8deg); }'));
|
||||
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("protected controls accept every purely visual property", () => {
|
||||
const themed = compileSkinCss(`
|
||||
:root {
|
||||
--skin-ink: #f8fafc;
|
||||
--skin-card: #0f172a;
|
||||
--skin-line: #38bdf8;
|
||||
--skin-pad: 14px;
|
||||
--skin-size: 56px;
|
||||
--skin-shadow: 0 10px 30px #0006;
|
||||
}
|
||||
[data-ws-part="voice.audio-dock.microphone"],
|
||||
[data-ws-part="voice.connection-status.reconnect"],
|
||||
[data-ws-part="home.footer.clear"],
|
||||
[data-ws-part="auth.password.dialog"] {
|
||||
color: var(--skin-ink);
|
||||
background-color: var(--skin-card);
|
||||
background-image: linear-gradient(135deg, #123456, #654321), url("assets/protected-pattern.png");
|
||||
border: 2px solid var(--skin-line);
|
||||
border-radius: 18px;
|
||||
font-family: var(--skin-font, Tahoma, "Segoe UI", sans-serif);
|
||||
font-size: 15px;
|
||||
padding: var(--skin-pad);
|
||||
width: var(--skin-size);
|
||||
height: var(--skin-size);
|
||||
box-shadow: var(--skin-shadow);
|
||||
text-shadow: 0 1px 2px #0008;
|
||||
}
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"]::before,
|
||||
[data-ws-part="auth.password.actions"] > button {
|
||||
background: var(--skin-line);
|
||||
border-color: var(--skin-line);
|
||||
border-radius: 12px;
|
||||
}
|
||||
`, "demo-skin", new Set(["assets/protected-pattern.png"]), 3);
|
||||
|
||||
assert.match(themed.css, /\[data-ws-part="voice\.audio-dock\.microphone"\]/);
|
||||
assert.match(themed.css, /wskin-asset:assets%2Fprotected-pattern\.png/);
|
||||
// The hide/move guarantees are unchanged.
|
||||
for (const css of [
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { display: none; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { visibility: hidden; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { opacity: 0; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { pointer-events: none; }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { clip-path: inset(100%); }',
|
||||
'[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }',
|
||||
':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock.microphone"] { margin-left: var(--skin-pull); }',
|
||||
// Literal filter/clip/content-visibility hiding is rejected, so a variable
|
||||
// must not smuggle the same value past the check.
|
||||
':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { filter: var(--skin-x); }',
|
||||
':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { -webkit-filter: var(--skin-x); }',
|
||||
':root { --skin-x: rect(0, 0, 0, 0); } [data-ws-part="voice.audio-dock.microphone"] { clip: var(--skin-x); }',
|
||||
':root { --skin-x: hidden; } [data-ws-part="voice.audio-dock.microphone"] { content-visibility: var(--skin-x); }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css);
|
||||
}
|
||||
});
|
||||
|
||||
test("indirect filter values stay free outside protected controls", () => {
|
||||
for (const version of [2, 3] as const) {
|
||||
assert.doesNotThrow(() => compileSkinCss(':root { --skin-glow: drop-shadow(0 0 4px #0ff); } [data-ws-part="voice.header"] { filter: var(--skin-glow); }', "demo-skin", new Set(), version));
|
||||
}
|
||||
// Literal visual filters remain allowed on protected controls.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock.microphone"] { filter: drop-shadow(0 0 4px #0ff) saturate(1.2); }'));
|
||||
});
|
||||
|
||||
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.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; }',
|
||||
]) {
|
||||
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);
|
||||
}
|
||||
|
||||
// Decorative host chrome is not on the recovery path: it may be repositioned,
|
||||
// resized, restacked and animated, at most with a warning.
|
||||
for (const css of [
|
||||
'[data-ws-part="host.watermark"] { position: fixed; }',
|
||||
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
|
||||
'[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; }',
|
||||
'[data-ws-part="host.plugins.launcher"] { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; }',
|
||||
'[data-ws-part="host.hint"] { position: absolute; transform: translateX(-10px); }',
|
||||
'[data-ws-part="host.voice-status-decoration"] { position: fixed; inset: 0; pointer-events: none; }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), 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; }'));
|
||||
// Overlay contents may use normal sizing and margins; only a viewport-sized
|
||||
// box would turn the library contents into a fullscreen mask.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] button { min-width: 44px; min-height: 44px; }'));
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { margin: 0; }'));
|
||||
});
|
||||
|
||||
test("keyframes follow the same protected-control rules as regular declarations", () => {
|
||||
const rejected: Array<[string, RegExp]> = [
|
||||
['@keyframes k { to { display: none; opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { transform: translateX(-9999px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
['@keyframes k { to { inset: 0 0 0 -120vw; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
['@keyframes k { to { filter: opacity(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/],
|
||||
['@keyframes k { to { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/],
|
||||
// A variable animation name must not hide the name from the walk.
|
||||
[':root { --skin-anim: k; } @keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: var(--skin-anim) 1s forwards; }', /cannot use indirect values/],
|
||||
['@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { --skin-anim: k; } [data-ws-part="voice.audio-dock"] { animation-name: var(--skin-anim); }', /cannot use indirect values/],
|
||||
];
|
||||
for (const [css, message] of rejected) {
|
||||
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
|
||||
}
|
||||
// A keyframe shared by a protected and a non-protected part is judged by the
|
||||
// protected reference.
|
||||
assert.throws(
|
||||
() => compile('@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation: k 1s; }'),
|
||||
/must remain available/,
|
||||
);
|
||||
|
||||
// Harmless fades, color tweens and gentle motion on non-protected parts, and
|
||||
// visual / motion keyframes on decorative host parts, still compile.
|
||||
for (const css of [
|
||||
'@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: fade 2s ease; }',
|
||||
'@keyframes tint { from { color: #fff; } to { color: #1d4f9c; } } [data-ws-part="home.header"] { animation: tint 1.2s; }',
|
||||
'@keyframes drift { from { transform: translateY(0); } to { transform: translateY(-6px); } } [data-ws-part="home.hero.eyebrow"] { animation: drift 3s infinite alternate; }',
|
||||
'@keyframes wm { from { opacity: .1; color: #8ab9cf; transform: translateX(0); } to { opacity: .3; color: #2b6d8a; transform: translateX(20px); } } [data-ws-part="host.watermark"] { animation: wm 4s infinite alternate; }',
|
||||
'@keyframes big { to { width: 100vw; height: 100vh; opacity: .2; } } [data-ws-part="host.watermark"] { animation: big 1s forwards; }',
|
||||
'@keyframes hide { to { display: none; } } [data-ws-part="host.hint"] { animation: hide 1s forwards; }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("keyframes hide protected parts only when the animation can rest there", () => {
|
||||
// Entrances and pulses that merely pass through a hidden/intermediate state
|
||||
// are legitimate: only `to`/`100%` (and a genuinely resting `from`) count.
|
||||
for (const css of [
|
||||
'@keyframes in { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="app"] { animation: in .3s; }',
|
||||
'@keyframes toastIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } [data-ws-part="app.toast"] { animation: toastIn .3s; }',
|
||||
'@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: fade .4s; }',
|
||||
'@keyframes slide { from { transform: translateX(-100%); } to { transform: none; } } [data-ws-part="voice.mobile-nav"] { animation: slide .25s; }',
|
||||
'@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="app.toast"] { animation: pop .2s; }',
|
||||
'@keyframes pulse { 50% { opacity: 0; } 100% { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: pulse 2s infinite; }',
|
||||
'@keyframes in { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } } [data-ws-part="host.plugins.overlay"] { animation: in .2s; }',
|
||||
'@keyframes pop { from { scale: 0; } to { scale: 1; } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }',
|
||||
'@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }',
|
||||
'@keyframes slide { from { transform: translateY(8px); } to { transform: translateY(0); } } [data-ws-part="host.plugins.overlay"] { animation: slide .2s; }',
|
||||
// A keyframe without a `to` frame ends on the element's own style.
|
||||
'@keyframes tint { 50% { opacity: 0; } } [data-ws-part="voice.connection-status"] { animation: tint 2s; }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
|
||||
const rejected: Array<[string, RegExp]> = [
|
||||
['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { 100% { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
// Reverse/alternate/fill-backwards animations can end (or hold) on `from`.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
|
||||
['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s alternate; }', /must remain available/],
|
||||
['@keyframes k { from { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-direction: alternate-reverse; }', /must remain available/],
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-fill-mode: both; }', /must remain available/],
|
||||
['@keyframes k { 0% { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
|
||||
// Declaration order cannot hide a reverse direction behind a longhand.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-direction: normal; animation: k 1s reverse; }', /must remain available/],
|
||||
// A variable fill mode is unknowable, so the start frame is treated as resting.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-fill-mode: var(--skin-fill); }', /must remain available/],
|
||||
// A paused animation renders its start frame from the first paint.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s paused; }', /must remain available/],
|
||||
['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-play-state: paused; }', /must remain available/],
|
||||
// Escaped `to`/`from` and `1e2%` must still be recognised as resting steps.
|
||||
['@keyframes k { \\74 o { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { t\\6f { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
|
||||
['@keyframes k { \\66 rom { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
|
||||
['@keyframes k { 1e2% { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
|
||||
// Direction/fill longhands in a sibling rule on the same subject still rest on `from`.
|
||||
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation-direction: reverse; animation-fill-mode: both; }', /must remain available/],
|
||||
];
|
||||
for (const [css, message] of rejected) {
|
||||
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("escaped animation names are matched and rewritten", () => {
|
||||
const escaped = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation-name: p\\75 lse; }');
|
||||
assert.match(escaped.css, /animation-name: ws-demo-skin-pulse/);
|
||||
assert.doesNotMatch(escaped.css, /p\\75 lse/);
|
||||
|
||||
const shorthand = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: p\\75 lse .3s ease; }');
|
||||
assert.match(shorthand.css, /animation: ws-demo-skin-pulse \.3s ease/);
|
||||
|
||||
// Only the name slot is rewritten: a keyframe named like a timing keyword
|
||||
// must not turn the timing function into a keyframe reference.
|
||||
const timing = compile('@keyframes linear { from { opacity: 1; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: linear 1s linear; }');
|
||||
assert.match(timing.css, /animation: linear 1s ws-demo-skin-linear/);
|
||||
});
|
||||
|
||||
test("keyword-shaped animation tokens do not become keyframe references", () => {
|
||||
const named = compile('@keyframes alternate { from { opacity: 1; } to { opacity: 1; } } @keyframes bob { from { transform: translateY(0); } to { transform: translateY(4px); } } [data-ws-part="voice.audio-dock"] { animation: bob 2s alternate; }');
|
||||
assert.match(named.css, /@keyframes ws-demo-skin-alternate/);
|
||||
assert.match(named.css, /animation: ws-demo-skin-bob 2s alternate/);
|
||||
assert.doesNotMatch(named.css, /animation: bob 2s ws-demo-skin-alternate/);
|
||||
});
|
||||
|
||||
test("normalised hidden values cannot hide protected parts", () => {
|
||||
const hidden: Array<[string, string]> = [
|
||||
["display", "none"],
|
||||
["visibility", "hidden"],
|
||||
["visibility", "collapse"],
|
||||
["opacity", ".0"],
|
||||
["opacity", "+0"],
|
||||
["opacity", "-1"],
|
||||
["opacity", "0%"],
|
||||
["opacity", "0.5%"],
|
||||
["opacity", "0.001"],
|
||||
["opacity", "calc(0)"],
|
||||
["filter", "opacity(0.0)"],
|
||||
["filter", "brightness(0)"],
|
||||
["-webkit-filter", "opacity(0)"],
|
||||
["pointer-events", "none"],
|
||||
["transform", "scale(0)"],
|
||||
["transform", "scaleX(0)"],
|
||||
["transform", "scaleY(0)"],
|
||||
["transform", "scale3d(0, 1, 1)"],
|
||||
["transform", "scale(0 0)"],
|
||||
["scale", "0"],
|
||||
["scale", "0%"],
|
||||
["scale", "0 0"],
|
||||
["content-visibility", "hidden"],
|
||||
["clip-path", "inset(50%)"],
|
||||
["clip-path", "inset(60% 0)"],
|
||||
["clip-path", "inset(0 60%)"],
|
||||
["clip-path", "circle(0)"],
|
||||
["clip-path", "ellipse(0 10px)"],
|
||||
["clip", "rect(0,0,0,0)"],
|
||||
["clip", "rect(0 0 0 0)"],
|
||||
["mask", "alpha(0)"],
|
||||
["mask-image", "luminance(0)"],
|
||||
["mask-image", "linear-gradient(transparent, transparent)"],
|
||||
["mask-image", "linear-gradient(#0000, #0000)"],
|
||||
["mask-image", "linear-gradient(rgb(0 0 0 / 0), rgb(0 0 0 / 0))"],
|
||||
["mask-image", "conic-gradient(from 0deg, transparent, transparent)"],
|
||||
["opacity", "0e0"],
|
||||
["opacity", "1e-3"],
|
||||
["filter", "opacity(1e-2)"],
|
||||
["transform", "scale(0e0)"],
|
||||
["scale", "1e-9"],
|
||||
];
|
||||
for (const [property, value] of hidden) {
|
||||
const direct = `[data-ws-part="voice.audio-dock"] { ${property}: ${value}; }`;
|
||||
assert.throws(() => compile(direct), /must remain available/, direct);
|
||||
const frame = `@keyframes k { to { ${property}: ${value}; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; }`;
|
||||
assert.throws(() => compile(frame), /must remain available/, frame);
|
||||
}
|
||||
// Partial effects and artwork clipping remain legitimate.
|
||||
for (const css of [
|
||||
'[data-ws-part="voice.audio-dock"] { opacity: .5; }',
|
||||
'[data-ws-part="voice.audio-dock"] { filter: opacity(.4); }',
|
||||
'[data-ws-part="voice.audio-dock"] { transform: scale(.5); }',
|
||||
'[data-ws-part="voice.audio-dock"] { scale: .8; }',
|
||||
'[data-ws-part="voice.audio-dock"] { clip-path: polygon(0 0, 100% 0, 100% 80%, 0 100%); }',
|
||||
'[data-ws-part="voice.audio-dock"] { clip-path: inset(20%); }',
|
||||
'[data-ws-part="voice.audio-dock"] { mask-image: linear-gradient(transparent, red); }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
});
|
||||
|
||||
test("selector variants cannot disguise a protected subject", () => {
|
||||
for (const css of [
|
||||
'[data-ws-part="VOICE.AUDIO-DOCK" i] { display: none; }',
|
||||
'[data-ws-part="voice.audio-dock" I] { opacity: 0; }',
|
||||
':not(:not([data-ws-part="voice.audio-dock"])) { display: none; }',
|
||||
':not(:not([data-ws-part="voice.audio-dock"]):hover) { visibility: hidden; }',
|
||||
':nth-child(2n of [data-ws-part="voice.audio-dock"]) { display: none; }',
|
||||
':nth-last-child(odd of .member, [data-ws-part="voice.audio-dock"]) { pointer-events: none; }',
|
||||
':not(:not([data-ws-part="voice.audio-dock"]), [data-ws-part="home.title"]) { display: none; }',
|
||||
':not(:is(:not([data-ws-part="voice.audio-dock"]))) { display: none; }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /must remain available/, css);
|
||||
}
|
||||
// The `s` flag keeps matching case-sensitive, so this selects nothing.
|
||||
assert.doesNotThrow(() => compile('[data-ws-part="VOICE.AUDIO-DOCK" s] { display: none; }'));
|
||||
// A single :not() still means "every other element".
|
||||
assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }'));
|
||||
});
|
||||
|
||||
test("escaped, namespaced and :is()/:where() animation names cannot bypass the protected-control locks", () => {
|
||||
const rejected: Array<[string, RegExp]> = [
|
||||
// Escaped property name used to skip the keyframe mapping walk.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { anim\\61 tion: k 1s forwards; }', /must remain available/],
|
||||
// A pack can predict the namespace and reference the already-renamed keyframe.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-k 1s forwards; }', /must remain available/],
|
||||
// The protected subject can be wrapped in a functional pseudo-class.
|
||||
[':is([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/],
|
||||
[':where([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/],
|
||||
['@keyframes k { to { opacity: 0; } } :is([data-ws-part="voice.audio-dock"]) { animation: k 1s forwards; }', /must remain available/],
|
||||
// -webkit-* animation longhands participate in the same walks.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation: k 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation-name: k; }', /must remain available/],
|
||||
['[data-ws-part="voice.audio-dock"] { -webkit-animation: var(--skin-a); }', /cannot use indirect values/],
|
||||
// Escaped *values* used to bail out of the mapping walk on a backslash and
|
||||
// still resolve to the renamed keyframe in the browser.
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\6b 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\00006b 1s forwards; }', /must remain available/],
|
||||
['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: \\6b; }', /must remain available/],
|
||||
// Prefixed visual-removal properties must use the same checks as the unprefixed form.
|
||||
['[data-ws-part="voice.audio-dock"] { -webkit-filter: opacity(0); }', /must remain available/],
|
||||
['[data-ws-part="voice.audio-dock"] { -webkit-transform: scale(0); }', /must remain available/],
|
||||
];
|
||||
for (const [css, message] of rejected) {
|
||||
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
|
||||
}
|
||||
|
||||
// `:not()` does not make the protected part the subject; only a v3 warning.
|
||||
assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }'));
|
||||
|
||||
// A harmless -webkit-animation on a non-protected part still compiles and its
|
||||
// keyframe name is rewritten into the skin namespace.
|
||||
const webkit = compile('@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { -webkit-animation: fade 2s ease; }');
|
||||
assert.match(webkit.css, /@keyframes ws-demo-skin-fade/);
|
||||
assert.match(webkit.css, /-webkit-animation: ws-demo-skin-fade 2s ease/);
|
||||
});
|
||||
|
||||
test("quoted animation names stay names even when they match shorthand keywords", () => {
|
||||
for (const name of ["linear", "ease", "reverse", "paused", "infinite", "none", "initial"]) {
|
||||
const frames = `@keyframes ${name} { from { opacity: .5; } to { opacity: 1; } }`;
|
||||
const shorthand = compile(`${frames} [data-ws-part="home.feature"] { animation: "${name}" 2s ease-in-out infinite; }`);
|
||||
assert.ok(shorthand.css.includes(`animation: "ws-demo-skin-${name}" 2s ease-in-out infinite`), shorthand.css);
|
||||
const longhand = compile(`${frames} [data-ws-part="home.feature"] { animation-name: "${name}"; }`);
|
||||
assert.ok(longhand.css.includes(`animation-name: "ws-demo-skin-${name}"`), longhand.css);
|
||||
assert.throws(() => compile(`@keyframes ${name} { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: "${name}" 1s ease; }`), /must remain available/);
|
||||
}
|
||||
const layers = compile('@keyframes linear { to { opacity: 1; } } @keyframes paused { to { opacity: 1; } } [data-ws-part="home.feature"] { animation: "linear" 2s ease, "paused" 3s linear; }');
|
||||
assert.ok(layers.css.includes('animation: "ws-demo-skin-linear" 2s ease, "ws-demo-skin-paused" 3s linear'), layers.css);
|
||||
});
|
||||
|
||||
test("keyframes cannot turn the plugin overlay into a fullscreen layer", () => {
|
||||
for (const css of [
|
||||
'@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }',
|
||||
'@keyframes k { to { width: 100vw; height: 100vh; } } [data-ws-part="host.plugins.overlay"] * { animation: k 1s forwards; }',
|
||||
'@keyframes k { to { zoom: 10; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }',
|
||||
'@keyframes k { to { transform: scale(10); } } [data-ws-part="host.plugins.overlay"] { animation-name: k; }',
|
||||
'@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { --skin-a: ws-demo-skin-k; animation: var(--skin-a) 1s forwards; }',
|
||||
'[data-ws-part="host.plugins.overlay"] * { width: calc(50vw * 2); }',
|
||||
'[data-ws-part="host.plugins.overlay"] * { width: calc(99vw + 1vw); }',
|
||||
]) {
|
||||
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
|
||||
}
|
||||
// The same animation is harmless on decorative host chrome.
|
||||
assert.doesNotThrow(() => compile('@keyframes k { to { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; } } [data-ws-part="host.watermark"] { animation: k 1s forwards; }'));
|
||||
});
|
||||
|
||||
test("large layout restyles of non-protected parts and decorative host chrome compile", () => {
|
||||
for (const css of [
|
||||
'[data-ws-part="home.header"] { display: grid; grid-template-columns: 1fr 2fr; gap: 16px; position: relative; width: 80vw; height: 50vh; }',
|
||||
'[data-ws-part="home.header"] { display: flex; flex-direction: column; align-items: stretch; translate: 24px 0; }',
|
||||
'[data-ws-part="voice.audio-dock"] > div:first-child { position: absolute; width: 100vw; height: 100vh; }',
|
||||
// Whole-page and protected-part layout rewrites are the owner's explicit
|
||||
// use case; placement is no longer mistaken for a yeet.
|
||||
'[data-ws-part="app"] { display: grid; grid-template-areas: "rail main"; grid-template-columns: 72px 1fr; position: relative; }',
|
||||
'[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; display: flex; flex-direction: column; gap: 10px; }',
|
||||
'[data-ws-part="home"] { display: flex; flex-direction: column; align-items: stretch; min-height: 100vh; }',
|
||||
// Official example skins (harbor, kaak) clip their own artwork.
|
||||
'[data-ws-part="home.header"] { clip-path: polygon(0 0, 100% 0, 100% 82%, 0 100%); }',
|
||||
'[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; transform: rotate(-8deg); }',
|
||||
]) {
|
||||
assert.doesNotThrow(() => compile(css), css);
|
||||
}
|
||||
});
|
||||
|
||||
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"));
|
||||
});
|
||||
@@ -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 selectorParser, { type Node as SelectorNode, type Pseudo as SelectorPseudo } from "postcss-selector-parser";
|
||||
import valueParser, { type Node as ValueNode } 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,26 +44,82 @@ 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. Purely visual properties (colour, background, border,
|
||||
* radius, font, shadow, padding, width/height) are deliberately absent: a
|
||||
* protected control may theme them with `var()`.
|
||||
*/
|
||||
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",
|
||||
]);
|
||||
/**
|
||||
* Visual properties whose literal hiding values (`filter: opacity(0)`,
|
||||
* `clip: rect(0 0 0 0)`, `content-visibility: hidden`) are rejected on
|
||||
* protected controls. They stay free on every other part, but a protected
|
||||
* control may not take them from `var()`/`attr()`, which would hide the
|
||||
* same value from the static check.
|
||||
*/
|
||||
const PROTECTED_INDIRECT_HIDE_PROPERTIES = new Set(["filter", "clip", "content-visibility"]);
|
||||
/** 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",
|
||||
]);
|
||||
/** CSS-wide keywords never name a keyframe and reset an animatable slot. */
|
||||
const CSS_WIDE_KEYWORDS = new Set(["initial", "inherit", "unset", "revert", "revert-layer"]);
|
||||
/** Shorthand keyword slots; a repeated category frees the word to be the name. */
|
||||
const ANIMATION_KEYWORD_CATEGORIES = new Map<string, string>([
|
||||
["linear", "timing"], ["ease", "timing"], ["ease-in", "timing"], ["ease-out", "timing"],
|
||||
["ease-in-out", "timing"], ["step-start", "timing"], ["step-end", "timing"],
|
||||
["normal", "direction"], ["reverse", "direction"], ["alternate", "direction"], ["alternate-reverse", "direction"],
|
||||
["none", "fill"], ["forwards", "fill"], ["backwards", "fill"], ["both", "fill"],
|
||||
["running", "play"], ["paused", "play"], ["infinite", "iteration"],
|
||||
]);
|
||||
/** Words that let an animation hold its `from`/`0%` frame. */
|
||||
const RESTING_START_KEYWORDS = new Set(["reverse", "alternate", "alternate-reverse", "backwards", "both", "paused"]);
|
||||
|
||||
export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } {
|
||||
const size = new TextEncoder().encode(source).byteLength;
|
||||
if (!size || size > MAX_CSS_BYTES) throw new SkinCssValidationError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
|
||||
@@ -67,6 +131,10 @@ 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`; these rules get their own
|
||||
// document-level scope, which the host anchors to the active skin attribute.
|
||||
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 +185,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) {
|
||||
@@ -133,37 +204,100 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
|
||||
|
||||
const referencedKeyframes = new Set<string>();
|
||||
const nonOptionalKeyframes = new Set<string>();
|
||||
// Keyframes inherit the protected/locked status of their referencing rules;
|
||||
// params are namespaced here, and `from`/`0%` only rests for some rules.
|
||||
const protectedKeyframeParts = new Map<string, string>();
|
||||
const lockedHostKeyframeParts = new Map<string, Set<string>>();
|
||||
const restingFromKeyframes = new Set<string>();
|
||||
// Direction/fill/play-state longhands may sit in a sibling rule on the same
|
||||
// subject; collect names per subject, then mark resting-from afterwards.
|
||||
const subjectKeyframes = new Map<string, Set<string>>();
|
||||
const restingSubjects = new Set<string>();
|
||||
root.walkRules((rule: Rule) => {
|
||||
if (hasKeyframesAncestor(rule)) return;
|
||||
const optionalTarget = hideableRules.has(rule);
|
||||
const protectedTarget = selectorSubjectProtectedPart(rule.selector);
|
||||
const lockedHostParts = selectorLockedHostParts(rule.selector);
|
||||
const subjects = [
|
||||
...selectorSubjectParts(rule.selector, PROTECTED_PART_IDS),
|
||||
...selectorSubjectParts(rule.selector, HOST_CHROME_PART_IDS).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part)),
|
||||
];
|
||||
const restsAtStart = subjects.length > 0 && ruleCanRestAtStart(rule);
|
||||
if (restsAtStart) for (const subject of subjects) restingSubjects.add(subject);
|
||||
rule.walkDecls((declaration: Declaration) => {
|
||||
const property = declaration.prop.toLowerCase();
|
||||
// Decode the property like the enforcement walk (`anim\61 tion`), and the
|
||||
// value so escaped identifiers match their declared names.
|
||||
const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase());
|
||||
if (property !== "animation" && property !== "animation-name") return;
|
||||
const value = declaration.value;
|
||||
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
|
||||
const decodedValue = decodeCssEscapes(declaration.value);
|
||||
if (/\b(?:var|attr)\s*\(/i.test(decodedValue)) {
|
||||
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
|
||||
return;
|
||||
}
|
||||
for (const name of keyframeNames.keys()) {
|
||||
if (!referencesCssIdentifier(value, name)) continue;
|
||||
referencedKeyframes.add(name);
|
||||
if (!optionalTarget) nonOptionalKeyframes.add(name);
|
||||
const { names } = parseAnimationLayers(decodedValue, property);
|
||||
for (const nameNode of names) {
|
||||
if (!nameNode) continue;
|
||||
const name = nameNode.value;
|
||||
for (const [original, scopedName] of keyframeNames) {
|
||||
if (name !== original && name !== scopedName) continue;
|
||||
referencedKeyframes.add(original);
|
||||
if (!optionalTarget) nonOptionalKeyframes.add(original);
|
||||
if (protectedTarget && !protectedKeyframeParts.has(scopedName)) {
|
||||
protectedKeyframeParts.set(scopedName, protectedTarget);
|
||||
}
|
||||
if (lockedHostParts.length) {
|
||||
const parts = lockedHostKeyframeParts.get(scopedName) ?? new Set<string>();
|
||||
for (const part of lockedHostParts) parts.add(part);
|
||||
lockedHostKeyframeParts.set(scopedName, parts);
|
||||
}
|
||||
if (restsAtStart) restingFromKeyframes.add(scopedName);
|
||||
for (const subject of subjects) {
|
||||
const names = subjectKeyframes.get(subject) ?? new Set<string>();
|
||||
names.add(scopedName);
|
||||
subjectKeyframes.set(subject, names);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
for (const subject of restingSubjects) {
|
||||
for (const name of subjectKeyframes.get(subject) ?? []) restingFromKeyframes.add(name);
|
||||
}
|
||||
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
|
||||
.filter((name) => !nonOptionalKeyframes.has(name))
|
||||
.map((name) => keyframeNames.get(name)!));
|
||||
|
||||
root.walkDecls((declaration: Declaration) => {
|
||||
const property = decodeCssEscapes(declaration.prop).toLowerCase();
|
||||
const unprefixedProperty = unprefixed(property);
|
||||
const value = declaration.value.trim();
|
||||
const decodedValue = decodeCssEscapes(value);
|
||||
const owningRule = findOwningRule(declaration);
|
||||
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
|
||||
const keyframeScope = keyframesRule?.params.trim() ?? null;
|
||||
// `to`/`100%` always rest, and `from`/`0%` when the rule can rest at start.
|
||||
const restingFrame = !keyframesRule
|
||||
|| (keyframeScope !== null && keyframeStepCanRest(owningRule!.selector, restingFromKeyframes.has(keyframeScope)));
|
||||
const canHideTarget = owningRule
|
||||
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
|
||||
: false;
|
||||
// A keyframe inherits the protected status of its referencing rules.
|
||||
const protectedTarget = owningRule
|
||||
? keyframesRule
|
||||
? (keyframeScope ? protectedKeyframeParts.get(keyframeScope) ?? null : null)
|
||||
: selectorSubjectProtectedPart(owningRule.selector)
|
||||
: null;
|
||||
// Every locked host part in the selector, not just the subject: `*` under
|
||||
// the overlay is still host chrome. Decorative parts are excluded.
|
||||
const hostChromeParts = owningRule
|
||||
? keyframesRule
|
||||
? (keyframeScope ? [...(lockedHostKeyframeParts.get(keyframeScope) ?? [])] : [])
|
||||
: selectorLockedHostParts(owningRule.selector)
|
||||
: [];
|
||||
const inHostChromeScope = hostChromeParts.length > 0;
|
||||
const inOverlayScope = hostChromeParts.includes("host.plugins.overlay");
|
||||
const overlaySubject = Boolean(!keyframesRule && owningRule
|
||||
&& selectorSubjectPart(owningRule.selector, HOST_CHROME_PART_IDS) === "host.plugins.overlay");
|
||||
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
|
||||
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
|
||||
throw declaration.error(pluginId
|
||||
@@ -173,33 +307,60 @@ 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 keeps its placement and footprint; decorative host parts skip
|
||||
// this lock. Overlay contents may size themselves unless viewport-sized.
|
||||
if (inHostChromeScope && !keyframesRule) {
|
||||
if (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 (overlaySubject && 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.");
|
||||
}
|
||||
// Overlay contents may size themselves, but not to the viewport.
|
||||
if (inOverlayScope && !overlaySubject && OVERLAY_SIZE_PROPERTIES.has(unprefixedProperty) && valueIsViewportSized(decodedValue)) {
|
||||
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
|
||||
}
|
||||
} else if (inHostChromeScope && restingFrame && keyframeEscapesHostLock(unprefixedProperty, decodedValue)) {
|
||||
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition, restack or resize host controls into a fullscreen layer.");
|
||||
}
|
||||
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
|
||||
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
|
||||
throw declaration.error("Executable CSS values are not allowed.");
|
||||
}
|
||||
const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase();
|
||||
if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
|
||||
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
|
||||
const indirectValue = restingFrame && /\b(?:var|attr)\s*\(/i.test(decodedValue);
|
||||
if (indirectValue && protectedTarget
|
||||
&& (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) || PROTECTED_INDIRECT_HIDE_PROPERTIES.has(unprefixedProperty))) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
|
||||
}
|
||||
const removesVisual = property === "all"
|
||||
|| (property === "display" && compactValue === "none")
|
||||
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|
||||
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|
||||
|| (property === "pointer-events" && compactValue === "none")
|
||||
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|
||||
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
|
||||
if (removesVisual && !canHideTarget && schemaVersion < 3) {
|
||||
if (indirectValue && !protectedTarget && INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
|
||||
}
|
||||
// An indirect animation name is checked at the declaration site. Locked
|
||||
// host chrome (the plugin overlay) uses the same rule, otherwise a
|
||||
// variable could point at a fullscreen keyframe.
|
||||
if (!keyframesRule && (unprefixedProperty === "animation" || unprefixedProperty === "animation-name")
|
||||
&& /\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 (inHostChromeScope) {
|
||||
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 through an indirect animation name.");
|
||||
}
|
||||
}
|
||||
// One predicate for every way a declaration can hide or disable a part.
|
||||
const hidesVisual = restingFrame && hidesVisually(unprefixedProperty, decodedValue);
|
||||
if (hidesVisual && protectedTarget) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`);
|
||||
}
|
||||
if (hidesVisual && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
|
||||
}
|
||||
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue))
|
||||
|| (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue))
|
||||
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue));
|
||||
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
|
||||
if (restingFrame && protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
|
||||
throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`);
|
||||
}
|
||||
if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
|
||||
if (schemaVersion >= 3 && hidesVisual && !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);
|
||||
const withScopedNames = rewriteScopedNames(value, unprefixedProperty, keyframeNames, fontFamilyNames);
|
||||
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
|
||||
if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
|
||||
return `wskin-asset:${encodeURIComponent(assetPath)}`;
|
||||
@@ -250,13 +411,591 @@ 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Functional pseudo-classes whose arguments keep the subject role. */
|
||||
const SUBJECT_PSEUDO_CLASSES = new Set([":is", ":where", ":matches", ":-webkit-any", ":-moz-any"]);
|
||||
|
||||
/** The nodes after the last combinator, i.e. the subject compound. */
|
||||
function lastCompound(nodes: SelectorNode[]): SelectorNode[] {
|
||||
let start = 0;
|
||||
for (let index = nodes.length - 1; index >= 0; index -= 1) {
|
||||
if (nodes[index].type === "combinator") { start = index + 1; break; }
|
||||
}
|
||||
return nodes.slice(start);
|
||||
}
|
||||
|
||||
/** Find a part in a compound; `:is()`/`:where()`/`:nth-child(… of S)` and
|
||||
* `:not(:not(X))` keep the subject role, a single `:not()` does not. */
|
||||
function compoundPart(nodes: SelectorNode[], parts: ReadonlySet<string>): string | null {
|
||||
for (const node of nodes) {
|
||||
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
|
||||
const value = node.value.replace(/^['"]|['"]$/g, "");
|
||||
if (node.insensitive) {
|
||||
const lower = value.toLowerCase();
|
||||
for (const part of parts) if (part.toLowerCase() === lower) return part;
|
||||
} else if (parts.has(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (node.type !== "pseudo" || !node.nodes) continue;
|
||||
const pseudo = node.value.toLowerCase();
|
||||
if (SUBJECT_PSEUDO_CLASSES.has(pseudo) || pseudo === ":nth-child" || pseudo === ":nth-last-child") {
|
||||
for (const nested of node.nodes) {
|
||||
const part = compoundPart(lastCompound(nested.nodes), parts);
|
||||
if (part) return part;
|
||||
}
|
||||
} else if (pseudo === ":not") {
|
||||
// `:not(:not(X))` and `:not(:not(X), Y)` are `X`; wrappers like
|
||||
// `:not(:is(:not(X)))` unwrap the same way. A single `:not(X)` is skipped.
|
||||
for (const argument of node.nodes) {
|
||||
const inner = nestedNegation(lastCompound(argument.nodes));
|
||||
if (!inner) continue;
|
||||
for (const nested of inner.nodes) {
|
||||
const part = compoundPart(lastCompound(nested.nodes), parts);
|
||||
if (part) return part;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A `:not(...)` argument that is itself a `:not`, possibly wrapped in `:is()`. */
|
||||
function nestedNegation(nodes: SelectorNode[]): SelectorPseudo | null {
|
||||
const direct = nodes.find((node): node is SelectorPseudo => node.type === "pseudo" && node.value.toLowerCase() === ":not");
|
||||
if (direct) return direct;
|
||||
for (const node of nodes) {
|
||||
if (node.type !== "pseudo" || !node.nodes || !SUBJECT_PSEUDO_CLASSES.has(node.value.toLowerCase())) continue;
|
||||
for (const nested of node.nodes) {
|
||||
const found = nestedNegation(lastCompound(nested.nodes));
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every matching part in the subject of any selector in a rule. */
|
||||
function selectorSubjectParts(selector: string, parts: ReadonlySet<string>): string[] {
|
||||
const found: string[] = [];
|
||||
try {
|
||||
const parsed = selectorParser().astSync(selector);
|
||||
for (const item of parsed.nodes) {
|
||||
const part = compoundPart(lastCompound(item.nodes), parts);
|
||||
if (part && !found.includes(part)) found.push(part);
|
||||
}
|
||||
} catch { /* A malformed selector is rejected elsewhere. */ }
|
||||
return found;
|
||||
}
|
||||
|
||||
function selectorSubjectPart(selector: string, parts: ReadonlySet<string>): string | null {
|
||||
return selectorSubjectParts(selector, parts)[0] ?? null;
|
||||
}
|
||||
|
||||
function selectorSubjectProtectedPart(selector: string): string | null {
|
||||
return selectorSubjectPart(selector, PROTECTED_PART_IDS);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** Host parts whose layout stays locked; decorative chrome is excluded. */
|
||||
function selectorLockedHostParts(selector: string): string[] {
|
||||
return selectorHostChromeParts(selector).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part));
|
||||
}
|
||||
|
||||
function unprefixed(property: string): string {
|
||||
return property.replace(/^-(?:webkit|moz|ms|o)-/, "");
|
||||
}
|
||||
|
||||
function isLayoutAffectingProperty(property: string): boolean {
|
||||
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
|
||||
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
|
||||
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
|
||||
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
|
||||
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
|
||||
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
|
||||
const local = unprefixed(property);
|
||||
if (LAYOUT_AFFECTING_PROPERTIES.has(local)) return true;
|
||||
if (/^(?:margin|padding)(?:-|$)/.test(local)) return true;
|
||||
if (/^border(?:-|$)/.test(local) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(local)) return true;
|
||||
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(local)) return true;
|
||||
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(local);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a positioning/margin/transform value can push a protected control
|
||||
* clearly off-screen: -1000 px / -100 % or +2000 px / +200 %. Ordinary layout
|
||||
* moves are legitimate, so only viewport-ejecting values are rejected.
|
||||
*/
|
||||
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform)(?:-|$)/;
|
||||
const OFFSET_LIMITS = { negativePx: 1000, positivePx: 2000, negativePercent: 100, positivePercent: 200 };
|
||||
|
||||
type Dimension = { value: number; unit: string };
|
||||
|
||||
const ABSOLUTE_UNIT_PIXELS: Record<string, number> = { px: 1, rem: 16, em: 16, ex: 8, rex: 8, ch: 8, cm: 37.8, mm: 3.78, q: 0.945, in: 96, pt: 1.333, pc: 16 };
|
||||
function absoluteLengthToPixels(value: number, unit: string): number | null {
|
||||
const factor = ABSOLUTE_UNIT_PIXELS[unit];
|
||||
return factor ? value * factor : null;
|
||||
}
|
||||
|
||||
type OffsetMeasurement = { kind: "pixels" | "percent"; value: number };
|
||||
|
||||
const VIEWPORT_UNIT_PATTERN = /^(?:s|l|d)?v(?:w|h|i|min|max)$|^cq(?:w|h|min|max|i|b)$/;
|
||||
|
||||
/** CSS `<number>` including a scientific-notation exponent. */
|
||||
const CSS_NUMBER_PATTERN = "[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?";
|
||||
|
||||
/** One CSS number, percentage or length, including a flat `calc()`. */
|
||||
function parseDimension(text: string): Dimension | null {
|
||||
const compact = text.trim().toLowerCase();
|
||||
const calc = /^calc\(([\s\S]*)\)$/.exec(compact);
|
||||
if (calc) return evaluateCalc(calc[1]);
|
||||
const match = new RegExp(`^(${CSS_NUMBER_PATTERN})([a-z%]*)$`).exec(compact);
|
||||
return match ? { value: Number(match[1]), unit: match[2] } : null;
|
||||
}
|
||||
|
||||
/** Flat `calc()`: sums of products over numbers and one unit; nested or mixed
|
||||
* input is unknown (`null` → allowed). A sign after `*`/`/` is a factor,
|
||||
* so `calc(2px*-1000)` is -2000px, not 2px + -1000. */
|
||||
function evaluateCalc(text: string): Dimension | null {
|
||||
const compact = text.replace(/\s+/g, "");
|
||||
const tokens = compact.match(new RegExp(`[*/]|${CSS_NUMBER_PATTERN}(?:[a-z%]+)?`, "g"));
|
||||
if (!tokens || tokens.join("") !== compact) return null;
|
||||
const total: Dimension = { value: 0, unit: "" };
|
||||
let term: Dimension | null = null;
|
||||
let pending: "*" | "/" | null = null;
|
||||
const addTerm = (): boolean => {
|
||||
if (!term || (total.unit && term.unit && total.unit !== term.unit)) return false;
|
||||
total.value += term.value;
|
||||
total.unit ||= term.unit;
|
||||
return true;
|
||||
};
|
||||
for (const token of tokens) {
|
||||
if (token === "*" || token === "/") { pending = token; continue; }
|
||||
const factor = parseDimension(token);
|
||||
if (!factor) return null;
|
||||
if (pending && term) {
|
||||
if (factor.unit && (term.unit || pending === "/")) return null;
|
||||
term = { value: pending === "/" ? term.value / factor.value : term.value * factor.value, unit: term.unit || factor.unit };
|
||||
pending = null;
|
||||
continue;
|
||||
}
|
||||
if (term && !addTerm()) return null;
|
||||
term = factor;
|
||||
pending = null;
|
||||
}
|
||||
return !pending && addTerm() ? total : null;
|
||||
}
|
||||
|
||||
/** Normalise one length for comparison; a bare number is not a length. */
|
||||
function lengthMeasurement(value: string): OffsetMeasurement | null {
|
||||
const dimension = parseDimension(value);
|
||||
if (!dimension?.unit) return null;
|
||||
if (dimension.unit === "%" || VIEWPORT_UNIT_PATTERN.test(dimension.unit)) return { kind: "percent", value: dimension.value };
|
||||
const pixels = absoluteLengthToPixels(dimension.value, dimension.unit);
|
||||
return pixels === null ? null : { kind: "pixels", value: pixels };
|
||||
}
|
||||
|
||||
function exceedsOffset(measurement: OffsetMeasurement | null): boolean {
|
||||
if (!measurement) return false;
|
||||
const [negative, positive] = measurement.kind === "percent"
|
||||
? [OFFSET_LIMITS.negativePercent, OFFSET_LIMITS.positivePercent]
|
||||
: [OFFSET_LIMITS.negativePx, OFFSET_LIMITS.positivePx];
|
||||
return measurement.value <= -negative || measurement.value >= positive;
|
||||
}
|
||||
|
||||
function valueMovesOffscreen(property: string, value: string): boolean {
|
||||
if (!OFFSET_PROPERTY_PATTERN.test(property)) return false;
|
||||
let offscreen = false;
|
||||
valueParser(value).walk((node) => {
|
||||
const name = node.type === "function" ? node.value.toLowerCase() : "";
|
||||
if (node.type === "word") offscreen ||= exceedsOffset(lengthMeasurement(node.value));
|
||||
else if (name === "calc") {
|
||||
offscreen ||= exceedsOffset(lengthMeasurement(valueParser.stringify(node)));
|
||||
return false;
|
||||
} else if (node.type === "function" && (name === "matrix" || name === "matrix3d")) {
|
||||
// A matrix can smuggle a large translation in unitless numbers.
|
||||
const items = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
|
||||
offscreen ||= (name === "matrix" ? [items[4], items[5]] : [items[12], items[13]])
|
||||
.some((item) => item <= -OFFSET_LIMITS.negativePx || item >= OFFSET_LIMITS.positivePx);
|
||||
return false;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
return offscreen;
|
||||
}
|
||||
|
||||
/** This declaration removes the element from view; partial effects stay allowed. */
|
||||
function hidesVisually(property: string, value: string): boolean {
|
||||
if (property === "all") return true;
|
||||
const text = decodeCssEscapes(value).trim().toLowerCase();
|
||||
if ((property === "display" && text === "none") || (property === "visibility" && /^(?:hidden|collapse)$/.test(text))
|
||||
|| (property === "pointer-events" && text === "none") || (property === "content-visibility" && text === "hidden")) return true;
|
||||
if (property === "opacity") return (numericValue(text) ?? 1) <= 0.01;
|
||||
if (property === "filter") return filterHides(text);
|
||||
if (property === "transform") return transformHides(text);
|
||||
if (property === "scale") return scalePropertyHides(text);
|
||||
if (property === "clip-path") return clipPathHides(text);
|
||||
if (property === "clip") return clipHides(text);
|
||||
return property === "mask" || property === "mask-image" ? maskHides(text) : false;
|
||||
}
|
||||
|
||||
/** Visit every function node; `test` gets the lower-cased name and its arguments. */
|
||||
function anyFunction(value: string, test: (name: string, args: string) => boolean): boolean {
|
||||
let hit = false;
|
||||
valueParser(value).walk((node) => {
|
||||
if (node.type === "function" && test(node.value.toLowerCase(), valueParser.stringify(node.nodes))) hit = true;
|
||||
});
|
||||
return hit;
|
||||
}
|
||||
|
||||
/** A number, a percentage as 0–1, or a flat `calc()` of numbers. */
|
||||
function numericValue(value: string): number | null {
|
||||
const dimension = parseDimension(value);
|
||||
if (!dimension) return null;
|
||||
return dimension.unit === "%" ? dimension.value / 100 : dimension.unit === "" ? dimension.value : null;
|
||||
}
|
||||
|
||||
function filterHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) => {
|
||||
const amount = numericValue(args);
|
||||
return amount !== null && (name === "opacity" ? amount <= 0.01 : name === "brightness" && amount <= 0);
|
||||
});
|
||||
}
|
||||
|
||||
function numbers(text: string): number[] {
|
||||
return text.split(/[\s,]+/).map(numericValue).filter((item): item is number => item !== null);
|
||||
}
|
||||
|
||||
function isZeroFactor(value: number): boolean {
|
||||
return Math.abs(value) <= 0.001;
|
||||
}
|
||||
|
||||
function transformHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) => {
|
||||
const factors = numbers(args);
|
||||
if (name === "scale" || name === "scale3d") return factors.slice(0, 2).some(isZeroFactor);
|
||||
return (name === "scalex" || name === "scaley") && isZeroFactor(factors[0] ?? 1);
|
||||
});
|
||||
}
|
||||
|
||||
function scalePropertyHides(value: string): boolean {
|
||||
const factors = numbers(value);
|
||||
return factors.length > 0 && (isZeroFactor(factors[0]) || (factors.length > 1 && isZeroFactor(factors[1])));
|
||||
}
|
||||
|
||||
function zeroLength(value: string | undefined): boolean {
|
||||
const dimension = value ? parseDimension(value) : null;
|
||||
return dimension !== null && isZeroFactor(dimension.value);
|
||||
}
|
||||
|
||||
function insetHides(args: string): boolean {
|
||||
const sides = args.split(/\bround\b/i)[0].trim().split(/\s+/).map(parseDimension);
|
||||
if (sides.some((side) => !side || (side.unit !== "" && side.unit !== "%"))) return false;
|
||||
const values = sides.map((side) => side!.value);
|
||||
const [top, right = top, bottom = top, left = right] = values;
|
||||
return top + bottom >= 100 || left + right >= 100;
|
||||
}
|
||||
|
||||
function clipPathHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) => {
|
||||
const shape = args.split(/\bat\b/i)[0].trim();
|
||||
if (name === "inset") return insetHides(args);
|
||||
if (name === "circle") return zeroLength(shape.split(/\s+/)[0]);
|
||||
return name === "ellipse" && shape.split(/\s+/).filter(Boolean).slice(0, 2).some(zeroLength);
|
||||
});
|
||||
}
|
||||
|
||||
function clipHides(value: string): boolean {
|
||||
const match = /^rect\(([\s\S]*)\)$/i.exec(value.trim());
|
||||
if (!match) return false;
|
||||
const sides = match[1].split(/[\s,]+/).filter(Boolean);
|
||||
return sides.length === 4 && sides.every(zeroLength);
|
||||
}
|
||||
|
||||
const GRADIENT_PRELUDE_KEYWORDS = new Set([
|
||||
"from", "to", "left", "right", "top", "bottom", "center", "at", "circle", "ellipse",
|
||||
"closest-side", "closest-corner", "farthest-side", "farthest-corner", "in",
|
||||
]);
|
||||
|
||||
/** `#rgb0` / `#rrggbb00`, `transparent`, or a colour function with alpha ≤ 0.01. */
|
||||
function colorIsTransparent(text: string): boolean {
|
||||
const value = text.trim().toLowerCase();
|
||||
if (value === "transparent" || /^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(value)) return true;
|
||||
return anyFunction(value, (name, args) => {
|
||||
if (!/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)$/.test(name)) return false;
|
||||
const slash = args.split("/");
|
||||
if (slash.length > 1) return (numericValue(slash[slash.length - 1].trim()) ?? 1) <= 0.01;
|
||||
const channels = numbers(args);
|
||||
return (name === "rgba" || name === "hsla") && channels.length >= 4 && channels[3] <= 0.01;
|
||||
});
|
||||
}
|
||||
|
||||
/** A gradient is a full mask only when every colour stop is fully transparent. */
|
||||
function gradientIsAllTransparent(args: string): boolean {
|
||||
let transparent = false;
|
||||
for (const segment of args.split(/,(?![^(]*\))/)) {
|
||||
const text = segment.trim().toLowerCase();
|
||||
if (!text) continue;
|
||||
const first = valueParser(text).nodes.find((node) => node.type !== "space" && node.type !== "comment");
|
||||
if (!first) continue;
|
||||
if (first.type === "function" ? colorIsTransparent(valueParser.stringify([first])) : colorIsTransparent(first.value)) {
|
||||
transparent = true;
|
||||
continue;
|
||||
}
|
||||
if (first.type === "word" && (GRADIENT_PRELUDE_KEYWORDS.has(first.value.toLowerCase()) || parseDimension(first.value)?.unit)) continue;
|
||||
return false;
|
||||
}
|
||||
return transparent;
|
||||
}
|
||||
|
||||
function maskHides(value: string): boolean {
|
||||
return anyFunction(value, (name, args) =>
|
||||
name === "alpha" || name === "luminance"
|
||||
? (numericValue(args) ?? 1) <= 0
|
||||
: name.endsWith("gradient") && gradientIsAllTransparent(args));
|
||||
}
|
||||
|
||||
/**
|
||||
* Name token per layer. In the shorthand a keyword fills the first slot of its
|
||||
* category; a repeated category (or any other word) is the name, so
|
||||
* `bob 2s alternate` references `bob`. Times, numbers and functions are skipped.
|
||||
*/
|
||||
function parseAnimationLayers(value: string, property: string): { parsed: ReturnType<typeof valueParser>; names: Array<ValueNode | null> } {
|
||||
const parsed = valueParser(value);
|
||||
const groups: ValueNode[][] = [[]];
|
||||
for (const node of parsed.nodes) {
|
||||
if (node.type === "div" && node.value === ",") groups.push([]);
|
||||
else if (node.type !== "space" && node.type !== "comment") groups[groups.length - 1].push(node);
|
||||
}
|
||||
const names = groups.map((nodes) => {
|
||||
const words = nodes.filter((node) => node.type === "word" || node.type === "string");
|
||||
if (property === "animation-name") {
|
||||
if (words[0]?.type === "string") return words[0];
|
||||
const name = words[0] ? decodeCssEscapes(words[0].value).toLowerCase() : "";
|
||||
return words[0] && name !== "none" && !CSS_WIDE_KEYWORDS.has(name) ? words[0] : null;
|
||||
}
|
||||
const used = new Set<string>();
|
||||
for (const node of words) {
|
||||
// Quoted strings always name keyframes, even "linear" or "none";
|
||||
// only unquoted words may fill the shorthand's keyword slots.
|
||||
if (node.type === "string") return node;
|
||||
const token = decodeCssEscapes(node.value).toLowerCase();
|
||||
const dimension = parseDimension(token);
|
||||
if (dimension && ["", "s", "ms"].includes(dimension.unit)) continue;
|
||||
const category = ANIMATION_KEYWORD_CATEGORIES.get(token);
|
||||
if (category && used.has(category)) return node;
|
||||
if (category) used.add(category);
|
||||
else if (node.type === "word" && CSS_WIDE_KEYWORDS.has(token)) continue;
|
||||
else return node;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return { parsed, names };
|
||||
}
|
||||
|
||||
/** Any restart/alternate/fill keyword or indirect value can hold the start frame.
|
||||
* Multi-layer rules are judged as a whole, which errs towards checking `from`. */
|
||||
function ruleCanRestAtStart(rule: Rule): boolean {
|
||||
let resting = false;
|
||||
rule.walkDecls((declaration: Declaration) => {
|
||||
const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase());
|
||||
if (!["animation", "animation-direction", "animation-fill-mode", "animation-play-state"].includes(property)) return;
|
||||
const value = decodeCssEscapes(declaration.value).toLowerCase();
|
||||
resting ||= /\b(?:var|attr)\s*\(/.test(value)
|
||||
|| valueParser(value).nodes.some((node) => node.type === "word" && RESTING_START_KEYWORDS.has(node.value));
|
||||
});
|
||||
return resting;
|
||||
}
|
||||
|
||||
/** `to`/`100%` always rest; `from`/`0%` rest for reverse/alternate, a
|
||||
* backwards/both fill, or a paused start. A long animation or a pause mid-way
|
||||
* (negative delay) can linger on an unchecked intermediate frame — accepted,
|
||||
* because recovery lives in a closed-shadow top-layer capsule. */
|
||||
function keyframeStepCanRest(selector: string, restsAtStart: boolean): boolean {
|
||||
return selector.split(",").some((step) => {
|
||||
const value = decodeCssEscapes(step).trim().toLowerCase();
|
||||
if (value === "to") return true;
|
||||
if (value === "from") return restsAtStart;
|
||||
const position = parseDimension(value);
|
||||
return position?.unit === "%" && (position.value >= 100 || (restsAtStart && position.value <= 0));
|
||||
});
|
||||
}
|
||||
|
||||
const OVERLAY_SIZE_PROPERTIES = new Set([
|
||||
"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",
|
||||
]);
|
||||
|
||||
function isViewportSizedDimension(dimension: Dimension | null): boolean {
|
||||
return Boolean(dimension && VIEWPORT_UNIT_PATTERN.test(dimension.unit) && Math.abs(dimension.value) >= 100);
|
||||
}
|
||||
|
||||
function valueIsViewportSized(value: string): boolean {
|
||||
let sized = false;
|
||||
valueParser(value).walk((node) => {
|
||||
if (node.type === "word") sized ||= isViewportSizedDimension(parseDimension(node.value));
|
||||
else if (node.type === "function" && node.value.toLowerCase() === "calc") {
|
||||
sized ||= isViewportSizedDimension(parseDimension(valueParser.stringify(node)));
|
||||
return false;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
return sized;
|
||||
}
|
||||
|
||||
function isIdentityNumber(value: number): boolean {
|
||||
return Math.abs(value - 1) <= 0.001;
|
||||
}
|
||||
|
||||
function isZeroAngleOrLength(value: string): boolean {
|
||||
return zeroLength(value);
|
||||
}
|
||||
|
||||
/** Identity transforms (`none`, `scale(1)`, `translate(0)`, `rotate(0deg)`). */
|
||||
function transformIsIdentity(value: string): boolean {
|
||||
const compact = value.trim().toLowerCase();
|
||||
if (compact === "none") return true;
|
||||
let seen = false;
|
||||
let identity = true;
|
||||
valueParser(compact).walk((node) => {
|
||||
if (node.type !== "function") return;
|
||||
seen = true;
|
||||
const name = node.value.toLowerCase();
|
||||
const args = valueParser.stringify(node.nodes);
|
||||
const factors = numbers(args);
|
||||
if (name === "scale" || name === "scale3d") identity &&= factors.length > 0 && factors.every(isIdentityNumber);
|
||||
else if (name === "scalex" || name === "scaley" || name === "scalez") identity &&= factors.length > 0 && isIdentityNumber(factors[0]);
|
||||
else if (/^translate(?:3d|[xyz])?$/.test(name)) identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength);
|
||||
else if (/^rotate(?:3d|[xyz])?$/.test(name) || name === "skew" || name === "skewx" || name === "skewy") {
|
||||
identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength);
|
||||
} else identity = false;
|
||||
});
|
||||
return seen && identity;
|
||||
}
|
||||
|
||||
function isNeutralLockValue(property: string, value: string): boolean {
|
||||
const compact = value.trim().toLowerCase();
|
||||
if (["none", "auto", "static"].includes(compact) || CSS_WIDE_KEYWORDS.has(compact)) return true;
|
||||
if (property === "scale" || property === "zoom") {
|
||||
const factors = numbers(compact);
|
||||
return factors.length > 0 && factors.every(isIdentityNumber);
|
||||
}
|
||||
if (property === "rotate") return isZeroAngleOrLength(compact);
|
||||
if (property === "transform") return transformIsIdentity(compact);
|
||||
if (property === "translate" || property.startsWith("inset") || /^(?:top|right|bottom|left)$/.test(property)) {
|
||||
return compact.split(/\s+/).every((token) => token === "auto" || isZeroAngleOrLength(token));
|
||||
}
|
||||
return compact === "0" || isZeroAngleOrLength(compact);
|
||||
}
|
||||
|
||||
/** Resting host-chrome keyframes reuse the direct lock per property: locked
|
||||
* properties only accept identity/neutral values; sizes only reject viewport sizes. */
|
||||
function keyframeEscapesHostLock(property: string, value: string): boolean {
|
||||
const compact = decodeCssEscapes(value).trim().toLowerCase();
|
||||
if (isNeutralLockValue(property, compact)) return false;
|
||||
if (OVERLAY_SIZE_PROPERTIES.has(property)) return valueIsViewportSized(value);
|
||||
return HOST_CHROME_LOCKED_PROPERTIES.has(property);
|
||||
}
|
||||
|
||||
function findOwningRule(node: Node): Rule | null {
|
||||
@@ -277,11 +1016,6 @@ function findKeyframesRule(rule: Rule): AtRule | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function referencesCssIdentifier(value: string, identifier: string): boolean {
|
||||
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
|
||||
}
|
||||
|
||||
export function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
|
||||
const parsed = valueParser(value);
|
||||
const resolvePackageAsset = (rawValue: string): string => {
|
||||
@@ -339,16 +1073,24 @@ function parseSingleFontFamily(value: string): string {
|
||||
}
|
||||
|
||||
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
|
||||
const parsed = valueParser(value);
|
||||
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
|
||||
parsed.walk((node) => {
|
||||
if (node.type !== "word" && node.type !== "string") return;
|
||||
const keyframe = keyframes.get(node.value);
|
||||
if (keyframe) node.value = keyframe;
|
||||
const family = fontFamilies.get(node.value.toLowerCase());
|
||||
if (family) node.value = family;
|
||||
});
|
||||
if (!["animation", "animation-name", "font", "font-family"].includes(property)) return value;
|
||||
// Rewrite against the decoded value: `p\75 lse` must become the scoped name
|
||||
// of `@keyframes pulse`, exactly like the matching walk above.
|
||||
const decoded = decodeCssEscapes(value);
|
||||
if (property === "animation" || property === "animation-name") {
|
||||
const { parsed, names } = parseAnimationLayers(decoded, property);
|
||||
for (const node of names) {
|
||||
const scoped = node ? keyframes.get(node.value) : undefined;
|
||||
if (node && scoped) node.value = scoped;
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
const parsed = valueParser(decoded);
|
||||
parsed.walk((node) => {
|
||||
if (node.type !== "word" && node.type !== "string") return;
|
||||
const family = fontFamilies.get(node.value.toLowerCase());
|
||||
if (family) node.value = family;
|
||||
});
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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",
|
||||
@@ -279,6 +275,9 @@ const PUBLIC_PART_IDS = new Set<string>([
|
||||
"voice.header",
|
||||
"voice.header-actions",
|
||||
"voice.plugin-toolbar",
|
||||
"voice.plugin-launcher",
|
||||
"voice.plugin-drawer",
|
||||
"voice.plugin-drawer.app",
|
||||
"voice.member",
|
||||
"voice.member-panel",
|
||||
"voice.member-panel.channels",
|
||||
@@ -336,25 +335,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",
|
||||
@@ -379,6 +369,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", "voice.plugin-drawer.app",
|
||||
]);
|
||||
const INTERACTIVE_PART_IDS = new Set([
|
||||
"voice.invite.create", "voice.invite.copy",
|
||||
@@ -399,6 +390,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",
|
||||
@@ -409,8 +401,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 {
|
||||
@@ -451,6 +444,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 {
|
||||
|
||||
@@ -67,6 +67,7 @@ export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
|
||||
"voice.connection-status",
|
||||
"voice.connection-controls",
|
||||
"voice.disconnect-control",
|
||||
"voice.plugin-launcher",
|
||||
] as const);
|
||||
export type SkinPluginHostWidget = typeof SKIN_PLUGIN_HOST_WIDGETS[number];
|
||||
export interface SkinPluginWidgetOptions {
|
||||
@@ -78,6 +79,8 @@ export interface SkinPluginWidgetOptions {
|
||||
memberDragDrop?: boolean;
|
||||
/** Select a supported host presentation for a channel tree. */
|
||||
layout?: "default" | "server-sidebar";
|
||||
pluginPresentation?: "dialog" | "drawer-below" | "drawer-side";
|
||||
communityLinks?: boolean;
|
||||
/** Provider identity used by the generic, UI-only home sign-in entry. */
|
||||
identityProviderId?: string;
|
||||
/** Provider display name used by the generic, UI-only home sign-in entry. */
|
||||
@@ -479,6 +482,7 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
|
||||
if (typeof rawNode.widget !== "string" || !HOST_WIDGETS.has(rawNode.widget)) fail("SKIN_PLUGIN_WIDGET_INVALID", "The component requests an unsupported host widget.");
|
||||
if (page === "demo") fail("SKIN_PLUGIN_WIDGET_INVALID", "Host widgets are available only on the home and voice client pages.");
|
||||
if (rawNode.widget === "home.visitor-count" && page !== "home") fail("SKIN_PLUGIN_WIDGET_INVALID", "The visitor count widget is available only on the home page.");
|
||||
if (rawNode.widget === "voice.plugin-launcher" && page !== "voice") fail("SKIN_PLUGIN_WIDGET_INVALID", "The plugin launcher is available only on the voice page.");
|
||||
if (rawNode.options !== undefined && inputSchemaVersion < 3) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Host widget options require components schema version 3.");
|
||||
// Preserve existing schema v2 packages; newly authored v3 widgets must declare every
|
||||
// permission needed by the trusted host UI they embed. Screen-share start was already gated.
|
||||
@@ -494,12 +498,21 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
|
||||
? new Set(["layout"])
|
||||
: rawNode.widget === "home.identity-provider"
|
||||
? new Set(["identityProviderId", "identityProviderLabel"])
|
||||
: new Set<string>();
|
||||
: rawNode.widget === "voice.plugin-launcher"
|
||||
? new Set(["pluginPresentation"])
|
||||
: rawNode.widget === "home.social-links"
|
||||
? new Set(["communityLinks"])
|
||||
: new Set<string>();
|
||||
if (!isRecord(rawNode.options)
|
||||
|| Object.keys(rawNode.options).some((key) => !supportedOptions.has(key))
|
||||
|| (rawNode.options.screenShare !== undefined && typeof rawNode.options.screenShare !== "boolean")
|
||||
|| (rawNode.options.memberActions !== undefined && typeof rawNode.options.memberActions !== "boolean")
|
||||
|| (rawNode.options.memberDragDrop !== undefined && typeof rawNode.options.memberDragDrop !== "boolean")
|
||||
|| (rawNode.options.communityLinks !== undefined && typeof rawNode.options.communityLinks !== "boolean")
|
||||
|| (rawNode.options.pluginPresentation !== undefined
|
||||
&& rawNode.options.pluginPresentation !== "dialog"
|
||||
&& rawNode.options.pluginPresentation !== "drawer-below"
|
||||
&& rawNode.options.pluginPresentation !== "drawer-side")
|
||||
|| (rawNode.options.layout !== undefined
|
||||
&& rawNode.options.layout !== "default"
|
||||
&& !(rawNode.widget === "voice.channel-tree" && rawNode.options.layout === "server-sidebar"))
|
||||
@@ -517,6 +530,8 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
|
||||
...(rawNode.options.memberActions !== undefined ? { memberActions: rawNode.options.memberActions } : {}),
|
||||
...(rawNode.options.memberDragDrop !== undefined ? { memberDragDrop: rawNode.options.memberDragDrop } : {}),
|
||||
...(rawNode.options.layout !== undefined ? { layout: rawNode.options.layout } : {}),
|
||||
...(rawNode.options.pluginPresentation !== undefined ? { pluginPresentation: rawNode.options.pluginPresentation } : {}),
|
||||
...(rawNode.options.communityLinks !== undefined ? { communityLinks: rawNode.options.communityLinks } : {}),
|
||||
...(rawNode.options.identityProviderId !== undefined ? { identityProviderId: rawNode.options.identityProviderId } : {}),
|
||||
...(rawNode.options.identityProviderLabel !== undefined ? { identityProviderLabel: rawNode.options.identityProviderLabel } : {}),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* 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",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Trusted host controls that an open skin may fold into its own layout through
|
||||
* `chrome.json#slots`. The key names the protected part, not a CSS hook: the
|
||||
* skin only declares an anchor rectangle, the host still owns, paints and
|
||||
* hit-tests the control. Extend this set (for example with `host.permission`)
|
||||
* when another protected control learns the same runtime placement.
|
||||
*/
|
||||
export const HOST_SLOTTABLE_PART_IDS: ReadonlySet<string> = new Set([
|
||||
"host.recovery",
|
||||
]);
|
||||
|
||||
/** 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";
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Browser-safe projections of the administrator update API.
|
||||
*
|
||||
* The console never receives download URLs or local paths. It selects a
|
||||
* version, and the server re-resolves the official GitHub release asset
|
||||
* before doing any work.
|
||||
*/
|
||||
export type UpdateDeploymentMode = "docker" | "release-package" | "source";
|
||||
export type UpdateUpgradePath = "docker-compose" | "release-package" | "source";
|
||||
export type UpdateTaskStatus =
|
||||
| "downloading"
|
||||
| "verifying"
|
||||
| "extracting"
|
||||
| "staging"
|
||||
| "restarting"
|
||||
| "succeeded"
|
||||
| "failed";
|
||||
export type UpdateStepStatus = "running" | "succeeded" | "failed";
|
||||
|
||||
export interface UpdateStepView {
|
||||
name: string;
|
||||
status: UpdateStepStatus;
|
||||
at: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface UpdateTaskView {
|
||||
id: string;
|
||||
status: UpdateTaskStatus;
|
||||
fromVersion: string;
|
||||
targetVersion: string;
|
||||
startedAt: string;
|
||||
updatedAt: string;
|
||||
finishedAt: string | null;
|
||||
errorCode: string | null;
|
||||
errorMessage: string | null;
|
||||
rolledBack: boolean;
|
||||
steps: UpdateStepView[];
|
||||
}
|
||||
|
||||
export interface UpdateDeploymentView {
|
||||
mode: UpdateDeploymentMode;
|
||||
platform: string;
|
||||
architecture: string;
|
||||
applyAllowed: boolean;
|
||||
reasonCode: string | null;
|
||||
upgradePath: UpdateUpgradePath;
|
||||
}
|
||||
|
||||
export interface UpdateStatusView {
|
||||
currentVersion: string;
|
||||
deployment: UpdateDeploymentView;
|
||||
task: UpdateTaskView | null;
|
||||
}
|
||||
|
||||
export interface UpdateReleaseView {
|
||||
version: string;
|
||||
tag: string;
|
||||
publishedAt: string;
|
||||
releaseUrl: string;
|
||||
assetName: string;
|
||||
assetSize: number;
|
||||
assetAvailable: boolean;
|
||||
hasChecksums: boolean;
|
||||
digest: string | null;
|
||||
canApply: boolean;
|
||||
blockedReason: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateCheckView {
|
||||
currentVersion: string;
|
||||
releases: UpdateReleaseView[];
|
||||
}
|
||||
|
||||
export interface UpdateApplyInput {
|
||||
version: string;
|
||||
confirmVersion: string;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { ArchiveError, extractReleaseArchive } from "./archive.js";
|
||||
import { createTarGz, createZip } from "./test-support.js";
|
||||
|
||||
function fixture(t: test.TestContext, name: string, data: Buffer): { directory: string; archive: string; destination: string } {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-archive-"));
|
||||
const archive = path.join(directory, name);
|
||||
writeFileSync(archive, data);
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
return { directory, archive, destination: path.join(directory, "out") };
|
||||
}
|
||||
|
||||
function rejectsWith(code: string) {
|
||||
return (error: unknown) => error instanceof ArchiveError && error.code === code;
|
||||
}
|
||||
|
||||
test("tar.gz release archives extract files and directories", async t => {
|
||||
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
|
||||
{ name: "webspeak/", type: "directory", mode: 0o755 },
|
||||
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
|
||||
{ name: "webspeak/dist/index.js", data: "console.log('ok');\n", mode: 0o755 },
|
||||
]));
|
||||
await extractReleaseArchive(archive, destination, "release.tar.gz");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(readFileSync(path.join(destination, "webspeak/dist/index.js"), "utf8"), "console.log('ok');\n");
|
||||
});
|
||||
|
||||
test("zip release archives extract stored entries", async t => {
|
||||
const { archive, destination } = fixture(t, "release.zip", createZip([
|
||||
{ name: "webspeak/", directory: true },
|
||||
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
|
||||
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>" },
|
||||
]));
|
||||
await extractReleaseArchive(archive, destination, "release.zip");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(readFileSync(path.join(destination, "webspeak/web/dist/index.html"), "utf8"), "<!doctype html>");
|
||||
});
|
||||
|
||||
test("tar entries that traverse or use absolute paths are rejected before writing", async t => {
|
||||
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:/escape.txt"]) {
|
||||
const { directory, archive, destination } = fixture(t, "release.tar.gz", createTarGz([{ name, data: "owned" }]));
|
||||
await assert.rejects(extractReleaseArchive(archive, destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
|
||||
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("zip entries that traverse or use absolute paths are rejected before writing", async t => {
|
||||
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:\\escape.txt"]) {
|
||||
const { directory, archive, destination } = fixture(t, "release.zip", createZip([{ name, data: "owned" }]));
|
||||
await assert.rejects(extractReleaseArchive(archive, destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
|
||||
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("official relative .bin symlinks are accepted and resolve inside the package", async t => {
|
||||
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
|
||||
{ name: "webspeak/", type: "directory" },
|
||||
{ name: "webspeak/node_modules/nanoid/bin/nanoid.cjs", data: "#!/usr/bin/env node\nconsole.log('nanoid');\n", mode: 0o755 },
|
||||
{ name: "webspeak/node_modules/.bin/nanoid", type: "symlink", linkname: "../nanoid/bin/nanoid.cjs" },
|
||||
]));
|
||||
await extractReleaseArchive(archive, destination, "release.tar.gz");
|
||||
const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
|
||||
assert.equal(lstatSync(link).isSymbolicLink(), true);
|
||||
assert.equal(readlinkSync(link), "../nanoid/bin/nanoid.cjs");
|
||||
assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
|
||||
});
|
||||
|
||||
test("zip relative symlinks are accepted while absolute targets are refused", async t => {
|
||||
const accepted = fixture(t, "release.zip", createZip([
|
||||
{ name: "webspeak/real.txt", data: "payload" },
|
||||
{ name: "webspeak/link.txt", data: "real.txt", mode: 0o120777 },
|
||||
]));
|
||||
await extractReleaseArchive(accepted.archive, accepted.destination, "release.zip");
|
||||
const link = path.join(accepted.destination, "webspeak/link.txt");
|
||||
assert.equal(lstatSync(link).isSymbolicLink(), true);
|
||||
assert.equal(readlinkSync(link), "real.txt");
|
||||
assert.equal(readFileSync(link, "utf8"), "payload");
|
||||
|
||||
const refused = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
|
||||
await assert.rejects(extractReleaseArchive(refused.archive, refused.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
});
|
||||
|
||||
test("absolute, escaping, empty and hard-link entries are refused", async t => {
|
||||
const absoluteTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "/etc/passwd" }]));
|
||||
await assert.rejects(extractReleaseArchive(absoluteTar.archive, absoluteTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
const driveTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "C:\\Windows\\system32" }]));
|
||||
await assert.rejects(extractReleaseArchive(driveTar.archive, driveTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
const hardlink = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "hardlink", linkname: "target" }]));
|
||||
await assert.rejects(extractReleaseArchive(hardlink.archive, hardlink.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
for (const linkname of ["", "..", "../outside", "a/../../../outside", "\\etc\\passwd"]) {
|
||||
const escaping = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname }]));
|
||||
await assert.rejects(extractReleaseArchive(escaping.archive, escaping.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
assert.equal(existsSync(path.join(escaping.directory, "outside")), false);
|
||||
}
|
||||
const zipAbsolute = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
|
||||
await assert.rejects(extractReleaseArchive(zipAbsolute.archive, zipAbsolute.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
|
||||
});
|
||||
|
||||
test("unsupported archive formats and malformed archives are rejected", async t => {
|
||||
const unsupported = fixture(t, "release.rar", Buffer.from("not an archive"));
|
||||
await assert.rejects(extractReleaseArchive(unsupported.archive, unsupported.destination, "release.rar"), rejectsWith("UPDATE_ARCHIVE_UNSUPPORTED"));
|
||||
const truncated = fixture(t, "release.tar.gz", Buffer.from("short"));
|
||||
await assert.rejects(extractReleaseArchive(truncated.archive, truncated.destination, "release.tar.gz"));
|
||||
const brokenZip = fixture(t, "release.zip", Buffer.alloc(64));
|
||||
await assert.rejects(extractReleaseArchive(brokenZip.archive, brokenZip.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_INVALID"));
|
||||
const invalidName = fixture(t, "release.tar.gz", createTarGz([{ name: "", data: "x" }]));
|
||||
await assert.rejects(extractReleaseArchive(invalidName.archive, invalidName.destination, "release.tar.gz"));
|
||||
});
|
||||
|
||||
test("declared extraction limits stop archive bombs", async t => {
|
||||
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
|
||||
{ name: "one.txt", data: "one" },
|
||||
{ name: "two.txt", data: "two" },
|
||||
]));
|
||||
await assert.rejects(
|
||||
extractReleaseArchive(archive, destination, "release.tar.gz", { maxEntries: 1 }),
|
||||
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
|
||||
);
|
||||
const fileLimit = fixture(t, "release.zip", createZip([{ name: "big.txt", data: "1234567890" }]));
|
||||
await assert.rejects(
|
||||
extractReleaseArchive(fileLimit.archive, fileLimit.destination, "release.zip", { maxFileBytes: 4 }),
|
||||
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,460 @@
|
||||
import { createReadStream, createWriteStream, type Stats } from "node:fs";
|
||||
import { chmod, mkdir, open, stat, symlink, writeFile, type FileHandle } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { once } from "node:events";
|
||||
import { createGunzip, createInflateRaw } from "node:zlib";
|
||||
import { Transform as StreamTransform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
|
||||
export type ArchiveErrorCode =
|
||||
| "UPDATE_ARCHIVE_INVALID"
|
||||
| "UPDATE_ARCHIVE_UNSAFE"
|
||||
| "UPDATE_ARCHIVE_LIMIT"
|
||||
| "UPDATE_ARCHIVE_UNSUPPORTED";
|
||||
|
||||
export class ArchiveError extends Error {
|
||||
constructor(readonly code: ArchiveErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = "ArchiveError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtractLimits {
|
||||
maxEntries: number;
|
||||
maxTotalBytes: number;
|
||||
maxFileBytes: number;
|
||||
}
|
||||
|
||||
const DEFAULT_LIMITS: ExtractLimits = {
|
||||
maxEntries: 50_000,
|
||||
maxTotalBytes: 4 * 1024 ** 3,
|
||||
maxFileBytes: 2 * 1024 ** 3,
|
||||
};
|
||||
|
||||
export async function extractReleaseArchive(
|
||||
archivePath: string,
|
||||
destination: string,
|
||||
archiveName: string,
|
||||
limits: Partial<ExtractLimits> = {},
|
||||
): Promise<void> {
|
||||
const effective = { ...DEFAULT_LIMITS, ...limits };
|
||||
await mkdir(destination, { recursive: true });
|
||||
if (/\.zip$/i.test(archiveName)) {
|
||||
await extractZip(archivePath, destination, effective);
|
||||
return;
|
||||
}
|
||||
if (/\.(?:tar\.gz|tgz)$/i.test(archiveName)) {
|
||||
await extractTarGz(archivePath, destination, effective);
|
||||
return;
|
||||
}
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "Only .tar.gz and .zip release packages are supported.");
|
||||
}
|
||||
|
||||
function unsafe(message: string): never {
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_UNSAFE", message);
|
||||
}
|
||||
|
||||
function invalid(message: string): never {
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_INVALID", message);
|
||||
}
|
||||
|
||||
function limitExceeded(message: string): never {
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_LIMIT", message);
|
||||
}
|
||||
|
||||
/** Reject absolute paths, drive letters, parent traversal and NUL bytes. */
|
||||
export function safeArchivePath(raw: string): string {
|
||||
if (!raw || raw.includes("\0")) unsafe("Archive entry has an invalid name.");
|
||||
const normalized = raw.replaceAll("\\", "/");
|
||||
if (normalized.startsWith("/")) unsafe("Archive entry uses an absolute path.");
|
||||
if (/^[A-Za-z]:/.test(normalized)) unsafe("Archive entry uses a drive-qualified path.");
|
||||
const parts = normalized.split("/").filter((part) => part !== "" && part !== ".");
|
||||
if (parts.some((part) => part === "..")) unsafe("Archive entry escapes the extraction directory.");
|
||||
return parts.join("/");
|
||||
}
|
||||
|
||||
function resolveEntry(destination: string, relative: string): string {
|
||||
const target = path.resolve(destination, relative);
|
||||
const root = path.resolve(destination);
|
||||
if (target !== root && !target.startsWith(root + path.sep)) unsafe("Archive entry escapes the extraction directory.");
|
||||
return target;
|
||||
}
|
||||
|
||||
const SYMLINK_ROOT = "/__webspeak_extract_root__";
|
||||
|
||||
/**
|
||||
* Official release packages use relative links inside node_modules/.bin
|
||||
* (for example `nanoid -> ../nanoid/bin/nanoid.cjs`). A link is accepted only
|
||||
* when its target is relative and, after lexical normalization, still points
|
||||
* strictly inside the extraction root. Absolute paths, drive letters, parent
|
||||
* traversal, empty targets and links that resolve to the root itself are
|
||||
* rejected before anything is created.
|
||||
*/
|
||||
export function safeSymlinkTarget(entryRelative: string, rawTarget: string): string {
|
||||
if (!rawTarget) unsafe("Archive symbolic link has an empty target.");
|
||||
if (rawTarget.includes("\0")) unsafe("Archive symbolic link target is invalid.");
|
||||
const normalized = rawTarget.replaceAll("\\", "/");
|
||||
if (normalized.startsWith("/")) unsafe("Archive symbolic link uses an absolute target.");
|
||||
if (/^[A-Za-z]:/.test(normalized)) unsafe("Archive symbolic link target is drive-qualified.");
|
||||
const entryDirectory = path.posix.dirname(entryRelative);
|
||||
const resolved = path.posix.resolve(SYMLINK_ROOT, entryDirectory === "." ? "" : entryDirectory, normalized);
|
||||
if (!resolved.startsWith(`${SYMLINK_ROOT}/`)) {
|
||||
unsafe("Archive symbolic link escapes the extraction directory.");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
async function createSymlink(destination: string, relative: string, linkTarget: string): Promise<void> {
|
||||
const root = path.resolve(destination);
|
||||
const target = resolveEntry(destination, relative);
|
||||
// Second boundary check against the real destination, not only the
|
||||
// archive-relative form. The link is never dereferenced while validating.
|
||||
const lexicallyResolved = path.resolve(destination, path.posix.dirname(relative), linkTarget);
|
||||
if (lexicallyResolved === root || !lexicallyResolved.startsWith(root + path.sep)) {
|
||||
unsafe("Archive symbolic link escapes the extraction directory.");
|
||||
}
|
||||
try {
|
||||
await symlink(linkTarget, target);
|
||||
} catch (error) {
|
||||
if (error instanceof ArchiveError) throw error;
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_INVALID", `Archive symbolic link ${relative} could not be created.`);
|
||||
}
|
||||
}
|
||||
|
||||
function isZeroBlock(buffer: Buffer): boolean {
|
||||
for (const byte of buffer) if (byte !== 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function readCString(buffer: Buffer): string {
|
||||
const end = buffer.indexOf(0);
|
||||
return (end >= 0 ? buffer.subarray(0, end) : buffer).toString("utf8");
|
||||
}
|
||||
|
||||
function readOctal(buffer: Buffer): number {
|
||||
const text = readCString(buffer).trim();
|
||||
if (!text) return 0;
|
||||
if (!/^[0-7]+$/.test(text)) invalid("Archive header has an invalid numeric field.");
|
||||
return Number.parseInt(text, 8);
|
||||
}
|
||||
|
||||
function verifyTarChecksum(header: Buffer): void {
|
||||
const expected = readOctal(header.subarray(148, 156));
|
||||
if (!expected) return;
|
||||
let sum = 0;
|
||||
for (let index = 0; index < header.length; index++) {
|
||||
sum += index >= 148 && index < 156 ? 0x20 : header[index];
|
||||
}
|
||||
if (sum !== expected) invalid("Archive header checksum does not match.");
|
||||
}
|
||||
|
||||
interface PaxFields {
|
||||
path?: string;
|
||||
linkpath?: string;
|
||||
}
|
||||
|
||||
function parsePax(buffer: Buffer): PaxFields {
|
||||
const fields: PaxFields = {};
|
||||
let offset = 0;
|
||||
while (offset < buffer.length) {
|
||||
const space = buffer.indexOf(0x20, offset);
|
||||
if (space < 0) break;
|
||||
const length = Number.parseInt(buffer.subarray(offset, space).toString("ascii"), 10);
|
||||
if (!Number.isFinite(length) || length <= 0 || offset + length > buffer.length) break;
|
||||
const record = buffer.subarray(space + 1, offset + length - 1).toString("utf8");
|
||||
const equals = record.indexOf("=");
|
||||
if (equals > 0) {
|
||||
const key = record.slice(0, equals);
|
||||
const value = record.slice(equals + 1);
|
||||
if (key === "path") fields.path = value;
|
||||
else if (key === "linkpath") fields.linkpath = value;
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
class TarReader {
|
||||
private buffer: Buffer = Buffer.alloc(0);
|
||||
private readonly iterator: AsyncIterator<Buffer>;
|
||||
constructor(stream: NodeJS.ReadableStream) {
|
||||
this.iterator = (stream as AsyncIterable<Buffer>)[Symbol.asyncIterator]();
|
||||
}
|
||||
async readExact(size: number): Promise<Buffer> {
|
||||
while (this.buffer.length < size) {
|
||||
const next = await this.iterator.next();
|
||||
if (next.done) invalid("Release archive ended unexpectedly.");
|
||||
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, next.value]) : next.value;
|
||||
}
|
||||
const result = this.buffer.subarray(0, size);
|
||||
this.buffer = this.buffer.subarray(size);
|
||||
return result;
|
||||
}
|
||||
async skip(size: number): Promise<void> {
|
||||
let remaining = size;
|
||||
while (remaining > 0) {
|
||||
const current = this.buffer.length ? this.buffer : undefined;
|
||||
if (current) {
|
||||
const take = Math.min(current.length, remaining);
|
||||
this.buffer = current.subarray(take);
|
||||
remaining -= take;
|
||||
} else {
|
||||
const next = await this.iterator.next();
|
||||
if (next.done) invalid("Release archive ended unexpectedly.");
|
||||
this.buffer = next.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function writeAll(stream: ReturnType<typeof createWriteStream>, chunk: Buffer): Promise<void> {
|
||||
if (!stream.write(chunk)) await once(stream, "drain");
|
||||
}
|
||||
|
||||
async function extractTarGz(file: string, destination: string, limits: ExtractLimits): Promise<void> {
|
||||
const reader = new TarReader(createReadStream(file).pipe(createGunzip()));
|
||||
let entries = 0;
|
||||
let total = 0;
|
||||
let longName: string | undefined;
|
||||
let pax: PaxFields = {};
|
||||
for (;;) {
|
||||
const header = await reader.readExact(512);
|
||||
if (isZeroBlock(header)) break;
|
||||
verifyTarChecksum(header);
|
||||
let name = readCString(header.subarray(0, 100));
|
||||
const prefix = readCString(header.subarray(345, 500));
|
||||
if (prefix) name = `${prefix}/${name}`;
|
||||
const size = readOctal(header.subarray(124, 136));
|
||||
if (size > limits.maxFileBytes) limitExceeded("Archive entry exceeds the file size limit.");
|
||||
const mode = readOctal(header.subarray(100, 108)) & 0o777;
|
||||
const type = header[156] === 0 ? "0" : String.fromCharCode(header[156]);
|
||||
const padded = Math.ceil(size / 512) * 512;
|
||||
if (type === "L") {
|
||||
if (size > 1024 * 1024) limitExceeded("Archive long-name header is too large.");
|
||||
longName = (await reader.readExact(size)).toString("utf8").replace(/\0+$/, "");
|
||||
await reader.skip(padded - size);
|
||||
continue;
|
||||
}
|
||||
if (type === "x" || type === "X") {
|
||||
if (size > 1024 * 1024) limitExceeded("Archive extended header is too large.");
|
||||
pax = { ...pax, ...parsePax(await reader.readExact(size)) };
|
||||
await reader.skip(padded - size);
|
||||
continue;
|
||||
}
|
||||
if (type === "g") {
|
||||
await reader.skip(padded);
|
||||
continue;
|
||||
}
|
||||
const entryName = pax.path ?? longName ?? name;
|
||||
const linkName = pax.linkpath ?? readCString(header.subarray(157, 257));
|
||||
longName = undefined;
|
||||
pax = {};
|
||||
if (!entryName) invalid("Archive entry has no name.");
|
||||
if (type === "1") unsafe(`Archive entry ${entryName} is a hard link; hard links are not accepted.`);
|
||||
if (type !== "0" && type !== "2" && type !== "7" && type !== "5") {
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `Archive entry ${entryName} has unsupported type ${type}.`);
|
||||
}
|
||||
entries++;
|
||||
if (entries > limits.maxEntries) limitExceeded("Archive contains too many entries.");
|
||||
total += size;
|
||||
if (total > limits.maxTotalBytes) limitExceeded("Archive expands beyond the size limit.");
|
||||
const relative = safeArchivePath(entryName);
|
||||
const target = resolveEntry(destination, relative);
|
||||
if (type === "5") {
|
||||
await mkdir(target, { recursive: true, mode: mode || 0o755 });
|
||||
await reader.skip(padded);
|
||||
continue;
|
||||
}
|
||||
if (type === "2") {
|
||||
if (size !== 0) invalid(`Archive symbolic link ${entryName} has unexpected content.`);
|
||||
const linkTarget = safeSymlinkTarget(relative, linkName);
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
await createSymlink(destination, relative, linkTarget);
|
||||
await reader.skip(padded);
|
||||
continue;
|
||||
}
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
const stream = createWriteStream(target, { mode: mode || 0o644, flags: "wx" });
|
||||
try {
|
||||
let remaining = size;
|
||||
while (remaining > 0) {
|
||||
const chunk = await reader.readExact(Math.min(remaining, 64 * 1024));
|
||||
remaining -= chunk.length;
|
||||
await writeAll(stream, chunk);
|
||||
}
|
||||
stream.end();
|
||||
await once(stream, "finish");
|
||||
} catch (error) {
|
||||
stream.destroy();
|
||||
throw error;
|
||||
}
|
||||
await reader.skip(padded - size);
|
||||
}
|
||||
}
|
||||
|
||||
interface ZipEntry {
|
||||
name: string;
|
||||
flags: number;
|
||||
method: number;
|
||||
compressedSize: number;
|
||||
uncompressedSize: number;
|
||||
localOffset: number;
|
||||
mode: number;
|
||||
directory: boolean;
|
||||
symlink: boolean;
|
||||
}
|
||||
|
||||
const EOCD_SIGNATURE = 0x06054b50;
|
||||
const CENTRAL_SIGNATURE = 0x02014b50;
|
||||
const LOCAL_SIGNATURE = 0x04034b50;
|
||||
|
||||
async function readZipEntryBuffer(
|
||||
handle: FileHandle,
|
||||
entry: ZipEntry,
|
||||
file: string,
|
||||
archiveSize: number,
|
||||
limit: number,
|
||||
): Promise<Buffer> {
|
||||
const header = Buffer.alloc(30);
|
||||
await handle.read(header, 0, 30, entry.localOffset);
|
||||
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) invalid(`ZIP entry ${entry.name} has an invalid local header.`);
|
||||
const nameLength = header.readUInt16LE(26);
|
||||
const extraLength = header.readUInt16LE(28);
|
||||
const dataStart = entry.localOffset + 30 + nameLength + extraLength;
|
||||
if (dataStart + entry.compressedSize > archiveSize) invalid(`ZIP entry ${entry.name} is truncated.`);
|
||||
if (entry.compressedSize === 0) return Buffer.alloc(0);
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
const collector = new StreamTransform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
total += chunk.length;
|
||||
if (total > limit) {
|
||||
callback(new ArchiveError("UPDATE_ARCHIVE_UNSAFE", `ZIP symbolic link ${entry.name} has an oversized target.`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const source = createReadStream(file, { start: dataStart, end: dataStart + entry.compressedSize - 1 });
|
||||
if (entry.method === 8) await pipeline(source, createInflateRaw(), collector);
|
||||
else await pipeline(source, collector);
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
async function extractZip(file: string, destination: string, limits: ExtractLimits): Promise<void> {
|
||||
const handle = await open(file, "r");
|
||||
try {
|
||||
const info: Stats = await handle.stat();
|
||||
if (info.size < 22) invalid("ZIP archive is truncated.");
|
||||
const tailSize = Math.min(info.size, 65_557);
|
||||
const tail = Buffer.alloc(tailSize);
|
||||
await handle.read(tail, 0, tailSize, info.size - tailSize);
|
||||
let eocd = -1;
|
||||
for (let index = tail.length - 22; index >= 0; index--) {
|
||||
if (tail.readUInt32LE(index) === EOCD_SIGNATURE) {
|
||||
const commentLength = tail.readUInt16LE(index + 20);
|
||||
if (index + 22 + commentLength === tail.length) { eocd = index; break; }
|
||||
}
|
||||
}
|
||||
if (eocd < 0) invalid("ZIP end-of-directory record was not found.");
|
||||
const entryCount = tail.readUInt16LE(eocd + 10);
|
||||
const directorySize = tail.readUInt32LE(eocd + 12);
|
||||
const directoryOffset = tail.readUInt32LE(eocd + 16);
|
||||
if (entryCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "ZIP64 release packages are not supported.");
|
||||
}
|
||||
if (entryCount > limits.maxEntries) limitExceeded("Archive contains too many entries.");
|
||||
if (directoryOffset + directorySize > info.size) invalid("ZIP central directory is outside the archive.");
|
||||
const directory = Buffer.alloc(directorySize);
|
||||
await handle.read(directory, 0, directorySize, directoryOffset);
|
||||
const entries: ZipEntry[] = [];
|
||||
let offset = 0;
|
||||
let total = 0;
|
||||
for (let index = 0; index < entryCount; index++) {
|
||||
if (offset + 46 > directory.length || directory.readUInt32LE(offset) !== CENTRAL_SIGNATURE) {
|
||||
invalid("ZIP central directory is malformed.");
|
||||
}
|
||||
const versionMadeBy = directory.readUInt16LE(offset + 4);
|
||||
const flags = directory.readUInt16LE(offset + 8);
|
||||
const method = directory.readUInt16LE(offset + 10);
|
||||
const compressedSize = directory.readUInt32LE(offset + 20);
|
||||
const uncompressedSize = directory.readUInt32LE(offset + 24);
|
||||
const nameLength = directory.readUInt16LE(offset + 28);
|
||||
const extraLength = directory.readUInt16LE(offset + 30);
|
||||
const commentLength = directory.readUInt16LE(offset + 32);
|
||||
const externalAttributes = directory.readUInt32LE(offset + 38);
|
||||
const localOffset = directory.readUInt32LE(offset + 42);
|
||||
const nameStart = offset + 46;
|
||||
if (nameStart + nameLength > directory.length) invalid("ZIP entry name is truncated.");
|
||||
const name = directory.subarray(nameStart, nameStart + nameLength).toString("utf8");
|
||||
offset = nameStart + nameLength + extraLength + commentLength;
|
||||
if (flags & 0x1) unsafe(`ZIP entry ${name} is encrypted.`);
|
||||
if (method !== 0 && method !== 8) throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `ZIP entry ${name} uses unsupported compression.`);
|
||||
if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localOffset === 0xffffffff) {
|
||||
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "ZIP64 release packages are not supported.");
|
||||
}
|
||||
const unixMode = versionMadeBy >> 8 === 3 ? externalAttributes >>> 16 : 0;
|
||||
const fileType = unixMode & 0o170000;
|
||||
if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000 && fileType !== 0o120000) {
|
||||
unsafe(`ZIP entry ${name} has an unsupported file type.`);
|
||||
}
|
||||
const symlinkEntry = fileType === 0o120000;
|
||||
if (symlinkEntry && uncompressedSize > 64 * 1024) {
|
||||
unsafe(`ZIP symbolic link ${name} has an oversized target.`);
|
||||
}
|
||||
const directoryEntry = !symlinkEntry && (name.endsWith("/") || fileType === 0o040000);
|
||||
if (!directoryEntry && uncompressedSize > limits.maxFileBytes) limitExceeded("Archive entry exceeds the file size limit.");
|
||||
total += directoryEntry ? 0 : uncompressedSize;
|
||||
if (total > limits.maxTotalBytes) limitExceeded("Archive expands beyond the size limit.");
|
||||
entries.push({
|
||||
name, flags, method, compressedSize, uncompressedSize, localOffset,
|
||||
mode: unixMode & 0o777, directory: directoryEntry, symlink: symlinkEntry,
|
||||
});
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const relative = safeArchivePath(entry.name);
|
||||
if (!relative) invalid("ZIP entry has an empty path.");
|
||||
const target = resolveEntry(destination, relative);
|
||||
if (entry.directory) {
|
||||
await mkdir(target, { recursive: true, mode: entry.mode || 0o755 });
|
||||
continue;
|
||||
}
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
if (entry.symlink) {
|
||||
const rawTarget = (await readZipEntryBuffer(handle, entry, file, info.size, 64 * 1024)).toString("utf8");
|
||||
const linkTarget = safeSymlinkTarget(relative, rawTarget);
|
||||
await createSymlink(destination, relative, linkTarget);
|
||||
continue;
|
||||
}
|
||||
if (entry.compressedSize === 0) {
|
||||
await writeFile(target, Buffer.alloc(0), { mode: entry.mode || 0o644, flag: "wx" });
|
||||
continue;
|
||||
}
|
||||
const header = Buffer.alloc(30);
|
||||
await handle.read(header, 0, 30, entry.localOffset);
|
||||
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) invalid(`ZIP entry ${entry.name} has an invalid local header.`);
|
||||
const nameLength = header.readUInt16LE(26);
|
||||
const extraLength = header.readUInt16LE(28);
|
||||
const dataStart = entry.localOffset + 30 + nameLength + extraLength;
|
||||
if (dataStart + entry.compressedSize > info.size) invalid(`ZIP entry ${entry.name} is truncated.`);
|
||||
const source = createReadStream(file, { start: dataStart, end: dataStart + entry.compressedSize - 1 });
|
||||
let writtenBytes = 0;
|
||||
const limiter = new StreamTransform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
writtenBytes += chunk.length;
|
||||
if (writtenBytes > entry.uncompressedSize) callback(new ArchiveError("UPDATE_ARCHIVE_INVALID", `ZIP entry ${entry.name} exceeds its declared size.`));
|
||||
else callback(null, chunk);
|
||||
},
|
||||
});
|
||||
const sink = createWriteStream(target, { mode: entry.mode || 0o644, flags: "wx" });
|
||||
if (entry.method === 8) await pipeline(source, createInflateRaw(), limiter, sink);
|
||||
else await pipeline(source, limiter, sink);
|
||||
const written = await stat(target);
|
||||
if (written.size !== entry.uncompressedSize) invalid(`ZIP entry ${entry.name} has an unexpected size.`);
|
||||
if (entry.mode) await chmod(target, entry.mode);
|
||||
}
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import {
|
||||
CodeSwapError, locatePackageRoot, restoreCode, setCodeSwapCopyForTests, swapCode, validateStagedPackage,
|
||||
} from "./code-swap.js";
|
||||
import { createPackageFiles } from "./test-support.js";
|
||||
|
||||
function workspace(t: TestContext): string {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
return directory;
|
||||
}
|
||||
|
||||
function packageInvalid(error: unknown): boolean {
|
||||
return error instanceof CodeSwapError && error.code === "UPDATE_PACKAGE_INVALID";
|
||||
}
|
||||
|
||||
function persistentState(root: string): void {
|
||||
writeFileSync(path.join(root, "config.json"), JSON.stringify({ siteName: "kept" }));
|
||||
for (const [directory, file] of [["data", "webspeak.db"], ["certs", "cert.pem"], ["skins", "skin.json"], ["plugins", "plugin.json"]]) {
|
||||
mkdirSync(path.join(root, directory), { recursive: true });
|
||||
writeFileSync(path.join(root, directory, file), `${directory}-content`);
|
||||
}
|
||||
}
|
||||
|
||||
test("staged packages must be complete, regular files and version-matched", t => {
|
||||
const root = workspace(t);
|
||||
createPackageFiles(root, "0.4.0");
|
||||
assert.doesNotThrow(() => validateStagedPackage(root, { version: "0.4.0", platform: "linux" }));
|
||||
assert.throws(() => validateStagedPackage(root, { version: "0.4.1", platform: "linux" }), packageInvalid);
|
||||
|
||||
const missing = workspace(t);
|
||||
createPackageFiles(missing, "0.4.0");
|
||||
rmSync(path.join(missing, "runtime", "node"));
|
||||
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
|
||||
|
||||
const linked = workspace(t);
|
||||
createPackageFiles(linked, "0.4.0");
|
||||
rmSync(path.join(linked, "runtime", "node"));
|
||||
symlinkSync(process.execPath, path.join(linked, "runtime", "node"));
|
||||
assert.throws(() => validateStagedPackage(linked, { version: "0.4.0", platform: "linux" }), packageInvalid);
|
||||
});
|
||||
|
||||
test("locatePackageRoot accepts both bare and single-wrapper layouts", t => {
|
||||
const bare = workspace(t);
|
||||
createPackageFiles(bare, "0.4.0");
|
||||
assert.equal(locatePackageRoot(bare, "0.4.0", "linux"), bare);
|
||||
|
||||
const wrapped = workspace(t);
|
||||
createPackageFiles(path.join(wrapped, "webspeak"), "0.4.0");
|
||||
assert.equal(locatePackageRoot(wrapped, "0.4.0", "linux"), path.join(wrapped, "webspeak"));
|
||||
|
||||
const missing = workspace(t);
|
||||
assert.throws(() => locatePackageRoot(missing, "0.4.0", "linux"), packageInvalid);
|
||||
});
|
||||
|
||||
test("code swap replaces only code and preserves data, config, certs, skins and plugins", t => {
|
||||
const root = workspace(t), staged = path.join(workspace(t), "staged"), backup = path.join(workspace(t), "backup");
|
||||
mkdirSync(path.join(root, "dist"), { recursive: true });
|
||||
mkdirSync(path.join(root, "node_modules"), { recursive: true });
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "old code");
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
|
||||
writeFileSync(path.join(root, "node_modules", "old.txt"), "old dependency");
|
||||
persistentState(root);
|
||||
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code", "node_modules/new.txt": "new dependency" });
|
||||
|
||||
swapCode(root, staged, backup);
|
||||
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "new code");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(readFileSync(path.join(root, "node_modules", "new.txt"), "utf8"), "new dependency");
|
||||
assert.equal(readFileSync(path.join(backup, "dist", "index.js"), "utf8"), "old code");
|
||||
assert.equal(readFileSync(path.join(backup, "node_modules", "old.txt"), "utf8"), "old dependency");
|
||||
for (const [directory, file, contents] of [
|
||||
["data", "webspeak.db", "data-content"], ["certs", "cert.pem", "certs-content"],
|
||||
["skins", "skin.json", "skins-content"], ["plugins", "plugin.json", "plugins-content"],
|
||||
]) {
|
||||
assert.equal(readFileSync(path.join(root, directory, file), "utf8"), contents);
|
||||
assert.equal(existsSync(path.join(backup, directory)), false);
|
||||
}
|
||||
assert.deepEqual(JSON.parse(readFileSync(path.join(root, "config.json"), "utf8")), { siteName: "kept" });
|
||||
assert.equal(existsSync(path.join(backup, "config.json")), false);
|
||||
});
|
||||
|
||||
test("code swap copies across filesystems when rename reports EXDEV", t => {
|
||||
const shared = "/dev/shm";
|
||||
if (!existsSync(shared)) {
|
||||
t.skip("no separate filesystem available for the EXDEV test");
|
||||
return;
|
||||
}
|
||||
const root = path.join(workspace(t), "root"), backup = path.join(workspace(t), "backup");
|
||||
const stagedBase = mkdtempSync(path.join(shared, "webspeak-swap-xdev-"));
|
||||
t.after(() => rmSync(stagedBase, { recursive: true, force: true }));
|
||||
const staged = path.join(stagedBase, "staged");
|
||||
|
||||
mkdirSync(path.join(root, "dist"), { recursive: true });
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "old code");
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
|
||||
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code", "node_modules/new.txt": "new dependency" });
|
||||
if (statSync(root).dev === statSync(staged).dev) {
|
||||
t.skip("tmp and /dev/shm share a device on this system");
|
||||
return;
|
||||
}
|
||||
|
||||
swapCode(root, staged, backup);
|
||||
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "new code");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(readFileSync(path.join(root, "node_modules", "new.txt"), "utf8"), "new dependency");
|
||||
assert.equal(readFileSync(path.join(backup, "dist", "index.js"), "utf8"), "old code");
|
||||
// The copy fallback removes the source only after a successful copy.
|
||||
assert.equal(existsSync(path.join(staged, "dist")), false);
|
||||
assert.equal(existsSync(path.join(staged, "package.json")), false);
|
||||
});
|
||||
|
||||
test("a cross-device copy that fails halfway leaves the complete previous tree in place", t => {
|
||||
const shared = "/dev/shm";
|
||||
if (!existsSync(shared)) {
|
||||
t.skip("no separate filesystem available for the EXDEV test");
|
||||
return;
|
||||
}
|
||||
const root = path.join(workspace(t), "root"), backup = path.join(workspace(t), "backup");
|
||||
const stagedBase = mkdtempSync(path.join(shared, "webspeak-swap-fail-"));
|
||||
t.after(() => {
|
||||
setCodeSwapCopyForTests(null);
|
||||
rmSync(stagedBase, { recursive: true, force: true });
|
||||
});
|
||||
const staged = path.join(stagedBase, "staged");
|
||||
|
||||
mkdirSync(path.join(root, "dist"), { recursive: true });
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "old code");
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
|
||||
persistentState(root);
|
||||
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code" });
|
||||
if (statSync(root).dev === statSync(staged).dev) {
|
||||
t.skip("tmp and /dev/shm share a device on this system");
|
||||
return;
|
||||
}
|
||||
|
||||
let copies = 0;
|
||||
setCodeSwapCopyForTests((_from, to) => {
|
||||
copies += 1;
|
||||
// Simulate the fallback copy dying after it has written part of the
|
||||
// entry, which is exactly the state that must never reach the root.
|
||||
mkdirSync(to, { recursive: true });
|
||||
writeFileSync(path.join(to, "index.js"), "half");
|
||||
throw new Error("simulated copy failure");
|
||||
});
|
||||
|
||||
assert.throws(() => swapCode(root, staged, backup), (error: unknown) =>
|
||||
error instanceof CodeSwapError && error.code === "UPDATE_SWAP_FAILED");
|
||||
assert.equal(copies, 1);
|
||||
|
||||
// The previous tree was restored completely, with no half-copied entry.
|
||||
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "old code");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.equal(readFileSync(path.join(root, "data", "webspeak.db"), "utf8"), "data-content");
|
||||
assert.deepEqual(readdirSync(root).filter((entry) => entry.includes(".copy-")), []);
|
||||
// The backup was not turned into a half-copied source for a later restore.
|
||||
assert.equal(existsSync(path.join(backup, "dist", "index.js")), false);
|
||||
// A failed copy leaves the staged package untouched for diagnosis/retry.
|
||||
assert.equal(readFileSync(path.join(staged, "dist", "index.js"), "utf8"), "new code");
|
||||
});
|
||||
|
||||
test("restoreCode returns the previous code and keeps rejected code for inspection", t => {
|
||||
const root = workspace(t), staged = path.join(workspace(t), "staged"), backup = path.join(workspace(t), "backup");
|
||||
mkdirSync(path.join(root, "dist"), { recursive: true });
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "old code");
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
|
||||
persistentState(root);
|
||||
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code" });
|
||||
|
||||
swapCode(root, staged, backup);
|
||||
restoreCode(root, backup);
|
||||
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "old code");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.equal(readFileSync(path.join(backup, "rejected", "dist", "index.js"), "utf8"), "new code");
|
||||
assert.equal(readFileSync(path.join(root, "data", "webspeak.db"), "utf8"), "data-content");
|
||||
|
||||
assert.throws(() => restoreCode(root, path.join(root, "absent-backup")), (error: unknown) =>
|
||||
error instanceof CodeSwapError && error.code === "UPDATE_ROLLBACK_FAILED");
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { parseStableVersion } from "./version.js";
|
||||
|
||||
/**
|
||||
* Only package code is ever moved. Persistent state (data/, config.json,
|
||||
* certs/) is deliberately absent from this list.
|
||||
*/
|
||||
export const CODE_ENTRIES = [
|
||||
"dist",
|
||||
"web/dist",
|
||||
"node_modules",
|
||||
"runtime",
|
||||
"package.json",
|
||||
"package-lock.json",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"config.example.json",
|
||||
// start-webspeak.sh is deliberately absent: the launcher must stay at the
|
||||
// install root for the whole swap so an interrupted update can still be
|
||||
// recovered by running ./start-webspeak.sh. It is installed atomically by
|
||||
// the updater before the runner swaps any code.
|
||||
"start-webspeak.cmd",
|
||||
] as const;
|
||||
|
||||
export type CodeSwapErrorCode = "UPDATE_PACKAGE_INVALID" | "UPDATE_SWAP_FAILED" | "UPDATE_ROLLBACK_FAILED";
|
||||
|
||||
export class CodeSwapError extends Error {
|
||||
constructor(readonly code: CodeSwapErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = "CodeSwapError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface StagedPackageOptions {
|
||||
version: string;
|
||||
platform?: NodeJS.Platform;
|
||||
}
|
||||
|
||||
function requireEntry(root: string, relative: string, kind: "file" | "directory"): void {
|
||||
const target = path.join(root, relative);
|
||||
let stats;
|
||||
try { stats = lstatSync(target); }
|
||||
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package is missing ${relative}.`); }
|
||||
if (stats.isSymbolicLink()) throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package entry ${relative} is a symbolic link.`);
|
||||
if (kind === "file" ? !stats.isFile() : !stats.isDirectory()) {
|
||||
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package entry ${relative} has the wrong type.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The extracted package must be a complete runnable release for this platform. */
|
||||
export function validateStagedPackage(root: string, options: StagedPackageOptions): void {
|
||||
requireEntry(root, "dist/index.js", "file");
|
||||
requireEntry(root, "web/dist/index.html", "file");
|
||||
requireEntry(root, "node_modules", "directory");
|
||||
requireEntry(root, "package.json", "file");
|
||||
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
|
||||
let manifest: unknown;
|
||||
try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); }
|
||||
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); }
|
||||
const version = manifest && typeof manifest === "object" && !Array.isArray(manifest)
|
||||
? (manifest as Record<string, unknown>).version
|
||||
: undefined;
|
||||
if (!parseStableVersion(version) || version !== options.version) {
|
||||
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package version does not match the selected release.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Archives usually contain one wrapper directory; accept both layouts. */
|
||||
export function locatePackageRoot(extractedDir: string, version: string, platform?: NodeJS.Platform): string {
|
||||
const entries = readdirSync(extractedDir, { withFileTypes: true });
|
||||
const root = entries.length === 1 && entries[0].isDirectory()
|
||||
? path.join(extractedDir, entries[0].name)
|
||||
: extractedDir;
|
||||
if (!existsSync(path.join(root, "package.json"))) {
|
||||
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package root was not found after extraction.");
|
||||
}
|
||||
validateStagedPackage(root, { version, platform });
|
||||
return root;
|
||||
}
|
||||
|
||||
function moveEntry(from: string, to: string): void {
|
||||
try {
|
||||
renameSync(from, to);
|
||||
return;
|
||||
} catch (error) {
|
||||
// Staging and backups may live on another filesystem than the install
|
||||
// directory. A rename cannot cross devices, so fall back to a copy.
|
||||
if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
|
||||
}
|
||||
// Copy into a temporary sibling first: a failure halfway through must
|
||||
// never leave a partial entry at `to`, because rollback would otherwise
|
||||
// mistake it for the complete previous version.
|
||||
const temporary = `${to}.copy-${process.pid}-${randomBytes(6).toString("hex")}`;
|
||||
try {
|
||||
copyEntry(from, temporary);
|
||||
renameSync(temporary, to);
|
||||
} catch (error) {
|
||||
rmSync(temporary, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
// The copy is committed at `to`. Removing the source is cleanup only.
|
||||
try { rmSync(from, { recursive: true, force: true }); } catch { /* Source remains for later cleanup. */ }
|
||||
}
|
||||
|
||||
type CopyEntry = (from: string, to: string) => void;
|
||||
|
||||
const defaultCopyEntry: CopyEntry = (from, to) => {
|
||||
cpSync(from, to, { recursive: true, force: false, errorOnExist: true, preserveTimestamps: true });
|
||||
};
|
||||
|
||||
let copyEntry: CopyEntry = defaultCopyEntry;
|
||||
|
||||
/** Test seam for exercising a cross-device copy that fails halfway through. */
|
||||
export function setCodeSwapCopyForTests(copy: CopyEntry | null): void {
|
||||
copyEntry = copy ?? defaultCopyEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test-only fault-injection seam. When the named directory exists, the swap
|
||||
* pauses in the exact window between "old code moved aside" and "new code
|
||||
* moved in" so a test can SIGKILL the runner. Production never sets this
|
||||
* variable; it is a local barrier directory, not a URL or network switch.
|
||||
*/
|
||||
const SWAP_BARRIER_ENV = "WEBSPEAK_TEST_SWAP_BARRIER_DIR";
|
||||
|
||||
function swapWindowBarrier(entry?: string): void {
|
||||
const directory = process.env[SWAP_BARRIER_ENV];
|
||||
if (!directory || !existsSync(directory)) return;
|
||||
if ((process.env.WEBSPEAK_TEST_SWAP_BARRIER_AFTER_ENTRY ?? "") !== (entry ?? "")) return;
|
||||
writeFileSync(path.join(directory, "swap-window-reached"), String(process.pid));
|
||||
const resume = path.join(directory, "resume");
|
||||
const deadline = Date.now() + 30_000;
|
||||
const waiter = new Int32Array(new SharedArrayBuffer(4));
|
||||
while (!existsSync(resume) && Date.now() < deadline) {
|
||||
Atomics.wait(waiter, 0, 0, 20);
|
||||
}
|
||||
}
|
||||
|
||||
function moveIfPresent(from: string, to: string): void {
|
||||
if (!existsSync(from)) return;
|
||||
mkdirSync(path.dirname(to), { recursive: true });
|
||||
moveEntry(from, to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backups written by this version contain only atomically moved entries.
|
||||
* The manifest records which entries were moved completely, so a backup that
|
||||
* was partially written by an older implementation (or tampered with) can be
|
||||
* rejected instead of overwriting an intact install tree.
|
||||
*/
|
||||
const SWAP_MANIFEST = ".webspeak-swap.json";
|
||||
|
||||
function writeSwapManifest(backupDir: string, entries: string[]): void {
|
||||
const target = path.join(backupDir, SWAP_MANIFEST);
|
||||
const temporary = `${target}.${process.pid}.tmp`;
|
||||
writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, entries }, null, 2), "utf8");
|
||||
renameSync(temporary, target);
|
||||
}
|
||||
|
||||
function readSwapManifest(backupDir: string): Set<string> | null {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(path.join(backupDir, SWAP_MANIFEST), "utf8"));
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
||||
const record = parsed as Record<string, unknown>;
|
||||
if (record.schemaVersion !== 1 || !Array.isArray(record.entries)) return null;
|
||||
return new Set(record.entries.filter((entry): entry is string => typeof entry === "string"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo only the entries that this swap actually moved. The entry whose move
|
||||
* failed is left untouched: its source is still intact and no partial
|
||||
* destination exists.
|
||||
*/
|
||||
function restoreMovedEntries(rootDir: string, backupDir: string, movedToBackup: string[], movedToRoot: string[]): void {
|
||||
const rejected = path.join(backupDir, "rejected");
|
||||
for (const entry of [...movedToRoot].reverse()) {
|
||||
moveIfPresent(path.join(rootDir, entry), path.join(rejected, entry));
|
||||
}
|
||||
for (const entry of [...movedToBackup].reverse()) {
|
||||
const saved = path.join(backupDir, entry);
|
||||
if (!existsSync(saved)) continue;
|
||||
const current = path.join(rootDir, entry);
|
||||
if (existsSync(current)) moveIfPresent(current, path.join(rejected, entry));
|
||||
moveIfPresent(saved, current);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the previous code aside, then move the verified side-by-side package
|
||||
* into place. `data/`, `config.json` and `certs/` are never in CODE_ENTRIES.
|
||||
*/
|
||||
export function swapCode(rootDir: string, stagedRoot: string, backupDir: string): void {
|
||||
const movedToBackup: string[] = [];
|
||||
const movedToRoot: string[] = [];
|
||||
try {
|
||||
if (existsSync(backupDir)) throw new Error("Backup directory already exists.");
|
||||
mkdirSync(backupDir, { recursive: true });
|
||||
writeSwapManifest(backupDir, []);
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
if (!existsSync(path.join(rootDir, entry))) continue;
|
||||
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
|
||||
movedToBackup.push(entry);
|
||||
swapWindowBarrier(entry);
|
||||
writeSwapManifest(backupDir, movedToBackup);
|
||||
}
|
||||
swapWindowBarrier();
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
if (!existsSync(path.join(stagedRoot, entry))) continue;
|
||||
moveIfPresent(path.join(stagedRoot, entry), path.join(rootDir, entry));
|
||||
movedToRoot.push(entry);
|
||||
}
|
||||
} catch (error) {
|
||||
try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
|
||||
catch { /* Report the original swap error; rollback failure is handled by the caller. */ }
|
||||
if (error instanceof CodeSwapError) throw error;
|
||||
throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore the previous code. New code is moved aside instead of deleted so it
|
||||
* remains available for diagnostics. When a swap manifest exists, only
|
||||
* entries it proves were moved completely are considered.
|
||||
*/
|
||||
export function restoreCode(rootDir: string, backupDir: string): void {
|
||||
if (!existsSync(backupDir)) throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", "Code backup directory is missing.");
|
||||
const manifest = readSwapManifest(backupDir);
|
||||
const rejected = path.join(backupDir, "rejected");
|
||||
try {
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
if (manifest && !manifest.has(entry)) continue;
|
||||
const current = path.join(rootDir, entry);
|
||||
if (existsSync(current) && existsSync(path.join(backupDir, entry))) {
|
||||
moveIfPresent(current, path.join(rejected, entry));
|
||||
}
|
||||
}
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
if (manifest && !manifest.has(entry)) continue;
|
||||
moveIfPresent(path.join(backupDir, entry), path.join(rootDir, entry));
|
||||
}
|
||||
} catch (error) {
|
||||
throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", error instanceof Error ? error.message : "Code rollback failed.");
|
||||
}
|
||||
}
|
||||
|
||||
export function removeStagingDirectory(directory: string): void {
|
||||
try { rmSync(directory, { recursive: true, force: true }); } catch { /* Best-effort cleanup. */ }
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import {
|
||||
assetKindFor, detectDeployment as detectRealDeployment, isReleasePackageRoot, releaseAssetName, runningUnderSupervisor, upgradePathFor,
|
||||
} from "./deployment.js";
|
||||
import type { DeploymentDetectionOptions } from "./deployment.js";
|
||||
|
||||
// Tests may themselves run inside the CI runner's systemd service.
|
||||
function detectDeployment(options: DeploymentDetectionOptions) {
|
||||
return detectRealDeployment({ isSupervised: false, ...options });
|
||||
}
|
||||
|
||||
function temporary(t: test.TestContext): string {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-deployment-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
return directory;
|
||||
}
|
||||
|
||||
function releasePackageRoot(t: test.TestContext, platform: "linux" | "win32" = "linux"): string {
|
||||
const root = temporary(t);
|
||||
const runtime = platform === "win32" ? "node.exe" : "node";
|
||||
for (const directory of ["runtime", "dist", "web/dist"]) mkdirSync(path.join(root, directory), { recursive: true });
|
||||
writeFileSync(path.join(root, "runtime", runtime), "");
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "");
|
||||
writeFileSync(path.join(root, "web", "dist", "index.html"), "");
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "1.0.0" }));
|
||||
return root;
|
||||
}
|
||||
|
||||
test("an explicit release-package override cannot bypass container detection", () => {
|
||||
const env = { WEBSPEAK_DEPLOYMENT_MODE: "release-package" };
|
||||
const info = detectDeployment({ rootDir: "/does/not/exist", env, isDocker: true, platform: "linux", architecture: "x64" });
|
||||
assert.equal(info.mode, "docker");
|
||||
assert.equal(info.applyAllowed, false);
|
||||
assert.equal(info.reasonCode, "DEPLOYMENT_DOCKER");
|
||||
assert.equal(info.upgradePath, "docker-compose");
|
||||
});
|
||||
|
||||
test("an explicit release-package override requires a complete package tree", t => {
|
||||
const missing = detectDeployment({
|
||||
rootDir: "/does/not/exist",
|
||||
env: { WEBSPEAK_DEPLOYMENT_MODE: "release-package" },
|
||||
isDocker: false,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
});
|
||||
assert.equal(missing.mode, "source");
|
||||
assert.equal(missing.applyAllowed, false);
|
||||
assert.equal(missing.reasonCode, "DEPLOYMENT_SOURCE");
|
||||
|
||||
const root = releasePackageRoot(t);
|
||||
const complete = detectDeployment({
|
||||
rootDir: root,
|
||||
env: { WEBSPEAK_DEPLOYMENT_MODE: "release-package" },
|
||||
isDocker: false,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
});
|
||||
assert.equal(complete.mode, "release-package");
|
||||
assert.equal(complete.applyAllowed, true);
|
||||
assert.equal(complete.reasonCode, null);
|
||||
});
|
||||
|
||||
test("docker and source deployments never allow an in-console apply", () => {
|
||||
const docker = detectDeployment({ rootDir: "/does/not/exist", env: {}, isDocker: true, platform: "linux", architecture: "x64" });
|
||||
assert.deepEqual(
|
||||
{ mode: docker.mode, applyAllowed: docker.applyAllowed, reasonCode: docker.reasonCode, upgradePath: docker.upgradePath },
|
||||
{ mode: "docker", applyAllowed: false, reasonCode: "DEPLOYMENT_DOCKER", upgradePath: "docker-compose" },
|
||||
);
|
||||
const source = detectDeployment({ rootDir: "/does/not/exist", env: {}, isDocker: false, platform: "linux", architecture: "x64" });
|
||||
assert.deepEqual(
|
||||
{ mode: source.mode, applyAllowed: source.applyAllowed, reasonCode: source.reasonCode, upgradePath: source.upgradePath },
|
||||
{ mode: "source", applyAllowed: false, reasonCode: "DEPLOYMENT_SOURCE", upgradePath: "source" },
|
||||
);
|
||||
});
|
||||
|
||||
test("a complete packaged tree is detected as a release package", t => {
|
||||
const root = releasePackageRoot(t);
|
||||
assert.equal(isReleasePackageRoot(root, "linux"), true);
|
||||
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
|
||||
assert.equal(info.mode, "release-package");
|
||||
assert.equal(info.assetKind, "linux-arm64");
|
||||
assert.equal(info.applyAllowed, false);
|
||||
assert.equal(info.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
|
||||
assert.equal(detectDeployment({ rootDir: root, env: { WEBSPEAK_DEPLOYMENT_MODE: "docker" }, isDocker: false, platform: "linux" }).mode, "docker");
|
||||
});
|
||||
|
||||
test("incomplete trees stay in source mode", t => {
|
||||
const root = temporary(t);
|
||||
assert.equal(isReleasePackageRoot(root, "linux"), false);
|
||||
mkdirSync(path.join(root, "runtime"), { recursive: true });
|
||||
writeFileSync(path.join(root, "runtime", "node"), "");
|
||||
assert.equal(isReleasePackageRoot(root, "linux"), false);
|
||||
});
|
||||
|
||||
test("asset names and platform support are pinned to official release shapes", () => {
|
||||
assert.equal(assetKindFor("linux", "x64"), "linux-x64");
|
||||
assert.equal(assetKindFor("linux", "arm64"), "linux-arm64");
|
||||
assert.equal(assetKindFor("win32", "x64"), "windows-x64");
|
||||
assert.equal(assetKindFor("linux", "riscv64"), null);
|
||||
assert.equal(assetKindFor("darwin", "arm64"), null);
|
||||
assert.equal(releaseAssetName("0.4.0", "linux-x64"), "webspeak-webclient-v0.4.0-linux-x64.tar.gz");
|
||||
assert.equal(releaseAssetName("0.4.0", "linux-arm64"), "webspeak-webclient-v0.4.0-linux-arm64.tar.gz");
|
||||
assert.equal(releaseAssetName("0.4.0", "windows-x64"), "webspeak-webclient-v0.4.0-windows-x64.zip");
|
||||
assert.equal(upgradePathFor("docker"), "docker-compose");
|
||||
assert.equal(upgradePathFor("release-package"), "release-package");
|
||||
assert.equal(upgradePathFor("source"), "source");
|
||||
});
|
||||
|
||||
test("windows release packages are visible but apply stays disabled", t => {
|
||||
const root = releasePackageRoot(t, "win32");
|
||||
const windows = detectDeployment({
|
||||
rootDir: root,
|
||||
env: {},
|
||||
isDocker: false,
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
});
|
||||
assert.equal(windows.mode, "release-package");
|
||||
assert.equal(windows.assetKind, "windows-x64");
|
||||
assert.equal(windows.applyAllowed, false);
|
||||
assert.equal(windows.reasonCode, "WINDOWS_APPLY_UNVERIFIED");
|
||||
assert.equal(windows.upgradePath, "release-package");
|
||||
|
||||
const linux = detectDeployment({
|
||||
rootDir: releasePackageRoot(t),
|
||||
env: {},
|
||||
isDocker: false,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
});
|
||||
assert.equal(linux.applyAllowed, true);
|
||||
assert.equal(linux.reasonCode, null);
|
||||
});
|
||||
|
||||
test("linux arm64 release packages are checkable but apply is gated off", t => {
|
||||
const root = releasePackageRoot(t);
|
||||
const arm64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
|
||||
assert.equal(arm64.mode, "release-package");
|
||||
assert.equal(arm64.assetKind, "linux-arm64");
|
||||
assert.equal(arm64.applyAllowed, false);
|
||||
assert.equal(arm64.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
|
||||
assert.equal(arm64.upgradePath, "release-package");
|
||||
|
||||
const x64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "x64" });
|
||||
assert.equal(x64.applyAllowed, true);
|
||||
assert.equal(x64.reasonCode, null);
|
||||
});
|
||||
|
||||
test("unsupported platforms are visible but cannot apply", t => {
|
||||
const root = releasePackageRoot(t);
|
||||
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "s390x" });
|
||||
assert.equal(info.mode, "release-package");
|
||||
assert.equal(info.applyAllowed, false);
|
||||
assert.equal(info.reasonCode, "ARCH_UNSUPPORTED");
|
||||
const darwin = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "darwin", architecture: "arm64" });
|
||||
assert.equal(darwin.applyAllowed, false);
|
||||
assert.equal(darwin.reasonCode, "PLATFORM_UNSUPPORTED");
|
||||
});
|
||||
|
||||
test("supervised packages cannot apply even with a release-package override", t => {
|
||||
const root = releasePackageRoot(t);
|
||||
for (const env of [{ INVOCATION_ID: "unit-invocation" }, { pm_id: "0" }, { SUPERVISOR_PROCESS_NAME: "webspeak" }]) {
|
||||
assert.equal(runningUnderSupervisor(env, ""), true);
|
||||
const deployment = detectDeployment({ rootDir: root, platform: "linux", architecture: "x64", isDocker: false,
|
||||
isSupervised: undefined, env: { ...env, WEBSPEAK_DEPLOYMENT_MODE: "release-package" } });
|
||||
assert.equal(deployment.mode, "release-package");
|
||||
assert.equal(deployment.applyAllowed, false);
|
||||
assert.equal(deployment.reasonCode, "DEPLOYMENT_SUPERVISED");
|
||||
assert.equal(deployment.assetKind, "linux-x64");
|
||||
}
|
||||
});
|
||||
|
||||
test("service cgroups are detected without blocking interactive user scopes", () => {
|
||||
assert.equal(runningUnderSupervisor({}, "0::/system.slice/webspeak.service\n"), true);
|
||||
assert.equal(runningUnderSupervisor({}, "0::/user.slice/user-1000.slice/user@1000.service/app.slice/webspeak.service\n"), true);
|
||||
assert.equal(runningUnderSupervisor({}, "0::/user.slice/user-1000.slice/user@1000.service/app.slice/terminal.scope\n"), false);
|
||||
assert.equal(runningUnderSupervisor({}, "0::/\n"), false);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { UpdateDeploymentMode, UpdateDeploymentView, UpdateUpgradePath } from "../shared/update.js";
|
||||
|
||||
export interface DeploymentDetectionOptions {
|
||||
rootDir: string;
|
||||
platform?: NodeJS.Platform;
|
||||
architecture?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
/** Test seam; omitted means inspect the real container markers. */
|
||||
isDocker?: boolean;
|
||||
/** Test seam; omitted means inspect service-manager environment and cgroups. */
|
||||
isSupervised?: boolean;
|
||||
}
|
||||
|
||||
export interface DeploymentInfo extends UpdateDeploymentView {
|
||||
platform: NodeJS.Platform;
|
||||
assetKind: "linux-x64" | "linux-arm64" | "windows-x64" | null;
|
||||
}
|
||||
|
||||
export function detectDeployment(options: DeploymentDetectionOptions): DeploymentInfo {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const architecture = options.architecture ?? process.arch;
|
||||
const env = options.env ?? process.env;
|
||||
const explicit = env.WEBSPEAK_DEPLOYMENT_MODE?.trim().toLowerCase();
|
||||
const packaged = isReleasePackageRoot(options.rootDir, platform);
|
||||
let mode: UpdateDeploymentMode;
|
||||
// Container detection always wins: an explicit "release-package" override
|
||||
// must never make an image replaceable from inside the container.
|
||||
if (explicit === "docker" || (options.isDocker ?? runningInContainer(env))) {
|
||||
mode = "docker";
|
||||
} else if (explicit === "source") {
|
||||
mode = "source";
|
||||
} else {
|
||||
// An explicit "release-package" only counts when the tree really is a
|
||||
// complete release package; otherwise applying would be unsafe.
|
||||
mode = packaged ? "release-package" : "source";
|
||||
}
|
||||
const assetKind = mode === "release-package" ? assetKindFor(platform, architecture) : null;
|
||||
let applyAllowed = mode === "release-package" && assetKind !== null;
|
||||
let reasonCode: string | null = null;
|
||||
if (mode === "docker") reasonCode = "DEPLOYMENT_DOCKER";
|
||||
else if (mode === "source") reasonCode = "DEPLOYMENT_SOURCE";
|
||||
else if (!assetKind) reasonCode = platform !== "linux" && platform !== "win32" ? "PLATFORM_UNSUPPORTED" : "ARCH_UNSUPPORTED";
|
||||
else if (platform === "win32") {
|
||||
// The copy-node.exe-then-swap approach has not been verified against a
|
||||
// real Windows release package. Report versions, but never fake an apply.
|
||||
applyAllowed = false;
|
||||
reasonCode = "WINDOWS_APPLY_UNVERIFIED";
|
||||
} else if (platform === "linux" && architecture === "arm64") {
|
||||
// arm64 packages are built and can be checked, but the in-place swap has
|
||||
// only been exercised on x64. Gate on the detected capability itself so
|
||||
// "unverified" is never rendered as "can apply" in the UI.
|
||||
applyAllowed = false;
|
||||
reasonCode = "LINUX_ARM64_APPLY_UNVERIFIED";
|
||||
} else if (options.isSupervised ?? runningUnderSupervisor(env)) {
|
||||
// A detached child stays inside its systemd cgroup, and other supervisors
|
||||
// can restart the old app while the runner is swapping it. Until there is
|
||||
// a supervisor-aware handoff, only foreground packages may apply updates.
|
||||
applyAllowed = false;
|
||||
reasonCode = "DEPLOYMENT_SUPERVISED";
|
||||
}
|
||||
return {
|
||||
mode,
|
||||
platform,
|
||||
architecture,
|
||||
applyAllowed,
|
||||
reasonCode,
|
||||
upgradePath: upgradePathFor(mode),
|
||||
assetKind,
|
||||
};
|
||||
}
|
||||
|
||||
export function runningUnderSupervisor(env: NodeJS.ProcessEnv = process.env, cgroup?: string): boolean {
|
||||
if (["INVOCATION_ID", "JOURNAL_STREAM", "NOTIFY_SOCKET", "SYSTEMD_EXEC_PID", "pm_id", "PM2_HOME", "SUPERVISOR_ENABLED", "SUPERVISOR_PROCESS_NAME"]
|
||||
.some((name) => Boolean(env[name]?.trim()))) return true;
|
||||
if (cgroup === undefined) {
|
||||
try { cgroup = readFileSync("/proc/self/cgroup", "utf8"); }
|
||||
catch { return false; }
|
||||
}
|
||||
// The user manager itself is not the app's supervisor: interactive shells
|
||||
// also run below user@UID.service. App-specific services still count.
|
||||
return cgroup.split(/[\n/]/).some((part) => part.endsWith(".service") && !/^user@\d+\.service$/.test(part));
|
||||
}
|
||||
|
||||
export function runningInContainer(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
if (env.WEBSPEAK_DEPLOYMENT_MODE?.trim().toLowerCase() === "docker") return true;
|
||||
if (existsSync("/.dockerenv")) return true;
|
||||
if (env.container) return true;
|
||||
try {
|
||||
const cgroup = readFileSync("/proc/1/cgroup", "utf8");
|
||||
return /(?:docker|kubepods|containerd|libpod|podman)/i.test(cgroup);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isReleasePackageRoot(rootDir: string, platform: NodeJS.Platform = process.platform): boolean {
|
||||
const runtime = platform === "win32" ? path.join(rootDir, "runtime", "node.exe") : path.join(rootDir, "runtime", "node");
|
||||
return existsSync(runtime)
|
||||
&& existsSync(path.join(rootDir, "dist", "index.js"))
|
||||
&& existsSync(path.join(rootDir, "web", "dist", "index.html"))
|
||||
&& existsSync(path.join(rootDir, "package.json"));
|
||||
}
|
||||
|
||||
export function assetKindFor(platform: NodeJS.Platform, architecture: string): DeploymentInfo["assetKind"] {
|
||||
if (platform === "win32" && architecture === "x64") return "windows-x64";
|
||||
if (platform === "linux" && architecture === "x64") return "linux-x64";
|
||||
if (platform === "linux" && architecture === "arm64") return "linux-arm64";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function releaseAssetName(version: string, assetKind: NonNullable<DeploymentInfo["assetKind"]>): string {
|
||||
return assetKind === "windows-x64"
|
||||
? `webspeak-webclient-v${version}-windows-x64.zip`
|
||||
: `webspeak-webclient-v${version}-${assetKind}.tar.gz`;
|
||||
}
|
||||
|
||||
export function upgradePathFor(mode: UpdateDeploymentMode): UpdateUpgradePath {
|
||||
return mode === "docker" ? "docker-compose" : mode === "release-package" ? "release-package" : "source";
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { compareVersions, parseReleaseTag } from "./version.js";
|
||||
|
||||
export const OFFICIAL_REPOSITORY = "EchoSixHIYA/WebSpeak-client-for-TeamSpeak";
|
||||
export const CHECKSUM_ASSET_NAME = "SHA256SUMS.txt";
|
||||
|
||||
export interface ReleaseAsset {
|
||||
name: string;
|
||||
size: number;
|
||||
url: string;
|
||||
digest: string | null;
|
||||
}
|
||||
|
||||
export interface OfficialRelease {
|
||||
version: string;
|
||||
tag: string;
|
||||
publishedAt: string;
|
||||
releaseUrl: string;
|
||||
assets: ReleaseAsset[];
|
||||
}
|
||||
|
||||
export type ReleaseSourceErrorCode = "UPDATE_RELEASE_UNAVAILABLE";
|
||||
|
||||
export class ReleaseSourceError extends Error {
|
||||
readonly code: ReleaseSourceErrorCode = "UPDATE_RELEASE_UNAVAILABLE";
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ReleaseSourceError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReleaseSourceOptions {
|
||||
fetch?: typeof fetch;
|
||||
apiBaseUrl?: string;
|
||||
repository?: string;
|
||||
userAgent?: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
const ALLOWED_DOWNLOAD_HOSTS = new Set([
|
||||
"github.com",
|
||||
"api.github.com",
|
||||
"objects.githubusercontent.com",
|
||||
"release-assets.githubusercontent.com",
|
||||
]);
|
||||
|
||||
export class GitHubReleaseSource {
|
||||
private readonly fetcher: typeof fetch;
|
||||
private readonly apiBaseUrl: string;
|
||||
private readonly repository: string;
|
||||
private readonly userAgent: string;
|
||||
private readonly timeoutMs: number;
|
||||
constructor(options: ReleaseSourceOptions = {}) {
|
||||
this.fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
|
||||
this.apiBaseUrl = (options.apiBaseUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
||||
this.repository = options.repository ?? OFFICIAL_REPOSITORY;
|
||||
this.userAgent = options.userAgent ?? "WebSpeak-Console-Updater";
|
||||
this.timeoutMs = options.timeoutMs ?? 12_000;
|
||||
}
|
||||
|
||||
private get owner(): string {
|
||||
return this.repository.split("/")[0];
|
||||
}
|
||||
|
||||
private get repo(): string {
|
||||
return this.repository.split("/")[1];
|
||||
}
|
||||
|
||||
async listStableReleases(): Promise<OfficialRelease[]> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.fetcher(`${this.apiBaseUrl}/repos/${this.repository}/releases?per_page=30`, {
|
||||
headers: {
|
||||
accept: "application/vnd.github+json",
|
||||
"user-agent": this.userAgent,
|
||||
"x-github-api-version": "2022-11-28",
|
||||
},
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
redirect: "error",
|
||||
});
|
||||
} catch {
|
||||
throw new ReleaseSourceError("The official release list could not be reached.");
|
||||
}
|
||||
if (!response.ok) throw new ReleaseSourceError(`The official release list returned HTTP ${response.status}.`);
|
||||
let value: unknown;
|
||||
try { value = await response.json(); }
|
||||
catch { throw new ReleaseSourceError("The official release list is not valid JSON."); }
|
||||
if (!Array.isArray(value)) throw new ReleaseSourceError("The official release list is not an array.");
|
||||
const releases: OfficialRelease[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const entry of value) {
|
||||
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
if (record.draft === true || record.prerelease === true) continue;
|
||||
const tag = typeof record.tag_name === "string" ? record.tag_name : "";
|
||||
const version = parseReleaseTag(tag)?.text;
|
||||
if (!version || seen.has(version)) continue;
|
||||
const releaseUrl = typeof record.html_url === "string" ? record.html_url : "";
|
||||
if (!isOfficialReleasePage(releaseUrl, this.owner, this.repo)) continue;
|
||||
const assets: ReleaseAsset[] = [];
|
||||
if (Array.isArray(record.assets)) {
|
||||
for (const asset of record.assets) {
|
||||
if (!asset || typeof asset !== "object" || Array.isArray(asset)) continue;
|
||||
const item = asset as Record<string, unknown>;
|
||||
const name = typeof item.name === "string" ? item.name : "";
|
||||
const url = typeof item.browser_download_url === "string" ? item.browser_download_url : "";
|
||||
if (!name || !url) continue;
|
||||
try { assertOfficialDownloadUrl(url, this.owner, this.repo); }
|
||||
catch { continue; }
|
||||
assets.push({
|
||||
name,
|
||||
size: typeof item.size === "number" && Number.isFinite(item.size) ? item.size : 0,
|
||||
url,
|
||||
digest: typeof item.digest === "string" && item.digest ? item.digest : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
seen.add(version);
|
||||
releases.push({
|
||||
version,
|
||||
tag,
|
||||
publishedAt: typeof record.published_at === "string" ? record.published_at : "",
|
||||
releaseUrl,
|
||||
assets,
|
||||
});
|
||||
}
|
||||
return releases.sort((left, right) => compareVersions(right.version, left.version));
|
||||
}
|
||||
|
||||
async findRelease(version: string): Promise<OfficialRelease | null> {
|
||||
const releases = await this.listStableReleases();
|
||||
return releases.find((release) => release.version === version) ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isOfficialReleasePage(value: string, owner: string, repo: string): boolean {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:"
|
||||
&& !url.username && !url.password
|
||||
&& url.hostname === "github.com"
|
||||
&& url.pathname.startsWith(`/${owner}/${repo}/releases/`);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only GitHub-owned hosts are accepted. For the release download path the
|
||||
* repository prefix is pinned so a tampered asset URL cannot point elsewhere.
|
||||
*/
|
||||
export function assertOfficialDownloadUrl(value: string, owner: string, repo: string): void {
|
||||
let url: URL;
|
||||
try { url = new URL(value); }
|
||||
catch { throw new ReleaseSourceError("The release asset URL is invalid."); }
|
||||
if (url.protocol !== "https:" || url.username || url.password || !ALLOWED_DOWNLOAD_HOSTS.has(url.hostname)) {
|
||||
throw new ReleaseSourceError("The release asset is not hosted on an official GitHub domain.");
|
||||
}
|
||||
if (url.hostname === "github.com" && !url.pathname.startsWith(`/${owner}/${repo}/releases/download/`)) {
|
||||
throw new ReleaseSourceError("The release asset is not part of the official repository.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { runRestartPlan } from "./restart-runner.js";
|
||||
|
||||
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
async function availablePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const port = address.port;
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
return port;
|
||||
}
|
||||
|
||||
async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!check()) {
|
||||
if (Date.now() > deadline) throw new Error("timed out waiting for condition");
|
||||
await sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
function appScript(version: string, port: number, pidFile: string): string {
|
||||
return `const http = require("node:http");
|
||||
const { writeFileSync } = require("node:fs");
|
||||
const server = http.createServer((request, response) => {
|
||||
if (request.url === "/api/health") {
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify({ status: "ok", version: ${JSON.stringify(version)} }));
|
||||
return;
|
||||
}
|
||||
response.statusCode = 404;
|
||||
response.end();
|
||||
});
|
||||
server.listen(${port}, "127.0.0.1", () => writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)));
|
||||
process.on("SIGTERM", () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 1000).unref(); });
|
||||
`;
|
||||
}
|
||||
|
||||
interface RunnerFixture {
|
||||
directory: string;
|
||||
rootDir: string;
|
||||
stagedRoot: string;
|
||||
backupDir: string;
|
||||
planPath: string;
|
||||
statePath: string;
|
||||
lockPath: string;
|
||||
pidFile: string;
|
||||
taskId: string;
|
||||
}
|
||||
|
||||
function runnerFixture(t: TestContext): RunnerFixture {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-runner-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
const rootDir = path.join(directory, "app");
|
||||
const stagedRoot = path.join(directory, "staged");
|
||||
const backupDir = path.join(directory, "backup");
|
||||
const statePath = path.join(directory, "data", "updates", "state.json");
|
||||
const lockPath = path.join(directory, "data", "updates", "update.lock");
|
||||
const taskId = "upd_runner_test";
|
||||
for (const directoryName of ["data", "config.json", "certs", "skins", "plugins"]) {
|
||||
const target = path.join(rootDir, directoryName);
|
||||
if (directoryName === "config.json") writeFileSync(target, JSON.stringify({ kept: true }));
|
||||
else {
|
||||
mkdirSync(target, { recursive: true });
|
||||
writeFileSync(path.join(target, "marker.txt"), `${directoryName} preserved`);
|
||||
}
|
||||
}
|
||||
for (const [root, version] of [[rootDir, "1.0.0"], [stagedRoot, "2.0.0"]] as const) {
|
||||
mkdirSync(path.join(root, "dist"), { recursive: true });
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version }));
|
||||
writeFileSync(path.join(root, "dist", "index.js"), `// version marker ${version}\n`);
|
||||
}
|
||||
return {
|
||||
directory, rootDir, stagedRoot, backupDir, statePath, lockPath, taskId,
|
||||
pidFile: path.join(directory, "app.pid"),
|
||||
planPath: path.join(directory, "plan.json"),
|
||||
};
|
||||
}
|
||||
|
||||
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; healthTimeoutMs?: number }) {
|
||||
mkdirSync(path.dirname(fixture.statePath), { recursive: true });
|
||||
writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() }));
|
||||
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile));
|
||||
writeFileSync(fixture.planPath, JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
taskId: fixture.taskId,
|
||||
rootDir: fixture.rootDir,
|
||||
statePath: fixture.statePath,
|
||||
lockPath: fixture.lockPath,
|
||||
stagedRoot: fixture.stagedRoot,
|
||||
backupDir: fixture.backupDir,
|
||||
fromVersion: "1.0.0",
|
||||
targetVersion: options.targetVersion,
|
||||
nodePath: process.execPath,
|
||||
appEntry: path.join(fixture.rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port, path: "/api/health" },
|
||||
waitForPid: null,
|
||||
parentTimeoutMs: 2_000,
|
||||
healthTimeoutMs: options.healthTimeoutMs ?? 1_500,
|
||||
pollIntervalMs: 50,
|
||||
appLogPath: path.join(fixture.directory, "app.log"),
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
async function stopPidFile(pidFile: string): Promise<void> {
|
||||
if (!existsSync(pidFile)) return;
|
||||
const pid = Number(readFileSync(pidFile, "utf8"));
|
||||
if (Number.isInteger(pid) && pid > 0) {
|
||||
try { process.kill(pid, "SIGTERM"); } catch { /* Already gone. */ }
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
try { process.kill(pid, 0); await sleep(50); }
|
||||
catch { return; }
|
||||
}
|
||||
try { process.kill(pid, "SIGKILL"); } catch { /* Already gone. */ }
|
||||
}
|
||||
}
|
||||
|
||||
test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
const port = await availablePort();
|
||||
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
|
||||
t.after(() => stopPidFile(fixture.pidFile));
|
||||
|
||||
assert.equal(await runRestartPlan(fixture.planPath), 0);
|
||||
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
|
||||
assert.equal(state.task.status, "succeeded");
|
||||
assert.equal(state.task.finishedAt === null, false);
|
||||
assert.deepEqual(state.task.steps.map((step: { name: string; status: string }) => [step.name, step.status]), [
|
||||
["restart", "succeeded"],
|
||||
["swap", "succeeded"],
|
||||
]);
|
||||
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "2\.0\.0"/);
|
||||
assert.match(readFileSync(path.join(fixture.backupDir, "dist", "index.js"), "utf8"), /version marker 1\.0\.0/);
|
||||
for (const directoryName of ["data", "certs", "skins", "plugins"]) {
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, directoryName, "marker.txt"), "utf8"), `${directoryName} preserved`);
|
||||
}
|
||||
assert.deepEqual(JSON.parse(readFileSync(path.join(fixture.rootDir, "config.json"), "utf8")), { kept: true });
|
||||
assert.equal(existsSync(fixture.lockPath), false);
|
||||
assert.equal(existsSync(fixture.stagedRoot), false);
|
||||
await waitFor(() => existsSync(fixture.pidFile));
|
||||
});
|
||||
|
||||
test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
const port = await availablePort();
|
||||
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "9.9.9", healthTimeoutMs: 800 });
|
||||
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
|
||||
// Simulate the previous process still serving while the runner takes over.
|
||||
const previous = spawn(process.execPath, [path.join(fixture.rootDir, "dist", "index.js")], { stdio: "ignore", detached: true });
|
||||
previous.unref();
|
||||
t.after(async () => { await stopPidFile(fixture.pidFile); try { previous.kill("SIGKILL"); } catch { /* Exited. */ } });
|
||||
await waitFor(() => existsSync(fixture.pidFile) && Number(readFileSync(fixture.pidFile, "utf8")) === previous.pid);
|
||||
|
||||
assert.equal(await runRestartPlan(fixture.planPath), 1);
|
||||
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
|
||||
assert.equal(state.task.status, "failed");
|
||||
assert.equal(state.task.rolledBack, true);
|
||||
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
|
||||
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
|
||||
assert.match(readFileSync(path.join(fixture.backupDir, "rejected", "dist", "index.js"), "utf8"), /version: "9\.9\.9"/);
|
||||
for (const directoryName of ["data", "certs", "skins", "plugins"]) {
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, directoryName, "marker.txt"), "utf8"), `${directoryName} preserved`);
|
||||
}
|
||||
assert.deepEqual(JSON.parse(readFileSync(path.join(fixture.rootDir, "config.json"), "utf8")), { kept: true });
|
||||
assert.equal(existsSync(fixture.lockPath), false);
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { CodeSwapError, restoreCode, swapCode } from "./code-swap.js";
|
||||
import { takeOverUpdateLock } from "./update-state.js";
|
||||
import type { PersistedUpdateState } from "./update-state.js";
|
||||
import type { UpdateTaskView } from "../shared/update.js";
|
||||
|
||||
export interface RestartPlan {
|
||||
schemaVersion: 1;
|
||||
taskId: string;
|
||||
rootDir: string;
|
||||
statePath: string;
|
||||
lockPath: string;
|
||||
stagedRoot: string;
|
||||
backupDir: string;
|
||||
fromVersion: string;
|
||||
targetVersion: string;
|
||||
/** Absolute path to the runtime bundled with the package (or a test stub). */
|
||||
nodePath: string;
|
||||
/** Absolute path to dist/index.js after the swap. */
|
||||
appEntry: string;
|
||||
health: { protocol: "http" | "https"; port: number; path: string };
|
||||
waitForPid: number | null;
|
||||
parentTimeoutMs: number;
|
||||
healthTimeoutMs: number;
|
||||
pollIntervalMs: number;
|
||||
appLogPath: string;
|
||||
}
|
||||
|
||||
class RunnerError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "RunnerError";
|
||||
}
|
||||
}
|
||||
|
||||
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
function readPlan(planPath: string): RestartPlan {
|
||||
const parsed: unknown = JSON.parse(readFileSync(planPath, "utf8"));
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new RunnerError("UPDATE_PLAN_INVALID", "Restart plan is invalid.");
|
||||
const plan = parsed as Record<string, unknown>;
|
||||
if (plan.schemaVersion !== 1
|
||||
|| typeof plan.taskId !== "string"
|
||||
|| typeof plan.rootDir !== "string"
|
||||
|| typeof plan.statePath !== "string"
|
||||
|| typeof plan.lockPath !== "string"
|
||||
|| typeof plan.stagedRoot !== "string"
|
||||
|| typeof plan.backupDir !== "string"
|
||||
|| typeof plan.fromVersion !== "string"
|
||||
|| typeof plan.targetVersion !== "string"
|
||||
|| typeof plan.nodePath !== "string"
|
||||
|| typeof plan.appEntry !== "string"
|
||||
|| !plan.health || typeof plan.health !== "object") {
|
||||
throw new RunnerError("UPDATE_PLAN_INVALID", "Restart plan is incomplete.");
|
||||
}
|
||||
const health = plan.health as Record<string, unknown>;
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
taskId: plan.taskId,
|
||||
rootDir: plan.rootDir,
|
||||
statePath: plan.statePath,
|
||||
lockPath: plan.lockPath,
|
||||
stagedRoot: plan.stagedRoot,
|
||||
backupDir: plan.backupDir,
|
||||
fromVersion: plan.fromVersion,
|
||||
targetVersion: plan.targetVersion,
|
||||
nodePath: plan.nodePath,
|
||||
appEntry: plan.appEntry,
|
||||
health: {
|
||||
protocol: health.protocol === "https" ? "https" : "http",
|
||||
port: typeof health.port === "number" ? health.port : 3040,
|
||||
path: typeof health.path === "string" ? health.path : "/api/health",
|
||||
},
|
||||
waitForPid: typeof plan.waitForPid === "number" && Number.isFinite(plan.waitForPid) ? plan.waitForPid : null,
|
||||
parentTimeoutMs: typeof plan.parentTimeoutMs === "number" ? plan.parentTimeoutMs : 60_000,
|
||||
healthTimeoutMs: typeof plan.healthTimeoutMs === "number" ? plan.healthTimeoutMs : 90_000,
|
||||
pollIntervalMs: typeof plan.pollIntervalMs === "number" ? plan.pollIntervalMs : 500,
|
||||
appLogPath: typeof plan.appLogPath === "string" ? plan.appLogPath : path.join(path.dirname(plan.statePath), "app.log"),
|
||||
};
|
||||
}
|
||||
|
||||
function loadState(plan: RestartPlan): PersistedUpdateState {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(plan.statePath, "utf8"));
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
&& (parsed as Record<string, unknown>).schemaVersion === 1
|
||||
&& (parsed as Record<string, unknown>).task
|
||||
&& typeof (parsed as Record<string, unknown>).task === "object"
|
||||
&& ((parsed as { task: { id?: unknown } }).task.id === plan.taskId)) {
|
||||
return parsed as PersistedUpdateState;
|
||||
}
|
||||
} catch { /* Build a task below. */ }
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: plan.taskId,
|
||||
status: "restarting",
|
||||
fromVersion: plan.fromVersion,
|
||||
targetVersion: plan.targetVersion,
|
||||
startedAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
finishedAt: null,
|
||||
errorCode: null,
|
||||
errorMessage: null,
|
||||
rolledBack: false,
|
||||
steps: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
class StateWriter {
|
||||
private state: PersistedUpdateState;
|
||||
constructor(private readonly plan: RestartPlan) {
|
||||
this.state = loadState(plan);
|
||||
}
|
||||
private write(): void {
|
||||
const task = this.state.task!;
|
||||
task.updatedAt = new Date().toISOString();
|
||||
mkdirSync(path.dirname(this.plan.statePath), { recursive: true });
|
||||
const temporary = `${this.plan.statePath}.${process.pid}.tmp`;
|
||||
writeFileSync(temporary, JSON.stringify(this.state, null, 2), "utf8");
|
||||
renameSync(temporary, this.plan.statePath);
|
||||
}
|
||||
get task(): UpdateTaskView {
|
||||
return this.state.task!;
|
||||
}
|
||||
step(name: string, status: UpdateTaskView["steps"][number]["status"], detail?: string): void {
|
||||
const task = this.state.task!;
|
||||
const existing = task.steps.find((step) => step.name === name);
|
||||
const at = new Date().toISOString();
|
||||
if (existing) {
|
||||
existing.status = status;
|
||||
existing.at = at;
|
||||
if (detail) existing.detail = detail;
|
||||
} else {
|
||||
task.steps.push({ name, status, at, ...(detail ? { detail } : {}) });
|
||||
}
|
||||
this.write();
|
||||
}
|
||||
status(status: UpdateTaskView["status"], error?: { code: string; message: string }): void {
|
||||
const task = this.state.task!;
|
||||
task.status = status;
|
||||
if (error) {
|
||||
task.errorCode = error.code;
|
||||
task.errorMessage = error.message;
|
||||
}
|
||||
if (status === "succeeded" || status === "failed") task.finishedAt = new Date().toISOString();
|
||||
this.write();
|
||||
}
|
||||
rolledBack(value: boolean): void {
|
||||
this.state.task!.rolledBack = value;
|
||||
this.write();
|
||||
}
|
||||
}
|
||||
|
||||
function processAlive(pid: number | null): boolean {
|
||||
if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForParent(pid: number | null, timeoutMs: number): Promise<void> {
|
||||
if (!pid) return;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (processAlive(pid)) {
|
||||
if (Date.now() > deadline) throw new RunnerError("UPDATE_RESTART_TIMEOUT", "The previous process did not stop in time.");
|
||||
await sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
interface HealthResponse {
|
||||
status?: string;
|
||||
version?: string;
|
||||
}
|
||||
|
||||
function probeHealth(plan: RestartPlan): Promise<HealthResponse | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = plan.health.protocol === "https" ? https : http;
|
||||
const request = client.get({
|
||||
hostname: "127.0.0.1",
|
||||
port: plan.health.port,
|
||||
path: plan.health.path,
|
||||
timeout: 2_000,
|
||||
...(plan.health.protocol === "https" ? { rejectUnauthorized: false } : {}),
|
||||
}, (response) => {
|
||||
if (response.statusCode !== 200) { response.resume(); resolve(null); return; }
|
||||
let body = "";
|
||||
response.setEncoding("utf8");
|
||||
response.on("data", (chunk: string) => { if (body.length < 64 * 1024) body += chunk; });
|
||||
response.on("end", () => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(body);
|
||||
resolve(parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as HealthResponse : null);
|
||||
} catch { resolve(null); }
|
||||
});
|
||||
response.on("error", () => resolve(null));
|
||||
});
|
||||
request.on("timeout", () => request.destroy());
|
||||
request.on("error", () => resolve(null));
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: number): Promise<HealthResponse | null> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let last: HealthResponse | null = null;
|
||||
while (Date.now() < deadline) {
|
||||
last = await probeHealth(plan);
|
||||
if (last?.status === "ok" && last.version === version) return last;
|
||||
await sleep(plan.pollIntervalMs);
|
||||
}
|
||||
return last?.version === version ? last : null;
|
||||
}
|
||||
|
||||
function startApp(plan: RestartPlan): ChildProcess {
|
||||
mkdirSync(path.dirname(plan.appLogPath), { recursive: true });
|
||||
const log = openSync(plan.appLogPath, "a");
|
||||
try {
|
||||
const child = spawn(plan.nodePath, [plan.appEntry], {
|
||||
cwd: plan.rootDir,
|
||||
env: process.env,
|
||||
detached: true,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", log, log],
|
||||
});
|
||||
child.unref();
|
||||
return child;
|
||||
} finally {
|
||||
closeSync(log);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureApp(plan: RestartPlan, expectedVersion: string): Promise<boolean> {
|
||||
let healthy = await waitForVersion(plan, expectedVersion, Math.min(5_000, plan.healthTimeoutMs));
|
||||
if (healthy) return true;
|
||||
let child: ChildProcess | undefined;
|
||||
try {
|
||||
child = startApp(plan);
|
||||
healthy = await waitForVersion(plan, expectedVersion, plan.healthTimeoutMs);
|
||||
if (healthy) return true;
|
||||
await stopApp(child);
|
||||
return false;
|
||||
} finally {
|
||||
child?.unref();
|
||||
}
|
||||
}
|
||||
|
||||
function exited(child: ChildProcess): boolean {
|
||||
return child.exitCode !== null || child.signalCode !== null;
|
||||
}
|
||||
|
||||
async function stopApp(child: ChildProcess | undefined): Promise<void> {
|
||||
if (!child || exited(child)) return;
|
||||
try { child.kill("SIGTERM"); } catch { /* Already gone. */ }
|
||||
const deadline = Date.now() + 6_000;
|
||||
while (!exited(child) && Date.now() < deadline) await sleep(100);
|
||||
if (exited(child)) return;
|
||||
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
|
||||
const hardDeadline = Date.now() + 2_000;
|
||||
while (!exited(child) && Date.now() < hardDeadline) await sleep(100);
|
||||
}
|
||||
|
||||
export async function runRestartPlan(planPath: string): Promise<number> {
|
||||
const plan = readPlan(planPath);
|
||||
const state = new StateWriter(plan);
|
||||
let swapped = false;
|
||||
let newApp: ChildProcess | undefined;
|
||||
state.status("restarting");
|
||||
state.step("restart", "running");
|
||||
// Take over the update lock before doing anything else. The parent process
|
||||
// is about to exit and its lock would otherwise have a dead pid, letting a
|
||||
// second instance starting in this window roll the healthy code back.
|
||||
let releaseLock: (() => void) | null = null;
|
||||
try {
|
||||
try {
|
||||
releaseLock = takeOverUpdateLock(plan.lockPath, plan.taskId);
|
||||
} catch (error) {
|
||||
throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over.");
|
||||
}
|
||||
await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
|
||||
state.step("swap", "running");
|
||||
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
|
||||
swapped = true;
|
||||
state.step("swap", "succeeded");
|
||||
let healthy = await waitForVersion(plan, plan.targetVersion, Math.min(5_000, plan.healthTimeoutMs));
|
||||
if (!healthy) {
|
||||
newApp = startApp(plan);
|
||||
healthy = await waitForVersion(plan, plan.targetVersion, plan.healthTimeoutMs);
|
||||
}
|
||||
if (!healthy) throw new RunnerError("UPDATE_HEALTH_CHECK_FAILED", `The updated version did not report ${plan.targetVersion} on /api/health.`);
|
||||
state.step("restart", "succeeded");
|
||||
state.status("succeeded");
|
||||
releaseLock();
|
||||
releaseLock = null;
|
||||
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
|
||||
return 0;
|
||||
} catch (error) {
|
||||
await stopApp(newApp);
|
||||
const code = error instanceof RunnerError || error instanceof CodeSwapError
|
||||
? error.code
|
||||
: "UPDATE_RESTART_FAILED";
|
||||
const message = error instanceof Error ? error.message : "The update could not be completed.";
|
||||
state.step("restart", "failed", message);
|
||||
let rolledBack = !swapped;
|
||||
if (swapped) {
|
||||
state.step("rollback", "running");
|
||||
try {
|
||||
restoreCode(plan.rootDir, plan.backupDir);
|
||||
state.step("rollback", "succeeded");
|
||||
rolledBack = true;
|
||||
} catch (rollbackError) {
|
||||
state.step("rollback", "failed", rollbackError instanceof Error ? rollbackError.message : "Code rollback failed.");
|
||||
state.rolledBack(false);
|
||||
state.status("failed", { code: "UPDATE_ROLLBACK_FAILED", message: `${message} Code rollback also failed.` });
|
||||
releaseLock?.();
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
const healthy = await ensureApp(plan, plan.fromVersion);
|
||||
state.rolledBack(rolledBack);
|
||||
if (!healthy) {
|
||||
state.status("failed", { code: "UPDATE_ROLLBACK_HEALTH_FAILED", message: `${message} The previous version did not become healthy.` });
|
||||
} else {
|
||||
state.status("failed", { code, message });
|
||||
}
|
||||
releaseLock?.();
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const planPath = process.argv[2];
|
||||
if (!planPath) {
|
||||
console.error("Usage: restart-runner <plan.json>");
|
||||
process.exit(2);
|
||||
}
|
||||
runRestartPlan(planPath)
|
||||
.then((code) => process.exit(code))
|
||||
.catch((error) => {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { createServer } from "node:net";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { UpdateService } from "./update-service.js";
|
||||
import { CODE_ENTRIES } from "./code-swap.js";
|
||||
|
||||
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
|
||||
const LAUNCHER_SOURCE = path.join(REPO_ROOT, "scripts", "start-webspeak.sh");
|
||||
const RUNNER_SOURCE = path.join(SOURCE_DIR, "restart-runner.ts");
|
||||
const TASK_ID = "upd_sigkill_window";
|
||||
|
||||
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
// Exercise a kill after every old entry's rename, before the manifest is
|
||||
// updated. In particular the backup is still partial for the first entries.
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
test(`launcher recovers a SIGKILL immediately after moving old ${entry}`, { timeout: 30_000, skip: process.platform !== "linux" }, async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port, true);
|
||||
// The Linux package need not contain the Windows launcher, but include it
|
||||
// here so the entire code-entry list has a tested interruption point.
|
||||
writeFileSync(path.join(fixture.rootDir, "start-webspeak.cmd"), "old launcher");
|
||||
const runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
|
||||
cwd: REPO_ROOT,
|
||||
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir, WEBSPEAK_TEST_SWAP_BARRIER_AFTER_ENTRY: entry },
|
||||
stdio: "ignore",
|
||||
});
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => { stop(app); stop(runner); });
|
||||
await waitFor(() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")), `runner never reached ${entry}`);
|
||||
stop(runner);
|
||||
await waitFor(() => !processAlive(runner.pid), "runner did not stop", 5_000);
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir, env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir }, stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), `launcher failed after ${entry}`);
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
|
||||
for (const [key, file] of Object.entries(fixture.markerFiles)) {
|
||||
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`);
|
||||
}
|
||||
const stale = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup", "package.json");
|
||||
assert.equal(JSON.parse(readFileSync(stale, "utf8")).version, "0.1.0");
|
||||
stop(app);
|
||||
await waitFor(() => !processAlive(app?.pid), "app did not stop", 5_000);
|
||||
});
|
||||
}
|
||||
|
||||
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
async function availablePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function waitFor(check: () => boolean | Promise<boolean>, message: string, timeoutMs = 15_000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!(await check())) {
|
||||
if (Date.now() > deadline) throw new Error(message);
|
||||
await sleep(25);
|
||||
}
|
||||
}
|
||||
|
||||
async function healthVersion(port: number): Promise<string | null> {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1_000) });
|
||||
if (!response.ok) return null;
|
||||
const body = await response.json() as { status?: string; version?: string };
|
||||
return body.status === "ok" ? body.version ?? null : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function processAlive(pid: number | undefined): boolean {
|
||||
if (!pid || pid <= 0) return false;
|
||||
try { process.kill(pid, 0); return true; }
|
||||
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
|
||||
}
|
||||
|
||||
function stop(child: ChildProcess | undefined): void {
|
||||
if (!child || !processAlive(child.pid)) return;
|
||||
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
|
||||
}
|
||||
|
||||
/** The stub reports the version from package.json, as the real app does. */
|
||||
function appScript(): string {
|
||||
return `const http = require("node:http");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const config = JSON.parse(fs.readFileSync(path.join(process.cwd(), "config.json"), "utf8"));
|
||||
const version = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")).version;
|
||||
http.createServer((request, response) => {
|
||||
if (request.url === "/api/health") {
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify({ status: "ok", version }));
|
||||
return;
|
||||
}
|
||||
response.statusCode = 404;
|
||||
response.end();
|
||||
}).listen(config.port, "127.0.0.1", () => fs.writeFileSync(config.startedFile, version));
|
||||
`;
|
||||
}
|
||||
|
||||
interface Fixture {
|
||||
directory: string;
|
||||
rootDir: string;
|
||||
dataDir: string;
|
||||
stagedRoot: string;
|
||||
backupDir: string;
|
||||
barrierDir: string;
|
||||
port: number;
|
||||
markerFiles: Record<string, string>;
|
||||
}
|
||||
|
||||
function buildFixture(t: TestContext, port: number, withStaleBackup = false): Fixture {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-recovery-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
const rootDir = path.join(directory, "app");
|
||||
const dataDir = path.join(rootDir, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
const stagedRoot = path.join(updatesDir, "tasks", TASK_ID, "staged");
|
||||
const backupDir = path.join(updatesDir, "backups", TASK_ID);
|
||||
const barrierDir = path.join(directory, "barrier");
|
||||
|
||||
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
|
||||
mkdirSync(path.join(rootDir, relative), { recursive: true });
|
||||
}
|
||||
writeFileSync(path.join(rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
|
||||
writeFileSync(path.join(rootDir, "package-lock.json"), "{}");
|
||||
writeFileSync(path.join(rootDir, "README.md"), "old readme");
|
||||
writeFileSync(path.join(rootDir, "LICENSE"), "old license");
|
||||
writeFileSync(path.join(rootDir, "config.example.json"), "{}");
|
||||
writeFileSync(path.join(rootDir, "web", "dist", "index.html"), "<!doctype html>\n");
|
||||
writeFileSync(path.join(rootDir, "node_modules", ".keep"), "");
|
||||
writeFileSync(path.join(rootDir, "dist", "index.js"), appScript());
|
||||
copyFileSync(process.execPath, path.join(rootDir, "runtime", "node"));
|
||||
chmodSync(path.join(rootDir, "runtime", "node"), 0o755);
|
||||
// This is the same file CI ships and applyUpdate installs before the swap.
|
||||
copyFileSync(LAUNCHER_SOURCE, path.join(rootDir, "start-webspeak.sh"));
|
||||
chmodSync(path.join(rootDir, "start-webspeak.sh"), 0o755);
|
||||
|
||||
const markerFiles: Record<string, string> = {
|
||||
config: path.join(rootDir, "config.json"),
|
||||
database: path.join(dataDir, "webspeak.db"),
|
||||
identity: path.join(dataDir, "identity.key"),
|
||||
cert: path.join(rootDir, "certs", "cert.pem"),
|
||||
skin: path.join(dataDir, "skins", "skin.json"),
|
||||
plugin: path.join(dataDir, "plugins", "plugin.json"),
|
||||
};
|
||||
mkdirSync(path.dirname(markerFiles.database), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.identity), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.cert), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.skin), { recursive: true });
|
||||
mkdirSync(path.dirname(markerFiles.plugin), { recursive: true });
|
||||
writeFileSync(markerFiles.config, JSON.stringify({ port, startedFile: path.join(directory, "started.txt") }));
|
||||
for (const [key, value] of Object.entries(markerFiles)) {
|
||||
if (key !== "config") writeFileSync(value, `${key} preserved`);
|
||||
}
|
||||
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
mkdirSync(stagedRoot, { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "dist"), { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "web", "dist"), { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "node_modules"), { recursive: true });
|
||||
mkdirSync(path.join(stagedRoot, "runtime"), { recursive: true });
|
||||
writeFileSync(path.join(stagedRoot, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
|
||||
writeFileSync(path.join(stagedRoot, "package-lock.json"), "{}");
|
||||
writeFileSync(path.join(stagedRoot, "README.md"), "new readme");
|
||||
writeFileSync(path.join(stagedRoot, "LICENSE"), "new license");
|
||||
writeFileSync(path.join(stagedRoot, "config.example.json"), "{}");
|
||||
writeFileSync(path.join(stagedRoot, "dist", "index.js"), "// new code marker\n");
|
||||
writeFileSync(path.join(stagedRoot, "web", "dist", "index.html"), "<!doctype html>\n");
|
||||
writeFileSync(path.join(stagedRoot, "node_modules", ".keep"), "");
|
||||
writeFileSync(path.join(stagedRoot, "runtime", "node"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
||||
copyFileSync(LAUNCHER_SOURCE, path.join(stagedRoot, "start-webspeak.sh"));
|
||||
|
||||
writeFileSync(path.join(updatesDir, "state.json"), JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: TASK_ID, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
}));
|
||||
writeFileSync(path.join(updatesDir, "update.lock"), JSON.stringify({ pid: 0, taskId: TASK_ID, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writeFileSync(path.join(updatesDir, "plan.json"), JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
taskId: TASK_ID,
|
||||
rootDir,
|
||||
statePath: path.join(updatesDir, "state.json"),
|
||||
lockPath: path.join(updatesDir, "update.lock"),
|
||||
stagedRoot,
|
||||
backupDir,
|
||||
fromVersion: "0.3.2",
|
||||
targetVersion: "0.4.0",
|
||||
nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port, path: "/api/health" },
|
||||
waitForPid: null,
|
||||
parentTimeoutMs: 2_000,
|
||||
healthTimeoutMs: 300,
|
||||
pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
if (withStaleBackup) {
|
||||
// A complete backup from an earlier, already successful update. Its name
|
||||
// sorts before the in-progress task's id, so the old "first complete
|
||||
// backup wins" launcher logic would wrongly restore this older build.
|
||||
const staleDir = path.join(updatesDir, "backups", "aaa_stale_backup");
|
||||
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
|
||||
mkdirSync(path.join(staleDir, relative), { recursive: true });
|
||||
}
|
||||
writeFileSync(path.join(staleDir, "dist", "index.js"), appScript());
|
||||
writeFileSync(path.join(staleDir, "web", "dist", "index.html"), "<!doctype html>\n");
|
||||
writeFileSync(path.join(staleDir, "node_modules", ".keep"), "");
|
||||
writeFileSync(path.join(staleDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.1.0" }));
|
||||
writeFileSync(path.join(staleDir, "package-lock.json"), "{}");
|
||||
writeFileSync(path.join(staleDir, "README.md"), "stale readme");
|
||||
writeFileSync(path.join(staleDir, "LICENSE"), "stale license");
|
||||
writeFileSync(path.join(staleDir, "config.example.json"), "{}");
|
||||
copyFileSync(process.execPath, path.join(staleDir, "runtime", "node"));
|
||||
chmodSync(path.join(staleDir, "runtime", "node"), 0o755);
|
||||
writeFileSync(path.join(staleDir, ".webspeak-swap.json"), JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
entries: ["dist", "web/dist", "node_modules", "runtime", "package.json", "package-lock.json", "README.md", "LICENSE", "config.example.json"],
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
mkdirSync(barrierDir, { recursive: true });
|
||||
|
||||
return { directory, rootDir, dataDir, stagedRoot, backupDir, barrierDir, port, markerFiles };
|
||||
}
|
||||
|
||||
test(
|
||||
"SIGKILL in the exact swap window is recovered by the official launcher with data intact",
|
||||
{ timeout: 40_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port);
|
||||
let runner: ChildProcess | undefined;
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => { stop(app); stop(runner); });
|
||||
|
||||
let runnerOutput = "";
|
||||
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
|
||||
cwd: REPO_ROOT,
|
||||
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
await waitFor(
|
||||
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
|
||||
`runner never reached the exact swap window: ${runnerOutput}`,
|
||||
);
|
||||
|
||||
// Precisely the failure state: old dist moved aside, new dist not yet in.
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "start-webspeak.sh")), true, "official launcher survived the swap");
|
||||
|
||||
stop(runner);
|
||||
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
|
||||
|
||||
// Restart through the shipped launcher itself, not a harness wrapper.
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "official launcher did not restore a healthy install");
|
||||
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
|
||||
for (const [key, file] of Object.entries(fixture.markerFiles)) {
|
||||
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
|
||||
}
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "rejected", "dist")), false, "no partial new code in the install root");
|
||||
|
||||
// Once Node is up, the existing initialize() path records the real failure.
|
||||
stop(app);
|
||||
await waitFor(() => !processAlive(app?.pid), "app did not stop", 5_000);
|
||||
const service = new UpdateService({
|
||||
rootDir: fixture.rootDir,
|
||||
dataDir: fixture.dataDir,
|
||||
currentVersion: "0.3.2",
|
||||
logger,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
env: {},
|
||||
isDocker: false,
|
||||
});
|
||||
service.initialize();
|
||||
const status = service.getStatus();
|
||||
assert.equal(status.task?.status, "failed");
|
||||
assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
|
||||
assert.equal(status.task?.rolledBack, true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"recovery prefers the in-progress task backup over an older lexicographically-first backup",
|
||||
{ timeout: 40_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port, true);
|
||||
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
|
||||
let runner: ChildProcess | undefined;
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => { stop(app); stop(runner); });
|
||||
|
||||
let runnerOutput = "";
|
||||
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
|
||||
cwd: REPO_ROOT,
|
||||
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
|
||||
await waitFor(
|
||||
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
|
||||
`runner never reached the exact swap window: ${runnerOutput}`,
|
||||
);
|
||||
|
||||
// Old code is only in the current task's backup; the stale backup is
|
||||
// untouched and still sitting under a lexicographically earlier name.
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
|
||||
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
|
||||
|
||||
stop(runner);
|
||||
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
|
||||
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "launcher did not restore the current task's 0.3.2 build");
|
||||
|
||||
// The current task's version, not the stale 0.1.0 build, is back in place.
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
|
||||
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0", "stale backup was not consumed");
|
||||
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true, "stale backup is still intact");
|
||||
|
||||
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
|
||||
for (const [key, file] of Object.entries(fixture.markerFiles)) {
|
||||
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,151 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { gzipSync } from "node:zlib";
|
||||
|
||||
/** Test-only archive builders. Not imported by production code. */
|
||||
|
||||
export interface TarFixtureEntry {
|
||||
name: string;
|
||||
data?: Buffer | string;
|
||||
type?: "file" | "directory" | "symlink" | "hardlink";
|
||||
linkname?: string;
|
||||
mode?: number;
|
||||
}
|
||||
|
||||
function octal(value: number, width: number): string {
|
||||
return value.toString(8).padStart(width, "0");
|
||||
}
|
||||
|
||||
function tarHeader(entry: TarFixtureEntry): Buffer {
|
||||
const buffer = Buffer.alloc(512);
|
||||
const directory = entry.type === "directory";
|
||||
const link = entry.type === "symlink" || entry.type === "hardlink";
|
||||
const data = entry.data === undefined ? Buffer.alloc(0) : Buffer.from(entry.data);
|
||||
const size = directory || link ? 0 : data.length;
|
||||
buffer.write(entry.name, 0, 100, "utf8");
|
||||
buffer.write(`${octal(entry.mode ?? (directory ? 0o755 : 0o644), 7)}\0`, 100, 8, "ascii");
|
||||
buffer.write("0000000\0", 108, 8, "ascii");
|
||||
buffer.write("0000000\0", 116, 8, "ascii");
|
||||
buffer.write(`${octal(size, 11)}\0`, 124, 12, "ascii");
|
||||
buffer.write("00000000000\0", 136, 12, "ascii");
|
||||
buffer.write(" ", 148, 8, "ascii");
|
||||
buffer.write(entry.type === "directory" ? "5" : entry.type === "symlink" ? "2" : entry.type === "hardlink" ? "1" : "0", 156, 1, "ascii");
|
||||
if (entry.linkname) buffer.write(entry.linkname, 157, 100, "utf8");
|
||||
buffer.write("ustar\0", 257, 6, "ascii");
|
||||
buffer.write("00", 263, 2, "ascii");
|
||||
buffer.write("root", 265, 32, "ascii");
|
||||
buffer.write("root", 297, 32, "ascii");
|
||||
buffer.write("0000000\0", 329, 8, "ascii");
|
||||
buffer.write("0000000\0", 337, 8, "ascii");
|
||||
let checksum = 0;
|
||||
for (const byte of buffer) checksum += byte;
|
||||
buffer.write(`${octal(checksum, 6)}\0 `, 148, 8, "ascii");
|
||||
return buffer;
|
||||
}
|
||||
|
||||
export function createTarGz(entries: TarFixtureEntry[]): Buffer {
|
||||
const chunks: Buffer[] = [];
|
||||
for (const entry of entries) {
|
||||
const data = entry.type === "directory" || entry.type === "symlink" || entry.type === "hardlink"
|
||||
? Buffer.alloc(0)
|
||||
: Buffer.from(entry.data ?? "");
|
||||
chunks.push(tarHeader(entry));
|
||||
if (data.length) {
|
||||
chunks.push(data, Buffer.alloc((512 - (data.length % 512)) % 512));
|
||||
}
|
||||
}
|
||||
chunks.push(Buffer.alloc(1024));
|
||||
return gzipSync(Buffer.concat(chunks));
|
||||
}
|
||||
|
||||
export interface ZipFixtureEntry {
|
||||
name: string;
|
||||
data?: Buffer | string;
|
||||
mode?: number;
|
||||
directory?: boolean;
|
||||
}
|
||||
|
||||
function crc32(buffer: Buffer): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of buffer) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
export function createZip(entries: ZipFixtureEntry[]): Buffer {
|
||||
const locals: Buffer[] = [];
|
||||
const central: Buffer[] = [];
|
||||
let offset = 0;
|
||||
for (const entry of entries) {
|
||||
const directory = entry.directory === true || entry.name.endsWith("/");
|
||||
const data = directory ? Buffer.alloc(0) : Buffer.from(entry.data ?? "");
|
||||
const name = Buffer.from(entry.name, "utf8");
|
||||
const mode = entry.mode ?? (directory ? 0o040755 : 0o100644);
|
||||
const crc = crc32(data);
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0, 6);
|
||||
local.writeUInt16LE(0, 8);
|
||||
local.writeUInt32LE(0, 10);
|
||||
local.writeUInt32LE(crc, 14);
|
||||
local.writeUInt32LE(data.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(name.length, 26);
|
||||
local.writeUInt16LE(0, 28);
|
||||
locals.push(local, name, data);
|
||||
const entryCentral = Buffer.alloc(46);
|
||||
entryCentral.writeUInt32LE(0x02014b50, 0);
|
||||
entryCentral.writeUInt16LE(0x0314, 4);
|
||||
entryCentral.writeUInt16LE(20, 6);
|
||||
entryCentral.writeUInt16LE(0, 8);
|
||||
entryCentral.writeUInt16LE(0, 10);
|
||||
entryCentral.writeUInt32LE(0, 12);
|
||||
entryCentral.writeUInt32LE(crc, 16);
|
||||
entryCentral.writeUInt32LE(data.length, 20);
|
||||
entryCentral.writeUInt32LE(data.length, 24);
|
||||
entryCentral.writeUInt16LE(name.length, 28);
|
||||
entryCentral.writeUInt16LE(0, 30);
|
||||
entryCentral.writeUInt16LE(0, 32);
|
||||
entryCentral.writeUInt16LE(0, 34);
|
||||
entryCentral.writeUInt16LE(0, 36);
|
||||
entryCentral.writeUInt32LE((mode << 16) >>> 0, 38);
|
||||
entryCentral.writeUInt32LE(offset, 42);
|
||||
central.push(entryCentral, name);
|
||||
offset += 30 + name.length + data.length;
|
||||
}
|
||||
const directory = Buffer.concat(central);
|
||||
const eocd = Buffer.alloc(22);
|
||||
eocd.writeUInt32LE(0x06054b50, 0);
|
||||
eocd.writeUInt16LE(0, 4);
|
||||
eocd.writeUInt16LE(0, 6);
|
||||
eocd.writeUInt16LE(entries.length, 8);
|
||||
eocd.writeUInt16LE(entries.length, 10);
|
||||
eocd.writeUInt32LE(directory.length, 12);
|
||||
eocd.writeUInt32LE(offset, 16);
|
||||
eocd.writeUInt16LE(0, 20);
|
||||
return Buffer.concat([...locals, directory, eocd]);
|
||||
}
|
||||
|
||||
export function sha256Hex(value: Buffer): string {
|
||||
return createHash("sha256").update(value).digest("hex");
|
||||
}
|
||||
|
||||
/** Minimal runnable release-package layout accepted by validateStagedPackage. */
|
||||
export function createPackageFiles(root: string, version: string, extra: Record<string, string> = {}): void {
|
||||
for (const directory of ["dist", "web/dist", "node_modules", "runtime"]) {
|
||||
mkdirSync(path.join(root, directory), { recursive: true });
|
||||
}
|
||||
writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "webspeak-webclient", version }), "utf8");
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
|
||||
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
|
||||
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
|
||||
for (const [relative, contents] of Object.entries(extra)) {
|
||||
const target = path.join(root, relative);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, contents, "utf8");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js";
|
||||
import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js";
|
||||
import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js";
|
||||
import { acquireUpdateLock, readUpdateState, writeUpdateState } from "./update-state.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
const ASSET_NAME = "webspeak-webclient-v0.4.0-linux-x64.tar.gz";
|
||||
const RELEASE_LIST_URL = `https://api.github.com/repos/${OFFICIAL_REPOSITORY}/releases?per_page=30`;
|
||||
|
||||
interface AssetFixture { name: string; data: Buffer; digest?: string | null; url?: string }
|
||||
interface ReleaseFixture {
|
||||
version: string;
|
||||
assets: AssetFixture[];
|
||||
prerelease?: boolean;
|
||||
draft?: boolean;
|
||||
releaseUrl?: string;
|
||||
}
|
||||
|
||||
function workspace(t: TestContext): string {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-service-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
return directory;
|
||||
}
|
||||
|
||||
function releaseJson(fixture: ReleaseFixture) {
|
||||
return {
|
||||
tag_name: `v${fixture.version}`,
|
||||
draft: fixture.draft === true,
|
||||
prerelease: fixture.prerelease === true,
|
||||
html_url: fixture.releaseUrl ?? `https://github.com/${OFFICIAL_REPOSITORY}/releases/tag/v${fixture.version}`,
|
||||
published_at: "2026-01-01T00:00:00.000Z",
|
||||
assets: fixture.assets.map((asset) => ({
|
||||
name: asset.name,
|
||||
size: asset.data.length,
|
||||
browser_download_url: asset.url ?? `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v${fixture.version}/${asset.name}`,
|
||||
digest: asset.digest ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeFetch(releases: ReleaseFixture[], downloads: Map<string, Buffer>) {
|
||||
return (async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === RELEASE_LIST_URL) {
|
||||
return new Response(JSON.stringify(releases.map(releaseJson)), { status: 200, headers: { "content-type": "application/json" } });
|
||||
}
|
||||
const body = downloads.get(url);
|
||||
if (body) return new Response(body as unknown as BodyInit, { status: 200, headers: { "content-type": "application/octet-stream" } });
|
||||
return new Response("not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer {
|
||||
return createTarGz([
|
||||
{ name: "webspeak/", type: "directory" },
|
||||
{ name: "webspeak/package.json", data: JSON.stringify({ name: "webspeak-webclient", version }) },
|
||||
{ name: "webspeak/dist/index.js", data: "// package entry\n" },
|
||||
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
|
||||
{ name: "webspeak/node_modules/.keep", data: "" },
|
||||
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
|
||||
...extra,
|
||||
]);
|
||||
}
|
||||
|
||||
function checksumText(assetName: string, archive: Buffer): string {
|
||||
return `${sha256Hex(archive)} ${assetName}\n`;
|
||||
}
|
||||
|
||||
interface ServiceFixture {
|
||||
service: UpdateService;
|
||||
launched: string[];
|
||||
dataDir: string;
|
||||
rootDir: string;
|
||||
}
|
||||
|
||||
function createService(
|
||||
t: TestContext,
|
||||
releases: ReleaseFixture[],
|
||||
downloads: Map<string, Buffer>,
|
||||
options: Partial<UpdateServiceOptions> = {},
|
||||
): ServiceFixture {
|
||||
const directory = workspace(t);
|
||||
const rootDir = options.rootDir ?? path.join(directory, "app");
|
||||
if (!options.rootDir) createPackageFiles(rootDir, "0.3.2");
|
||||
const dataDir = path.join(directory, "data");
|
||||
const launched: string[] = [];
|
||||
const service = new UpdateService({
|
||||
rootDir,
|
||||
dataDir,
|
||||
currentVersion: "0.3.2",
|
||||
logger,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
env: {},
|
||||
isDocker: false,
|
||||
isSupervised: false,
|
||||
fetch: fakeFetch(releases, downloads),
|
||||
now: () => new Date("2026-01-01T00:00:00.000Z"),
|
||||
launchRunner: async (planPath) => { launched.push(planPath); },
|
||||
healthTimeoutMs: 100,
|
||||
downloadTimeoutMs: 2_000,
|
||||
...options,
|
||||
});
|
||||
service.initialize();
|
||||
return { service, launched, dataDir, rootDir };
|
||||
}
|
||||
|
||||
function updateErrorCode(code: UpdateErrorCode) {
|
||||
return (error: unknown) => error instanceof UpdateError && error.code === code;
|
||||
}
|
||||
|
||||
function digest(archive: Buffer): string {
|
||||
return `sha256:${sha256Hex(archive)}`;
|
||||
}
|
||||
|
||||
test("release checks list only official stable versions and expose blocked reasons", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const downloads = new Map<string, Buffer>();
|
||||
const assetUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`;
|
||||
const checksumUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`;
|
||||
downloads.set(assetUrl, archive);
|
||||
downloads.set(checksumUrl, Buffer.from(checksumText(ASSET_NAME, archive)));
|
||||
const { service } = createService(t, [
|
||||
{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive, digest: digest(archive) },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)), digest: digest(Buffer.from(checksumText(ASSET_NAME, archive))) },
|
||||
],
|
||||
},
|
||||
{ version: "0.4.1", assets: [{ name: "webspeak-webclient-v0.4.1-linux-x64.tar.gz", data: archive }] },
|
||||
{
|
||||
version: "0.4.2",
|
||||
assets: [{ name: ASSET_NAME, data: archive }],
|
||||
releaseUrl: "https://evil.example/releases/tag/v0.4.2",
|
||||
},
|
||||
{
|
||||
version: "0.4.3",
|
||||
assets: [{ name: "webspeak-webclient-v0.4.3-linux-x64.tar.gz", data: archive, url: "https://evil.example/package.tar.gz" }],
|
||||
},
|
||||
{ version: "0.5.0", assets: [], prerelease: true },
|
||||
{ version: "0.6.0", assets: [], draft: true },
|
||||
{ version: "0.3.2", assets: [] },
|
||||
], downloads);
|
||||
|
||||
const check = await service.checkForUpdates();
|
||||
assert.deepEqual(check.releases.map((release) => release.version), ["0.4.3", "0.4.1", "0.4.0"]);
|
||||
const ready = check.releases.find((release) => release.version === "0.4.0")!;
|
||||
assert.equal(ready.assetName, ASSET_NAME);
|
||||
assert.equal(ready.assetAvailable, true);
|
||||
assert.equal(ready.hasChecksums, true);
|
||||
assert.equal(ready.canApply, true);
|
||||
assert.equal(ready.blockedReason, null);
|
||||
assert.equal(ready.digest, digest(archive));
|
||||
const noChecksum = check.releases.find((release) => release.version === "0.4.1")!;
|
||||
assert.equal(noChecksum.canApply, false);
|
||||
assert.equal(noChecksum.blockedReason, "UPDATE_CHECKSUM_MISSING");
|
||||
const maliciousAsset = check.releases.find((release) => release.version === "0.4.3")!;
|
||||
assert.equal(maliciousAsset.assetAvailable, false);
|
||||
assert.equal(maliciousAsset.canApply, false);
|
||||
assert.equal(maliciousAsset.blockedReason, "UPDATE_ASSET_UNAVAILABLE");
|
||||
});
|
||||
|
||||
test("apply requires a matching confirmation and a supported deployment", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const { service, launched } = createService(t, [{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
|
||||
],
|
||||
}], new Map());
|
||||
await assert.rejects(service.applyUpdate("0.4.0", "0.4.1"), updateErrorCode("UPDATE_CONFIRMATION_REQUIRED"));
|
||||
await assert.rejects((service.applyUpdate as unknown as (version: string) => Promise<unknown>)("0.4.0"), updateErrorCode("UPDATE_CONFIRMATION_REQUIRED"));
|
||||
await assert.rejects(service.applyUpdate("not-a-version", "not-a-version"), updateErrorCode("UPDATE_VERSION_INVALID"));
|
||||
await assert.rejects(service.applyUpdate("0.3.2", "0.3.2"), updateErrorCode("UPDATE_VERSION_NOT_NEWER"));
|
||||
assert.equal(launched.length, 0);
|
||||
|
||||
const sourceDirectory = workspace(t);
|
||||
const source = createService(t, [], new Map(), { rootDir: sourceDirectory });
|
||||
assert.equal(source.service.getStatus().deployment.mode, "source");
|
||||
await assert.rejects(source.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
|
||||
assert.equal(source.launched.length, 0);
|
||||
|
||||
const docker = createService(t, [], new Map(), { isDocker: true });
|
||||
assert.equal(docker.service.getStatus().deployment.mode, "docker");
|
||||
await assert.rejects(docker.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
|
||||
assert.equal(docker.launched.length, 0);
|
||||
});
|
||||
|
||||
test("a missing SHA256SUMS entry refuses the update and persists a failed task", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const assetName = "webspeak-webclient-v0.4.1-linux-x64.tar.gz";
|
||||
const { service, launched, dataDir } = createService(t, [{
|
||||
version: "0.4.1",
|
||||
assets: [{ name: assetName, data: archive }],
|
||||
}], new Map([[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.1/${assetName}`, archive]]));
|
||||
|
||||
const check = await service.checkForUpdates();
|
||||
assert.equal(check.releases[0].blockedReason, "UPDATE_CHECKSUM_MISSING");
|
||||
await assert.rejects(service.applyUpdate("0.4.1", "0.4.1"), updateErrorCode("UPDATE_CHECKSUM_MISSING"));
|
||||
assert.equal(launched.length, 0);
|
||||
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
|
||||
assert.equal(state.task?.status, "failed");
|
||||
assert.equal(state.task?.errorCode, "UPDATE_CHECKSUM_MISSING");
|
||||
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false);
|
||||
assert.equal(existsSync(path.join(dataDir, "updates", "tasks", state.task!.id)), false);
|
||||
});
|
||||
|
||||
test("a wrong checksum, digest mismatch or unsupported digest refuses the package", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const baseRelease = (digestValue: string | null): ReleaseFixture => ({
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive, digest: digestValue },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
|
||||
],
|
||||
});
|
||||
const archiveUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`;
|
||||
const checksumUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`;
|
||||
const downloads = new Map<string, Buffer>([
|
||||
[archiveUrl, archive],
|
||||
[checksumUrl, Buffer.from(checksumText(ASSET_NAME, archive))],
|
||||
]);
|
||||
|
||||
const badChecksum = createService(t, [{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(`${"0".repeat(64)} ${ASSET_NAME}\n`) },
|
||||
],
|
||||
}], new Map([[archiveUrl, archive], [checksumUrl, Buffer.from(`${"0".repeat(64)} ${ASSET_NAME}\n`)]]));
|
||||
await assert.rejects(badChecksum.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_CHECKSUM_MISMATCH"));
|
||||
assert.equal(badChecksum.launched.length, 0);
|
||||
|
||||
const wrongDigest = createService(t, [baseRelease(`sha256:${"0".repeat(64)}`)], new Map(downloads));
|
||||
await assert.rejects(wrongDigest.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DIGEST_MISMATCH"));
|
||||
|
||||
const unsupportedDigest = createService(t, [baseRelease("md5:abc")], new Map(downloads));
|
||||
await assert.rejects(unsupportedDigest.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DIGEST_UNSUPPORTED"));
|
||||
});
|
||||
|
||||
test("unsafe archives are refused before any code is staged", async t => {
|
||||
const archive = packageArchive("0.4.0", [{ name: "webspeak/../../escape.txt", data: "owned" }]);
|
||||
const { service, launched, dataDir } = createService(t, [{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
|
||||
],
|
||||
}], new Map([
|
||||
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
|
||||
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, Buffer.from(checksumText(ASSET_NAME, archive))],
|
||||
]));
|
||||
|
||||
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_ARCHIVE_UNSAFE"));
|
||||
assert.equal(launched.length, 0);
|
||||
assert.equal(existsSync(path.join(dataDir, "..", "escape.txt")), false);
|
||||
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
|
||||
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
|
||||
});
|
||||
|
||||
test("a verified package is staged, persisted and handed to the restart runner", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
|
||||
const { service, launched, dataDir } = createService(t, [{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive, digest: digest(archive) },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: checksums, digest: digest(checksums) },
|
||||
],
|
||||
}], new Map([
|
||||
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
|
||||
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, checksums],
|
||||
]));
|
||||
|
||||
const task = await service.applyUpdate("0.4.0", "0.4.0");
|
||||
assert.equal(task.status, "restarting");
|
||||
assert.equal(task.targetVersion, "0.4.0");
|
||||
assert.deepEqual(task.steps.map((step) => [step.name, step.status]), [
|
||||
["download", "succeeded"],
|
||||
["checksum", "succeeded"],
|
||||
["extract", "succeeded"],
|
||||
["stage", "succeeded"],
|
||||
["restart", "running"],
|
||||
]);
|
||||
|
||||
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
|
||||
assert.equal(state.task?.id, task.id);
|
||||
assert.equal(state.task?.status, "restarting");
|
||||
assert.equal(launched.length, 1);
|
||||
const plan = JSON.parse(readFileSync(launched[0], "utf8"));
|
||||
assert.equal(plan.taskId, task.id);
|
||||
assert.equal(plan.targetVersion, "0.4.0");
|
||||
assert.equal(plan.fromVersion, "0.3.2");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(plan.stagedRoot, "package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), true);
|
||||
|
||||
// The old process is gone once the restarted instance reads the state.
|
||||
writeFileSync(path.join(dataDir, "updates", "update.lock"), JSON.stringify({ pid: 0, taskId: task.id, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
const restarted = new UpdateService({
|
||||
rootDir: path.dirname(plan.rootDir),
|
||||
dataDir,
|
||||
currentVersion: "0.4.0",
|
||||
logger,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
env: {},
|
||||
isDocker: false,
|
||||
fetch: fakeFetch([], new Map()),
|
||||
now: () => new Date("2026-01-01T00:00:00.000Z"),
|
||||
});
|
||||
restarted.initialize();
|
||||
assert.equal(restarted.getStatus().task?.status, "succeeded");
|
||||
assert.equal(restarted.getStatus().task?.finishedAt, "2026-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("a concurrent lock leaves the running task state untouched", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const { service, dataDir } = createService(t, [{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
|
||||
],
|
||||
}], new Map());
|
||||
mkdirSync(path.join(dataDir, "updates"), { recursive: true });
|
||||
writeFileSync(path.join(dataDir, "updates", "update.lock"), JSON.stringify({ pid: process.pid, taskId: "upd_running", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writeFileSync(path.join(dataDir, "updates", "state.json"), JSON.stringify({ schemaVersion: 1, task: null }));
|
||||
service.initialize();
|
||||
|
||||
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_IN_PROGRESS"));
|
||||
assert.equal(readUpdateState(path.join(dataDir, "updates", "state.json")).task, null);
|
||||
assert.equal(service.getStatus().task, null);
|
||||
});
|
||||
|
||||
test("getStatus reports the task the restart runner persisted, not stale memory", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
|
||||
const { service, dataDir } = createService(t, [{
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: checksums },
|
||||
],
|
||||
}], new Map([
|
||||
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
|
||||
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, checksums],
|
||||
]));
|
||||
|
||||
const task = await service.applyUpdate("0.4.0", "0.4.0");
|
||||
assert.equal(service.getStatus().task?.status, "restarting");
|
||||
// The runner rolls the task back in another process, after this one
|
||||
// already returned the prepared task.
|
||||
writeUpdateState(path.join(dataDir, "updates", "state.json"), {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
...task, status: "failed", finishedAt: "2026-01-01T00:05:00.000Z", updatedAt: "2026-01-01T00:05:00.000Z",
|
||||
errorCode: "UPDATE_HEALTH_CHECK_FAILED", errorMessage: "health check failed", rolledBack: true,
|
||||
},
|
||||
});
|
||||
const status = service.getStatus();
|
||||
assert.equal(status.task?.status, "failed");
|
||||
assert.equal(status.task?.rolledBack, true);
|
||||
assert.equal(status.task?.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
|
||||
});
|
||||
|
||||
test("initialization restores the previous code from an interrupted swap backup", t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const taskId = "upd_interrupted_swap";
|
||||
const statePath = path.join(fixture.dataDir, "updates", "state.json");
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
|
||||
|
||||
// The process died after moving the previous code aside and only part of
|
||||
// the new package had been moved in.
|
||||
mkdirSync(path.join(backupDir, "dist"), { recursive: true });
|
||||
writeFileSync(path.join(backupDir, "dist", "index.js"), "// old code\n");
|
||||
writeFileSync(path.join(backupDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
|
||||
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), "// new code\n");
|
||||
writeFileSync(path.join(fixture.rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
|
||||
|
||||
writeUpdateState(statePath, {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
});
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
|
||||
const restarted = new UpdateService({
|
||||
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
|
||||
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
|
||||
now: () => new Date("2026-01-01T00:10:00.000Z"),
|
||||
});
|
||||
restarted.initialize();
|
||||
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// old code\n");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
const status = restarted.getStatus();
|
||||
assert.equal(status.task?.status, "failed");
|
||||
assert.equal(status.task?.rolledBack, true);
|
||||
assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
|
||||
assert.equal(existsSync(lockPath), false);
|
||||
});
|
||||
|
||||
test("initialization keeps a live task but reconciles it once its process is gone", async t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const running = {
|
||||
schemaVersion: 1 as const,
|
||||
task: {
|
||||
id: "upd_live", status: "downloading" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
};
|
||||
const statePath = path.join(fixture.dataDir, "updates", "state.json");
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
mkdirSync(path.dirname(statePath), { recursive: true });
|
||||
writeFileSync(statePath, JSON.stringify(running));
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_live", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
const restarted = new UpdateService({
|
||||
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
|
||||
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
|
||||
now: () => new Date("2026-01-01T00:00:00.000Z"),
|
||||
});
|
||||
restarted.initialize();
|
||||
assert.equal(restarted.getStatus().task?.status, "downloading");
|
||||
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId: "upd_live", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
restarted.initialize();
|
||||
assert.equal(restarted.getStatus().task?.status, "failed");
|
||||
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
|
||||
});
|
||||
|
||||
test("a replacement app can update again after the runner finishes its cached task", async t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const statePath = path.join(fixture.dataDir, "updates", "state.json");
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
const task = {
|
||||
id: "upd_completed_runner", status: "restarting" as const, fromVersion: "0.3.1", targetVersion: "0.3.2",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
};
|
||||
const release = acquireUpdateLock(lockPath, task.id);
|
||||
t.after(release);
|
||||
writeUpdateState(statePath, { schemaVersion: 1, task });
|
||||
fixture.service.initialize();
|
||||
assert.equal(fixture.service.getStatus().task?.status, "restarting");
|
||||
writeUpdateState(statePath, { schemaVersion: 1, task: { ...task, status: "succeeded", finishedAt: "2026-01-01T00:01:00.000Z" } });
|
||||
release();
|
||||
assert.equal(fixture.service.getStatus().task?.status, "succeeded");
|
||||
// It reaches release lookup instead of being rejected by a stale active task.
|
||||
await assert.rejects(fixture.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_VERSION_NOT_FOUND"));
|
||||
});
|
||||
|
||||
test("supervised packages can check releases but cannot download or launch an update", async t => {
|
||||
const fixture = createService(t, [{ version: "0.4.0", assets: [] }], new Map(), { isSupervised: true });
|
||||
const checked = await fixture.service.checkForUpdates();
|
||||
assert.equal(checked.releases[0]?.blockedReason, "DEPLOYMENT_SUPERVISED");
|
||||
assert.equal(checked.releases[0]?.canApply, false);
|
||||
await assert.rejects(fixture.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
|
||||
assert.deepEqual(fixture.launched, []);
|
||||
assert.equal(fixture.service.getStatus().task, null);
|
||||
});
|
||||
|
||||
test("initialization does not roll back a task whose lock belongs to another live process", async t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const taskId = "upd_other_process";
|
||||
const statePath = path.join(fixture.dataDir, "updates", "state.json");
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
const owner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
|
||||
t.after(() => { try { owner.kill("SIGKILL"); } catch { /* Already gone. */ } });
|
||||
await once(owner, "spawn");
|
||||
assert.ok(owner.pid);
|
||||
|
||||
writeUpdateState(statePath, {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
});
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: owner.pid, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
|
||||
const restarted = new UpdateService({
|
||||
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
|
||||
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
|
||||
now: () => new Date("2026-01-01T00:10:00.000Z"),
|
||||
});
|
||||
restarted.initialize();
|
||||
|
||||
const status = restarted.getStatus();
|
||||
assert.equal(status.task?.status, "restarting");
|
||||
assert.equal(status.task?.errorCode, null);
|
||||
assert.equal(status.task?.rolledBack, false);
|
||||
assert.equal(existsSync(lockPath), true);
|
||||
});
|
||||
|
||||
/** Every module the detached runner imports, compiled side by side. */
|
||||
const RUNNER_RUNTIME_FILES = ["restart-runner.js", "code-swap.js", "version.js", "update-state.js"];
|
||||
|
||||
async function compileRunnerSources(destination: string): Promise<void> {
|
||||
const { build } = await import("esbuild");
|
||||
const sourceDirectory = path.dirname(fileURLToPath(import.meta.url));
|
||||
await build({
|
||||
entryPoints: RUNNER_RUNTIME_FILES.map((file) => path.join(sourceDirectory, file.replace(/\.js$/, ".ts"))),
|
||||
outdir: destination,
|
||||
bundle: false,
|
||||
format: "esm",
|
||||
platform: "node",
|
||||
target: "node22",
|
||||
logLevel: "silent",
|
||||
});
|
||||
}
|
||||
|
||||
function processIsAlive(pid: number): boolean {
|
||||
try { process.kill(pid, 0); return true; }
|
||||
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
|
||||
}
|
||||
|
||||
async function stopProcess(pid: number): Promise<void> {
|
||||
try { process.kill(pid, "SIGKILL"); } catch { /* Already gone. */ }
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (Date.now() < deadline && processIsAlive(pid)) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
}
|
||||
|
||||
test("the real restart runner starts with every runtime module and survives the grace window", async t => {
|
||||
const directory = workspace(t);
|
||||
const compiled = path.join(directory, "compiled");
|
||||
await compileRunnerSources(compiled);
|
||||
const rootDir = path.join(directory, "app");
|
||||
createPackageFiles(rootDir, "0.3.2");
|
||||
const dataDir = path.join(directory, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
const taskId = "upd_real_runner";
|
||||
const statePath = path.join(updatesDir, "state.json");
|
||||
writeUpdateState(statePath, {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
});
|
||||
const planPath = path.join(updatesDir, "plan.json");
|
||||
const runnerDirectory = path.join(updatesDir, "runner");
|
||||
const lockPath = path.join(updatesDir, "update.lock");
|
||||
writeFileSync(planPath, JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
taskId,
|
||||
rootDir,
|
||||
statePath,
|
||||
lockPath,
|
||||
stagedRoot: path.join(updatesDir, "staged"),
|
||||
backupDir: path.join(updatesDir, "backups", taskId),
|
||||
fromVersion: "0.3.2",
|
||||
targetVersion: "0.4.0",
|
||||
nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
// Deliberately not 3040 so the test cannot collide with a real server.
|
||||
health: { protocol: "http", port: 39999, path: "/api/health" },
|
||||
// The test process stays alive, so the runner waits instead of swapping.
|
||||
waitForPid: process.pid,
|
||||
parentTimeoutMs: 60_000,
|
||||
healthTimeoutMs: 100,
|
||||
pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
|
||||
const service = new UpdateService({
|
||||
rootDir, dataDir, currentVersion: "0.3.2", logger,
|
||||
platform: "linux", architecture: "x64", env: {}, isDocker: false,
|
||||
fetch: fakeFetch([], new Map()),
|
||||
runnerSourceDir: compiled,
|
||||
runnerStartupTimeoutMs: 600,
|
||||
});
|
||||
// Call the real launcher: no spawn mock, the compiled runner is executed.
|
||||
const pid = await service.launchRunner(planPath, runnerDirectory);
|
||||
t.after(() => stopProcess(pid));
|
||||
|
||||
assert.ok(Number.isInteger(pid) && pid > 0, "the runner reported a pid");
|
||||
for (const file of RUNNER_RUNTIME_FILES) {
|
||||
assert.equal(existsSync(path.join(runnerDirectory, file)), true, `${file} was copied next to the runner`);
|
||||
}
|
||||
assert.doesNotThrow(() => process.kill(pid, 0), "the runner is still alive after the grace window");
|
||||
const lock = JSON.parse(readFileSync(lockPath, "utf8"));
|
||||
assert.equal(lock.taskId, taskId);
|
||||
assert.equal(lock.pid, pid);
|
||||
const log = readFileSync(path.join(updatesDir, "runner.log"), "utf8");
|
||||
assert.ok(!log.includes("ERR_MODULE_NOT_FOUND"), `runner log has no missing module: ${log}`);
|
||||
});
|
||||
|
||||
test("the runner handshake requires lock takeover and a later death is caught before exit", async t => {
|
||||
const directory = workspace(t);
|
||||
const compiled = path.join(directory, "compiled");
|
||||
await compileRunnerSources(compiled);
|
||||
const rootDir = path.join(directory, "app");
|
||||
createPackageFiles(rootDir, "0.3.2");
|
||||
const dataDir = path.join(directory, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
const taskId = "upd_handshake";
|
||||
const statePath = path.join(updatesDir, "state.json");
|
||||
const lockPath = path.join(updatesDir, "update.lock");
|
||||
const planPath = path.join(updatesDir, "plan.json");
|
||||
const makeTask = () => ({
|
||||
id: taskId, status: "restarting" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
});
|
||||
const writePlan = () => writeFileSync(planPath, JSON.stringify({
|
||||
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
|
||||
stagedRoot: path.join(updatesDir, "staged"),
|
||||
backupDir: path.join(updatesDir, "backups", taskId),
|
||||
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port: 39998, path: "/api/health" },
|
||||
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
writeUpdateState(statePath, { schemaVersion: 1, task: makeTask() });
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writePlan();
|
||||
|
||||
const service = new UpdateService({
|
||||
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
|
||||
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
|
||||
});
|
||||
const pid = await service.launchRunner(planPath, path.join(updatesDir, "runner"));
|
||||
t.after(() => stopProcess(pid));
|
||||
assert.equal(service.runnerStillHealthy(), true, "runner owns the lock right after the handshake");
|
||||
|
||||
await stopProcess(pid);
|
||||
assert.equal(service.runnerStillHealthy(), false, "a runner that died after 202 is caught before process.exit");
|
||||
});
|
||||
|
||||
test("a runner that cannot take over the lock never passes the handshake", async t => {
|
||||
const directory = workspace(t);
|
||||
const compiled = path.join(directory, "compiled");
|
||||
await compileRunnerSources(compiled);
|
||||
const rootDir = path.join(directory, "app");
|
||||
createPackageFiles(rootDir, "0.3.2");
|
||||
const dataDir = path.join(directory, "data");
|
||||
const updatesDir = path.join(dataDir, "updates");
|
||||
mkdirSync(updatesDir, { recursive: true });
|
||||
const taskId = "upd_bad_lock";
|
||||
const statePath = path.join(updatesDir, "state.json");
|
||||
const lockPath = path.join(updatesDir, "update.lock");
|
||||
const planPath = path.join(updatesDir, "plan.json");
|
||||
writeUpdateState(statePath, {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
});
|
||||
// A different task owns the lock: the runner must refuse to steal it.
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_other", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
writeFileSync(planPath, JSON.stringify({
|
||||
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
|
||||
stagedRoot: path.join(updatesDir, "staged"),
|
||||
backupDir: path.join(updatesDir, "backups", taskId),
|
||||
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
|
||||
appEntry: path.join(rootDir, "dist", "index.js"),
|
||||
health: { protocol: "http", port: 39997, path: "/api/health" },
|
||||
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
|
||||
appLogPath: path.join(updatesDir, "app.log"),
|
||||
}, null, 2));
|
||||
|
||||
const service = new UpdateService({
|
||||
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
|
||||
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
|
||||
});
|
||||
await assert.rejects(
|
||||
service.launchRunner(planPath, path.join(updatesDir, "runner")),
|
||||
updateErrorCode("UPDATE_RUNNER_FAILED"),
|
||||
);
|
||||
assert.equal(service.runnerStillHealthy(), true, "no runner was recorded, so the guard is a no-op");
|
||||
});
|
||||
@@ -0,0 +1,653 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import {
|
||||
chmodSync, closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync,
|
||||
} from "node:fs";
|
||||
import { rename, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
|
||||
import { ArchiveError, extractReleaseArchive } from "./archive.js";
|
||||
import { CodeSwapError, locatePackageRoot, restoreCode } from "./code-swap.js";
|
||||
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
|
||||
import {
|
||||
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
|
||||
type OfficialRelease, type ReleaseAsset,
|
||||
} from "./releases.js";
|
||||
import {
|
||||
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
|
||||
reconcileInterruptedState, updateLockIsHeld, UpdateLockedError, writeUpdateState, type PersistedUpdateState,
|
||||
} from "./update-state.js";
|
||||
import { compareVersions, isNewerVersion, isValidVersion } from "./version.js";
|
||||
|
||||
export type UpdateErrorCode =
|
||||
| "UPDATE_IN_PROGRESS"
|
||||
| "UPDATE_NOT_SUPPORTED"
|
||||
| "UPDATE_VERSION_INVALID"
|
||||
| "UPDATE_VERSION_NOT_NEWER"
|
||||
| "UPDATE_VERSION_NOT_FOUND"
|
||||
| "UPDATE_CONFIRMATION_REQUIRED"
|
||||
| "UPDATE_ASSET_UNAVAILABLE"
|
||||
| "UPDATE_CHECKSUM_MISSING"
|
||||
| "UPDATE_CHECKSUM_MISMATCH"
|
||||
| "UPDATE_DIGEST_MISMATCH"
|
||||
| "UPDATE_DIGEST_UNSUPPORTED"
|
||||
| "UPDATE_DOWNLOAD_FAILED"
|
||||
| "UPDATE_DOWNLOAD_TOO_LARGE"
|
||||
| "UPDATE_ARCHIVE_UNSAFE"
|
||||
| "UPDATE_ARCHIVE_INVALID"
|
||||
| "UPDATE_ARCHIVE_LIMIT"
|
||||
| "UPDATE_ARCHIVE_UNSUPPORTED"
|
||||
| "UPDATE_PACKAGE_INVALID"
|
||||
| "UPDATE_SWAP_FAILED"
|
||||
| "UPDATE_ROLLBACK_FAILED"
|
||||
| "UPDATE_RELEASE_UNAVAILABLE"
|
||||
| "UPDATE_RUNNER_MISSING"
|
||||
| "UPDATE_RUNNER_FAILED"
|
||||
| "UPDATE_FAILED";
|
||||
|
||||
export class UpdateError extends Error {
|
||||
constructor(readonly code: UpdateErrorCode, message: string, readonly statusCode = 400) {
|
||||
super(message);
|
||||
this.name = "UpdateError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface UpdateServiceOptions {
|
||||
rootDir: string;
|
||||
dataDir: string;
|
||||
currentVersion: string;
|
||||
logger: Logger;
|
||||
port?: number;
|
||||
https?: boolean;
|
||||
platform?: NodeJS.Platform;
|
||||
architecture?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
isDocker?: boolean;
|
||||
isSupervised?: boolean;
|
||||
fetch?: typeof fetch;
|
||||
apiBaseUrl?: string;
|
||||
repository?: string;
|
||||
now?: () => Date;
|
||||
/** Compiled directory containing the restart runner and its runtime imports. */
|
||||
runnerSourceDir?: string;
|
||||
/** Test seam replacing the detached runner spawn. */
|
||||
launchRunner?: (planPath: string, runnerDir: string) => Promise<void>;
|
||||
/** How long a freshly spawned runner must stay alive before apply succeeds. */
|
||||
runnerStartupTimeoutMs?: number;
|
||||
healthTimeoutMs?: number;
|
||||
downloadTimeoutMs?: number;
|
||||
}
|
||||
|
||||
const CHECKSUM_LIMIT = 1024 * 1024;
|
||||
const DOWNLOAD_LIMIT = 512 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Install the recovery-capable launcher before the runner tears down dist/
|
||||
* and runtime/. The staged package ships the canonical script (same file CI
|
||||
* generates), so even the first upgrade from the old four-line launcher has
|
||||
* a self-healing ./start-webspeak.sh on the official path at all times.
|
||||
*/
|
||||
function installRecoveryLauncher(rootDir: string, stagedRoot: string): void {
|
||||
const source = path.join(stagedRoot, "start-webspeak.sh");
|
||||
// Source installs and hand-built test packages have no launcher; real
|
||||
// release packages always do.
|
||||
if (!existsSync(source)) return;
|
||||
const target = path.join(rootDir, "start-webspeak.sh");
|
||||
const temporary = `${target}.${process.pid}.tmp`;
|
||||
try {
|
||||
copyFileSync(source, temporary);
|
||||
chmodSync(temporary, 0o755);
|
||||
renameSync(temporary, target);
|
||||
} catch (error) {
|
||||
try { rmSync(temporary, { force: true }); } catch { /* Preserve the original error. */ }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every local module the restart runner imports at runtime. The runner is
|
||||
* copied into an isolated directory under data/updates, so any omission here
|
||||
* makes Node fail with ERR_MODULE_NOT_FOUND before the helper can swap code.
|
||||
*/
|
||||
const RUNNER_RUNTIME_FILES = ["restart-runner.js", "code-swap.js", "version.js", "update-state.js"] as const;
|
||||
|
||||
interface DownloadResult {
|
||||
sha256: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export class UpdateService {
|
||||
readonly deployment: DeploymentInfo;
|
||||
private readonly source: GitHubReleaseSource;
|
||||
private readonly updatesDir: string;
|
||||
private readonly statePath: string;
|
||||
private readonly lockPath: string;
|
||||
private readonly tasksDir: string;
|
||||
private readonly backupsDir: string;
|
||||
private readonly fetcher: typeof fetch;
|
||||
private readonly now: () => Date;
|
||||
private state: PersistedUpdateState = emptyUpdateState();
|
||||
private applying = false;
|
||||
private releaseLock: (() => void) | null = null;
|
||||
private runnerPid: number | null = null;
|
||||
|
||||
constructor(private readonly options: UpdateServiceOptions) {
|
||||
this.deployment = detectDeployment({
|
||||
rootDir: options.rootDir,
|
||||
platform: options.platform,
|
||||
architecture: options.architecture,
|
||||
env: options.env,
|
||||
isDocker: options.isDocker,
|
||||
isSupervised: options.isSupervised,
|
||||
});
|
||||
this.source = new GitHubReleaseSource({
|
||||
fetch: options.fetch,
|
||||
apiBaseUrl: options.apiBaseUrl,
|
||||
repository: options.repository,
|
||||
});
|
||||
this.fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
|
||||
this.now = options.now ?? (() => new Date());
|
||||
this.updatesDir = path.join(options.dataDir, "updates");
|
||||
this.statePath = path.join(this.updatesDir, "state.json");
|
||||
this.lockPath = path.join(this.updatesDir, "update.lock");
|
||||
this.tasksDir = path.join(this.updatesDir, "tasks");
|
||||
this.backupsDir = path.join(this.updatesDir, "backups");
|
||||
}
|
||||
|
||||
initialize(): void {
|
||||
mkdirSync(this.updatesDir, { recursive: true });
|
||||
this.state = readUpdateState(this.statePath);
|
||||
const task = this.state.task;
|
||||
// A live lock owner (for example a second process starting by mistake)
|
||||
// must not have its in-flight task reconciled as interrupted.
|
||||
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath, task.id)) {
|
||||
const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null;
|
||||
const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
|
||||
if (changed) writeUpdateState(this.statePath, this.state);
|
||||
}
|
||||
clearStaleUpdateLock(this.lockPath);
|
||||
this.options.logger.info({
|
||||
deployment: this.deployment.mode,
|
||||
version: this.options.currentVersion,
|
||||
task: this.state.task?.status ?? "idle",
|
||||
}, "Update service initialized");
|
||||
}
|
||||
|
||||
/**
|
||||
* A crash during the swap leaves the previous code in the backup directory
|
||||
* and possibly only partial new code in the install directory. Restore the
|
||||
* previous code before reporting the task, rather than trusting a version
|
||||
* whose files may be incomplete.
|
||||
*/
|
||||
private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null {
|
||||
const backupDir = path.join(this.backupsDir, task.id);
|
||||
if (!existsSync(backupDir)) return null;
|
||||
const now = this.now().toISOString();
|
||||
let restored = false;
|
||||
try {
|
||||
restoreCode(this.options.rootDir, backupDir);
|
||||
restored = true;
|
||||
} catch (error) {
|
||||
this.options.logger.warn({
|
||||
taskId: task.id,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Interrupted update code could not be restored from backup");
|
||||
}
|
||||
task.status = "failed";
|
||||
task.finishedAt = now;
|
||||
task.updatedAt = now;
|
||||
task.rolledBack = restored;
|
||||
if (restored) {
|
||||
task.errorCode = "UPDATE_INTERRUPTED";
|
||||
task.errorMessage = "The process stopped during the update. The previous version was restored from the backup.";
|
||||
} else {
|
||||
task.errorCode = "UPDATE_ROLLBACK_FAILED";
|
||||
task.errorMessage = "The process stopped during the update and the code could not be restored automatically. Restore the previous version from the backup.";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
getStatus(): UpdateStatusView {
|
||||
// The restart runner updates the persisted task after this process has
|
||||
// already returned a response, so always report the on-disk state. Do not
|
||||
// replace the in-memory state: an apply in progress still writes to it.
|
||||
const state = readUpdateState(this.statePath);
|
||||
return {
|
||||
currentVersion: this.options.currentVersion,
|
||||
deployment: {
|
||||
mode: this.deployment.mode,
|
||||
platform: this.deployment.platform,
|
||||
architecture: this.deployment.architecture,
|
||||
applyAllowed: this.deployment.applyAllowed,
|
||||
reasonCode: this.deployment.reasonCode,
|
||||
upgradePath: this.deployment.upgradePath,
|
||||
},
|
||||
task: state.task,
|
||||
};
|
||||
}
|
||||
|
||||
async checkForUpdates(): Promise<UpdateCheckView> {
|
||||
let releases: OfficialRelease[];
|
||||
try { releases = await this.source.listStableReleases(); }
|
||||
catch (error) { throw mapError(error); }
|
||||
const newer = releases
|
||||
.filter((release) => isNewerVersion(release.version, this.options.currentVersion))
|
||||
.sort((left, right) => compareVersions(right.version, left.version));
|
||||
return {
|
||||
currentVersion: this.options.currentVersion,
|
||||
releases: newer.map((release) => this.toReleaseView(release)),
|
||||
};
|
||||
}
|
||||
|
||||
private toReleaseView(release: OfficialRelease): UpdateReleaseView {
|
||||
const assetName = this.deployment.assetKind ? releaseAssetName(release.version, this.deployment.assetKind) : "";
|
||||
const asset = assetName ? release.assets.find((item) => item.name === assetName) ?? null : null;
|
||||
const checksums = release.assets.find((item) => item.name === CHECKSUM_ASSET_NAME) ?? null;
|
||||
let blockedReason: string | null = null;
|
||||
if (!this.deployment.applyAllowed) blockedReason = this.deployment.reasonCode ?? "DEPLOYMENT_SOURCE";
|
||||
else if (!asset) blockedReason = "UPDATE_ASSET_UNAVAILABLE";
|
||||
else if (!checksums) blockedReason = "UPDATE_CHECKSUM_MISSING";
|
||||
return {
|
||||
version: release.version,
|
||||
tag: release.tag,
|
||||
publishedAt: release.publishedAt,
|
||||
releaseUrl: release.releaseUrl,
|
||||
assetName,
|
||||
assetSize: asset?.size ?? 0,
|
||||
assetAvailable: Boolean(asset),
|
||||
hasChecksums: Boolean(checksums),
|
||||
digest: asset?.digest ?? null,
|
||||
canApply: blockedReason === null,
|
||||
blockedReason,
|
||||
};
|
||||
}
|
||||
|
||||
async applyUpdate(version: string, confirmVersion: string): Promise<UpdateTaskView> {
|
||||
if (version !== confirmVersion) {
|
||||
throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
|
||||
}
|
||||
if (!this.deployment.applyAllowed) {
|
||||
throw new UpdateError("UPDATE_NOT_SUPPORTED", this.deployment.reasonCode ?? "Updates cannot be applied from this deployment.", 409);
|
||||
}
|
||||
if (!isValidVersion(version)) throw new UpdateError("UPDATE_VERSION_INVALID", "The selected version is invalid.");
|
||||
if (!isNewerVersion(version, this.options.currentVersion)) {
|
||||
throw new UpdateError("UPDATE_VERSION_NOT_NEWER", "The selected version is not newer than the running version.", 409);
|
||||
}
|
||||
if (this.applying) {
|
||||
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
|
||||
}
|
||||
// The runner finishes after the replacement app has initialized. Its
|
||||
// terminal state on disk must replace that app's cached "restarting"
|
||||
// state before the next update; never reload during our own active apply.
|
||||
this.state = readUpdateState(this.statePath);
|
||||
if (this.state.task && isActiveTaskStatus(this.state.task.status)) {
|
||||
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
|
||||
}
|
||||
this.applying = true;
|
||||
this.runnerPid = null;
|
||||
const taskId = `upd_${Date.now().toString(36)}_${randomBytes(6).toString("hex")}`;
|
||||
const startedAt = this.now().toISOString();
|
||||
const task: UpdateTaskView = {
|
||||
id: taskId,
|
||||
status: "downloading",
|
||||
fromVersion: this.options.currentVersion,
|
||||
targetVersion: version,
|
||||
startedAt,
|
||||
updatedAt: startedAt,
|
||||
finishedAt: null,
|
||||
errorCode: null,
|
||||
errorMessage: null,
|
||||
rolledBack: false,
|
||||
steps: [],
|
||||
};
|
||||
const taskDirectory = path.join(this.tasksDir, taskId);
|
||||
try {
|
||||
this.releaseLock = acquireUpdateLock(this.lockPath, taskId);
|
||||
this.state = { schemaVersion: 1, task };
|
||||
writeUpdateState(this.statePath, this.state);
|
||||
mkdirSync(taskDirectory, { recursive: true });
|
||||
const release = await this.source.findRelease(version);
|
||||
if (!release) throw new UpdateError("UPDATE_VERSION_NOT_FOUND", "The selected stable release is no longer published.", 404);
|
||||
if (!this.deployment.assetKind) throw new UpdateError("UPDATE_NOT_SUPPORTED", "This platform has no release package.", 409);
|
||||
const assetName = releaseAssetName(version, this.deployment.assetKind);
|
||||
const asset = release.assets.find((item) => item.name === assetName);
|
||||
if (!asset) throw new UpdateError("UPDATE_ASSET_UNAVAILABLE", "The official release has no package for this platform.", 404);
|
||||
const checksumAsset = release.assets.find((item) => item.name === CHECKSUM_ASSET_NAME);
|
||||
if (!checksumAsset) throw new UpdateError("UPDATE_CHECKSUM_MISSING", "The official release has no SHA256SUMS.txt; updates are refused.", 409);
|
||||
const downloadDirectory = path.join(taskDirectory, "download");
|
||||
mkdirSync(downloadDirectory, { recursive: true });
|
||||
const archivePath = path.join(downloadDirectory, assetName);
|
||||
const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME);
|
||||
this.startStep(task, "download");
|
||||
const [archive, checksumFile] = await Promise.all([
|
||||
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT),
|
||||
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT),
|
||||
]);
|
||||
this.finishStep(task, "download", "succeeded");
|
||||
this.updateTaskStatus(task, "verifying");
|
||||
this.startStep(task, "checksum");
|
||||
this.verifyChecksums(checksumPath, assetName, archive.sha256, checksumFile.sha256, asset, checksumAsset);
|
||||
this.finishStep(task, "checksum", "succeeded");
|
||||
this.updateTaskStatus(task, "extracting");
|
||||
this.startStep(task, "extract");
|
||||
const extractedDirectory = path.join(taskDirectory, "extracted");
|
||||
try {
|
||||
await extractReleaseArchive(archivePath, extractedDirectory, assetName);
|
||||
} catch (error) {
|
||||
if (error instanceof ArchiveError) throw new UpdateError(error.code, error.message, 422);
|
||||
throw error;
|
||||
}
|
||||
this.finishStep(task, "extract", "succeeded");
|
||||
this.updateTaskStatus(task, "staging");
|
||||
this.startStep(task, "stage");
|
||||
let stagedRoot: string;
|
||||
try {
|
||||
if (!existsSync(archivePath)) throw new Error("Downloaded release package is missing.");
|
||||
stagedRoot = locatePackageRoot(extractedDirectory, version, this.deployment.platform);
|
||||
} catch (error) {
|
||||
if (error instanceof CodeSwapError) throw new UpdateError("UPDATE_PACKAGE_INVALID", error.message, 422);
|
||||
throw error;
|
||||
}
|
||||
this.finishStep(task, "stage", "succeeded");
|
||||
installRecoveryLauncher(this.options.rootDir, stagedRoot);
|
||||
const planPath = path.join(taskDirectory, "plan.json");
|
||||
const runnerDirectory = path.join(taskDirectory, "runner");
|
||||
const plan = {
|
||||
schemaVersion: 1,
|
||||
taskId,
|
||||
rootDir: this.options.rootDir,
|
||||
statePath: this.statePath,
|
||||
lockPath: this.lockPath,
|
||||
stagedRoot,
|
||||
backupDir: path.join(this.backupsDir, taskId),
|
||||
fromVersion: this.options.currentVersion,
|
||||
targetVersion: version,
|
||||
nodePath: path.join(this.options.rootDir, this.deployment.platform === "win32" ? "runtime/node.exe" : "runtime/node"),
|
||||
appEntry: path.join(this.options.rootDir, "dist", "index.js"),
|
||||
health: {
|
||||
protocol: this.options.https ? "https" : "http",
|
||||
port: this.options.port ?? 3040,
|
||||
path: "/api/health",
|
||||
},
|
||||
waitForPid: process.pid,
|
||||
parentTimeoutMs: 60_000,
|
||||
healthTimeoutMs: this.options.healthTimeoutMs ?? 90_000,
|
||||
pollIntervalMs: 500,
|
||||
appLogPath: path.join(taskDirectory, "app.log"),
|
||||
};
|
||||
writeFileSync(planPath, JSON.stringify(plan, null, 2), { encoding: "utf8", mode: 0o600 });
|
||||
this.updateTaskStatus(task, "restarting");
|
||||
this.startStep(task, "restart");
|
||||
writeUpdateState(this.statePath, this.state);
|
||||
try {
|
||||
if (this.options.launchRunner) await this.options.launchRunner(planPath, runnerDirectory);
|
||||
else await this.launchRunner(planPath, runnerDirectory);
|
||||
} catch (error) {
|
||||
if (error instanceof UpdateError) throw error;
|
||||
throw new UpdateError("UPDATE_RUNNER_FAILED", error instanceof Error ? error.message : "The restart runner could not be started.");
|
||||
}
|
||||
this.releaseLock = null;
|
||||
this.options.logger.info({ taskId, from: task.fromVersion, to: version }, "Update prepared; restart runner started");
|
||||
return task;
|
||||
} catch (error) {
|
||||
const updateError = mapError(error);
|
||||
// A lock conflict belongs to another task. Never overwrite its persisted
|
||||
// state just because this request was rejected.
|
||||
const ownsTask = this.releaseLock !== null || this.state.task?.id === taskId;
|
||||
task.status = "failed";
|
||||
task.updatedAt = this.now().toISOString();
|
||||
task.finishedAt = task.updatedAt;
|
||||
task.errorCode = updateError.code;
|
||||
task.errorMessage = updateError.message;
|
||||
const runningStep = [...task.steps].reverse().find((step) => step.status === "running");
|
||||
this.finishStep(task, runningStep?.name ?? "prepare", "failed", updateError.message);
|
||||
if (ownsTask) {
|
||||
this.state = { schemaVersion: 1, task };
|
||||
try { writeUpdateState(this.statePath, this.state); } catch { /* Preserve the original error. */ }
|
||||
}
|
||||
try { rmSync(taskDirectory, { recursive: true, force: true }); } catch { /* Best effort. */ }
|
||||
this.releaseLock?.();
|
||||
this.releaseLock = null;
|
||||
this.runnerPid = null;
|
||||
// A runner that died after taking over leaves its own pid in the lock.
|
||||
// Only a provably dead owner is removed; a live lock is left alone.
|
||||
clearStaleUpdateLock(this.lockPath);
|
||||
throw updateError;
|
||||
} finally {
|
||||
this.applying = false;
|
||||
}
|
||||
}
|
||||
|
||||
private updateTaskStatus(task: UpdateTaskView, status: UpdateTaskStatus): void {
|
||||
task.status = status;
|
||||
task.updatedAt = this.now().toISOString();
|
||||
writeUpdateState(this.statePath, this.state);
|
||||
}
|
||||
|
||||
private startStep(task: UpdateTaskView, name: string, detail?: string): void {
|
||||
const at = this.now().toISOString();
|
||||
const existing = task.steps.find((step) => step.name === name);
|
||||
if (existing) { existing.status = "running"; existing.at = at; if (detail) existing.detail = detail; }
|
||||
else task.steps.push({ name, status: "running", at, ...(detail ? { detail } : {}) });
|
||||
task.updatedAt = at;
|
||||
}
|
||||
|
||||
private finishStep(task: UpdateTaskView, name: string, status: "succeeded" | "failed", detail?: string): void {
|
||||
const at = this.now().toISOString();
|
||||
const existing = task.steps.find((step) => step.name === name);
|
||||
if (existing) { existing.status = status; existing.at = at; if (detail) existing.detail = detail; }
|
||||
else task.steps.push({ name, status, at, ...(detail ? { detail } : {}) });
|
||||
task.updatedAt = at;
|
||||
}
|
||||
|
||||
private verifyChecksums(
|
||||
checksumPath: string,
|
||||
assetName: string,
|
||||
archiveSha256: string,
|
||||
checksumSha256: string,
|
||||
asset: ReleaseAsset,
|
||||
checksumAsset: ReleaseAsset,
|
||||
): void {
|
||||
const text = readFileSync(checksumPath, "utf8");
|
||||
const expected = parseChecksumFile(text).get(assetName);
|
||||
if (!expected) throw new UpdateError("UPDATE_CHECKSUM_MISSING", "SHA256SUMS.txt has no entry for the selected package; the update is refused.", 409);
|
||||
if (expected !== archiveSha256) throw new UpdateError("UPDATE_CHECKSUM_MISMATCH", "The downloaded package does not match SHA256SUMS.txt.", 422);
|
||||
this.crossCheckDigest(asset, archiveSha256);
|
||||
this.crossCheckDigest(checksumAsset, checksumSha256);
|
||||
}
|
||||
|
||||
private crossCheckDigest(asset: ReleaseAsset, actual: string): void {
|
||||
if (!asset.digest) return;
|
||||
const [algorithm, value] = asset.digest.split(":", 2);
|
||||
if (algorithm?.toLowerCase() !== "sha256" || !/^[a-f0-9]{64}$/i.test(value ?? "")) {
|
||||
throw new UpdateError("UPDATE_DIGEST_UNSUPPORTED", "GitHub supplied an unsupported asset digest.", 409);
|
||||
}
|
||||
if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422);
|
||||
}
|
||||
|
||||
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number): Promise<DownloadResult> {
|
||||
try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); }
|
||||
catch (error) { throw mapError(error); }
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.fetcher(asset.url, {
|
||||
headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" },
|
||||
signal: AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502);
|
||||
}
|
||||
if (response.url) {
|
||||
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
|
||||
catch (error) { throw mapError(error); }
|
||||
}
|
||||
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
|
||||
const declared = Number(response.headers.get("content-length") ?? "");
|
||||
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
|
||||
const temporary = `${destination}.${process.pid}.tmp`;
|
||||
const hash = createHash("sha256");
|
||||
const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
|
||||
let bytes = 0;
|
||||
try {
|
||||
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
|
||||
const buffer = Buffer.from(chunk);
|
||||
bytes += buffer.length;
|
||||
if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
|
||||
hash.update(buffer);
|
||||
if (!stream.write(buffer)) await new Promise<void>((resolve) => stream.once("drain", resolve));
|
||||
}
|
||||
stream.end();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
stream.once("finish", resolve);
|
||||
stream.once("error", reject);
|
||||
});
|
||||
await rename(temporary, destination);
|
||||
} catch (error) {
|
||||
stream.destroy();
|
||||
await rm(temporary, { force: true }).catch(() => undefined);
|
||||
if (error instanceof UpdateError) throw error;
|
||||
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502);
|
||||
}
|
||||
return { sha256: hash.digest("hex"), bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the runner and all of its runtime imports into an isolated directory,
|
||||
* start it detached, and wait until it has taken over the update lock.
|
||||
* A successful spawn alone is not enough: Node resolves the whole ESM module
|
||||
* graph before executing the helper, so a missing file only shows up as an
|
||||
* early exit. Ownership of the lock also proves the runner is alive after
|
||||
* its startup window and really controls this task before we promise 202.
|
||||
*/
|
||||
async launchRunner(planPath: string, runnerDirectory: string): Promise<number> {
|
||||
const sourceDirectory = this.options.runnerSourceDir ?? path.dirname(fileURLToPath(import.meta.url));
|
||||
const missing = RUNNER_RUNTIME_FILES.filter((file) => !existsSync(path.join(sourceDirectory, file)));
|
||||
if (missing.length > 0) {
|
||||
throw new UpdateError(
|
||||
"UPDATE_RUNNER_MISSING",
|
||||
`The compiled restart runner is incomplete (missing ${missing.join(", ")}); rebuild the application before updating.`,
|
||||
500,
|
||||
);
|
||||
}
|
||||
mkdirSync(runnerDirectory, { recursive: true });
|
||||
for (const file of RUNNER_RUNTIME_FILES) {
|
||||
copyFileSync(path.join(sourceDirectory, file), path.join(runnerDirectory, file));
|
||||
}
|
||||
writeFileSync(path.join(runnerDirectory, "package.json"), JSON.stringify({ type: "module" }), "utf8");
|
||||
let nodePath: string;
|
||||
if (this.deployment.platform === "win32") {
|
||||
nodePath = path.join(runnerDirectory, "node.exe");
|
||||
copyFileSync(process.execPath, nodePath);
|
||||
} else {
|
||||
nodePath = process.execPath;
|
||||
}
|
||||
const log = path.join(path.dirname(planPath), "runner.log");
|
||||
const graceMs = this.options.runnerStartupTimeoutMs ?? 1_500;
|
||||
return new Promise<number>((resolve, reject) => {
|
||||
let child: ChildProcess;
|
||||
let fd: number | null = null;
|
||||
try {
|
||||
fd = openSync(log, "a");
|
||||
child = spawn(nodePath, [path.join(runnerDirectory, "restart-runner.js"), planPath], {
|
||||
cwd: this.options.rootDir,
|
||||
env: process.env,
|
||||
detached: true,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", fd, fd],
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
} finally {
|
||||
if (fd !== null) closeSync(fd);
|
||||
}
|
||||
let settled = false;
|
||||
let poll: NodeJS.Timeout | undefined;
|
||||
const fail = (message: string) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (poll) clearInterval(poll);
|
||||
reject(new UpdateError("UPDATE_RUNNER_FAILED", message, 500));
|
||||
};
|
||||
child.once("error", (error) => fail(error.message));
|
||||
child.once("exit", (code, signal) => {
|
||||
fail(`The restart runner exited before taking over (code ${code ?? "none"}, signal ${signal ?? "none"}).`);
|
||||
});
|
||||
child.once("spawn", () => {
|
||||
child.unref();
|
||||
const deadline = Date.now() + graceMs;
|
||||
poll = setInterval(() => {
|
||||
if (settled) return;
|
||||
const pid = child.pid;
|
||||
if (!pid) {
|
||||
fail("The restart runner did not report a process id.");
|
||||
return;
|
||||
}
|
||||
if (Date.now() > deadline) {
|
||||
fail("The restart runner did not take over the update lock in time.");
|
||||
return;
|
||||
}
|
||||
if (!pidIsAlive(pid) || !lockOwnedBy(this.lockPath, pid)) return;
|
||||
settled = true;
|
||||
if (poll) clearInterval(poll);
|
||||
this.runnerPid = pid;
|
||||
resolve(pid);
|
||||
}, 25);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Last chance guard for the promise made with 202. The parent still exists
|
||||
* for a short window after the handshake, so re-check that the runner is
|
||||
* alive and still owns the lock before the caller exits the process.
|
||||
*/
|
||||
runnerStillHealthy(): boolean {
|
||||
const pid = this.runnerPid;
|
||||
// No runner was launched through this instance (source install, mocked
|
||||
// route test): there is nothing extra to verify.
|
||||
if (pid === null) return true;
|
||||
return pidIsAlive(pid) && lockOwnedBy(this.lockPath, pid);
|
||||
}
|
||||
}
|
||||
|
||||
function pidIsAlive(pid: number): boolean {
|
||||
try { process.kill(pid, 0); return true; }
|
||||
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
|
||||
}
|
||||
|
||||
function lockOwnedBy(lockPath: string, pid: number): boolean {
|
||||
try {
|
||||
const record = JSON.parse(readFileSync(lockPath, "utf8")) as { pid?: unknown };
|
||||
return record?.pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function repositoryParts(repository: string | undefined): [string, string] {
|
||||
const [owner, repo] = (repository ?? "EchoSixHIYA/WebSpeak-client-for-TeamSpeak").split("/");
|
||||
return [owner, repo];
|
||||
}
|
||||
|
||||
export function parseChecksumFile(text: string): Map<string, string> {
|
||||
const entries = new Map<string, string>();
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const match = /^([a-fA-F0-9]{64})\s+\*?(.+?)\s*$/.exec(line.trim());
|
||||
if (!match) continue;
|
||||
const name = match[2].replace(/^\.\//, "");
|
||||
if (!entries.has(name)) entries.set(name, match[1].toLowerCase());
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function mapError(error: unknown): UpdateError {
|
||||
if (error instanceof UpdateError) return error;
|
||||
if (error instanceof UpdateLockedError) return new UpdateError("UPDATE_IN_PROGRESS", error.message, 409);
|
||||
if (error instanceof ReleaseSourceError) return new UpdateError("UPDATE_RELEASE_UNAVAILABLE", error.message, 502);
|
||||
if (error instanceof ArchiveError) return new UpdateError(error.code, error.message, 422);
|
||||
if (error instanceof CodeSwapError) return new UpdateError(error.code, error.message, 422);
|
||||
return new UpdateError("UPDATE_FAILED", error instanceof Error ? error.message : "The update failed.", 500);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { UpdateTaskView } from "../shared/update.js";
|
||||
import {
|
||||
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
|
||||
reconcileInterruptedState, takeOverUpdateLock, UpdateLockedError, updateLockIsHeld, writeUpdateState,
|
||||
} from "./update-state.js";
|
||||
|
||||
function workspace(t: TestContext): string {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-state-"));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
return directory;
|
||||
}
|
||||
|
||||
function task(overrides: Partial<UpdateTaskView> = {}): UpdateTaskView {
|
||||
return {
|
||||
id: "upd_test",
|
||||
status: "restarting",
|
||||
fromVersion: "0.3.2",
|
||||
targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
finishedAt: null,
|
||||
errorCode: null,
|
||||
errorMessage: null,
|
||||
rolledBack: false,
|
||||
steps: [{ name: "swap", status: "running", at: "2026-01-01T00:00:00.000Z" }],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** A second process that stays alive while a lock records its pid. */
|
||||
async function liveProcess(t: TestContext): Promise<ChildProcess> {
|
||||
const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
|
||||
t.after(() => { try { child.kill("SIGKILL"); } catch { /* Already gone. */ } });
|
||||
await once(child, "spawn");
|
||||
return child;
|
||||
}
|
||||
|
||||
test("state files round-trip and malformed files fall back to idle", t => {
|
||||
const directory = workspace(t), filename = path.join(directory, "state.json");
|
||||
assert.deepEqual(readUpdateState(filename), emptyUpdateState());
|
||||
writeUpdateState(filename, { schemaVersion: 1, task: task() });
|
||||
const loaded = readUpdateState(filename);
|
||||
assert.equal(loaded.task?.id, "upd_test");
|
||||
assert.deepEqual(loaded.task?.steps, [{ name: "swap", status: "running", at: "2026-01-01T00:00:00.000Z" }]);
|
||||
for (const contents of ["not json", "{}", JSON.stringify({ schemaVersion: 2, task: task() }), JSON.stringify({ schemaVersion: 1, task: { id: 42 } })]) {
|
||||
writeFileSync(filename, contents);
|
||||
assert.deepEqual(readUpdateState(filename), emptyUpdateState());
|
||||
}
|
||||
});
|
||||
|
||||
test("interrupted tasks reconcile against the version that is actually running", () => {
|
||||
const completed = { schemaVersion: 1 as const, task: task({ targetVersion: "0.4.0" }) };
|
||||
assert.equal(reconcileInterruptedState(completed, "0.4.0", "2026-01-01T01:00:00.000Z"), true);
|
||||
assert.equal(completed.task?.status, "succeeded");
|
||||
assert.equal(completed.task?.finishedAt, "2026-01-01T01:00:00.000Z");
|
||||
|
||||
const interrupted = { schemaVersion: 1 as const, task: task({ targetVersion: "0.4.0" }) };
|
||||
assert.equal(reconcileInterruptedState(interrupted, "0.3.2", "2026-01-01T01:00:00.000Z"), true);
|
||||
assert.equal(interrupted.task?.status, "failed");
|
||||
assert.equal(interrupted.task?.errorCode, "UPDATE_INTERRUPTED");
|
||||
|
||||
const finished = { schemaVersion: 1 as const, task: task({ status: "succeeded" as const }) };
|
||||
assert.equal(reconcileInterruptedState(finished, "0.3.2", "2026-01-01T01:00:00.000Z"), false);
|
||||
assert.equal(isActiveTaskStatus("downloading"), true);
|
||||
assert.equal(isActiveTaskStatus("failed"), false);
|
||||
});
|
||||
|
||||
test("the update lock is exclusive and safe to release", t => {
|
||||
const directory = workspace(t), lock = path.join(directory, "update.lock");
|
||||
const release = acquireUpdateLock(lock, "task-one");
|
||||
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "task-one");
|
||||
assert.throws(() => acquireUpdateLock(lock, "task-two"), (error: unknown) => error instanceof UpdateLockedError);
|
||||
release();
|
||||
assert.equal(existsSync(lock), false);
|
||||
const second = acquireUpdateLock(lock, "task-two");
|
||||
second();
|
||||
assert.equal(existsSync(lock), false);
|
||||
});
|
||||
|
||||
test("locks left by dead processes are reclaimed while live locks are preserved", t => {
|
||||
const directory = workspace(t), lock = path.join(directory, "update.lock");
|
||||
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
const release = acquireUpdateLock(lock, "new-task");
|
||||
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "new-task");
|
||||
release();
|
||||
|
||||
writeFileSync(lock, JSON.stringify({ pid: process.pid, taskId: "live-task", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
clearStaleUpdateLock(lock);
|
||||
assert.equal(existsSync(lock), true);
|
||||
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
clearStaleUpdateLock(lock);
|
||||
assert.equal(existsSync(lock), false);
|
||||
});
|
||||
|
||||
test("a live lock and an unreadable lock are never cleared, and count as held", async t => {
|
||||
const directory = workspace(t), lock = path.join(directory, "update.lock");
|
||||
const owner = await liveProcess(t);
|
||||
writeFileSync(lock, JSON.stringify({ pid: owner.pid, taskId: "live-task", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
clearStaleUpdateLock(lock);
|
||||
assert.equal(existsSync(lock), true);
|
||||
assert.equal(updateLockIsHeld(lock), true);
|
||||
assert.equal(updateLockIsHeld(lock, "live-task"), true);
|
||||
assert.equal(updateLockIsHeld(lock, "other-task"), false);
|
||||
assert.throws(() => acquireUpdateLock(lock, "new-task"), (error: unknown) => error instanceof UpdateLockedError);
|
||||
|
||||
// A lock that cannot be parsed may belong to a live owner, so it must not
|
||||
// be deleted and must conservatively block new updates.
|
||||
writeFileSync(lock, "not a lock record");
|
||||
clearStaleUpdateLock(lock);
|
||||
assert.equal(existsSync(lock), true);
|
||||
assert.equal(updateLockIsHeld(lock), true);
|
||||
assert.throws(() => acquireUpdateLock(lock, "new-task"), (error: unknown) => error instanceof UpdateLockedError);
|
||||
});
|
||||
|
||||
test("a lock left by a dead process is reported free and reclaimed", t => {
|
||||
const directory = workspace(t), lock = path.join(directory, "update.lock");
|
||||
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
assert.equal(updateLockIsHeld(lock), false);
|
||||
clearStaleUpdateLock(lock);
|
||||
assert.equal(existsSync(lock), false);
|
||||
const release = acquireUpdateLock(lock, "new-task");
|
||||
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "new-task");
|
||||
release();
|
||||
});
|
||||
|
||||
test("the restart runner can take over its own task but never another task's lock", async t => {
|
||||
const directory = workspace(t), lock = path.join(directory, "update.lock");
|
||||
const previousOwner = await liveProcess(t);
|
||||
writeFileSync(lock, JSON.stringify({ pid: previousOwner.pid, taskId: "task-shared", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
assert.doesNotThrow(() => process.kill(previousOwner.pid!, 0), "the original owner is still alive");
|
||||
|
||||
const release = takeOverUpdateLock(lock, "task-shared");
|
||||
const record = JSON.parse(readFileSync(lock, "utf8"));
|
||||
assert.equal(record.pid, process.pid);
|
||||
assert.equal(record.taskId, "task-shared");
|
||||
assert.equal(updateLockIsHeld(lock, "task-shared"), true);
|
||||
release();
|
||||
assert.equal(existsSync(lock), false);
|
||||
|
||||
writeFileSync(lock, JSON.stringify({ pid: previousOwner.pid, taskId: "task-other", createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
assert.throws(() => takeOverUpdateLock(lock, "task-shared"), (error: unknown) => error instanceof UpdateLockedError);
|
||||
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "task-other");
|
||||
assert.equal(updateLockIsHeld(lock, "task-other"), true);
|
||||
});
|
||||
|
||||
test("state writes replace the destination atomically", t => {
|
||||
const directory = workspace(t), filename = path.join(directory, "nested", "state.json");
|
||||
writeUpdateState(filename, { schemaVersion: 1, task: task({ id: "first" }) });
|
||||
writeUpdateState(filename, { schemaVersion: 1, task: task({ id: "second" }) });
|
||||
assert.equal(readUpdateState(filename).task?.id, "second");
|
||||
assert.equal(existsSync(`${filename}.${process.pid}.tmp`), false);
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
|
||||
|
||||
export interface PersistedUpdateState {
|
||||
schemaVersion: 1;
|
||||
task: UpdateTaskView | null;
|
||||
}
|
||||
|
||||
export interface UpdateLockRecord {
|
||||
pid: number;
|
||||
taskId: string;
|
||||
createdAt: string;
|
||||
/** Opaque process start marker; guards against PID reuse where available. */
|
||||
processStart?: string | null;
|
||||
}
|
||||
|
||||
export class UpdateLockedError extends Error {
|
||||
readonly code = "UPDATE_IN_PROGRESS";
|
||||
constructor(message = "Another update task is already running.") {
|
||||
super(message);
|
||||
this.name = "UpdateLockedError";
|
||||
}
|
||||
}
|
||||
|
||||
const ACTIVE_STATUSES: UpdateTaskStatus[] = ["downloading", "verifying", "extracting", "staging", "restarting"];
|
||||
|
||||
export function isActiveTaskStatus(status: UpdateTaskStatus | string): boolean {
|
||||
return (ACTIVE_STATUSES as string[]).includes(status);
|
||||
}
|
||||
|
||||
export function emptyUpdateState(): PersistedUpdateState {
|
||||
return { schemaVersion: 1, task: null };
|
||||
}
|
||||
|
||||
export function readUpdateState(filename: string): PersistedUpdateState {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(filename, "utf8"));
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return emptyUpdateState();
|
||||
const record = parsed as Record<string, unknown>;
|
||||
if (record.schemaVersion !== 1) return emptyUpdateState();
|
||||
return { schemaVersion: 1, task: parseTask(record.task) };
|
||||
} catch {
|
||||
return emptyUpdateState();
|
||||
}
|
||||
}
|
||||
|
||||
function parseTask(value: unknown): UpdateTaskView | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const task = value as Record<string, unknown>;
|
||||
if (typeof task.id !== "string" || !task.id
|
||||
|| typeof task.status !== "string"
|
||||
|| typeof task.fromVersion !== "string"
|
||||
|| typeof task.targetVersion !== "string"
|
||||
|| typeof task.startedAt !== "string"
|
||||
|| typeof task.updatedAt !== "string") return null;
|
||||
return {
|
||||
id: task.id,
|
||||
status: task.status as UpdateTaskStatus,
|
||||
fromVersion: task.fromVersion,
|
||||
targetVersion: task.targetVersion,
|
||||
startedAt: task.startedAt,
|
||||
updatedAt: task.updatedAt,
|
||||
finishedAt: typeof task.finishedAt === "string" ? task.finishedAt : null,
|
||||
errorCode: typeof task.errorCode === "string" ? task.errorCode : null,
|
||||
errorMessage: typeof task.errorMessage === "string" ? task.errorMessage : null,
|
||||
rolledBack: task.rolledBack === true,
|
||||
steps: Array.isArray(task.steps)
|
||||
? task.steps.filter((step): step is UpdateTaskView["steps"][number] => Boolean(step)
|
||||
&& typeof step === "object"
|
||||
&& !Array.isArray(step)
|
||||
&& typeof (step as Record<string, unknown>).name === "string"
|
||||
&& typeof (step as Record<string, unknown>).status === "string"
|
||||
&& typeof (step as Record<string, unknown>).at === "string")
|
||||
.map((step) => ({
|
||||
name: step.name,
|
||||
status: step.status,
|
||||
at: step.at,
|
||||
...(typeof step.detail === "string" ? { detail: step.detail } : {}),
|
||||
}))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function writeUpdateState(filename: string, state: PersistedUpdateState): void {
|
||||
mkdirSync(path.dirname(filename), { recursive: true });
|
||||
const temporary = `${filename}.${process.pid}.tmp`;
|
||||
writeFileSync(temporary, JSON.stringify(state, null, 2), { encoding: "utf8", mode: 0o600 });
|
||||
renameSync(temporary, filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a task that was active when the previous process stopped. If the
|
||||
* running version already matches the target the update completed; otherwise
|
||||
* it failed and is reported as interrupted.
|
||||
*/
|
||||
export function reconcileInterruptedState(state: PersistedUpdateState, currentVersion: string, now: string): boolean {
|
||||
const task = state.task;
|
||||
if (!task || !isActiveTaskStatus(task.status)) return false;
|
||||
if (task.targetVersion === currentVersion) {
|
||||
task.status = "succeeded";
|
||||
task.finishedAt = now;
|
||||
task.updatedAt = now;
|
||||
return true;
|
||||
}
|
||||
task.status = "failed";
|
||||
task.finishedAt = now;
|
||||
task.updatedAt = now;
|
||||
task.errorCode = "UPDATE_INTERRUPTED";
|
||||
task.errorMessage = "The process stopped before the update completed. The previous version is still running.";
|
||||
return true;
|
||||
}
|
||||
|
||||
function processIsAlive(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return false;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Linux exposes the process start time in /proc/<pid>/stat. It is used only
|
||||
* as an extra guard against PID reuse: when it is unavailable (Windows,
|
||||
* macOS, restricted /proc) liveness falls back to the pid check alone and
|
||||
* never throws.
|
||||
*/
|
||||
function processStartMarker(pid: number): string | null {
|
||||
try {
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
||||
const close = stat.lastIndexOf(")");
|
||||
if (close < 0) return null;
|
||||
const fields = stat.slice(close + 2).trim().split(/\s+/);
|
||||
// Field 3 is the state; starttime is field 22, i.e. index 19 here.
|
||||
return fields[19] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseLockRecord(raw: string): UpdateLockRecord | null {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
||||
const record = parsed as Record<string, unknown>;
|
||||
const pid = Number(record.pid);
|
||||
if (!Number.isInteger(pid) || pid < 0 || typeof record.taskId !== "string" || !record.taskId) return null;
|
||||
return {
|
||||
pid,
|
||||
taskId: record.taskId,
|
||||
createdAt: typeof record.createdAt === "string" ? record.createdAt : "",
|
||||
processStart: typeof record.processStart === "string" ? record.processStart : null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface LockFile {
|
||||
raw: string;
|
||||
record: UpdateLockRecord | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Missing lock => null. A lock that exists but cannot be read or parsed is
|
||||
* reported with `record: null`; callers must treat it as potentially held
|
||||
* rather than deleting a lock another process may still own.
|
||||
*/
|
||||
function readLockFile(lockPath: string): LockFile | null {
|
||||
try {
|
||||
const raw = readFileSync(lockPath, "utf8");
|
||||
return { raw, record: parseLockRecord(raw) };
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
||||
return { raw: "", record: null };
|
||||
}
|
||||
}
|
||||
|
||||
function lockOwnerIsAlive(record: UpdateLockRecord): boolean {
|
||||
if (!processIsAlive(record.pid)) return false;
|
||||
if (!record.processStart) return true;
|
||||
const current = processStartMarker(record.pid);
|
||||
// If the platform cannot report a start marker, keep the pid-only answer.
|
||||
return current === null || current === record.processStart;
|
||||
}
|
||||
|
||||
function lockPayload(taskId: string): string {
|
||||
return JSON.stringify({
|
||||
pid: process.pid,
|
||||
taskId,
|
||||
createdAt: new Date().toISOString(),
|
||||
processStart: processStartMarker(process.pid),
|
||||
} satisfies UpdateLockRecord);
|
||||
}
|
||||
|
||||
function releaseLock(lockPath: string, payload: string, taskId: string): () => void {
|
||||
return () => {
|
||||
const file = readLockFile(lockPath);
|
||||
// Never delete a lock that became unreadable or was replaced by another
|
||||
// process; only remove the exact record this process wrote.
|
||||
if (!file || !file.record || file.raw !== payload) return;
|
||||
if (file.record.taskId !== taskId || file.record.pid !== process.pid) return;
|
||||
try { unlinkSync(lockPath); } catch { /* Another process reclaimed it. */ }
|
||||
};
|
||||
}
|
||||
|
||||
/** Remove a lock only after proving the observed record is dead and unchanged. */
|
||||
function reclaimDeadLock(lockPath: string, observed: LockFile): void {
|
||||
const current = readLockFile(lockPath);
|
||||
if (!current || current.raw !== observed.raw) return;
|
||||
try { unlinkSync(lockPath); } catch { /* Another process reclaimed it. */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-process mutex. Lock files written by a dead process are reclaimed so
|
||||
* a crash cannot permanently block the maintenance page. A lock that cannot
|
||||
* be parsed is treated as held: refusing an update is safer than deleting a
|
||||
* live lock.
|
||||
*/
|
||||
export function acquireUpdateLock(lockPath: string, taskId: string): () => void {
|
||||
mkdirSync(path.dirname(lockPath), { recursive: true });
|
||||
const payload = lockPayload(taskId);
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
||||
return releaseLock(lockPath, payload, taskId);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||
const file = readLockFile(lockPath);
|
||||
if (!file) continue;
|
||||
if (!file.record) {
|
||||
throw new UpdateLockedError("An unreadable update lock is present; refusing to start an update.");
|
||||
}
|
||||
if (file.record.pid === process.pid && file.record.taskId === taskId) {
|
||||
return releaseLock(lockPath, file.raw, taskId);
|
||||
}
|
||||
if (lockOwnerIsAlive(file.record)) throw new UpdateLockedError();
|
||||
reclaimDeadLock(lockPath, file);
|
||||
}
|
||||
}
|
||||
throw new UpdateLockedError();
|
||||
}
|
||||
|
||||
/**
|
||||
* The restart runner inherits an update that its parent process started but
|
||||
* cannot finish. It must own the lock while it swaps and health-checks the
|
||||
* new code, otherwise a second instance starting in that window would see a
|
||||
* dead parent pid and roll the healthy code back.
|
||||
*
|
||||
* Only the same task may be taken over. A live lock for another task is
|
||||
* never stolen, and an unreadable lock is refused.
|
||||
*/
|
||||
export function takeOverUpdateLock(lockPath: string, taskId: string): () => void {
|
||||
mkdirSync(path.dirname(lockPath), { recursive: true });
|
||||
const payload = lockPayload(taskId);
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
const file = readLockFile(lockPath);
|
||||
if (!file) {
|
||||
try {
|
||||
writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
||||
return releaseLock(lockPath, payload, taskId);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (!file.record) {
|
||||
throw new UpdateLockedError("The update lock is unreadable; the restart runner will not take over.");
|
||||
}
|
||||
if (file.record.taskId !== taskId) {
|
||||
throw new UpdateLockedError("A different update task holds the lock; the restart runner will not steal it.");
|
||||
}
|
||||
const temporary = `${lockPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
||||
try {
|
||||
writeFileSync(temporary, payload, { encoding: "utf8", mode: 0o600 });
|
||||
renameSync(temporary, lockPath);
|
||||
return releaseLock(lockPath, payload, taskId);
|
||||
} catch (error) {
|
||||
try { rmSync(temporary, { force: true }); } catch { /* Best effort. */ }
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
throw new UpdateLockedError("The update lock could not be taken over.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a lock only when its owner is provably dead. Unreadable locks are
|
||||
* left in place so a live owner is never deleted by mistake.
|
||||
*/
|
||||
export function clearStaleUpdateLock(lockPath: string): void {
|
||||
const file = readLockFile(lockPath);
|
||||
if (!file || !file.record) return;
|
||||
if (lockOwnerIsAlive(file.record)) return;
|
||||
reclaimDeadLock(lockPath, file);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a live process still owns the lock, optionally for a specific
|
||||
* task. An unreadable lock is conservatively reported as held.
|
||||
*/
|
||||
export function updateLockIsHeld(lockPath: string, taskId?: string): boolean {
|
||||
const file = readLockFile(lockPath);
|
||||
if (!file) return false;
|
||||
if (!file.record) return true;
|
||||
if (!lockOwnerIsAlive(file.record)) return false;
|
||||
return taskId === undefined || file.record.taskId === taskId;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { compareVersions, isNewerVersion, isValidVersion, parseReleaseTag, parseStableVersion } from "./version.js";
|
||||
|
||||
test("stable versions require exactly three numeric segments", () => {
|
||||
assert.deepEqual(parseStableVersion(" 01.002.0003 "), { major: 1, minor: 2, patch: 3, text: "1.2.3" });
|
||||
for (const value of ["1.2", "1.2.3-beta", "v1.2.3", "1.2.3.4", "", null, 1.2]) {
|
||||
assert.equal(parseStableVersion(value), null);
|
||||
}
|
||||
});
|
||||
|
||||
test("release tags accept only the v-prefixed stable shape", () => {
|
||||
assert.equal(parseReleaseTag("v0.3.2")?.text, "0.3.2");
|
||||
assert.equal(parseReleaseTag("0.3.2"), null);
|
||||
assert.equal(parseReleaseTag("v0.3.2-rc.1"), null);
|
||||
assert.equal(parseReleaseTag("vv0.3.2"), null);
|
||||
});
|
||||
|
||||
test("version comparison and newer checks are numeric", () => {
|
||||
assert.ok(compareVersions("0.10.0", "0.9.9") > 0);
|
||||
assert.ok(compareVersions("1.0.0", "1.0.0") === 0);
|
||||
assert.ok(compareVersions("1.0.0", "1.0.1") < 0);
|
||||
assert.equal(isNewerVersion("0.3.3", "0.3.2"), true);
|
||||
assert.equal(isNewerVersion("0.3.2", "0.3.2"), false);
|
||||
assert.equal(isNewerVersion("not-a-version", "0.3.2"), false);
|
||||
assert.equal(isValidVersion("2.0.0"), true);
|
||||
assert.equal(isValidVersion("2.0"), false);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Stable semantic versions only. Pre-release/rolling channels are deliberate non-goals. */
|
||||
export interface StableVersion {
|
||||
major: number;
|
||||
minor: number;
|
||||
patch: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
const STABLE = /^(\d{1,6})\.(\d{1,6})\.(\d{1,6})$/;
|
||||
|
||||
export function parseStableVersion(value: unknown): StableVersion | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const match = STABLE.exec(value.trim());
|
||||
if (!match) return null;
|
||||
const [, major, minor, patch] = match;
|
||||
return { major: Number(major), minor: Number(minor), patch: Number(patch), text: `${Number(major)}.${Number(minor)}.${Number(patch)}` };
|
||||
}
|
||||
|
||||
/** `v1.2.3` is the only accepted release tag shape. */
|
||||
export function parseReleaseTag(value: unknown): StableVersion | null {
|
||||
if (typeof value !== "string" || !value.startsWith("v")) return null;
|
||||
return parseStableVersion(value.slice(1));
|
||||
}
|
||||
|
||||
export function isValidVersion(value: unknown): value is string {
|
||||
return parseStableVersion(value) !== null;
|
||||
}
|
||||
|
||||
export function compareVersions(left: string, right: string): number {
|
||||
const a = parseStableVersion(left);
|
||||
const b = parseStableVersion(right);
|
||||
if (!a || !b) return 0;
|
||||
return a.major - b.major || a.minor - b.minor || a.patch - b.patch;
|
||||
}
|
||||
|
||||
export function isNewerVersion(candidate: string, current: string): boolean {
|
||||
return compareVersions(candidate, current) > 0;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.1'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 301
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.2'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 302
|
||||
|
||||
android {
|
||||
namespace = "io.webspeak.client"
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
<!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 requestedSkin = params.get("skin");
|
||||
const previewSkins = new Set(["none", "/host-chrome-demo.wskin", "/host-chrome-themed.wskin"]);
|
||||
const skinUrl = previewSkins.has(requestedSkin) ? requestedSkin : "/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"); });
|
||||
|
||||
void (async () => {
|
||||
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.textContent = `Active skin: ${skin.id} v${skin.version} · hidden parts: ${JSON.stringify(skin.chromeData?.hiddenParts ?? [])} · visible parts: ${JSON.stringify(skin.chromeData?.visibleParts ?? [])} · icon overrides: ${Object.keys(skin.chromeData?.icons ?? {}).length}`;
|
||||
} 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>
|
||||
@@ -25,7 +25,7 @@
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"version": "0.3.1"
|
||||
"version": "0.3.2"
|
||||
},
|
||||
"node_modules/@babel/helper-string-parser": {
|
||||
"version": "7.27.1",
|
||||
@@ -2952,5 +2952,5 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "0.3.1"
|
||||
"version": "0.3.2"
|
||||
}
|
||||
@@ -27,5 +27,5 @@
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"version": "0.3.1"
|
||||
"version": "0.3.2"
|
||||
}
|
||||
@@ -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,485 @@
|
||||
<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"
|
||||
@keydown.escape="onRecoveryEscape"
|
||||
@click="compactPinned = compact || compactPinned"
|
||||
@focusout="onRecoveryFocusOut"
|
||||
class="ws-host-recovery"
|
||||
:class="{ 'ws-host-recovery-compact': compact }"
|
||||
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
|
||||
:tabindex="compact || compactPinned ? 0 : undefined"
|
||||
data-ws-host-recovery
|
||||
role="region"
|
||||
:aria-label="copy.recovery"
|
||||
>
|
||||
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
data-ws-recovery-action="built-in"
|
||||
:title="copy.shortcut"
|
||||
@click="useBuiltInSkin"
|
||||
>{{ copy.useBuiltIn }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-host-recovery-action"
|
||||
v-if="pluginLibraryAvailable"
|
||||
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 {
|
||||
activeHostSlot,
|
||||
hostChromeActiveSkinId,
|
||||
isHostPartHidden,
|
||||
isHostPartVisuallyReachable,
|
||||
isRecoveryShortcut,
|
||||
isThirdPartySkinActive,
|
||||
openPluginLibrary,
|
||||
requestBuiltInSkin,
|
||||
} from "../services/host-chrome.js";
|
||||
import {
|
||||
createHostOwnedLayer,
|
||||
syncRecoveryPopover,
|
||||
type HostOwnedLayer,
|
||||
} from "../services/host-owned-layer.js";
|
||||
import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
|
||||
import {
|
||||
bindFloatingAvoidance,
|
||||
type FloatingAvoidance,
|
||||
type FloatingPosition,
|
||||
} from "../services/host-floating-placement.js";
|
||||
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
|
||||
import { thirdPartyAllowed } from "../services/instance-authorization.js";
|
||||
import {
|
||||
RECOVERY_CONTROL_DEFAULTS,
|
||||
bindHostControlTheme,
|
||||
findSkinRoot,
|
||||
} from "../services/host-control-tokens.js";
|
||||
|
||||
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: 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 var(--ws-control-border, #9db6b2);
|
||||
border-radius: var(--ws-control-radius, 999px);
|
||||
background: var(--ws-control-background, color-mix(in srgb, #ffffff 92%, transparent));
|
||||
color: var(--ws-control-foreground, #31524f);
|
||||
font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
|
||||
font-size: var(--ws-control-font-size, 11px);
|
||||
box-shadow: 0 6px 18px #0f2a2626;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.ws-host-recovery:popover-open { display: flex; }
|
||||
/* Runtime collision avoidance (host-floating-placement.ts): when the default
|
||||
corner would cover a skin control, the floating capsule moves. A docked
|
||||
(slotted) capsule carries no data-ws-float and uses inline placement. */
|
||||
.ws-host-recovery[data-ws-float$="right"] { left: auto; right: max(12px, env(safe-area-inset-right)); }
|
||||
.ws-host-recovery[data-ws-float^="top"] { bottom: auto; top: max(12px, env(safe-area-inset-top)); }
|
||||
.ws-host-recovery[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
|
||||
.ws-host-recovery[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
|
||||
.ws-host-recovery-mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
.ws-host-recovery button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: var(--ws-control-hit, 28px);
|
||||
padding: 4px 9px;
|
||||
border: 1px solid var(--ws-control-border, #9db6b2);
|
||||
border-radius: var(--ws-control-radius, 999px);
|
||||
background: var(--ws-control-background, #fff);
|
||||
color: var(--ws-control-foreground, #31524f);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
|
||||
border-color: var(--ws-control-builtin-border, #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; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) { gap: 0; padding: 4px; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-action { display: none; }
|
||||
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-mark {
|
||||
min-width: var(--ws-control-hit, 28px);
|
||||
min-height: var(--ws-control-hit, 28px);
|
||||
}
|
||||
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
|
||||
}
|
||||
`;
|
||||
|
||||
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 && Boolean(props.pluginLibraryAvailable),
|
||||
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);
|
||||
|
||||
let slotBinding: HostSlotBinding | undefined;
|
||||
|
||||
/**
|
||||
* Theme the capsule even when the skin does not declare a slot. While a slot
|
||||
* binding exists it reads the anchor first and owns the tokens; this
|
||||
* root-level pass covers the slot-less capsule and refreshes itself when the
|
||||
* skin stylesheet arrives after the stored skin id.
|
||||
*/
|
||||
const recoveryTheme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
control: () => recoveryPopover.value,
|
||||
part: "host.recovery",
|
||||
defaults: RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
// While a slot binding exists it owns the capsule tokens (anchor first).
|
||||
active: () => !slotBinding,
|
||||
}) : null;
|
||||
|
||||
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
|
||||
|
||||
/**
|
||||
* Optional anchor from the active skin's chrome.json. Only third-party skins
|
||||
* can declare it; the host still owns the capsule and the module falls back to
|
||||
* the default corner whenever the anchor stops being usable.
|
||||
*/
|
||||
const slotConfig = computed(() => activeHostSlot("host.recovery"));
|
||||
const slotMode = ref<"floating" | "slotted">("floating");
|
||||
const compactHold = ref(true);
|
||||
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
// Keep the full capsule visible for a moment after it first docks into a
|
||||
// newly activated skin, so the entry stays discoverable before it folds into
|
||||
// the skin's layout. The skin id is known from localStorage before the skin
|
||||
// (and its anchor) has loaded, so the 5 s window starts on the first
|
||||
// floating -> slotted transition for that skin, not on the id change.
|
||||
let compactHoldStarted = false;
|
||||
watch(hostChromeActiveSkinId, () => {
|
||||
compactHold.value = true;
|
||||
compactHoldStarted = false;
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
compactHoldTimer = undefined;
|
||||
}, { immediate: true });
|
||||
watch(slotMode, (mode) => {
|
||||
if (mode !== "slotted" || compactHoldStarted) return;
|
||||
compactHoldStarted = true;
|
||||
compactHoldTimer = setTimeout(() => { compactHold.value = false; }, 5000);
|
||||
});
|
||||
|
||||
/** Set by the shortcut; cleared once focus leaves the capsule. */
|
||||
const shortcutExpanded = ref(false);
|
||||
/** A tap/click on the compact mark keeps it expanded (no hover on touch). */
|
||||
const compactPinned = ref(false);
|
||||
|
||||
/**
|
||||
* Floating (not docked) capsule: corner chosen at runtime so it does not cover
|
||||
* skin controls, and folded to its mark when every corner collides.
|
||||
*/
|
||||
const floatPosition = ref<FloatingPosition>("bottom-left");
|
||||
const floatCompact = ref(false);
|
||||
let floatingAvoidance: FloatingAvoidance | undefined;
|
||||
let floatingElement: HTMLElement | null = null;
|
||||
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
|
||||
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
|
||||
|
||||
const compact = computed(() => !shortcutExpanded.value
|
||||
&& !compactPinned.value
|
||||
&& (slotMode.value === "slotted"
|
||||
? Boolean(slotConfig.value?.compact) && !compactHold.value
|
||||
: floatCompact.value));
|
||||
|
||||
function onRecoveryEscape() {
|
||||
shortcutOpen.value = false;
|
||||
shortcutExpanded.value = false;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
/** Unpin when the pointer goes down anywhere outside the host layer. */
|
||||
function onDocumentPointerDown(event: PointerEvent) {
|
||||
if (!compactPinned.value || !layer) return;
|
||||
// Events from inside the closed shadow root are retargeted to its host.
|
||||
if (event.composedPath().includes(layer.host)) return;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
function onRecoveryFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget;
|
||||
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
|
||||
shortcutExpanded.value = false;
|
||||
compactPinned.value = false;
|
||||
}
|
||||
|
||||
function syncSlotBinding() {
|
||||
slotBinding?.dispose();
|
||||
slotBinding = undefined;
|
||||
// Disposing a slot clears its inline tokens; restore the root-level theme
|
||||
// before deciding whether a new anchor should override it.
|
||||
recoveryTheme?.apply();
|
||||
// A fresh binding starts floating and reports its first successful dock.
|
||||
slotMode.value = "floating";
|
||||
const control = recoveryPopover.value;
|
||||
const config = slotConfig.value;
|
||||
if (!control || !config || !layer) return;
|
||||
slotBinding = bindHostSlot({
|
||||
layer,
|
||||
control,
|
||||
anchor: config.anchor,
|
||||
skinId: hostChromeActiveSkinId.value,
|
||||
align: config.align,
|
||||
onModeChange: change => { slotMode.value = change.mode; },
|
||||
});
|
||||
}
|
||||
|
||||
function bindFloating() {
|
||||
const control = recoveryPopover.value;
|
||||
// Idempotent: called on mount and whenever the popover element appears.
|
||||
if (floatingAvoidance && floatingElement === control) return;
|
||||
floatingAvoidance?.dispose();
|
||||
floatingAvoidance = undefined;
|
||||
floatingElement = null;
|
||||
if (!control || !layer) return;
|
||||
const host = layer.host;
|
||||
floatingElement = control;
|
||||
floatingAvoidance = bindFloatingAvoidance({
|
||||
element: control,
|
||||
isSelf: node => node === host || host.contains(node),
|
||||
// Same numbers as RECOVERY_LAYER_CSS, including env(safe-area-inset-*).
|
||||
margins: insets => ({
|
||||
top: Math.max(12, insets.top),
|
||||
right: Math.max(12, insets.right),
|
||||
bottom: 38 + insets.bottom,
|
||||
left: Math.max(12, insets.left),
|
||||
}),
|
||||
insetsParent: layer.shadow,
|
||||
defaultPosition: "bottom-left",
|
||||
apply: next => { floatPosition.value = next; },
|
||||
compactSize: () => {
|
||||
const hit = Number.parseFloat(getComputedStyle(control).getPropertyValue("--ws-control-hit")) || 28;
|
||||
return { width: hit + 10, height: hit + 10 };
|
||||
},
|
||||
onCompactChange: next => { floatCompact.value = next; },
|
||||
// Never move the capsule under the user's pointer or focus, and leave a
|
||||
// docked capsule to the slot binding.
|
||||
paused: () => slotMode.value === "slotted"
|
||||
|| shortcutExpanded.value
|
||||
|| compactPinned.value
|
||||
|| (canHover() && control.matches(":hover"))
|
||||
|| Boolean(layer.shadow.activeElement),
|
||||
});
|
||||
}
|
||||
|
||||
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.repeat || !thirdPartyAllowed.value) return;
|
||||
// The recovery chord must survive a capture-phase preventDefault() from a
|
||||
// skin or plugin, so it is handled before anything else.
|
||||
if (isRecoveryShortcut(event)) {
|
||||
event.preventDefault();
|
||||
shortcutOpen.value = true;
|
||||
shortcutExpanded.value = true;
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
recoveryPopover.value?.querySelector("button")?.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let reachabilityTimer: ReturnType<typeof setInterval> | undefined;
|
||||
function refreshLauncherReachability() {
|
||||
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
|
||||
}
|
||||
|
||||
watch([recoveryVisible, recoveryPopover], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
slotBinding?.revalidate();
|
||||
bindFloating();
|
||||
floatingAvoidance?.revalidate();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
watch([recoveryPopover, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => recoveryTheme?.apply());
|
||||
}, { flush: "post", immediate: true });
|
||||
watch([slotConfig, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
});
|
||||
}, { flush: "post" });
|
||||
// Home <-> voice page and skin switches replace the controls the floating
|
||||
// capsule was avoiding; re-place it promptly (and back to its default corner
|
||||
// when that is free) instead of leaving it where the previous screen needed it.
|
||||
watch([() => props.connected, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => floatingAvoidance?.screenChanged());
|
||||
}, { flush: "post" });
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
|
||||
|
||||
onMounted(() => {
|
||||
refreshLauncherReachability();
|
||||
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
|
||||
window.addEventListener("resize", refreshLauncherReachability);
|
||||
window.addEventListener("keydown", onKeydown, true);
|
||||
window.addEventListener("pointerdown", onDocumentPointerDown, true);
|
||||
void nextTick(() => {
|
||||
syncPopover();
|
||||
syncSlotBinding();
|
||||
bindFloating();
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
if (reachabilityTimer) clearInterval(reachabilityTimer);
|
||||
if (compactHoldTimer) clearTimeout(compactHoldTimer);
|
||||
slotBinding?.dispose();
|
||||
floatingAvoidance?.dispose();
|
||||
floatingAvoidance = undefined;
|
||||
floatingElement = null;
|
||||
recoveryTheme?.dispose();
|
||||
window.removeEventListener("resize", refreshLauncherReachability);
|
||||
window.removeEventListener("keydown", onKeydown, true);
|
||||
window.removeEventListener("pointerdown", onDocumentPointerDown, true);
|
||||
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,12 +24,42 @@ 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';
|
||||
import { hostChromeActiveSkinId } from '../services/host-chrome.js';
|
||||
import {
|
||||
PERMISSION_CONTROL_DEFAULTS,
|
||||
bindHostControlTheme,
|
||||
findSkinRoot,
|
||||
} from '../services/host-control-tokens.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 var(--ws-control-border,#dbe3f1);border-radius:var(--ws-control-radius,20px);background:var(--ws-control-background,#fff);color:var(--ws-control-foreground,#25324b);font-family:var(--ws-control-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--ws-control-font-size,14px);line-height:1.75;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:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:var(--ws-control-foreground,#526079)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));border:1px solid var(--ws-control-border,#dce3f3);border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:var(--ws-control-accent,#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:var(--ws-control-hit,42px);padding:9px 16px;border:1px solid var(--ws-control-border,#d9e1ef);border-radius:var(--ws-control-radius,10px);background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));color:var(--ws-control-foreground,#43516d);font:600 var(--ws-control-font-size,14px)/1.5 var(--ws-control-font,system-ui);cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:var(--ws-control-accent,#5265df);color:var(--ws-control-on-accent,#fff);border-color:var(--ws-control-accent,#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 var(--ws-control-accent,#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]);
|
||||
|
||||
/** The authorization dialog is host-owned; only sanitized tokens can theme it. */
|
||||
const theme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
control: () => dialog.value,
|
||||
part: 'host.permission',
|
||||
defaults: PERMISSION_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
}) : null;
|
||||
|
||||
watch([dialog, hostChromeActiveSkinId], () => { theme?.apply(); }, { flush: 'post', immediate: true });
|
||||
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
|
||||
watch([dialog, authorizationRequested, authorizationDecision], () => {
|
||||
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
|
||||
theme?.apply();
|
||||
firstVisit.value = authorizationDecision.value === null;
|
||||
checked.value = authorizationDecision.value === true;
|
||||
dialog.value.showModal();
|
||||
@@ -34,12 +68,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(); theme?.dispose(); 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="skinIcon ? 'language.trigger' : undefined" />
|
||||
<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" />
|
||||
@@ -50,6 +50,7 @@ import Icon from "./Icon.vue";
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
skinIcon?: boolean;
|
||||
modelValue: Language;
|
||||
menuLabel?: string;
|
||||
}>(), {
|
||||
|
||||
@@ -1,15 +1,29 @@
|
||||
<template>
|
||||
<Teleport to="#webspeak-plugin-toolbar">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-toolbar">
|
||||
<button ref="launcher" class="header-action ws-plugin-toolbar-trigger" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<Teleport :to="toolbarTarget ?? 'body'">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" :data-ws-float="toolbarTarget ? undefined : fallbackPosition" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
|
||||
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @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 v-if="presentation === 'drawer-side'">{{ tr('title') }}</span>
|
||||
</button>
|
||||
<button v-for="entry in pinnedApps" :key="entry.manifest.id" class="header-action ws-plugin-toolbar-shortcut" type="button" :title="entry.manifest.name" :aria-label="entry.manifest.name" :disabled="busy || entry.runtime.state === 'failed'" @click="launch(entry.manifest.id)">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</button>
|
||||
<section v-if="drawerOpen" :id="drawerId" ref="drawer" class="ws-plugin-drawer" data-ws-part="voice.plugin-drawer" :aria-label="tr('title')">
|
||||
<input ref="drawerSearch" v-model="search" class="ws-plugin-drawer-search" type="search" :placeholder="ui.search" :aria-label="ui.search" />
|
||||
<p v-if="error" role="alert">{{ error }}</p>
|
||||
<p v-else-if="busy && !available.length" role="status">{{ tr('loading') }}</p>
|
||||
<p v-else-if="!filtered.length">{{ available.length ? ui.noResults : tr('empty') }}</p>
|
||||
<ul v-if="filtered.length">
|
||||
<li v-for="entry in filtered" :key="entry.manifest.id">
|
||||
<button type="button" class="ws-plugin-drawer-app" data-ws-part="voice.plugin-drawer.app" :disabled="busy || entry.runtime.state === 'failed'" :title="entry.runtime.error || entry.manifest.name" @click="launch(entry.manifest.id)">
|
||||
<span class="ws-plugin-drawer-mark" aria-hidden="true">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</span>
|
||||
<span>{{ entry.manifest.name }}</span><span v-if="entry.toolbarPinned" aria-hidden="true">★</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
<Teleport to="body">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
|
||||
<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>
|
||||
@@ -19,13 +33,13 @@
|
||||
<button class="ws-plugin-close" type="button" :title="tr('close')" :aria-label="tr('close')" @click="close"><svg viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" /></svg></button>
|
||||
</div>
|
||||
</header>
|
||||
<nav class="ws-plugin-navigation" :aria-label="tr('title')">
|
||||
<nav v-if="dialogLibrary" class="ws-plugin-navigation" :aria-label="tr('title')">
|
||||
<button type="button" :class="{ active: !appView }" @click="appView = false">{{ ui.workspace }}</button>
|
||||
<button v-if="current" type="button" :class="{ active: appView }" @click="appView = true">{{ current.manifest.name }}</button>
|
||||
<span v-if="current && appView" class="ws-plugin-version">v{{ current.manifest.version }}</span>
|
||||
</nav>
|
||||
<p v-if="error" role="alert" class="ws-plugin-error">{{ error }}</p>
|
||||
<div v-show="!appView" class="ws-plugin-library">
|
||||
<div v-if="dialogLibrary" v-show="!appView" class="ws-plugin-library">
|
||||
<div class="ws-plugin-library-heading"><div><h2>{{ tr('title') }}</h2><span>{{ available.length }} {{ ui.count }}</span></div><button type="button" :disabled="busy" @click="refresh">{{ busy ? tr('loading') : tr('refresh') }}</button></div>
|
||||
<input v-model="search" class="ws-plugin-search" type="search" :placeholder="ui.search" :aria-label="ui.search" />
|
||||
<p v-if="!busy && !filtered.length" class="ws-plugin-empty">{{ available.length ? ui.noResults : tr('empty') }}</p>
|
||||
@@ -47,23 +61,37 @@
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, useId, watch } from 'vue';
|
||||
import { createPluginAppClient, type AvailablePluginApp, type PluginAppClient } from '../services/plugin-app-client.js';
|
||||
import { type PluginAppLaunch, pluginRecord } from '../../../src/shared/plugins.js';
|
||||
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';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage }>();
|
||||
import { isHostPartHidden, isHostPartVisuallyReachable, pluginLibraryRequests } from '../services/host-chrome.js';
|
||||
import type { SkinPluginWidgetOptions } from '../../../src/shared/skin-plugin.js';
|
||||
import { bindFloatingAvoidance, type FloatingAvoidance, type FloatingPosition } from '../services/host-floating-placement.js';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null; presentation: NonNullable<SkinPluginWidgetOptions['pluginPresentation']> }>();
|
||||
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
|
||||
const ui = computed(() => pluginWindowTranslations[props.language]);
|
||||
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
|
||||
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
|
||||
const pinnedApps = computed(() => available.value.filter(entry => entry.toolbarPinned));
|
||||
const toolbar = ref<HTMLElement | null>(null);
|
||||
// The fallback toolbar floats in a viewport corner the skin knows nothing
|
||||
// about; move it off any skin control it would cover (runtime only).
|
||||
const fallbackPosition = ref<FloatingPosition>('bottom-right');
|
||||
let fallbackAvoidance: FloatingAvoidance | undefined;
|
||||
const drawerOpen = ref(false);
|
||||
const drawer = ref<HTMLElement | null>(null);
|
||||
const drawerSearch = ref<HTMLInputElement | null>(null);
|
||||
const drawerId = useId();
|
||||
const dialogLibrary = ref(false);
|
||||
const busy = ref(false), error = ref(''), theme = ref<'light' | 'dark'>('light');
|
||||
const visible = ref(false), maximized = ref(false), appView = ref(false), dragging = ref(false), search = ref('');
|
||||
const position = ref<Record<string, string>>({});
|
||||
const filtered = computed(() => available.value.filter(entry => `${entry.manifest.name} ${entry.manifest.description}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())));
|
||||
const filtered = computed(() => available.value
|
||||
.filter(entry => `${entry.manifest.name} ${entry.manifest.description}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase()))
|
||||
.sort((a, b) => Number(b.toolbarPinned) - Number(a.toolbarPinned)));
|
||||
let epoch = 0, pending: AbortController | undefined, opening: { client: PluginAppClient; key: string } | undefined, observer: MutationObserver | undefined;
|
||||
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; moved: boolean } | undefined;
|
||||
let resizeObserver: ResizeObserver | undefined;
|
||||
@@ -88,31 +116,75 @@ async function refresh() {
|
||||
finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
|
||||
}
|
||||
function toggle() {
|
||||
if (visible.value) { minimize(); return; }
|
||||
detectTheme(); visible.value = true;
|
||||
if (!current.value) { appView.value = false; void refresh(); }
|
||||
if (props.presentation === 'dialog') {
|
||||
if (visible.value && dialogLibrary.value) { minimize(); return; }
|
||||
openLibraryDialog();
|
||||
return;
|
||||
}
|
||||
if (drawerOpen.value) { drawerOpen.value = false; return; }
|
||||
openDrawer();
|
||||
}
|
||||
function openDrawer() {
|
||||
drawerOpen.value = true;
|
||||
detectTheme();
|
||||
visible.value = false;
|
||||
search.value = '';
|
||||
if (!busy.value) void refresh();
|
||||
void nextTick(() => { fitDrawer(); drawerSearch.value?.focus({ preventScroll: true }); });
|
||||
}
|
||||
function openLibraryDialog() {
|
||||
drawerOpen.value = false;
|
||||
detectTheme();
|
||||
dialogLibrary.value = true;
|
||||
visible.value = true;
|
||||
appView.value = false;
|
||||
if (!busy.value) void refresh();
|
||||
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
|
||||
}
|
||||
function dismissDrawer(event: KeyboardEvent) {
|
||||
if (!drawerOpen.value) return;
|
||||
event.stopPropagation();
|
||||
drawerOpen.value = false;
|
||||
launcher.value?.focus();
|
||||
}
|
||||
function closeDrawerOutside(event: PointerEvent) {
|
||||
if (drawerOpen.value && toolbar.value && !event.composedPath().includes(toolbar.value)) drawerOpen.value = false;
|
||||
}
|
||||
function fitDrawer() {
|
||||
const element = drawer.value;
|
||||
if (!element || props.presentation !== 'drawer-below') return;
|
||||
element.style.translate = '';
|
||||
const box = element.getBoundingClientRect();
|
||||
const delta = Math.max(8 - box.left, Math.min(0, document.documentElement.clientWidth - 8 - box.right));
|
||||
if (delta) element.style.translate = `${delta}px 0`;
|
||||
}
|
||||
function minimize() { endDrag(); visible.value = false; launcher.value?.focus(); }
|
||||
function close() { stop(); error.value = ''; available.value = []; search.value = ''; minimize(); }
|
||||
function close() { drawerOpen.value = false; stop(); error.value = ''; available.value = []; search.value = ''; minimize(); }
|
||||
function stop() {
|
||||
++epoch; pending?.abort(); pending = undefined; const old = opening; opening = undefined; current.value = null; appView.value = false; busy.value = false;
|
||||
if (old) void old.client.cancelOpen(old.key).catch(() => undefined);
|
||||
}
|
||||
async function launch(id: string) {
|
||||
if (!thirdPartyAllowed.value) return;
|
||||
if (!thirdPartyAllowed.value || !props.connected || !props.sessionToken || busy.value) return;
|
||||
if (drawerOpen.value) dialogLibrary.value = false;
|
||||
drawerOpen.value = false;
|
||||
detectTheme(); visible.value = true;
|
||||
if (current.value?.manifest.id === id) { appView.value = true; return; }
|
||||
if (current.value?.manifest.id === id) { appView.value = true; focusAppWindow(); return; }
|
||||
stop(); const owner = ++epoch, controller = new AbortController(), service = client(), key = crypto.randomUUID(); pending = controller; opening = { client: service, key }; busy.value = true; error.value = '';
|
||||
try {
|
||||
const app = await service.open(id, { openId: key, theme: theme.value, language: props.language }, controller.signal);
|
||||
if (owner !== epoch) return;
|
||||
if (new URL(app.url).origin === location.origin) throw new Error('PLUGIN_SEPARATE_ORIGIN_REQUIRED');
|
||||
current.value = app; appView.value = true;
|
||||
focusAppWindow();
|
||||
} catch (e) {
|
||||
if (owner === epoch) { const old = opening; opening = undefined; if (old) void old.client.cancelOpen(old.key).catch(() => undefined); if (!controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
} finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
|
||||
}
|
||||
function focusAppWindow() {
|
||||
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
|
||||
}
|
||||
watch([() => props.toolbarTarget, () => props.presentation], () => { drawerOpen.value = false; });
|
||||
function message(event: MessageEvent) {
|
||||
if (!current.value || event.source !== frame.value?.contentWindow || event.origin !== new URL(current.value.url).origin || !pluginRecord(event.data)) return;
|
||||
if (event.data.type === 'webspeak-app-closed' && event.data.id === current.value.id) { stop(); error.value = tr('context'); }
|
||||
@@ -153,10 +225,42 @@ watch(thirdPartyAllowed, allowed => {
|
||||
else if (props.connected) void refresh();
|
||||
}, { 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 toolbar launcher.
|
||||
watch(pluginLibraryRequests, () => {
|
||||
if (!thirdPartyAllowed.value || !props.connected || !props.sessionToken) return;
|
||||
if (props.presentation !== 'dialog' && isHostPartVisuallyReachable('host.plugins.launcher')) openDrawer();
|
||||
else openLibraryDialog();
|
||||
});
|
||||
watch([toolbar, () => props.toolbarTarget], ([element, target]) => {
|
||||
fallbackAvoidance?.dispose();
|
||||
fallbackAvoidance = undefined;
|
||||
fallbackPosition.value = 'bottom-right';
|
||||
if (!element || target) return;
|
||||
fallbackAvoidance = bindFloatingAvoidance({
|
||||
element,
|
||||
isSelf: node => element.contains(node),
|
||||
// Same numbers as .ws-plugin-toolbar-fallback in plugin-overlay.css.
|
||||
margins: insets => ({ top: 16 + insets.top, right: 16, bottom: 16 + insets.bottom, left: 16 }),
|
||||
defaultPosition: 'bottom-right',
|
||||
apply: next => { fallbackPosition.value = next; },
|
||||
// Sticky :hover after a tap on touch screens must not pause avoidance.
|
||||
paused: () => drawerOpen.value
|
||||
|| (matchMedia('(hover: hover)').matches && element.matches(':hover'))
|
||||
|| element.contains(document.activeElement),
|
||||
});
|
||||
}, { flush: 'post' });
|
||||
onBeforeUnmount(() => { fallbackAvoidance?.dispose(); fallbackAvoidance = undefined; });
|
||||
onMounted(() => {
|
||||
document.addEventListener('pointerdown', closeDrawerOutside, true);
|
||||
window.addEventListener('resize', fitDrawer);
|
||||
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);
|
||||
if (props.connected && thirdPartyAllowed.value) void refresh();
|
||||
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(() => {
|
||||
document.removeEventListener('pointerdown', closeDrawerOutside, true);
|
||||
window.removeEventListener('resize', fitDrawer);
|
||||
});
|
||||
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">
|
||||
<Teleport v-if="layer" :to="layer.container">
|
||||
<section v-if="error" ref="banner" 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>
|
||||
@@ -8,9 +8,16 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js";
|
||||
import { createHostOwnedLayer, type HostOwnedLayer } from "../services/host-owned-layer.js";
|
||||
import { hostChromeActiveSkinId } from "../services/host-chrome.js";
|
||||
import {
|
||||
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
bindHostControlTheme,
|
||||
findSkinRoot,
|
||||
} from "../services/host-control-tokens.js";
|
||||
|
||||
defineEmits<{ "use-built-in": [] }>();
|
||||
|
||||
@@ -19,9 +26,11 @@ const props = defineProps<{
|
||||
language: Language;
|
||||
}>();
|
||||
const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.language)]);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
// The banner is trusted host UI: render it in a closed shadow root so compiled
|
||||
// skin CSS cannot restyle it (or hide it) from the document. The layer's fixed
|
||||
// wrapper is pointer-transparent, so the banner re-enables pointer events.
|
||||
const SKIN_LOAD_LAYER_CSS = `
|
||||
.skin-load-recovery {
|
||||
position: fixed;
|
||||
z-index: 2147482500;
|
||||
@@ -32,21 +41,50 @@ const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.l
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
width: min(720px, calc(100vw - 24px));
|
||||
box-sizing: border-box;
|
||||
padding: 10px 12px;
|
||||
transform: translateX(-50%);
|
||||
border: 1px solid #f59e0b;
|
||||
border-radius: 12px;
|
||||
color: #78350f;
|
||||
background: #fffbeb;
|
||||
border: 1px solid var(--ws-control-border, #f59e0b);
|
||||
border-radius: var(--ws-control-radius, 12px);
|
||||
color: var(--ws-control-foreground, #78350f);
|
||||
background: var(--ws-control-background, #fffbeb);
|
||||
box-shadow: 0 8px 28px #0f172a33;
|
||||
font: 14px/1.45 ui-sans-serif, system-ui, sans-serif;
|
||||
font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
|
||||
font-size: var(--ws-control-font-size, 14px);
|
||||
line-height: 1.45;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.skin-load-recovery p { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
|
||||
.skin-load-recovery button { flex: 0 0 auto; min-height: 44px; max-width: 100%; padding: 7px 10px; border: 1px solid #b45309; border-radius: 8px; color: #78350f; background: #fff; cursor: pointer; white-space: normal; }
|
||||
.skin-load-recovery button:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; }
|
||||
|
||||
.skin-load-recovery button { flex: 0 0 auto; min-height: var(--ws-control-hit, 44px); max-width: 100%; padding: 7px 10px; border: 1px solid var(--ws-control-accent, #b45309); border-radius: var(--ws-control-radius, 8px); color: var(--ws-control-foreground, #78350f); background: var(--ws-control-background, #fff); font: inherit; cursor: pointer; white-space: normal; }
|
||||
.skin-load-recovery button:focus-visible { outline: 3px solid var(--ws-control-accent, #1d4ed8); outline-offset: 2px; }
|
||||
@media (max-width: 520px) {
|
||||
.skin-load-recovery { align-items: stretch; flex-direction: column; gap: 7px; }
|
||||
.skin-load-recovery button { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
`;
|
||||
|
||||
const layer: HostOwnedLayer | null = createHostOwnedLayer("skin-load", SKIN_LOAD_LAYER_CSS);
|
||||
const banner = ref<HTMLElement | null>(null);
|
||||
|
||||
/**
|
||||
* Tokens come from the active skin root, never from the document. The banner
|
||||
* appears when a skin failed to load, so a missing root simply keeps the
|
||||
* built-in amber surface; an unreadable palette reverts the same way.
|
||||
*/
|
||||
const theme = layer ? bindHostControlTheme({
|
||||
layer,
|
||||
control: () => banner.value,
|
||||
part: "app.skin-load-recovery",
|
||||
defaults: SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
|
||||
source: () => findSkinRoot(hostChromeActiveSkinId.value),
|
||||
}) : null;
|
||||
|
||||
watch([() => props.error, banner, hostChromeActiveSkinId], () => {
|
||||
void nextTick(() => theme?.apply());
|
||||
}, { flush: "post", immediate: true });
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
theme?.dispose();
|
||||
layer?.dispose();
|
||||
});
|
||||
</script>
|
||||
@@ -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 && pluginLibraryAvailable" 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;
|
||||
@@ -58,6 +63,7 @@ const props = defineProps<{
|
||||
modelValue: string;
|
||||
menuLabel: string;
|
||||
options: SkinOption[];
|
||||
pluginLibraryAvailable?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -67,7 +73,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 +109,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;
|
||||
|
||||
@@ -273,7 +273,51 @@
|
||||
>{{ tr("exportBackup") }}</button
|
||||
></article
|
||||
>
|
||||
<div class="alert info system-notice"><Icon name="info" :size="16"/><span>{{ tr('updateNotice', {version: operations.diagnostics.version || '—'}) }}</span></div>
|
||||
<article class="operation-card update-card" data-admin-update="version">
|
||||
<header>
|
||||
<div><h3>{{ tr('updateTitle') }}</h3><p>{{ tr('updateLead') }}</p></div>
|
||||
<span :class="['state-pill', canApplyUpdates ? 'active' : '']">{{ canApplyUpdates ? tr('updateCanApply') : tr('updateCannotApply') }}</span>
|
||||
</header>
|
||||
<dl class="diagnostic-list">
|
||||
<div><dt>{{ tr('updateCurrentVersion') }}</dt><dd>{{ operations.update.currentVersion || operations.diagnostics.version || '—' }}</dd></div>
|
||||
<div><dt>{{ tr('updateDeploymentMode') }}</dt><dd>{{ deploymentLabel }}</dd></div>
|
||||
<div><dt>{{ tr('updateArchitecture') }}</dt><dd>{{ operations.update.deployment.platform || '—' }} / {{ operations.update.deployment.architecture || '—' }}</dd></div>
|
||||
</dl>
|
||||
<div v-if="operations.update.task" class="update-task" data-admin-update-task>
|
||||
<strong>{{ tr('updateTaskTitle') }}: {{ updateTaskStatusLabel }}</strong>
|
||||
<small v-if="updateTaskErrorText">{{ updateTaskErrorText }}</small>
|
||||
<small v-else-if="operations.update.task.status === 'succeeded'">{{ tr('updateRestartHint') }}</small>
|
||||
<small v-if="operations.update.task.rolledBack">{{ tr('updateRolledBack') }}</small>
|
||||
<small v-if="operations.update.task.finishedAt">{{ formatDate(operations.update.task.finishedAt) }}</small>
|
||||
</div>
|
||||
<div v-if="!canApplyUpdates" class="alert info system-notice">
|
||||
<Icon name="info" :size="16"/><span>{{ blockedUpdateText }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<p v-if="canApplyUpdates" class="field-help">{{ tr('updateBackupHint') }}</p>
|
||||
<div class="update-actions">
|
||||
<button class="secondary-button" type="button" data-admin-update="check" :disabled="updateChecking" @click="checkForUpdates">
|
||||
<span v-if="updateChecking" class="spinner small"></span><Icon v-else name="refresh" :size="17"/>
|
||||
{{ updateChecking ? tr('updateChecking') : tr('updateCheckAction') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="availableUpdates.length" class="update-release-list">
|
||||
<strong v-if="canApplyUpdates">{{ tr('updateSelectRelease') }}</strong>
|
||||
<p v-if="canApplyUpdates" class="field-help">{{ tr('updateChecksumNotice') }}</p>
|
||||
<label v-for="release in availableUpdates" :key="release.version" class="update-release-row">
|
||||
<input v-if="canApplyUpdates" v-model="selectedVersion" type="radio" :value="release.version" :disabled="!release.canApply || updateApplying" />
|
||||
<span><strong>v{{ release.version }}</strong> <small>{{ formatDate(release.publishedAt) }}</small></span>
|
||||
<a v-if="release.releaseUrl" :href="release.releaseUrl" target="_blank" rel="noreferrer">{{ tr('updateReleaseNotes') }}</a>
|
||||
<small v-if="!release.canApply" class="muted-label">{{ releaseBlockedText(release) }}</small>
|
||||
</label>
|
||||
<button v-if="canApplyUpdates" class="primary-button" type="button" data-admin-update="apply" :disabled="!selectedRelease || updateApplying" @click="applySelectedUpdate">
|
||||
<span v-if="updateApplying" class="spinner small"></span>
|
||||
{{ updateApplying ? tr('updateApplying') : tr('updateApplyAction') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-else-if="updateChecked" class="field-help">{{ tr('updateUpToDate') }}</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -288,13 +332,54 @@ import type { AdminConnectionRecord } from "../../../../src/shared/admin-respons
|
||||
const props = defineProps<{
|
||||
model: ReturnType<typeof useAdminOperations>;
|
||||
initialSection?: string;
|
||||
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText">;
|
||||
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText" | "errorText">;
|
||||
}>();
|
||||
// Request ownership, cancellation and drafts remain in the page's controller.
|
||||
const { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
|
||||
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup } = props.model;
|
||||
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText } = props.i18n;
|
||||
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup,
|
||||
updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion, checkForUpdates, applyUpdate } = props.model;
|
||||
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText, errorText } = props.i18n;
|
||||
type OperationsSection = 'sessions' | 'invites' | 'logs' | 'audit' | 'maintenance';
|
||||
const canApplyUpdates = computed(() => operations.update.deployment.applyAllowed);
|
||||
const deploymentLabel = computed(() => {
|
||||
const mode = operations.update.deployment.mode;
|
||||
return mode === 'docker' ? tr('updateModeDocker') : mode === 'release-package' ? tr('updateModeReleasePackage') : tr('updateModeSource');
|
||||
});
|
||||
function blockedReasonText(code: string | null) {
|
||||
switch (code) {
|
||||
case 'DEPLOYMENT_DOCKER': return tr('updateBlockedDocker');
|
||||
case 'DEPLOYMENT_SOURCE': return tr('updateBlockedSource');
|
||||
case 'DEPLOYMENT_SUPERVISED': return tr('updateBlockedSupervised');
|
||||
case 'PLATFORM_UNSUPPORTED': return tr('updateBlockedPlatform');
|
||||
case 'ARCH_UNSUPPORTED': return tr('updateBlockedArch');
|
||||
case 'WINDOWS_APPLY_UNVERIFIED': return tr('updateBlockedWindows');
|
||||
case 'LINUX_ARM64_APPLY_UNVERIFIED': return tr('updateBlockedArm64');
|
||||
case 'UPDATE_ASSET_UNAVAILABLE': return tr('updateAssetMissing');
|
||||
case 'UPDATE_CHECKSUM_MISSING': return tr('updateChecksumMissing');
|
||||
default: return tr('updateBlockedUnavailable');
|
||||
}
|
||||
}
|
||||
const blockedUpdateText = computed(() => blockedReasonText(operations.update.deployment.reasonCode));
|
||||
const releaseBlockedText = (release: { blockedReason: string | null }) => blockedReasonText(release.blockedReason);
|
||||
function updateStatusText(status: string | undefined) {
|
||||
switch (status) {
|
||||
case 'downloading': return tr('updateStatusDownloading');
|
||||
case 'verifying': return tr('updateStatusVerifying');
|
||||
case 'extracting': return tr('updateStatusExtracting');
|
||||
case 'staging': return tr('updateStatusStaging');
|
||||
case 'restarting': return tr('updateStatusRestarting');
|
||||
case 'succeeded': return tr('updateStatusSucceeded');
|
||||
case 'failed': return tr('updateStatusFailed');
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
const updateTaskStatusLabel = computed(() => updateStatusText(operations.update.task?.status));
|
||||
const updateTaskErrorText = computed(() => operations.update.task?.errorCode ? errorText(operations.update.task.errorCode) : '');
|
||||
const selectedRelease = computed(() => availableUpdates.value.find(release => release.version === selectedVersion.value && release.canApply) ?? null);
|
||||
function applySelectedUpdate() {
|
||||
const release = selectedRelease.value;
|
||||
if (release) void applyUpdate(release);
|
||||
}
|
||||
const normalizeSection = (value?: string): OperationsSection => value === 'invites' || value === 'logs' || value === 'audit' || value === 'maintenance' ? value : 'sessions';
|
||||
const activeSection = ref<OperationsSection>(normalizeSection(props.initialSection));
|
||||
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<nav class="plugin-tabs" :aria-label="tr('store')"><button type="button" :aria-current="tab==='store'?'page':undefined" @click="tab='store'"><Icon name="compass" :size="16" />{{ text('discover') }}</button><button type="button" :aria-current="tab==='installed'?'page':undefined" @click="tab='installed'"><Icon name="grid" :size="16" />{{ tr('installed') }}<span>{{ model.installed.value.length }}</span></button></nav>
|
||||
<div class="plugin-tools"><label class="plugin-search"><Icon name="search" :size="16" /><input v-model="search" type="search" :aria-label="text('search')" :placeholder="text('search')" /></label><button class="plugin-refresh" type="button" :disabled="model.busy.value" :title="tr('refresh')" :aria-label="tr('refresh')" @click="model.load"><Icon name="refresh" :size="17" /></button></div>
|
||||
</div>
|
||||
<p v-if="model.error.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('error') }}: {{ model.error.value }}</p>
|
||||
<p v-if="model.error.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ describeError(model.error.value) }}</p>
|
||||
<p v-if="tab==='store' && model.catalogError.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('catalogError') }} · {{ model.catalogError.value }}</p>
|
||||
<p v-if="notice" class="plugin-feedback" role="status"><Icon name="check" :size="17" />{{ notice }}</p>
|
||||
<div class="plugin-section-heading"><div><h3>{{ tab==='store'?text('discover'):tr('installed') }}</h3><span v-if="tab==='store'" class="plugin-source"><i></i>{{ text('source') }}</span></div><a v-if="tab==='store'" :href="PLUGIN_STORE_REPOSITORY" target="_blank" rel="noopener noreferrer"><Icon name="github" :size="16" />GitHub ↗</a><button v-else class="plugin-button" type="button" :disabled="model.busy.value" @click="fileInput?.click()"><Icon name="share" :size="15" />{{ tr('upload') }}</button></div>
|
||||
@@ -19,20 +19,108 @@
|
||||
<article v-for="entry in catalogEntries" :key="entry.id" class="plugin-market-card">
|
||||
<div class="plugin-card-visual"><div class="plugin-card-symbol"><Icon name="grid" :size="38" /></div><span>API {{ entry.manifest?.apiVersion ?? '—' }}</span><i aria-hidden="true"></i></div>
|
||||
<div class="plugin-card-body"><div class="plugin-card-title"><h4>{{ entry.manifest?.name ?? entry.id }}</h4><small>v{{ entry.manifest?.version ?? '—' }}</small></div><p class="plugin-author">{{ entry.manifest?.author }} · {{ entry.manifest?.license }}</p><p class="plugin-description">{{ entry.manifest?.description }}</p><div class="plugin-tags"><span v-for="scope in entry.manifest?.scopes" :key="scope"><Icon name="server" :size="12" />{{ tr(scope) }}</span></div><div class="plugin-permissions"><span>{{ tr('client') }}</span><span v-if="entry.manifest?.server">{{ tr('backend') }}</span></div><p v-if="entry.error" class="is-error">{{ entry.error }}</p></div>
|
||||
<footer><a :href="entry.repository" target="_blank" rel="noopener noreferrer" :aria-label="`${entry.manifest?.name ?? entry.id} · GitHub`"><Icon name="github" :size="16" />GitHub ↗</a><button class="plugin-button primary" type="button" :disabled="model.busy.value || !entry.manifest || !!entry.error" @click="install(entry)"><Icon name="download" :size="15" />{{ installLabel(entry) }}</button></footer>
|
||||
<footer><a :href="entry.repository" target="_blank" rel="noopener noreferrer" :aria-label="`${tr('viewRepository')} · ${entry.manifest?.name ?? entry.id}`"><Icon name="github" :size="16" />{{ tr('viewRepository') }} ↗</a><button class="plugin-button primary" type="button" :disabled="model.busy.value || !entry.manifest || !!entry.error" @click="install(entry)"><Icon name="download" :size="15" />{{ installLabel(entry) }}</button></footer>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else class="plugin-installed-list">
|
||||
<article v-for="plugin in installedEntries" :key="plugin.manifest.id" class="plugin-installed-card">
|
||||
<header><div class="plugin-installed-icon"><Icon name="grid" :size="23" /></div><div class="plugin-installed-name"><h4>{{ plugin.manifest.name }}</h4><p>v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}</p></div><span class="plugin-status" :class="{active:plugin.settings.enabled}"><i></i>{{ tr(plugin.runtime?.state ?? 'disabled') }}</span></header>
|
||||
<p class="plugin-description">{{ plugin.manifest.description }}</p><p v-if="plugin.runtime?.error" class="is-error" role="alert">{{ plugin.runtime.error }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span></div>
|
||||
<p class="plugin-description">{{ plugin.manifest.description }}</p><p v-if="plugin.runtime?.error" class="is-error" role="alert">{{ plugin.manifest.id === musicBotId && plugin.runtime.error === 'PLUGIN_START_FAILED' && !plugin.settings.hasServerConfig ? tr('musicBotConfigHelp') : plugin.runtime.error }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span><a v-if="repository(plugin.manifest.id)" :href="repository(plugin.manifest.id)" target="_blank" rel="noopener noreferrer"><Icon name="github" :size="14" />{{ tr('viewRepository') }} ↗</a></div>
|
||||
<details :open="expanded===plugin.manifest.id" @toggle="onToggle($event,plugin.manifest.id)"><summary><Icon name="settings" :size="16" />{{ text('configure') }}<Icon class="plugin-chevron" name="chevron-down" :size="15" /></summary><fieldset :disabled="model.busy.value">
|
||||
<div class="plugin-enable-row"><div><strong>{{ tr('enabled') }}</strong><p>{{ text('review') }}</p></div><label class="plugin-switch"><input v-model="model.drafts[plugin.manifest.id].enabled" type="checkbox" :aria-label="tr('enabled')" /><span></span></label></div>
|
||||
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].trusted" type="checkbox" />{{ tr('trust') }}</label><p class="plugin-trust-note">{{ tr('enableNote') }}</p>
|
||||
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].toolbarPinned" type="checkbox" />{{ tr('toolbarPin') }}</label>
|
||||
<label>{{ tr('scope') }}<select v-model="model.drafts[plugin.manifest.id].scope"><option v-for="scope in plugin.manifest.scopes" :key="scope" :value="scope">{{ tr(scope) }}</option></select></label>
|
||||
<label v-if="model.drafts[plugin.manifest.id].scope==='server'">{{ tr('targets') }}<textarea v-model="model.drafts[plugin.manifest.id].targets" rows="3" maxlength="15000" placeholder="voice.example.com:9987"></textarea></label>
|
||||
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="65536" spellcheck="false"></textarea></label><template v-if="plugin.manifest.server"><label>{{ tr('privateConfig') }}<small>{{ tr(plugin.settings.hasServerConfig?'secretSaved':'secretEmpty') }}</small><select v-model="model.drafts[plugin.manifest.id].serverConfigAction"><option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option></select><textarea v-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace'" v-model="model.drafts[plugin.manifest.id].serverConfig" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" autocapitalize="off" autocorrect="off"></textarea></label></template></details>
|
||||
<details class="plugin-advanced">
|
||||
<summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary>
|
||||
<template v-if="plugin.manifest.id === musicBotId && plugin.manifest.server">
|
||||
<p class="plugin-config-help">{{ tr('musicBotConfigHelp') }}</p>
|
||||
<a class="plugin-setup-link" :href="`${musicBotRepository}#配置`" target="_blank" rel="noopener noreferrer">{{ tr('setupGuide') }} ↗</a>
|
||||
<label>{{ tr('privateConfig') }}
|
||||
<small>{{ tr(plugin.settings.hasServerConfig ? 'secretSaved' : 'secretEmpty') }}</small>
|
||||
<select v-model="model.drafts[plugin.manifest.id].serverConfigAction">
|
||||
<option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div v-if="model.drafts[plugin.manifest.id].serverConfigAction === 'replace'" class="plugin-config-grid">
|
||||
<div v-for="field in musicBotPrivateFields" :key="field.key" class="plugin-config-field">
|
||||
<div v-if="field.type === 'json'" role="group" :aria-label="field.key">
|
||||
<p>{{ field.key }}</p>
|
||||
<PluginConfigValue fixed string-children :labels="valueLabels" :model-value="model.musicBotCollection(plugin.manifest.id, 'privateFields', field.key)" @update:model-value="model.setMusicBotCollection(plugin.manifest.id, 'privateFields', field.key, $event)" />
|
||||
</div>
|
||||
<label v-else>{{ field.key }}{{ field.key === 'apiKey' ? ' *' : '' }}
|
||||
<input v-model="model.drafts[plugin.manifest.id].privateFields[field.key]" :type="field.type" :placeholder="field.placeholder" :aria-required="field.key === 'apiKey'" :autocomplete="field.type === 'password' ? 'new-password' : 'off'" spellcheck="false" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p class="plugin-config-help">{{ tr('config') }}</p>
|
||||
<div class="plugin-config-grid">
|
||||
<div v-for="field in musicBotPublicFields" :key="field.key" class="plugin-config-field">
|
||||
<div v-if="field.type === 'json'" role="group" :aria-label="field.key">
|
||||
<p>{{ field.key }}</p>
|
||||
<PluginConfigValue fixed string-children :labels="valueLabels" :model-value="model.musicBotCollection(plugin.manifest.id, 'publicFields', field.key)" @update:model-value="model.setMusicBotCollection(plugin.manifest.id, 'publicFields', field.key, $event)" />
|
||||
</div>
|
||||
<label v-else>{{ field.key }}
|
||||
<select v-if="field.choices" v-model="model.drafts[plugin.manifest.id].publicFields[field.key]">
|
||||
<option value="">{{ tr('configDefault') }} ({{ field.placeholder }})</option>
|
||||
<option v-for="choice in field.choices" :key="choice" :value="choice">{{ choice }}</option>
|
||||
</select>
|
||||
<input v-else v-model="model.drafts[plugin.manifest.id].publicFields[field.key]" :type="field.type" :placeholder="field.placeholder" spellcheck="false" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div v-if="plugin.manifest.id === fileTransferId" class="plugin-config-group">
|
||||
<label>{{ tr('maxFileSize') }}
|
||||
<input v-model="model.drafts[plugin.manifest.id].publicFields.maxFileMiB" type="number" min="1" max="2048" placeholder="256" />
|
||||
</label>
|
||||
<p>{{ tr('fileTransferIceHelp') }}</p>
|
||||
</div>
|
||||
<div v-else-if="plugin.manifest.id === watchTogetherId" class="plugin-config-group">
|
||||
<label>{{ tr('playbackControl') }}
|
||||
<select v-model="model.drafts[plugin.manifest.id].publicFields.control">
|
||||
<option value="">{{ tr('configDefault') }} · {{ tr('controlEveryone') }}</option>
|
||||
<option value="everyone">{{ tr('controlEveryone') }}</option>
|
||||
<option value="host">{{ tr('controlHost') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p>{{ tr('watchTogetherConfigHelp') }}</p>
|
||||
</div>
|
||||
<div v-else class="plugin-config-group" role="group" :aria-label="tr('config')">
|
||||
<p>{{ tr('config') }}</p>
|
||||
<PluginConfigValue :labels="valueLabels" :model-value="model.configValue(plugin.manifest.id, 'config')" @update:model-value="model.setConfigValue(plugin.manifest.id, 'config', $event)" />
|
||||
</div>
|
||||
<template v-if="plugin.manifest.server && plugin.manifest.id !== watchTogetherId">
|
||||
<p v-if="plugin.manifest.id !== fileTransferId" class="plugin-config-help">
|
||||
{{ tr('privateConfigHelp') }}
|
||||
</p>
|
||||
<label>{{ tr('privateConfig') }}
|
||||
<small>{{ tr(plugin.settings.hasServerConfig?'secretSaved':'secretEmpty') }}</small>
|
||||
<small v-if="plugin.manifest.id === fileTransferId">{{ tr('replaceIceHelp') }}</small>
|
||||
<select v-model="model.drafts[plugin.manifest.id].serverConfigAction">
|
||||
<option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div v-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace' && plugin.manifest.id === fileTransferId" class="plugin-config-group">
|
||||
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].defaultIce" type="checkbox" />{{ tr('defaultIce') }}</label>
|
||||
<template v-if="!model.drafts[plugin.manifest.id].defaultIce">
|
||||
<div v-for="(server, index) in model.drafts[plugin.manifest.id].iceServers" :key="index" class="plugin-config-grid">
|
||||
<label>{{ tr('iceUrls') }}<input v-model="server.urls" type="text" placeholder="turn:turn.example.com:3478" /></label>
|
||||
<label>{{ tr('iceUsername') }}<input v-model="server.username" type="text" autocomplete="off" /></label>
|
||||
<label>{{ tr('iceCredential') }}<input v-model="server.credential" type="password" autocomplete="new-password" /></label>
|
||||
<button type="button" class="plugin-button" @click="model.drafts[plugin.manifest.id].iceServers.splice(index, 1)">{{ tr('remove') }}</button>
|
||||
</div>
|
||||
<button type="button" class="plugin-button" @click="model.drafts[plugin.manifest.id].iceServers.push({urls:'',username:'',credential:''})">{{ tr('addIce') }}</button>
|
||||
</template>
|
||||
</div>
|
||||
<div v-else-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace'" class="plugin-config-group" role="group" :aria-label="tr('privateConfig')">
|
||||
<PluginConfigValue secret :labels="valueLabels" :model-value="model.configValue(plugin.manifest.id, 'serverConfig')" @update:model-value="model.setConfigValue(plugin.manifest.id, 'serverConfig', $event)" />
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
</details>
|
||||
<div class="plugin-settings-actions"><button v-if="plugin.manifest.server" class="plugin-button" type="button" :disabled="!plugin.settings.enabled" @click="model.restart(plugin)">{{ tr('restart') }}</button><button class="plugin-button danger" type="button" @click="remove(plugin)"><Icon name="trash" :size="14" />{{ tr('remove') }}</button><button class="plugin-button primary" type="button" @click="save(plugin)"><Icon name="check" :size="15" />{{ tr('save') }}</button></div>
|
||||
</fieldset></details>
|
||||
</article>
|
||||
@@ -44,18 +132,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import Icon from '../Icon.vue';
|
||||
import PluginConfigValue from './PluginConfigValue.vue';
|
||||
import type { SiteLanguage } from '../../../../src/site-copy.js';
|
||||
import { PLUGIN_STORE_REPOSITORY, type InstalledPlugin, type PluginStoreEntry, type PluginManifest } from '../../../../src/shared/plugins.js';
|
||||
import type { useAdminPlugins } from '../../composables/useAdminPlugins.js';
|
||||
import { fileTransferId, watchTogetherId, musicBotId, musicBotPrivateFields, musicBotPublicFields, musicBotRepository, type useAdminPlugins } from '../../composables/useAdminPlugins.js';
|
||||
import { pluginTranslations, type PluginTextKey } from '../../i18n/plugins.js';
|
||||
import { pluginStoreTranslations, type PluginStoreTextKey } from '../../i18n/plugin-store.js';
|
||||
const props=defineProps<{model:ReturnType<typeof useAdminPlugins>;language:SiteLanguage}>();
|
||||
const tr=(key:PluginTextKey)=>pluginTranslations[props.language][key],text=(key:PluginStoreTextKey)=>pluginStoreTranslations[props.language][key];
|
||||
const valueLabels=computed(()=>({type:tr('valueType'),key:tr('fieldKey'),value:tr('fieldValue'),add:tr('addField'),remove:tr('remove')}));
|
||||
function describeError(code:string) {
|
||||
if(code==='TSMB_API_KEY_REQUIRED')return tr('musicBotConfigHelp');
|
||||
if(code==='PLUGIN_FILE_LIMIT_INVALID')return tr('maxFileSize');
|
||||
if(code==='PLUGIN_ICE_URL_INVALID')return tr('iceInvalid');
|
||||
if(code==='PLUGIN_CHECKSUM')return tr('storeChecksum');
|
||||
if(code==='PLUGIN_PACKAGE_MISMATCH')return tr('storeMismatch');
|
||||
return `${tr('error')} (${code})`;
|
||||
}
|
||||
const tab=ref<'store'|'installed'>('store'),search=ref(''),expanded=ref(''),notice=ref(''),fileInput=ref<HTMLInputElement|null>(null);
|
||||
const enabledCount=computed(()=>props.model.installed.value.filter(p=>p.settings.enabled).length);
|
||||
const matches=(manifest:PluginManifest|null,id:string)=>[manifest?.name,manifest?.author,manifest?.description,id].join(' ').toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase());
|
||||
const catalogEntries=computed(()=>(props.model.catalog.value?.entries??[]).filter(e=>matches(e.manifest,e.id)));
|
||||
const installedEntries=computed(()=>props.model.installed.value.filter(p=>matches(p.manifest,p.manifest.id)));
|
||||
function repository(id:string){
|
||||
if(id===musicBotId)return musicBotRepository;
|
||||
return props.model.catalog.value?.entries.find(entry=>entry.id===id)?.repository;
|
||||
}
|
||||
function installLabel(entry:PluginStoreEntry){const local=props.model.installed.value.find(p=>p.manifest.id===entry.id);return !local?text('add'):local.manifest.version===entry.manifest?.version?text('reinstall'):text('update');}
|
||||
async function install(entry:PluginStoreEntry){notice.value='';await props.model.install(entry);if(!props.model.error.value){tab.value='installed';expanded.value=entry.id;notice.value=text('installedNotice');}}
|
||||
async function upload(event:Event){const input=event.target as HTMLInputElement,file=input.files?.[0];if(file){notice.value='';await props.model.upload(file);if(!props.model.error.value){tab.value='installed';notice.value=text('installedNotice');}}input.value='';}
|
||||
@@ -64,6 +166,13 @@ function remove(plugin:InstalledPlugin){if(window.confirm(tr('removed'))){notice
|
||||
function onToggle(event:Event,id:string){if((event.target as HTMLDetailsElement).open)expanded.value=id;else if(expanded.value===id)expanded.value='';}
|
||||
</script>
|
||||
<style scoped>
|
||||
.plugin-admin .plugin-config-help{margin:0 0 12px;color:var(--admin-muted);font-size:12px;line-height:1.6}
|
||||
.plugin-setup-link,.plugin-installed-meta a{color:var(--admin-accent);display:inline-flex;align-items:center;gap:5px}
|
||||
.plugin-setup-link{margin-bottom:12px;font-size:12px}
|
||||
.plugin-config-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));column-gap:16px}
|
||||
.plugin-config-grid input,.plugin-config-group input{box-sizing:border-box;width:100%;min-width:0;padding:10px 12px;border:1px solid var(--admin-border);border-radius:8px;background:var(--admin-field);color:var(--admin-text);font-size:12px}
|
||||
.plugin-config-field,.plugin-config-group{font-size:12px;color:var(--admin-muted);min-width:0}
|
||||
.plugin-config-field [role=group],.plugin-config-group{display:grid;gap:8px;margin-bottom:12px}
|
||||
section.page-content.plugin-admin{display:grid;grid-template-columns:minmax(0,1fr);grid-auto-rows:max-content;align-content:start;gap:24px;color:var(--admin-text);min-width:0}
|
||||
.plugin-admin :is(h2,h3,h4,p){margin:0}.plugin-admin :is(button,input,select,textarea){font:inherit}.plugin-admin button{cursor:pointer}.plugin-admin button:disabled{opacity:.5;cursor:wait}
|
||||
.plugin-hero{position:relative;display:flex;align-items:center;justify-content:space-between;gap:28px;overflow:hidden;padding:32px;border:1px solid var(--admin-border);border-radius:20px;background:radial-gradient(ellipse at 100% 0,color-mix(in srgb,var(--admin-accent) 12%,transparent),transparent 65%),var(--admin-surface)}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<template>
|
||||
<div class="config-value">
|
||||
<select v-if="!fixed" :aria-label="labels.type" :value="kind" @change="changeType">
|
||||
<option v-for="type in types" :key="type">{{ type }}</option>
|
||||
</select>
|
||||
<template v-if="objectRows">
|
||||
<div v-for="[key, value] in objectRows" :key="key" class="config-row">
|
||||
<span class="config-key">{{ key }}</span>
|
||||
<PluginConfigValue :model-value="value" :labels="labels" :secret="secret" :fixed="stringChildren" @update:model-value="setKey(key, $event)" />
|
||||
<button type="button" :aria-label="`${labels.remove} ${key}`" @click="removeKey(key)">×</button>
|
||||
</div>
|
||||
<div class="config-add">
|
||||
<input v-model="newKey" :aria-label="labels.key" :placeholder="labels.key" autocomplete="off" @keydown.enter.prevent="addKey" />
|
||||
<button type="button" :disabled="!canAddKey" @click="addKey">{{ labels.add }}</button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="Array.isArray(modelValue)">
|
||||
<div v-for="(value, index) in modelValue" :key="index" class="config-row">
|
||||
<span class="config-key">{{ index + 1 }}</span>
|
||||
<PluginConfigValue :model-value="value" :labels="labels" :secret="secret" :fixed="stringChildren" @update:model-value="setItem(index, $event)" />
|
||||
<button type="button" :aria-label="`${labels.remove} ${index + 1}`" @click="removeItem(index)">×</button>
|
||||
</div>
|
||||
<button type="button" @click="emit('update:modelValue', [...modelValue, ''])">{{ labels.add }}</button>
|
||||
</template>
|
||||
<select v-else-if="typeof modelValue === 'boolean'" :aria-label="labels.value" :value="String(modelValue)" @change="emit('update:modelValue', inputValue($event) === 'true')">
|
||||
<option value="true">true</option>
|
||||
<option value="false">false</option>
|
||||
</select>
|
||||
<input v-else-if="typeof modelValue === 'number'" :aria-label="labels.value" type="number" step="any" :value="modelValue" @input="setNumber" />
|
||||
<input v-else-if="typeof modelValue === 'string'" :aria-label="labels.value" :type="secret ? 'password' : 'text'" :value="modelValue" :autocomplete="secret ? 'new-password' : 'off'" spellcheck="false" @input="emit('update:modelValue', inputValue($event))" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import type { JsonValue } from '../../../../src/shared/plugins.js';
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: JsonValue;
|
||||
labels: { type: string; key: string; value: string; add: string; remove: string };
|
||||
secret?: boolean;
|
||||
fixed?: boolean;
|
||||
stringChildren?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: JsonValue] }>();
|
||||
const defaults: Record<string, JsonValue> = { text: '', number: 0, boolean: false, list: [], object: {}, null: null };
|
||||
const types = Object.keys(defaults);
|
||||
const kind = computed(() => {
|
||||
const value = props.modelValue;
|
||||
if (value === null) return 'null';
|
||||
if (Array.isArray(value)) return 'list';
|
||||
return typeof value === 'string' ? 'text' : typeof value;
|
||||
});
|
||||
const objectValue = computed(() => kind.value === 'object' ? props.modelValue as Record<string, JsonValue> : null);
|
||||
const objectRows = computed(() => objectValue.value && Object.entries(objectValue.value));
|
||||
const newKey = ref('');
|
||||
const canAddKey = computed(() => Boolean(newKey.value.trim()) && !Object.hasOwn(objectValue.value ?? {}, newKey.value.trim()));
|
||||
|
||||
function inputValue(event: Event): string {
|
||||
return (event.target as HTMLInputElement | HTMLSelectElement).value;
|
||||
}
|
||||
function changeType(event: Event) {
|
||||
const type = inputValue(event);
|
||||
if (Object.hasOwn(defaults, type)) emit('update:modelValue', defaults[type]);
|
||||
}
|
||||
function setNumber(event: Event) {
|
||||
const value = (event.target as HTMLInputElement).valueAsNumber;
|
||||
if (Number.isFinite(value)) emit('update:modelValue', value);
|
||||
}
|
||||
function setKey(key: string, value: JsonValue) {
|
||||
emit('update:modelValue', {...objectValue.value, [key]:value});
|
||||
}
|
||||
function addKey() {
|
||||
if (!canAddKey.value) return;
|
||||
setKey(newKey.value.trim(), '');
|
||||
newKey.value = '';
|
||||
}
|
||||
function removeKey(key: string) {
|
||||
const next = {...objectValue.value};
|
||||
delete next[key];
|
||||
emit('update:modelValue', next);
|
||||
}
|
||||
function setItem(index: number, value: JsonValue) {
|
||||
if (!Array.isArray(props.modelValue)) return;
|
||||
emit('update:modelValue', props.modelValue.map((item, i) => i === index ? value : item));
|
||||
}
|
||||
function removeItem(index: number) {
|
||||
if (!Array.isArray(props.modelValue)) return;
|
||||
emit('update:modelValue', props.modelValue.filter((_, i) => i !== index));
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.config-value{min-width:0;display:grid;gap:8px;align-content:start}
|
||||
.config-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr) auto;align-items:start;gap:8px}
|
||||
.config-key{padding-top:9px;overflow-wrap:anywhere}
|
||||
.config-add{display:flex;gap:8px}
|
||||
.config-value :is(input,select,button){box-sizing:border-box;min-width:0;padding:7px 9px;border:1px solid var(--admin-border);border-radius:8px;background:var(--admin-field);color:var(--admin-text)}
|
||||
.config-add input{flex:1}
|
||||
.config-value>button,.config-value>select{justify-self:start}
|
||||
@media(max-width:600px){.config-row{grid-template-columns:minmax(0,1fr) auto}.config-key{grid-column:1/-1;padding-top:0}}
|
||||
</style>
|
||||
@@ -47,15 +47,16 @@
|
||||
:value="inputVolume * 100"
|
||||
:style="rangeStyle(inputVolume, 1)"
|
||||
:aria-label="t('inputVolume')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onInputVolume"
|
||||
/>
|
||||
<div class="dock-panel-divider"></div>
|
||||
<label class="dock-switch-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong></span>
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -131,12 +132,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
const props = defineProps<{
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive" | "backgroundCallActive">;
|
||||
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
|
||||
t: (key: string) => string;
|
||||
rangeStyle: (value: number, max: number) => Record<string, string>;
|
||||
}>();
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive } = props.model;
|
||||
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
|
||||
const emit = defineEmits<{ settings: []; outputMute: [] }>();
|
||||
</script>
|
||||
@@ -25,6 +25,15 @@
|
||||
:size="19" /></button></header
|
||||
><div class="settings-content">
|
||||
<div class="settings-audio-card">
|
||||
<section class="settings-section">
|
||||
<label class="settings-form-row background-call-setting">
|
||||
<span><strong>{{ t("backgroundCallTitle") }}</strong><small>{{ t("backgroundCallHint") }}</small></span>
|
||||
<input type="checkbox" :checked="backgroundCallEnabled" @change="onBackgroundCallChange" />
|
||||
</label>
|
||||
<p v-if="backgroundCallActive" class="settings-hint background-call-note">{{ t("backgroundCallProcessingHint") }}</p>
|
||||
<p v-if="backgroundCallActive && backgroundCallInterrupted" class="settings-error background-call-note">{{ t("backgroundCallInterrupted") }}</p>
|
||||
<p v-else-if="!backgroundCallActive && backgroundCallEnabled" class="settings-hint background-call-note">{{ t("backgroundCallPending") }}</p>
|
||||
</section>
|
||||
<section class="settings-section"
|
||||
><h3
|
||||
><Icon
|
||||
@@ -78,10 +87,10 @@
|
||||
></div
|
||||
><label class="settings-form-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label
|
||||
><div class="settings-form-row settings-range-form-row"
|
||||
@@ -97,6 +106,7 @@
|
||||
:value="inputVolume * 100"
|
||||
:style="rangeStyle(inputVolume, 1)"
|
||||
:aria-label="t('inputVolume')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onInputVolume"
|
||||
/></div
|
||||
></div
|
||||
@@ -113,12 +123,13 @@
|
||||
:value="voxThreshold * 1000"
|
||||
:style="rangeStyle(voxThreshold, 0.08)"
|
||||
:aria-label="t('voxThreshold')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onVoxThreshold"
|
||||
/></div
|
||||
></div
|
||||
><div class="audio-level-row"
|
||||
><span>{{ t("micLevel") }}</span
|
||||
><strong>{{ Math.round(micLevel * 100) }}%</strong></div
|
||||
><strong>{{ backgroundCallActive ? t('backgroundCallNative') : `${Math.round(micLevel * 100)}%` }}</strong></div
|
||||
><div class="audio-level-track"
|
||||
><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div
|
||||
><div class="mic-test"
|
||||
@@ -214,7 +225,9 @@
|
||||
><div class="audio-diagnostic"
|
||||
><span>{{ t("audioStatus") }}</span
|
||||
><strong>{{
|
||||
audioContextState === "running"
|
||||
backgroundCallActive && backgroundCallInterrupted
|
||||
? t("audioSuspended")
|
||||
: backgroundCallActive || audioContextState === "running"
|
||||
? microphoneError
|
||||
? t("audioUnavailable")
|
||||
: t("audioReady")
|
||||
@@ -255,6 +268,10 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
|
||||
| "backgroundCallEnabled"
|
||||
| "backgroundCallActive"
|
||||
| "backgroundCallInterrupted"
|
||||
| "setBackgroundCallEnabled"
|
||||
| "inputDevices"
|
||||
| "outputDevices"
|
||||
| "selectedInputDeviceId"
|
||||
@@ -300,6 +317,10 @@ const { onDialogKeydown } = useDialogFocus(dialog, () => emit("close"));
|
||||
|
||||
// The page owns the stable voice refs and audio controller; this dialog only presents them.
|
||||
const {
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
inputDevices,
|
||||
outputDevices,
|
||||
selectedInputDeviceId,
|
||||
@@ -332,6 +353,10 @@ const {
|
||||
toggleMicrophone,
|
||||
} = props.controls;
|
||||
|
||||
function onBackgroundCallChange(event: Event): void {
|
||||
setBackgroundCallEnabled((event.target as HTMLInputElement).checked);
|
||||
}
|
||||
|
||||
const inputDeviceOptions = computed(() => [
|
||||
{ value: "", label: props.t("defaultMicrophone") },
|
||||
...inputDevices.map((device, index) => ({
|
||||
@@ -347,3 +372,12 @@ const outputDeviceOptions = computed(() => [
|
||||
})),
|
||||
]);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.background-call-setting { display: flex; align-items: flex-start; gap: 16px; }
|
||||
.background-call-setting span { flex: 1; min-width: 0; }
|
||||
.background-call-setting strong, .background-call-setting small { display: block; }
|
||||
.background-call-setting small { margin-top: 6px; font-size: 12px; line-height: 1.65; color: var(--text-muted); }
|
||||
.background-call-setting input { flex: none; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); }
|
||||
.background-call-note { font-size: 12px; line-height: 1.65; }
|
||||
</style>
|
||||
@@ -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
|
||||
@@ -101,7 +102,7 @@
|
||||
:options="skinOptions"
|
||||
@change="emit('skinChange', $event)"
|
||||
/>
|
||||
<LanguageSwitcher
|
||||
<LanguageSwitcher skin-icon
|
||||
v-model="language"
|
||||
class="join-language-switcher"
|
||||
:menu-label="t('languageMenu')"
|
||||
|
||||
@@ -27,6 +27,7 @@ const eventLabels: Record<string, AdminTranslationKey> = {
|
||||
ADMIN_SKIN_INSTALLED: "skinInstalledEvent", ADMIN_SKIN_REMOVED: "skinRemovedEvent",
|
||||
ADMIN_SKIN_ENABLED: "skinEnabledEvent", ADMIN_SKIN_DISABLED: "skinDisabledEvent",
|
||||
INVITE_CREATED: "inviteCreatedEvent", INVITE_REVOKED: "inviteRevokedEvent", INVITE_CONSUMED: "inviteConsumedEvent",
|
||||
ADMIN_UPDATE_STARTED: "updateStartedEvent",
|
||||
TS_ADMIN_SETTINGS_UPDATED: "tsAdminSaved",
|
||||
TS_ADMIN_OVERVIEW_READ: "tsAdminReadEvent",
|
||||
TS_ADMIN_OVERVIEW_FAILED: "tsAdminReadFailedEvent",
|
||||
@@ -51,6 +52,18 @@ const errorLabels: Record<string, AdminTranslationKey> = {
|
||||
TS_ADMIN_CLIENT_CHANGED: "tsAdminClientChanged", TS_ADMIN_CONFIG_CHANGED: "tsAdminConfigChanged", TS_ADMIN_PARTIAL_SUCCESS: "tsAdminPartialError",
|
||||
TS_ADMIN_RATE_LIMITED: "tsAdminRateError", TS_ADMIN_TLS_FAILED: "tsAdminTlsError",
|
||||
TS_ADMIN_READ_FAILED: "tsAdminReadError", TS_ADMIN_TIMEOUT: "tsAdminTimeoutError",
|
||||
UPDATE_IN_PROGRESS: "updateErrorInProgress", UPDATE_CHECKSUM_MISSING: "updateErrorChecksum",
|
||||
UPDATE_CHECKSUM_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_UNSUPPORTED: "updateErrorChecksum",
|
||||
UPDATE_ARCHIVE_UNSAFE: "updateErrorArchive", UPDATE_ARCHIVE_INVALID: "updateErrorArchive", UPDATE_ARCHIVE_LIMIT: "updateErrorArchive", UPDATE_ARCHIVE_UNSUPPORTED: "updateErrorArchive",
|
||||
UPDATE_PACKAGE_INVALID: "updateErrorPackage", UPDATE_DOWNLOAD_FAILED: "updateErrorDownload", UPDATE_DOWNLOAD_TOO_LARGE: "updateErrorDownload",
|
||||
UPDATE_FAILED: "updateErrorApply", UPDATE_ROLLBACK_FAILED: "updateErrorRollbackFailed", UPDATE_INTERRUPTED: "updateErrorInterrupted",
|
||||
UPDATE_SWAP_FAILED: "updateErrorSwap", UPDATE_LOCK_FAILED: "updateErrorLockFailed",
|
||||
UPDATE_UNAVAILABLE: "updateErrorUnavailable", UPDATE_RESTART_UNAVAILABLE: "updateErrorUnavailable",
|
||||
UPDATE_HEALTH_CHECK_FAILED: "updateErrorApply", UPDATE_ROLLBACK_HEALTH_FAILED: "updateErrorGeneric",
|
||||
UPDATE_RESTART_FAILED: "updateErrorGeneric", UPDATE_RESTART_TIMEOUT: "updateErrorGeneric", UPDATE_PLAN_INVALID: "updateErrorGeneric",
|
||||
UPDATE_NOT_SUPPORTED: "updateErrorGeneric", UPDATE_RELEASE_UNAVAILABLE: "updateErrorGeneric", UPDATE_ASSET_UNAVAILABLE: "updateErrorGeneric",
|
||||
UPDATE_CONFIRMATION_REQUIRED: "updateErrorGeneric", UPDATE_VERSION_INVALID: "updateErrorGeneric", UPDATE_VERSION_NOT_NEWER: "updateErrorGeneric",
|
||||
UPDATE_VERSION_NOT_FOUND: "updateErrorGeneric", UPDATE_RUNNER_MISSING: "updateErrorGeneric", UPDATE_RUNNER_FAILED: "updateErrorGeneric",
|
||||
};
|
||||
const connectionErrors: Record<string, AdminTranslationKey> = {
|
||||
PASSWORD_REQUIRED: "serverPasswordRequiredError", SERVER_PASSWORD_REQUIRED: "serverPasswordRequiredError",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { onScopeDispose, reactive, ref, type Ref } from "vue";
|
||||
import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord, AdminUpdateRelease, AdminUpdateStatus } from "../../../src/shared/admin-responses.js";
|
||||
import type { copy } from "../i18n/admin.js";
|
||||
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
@@ -12,19 +12,31 @@ interface Options {
|
||||
refreshOverview(): Promise<void>;
|
||||
}
|
||||
|
||||
function emptyUpdateStatus(): AdminUpdateStatus {
|
||||
return {
|
||||
currentVersion: "",
|
||||
deployment: { mode: "source", platform: "", architecture: "", applyAllowed: false, reasonCode: "UPDATE_UNAVAILABLE", upgradePath: "source" },
|
||||
task: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function useAdminOperations(options: Options) {
|
||||
const requests = createAdminRequests();
|
||||
const operationsLoading = ref(false), terminatingSession = ref(""), inviteSubmitting = ref(false);
|
||||
const updateChecking = ref(false), updateApplying = ref(false), updateChecked = ref(false);
|
||||
const availableUpdates = ref<AdminUpdateRelease[]>([]), selectedVersion = ref("");
|
||||
const revokingInvites = reactive(new Set<string>());
|
||||
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
|
||||
const createdInvite = ref<{ token: string; link: string } | null>(null);
|
||||
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[],
|
||||
diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 },
|
||||
update: emptyUpdateStatus(),
|
||||
logs: { available: false, entries: [] as AdminLog[], sessions: [] as AdminConnectionRecord[] }, audit: [] as Array<{ event: string; createdAt: string }> });
|
||||
let noticeTimer: number | undefined;
|
||||
function cancelRequests() {
|
||||
requests.reset();
|
||||
operationsLoading.value = false; terminatingSession.value = ""; inviteSubmitting.value = false;
|
||||
updateChecking.value = false; updateApplying.value = false;
|
||||
revokingInvites.clear();
|
||||
if (noticeTimer !== undefined) window.clearTimeout(noticeTimer);
|
||||
noticeTimer = undefined;
|
||||
@@ -35,6 +47,8 @@ export function useAdminOperations(options: Options) {
|
||||
operations.sessions = []; operations.invites = []; operations.audit = [];
|
||||
operations.logs = { available: false, entries: [], sessions: [] };
|
||||
operations.diagnostics = { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 };
|
||||
operations.update = emptyUpdateStatus();
|
||||
availableUpdates.value = []; selectedVersion.value = ""; updateChecked.value = false;
|
||||
Object.assign(inviteForm, { channel: "", expiresInHours: 24, maxUses: 0 });
|
||||
}
|
||||
onScopeDispose(reset);
|
||||
@@ -45,13 +59,15 @@ export function useAdminOperations(options: Options) {
|
||||
const request = requests.begin("load");
|
||||
operationsLoading.value = true;
|
||||
try {
|
||||
const [sessions, invites, diagnostics, logs, audit] = await Promise.all([
|
||||
options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
|
||||
const [sessions, invites, diagnostics, update, logs, audit] = await Promise.all([
|
||||
options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal),
|
||||
options.api.updateStatus(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
|
||||
]);
|
||||
if (!request.isCurrent()) return;
|
||||
operations.sessions = sessions.sessions;
|
||||
operations.invites = invites.invites;
|
||||
operations.diagnostics = { ...diagnostics.gateway, schemaVersion: diagnostics.database.schemaVersion, createdSessions: diagnostics.sessions.created };
|
||||
operations.update = update;
|
||||
operations.logs = logs;
|
||||
operations.audit = audit.events;
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
@@ -103,6 +119,31 @@ export function useAdminOperations(options: Options) {
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { request.finish(); }
|
||||
}
|
||||
async function checkForUpdates() {
|
||||
if (updateChecking.value) return;
|
||||
const request = requests.begin("update-check");
|
||||
updateChecking.value = true; updateChecked.value = false; availableUpdates.value = []; options.errorMessage.value = "";
|
||||
try {
|
||||
const result = await options.api.checkUpdates(request.signal);
|
||||
if (!request.isCurrent()) return;
|
||||
availableUpdates.value = result.releases;
|
||||
selectedVersion.value = result.releases.find(release => release.canApply)?.version ?? "";
|
||||
updateChecked.value = true;
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { if (request.isCurrent()) updateChecking.value = false; request.finish(); }
|
||||
}
|
||||
async function applyUpdate(release: AdminUpdateRelease) {
|
||||
if (updateApplying.value) return;
|
||||
if (!window.confirm(options.tr("updateConfirmApply", { version: release.version }))) return;
|
||||
const request = requests.begin("update-apply");
|
||||
updateApplying.value = true; options.errorMessage.value = "";
|
||||
try {
|
||||
const result = await options.api.applyUpdate({ version: release.version, confirmVersion: release.version }, request.signal);
|
||||
if (!request.isCurrent()) return;
|
||||
operations.update = { ...operations.update, task: result.task, deployment: { ...operations.update.deployment, applyAllowed: false } };
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { if (request.isCurrent()) updateApplying.value = false; request.finish(); }
|
||||
}
|
||||
async function downloadBackup() {
|
||||
const request = requests.begin("backup");
|
||||
try {
|
||||
@@ -118,5 +159,7 @@ export function useAdminOperations(options: Options) {
|
||||
finally { request.finish(); }
|
||||
}
|
||||
return { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
|
||||
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, cancelRequests, reset };
|
||||
updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion,
|
||||
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, checkForUpdates, applyUpdate,
|
||||
cancelRequests, reset };
|
||||
}
|
||||
@@ -1,23 +1,112 @@
|
||||
import { reactive, ref, shallowRef } from 'vue';
|
||||
import { createAdminRequests } from '../services/admin-requests.js';
|
||||
import { isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js';
|
||||
import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js';
|
||||
import { AdminApiError, isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js';
|
||||
import { parsePluginPackage, pluginRecord, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type JsonValue, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js';
|
||||
|
||||
export const musicBotId = 'community.webspeak-tsmb';
|
||||
export const musicBotRepository = 'https://github.com/Funvvell/webspeak-plugin-tsmb';
|
||||
|
||||
interface ConfigField {
|
||||
key: string;
|
||||
type: 'url' | 'password' | 'text' | 'number' | 'json' | 'select' | 'boolean';
|
||||
placeholder?: string;
|
||||
choices?: readonly string[];
|
||||
}
|
||||
|
||||
export const musicBotPrivateFields: readonly ConfigField[] = [
|
||||
{key:'baseUrl',type:'url',placeholder:'http://127.0.0.1:3000'},
|
||||
{key:'apiKey',type:'password',placeholder:'tsmb_…'},
|
||||
{key:'requestTimeoutMs',type:'number',placeholder:'8000'},
|
||||
{key:'connectTimeoutMs',type:'number',placeholder:'4000'},
|
||||
{key:'maxResponseBytes',type:'number',placeholder:'1048576'},
|
||||
{key:'maxCoverBytes',type:'number',placeholder:'2097152'},
|
||||
{key:'coverAllowedHosts',type:'json',placeholder:'[]'},
|
||||
];
|
||||
|
||||
export const musicBotPublicFields: readonly ConfigField[] = [
|
||||
{key:'botId',type:'text'},
|
||||
{key:'botIdByScope',type:'json',placeholder:'{}'},
|
||||
{key:'webUiUrl',type:'url'},
|
||||
{key:'controlPolicy',type:'select',choices:['everyone','host','readonly'],placeholder:'everyone'},
|
||||
{key:'pollIntervalMs',type:'number',placeholder:'2000'},
|
||||
{key:'progressIntervalMs',type:'number',placeholder:'500'},
|
||||
{key:'searchLimit',type:'number',placeholder:'20'},
|
||||
{key:'searchMaxLimit',type:'number',placeholder:'50'},
|
||||
{key:'searchOffsetMax',type:'number',placeholder:'500'},
|
||||
{key:'maxQueueDisplay',type:'number',placeholder:'50'},
|
||||
{key:'lyricsEnabled',type:'boolean',choices:['true','false'],placeholder:'true'},
|
||||
{key:'coverProxyEnabled',type:'boolean',choices:['true','false'],placeholder:'true'},
|
||||
{key:'heartbeatMs',type:'number',placeholder:'10000'},
|
||||
{key:'idleRoomTTLms',type:'number',placeholder:'1800000'},
|
||||
{key:'locale',type:'text',placeholder:'auto'},
|
||||
];
|
||||
|
||||
export const fileTransferId = 'community.p2p-file-transfer';
|
||||
export const watchTogetherId = 'community.watch-together';
|
||||
|
||||
const exampleFields: Readonly<Record<string, readonly ConfigField[]>> = {
|
||||
[fileTransferId]: [{key:'maxFileMiB',type:'number',placeholder:'256'}],
|
||||
[watchTogetherId]: [{key:'control',type:'select',choices:['everyone','host'],placeholder:'everyone'}],
|
||||
};
|
||||
|
||||
function makeConfigDraft(fields: readonly ConfigField[], config?: JsonValue): Record<string, string> {
|
||||
return Object.fromEntries(fields.map(({key,type}) => {
|
||||
const value = pluginRecord(config) ? config[key] : undefined;
|
||||
return [key, value === undefined ? '' : type === 'json' ? JSON.stringify(value) : String(value)];
|
||||
}));
|
||||
}
|
||||
|
||||
function readConfigFields(fields: readonly ConfigField[], draft: Record<string, string>, existing?: JsonValue): Record<string, JsonValue> {
|
||||
const config = pluginRecord(existing) ? {...existing} as Record<string, JsonValue> : {};
|
||||
for (const {key,type} of fields) {
|
||||
const input = String(draft[key] ?? '').trim();
|
||||
if (!input) { delete config[key]; continue; }
|
||||
if (type === 'number' || type === 'json' || type === 'boolean') {
|
||||
try {
|
||||
const value: JsonValue = JSON.parse(input);
|
||||
if (type === 'number' && !Number.isSafeInteger(value)) throw new Error();
|
||||
if (key === 'coverAllowedHosts' && (!Array.isArray(value) || !value.every(host => typeof host === 'string'))) throw new Error();
|
||||
if (key === 'botIdByScope' && (!pluginRecord(value) || !Object.values(value).every(id => typeof id === 'string'))) throw new Error();
|
||||
config[key] = value;
|
||||
} catch { throw new Error(`Invalid value: ${key}`); }
|
||||
} else {
|
||||
config[key] = input;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
export function useAdminPlugins(api: AdminApi) {
|
||||
const installed=shallowRef<InstalledPlugin[]>([]),catalog=shallowRef<PluginCatalog|null>(null),runtime=shallowRef<PluginRuntimeSettings|null>(null);
|
||||
const origin=ref(''),busy=ref(false),error=ref(''),catalogError=ref(''),requests=createAdminRequests();
|
||||
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;toolbarPinned:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string}>>({});
|
||||
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;toolbarPinned:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string;publicFields:Record<string,string>;privateFields:Record<string,string>;iceServers:{urls:string;username:string;credential:string}[];defaultIce:boolean}>>({});
|
||||
function apply(records:InstalledPlugin[]){
|
||||
installed.value=records;
|
||||
for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,toolbarPinned:record.settings.toolbarPinned,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''};
|
||||
for(const record of records)if(!drafts[record.manifest.id]){
|
||||
const musicBot = record.manifest.id === musicBotId;
|
||||
drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,toolbarPinned:record.settings.toolbarPinned,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:'',publicFields:makeConfigDraft(musicBot?musicBotPublicFields:exampleFields[record.manifest.id]??[],record.settings.config),privateFields:musicBot?makeConfigDraft(musicBotPrivateFields):{},iceServers:[],defaultIce:true};
|
||||
}
|
||||
for(const id of Object.keys(drafts))if(!records.some(r=>r.manifest.id===id))delete drafts[id];
|
||||
}
|
||||
async function work(run:(signal:AbortSignal,current:()=>boolean)=>Promise<void>){
|
||||
if(busy.value)return;const request=requests.begin('plugins');busy.value=true;error.value='';
|
||||
const timer=setTimeout(()=>{if(request.isCurrent()){error.value='PLUGIN_TIMEOUT';requests.cancel('plugins');busy.value=false;}},90_000);
|
||||
try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof Error?e.message:'PLUGIN_FAILED';}
|
||||
try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof AdminApiError?e.code:e instanceof Error?e.message:'PLUGIN_FAILED';}
|
||||
finally{clearTimeout(timer);if(request.isCurrent())busy.value=false;request.finish();}
|
||||
}
|
||||
function configValue(id: string, key: 'config' | 'serverConfig'): JsonValue {
|
||||
return JSON.parse(drafts[id][key] || '{}') as JsonValue;
|
||||
}
|
||||
function setConfigValue(id: string, key: 'config' | 'serverConfig', value: JsonValue) {
|
||||
drafts[id][key] = JSON.stringify(value);
|
||||
}
|
||||
function musicBotCollection(id: string, section: 'publicFields' | 'privateFields', key: string): JsonValue {
|
||||
const value = drafts[id][section][key];
|
||||
return value ? JSON.parse(value) as JsonValue : key === 'coverAllowedHosts' ? [] : {};
|
||||
}
|
||||
function setMusicBotCollection(id: string, section: 'publicFields' | 'privateFields', key: string, value: JsonValue) {
|
||||
drafts[id][section][key] = JSON.stringify(value);
|
||||
}
|
||||
function load(){return work(async(signal,current)=>{
|
||||
const records=await api.plugins(signal);if(current())apply(records.plugins);
|
||||
const settings=await api.pluginRuntime(signal);if(current()){runtime.value=settings.runtime;origin.value=settings.runtime.publicOrigin;}
|
||||
@@ -29,7 +118,23 @@ export function useAdminPlugins(api: AdminApi) {
|
||||
});}
|
||||
function save(record:InstalledPlugin){return work(async(signal,current)=>{
|
||||
const draft=drafts[record.manifest.id],captured=JSON.stringify(draft);
|
||||
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,toolbarPinned:draft.toolbarPinned,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})};
|
||||
const musicBot=record.manifest.id===musicBotId;
|
||||
const fields=musicBot?musicBotPublicFields:exampleFields[record.manifest.id];
|
||||
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,toolbarPinned:draft.toolbarPinned,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:fields?readConfigFields(fields,draft.publicFields,record.settings.config):JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction};
|
||||
if(record.manifest.id===fileTransferId && pluginRecord(settings.config) && typeof settings.config.maxFileMiB==='number'
|
||||
&& (settings.config.maxFileMiB<1 || settings.config.maxFileMiB>2048)) throw new Error('PLUGIN_FILE_LIMIT_INVALID');
|
||||
if(draft.serverConfigAction==='replace'){
|
||||
if(record.manifest.id===fileTransferId){
|
||||
settings.serverConfig=draft.defaultIce?{}:{iceServers:draft.iceServers.map(({urls,username,credential})=>({
|
||||
urls:urls.split(/\s+/).filter(Boolean),...(username.trim()?{username:username.trim()}:{}),...(credential?{credential}:{}),
|
||||
}))};
|
||||
if(!draft.defaultIce && draft.iceServers.some(server=>!server.urls.trim() || server.urls.trim().split(/\s+/).some(url=>!/^(stun|stuns|turn|turns):\S+$/i.test(url)))) throw new Error('PLUGIN_ICE_URL_INVALID');
|
||||
}else{
|
||||
settings.serverConfig=musicBot?readConfigFields(musicBotPrivateFields,draft.privateFields):JSON.parse(draft.serverConfig || '{}');
|
||||
}
|
||||
if(musicBot && pluginRecord(settings.serverConfig) && (typeof settings.serverConfig.apiKey !== 'string' || !/^tsmb_[A-Za-z0-9_-]{20,}$/.test(settings.serverConfig.apiKey))) throw new Error('TSMB_API_KEY_REQUIRED');
|
||||
}
|
||||
if(musicBot && draft.enabled && (draft.serverConfigAction==='remove' || (draft.serverConfigAction==='keep' && !record.settings.hasServerConfig))) throw new Error('TSMB_API_KEY_REQUIRED');
|
||||
const result=await api.configurePlugin(record.manifest.id,record.revision,settings,signal);
|
||||
if(current()){if(JSON.stringify(drafts[record.manifest.id])===captured)delete drafts[record.manifest.id];apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));}
|
||||
});}
|
||||
@@ -41,7 +146,7 @@ export function useAdminPlugins(api: AdminApi) {
|
||||
const result=await api.uploadPlugin(pack,installed.value.find(p=>p.manifest.id===pack.manifest.id)?.revision??null,signal);
|
||||
if(current()){delete drafts[pack.manifest.id];apply([...installed.value.filter(p=>p.manifest.id!==pack.manifest.id),result.plugin]);}
|
||||
});}
|
||||
function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';}}
|
||||
function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';draft.iceServers=[];draft.defaultIce=true;for(const key of Object.keys(draft.privateFields))draft.privateFields[key]='';}}
|
||||
function reset(){cancelRequests();installed.value=[];catalog.value=null;runtime.value=null;origin.value='';error.value='';catalogError.value='';for(const id of Object.keys(drafts))delete drafts[id];}
|
||||
return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset};
|
||||
return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset,configValue,setConfigValue,musicBotCollection,setMusicBotCollection};
|
||||
}
|
||||
@@ -35,6 +35,8 @@ export function useAdminSkins(options: Options) {
|
||||
const code = error instanceof AdminApiError ? error.code : "";
|
||||
if (["SKIN_STORE_CHANGED", "SKIN_STORE_INSTALLED_CHANGED", "SKIN_STORE_NOT_NEWER"].includes(code)) return options.tr("skinStoreChanged");
|
||||
if (code === "SKIN_STORE_INCOMPATIBLE") return options.tr("skinStoreIncompatible");
|
||||
if (code === "SKIN_STORE_CHECKSUM") return options.tr("skinStoreChecksum");
|
||||
if (code === "SKIN_STORE_PACKAGE_MISMATCH") return options.tr("skinStoreMismatch");
|
||||
if (code.startsWith("SKIN_") && code !== "SKIN_STORE_UNAVAILABLE" && code !== "SKIN_STORAGE_UNAVAILABLE") return options.tr("skinStoreInvalid");
|
||||
return options.tr("skinStoreUnavailable");
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
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();
|
||||
@@ -134,6 +143,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))),
|
||||
|
||||
@@ -5,6 +5,8 @@ export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.j
|
||||
import { createAudioSinkRouter } from "../voice/audio-sink.js";
|
||||
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
|
||||
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
import { createNativeMicrophoneCapture } from "../voice/native-microphone.js";
|
||||
import { createCallMediaSession } from "../services/call-media-session.js";
|
||||
import { createVoiceConnection } from "../voice/connection.js";
|
||||
import { createVoiceCommands } from "../voice/commands.js";
|
||||
import { createVoiceSessionState } from "../voice/session-state.js";
|
||||
@@ -21,7 +23,7 @@ import type { ChatMessage } from "../../../src/shared/voice-models.js";
|
||||
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
|
||||
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
|
||||
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
|
||||
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
|
||||
import { computed, onScopeDispose, reactive, ref, shallowRef, watch } from "vue";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
|
||||
export interface VoiceState {
|
||||
@@ -257,6 +259,11 @@ export function useVoiceWebSocket() {
|
||||
let micStream: MediaStream | null = null;
|
||||
const microphoneCaptureFactory = createMicrophoneCaptureFactory();
|
||||
let microphoneCapture: MicrophoneCapture | null = null;
|
||||
let microphoneNative = false;
|
||||
const backgroundCallEnabled = ref(false);
|
||||
const backgroundCallActive = ref(false);
|
||||
const backgroundCallInterrupted = ref(false);
|
||||
let backgroundCallTouched = false;
|
||||
let pendingMicrophoneCapture: AbortController | null = null;
|
||||
const accompanimentActive = ref(false);
|
||||
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
|
||||
@@ -345,7 +352,7 @@ export function useVoiceWebSocket() {
|
||||
stunServer: () => webRtcStunServer,
|
||||
prepareMicrophone: async () => {
|
||||
await ensureMicrophone();
|
||||
return micStream ? { context: getAudioCtx(), stream: micStream,
|
||||
return micStream ? { context: microphoneNative ? null : getAudioCtx(), stream: micStream,
|
||||
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
|
||||
},
|
||||
stopPcm: stopCaptureGraph,
|
||||
@@ -366,6 +373,7 @@ export function useVoiceWebSocket() {
|
||||
async onFallback(reason, isCurrent) {
|
||||
if (!isCurrent()) return;
|
||||
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
|
||||
backgroundCallActive.value = false;
|
||||
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
|
||||
try { await startMicrophone(); }
|
||||
catch (error) { if (isCurrent()) setMicrophoneError(error); }
|
||||
@@ -387,6 +395,38 @@ export function useVoiceWebSocket() {
|
||||
onPlaying: syncAudioContextNotice,
|
||||
},
|
||||
});
|
||||
const callMediaSession = createCallMediaSession({
|
||||
resume() {
|
||||
// A media Play command resumes listening only. Unmuting needs an explicit
|
||||
// microphone action, never a page visibility or system playback event.
|
||||
outputMuted.value = false;
|
||||
applyOutputVolume();
|
||||
webrtc.resumePlayback();
|
||||
},
|
||||
pause() {
|
||||
setMicrophoneMuted(true);
|
||||
outputMuted.value = true;
|
||||
applyOutputVolume();
|
||||
},
|
||||
toggleMicrophone: () => setMicrophoneMuted(!microphoneMuted.value),
|
||||
hangup: () => disconnect(),
|
||||
});
|
||||
function syncCallMediaSession(): void {
|
||||
callMediaSession.sync({ active: state.connected && backgroundCallActive.value,
|
||||
muted: microphoneMuted.value, outputMuted: outputMuted.value, title: serverInfo.value?.name || "WebSpeak" });
|
||||
}
|
||||
watch([() => state.connected, backgroundCallActive, microphoneMuted, outputMuted, serverInfo], syncCallMediaSession);
|
||||
const resumeVisibleCall = () => {
|
||||
if (!state.connected || !backgroundCallActive.value || document.visibilityState !== "visible") return;
|
||||
webrtc.resumePlayback();
|
||||
};
|
||||
document.addEventListener("visibilitychange", resumeVisibleCall);
|
||||
window.addEventListener("pageshow", resumeVisibleCall);
|
||||
onScopeDispose(() => {
|
||||
callMediaSession.dispose();
|
||||
document.removeEventListener("visibilitychange", resumeVisibleCall);
|
||||
window.removeEventListener("pageshow", resumeVisibleCall);
|
||||
});
|
||||
const audioDiagnostics = createAudioDiagnostics({
|
||||
source() {
|
||||
const socket = ws.value;
|
||||
@@ -398,7 +438,7 @@ export function useVoiceWebSocket() {
|
||||
presentation({ peer }) {
|
||||
return {
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live" && !track.muted)),
|
||||
microphonePermission: audioPermission.value,
|
||||
playbackState: peer
|
||||
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
|
||||
@@ -414,6 +454,7 @@ export function useVoiceWebSocket() {
|
||||
preferredInputDeviceId: committedInputDeviceId,
|
||||
inputDeviceId: committedInputDeviceId,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
backgroundCallEnabled: backgroundCallEnabled.value,
|
||||
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
|
||||
noiseSuppressionLevel: committedNoiseSuppressionLevel,
|
||||
voxThreshold: voxThreshold.value,
|
||||
@@ -433,6 +474,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
|
||||
if (!backgroundCallTouched) backgroundCallEnabled.value = preferences.backgroundCallEnabled === true;
|
||||
if (!inputDeviceTouched) {
|
||||
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
@@ -549,7 +591,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
|
||||
function syncAudioContextNotice(): void {
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
if (!microphoneNative && audioCtx && audioCtx.state === "suspended") {
|
||||
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
|
||||
} else {
|
||||
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
|
||||
@@ -702,9 +744,10 @@ export function useVoiceWebSocket() {
|
||||
pendingMicrophoneCapture?.abort();
|
||||
const controller = new AbortController();
|
||||
pendingMicrophoneCapture = controller;
|
||||
const ctx = getAudioCtx();
|
||||
const native = backgroundCallActive.value;
|
||||
const ctx = native ? null : getAudioCtx();
|
||||
const assertCurrent = (): void => {
|
||||
if (generation !== microphoneGeneration || audioCtx !== ctx || controller.signal.aborted) throw new CancelledMediaOperation();
|
||||
if (generation !== microphoneGeneration || (ctx && audioCtx !== ctx) || controller.signal.aborted) throw new CancelledMediaOperation();
|
||||
};
|
||||
let nextStream: MediaStream | null = null;
|
||||
let nextCapture: MicrophoneCapture | null = null;
|
||||
@@ -712,24 +755,35 @@ export function useVoiceWebSocket() {
|
||||
try {
|
||||
nextStream = await requestMediaBeforeAudioResume(
|
||||
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }),
|
||||
() => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
() => ctx?.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
);
|
||||
assertCurrent();
|
||||
audioPermission.value = "granted";
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
if (native) {
|
||||
nextCapture = createNativeMicrophoneCapture(nextStream);
|
||||
factoryOwnsStream = true;
|
||||
} else {
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx!, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
}
|
||||
assertCurrent();
|
||||
// Commit only a complete graph. Permission and node failures leave the
|
||||
// previous stream, PCM route and WebRTC peer untouched.
|
||||
stopMicrophone(false);
|
||||
micStream = nextStream;
|
||||
microphoneCapture = nextCapture;
|
||||
microphoneNative = native;
|
||||
backgroundCallInterrupted.value = false;
|
||||
sessionTrace.record("microphone.route", { native });
|
||||
const microphoneTrack = nextStream.getAudioTracks()[0];
|
||||
if (microphoneTrack) {
|
||||
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
|
||||
const recordTrack = (stateName: string) => {
|
||||
sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
|
||||
if (micStream === nextStream && native) backgroundCallInterrupted.value = microphoneTrack.muted || microphoneTrack.readyState !== "live";
|
||||
};
|
||||
recordTrack(microphoneTrack.readyState);
|
||||
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
|
||||
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
|
||||
@@ -759,8 +813,8 @@ export function useVoiceWebSocket() {
|
||||
|
||||
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
|
||||
async function ensureMicrophone(): Promise<void> {
|
||||
if (microphoneStartPromise) return microphoneStartPromise;
|
||||
if (micStream) return;
|
||||
if (microphoneStartPromise) await microphoneStartPromise;
|
||||
if (micStream && microphoneNative === backgroundCallActive.value) return;
|
||||
if (!microphoneStartPromise) {
|
||||
const generation = microphoneGeneration + 1;
|
||||
const pending = startMicrophone().then(async () => {
|
||||
@@ -793,6 +847,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function startAccompaniment(): Promise<void> {
|
||||
if (backgroundCallActive.value) {
|
||||
accompanimentErrorCode.value = "backgroundMode";
|
||||
throw new DOMException("Accompaniment is unavailable in native call mode", "NotSupportedError");
|
||||
}
|
||||
await accompaniment.start();
|
||||
}
|
||||
|
||||
@@ -827,6 +885,8 @@ export function useVoiceWebSocket() {
|
||||
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
|
||||
microphoneCapture?.dispose();
|
||||
microphoneCapture = null;
|
||||
microphoneNative = false;
|
||||
backgroundCallInterrupted.value = false;
|
||||
webrtc.releaseInput();
|
||||
micStream = null;
|
||||
if (closeContext) {
|
||||
@@ -1067,6 +1127,8 @@ export function useVoiceWebSocket() {
|
||||
commands.clear(new Error("语音连接已关闭"));
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
webrtc.stop();
|
||||
backgroundCallActive.value = false;
|
||||
callMediaSession.dispose();
|
||||
remotePlayback.clearAll();
|
||||
stopMicrophone();
|
||||
clearSpeakingState();
|
||||
@@ -1106,6 +1168,9 @@ export function useVoiceWebSocket() {
|
||||
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
|
||||
screenShare.setIceServers(msg.screenShareIceServers);
|
||||
webRtcStunServer = msg.webRtcStunServer ?? "";
|
||||
backgroundCallActive.value = backgroundCallEnabled.value && msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined";
|
||||
sessionTrace.record("call.background", { requested: backgroundCallEnabled.value, native: backgroundCallActive.value });
|
||||
syncCallMediaSession();
|
||||
sessionState.connected(msg);
|
||||
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
|
||||
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
|
||||
@@ -1441,6 +1506,12 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
function setBackgroundCallEnabled(enabled: boolean): void {
|
||||
backgroundCallTouched = true;
|
||||
backgroundCallEnabled.value = enabled;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
|
||||
if (noiseSuppressionLevel.value === level) return;
|
||||
noiseSuppressionTouched = true;
|
||||
@@ -1479,7 +1550,7 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => sessionTrace.dispose());
|
||||
onScopeDispose(() => { disconnect(); sessionTrace.dispose(); });
|
||||
|
||||
return {
|
||||
pluginSession,
|
||||
@@ -1495,6 +1566,10 @@ export function useVoiceWebSocket() {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
noiseSuppressionEnabled,
|
||||
noiseSuppressionLevel,
|
||||
inputVolume,
|
||||
|
||||
@@ -166,7 +166,9 @@ export function useWebClientAudioControls({
|
||||
await startAccompaniment();
|
||||
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
|
||||
} catch {
|
||||
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
|
||||
const messageKey = accompanimentErrorCode.value === "backgroundMode"
|
||||
? "backgroundCallProcessingHint"
|
||||
: accompanimentErrorCode.value === "needsWebRtc"
|
||||
? "accompanimentNeedsWebRtc"
|
||||
: accompanimentErrorCode.value === "noAudio"
|
||||
? "accompanimentNoAudio"
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
setInstanceHiddenParts(Array.isArray(config.hiddenHostParts)
|
||||
? 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;
|
||||
|
||||