Compare commits

...
15 Commits
Author SHA1 Message Date
illusia a84f66b47d release: prepare v0.3.2 2026-11-14 23:49:15 +08:00
ILLUSIA af1d1f8a88 Merge pull request #58 from EchoSixHIYA/dev
Merge WebSpeak 0.3.2 updates into master
2026-11-14 23:43:43 +08:00
illusia 2cb8b8d161 Match KAAK plugin launcher icon sizing to rail controls 2026-11-14 23:33:01 +08:00
illusia 12a37fc26f Place KAAK application launcher in the server rail 2026-11-14 23:26:06 +08:00
illusia f20a372f4b docs: update WebSpeak development skills for 0.3.2 2026-11-14 21:48:25 +08:00
illusia 15ca32b7a8 Dock plugin launchers in skins and expose example app settings 2026-11-14 21:35:22 +08:00
illusia 274bd81dc3 Fix workshop installs and make plugin configuration editable 2026-11-14 19:53:26 +08:00
illusia 6a35d9be3d Merge PR #57: integrate host chrome theming and skin recovery 2026-11-14 18:59:15 +08:00
illusia ed752a5a6f docs: show skins in a live TeamSpeak room [skip ci] 2026-11-13 20:31:59 +08:00
illusia 9012448544 release: prepare v0.3.1 2026-11-13 19:52:40 +08:00
illusia a5cf3eeb0c docs: publish November 13 demo notes and skin screenshots 2026-11-13 19:49:31 +08:00
illusia e82116239a fix: improve voice playback, diagnostics and workspace controls 2026-11-13 19:49:31 +08:00
OddTurtleHead f8d61d22ef feat: add host chrome theming and a skin-proof recovery layer
Allow skins to theme host chrome through a second scope and explicit
visibleParts. Official and built-in skins stay decoration-free by
default.

Harden the CSS compiler so skins cannot hide the document root, push
protected controls off-screen, or target the host layer with sibling
selectors. Move recovery and authorization UI into a closed Shadow DOM
on the top layer, so a third-party skin cannot block the built-in
skin reset.
2026-11-11 18:06:20 +08:00
illusia 72d7e6e013 feat: add private expiring workspace invites and restore KAAK home 2026-11-04 17:42:34 +08:00
illusia 33ba062686 docs: automate ecosystem catalog pull requests [skip ci] 2026-11-03 20:42:24 +08:00
139 changed files with 5068 additions and 409 deletions

No files matched your search

@@ -1,6 +1,6 @@
---
name: webspeak-plugin-development
description: Build, review and package WebSpeak API v2 functional applications with standard browser code and optional Node services, including GitHub distribution. Use for .wplugin applications rather than .wskin skins or their presentation components.
description: Build, review and package WebSpeak API v2 applications with standard browser code and optional Node services, and automatically submit completed releases to the official catalog by pull request. Use for .wplugin applications rather than .wskin skins.
---
# WebSpeak Application Development
@@ -19,11 +19,33 @@ Provide responsive light/dark styles and suitable language handling using contex
Verify import, trust, enable, update, failure/restart, custom routes, persistence and revocation. Collaborative apps need two real browser participants and late-join/concurrent-change/channel-boundary/disconnect tests. Distinguish mocked HTTP, actual processes, browser interactions and independent networks. Claim only demonstrated capabilities. Keep credentials and diagnostics out of artifacts.
For distribution use schema v2 catalog entries, matching manifest, raw-package SHA-256 and fixed refs. Publishing and deployment follow the user's task authorization; this skill does not itself authorize either.
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.
## Floating host workspace
## Administrator configuration
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.
- 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 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.
Use the catalog's PR template, or `Summary`, `Package`, `Validation` and `Preview` sections when none exists. Include purpose and ID/version; source, author/license, required WebSpeak/API version and scopes; a published UI preview; immutable package commit/path/raw URL and SHA-256; backend presence/dependencies and external configuration; and validation commands with actual results. Cover import/trust/enable/update, persistence, minimize/resume, disconnect/revocation and relevant two-participant tests. Distinguish real independent-network P2P/collaboration testing from same-host browser tests. Confirm that no credentials or temporary runtime URLs are included.
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.
## Host launcher and application window
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.
@@ -1,6 +1,6 @@
---
name: webspeak-skin-development
description: Develop, review, package, or validate portable WebSpeak .wskin skins. Keep skin UI and implementation inside the package and use only released runtime APIs.
description: Develop, review, package, or validate portable WebSpeak .wskin skins, and automatically submit completed releases to the official catalog by pull request. Keep implementation inside the package and use released runtime APIs.
metadata:
short-description: Develop portable WebSpeak skins
---
@@ -11,6 +11,8 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
## Workflow
When a WebSpeak checkout is unavailable, read the [published skin guide](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/SKIN_DEVELOPMENT.md) and its examples.
1. Locate the `webspeak-webclient` repository root, then read the single current contract and workflow in `docs/SKIN_DEVELOPMENT.md`. It covers package schemas, runtime data, permissions, actions, security boundaries, and validation. If a request needs an undocumented capability, identify the missing public contract before editing and treat that work as a separate platform change. Inspect the closest example under `docs/examples/`; do not copy unrelated product-specific content.
2. Choose the least complex supported package format that can express the request: CSS/assets for appearance, `content.json` for localized copy, `layout.json` for author defaults, `components.json` for declarative structure and supported interactions, and the documented v4 Wasm plugin path only when local logic is required. JavaScript files in a package are not executed by the current runtime.
3. Keep all skin-authored implementation in the package. Use stable public skin parts, component schema, published context fields, existing host widgets, and permission-gated actions. Do not add a widget, data field, action, CSS hook, or branch to core code for one skin. If a reusable platform capability is missing, identify the exact contract gap and treat it as separate platform work: define a generic, versioned API and compatibility behavior first; only then use that released API from the package.
@@ -18,6 +20,27 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
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. 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.
Use the catalog's PR template, or `Summary`, `Package`, `Validation` and `Preview` sections when none exists. Include purpose and skin ID/version; source, author/license and minimum WebSpeak version; a published screenshot/preview; immutable package commit/path/raw URL and SHA-256; validation commands and actual results, including runtime/browser, desktop/narrow layouts and languages checked. Confirm independent installation and no duplicate ID. State material gaps without claiming unperformed tests.
Return the actual PR URL and validation outcome, and attach the PR to the chat when supported. If authentication or repository policy blocks submission, preserve the reviewable branch/diff, identify the concrete blocker and request only the missing destination or access. Do not claim a PR was submitted when it exists only locally, and do not auto-merge.
## Compatibility and truthfulness
- `minAppVersion` is a lower compatibility bound, not a guarantee that an older or unrelated runtime implements every API. Read the current schema and runtime documentation before using a capability.
@@ -29,6 +52,7 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
- `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
+1 -1
View File
@@ -9,7 +9,7 @@ on:
version:
description: Release version without the v prefix
required: true
default: 0.3.0
default: 0.3.2
type: string
permissions:
+30 -5
View File
@@ -19,7 +19,7 @@
</p>
</div>
当前版本 / Current version: **[v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0)** · [更新内容 / 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)
## 关于 WebSpeak · Overview
@@ -51,7 +51,18 @@ Join voice channels, chat and share your screen from a browser. Deploy your own
<summary>更多界面与语言 · More screenshots & languages</summary>
- [简体中文](./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)
- 日间、夜间、ILLUSIA、KAAK 与社区皮肤 / Day, Night, ILLUSIA, KAAK and community skins
以下皮肤截图拍摄于已连接的 TeamSpeak 语音房间。 / The skin screenshots below were captured in a connected TeamSpeak voice room.
| 日间 · Day | 夜间 · Night |
| --- | --- |
| ![日间皮肤 · Day skin](./docs/screenshots/skin-day.png) | ![夜间皮肤 · Night skin](./docs/screenshots/skin-night.png) |
| ILLUSIA | KAAK |
| --- | --- |
| ![ILLUSIA 皮肤 · ILLUSIA skin](./docs/screenshots/skin-illusia.png) | ![KAAK 皮肤 · KAAK skin](./docs/screenshots/skin-kaak.png) |
![Discord Voice 社区皮肤 · Discord Voice community skin](./docs/screenshots/skin-discord.png)
</details>
@@ -95,9 +106,20 @@ 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.0 中,提供独立于皮肤的悬浮应用入口。
皮肤包负责界面、布局及其附属小组件;功能插件使用标准浏览器环境和可选 Node 后端,自行实现业务功能。功能插件 API v2 已包含在 v0.3.1 中,从语音工作区的应用库启动,支持工具栏和皮肤侧栏入口。
Skins own appearance, layout and attached widgets. Functional plugin API v2 is included in v0.3.0 with a skin-independent floating 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
| 扩展 · Extension | 开发 Skill · Development skill | 收录 PR · Catalog PR |
| --- | --- | --- |
| 皮肤及附属小组件 · Skins & attached widgets | [Skin Development Skill](./.agents/skills/webspeak-skin-development/SKILL.md) | [webspeak-skins](https://github.com/Huddle-Up-Forge/webspeak-skins) |
| 独立功能应用 · Functional applications | [Plugin Development Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) | [webspeak-plugin](https://github.com/Huddle-Up-Forge/webspeak-plugin) |
使用对应 Skill 开发时,Agent 会在完成构建与验证后,发布独立仓库中的源码、包及校验元数据,并自动向相应分发仓库提交规范的收录 PR。PR 包含用途、版本与兼容性、许可证、界面预览、不可变包地址、SHA-256 和实际验证结果;完成后返回 PR 链接,交由维护者审查。已收录包的纯版本更新遵循目录的元数据更新规则,不重复添加索引或制造空 PR。
The skills complete the contribution workflow automatically: publish validated source, packages and integrity metadata in an independent repository, then submit a focused catalog PR with compatibility, license, preview, immutable package reference, SHA-256 and test evidence. They return the PR for maintainer review. Version-only updates follow the catalog's metadata policy instead of duplicating entries or creating empty PRs.
## 社区 · Community
@@ -122,11 +144,14 @@ Skins own appearance, layout and attached widgets. Functional plugin API v2 is i
<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
+5 -3
View File
@@ -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 与会话,传输、播放等任务不会因收起窗口而重置。关闭窗口、切换至另一个应用或语音会话撤销时,宿主结束当前应用会话。当前同时承载一个前端应用;不要把窗口最小化当成退出事件。
+17 -1
View File
@@ -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.0](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Mit Plugin-API v2, schwebenden Anwendungen und gemeinsamer Instanzberechtigung.
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,22 @@ 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.
- Die Rauschunterdrückung bietet jetzt Aus, Standard und Stark. Stark kombiniert die Browserfunktion mit RNNoise. Siehe #53.
- Das Sprachstatusfenster exportiert die letzten zwei Minuten der Gateway-, Sprach- und Mikrofondiagnose. Die Aufnahme im Hintergrund hängt vom Browser und Betriebssystem ab. Siehe #49 und #55.
- Der Plugin-Einstieg befindet sich in der Werkzeugleiste des Sprachbereichs. Administratoren können Plugin-Kurzbefehle anheften. Siehe #56.
- Private Arbeitsbereichseinladungen können ablaufen. Die KAAK-Willkommensseite wurde wiederhergestellt, das überdeckte Skin-Menü in der Demo und zu kurze Wartezeiten bei großen Downloads wurden korrigiert. Die README zeigt fünf Skins.
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### Plugin-Anwendungen
+17 -1
View File
@@ -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.0 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Includes plugin API v2, floating applications and unified instance authorization.
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.
@@ -341,6 +341,22 @@ 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.
- Added Off, Standard and Strong noise suppression. Strong combines browser suppression with RNNoise. See #53.
- The voice performance panel can export two minutes of gateway, voice and microphone diagnostics for disconnects and interrupted background capture. Background capture still depends on browser and OS policies. See #49 and #55.
- Moved the plugin launcher into the voice workspace toolbar. Administrators can pin plugin shortcuts. See #56.
- Added expiring private workspace invites and restored the KAAK welcome page. Fixed an obscured skin menu in the demo and premature timeouts on large skin downloads. The README now shows five skins.
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### Plugin applications
+17 -1
View File
@@ -13,7 +13,7 @@
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
安定版:[v0.3.0 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。API v2、フローティングアプリ、インスタンス単位の許可に対応。
安定版:[v0.3.2 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · スキンの復元、アプリライブラリの配置、プラグイン設定フォーム。
@@ -276,6 +276,22 @@ 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。
- ノイズ抑制にオフ・標準・強の3段階を追加しました。強ではブラウザーのノイズ抑制と RNNoise を併用します。関連 #53。
- 音声パネルから直近2分間のゲートウェイ、音声、マイクの診断をエクスポートできます。バックグラウンドでの録音はブラウザーと OS の制約を受けます。関連 #49、#55。
- プラグインの入口を音声ワークスペースのツールバーに移動し、管理者がショートカットを固定できるようにしました。関連 #56。
- 有効期限付きの非公開招待を追加し、KAAK のウェルカム画面を復元しました。デモのスキンメニューが隠れる問題と、大きなスキンのダウンロードが早くタイムアウトする問題を修正しました。README に5種類のスキン画像を追加しました。
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### プラグインアプリ
+17 -1
View File
@@ -13,7 +13,7 @@
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
Стабильный выпуск: [изменения v0.3.0](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). API v2, плавающие приложения и единое разрешение для экземпляра.
Стабильный выпуск: [изменения v0.3.2](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Восстановление темы, библиотека приложений и формы настройки плагинов.
@@ -276,6 +276,22 @@ 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.
- Доступны три уровня шумоподавления: выключено, стандартное и усиленное. Усиленный режим сочетает обработку браузера и RNNoise. См. #53.
- Панель состояния голоса экспортирует последние две минуты диагностики шлюза, голоса и микрофона. Запись в фоне зависит от браузера и ОС. См. #49 и #55.
- Кнопка плагинов перенесена на панель инструментов голосового пространства. Администраторы могут закреплять ярлыки плагинов. См. #56.
- Добавлены личные приглашения с ограниченным сроком действия и восстановлена страница приветствия KAAK. Исправлено перекрытие меню скинов в демо и преждевременное истечение времени загрузки больших скинов. В README добавлены снимки пяти скинов.
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### Приложения-плагины
+36 -1
View File
@@ -13,7 +13,7 @@
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
稳定版:[v0.3.0 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。包含功能插件 API v2、悬浮应用界面和实例统一授权。
稳定版:[v0.3.2 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 皮肤恢复入口、应用库布局和插件配置表单。
@@ -75,6 +75,23 @@ WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语
</details>
<details>
<summary>展开日间、夜间、ILLUSIA、KAAK 与 Discord Voice 皮肤预览</summary>
以下截图拍摄于已连接的 TeamSpeak 语音房间。
| 日间 | 夜间 |
| --- | --- |
| ![日间皮肤](./screenshots/skin-day.png) | ![夜间皮肤](./screenshots/skin-night.png) |
| ILLUSIA | KAAK |
| --- | --- |
| ![ILLUSIA 皮肤](./screenshots/skin-illusia.png) | ![KAAK 皮肤](./screenshots/skin-kaak.png) |
![Discord Voice 社区皮肤](./screenshots/skin-discord.png)
</details>
<a id="deployment"></a>
## 部署与首次配置
@@ -343,8 +360,26 @@ relay.example.com {
## 更新日志
<a id="live-update-2026-11-13"></a>
<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。
- 新增关闭、标准和强三档降噪。强档在浏览器降噪基础上使用 RNNoise。关联 #53。
- 语音性能面板可导出最近两分钟的网关、语音和麦克风诊断,帮助定位掉线和后台采音中断。后台采音仍受浏览器和操作系统限制。关联 #49、#55。
- 将插件入口移至语音工作区顶部工具栏,管理员可固定插件快捷入口。关联 #56。
- 支持有有效期的私密工作区邀请,恢复 KAAK 欢迎页,并修复演示页皮肤菜单被遮挡及首次下载较大皮肤时容易超时的问题。README 补齐五款皮肤截图。
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### 插件系统
+137 -14
View File
@@ -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,11 +221,20 @@ 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` 页面。
可信语音导航控件包括 `voice.channel-tree`、`voice.server-switcher` 和 `voice.server-header`。频道树要求 `session.channels.read`、`session.members.read`、`session.memberAvatars.read` 与 `session.channel.join`;头像只由宿主读取并在频道树中绘制。它可选 `layout: "server-sidebar"` 展示频道成员并让频道行与成员行分别控制折叠;未指定时保留默认呈现。独立服务器切换器要求 `servers.quickList.read` 与 `servers.quickList.switch`。服务器头部还要求 `session.status.read`,并在同一可信部件中组合服务器身份、状态、频道搜索和快速切换。两种入口都只接收不透明本地标识,点击后复用 WebSpeak 当前连接流程。v3 还可用 `session.invite.copy` 授权 `session.copyInviteLink`,让宿主复制当前公开服务器与频道的邀请链接并排除连接凭据。语音状态投影中的 `serverLabel` 会在看起来像 IP、域名或连接目标时省略,避免把地址显示为服务器名称。
可信语音导航控件包括 `voice.channel-tree`、`voice.server-switcher` 和 `voice.server-header`。频道树要求 `session.channels.read`、`session.members.read`、`session.memberAvatars.read` 与 `session.channel.join`;头像只由宿主读取并在频道树中绘制。它可选 `layout: "server-sidebar"` 展示频道成员并让频道行与成员行分别控制折叠;未指定时保留默认呈现。独立服务器切换器要求 `servers.quickList.read` 与 `servers.quickList.switch`。服务器头部还要求 `session.status.read`,并在同一可信部件中组合服务器身份、状态、频道搜索和快速切换。两种入口都只接收不透明本地标识,点击后复用 WebSpeak 当前连接流程。v3 还可用 `session.invite.copy` 授权 `session.copyInviteLink`,让宿主打开当前会话的邀请对话框,生成限时票据链接;皮肤不能读取票据或连接凭据。语音状态投影中的 `serverLabel` 会在看起来像 IP、域名或连接目标时省略,避免把地址显示为服务器名称。
示例包见 [KAAK voice 示例](./examples/KAAK-VOICE.md),其 components.json 使用完整首页与语音工作区 surface,展示收藏服务器、频道树、在线成员、聊天和可信语音控制的组合;[Open Voice Surface](./examples/OPEN-VOICE-SURFACE.md) 保留为通用格式验证脚手架。KAAK 的语音视觉参考来自用户授权进入的前两个语音房间;只记录布局,不保留服务器/房间标识、成员名或聊天内容。组件按本地用户授权后才渲染;权限对每个皮肤版本、页面和组件分别保存,可在宿主权限入口撤销。页面替换时,宿主会额外显示“返回标准界面”和“恢复内置皮肤”入口;拒绝授权或离开 surface 后,普通页面可立即恢复。
@@ -287,7 +299,8 @@ widget 的可选 `mount` 只接受这些公开锚点:`home.header.after`、`ho
宿主动作只允许从公开运行时 API 中选择,并在调用时重新核对权限、参数和当前会话:
- `session.copyInviteLink`(`session.invite.copy`)复制不含连接凭据的当前服务器/频道邀请链接。
- `session.copyInviteLink`(`session.invite.copy`)打开宿主邀请对话框,生成并复制当前服务器/频道的限时票据链接。有效期为 1–43200 分钟;服务器密码及已成功使用的频道密码仅由服务端加密保存和使用,不传给皮肤或受邀浏览器。若本次会话尚未提供所需服务器密码或当前上锁频道密码,由宿主对话框向创建者收集。邀请凭据失效时提示受邀者联系创建者,不要求受邀者补输服务器密码。受邀者只需输入昵称,不能用链接参数覆盖票据绑定的服务器和频道。
邀请对话框公开样式部件:`voice.invite.backdrop`、`voice.invite.dialog`、`voice.invite.form`、`voice.invite.create`、`voice.invite.copy`。这些钩子仅用于外观;输入值与票据不进入皮肤数据投影。
- `voice.joinChannel`(`session.channel.join`)仅请求加入当前公开可见的频道,继续使用宿主的频道密码和权限流程。
- `favorites.switch`(`favorites.switch`)与 `quickServers.switch`(`servers.quickList.switch`)使用不透明令牌选择本机已有目标,并复用宿主连接流程。
- `chat.sendMessage`(`chat.channel.send`)只向当前公开文字频道发送消息,不包括私聊。
@@ -387,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.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`、`app.skin-load-recovery`、`skin.library`;`host.recovery` / `host.permission` 仅为概念标识(闭合 Shadow DOM + 顶层,无 CSS 钩子,见下文) |
| 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) |
`voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
@@ -414,6 +429,100 @@ 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 开放皮肤生效。
- 宿主外壳的布局与层级由 WebSpeak 拥有:皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform` 等把 `host.plugins.overlay` 之类控件变成全屏遮罩。
- 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。
- 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。
- 无 Popover API 或顶层提升被拒绝时,恢复胶囊会退回固定宿主层并使用 32 位最大 `z-index: 2147483647`。宿主层在 `#app` 之后追加到 `document.body`;与树内皮肤层同为最大层级时,后绘制的宿主层仍在上面。顶层(top layer)路径的 `showPopover()` / `showModal()` 仍高于两者。
可主题化的宿主部件:
| 部件 | 内容 |
| --- | --- |
| `host.plugins.launcher` | 语音工作区顶部的插件按钮(颜色、尺寸、圆角、背景图均可改;也可声明式隐藏) |
| `host.plugins.overlay` | 应用库浮层窗口外壳;**不含**权限对话框里的批准/拒绝(`host.permission`) |
| `host.watermark` | 页面大淡 WebSpeak 品牌水印 |
| `host.hint` | 非关键提示文案(「音频控制始终保留…」一类) |
| `host.voice-status-decoration` | 右栏空的 Voice status 装饰条;与必要状态 `voice.connection-status`、`voice.audio-status` 完全分开 |
### 恢复入口与授权对话框:结构上不可被皮肤触及
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或主题化的 CSS 钩子:当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们:
1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `<dialog>` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅使用独立部件 `app.skin-load-recovery`(「切换到内置皮肤」),与恢复胶囊不是同一个钩子。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
示例(v3 `skin.css`):
```css
/* 只命中宿主部件,编译后进入文档级宿主作用域 */
[data-ws-part="host.plugins.launcher"] {
background: #1d4f9c;
color: #fff;
border-radius: 4px;
padding: 8px 12px;
font-size: 12px;
}
[data-ws-part="host.watermark"] { color: #dbe8f7; opacity: .08; }
[data-ws-part="host.hint"] { display: none; }
```
宿主图标槽用 `data-ws-icon-slot` 标记,槽名即部件名,可在 CSS 中直接换背景位图;也可用下面的 `chrome.json` 声明式覆盖。可用槽名:
| 槽名 | 位置 |
| --- | --- |
| `host.plugins.launcher` | 顶部工具栏插件按钮图标 |
| `language.trigger` | 语言下拉触发器图标 |
| `skin.trigger` | 皮肤下拉触发器图标 |
| `home.toolbar.settings` | 首页工具栏设置图标 |
| `voice.performance` | 语音页 Voice status / 性能触发器图标 |
### `chrome.json`:声明式显示 / 隐藏与图标位图覆盖
v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB:
```json
{
"schemaVersion": 1,
"visibleParts": ["host.watermark", "host.hint", "host.voice-status-decoration"],
"hiddenParts": ["home.footer.decoration"],
"icons": {
"language.trigger": "assets/icons/language.png",
"skin.trigger": "assets/icons/skin.png",
"host.plugins.launcher": "assets/icons/apps.png"
}
}
```
| 字段 | 规则 |
| --- | --- |
| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 |
| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 |
| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 |
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
实例级默认值:启动网关时设置环境变量 `WEBSPEAK_HOST_CHROME_HIDDEN_PARTS`(逗号或空格分隔,例如 `host.watermark,host.hint`)。`/api/public-config` 会返回校验后的 `hiddenHostParts`,宿主据此默认折叠这些非关键装饰;未知或受保护的名字会被忽略。宿主的三个装饰部件默认就是隐藏的;皮肤通过 `chrome.json` 的 `visibleParts` 开启,实例默认值与皮肤 `hiddenParts` 取并集并优先于 `visibleParts`。
`home.footer` 是容器,包含必要的「清除本地数据」链接 `home.footer.clear`,因此**不在**可隐藏列表;纯装饰文案被拆分为 `home.footer.decoration`,只隐藏它不会破坏恢复路径。
### 令牌、字体、动效和图片
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
@@ -476,28 +585,42 @@ v1/v2 外观可以因窄屏而更换图片裁切或装饰,但 @media 规则也
v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显示状态,因此皮肤开发者必须保留语音操作路径;授权界面、皮肤选择和恢复入口由宿主在皮肤作用域之外提供。以下选择器是旧格式对可选装饰部件的透明度白名单:
下面这份清单是**唯一**的可隐藏装饰部件白名单,由 `src/shared/skin-visual-parts.ts` 的 `DECORATIVE_PART_IDS` 定义;CSS 校验器(`OPTIONAL_VISUAL_PARTS`)、布局编辑器(`DECORATIVE_PART_IDS`)与 `chrome.json` 的 `hiddenParts` 共用它,三者永远一致:
```css
[data-ws-part="demo.avatar"]
[data-ws-part="demo.badge"]
[data-ws-part="demo.note"]
[data-ws-part="demo.poke-notification"]
[data-ws-part="demo.wave"]
[data-ws-part="demo.member-status"]
[data-ws-part="home.feature"]
[data-ws-part="home.features"]
[data-ws-part="home.footer.decoration"]
[data-ws-part="home.hero.eyebrow"]
[data-ws-part="home.gateway-status"]
[data-ws-part="home.features"]
[data-ws-part="home.feature"]
[data-ws-part="home.join-card.sonar"]
[data-ws-part="home.join-card.waveform"]
[data-ws-part="home.visitors"]
[data-ws-part="voice.activity.artwork"]
[data-ws-part="voice.activity-heading"]
[data-ws-part="voice.member.avatar"]
[data-ws-part="voice.member.avatar-wrap"]
[data-ws-part="voice.member.live-indicator"]
[data-ws-part="voice.member-row.avatar"]
[data-ws-part="voice.performance.metrics"]
[data-ws-part="voice.performance.webrtc-stats"]
[data-ws-part="voice.screen-player.viewer-avatar"]
[data-ws-part="voice.screen-player.live"]
[data-ws-part="demo.badge"]
[data-ws-part="demo.wave"]
[data-ws-part="demo.avatar"]
[data-ws-part="demo.member-status"]
[data-ws-part="demo.note"]
[data-ws-part="host.watermark"]
[data-ws-part="host.hint"]
[data-ws-part="host.voice-status-decoration"]
[data-ws-part="host.plugins.launcher"]
```
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
+1 -1
View File
@@ -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.
+3 -1
View File
@@ -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.127 requires WebSpeak 0.2.8 with workspace API v1. Its manifest opts into the generic persistent workspace policy: first-time visitors keep the connection home until a successful voice connection; returning visitors and disconnected users retain the workspace and server rail. Restoring the workspace never starts a connection or captures the microphone. The host restores the recent target only for ordinary visits, preserving explicit invitation and target links. Clearing browser data resets this history.
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.
Binary file not shown.
@@ -263,6 +263,7 @@
}
]
},
{"widget":"voice.plugin-launcher","part":"plugin-launcher","options":{"pluginPresentation":"drawer-side"}},
{
"tag": "div",
"className": "dc-sidebar-scroll",
+2 -2
View File
@@ -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"
}
+17
View File
@@ -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;
}
Binary file not shown.
@@ -0,0 +1,12 @@
{
"schemaVersion": 1,
"hiddenParts": ["host.plugins.launcher"],
"visibleParts": ["host.watermark", "host.hint", "host.voice-status-decoration"],
"icons": {
"language.trigger": "assets/icons/language.png",
"skin.trigger": "assets/icons/skin.png",
"host.plugins.launcher": "assets/icons/apps.png",
"home.toolbar.settings": "assets/icons/settings.png",
"voice.performance": "assets/icons/status.png"
}
}
@@ -0,0 +1,13 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.host-chrome-demo",
"name": "Host Chrome Demo",
"version": "1.0.0",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "Minimal open skin demonstrating host chrome theming, declarative hiding and bitmap icon overrides.",
"entry": "skin.css",
"chrome": "chrome.json",
"minAppVersion": "0.3.2"
}
+71
View File
@@ -0,0 +1,71 @@
/* Host chrome demo — v3 open skin (schemaVersion 3).
Every selector uses :root, [data-ws-page] or [data-ws-part].
Host-only selectors are compiled into :root[data-ws-host-skin="…"]. */
:root {
--skin-accent: #1d4f9c;
--skin-panel: #ffffff;
--skin-border: #c9c9c9;
--skin-text: #141414;
}
[data-ws-page] {
color-scheme: light;
font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif;
font-size: 12px;
color: #141414;
}
[data-ws-part="home.header"] ,
[data-ws-part="voice.header"] {
background: linear-gradient(180deg, #fbfbfb, #e9e9e9);
border-bottom: 1px solid var(--skin-border);
}
[data-ws-part="voice.audio-dock"] {
border-top: 1px solid var(--skin-border);
background: #f7f9fb;
}
/* --- Host chrome (outside .ws-skin-root) --- */
[data-ws-part="host.plugins.launcher"] {
background: #1d4f9c;
color: #ffffff;
border: 1px solid #163c78;
border-radius: 3px;
padding: 7px 12px;
font-size: 12px;
font-weight: 600;
letter-spacing: .02em;
box-shadow: none;
}
[data-ws-part="host.plugins.launcher"]:hover {
background: #2a63bb;
}
[data-ws-part="host.plugins.overlay"] {
border: 2px solid #1d4f9c;
border-radius: 4px;
}
[data-ws-part="host.watermark"] {
color: #1d4f9c;
opacity: .12;
font-family: Tahoma, sans-serif;
}
[data-ws-part="host.hint"] {
color: #1d4f9c;
border-left: 2px solid #1d4f9c;
padding-left: 6px;
}
[data-ws-part="host.voice-status-decoration"] {
opacity: .45;
}
/* Icon slots can also be addressed directly from CSS. */
[data-ws-part="host.plugins.launcher"] [data-ws-icon-slot="host.plugins.launcher"] {
background-color: transparent;
}
Binary file not shown.
Binary file not shown.
+3 -1
View File
@@ -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 }
}
]
},
+2 -6
View File
@@ -3,16 +3,12 @@
"packageType": "open-skin",
"id": "community.kaak-voice",
"name": "KAAK",
"version": "3.1.127",
"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",
"workspace": {
"apiVersion": 1,
"mode": "persistent"
}
"minAppVersion": "0.3.2"
}
+63 -1
View File
@@ -3896,6 +3896,7 @@
[data-ws-plugin-part="kaak-workspace.server-banner"] [data-ws-part="voice.server-banner.body"] { margin-top: 3px; font-size: 10px; line-height: 14px; }
}
[data-ws-part="voice.invite.backdrop"],
[data-ws-part="auth.password.backdrop"] {
padding: 16px;
background: rgba(10, 11, 13, .54);
@@ -3904,6 +3905,7 @@
[data-ws-part="auth.password.backdrop"][data-ws-state="server-password"] {
background: rgba(29, 40, 34, .3);
}
[data-ws-part="voice.invite.dialog"],
[data-ws-part="auth.password.dialog"] {
position: relative;
display: flex;
@@ -4698,8 +4700,68 @@
[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; }
}
[data-ws-part="voice.invite.create"], [data-ws-part="voice.invite.copy"] {
color: #172008;
background: var(--skin-kaak-accent);
}
[data-ws-part="voice.invite.dialog"] {
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; }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-android-gateway",
"version": "0.3.0",
"version": "0.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-android-gateway",
"version": "0.3.0",
"version": "0.3.2",
"dependencies": {
"@honeybbq/teamspeak": "1.0.0-beta.23",
"express": "^4.21.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-android-gateway",
"version": "0.3.0",
"version": "0.3.2",
"private": true,
"type": "module",
"main": "index.cjs",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-webclient",
"version": "0.3.0",
"version": "0.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.3.0",
"version": "0.3.2",
"license": "AGPL-3.0-only",
"dependencies": {
"@discordjs/opus": "^0.10.0",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-webclient",
"version": "0.3.0",
"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/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/test/host-chrome-recovery.test.mjs",
"verify": "npm test && npm run build && npm run web:build",
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
"skin:host-chrome:build": "node web/scripts/build-host-chrome-demo-skin.mjs",
"skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs",
"skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs",
"start": "node dist/index.js",
+9
View File
@@ -1,3 +1,4 @@
import { WorkspaceInvites, type WorkspaceInviteCredentials } from "../server/workspace-invites.js";
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
@@ -295,6 +296,14 @@ export class AdminService {
};
}
createWorkspaceInvite(credentials: WorkspaceInviteCredentials, expiresInMinutes: number, now = Date.now()) {
return new WorkspaceInvites(this.database, this.masterSecret).create(credentials, expiresInMinutes, now);
}
getWorkspaceInvite(token: string, now = Date.now()) {
return new WorkspaceInvites(this.database, this.masterSecret).get(token, now);
}
createManagedInvite(input: ManagedInviteInput): { invite: ManagedInviteView; token: string } {
const channel = input.channel.trim();
if (channel.length > 100) throw new AdminInputError("INVALID_INVITE_CHANNEL", "Invite channel cannot exceed 100 characters");
+52
View File
@@ -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");
});
+38 -9
View File
@@ -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 {
+2 -2
View File
@@ -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);
}
+7 -1
View File
@@ -109,7 +109,13 @@ async function runRelayMode(): Promise<void> {
import("./server/voice-gateway.js"),
]);
const logger = createLogger(LOG_DIR);
const [{ WebSpeakDatabase }, { loadOrCreateMasterSecret }, { WorkspaceInvites }] = await Promise.all([
import("./persistence/database.js"), import("./security/master-secret.js"), import("./server/workspace-invites.js"),
]);
const inviteDatabase = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db"));
const workspaceInvites = new WorkspaceInvites(inviteDatabase, loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key")));
const voiceGateway = createVoiceGatewayServer({
workspaceInvites,
host: voiceHost,
port: voicePort,
sharedToken: token,
@@ -144,7 +150,7 @@ async function runRelayMode(): Promise<void> {
if (stopping) return;
stopping = true;
relay.close();
void voiceGateway.stop().finally(() => process.exit(0));
void voiceGateway.stop().finally(() => { inviteDatabase.close(); process.exit(0); });
};
process.once("SIGINT", shutdown);
process.once("SIGTERM", shutdown);
+3 -3
View File
@@ -15,7 +15,7 @@ test("relay voice endpoint is stored by the current database migration", (contex
rmSync(directory, { recursive: true, force: true });
});
assert.equal(DATABASE_SCHEMA_VERSION, 12);
assert.equal(DATABASE_SCHEMA_VERSION, 13);
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
assert.equal(database.getTsAdminSettings().transport, "web");
assert.equal(database.getTsAdminSettings().enabled, false);
@@ -38,13 +38,13 @@ test("schema 11 migration preserves encrypted SSH credentials and does not silen
const original = new WebSpeakDatabase(filename);
original.close();
const old = new DatabaseSync(filename);
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; PRAGMA user_version = 11;");
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; DROP TABLE workspace_invites; PRAGMA user_version = 11;");
old.prepare("UPDATE ts_admin_settings SET enabled=1, query_port=10222, username='query-owner', password_encrypted=?, host_key_fingerprint=?").run(encrypted, `SHA256:${"A".repeat(43)}`);
old.close();
const migrated = new WebSpeakDatabase(filename);
t.after(() => { migrated.close(); rmSync(directory, { recursive: true, force: true }); });
const settings = migrated.getTsAdminSettings();
assert.equal(migrated.schemaVersion, 12);
assert.equal(migrated.schemaVersion, 13);
assert.equal(settings.transport, "ssh"); assert.equal(settings.enabled, true);
assert.equal(settings.queryPort, 10222); assert.equal(settings.username, "query-owner");
assert.equal(settings.passwordEncrypted, encrypted);
+24 -1
View File
@@ -6,7 +6,7 @@ import type { AdminCredential } from "../security/admin-password.js";
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
export const DATABASE_SCHEMA_VERSION = 12;
export const DATABASE_SCHEMA_VERSION = 13;
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
@@ -190,6 +190,18 @@ export class WebSpeakDatabase {
this.migrate(existed);
}
saveWorkspaceInvite(tokenHash: string, encrypted: string, expiresAt: number, now = Date.now()): void {
this.database.prepare("DELETE FROM workspace_invites WHERE expires_at <= ?").run(now);
const count = this.database.prepare("SELECT COUNT(*) AS n FROM workspace_invites").get() as { n: number };
if (count.n >= 4096) throw new Error("INVITE_LIMIT_REACHED");
this.database.prepare("INSERT INTO workspace_invites(token_hash, payload_encrypted, expires_at) VALUES (?, ?, ?)").run(tokenHash, encrypted, expiresAt);
}
getWorkspaceInvite(tokenHash: string, now = Date.now()): string | null {
const row = this.database.prepare("SELECT payload_encrypted FROM workspace_invites WHERE token_hash = ? AND expires_at > ?").get(tokenHash, now) as { payload_encrypted: string } | undefined;
return row?.payload_encrypted ?? null;
}
close(): void {
this.database.close();
}
@@ -731,6 +743,17 @@ export class WebSpeakDatabase {
PRAGMA user_version = 12;
`);
});
version = 12;
}
if (version === 12) {
this.transaction(() => {
this.database.exec(`CREATE TABLE workspace_invites (
token_hash TEXT PRIMARY KEY,
payload_encrypted TEXT NOT NULL,
expires_at INTEGER NOT NULL
); CREATE INDEX workspace_invites_expiry ON workspace_invites(expires_at);
PRAGMA user_version = 13;`);
});
}
}
+14 -4
View File
@@ -28,7 +28,17 @@ export class PluginRegistry {
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
this.readSecret(record);record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
this.readSecret(record);
if (pluginRecord(v.settings) && v.settings.toolbarPinned === undefined) {
const legacyHash=createHash("sha256").update(JSON.stringify({manifest,settings:v.settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt})).digest("hex");
pluginAssert(legacyHash===v.revision);
record.revision="";
this.records.set(manifest.id,record);
try { await this.commit(record); }
catch { /* keep the migrated record usable in memory if disk replacement fails */ }
} else {
record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
}
} catch { /* Invalid or obsolete packages are never executed. */ }
}
}
@@ -41,12 +51,12 @@ export class PluginRegistry {
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
}
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&manifest.scopes.includes(value.scope as never));
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&(value.toolbarPinned===undefined||typeof value.toolbarPinned==='boolean')&&manifest.scopes.includes(value.scope as never));
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
return {enabled:value.enabled,trusted:value.trusted,toolbarPinned:value.toolbarPinned===true,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
}
private readSecret(record: StoredPlugin): JsonValue {
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
@@ -66,7 +76,7 @@ export class PluginRegistry {
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
const old=previous?.settings;
const settings={enabled:false,trusted:false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
const settings={enabled:false,trusted:false,toolbarPinned:old?.toolbarPinned??false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
});}
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
+1 -1
View File
@@ -105,7 +105,7 @@ export class PluginRuntime {
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
directory(voiceToken:string) {
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,runtime:this.status(policy.manifest.id)}));
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,toolbarPinned:policy.settings.toolbarPinned,runtime:this.status(policy.manifest.id)}));
}
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
+6 -1
View File
@@ -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);
}
}
+7
View File
@@ -49,3 +49,10 @@ test("expired tickets do not evict a still-valid join when capacity is reclaimed
assert.deepEqual(tickets.consume(live, 100), payload);
assert.deepEqual(tickets.consume(latest, 100), payload);
});
test("invitation expiry also bounds a previously issued one-use join ticket", () => {
const store = new JoinTicketStore();
const token = store.create({ target: { host: "1.1.1.1", port: 9987 }, serverPassword: "secret", nickname: "Guest", inviteExpiresAt: 2000 }, 1000);
assert.equal(store.consume(token,2000),null);
});
+5 -1
View File
@@ -3,9 +3,13 @@ import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export interface JoinTicketPayload {
target: TeamSpeakTarget;
invitationTarget?: TeamSpeakTarget;
serverPassword: string;
nickname: string;
channel?: string;
channelId?: string;
channelPassword?: string;
inviteExpiresAt?: number;
identity?: string;
rememberIdentity?: boolean;
accelerated?: boolean;
@@ -30,7 +34,7 @@ export class JoinTicketStore {
this.tickets.delete(oldest);
}
const token = randomBytes(24).toString("base64url");
this.tickets.set(token, { payload, expiresAt: now + this.ttlMs });
this.tickets.set(token, { payload, expiresAt: Math.min(now + this.ttlMs, payload.inviteExpiresAt ?? Infinity) });
return token;
}
@@ -1,3 +1,5 @@
import { WorkspaceInvites } from "./workspace-invites.js";
import { createVoiceGatewayAuthHeaders } from "./voice-gateway-auth.js";
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { createServer as createPortProbe } from "node:net";
@@ -17,11 +19,14 @@ const logger: Logger = { debug: noop, info: noop, warn: noop, error: noop, child
test("ingress keeps the page origin and delegates the voice ticket to the selected relay", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-relay-delegation-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const relayDatabase = new WebSpeakDatabase(path.join(directory, "relay.db"));
const workspaceInvites = new WorkspaceInvites(relayDatabase, Buffer.alloc(32, 9));
const relayPort = await availablePort();
const ingressPort = await availablePort();
const relayToken = "integration-test-relay-token";
const relayEndpoint = `http://127.0.0.1:${relayPort}`;
const relay = createVoiceGatewayServer({
workspaceInvites,
host: "127.0.0.1",
port: relayPort,
sharedToken: relayToken,
@@ -46,6 +51,7 @@ test("ingress keeps the page origin and delegates the voice ticket to the select
await ingress.stop();
await relay.stop();
database.close();
relayDatabase.close();
await rm(directory, { recursive: true, force: true });
});
@@ -82,6 +88,31 @@ test("ingress keeps the page origin and delegates the voice ticket to the select
assert.ok(result.ticket);
assert.equal(result.voiceEndpoint, relayEndpoint);
assert.equal(localTickets.consume(result.ticket!), null);
const credentials = { target: {host:"203.0.113.20",port:9987}, serverPassword:"relay-server-secret", channelId:"42", channelPassword:"relay-channel-secret" };
const invite = workspaceInvites.create(credentials,60);
const lookup = {token:invite.token,purpose:"workspace-invite"};
const lookupUrl = relayEndpoint+"/api/relay/workspace-invite";
const unsigned = await fetch(lookupUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(lookup)});
assert.equal(unsigned.status,401,"relay credentials must never be public");
const authHeaders = createVoiceGatewayAuthHeaders(relayToken,lookup);
const requestLookup = () => fetch(lookupUrl,{method:"POST",headers:{"content-type":"application/json",...authHeaders},body:JSON.stringify(lookup)});
const authorized = await requestLookup();
assert.equal(authorized.status,200);
assert.equal(authorized.headers.get("cache-control"),"no-store");
assert.deepEqual((await authorized.json() as {access:unknown}).access,{...credentials,expiresAt:invite.expiresAt});
assert.equal((await requestLookup()).status,401,"relay invitation requests cannot be replayed");
const invited = await fetch(origin+"/api/join-ticket", {method:"POST",headers:{origin,"content-type":"application/json"},body:JSON.stringify({nickname:"Invitee",invite:invite.token,target:"127.0.0.1:1",channel:"other"})});
assert.equal(invited.status,201);
const invitedBody = await invited.json() as {ticket:string};
assert.deepEqual(Object.keys(invitedBody).sort(),["ok","ticket"]);
const invitedPayload = localTickets.consume(invitedBody.ticket)!;
assert.deepEqual(invitedPayload.target,credentials.target);
assert.equal(invitedPayload.serverPassword,credentials.serverPassword);
assert.equal(invitedPayload.channelId,credentials.channelId);
assert.equal(invitedPayload.channelPassword,credentials.channelPassword);
assert.equal(invitedPayload.inviteExpiresAt,invite.expiresAt);
assert.equal(invitedPayload.channel,undefined);
});
async function availablePort(): Promise<number> {
+42 -10
View File
@@ -5,7 +5,7 @@ import { readFileSync } from "node:fs";
import path from "node:path";
import { VoiceBridge, createTrustedProxies, resolveClientIp, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
import { resolveTeamSpeakTarget, TeamSpeakAliasLookupError } from "./teamspeak-alias.js";
import { createAdminRouter } from "../admin/admin-router.js";
@@ -15,12 +15,13 @@ import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget, TeamSpeakTargetResol
import { parseIdentity } from "@honeybbq/teamspeak/client";
import { JoinRateLimiter } from "./join-rate-limit.js";
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
import { createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voice-gateway-auth.js";
import { parseDelegatedVoiceSession, createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voice-gateway-auth.js";
import type { SkinRegistry } from "../admin/skin-registry.js";
import { resolveVisitorTotal } from "./visitor-count.js";
import type { PluginRegistry } from "../plugins/registry.js";
import { PluginRuntime } from "../plugins/runtime.js";
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
import { parseHiddenHostParts } from "../shared/skin-chrome.js";
export interface WebServerOptions {
port: number;
@@ -63,7 +64,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
const json = express.json({ limit: "100kb" });
app.use((request, response, next) => request.path.startsWith("/api/admin/plugins") ? next() : json(request, response, next));
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRuntimeEnabled: !!options.pluginRegistry }, logger);
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, createWorkspaceInvite: (credentials, minutes) => options.adminService.createWorkspaceInvite(credentials, minutes), pluginRuntimeEnabled: !!options.pluginRegistry }, logger);
const pluginRuntime = options.pluginRegistry ? new PluginRuntime({ registry: options.pluginRegistry, participant: token => voiceBridge.resolvePluginParticipant(token), logger,
...options.pluginRuntime, ...(options.certDir ? { tls: { cert: readFileSync(path.join(options.certDir,"cert.pem")), key: readFileSync(path.join(options.certDir,"key.pem")) } } : {}) }) : undefined;
app.use("/api/plugins", createPluginRuntimeRouter(pluginRuntime));
@@ -123,6 +124,9 @@ export function createWebServer(options: WebServerOptions): WebServer {
...(visitorTotal === null ? {} : { visitorTotal }),
accelerationAvailable: acceleration.length > 0,
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
// Instance-level default for non-critical host decorations. Unknown or
// protected names are ignored by the shared validator.
hiddenHostParts: parseHiddenHostParts(process.env.WEBSPEAK_HOST_CHROME_HIDDEN_PARTS),
});
});
@@ -195,15 +199,23 @@ export function createWebServer(options: WebServerOptions): WebServer {
}
const policy = options.adminService.getConnectionPolicy();
const managedInvite = inviteToken ? options.adminService.getManagedInvite(inviteToken) : null;
if (inviteToken && !managedInvite) {
const isWorkspaceInvite = /^wi_[A-Za-z0-9_-]{43}$/.test(inviteToken);
let workspaceInvite = isWorkspaceInvite ? options.adminService.getWorkspaceInvite(inviteToken) : null;
if (!workspaceInvite && isWorkspaceInvite) {
const relays = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration).filter(relay => relay.voiceEndpoint);
const accesses = await Promise.all(relays.map(relay => resolveRemoteWorkspaceInvite(relay, inviteToken)));
workspaceInvite = accesses.find(access => access !== null) ?? null;
}
const managedInvite = inviteToken && !isWorkspaceInvite ? options.adminService.getManagedInvite(inviteToken) : null;
if (inviteToken && !managedInvite && !workspaceInvite) {
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
return;
}
let targetText = managedInvite?.target ?? policy.defaultTarget;
let targetText = workspaceInvite ? formatTeamSpeakTarget(workspaceInvite.target) : managedInvite?.target ?? policy.defaultTarget;
let target: TeamSpeakTarget;
let serverPassword = policy.serverPassword;
const channel = requestedChannel || managedInvite?.channel || "";
let invitationTarget: TeamSpeakTarget;
let serverPassword = workspaceInvite?.serverPassword ?? policy.serverPassword;
const channel = workspaceInvite ? "" : requestedChannel || managedInvite?.channel || "";
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
@@ -216,7 +228,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
return;
}
try {
if (!managedInvite) {
if (!managedInvite && !workspaceInvite) {
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
targetText = formatTeamSpeakConnectionTarget(parseTeamSpeakConnectionTarget(body.target));
const isDefault = targetText === policy.defaultTarget;
@@ -230,6 +242,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
}
}
target = await resolveTeamSpeakTarget(targetText);
invitationTarget = { ...target };
// Open-mode defaults are user targets too; validate the resolved address
// and pass that exact IP to the voice connection to prevent DNS rebinding.
if (!managedInvite && policy.accessMode === "open") target = await resolveSafeOpenTarget(target);
@@ -238,7 +251,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
return;
}
if (inviteToken) {
if (managedInvite) {
const consumedInvite = options.adminService.consumeManagedInvite(inviteToken);
if (!consumedInvite) {
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
@@ -249,9 +262,11 @@ export function createWebServer(options: WebServerOptions): WebServer {
const sessionPayload: DelegatedVoiceSession = {
target,
invitationTarget,
serverPassword,
nickname,
...(channel ? { channel } : {}),
...(workspaceInvite ? { channelId: workspaceInvite.channelId, channelPassword: workspaceInvite.channelPassword, inviteExpiresAt: workspaceInvite.expiresAt } : {}),
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
};
const selectedRelay = accelerationRequested
@@ -332,6 +347,23 @@ function resolveAccelerationOptions(
return Array.isArray(value) ? value : [value];
}
async function resolveRemoteWorkspaceInvite(relay: ConfiguredAccelerationRelay, token: string): Promise<import("./workspace-invites.js").WorkspaceInviteAccess | null> {
const body = { token, purpose: "workspace-invite" };
try {
const response = await fetch(new URL("/api/relay/workspace-invite", relay.voiceEndpoint), {
method: "POST", headers: { "content-type": "application/json", ...createVoiceGatewayAuthHeaders(relay.token, body) },
body: JSON.stringify(body), signal: AbortSignal.timeout(4000), cache: "no-store", redirect: "error",
});
if (!response.ok) return null;
const result: unknown = await response.json();
if (!isRecord(result) || result.ok !== true || !isRecord(result.access)) return null;
const value = result.access;
const session = parseDelegatedVoiceSession({ ...value, nickname: "Invite validation", inviteExpiresAt: value.expiresAt });
if (!session?.channelId || session.channelPassword === undefined || typeof value.expiresAt !== "number") return null;
return { target: session.target, serverPassword: session.serverPassword, channelId: session.channelId, channelPassword: session.channelPassword, expiresAt: value.expiresAt };
} catch { return null; }
}
async function createRemoteVoiceTicket(relay: ConfiguredAccelerationRelay, payload: DelegatedVoiceSession): Promise<string> {
const endpoint = new URL("/api/relay/voice-ticket", relay.voiceEndpoint);
const response = await fetch(endpoint, {
+56 -2
View File
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { createServer } from "node:net";
@@ -130,11 +131,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
});
database.close();
const legacy = new DatabaseSync(file);
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; PRAGMA user_version = 8;");
legacy.close();
const migrated = new WebSpeakDatabase(file);
try {
assert.equal(migrated.schemaVersion, 12);
assert.equal(migrated.schemaVersion, 13);
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
assert.equal(migrated.getSettings().tsTarget, null);
const invite = migrated.consumeManagedInvite("legacy-token");
@@ -162,3 +163,56 @@ async function availablePort(): Promise<number> {
await new Promise<void>((resolve, reject) => socket.close((error) => error ? reject(error) : resolve()));
return address.port;
}
test("workspace invite credentials persist encrypted and redeem as opaque channel-bound join tickets", async context => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-workspace-invite-"));
const file = path.join(directory, "webspeak.db"), key = Buffer.alloc(32, 7);
let database = new WebSpeakDatabase(file);
let service = new AdminService(database, key, logger, path.join(directory, "missing.json"));
await service.initialize();
const credentials = { target: { host: "1.1.1.1", port: 9987 }, serverPassword: "private-server-password", channelId: "123", channelPassword: "private-channel-password" };
const now = Date.now();
const created = service.createWorkspaceInvite(credentials, 60, now);
assert.ok(!JSON.stringify(created).includes("private-"));
assert.deepEqual(service.getWorkspaceInvite(created.token, now), { ...credentials, expiresAt: now+3600000 });
assert.equal(service.getWorkspaceInvite(created.token, now+3600000), null);
assert.equal(service.getWorkspaceInvite(created.token.slice(0,-1)+"!", now), null);
for (const expiry of [0, -1, 0.5, 43201, NaN]) assert.throws(() => service.createWorkspaceInvite(credentials, expiry));
const legacyToken = "wi_" + "z".repeat(29);
const legacyAdminInvite = service.createManagedInvite({ channel: "Lobby", expiresInHours: 1, maxUses: 0 });
const raw = new DatabaseSync(file);
raw.prepare("UPDATE managed_invites SET token_hash = ? WHERE id = ?").run(createHash("sha256").update(legacyToken).digest("hex"), legacyAdminInvite.invite.id);
const row = raw.prepare("SELECT payload_encrypted, token_hash FROM workspace_invites").get()!;
assert.ok(!String(row.payload_encrypted).includes("private-"));
assert.notEqual(row.token_hash, created.token);
raw.close();
database.close();
database = new WebSpeakDatabase(file);
service = new AdminService(database, key, logger, path.join(directory, "missing.json"));
await service.initialize();
assert.deepEqual(service.getWorkspaceInvite(created.token, now), { ...credentials, expiresAt: now+3600000 });
const tickets = new JoinTicketStore(), port = await availablePort(), origin = `http://127.0.0.1:${port}`;
const server = createWebServer({ port, adminService: service, voiceBridgeOptions: { joinTickets: tickets }, logger });
context.after(async () => { await server.stop(); database.close(); await rm(directory, {recursive:true,force:true}); });
await server.start();
const response = await fetch(origin+"/api/join-ticket", { method: "POST", headers: {origin,"content-type":"application/json"}, body: JSON.stringify({nickname:"Invitee", invite:created.token, target:"127.0.0.1:9987", channel:"other-channel", serverPassword:"attacker-password"}) });
assert.equal(response.status,201);
const result = await response.json() as {ok: boolean; ticket:string};
assert.deepEqual(Object.keys(result).sort(),["ok","ticket"]);
assert.ok(!JSON.stringify(result).includes("private-"));
const payload = tickets.consume(result.ticket)!;
assert.deepEqual(payload.target,credentials.target);
assert.equal(payload.serverPassword,credentials.serverPassword);
assert.equal(payload.channelId,credentials.channelId);
assert.equal(payload.channelPassword,credentials.channelPassword);
assert.equal(payload.channel,undefined);
assert.equal(payload.inviteExpiresAt,created.expiresAt);
assert.equal(tickets.consume(result.ticket),null);
const expired = service.createWorkspaceInvite(credentials,1,now-120000);
const denied = await fetch(origin+"/api/join-ticket",{method:"POST",headers:{origin,"content-type":"application/json"},body:JSON.stringify({nickname:"Invitee",invite:expired.token})});
assert.equal(denied.status,400);
assert.equal((await denied.json() as {code:string}).code,"INVITE_INVALID");
const legacy = await fetch(origin+"/api/join-ticket", {method:"POST",headers:{origin,"content-type":"application/json"},body:JSON.stringify({nickname:"Legacy invitee",invite:legacyToken})});
assert.equal(legacy.status,201,"an administrator token that happens to start with wi_ must remain valid");
});
+16
View File
@@ -526,3 +526,19 @@ test("a live relay tunnel survives the reconnect guard untouched", () => {
assert.notEqual(f.state.adapter, null, "an open tunnel's adapter stays usable");
assert.notEqual(f.state.client, null, "an open tunnel's SDK client stays usable");
});
test("reconnecting to a protected channel uses its successful password rather than a failed attempt", async () => {
const f=fixture();
await f.client.switchChannel(10n,"correct-secret");
const first=f.sdk.inputCommands.find(c=>c.startsWith("clientmove "))!;
f.sdk.inputUpdate=async command=>{if(command.includes("cid=20"))throw new Error("invalid channel password");};
await assert.rejects(f.client.switchChannel(20n,"wrong-password"));
(f.client as unknown as {adapter:unknown}).adapter={connect:async()=>{}};
await f.client.connect();
const moves=f.sdk.inputCommands.filter(c=>c.startsWith("clientmove "));
assert.equal(moves.length,3);
assert.match(moves[2],/cid=10(?:\s|$)/);
assert.equal(moves[2].match(/cpw=([^\s]+)/)?.[1],first.match(/cpw=([^\s]+)/)?.[1]);
assert.ok(first.includes("cpw="));
});
+3 -1
View File
@@ -118,6 +118,7 @@ export class TSClient extends EventEmitter {
private inputStateQueue: Promise<void> = Promise.resolve();
private channelSwitchQueue: Promise<void> = Promise.resolve();
private preferredChannelId = 0n;
private readonly channelPasswords = new Map<bigint, string>();
private accelerationClient: AccelerationRelayClient | null = null;
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
private readonly channelPasswordProtection = new Map<bigint, boolean>();
@@ -219,7 +220,7 @@ export class TSClient extends EventEmitter {
this.preferredChannelId = connectedChannelId;
} else if (connectedChannelId !== this.preferredChannelId) {
try {
await tsClientMove(client, this.clientId, this.preferredChannelId);
await tsClientMove(client, this.clientId, this.preferredChannelId, this.channelPasswords.get(this.preferredChannelId));
} catch (error: unknown) {
// The old channel may have been deleted or become inaccessible. The
// SDK has already left us in the server/default channel, which is the
@@ -530,6 +531,7 @@ export class TSClient extends EventEmitter {
await tsClientMove(client, clientId, channelId, password);
if (!isCurrent()) throw new Error("TeamSpeak session changed while switching channels");
this.preferredChannelId = channelId;
if (password) this.channelPasswords.set(channelId, password);
};
// Rapid clicks used to issue overlapping clientmove commands. The SDK and
+60 -4
View File
@@ -27,7 +27,10 @@ class TeamSpeakStub extends EventEmitter {
async connect() { this.connectCalls++; this.disconnected = false; if (this.emitDirectorySnapshotOnConnect) this.emit("directorySnapshot", this.directory); }
async disconnect() { this.disconnected = true; }
getClientId() { return 1; }
getChannelId() { return 1n; }
channelId = 1n;
lastChannelPassword = "";
async switchChannel(id: bigint, password?: string) { this.channelId = id; this.lastChannelPassword = password ?? ""; }
getChannelId() { return this.channelId; }
isConnected() { return !this.disconnected; }
async getServerInfo() { this.serverInfoCalls++; return { name: "兄弟们的teamspeak", iconId: null }; }
async getServerPresentation() {
@@ -43,15 +46,17 @@ class TeamSpeakStub extends EventEmitter {
}
async function fixture(t: TestContext, overrides: {
createTeamSpeakClient?: () => TSClient;
createTeamSpeakClient?: (options: import("./ts-client.js").TSClientOptions) => TSClient;
createEncoder?: () => Pick<OpusEncoder, "encode" | "dispose">;
configureSdk?: (sdk: TeamSpeakStub) => void;
waitForFirstMessage?: boolean;
createWorkspaceInvite?: import("./voice-bridge.js").VoiceBridgeOptions["createWorkspaceInvite"];
connection?: Partial<import("./join-ticket.js").JoinTicketPayload>;
} = {}) {
const sdk = new TeamSpeakStub();
overrides.configureSdk?.(sdk);
const tickets = new JoinTicketStore();
const bridge = new VoiceBridge({ joinTickets: tickets }, pino({ enabled: false }), undefined, {
const bridge = new VoiceBridge({ joinTickets: tickets, createWorkspaceInvite: overrides.createWorkspaceInvite }, pino({ enabled: false }), undefined, {
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
});
@@ -62,7 +67,7 @@ async function fixture(t: TestContext, overrides: {
await once(server, "listening");
const address = server.address();
assert.ok(address && typeof address !== "string");
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "" });
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "", ...overrides.connection });
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);
const messages: Array<{ data: Buffer; binary: boolean }> = [];
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
@@ -80,6 +85,7 @@ async function fixture(t: TestContext, overrides: {
const entries = (bridge as unknown as { entries: Map<string, {
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
isAlive: boolean; lastPongAt: number; missedHeartbeats: number; avatarCache: Map<string, string | null>;
channelTree: import("../shared/voice-models.js").ChannelInfo[];
members: Map<number, { id: number; uid: string }>; eventLog: unknown[];
}> }).entries;
return { bridge, sdk, socket, messages, entries, wss };
@@ -428,3 +434,53 @@ for (const order of ["kick-first", "disconnect-first"] as const) {
assert.match(failures[0].detail, /Removed by operator/);
});
}
test("workspace invitations use authenticated session credentials and remember only successful channel passwords", async t => {
let credentials: unknown;
const f = await fixture(t, { connection: { serverPassword: "server-secret", invitationTarget: { host: "original.example.com", port: 9987 } },
createWorkspaceInvite: (value, minutes) => { credentials = value; assert.equal(minutes, 60); return { token: "wi_" + "x".repeat(43), expiresAt: Date.now()+3600000 }; },
});
while (!messageTypes(f.messages).includes("connected")) await nextTurn();
const entry = [...f.entries.values()][0]!;
entry.channelTree.push({ id: "1", parentID: "0", name: "Locked", passwordProtected: true });
let reply = waitForMessage(f.socket, "error");
f.socket.send(JSON.stringify({ type: "createInvite", requestId: "missing-password", payload: { expiresInMinutes: 60 } }));
assert.equal(((await reply).error as { code: string }).code, "CHANNEL_PASSWORD_REQUIRED");
const switched = waitForMessage(f.socket, "channelSwitched");
f.socket.send(JSON.stringify({ type: "switchChannel", requestId: "switch", payload: { channelId: "1", password: "channel-secret" } }));
await switched;
reply = waitForMessage(f.socket, "inviteCreated");
f.socket.send(JSON.stringify({ type: "createInvite", requestId: "invite", payload: { expiresInMinutes: 60, target: "127.0.0.1", channelId: "999" } }));
const result = await reply;
assert.equal(result.requestId, "invite");
assert.deepEqual(credentials, { target: { host: "original.example.com", port: 9987 }, serverPassword: "server-secret", channelId: "1", channelPassword: "channel-secret" });
assert.ok(!JSON.stringify(f.messages).includes("server-secret"));
assert.ok(!JSON.stringify(f.messages).includes("channel-secret"));
});
test("an invited connection joins its bound channel using server-only credentials before reporting connected", async t => {
let sdk: TeamSpeakStub;
const f = await fixture(t, { connection: { serverPassword: "private-server", channelId: "9", channelPassword: "private-channel" },
configureSdk: value => { sdk = value; },
createTeamSpeakClient: options => { assert.equal(options.serverPassword, "private-server"); return sdk as unknown as TSClient; },
});
while (!messageTypes(f.messages).includes("connected")) await nextTurn();
assert.equal(f.sdk.channelId, 9n);
assert.equal(f.sdk.lastChannelPassword, "private-channel");
assert.ok(!JSON.stringify(f.messages).includes("private-channel"));
assert.ok(!JSON.stringify(f.messages).includes("private-server"));
});
test("an authenticated creator may supply a missing server password without disclosing it to the recipient", async t => {
const f=await fixture(t,{createWorkspaceInvite: credentials=>{
assert.equal(credentials.serverPassword,"creator-provided");
return {token:"wi_"+"a".repeat(43),expiresAt:Date.now()+60000};
}});
while(!messageTypes(f.messages).includes("connected"))await nextTurn();
const reply=waitForMessage(f.socket,"inviteCreated");
f.socket.send(JSON.stringify({type:"createInvite",requestId:"provided",payload:{expiresInMinutes:1,serverPassword:"creator-provided"}}));
assert.equal((await reply).requestId,"provided");
assert.ok(!JSON.stringify(f.messages).includes("creator-provided"));
});
+23
View File
@@ -50,6 +50,7 @@ function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>):
}
export interface VoiceBridgeOptions {
createWorkspaceInvite?: (credentials: import("./workspace-invites.js").WorkspaceInviteCredentials, minutes: number) => { token: string; expiresAt: number };
pluginRuntimeEnabled?: boolean;
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
@@ -83,6 +84,7 @@ export interface AdminSessionSummary {
type ServerEvent = SharedServerEvent & { kind: "joined" | "left" | "moved" | "poke" | "connection" };
interface WebClientEntry extends SessionDirectoryState {
rememberChannelPassword?: (id: string, password: string) => void;
id: string;
session: ManagedSession;
tsClient: TSClient;
@@ -168,6 +170,8 @@ export class VoiceBridge {
const { target, serverPassword, nickname } = connection;
const channelName = connection.channel;
const channelPasswords = new Map<string, string>();
let lastInviteAt = 0;
const acceleration = connection.accelerated ? this.getAccelerationOptions(connection.accelerationRelayId) : undefined;
if (connection.accelerated && !acceleration) {
ws.close(4006, "ACCELERATION_UNAVAILABLE");
@@ -231,6 +235,7 @@ export class VoiceBridge {
}
entry = {
id: entryId,
rememberChannelPassword: (id, password) => channelPasswords.set(id, password),
session,
tsClient,
ws,
@@ -450,6 +455,11 @@ export class VoiceBridge {
const connectTeamSpeak = async (isReconnect: boolean): Promise<void> => {
try {
await tsClient.connect();
if (connection.channelId && !isReconnect) {
if (tsClient.getChannelId().toString() !== connection.channelId) await tsClient.switchChannel(BigInt(connection.channelId), connection.channelPassword || undefined);
if (tsClient.getChannelId().toString() !== connection.channelId) throw new Error("Invited channel could not be joined");
if (connection.channelPassword) channelPasswords.set(connection.channelId, connection.channelPassword);
}
if (session.state !== "authenticating") return;
session.transition("syncing");
tsReady = true;
@@ -612,6 +622,19 @@ export class VoiceBridge {
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪", command.requestId);
return;
}
if (command.type === "createInvite") {
if (!this.options.createWorkspaceInvite) { sendProtocolError(sendJson, "INVITE_UNAVAILABLE", "Invitations are unavailable on this gateway", command.requestId); return; }
if (Date.now() - lastInviteAt < 1000) { sendProtocolError(sendJson, "RATE_LIMITED", "Please wait before creating another invitation", command.requestId); return; }
const channelId = tsClient.getChannelId().toString();
const password = command.payload.channelPassword || channelPasswords.get(channelId) || "";
if (entry!.channelTree.find(c => c.id === channelId)?.passwordProtected && !password) { sendProtocolError(sendJson, "CHANNEL_PASSWORD_REQUIRED", "Enter the current channel password to share access", command.requestId); return; }
try {
const result = this.options.createWorkspaceInvite({ target: connection.invitationTarget ?? target, serverPassword: command.payload.serverPassword ?? serverPassword, channelId, channelPassword: password }, command.payload.expiresInMinutes);
lastInviteAt = Date.now();
sendJson({ type: "inviteCreated", requestId: command.requestId, ...result });
} catch { sendProtocolError(sendJson, "INVITE_CREATE_FAILED", "Could not create invitation", command.requestId); }
return;
}
void handleCommand(entry!, command, sendJson);
});
+2
View File
@@ -11,6 +11,7 @@ import { teamSpeakServerErrorCode } from "../errors.js";
export interface VoiceCommandContext extends AudioStatsSource {
tsClient: Pick<TSClient, "execCommandWithResponse" | "switchChannel" | "getClientId" | "getChannelId" | "moveClient" | "sendTextMessage" | "poke" | "setAway" | "setInputMuted" | "setAccompanimentActive">;
channelTree: ChannelInfo[];
rememberChannelPassword?: (id: string, password: string) => void;
members: ReadonlyMap<number, { uid?: string }>;
whisperTargetIds: Set<number>;
whisperActive: boolean;
@@ -63,6 +64,7 @@ export async function handleCommand(
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
try {
await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined);
if (channelPassword) entry.rememberChannelPassword?.(rawId, channelPassword);
} catch (error: unknown) {
const rawMessage = error instanceof Error ? error.message : String(error);
if (/already member/i.test(rawMessage)) {
+11
View File
@@ -45,3 +45,14 @@ test("delegated voice session parser accepts only bounded TeamSpeak session data
assert.equal(parseDelegatedVoiceSession({ ...payload, nickname: "" }), null);
assert.equal(parseDelegatedVoiceSession({ ...payload, serverPassword: "x".repeat(513) }), null);
});
test("relay sessions retain invitation channel credentials and reject expired authorization", () => {
const inviteExpiresAt=Date.now()+60000;
const session={...payload,invitationTarget:{host:"original.example.com",port:9987},channelId:"9",channelPassword:"private",inviteExpiresAt};
assert.deepEqual(parseDelegatedVoiceSession(session),session);
assert.equal(parseDelegatedVoiceSession({...session,inviteExpiresAt:Date.now()-1}),null);
assert.equal(parseDelegatedVoiceSession({...session,channelPassword:"x".repeat(513)}),null);
assert.equal(parseDelegatedVoiceSession({...session,channelId:"0"}),null);
assert.equal(parseDelegatedVoiceSession({...session,invitationTarget:{host:"http://bad",port:9987}}),null);
});
+16
View File
@@ -7,9 +7,13 @@ const MAX_NONCES = 10_000;
export interface DelegatedVoiceSession {
target: TeamSpeakTarget;
invitationTarget?: TeamSpeakTarget;
serverPassword: string;
nickname: string;
channel?: string;
channelId?: string;
channelPassword?: string;
inviteExpiresAt?: number;
identity?: string;
rememberIdentity?: boolean;
}
@@ -72,17 +76,29 @@ export function parseDelegatedVoiceSession(value: unknown): DelegatedVoiceSessio
const { host, port } = value.target;
if (typeof host !== "string" || host.length < 1 || host.length > 253 || /[\s\u0000-\u001f\u007f\/#@?]/.test(host)) return null;
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) return null;
if (value.invitationTarget !== undefined) {
const original = value.invitationTarget;
if (!isRecord(original) || typeof original.host !== "string" || !original.host || original.host.length > 253 || /[\s\u0000-\u001f\u007f\/#@?]/.test(original.host)
|| typeof original.port !== "number" || !Number.isInteger(original.port) || original.port < 1 || original.port > 65535) return null;
}
if (typeof value.serverPassword !== "string" || value.serverPassword.length > 512) return null;
if (typeof value.nickname !== "string" || !value.nickname.trim() || value.nickname.length > 30) return null;
if (value.channel !== undefined && (typeof value.channel !== "string" || value.channel.length > 100)) return null;
if (value.inviteExpiresAt !== undefined && (typeof value.inviteExpiresAt !== "number" || !Number.isSafeInteger(value.inviteExpiresAt) || value.inviteExpiresAt <= Date.now())) return null;
if (value.channelId !== undefined && (typeof value.channelId !== "string" || !/^[1-9]\d{0,19}$/.test(value.channelId))) return null;
if (value.channelPassword !== undefined && (typeof value.channelPassword !== "string" || value.channelPassword.length > 512)) return null;
if (value.identity !== undefined && (typeof value.identity !== "string" || value.identity.length > 8192)) return null;
if (value.rememberIdentity !== undefined && typeof value.rememberIdentity !== "boolean") return null;
return {
target: { host, port },
...(isRecord(value.invitationTarget) ? { invitationTarget: { host: value.invitationTarget.host as string, port: value.invitationTarget.port as number } } : {}),
serverPassword: value.serverPassword,
nickname: value.nickname.trim(),
...(typeof value.channel === "string" && value.channel ? { channel: value.channel } : {}),
...(typeof value.inviteExpiresAt === "number" ? { inviteExpiresAt: value.inviteExpiresAt } : {}),
...(typeof value.channelId === "string" ? { channelId: value.channelId } : {}),
...(typeof value.channelPassword === "string" ? { channelPassword: value.channelPassword } : {}),
...(typeof value.identity === "string" && value.identity ? { identity: value.identity } : {}),
...(value.rememberIdentity === true ? { rememberIdentity: true } : {}),
};
+15
View File
@@ -8,6 +8,7 @@ import type { WebRtcAudioOptions } from "./webrtc-audio.js";
import type { ScreenShareIceServer } from "./screen-share.js";
export interface VoiceGatewayServerOptions {
workspaceInvites?: import("./workspace-invites.js").WorkspaceInvites;
host: string;
port: number;
sharedToken: string;
@@ -30,6 +31,7 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
const verifier = new VoiceGatewayRequestVerifier();
const voiceBridgeOptions: VoiceBridgeOptions = {
joinTickets: tickets,
...(options.workspaceInvites ? { createWorkspaceInvite: (credentials, minutes) => options.workspaceInvites!.create(credentials, minutes) } : {}),
webRtc: options.webRtc,
screenShareIceServers: options.screenShareIceServers,
trustedProxies: options.trustedProxies,
@@ -61,6 +63,19 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
response.status(201).json({ ok: true, ticket: tickets.create(session) });
});
app.post("/api/relay/workspace-invite", (request, response) => {
response.setHeader("Cache-Control", "no-store");
const authenticated = verifier.verify(options.sharedToken, {
timestamp: request.get("x-webspeak-relay-timestamp"), nonce: request.get("x-webspeak-relay-nonce"), signature: request.get("x-webspeak-relay-signature"),
}, request.body);
if (!authenticated) { response.status(401).json({ ok: false, code: "RELAY_AUTH_REJECTED" }); return; }
const body = request.body;
if (body?.purpose !== "workspace-invite" || typeof body.token !== "string" || !/^wi_[A-Za-z0-9_-]{43}$/.test(body.token)) { response.status(400).json({ ok: false }); return; }
const access = options.workspaceInvites?.get(body.token);
if (!access) { response.status(404).json({ ok: false }); return; }
response.json({ ok: true, access });
});
bridge.attach(server);
return {
+1
View File
@@ -116,6 +116,7 @@ function fixture() {
closed: false, closePromise: null, audioTimer: null, activityTimer: undefined,
pendingFrames: new Map([[1, []]]), memberVolumes: new Map([[1, 1]]),
partialPcmByClient: new Map([[1, Buffer.alloc(2)]]), activeSpeakerIds: new Set([1]),
decoderCodecByClient: new Map([[1, 4], [2, 5]]),
decoderByClient: new Map([
[1, { dispose() { released.push("decoder-1"); throw new Error("Decoder failed"); } }],
[2, { dispose() { released.push("decoder-2"); } }],
+40 -10
View File
@@ -11,13 +11,15 @@ import type { TSVoiceData } from "./ts-client.js";
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
import { OpusEncoder } from "./opus-codec.js";
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
const AUDIO_SAMPLE_RATE = 48_000;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const AUDIO_CHANNELS = 2;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
@@ -102,6 +104,7 @@ export class WebRtcAudioSession {
private readonly onVoiceActivity: (clientIds: number[]) => void;
private readonly outgoingTrack: MediaStreamTrack;
private readonly decoderByClient = new Map<number, OpusEncoder>();
private readonly decoderCodecByClient = new Map<number, 4 | 5>();
private readonly partialPcmByClient = new Map<number, Buffer>();
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
private readonly memberVolumes = new Map<number, number>();
@@ -198,7 +201,7 @@ export class WebRtcAudioSession {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
});
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1));
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, AUDIO_CHANNELS));
try {
this.encoder = createEncoder();
} catch (error: unknown) {
@@ -240,22 +243,37 @@ export class WebRtcAudioSession {
this.outgoingPayloadType = opus[0]!.payloadType;
await transceiver.sender.replaceTrack(this.outgoingTrack);
const answer = await this.peer.createAnswer();
await this.peer.setLocalDescription(answer);
await this.peer.setLocalDescription({
...answer,
sdp: addOpusFmtpParameters(answer.sdp ?? "", ["stereo=1", "sprop-stereo=1"]),
});
const description = this.peer.localDescription;
if (!description) throw new Error("WebRTC answer was not created");
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
return { type: description.type, sdp: description.sdp };
return {
type: description.type,
sdp: addOpusFmtpParameters(description.sdp, ["stereo=1", "sprop-stereo=1"]),
};
}
pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
let decoder = this.decoderByClient.get(data.clientId);
if (decoder && this.decoderCodecByClient.get(data.clientId) !== data.codec) {
try { decoder.dispose(); } catch { /* a codec transition must still reset queued PCM */ }
this.decoderByClient.delete(data.clientId);
this.decoderCodecByClient.delete(data.clientId);
this.partialPcmByClient.delete(data.clientId);
this.pendingFrames.delete(data.clientId);
decoder = undefined;
}
if (!decoder) {
try {
// @discordjs/opus exposes decoding on OpusEncoder instances too;
// there is no separate OpusDecoder constructor in that package.
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, data.codec === 4 ? 1 : 2);
this.decoderByClient.set(data.clientId, decoder);
this.decoderCodecByClient.set(data.clientId, data.codec);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
return;
@@ -264,16 +282,26 @@ export class WebRtcAudioSession {
try {
const pcm = decoder.decode(data.data);
this.stats.webrtcDownlinkDecodedFrames++;
if (pcm.length < 2) {
const inputChannels = data.codec === 4 ? 1 : 2;
if (pcm.length < inputChannels * 2 || pcm.length % (inputChannels * 2) !== 0) {
this.stats.webrtcDownlinkShortFrames++;
return;
}
let stereoPcm = pcm;
if (inputChannels === 1) {
stereoPcm = Buffer.allocUnsafe(pcm.length * AUDIO_CHANNELS);
for (let inputOffset = 0, outputOffset = 0; inputOffset < pcm.length; inputOffset += 2, outputOffset += 4) {
const sample = pcm.readInt16LE(inputOffset);
stereoPcm.writeInt16LE(sample, outputOffset);
stereoPcm.writeInt16LE(sample, outputOffset + 2);
}
}
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
// decoded frame per speaker and split every decoded buffer into the
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
// anything after the first 20 ms.
const pendingPcm = this.partialPcmByClient.get(data.clientId);
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
const combined = pendingPcm ? Buffer.concat([pendingPcm, stereoPcm]) : stereoPcm;
const rms = this.calculateRms(pcm);
// RMS is used only for the UI speaking indicator. Every decoded frame,
// including quiet/comfort-noise frames, continues into the queue so the
@@ -326,6 +354,7 @@ export class WebRtcAudioSession {
this.closePromise = Promise.resolve().then(async () => {
const decoders = [...this.decoderByClient.values()];
this.decoderByClient.clear();
this.decoderCodecByClient.clear();
for (const decoder of decoders) {
try { decoder.dispose(); } catch { /* continue releasing other resources */ }
}
@@ -368,13 +397,13 @@ export class WebRtcAudioSession {
this.stats.webrtcQueueUnderrunTicks++;
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
if (!frame) continue;
const volume = this.memberVolumes.get(clientId) ?? 1;
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
}
}
@@ -383,7 +412,7 @@ export class WebRtcAudioSession {
// source packets with our encoded silence/mixes corrupts decoder history
// and can suppress otherwise valid speech without any packet loss.
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
// the waveform's apparent loudness as the source level changes, which
// is especially noticeable on music. Only clip actual overflow caused
@@ -450,6 +479,7 @@ export class WebRtcAudioSession {
const decoder = this.decoderByClient.get(clientId);
if (!decoder) return;
this.decoderByClient.delete(clientId);
this.decoderCodecByClient.delete(clientId);
try { decoder.dispose(); } catch { /* continue after codec cleanup failures */ }
}
+35
View File
@@ -0,0 +1,35 @@
import { createHash, randomBytes } from "node:crypto";
import type { WebSpeakDatabase } from "../persistence/database.js";
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export interface WorkspaceInviteCredentials {
target: TeamSpeakTarget;
serverPassword: string;
channelId: string;
channelPassword: string;
}
export type WorkspaceInviteAccess = WorkspaceInviteCredentials & { expiresAt: number };
const purpose = "webspeak:workspace-invite:v1";
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
/** Both normal and relay gateways keep invitation credentials in their own persistent data directory. */
export class WorkspaceInvites {
constructor(private readonly database: WebSpeakDatabase, private readonly key: Buffer) {}
create(credentials: WorkspaceInviteCredentials, expiresInMinutes: number, now = Date.now()): { token: string; expiresAt: number } {
if (!Number.isInteger(expiresInMinutes) || expiresInMinutes < 1 || expiresInMinutes > 43200) throw new Error("INVALID_INVITE_EXPIRY");
const token = "wi_" + randomBytes(32).toString("base64url");
const expiresAt = now + expiresInMinutes * 60000;
this.database.saveWorkspaceInvite(hash(token), encryptSecret(JSON.stringify({ ...credentials, expiresAt }), this.key, purpose), expiresAt, now);
return { token, expiresAt };
}
get(token: string, now = Date.now()): WorkspaceInviteAccess | null {
if (!/^wi_[A-Za-z0-9_-]{43}$/.test(token)) return null;
const encrypted = this.database.getWorkspaceInvite(hash(token), now);
if (!encrypted) return null;
try { return JSON.parse(decryptSecret(encrypted, this.key, purpose)) as WorkspaceInviteAccess; }
catch { return null; }
}
}
+8
View File
@@ -5,6 +5,7 @@ import { normalizeScreenShareIceServers, parseScreenShareMessage } from "./scree
test("all command payloads preserve request IDs through the shared parser", () => {
const payloads: ClientCommandPayloads = {
createInvite: { expiresInMinutes: 60 },
switchChannel: { channelId: "18446744073709551615", password: "secret" },
moveClient: { clientId: 2, channelId: "1" }, sendTextMessage: { message: "hello" },
sendServerMessage: { message: "hello" }, sendPrivateMessage: { clientId: 2, message: "hello" },
@@ -65,3 +66,10 @@ test("screen signal bounds and ICE filtering are identical in both environments"
// @ts-expect-error A microphone payload must never type-check as a move request.
const invalidCommand: ClientCommand = { type: "moveClient", payload: { muted: true } };
void invalidCommand;
test("invitation commands bound both expiry and optional creator credentials", () => {
for(const payload of [{expiresInMinutes:0},{expiresInMinutes:43201},{expiresInMinutes:1.5},{expiresInMinutes:60,serverPassword:1},{expiresInMinutes:60,serverPassword:"x".repeat(513)},{expiresInMinutes:60,channelPassword:"x".repeat(513)}]) {
assert.ok("error" in parseClientCommand(JSON.stringify({type:"createInvite",payload})));
}
});
+8 -1
View File
@@ -1,5 +1,6 @@
/** Payloads stay correlated with their command names across both runtimes. */
export interface ClientCommandPayloads {
createInvite: { expiresInMinutes: number; channelPassword?: string; serverPassword?: string };
switchChannel: { channelId: string; password?: string };
moveClient: { clientId: number; channelId: string; password?: string };
sendTextMessage: { message: string; channelId?: string };
@@ -36,13 +37,19 @@ export function parseClientCommand(raw: string): ClientCommandResult {
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
}
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]);
const supportedTypes = new Set(["createInvite", "switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
if (!isRecord(value.payload)) {
return { error: { code: "INVALID_PAYLOAD", message: "消息参数无效" } };
}
if (value.type === "createInvite" && (!Number.isInteger(value.payload.expiresInMinutes) || Number(value.payload.expiresInMinutes) < 1 || Number(value.payload.expiresInMinutes) > 43200 || (value.payload.channelPassword !== undefined && (typeof value.payload.channelPassword !== "string" || value.payload.channelPassword.length > 512)))) {
return { error: { code: "INVALID_INVITE", message: "Invalid invitation expiry or credentials" } };
}
if (value.type === "createInvite" && value.payload.serverPassword !== undefined && (typeof value.payload.serverPassword !== "string" || value.payload.serverPassword.length > 512)) {
return { error: { code: "INVALID_INVITE", message: "Invalid invitation credentials" } };
}
if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
+45
View File
@@ -0,0 +1,45 @@
/** Add Opus channel negotiation parameters to audio payloads in an SDP document. */
export function addOpusFmtpParameters(sdp: string, parameters: readonly string[]): string {
if (!sdp || parameters.length === 0) return sdp;
const lines = sdp.split(/\r?\n/);
const output: string[] = [];
let section: string[] = [];
const flush = () => {
if (section[0]?.startsWith("m=audio ")) patchAudioSection(section, parameters);
output.push(...section);
section = [];
};
for (const line of lines) {
if (line.startsWith("m=")) {
if (section.length) flush();
}
section.push(line);
}
if (section.length) flush();
return output.join("\r\n");
}
function patchAudioSection(section: string[], parameters: readonly string[]): void {
const payloads = new Set(section[0]!.trim().split(/\s+/).slice(3));
const opusPayloads = section.flatMap(line => {
const match = /^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?\s*$/i.exec(line);
return match && payloads.has(match[1]!) ? [match[1]!] : [];
});
for (const payload of opusPayloads) {
const prefix = `a=fmtp:${payload}`;
const index = section.findIndex(line => new RegExp(`^${prefix}(?:\\s|$)`).test(line));
if (index < 0) {
const rtpmap = section.findIndex(line => line.startsWith(`a=rtpmap:${payload} `));
if (rtpmap >= 0) section.splice(rtpmap + 1, 0, `${prefix} ${parameters.join(";")}`);
continue;
}
const parts = section[index]!.slice(prefix.length).trim().split(";").filter(Boolean);
for (const parameter of parameters) {
const name = parameter.split("=", 1)[0]!.trim().toLowerCase();
const existing = parts.findIndex(part => part.split("=", 1)[0]!.trim().toLowerCase() === name);
if (existing < 0) parts.push(parameter);
else parts[existing] = parameter;
}
section[index] = `${prefix} ${parts.join(";")}`;
}
}
+4 -4
View File
@@ -15,9 +15,9 @@ export interface PluginManifest {
}
export interface PluginFile { encoding: "utf8" | "base64"; data: string }
export interface PluginPackage { manifest: PluginManifest; files: Record<string, PluginFile> }
export interface PluginSettings { enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
export interface PluginSettings { enabled: boolean; trusted: boolean; toolbarPinned: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
export interface PluginSettingsInput {
enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
enabled: boolean; trusted: boolean; toolbarPinned?: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
serverConfigAction?: "keep" | "replace" | "remove"; serverConfig?: JsonValue;
}
export interface PluginRuntimeStatus { state: "disabled" | "client" | "stopped" | "starting" | "running" | "failed"; error?: string }
@@ -95,8 +95,8 @@ export function parsePluginJson(v: unknown, maxBytes = 64 * 1024): JsonValue {
export function readInstalledPlugin(v: unknown): InstalledPlugin {
pluginAssert(pluginRecord(v) && pluginRecord(v.settings) && typeof v.revision === "string" && /^[a-f0-9]{64}$/.test(v.revision) && typeof v.installedAt === "number" && Number.isFinite(v.installedAt));
const manifest=parsePluginManifest(v.manifest),s=v.settings;
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && (s.toolbarPinned === undefined || typeof s.toolbarPinned === "boolean") && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,toolbarPinned:s.toolbarPinned===true,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
if(v.runtime!==undefined){pluginAssert(pluginRecord(v.runtime) && ["disabled","client","stopped","starting","running","failed"].includes(String(v.runtime.state)) && (v.runtime.error===undefined||typeof v.runtime.error==="string"));result.runtime={state:v.runtime.state as PluginRuntimeStatus["state"],...(v.runtime.error?{error:v.runtime.error as string}:{})};}
return result;
}
+1
View File
@@ -9,6 +9,7 @@ const stream = {
};
const event = { id: "event-1", kind: "joined", message: "Member joined", timestamp: 1_000 };
const samples: Record<ServerMessage["type"], ServerMessage> = {
inviteCreated: { type: "inviteCreated", requestId: "test", token: "wi_" + "a".repeat(43), expiresAt: 1800000000000 },
connected: { type: "connected", tsClientId: 1, members: [{ id: 1, nickname: "Owner" }], serverEventLog: [event] },
serverInfo: {
type: "serverInfo", name: "兄弟们的teamspeak", icon: "data:image/png;base64,iVBORw0KGgo=",
+2
View File
@@ -12,6 +12,7 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
export type ServerMessage =
| Message<"inviteCreated", Request & { token: string; expiresAt: number }>
| Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
| Message<"memberEnter", ChannelMember>
@@ -151,6 +152,7 @@ const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> =
&& optional(m.scope, text) && optional(m.senderUid, text) && optional(m.targetId, channelId),
pokeReceived: m => text(m.message) && optional(m.invokerId, finite) && optional(m.invokerName, text) && optional(m.timestamp, finite) && optional(m.invokerUid, text),
serverEvent: m => event(m.event),
inviteCreated: m => text(m.token) && /^wi_[A-Za-z0-9_-]{43}$/.test(m.token) && typeof m.expiresAt === "number" && Number.isSafeInteger(m.expiresAt),
channelSwitched: m => channelId(m.channelId),
audioStats: m => text(m.sequence) && m.sequence.length <= 64 && isRecord(m.stats),
latencyPong: m => text(m.sequence) && (m.teamSpeakLatencyMs === null || finite(m.teamSpeakLatencyMs)) && boolean(m.teamSpeakReachable)
+242
View File
@@ -0,0 +1,242 @@
import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js";
/**
* `chrome.json` is an optional, declarative companion to an open skin.
*
* It describes two host-chrome capabilities that CSS alone cannot express
* safely:
* - `visibleParts`: decorations the skin asks the host to render. This is the
* only opt-in; official and built-in skins stay clean.
* - `hiddenParts`: non-critical decorations the skin wants collapsed by
* default. Only explicitly optional parts are accepted.
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
*
* Both the browser importer and the server-side registry parse the exact same
* document, so a package accepted by one is accepted by the other.
*/
export const SKIN_CHROME_MAX_BYTES = 32 * 1024;
export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32;
export const SKIN_CHROME_MAX_ICONS = 16;
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
export const SKIN_ICON_DIRECTORY = "assets/icons/";
const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]);
/**
* Decorative host chrome that is hidden unless a skin explicitly opts in.
* Official and built-in skins ship no `chrome.json`, so they stay identical to
* production; a host-chrome pack opts in with `chrome.json#visibleParts`.
*/
export const DEFAULT_HIDDEN_HOST_PARTS: ReadonlySet<string> = new Set([
"host.watermark",
"host.hint",
"host.voice-status-decoration",
]);
export interface SkinChromeDocument {
schemaVersion: 1;
hiddenParts: string[];
/**
* Parts from `DEFAULT_HIDDEN_HOST_PARTS` (or other decorative parts) that a
* skin asks the host to render. This is the only opt-in for decorations; a
* chrome.json that omits it keeps the same clean chrome as built-in skins.
*/
visibleParts?: string[];
icons: Record<string, string>;
}
export interface SkinChromeAssetInfo {
bytes: number;
mime: string;
}
export class SkinChromeError extends Error {
constructor(message: string, readonly code: string) {
super(message);
this.name = "SkinChromeError";
}
}
function reject(message: string, code: string): never {
throw new SkinChromeError(message, code);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
/** Validate and normalize an icon asset path. Only package-local bitmaps under assets/icons/ are allowed. */
export function normalizeSkinIconPath(raw: unknown): string {
if (typeof raw !== "string" || !raw || raw.length > 160) {
return reject("An icon path must be a short, non-empty string.", "SKIN_ICON_PATH");
}
const path = raw.split(/[?#]/, 1)[0];
if (!path.startsWith(SKIN_ICON_DIRECTORY)) {
return reject(`Icon bitmaps must live in ${SKIN_ICON_DIRECTORY}.`, "SKIN_ICON_PATH");
}
const segments = path.split("/");
if (segments.length !== 3 || segments.some((segment) => !segment || segment === "." || segment === "..")) {
return reject("An icon path must be a single file inside assets/icons/.", "SKIN_ICON_PATH");
}
const filename = segments[2];
const extension = filename.split(".").pop()?.toLowerCase() ?? "";
if (!SUPPORTED_ICON_EXTENSIONS.has(extension)) {
return reject("Icon bitmaps must be PNG, JPEG, WebP, AVIF or GIF files (SVG is not allowed).", "SKIN_ICON_PATH");
}
if (/[\\:\0%\s]/.test(path) || /^[a-z]:/i.test(path) || path.startsWith("/") || path.includes("//")) {
return reject("An icon path must be a safe, package-relative path.", "SKIN_ICON_PATH");
}
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(filename)) {
return reject("An icon filename contains unsupported characters.", "SKIN_ICON_PATH");
}
return path;
}
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
const bytes = new TextEncoder().encode(source).byteLength;
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
return reject("chrome.json must be between 1 byte and 32 KiB.", "SKIN_CHROME_SIZE");
}
let raw: unknown;
try { raw = JSON.parse(source); }
catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); }
if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID");
for (const key of Object.keys(raw)) {
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") {
return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID");
}
}
if (raw.schemaVersion !== 1) return reject("chrome.json must use schemaVersion 1.", "SKIN_CHROME_INVALID");
const hiddenParts: string[] = [];
if (raw.hiddenParts !== undefined) {
if (!Array.isArray(raw.hiddenParts) || raw.hiddenParts.length > SKIN_CHROME_MAX_HIDDEN_PARTS) {
return reject("hiddenParts must be an array of at most 32 part names.", "SKIN_CHROME_HIDDEN_INVALID");
}
for (const entry of raw.hiddenParts) {
if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) {
return reject(`Only explicitly optional decorative parts may be hidden: ${String(entry)}.`, "SKIN_CHROME_HIDDEN_INVALID");
}
if (!hiddenParts.includes(entry)) hiddenParts.push(entry);
}
}
let visibleParts: string[] | undefined;
if (raw.visibleParts !== undefined) {
if (!Array.isArray(raw.visibleParts) || raw.visibleParts.length > SKIN_CHROME_MAX_HIDDEN_PARTS) {
return reject("visibleParts must be an array of at most 32 part names.", "SKIN_CHROME_VISIBLE_INVALID");
}
visibleParts = [];
for (const entry of raw.visibleParts) {
if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) {
return reject(`Only explicitly optional decorative parts may be shown: ${String(entry)}.`, "SKIN_CHROME_VISIBLE_INVALID");
}
if (!visibleParts.includes(entry)) visibleParts.push(entry);
}
}
const icons: Record<string, string> = Object.create(null) as Record<string, string>;
if (raw.icons !== undefined) {
if (!isRecord(raw.icons)) return reject("icons must be an object mapping slot names to asset paths.", "SKIN_ICON_INVALID");
const entries = Object.entries(raw.icons);
if (entries.length > SKIN_CHROME_MAX_ICONS) {
return reject(`A skin may override at most ${SKIN_CHROME_MAX_ICONS} icons.`, "SKIN_ICON_INVALID");
}
for (const [slot, path] of entries) {
if (!SKIN_ICON_SLOT_IDS.has(slot)) {
return reject(`Unknown icon slot: ${slot}.`, "SKIN_ICON_INVALID");
}
icons[slot] = normalizeSkinIconPath(path);
}
}
return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons };
}
/**
* Merge the instance default, the skin's explicit opt-ins and its hidden list
* into the set of optional host parts the host must not render.
*
* Decorations are hidden by default so official/built-in skins match
* production. A pack opts in with `visibleParts`; a pack that ships a
* chrome.json without that field (icons-only or hiddenParts-only) stays hidden,
* and `hiddenParts` still wins over both.
*
* The decision is intentionally independent of the generated host CSS: the
* importer appends `compileSkinChromeCss()` output after the author CSS, so
* sniffing the combined string for `data-ws-part="host.…"` would treat every
* hiddenParts entry as a declaration that the skin themes host chrome.
*/
export function resolveHiddenHostParts(
document: SkinChromeDocument | undefined,
instanceHiddenParts: readonly string[],
): ReadonlySet<string> {
const hidden = new Set<string>(instanceHiddenParts.filter((part) => DECORATIVE_PART_IDS.has(part)));
const visible = new Set<string>(document?.visibleParts ?? []);
for (const part of DEFAULT_HIDDEN_HOST_PARTS) {
if (!visible.has(part)) hidden.add(part);
}
for (const part of document?.hiddenParts ?? []) hidden.add(part);
return hidden;
}
/** Compile-time path and size validation against the actual package contents. */
export function validateSkinChromeAssets(
document: SkinChromeDocument,
lookup: (path: string) => SkinChromeAssetInfo | undefined,
): void {
let total = 0;
for (const [slot, path] of Object.entries(document.icons)) {
const asset = lookup(path);
if (!asset) return reject(`Icon bitmap is missing from the package: ${path}`, "SKIN_ICON_MISSING");
if (!asset.mime.startsWith("image/") || asset.mime === "image/svg+xml") {
return reject(`Icon bitmap is not a supported raster image: ${path}`, "SKIN_ICON_INVALID");
}
if (!asset.bytes || asset.bytes > SKIN_ICON_MAX_BYTES) {
return reject(`Icon bitmap ${path} exceeds ${SKIN_ICON_MAX_BYTES / 1024} KiB.`, "SKIN_ICON_SIZE");
}
total += asset.bytes;
if (total > SKIN_ICONS_MAX_TOTAL_BYTES) {
return reject(`All icon bitmaps together exceed ${SKIN_ICONS_MAX_TOTAL_BYTES / 1024} KiB.`, "SKIN_ICON_SIZE");
}
void slot;
}
}
/** Instance-level default: comma/space separated optional part names, or a JSON array. */
export function parseHiddenHostParts(value: unknown): string[] {
const entries = typeof value === "string"
? value.split(/[\s,]+/)
: Array.isArray(value) ? value : [];
const result: string[] = [];
for (const entry of entries) {
if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) continue;
if (!result.includes(entry) && result.length < SKIN_CHROME_MAX_HIDDEN_PARTS) result.push(entry);
}
return result;
}
function cssString(value: string): string {
return value.replace(/["\\\n\r]/g, (character) => `\\${character}`);
}
/**
* Generate host-owned CSS. It is appended to the compiled skin CSS by the
* importer, so `wskin-asset:` markers are resolved together with author CSS.
* The document-level scope reaches both the skin root and Teleported host
* chrome, while never selecting arbitrary html/body content.
*/
export function compileSkinChromeCss(document: SkinChromeDocument, skinId: string): string {
const scope = `:root[${HOST_SKIN_ATTRIBUTE}="${cssString(skinId)}"]`;
const rules: string[] = [];
for (const part of document.hiddenParts) {
rules.push(`${scope} [data-ws-part="${cssString(part)}"] { display: none !important; }`);
}
for (const [slot, path] of Object.entries(document.icons)) {
const target = `${scope} [data-ws-icon-slot="${cssString(slot)}"]`;
rules.push(`${target} { background-image: url("wskin-asset:${encodeURIComponent(path)}") !important; background-position: center !important; background-repeat: no-repeat !important; background-size: contain !important; }`);
rules.push(`${target} > * { visibility: hidden !important; }`);
}
return rules.length ? rules.join("\n") + "\n" : "";
}
+341
View File
@@ -0,0 +1,341 @@
import assert from "node:assert/strict";
import test from "node:test";
import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js";
import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js";
import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js";
import {
compileSkinChromeCss,
DEFAULT_HIDDEN_HOST_PARTS,
parseHiddenHostParts,
parseSkinChromeDocument,
resolveHiddenHostParts,
SKIN_ICON_MAX_BYTES,
validateSkinChromeAssets,
} from "./skin-chrome.js";
const assets = new Set<string>();
const compile = (css: string, version: 1 | 2 | 3 | 4 = 3, id = "demo-skin") =>
compileSkinCss(css, id, assets, version);
test("the CSS hide whitelist and the layout decorative registry are one shared set", () => {
assert.deepEqual([...OPTIONAL_VISUAL_PARTS].sort(), [...DECORATIVE_PART_IDS].sort());
assert.deepEqual([...LAYOUT_DECORATIVE].sort(), [...DECORATIVE_PART_IDS].sort());
for (const part of ["host.watermark", "host.hint", "host.voice-status-decoration", "home.footer.decoration"]) {
assert.ok(OPTIONAL_VISUAL_PARTS.has(part), `${part} must be hideable`);
}
// home.footer contains the necessary "clear local data" link: only its
// decorative children may be hidden, never the container.
assert.equal(OPTIONAL_VISUAL_PARTS.has("home.footer"), false);
assert.ok(PROTECTED_PART_IDS.has("home.footer"), "the footer container must not be hidden");
assert.ok(PROTECTED_PART_IDS.has("home.footer.clear"));
// Decorative password-dialog children stay hideable: existing skins rely on it.
for (const part of ["auth.password.decoration", "auth.password.eyebrow", "auth.password.lead", "auth.password.label", "auth.password.field-icon"]) {
assert.equal(PROTECTED_PART_IDS.has(part), false, `${part} must stay hideable`);
}
for (const part of ["auth.password.dialog", "auth.password.form", "auth.password.field", "auth.password.error", "auth.password.actions"]) {
assert.ok(PROTECTED_PART_IDS.has(part), `${part} must be protected`);
}
// A screen-share exit button is a control but not part of the essential audio
// path; v3 skins may still hide it, so it is not in the protected set.
assert.equal(PROTECTED_PART_IDS.has("voice.screen-player.exit"), false);
// The load-failure banner and the library recovery entry are distinct parts.
assert.ok(PROTECTED_PART_IDS.has("app.skin-load-recovery"));
assert.ok(PROTECTED_PART_IDS.has("host.recovery"));
});
test("host chrome selectors compile into the document-level host scope", () => {
const themed = compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }');
assert.match(themed.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/);
assert.doesNotMatch(themed.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/);
const scoped = compile('[data-ws-part="host.plugins.launcher"]:hover { color: white; }');
assert.match(scoped.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]:hover/);
const overlay = compile('[data-ws-part="host.plugins.overlay"] { border-color: red; }');
assert.match(overlay.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.overlay"\]/);
// Ordinary page parts keep the original skin-root scope.
const page = compile('[data-ws-part="home.header"] { color: teal; }');
assert.match(page.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="home\.header"\]/);
assert.doesNotMatch(page.css, /data-ws-host-skin/);
});
test("the extended scope cannot escape to html/body or host internals", () => {
const rejected: Array<[string, RegExp]> = [
['html [data-ws-part="host.watermark"] { color: red; }', /cannot target html or body/],
['body [data-ws-part="host.watermark"] { color: red; }', /cannot target html or body/],
['[data-ws-host-skin] [data-ws-part="host.watermark"] { color: red; }', /host attribute/],
['[data-ws-route="webclient"] [data-ws-part="host.watermark"] { color: red; }', /host attribute/],
['[data-ws-part="home.header"] [data-ws-part="host.watermark"] { color: red; }', /cannot be mixed/],
['[data-ws-part="host.recovery"] { display: none; }', /Trusted or unknown host part/],
['[data-ws-part="host.permission"] { display: none; }', /Trusted or unknown host part/],
['[data-ws-part="host.unknown"] { color: red; }', /Trusted or unknown host part/],
[':root { --ws-internal-token: red; }', /--skin- prefix/],
['[data-ws-part="host.hint"] { behavior: url(x.htc); }', /Executable CSS/],
['[data-ws-part="host.hint"] { background: url("https://example.invalid/x.png"); }', /Only relative paths/],
];
for (const [css, message] of rejected) {
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
}
assert.throws(() => compile('[data-ws-part="host.watermark"] { color: red; }', 1), /requires an open/);
assert.throws(() => compile('[data-ws-part="host.watermark"] { color: red; }', 2), /requires an open/);
});
test("a leading :root cannot escape the skin root through a sibling combinator", () => {
// `:root` is rewritten in place, so these become `.ws-skin-root … ~ …` and
// would select the body-level host layer in the preview/fixture topology.
for (const css of [
':root ~ [data-ws-host-layer] { display: none !important; }',
':root ~ * { display: none !important; }',
':root ~ div { pointer-events: none !important; }',
':root + [data-ws-host-layer] { display: none; }',
':root + * { visibility: hidden; }',
':root:hover ~ * { display: none !important; }',
':ROOT ~ * { display: none !important; }',
]) {
assert.throws(() => compile(css), /sibling combinator after :root/, css);
}
// Descendant scoping (the documented form) still compiles into the skin root.
const descendant = compile(':root [data-ws-part="home.header"] { color: teal; }');
assert.match(descendant.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="home\.header"\]/);
// `>` and the descendant combinator are not sibling escapes.
assert.doesNotThrow(() => compile(':root > [data-ws-part="home.header"] { color: teal; }'));
assert.doesNotThrow(() => compile(':root { --skin-accent: #4c8f88; }'));
});
test("host-owned layer attributes are not skin hooks", () => {
for (const attribute of [
"data-ws-host-layer",
"data-ws-host-recovery",
"data-ws-host-layer-content",
"data-ws-recovery-action",
]) {
// A public hook in the same selector gets past the "must use a public hook"
// check, so the attribute-name rejection is what stops the selector.
assert.throws(() => compile(`:root [${attribute}] { display: none; }`), /host attribute/, attribute);
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute);
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}="x"] { color: red; }`), /host attribute/, attribute);
}
// Normal descendant theming of a public part remains accepted.
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }'));
});
test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => {
for (const part of [
"voice.audio-dock",
"voice.audio-dock.microphone",
"voice.audio-dock.output",
"voice.connection-status",
"voice.audio-status",
"voice.connection-status.reconnect",
"home.security-note",
"home.footer",
"home.footer.clear",
"app.toast",
]) {
const mustNameSubject = (error: unknown) => error instanceof Error
&& error.message.includes(`"${part}"`)
&& /must remain available/.test(error.message);
assert.throws(() => compile(`[data-ws-part="${part}"] { display: none; }`), mustNameSubject, part);
assert.throws(() => compile(`[data-ws-part="${part}"] { opacity: 0; }`), mustNameSubject, part);
}
// Existing skins legitimately hide a decorative child *inside* the audio
// dock; only the dock/control subject itself is protected.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }'));
// Hiding the screen-share exit button is a visual choice, not an essential
// audio/recovery path: v3 skins may still do it. Legacy v1/v2 skins keep the
// layout guard, so this cannot be used as a positioning attack.
assert.doesNotThrow(() => compile('[data-ws-part="voice.screen-player.exit"] { display: none; }'));
assert.throws(() => compile('[data-ws-part="voice.screen-player.exit"] { display: none; }', 1), /must not change layout/);
// Explicitly optional decorations remain hideable.
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { display: none; }'));
assert.doesNotThrow(() => compile('[data-ws-part="home.footer.decoration"] { visibility: hidden; }'));
});
test("chrome.json declares hidden parts and icon bitmaps, with path and size validation", () => {
const valid = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
hiddenParts: ["host.watermark", "host.hint", "host.watermark"],
icons: { "language.trigger": "assets/icons/language.png", "host.plugins.launcher": "assets/icons/apps.png" },
}));
assert.deepEqual(valid.hiddenParts, ["host.watermark", "host.hint"]);
assert.equal(valid.icons["language.trigger"], "assets/icons/language.png");
assert.equal(valid.visibleParts, undefined);
const optedIn = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
visibleParts: ["host.watermark", "host.hint", "host.watermark"],
}));
assert.deepEqual(optedIn.visibleParts, ["host.watermark", "host.hint"]);
const lookup = (path: string) => path.endsWith(".png") ? { bytes: 128, mime: "image/png" } : undefined;
assert.doesNotThrow(() => validateSkinChromeAssets(valid, lookup));
const generated = compileSkinChromeCss(valid, "demo-skin");
assert.match(generated, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.watermark"\] \{ display: none !important; \}/);
assert.match(generated, /\[data-ws-icon-slot="language\.trigger"\] \{ background-image: url\("wskin-asset:assets%2Ficons%2Flanguage\.png"\)/);
assert.match(generated, /\[data-ws-icon-slot="language\.trigger"\] > \* \{ visibility: hidden/);
const invalidDocuments: Array<[unknown, RegExp]> = [
[{ schemaVersion: 2, hiddenParts: [] }, /schemaVersion 1/],
[{ schemaVersion: 1, hiddenParts: ["voice.audio-dock"] }, /explicitly optional/],
[{ schemaVersion: 1, hiddenParts: ["host.recovery"] }, /explicitly optional/],
[{ schemaVersion: 1, hiddenParts: ["home.footer"] }, /explicitly optional/],
[{ schemaVersion: 1, visibleParts: ["voice.audio-dock"] }, /explicitly optional/],
[{ schemaVersion: 1, icons: { "unknown.slot": "assets/icons/x.png" } }, /Unknown icon slot/],
[{ schemaVersion: 1, icons: { "language.trigger": "../escape.png" } }, /assets\/icons/],
[{ schemaVersion: 1, icons: { "language.trigger": "assets/icons/x.svg" } }, /SVG is not allowed/],
[{ schemaVersion: 1, icons: { "language.trigger": "https://example.invalid/x.png" } }, /assets\/icons/],
[{ schemaVersion: 1, extra: true }, /unsupported field/],
];
for (const [value, message] of invalidDocuments) {
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
}
assert.throws(() => validateSkinChromeAssets(valid, () => undefined), /missing from the package/);
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: SKIN_ICON_MAX_BYTES + 1, mime: "image/png" })), /exceeds/);
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/);
});
test("instance-level hidden parts ignore unknown and protected names", () => {
assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]);
assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]);
assert.deepEqual(parseHiddenHostParts(undefined), []);
});
test("host-scope CSS cannot make the document root the subject of a hiding rule", () => {
for (const css of [
// The verified escape: the root is promoted to the host scope but still the subject.
':root:has([data-ws-part="host.watermark"]) { display: none; }',
':root:has([data-ws-part="host.hint"]) { visibility: hidden; }',
'[data-ws-part="host.watermark"] :root { display: none; }',
'*:has([data-ws-part="host.watermark"]) { display: none; }',
'html:has([data-ws-part="host.watermark"]) { display: none; }',
'body:has([data-ws-part="host.watermark"]) { display: none; }',
'[data-ws-part="host.watermark"] + body { display: none; }',
]) {
assert.throws(() => compile(css), /must start from a themeable|document root|cannot target html or body/, css);
}
// Legitimate host-part theming still compiles into the document-level scope.
const launcher = compile('[data-ws-part="host.plugins.launcher"] { color: white; }');
assert.match(launcher.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/);
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"]:has(span) { color: red; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] [data-ws-icon-slot="host.plugins.launcher"] { opacity: .5; }'));
});
test("protected controls cannot be hidden through variables or moved off-screen", () => {
assert.throws(
() => compile(':root { --skin-hide: none; } [data-ws-part="voice.audio-dock"] { display: var(--skin-hide); }'),
/cannot use indirect values/,
);
assert.throws(
() => compile('[data-ws-part="voice.audio-dock"] { position: fixed; left: -9999px; }'),
/must remain on screen/,
);
assert.throws(
() => compile('[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }'),
/must remain on screen/,
);
assert.throws(
() => compile('[data-ws-part="voice.audio-dock"] { inset: 0 0 0 -120vw; }'),
/must remain on screen/,
);
// Large negative margins are the same escape as an inset: reject the pattern
// generically, including longhands, shorthand, relative units and calc().
for (const css of [
'[data-ws-part="voice.audio-dock"] { margin-left: -9999px; }',
'[data-ws-part="voice.audio-dock"] { margin-inline: -9999px; }',
'[data-ws-part="voice.audio-dock"] { margin-block-start: -1200px; }',
'[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }',
'[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }',
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }',
'[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }',
]) {
assert.throws(() => compile(css), /must remain on screen/, css);
}
assert.throws(
() => compile(':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock"] { margin-left: var(--skin-pull); }'),
/cannot use indirect values/,
);
// Ordinary appearance tokens and optional decorations keep working.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { background: var(--skin-panel); }'));
assert.doesNotThrow(() => compile(':root { --skin-hide: none; } [data-ws-part="host.watermark"] { display: var(--skin-hide); }'));
// A small margin on a protected control and a decorative dock child are still
// legitimate v3 theming.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }'));
// The off-screen guard only protects the subject, not decorative or
// non-protected parts.
assert.doesNotThrow(() => compile('[data-ws-part="home.header"] { margin-left: -9999px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }'));
});
test("host chrome cannot be restyled into a viewport-sized overlay", () => {
assert.throws(
() => compile('[data-ws-part="host.plugins.overlay"] { position: fixed; inset: 0; z-index: 2147483647; }'),
/layout is owned by WebSpeak/,
);
assert.throws(() => compile('[data-ws-part="host.watermark"] { position: fixed; }'), /layout is owned by WebSpeak/);
assert.throws(() => compile('[data-ws-part="host.plugins.overlay"] { width: 100vw; height: 100vh; }'), /fullscreen overlay/);
// Descendant rules are the same escape: `*` can turn the library contents
// into a viewport mask even when the shell itself is frozen.
for (const css of [
'[data-ws-part="host.plugins.overlay"] * { position: fixed; inset: 0; z-index: 2147483647; }',
'[data-ws-part="host.plugins.overlay"] * { width: 100vw; height: 100vh; }',
'[data-ws-part="host.plugins.overlay"] .ws-plugin-library { position: fixed; top: 0; left: 0; }',
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
]) {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
// zoom (and any comparable scaling) must not blow the shell up either.
for (const css of [
'[data-ws-part="host.plugins.overlay"] { zoom: 10; }',
'[data-ws-part="host.plugins.overlay"] * { zoom: 10; }',
'[data-ws-part="host.plugins.overlay"] { transform: scale(10); }',
]) {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
// Colors, borders, radius, shadows and artwork stay available, including on
// descendants of the overlay.
const themed = compile('[data-ws-part="host.plugins.overlay"] { border: 2px solid #1d4f9c; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px #0003; }');
assert.match(themed.css, /data-ws-part="host\.plugins\.overlay"/);
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { color: #fff; border-color: #1d4f9c; border-radius: 6px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }'));
});
test("official and built-in skins hide host decorations unless the active skin opts in", () => {
const decorations = ["host.watermark", "host.hint", "host.voice-status-decoration"];
assert.deepEqual([...DEFAULT_HIDDEN_HOST_PARTS].sort(), [...decorations].sort());
// Built-in skins ship no chrome.json: decorations are hidden, launcher stays.
const builtin = resolveHiddenHostParts(undefined, []);
for (const part of decorations) assert.ok(builtin.has(part), `${part} must be hidden for built-in skins`);
assert.equal(builtin.has("host.plugins.launcher"), false);
// An explicit opt-in shows them again; hiddenParts still wins.
const optedIn = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], visibleParts: decorations, icons: {} }, []);
for (const part of decorations) assert.equal(optedIn.has(part), false, `${part} must be visible after opting in`);
const explicitlyHidden = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.hint"], visibleParts: decorations, icons: {} }, []);
assert.ok(explicitlyHidden.has("host.hint"));
// hiddenParts-only chrome.json is not an opt-in: decorations stay hidden.
// This is the production path that previously reported a false positive
// because the appended chrome CSS itself contained `data-ws-part="host.…"`.
const hiddenOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.plugins.launcher"], icons: {} }, []);
for (const part of decorations) assert.ok(hiddenOnly.has(part), `${part} must stay hidden for a hiddenParts-only pack`);
assert.ok(hiddenOnly.has("host.plugins.launcher"));
const watermarkOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.watermark"], icons: {} }, []);
for (const part of decorations) assert.ok(watermarkOnly.has(part), `${part} must stay hidden when only watermark is declared`);
// chrome.json alone (for example an icon-only override) is not an opt-in.
const iconOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], icons: {} }, []);
for (const part of decorations) assert.ok(iconOnly.has(part), `${part} must stay hidden without visibleParts`);
// Instance defaults cannot be re-enabled by a skin.
const instanceHidden = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], visibleParts: decorations, icons: {} }, ["host.watermark"]);
assert.ok(instanceHidden.has("host.watermark"));
});
+290 -24
View File
@@ -1,6 +1,14 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import {
DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS,
HOST_CHROME_PART_IDS,
HOST_SKIN_ATTRIBUTE,
PROTECTED_PART_IDS,
} from "./skin-visual-parts.js";
export { OPTIONAL_VISUAL_PARTS };
export type SkinCssSchemaVersion = 1 | 2 | 3 | 4;
export type SkinCssAssets = Readonly<Record<string, unknown>> | Map<string, unknown> | Set<string>;
@@ -36,25 +44,55 @@ const LAYOUT_AFFECTING_PROPERTIES = new Set([
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
]);
const OPTIONAL_VISUAL_PARTS = new Set([
"home.hero.eyebrow",
"home.gateway-status",
"home.features",
"home.feature",
"home.visitors",
"home.join-card.waveform",
"home.join-card.sonar",
"voice.activity-heading",
"voice.member.avatar",
"voice.member.live-indicator",
"voice.member-row.avatar",
"voice.screen-player.viewer-avatar",
"voice.screen-player.live",
"demo.badge",
"demo.wave",
"demo.avatar",
"demo.member-status",
"demo.note",
/**
* Properties that let a skin move a host-chrome part into a viewport-sized
* overlay or out from under the host's own layout. Appearance properties
* (colors, borders, radius, shadows, artwork) stay available.
*/
const HOST_CHROME_LOCKED_PROPERTIES = new Set([
"all", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
"inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end",
"z-index", "transform", "translate", "scale", "rotate", "zoom", "float", "clear",
"clip", "clip-path", "mask", "mask-image", "perspective", "contain",
]);
/**
* The plugin library shell additionally owns its footprint: without a locked
* size a skin could still stretch it over the recovery entry even though
* `position`/`inset`/`z-index` are frozen.
*/
const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([
...HOST_CHROME_LOCKED_PROPERTIES,
"width", "height", "min-width", "min-height", "max-width", "max-height",
"inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size",
"aspect-ratio", "margin", "margin-block", "margin-inline", "margin-block-start", "margin-block-end",
"margin-inline-start", "margin-inline-end",
]);
/** Properties whose indirect values could smuggle a hidden or moved control past the static checks. */
const INDIRECT_VALUE_PROPERTIES = new Set([
"all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image",
"position", "top", "right", "bottom", "left", "inset",
"inset-block", "inset-inline", "inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end",
"transform", "translate", "scale", "rotate", "zoom",
// Margins move a subject just like insets do; a variable could resolve to a
// viewport-sized negative value, so protected controls may not use them.
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left",
"margin-block", "margin-block-start", "margin-block-end",
"margin-inline", "margin-inline-start", "margin-inline-end",
]);
/** Attributes a skin author must never use to reach outside the public hooks. */
const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
HOST_SKIN_ATTRIBUTE,
"data-ws-skin",
"data-ws-route",
"data-theme",
"data-ws-hidden-host-parts",
// Host-owned recovery layer internals. They are deliberately not skin hooks,
// and naming them keeps `:root [data-ws-host-layer]` / mixed selectors from
// opting into the element by attribute.
"data-ws-host-layer",
"data-ws-host-recovery",
"data-ws-host-layer-content",
"data-ws-recovery-action",
]);
export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
@@ -67,6 +105,12 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
// Host chrome is Teleported outside `.ws-skin-root`. Rules that target only
// registered host parts use a second, document-level scope anchored to an
// attribute the host sets while this exact skin is active. Author CSS never
// names html/body: the host generates the scope itself.
const hostSkinScope = `:root[${HOST_SKIN_ATTRIBUTE}="${id}"]`;
const hostScopeNodes = selectorParser().astSync(hostSkinScope).first!.nodes.map((node) => node.clone());
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
@@ -117,12 +161,15 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const text = selector.toString().trim();
if (!text) throw new SkinCssValidationError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinCssValidationError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
const hostScope = assertHostChromeSelector(text, schemaVersion, Boolean(pluginId));
const activeScope = hostScope ? hostSkinScope : scope;
const activeNodes = hostScope ? hostScopeNodes : scopeNodes;
if (/^:root\b/.test(text)) {
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, activeScope)).first!.clone());
return;
}
selector.prepend(selectorParser.combinator({ value: " " }));
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
for (let index = activeNodes.length - 1; index >= 0; index -= 1) selector.prepend(activeNodes[index].clone());
});
}).processSync(rule.selector);
} catch (error) {
@@ -157,6 +204,7 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
root.walkDecls((declaration: Declaration) => {
const property = decodeCssEscapes(declaration.prop).toLowerCase();
const unprefixedProperty = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
const value = declaration.value.trim();
const decodedValue = decodeCssEscapes(value);
const owningRule = findOwningRule(declaration);
@@ -164,6 +212,16 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
// Trusted UI and essential audio/recovery controls stay available even for
// open skins. The host also draws authorization and recovery UI outside the
// skin root, so a container-level hide cannot remove them either.
const protectedTarget = owningRule && !keyframesRule ? selectorSubjectProtectedPart(owningRule.selector) : null;
// Every themeable host part referenced anywhere in the selector. A rule may
// target a descendant of the overlay (for example with `*`), so the subject
// alone is not enough to decide whether host chrome layout is at stake.
const hostChromeParts = owningRule && !keyframesRule ? selectorHostChromeParts(owningRule.selector) : [];
const inHostChromeScope = hostChromeParts.length > 0;
const inOverlayScope = hostChromeParts.includes("host.plugins.overlay");
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
@@ -173,13 +231,26 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
}
// Host chrome lives outside the skin root and owns its own placement. A
// skin may repaint it (colors, borders, radius, artwork) but must not turn
// it — or any of its descendants — into a viewport-sized overlay above
// authorization/recovery UI.
if (inHostChromeScope && HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls.");
}
if (inOverlayScope && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
throw declaration.error("Executable CSS values are not allowed.");
}
const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase();
if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
if (protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
}
if (!canHideTarget && schemaVersion < 3) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
}
const removesVisual = property === "all"
|| (property === "display" && compactValue === "none")
@@ -188,16 +259,25 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
|| (property === "pointer-events" && compactValue === "none")
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
if (removesVisual && protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`);
}
if (removesVisual && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
}
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue))
|| (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue))
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue));
if (visuallyRemoves && protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" must remain visible.`);
}
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
}
if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`);
}
if (schemaVersion >= 3 && removesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
@@ -250,6 +330,136 @@ function selectorUsesPublicHook(selector: string, allowCustomClasses = false): b
}
}
/**
* A leading `:root` is rewritten in place to `.ws-skin-root[data-ws-skin=…]`.
* With a sibling combinator (`+` / `~`) that would select siblings of the
* skin root — for example the host-owned layer, which is a body child and a
* sibling of the skin root in the preview fixture. Skin scope must only apply
* to the root's own subtree, so reject that shape structurally. A leading
* `:root` followed by a descendant combinator (`:root [data-ws-part="…"]`)
* remains valid.
*/
function assertNoRootSiblingEscape(parsed: selectorParser.Root): void {
for (const item of parsed.nodes) {
const first = item.nodes[0];
if (!first || first.type !== "pseudo" || first.value.toLowerCase() !== ":root") continue;
const combinator = item.nodes.find((node) => node.type === "combinator");
if (combinator && (combinator.value === "+" || combinator.value === "~")) {
throw new SkinCssValidationError(
"Skin selectors cannot use a sibling combinator after :root; the scope must stay inside the skin root.",
"SKIN_CSS_SELECTOR",
);
}
}
}
/**
* Decide whether one selector of an author rule targets host chrome, and
* enforce the boundary around the extended document-level scope.
*
* Returns true when the compiled rule must use `:root[data-ws-host-skin=…]`.
* Author CSS can never name html/body or the host marker attribute itself; the
* host generates that anchor. Host parts are only available to open (v3/v4)
* skins and may not be mixed with page parts in the same selector.
*/
function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchemaVersion, isPluginStyle: boolean): boolean {
let parsed: selectorParser.Root;
try { parsed = selectorParser().astSync(selector); }
catch { throw new SkinCssValidationError("A CSS selector is invalid.", "SKIN_CSS_SELECTOR"); }
assertNoRootSiblingEscape(parsed);
const partNames: string[] = [];
parsed.walk((node) => {
if (node.type === "tag" && ["html", "body"].includes(node.value.toLowerCase())) {
throw new SkinCssValidationError("Skin selectors cannot target html or body elements.", "SKIN_CSS_SELECTOR");
}
if (node.type === "attribute" && FORBIDDEN_SCOPE_ATTRIBUTES.has(node.attribute.toLowerCase())) {
throw new SkinCssValidationError(`Skin selectors cannot reference the host attribute ${node.attribute}.`, "SKIN_CSS_SELECTOR");
}
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
partNames.push(node.value.replace(/^['"]|['"]$/g, ""));
}
});
const hostParts = partNames.filter((part) => HOST_CHROME_PART_IDS.has(part));
const unknownHostParts = partNames.filter((part) => part.startsWith("host.") && !HOST_CHROME_PART_IDS.has(part));
if (unknownHostParts.length) {
throw new SkinCssValidationError(`Trusted or unknown host part cannot be styled: ${unknownHostParts[0]}.`, "SKIN_CSS_SELECTOR");
}
if (!hostParts.length) return false;
if (hostParts.length !== partNames.length) {
throw new SkinCssValidationError("Host chrome parts cannot be mixed with page parts in one selector.", "SKIN_CSS_SELECTOR");
}
if (isPluginStyle) throw new SkinCssValidationError("Plugin styles cannot target host chrome parts.", "SKIN_CSS_SELECTOR");
if (schemaVersion < 3) throw new SkinCssValidationError("Host chrome theming requires an open (schemaVersion 3 or 4) skin.", "SKIN_CSS_SELECTOR");
assertHostChromeSubject(parsed);
return true;
}
/**
* A host-scope rule is promoted to the document root. To keep that promotion
* from turning the root/html/body (or an arbitrary ancestor) into the rule's
* subject, every host-scope selector must be anchored on a themeable host part
* in its first compound and must never end in `:root`.
*/
function assertHostChromeSubject(parsed: selectorParser.Root): void {
for (const item of parsed.nodes) {
if (!item.nodes.length) continue;
const firstCombinator = item.nodes.findIndex((node) => node.type === "combinator");
if (firstCombinator === 0) {
throw new SkinCssValidationError("Host chrome rules must start from a themeable host part.", "SKIN_CSS_SELECTOR");
}
const firstCompound = firstCombinator === -1 ? item.nodes : item.nodes.slice(0, firstCombinator);
const anchored = firstCompound.some((node) => node.type === "attribute"
&& node.attribute.toLowerCase() === "data-ws-part"
&& HOST_CHROME_PART_IDS.has((node.value ?? "").replace(/^['"]|['"]$/g, "")));
if (!anchored) {
throw new SkinCssValidationError("Host chrome rules must start from a themeable [data-ws-part=\"host.…\"] selector; the document root cannot be themed or hidden.", "SKIN_CSS_SELECTOR");
}
let subjectStart = 0;
for (let index = item.nodes.length - 1; index >= 0; index -= 1) {
if (item.nodes[index].type === "combinator") { subjectStart = index + 1; break; }
}
for (let index = subjectStart; index < item.nodes.length; index += 1) {
const node = item.nodes[index];
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") {
throw new SkinCssValidationError("Host chrome rules cannot make the document root the subject of a rule.", "SKIN_CSS_SELECTOR");
}
}
}
}
/** Find a protected part in the subject (last compound) of any selector in a rule. */
function selectorSubjectProtectedPart(selector: string): string | null {
try {
const parsed = selectorParser().astSync(selector);
for (const item of parsed.nodes) {
let start = 0;
for (let index = item.nodes.length - 1; index >= 0; index -= 1) {
if (item.nodes[index].type === "combinator") { start = index + 1; break; }
}
for (let index = start; index < item.nodes.length; index += 1) {
const node = item.nodes[index];
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) continue;
const part = node.value.replace(/^['"]|['"]$/g, "");
if (PROTECTED_PART_IDS.has(part)) return part;
}
}
} catch { /* A malformed selector is rejected elsewhere. */ }
return null;
}
/** Find every themeable host part referenced by a selector, in any compound. */
function selectorHostChromeParts(selector: string): string[] {
const parts: string[] = [];
try {
selectorParser().astSync(selector).walk((node) => {
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) return;
const part = node.value.replace(/^['"]|['"]$/g, "");
if (HOST_CHROME_PART_IDS.has(part) && !parts.includes(part)) parts.push(part);
});
} catch { /* A malformed selector is rejected elsewhere. */ }
return parts;
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
@@ -259,6 +469,62 @@ function isLayoutAffectingProperty(property: string): boolean {
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
}
/**
* True when a positioning/margin/transform value can push a protected control
* off-screen. Thresholds are deliberately low: a protected control has a
* minimum 44 px hit target, so an offset of a hundred pixels is already enough
* to make it unreachable. Percentages and viewport units are compared against a
* full viewport/containing block.
*/
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform|scale|rotate)(?:-|$)/;
const ABSOLUTE_OFFSET_LIMIT_PX = 100;
const RELATIVE_OFFSET_LIMIT = 100;
function absoluteLengthToPixels(magnitude: number, unit: string): number | null {
switch (unit) {
case "px": return magnitude;
case "rem": case "em": return magnitude * 16;
case "ex": case "rex": case "ch": return magnitude * 8;
case "cm": return magnitude * 37.8;
case "mm": return magnitude * 3.78;
case "q": return magnitude * 0.945;
case "in": return magnitude * 96;
case "pt": return magnitude * 1.333;
case "pc": return magnitude * 16;
default: return null;
}
}
function valueMovesOffscreen(property: string, value: string): boolean {
if (!OFFSET_PROPERTY_PATTERN.test(property)) return false;
let offscreen = false;
valueParser(value).walk((node) => {
if (node.type !== "word") return;
const match = /^(-?(?:\d+|\d*\.\d+))(px|rem|em|r?ex|ch|%|cm|mm|q|in|pt|pc|(?:s|l|d)?v(?:w|h|min|max)|cq(?:w|h|min|max|i|b))$/i.exec(node.value);
if (!match) return;
const magnitude = Math.abs(Number(match[1]));
const unit = match[2].toLowerCase();
if (unit === "%" || /^(?:s|l|d)?v(?:w|h|min|max)$/.test(unit) || /^cq(?:w|h|min|max|i|b)$/.test(unit)) {
if (magnitude >= RELATIVE_OFFSET_LIMIT) offscreen = true;
return;
}
const pixels = absoluteLengthToPixels(magnitude, unit);
if (pixels !== null && pixels >= ABSOLUTE_OFFSET_LIMIT_PX) offscreen = true;
});
// A matrix transform can smuggle a large translation in unitless numbers.
if (property === "transform") {
valueParser(value).walk((node) => {
if (node.type !== "function") return;
const name = node.value.toLowerCase();
if (name !== "matrix" && name !== "matrix3d") return;
const numbers = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
const translations = name === "matrix" ? [numbers[4], numbers[5]] : [numbers[12], numbers[13]];
if (translations.some((translation) => Number.isFinite(translation) && Math.abs(translation) >= ABSOLUTE_OFFSET_LIMIT_PX)) offscreen = true;
});
}
return offscreen;
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
+31 -15
View File
@@ -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");
+36 -33
View File
@@ -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",
@@ -278,6 +274,10 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.favorite-servers.tooltip",
"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",
@@ -321,6 +321,11 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.screen-player.viewers",
"voice.screen-player.volume",
"voice.screen-share-error",
"voice.invite.backdrop",
"voice.invite.dialog",
"voice.invite.form",
"voice.invite.create",
"voice.invite.copy",
"voice.screen-share-settings",
"voice.screen-share-settings.actions",
"voice.screen-share-settings.fields",
@@ -330,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",
@@ -373,8 +369,10 @@ 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",
"voice.connection-status.nickname.input", "voice.connection-status.reconnect",
"demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select",
"demo.chat.input", "demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss",
@@ -392,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",
@@ -402,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 {
@@ -444,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 {
+17 -2
View File
@@ -15,7 +15,7 @@ export const SKIN_PLUGIN_PERMISSIONS = Object.freeze({
"ui.surface.replace": Object.freeze({ policyVersion: 1, description: "Replace the built-in public page with a custom skin surface; the host recovery controls remain available." }),
"ui.input.read": Object.freeze({ policyVersion: 1, description: "Read values entered or autofilled in this plugin's own input fields. Never enter passwords or other secrets." }),
"session.status.read": Object.freeze({ policyVersion: 1, description: "Read the current connection and channel summary." }),
"session.invite.copy": Object.freeze({ policyVersion: 1, description: "Copy a WebSpeak invite link for the current public server and channel; credentials are excluded." }),
"session.invite.copy": Object.freeze({ policyVersion: 1, description: "Open the trusted invitation dialog for the current session; ticket creation, expiry and credentials remain host-owned." }),
"session.channels.read": Object.freeze({ policyVersion: 1, description: "Read the public TeamSpeak channel tree; the demo page uses synthetic sample data." }),
"session.members.read": Object.freeze({ policyVersion: 1, description: "Read visible member names, initials derived from those names, and speaking states; the demo page uses synthetic sample data." }),
"session.memberAvatars.read": Object.freeze({ policyVersion: 1, description: "Display cached TeamSpeak profile pictures for visible members inside trusted host member-card or channel-tree widgets. Images are not exposed to skin markup or plugin runtimes." }),
@@ -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 } : {}),
};
+155
View File
@@ -0,0 +1,155 @@
/**
* Single source of truth for the public skin part policy.
*
* `skin-css.ts` (CSS hiding whitelist), `skin-layout.ts` (layout editor
* metadata) and `skin-chrome.ts` (declarative host chrome document) all read
* these sets so a part can never be "hideable" in one layer and protected in
* another. Adding a part here is the only way to make it explicitly optional.
*/
/** Password dialog parts are trusted in both the CSS and layout layers. */
export const AUTH_PASSWORD_PART_IDS = [
"auth.password.backdrop",
"auth.password.dialog",
"auth.password.decoration",
"auth.password.eyebrow",
"auth.password.title",
"auth.password.lead",
"auth.password.form",
"auth.password.label",
"auth.password.field",
"auth.password.field-icon",
"auth.password.error",
"auth.password.actions",
] as const;
/**
* Host chrome is drawn by WebSpeak outside `.ws-skin-root` (Teleport to body)
* or is painted by the host with fixed artwork. A skin may theme these parts,
* but only through the dedicated document-level host scope, never with a
* global `html` / `body` selector.
*/
export const HOST_CHROME_PART_IDS: ReadonlySet<string> = new Set([
"host.plugins.launcher",
"host.plugins.overlay",
"host.watermark",
"host.hint",
"host.voice-status-decoration",
]);
/** Host parts that must stay reachable and can never be hidden or themed. */
export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
"host.recovery",
"host.permission",
]);
/** All host-owned parts (used by the part registry and documentation). */
export const HOST_PART_IDS: ReadonlySet<string> = new Set([
...HOST_CHROME_PART_IDS,
...HOST_TRUSTED_PART_IDS,
]);
/**
* Explicitly optional (decorative) visual parts. Both `OPTIONAL_VISUAL_PARTS`
* in the CSS compiler and `DECORATIVE_PART_IDS` in the layout registry are
* aliases of this set.
*
* `home.footer` is deliberately absent: the footer contains the necessary
* "clear local data" recovery link. The purely decorative text is split into
* `home.footer.decoration`, which is the part that may be hidden.
*/
export const DECORATIVE_PART_IDS: ReadonlySet<string> = new Set([
"demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave",
"demo.member-status",
"home.feature", "home.features", "home.footer.decoration", "home.hero.eyebrow",
"home.gateway-status", "home.join-card.sonar", "home.join-card.waveform", "home.visitors",
"voice.activity.artwork", "voice.activity-heading", "voice.member.avatar",
"voice.member.avatar-wrap", "voice.member.live-indicator", "voice.member-row.avatar",
"voice.performance.metrics", "voice.performance.webrtc-stats",
"voice.screen-player.viewer-avatar", "voice.screen-player.live",
"host.watermark", "host.hint", "host.voice-status-decoration", "host.plugins.launcher",
]);
/** Trusted host UI: authorization, connection status, identity and recovery. */
export const TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
...AUTH_PASSWORD_PART_IDS,
...HOST_TRUSTED_PART_IDS,
"app",
"app.toast",
"app.skin-load-recovery",
"home.security-note",
"home.identity-import.security",
"voice.connection-status",
"voice.screen-share-error",
]);
/**
* Parts that even an open (v3/v4) skin must never visually remove: the
* permission/recovery entries and the essential audio operation path.
*
* This is deliberately narrower than `TRUSTED_PART_IDS`: trusted metadata also
* covers decorative children of the password dialog (`auth.password.decoration`,
* `auth.password.eyebrow`, `auth.password.lead`, `auth.password.label`,
* `auth.password.field-icon`), which existing skins legitimately hide. Only the
* dialog shell, form, field, error and action row are protected.
*/
export const PROTECTED_PART_IDS: ReadonlySet<string> = new Set([
"app",
"app.toast",
"app.skin-load-recovery",
"home.security-note",
"home.identity-import.security",
// The footer container holds the necessary "clear local data" recovery
// link; only its decorative children may be hidden.
"home.footer",
"home.footer.clear",
"voice.connection-status",
"voice.connection-status.reconnect",
"voice.connection-status.nickname.input",
"voice.audio-status",
"voice.audio-dock",
"voice.audio-dock.microphone",
"voice.audio-dock.output",
"voice.audio-dock.microphone-panel",
"voice.audio-dock.output-panel",
"voice.audio-settings",
"voice.screen-share-error",
"voice.mobile-nav",
"voice.mobile-more",
"demo.reconnect.restore",
"auth.password.dialog",
"auth.password.form",
"auth.password.field",
"auth.password.error",
"auth.password.actions",
"host.recovery",
"host.permission",
]);
/** Stable icon bitmap slots. `chrome.json` may only reference these names. */
export const SKIN_ICON_SLOT_IDS: ReadonlySet<string> = new Set([
"host.plugins.launcher",
"language.trigger",
"skin.trigger",
"voice.performance",
"home.toolbar.settings",
]);
export function isHostChromePart(part: string): boolean {
return HOST_CHROME_PART_IDS.has(part);
}
export function isHostPart(part: string): boolean {
return HOST_PART_IDS.has(part) || part.startsWith("host.");
}
export function isDecorativePart(part: string): boolean {
return DECORATIVE_PART_IDS.has(part);
}
export function isProtectedPart(part: string): boolean {
return PROTECTED_PART_IDS.has(part);
}
/** Document-level marker set by the host while a custom skin is active. */
export const HOST_SKIN_ATTRIBUTE = "data-ws-host-skin";
+2 -2
View File
@@ -1,7 +1,7 @@
apply plugin: 'com.android.application'
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.0'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 300
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"
+214
View File
@@ -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>&nbsp;&nbsp;👤 Demo User</p><p>&nbsp;&nbsp;♫ 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>
+2 -2
View File
@@ -25,7 +25,7 @@
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
},
"version": "0.3.0"
"version": "0.3.2"
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
@@ -2952,5 +2952,5 @@
}
}
},
"version": "0.3.0"
"version": "0.3.2"
}
+1 -1
View File
@@ -27,5 +27,5 @@
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
},
"version": "0.3.0"
"version": "0.3.2"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+104
View File
@@ -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.`);
+252
View File
@@ -0,0 +1,252 @@
<template>
<!-- Host chrome is intentionally outside .ws-skin-root so a v3 surface
replacement cannot delete the recovery path or the authorization UI. -->
<Teleport to="body">
<div class="ws-host-chrome" data-ws-host-chrome>
<div
v-if="!isHostPartHidden('host.watermark')"
class="ws-host-watermark"
data-ws-part="host.watermark"
aria-hidden="true"
>WebSpeak</div>
<p
v-if="!isHostPartHidden('host.hint')"
class="ws-host-hint"
data-ws-part="host.hint"
>{{ copy.hint }}</p>
<div
v-if="!isHostPartHidden('host.voice-status-decoration')"
class="ws-host-voice-status-decoration"
data-ws-part="host.voice-status-decoration"
aria-hidden="true"
><span></span><span></span></div>
</div>
</Teleport>
<!-- Trusted recovery entry. It lives in a closed shadow root and a manual
popover, so no compiled skin selector can target it (shadow boundary)
and no normal stacking context can cover it (top layer). It carries no
`data-ws-part`: there is intentionally no skin hook for this control. -->
<Teleport v-if="layer" :to="layer.container">
<div
ref="recoveryPopover"
popover="manual"
class="ws-host-recovery"
data-ws-host-recovery
role="region"
:aria-label="copy.recovery"
>
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
<button
type="button"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
type="button"
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 {
isHostPartHidden,
isHostPartVisuallyReachable,
isRecoveryShortcut,
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
syncRecoveryPopover,
type HostOwnedLayer,
} from "../services/host-owned-layer.js";
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
import { thirdPartyAllowed } from "../services/instance-authorization.js";
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; 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 #9db6b2;
border-radius: 999px;
background: color-mix(in srgb, #ffffff 92%, transparent);
color: #31524f;
box-shadow: 0 6px 18px #0f2a2626;
pointer-events: auto;
}
.ws-host-recovery:popover-open { display: flex; }
.ws-host-recovery-mark { font-size: 12px; line-height: 1; }
.ws-host-recovery button {
display: inline-flex;
align-items: center;
min-height: 28px;
padding: 4px 9px;
border: 1px solid #9db6b2;
border-radius: 999px;
background: #fff;
color: #31524f;
font: inherit;
cursor: pointer;
white-space: nowrap;
}
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
border-color: #b45309;
background: #fff7ed;
color: #7c2d12;
}
.ws-host-recovery button:hover { filter: brightness(.96); }
.ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { .ws-host-recovery button { transition: none; } }
`;
const layer: HostOwnedLayer | null = createHostOwnedLayer("recovery", RECOVERY_LAYER_CSS);
// CSS-only hiding is invisible to `isHostPartHidden`, so sample the launcher's
// live geometry. A one-second interval is enough for a recovery fallback and
// stays cheaper than a MutationObserver on the whole document. While a
// third-party skin is active the entry is persistent and this sample only
// matters for the official-skin fallback.
const launcherReachable = ref(true);
const showRecovery = computed(() => shouldShowRecovery({
connected: props.connected && 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);
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
}
function useBuiltInSkin() {
shortcutOpen.value = false;
requestBuiltInSkin();
}
function openLibrary() {
shortcutOpen.value = false;
openPluginLibrary();
}
function onKeydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.repeat || !thirdPartyAllowed.value) return;
if (isRecoveryShortcut(event)) {
event.preventDefault();
shortcutOpen.value = true;
void nextTick(() => recoveryPopover.value?.querySelector("button")?.focus());
return;
}
if (event.key === "Escape" && shortcutOpen.value) shortcutOpen.value = false;
}
let reachabilityTimer: ReturnType<typeof setInterval> | undefined;
function refreshLauncherReachability() {
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
}
watch([recoveryVisible, recoveryPopover], () => { void nextTick(syncPopover); }, { flush: "post" });
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
onMounted(() => {
refreshLauncherReachability();
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown);
void nextTick(syncPopover);
});
onBeforeUnmount(() => {
if (reachabilityTimer) clearInterval(reachabilityTimer);
window.removeEventListener("resize", refreshLauncherReachability);
window.removeEventListener("keydown", onKeydown);
layer?.dispose();
});
</script>
<style scoped>
.ws-host-chrome {
position: fixed;
inset: 0;
z-index: 0;
overflow: hidden;
pointer-events: none;
}
.ws-host-watermark {
position: absolute;
top: clamp(8px, 6vh, 64px);
right: clamp(12px, 3vw, 64px);
color: #8ab9cf;
font: 800 clamp(40px, 7vw, 104px)/1 ui-sans-serif, system-ui, sans-serif;
letter-spacing: -.06em;
opacity: .14;
user-select: none;
white-space: nowrap;
}
.ws-host-hint {
position: absolute;
bottom: calc(10px + env(safe-area-inset-bottom));
left: 14px;
max-width: min(46vw, 420px);
margin: 0;
color: #6d8b88;
font: 11px/1.4 ui-sans-serif, system-ui, sans-serif;
opacity: .8;
user-select: none;
}
.ws-host-voice-status-decoration {
position: absolute;
top: 0;
right: 0;
display: flex;
align-items: center;
gap: 8px;
width: min(28vw, 320px);
height: 28px;
padding: 0 12px;
opacity: .28;
}
.ws-host-voice-status-decoration span {
display: block;
height: 6px;
border-radius: 3px;
background: #95b6b1;
}
.ws-host-voice-status-decoration span:first-child { width: 64px; }
.ws-host-voice-status-decoration span:last-child { flex: 1; opacity: .6; }
@media (max-width: 640px) {
.ws-host-hint { max-width: 62vw; }
.ws-host-voice-status-decoration { display: none; }
}
</style>
+18 -9
View File
@@ -1,5 +1,9 @@
<template>
<Teleport to="body">
<!-- The authorization dialog is host-owned trusted UI: it is rendered in a
closed shadow root and promoted with showModal(), so compiled skin CSS
cannot select, restyle, cover or disable it. It deliberately carries no
`data-ws-part`; there is no skin hook for this dialog. -->
<Teleport v-if="layer" :to="layer.container">
<dialog ref="dialog" class="ws-instance-authorization" @cancel.prevent="cancel" @close="authorizationRequested = false">
<form @submit.prevent="save">
<div class="ws-authorization-mark" aria-hidden="true">◈</div>
@@ -20,6 +24,18 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue';
import type { SiteLanguage } from '../../../src/site-copy.js';
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
import { createHostOwnedLayer, type HostOwnedLayer } from '../services/host-owned-layer.js';
const AUTHORIZATION_LAYER_CSS = `
:host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:inherit;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
`;
const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHORIZATION_LAYER_CSS);
const props = defineProps<{ language: SiteLanguage }>();
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
const copy = computed(() => instanceAuthorizationCopy[props.language]);
@@ -34,12 +50,5 @@ function finish() { authorizationRequested.value = false; dialog.value?.close();
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
function decline() { setInstanceAuthorization(false); finish(); }
function cancel() { if (firstVisit.value) decline(); else finish(); }
onBeforeUnmount(() => dialog.value?.close());
onBeforeUnmount(() => { dialog.value?.close(); layer?.dispose(); });
</script>
<style>
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:14px/1.75 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto}
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
</style>
+2 -1
View File
@@ -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;
}>(), {
+117 -37
View File
@@ -1,11 +1,29 @@
<template>
<Teleport :to="toolbarTarget ?? 'body'">
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" 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>
<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">
<button ref="launcher" class="ws-plugin-launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
<span>{{ tr('title') }}</span><i v-if="current" />
</button>
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
<section v-show="visible" ref="windowElement" class="ws-plugin-window" data-ws-part="host.plugins.overlay" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
<div class="ws-plugin-window-title"><strong>{{ current && appView ? current.manifest.name : tr('title') }}</strong><small>WebSpeak</small></div>
@@ -15,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>
@@ -43,26 +61,35 @@
</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';
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 toolbar = ref<HTMLElement | null>(null);
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 launcherPosition = 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; kind: 'window' | 'launcher'; moved: boolean } | undefined;
let suppressLauncherClick = false, resizeObserver: ResizeObserver | undefined;
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; moved: boolean } | undefined;
let resizeObserver: ResizeObserver | undefined;
const browserFeatures = computed(() => {
const policy = (document as Document & { featurePolicy?: { features(): string[] } }).featurePolicy;
const features = policy?.features() ?? ['fullscreen', 'autoplay', 'camera', 'microphone', 'display-capture', 'clipboard-read', 'clipboard-write', 'geolocation', 'screen-wake-lock'];
@@ -84,41 +111,81 @@ async function refresh() {
finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
}
function toggle() {
if (suppressLauncherClick) { suppressLauncherClick = false; return; }
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 (current.value?.manifest.id === id) { appView.value = true; 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; 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'); }
}
function appearance() { if (current.value && opening) void opening.client.appearance(current.value.id, theme.value, props.language).catch(() => undefined); }
function fitWindow() {
if (launcher.value && launcherPosition.value.left) {
const box = launcher.value.getBoundingClientRect();
launcherPosition.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, right: 'auto', bottom: 'auto' };
}
if (!visible.value || maximized.value || !windowElement.value) return;
const box = windowElement.value.getBoundingClientRect();
position.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, transform: 'none' };
@@ -128,35 +195,48 @@ function startDrag(event: PointerEvent) {
if (event.button !== 0 || maximized.value || (event.target as HTMLElement).closest('button')) return;
const box = windowElement.value?.getBoundingClientRect(); if (!box) return;
event.preventDefault(); const handle = event.currentTarget as HTMLElement;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, kind: 'window', moved: false }; dragging.value = true;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, moved: false }; dragging.value = true;
handle.setPointerCapture(event.pointerId);
}
function startLauncherDrag(event: PointerEvent) {
if (event.button !== 0 || !launcher.value) return;
const box = launcher.value.getBoundingClientRect(); suppressLauncherClick = false;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle: launcher.value, kind: 'launcher', moved: false };
launcher.value.setPointerCapture(event.pointerId);
}
function moveDrag(event: PointerEvent) {
if (!drag || drag.id !== event.pointerId) return;
const target = drag.kind === 'launcher' ? launcher.value : windowElement.value; if (!target) return;
const target = windowElement.value; if (!target) return;
if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5 && !drag.moved) return;
drag.moved = true; const box = target.getBoundingClientRect();
const next = { left: `${Math.max(8, Math.min(drag.left + event.clientX - drag.x, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(drag.top + event.clientY - drag.y, innerHeight - box.height - 8))}px`, transform: 'none' };
if (drag.kind === 'launcher') launcherPosition.value = { ...next, right: 'auto', bottom: 'auto' }; else position.value = next;
position.value = next;
}
function endDrag() {
const old = drag; drag = undefined; dragging.value = false;
if (old?.kind === 'launcher' && old.moved) suppressLauncherClick = true;
if (old?.handle.hasPointerCapture(old.id)) old.handle.releasePointerCapture(old.id);
}
watch(windowElement, element => { resizeObserver?.disconnect(); if (element) { resizeObserver = new ResizeObserver(fitWindow); resizeObserver.observe(element); } });
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, close);
watch(thirdPartyAllowed, allowed => { if (!allowed) close(); }, { flush: 'sync' });
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, () => {
close();
if (props.connected && thirdPartyAllowed.value) void refresh();
});
watch(thirdPartyAllowed, allowed => {
if (!allowed) close();
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();
});
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);
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
if (props.connected && thirdPartyAllowed.value) void refresh();
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">
<section v-if="error" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
<p>{{ labels.skinLoadError(error.skinId) }}</p>
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
</section>
+10 -1
View File
@@ -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;
+115 -5
View File
@@ -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,19 +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>
@@ -43,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='';}
@@ -63,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>
+12 -13
View File
@@ -50,15 +50,14 @@
@input="onInputVolume"
/>
<div class="dock-panel-divider"></div>
<label class="dock-switch-row"
><span
><strong>{{ t("noiseSuppression") }}</strong></span
><input
type="checkbox"
:checked="noiseSuppressionEnabled"
:aria-label="t('noiseSuppression')"
@change="onNoiseSuppressionToggle"
/></label>
<label class="dock-switch-row">
<span><strong>{{ t("noiseSuppression") }}</strong></span>
<select class="noise-suppression-level" :value="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>
</select>
</label>
</div>
</div>
<div
@@ -132,12 +131,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" | "noiseSuppressionEnabled" | "accompanimentActive">;
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionToggle" | "toggleAccompaniment">;
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
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, noiseSuppressionEnabled, accompanimentActive } = props.model;
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionToggle, toggleAccompaniment } = props.controls;
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
const emit = defineEmits<{ settings: []; outputMute: [] }>();
</script>
@@ -76,16 +76,14 @@
/>
{{ microphoneMuted ? t("unmuteMic") : t("muteMic") }}</button
></div
><label
class="noise-suppression-toggle settings-form-row"
><span
><strong>{{ t("noiseSuppression") }}</strong
><small>{{ t("noiseSuppressionHint") }}</small></span
><input
type="checkbox"
:checked="noiseSuppressionEnabled"
:aria-label="t('noiseSuppression')"
@change="onNoiseSuppressionToggle" /></label
><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">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label
><div class="settings-form-row settings-range-form-row"
><label class="settings-label">{{ t("inputVolume") }}</label
><div class="settings-form-control"
@@ -265,7 +263,7 @@ type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
| "audioPermission"
| "audioContextState"
| "microphoneMuted"
| "noiseSuppressionEnabled"
| "noiseSuppressionLevel"
| "inputVolume"
| "outputVolume"
| "voxThreshold"
@@ -277,7 +275,7 @@ type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
type AudioSettingsControls = Pick<ReturnType<typeof useWebClientAudioControls>,
| "settingsError"
| "onInputVolume"
| "onNoiseSuppressionToggle"
| "onNoiseSuppressionChange"
| "onOutputVolume"
| "onVoxThreshold"
| "onNotificationVolume"
@@ -310,7 +308,7 @@ const {
audioPermission,
audioContextState,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
outputVolume,
voxThreshold,
@@ -322,7 +320,7 @@ const {
const {
settingsError: audioSettingsError,
onInputVolume,
onNoiseSuppressionToggle,
onNoiseSuppressionChange,
onOutputVolume,
onVoxThreshold,
onNotificationVolume,
@@ -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"
@@ -33,15 +34,21 @@
><div
><strong>{{ t("voiceStatus") }}</strong
><small>{{ t("voiceStatusHint") }}</small></div
><button
><div class="performance-panel-tools"><button
type="button"
class="performance-refresh"
:title="t('exportAudioTrace')"
:aria-label="t('exportAudioTrace')"
:disabled="!traceEvents.length"
@click="exportTrace"
><Icon name="download" :size="15" /></button><button
type="button"
class="performance-refresh"
:title="t('measureNow')"
:aria-label="t('measureNow')"
:disabled="performanceRunning"
@click="refreshPerformanceProbe"
><Icon
name="refresh"
:size="15" /></button
><Icon name="refresh" :size="15" /></button></div
></header>
<div
class="voice-status-summary"
@@ -147,6 +154,7 @@
: t("voiceStatusWaiting")
}}</p
>
<p class="performance-status">{{ t("backgroundVoiceHint") }} · {{ t("audioTraceHint") }}</p>
<section
v-if="showScreenShare && screenShareWebRtcStats.peers.length"
class="webrtc-stats"
@@ -224,7 +232,7 @@ import type { useWebClientPerformance } from "../../composables/useWebClientPerf
import type { ScreenShareWebRtcStats } from "../../composables/useVoiceWebSocket.js";
const props = defineProps<{ model: ReturnType<typeof useWebClientPerformance>; screenShareWebRtcStats: ScreenShareWebRtcStats; showScreenShare?: boolean; t: (key: string) => string }>();
const showScreenShare = props.showScreenShare !== false;
const { panelOpen: performancePanelOpen, running: performanceRunning, stats: performanceStats, togglePanel: togglePerformancePanel, refresh: refreshPerformanceProbe } = props.model;
const { panelOpen: performancePanelOpen, running: performanceRunning, stats: performanceStats, traceEvents, togglePanel: togglePerformancePanel, refresh: refreshPerformanceProbe, exportTrace } = props.model;
const root = ref<HTMLElement | null>(null);
const trigger = ref<HTMLButtonElement | null>(null);
const t = props.t;
@@ -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')"
@@ -0,0 +1,54 @@
<template>
<div class="modal-backdrop workspace-invite-backdrop" data-ws-part="voice.invite.backdrop" @click.self="emit('close')">
<section ref="dialog" class="channel-password-modal workspace-invite-dialog" data-ws-part="voice.invite.dialog" tabindex="-1" role="dialog" aria-modal="true" aria-labelledby="workspace-invite-title" @keydown="onDialogKeydown">
<button class="qq-modal-close" type="button" :aria-label="t('close')" @click="emit('close')">×</button>
<h2 id="workspace-invite-title">{{ t('workspaceInviteTitle') }}</h2>
<p>{{ t('workspaceInviteLead') }}</p>
<form class="channel-password-form" data-ws-part="voice.invite.form" @submit.prevent="generate">
<label>{{ t('workspaceInviteExpiry') }}<input v-model.number="minutes" type="number" min="1" max="43200" required :disabled="busy" /></label>
<label>{{ t('workspaceInviteServerPassword') }}<input v-model="serverPassword" type="password" maxlength="512" autocomplete="off" :disabled="busy" /></label>
<label>{{ t('workspaceInvitePassword') }}<input v-model="password" type="password" maxlength="512" autocomplete="off" :disabled="busy" /></label>
<p v-if="error" role="alert">{{ error }}</p>
<button class="primary-button" data-ws-part="voice.invite.create" type="submit" :disabled="busy">{{ t('workspaceInviteCreate') }}</button>
</form>
<div v-if="link" class="workspace-invite-result" aria-live="polite">
<input :value="link" readonly :aria-label="t('workspaceInviteCopy')" @focus="($event.target as HTMLInputElement).select()" />
<small>{{ t('workspaceInviteExpiresAt') }} {{ new Date(expiresAt).toLocaleString() }}</small>
<button class="primary-button" data-ws-part="voice.invite.copy" type="button" @click="copy">{{ copied ? t('copiedToast') : t('workspaceInviteCopy') }}</button>
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useDialogFocus } from "../../composables/useDialogFocus.js";
const props = defineProps<{ t: (key: string) => string; create: (minutes: number, password: string, serverPassword: string) => Promise<{ token: string; expiresAt: number }> }>();
const emit = defineEmits<{ close: [] }>();
const dialog = ref<HTMLElement | null>(null);
const { onDialogKeydown } = useDialogFocus(dialog, () => emit("close"));
const minutes = ref(1440), password = ref(""), serverPassword = ref(""), busy = ref(false), error = ref(""), link = ref(""), expiresAt = ref(0), copied = ref(false);
async function generate() {
if (busy.value) return;
busy.value = true; error.value = ""; link.value = ""; copied.value = false;
try {
const result = await props.create(minutes.value, password.value, serverPassword.value);
const url = new URL("/", location.origin); url.searchParams.set("invite", result.token);
link.value = url.toString(); expiresAt.value = result.expiresAt; password.value = ""; serverPassword.value = "";
} catch { error.value = props.t("workspaceInviteError"); }
finally { busy.value = false; }
}
async function copy() {
try { await navigator.clipboard.writeText(link.value); copied.value = true; }
catch { error.value = props.t("copyFailedToast"); }
}
</script>
<style scoped>
.workspace-invite-backdrop { z-index: 2147483000 !important; }
.workspace-invite-dialog .primary-button { width: 100%; min-height: 44px; padding: 10px 16px; font: inherit; font-weight: 600; border-radius: 10px; }
.workspace-invite-dialog { max-width: min(520px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); overflow: auto; }
.workspace-invite-dialog h2 { color: inherit !important; }
.workspace-invite-dialog p { line-height: 1.6; }
.workspace-invite-dialog label, .workspace-invite-result { display: grid; gap: 10px; margin-block: 14px; }
.workspace-invite-dialog input { box-sizing: border-box; width: 100%; min-width: 0; padding: 11px 12px; border: 1px solid currentColor; border-radius: 10px; background: transparent; color: inherit; font: inherit; }
.workspace-invite-result small { overflow-wrap: anywhere; }
</style>
+113 -8
View File
@@ -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;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,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,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};
}
+2
View File
@@ -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");
}
+18 -4
View File
@@ -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";
@@ -31,17 +32,25 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
let disposed = false;
const owns = (operation: ReturnType<typeof createSkinOperation>) => !disposed && current === operation;
function cancel() { current?.cancel(); current = undefined; }
function begin() {
function begin(timeoutMs = options.timeoutMs) {
cancel();
return current = createSkinOperation({ timeoutMs: options.timeoutMs });
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();
if (!canUseSkin(id)) id = fallbackId();
const entry = catalogSkins.value.find(skin => skin.id === id);
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal }));
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal, timeoutMs: operation.timeoutMs }));
if (!owns(operation)) return;
if (!builtin(id) && !skin) throw new Error("The selected skin could not be activated.");
activeSkin.value = skin;
@@ -89,7 +98,8 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
}
async function select(id: string) {
if (disposed) return;
const operation = begin();
// A user-selected package can take longer to download on a cold cache.
const operation = begin(options.timeoutMs ?? (builtin(id) ? undefined : 25_000));
try {
try { localStorage.setItem("webspeak:skin-choice", id); } catch { /* Optional storage. */ }
await apply(id, operation, true, true);
@@ -133,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))),
+87 -20
View File
@@ -10,6 +10,7 @@ import { createVoiceCommands } from "../voice/commands.js";
import { createVoiceSessionState } from "../voice/session-state.js";
import { applySavedMemberVolumes } from "../voice/member-volume-preferences.js";
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
import { createVoiceSessionTrace } from "../voice/session-trace.js";
export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
import type { SinkAudioElement } from "../voice/webrtc-playback.js";
import { createScreenShareController } from "../voice/screen-share.js";
@@ -20,7 +21,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 { reactive, ref, shallowRef } from "vue";
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
export interface VoiceState {
@@ -197,6 +198,7 @@ class CancelledMediaOperation extends Error {
}
export function useVoiceWebSocket() {
const sessionTrace = createVoiceSessionTrace();
const ws = shallowRef<WebSocket | null>(null);
const serverInfo = shallowRef<VoiceServerInfo | null>(null);
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
@@ -215,10 +217,12 @@ export function useVoiceWebSocket() {
const { members, channels, chatMessages, serverEvents, pokeNotifications } = sessionState;
let chatGeneration = 0;
const voiceConnection = createVoiceConnection({
onSocket: socket => { ws.value = socket; },
onSocket: socket => { ws.value = socket; sessionTrace.record("gateway.socket", { state: socket ? "connecting" : "closed" }); },
onSocketOpen: () => sessionTrace.record("gateway.socket", { state: "open" }),
onMessage: handleMessage,
onAudio: handleAudioFrame,
onClose(event) {
sessionTrace.record("gateway.socket.closed", { code: event.code, clean: event.wasClean });
releaseSessionResources();
state.connected = false;
state.connecting = false;
@@ -235,6 +239,7 @@ export function useVoiceWebSocket() {
onFailure({ code, detail, cause }) {
state.connecting = false;
state.errorCode = normalizedClientErrorCode(code, "REQUEST_FAILED");
sessionTrace.record("gateway.connection.failed", { code: state.errorCode });
state.error = cause instanceof Error ? cause.message : joinTicketReason(state.errorCode, detail);
},
});
@@ -302,9 +307,10 @@ export function useVoiceWebSocket() {
onError: error => { setMicrophoneError(error); },
});
const microphoneMuted = ref(false);
const noiseSuppressionEnabled = ref(true);
const noiseSuppressionLevel = ref<"off" | "standard" | "strong">("strong");
const noiseSuppressionEnabled = computed(() => noiseSuppressionLevel.value !== "off");
let noiseSuppressionTouched = false;
let committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
let committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
const inputVolume = ref(1);
const outputVolume = ref(1);
const outputMuted = ref(false);
@@ -352,9 +358,14 @@ export function useVoiceWebSocket() {
if (rms !== null && !microphoneMuted.value && track.enabled && rms >= voxThreshold.value) markSpeaking(state.tsClientId);
else if (state.tsClientId) clearSpeaking(state.tsClientId);
},
onReady: syncWebRtcMemberVolumes,
onReady() {
sessionTrace.record("webrtc.media", { state: "active" });
syncWebRtcMemberVolumes();
},
onConnectionState(stateName) { sessionTrace.record("webrtc.connection", { state: stateName }); },
async onFallback(reason, isCurrent) {
if (!isCurrent()) return;
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
try { await startMicrophone(); }
catch (error) { if (isCurrent()) setMicrophoneError(error); }
@@ -403,7 +414,8 @@ export function useVoiceWebSocket() {
preferredInputDeviceId: committedInputDeviceId,
inputDeviceId: committedInputDeviceId,
microphoneMuted: microphoneMuted.value,
noiseSuppressionEnabled: committedNoiseSuppressionEnabled,
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
noiseSuppressionLevel: committedNoiseSuppressionLevel,
voxThreshold: voxThreshold.value,
inputGain: inputVolume.value,
outputVolume: outputVolume.value,
@@ -426,9 +438,15 @@ export function useVoiceWebSocket() {
committedInputDeviceId = selectedInputDeviceId.value;
}
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
if (!noiseSuppressionTouched && typeof preferences.noiseSuppressionEnabled === "boolean") {
noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
committedNoiseSuppressionEnabled = preferences.noiseSuppressionEnabled;
if (!noiseSuppressionTouched) {
const storedLevel = preferences.noiseSuppressionLevel;
if (storedLevel === "off" || storedLevel === "standard" || storedLevel === "strong") {
noiseSuppressionLevel.value = storedLevel;
committedNoiseSuppressionLevel = storedLevel;
} else if (typeof preferences.noiseSuppressionEnabled === "boolean") {
noiseSuppressionLevel.value = preferences.noiseSuppressionEnabled ? "strong" : "off";
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
}
}
if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08);
if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain));
@@ -482,7 +500,10 @@ export function useVoiceWebSocket() {
audioCtx = new AudioContext({ sampleRate: 48000 }) as SinkAudioContext;
audioContextState.value = audioCtx.state;
audioCtx.addEventListener("statechange", () => {
if (audioCtx) audioContextState.value = audioCtx.state;
if (audioCtx) {
audioContextState.value = audioCtx.state;
sessionTrace.record("audio.context", { state: audioCtx.state });
}
});
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"
|| typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
@@ -573,7 +594,7 @@ export function useVoiceWebSocket() {
sampleRate: { ideal: 48000 },
channelCount: { ideal: 1 },
echoCancellation: true,
noiseSuppression: noiseSuppressionEnabled.value,
noiseSuppression: noiseSuppressionLevel.value !== "off",
// Keep the microphone's natural dynamics. Browser AGC can make speech
// pump in volume, especially while background noise changes.
autoGainControl: false,
@@ -698,7 +719,7 @@ export function useVoiceWebSocket() {
factoryOwnsStream = true;
nextCapture = await microphoneCaptureFactory.prepare({
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
noiseSuppression: noiseSuppressionEnabled.value, volume: inputVolume.value, onSamples: handleCaptureChunk,
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
});
assertCurrent();
// Commit only a complete graph. Permission and node failures leave the
@@ -706,13 +727,21 @@ export function useVoiceWebSocket() {
stopMicrophone(false);
micStream = nextStream;
microphoneCapture = nextCapture;
const microphoneTrack = nextStream.getAudioTracks()[0];
if (microphoneTrack) {
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
recordTrack(microphoneTrack.readyState);
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
microphoneTrack.addEventListener("ended", () => recordTrack("ended"));
}
Object.assign(microphoneProcessing, nextCapture.processing);
nextCapture.setVolume(inputVolume.value);
nextCapture.activate();
// The fallback for a later failed change is this actual live graph, even
// if device enumeration or WebRTC negotiation is still in progress.
committedInputDeviceId = selectedInputDeviceId.value;
committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
clearMicrophoneError();
} catch (error) {
nextCapture?.dispose();
@@ -795,6 +824,7 @@ export function useVoiceWebSocket() {
pendingMicrophoneCapture = null;
}
stopCaptureGraph();
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
microphoneCapture?.dispose();
microphoneCapture = null;
webrtc.releaseInput();
@@ -834,13 +864,13 @@ export function useVoiceWebSocket() {
await refreshAudioDevices();
if (!isCurrent()) return;
committedInputDeviceId = selectedInputDeviceId.value;
committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
committedNoiseSuppressionLevel = noiseSuppressionLevel.value;
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
await saveAudioPreferences();
} catch (error) {
if (!isCurrent() || error instanceof CancelledMediaOperation) return;
selectedInputDeviceId.value = committedInputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
noiseSuppressionLevel.value = committedNoiseSuppressionLevel;
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
throw error;
}
@@ -1031,7 +1061,7 @@ export function useVoiceWebSocket() {
deviceListGeneration++;
selectedInputDeviceId.value = committedInputDeviceId;
selectedOutputDeviceId.value = committedOutputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
noiseSuppressionLevel.value = committedNoiseSuppressionLevel;
microphoneTest.dispose();
audioDiagnostics.reset();
commands.clear(new Error("语音连接已关闭"));
@@ -1057,6 +1087,7 @@ export function useVoiceWebSocket() {
};
break;
case "connected":
sessionTrace.record("teamspeak.session", { state: "connected" });
const wasReconnecting = state.reconnecting;
state.connected = true;
state.connecting = false;
@@ -1106,6 +1137,7 @@ export function useVoiceWebSocket() {
break;
}
case "disconnected":
sessionTrace.record("teamspeak.session", { state: "disconnected", recoverable: msg.recoverable !== false });
state.connected = false;
state.connecting = false;
state.reconnecting = Boolean(msg.recoverable !== false);
@@ -1114,6 +1146,7 @@ export function useVoiceWebSocket() {
releaseSessionResources();
break;
case "reconnecting":
sessionTrace.record("teamspeak.reconnect", { state: "retrying", attempt: Number(msg.attempt) || 0 });
state.connected = false;
state.connecting = false;
state.reconnecting = true;
@@ -1122,10 +1155,12 @@ export function useVoiceWebSocket() {
releaseSessionResources();
break;
case "reconnected":
sessionTrace.record("teamspeak.reconnect", { state: "restored" });
state.reconnecting = false;
state.reconnectFailed = false;
break;
case "reconnectFailed":
sessionTrace.record("teamspeak.reconnect", { state: "failed", code: normalizedClientErrorCode(msg.code) });
state.connected = false;
state.connecting = false;
state.reconnecting = false;
@@ -1135,6 +1170,7 @@ export function useVoiceWebSocket() {
releaseSessionResources();
break;
case "connectionFailed":
sessionTrace.record("teamspeak.session", { state: "connection-failed", code: normalizedClientErrorCode(msg.code) });
state.connected = false;
state.connecting = false;
state.reconnecting = false;
@@ -1168,6 +1204,11 @@ export function useVoiceWebSocket() {
}
}
break;
case "inviteCreated": {
createdInvite = { token: msg.token, expiresAt: msg.expiresAt };
commands.settle(msg.requestId ?? "");
break;
}
case "commandCompleted": {
const requestId = typeof msg.requestId === "string" ? msg.requestId : "";
commands.settle(requestId);
@@ -1175,6 +1216,7 @@ export function useVoiceWebSocket() {
}
case "error":
state.errorCode = normalizedClientErrorCode(msg.error?.code, "OPERATION_FAILED");
sessionTrace.record("teamspeak.session.error", { code: state.errorCode });
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
{
const requestId = typeof msg.requestId === "string" ? msg.requestId : "";
@@ -1195,16 +1237,29 @@ export function useVoiceWebSocket() {
return;
}
const clientId = (data[1] << 8) | data[2];
const codec = data[0];
if (clientId === state.tsClientId) return;
if (codec !== 4 && codec !== 5) {
audioDiagnostics.count("framesDropped");
return;
}
audioDiagnostics.count("framesReceived");
markSpeaking(clientId);
remotePlayback.play(clientId, data.slice(3));
remotePlayback.play(clientId, codec, data.slice(3));
}
function sendCmd<K extends ClientCommandType>(type: K, payload: ClientCommandPayloads[K]): void {
commands.send(type, payload);
}
let createdInvite: { token: string; expiresAt: number } | null = null;
async function createInvite(expiresInMinutes: number, channelPassword = "", serverPassword = ""): Promise<{ token: string; expiresAt: number }> {
createdInvite = null;
await sendCommandAndWait("createInvite", { expiresInMinutes, ...(channelPassword ? { channelPassword } : {}), ...(serverPassword ? { serverPassword } : {}) });
if (!createdInvite) throw new Error("Invitation was not created");
return createdInvite;
}
function sendCommandAndWait<K extends ClientCommandType>(type: K, payload: ClientCommandPayloads[K], timeoutMs = 8_000): Promise<void> {
return commands.sendAndWait(type, payload, timeoutMs);
}
@@ -1386,17 +1441,23 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
async function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
if (noiseSuppressionEnabled.value === enabled) return;
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
if (noiseSuppressionLevel.value === level) return;
noiseSuppressionTouched = true;
noiseSuppressionEnabled.value = enabled;
const previousLevel = noiseSuppressionLevel.value;
noiseSuppressionLevel.value = level;
try {
await reconfigureMicrophone();
} catch (error) {
noiseSuppressionLevel.value = previousLevel;
setMicrophoneError(error);
}
}
function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
return setNoiseSuppressionLevel(enabled ? (noiseSuppressionLevel.value === "off" ? "strong" : noiseSuppressionLevel.value) : "off");
}
function setOutputVolume(volume: number): void {
outputVolume.value = Math.max(0, Math.min(1, volume));
applyOutputVolume();
@@ -1418,6 +1479,8 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
onBeforeUnmount(() => sessionTrace.dispose());
return {
pluginSession,
...screenShare.api,
@@ -1433,6 +1496,7 @@ export function useVoiceWebSocket() {
pokeNotifications,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
outputVolume,
outputMuted,
@@ -1459,6 +1523,7 @@ export function useVoiceWebSocket() {
accompanimentErrorCode,
setVolume,
setInputVolume,
setNoiseSuppressionLevel,
setNoiseSuppressionEnabled,
setOutputVolume,
toggleOutputMute,
@@ -1473,6 +1538,7 @@ export function useVoiceWebSocket() {
playNotification,
connect,
reconnectNow,
createInvite,
disconnect,
switchChannel,
moveClient,
@@ -1490,5 +1556,6 @@ export function useVoiceWebSocket() {
checkSupport,
clearError,
measureVoiceAudioStatus,
sessionTrace,
};
}
@@ -1,9 +1,11 @@
import { computed, onScopeDispose, ref, watch, type Ref } from "vue";
import type { LocalPreferences } from "../services/local-persistence.js";
type NoiseSuppressionLevel = NonNullable<LocalPreferences["noiseSuppressionLevel"]>;
interface UseWebClientAudioControlsOptions {
settingsOpen: Ref<boolean>;
microphoneMuted: Readonly<Ref<boolean>>;
noiseSuppressionEnabled: Readonly<Ref<boolean>>;
noiseSuppressionLevel: Readonly<Ref<NoiseSuppressionLevel>>;
inputVolume: Readonly<Ref<number>>;
voxThreshold: Readonly<Ref<number>>;
notificationVolume: Readonly<Ref<number>>;
@@ -14,7 +16,7 @@ interface UseWebClientAudioControlsOptions {
whisperTargetIds: Set<number>;
prepareInputDevices: () => Promise<void>;
setInputVolume: (value: number) => void;
setNoiseSuppressionEnabled: (enabled: boolean) => Promise<void>;
setNoiseSuppressionLevel: (level: NoiseSuppressionLevel) => Promise<void>;
setOutputVolume: (value: number) => void;
setVoxThreshold: (value: number) => void;
setNotificationVolume: (value: number) => void;
@@ -34,7 +36,7 @@ interface UseWebClientAudioControlsOptions {
export function useWebClientAudioControls({
settingsOpen,
microphoneMuted,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
voxThreshold,
notificationVolume,
@@ -45,7 +47,7 @@ export function useWebClientAudioControls({
whisperTargetIds,
prepareInputDevices,
setInputVolume,
setNoiseSuppressionEnabled,
setNoiseSuppressionLevel,
setOutputVolume,
setVoxThreshold,
setNotificationVolume,
@@ -92,12 +94,13 @@ export function useWebClientAudioControls({
setInputVolume(Number((event.target as HTMLInputElement).value) / 100);
}
function onNoiseSuppressionToggle(event: Event): void {
void setNoiseSuppressionEnabled((event.target as HTMLInputElement).checked);
function onNoiseSuppressionChange(event: Event): void {
const level = (event.target as HTMLSelectElement).value;
if (level === "off" || level === "standard" || level === "strong") void setNoiseSuppressionLevel(level);
}
function toggleNoiseSuppression(): void {
void setNoiseSuppressionEnabled(!noiseSuppressionEnabled.value);
void setNoiseSuppressionLevel(noiseSuppressionLevel.value === "off" ? "strong" : "off");
}
function onOutputVolume(event: Event): void {
@@ -244,7 +247,7 @@ export function useWebClientAudioControls({
whisperPttActive,
micMeterBars,
onInputVolume,
onNoiseSuppressionToggle,
onNoiseSuppressionChange,
toggleNoiseSuppression,
onOutputVolume,
onVoxThreshold,
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more