Compare commits

...
17 Commits
Author SHA1 Message Date
illusia 001457d004 fix: validate merged voice fallback and host toolbar features 2026-11-27 08:53:26 +08:00
illusia 02509ea551 Merge PR #64: dock trusted recovery controls in skin toolbars
# Conflicts:
#	package.json
2026-11-27 08:42:18 +08:00
illusia b3104e1411 Merge PR #63: Cloudflare Tunnel voice and WebRTC fallback 2026-11-27 08:41:47 +08:00
OddTurtleHead b6e7b1e4da feat(voice): support Cloudflare Tunnel deployments and WebRTC fallback
Route page and signaling traffic through Cloudflare Tunnel while sending
WebRTC media over direct UDP, with optional TURN REST as a fallback.
When WebRTC was already offered and then fails, stay in the current
session, automatically resume compatibility audio, and keep a Reconnect
WebRTC control. A reconnect retries WebRTC only, leaves compatibility
running until it succeeds, and stays on compatibility if it fails again.

Database schema 14 adds nullable voice override columns and is a one-way
boundary: older binaries reject this database. This change is for review,
not a production rollout.
2026-11-26 23:47:50 +08:00
OddTurtleHead 4e8ea3081c fix(skin): repair host recovery compatibility and placement
Align the toolbar example with its first compatible runtime, restore recovery after shortcut focus leaves, and harden observer scheduling, contrast, floating avoidance, and private selector validation.
2026-11-26 23:06:43 +08:00
OddTurtleHead df826f575e feat(skin): match Classic toolbar icon buttons for host recovery
Add slot appearance "icon" and "icon-and-label", allow an explicit 22px
toolbar height, preserve transparent backgrounds, and introduce hover,
surface, gap, and icon-size tokens so host-owned recovery and library
buttons can match the Classic microphone control. Shortcut and failed-
anchor fallbacks stay full label capsules. Update the example skin, docs,
and tests, including a Classic toolbar fixture.
2026-11-26 23:06:43 +08:00
OddTurtleHead 4131d9c319 fix(skin): keep split fallback capsule clear of docked toolbars at 320px
The library toolbar falls back to the floating capsule when its docked footprint would cover the built-in toolbar in split mode. The fallback was positioned by light-DOM floating avoidance, which cannot see toolbars inside the closed shadow root, so it could land on the still-docked built-in button and hide/cover the library action (GUI retest at 318/320px). Exclude docked toolbar footprints from floating positions, give the slotted capsule the same sibling guard, and assert real elementFromPoint hit testing plus rect disjointness in the 320px iframe fixture.
2026-11-26 23:06:43 +08:00
OddTurtleHead e5c891fc94 fix(skin): verify real launcher dedup and keep split recovery tappable at 320px
- Fall back an overlapping docked recovery toolbar to the visible capsule so
  split built-in/library buttons never cover each other on narrow screens.
- Add browser fixtures mounting real HostChrome + real PluginPanel for group,
  split and legacy capsule modes, including a genuine 320px iframe viewport.
- Assert the real launcher is suppressed by toolbar slots and never duplicated
  after a bad-anchor fallback, with both split toolbars observable and clickable.
2026-11-26 23:06:43 +08:00
OddTurtleHead cfbf488f75 fix(skin): match macOS recovery shortcut by physical key code and forbid toolbar hook attribute 2026-11-26 23:06:43 +08:00
OddTurtleHead 881354e283 feat(skin): dock recovery as host-owned toolbar buttons
Add chrome.json slot mode "toolbar" with grouped and per-action recovery buttons, page-specific anchor candidates and sanitized toolbar style tokens. Keep the floating capsule as the bad-anchor fallback, hide the duplicate plugin launcher, and preserve legacy capsule slots. Document the full contract, add a minimal toolbar example package, and cover the new behavior in unit and browser tests.
2026-11-26 23:06:43 +08:00
illusia 9a12e2ee7b fix(release): package native files for console updates 2026-11-26 16:39:11 +08:00
illusia 3e4be94ae7 release: prepare v0.3.3 2026-11-26 16:30:40 +08:00
illusia 3339d09936 test(updater): stop recovery processes before removing fixtures 2026-11-26 16:20:55 +08:00
illusia 462bab57d2 fix(updater): honor launcher recovery locks during initialization 2026-11-26 16:20:03 +08:00
illusia 6bbc292056 fix(updater): lock launcher recovery and cancel failed downloads 2026-11-26 16:17:08 +08:00
ILLUSIA e3c71f07b1 Merge pull request #62 from OddTurtleHead/fix/updater-recovery-consistency
fix(updater): preserve recovery consistency across interrupted updates
2026-11-26 16:05:42 +08:00
OddTurtleHead cf1cc9fb94 fix(updater): preserve recovery consistency across interrupted updates
Keep health checks, rollback reporting, launcher recovery, and download failure handling consistent so verified updates cannot report false success or crash during recoverable I/O failures.
2026-11-25 23:51:16 +08:00
125 changed files with 8343 additions and 427 deletions

No files matched your search

@@ -25,6 +25,7 @@ When a WebSpeak checkout is unavailable, read the [published skin guide](https:/
- 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.
- To fold recovery into a skin top bar, declare `chrome.json#slots` with `"mode": "toolbar"` (one grouped entry) or the independent `host.recovery.built-in` / `host.recovery.library` keys. Supply page-specific anchor candidates and `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*` tokens; never target the host toolbar DOM. The host keeps the button labels, click handlers, minimum hit target and floating-capsule fallback, and hides the ordinary plugin launcher so the library has one entry. See [Host chrome toolbar example](../../../docs/examples/HOST-CHROME-TOOLBAR.md).
- 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
+33 -2
View File
@@ -9,7 +9,7 @@ on:
version:
description: Release version without the v prefix
required: true
default: 0.3.2
default: 0.3.3
type: string
permissions:
@@ -214,7 +214,38 @@ jobs:
grep -q '"status":"ok"' <<<"$health"
grep -q "\"version\":\"$release_version\"" <<<"$health"
)
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
# Native rebuilds can leave hard-linked objects and Python/toolchain
# symlinks in scratch directories. Ship independent files and keep
# build-only scratch paths out of the portable runtime archive.
tar --hard-dereference \
--exclude='*/@discordjs/opus/build-tmp-*' \
--exclude='*/node_gyp_bins' \
-czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
# Verify the shipped tarball is accepted by the same extractor and
# package validator used by console updates, including .bin links.
node --input-type=module - "$GITHUB_WORKSPACE/${package_name}.tar.gz" "$RUNNER_TEMP/${package_name}-updater-check" "$release_version" <<'NODE'
import path from 'node:path';
import { rm } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
import { extractReleaseArchive } from './dist/updater/archive.js';
import { locatePackageRoot } from './dist/updater/code-swap.js';
const [archive, destination, version] = process.argv.slice(2);
try {
await extractReleaseArchive(archive, destination, path.basename(archive));
const root = locatePackageRoot(destination, version, 'linux');
const nativeSmoke = spawnSync(path.join(root, 'runtime', 'node'), ['--input-type=commonjs', '-e', `
const { OpusEncoder } = require('@discordjs/opus');
const encoder = new OpusEncoder(48000, 2);
const packet = encoder.encode(Buffer.alloc(3840));
if (encoder.decode(packet).length !== 3840) throw new Error('Packaged Opus codec failed');
`], { cwd: root, encoding: 'utf8', timeout: 15000 });
if (nativeSmoke.error) throw nativeSmoke.error;
if (nativeSmoke.status !== 0) throw new Error(nativeSmoke.stderr || 'Packaged Opus runtime failed');
console.log(`Console updater accepts ${path.basename(archive)}`);
} finally {
await rm(destination, { recursive: true, force: true });
}
NODE
- uses: actions/upload-artifact@v4
with:
name: linux-${{ matrix.arch }}
+4 -1
View File
@@ -19,7 +19,7 @@
</p>
</div>
当前版本 / 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)
当前版本 / Current version: **[v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
## 关于 WebSpeak · Overview
@@ -82,6 +82,7 @@ docker compose up -d
1. 打开 `http://127.0.0.1:3040/admin`,使用 `admin` / `admin` 登录并设置至少 12 位新密码。Open the console, sign in and replace the default password.
2. 配置 TeamSpeak 目标和访问模式;公网使用 HTTPS。Set the TeamSpeak target and access mode; use HTTPS for public access.
3. 启用 WebRTC 时放行配置的 UDP 范围,默认 `40000–40099`。Allow the configured UDP range when enabling WebRTC.
4. Cloudflare Tunnel 或受限网络可在管理台“服务器 → 语音”配置 TURN 后备、语音模式和自适应音频,保存后对新的语音连接生效。Configure TURN fallback, voice mode, and adaptive audio under Admin → Voice; changes apply to new voice connections after saving.
数据保存在 `webspeak-data` volume,升级时保留它。Docker 控制台只能检查版本;升级请在宿主机执行 `docker compose pull && docker compose up -d`,且不要执行 `docker compose down -v`。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
@@ -96,6 +97,8 @@ Data persists in the `webspeak-data` volume. On Docker, the console only checks
- [Deutsch](./docs/README.de.md)
- [Русский](./docs/README.ru.md)
- [日本語](./docs/README.ja.md)
- [Cloudflare Tunnel 语音部署与排障](./docs/CLOUDFLARE_TUNNEL_VOICE.md)
- [语音兼容性说明 / Voice compatibility notes](./docs/VOICE_FIX_REPORT.md)
- [皮肤开发指南 / Skin development guide](./docs/SKIN_DEVELOPMENT.md)
- [皮肤开发 Agent Skill / Skin Development Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
+65
View File
@@ -0,0 +1,65 @@
# Cloudflare Tunnel for WebSpeak
Cloudflare Tunnel publishes the WebSpeak **HTTPS/WSS** entry without opening a
public inbound port. It does **not** carry WebRTC media UDP, and it does not
make the gateway's `40000–40099/UDP` range reachable.
## Setup
1. Create a tunnel in the Cloudflare dashboard and copy its UUID and
credentials JSON.
2. Copy `config.yml.example` to `config.yml` and replace the UUID and
hostname. Rename the downloaded credentials file to
`REPLACE_WITH_TUNNEL_UUID.json`, or update the credentials path and Compose
mount to match its actual name. Point `service` at the WebSpeak HTTP listener
(`3040` by default).
3. Run cloudflared on the host (recommended on Windows/macOS):
```bash
cloudflared tunnel --config config.yml run
```
On Linux, `docker compose up -d` in this directory can run it in host mode.
4. In WebSpeak administration, set **Public media address** to the gateway's
public IP (for example `192.0.2.10`), not the Cloudflare hostname.
Allow `40000–40099/UDP` on the host firewall and security group.
5. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so browsers try direct UDP
first. `WEBSPEAK_VOICE_PROFILE=auto` is the default: requests from a trusted
Cloudflare hop use the adaptive audio path, while other requests keep the
legacy path. The default trusted proxy list contains loopback only; if
cloudflared connects from another address, add that IP/CIDR to
`WEBSPEAK_TRUSTED_PROXIES`. Headers injected by a direct untrusted client are
ignored. Configure TURN only as the fallback for mobile networks or
UDP-blocked clients; see `deploy/coturn`.
6. Opus over WebSocket is opt-in. It requires an adaptive profile and either
the Admin → Voice setting or `WEBSPEAK_VOICE_OPUS_WS=1`; without it the
browser uses PCM.
## Why not use the Cloudflare hostname as the media address?
A Cloudflare-proxied hostname resolves to Cloudflare edge addresses. Those
edges do not forward the gateway's UDP media ports, so using them as ICE
candidates produces a path that looks configured but cannot carry audio.
WebSpeak therefore no longer infers the request `Host` as an ICE address when
the request arrives through a trusted Cloudflare hop and no media host was
configured. Without a public media address or TURN, the server reports
`NO_MEDIA_PATH` and, because WebRTC was not advertised, the browser uses the
compatibility transport. If an advertised WebRTC connection later fails, the
browser stays in the session with `WEBRTC_FAILED` and offers WebRTC reconnect;
it does not silently switch to compatibility transport.
## Verify
- `curl -I https://voice.example.com` succeeds through the tunnel.
- `chrome://webrtc-internals` shows host/srflx candidates to the public IP and,
when UDP is available, a direct selected pair.
- If the selected pair is `relay`, confirm TURN is reachable and that direct
UDP is actually blocked; do not switch the global policy to `relay` just
because the page is behind a Tunnel.
For the full voice rollout and rollback notes, see
[`docs/CLOUDFLARE_TUNNEL_VOICE.md`](../../docs/CLOUDFLARE_TUNNEL_VOICE.md).
This template has not been exercised end-to-end with a live coturn/Tunnel
deployment. Browser Opus fallback, especially on Safari and Firefox, also
requires device testing.
+10
View File
@@ -0,0 +1,10 @@
tunnel: REPLACE_WITH_TUNNEL_UUID
credentials-file: /etc/cloudflared/REPLACE_WITH_TUNNEL_UUID.json
ingress:
- hostname: voice.example.com
service: http://127.0.0.1:3040
originRequest:
connectTimeout: 30s
noTLSVerify: false
- service: http_status:404
+12
View File
@@ -0,0 +1,12 @@
services:
cloudflared:
image: cloudflare/cloudflared:latest
container_name: webspeak-cloudflared
restart: unless-stopped
# Linux only. On Docker Desktop for Windows/macOS, run cloudflared on the
# host and use http://127.0.0.1:3040 instead.
network_mode: host
command: tunnel --config /etc/cloudflared/config.yml run
volumes:
- ./config.yml:/etc/cloudflared/config.yml:ro
- ./REPLACE_WITH_TUNNEL_UUID.json:/etc/cloudflared/REPLACE_WITH_TUNNEL_UUID.json:ro
+8
View File
@@ -0,0 +1,8 @@
# Copy to .env and replace the secret. Keep this file out of git.
TURN_SECRET=replace-with-at-least-32-random-bytes
TURN_REALM=webspeak
# Public IPv4 of this host. Behind 1:1 NAT, use PUBLIC/PRIVATE, e.g.
# 192.0.2.10/10.0.0.5
TURN_EXTERNAL_IP=203.0.113.10
TURN_MIN_PORT=49160
TURN_MAX_PORT=49200
+82
View File
@@ -0,0 +1,82 @@
# WebSpeak TURN (coturn) deployment
TURN is a **fallback** for voice media when a browser cannot reach the WebSpeak
gateway over UDP, for example on mobile networks or networks that block UDP.
It is not required for the normal direct UDP path.
## 1. Configure
```bash
cp .env.example .env
# Generate a secret and put the same value in WEBSPEAK_TURN_REST_SECRET:
openssl rand -hex 32
```
Set `TURN_EXTERNAL_IP` to the host's public IPv4. If the host is behind 1:1
NAT, use `PUBLIC/PRIVATE` (for example `203.0.113.10/10.0.0.5`). The relay
range `49160–49200/UDP` is separate from WebSpeak's WebRTC range
`40000–40099/UDP`; do not reuse the WebRTC range.
## 2. Start and expose
```bash
docker compose --env-file .env up -d
docker compose logs -f coturn
```
Allow inbound:
- `3478/UDP` and `3478/TCP` for `turn:`
- `49160–49200/UDP` for relayed media
- `5349/TCP` only if you add TLS certificates for `turns:`
Do **not** put the TURN relay range behind Cloudflare Tunnel; Cloudflare Tunnel
does not carry this UDP traffic.
## 3. Connect WebSpeak
Use the same secret as coturn's `static-auth-secret`:
```bash
WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp'
WEBSPEAK_TURN_REST_SECRET='<same value as TURN_SECRET>'
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
# Keep direct UDP first. Use "relay" only where UDP is known to be blocked.
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all
# Auto keeps direct and untrusted-proxy traffic on the legacy audio path.
WEBSPEAK_VOICE_PROFILE=auto
```
TURN does not require Opus; `WEBSPEAK_VOICE_OPUS_WS` remains off by default.
`WEBSPEAK_TURN_REST_URLS` accepts only `turn:`/`turns:` URL tokens. For static
ICE credentials, use `WEBSPEAK_VOICE_ICE_SERVERS` with a JSON array of ICE
server objects instead. WebSpeak generates short-lived `username`/`credential`
pairs with HMAC-SHA1, compatible with coturn's `use-auth-secret`.
## 4. Verify
From a network that blocks direct UDP, open the voice page and check:
- `chrome://webrtc-internals` (Chrome/Edge) or `about:webrtc` (Firefox)
- The selected candidate pair should become `relay` only when direct UDP fails.
- `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` must not be changed to `relay`
merely because a Tunnel is in front of HTTPS.
If TURN succeeds but audio still stutters, check whether the connection's
`voiceProfile` is `adaptive`; on a direct or legacy profile the old 80 ms
compatibility window is expected. TURN reachability alone does not enable the
adaptive jitter buffer.
## Security notes
- Keep the secret out of shell history, process listings where possible, and
git. Prefer an `.env` file with restrictive permissions.
- The compose file denies private, loopback and link-local peer ranges to
reduce abuse. If the WebSpeak gateway itself is on a private address, add a
narrowly scoped `--allowed-peer-ip` for that address and review the risk.
- This template has no TLS listener. Add certificates and a `turns:` URL only
when you need TURN over TLS on `5349/TCP`; test certificate renewal.
- This template has not been exercised end-to-end with a live Tunnel and
browser deployment; validate TURN reachability and credentials in the target
network before relying on it.
+40
View File
@@ -0,0 +1,40 @@
services:
coturn:
image: coturn/coturn:4.6.3
container_name: webspeak-coturn
restart: unless-stopped
# Host networking keeps the configured relay UDP range and external-ip
# mapping predictable. On Linux, replace it with explicit ports only if
# your platform does not support host mode.
network_mode: host
environment:
TURN_SECRET: ${TURN_SECRET:?set TURN_SECRET in .env}
TURN_REALM: ${TURN_REALM:-webspeak}
TURN_EXTERNAL_IP: ${TURN_EXTERNAL_IP:?set TURN_EXTERNAL_IP in .env}
TURN_MIN_PORT: ${TURN_MIN_PORT:-49160}
TURN_MAX_PORT: ${TURN_MAX_PORT:-49200}
command:
- -n
- --log-file=stdout
- --no-cli
- --fingerprint
- --lt-cred-mech
- --use-auth-secret
- --static-auth-secret=${TURN_SECRET}
- --realm=${TURN_REALM}
- --external-ip=${TURN_EXTERNAL_IP}
- --listening-port=3478
- --min-port=${TURN_MIN_PORT}
- --max-port=${TURN_MAX_PORT}
- --stale-nonce=600
- --no-multicast-peers
- --denied-peer-ip=0.0.0.0-0.255.255.255
- --denied-peer-ip=10.0.0.0-10.255.255.255
- --denied-peer-ip=127.0.0.0-127.255.255.255
- --denied-peer-ip=169.254.0.0-169.254.255.255
- --denied-peer-ip=172.16.0.0-172.31.255.255
- --denied-peer-ip=192.168.0.0-192.168.255.255
- --denied-peer-ip=::1
- --denied-peer-ip=fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
- --denied-peer-ip=fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff
- --denied-peer-ip=ff00::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
+197
View File
@@ -0,0 +1,197 @@
# Cloudflare Tunnel 下的 WebSpeak 语音
本文说明“网页/信令走 Cloudflare Tunnel,媒体尽量直连 UDP”的部署方式。
核心原则:
- **WebRTC 优先直连**:浏览器直接向网关公网 IP 的 `40000–40099/UDP` 发包。
- **Tunnel 只承载 HTTPS/WSS**:Cloudflare Tunnel 不转发 UDP,不能把
Cloudflare 代理域名当作 ICE 媒体地址。
- **TURN 只做后备**:手机流量、公司网络或 UDP 被拦时,才让媒体走
`turn:`/`turns:`,不默认全程 `relay`。
- **CFT 是增量路径**:默认 `WEBSPEAK_VOICE_PROFILE=auto`,非可信 Cloudflare
请求继续使用原有的 80ms 固定窗口、裸 1920 字节 PCM 和旧混音参数;只有
经过可信 Cloudflare 代理的请求(或显式 `adaptive`)才启用自适应 buffer /
pacer / 修正后的 RTP marker。不配置 CFT、TURN 或新变量时,直连部署保持原行为。
## 兼容性矩阵
| 部署 | 媒体路径 | 音频 profile | 需要 TURN |
| --- | --- | --- | --- |
| 直连,无 CFT | 浏览器 → 网关 UDP `40000–40099` | `legacy`(默认) | 否 |
| 直连,显式 `PROFILE=adaptive` | 同上,直连优先 | `adaptive` | 否 |
| CFT + 显式公网 IP | 浏览器 → 网关 UDP,CF 只走信令 | `adaptive` | 否 |
| CFT + 无公网媒体地址 | 无直连;兼容模式或 TURN | `adaptive` | 是(若需要 WebRTC) |
| 手机/UDP 被拦 | TURN relay 后备 | `adaptive` | 是 |
`legacy` 不是“禁用 WebRTC”,它只锁定旧音频时序和旧帧路径;WebRTC、STUN、
UDP 端口仍按原配置工作。
## 1. 管理控制台与部署检查
### 1.1 管理控制台(推荐)
管理台“服务器 → 语音”提供与部署相关的全部开关,不再需要仅为 CFT/TURN
修改环境变量:
- **语音模式**:`自动`(推荐,直连走 `legacy`、可信 Cloudflare 代理走
`adaptive`)、`兼容模式`、`自适应`。
- **兼容模式 Opus**:仅 `adaptive` 生效,默认关闭;浏览器不支持时自动回退
PCM。
- **自适应 jitter 上限**:80–500 ms,配置自适应缓冲目标的上限;它不是严格的
播放前瞻上限,调低也不会恢复旧版超限 `clear()` 行为。
- **TURN 后备**:TURN REST URL、共享密钥和凭证有效期。TURN 只在直连 UDP
失败后使用,不作为默认路径。
保存后对**新的语音连接**生效,不需要重启网关。配置持久化在数据库中:控制台
非空值覆盖对应环境变量,未配置的字段继续继承环境变量;清空 TURN URL 或在
控制台移除密钥会显式停用 TURN。TURN 共享密钥使用网关主密钥加密存储,管理
API 只返回“是否已配置”,不会把明文回传浏览器。
静态 `WEBSPEAK_VOICE_ICE_SERVERS` 以及浏览器/网关的 `transportPolicy` 仍由
环境变量控制,控制台刻意不提供“全程 relay”开关,避免误把直连优先改成中继
优先;需要排障时再临时设置环境变量并重启。
Cloudflare 判定只接受来自 `WEBSPEAK_TRUSTED_PROXIES` 中直接相邻代理的
`cf-ray`、`cf-connecting-ip` 或包含 `cloudflare` 的 `cdn-loop`。默认只信任
本机回环地址;cloudflared 若从其他地址连接,应把其来源 IP/CIDR 加入该变量。
直连客户端自行注入这些头不会被当作 Cloudflare,也不会切换到 `adaptive`。
### 1.2 部署检查清单
1. 管理台“服务器 → 语音”先选 `自动`,再在“高级参数 → 公网媒体地址”填写网关的**公网 IP**,例如 `192.0.2.10`,不要填 Cloudflare 的代理域名。保存后重新连接。
2. 主机防火墙/安全组放行 `40000–40099/UDP`,并确认云厂商安全组也放行。
3. 如果网关本身在 NAT 后面,需要把 UDP 端口映射到网关,或给网关一个
可直连的公网地址;仅做 TCP 端口映射不够。
4. `webrtc_public_host` 为空时,直连部署仍可按请求入口推断;但通过
Cloudflare 的请求不会再拿 CF 边缘 `Host` 当 ICE 地址,避免“看起来
配置好了、实际没有媒体路径”。Cloudflare 场景请显式填写公网媒体地址。
## 2. 服务端环境变量
在启动 WebSpeak 的环境里设置;修改后重启进程,并对新连接生效。控制台已保存
的非空语音配置优先于这里的环境变量;控制台留空的字段才继承环境变量。日常
CFT/TURN 调整建议直接用控制台,避免同时维护两套配置。
| 变量 | 默认 | 作用 |
| --- | --- | --- |
| `WEBSPEAK_VOICE_PROFILE` | `auto` | `auto`:非可信 Cloudflare 请求用 `legacy`,可信 Cloudflare 代理请求用 `adaptive`;也可显式 `legacy`/`adaptive`。非 CFT 不配置时保持原行为。 |
| `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY` | `all` | 浏览器 ICE 策略。直连优先保持 `all`;只有确认 UDP 完全不可用才设 `relay`。 |
| `WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY` | `all` | werift 网关侧策略。网关自身在 NAT 后才考虑 `relay`。 |
| `WEBSPEAK_VOICE_ICE_SERVERS` | 空 | 静态 ICE 列表,JSON 数组或逗号分隔的 STUN URL;最多 8 个。 |
| `WEBSPEAK_TURN_REST_URLS` | 空 | coturn REST 的 `turn:`/`turns:` URL,逗号分隔;最多 8 个。 |
| `WEBSPEAK_TURN_REST_SECRET` | 空 | 与 coturn `static-auth-secret` 相同的密钥,至少 16 字符才启用。 |
| `WEBSPEAK_TURN_REST_TTL_SECONDS` | `21600` | TURN 临时凭证有效期,范围 300–86400。 |
| `WEBSPEAK_VOICE_OPUS_WS` | `0` | 兼容模式是否允许浏览器用 WebCodecs 发 Opus;仅 `adaptive` 且环境变量或控制台显式启用时生效,不支持时自动回退 PCM。 |
| `WEBSPEAK_VOICE_JITTER_MAX_MS` | `300` | 自适应 jitter buffer 的上限,范围 80–500;仅 `adaptive` 生效。 |
示例(直连优先 + TURN 后备):
```bash
WEBSPEAK_VOICE_PROFILE=auto
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all
WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY=all
WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp'
WEBSPEAK_TURN_REST_SECRET='<与 coturn 相同的密钥>'
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
```
直连部署若也想启用自适应 buffer / pacer,显式设置
`WEBSPEAK_VOICE_PROFILE=adaptive`;这会改变非 CFT 的音频时序,但不是开通
CFT 的必选项。
`turn:` 的 UDP/TCP 3478 适合大多数场景;如已给 coturn 配好证书,可再加
`turns:turn.example.com:5349?transport=tcp`。TURN 的 relay 端口默认
`49160–49200/UDP`,与 WebRTC 的 `40000–40099/UDP` 分开,见
`deploy/coturn/`。
### 关于 werift 与 `turns:`
已核对 `werift` 源码:`parseIceServers` 会把 `turns:` 解析为
`turnTransport: "tls"`,`createTurnClient` 走 `TlsTransport`;
`iceUseTcp: false` 只影响 ICE-TCP host candidate 的收集,不会阻止 TURN 的
TLS 控制连接。因此 `turns:` 在 `iceUseTcp: false` 下仍可用。该结论是源码
级核实,未在真实 coturn 上做端到端联调。
## 3. 兼容模式(PCM/Opus over WebSocket)
兼容模式不依赖 UDP,任何部署都可用。以下自适应/Opus/pacer 只在
`voiceProfile=adaptive` 时生效;`legacy` 直连保留原来的 80ms 固定窗口,
超过窗口会 `clear()` 解码器并重建,和旧版一致。
自适应分支:
- jitter buffer:目标超前量按到达 jitter 估算,初始 80ms,上限默认
300ms;溢出时只重排播放头、保留 `AudioDecoder`,不再每次超过 80ms
就销毁解码器。
- 解码队列硬上限 12;只有极深积压才丢最新帧。
- 上行 20ms pacer;新帧格式 `0x01 + PCM` 和 `0x02 + Opus`,旧 1920 字节
PCM 仍兼容。
- 仅当 `adaptive` 且环境变量或控制台显式启用 Opus,同时浏览器支持
WebCodecs 时才发 Opus,否则自动回退 PCM。
legacy 分支:
- 80ms 固定播放窗口;超限清空当前 speaker 的 source 和 decoder。
- 浏览器发送裸 1920 字节 PCM,不创建 Opus encoder。
- 服务端不启用 pacer;WebRTC 混音保持 4 帧队列和每包 marker。
验证:
1. 在 Chrome/Edge 打开 `chrome://webrtc-internals`:已下发 WebRTC offer 后
若建连或传输失败,页面应留在当前 TeamSpeak/WebSocket 会话,自动恢复
PCM/Opus over WebSocket 的上下行兼容音频(上行需要已有麦克风权限),
同时显示 `WEBRTC_FAILED` 和“重新连接 WebRTC”。
2. 点击“重新连接 WebRTC”只重试 WebRTC,不重新连接 TeamSpeak,也不新建
语音 WebSocket。重连协商期间保持兼容收发;只有 WebRTC 真正 ready 后才
停止兼容传输、清除失败横幅和按钮。再次失败则继续兼容保通话,横幅和
按钮保留。
3. 网关未 advertise WebRTC 的禁用、浏览器不支持或 `NO_MEDIA_PATH` 路径仍
直接使用兼容模式,不显示这块 WebRTC 失败按钮。
4. 在管理台或日志看 `audio.opus` trace:`active` 表示 Opus 已启用,
`pcm-fallback` 表示回退。
5. 连续说话 2–3 分钟,观察是否还有周期性“整段静音/重启”式卡顿;新
逻辑不应再因 80ms 硬窗口反复 `clear()`。
## 4. 验收与回滚
**验收顺序**
1. 同一网络下先用直连 UDP:`chrome://webrtc-internals` 选中 pair 应为
`host`/`srflx`,不是 `relay`。
2. 手机 4G/5G 或关 UDP 的 Wi-Fi 再测:没有直连时才会出现 `relay`,且
音频可通。
3. 对未下发 WebRTC 的路径(关闭 WebRTC、无媒体路径或浏览器不支持)测
2–3 分钟兼容模式。确认连接
`connected` 消息中的 `voiceProfile` 为 `adaptive` 后,`bufferResets`
不应持续增长、没有解码器反复重建;若为 `legacy`,看到旧 80ms 行为是
预期的。
**回滚**
- 恢复非 CFT 旧行为:在管理台“语音模式”选 `兼容模式`,或设置
`WEBSPEAK_VOICE_PROFILE=legacy`(没有控制台覆盖时)。legacy 会恢复
80ms/`clear()`、裸 PCM、旧 WebRTC mixer;不需要回退前端构建。
- 关闭兼容模式 Opus:在管理台取消“兼容模式使用 Opus”,或设置
`WEBSPEAK_VOICE_OPUS_WS=0`;注意只有 `adaptive` 会下发 Opus 能力。
- 限制 jitter 缓冲:管理台把“自适应 jitter 上限”调到 80,或设置
`WEBSPEAK_VOICE_JITTER_MAX_MS=80`;这只是把上限压回 80ms,**不会恢复
旧版“超过 80ms 就 `clear()` 解码器”的行为**。要完全回到旧行为,使用
`兼容模式` / `legacy`。
- 关闭 TURN:在管理台清空 TURN URL(或移除密钥,会同时清空 URL),或删除
`WEBSPEAK_TURN_REST_URLS` / `WEBSPEAK_TURN_REST_SECRET` 环境变量;浏览器
只保留直连/STUN;不要为了“排障”把
`WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY` 改成 `relay`,那会掩盖直连问题。
- 媒体地址配置错误时,先清空管理台“公网媒体地址”并确认非 Cloudflare
直连入口,再检查防火墙;Cloudflare 请求下留空会禁用直连,需要 TURN。
- 语音覆盖配置保存在现有 metadata 表,数据库保持 schema 13;TURN 密钥仍加密。
回退到 0.3.3 时旧程序会忽略新增元数据,不影响启动,也不会清除这些配置。
自动更新失败时可以继续使用现有代码回滚流程,无需降级数据库。
## 5. 已知限制
- 本文的 coturn/cloudflared 模板未做真实端到端联调;部署前必须在
目标网络验证 `3478/UDP`、`3478/TCP`、relay 端口和凭证一致性。
- Safari/Firefox 的 WebCodecs Opus 支持差异未在真实设备上逐一验证;
不支持时会回退 PCM,但兼容模式的 CPU/带宽开销会更高。
- Cloudflare Tunnel 不承载本文的 WebRTC UDP 媒体;即使 HTTPS/WSS 正常,
仍需要独立可达的公网媒体地址,或配置 TURN/使用兼容模式。
+20 -2
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.2](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin-Wiederherstellung, App-Bibliothek und Plugin-Formulare.
Stabile Version: [Hinweise zu v0.3.3](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Konsolen-Updates, Wiederherstellung und bessere Skin-Kompatibilität.
@@ -193,7 +193,11 @@ Unter **Server → Erweiterte Einstellungen** die **öffentliche Medienadresse**
**IPv6-Kandidaten** sind optional und behalten IPv4 bei; IPv6-Routing und Firewall müssen passen. Als **Sprach-STUN** kann `stun:turn.teamspeak.com:3478` eingetragen werden. Browser und Gateway verwenden dann denselben Dienst. Leer behält das bisherige Verhalten bei: STUN des Gateway-SDKs, kein Browser-STUN. Zulässig sind IPv4-erreichbare UDP-STUN-Domains oder IPv4-Adressen, keine IPv6-Literale oder TURN-Zugangsdaten.
Speichern und neu verbinden. Den gesamten UDP-Portbereich öffnen und bei statischer Weiterleitung die Portnummern erhalten. STUN findet Adressabbildungen, leitet aber keine Audiodaten weiter. Ein reiner TCP-Tunnel ohne nutzbaren UDP-/IPv6-Pfad führt weiter zum kompatiblen Transport.
Speichern und neu verbinden. Erreichbare Webseiten und WebSockets bedeuten nicht, dass UDP-Medien erreichbar sind. Den gesamten UDP-Portbereich öffnen und bei statischer Weiterleitung die Portnummern erhalten. STUN findet Adressabbildungen, leitet aber keine Audiodaten weiter und überwindet nicht jedes NAT.
Für Mobilfunk oder blockiertes UDP kann ein externer TURN-Dienst als optionales Fallback unter **Administration → Sprache** mit TURN-REST-URL, gemeinsamem Geheimnis und Gültigkeitsdauer eingerichtet werden; entsprechende Umgebungsvariablen sind `WEBSPEAK_TURN_REST_URLS` und `WEBSPEAK_TURN_REST_SECRET`. Konsolenwerte haben Vorrang und gelten ohne Neustart für neue Verbindungen. `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` versucht zuerst direktes UDP.
`WEBSPEAK_VOICE_PROFILE` ist standardmäßig `auto`: Nur Anfragen über einen vertrauenswürdigen Cloudflare-Proxy verwenden den adaptiven Puffer; direkte und andere Anfragen behalten das bisherige Verhalten mit 80 ms/Roh-PCM. Lokale Tunnel-Verbindungen sind standardmäßig vertrauenswürdig; wenn cloudflared von einer anderen Adresse verbindet, `WEBSPEAK_TRUSTED_PROXIES` konfigurieren. Für adaptive Nutzung auch bei direktem Zugriff explizit `adaptive` wählen oder unter Administration → Sprache festlegen. Opus über WebSocket ist standardmäßig aus und benötigt das adaptive Profil; es lässt sich unter Administration → Sprache oder mit `WEBSPEAK_VOICE_OPUS_WS=1` aktivieren. Ohne direktes UDP oder TURN meldet die Sitzung `NO_MEDIA_PATH` und verwendet den kompatiblen Transport. Details stehen in [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md).
### ICE-Kandidaten für Bildschirmfreigabe
@@ -341,6 +345,20 @@ Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und opti
<a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**Schwerpunkt: stabile Versionen prüfen und Updates direkt in der Verwaltung installieren.**
- Die Konsole prüft offizielle GitHub Releases; Administratoren wählen eine Version und bestätigen die Installation nach SHA-256-Prüfung. Die Installation unterstützt zunächst offizielle Linux-x64-Pakete im Vordergrund. Windows, Linux arm64, Docker, Quellinstallationen und von systemd, PM2 oder Supervisor verwaltete Instanzen können Versionen und Versionshinweise prüfen; die Installation bleibt manuell.
- Nur Programmdateien werden ersetzt. `data/`, `config.json`, `certs/`, installierte Skins und Plugins bleiben erhalten. Der Prozessneustart trennt Sprachsitzungen und Konsole kurzzeitig. SHA256SUMS.txt ist eine Integritätsprüfsumme, keine digitale Signatur.
- Gesundheitsprüfung, Rollback und Startwiederherstellung nach Unterbrechungen wurden gehärtet. Wiederherstellung und Update verwenden dieselbe Sperre. Größenlimits, Schreibfehler und Abbruch beenden Anfragen, geben Leser frei und bereinigen parallele Downloads.
- Skins können Wiederherstellungsbedienelemente über deklarierte Slots platzieren und Host-Bedienelemente über geschützte Variablen gestalten. Bei unbrauchbaren Werten greifen Standardlayout und -farben. Verbesserte Vermeidung verdeckter Elemente, Toast-Hit-Tests sowie Kompatibilität mit verzögertem Skin-Laden und Animationen; Wiederherstellungskürzel bleiben verfügbar.
- Enthält #60, #61, #62 und nachfolgende Korrekturen sowie aktualisierte Skin-Anleitungen und Beispiele. Danke an OddTurtleHead.
**Upgrade:** v0.3.2 und ältere Versionen zuerst manuell auf v0.3.3 aktualisieren. Danach sind Konsolen-Updates für künftige stabile Versionen auf unterstützten Installationen verfügbar. Daten vorher sichern. Docker: `docker compose pull && docker compose up -d` unter Beibehaltung des Datenvolumes. Verwaltete Dienste vor dem Dateiaustausch stoppen und anschließend neu starten.
Prüfung: 1102 automatisierte Tests, Frontend-/Backend-Builds und Docker-Startprüfung bestanden.
### [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).
+20 -4
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.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.
Stable release: [v0.3.3 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Console updates, reliable recovery, and skin compatibility improvements.
@@ -195,11 +195,13 @@ The port range is locked while WebRTC is enabled. Disable and save WebRTC before
### Voice WebRTC behind a reverse proxy or TCP tunnel
The WebRTC advanced settings now include a **public media address**, **IPv6 candidates**, and a **voice STUN server**. The media address must be a gateway IP or hostname reachable over UDP, without a scheme, path or port. It overrides the address inferred from `Origin`, `X-Forwarded-Host`, or `Host`; DNS names are resolved into IP candidates. IPv6 is opt-in and retains IPv4 candidates.
The WebRTC advanced settings now include a **public media address**, **IPv6 candidates**, and a **voice STUN server**. The media address must be a gateway IP or hostname reachable directly over UDP, without a scheme, path or port. Prefer the host's public IP; do not use the Cloudflare-proxied hostname. It overrides the address inferred from `Origin`, `X-Forwarded-Host`, or `Host`; DNS names are resolved into IP candidates. IPv6 is opt-in and retains IPv4 candidates.
Set a UDP STUN URL such as `stun:turn.teamspeak.com:3478` to use the same discovery service in the browser and gateway. Empty preserves the previous behavior: the gateway library uses its built-in STUN service while the browser has none. The gateway requires an IPv4-reachable UDP STUN hostname or IPv4 address; IPv6 literals and TURN credentials are not accepted. IPv6 media candidates work independently of STUN. Save and reconnect to apply changes.
HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. Deployments with only a TCP tunnel and no usable UDP/IPv6 path still fall back to compatibility transport.
HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. For mobile or UDP-blocked clients, configure an external TURN service as an optional fallback directly under Admin → Voice with the TURN REST URL, shared secret, and credential lifetime; the equivalent environment variables are `WEBSPEAK_TURN_REST_URLS` and `WEBSPEAK_TURN_REST_SECRET`. Console values take precedence and apply to new connections without a gateway restart. Keep `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` so direct UDP is tried first. `WEBSPEAK_VOICE_PROFILE` defaults to `auto`: only requests received through a trusted Cloudflare proxy use the adaptive buffer; direct and other requests keep the legacy 80 ms/raw-PCM path. Loopback tunnel connections are trusted by default; configure `WEBSPEAK_TRUSTED_PROXIES` when cloudflared connects from another address. Set `adaptive` explicitly to use it on direct deployments too; Admin → Voice can override this mode. Opus over WebSocket is off by default; enable it under Admin → Voice or with `WEBSPEAK_VOICE_OPUS_WS=1`, and use the `adaptive` profile. If neither direct UDP nor TURN provides a media path, the session reports `NO_MEDIA_PATH` and uses the compatibility transport.
See [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) for the direct-UDP-first topology, coturn/cloudflared templates, verification and rollback notes.
### Screen-share ICE candidates
@@ -308,7 +310,7 @@ Disable and save the relay configuration to remove the relay option from the wel
Skins own appearance, layout and their attached widgets. Administrators install, enable and choose the default skin. Authors use the public contract without changing WebSpeak source code.
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) · [Host chrome toolbar example](./examples/HOST-CHROME-TOOLBAR.md)
### Functional plugins `.wplugin`
@@ -347,6 +349,20 @@ Functional plugins are independent applications using standard browser capabilit
<a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**Highlight: stable-release checks and one-click updates in the administration console.**
- Administrators can check official GitHub Releases, select a version and confirm installation. Packages must pass SHA-256 verification. Installation initially supports official Linux x64 packages running in the foreground. Windows, Linux arm64, Docker, source installs and instances managed by systemd, PM2 or Supervisor retain version checks and release-note links; installation follows their manual deployment procedure.
- Updates replace application files while preserving `data/`, `config.json`, `certs/`, installed skins and plugins. Installation restarts the process and briefly disconnects voice sessions and the console. SHA256SUMS.txt is an integrity checksum, not a digital signature.
- Hardened health checks, rollback and startup recovery after interrupted updates. Recovery shares the update lock, preventing a duplicate launch from rolling back a live update. Size-limit errors, disk-write failures and cancellation abort requests, release response readers and clean up sibling downloads.
- Skins can place recovery controls in declared slots and style host controls through protected tokens, with default placement and colours when unusable. Improved floating-control avoidance, hit-testing through toasts, late skin loading and animation compatibility; recovery shortcuts remain available.
- Includes #60, #61, #62 and follow-up maintenance fixes, plus updated skin development documentation and examples. Thanks to OddTurtleHead.
**Upgrading:** manually upgrade v0.3.2 or earlier to v0.3.3 first. Supported installs can then use the console for future stable releases. Back up data before upgrading. Docker uses `docker compose pull && docker compose up -d` with the data volume preserved. Stop managed services before replacing application files, then start them again.
Validation: 1,102 automated tests, frontend/backend builds and the Docker startup health check passed.
### [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).
+20 -2
View File
@@ -13,7 +13,7 @@
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
安定版:[v0.3.2 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · スキンの復元、アプリライブラリの配置、プラグイン設定フォーム。
安定版:[v0.3.3 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · コンソール更新、復元処理、スキン互換性の改善。
@@ -180,7 +180,11 @@ WebSpeak 管理画面と音声接続は、この機能に依存しません。
**IPv6 候補**は任意で、IPv4 も維持します。IPv6 の経路とファイアウォール許可が必要です。**音声 STUN** に `stun:turn.teamspeak.com:3478` を設定すると、ブラウザーとゲートウェイが同じサービスを使います。空欄では従来どおり、ゲートウェイのライブラリ内蔵 STUN を使い、ブラウザーには設定しません。IPv4 で到達可能な UDP STUN ドメイン・IPv4 アドレスに対応し、IPv6 リテラルや TURN 認証情報は指定できません。
保存後に再接続してください。UDP 範囲全体を許可し、固定ポート転送では番号を維持します。STUN はアドレスを検出するだけで音声を中継しません。利用可能な UDP/IPv6 経路のない TCP Tunnel だけでは、互換転送に戻ります。
保存後に再接続してください。ページと WebSocket に到達できても、UDP メディアが到達可能とは限りません。UDP 範囲全体を許可し、固定ポート転送では番号を維持します。STUN はアドレスを検出するだけで音声を中継せず、すべての NAT を通過できるわけでもありません。
モバイル回線や UDP が遮断される環境では、**管理コンソール → サーバー → 音声**で外部 TURN を任意のフォールバックとして設定できます。TURN REST URL、共有シークレット、認証情報の有効期限を入力してください。対応する環境変数は `WEBSPEAK_TURN_REST_URLS` と `WEBSPEAK_TURN_REST_SECRET` です。コンソールの値が優先され、ゲートウェイの再起動なしで新しい接続に適用されます。`WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` ではまず直接 UDP を試します。
`WEBSPEAK_VOICE_PROFILE` の初期値は `auto` です。信頼できる Cloudflare プロキシを経由した要求だけが適応バッファを使い、直接接続などの要求は従来の 80 ms / 生 PCM の動作を維持します。ローカルの Tunnel 接続は初期状態で信頼されます。cloudflared が別のアドレスから接続する場合は `WEBSPEAK_TRUSTED_PROXIES` を設定してください。直接接続でも適応モードを使うには `adaptive` を明示的に選ぶか、「音声」で指定します。WebSocket 経由の Opus は初期状態で無効で、適応モードが必要です。「音声」または `WEBSPEAK_VOICE_OPUS_WS=1` で有効にできます。直接 UDP と TURN のどちらもメディア経路を提供できない場合、セッションは `NO_MEDIA_PATH` を報告して互換トランスポートを使います。詳細は [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md) を参照してください。
### 画面共有の ICE 候補
@@ -276,6 +280,20 @@ relay.example.com {
<a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**主な変更:管理コンソールから安定版の確認とワンクリック更新が可能になりました。**
- 公式 GitHub Releases を確認し、管理者がバージョンを選んでインストールを承認します。パッケージは SHA-256 検証が必須です。自動インストールの対象は、フォアグラウンドで実行する公式 Linux x64 パッケージです。Windows、Linux arm64、Docker、ソース実行、systemd・PM2・Supervisor 管理の環境では、バージョン確認とリリースノートの閲覧ができ、インストールは手動です。
- 置き換えるのはプログラムファイルのみです。`data/`、`config.json`、`certs/`、インストール済みのスキンとプラグインは保持します。プロセスの再起動により、音声セッションと管理画面が一時的に切断されます。SHA256SUMS.txt は整合性のチェックサムであり、デジタル署名ではありません。
- ヘルスチェック、ロールバック、中断後の起動復元を強化しました。復元処理は更新処理とロックを共有し、重複起動による実行中の更新の巻き戻しを防ぎます。サイズ超過、書き込み失敗、キャンセル時にはリクエストと並列ダウンロードを中止し、読み取りストリームを解放します。
- 宣言したスロットと保護されたスタイル変数で、スキン内の復元入口とホスト操作部を調整できます。利用できない配置や色は標準に戻ります。浮動ボタンの重なり回避、通知の下にある要素の判定、スキンの遅延読み込みとアニメーションの互換性を改善し、復元ショートカットを維持しました。
- #60、#61、#62 と追加修正を収録し、スキン開発ガイドとサンプルを更新しました。OddTurtleHead の貢献に感謝します。
**更新方法:** v0.3.2 以前は、最初に v0.3.3 へ手動で更新してください。その後、対応する環境ではコンソールから今後の安定版をインストールできます。事前にデータをバックアップしてください。Docker はデータボリュームを保持して `docker compose pull && docker compose up -d` を実行します。サービス管理下では、停止してからプログラムファイルを置き換え、再起動してください。
検証:1102 件の自動テスト、フロントエンド・バックエンドのビルド、Docker 起動ヘルスチェックを通過。
### [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)に感謝します。
+20 -2
View File
@@ -13,7 +13,7 @@
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
Стабильный выпуск: [изменения v0.3.2](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Восстановление темы, библиотека приложений и формы настройки плагинов.
Стабильный выпуск: [изменения v0.3.3](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Обновление из консоли, восстановление и улучшенная совместимость скинов.
@@ -180,7 +180,11 @@ webspeak.example.com {
**IPv6-кандидаты** включаются отдельно и сохраняют IPv4; необходимы маршрутизация IPv6 и правила firewall. В поле **голосовой STUN** можно указать `stun:turn.teamspeak.com:3478`: браузер и шлюз используют один сервис. Пустое поле сохраняет прежнее поведение: встроенный STUN библиотеки шлюза и отсутствие STUN в браузере. Поле принимает доступный по IPv4 UDP STUN с доменом или IPv4, но не IPv6-литералы и не учётные данные TURN.
Сохраните настройки и подключитесь заново. Откройте весь диапазон UDP и сохраняйте номера портов при статическом пробросе. STUN обнаруживает отображения адресов, но не ретранслирует звук. Один TCP Tunnel без доступного UDP/IPv6 не предотвращает переход на совместимый транспорт.
Сохраните настройки и подключитесь заново. Доступность страницы и WebSocket не означает доступность UDP-медиа. Откройте весь диапазон UDP и сохраняйте номера портов при статическом пробросе. STUN обнаруживает отображения адресов, но не ретранслирует звук и не гарантирует прохождение любого NAT.
Для мобильных сетей или при блокировке UDP можно настроить внешний TURN как необязательный резерв в разделе **Панель администратора → Сервер → Голос**: укажите TURN REST URL, общий секрет и срок действия учётных данных. Эквивалентные переменные окружения — `WEBSPEAK_TURN_REST_URLS` и `WEBSPEAK_TURN_REST_SECRET`. Значения из консоли имеют приоритет и применяются к новым соединениям без перезапуска. `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all` сначала пытается использовать прямой UDP.
`WEBSPEAK_VOICE_PROFILE` по умолчанию имеет значение `auto`: адаптивный буфер используется только для запросов через доверенный прокси Cloudflare; прямые и другие запросы сохраняют прежний путь с окном 80 мс и сырым PCM. Локальные подключения Tunnel доверены по умолчанию; если cloudflared подключается с другого адреса, задайте `WEBSPEAK_TRUSTED_PROXIES`. Чтобы использовать адаптивный режим и при прямом подключении, выберите `adaptive` явно или задайте его в разделе «Голос». Opus через WebSocket по умолчанию выключен и требует адаптивного профиля; включите его в разделе «Голос» или через `WEBSPEAK_VOICE_OPUS_WS=1`. Если ни прямой UDP, ни TURN не даёт медиапуть, сессия сообщает `NO_MEDIA_PATH` и использует совместимый транспорт. Подробности: [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md).
### ICE для демонстрации экрана
@@ -276,6 +280,20 @@ relay.example.com {
<a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**Главное: проверка стабильных версий и установка обновлений из консоли администратора.**
- Консоль проверяет официальные GitHub Releases; администратор выбирает версию и подтверждает установку после проверки SHA-256. Установка пока поддерживается для официальных пакетов Linux x64, запущенных в переднем плане. Windows, Linux arm64, Docker, исходники и экземпляры под управлением systemd, PM2 или Supervisor могут проверять версии и открывать примечания; установка остаётся ручной.
- Заменяются только файлы программы. `data/`, `config.json`, `certs/`, установленные скины и плагины сохраняются. Перезапуск ненадолго отключает голосовые сеансы и консоль. SHA256SUMS.txt — контрольная сумма целостности, а не цифровая подпись.
- Усилены проверка работоспособности, откат и восстановление запуска после прерванного обновления. Восстановление использует общую блокировку с обновлением, чтобы повторный запуск не откатывал активную установку. При превышении лимита, ошибке записи или отмене запросы прерываются, потоки освобождаются, параллельная загрузка отменяется.
- Скины могут размещать элементы восстановления в объявленных слотах и оформлять элементы хоста через защищённые переменные. При непригодном оформлении используются стандартные расположение и цвета. Улучшены обход перекрытий, проверка элементов под уведомлениями, поздняя загрузка скинов и совместимость анимаций; сочетания клавиш восстановления сохранены.
- Включены #60, #61, #62 и последующие исправления, обновлены руководство и примеры скинов. Спасибо OddTurtleHead.
**Переход:** v0.3.2 и более ранние версии сначала обновляются до v0.3.3 вручную. После этого поддерживаемые установки могут получать следующие стабильные версии через консоль. Сделайте резервную копию. Docker: `docker compose pull && docker compose up -d` с сохранением тома данных. Управляемую службу остановите перед заменой файлов, затем запустите снова.
Проверено: 1102 автоматических теста, сборки фронтенда и бэкенда, проверка запуска Docker.
### [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).
+22 -6
View File
@@ -13,7 +13,7 @@
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
稳定版:[v0.3.2 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 皮肤恢复入口、应用库布局和插件配置表单。
稳定版:[v0.3.3 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 控制台一键更新、升级恢复与皮肤兼容性改进。
@@ -214,11 +214,13 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
在管理后台的 WebRTC 高级参数中可设置:
- **公网媒体地址**:WebSpeak 网关可被 UDP 访问的 IP 或域名,不含协议、路径或端口。优先于网页入口推断;留空时按 `Origin`、`X-Forwarded-Host`、`Host` 推断。域名会解析为 IP 候选。反代域名不一定是媒体地址。
- **公网媒体地址**:WebSpeak 网关可被 UDP 直达的 IP 或域名,不含协议、路径或端口。有公网 IP 时优先填它;Cloudflare Tunnel/纯 TCP 入口不要填 CF 代理域名。优先于网页入口推断;留空时按 `Origin`、`X-Forwarded-Host`、`Host` 推断,但 Cloudflare 请求不会再拿 CF 边缘 Host 当媒体地址。域名会解析为 IP 候选。
- **启用 IPv6 候选**:默认关闭;开启后保留 IPv4,同时收集 IPv6。需确保 IPv6 路由及 UDP 防火墙放行。
- **语音 STUN 服务**:可设置 `stun:turn.teamspeak.com:3478`,浏览器和网关使用同一服务发现公网映射。留空保留旧行为:werift 网关仍使用库内置 STUN,浏览器不配置 STUN。当前字段仅支持可通过 IPv4 访问的 UDP STUN 域名或 IPv4 地址,不接受 IPv6 字面量、TURN 或凭据;IPv6 媒体候选独立于 STUN 开关。
保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。只有 TCP 隧道而无可用 UDP/IPv6 路径时,仍会回退兼容传输。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。
保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。
手机流量或 UDP 被拦时,可配置外部 TURN 作为可选后备:在管理台“服务器 → 语音”填写 TURN REST URL、共享密钥和有效期,或使用 `WEBSPEAK_TURN_REST_URLS`、`WEBSPEAK_TURN_REST_SECRET` 环境变量。控制台保存的配置优先,且不需要重启网关,对新连接生效。默认保持 `WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all`,先试直连;只有确认 UDP 完全不可用时才用 `relay`。`WEBSPEAK_VOICE_PROFILE` 默认 `auto`:只有经过可信 Cloudflare 代理的请求才启用自适应 buffer,直连及其他请求继续使用旧 80ms/裸 PCM 行为;本机 Tunnel 连接默认可信,cloudflared 从其他地址连接时需配置 `WEBSPEAK_TRUSTED_PROXIES`。需要直连也启用时显式设 `adaptive`,也可在控制台“语音模式”覆盖。WebSocket Opus 默认关闭,可在“服务器 → 语音”或通过 `WEBSPEAK_VOICE_OPUS_WS=1` 启用,并需使用 `adaptive`。直连 UDP 与 TURN 都无法提供媒体路径时,会话报告 `NO_MEDIA_PATH` 并使用兼容传输。完整部署、验收和回滚见 [`CLOUDFLARE_TUNNEL_VOICE.md`](CLOUDFLARE_TUNNEL_VOICE.md),模板见 `deploy/coturn/` 和 `deploy/cloudflared/`。
### 屏幕共享的 ICE 候选
@@ -329,7 +331,7 @@ relay.example.com {
皮肤包负责外观、布局及其附属小组件。管理员可安装、启用和设置默认皮肤;开发时遵循公开接口,无需修改 WebSpeak 源码。
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) · [宿主顶栏 toolbar 示例](./examples/HOST-CHROME-TOOLBAR.md)
### 功能插件 `.wplugin`
@@ -366,12 +368,26 @@ relay.example.com {
## 更新日志
<a id="live-update-2026-11-13"></a>
<a id="latest-release-notes"></a>
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
**本次重点:管理员控制台新增正式版本检查与一键更新。**
- 管理员可检查官方 GitHub Releases,选择版本并确认安装;下载包必须通过 SHA-256 校验。首期自动安装支持前台运行的 Linux x64 官方发布包。Windows、Linux arm64、Docker、源码,以及 systemd、PM2、Supervisor 托管实例均保留版本检查和发行说明入口,安装仍按各部署方式手动完成。
- 更新仅替换程序文件,保留 `data/`、`config.json`、`certs/` 及已安装的皮肤和插件。安装会重启进程,语音会话和管理页面会短暂断开。SHA256SUMS.txt 是完整性校验和,不是数字签名。
- 加固升级健康检查、失败回滚和断电/进程中断后的启动恢复;恢复流程与更新进程共享锁,防止正常更新被重复启动误回滚。下载超限、写盘失败或取消时会中止请求、释放响应流,并清理并行下载。
- 皮肤可通过声明的布局槽位和受保护样式变量调整恢复入口与宿主控件的外观;不可读或不可用时回退到默认布局和样式。改进浮动入口的遮挡避让、提示消息穿透判断、皮肤延迟加载和动画兼容性,保留恢复快捷键。
- 纳入 #60、#61、#62 及后续维护修复,更新皮肤开发文档和示例。感谢 OddTurtleHead 的贡献。
**升级说明:** v0.3.2 及更早版本请先手动升级到 v0.3.3;之后可在支持的部署中使用控制台安装后续正式版。升级前请备份数据。Docker 使用 `docker compose pull && docker compose up -d` 并保留数据卷;服务托管实例请停止服务、替换程序文件后再启动。
验证:1102 项自动化测试通过,前后端构建及 Docker 启动健康检查通过。
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
<a id="live-update-2026-11-13"></a>
- 第三方皮肤可以为宿主装饰添加样式。恢复入口和授权弹窗由宿主管理,应用皮肤后仍能切回内置皮肤。感谢 ph1gros 对 TS3 版本识别及兼容性文档的贡献(#46),以及 OddTurtleHead 对宿主装饰和皮肤恢复的贡献(#57)。
- 日间、夜间和 ILLUSIA 的应用库在顶部工具栏展开。KAAK 3.1.134 将应用库放入最左侧图标栏,按钮与相邻控件对齐。固定应用排在列表前面。
- 插件后台提供字段编辑器,以及 P2P 文件传输、视频同看和 TSMusicBot 的配置表单。插件页面可以打开对应仓库。
+138 -13
View File
@@ -26,6 +26,8 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
宿主外壳与恢复入口的 toolbar 停靠见 [Host Chrome Toolbar 示例](examples/HOST-CHROME-TOOLBAR.md):它用最小包演示 `mode: "toolbar"`、按页候选锚点、工具栏令牌、应用库去重和坏锚点回退,不包含任何真实服务器或成员数据。
## 使用与发布
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
@@ -406,7 +408,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 以胶囊或 `mode: "toolbar"` 的宿主按钮停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 以及 `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
| 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) |
`voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
@@ -438,7 +440,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。
- 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。
- 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-recovery-toolbar`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]`、`:root [data-ws-part="home.header"] [data-ws-host-recovery-toolbar]` 这类带公开钩子的混合写法)。
- 无 Popover API 或顶层提升被拒绝时,恢复胶囊会退回固定宿主层并使用 32 位最大 `z-index: 2147483647`。宿主层在 `#app` 之后追加到 `document.body`;与树内皮肤层同为最大层级时,后绘制的宿主层仍在上面。顶层(top layer)路径的 `showPopover()` / `showModal()` 仍高于两者。
可主题化的宿主部件:
@@ -453,15 +455,15 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
### 恢复入口与授权对话框:结构上不可被皮肤触及
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局,或声明 `mode: "toolbar"` 后以无胶囊壳的宿主按钮并入皮肤顶栏(见下文「工具栏模式」):
1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `<dialog>` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点,或用 `mode: "toolbar"` 改成宿主顶栏按钮);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;无论胶囊是停靠、浮动还是被 `mode: "toolbar"` 替换,快捷键都会临时隐藏工具栏并显示完整胶囊。macOS 上 ⌥ 会把字母键变成派生字符(美式为 `®`),宿主同时按物理键码 `KeyR` 判定,所以该组合键仍然生效。它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
@@ -469,7 +471,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复入口停靠在皮肤界面里,而不是固定盖在左下角。默认仍是带胶囊壳的恢复胶囊;显式写 `mode: "toolbar"` 时改为无胶囊壳的宿主按钮,可直接并入皮肤顶栏。两种形态都是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它们的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
```json
"slots": {
@@ -479,10 +481,12 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
| 字段 | 规则 |
| --- | --- |
| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 |
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
| 键名 | `host.recovery` 表示整组恢复入口(胶囊或 toolbar 组合);`host.recovery.built-in` 与 `host.recovery.library` 表示两个独立按钮,只接受 toolbar 形态。同一份 `chrome.json` 只能二选一:声明了 `host.recovery` 就不能再声明独立按钮键,反之亦然。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称,或 1–8 个候选名称组成的数组(按页面/组件变体排列,重复项自动去重);宿主按顺序取第一个可见匹配,因此同一份声明可同时覆盖首页和语音页。每个候选名最长 240 字符,不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;控件在锚点矩形内按此水平对齐,并垂直居中。 |
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。仅胶囊模式可用;`mode: "toolbar"` 与 `compact: true` 同时出现会被拒绝。 |
| `mode` | 可选,`"capsule"` 或 `"toolbar"`。`host.recovery` 省略时保持历史默认 `"capsule"`(旧皮肤无需改动);`host.recovery.built-in` / `host.recovery.library` 省略时为 `"toolbar"`,且显式写 `"capsule"` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。 |
| `appearance` | 可选,`"label"`(默认)、`"icon"` 或 `"icon-and-label"`,只接受 toolbar 模式。`label` 保持旧文字按钮;`icon` 使用宿主 16px 图标、24px 宽按钮和零内边距;`icon-and-label` 同时显示图标和本地化文字。三种形态都保留 `aria-label` / `title`。胶囊只接受 `label`;未知值或胶囊中的图标形态会以 `SKIN_CHROME_SLOT_INVALID` 拒绝。 |
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
@@ -490,11 +494,11 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊或 toolbar 按钮位于顶层,会挡住它下面的一切,因此宿主还会检查控件的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;同一页面内,当前位置不遮挡时不会为了回到默认角落而移动(默认角落“看起来空”可能只是被模态对话框的遮罩或提示条暂时挡住);进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,并在默认角落和当前位置都空闲(鼠标也不在那里)时回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。这些胶囊令牌也是 toolbar 颜色的最终回退;toolbar 的圆角、内边距、高度和阴影使用下一节自己的默认值,不会继承胶囊的 999px 圆角或浮动阴影。
| 令牌 | 规则 |
| --- | --- |
@@ -512,6 +516,106 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
#### 工具栏模式:把恢复按钮并进皮肤顶栏(`mode: "toolbar"`)
默认的恢复入口是带胶囊壳的浮动/停靠胶囊。若皮肤顶栏已有自己的按钮风格,可以在 `chrome.json` 中显式声明 `mode: "toolbar"`,让宿主在锚点位置绘制**无胶囊壳的真实宿主按钮**。按钮仍由宿主创建、标注、聚焦和点击,位于闭合 Shadow DOM 的顶层;皮肤只提供锚点、`appearance` 形态声明和 `--skin-recovery-toolbar-*` 令牌,不能替换宿主图标、文案、顺序、点击处理或取得 DOM。`.ws-host-toolbar`、`data-ws-host-recovery-toolbar` 与 `data-ws-recovery-action` 都不是公开钩子,皮肤选择器引用它们会被拒绝。
两种声明方式互斥,同一份 `chrome.json` 只能选一种:
**组合式**(两个动作共用一个锚点,并排成一组,顺序为先「使用内置皮肤」、后「应用库」):
```json
"slots": {
"host.recovery": {
"mode": "toolbar",
"appearance": "icon",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
```
**独立式**(每个动作有自己的锚点,可放在顶栏两侧或不同部件上):
```json
"slots": {
"host.recovery.built-in": {
"mode": "toolbar",
"appearance": "icon-and-label",
"anchor": ["home.header-tools", "voice.header-actions"],
"align": "end"
},
"host.recovery.library": {
"mode": "toolbar",
"appearance": "icon",
"anchor": ["home.header-tools", "voice.header-actions"],
"align": "start"
}
}
```
上面只是示意:两个独立按钮若使用同一锚点,应选不同的 `align` 或不同锚点,否则会互相覆盖。
规则:
- `mode` 省略时,`host.recovery` 仍是 `capsule`,旧皮肤行为不变;独立按钮键省略时是 `toolbar`,显式写 `capsule` 会被拒绝。模式必须显式声明,宿主不会从 `compact` 或其他字段推断。
- `compact` 只适用于胶囊;toolbar 配 `compact` 会被拒绝。toolbar 不会折叠成 ◈;`appearance` 省略时仍显示完整文字按钮。
- `appearance: "icon"` 只改变 toolbar 的可见内容,不移除按钮的可访问名称。宿主图标为内联 SVG,`aria-hidden="true"`;按钮保留当前语言的 `aria-label`,`title` 仍说明动作/快捷键。`icon-and-label` 同时显示图标和文字。快捷键与失败回退始终使用完整文字胶囊,不受 toolbar 外观影响。
- 组合式下「应用库」按钮只在应用库可用(已连接且插件会话就绪)时渲染;「使用内置皮肤」始终渲染。
- 独立式下每个动作独立停靠:一个锚点失效只把该动作放回浮动胶囊,另一个仍留在工具栏;两个都失效时显示完整浮动胶囊。toolbar 模式下的胶囊永不折叠,因为它是兜底入口而不是设计目标。
- 回退、抗抖动和复查节奏与胶囊相同:锚点失效立即回退;恢复后需连续 2 次检查通过才重新停靠;停靠时约 400 ms 复查,浮动时约 1 s。
- 锚点候选数组按顺序取第一个可见项;页面切换、皮肤重载或锚点显隐后会重新解析,不要求重新绑定。
- 快捷键 `Ctrl+Alt+Shift+R` / `⌘+⌥+⇧+R` 会隐藏工具栏并召唤完整胶囊;关闭(Escape 或焦点离开)后,锚点仍有效的 toolbar 自动恢复。快捷键仍在捕获阶段处理。
- 按钮的最小命中高度、可见图标/文字、焦点环和指针/键盘操作都由宿主保证;皮肤不能通过选择器隐藏 toolbar、移除可访问名称或把按钮变成零尺寸。`appearance` 只能选择宿主提供的三种形态。
**应用库去重**:只要皮肤声明了 toolbar 形式的恢复入口(组合式的 `host.recovery`,或独立式的 `host.recovery.library`),并且应用库可用,宿主就把工具栏里的「应用库」按钮当作该页唯一的应用库入口,并隐藏普通的 `host.plugins.launcher`。即使锚点失效、入口退回浮动胶囊,启动器仍保持隐藏(胶囊继续提供应用库按钮),避免同一页出现两个入口;应用库不可用时启动器照常显示,工具栏也不渲染该按钮。这个去重只影响 toolbar 声明,不改变普通胶囊皮肤或内置皮肤。
**工具栏令牌**:皮肤在皮肤根、锚点或锚点祖先上声明下列普通变量;宿主从每个按钮当前锚点的计算样式读取、校验,再写入闭合 Shadow DOM。每个 `--skin-recovery-toolbar-*` 都有全局回退 `--skin-host-toolbar-*`,前者优先。组合式和独立式按钮共用同一组变量名;由于值按锚点继承,不同页面或不同锚点可以给同一变量不同的值。
| 令牌 | 默认与规则 |
| --- | --- |
| `--skin-recovery-toolbar-background` | 按钮背景。省略时沿用已解析的胶囊底色(`--skin-recovery-background` / `--skin-host-background` / 宿主白色)。完全透明(`transparent` 或 alpha 0)会保留;非零 alpha 仍按旧规则转为不透明 RGB。 |
| `--skin-recovery-toolbar-foreground` | 图标/文字色。与不透明按钮背景的对比度必须 ≥ 4.5;背景透明时改与 `surface` 令牌或宿主采样的锚点/祖先不透明底色比较。整组颜色不可读时,背景和文字一起回退到已解析的胶囊配色。 |
| `--skin-recovery-toolbar-border` | 边框色。完全不透明时与有效背景的对比度必须 ≥ 3,否则使用已解析的胶囊边框;完全透明边框有效。 |
| `--skin-recovery-toolbar-hover-background` | 悬停背景,默认使用正常背景;宿主独立检查悬停后的文字对比度,不合格时回退到正常背景。 |
| `--skin-recovery-toolbar-hover-border` | 悬停边框,默认使用正常边框;校验颜色语法,允许 Classic 的 subtle `#b8cfe8` 边缘,不强制 3:1。 |
| `--skin-recovery-toolbar-surface` | 可选的完全不透明底色,仅用于透明按钮/悬停背景的文字对比度检查,不绘制按钮本身。优先级为 per-part、global、锚点/祖先计算背景采样、宿主白色。渐变或图片顶栏应显式提供该令牌。 |
| `--skin-recovery-toolbar-radius` | 圆角,px 长度,限制 0–24,默认 6;胶囊的 999px 不会带入 toolbar。 |
| `--skin-recovery-toolbar-font` | 字体族列表,规则与胶囊相同:只接受已安装字体或通用族名,皮肤 `@font-face`(包括 `ws-` 前缀)整项忽略。 |
| `--skin-recovery-toolbar-font-size` | 字号,px,默认沿用当前尺寸档位的宿主字号(≥ 11/12/13 px),限制 11–20 px;不能低于宿主下限。 |
| `--skin-recovery-toolbar-padding` | 一个或两个长度值(`上下 左右`,或一个值表示四边相同),默认 `6px 12px`,每个方向限制 0–48 px;接受 px 和无单位 `0`。`appearance: "icon"` 时宿主强制零内边距。 |
| `--skin-recovery-toolbar-height` | 最小高度,px。省略时保持当前尺寸档位的 28/32/36 px;显式值限制 22–72 px,因此 Classic 22px 仅在 toolbar 生效。胶囊仍保持 28/32/36 px。 |
| `--skin-recovery-toolbar-shadow` | `none` 或单个简单 `box-shadow`(2–4 个 px 偏移/尺寸加一个颜色,最长 160 字符),默认 `none`。`url()`、`var()`、多个阴影和额外声明一律忽略为 `none`,胶囊阴影不会带入。 |
| `--skin-recovery-toolbar-gap` | 组合式两个宿主按钮之间的间距,px,默认 4,限制 0–16;Classic 可设 `1px`。独立式各自只有一个按钮。 |
| `--skin-recovery-toolbar-icon-size` | 宿主图标边长,px,默认 16,限制 12–24。`appearance: "icon"` 时按钮宽度为 `max(24px, icon-size + 8px)`,16px 图标对应 Classic 24px 按钮。 |
无效、不可读的颜色,越界的字号/高度/内边距/间距/图标尺寸,皮肤字体和非法阴影都只会回退到可见的宿主默认值,不会隐藏按钮。toolbar 文案由宿主按当前界面语言本地化,长文本换行而不是裁掉;`prefers-reduced-motion` 下同样没有过渡。
**Classic 麦克风按钮对齐示例**(22px 高、透明底、1px 边框、2px 圆角、11px 字号、16px 图标、1px 组间距):
```css
:root {
--skin-host-toolbar-background: transparent;
--skin-host-toolbar-foreground: #1a1a1a;
--skin-host-toolbar-border: transparent;
--skin-host-toolbar-hover-background: #eaf2fd;
--skin-host-toolbar-hover-border: #b8cfe8;
--skin-host-toolbar-radius: 2px;
--skin-host-toolbar-font-size: 11px;
--skin-host-toolbar-padding: 0 4px;
--skin-host-toolbar-height: 22px;
--skin-host-toolbar-gap: 1px;
--skin-host-toolbar-icon-size: 16px;
--skin-host-toolbar-surface: #ffffff;
}
```
配合 `"appearance": "icon"` 使用。`surface` 只参与可读性计算;顶栏实际不是白色时应改成真实不透明底色。图标按钮的零内边距由宿主强制执行,`padding` 令牌仍用于 `label` / `icon-and-label`。
**旧 slots 兼容**:旧包里的 `{ "anchor": ..., "align": ..., "compact": ... }` 没有 `mode`,仍按胶囊停靠,行为不变;`chrome.json` 的其它字段(`visibleParts`、`hiddenParts`、`icons`)不受影响。只有显式写 `mode: "toolbar"` 才会切换形态。
**不影响其它宿主控件**:工具栏令牌只作用于恢复按钮。授权对话框(`--skin-permission-*`)和皮肤加载失败横幅(`--skin-load-recovery-*`)继续使用各自令牌与默认外观;本节的变量不会改变它们。
#### 受保护控件的主题化
28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
@@ -628,7 +732,28 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 |
| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 |
| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 |
| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 |
| `slots` | 可选,最多 8 项;键名只能是 `host.recovery`(整组)或 `host.recovery.built-in` / `host.recovery.library`(独立 toolbar 按钮),两种写法互斥。值只能包含 `anchor`、`align`、`compact`、`mode`、`appearance`;`anchor` 可以是单个部件名或最多 8 个候选名的数组。详见上文「将恢复入口停靠到皮肤布局」与「工具栏模式」。未知键、指向 `host.*` 或可信宿主部件的锚点、`toolbar` 配 `compact`、非法 `appearance` 或胶囊中的图标形态都会被拒绝。 |
工具栏形态只需在 `host.recovery` 上写 `"mode": "toolbar"`(两个按钮共用一个锚点):
```json
"slots": {
"host.recovery": {
"mode": "toolbar",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
```
也可以改用独立按钮键,让两个动作各自停靠:
```json
"slots": {
"host.recovery.built-in": { "anchor": ["home.header-tools", "voice.header-actions"], "align": "end" },
"host.recovery.library": { "anchor": ["home.header-tools", "voice.header-actions"], "align": "start" }
}
```
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
+90
View File
@@ -0,0 +1,90 @@
# Cloudflare Tunnel 语音兼容性说明
## 范围
本文件说明网页/信令通过 Cloudflare Tunnel、WebRTC 媒体尽量直连 UDP 的兼容性
改动。默认行为是 `WEBSPEAK_VOICE_PROFILE=auto`:
- 非 Cloudflare 请求保持 `legacy`:80ms 固定窗口、超限 `clear()`、裸
1920-byte PCM、旧 WebRTC mixer。
- 只有来自受信任代理且带 Cloudflare 标记的请求才自动进入 `adaptive`。
- 显式 `legacy` 或 `adaptive` 覆盖自动判定。
- TURN 是可选后备,不默认强制 `relay`。
本文件是内部实现说明,不代表整体验收、发布或实际部署证明。
## 主要改动
### WebRTC、ICE 与回退
- `src/server/voice-ice-config.ts`:支持静态 ICE、TURN REST、浏览器/网关
transport policy、语音 profile、Opus WebSocket 和 jitter 上限。
- `src/server/turn-credentials.ts`:按 coturn `use-auth-secret` 生成短期凭证。
- `src/server/voice-bridge.ts`:仅当直接相邻代理位于
`WEBSPEAK_TRUSTED_PROXIES` 中时,才根据 `cf-ray`、`cf-connecting-ip` 或
`cdn-loop` 判定 Cloudflare。直连客户端注入这些头不会改变 profile。
- Cloudflare 请求不再把 Tunnel `Host` 当作 ICE 媒体地址。未配置公网媒体
地址且没有 TURN 时返回 `NO_MEDIA_PATH`,浏览器使用兼容传输。
- 已下发 WebRTC 后建连或传输失败会自动恢复 PCM/Opus over WebSocket 的
上下行兼容音频,页面留在当前 TeamSpeak/WebSocket 会话;上行需要已有
麦克风权限。横幅继续使用 `WEBRTC_FAILED`,并保留“重新连接 WebRTC”。
- “重新连接 WebRTC”只重试 WebRTC,不调用整段连接流程、不新建语音
WebSocket。重连期间保持兼容收发,等 `onReady` 后才停止兼容音频并清除
失败横幅和按钮,避免双路音频或切换静音。
- 重连再次失败时继续留在兼容模式保通话,横幅和按钮保留。网关未
advertise WebRTC 的既有兼容路径不变,也不显示这块失败按钮。
- `src/server/webrtc-audio.ts` 与 `web/src/voice/webrtc-transport.ts`:浏览器
和网关使用完整 ICE 列表;无 TURN 的 `relay` 策略快速失败。
- 已从 werift 源码确认 `turns:` 使用 TLS 控制连接;未做真实 coturn 端到端
联调。
### 兼容模式音频
- `legacy` 保留旧播放窗口、解码器重建、裸 PCM、4 帧 mixer 队列和每包
marker。
- `adaptive` 使用 `web/src/voice/jitter-buffer.ts`、可选服务端 pacer 和可选
Opus-over-WebSocket;Opus 默认关闭。
- `web/src/voice/opus-uplink.ts` 使用 WebCodecs Opus;不支持或失败时回退 PCM。
- Safari/Firefox 的 Opus 行为未逐台真机验证。
### 管理台与持久化
- 管理台“服务器 → 语音”提供 profile、Opus、jitter 上限和 TURN REST 配置。
- 非空控制台值覆盖环境变量;未修改字段保持数据库 `NULL`,继续继承环境变量。
- 清空 TURN URL 或移除密钥会显式停用环境变量中的 TURN REST。
- TURN 密钥使用网关主密钥加密存储,API 只返回是否已配置。
- 无关设置保存不会把未修改的语音字段写成控制台覆盖值。
## 示例配置
```bash
WEBSPEAK_VOICE_PROFILE=auto
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY=all
WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY=all
WEBSPEAK_VOICE_JITTER_MAX_MS=300
WEBSPEAK_VOICE_OPUS_WS=0
WEBSPEAK_TURN_REST_URLS='turn:turn.example.com:3478?transport=udp,turn:turn.example.com:3478?transport=tcp'
WEBSPEAK_TURN_REST_SECRET='<replace-with-demo-secret>'
WEBSPEAK_TURN_REST_TTL_SECONDS=21600
```
公网媒体地址示例使用 `192.0.2.10`;实际部署必须替换为可直接通过 UDP 到达的
地址。Cloudflare Tunnel 不转发 WebRTC UDP,也不能作为媒体地址。
## 数据库与回滚
- 语音覆盖配置写入现有 metadata 表,数据库保持 schema 13;未设置的值继承
环境变量,TURN 密钥继续加密保存。
- 0.3.3 会忽略并保留这些元数据,可以在自动更新健康检查失败后直接恢复旧代码。
- 恢复非 Cloudflare 旧音频行为:选择 `legacy`,或确保没有控制台覆盖后设置
`WEBSPEAK_VOICE_PROFILE=legacy`。
- 关闭 Opus:取消控制台选项或设置 `WEBSPEAK_VOICE_OPUS_WS=0`。
- 关闭 TURN:清空 TURN URL/移除密钥,或删除对应环境变量。
## 验证边界
- coturn/cloudflared 模板未在真实目标网络端到端联调。
- TURN 的 UDP/TCP/TLS、relay 端口和凭证一致性仍需在目标网络验证。
- Safari/Firefox WebCodecs Opus 与真实浏览器 jitter 表现仍需设备测试。
- 自动化测试和构建结果以本次审查的测试记录为准;历史报告中的通过数量
不应被视为本次独立复跑结果。
+106
View File
@@ -0,0 +1,106 @@
# Host chrome toolbar example
A minimal schema v3 open skin that docks the trusted recovery entry into the page header as Classic-aligned, host-owned icon buttons instead of the floating capsule shell. It is the smallest reference for `chrome.json` `mode: "toolbar"`, `appearance`, page-specific anchor candidates, transparent toolbar tokens, application-library de-duplication and the floating-capsule fallback.
- Source: [host-chrome-toolbar](./host-chrome-toolbar/)
- Importable package: [host-chrome-toolbar.wskin](./host-chrome-toolbar.wskin)
- Author: WebSpeak Community
- Shared component and permission rules: [skin development guide](../SKIN_DEVELOPMENT.md)
- Host chrome and toolbar contract: [skin development guide](../SKIN_DEVELOPMENT.md) (see the `chrome.json#slots` and toolbar-mode sections)
## Package layout
```text
host-chrome-toolbar/
manifest.json # schema v3, version 1.1.2, minAppVersion 0.3.4-dev.0, author WebSpeak Community
chrome.json # one grouped toolbar slot with a home/voice anchor list
skin.css # light page theme, Classic toolbar tokens and header space
```
This package requires WebSpeak 0.3.4-dev.0 or later. Released WebSpeak 0.3.3 and earlier do not accept `mode`, `appearance`, or anchor candidate arrays, so importing it there cannot provide toolbar-mode behavior. Older slots without those fields remain valid and keep their capsule presentation.
`skin.css` uses only public `data-ws-part` hooks and sets `--skin-host-toolbar-*` / `--skin-recovery-toolbar-*` variables. It never targets the host toolbar DOM, the recovery capsule, the authorization dialog or the load-failure banner.
## Grouped declaration
```json
{
"schemaVersion": 1,
"slots": {
"host.recovery": {
"mode": "toolbar",
"appearance": "icon",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
}
```
- `mode: "toolbar"` asks the host to render two real host buttons without the capsule shell.
- `appearance: "icon"` selects the host-owned 16px built-in-skin and application-library SVGs. Each button is 24px wide, has zero padding and keeps its localized `aria-label` and `title`.
- The anchor list covers both pages; the host picks the first visible one and re-resolves it after a page switch. A missing or hidden anchor returns the complete, visible floating capsule.
- While the library is available, the host hides the ordinary application-library launcher so the page keeps exactly one library entry. The fallback capsule keeps that entry when the anchor fails.
- The host owns the icons, labels, click handlers, focus behaviour, shortcut handling and fallback. The skin only supplies the anchor, appearance and token values.
- Old slots without `mode` keep the capsule presentation; this example opts in explicitly.
## Classic tokens
```css
:root {
--skin-host-toolbar-background: transparent;
--skin-host-toolbar-foreground: #1a1a1a;
--skin-host-toolbar-border: transparent;
--skin-host-toolbar-hover-background: #eaf2fd;
--skin-host-toolbar-hover-border: #b8cfe8;
--skin-host-toolbar-surface: #f4f7fb;
--skin-host-toolbar-radius: 2px;
--skin-host-toolbar-font-size: 11px;
--skin-host-toolbar-padding: 0 4px;
--skin-host-toolbar-height: 22px;
--skin-host-toolbar-gap: 1px;
--skin-host-toolbar-icon-size: 16px;
}
```
This produces 22px-high buttons, a transparent normal surface, a 1px transparent border, 2px corners, 11px type, 16px icons and a 1px gap. Hover uses `#eaf2fd` with a `#b8cfe8` edge. `surface` is not painted; it tells the host which opaque colour to use for contrast checks. Set it to the real header colour when adapting the example.
The package also declares an opaque `--skin-recovery-*` capsule palette. Capsule mode keeps its historical 28/32/36px size floors, full text labels and fixed `#fff7ed` built-in action; toolbar tokens never shrink or restyle that escape hatch.
## Independent declaration
Use the per-action keys when the two actions need different anchors or appearances. Do not declare them together with `host.recovery`.
```json
{
"schemaVersion": 1,
"slots": {
"host.recovery.built-in": {
"mode": "toolbar",
"appearance": "icon-and-label",
"anchor": ["home.header-tools", "voice.header-actions"],
"align": "end"
},
"host.recovery.library": {
"mode": "toolbar",
"appearance": "icon",
"anchor": ["home.header-tools", "voice.header-actions"],
"align": "start"
}
}
}
```
`appearance` defaults to `"label"` for backward compatibility. The accepted toolbar values are `"label"`, `"icon"` and `"icon-and-label"`; unknown values and icon appearances in capsule mode are rejected with `SKIN_CHROME_SLOT_INVALID`.
## Trying it
1. Build or import [host-chrome-toolbar.wskin](./host-chrome-toolbar.wskin) in a local WebSpeak instance.
2. Allow the third-party skin when the host asks.
3. Connect to **Demo Server**, join **Demo Lobby**, and check the header as **Demo User**.
4. Confirm the two 24px host icons appear at the end of the home and voice headers, remain transparent at rest, use the Classic hover colours, and open the built-in-skin and application-library actions.
5. Remove or hide the anchor in the page inspector; the complete floating capsule should appear at a free corner. Restore the anchor; the toolbar should re-dock after the anti-flap check.
6. Press `Ctrl+Alt+Shift+R` (`⌘+⌥+⇧+R` on macOS); the toolbar hides, the complete full-text capsule appears and focuses its first button. Press Escape to return to the toolbar.
7. Check a narrow viewport and all five interface languages. Icon-only names must remain available to assistive technology, and the fallback capsule must keep readable localized labels.
The example contains no server addresses, member names, chat contents or other real instance data. Public descriptions use only the Demo Server / Demo Lobby / Demo User placeholders.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,11 @@
{
"schemaVersion": 1,
"slots": {
"host.recovery": {
"mode": "toolbar",
"appearance": "icon",
"anchor": ["home.header", "voice.header"],
"align": "end"
}
}
}
@@ -0,0 +1,13 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.host-chrome-toolbar",
"name": "Host Chrome Toolbar",
"version": "1.1.2",
"author": "WebSpeak Community",
"license": "AGPL-3.0-only",
"description": "Minimal open skin that docks Classic-aligned host-owned recovery icons into the page header.",
"entry": "skin.css",
"chrome": "chrome.json",
"minAppVersion": "0.3.4-dev.0"
}
@@ -0,0 +1,76 @@
/* Host chrome toolbar demo — v3 open skin (schemaVersion 3).
The host owns the recovery structure, icons, labels, focus and actions.
This package only declares an anchor, appearance and validated tokens. */
:root {
color-scheme: light;
--skin-demo-surface: #f4f7fb;
--skin-demo-foreground: #1a1a1a;
--skin-demo-border: #d5dee8;
--skin-demo-accent: #1d4ed8;
/* Classic microphone-button geometry and colours. `surface` is the opaque
colour used to check text contrast behind the transparent toolbar. */
--skin-host-toolbar-background: transparent;
--skin-host-toolbar-foreground: #1a1a1a;
--skin-host-toolbar-border: transparent;
--skin-host-toolbar-hover-background: #eaf2fd;
--skin-host-toolbar-hover-border: #b8cfe8;
--skin-host-toolbar-surface: #f4f7fb;
--skin-host-toolbar-radius: 2px;
--skin-host-toolbar-font: Tahoma, "Segoe UI", sans-serif;
--skin-host-toolbar-font-size: 11px;
--skin-host-toolbar-padding: 0 4px;
--skin-host-toolbar-height: 22px;
--skin-host-toolbar-gap: 1px;
--skin-host-toolbar-icon-size: 16px;
--skin-host-toolbar-shadow: none;
/* The fallback and shortcut capsule remains opaque and full-text. */
--skin-recovery-background: #ffffff;
--skin-recovery-foreground: #1a1a1a;
--skin-recovery-border: #9db6b2;
--skin-recovery-accent: #1d4ed8;
--skin-recovery-radius: 8px;
}
[data-ws-page] {
color: #1a1a1a;
background: #ffffff;
font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif;
}
[data-ws-part="home.header"],
[data-ws-part="voice.header"] {
background: #f4f7fb;
border-bottom: 1px solid var(--skin-demo-border);
color: var(--skin-demo-foreground);
}
/* Keep the two 24px icon buttons clear of ordinary header actions. */
[data-ws-part="home.header"],
[data-ws-part="voice.header"] {
padding-right: 72px;
}
[data-ws-part="home.join-card"],
[data-ws-part="home.content"],
[data-ws-part="voice.workspace"],
[data-ws-part="voice.content"] {
color: var(--skin-demo-foreground);
}
[data-ws-part="home.join-card"] {
background: #ffffff;
border: 1px solid var(--skin-demo-border);
border-radius: 12px;
box-shadow: 0 16px 40px #10203012;
}
[data-ws-part="voice.audio-dock"] {
background: #f4f7fb;
border-top: 1px solid var(--skin-demo-border);
}
[data-ws-part="home.footer"] { color: #52606d; }
[data-ws-part="home.footer.clear"] { color: var(--skin-demo-accent); }
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-android-gateway",
"version": "0.3.2",
"version": "0.3.4-dev.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-android-gateway",
"version": "0.3.2",
"version": "0.3.4-dev.0",
"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.2",
"version": "0.3.4-dev.0",
"private": true,
"type": "module",
"main": "index.cjs",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-webclient",
"version": "0.3.2",
"version": "0.3.4-dev.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.3.2",
"version": "0.3.4-dev.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@discordjs/opus": "^0.10.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-webclient",
"version": "0.3.2",
"version": "0.3.4-dev.0",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/turn-credentials.test.ts src/server/voice-ice-config.test.ts src/server/audio-pacer.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/voice-ice.test.ts src/shared/voice-profile.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/jitter-buffer.test.ts web/test/remote-playback.test.ts web/test/opus-uplink.test.ts web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/host-recovery-presentation.test.ts web/test/opus-uplink-browser.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",
+100 -23
View File
@@ -28,8 +28,8 @@ code_missing() {
return 1
}
# A backup can only repair an install if it recorded a swap and still holds
# every entry needed to boot. Partial/legacy backups must be skipped.
# A backup can only repair a missing-code install if it is complete. Partial
# backups are still resumable when they belong to the active task.
backup_is_complete() {
[ -f "$1/.webspeak-swap.json" ] || return 1
for entry in $required_entries; do
@@ -52,6 +52,86 @@ task_backup_can_repair() {
return 0
}
state_file="$data_dir/updates/state.json"
lock_file="$data_dir/updates/update.lock"
read_update_task() {
task_id=""
task_status=""
if [ -f "$state_file" ]; then
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
fi
case "$task_id" in
""|*[!A-Za-z0-9_-]*) task_id="" ;;
esac
}
read_update_task
process_start() {
# After the last ')' field 3 is first; starttime (field 22) is twentieth.
if [ -r "/proc/$1/stat" ]; then
sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}'
fi
}
release_recovery_lock() {
if [ "${lock_owned:-0}" = 1 ] && [ "$(cat "$lock_file" 2>/dev/null)" = "$lock_payload" ]; then
rm -f -- "$lock_file"
fi
lock_owned=0
}
acquire_recovery_lock() {
# Share the updater's exclusive-create JSON lock. A distinct task id stops
# a delayed restart runner from taking this recovery lock over. Keep it for
# the entire restore, and only reclaim a proven-dead, unchanged owner.
mkdir -p "$data_dir/updates"
lock_owned=0
start=$(process_start "$$")
lock_payload="{\"pid\":$$,\"taskId\":\"recovery_$$\",\"createdAt\":\"\",\"processStart\":\"$start\"}"
for attempt in 1 2 3 4; do
if (umask 077; set -C; printf '%s\n' "$lock_payload" > "$lock_file") 2>/dev/null; then
lock_owned=1
trap 'release_recovery_lock' 0
trap 'exit 1' HUP INT TERM
return 0
fi
observed=$(cat "$lock_file" 2>/dev/null) || return 1
owner=$(printf '%s\n' "$observed" | sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\)[[:space:]]*[,}].*/\1/p' | head -n 1)
owner_task=$(printf '%s\n' "$observed" | sed -n 's/.*"taskId"[[:space:]]*:[[:space:]]*"\([^"]\{1,\}\)".*/\1/p' | head -n 1)
case "$owner" in ""|*[!0-9]*) return 1 ;; esac
[ -n "$owner_task" ] || return 1
if [ "$owner" != 0 ]; then
if kill -0 "$owner" 2>/dev/null || [ -d "/proc/$owner" ]; then
saved_start=$(printf '%s\n' "$observed" | sed -n 's/.*"processStart"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
current_start=$(process_start "$owner")
# Unknown markers and inaccessible processes are conservatively live.
if [ -z "$saved_start" ] || [ -z "$current_start" ] || [ "$saved_start" = "$current_start" ]; then
return 1
fi
elif [ ! -d /proc ]; then
return 1
fi
fi
[ "$(cat "$lock_file" 2>/dev/null)" = "$observed" ] || continue
rm -f -- "$lock_file" || return 1
done
return 1
}
recovery_needed() {
if code_missing; then
return 0
fi
case "$task_status" in
downloading|verifying|extracting|staging|restarting)
[ -n "$task_id" ] && [ -d "$backups/$task_id" ] && [ -f "$backups/$task_id/.webspeak-swap.json" ]
return $?
;;
esac
return 1
}
restore_from_backup() {
backup="$1"
# Move whatever partial new code the interrupted swap left in the install
@@ -80,33 +160,29 @@ restore_from_backup() {
done
}
if code_missing; then
if recovery_needed; then
if ! acquire_recovery_lock; then
echo "WebSpeak update or recovery is already running, or its lock cannot be verified; refusing to change application files." >&2
exit 75
fi
# The runner may have completed between the first state read and the lock.
read_update_task
fi
if [ "${lock_owned:-0}" = 1 ] && recovery_needed; then
restore_backup=""
# The interrupted task is the source of truth: backups/<task.id> holds the
# exact version that was running before the swap. A successful earlier
# update leaves its backup behind (M1 does not clean it up), so picking the
# first or alphabetically smallest backup can resurrect a much older build.
state_file="$data_dir/updates/state.json"
task_id=""
if [ -f "$state_file" ]; then
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
fi
# Task ids are generated as upd_<base36>_<hex>. Reject anything else so a
# tampered state.json cannot become a path traversal or a glob pattern.
case "$task_id" in
""|*[!A-Za-z0-9_-]*) task_id="" ;;
esac
if [ -n "$task_id" ]; then
# The interrupted task is the source of truth. Its backup may be partial
# while the old tree is being saved or while a previous recovery is still
# consuming it, but it must never be replaced by an older complete backup.
if [ -n "$task_id" ] && [ -d "$backups/$task_id" ]; then
candidate="$backups/$task_id"
if task_backup_can_repair "$candidate"; then
restore_backup="$candidate"
fi
fi
# No usable task backup (e.g. state.json was lost): use the most recently
# modified complete backup rather than whichever name happens to sort first.
if [ -z "$restore_backup" ]; then
else
# No current task backup (e.g. state.json was lost): use the most recently
# modified complete backup rather than whichever name happens to sort first.
for manifest in "$backups"/*/.webspeak-swap.json; do
[ -f "$manifest" ] || continue
backup="${manifest%/.webspeak-swap.json}"
@@ -129,4 +205,5 @@ if code_missing; then
fi
fi
release_recovery_lock
exec "$PWD/runtime/node" "$PWD/dist/index.js"
+7
View File
@@ -615,6 +615,13 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
webRtcStunServer: body.webRtcStunServer as string | undefined,
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
voiceProfile: body.voiceProfile as AdminSettingsInput["voiceProfile"],
voiceTurnUrls: typeof body.voiceTurnUrls === "string" ? body.voiceTurnUrls.slice(0, 4096) : undefined,
voiceTurnSecret: typeof body.voiceTurnSecret === "string" ? body.voiceTurnSecret.slice(0, 512) : undefined,
voiceTurnSecretAction: readPasswordAction(body.voiceTurnSecretAction),
voiceTurnTtlSeconds: readOptionalInteger(body, "voiceTurnTtlSeconds"),
voiceOpusWs: typeof body.voiceOpusWs === "boolean" ? body.voiceOpusWs : undefined,
voiceJitterMaxMs: readOptionalInteger(body, "voiceJitterMaxMs"),
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
relayEnabled: body.relayEnabled === true,
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
+122 -1
View File
@@ -15,8 +15,10 @@ import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from ".
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
import { pingTeamSpeakHost } from "../server/network-probe.js";
import { normalizeVoiceMediaHost, normalizeVoiceStunServer } from "../shared/voice-ice.js";
import { normalizeVoiceMediaHost, normalizeVoiceStunServer, normalizeVoiceTurnRestUrls, VOICE_JITTER_MAX_MS, VOICE_JITTER_MIN_MS, VOICE_TURN_MIN_SECRET_LENGTH, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MAX_SECONDS, VOICE_TURN_TTL_MIN_SECONDS } from "../shared/voice-ice.js";
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
import { DEFAULT_VOICE_ICE_CONFIG, type VoiceIceConfig } from "../server/voice-ice-config.js";
import { isVoiceProfileSetting } from "../shared/voice-profile.js";
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
@@ -43,6 +45,7 @@ export interface ManagedInviteView {
}
type ProbeFunction = typeof probeTeamSpeak;
const VOICE_TURN_SECRET_PURPOSE = "webspeak:voice-turn-rest-secret:v1";
export class AdminService {
private readonly tsAdmin: TsAdminService;
@@ -56,6 +59,8 @@ export class AdminService {
private readonly probe: ProbeFunction = probeTeamSpeak,
private readonly version = "0.1.0",
tsAdminClientFactory?: TsAdminQueryClientFactory,
/** Environment baseline; console values override it without requiring a restart. */
private readonly voiceIceDefaults: VoiceIceConfig = DEFAULT_VOICE_ICE_CONFIG,
) {
this.tsAdmin = new TsAdminService(database, masterSecret, logger, () => {
const settings = database.getSettings();
@@ -124,6 +129,7 @@ export class AdminService {
getAdminSettings(): AdminSettings {
const settings = this.database.getSettings();
const turn = this.resolveVoiceTurnSettings(settings);
return {
target: settingsTarget(settings),
hasPassword: Boolean(settings.tsPasswordEncrypted),
@@ -144,6 +150,12 @@ export class AdminService {
webRtcStunServer: settings.webRtcStunServer,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
voiceProfile: settings.voiceProfile ?? this.voiceIceDefaults.profile,
voiceTurnUrls: turn.urls.join("\n"),
hasVoiceTurnSecret: turn.secret.length > 0,
voiceTurnTtlSeconds: turn.ttlSeconds,
voiceOpusWs: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket,
voiceJitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs,
relayConfigured: settings.relayConfigured,
relayEnabled: settings.relayEnabled,
relayName: settings.relayName,
@@ -166,6 +178,43 @@ export class AdminService {
};
}
/** Resolve environment defaults plus console overrides for every new voice connection. */
getVoiceIceConfig(): VoiceIceConfig {
const settings = this.database.getSettings();
const turn = this.resolveVoiceTurnSettings(settings);
const turnRest = turn.urls.length > 0 && turn.secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
? { urls: turn.urls, secret: turn.secret, ttlSeconds: turn.ttlSeconds }
: undefined;
return {
servers: [...this.voiceIceDefaults.servers],
...(turnRest ? { turnRest } : {}),
transportPolicy: this.voiceIceDefaults.transportPolicy,
gatewayTransportPolicy: this.voiceIceDefaults.gatewayTransportPolicy,
profile: settings.voiceProfile ?? this.voiceIceDefaults.profile,
opusWebSocket: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket,
jitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs,
};
}
private resolveVoiceTurnSettings(settings: ReturnType<WebSpeakDatabase["getSettings"]>): { urls: string[]; secret: string; ttlSeconds: number } {
const baseline = this.voiceIceDefaults.turnRest;
const urls = settings.voiceTurnUrls === null
? baseline?.urls ?? []
: normalizeVoiceTurnRestUrls(settings.voiceTurnUrls) ?? [];
const ttlSeconds = settings.voiceTurnTtlSeconds ?? baseline?.ttlSeconds ?? VOICE_TURN_TTL_DEFAULT_SECONDS;
let secret = "";
if (settings.voiceTurnSecretEncrypted === null) {
secret = baseline?.secret ?? "";
} else if (settings.voiceTurnSecretEncrypted !== "") {
try {
secret = decryptSecret(settings.voiceTurnSecretEncrypted, this.masterSecret, VOICE_TURN_SECRET_PURPOSE);
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TURN shared secret could not be decrypted");
}
}
return { urls, secret, ttlSeconds };
}
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
const relays: ConfiguredAccelerationRelay[] = [];
for (const node of this.database.listRelayNodes()) {
@@ -420,6 +469,60 @@ export class AdminService {
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
}
const voiceProfile = input.voiceProfile === undefined ? current.voiceProfile : input.voiceProfile;
if (voiceProfile !== null && !isVoiceProfileSetting(voiceProfile)) {
throw new AdminInputError("INVALID_VOICE_PROFILE", "Voice profile must be auto, legacy or adaptive");
}
let voiceTurnUrls = current.voiceTurnUrls;
let requestedTurnUrls = current.voiceTurnUrls === null
? this.voiceIceDefaults.turnRest?.urls ?? []
: normalizeVoiceTurnRestUrls(current.voiceTurnUrls) ?? [];
if (input.voiceTurnUrls !== undefined) {
const normalized = normalizeVoiceTurnRestUrls(input.voiceTurnUrls);
if (normalized === null) throw new AdminInputError("INVALID_VOICE_TURN_URLS", "Use one turn:/turns: URL per entry, at most eight");
voiceTurnUrls = normalized.join("\n");
requestedTurnUrls = normalized;
}
let voiceTurnSecretEncrypted = current.voiceTurnSecretEncrypted;
const voiceTurnSecretAction = input.voiceTurnSecretAction ?? (input.voiceTurnSecret === undefined ? "keep" : "replace");
if (voiceTurnSecretAction === "remove") {
voiceTurnSecretEncrypted = "";
voiceTurnUrls = "";
requestedTurnUrls = [];
}
if (voiceTurnSecretAction === "replace") {
const secret = input.voiceTurnSecret?.trim() ?? "";
if (secret && secret.length < VOICE_TURN_MIN_SECRET_LENGTH) {
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", `The TURN shared secret must contain at least ${VOICE_TURN_MIN_SECRET_LENGTH} characters`);
}
voiceTurnSecretEncrypted = secret ? encryptSecret(secret, this.masterSecret, VOICE_TURN_SECRET_PURPOSE) : "";
}
const voiceTurnTtlSeconds = input.voiceTurnTtlSeconds === undefined ? current.voiceTurnTtlSeconds : input.voiceTurnTtlSeconds;
if (voiceTurnTtlSeconds !== null && (!Number.isInteger(voiceTurnTtlSeconds) || voiceTurnTtlSeconds < VOICE_TURN_TTL_MIN_SECONDS || voiceTurnTtlSeconds > VOICE_TURN_TTL_MAX_SECONDS)) {
throw new AdminInputError("INVALID_VOICE_TURN_TTL", `TURN credential lifetime must be between ${VOICE_TURN_TTL_MIN_SECONDS} and ${VOICE_TURN_TTL_MAX_SECONDS} seconds`);
}
const voiceOpusWs = input.voiceOpusWs === undefined ? current.voiceOpusWs : input.voiceOpusWs;
if (voiceOpusWs !== null && typeof voiceOpusWs !== "boolean") {
throw new AdminInputError("INVALID_VOICE_OPUS", "Opus over WebSocket must be a boolean");
}
const voiceJitterMaxMs = input.voiceJitterMaxMs === undefined ? current.voiceJitterMaxMs : input.voiceJitterMaxMs;
if (voiceJitterMaxMs !== null && (!Number.isInteger(voiceJitterMaxMs) || voiceJitterMaxMs < VOICE_JITTER_MIN_MS || voiceJitterMaxMs > VOICE_JITTER_MAX_MS)) {
throw new AdminInputError("INVALID_VOICE_JITTER_MAX", `Adaptive jitter limit must be between ${VOICE_JITTER_MIN_MS} and ${VOICE_JITTER_MAX_MS} ms`);
}
let turnSecret = "";
if (voiceTurnSecretEncrypted === null) {
turnSecret = this.voiceIceDefaults.turnRest?.secret ?? "";
} else if (voiceTurnSecretEncrypted !== "") {
try {
turnSecret = decryptSecret(voiceTurnSecretEncrypted, this.masterSecret, VOICE_TURN_SECRET_PURPOSE);
} catch {
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", "The stored TURN shared secret cannot be decrypted; enter it again");
}
}
if (requestedTurnUrls.length > 0 && turnSecret.length < VOICE_TURN_MIN_SECRET_LENGTH) {
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", `Configure a TURN shared secret of at least ${VOICE_TURN_MIN_SECRET_LENGTH} characters for the TURN URLs`);
}
let encryptedPassword = current.tsPasswordEncrypted;
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
if (action === "remove") encryptedPassword = null;
@@ -489,6 +592,12 @@ export class AdminService {
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
webRtcUdpStart,
webRtcUdpEnd,
voiceProfile,
voiceTurnUrls,
voiceTurnSecretEncrypted,
voiceTurnTtlSeconds,
voiceOpusWs,
voiceJitterMaxMs,
relayConfigured,
relayEnabled,
relayName,
@@ -615,6 +724,12 @@ export class AdminService {
webRtcStunServer: settings.webRtcStunServer,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
voiceProfile: settings.voiceProfile,
voiceTurnUrls: settings.voiceTurnUrls,
voiceTurnSecretEncrypted: settings.voiceTurnSecretEncrypted,
voiceTurnTtlSeconds: settings.voiceTurnTtlSeconds,
voiceOpusWs: settings.voiceOpusWs,
voiceJitterMaxMs: settings.voiceJitterMaxMs,
relayConfigured: settings.relayConfigured,
relayEnabled: settings.relayEnabled,
relayName: settings.relayName,
@@ -647,6 +762,12 @@ export class AdminService {
webRtcStunServer: current.webRtcStunServer,
webRtcUdpStart: current.webRtcUdpStart,
webRtcUdpEnd: current.webRtcUdpEnd,
voiceProfile: current.voiceProfile,
voiceTurnUrls: current.voiceTurnUrls,
voiceTurnSecretEncrypted: current.voiceTurnSecretEncrypted,
voiceTurnTtlSeconds: current.voiceTurnTtlSeconds,
voiceOpusWs: current.voiceOpusWs,
voiceJitterMaxMs: current.voiceJitterMaxMs,
relayConfigured: current.relayConfigured,
relayEnabled: current.relayEnabled,
relayName: current.relayName,
+7
View File
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
import { readVoiceIceConfig } from "./server/voice-ice-config.js";
import { SkinRegistry } from "./admin/skin-registry.js";
import { PluginRegistry } from "./plugins/registry.js";
import { UpdateService } from "./updater/update-service.js";
@@ -18,6 +19,7 @@ const LOG_DIR = path.join(DATA_DIR, "logs");
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
const APP_VERSION = readPackageVersion();
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
const VOICE_ICE_CONFIG = readVoiceIceConfig(process.env);
async function main() {
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
@@ -43,6 +45,8 @@ async function main() {
CONFIG_PATH,
undefined,
APP_VERSION,
undefined,
VOICE_ICE_CONFIG,
);
await adminService.initialize();
removeObsoleteBootstrapFile();
@@ -93,6 +97,8 @@ async function main() {
joinTickets,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
webRtc: () => adminService.getWebRtcAudioOptions(),
// Read per new connection so console changes apply without a process restart.
voiceIce: () => adminService.getVoiceIceConfig(),
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
// The public gateway only uses the relay configuration explicitly
// saved in the admin console. Environment variables belong to the
@@ -163,6 +169,7 @@ async function runRelayMode(): Promise<void> {
: {}),
udpPortRange: [webRtcUdpStart, webRtcUdpEnd] as [number, number],
},
voiceIce: VOICE_ICE_CONFIG,
screenShareIceServers: SCREEN_SHARE_ICE_SERVERS,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
});
+29
View File
@@ -7,6 +7,35 @@ import { DatabaseSync } from "node:sqlite";
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
import { DATABASE_SCHEMA_VERSION, WebSpeakDatabase } from "./database.js";
test("voice overrides preserve schema 13 and survive an old binary updating ordinary settings", t => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-voice-rollback-"));
const filename = path.join(directory, "webspeak.db");
t.after(() => rmSync(directory, { recursive: true, force: true }));
const database = new WebSpeakDatabase(filename);
const encrypted = encryptSecret("turn-test-secret-value", Buffer.alloc(32, 7), "webspeak:voice-turn-rest-secret:v1");
database.updateSettings({ ...database.getSettings(), voiceProfile: "adaptive", voiceTurnUrls: "turn:turn.example.com:3478",
voiceTurnSecretEncrypted: encrypted, voiceTurnTtlSeconds: 3600, voiceOpusWs: true, voiceJitterMaxMs: 200 });
database.close();
const legacy = new DatabaseSync(filename);
try {
const version = legacy.prepare("PRAGMA user_version").get() as { user_version: number };
assert.equal(version.user_version, 13, "0.3.3 rejects any schema version above 13");
assert.equal((legacy.prepare("PRAGMA table_info(settings)").all() as { name: string }[]).some(row => row.name.startsWith("voice_")), false);
legacy.prepare("UPDATE settings SET site_name = ? WHERE id = 1").run("Updated by old binary");
} finally { legacy.close(); }
const reopened = new WebSpeakDatabase(filename);
try {
const settings = reopened.getSettings();
assert.equal(settings.siteName, "Updated by old binary");
assert.equal(settings.voiceProfile, "adaptive");
assert.equal(settings.voiceTurnSecretEncrypted, encrypted);
assert.equal(settings.voiceOpusWs, true);
assert.equal(settings.voiceJitterMaxMs, 200);
reopened.setMeta("voice_settings_v1", "invalid-json");
assert.equal(reopened.getSettings().voiceProfile, null);
} finally { reopened.close(); }
});
test("relay voice endpoint is stored by the current database migration", (context) => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-relay-db-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.sqlite"));
+43
View File
@@ -5,8 +5,10 @@ import { DatabaseSync } from "node:sqlite";
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";
import type { VoiceProfileSetting } from "../shared/voice-profile.js";
export const DATABASE_SCHEMA_VERSION = 13;
const VOICE_SETTINGS_META_KEY = "voice_settings_v1";
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
@@ -31,6 +33,13 @@ export interface PersistedSettings {
webRtcStunServer: string;
webRtcUdpStart: number;
webRtcUdpEnd: number;
/** Console-owned overrides; null inherits the environment baseline. */
voiceProfile: VoiceProfileSetting | null;
voiceTurnUrls: string | null;
voiceTurnSecretEncrypted: string | null;
voiceTurnTtlSeconds: number | null;
voiceOpusWs: boolean | null;
voiceJitterMaxMs: number | null;
relayConfigured: boolean;
relayEnabled: boolean;
relayName: string;
@@ -58,6 +67,12 @@ export interface SettingsUpdate {
webRtcStunServer?: string;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
voiceProfile?: VoiceProfileSetting | null;
voiceTurnUrls?: string | null;
voiceTurnSecretEncrypted?: string | null;
voiceTurnTtlSeconds?: number | null;
voiceOpusWs?: boolean | null;
voiceJitterMaxMs?: number | null;
relayConfigured: boolean;
relayEnabled: boolean;
relayName: string;
@@ -247,6 +262,7 @@ export class WebSpeakDatabase {
getSettings(): PersistedSettings {
const row = this.database.prepare("SELECT * FROM settings WHERE id = 1").get() as SettingsRow;
const voice = this.readVoiceSettings();
return {
siteName: row.site_name,
welcomeText: row.welcome_text,
@@ -269,6 +285,7 @@ export class WebSpeakDatabase {
webRtcStunServer: row.webrtc_stun_server,
webRtcUdpStart: row.webrtc_udp_start,
webRtcUdpEnd: row.webrtc_udp_end,
...voice,
relayConfigured: row.relay_configured === 1,
relayEnabled: row.relay_enabled === 1,
relayName: row.relay_name,
@@ -757,6 +774,26 @@ export class WebSpeakDatabase {
}
}
/** Optional settings must survive a code-only rollback to the 0.3.3 schema. */
private readVoiceSettings(): Pick<PersistedSettings, "voiceProfile" | "voiceTurnUrls" | "voiceTurnSecretEncrypted" | "voiceTurnTtlSeconds" | "voiceOpusWs" | "voiceJitterMaxMs"> {
let value: Record<string, unknown> = {};
try {
const parsed: unknown = JSON.parse(this.getMeta(VOICE_SETTINGS_META_KEY) ?? "{}");
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) value = parsed as Record<string, unknown>;
} catch { /* A malformed optional value inherits the deployment defaults. */ }
return {
voiceProfile: value.voiceProfile === "legacy" || value.voiceProfile === "adaptive" || value.voiceProfile === "auto"
? value.voiceProfile : null,
voiceTurnUrls: typeof value.voiceTurnUrls === "string" ? value.voiceTurnUrls : null,
voiceTurnSecretEncrypted: typeof value.voiceTurnSecretEncrypted === "string" ? value.voiceTurnSecretEncrypted : null,
voiceTurnTtlSeconds: Number.isInteger(value.voiceTurnTtlSeconds) && Number(value.voiceTurnTtlSeconds) >= 300 && Number(value.voiceTurnTtlSeconds) <= 86400
? Number(value.voiceTurnTtlSeconds) : null,
voiceOpusWs: typeof value.voiceOpusWs === "boolean" ? value.voiceOpusWs : null,
voiceJitterMaxMs: Number.isInteger(value.voiceJitterMaxMs) && Number(value.voiceJitterMaxMs) >= 80 && Number(value.voiceJitterMaxMs) <= 500
? Number(value.voiceJitterMaxMs) : null,
};
}
private writeSettings(settings: SettingsUpdate, now: string): void {
this.database.prepare(
`UPDATE settings SET
@@ -791,6 +828,12 @@ export class WebSpeakDatabase {
settings.relayTokenEncrypted,
now,
);
// writeSettings is called within the caller's settings transaction. Older
// binaries ignore this key and keep it intact when updating other fields.
this.setMeta(VOICE_SETTINGS_META_KEY, JSON.stringify({
...this.readVoiceSettings(),
...Object.fromEntries(Object.entries(settings).filter(([key, value]) => key.startsWith("voice") && value !== undefined)),
}));
}
private insertAudit(event: string, details: Record<string, unknown>, now: string): void {
+73
View File
@@ -0,0 +1,73 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { AudioPacer } from "./audio-pacer.js";
function fakeClock() {
let now = 0;
let nextId = 1;
let task: { id: number; at: number; callback: () => void } | null = null;
const schedule = (callback: () => void, delayMs: number) => {
task = { id: nextId++, at: now + delayMs, callback };
return task as unknown as ReturnType<typeof setTimeout>;
};
const cancel = (handle: ReturnType<typeof setTimeout>) => {
if (task && task.id === (handle as unknown as { id: number }).id) task = null;
};
const runNext = () => {
assert.ok(task, "expected a scheduled tick");
now = Math.max(now, task.at);
const callback = task.callback;
task = null;
callback();
};
return { now: () => now, setNow: (value: number) => { now = value; }, schedule, cancel, runNext, hasTask: () => task !== null };
}
test("pacer emits one frame every 20 ms and preserves order", () => {
const clock = fakeClock();
const sent: number[] = [];
const pacer = new AudioPacer((_data, codec) => sent.push(codec), {
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
});
pacer.push(Buffer.from([1]), 1);
pacer.push(Buffer.from([2]), 2);
pacer.push(Buffer.from([3]), 3);
assert.equal(sent.length, 0, "frames wait for the first timer turn");
clock.runNext();
assert.deepEqual(sent, [1]);
assert.equal(pacer.getStats().currentFrames, 2);
clock.runNext();
assert.deepEqual(sent, [1, 2]);
clock.runNext();
assert.deepEqual(sent, [1, 2, 3]);
assert.equal(pacer.getStats().currentFrames, 0);
assert.equal(clock.hasTask(), false);
});
test("pacer drops the oldest frame when the queue is full and records peak", () => {
const clock = fakeClock();
const pacer = new AudioPacer(() => {}, { now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 2 });
pacer.push(Buffer.from([1]), 1);
pacer.push(Buffer.from([2]), 2);
pacer.push(Buffer.from([3]), 3);
const stats = pacer.getStats();
assert.equal(stats.currentFrames, 2);
assert.equal(stats.peakFrames, 2);
assert.equal(stats.droppedFrames, 1);
pacer.close();
});
test("a late event-loop turn resets the deadline instead of bursting", () => {
const clock = fakeClock();
const sent: number[] = [];
const pacer = new AudioPacer(() => sent.push(1), {
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
});
pacer.push(Buffer.from([1]), 1);
pacer.push(Buffer.from([2]), 2);
clock.setNow(100);
clock.runNext();
assert.equal(sent.length, 1);
assert.equal(pacer.getStats().lateTicks, 1);
pacer.close();
});
+138
View File
@@ -0,0 +1,138 @@
import { performance } from "node:perf_hooks";
/**
* A tiny 20 ms sender for browser PCM/Opus uplink. Cloudflare Tunnel can
* deliver a burst of WebSocket frames at once; forwarding those frames to
* TeamSpeak immediately preserves the burst and makes the receiving client's
* jitter buffer work harder. This pacer absorbs the burst and emits at a fixed
* cadence, dropping the oldest frame only when the queue is genuinely behind.
*/
export interface PacerFrame {
data: Buffer;
codec: number;
enqueuedAt: number;
}
export interface AudioPacerOptions {
frameMs?: number;
maxFrames?: number;
maxLagMs?: number;
now?: () => number;
schedule?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancel?: (timer: ReturnType<typeof setTimeout>) => void;
onStats?: (stats: AudioPacerStats) => void;
}
export interface AudioPacerStats {
currentFrames: number;
peakFrames: number;
droppedFrames: number;
lateTicks: number;
sentFrames: number;
}
export class AudioPacer {
private readonly frameMs: number;
private readonly maxFrames: number;
private readonly maxLagMs: number;
private readonly now: () => number;
private readonly schedule: NonNullable<AudioPacerOptions["schedule"]>;
private readonly cancel: NonNullable<AudioPacerOptions["cancel"]>;
private readonly onStats: AudioPacerOptions["onStats"];
private readonly queue: PacerFrame[] = [];
private timer: ReturnType<typeof setTimeout> | null = null;
private nextAt: number | null = null;
private closed = false;
private droppedFrames = 0;
private lateTicks = 0;
private sentFrames = 0;
private peakFrames = 0;
constructor(
private readonly send: (data: Buffer, codec: number) => void,
options: AudioPacerOptions = {},
) {
this.frameMs = Math.max(1, options.frameMs ?? 20);
this.maxFrames = Math.max(1, options.maxFrames ?? 6);
this.maxLagMs = Math.max(0, options.maxLagMs ?? 40);
this.now = options.now ?? (() => performance.now());
this.schedule = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
this.cancel = options.cancel ?? ((handle) => clearTimeout(handle));
this.onStats = options.onStats;
}
push(data: Buffer, codec: number): boolean {
if (this.closed || !data.length) return false;
while (this.queue.length >= this.maxFrames) {
this.queue.shift();
this.droppedFrames++;
}
this.queue.push({ data, codec, enqueuedAt: this.now() });
this.peakFrames = Math.max(this.peakFrames, this.queue.length);
if (!this.timer) {
this.nextAt = this.now();
this.arm(0);
}
this.emitStats();
return true;
}
private arm(delayMs: number): void {
this.timer = this.schedule(() => this.tick(), Math.max(0, delayMs));
// Do not keep the Node process alive solely for an idle voice pacer.
(this.timer as unknown as { unref?: () => void }).unref?.();
}
private tick(): void {
this.timer = null;
if (this.closed) return;
if (!this.queue.length) {
this.nextAt = null;
return;
}
const now = this.now();
if (this.nextAt !== null && now - this.nextAt > this.maxLagMs) {
// A late event loop turn must not create a catch-up burst. Drop the
// accumulated backlog of time and emit one frame from the current time.
this.lateTicks++;
this.nextAt = now;
}
const frame = this.queue.shift()!;
try { this.send(frame.data, frame.codec); } catch { /* sendVoice reports its own failure */ }
this.sentFrames++;
if (this.queue.length) {
this.nextAt = this.nextAt === null ? now + this.frameMs : this.nextAt + this.frameMs;
if (this.nextAt < now + 1) this.nextAt = now + this.frameMs;
this.arm(this.nextAt - now);
} else {
this.nextAt = null;
}
this.emitStats();
}
private emitStats(): void {
this.onStats?.(this.getStats());
}
getStats(): AudioPacerStats {
return {
currentFrames: this.queue.length,
peakFrames: this.peakFrames,
droppedFrames: this.droppedFrames,
lateTicks: this.lateTicks,
sentFrames: this.sentFrames,
};
}
close(): void {
this.closed = true;
if (this.timer) {
this.cancel(this.timer);
this.timer = null;
}
this.queue.length = 0;
this.nextAt = null;
this.emitStats();
}
}
+17
View File
@@ -3,6 +3,8 @@ import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
export interface AudioFlowStats extends WebRtcAudioStats {
ingressFrames: number;
ingressPcmFrames: number;
ingressOpusFrames: number;
ingressDroppedFrames: number;
ingressFirstAt: number | null;
ingressLastAt: number | null;
@@ -13,6 +15,10 @@ export interface AudioFlowStats extends WebRtcAudioStats {
tsSendLastAt: number | null;
tsSendMaxGapMs: number;
tsEncodeMaxMs: number;
uplinkQueueCurrentFrames: number;
uplinkQueuePeakFrames: number;
uplinkQueueDroppedFrames: number;
uplinkPacerLateTicks: number;
tsReceiveFrames: number;
tsReceiveFirstAt: number | null;
tsReceiveLastAt: number | null;
@@ -38,6 +44,8 @@ export interface AudioStatsSource {
export function createAudioFlowStats(): AudioFlowStats {
return {
ingressFrames: 0,
ingressPcmFrames: 0,
ingressOpusFrames: 0,
ingressDroppedFrames: 0,
ingressFirstAt: null,
ingressLastAt: null,
@@ -48,6 +56,10 @@ export function createAudioFlowStats(): AudioFlowStats {
tsSendLastAt: null,
tsSendMaxGapMs: 0,
tsEncodeMaxMs: 0,
uplinkQueueCurrentFrames: 0,
uplinkQueuePeakFrames: 0,
uplinkQueueDroppedFrames: 0,
uplinkPacerLateTicks: 0,
tsReceiveFrames: 0,
tsReceiveFirstAt: null,
tsReceiveLastAt: null,
@@ -95,11 +107,16 @@ export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeSt
return {
transport: entry.webrtc ? "webrtc" : "websocket",
ingressFrames: stats.ingressFrames,
ingressPcmFrames: stats.ingressPcmFrames,
ingressOpusFrames: stats.ingressOpusFrames,
ingressDroppedFrames: stats.ingressDroppedFrames,
ingressMaxGapMs: stats.ingressMaxGapMs,
tsSendFrames: stats.tsSendFrames,
tsSendErrors: stats.tsSendErrors,
tsSendMaxGapMs: stats.tsSendMaxGapMs,
uplinkQueuePeakFrames: stats.uplinkQueuePeakFrames,
uplinkQueueDroppedFrames: stats.uplinkQueueDroppedFrames,
uplinkPacerLateTicks: stats.uplinkPacerLateTicks,
tsReceiveFrames: stats.tsReceiveFrames,
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
egressFrames: stats.egressFrames,
+42 -7
View File
@@ -8,7 +8,7 @@ import type { TSVoiceData } from "./ts-client.js";
function fixture() {
const state = { current: true, ready: true, now: 0, targets: null as number[] | null, disposed: 0,
peer: null as { pushTeamSpeakVoice(data: TSVoiceData): void } | null };
peer: null as { isConnected: boolean; pushTeamSpeakVoice(data: TSVoiceData): void } | null };
const audio = createAudioFlowStats();
const packets: Buffer[] = [];
const encoded: Buffer[] = [];
@@ -34,7 +34,7 @@ function fixture() {
const transport = new SessionAudioTransport({
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
sendJson: message => { notices.push(message); },
sendJson: message => { notices.push(message); }, pacing: false,
}, encoder, () => state.now, () => state.now);
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
@@ -117,8 +117,8 @@ test("repeated malformed frames are counted in full but reported once per window
assert.equal(f.audio.ingressDroppedFrames, 4, "every discarded frame still reaches the flow counters");
assert.equal(f.notices.length, 2, "the browser sees one error per window, not one per frame");
assert.deepEqual(f.warnings, [
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 1 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 4 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 1 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 4 },
], "operators get the same rate-limited view through the logger");
});
@@ -131,9 +131,22 @@ test("an encoder failure and a malformed frame do not suppress each other", t =>
t.mock.restoreAll();
});
test("tagged PCM and pre-encoded Opus frames share the uplink without double encoding", () => {
const f = fixture();
f.transport.receivePcm(Buffer.concat([Buffer.from([1]), Buffer.alloc(1_920)]));
f.transport.receivePcm(Buffer.concat([Buffer.from([2]), Buffer.from([1, 2, 3])]));
assert.equal(f.encoded.length, 1);
assert.equal(f.audio.ingressPcmFrames, 1);
assert.equal(f.audio.ingressOpusFrames, 1);
assert.deepEqual(f.forwarded.map(({ data, codec }) => ({ data: [...data], codec })), [
{ data: [9, 8, 7], codec: 4 },
{ data: [1, 2, 3], codec: 4 },
]);
});
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
const f = fixture();
f.state.peer = { pushTeamSpeakVoice() {} };
f.state.peer = { isConnected: true, pushTeamSpeakVoice() {} };
f.transport.receivePcm(Buffer.alloc(1_920));
const opus = Buffer.from([3, 2, 1]);
f.transport.receiveWebRtc(opus, 5);
@@ -175,7 +188,7 @@ test("backpressure drops bursts above 4096 bytes and resumes without a retained
test("WebRTC downlink owns egress without a duplicate WebSocket packet", () => {
const f = fixture();
const received: TSVoiceData[] = [];
f.state.peer = { pushTeamSpeakVoice: data => { received.push(data); } };
f.state.peer = { isConnected: true, pushTeamSpeakVoice: data => { received.push(data); } };
f.transport.receiveTeamSpeak(f.remote());
assert.equal(received.length, 1);
assert.equal(f.packets.length, 0);
@@ -185,6 +198,28 @@ test("WebRTC downlink owns egress without a duplicate WebSocket packet", () => {
assert.equal(f.packets.length, 1);
});
test("negotiating WebRTC keeps both compatibility directions until the media path connects", () => {
const f = fixture();
const received: TSVoiceData[] = [];
f.state.peer = { isConnected: false, pushTeamSpeakVoice: data => received.push(data) };
f.transport.receivePcm(Buffer.alloc(1920));
f.transport.receiveTeamSpeak(f.remote());
assert.equal(f.forwarded.length, 1);
assert.equal(f.packets.length, 1);
assert.equal(received.length, 0);
f.state.peer.isConnected = true;
f.transport.receivePcm(Buffer.alloc(1920));
f.transport.receiveTeamSpeak(f.remote());
assert.equal(f.forwarded.length, 1);
assert.equal(f.packets.length, 1);
assert.equal(received.length, 1);
f.state.peer.isConnected = false;
f.transport.receivePcm(Buffer.alloc(1920));
f.transport.receiveTeamSpeak(f.remote());
assert.equal(f.forwarded.length, 2);
assert.equal(f.packets.length, 2);
});
test("encoding failures are counted and reported at most once per five seconds", t => {
const f = fixture();
t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); });
@@ -207,7 +242,7 @@ test("SDK and downlink failures cannot escape the audio callbacks", t => {
assert.equal(f.notices.length, 0, "SDK failure must not be reported as an encoder failure");
t.mock.method(f.socket, "send", () => { throw new Error("Socket closed"); });
f.transport.receiveTeamSpeak(f.remote());
f.state.peer = { pushTeamSpeakVoice() { throw new Error("Peer closed"); } };
f.state.peer = { isConnected: true, pushTeamSpeakVoice() { throw new Error("Peer closed"); } };
f.transport.receiveTeamSpeak(f.remote());
assert.equal(f.audio.egressDroppedFrames, 2);
});
+57 -9
View File
@@ -5,8 +5,19 @@ import type { ServerMessage } from "../shared/server-messages.js";
import type { AudioFlowStats } from "./audio-stats.js";
import type { TSClient, TSVoiceData } from "./ts-client.js";
import type { WebRtcAudioSession } from "./webrtc-audio.js";
import { AudioPacer } from "./audio-pacer.js";
import {
VOICE_MAX_OPUS_FRAME_BYTES,
VOICE_OPUS_TAG,
VOICE_PCM_FRAME_BYTES,
VOICE_PCM_TAG,
} from "../shared/voice-audio.js";
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES;
const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 1;
const PCM_FRAME_TAG = VOICE_PCM_TAG;
const OPUS_FRAME_TAG = VOICE_OPUS_TAG;
const MAX_OPUS_FRAME_BYTES = VOICE_MAX_OPUS_FRAME_BYTES;
// Keep the established byte guard; the browser also bounds playback by time.
const MAX_BUFFERED_BYTES = 4_096;
// A client that keeps sending bad audio must not turn into one JSON error per
@@ -30,9 +41,11 @@ export interface SessionAudioOptions {
isCurrent(): boolean;
isReady(): boolean;
selfId(): number;
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice" | "isConnected"> | null;
whisperTargets(): readonly number[] | null;
sendJson(message: ServerMessage): void;
/** Tests that assert synchronous SDK calls can opt out; production keeps pacing. */
pacing?: boolean;
}
/** A session owns one encoder and one active audio route in each direction. */
@@ -42,6 +55,7 @@ export class SessionAudioTransport {
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
private readonly reportedAt = new Map<string, number>();
private readonly logger: LoggerType | null;
private readonly pacer: AudioPacer | null;
private pcmTokens = PCM_BURST_FRAMES;
private pcmRefilledAt: number | null = null;
@@ -49,12 +63,31 @@ export class SessionAudioTransport {
private readonly rateClock: () => number = performance.now.bind(performance)) {
this.encoder = encoder;
this.logger = options.logger ?? null;
this.pacer = options.pacing === false ? null : new AudioPacer(
(data, codec) => {
if (!this.mediaPeer()) this.sendVoice(data, codec);
},
{
now: this.rateClock,
onStats: stats => {
options.audio.uplinkQueueCurrentFrames = stats.currentFrames;
options.audio.uplinkQueuePeakFrames = Math.max(options.audio.uplinkQueuePeakFrames, stats.peakFrames);
options.audio.uplinkQueueDroppedFrames = stats.droppedFrames;
options.audio.uplinkPacerLateTicks = stats.lateTicks;
},
},
);
}
private isCurrent(): boolean {
return !this.closed && this.options.isCurrent() && this.options.socket.readyState === WebSocket.OPEN;
}
private mediaPeer() {
const peer = this.options.peer();
return peer?.isConnected ? peer : null;
}
private recordIngress(): void {
const stats = this.options.audio;
const now = this.clock();
@@ -112,7 +145,7 @@ export class SessionAudioTransport {
// logged anywhere, so without this an operator has no way to notice a client
// that keeps sending malformed audio until the session is torn down.
this.logger?.warn(
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: AUDIO_FRAME_BYTES, droppedFrames: this.options.audio.ingressDroppedFrames },
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: `${AUDIO_FRAME_BYTES} or tagged`, droppedFrames: this.options.audio.ingressDroppedFrames },
"Discarded malformed browser audio frame",
);
try {
@@ -127,8 +160,12 @@ export class SessionAudioTransport {
// route is down is discarded whatever its size, so calling it malformed would
// misattribute the drop and raise a spurious client error in the browser.
// Late TCP frames from before a WebRTC switch must not duplicate RTP audio.
if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; }
if (frame.length !== AUDIO_FRAME_BYTES) {
if (!this.options.isReady() || this.mediaPeer()) { stats.ingressDroppedFrames++; return; }
const legacyPcm = frame.length === AUDIO_FRAME_BYTES ? frame : null;
const taggedPcm = frame.length === TAGGED_PCM_FRAME_BYTES && frame[0] === PCM_FRAME_TAG ? frame.subarray(1) : null;
const opus = frame.length > 1 && frame.length <= MAX_OPUS_FRAME_BYTES + 1 && frame[0] === OPUS_FRAME_TAG
? frame.subarray(1) : null;
if (!legacyPcm && !taggedPcm && !opus) {
stats.ingressDroppedFrames++;
this.reportInvalidFrame(frame.length);
return;
@@ -141,17 +178,26 @@ export class SessionAudioTransport {
if (this.pcmTokens < 1) {
stats.ingressDroppedFrames++;
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser audio above the real-time budget");
}
return;
}
this.pcmTokens--;
this.recordIngress();
if (opus) {
stats.ingressOpusFrames++;
// The pacer absorbs Cloudflare's bursty WebSocket delivery. Opus is
// already encoded, so this costs one buffer copy and no CPU-heavy encode.
if (this.pacer) this.pacer.push(opus, 4);
else this.sendVoice(opus, 4);
return;
}
stats.ingressPcmFrames++;
const startedAt = this.clock();
let encoded: Buffer;
try {
if (!this.encoder) throw new Error("Encoder unavailable");
encoded = this.encoder.encode(frame);
encoded = this.encoder.encode(taggedPcm ?? legacyPcm!);
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
} catch {
stats.tsSendErrors++;
@@ -159,7 +205,8 @@ export class SessionAudioTransport {
this.reportEncoderFailure();
return;
}
this.sendVoice(encoded, 4);
this.pacer?.push(encoded, 4);
if (!this.pacer) this.sendVoice(encoded, 4);
}
receiveWebRtc(data: Buffer, codec: number): void {
@@ -187,7 +234,7 @@ export class SessionAudioTransport {
stats.egressLastAt = now;
const key = String(data.clientId);
stats.egressFramesByClient[key] = (stats.egressFramesByClient[key] ?? 0) + 1;
const peer = this.options.peer();
const peer = this.mediaPeer();
if (peer) {
try { peer.pushTeamSpeakVoice(data); stats.egressFrames++; }
catch { stats.egressDroppedFrames++; }
@@ -214,6 +261,7 @@ export class SessionAudioTransport {
if (this.closed) return;
this.closed = true;
this.reportedAt.clear();
this.pacer?.close();
const encoder = this.encoder;
this.encoder = null;
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createHmac } from "node:crypto";
import { createTurnRestCredential, createTurnRestUsername } from "./turn-credentials.js";
test("TURN REST username and credential match coturn's HMAC contract", () => {
const secret = "a-test-secret-with-enough-length";
const config = { urls: ["turns:turn.example.com:443?transport=tcp"], secret, ttlSeconds: 3_600 };
const now = 1_700_000_000_000;
const credential = createTurnRestCredential(config, "session-1", now);
const expiry = Math.floor(now / 1_000) + 3_600;
const username = createTurnRestUsername(expiry, "session-1");
assert.equal(credential.username, username);
assert.equal(credential.credential, createHmac("sha1", secret).update(username).digest("base64"));
});
test("TURN REST session ids are sanitized and expiry stays in the future", () => {
const credential = createTurnRestCredential(
{ urls: ["turn:turn.example.com:3478?transport=udp"], secret: "another-long-test-secret", ttlSeconds: 300 },
"bad session:id!",
1_000,
);
assert.match(credential.username!, /^[0-9]+:badsessionid/);
assert.equal(credential.credential?.length, 28);
});
+36
View File
@@ -0,0 +1,36 @@
import { createHmac, randomBytes } from "node:crypto";
import type { VoiceIceServer } from "../shared/voice-ice.js";
export interface TurnRestConfig {
urls: string[];
secret: string;
ttlSeconds: number;
}
/**
* coturn's `use-auth-secret` REST API:
* username = "<expiry unix seconds>:<session id>"
* credential = base64(HMAC-SHA1(secret, username))
*
* Credentials are minted per browser connection; they are not shared between
* sessions and never need to be persisted.
*/
export function createTurnRestCredential(
config: TurnRestConfig,
sessionId: string,
nowMs = Date.now(),
): VoiceIceServer {
const suffix = sessionId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || randomBytes(8).toString("hex");
const expiry = Math.floor(nowMs / 1_000) + Math.max(1, Math.trunc(config.ttlSeconds));
const username = `${expiry}:${suffix}`;
const credential = createHmac("sha1", config.secret).update(username).digest("base64");
return {
urls: config.urls.length === 1 ? config.urls[0]! : [...config.urls],
username,
credential,
};
}
export function createTurnRestUsername(expirySeconds: number, sessionId: string): string {
return `${Math.trunc(expirySeconds)}:${sessionId}`;
}
+114 -3
View File
@@ -11,7 +11,8 @@ import { OpusEncoder } from "./opus-codec.js";
import { normalizeTeamSpeakKickedReason } from "../errors.js";
import type { TSClient, TSClientAvatar, TSDirectorySnapshot } from "./ts-client.js";
import type { AudioFlowStats } from "./audio-stats.js";
import type { WebRtcAudioSession } from "./webrtc-audio.js";
import type { WebRtcAudioSession, WebRtcAudioOptions } from "./webrtc-audio.js";
import type { VoiceBridgeOptions } from "./voice-bridge.js";
// Real loopback HTTP/WebSocket and native codec, with only the external SDK
// replaced. This validates gateway wiring, not a connection to TeamSpeak.
@@ -52,11 +53,19 @@ async function fixture(t: TestContext, overrides: {
waitForFirstMessage?: boolean;
createWorkspaceInvite?: import("./voice-bridge.js").VoiceBridgeOptions["createWorkspaceInvite"];
connection?: Partial<import("./join-ticket.js").JoinTicketPayload>;
webRtc?: WebRtcAudioOptions;
voiceIce?: VoiceBridgeOptions["voiceIce"];
headers?: Record<string, string>;
} = {}) {
const sdk = new TeamSpeakStub();
overrides.configureSdk?.(sdk);
const tickets = new JoinTicketStore();
const bridge = new VoiceBridge({ joinTickets: tickets, createWorkspaceInvite: overrides.createWorkspaceInvite }, pino({ enabled: false }), undefined, {
const bridge = new VoiceBridge({
joinTickets: tickets,
createWorkspaceInvite: overrides.createWorkspaceInvite,
...(overrides.webRtc ? { webRtc: overrides.webRtc } : {}),
...(overrides.voiceIce ? { voiceIce: overrides.voiceIce } : {}),
}, pino({ enabled: false }), undefined, {
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
});
@@ -68,7 +77,7 @@ async function fixture(t: TestContext, overrides: {
const address = server.address();
assert.ok(address && typeof address !== "string");
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 socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`, overrides.headers ? { headers: overrides.headers } : undefined);
const messages: Array<{ data: Buffer; binary: boolean }> = [];
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
const first = once(socket, "message");
@@ -107,6 +116,18 @@ function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, ty
});
}
async function waitForBufferedMessage<T extends Record<string, unknown>>(
messages: Array<{ data: Buffer; binary: boolean }>,
type: string,
): Promise<T> {
for (let attempt = 0; attempt < 100; attempt++) {
const found = messages.find(message => !message.binary && (JSON.parse(message.data.toString()) as { type?: string }).type === type);
if (found) return JSON.parse(found.data.toString()) as T;
await nextTurn();
}
throw new Error(`message ${type} was not published`);
}
// The native Opus codec is unavailable in some environments. These tests only
// exercise gateway wiring, so the encoder is stubbed out.
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
@@ -153,6 +174,96 @@ test("server identity lookup waits until the directory sync publishes the connec
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a direct connection keeps the legacy audio profile and the original media path", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
webRtc: { enabled: true, stunServer: "stun:stun.example.invalid:3478" },
voiceIce: {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: 300,
},
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(connected.voiceProfile, "legacy");
assert.equal(connected.webrtcAvailable, true);
assert.equal(connected.webrtcUnavailableReason, undefined);
assert.equal(connected.audioFrameVersion, undefined);
assert.equal(connected.audioUplinkCodecs, undefined);
assert.equal(connected.audioJitterMaxMs, undefined);
assert.equal(connected.voiceIceTransportPolicy, "all");
assert.deepEqual(connected.voiceIceServers, [{ urls: "stun:stun.example.invalid:3478" }]);
});
test("an explicit adaptive profile enables the new audio path on a direct connection", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
webRtc: { enabled: true },
voiceIce: {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "adaptive",
opusWebSocket: true,
jitterMaxMs: 300,
},
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(connected.voiceProfile, "adaptive");
assert.equal(connected.webrtcAvailable, true);
assert.equal(connected.audioFrameVersion, 2);
assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]);
assert.equal(connected.audioJitterMaxMs, 300);
});
test("a Cloudflare request opts into adaptive audio without inventing an ICE host", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
webRtc: { enabled: true },
voiceIce: {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: 300,
},
headers: { "cf-ray": "test-ray" },
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(connected.voiceProfile, "adaptive");
assert.equal(connected.webrtcAvailable, false);
assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH");
assert.equal(connected.audioFrameVersion, 2);
assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]);
assert.equal(connected.audioJitterMaxMs, 300);
assert.deepEqual(connected.voiceIceServers, []);
});
test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => {
let calls = 0;
const f = await fixture(t, {
webRtc: { enabled: true },
voiceIce: () => {
calls++;
return {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: 300,
};
},
headers: { "cf-ray": "console-refresh-ray" },
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(calls, 1);
assert.equal(connected.voiceProfile, "adaptive");
});
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
waitForFirstMessage: false,
+38 -1
View File
@@ -3,7 +3,7 @@ import test from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import type { IncomingMessage } from "node:http";
import pino from "pino";
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
import { VoiceBridge, createTrustedProxies, isCloudflareRequest, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
import { JoinTicketStore } from "./join-ticket.js";
import { createAudioFlowStats } from "./audio-stats.js";
import { SessionAudioTransport } from "./session-audio.js";
@@ -18,6 +18,7 @@ function deferred() {
}
class PeerStub {
isConnected = true;
closed = false;
closeResult = Promise.resolve();
answerResult = Promise.resolve();
@@ -40,6 +41,8 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
tsClient: { isConnected: () => true, setInputMuted: async (_muted: boolean) => {}, setAccompanimentActive: async (_active: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
audioTransport: null as SessionAudioTransport | null,
voiceIceServers: [], voiceIceTransportPolicy: "all" as const, voiceIceGatewayTransportPolicy: "all" as const,
voiceProfile: "legacy" as const,
};
let forwarded = 0;
let configurePeer = (_peer: PeerStub): void => {};
@@ -62,6 +65,7 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
isCurrent: () => bridge.entries.get(entry.id) === entry,
isReady: () => entry.session.state === "connected", selfId: () => 1,
peer: () => entry.webrtc, whisperTargets: () => null, sendJson: message => messages.push(message),
pacing: false,
}, { encode: frame => frame, dispose() {} });
const offer = (sdp: string) => bridge.handleWebRtcOffer(entry, { type: "offer", sdp }, message => messages.push(message));
return { bridge, entry, peers, messages, offer, forwarded: () => forwarded, configure: (callback: typeof configurePeer) => { configurePeer = callback; } };
@@ -174,6 +178,27 @@ test("WebRTC candidates use the voice gateway host when the page Origin belongs
assert.equal(resolveWebRtcPublicHost(request), "voice-relay.example.com");
});
test("Cloudflare headers only classify a request from a trusted proxy", () => {
const trusted = createTrustedProxies(["127.0.0.1", "198.51.100.0/24"]);
const headers = { "cf-ray": "abc123-SJC", "cf-connecting-ip": "203.0.113.10" };
assert.equal(isCloudflareRequest(ipRequest("192.0.2.7", headers), trusted), false);
assert.equal(isCloudflareRequest(ipRequest("127.0.0.1", headers), trusted), true);
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, cloudflare two" }), trusted), true);
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, other two" }), trusted), false);
});
test("a Cloudflare-proxied request never falls back to the edge hostname for ICE", () => {
const request = {
headers: {
host: "voice.example.com",
"cf-ray": "abc123-SJC",
"cf-connecting-ip": "203.0.113.10",
},
} as unknown as IncomingMessage;
assert.equal(resolveWebRtcPublicHost(request, { allowHostFallback: false }), undefined);
assert.equal(resolveWebRtcPublicHost(request), "voice.example.com");
});
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
const f = fixture();
const inputs: Array<[string, boolean]> = [];
@@ -234,6 +259,18 @@ test("an unset media override still uses a literal request host", async () => {
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
});
test("TURN servers are passed to werift while direct-first remains the default policy", async () => {
const f = fixture({ enabled: true, publicHost: "192.0.2.20" });
Object.assign(f.entry, {
webrtcPublicHost: "192.0.2.20",
voiceIceServers: [{ urls: "turns:turn.example.com:443?transport=tcp", username: "u", credential: "c" }],
voiceIceGatewayTransportPolicy: "all" as const,
});
await f.offer("turn");
assert.deepEqual(f.peers[0].options.iceServers, f.entry.voiceIceServers);
assert.equal(f.peers[0].options.iceTransportPolicy, "all");
});
function ipRequest(remoteAddress: string | undefined, headers: Record<string, string> = {}): IncomingMessage {
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
}
+97 -4
View File
@@ -28,6 +28,15 @@ import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenSha
import { OpusEncoder } from "./opus-codec.js";
import { avatarDataUrl } from "./directory-view.js";
import type { PluginParticipant } from "../shared/plugins.js";
import {
hasVoiceTurnServer,
normalizeVoiceIceServers,
normalizeVoiceIceTransportPolicy,
type VoiceIceServer,
type VoiceIceTransportPolicy,
} from "../shared/voice-ice.js";
import { resolveVoiceIceServers, type VoiceIceConfig } from "./voice-ice-config.js";
import { resolveVoiceProfile, type VoiceProfile } from "../shared/voice-profile.js";
const HEARTBEAT_INTERVAL_MS = 30_000;
const MAX_MISSED_HEARTBEATS = 2;
@@ -54,6 +63,8 @@ export interface VoiceBridgeOptions {
pluginRuntimeEnabled?: boolean;
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
/** TURN / ICE deployment configuration; resolved for each new connection. */
voiceIce?: VoiceIceConfig | (() => VoiceIceConfig);
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
accelerationName?: string | (() => string | undefined);
@@ -97,6 +108,10 @@ interface WebClientEntry extends SessionDirectoryState {
acceleration?: AccelerationRelayOptions;
identityLeaseKey?: string;
webrtcPublicHost?: string;
voiceProfile: VoiceProfile;
voiceIceServers: VoiceIceServer[];
voiceIceTransportPolicy: VoiceIceTransportPolicy;
voiceIceGatewayTransportPolicy: VoiceIceTransportPolicy;
events: SessionEventCoordinator | null;
eventLog: ServerEvent[];
audioTransport: SessionAudioTransport | null;
@@ -178,7 +193,13 @@ export class VoiceBridge {
return;
}
const clientIp = resolveClientIp(req, this.trustedProxies);
const webrtcPublicHost = resolveWebRtcPublicHost(req);
// Cloudflare Tunnel forwards the public hostname in `Host`, but that
// hostname points at Cloudflare's edge, not at this origin's UDP ports.
// Never advertise it as an ICE media address.
const cloudflareRequest = isCloudflareRequest(req, this.trustedProxies);
const webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest });
const voiceIce = this.getVoiceIceConfig();
const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest);
let identity;
try {
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
@@ -190,6 +211,9 @@ export class VoiceBridge {
return;
}
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const voiceIceServers = this.buildVoiceIceServers(entryId, voiceIce);
const voiceIceTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.transportPolicy);
const voiceIceGatewayTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.gatewayTransportPolicy);
let entry: WebClientEntry | null = null;
const session = this.sessionManager.admit(entryId, async (reason) => {
if (entry) await this.cleanupEntry(entry, reason);
@@ -247,6 +271,10 @@ export class VoiceBridge {
...(acceleration ? { acceleration } : {}),
...(identityLeaseKey ? { identityLeaseKey } : {}),
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
voiceProfile,
voiceIceServers,
voiceIceTransportPolicy,
voiceIceGatewayTransportPolicy,
channelTree: [],
members: new Map(),
avatarCache: new Map(),
@@ -281,6 +309,7 @@ export class VoiceBridge {
peer: () => entry!.webrtc,
whisperTargets: () => entry!.whisperActive ? [...entry!.whisperTargetIds] : null,
sendJson: message => sendJson(message),
pacing: entry!.voiceProfile === "adaptive",
}, this.dependencies.createEncoder?.() ?? new OpusEncoder(48000, 1));
} catch (error: unknown) {
this.logger.error({ err: error, entryId }, "Could not create Opus encoder");
@@ -328,6 +357,13 @@ export class VoiceBridge {
}
session.transition("connected");
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
const webRtc = this.getWebRtcOptions();
const hasDirectMediaPath = Boolean(webRtc?.publicHost || entry!.webrtcPublicHost);
const hasRelayMediaPath = hasVoiceTurnServer(entry!.voiceIceServers);
const webRtcAvailable = webRtc?.enabled === true && (hasDirectMediaPath || hasRelayMediaPath);
const webRtcUnavailableReason = webRtc?.enabled !== true
? "DISABLED" as const
: webRtcAvailable ? undefined : "NO_MEDIA_PATH" as const;
sendJson({
type: "connected",
tsClientId: events.selfId,
@@ -335,8 +371,19 @@ export class VoiceBridge {
serverEventLog: entry!.eventLog,
whisperTargetIds: [...entry!.whisperTargetIds],
whisperActive: entry!.whisperActive,
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
webrtcAvailable: webRtcAvailable,
...(webRtcUnavailableReason ? { webrtcUnavailableReason: webRtcUnavailableReason } : {}),
webRtcStunServer: webRtc?.stunServer ?? "",
voiceProfile: entry!.voiceProfile,
voiceIceServers: entry!.voiceIceServers,
voiceIceTransportPolicy: entry!.voiceIceTransportPolicy,
...(entry!.voiceProfile === "adaptive" ? {
audioFrameVersion: 2 as const,
audioUplinkCodecs: voiceIce?.opusWebSocket === true
? ["pcm", "opus"] as ("pcm" | "opus")[]
: ["pcm"] as ("pcm" | "opus")[],
audioJitterMaxMs: voiceIce?.jitterMaxMs ?? 300,
} : {}),
screenShareIceServers: this.getScreenShareIceServers(),
accelerated: Boolean(entry!.acceleration),
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
@@ -838,6 +885,18 @@ export class VoiceBridge {
return typeof configured === "function" ? configured() : configured;
}
private getVoiceIceConfig(): VoiceIceConfig | undefined {
const configured = this.options.voiceIce;
return typeof configured === "function" ? configured() : configured;
}
private buildVoiceIceServers(entryId: string, config = this.getVoiceIceConfig()): VoiceIceServer[] {
const servers = resolveVoiceIceServers(config, entryId);
const stunServer = this.getWebRtcOptions()?.stunServer;
if (stunServer) servers.push({ urls: stunServer });
return normalizeVoiceIceServers(servers);
}
private getScreenShareIceServers(): ScreenShareIceServer[] {
const configured = this.options.screenShareIceServers;
const servers = typeof configured === "function" ? configured() : configured;
@@ -900,12 +959,25 @@ export class VoiceBridge {
try {
const publicAddresses = await resolveVoiceMediaAddresses(config.publicHost || entry.webrtcPublicHost, config.ipv6Enabled === true);
if (!isCurrent()) return;
const iceServers = config.iceServers?.length ? config.iceServers : entry.voiceIceServers;
const configuredGatewayPolicy = config.iceTransportPolicy ?? entry.voiceIceGatewayTransportPolicy;
// Relay-only gathering without a TURN server would leave the gateway
// with no candidates at all. Fall back to direct gathering instead.
const gatewayPolicy = configuredGatewayPolicy === "relay" && !hasVoiceTurnServer(iceServers)
? "all"
: configuredGatewayPolicy;
if (configuredGatewayPolicy === "relay" && gatewayPolicy === "all") {
this.logger.warn({ entryId: entry.id }, "Relay-only WebRTC gateway policy has no TURN server; using direct candidates");
}
peer = this.createWebRtcSession({
connectionId: entry.id,
publicAddresses,
...(config.publicHost || entry.webrtcPublicHost ? { publicHost: config.publicHost || entry.webrtcPublicHost } : {}),
ipv6Enabled: config.ipv6Enabled,
stunServer: config.stunServer,
iceServers,
iceTransportPolicy: gatewayPolicy,
profile: entry.voiceProfile,
udpPortRange: config.udpPortRange,
logger: this.logger,
microphoneMuted: muted,
@@ -938,7 +1010,28 @@ export class VoiceBridge {
}
}
export function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
/**
* Headers Cloudflare adds to proxied requests (including Tunnel origins).
* Only a configured trusted proxy may assert that a request came through
* Cloudflare; otherwise a direct client could spoof the adaptive audio path
* and suppress the legacy Host-based ICE fallback.
*/
export function isCloudflareRequest(request: IncomingMessage, trustedProxies: BlockList): boolean {
const direct = normalizeClientIp(request.socket.remoteAddress);
if (!direct || !isTrustedProxy(direct, trustedProxies)) return false;
const cdnLoop = firstHeader(request.headers["cdn-loop"]);
return Boolean(
firstHeader(request.headers["cf-ray"])
|| firstHeader(request.headers["cf-connecting-ip"])
|| (cdnLoop && /\bcloudflare\b/i.test(cdnLoop))
);
}
export function resolveWebRtcPublicHost(
request: IncomingMessage,
options: { allowHostFallback?: boolean } = {},
): string | undefined {
if (options.allowHostFallback === false) return undefined;
const origin = firstHeader(request.headers.origin);
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
const directHost = firstHeader(request.headers.host);
+3
View File
@@ -6,6 +6,7 @@ import { parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice
import type { Logger } from "../logger.js";
import type { WebRtcAudioOptions } from "./webrtc-audio.js";
import type { ScreenShareIceServer } from "./screen-share.js";
import type { VoiceIceConfig } from "./voice-ice-config.js";
export interface VoiceGatewayServerOptions {
workspaceInvites?: import("./workspace-invites.js").WorkspaceInvites;
@@ -14,6 +15,7 @@ export interface VoiceGatewayServerOptions {
sharedToken: string;
logger: Logger;
webRtc: WebRtcAudioOptions;
voiceIce?: VoiceIceConfig;
screenShareIceServers?: ScreenShareIceServer[];
trustedProxies?: readonly string[];
}
@@ -33,6 +35,7 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
joinTickets: tickets,
...(options.workspaceInvites ? { createWorkspaceInvite: (credentials, minutes) => options.workspaceInvites!.create(credentials, minutes) } : {}),
webRtc: options.webRtc,
voiceIce: options.voiceIce,
screenShareIceServers: options.screenShareIceServers,
trustedProxies: options.trustedProxies,
};
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { readVoiceIceConfig, resolveVoiceIceServers } from "./voice-ice-config.js";
test("voice ICE env parses static servers and direct-first defaults", () => {
const config = readVoiceIceConfig({
WEBSPEAK_VOICE_ICE_SERVERS: '[{"urls":"stun:stun.example.com:3478"}]',
});
assert.deepEqual(config.servers, [{ urls: "stun:stun.example.com:3478" }]);
assert.equal(config.transportPolicy, "all");
assert.equal(config.gatewayTransportPolicy, "all");
assert.equal(config.profile, "auto");
assert.equal(config.opusWebSocket, false);
assert.equal(config.jitterMaxMs, 300);
assert.equal(config.turnRest, undefined);
});
test("voice profile is explicit-only for Opus and can force legacy or adaptive", () => {
assert.equal(readVoiceIceConfig({}).profile, "auto");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "legacy" }).profile, "legacy");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive" }).profile, "adaptive");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "invalid" }).profile, "auto");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive", WEBSPEAK_VOICE_OPUS_WS: "1" }).opusWebSocket, true);
});
test("TURN REST env mints a per-session credential and keeps direct-first policy", () => {
const config = readVoiceIceConfig({
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443?transport=tcp,turn:turn.example.com:3478?transport=udp",
WEBSPEAK_TURN_REST_SECRET: "a-test-secret-with-enough-length",
WEBSPEAK_TURN_REST_TTL_SECONDS: "3600",
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY: "relay",
});
assert.equal(config.transportPolicy, "relay");
assert.ok(config.turnRest);
const servers = resolveVoiceIceServers(config, "session-a", 1_000_000);
assert.equal(servers.length, 1);
assert.match(servers[0]!.username!, /^[0-9]+:session-a$/);
assert.ok(servers[0]!.credential);
});
test("short TURN secret is ignored instead of starting a broken relay", () => {
const config = readVoiceIceConfig({
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443",
WEBSPEAK_TURN_REST_SECRET: "short",
});
assert.equal(config.turnRest, undefined);
assert.deepEqual(resolveVoiceIceServers(config, "x"), []);
});
+139
View File
@@ -0,0 +1,139 @@
import {
hasVoiceTurnServer,
normalizeVoiceIceServers,
normalizeVoiceIceTransportPolicy,
VOICE_JITTER_DEFAULT_MS,
VOICE_JITTER_MAX_MS,
VOICE_JITTER_MIN_MS,
VOICE_TURN_MIN_SECRET_LENGTH,
VOICE_TURN_TTL_DEFAULT_SECONDS,
VOICE_TURN_TTL_MAX_SECONDS,
VOICE_TURN_TTL_MIN_SECONDS,
type VoiceIceServer,
type VoiceIceTransportPolicy,
} from "../shared/voice-ice.js";
import { createTurnRestCredential, type TurnRestConfig } from "./turn-credentials.js";
import { normalizeVoiceProfileSetting, type VoiceProfileSetting } from "../shared/voice-profile.js";
export interface VoiceIceConfig {
servers: VoiceIceServer[];
turnRest?: TurnRestConfig;
/** Browser policy; keep `all` for direct UDP-first deployments. */
transportPolicy: VoiceIceTransportPolicy;
/** werift policy; use `relay` only when the gateway itself is behind NAT. */
gatewayTransportPolicy: VoiceIceTransportPolicy;
/** Per-connection audio profile: direct traffic defaults to legacy. */
profile: VoiceProfileSetting;
opusWebSocket: boolean;
jitterMaxMs: number;
}
export interface VoiceIceSettings {
servers: VoiceIceServer[];
transportPolicy: VoiceIceTransportPolicy;
gatewayTransportPolicy: VoiceIceTransportPolicy;
profile: VoiceProfileSetting;
opusWebSocket: boolean;
jitterMaxMs: number;
}
/** Baseline used when neither the console nor the environment configures a value. */
export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: VOICE_JITTER_DEFAULT_MS,
};
function parseBoolean(value: string | undefined, fallback: boolean): boolean {
if (value === undefined) return fallback;
const normalized = value.trim().toLowerCase();
if (!normalized) return fallback;
return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
}
function parseInteger(value: string | undefined, fallback: number, min: number, max: number): number {
if (!value?.trim()) return fallback;
const parsed = Number(value);
if (!Number.isInteger(parsed)) return fallback;
return Math.max(min, Math.min(max, parsed));
}
function parseStaticServers(raw: string | undefined): VoiceIceServer[] {
const value = raw?.trim();
if (!value) return [];
if (value.startsWith("[") || value.startsWith("{")) {
try {
const parsed: unknown = JSON.parse(value);
if (Array.isArray(parsed)) return normalizeVoiceIceServers(parsed);
if (parsed && typeof parsed === "object") return normalizeVoiceIceServers([parsed]);
return [];
} catch {
// Fall through to the convenient comma/space-separated STUN form.
}
}
return normalizeVoiceIceServers(value.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
}
function parseTurnRestUrls(raw: string | undefined): string[] {
if (!raw?.trim()) return [];
// Environment parsing stays lenient: one bad entry must not disable a
// previously working TURN deployment during an upgrade.
const urls = raw.split(/[\s,]+/).filter(Boolean).flatMap((token) => {
const [server] = normalizeVoiceIceServers([{ urls: token }]);
if (!server) return [];
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
return candidates.filter((url) => /^turns?:/i.test(url));
});
return [...new Set(urls)].slice(0, 8);
}
export function readVoiceIceConfig(env: NodeJS.ProcessEnv = process.env): VoiceIceConfig {
const servers = parseStaticServers(env.WEBSPEAK_VOICE_ICE_SERVERS);
const turnUrls = parseTurnRestUrls(env.WEBSPEAK_TURN_REST_URLS);
const secret = env.WEBSPEAK_TURN_REST_SECRET?.trim() ?? "";
const ttlSeconds = parseInteger(env.WEBSPEAK_TURN_REST_TTL_SECONDS, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MIN_SECONDS, VOICE_TURN_TTL_MAX_SECONDS);
const turnRest = turnUrls.length && secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
? { urls: turnUrls, secret, ttlSeconds }
: undefined;
return {
...DEFAULT_VOICE_ICE_CONFIG,
servers,
...(turnRest ? { turnRest } : {}),
transportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY),
gatewayTransportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY),
profile: normalizeVoiceProfileSetting(env.WEBSPEAK_VOICE_PROFILE),
// Opus over WebSocket is additive and remains opt-in even in adaptive mode.
opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, false),
jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS),
};
}
/** Build the per-connection list, minting one short-lived TURN credential. */
export function resolveVoiceIceServers(
config: VoiceIceConfig | undefined,
sessionId: string,
nowMs = Date.now(),
): VoiceIceServer[] {
if (!config) return [];
const servers = [...config.servers];
if (config.turnRest) {
servers.push(createTurnRestCredential(config.turnRest, sessionId, nowMs));
}
return normalizeVoiceIceServers(servers);
}
export function voiceConfigSettings(config: VoiceIceConfig): VoiceIceSettings {
return {
servers: normalizeVoiceIceServers(config.servers),
transportPolicy: config.transportPolicy,
gatewayTransportPolicy: config.gatewayTransportPolicy,
profile: config.profile,
opusWebSocket: config.opusWebSocket,
jitterMaxMs: config.jitterMaxMs,
};
}
export { hasVoiceTurnServer };
+83
View File
@@ -109,6 +109,89 @@ for (const scenario of ["silence gaps", "alternating speakers", "volume changes"
});
}
test("WebRTC marks only the first audible RTP packet after a gap", () => {
const packets: RtpPacket[] = [];
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
closed: false,
outgoingPayloadType: 111,
sequenceNumber: 0,
timestamp: 0,
ssrc: 7,
lastAudioRtpAt: null as number | null,
lastEgressRtpAt: null as number | null,
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
}) as unknown as WebRtcAudioSession;
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
send(Buffer.from([1]), true);
send(Buffer.from([2]), true);
send(Buffer.from([3]), false);
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false]);
(session as unknown as { lastAudioRtpAt: number | null }).lastAudioRtpAt = performance.now() - 50;
send(Buffer.from([4]), true);
send(Buffer.from([5]), true);
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false, true, false]);
});
test("legacy RTP pacing keeps the original marker on every packet", () => {
const packets: RtpPacket[] = [];
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
closed: false,
outgoingPayloadType: 111,
sequenceNumber: 0,
timestamp: 0,
ssrc: 7,
lastAudioRtpAt: null as number | null,
lastEgressRtpAt: null as number | null,
rtpMarkerAlways: true,
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
}) as unknown as WebRtcAudioSession;
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
send(Buffer.from([1]), true);
send(Buffer.from([2]), false);
assert.deepEqual(packets.map(packet => packet.header.marker), [true, true]);
});
test("legacy WebRTC profile selects the original bounded mixer constants", async t => {
const session = new WebRtcAudioSession({ connectionId: "legacy-mixer", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(() => session.close());
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
assert.equal(internals.mixerQueueFrames, 4);
assert.equal(internals.maxMixerFrameAgeMs, 80);
assert.equal(internals.mixerQueueAfterLateTick, 1);
assert.equal(internals.rtpMarkerAlways, true);
});
test("adaptive WebRTC profile keeps the longer queue and corrected marker", async t => {
const session = new WebRtcAudioSession({ connectionId: "adaptive-mixer", profile: "adaptive", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(() => session.close());
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
assert.equal(internals.mixerQueueFrames, 6);
assert.equal(internals.maxMixerFrameAgeMs, 200);
assert.equal(internals.mixerQueueAfterLateTick, 2);
assert.equal(internals.rtpMarkerAlways, false);
});
test("late-tick trimming keeps legacy queue bounds and clears adaptive stale frames", () => {
for (const [profile, queueAfterLateTick, frameAgeMs, frameCount, expectedRemaining, expectedDropped] of [
["legacy", 1, 0, 3, 1, 2],
["legacy", 1, 100, 1, 0, 1],
["adaptive", 2, 100, 3, 0, 3],
] as const) {
const queue = Array.from({ length: frameCount }, () => ({ pcm: Buffer.alloc(4), receivedAt: performance.now() - frameAgeMs - 1 }));
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
pendingFrames: new Map([["speaker", queue]]),
mixerQueueAfterLateTick: queueAfterLateTick,
maxMixerFrameAgeMs: 100,
stats: { webrtcQueueDroppedFrames: 0 },
}) as WebRtcAudioSession;
(session as unknown as { trimQueuesAfterLateTick(): void }).trimQueuesAfterLateTick();
assert.equal(queue.length, expectedRemaining, profile);
assert.equal((session as unknown as { stats: { webrtcQueueDroppedFrames: number } }).stats.webrtcQueueDroppedFrames, expectedDropped, profile);
}
});
function fixture() {
const released: string[] = [];
// Exercise the real close path with failures at codec/track/peer boundaries.
+51 -9
View File
@@ -12,6 +12,8 @@ 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";
import type { VoiceIceServer, VoiceIceTransportPolicy } from "../shared/voice-ice.js";
import type { VoiceProfile } from "../shared/voice-profile.js";
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
@@ -23,9 +25,15 @@ 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;
const MAX_MIXER_QUEUE_FRAMES = 4;
const MAX_MIXER_QUEUE_FRAMES = 6;
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
const MAX_MIXER_FRAME_AGE_MS = 200;
const MAX_MIXER_QUEUE_AFTER_LATE_TICK = 2;
// The pre-CFT implementation used a 4-frame queue, an 80 ms age bound and one
// retained frame after a late tick. Keep those values for direct deployments.
const LEGACY_MAX_MIXER_QUEUE_FRAMES = 4;
const LEGACY_MAX_MIXER_FRAME_AGE_MS = LEGACY_MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
const LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK = 1;
const MIXER_UNDERRUN_WINDOW_MS = 200;
// This threshold is used only for the speaking indicator. It must never decide
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
@@ -40,6 +48,9 @@ export interface WebRtcAudioOptions {
publicHost?: string;
ipv6Enabled?: boolean;
stunServer?: string;
/** Full ICE list, including TURN; takes precedence over `stunServer`. */
iceServers?: VoiceIceServer[];
iceTransportPolicy?: VoiceIceTransportPolicy;
udpPortRange?: [number, number];
}
@@ -51,6 +62,10 @@ export interface WebRtcAudioSessionOptions {
publicAddresses?: string[];
ipv6Enabled?: boolean;
stunServer?: string;
iceServers?: VoiceIceServer[];
iceTransportPolicy?: VoiceIceTransportPolicy;
/** `legacy` preserves the direct-deployment mixer; `adaptive` is the CFT path. */
profile?: VoiceProfile;
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
@@ -122,7 +137,12 @@ export class WebRtcAudioSession {
private nextAudioDeadline = 0;
private lastIngressRtpAt: number | null = null;
private lastEgressRtpAt: number | null = null;
private lastAudioRtpAt: number | null = null;
private lastQueueEnqueuedAt: number | null = null;
private readonly mixerQueueFrames: number;
private readonly maxMixerFrameAgeMs: number;
private readonly mixerQueueAfterLateTick: number;
private readonly rtpMarkerAlways: boolean;
private microphoneMuted: boolean;
private accompanimentActive: boolean;
private readonly stats: WebRtcAudioStats = {
@@ -150,19 +170,31 @@ export class WebRtcAudioSession {
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
this.onVoiceFrame = options.onVoiceFrame;
this.onVoiceActivity = options.onVoiceActivity;
const profile = options.profile ?? "legacy";
this.mixerQueueFrames = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_FRAMES : MAX_MIXER_QUEUE_FRAMES;
this.maxMixerFrameAgeMs = profile === "legacy" ? LEGACY_MAX_MIXER_FRAME_AGE_MS : MAX_MIXER_FRAME_AGE_MS;
this.mixerQueueAfterLateTick = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK : MAX_MIXER_QUEUE_AFTER_LATE_TICK;
this.rtpMarkerAlways = profile === "legacy";
this.microphoneMuted = options.microphoneMuted === true;
this.accompanimentActive = options.accompanimentActive === true;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicAddresses ?? (options.publicHost ? [options.publicHost] : undefined);
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
const iceServers = options.iceServers?.length
? options.iceServers
: options.stunServer ? [{ urls: options.stunServer }] : [];
this.peer = new RTCPeerConnection({
// Both audio routes carry Opus; accepting PCMU would label Opus output
// as another codec and silently discard the peer's incoming audio.
codecs: { audio: [useOPUS()] },
iceServers: options.stunServer ? [{ urls: options.stunServer }] : [],
iceServers,
iceTransportPolicy: options.iceTransportPolicy ?? "all",
iceUseIpv4: true,
iceUseIpv6: options.ipv6Enabled === true,
// This controls ICE-TCP host candidates, not TURN control transport.
// werift parses `turns:` as a TLS TURN client independently; verified in
// peerConnection.ts createTransport() -> parseIceServers().
iceUseTcp: false,
icePortRange: [...udpPortRange] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
@@ -226,6 +258,10 @@ export class WebRtcAudioSession {
};
}
get isConnected(): boolean {
return !this.closed && this.peer.connectionState === "connected";
}
getStats(): WebRtcAudioStats {
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
}
@@ -315,7 +351,7 @@ export class WebRtcAudioSession {
queue = [];
this.pendingFrames.set(data.clientId, queue);
}
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
if (queue.length >= this.mixerQueueFrames) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
@@ -398,6 +434,7 @@ export class WebRtcAudioSession {
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
const hasAudio = this.pendingFrames.size > 0;
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
@@ -422,25 +459,30 @@ export class WebRtcAudioSession {
}
try {
const encoded = this.encoder.encode(pcm);
this.sendRtpAudio(encoded);
this.sendRtpAudio(encoded, hasAudio);
} catch {
// A peer closing concurrently may reject a packet; teardown owns the
// session lifecycle and no per-frame error needs to reach the logs.
}
}
private sendRtpAudio(encoded: Buffer): void {
private sendRtpAudio(encoded: Buffer, hasAudio: boolean): void {
const now = performance.now();
const marker = this.rtpMarkerAlways
? true
: hasAudio && (this.lastAudioRtpAt === null || now - this.lastAudioRtpAt > 40);
const packet = new RtpPacket(new RtpHeader({
payloadType: this.outgoingPayloadType,
sequenceNumber: this.sequenceNumber,
timestamp: this.timestamp,
ssrc: this.ssrc,
marker: true,
marker,
}), encoded);
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
this.outgoingTrack.writeRtp(packet);
const sentAt = performance.now();
if (hasAudio) this.lastAudioRtpAt = sentAt;
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
this.lastEgressRtpAt = sentAt;
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
@@ -497,11 +539,11 @@ export class WebRtcAudioSession {
private trimQueuesAfterLateTick(): void {
const now = performance.now();
for (const [clientId, queue] of this.pendingFrames) {
while (queue.length > 1) {
while (queue.length > this.mixerQueueAfterLateTick) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
while (queue[0] && now - queue[0].receivedAt > this.maxMixerFrameAgeMs) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
+7
View File
@@ -15,6 +15,13 @@ export interface AdminSettingsInput {
webRtcStunServer?: string;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
voiceProfile?: "auto" | "legacy" | "adaptive";
voiceTurnUrls?: string;
voiceTurnSecret?: string;
voiceTurnSecretAction?: "keep" | "replace" | "remove";
voiceTurnTtlSeconds?: number;
voiceOpusWs?: boolean;
voiceJitterMaxMs?: number;
relaySettingsAction?: "keep" | "replace" | "remove";
relayEnabled?: boolean;
relayName?: string;
+6
View File
@@ -33,6 +33,12 @@ const settings = object({
webRtcPublicHost: value => value === undefined ? "" : text(value),
webRtcIpv6Enabled: value => value === undefined ? false : boolean(value),
webRtcStunServer: value => value === undefined ? "" : text(value),
voiceProfile: value => value === undefined ? "auto" as const : choice("auto", "legacy", "adaptive")(value),
voiceTurnUrls: value => value === undefined ? "" : text(value),
hasVoiceTurnSecret: value => value === undefined ? false : boolean(value),
voiceTurnTtlSeconds: value => value === undefined ? 21600 : number(value),
voiceOpusWs: value => value === undefined ? false : boolean(value),
voiceJitterMaxMs: value => value === undefined ? 300 : number(value),
relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean,
relayNodes: array(relayNode), internalPort: number, updatedAt: text,
});
+9
View File
@@ -60,12 +60,21 @@ test("every current gateway message survives JSON transport and shared validatio
}
});
test("voice profile is optional and invalid values are rejected", () => {
const adaptive = parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "adaptive" });
assert.equal(adaptive?.type === "connected" ? adaptive.voiceProfile : undefined, "adaptive");
const legacy = parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "legacy" });
assert.equal(legacy?.type === "connected" ? legacy.voiceProfile : undefined, "legacy");
assert.equal(parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "future" }), null);
});
test("malformed nested directory and event data is rejected before client state changes", () => {
for (const message of [
null, [], {}, { type: "toString" }, { type: "futureMessage" },
{ type: "connected", tsClientId: 1, members: [null] },
{ type: "connected", tsClientId: 1, members: [{ id: "1", nickname: "bad id" }] },
{ type: "connected", tsClientId: 1, serverEventLog: [{ id: "incomplete" }] },
{ type: "connected", tsClientId: 1, voiceProfile: "future" },
{ type: "serverInfo", name: "TeamSpeak", icon: "https://example.com/icon.png" },
{ type: "serverInfo", name: "TeamSpeak", bannerUrl: "javascript:alert(1)" },
{ type: "serverInfo", name: "TeamSpeak", welcomeMessage: "x".repeat(4_097) },
+16 -3
View File
@@ -1,8 +1,9 @@
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
import { normalizeScreenShareIceServers, parseScreenShareSignal, SCREEN_SHARE_LEGACY_AVATAR_BUDGET, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
import { normalizeVoiceStunServer } from "./voice-ice.js";
import { normalizeVoiceIceServers, normalizeVoiceIceTransportPolicy, normalizeVoiceStunServer, type VoiceIceServer } from "./voice-ice.js";
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
import { isVoiceProfile, type VoiceProfile } from "./voice-profile.js";
export type { SessionDescription } from "./webrtc.js";
type Message<T extends string, Fields = object> = { type: T } & Fields;
@@ -13,7 +14,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<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webrtcUnavailableReason?: "DISABLED" | "NO_MEDIA_PATH"; webRtcStunServer?: string; voiceProfile?: VoiceProfile; voiceIceServers?: VoiceIceServer[]; voiceIceTransportPolicy?: "all" | "relay"; audioFrameVersion?: 2; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
| Message<"memberEnter", ChannelMember>
| Message<"memberLeave", { id: number }>
@@ -88,8 +89,11 @@ export function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStat
const count = (key: string): number => finite(value[key]) && value[key] >= 0 ? value[key] : 0;
return {
transport: value.transport === "webrtc" ? "webrtc" : "websocket",
ingressFrames: count("ingressFrames"), ingressDroppedFrames: count("ingressDroppedFrames"), ingressMaxGapMs: count("ingressMaxGapMs"),
ingressFrames: count("ingressFrames"), ingressPcmFrames: count("ingressPcmFrames"), ingressOpusFrames: count("ingressOpusFrames"),
ingressDroppedFrames: count("ingressDroppedFrames"), ingressMaxGapMs: count("ingressMaxGapMs"),
tsSendFrames: count("tsSendFrames"), tsSendErrors: count("tsSendErrors"), tsSendMaxGapMs: count("tsSendMaxGapMs"),
uplinkQueuePeakFrames: count("uplinkQueuePeakFrames"), uplinkQueueDroppedFrames: count("uplinkQueueDroppedFrames"),
uplinkPacerLateTicks: count("uplinkPacerLateTicks"),
tsReceiveFrames: count("tsReceiveFrames"), tsReceiveMaxGapMs: count("tsReceiveMaxGapMs"),
egressFrames: count("egressFrames"), egressDroppedFrames: count("egressDroppedFrames"), egressMaxGapMs: count("egressMaxGapMs"),
webrtcIngressRtpFrames: count("webrtcIngressRtpFrames"), webrtcIngressRtpMaxGapMs: count("webrtcIngressRtpMaxGapMs"),
@@ -138,6 +142,13 @@ export function parseScreenShareStream(value: unknown): ScreenShareStreamDescrip
const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> = {
connected: m => optional(m.pluginSession, v => text(v) && /^[A-Za-z0-9_-]{43}$/.test(v)) && clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
&& optional(m.webrtcUnavailableReason, v => v === "DISABLED" || v === "NO_MEDIA_PATH")
&& optional(m.voiceProfile, isVoiceProfile)
&& optional(m.voiceIceServers, v => Array.isArray(v) && normalizeVoiceIceServers(v).length === v.length)
&& optional(m.voiceIceTransportPolicy, v => v === "all" || v === "relay")
&& optional(m.audioFrameVersion, v => v === 2)
&& optional(m.audioUplinkCodecs, v => Array.isArray(v) && v.length > 0 && v.every(codec => codec === "pcm" || codec === "opus"))
&& optional(m.audioJitterMaxMs, v => finite(v) && Number.isInteger(v) && v >= 80 && v <= 500)
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
serverInfo: m => text(m.name) && m.name.length <= 256
&& optional(m.icon, v => v === null || (text(v) && v.length <= 180_000
@@ -191,6 +202,8 @@ export function parseServerMessage(value: unknown): ServerMessage | null {
let result = value;
if (value.type === "connected") {
result = { ...value, ...(value.webRtcStunServer === undefined ? {} : { webRtcStunServer: normalizeVoiceStunServer(value.webRtcStunServer)! }), screenShareIceServers: normalizeScreenShareIceServers(Array.isArray(value.screenShareIceServers) ? value.screenShareIceServers : undefined) };
if (Array.isArray(value.voiceIceServers)) result = { ...result, voiceIceServers: normalizeVoiceIceServers(value.voiceIceServers) };
if (value.voiceIceTransportPolicy !== undefined) result = { ...result, voiceIceTransportPolicy: normalizeVoiceIceTransportPolicy(value.voiceIceTransportPolicy) };
} else if (value.type === "audioStats") {
result = { ...value, stats: parseVoiceAudioBridgeStats(value.stats) };
} else if (value.type === "screenShareList") {
+90 -7
View File
@@ -18,7 +18,8 @@ import {
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
* - `slots`: declarative anchors for trusted host controls. A skin never
* receives the control; it only names a part it already renders so the
* host can position its own top-layer capsule there and fall back to the
* host can position its own top-layer capsule (or, with an explicit
* `mode: "toolbar"`, chrome-less host buttons) there and fall back to the
* default corner when the anchor stops being usable.
*
* Both the browser importer and the server-side registry parse the exact same
@@ -29,6 +30,7 @@ export const SKIN_CHROME_MAX_BYTES = 32 * 1024;
export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32;
export const SKIN_CHROME_MAX_ICONS = 16;
export const SKIN_CHROME_MAX_SLOTS = 8;
export const SKIN_CHROME_MAX_SLOT_ANCHORS = 8;
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
export const SKIN_ICON_DIRECTORY = "assets/icons/";
@@ -72,13 +74,39 @@ export interface SkinChromeDocument {
export type SkinChromeSlotAlign = "start" | "center" | "end";
/**
* How a slotted recovery control is presented:
* - `capsule` (default): the existing rounded host capsule with its own shell.
* - `toolbar`: independent, chrome-less host buttons that can match a skin's
* top bar. The host still creates the buttons, their labels, focus and
* click handlers; the skin only names anchors and style tokens.
*
* The mode is explicit and never inferred from `compact`: an old slot without
* `mode` keeps docking the capsule exactly as before.
*/
export type SkinChromeSlotMode = "capsule" | "toolbar";
/** Toolbar buttons may show host-owned icons without losing their accessible names. */
export type SkinChromeSlotAppearance = "label" | "icon" | "icon-and-label";
/** One anchor name, or ordered candidates (for example one per page). */
export type SkinChromeSlotAnchor = string | string[];
export interface SkinChromeSlot {
/** Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box. */
anchor: string;
/**
* Existing `data-ws-part` inside `.ws-skin-root` used as the anchor box.
* A list lists page/component candidates: the host takes the first visible
* one, so one slot can cover both the home and the voice page.
*/
anchor: SkinChromeSlotAnchor;
/** Horizontal alignment inside the anchor; the control is vertically centred. */
align: SkinChromeSlotAlign;
/** Collapse to the mark only until hovered or focused. */
/** Collapse to the mark only until hovered or focused (capsule mode only). */
compact: boolean;
/** Explicit presentation; see `SkinChromeSlotMode`. */
mode: SkinChromeSlotMode;
/** Toolbar-only label/icon shape; the host always supplies the icon and name. */
appearance: SkinChromeSlotAppearance;
}
export interface SkinChromeAssetInfo {
@@ -147,10 +175,36 @@ function normalizeSlotAnchor(raw: unknown): string {
return raw;
}
/**
* A slot may name one anchor or an ordered candidate list (one per page or
* per component variant). Candidates are validated exactly like a single
* anchor; duplicates are removed so a page cannot be tried twice per check.
*/
function normalizeSlotAnchors(raw: unknown): SkinChromeSlotAnchor {
if (!Array.isArray(raw)) return normalizeSlotAnchor(raw);
if (!raw.length || raw.length > SKIN_CHROME_MAX_SLOT_ANCHORS) {
return reject(`A slot anchor list must contain between 1 and ${SKIN_CHROME_MAX_SLOT_ANCHORS} part names.`, "SKIN_CHROME_SLOT_INVALID");
}
const anchors: string[] = [];
for (const entry of raw) {
const anchor = normalizeSlotAnchor(entry);
if (!anchors.includes(anchor)) anchors.push(anchor);
}
return anchors;
}
function isSlotMode(value: unknown): value is SkinChromeSlotMode {
return value === "capsule" || value === "toolbar";
}
function isSlotAlign(value: unknown): value is SkinChromeSlotAlign {
return value === "start" || value === "center" || value === "end";
}
function isSlotAppearance(value: unknown): value is SkinChromeSlotAppearance {
return value === "label" || value === "icon" || value === "icon-and-label";
}
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
const bytes = new TextEncoder().encode(source).byteLength;
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
@@ -226,20 +280,49 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID");
}
for (const key of Object.keys(value)) {
if (key !== "anchor" && key !== "align" && key !== "compact") {
if (key !== "anchor" && key !== "align" && key !== "compact" && key !== "mode" && key !== "appearance") {
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
}
}
const anchor = normalizeSlotAnchor(value.anchor);
const anchor = normalizeSlotAnchors(value.anchor);
const align = value.align === undefined ? "end" : value.align;
if (!isSlotAlign(align)) {
return reject(`Slot ${part} has an invalid align value: ${String(align)}.`, "SKIN_CHROME_SLOT_INVALID");
}
// The group slot keeps the historical capsule default. The two
// single-action slots only exist for toolbar presentation; a one-button
// capsule would be a new, ambiguous surface with no product need.
const mode = value.mode === undefined
? (part === "host.recovery" ? "capsule" : "toolbar")
: value.mode;
if (!isSlotMode(mode)) {
return reject(`Slot ${part} has an invalid mode value: ${String(mode)}.`, "SKIN_CHROME_SLOT_INVALID");
}
if (part !== "host.recovery" && mode !== "toolbar") {
return reject(`Slot ${part} only supports toolbar mode.`, "SKIN_CHROME_SLOT_INVALID");
}
const compact = value.compact === undefined ? false : value.compact;
if (typeof compact !== "boolean") {
return reject(`Slot ${part} compact must be a boolean.`, "SKIN_CHROME_SLOT_INVALID");
}
slots[part] = { anchor, align, compact };
if (mode === "toolbar" && compact) {
return reject(`Slot ${part} compact is only valid in capsule mode.`, "SKIN_CHROME_SLOT_INVALID");
}
const appearance = value.appearance === undefined ? "label" : value.appearance;
if (!isSlotAppearance(appearance)) {
return reject(`Slot ${part} has an invalid appearance value: ${String(appearance)}.`, "SKIN_CHROME_SLOT_INVALID");
}
if (mode !== "toolbar" && appearance !== "label") {
return reject(`Slot ${part} appearance is only available in toolbar mode.`, "SKIN_CHROME_SLOT_INVALID");
}
slots[part] = { anchor, align, compact, mode, appearance };
}
const perAction = slots["host.recovery.built-in"] !== undefined || slots["host.recovery.library"] !== undefined;
if (slots["host.recovery"] && perAction) {
return reject(
"Declare either host.recovery or its per-action slots (host.recovery.built-in / host.recovery.library), not both.",
"SKIN_CHROME_SLOT_INVALID",
);
}
}
+102 -4
View File
@@ -108,12 +108,15 @@ test("host-owned layer attributes are not skin hooks", () => {
for (const attribute of [
"data-ws-host-layer",
"data-ws-host-recovery",
"data-ws-host-recovery-toolbar",
"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);
// A :root-prefixed mixed selector with a public part hook must also fail.
assert.throws(() => compile(`:root [data-ws-part="home.header"] [${attribute}] { color: red; }`), /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);
}
@@ -121,6 +124,21 @@ test("host-owned layer attributes are not skin hooks", () => {
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }'));
});
test("the host toolbar's private class is not a skin hook", () => {
for (const css of [
':root .ws-host-toolbar { color: red; }',
':root [data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
'[data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
'[data-ws-part="home.header"].ws-host-toolbar { color: red; }',
':root .WS-HOST-TOOLBAR { color: red; }',
':root .\\77 s-host-toolbar { color: red; }',
]) {
assert.throws(() => compile(css), /private host class/i, css);
}
// Ordinary descendant classes remain available when a public hook anchors them.
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] .skin-button { color: teal; }'));
});
test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => {
for (const part of [
"voice.audio-dock",
@@ -197,22 +215,28 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val
});
test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], ["host.recovery"]);
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], [
"host.recovery",
"host.recovery.built-in",
"host.recovery.library",
]);
const explicit = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true },
"host.recovery": { anchor: "voice.audio-dock", align: "start", compact: true, appearance: "label" },
},
}));
assert.deepEqual(explicit.slots?.["host.recovery"], {
anchor: "voice.audio-dock",
align: "start",
compact: true,
mode: "capsule",
appearance: "label",
});
// Defaults: align "end", compact off. Component and runtime-plugin parts are
// ordinary anchors; only host/trusted parts are off limits.
// Old slots without `mode` keep the docked capsule: the presentation is
// explicit, never inferred from compact or any other field.
const defaults = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
@@ -223,6 +247,8 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
anchor: "skin.voice.harbor-dock.part-anchor",
align: "end",
compact: false,
mode: "capsule",
appearance: "label",
});
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
@@ -246,6 +272,78 @@ test("chrome.json slots accept skin-owned anchors and reject trusted host UI", (
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "float" } } }, /invalid mode/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "toolbar", appearance: "text" } } }, /invalid appearance/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", appearance: "icon" } } }, /appearance is only available in toolbar mode/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "capsule", appearance: "icon-and-label" } } }, /appearance is only available in toolbar mode/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", mode: "toolbar", compact: true } } }, /compact is only valid in capsule mode/],
[{ schemaVersion: 1, slots: { "host.recovery.built-in": { anchor: "voice.audio-dock", mode: "capsule" } } }, /only supports toolbar mode/],
[{ schemaVersion: 1, slots: { "host.recovery.built-in": { anchor: "voice.audio-dock", compact: true } } }, /compact is only valid in capsule mode/],
];
for (const [value, message] of invalidDocuments) {
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
}
});
test("chrome.json toolbar slots support page candidates and separate action buttons", () => {
const toolbar = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery": {
mode: "toolbar",
anchor: [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
"skin.home.topbar.part-host-actions",
],
align: "end",
appearance: "icon",
},
},
}));
assert.deepEqual(toolbar.slots?.["host.recovery"], {
anchor: [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
],
align: "end",
compact: false,
mode: "toolbar",
appearance: "icon",
});
const perAction = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery.built-in": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-built-in",
align: "start",
appearance: "icon-and-label",
},
"host.recovery.library": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-library",
},
},
}));
assert.deepEqual(perAction.slots?.["host.recovery.built-in"], {
anchor: "skin.voice.topbar.part-built-in",
align: "start",
compact: false,
mode: "toolbar",
appearance: "icon-and-label",
});
// Single-action slots are toolbar-only and default to toolbar mode.
assert.equal(perAction.slots?.["host.recovery.library"]?.mode, "toolbar");
assert.equal(perAction.slots?.["host.recovery.library"]?.align, "end");
assert.equal(perAction.slots?.["host.recovery.library"]?.appearance, "label");
const invalidDocuments: Array<[unknown, RegExp]> = [
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: [] } } }, /between 1 and 8/],
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: Array.from({ length: 9 }, (_, index) => `part-${index}`) } } }, /between 1 and 8/],
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: ["voice.audio-dock", "host.plugins.launcher"] } } }, /trusted host UI/],
[{ schemaVersion: 1, slots: { "host.recovery": { mode: "toolbar", anchor: "voice.audio-dock" }, "host.recovery.built-in": { mode: "toolbar", anchor: "voice.audio-dock" } } }, /either host.recovery or its per-action slots/],
];
for (const [value, message] of invalidDocuments) {
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
+5
View File
@@ -104,9 +104,11 @@ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
// opting into the element by attribute.
"data-ws-host-layer",
"data-ws-host-recovery",
"data-ws-host-recovery-toolbar",
"data-ws-host-layer-content",
"data-ws-recovery-action",
]);
const FORBIDDEN_SCOPE_CLASSES = new Set(["ws-host-toolbar"]);
/** CSS-wide keywords never name a keyframe and reset an animatable slot. */
const CSS_WIDE_KEYWORDS = new Set(["initial", "inherit", "unset", "revert", "revert-layer"]);
/** Shorthand keyword slots; a repeated category frees the word to be the name. */
@@ -456,6 +458,9 @@ function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchema
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 === "class" && FORBIDDEN_SCOPE_CLASSES.has(decodeCssEscapes(node.value).toLowerCase())) {
throw new SkinCssValidationError(`Skin selectors cannot reference the private host class .${node.value}.`, "SKIN_CSS_SELECTOR");
}
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
partNames.push(node.value.replace(/^['"]|['"]$/g, ""));
}
+9 -2
View File
@@ -47,11 +47,18 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
* Trusted host controls that an open skin may fold into its own layout through
* `chrome.json#slots`. The key names the protected part, not a CSS hook: the
* skin only declares an anchor rectangle, the host still owns, paints and
* hit-tests the control. Extend this set (for example with `host.permission`)
* when another protected control learns the same runtime placement.
* hit-tests the control.
*
* `host.recovery` is the historical capsule group. The two action keys only
* exist for `mode: "toolbar"` and let a skin dock the "use built-in skin" and
* "application library" host buttons separately; they are still host-owned
* buttons, never DOM hooks. Extend this set when another protected control
* learns the same runtime placement.
*/
export const HOST_SLOTTABLE_PART_IDS: ReadonlySet<string> = new Set([
"host.recovery",
"host.recovery.built-in",
"host.recovery.library",
]);
/** All host-owned parts (used by the part registry and documentation). */
+8
View File
@@ -0,0 +1,8 @@
/** Shared binary framing for the compatibility (PCM/Opus over WebSocket) path. */
export const VOICE_FRAME_SAMPLES = 960;
export const VOICE_PCM_FRAME_BYTES = VOICE_FRAME_SAMPLES * 2;
export const VOICE_PCM_TAG = 0x01;
export const VOICE_OPUS_TAG = 0x02;
/** RFC 6716 maximum Opus packet length; the server validates the same bound. */
export const VOICE_MAX_OPUS_FRAME_BYTES = 1_275;
+49
View File
@@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
hasVoiceTurnServer,
normalizeVoiceIceServers,
normalizeVoiceIceTransportPolicy,
normalizeVoiceTurnRestUrls,
} from "./voice-ice.js";
test("voice ICE normalization accepts STUN and TURN URLs", () => {
const servers = normalizeVoiceIceServers([
{ urls: "stun:stun.example.com:3478" },
{ urls: "stuns:stun.example.com:5349" },
{ urls: ["turns:turn.example.com:443?transport=tcp", "turn:turn.example.com:3478?transport=udp"], username: "u", credential: "c" },
]);
assert.deepEqual(servers, [
{ urls: "stun:stun.example.com:3478" },
{ urls: "stuns:stun.example.com:5349" },
{ urls: ["turns:turn.example.com:443?transport=tcp", "turn:turn.example.com:3478?transport=udp"], username: "u", credential: "c" },
]);
assert.equal(hasVoiceTurnServer(servers), true);
});
test("voice ICE normalization drops malformed, half-credentialed, and duplicate entries", () => {
assert.deepEqual(normalizeVoiceIceServers([
{ urls: "http://turn.example.com" },
{ urls: "turns:turn.example.com:443?transport=udp" },
{ urls: "turn:turn.example.com:3478", username: "u" },
{ urls: "stun:stun.example.com:3478" },
{ urls: "stun:stun.example.com:3478" },
]), [{ urls: "stun:stun.example.com:3478" }]);
});
test("transport policy defaults to direct-first", () => {
assert.equal(normalizeVoiceIceTransportPolicy(undefined), "all");
assert.equal(normalizeVoiceIceTransportPolicy("relay"), "relay");
assert.equal(normalizeVoiceIceTransportPolicy("invalid"), "all");
});
test("TURN REST URL input is strict and keeps direct-first configuration bounded", () => {
assert.deepEqual(normalizeVoiceTurnRestUrls(" turn:turn.example.com:3478\nturns:turn.example.com:5349?transport=tcp "), [
"turn:turn.example.com:3478",
"turns:turn.example.com:5349?transport=tcp",
]);
assert.deepEqual(normalizeVoiceTurnRestUrls(""), []);
assert.equal(normalizeVoiceTurnRestUrls("stun:stun.example.com:3478"), null);
assert.equal(normalizeVoiceTurnRestUrls("https://turn.example.com"), null);
assert.equal(normalizeVoiceTurnRestUrls("turn:turn.example.com:3478\nbad"), null);
});
+109 -1
View File
@@ -15,7 +15,7 @@ export function normalizeVoiceMediaHost(value: unknown): string | null {
return host.toLowerCase();
}
/** Voice currently exposes UDP STUN discovery only, without relay credentials. */
/** UDP STUN discovery only; TURN credentials are supplied separately. */
export function normalizeVoiceStunServer(value: unknown): string | null {
if (typeof value !== "string" || value.length > 300) return null;
if (!value.trim()) return "";
@@ -28,3 +28,111 @@ export function normalizeVoiceStunServer(value: unknown): string | null {
if (!host || port < 1 || port > 65535) return null;
return `stun:${host}:${port}`;
}
export interface VoiceIceServer {
urls: string | string[];
username?: string;
credential?: string;
}
export type VoiceIceTransportPolicy = "all" | "relay";
export const VOICE_TURN_TTL_DEFAULT_SECONDS = 21_600;
export const VOICE_TURN_TTL_MIN_SECONDS = 300;
export const VOICE_TURN_TTL_MAX_SECONDS = 86_400;
export const VOICE_TURN_MIN_SECRET_LENGTH = 16;
export const VOICE_JITTER_DEFAULT_MS = 300;
export const VOICE_JITTER_MIN_MS = 80;
export const VOICE_JITTER_MAX_MS = 500;
const MAX_ICE_SERVER_COUNT = 8;
const MAX_ICE_URL_LENGTH = 512;
const MAX_ICE_CREDENTIAL_LENGTH = 512;
const ICE_URL_PATTERN = /^(stun|stuns|turn|turns):([a-z0-9.-]+|\[[0-9a-f:.]+\])(?::(\d{1,5}))?(?:\?transport=(udp|tcp))?$/i;
function normalizeIceUrl(value: unknown): string | null {
if (typeof value !== "string") return null;
const url = value.trim();
if (!url || url.length > MAX_ICE_URL_LENGTH) return null;
const match = ICE_URL_PATTERN.exec(url);
if (!match) return null;
const scheme = match[1]!.toLowerCase();
const port = match[3] === undefined ? undefined : Number(match[3]);
if (port !== undefined && (port < 1 || port > 65_535)) return null;
const transport = match[4]?.toLowerCase();
if (scheme === "stun" || scheme === "stuns") {
return transport ? null : `${scheme}:${match[2]}${port === undefined ? "" : `:${port}`}`;
}
if (scheme === "turns" && transport === "udp") return null;
return `${scheme}:${match[2]}${port === undefined ? "" : `:${port}`}${transport ? `?transport=${transport}` : ""}`;
}
/**
* Bound server-owned ICE configuration before it reaches a browser or werift.
* TURN is accepted only as an explicitly configured external service; no
* gateway-owned relay is inserted here.
*/
export function normalizeVoiceIceServers(value?: readonly unknown[]): VoiceIceServer[] {
if (!value?.length) return [];
const normalized: VoiceIceServer[] = [];
const seen = new Set<string>();
for (const raw of value) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
const candidate = raw as Record<string, unknown>;
const rawUrls = candidate.urls;
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
.map(normalizeIceUrl)
.filter((url): url is string => url !== null);
const uniqueUrls = [...new Set(urls)];
if (!uniqueUrls.length) continue;
const username = typeof candidate.username === "string" && candidate.username.length <= MAX_ICE_CREDENTIAL_LENGTH
? candidate.username
: undefined;
const credential = typeof candidate.credential === "string" && candidate.credential.length <= MAX_ICE_CREDENTIAL_LENGTH
? candidate.credential
: undefined;
// Do not forward a half-configured TURN credential pair.
if ((username === undefined) !== (credential === undefined)) continue;
const key = JSON.stringify([uniqueUrls, username ?? ""]);
if (seen.has(key)) continue;
seen.add(key);
normalized.push({
urls: uniqueUrls.length === 1 ? uniqueUrls[0]! : uniqueUrls,
...(username !== undefined ? { username } : {}),
...(credential !== undefined ? { credential } : {}),
});
if (normalized.length >= MAX_ICE_SERVER_COUNT) break;
}
return normalized;
}
export function normalizeVoiceIceTransportPolicy(value: unknown): VoiceIceTransportPolicy {
return value === "relay" ? "relay" : "all";
}
/**
* Normalize the TURN REST service URL list used by the admin console.
* Unlike the environment parser, an invalid token is a configuration error
* rather than a silently ignored value.
*/
export function normalizeVoiceTurnRestUrls(value: unknown): string[] | null {
if (typeof value !== "string" || value.length > 4096) return null;
const tokens = value.trim() ? value.trim().split(/[\s,]+/).filter(Boolean) : [];
if (tokens.length > MAX_ICE_SERVER_COUNT) return null;
const urls: string[] = [];
for (const token of tokens) {
const [server] = normalizeVoiceIceServers([{ urls: token }]);
if (!server) return null;
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
if (!candidates.every((url) => /^turns?:/i.test(url))) return null;
urls.push(...candidates);
}
return [...new Set(urls)];
}
export function hasVoiceTurnServer(servers: readonly VoiceIceServer[]): boolean {
return servers.some((server) => {
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
return urls.some((url) => /^turns?:/i.test(url));
});
}
+5
View File
@@ -58,11 +58,16 @@ export interface ServerEvent {
export interface VoiceAudioBridgeStats {
transport: "webrtc" | "websocket";
ingressFrames: number;
ingressPcmFrames?: number;
ingressOpusFrames?: number;
ingressDroppedFrames: number;
ingressMaxGapMs: number;
tsSendFrames: number;
tsSendErrors: number;
tsSendMaxGapMs: number;
uplinkQueuePeakFrames?: number;
uplinkQueueDroppedFrames?: number;
uplinkPacerLateTicks?: number;
tsReceiveFrames: number;
tsReceiveMaxGapMs: number;
egressFrames: number;
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { normalizeVoiceProfileSetting, resolveVoiceProfile } from "./voice-profile.js";
test("auto keeps direct requests on legacy and opts Cloudflare requests into adaptive", () => {
assert.equal(normalizeVoiceProfileSetting(undefined), "auto");
assert.equal(normalizeVoiceProfileSetting(""), "auto");
assert.equal(normalizeVoiceProfileSetting("unknown"), "auto");
assert.equal(resolveVoiceProfile("auto", false), "legacy");
assert.equal(resolveVoiceProfile("auto", true), "adaptive");
});
test("explicit profile settings override request detection in both directions", () => {
assert.equal(resolveVoiceProfile("legacy", true), "legacy");
assert.equal(resolveVoiceProfile("adaptive", false), "adaptive");
assert.equal(normalizeVoiceProfileSetting(" LEGACY "), "legacy");
assert.equal(normalizeVoiceProfileSetting("Adaptive"), "adaptive");
});
+26
View File
@@ -0,0 +1,26 @@
export type VoiceProfile = "legacy" | "adaptive";
export type VoiceProfileSetting = VoiceProfile | "auto";
/**
* `auto` is the deployment default: direct HTTP/WebSocket traffic keeps the
* historical audio path, while Cloudflare-proxied connections opt into the
* adaptive path automatically. Explicit `legacy`/`adaptive` wins everywhere.
*/
export function normalizeVoiceProfileSetting(value: unknown): VoiceProfileSetting {
if (typeof value !== "string") return "auto";
const normalized = value.trim().toLowerCase();
return normalized === "legacy" || normalized === "adaptive" ? normalized : "auto";
}
export function resolveVoiceProfile(setting: VoiceProfileSetting, cloudflareRequest: boolean): VoiceProfile {
if (setting === "legacy" || setting === "adaptive") return setting;
return cloudflareRequest ? "adaptive" : "legacy";
}
export function isVoiceProfile(value: unknown): value is VoiceProfile {
return value === "legacy" || value === "adaptive";
}
export function isVoiceProfileSetting(value: unknown): value is VoiceProfileSetting {
return value === "auto" || isVoiceProfile(value);
}
+1 -1
View File
@@ -67,7 +67,7 @@ test("official relative .bin symlinks are accepted and resolve inside the packag
await extractReleaseArchive(archive, destination, "release.tar.gz");
const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
assert.equal(lstatSync(link).isSymbolicLink(), true);
assert.equal(readlinkSync(link), "../nanoid/bin/nanoid.cjs");
assert.equal(readlinkSync(link), path.normalize("../nanoid/bin/nanoid.cjs"));
assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
});
+5
View File
@@ -37,6 +37,11 @@ test("staged packages must be complete, regular files and version-matched", t =>
rmSync(path.join(missing, "runtime", "node"));
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
const missingLauncher = workspace(t);
createPackageFiles(missingLauncher, "0.4.0");
rmSync(path.join(missingLauncher, "start-webspeak.sh"));
assert.throws(() => validateStagedPackage(missingLauncher, { version: "0.4.0", platform: "linux" }), packageInvalid);
const linked = workspace(t);
createPackageFiles(linked, "0.4.0");
rmSync(path.join(linked, "runtime", "node"));
+13 -7
View File
@@ -56,6 +56,7 @@ export function validateStagedPackage(root: string, options: StagedPackageOption
requireEntry(root, "node_modules", "directory");
requireEntry(root, "package.json", "file");
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
requireEntry(root, options.platform === "win32" ? "start-webspeak.cmd" : "start-webspeak.sh", "file");
let manifest: unknown;
try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); }
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); }
@@ -145,10 +146,10 @@ function moveIfPresent(from: string, to: string): void {
}
/**
* Backups written by this version contain only atomically moved entries.
* The manifest records which entries were moved completely, so a backup that
* was partially written by an older implementation (or tampered with) can be
* rejected instead of overwriting an intact install tree.
* Backups written by this version journal each entry before moving it. The
* journal may therefore contain an entry whose move never started, but it can
* never omit an entry that reached the backup. Recovery acts only on entries
* that actually exist in the backup, so a kill between journal and move is safe.
*/
const SWAP_MANIFEST = ".webspeak-swap.json";
@@ -203,10 +204,10 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
writeSwapManifest(backupDir, []);
for (const entry of CODE_ENTRIES) {
if (!existsSync(path.join(rootDir, entry))) continue;
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
movedToBackup.push(entry);
swapWindowBarrier(entry);
writeSwapManifest(backupDir, movedToBackup);
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
swapWindowBarrier(entry);
}
swapWindowBarrier();
for (const entry of CODE_ENTRIES) {
@@ -216,7 +217,12 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
}
} catch (error) {
try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
catch { /* Report the original swap error; rollback failure is handled by the caller. */ }
catch (rollbackError) {
throw new CodeSwapError(
"UPDATE_ROLLBACK_FAILED",
`${error instanceof Error ? error.message : "Release package swap failed."} Code rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : "unknown error"}`,
);
}
if (error instanceof CodeSwapError) throw error;
throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed.");
}
+73 -4
View File
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { setCodeSwapCopyForTests } from "./code-swap.js";
import { runRestartPlan } from "./restart-runner.js";
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
@@ -27,13 +30,13 @@ async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
}
}
function appScript(version: string, port: number, pidFile: string): string {
function appScript(version: string, port: number, pidFile: string, status = "ok"): string {
return `const http = require("node:http");
const { writeFileSync } = require("node:fs");
const server = http.createServer((request, response) => {
if (request.url === "/api/health") {
response.setHeader("content-type", "application/json");
response.end(JSON.stringify({ status: "ok", version: ${JSON.stringify(version)} }));
response.end(JSON.stringify({ status: ${JSON.stringify(status)}, version: ${JSON.stringify(version)} }));
return;
}
response.statusCode = 404;
@@ -85,10 +88,10 @@ function runnerFixture(t: TestContext): RunnerFixture {
};
}
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; healthTimeoutMs?: number }) {
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; reportedStatus?: string; healthTimeoutMs?: number }) {
mkdirSync(path.dirname(fixture.statePath), { recursive: true });
writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() }));
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile));
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile, options.reportedStatus));
writeFileSync(fixture.planPath, JSON.stringify({
schemaVersion: 1,
taskId: fixture.taskId,
@@ -123,6 +126,21 @@ async function stopPidFile(pidFile: string): Promise<void> {
}
}
test("a runner refused by another lock owner leaves its files and state untouched", async t => {
const fixture = runnerFixture(t);
writePlan(fixture, await availablePort(), fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
const owner = JSON.stringify({ pid: process.pid, taskId: "recovery_owner", createdAt: new Date().toISOString() });
writeFileSync(fixture.lockPath, owner);
writeFileSync(fixture.statePath, JSON.stringify({ schemaVersion: 1, task: null }));
const before = readFileSync(fixture.statePath, "utf8");
assert.equal(await runRestartPlan(fixture.planPath), 1);
assert.equal(readFileSync(fixture.statePath, "utf8"), before);
assert.equal(readFileSync(fixture.lockPath, "utf8"), owner);
assert.equal(existsSync(fixture.backupDir), false);
assert.equal(existsSync(fixture.pidFile), false);
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "1.0.0");
});
test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
@@ -148,6 +166,57 @@ test("a healthy target version completes the swap and leaves persistent state al
await waitFor(() => existsSync(fixture.pidFile));
});
test("a failed in-process rollback is persisted as a rollback failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
const originalRename = fs.renameSync;
t.after(() => {
fs.renameSync = originalRename;
syncBuiltinESMExports();
setCodeSwapCopyForTests(null);
});
const exdev = () => Object.assign(new Error("cross-device link"), { code: "EXDEV" });
fs.renameSync = ((from, to) => {
if (from === path.join(fixture.rootDir, "dist") && to === path.join(fixture.backupDir, "dist")) throw exdev();
if (from === path.join(fixture.stagedRoot, "dist") && to === path.join(fixture.rootDir, "dist")) throw new Error("simulated staging failure");
if (from === path.join(fixture.backupDir, "dist") && to === path.join(fixture.rootDir, "dist")) throw exdev();
return originalRename(from, to);
}) as typeof fs.renameSync;
syncBuiltinESMExports();
let copies = 0;
setCodeSwapCopyForTests((from, to) => {
copies += 1;
if (copies === 2) throw new Error("simulated rollback copy failure");
fs.cpSync(from, to, { recursive: true });
});
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, false);
assert.equal(state.task.errorCode, "UPDATE_ROLLBACK_FAILED");
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
});
test("a target reporting the expected version with an error status is not accepted as healthy", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, {
targetVersion: "2.0.0", reportedVersion: "2.0.0", reportedStatus: "error", healthTimeoutMs: 500,
});
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
t.after(() => stopPidFile(fixture.pidFile));
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, true);
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
});
test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
+12 -3
View File
@@ -217,7 +217,7 @@ async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: num
if (last?.status === "ok" && last.version === version) return last;
await sleep(plan.pollIntervalMs);
}
return last?.version === version ? last : null;
return null;
}
function startApp(plan: RestartPlan): ChildProcess {
@@ -273,8 +273,6 @@ export async function runRestartPlan(planPath: string): Promise<number> {
const state = new StateWriter(plan);
let swapped = false;
let newApp: ChildProcess | undefined;
state.status("restarting");
state.step("restart", "running");
// Take over the update lock before doing anything else. The parent process
// is about to exit and its lock would otherwise have a dead pid, letting a
// second instance starting in this window roll the healthy code back.
@@ -285,6 +283,8 @@ export async function runRestartPlan(planPath: string): Promise<number> {
} catch (error) {
throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over.");
}
state.status("restarting");
state.step("restart", "running");
await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
state.step("swap", "running");
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
@@ -303,12 +303,21 @@ export async function runRestartPlan(planPath: string): Promise<number> {
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
return 0;
} catch (error) {
// A recovery process or another update owns the tree. Without ownership
// this runner must not rewrite its state or start an app during recovery.
if (!releaseLock) return 1;
await stopApp(newApp);
const code = error instanceof RunnerError || error instanceof CodeSwapError
? error.code
: "UPDATE_RESTART_FAILED";
const message = error instanceof Error ? error.message : "The update could not be completed.";
state.step("restart", "failed", message);
if (!swapped && code === "UPDATE_ROLLBACK_FAILED") {
state.rolledBack(false);
state.status("failed", { code, message });
releaseLock?.();
return 1;
}
let rolledBack = !swapped;
if (swapped) {
state.step("rollback", "running");
+150 -2
View File
@@ -2,12 +2,13 @@ import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process";
import { createServer } from "node:net";
import test, { type TestContext } from "node:test";
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { UpdateService } from "./update-service.js";
import { CODE_ENTRIES } from "./code-swap.js";
import { CODE_ENTRIES, swapCode } from "./code-swap.js";
import { acquireUpdateLock, updateLockIsHeld } from "./update-state.js";
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
@@ -17,6 +18,71 @@ const TASK_ID = "upd_sigkill_window";
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
for (const lockKind of ["live", "unreadable"] as const) {
test(`launcher preserves a target while the update lock is ${lockKind}`, { timeout: 15_000, skip: process.platform !== "linux" }, async t => {
const fixture = buildFixture(t, await availablePort());
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
if (lockKind === "live") {
const release = acquireUpdateLock(lockPath, TASK_ID);
t.after(release);
assert.equal(updateLockIsHeld(lockPath, TASK_ID), true);
} else {
writeFileSync(lockPath, "{invalid");
}
const before = readFileSync(lockPath, "utf8");
const app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir, env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir }, stdio: "ignore",
});
t.after(() => stop(app));
await waitFor(() => app.exitCode !== null, "launcher did not refuse the held update lock", 5_000);
assert.equal(app.exitCode, 75);
assert.equal(readFileSync(lockPath, "utf8"), before);
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(JSON.parse(readFileSync(path.join(fixture.backupDir, "package.json"), "utf8")).version, "0.3.2");
});
}
test("concurrent launchers cannot restore the same interrupted tree together", { timeout: 20_000, skip: process.platform !== "linux" }, async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
const bin = path.join(fixture.directory, "bin");
mkdirSync(bin);
// Pause the first real restore at mv, without adding a production test hook.
writeFileSync(path.join(bin, "mv"), `#!/bin/sh
printf '%s' "$$" > "$RECOVERY_TEST_BARRIER/entered"
attempt=0
while [ ! -f "$RECOVERY_TEST_BARRIER/resume" ] && [ "$attempt" -lt 200 ]; do
sleep 0.05
attempt=$((attempt + 1))
done
exec /bin/mv "$@"
`, { mode: 0o755 });
const env = { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir,
PATH: `${bin}${path.delimiter}${process.env.PATH}`, RECOVERY_TEST_BARRIER: fixture.barrierDir };
const first = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" });
let second: ChildProcess | undefined;
try {
await waitFor(() => existsSync(path.join(fixture.barrierDir, "entered")), "first launcher did not start restoring");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
assert.equal(updateLockIsHeld(lockPath), true);
const owner = readFileSync(lockPath, "utf8");
second = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" });
await waitFor(() => second!.exitCode !== null, "second launcher did not refuse concurrent recovery", 5_000);
assert.equal(second.exitCode, 75);
assert.equal(readFileSync(lockPath, "utf8"), owner);
writeFileSync(path.join(fixture.barrierDir, "resume"), "");
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "first launcher did not finish recovery");
assert.equal(existsSync(lockPath), false);
} finally {
// Stop children before buildFixture's after hook removes their files.
writeFileSync(path.join(fixture.barrierDir, "resume"), "");
stop(first); stop(second);
await waitFor(() => !processAlive(first.pid) && !processAlive(second?.pid), "recovery processes did not stop", 5_000);
}
});
// Exercise a kill after every old entry's rename, before the manifest is
// updated. In particular the backup is still partial for the first entries.
for (const entry of CODE_ENTRIES) {
@@ -81,6 +147,11 @@ async function healthVersion(port: number): Promise<string | null> {
}
}
function startedVersion(fixture: Fixture): string | null {
const { startedFile } = JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")) as { startedFile: string };
return existsSync(startedFile) ? readFileSync(startedFile, "utf8") : null;
}
function processAlive(pid: number | undefined): boolean {
if (!pid || pid <= 0) return false;
try { process.kill(pid, 0); return true; }
@@ -309,6 +380,83 @@ test(
},
);
test(
"launcher resumes a partial current backup instead of installing a stale complete backup",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port, true);
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
mkdirSync(fixture.backupDir, { recursive: true });
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "dist"));
writeFileSync(path.join(fixture.backupDir, ".webspeak-swap.json"), JSON.stringify({ schemaVersion: 1, entries: ["dist"] }));
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the partial current backup");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0");
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
},
);
test(
"launcher resumes a rollback that already consumed part of the current backup",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
for (const entry of ["runtime", "package.json"]) {
rmSync(path.join(fixture.rootDir, entry), { recursive: true, force: true });
renameSync(path.join(fixture.backupDir, entry), path.join(fixture.rootDir, entry));
}
mkdirSync(path.join(fixture.backupDir, "rejected"), { recursive: true });
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "rejected", "dist"));
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the interrupted rollback");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), true);
},
);
test(
"launcher rolls back an active fully swapped tree before starting the target",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript());
copyFileSync(process.execPath, path.join(fixture.stagedRoot, "runtime", "node"));
chmodSync(path.join(fixture.stagedRoot, "runtime", "node"), 0o755);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resolve the active swapped tree");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
},
);
test(
"recovery prefers the in-progress task backup over an older lexicographically-first backup",
{ timeout: 40_000 },
+1
View File
@@ -143,6 +143,7 @@ export function createPackageFiles(root: string, version: string, extra: Record<
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
writeFileSync(path.join(root, "start-webspeak.sh"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
for (const [relative, contents] of Object.entries(extra)) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
+199 -1
View File
@@ -1,6 +1,9 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { once } from "node:events";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { Writable } from "node:stream";
import test, { type TestContext } from "node:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -8,6 +11,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js";
import { swapCode } from "./code-swap.js";
import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js";
import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js";
import { acquireUpdateLock, readUpdateState, writeUpdateState } from "./update-state.js";
@@ -67,6 +71,7 @@ function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
{ name: "webspeak/node_modules/.keep", data: "" },
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
{ name: "webspeak/start-webspeak.sh", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
...extra,
]);
}
@@ -269,6 +274,142 @@ test("unsafe archives are refused before any code is staged", async t => {
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
});
test("an asynchronous download write failure rejects the update without crashing the process", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
});
const originalCreateWriteStream = fs.createWriteStream;
t.after(() => {
fs.createWriteStream = originalCreateWriteStream;
syncBuiltinESMExports();
});
fs.createWriteStream = (() => new Writable({
write(_chunk, _encoding, callback) {
setImmediate(() => callback(new Error("simulated ENOSPC")));
},
})) as unknown as typeof fs.createWriteStream;
syncBuiltinESMExports();
const cancelled = new Set<string>();
const responses: Response[] = [];
const signals: AbortSignal[] = [];
const stalledBody = (url: string) => new ReadableStream({
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
pull() { return new Promise(() => {}); },
cancel() { cancelled.add(url); },
});
const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
if (String(input) === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
signals.push(init!.signal!);
const response = new Response(stalledBody(String(input)), { status: 200 });
responses.push(response);
return response;
}) as typeof globalThis.fetch;
const { service, launched } = createService(t, [], new Map(), { fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_FAILED"));
assert.equal(launched.length, 0);
assert.equal(cancelled.size, 2);
assert.ok(signals.every(signal => signal.aborted));
assert.ok(responses.every(response => !response.body!.locked));
});
test("a rejected asset aborts its stalled sibling before update cleanup returns", { timeout: 5_000 }, async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({ version: "0.4.0", assets: [{ name: ASSET_NAME, data: archive }, { name: CHECKSUM_ASSET_NAME, data: checksums }] });
const responses: Response[] = [], signals: AbortSignal[] = [];
let cancelled = 0;
const { service, dataDir } = createService(t, [], new Map(), { fetch: (async (input, init) => {
const url = String(input);
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]));
signals.push(init!.signal!);
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new Uint8Array([1])); },
pull() { return new Promise(() => {}); },
cancel() { cancelled++; },
});
const response = new Response(body, { headers: url.endsWith(ASSET_NAME) ? { "content-length": String(513 * 1024 * 1024) } : {} });
responses.push(response);
return response;
}) as typeof fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE"));
assert.equal(cancelled, 2);
assert.ok(signals.every(signal => signal.aborted));
assert.ok(responses.every(response => !response.body!.locked));
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false);
});
test("download rejection cancels its body and releases the reader, including unread responses", async t => {
for (const declaredSize of [false, true]) {
let cancelled = false;
let signal: AbortSignal | null | undefined;
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
cancel() { cancelled = true; },
});
const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => {
signal = init?.signal;
return new Response(body, { headers: declaredSize ? { "content-length": "3" } : {} });
}) as typeof fetch });
const target = path.join(workspace(t), "asset");
// A small injected byte limit exercises the production rejection path
// without allocating or writing a 512 MiB package in a regression test.
const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise<unknown> };
await assert.rejects(download.downloadAsset({ name: ASSET_NAME,
url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 1),
updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE"));
assert.equal(cancelled, true);
assert.equal(body.locked, false);
assert.equal(signal?.aborted, true);
assert.equal(existsSync(target), false);
assert.equal(existsSync(`${target}.${process.pid}.tmp`), false);
}
});
test("a successful download releases its reader without aborting the request", async t => {
let signal: AbortSignal | null | undefined;
const response = new Response(new Uint8Array([1, 2, 3]));
const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => {
signal = init?.signal; return response;
}) as typeof fetch });
const target = path.join(workspace(t), "asset");
const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise<unknown> };
await download.downloadAsset({ name: ASSET_NAME,
url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 4);
assert.deepEqual(readFileSync(target), Buffer.from([1, 2, 3]));
assert.equal(response.body!.locked, false);
assert.equal(signal?.aborted, false);
});
test("a download redirected outside GitHub is refused before it is written", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
});
const fetch = (async (input: string | URL | Request) => {
const url = String(input);
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
const response = new Response(url.endsWith(ASSET_NAME) ? new Uint8Array(archive) : new Uint8Array(checksums), { status: 200 });
if (url.endsWith(ASSET_NAME)) Object.defineProperty(response, "url", { value: "https://example.invalid/package.tar.gz" });
return response;
}) as typeof globalThis.fetch;
const { service, launched } = createService(t, [], new Map(), { fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_RELEASE_UNAVAILABLE"));
assert.equal(launched.length, 0);
});
test("a verified package is staged, persisted and handed to the restart runner", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
@@ -400,7 +541,7 @@ test("initialization restores the previous code from an interrupted swap backup"
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
@@ -415,6 +556,39 @@ test("initialization restores the previous code from an interrupted swap backup"
assert.equal(existsSync(lockPath), false);
});
test("initialization keeps a complete target tree consistent with the running target version", t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_complete_target";
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
const stagedRoot = path.join(fixture.dataDir, "updates", "tasks", taskId, "staged");
createPackageFiles(stagedRoot, "0.4.0", { "dist/index.js": "// complete target code\n" });
swapCode(fixture.rootDir, stagedRoot, backupDir);
writeUpdateState(statePath, {
schemaVersion: 1,
task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
});
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
restarted.initialize();
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// complete target code\n");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(restarted.getStatus().task?.status, "succeeded");
assert.equal(restarted.getStatus().task?.rolledBack, false);
assert.equal(existsSync(lockPath), false);
});
test("initialization keeps a live task but reconciles it once its process is gone", async t => {
const fixture = createService(t, [], new Map());
const running = {
@@ -444,6 +618,30 @@ test("initialization keeps a live task but reconciles it once its process is gon
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
});
test("initialization preserves an interrupted tree while a launcher recovery owns the lock", t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_launcher_recovery";
const updates = path.join(fixture.dataDir, "updates");
const staged = path.join(updates, "tasks", taskId, "staged");
createPackageFiles(staged, "0.4.0");
const backup = path.join(updates, "backups", taskId);
swapCode(fixture.rootDir, staged, backup);
writeUpdateState(path.join(updates, "state.json"), { schemaVersion: 1, task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
} });
const lockPath = path.join(updates, "update.lock");
const release = acquireUpdateLock(lockPath, "recovery_other_launcher");
t.after(release);
const owner = readFileSync(lockPath, "utf8");
fixture.service.initialize();
assert.equal(readFileSync(lockPath, "utf8"), owner);
assert.equal(fixture.service.getStatus().task?.status, "restarting");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(JSON.parse(readFileSync(path.join(backup, "package.json"), "utf8")).version, "0.3.2");
});
test("a replacement app can update again after the runner finishes its cached task", async t => {
const fixture = createService(t, [], new Map());
const statePath = path.join(fixture.dataDir, "updates", "state.json");
+76 -29
View File
@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { CodeSwapError, locatePackageRoot, restoreCode } from "./code-swap.js";
import { CodeSwapError, locatePackageRoot, restoreCode, validateStagedPackage } from "./code-swap.js";
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
import {
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
@@ -162,7 +162,7 @@ export class UpdateService {
const task = this.state.task;
// A live lock owner (for example a second process starting by mistake)
// must not have its in-flight task reconciled as interrupted.
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath, task.id)) {
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath)) {
const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null;
const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
if (changed) writeUpdateState(this.statePath, this.state);
@@ -184,6 +184,15 @@ export class UpdateService {
private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null {
const backupDir = path.join(this.backupsDir, task.id);
if (!existsSync(backupDir)) return null;
if (this.options.currentVersion === task.targetVersion) {
try {
validateStagedPackage(this.options.rootDir, { version: task.targetVersion, platform: this.options.platform });
return null;
} catch {
// A process can read the target version before every target entry is in
// place. Fall through to recovery when the on-disk tree is incomplete.
}
}
const now = this.now().toISOString();
let restored = false;
try {
@@ -321,10 +330,22 @@ export class UpdateService {
const archivePath = path.join(downloadDirectory, assetName);
const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME);
this.startStep(task, "download");
const [archive, checksumFile] = await Promise.all([
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT),
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT),
]);
const downloadsController = new AbortController();
const downloads = [
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT, downloadsController.signal),
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT, downloadsController.signal),
];
let archive: DownloadResult;
let checksumFile: DownloadResult;
try {
[archive, checksumFile] = await Promise.all(downloads);
} catch (error) {
downloadsController.abort();
// No sibling may still hold a response reader or write into the task
// directory when applyUpdate's failure cleanup removes that directory.
await Promise.allSettled(downloads);
throw error;
}
this.finishStep(task, "download", "succeeded");
this.updateTaskStatus(task, "verifying");
this.startStep(task, "checksum");
@@ -467,50 +488,76 @@ export class UpdateService {
if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422);
}
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number): Promise<DownloadResult> {
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number, cancelSignal?: AbortSignal): Promise<DownloadResult> {
try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); }
let response: Response;
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000), ...(cancelSignal ? [cancelSignal] : [])]);
try {
response = await this.fetcher(asset.url, {
headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" },
signal: AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000),
signal,
});
} catch (error) {
controller.abort();
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502);
}
if (response.url) {
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); }
}
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
const declared = Number(response.headers.get("content-length") ?? "");
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
const temporary = `${destination}.${process.pid}.tmp`;
const hash = createHash("sha256");
const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
let bytes = 0;
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
let stream: ReturnType<typeof createWriteStream> | undefined;
let temporary: string | undefined;
let onAbort: (() => void) | undefined;
try {
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
const buffer = Buffer.from(chunk);
if (response.url) {
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); }
}
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
const declared = Number(response.headers.get("content-length") ?? "");
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
temporary = `${destination}.${process.pid}.tmp`;
const hash = createHash("sha256");
signal.throwIfAborted();
reader = response.body.getReader();
stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
let bytes = 0;
let failStream!: (error: Error) => void;
const streamFailure = new Promise<Error>((resolve) => { failStream = resolve; });
stream.on("error", failStream);
onAbort = () => failStream(signal.reason instanceof Error ? signal.reason : new Error("Download aborted."));
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
const writer = stream;
const finished = new Promise<void>((resolve) => { writer.once("finish", resolve); });
while (true) {
const next = await Promise.race([reader.read(), streamFailure]);
if (next instanceof Error) throw next;
if (next.done) break;
const buffer = Buffer.from(next.value);
bytes += buffer.length;
if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
hash.update(buffer);
if (!stream.write(buffer)) await new Promise<void>((resolve) => stream.once("drain", resolve));
if (!stream.write(buffer)) {
const drained = await Promise.race([streamFailure, new Promise<void>((resolve) => { writer.once("drain", resolve); })]);
if (drained instanceof Error) throw drained;
}
}
stream.end();
await new Promise<void>((resolve, reject) => {
stream.once("finish", resolve);
stream.once("error", reject);
});
const streamError = await Promise.race([finished.then(() => null), streamFailure]);
if (streamError) throw streamError;
await rename(temporary, destination);
return { sha256: hash.digest("hex"), bytes };
} catch (error) {
stream.destroy();
await rm(temporary, { force: true }).catch(() => undefined);
controller.abort();
await (reader ? reader.cancel() : response.body?.cancel())?.catch(() => undefined);
stream?.destroy();
if (temporary) await rm(temporary, { force: true }).catch(() => undefined);
if (error instanceof UpdateError) throw error;
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502);
} finally {
if (onAbort) signal.removeEventListener("abort", onAbort);
reader?.releaseLock();
}
return { sha256: hash.digest("hex"), bytes };
}
/**
+2 -2
View File
@@ -1,7 +1,7 @@
apply plugin: 'com.android.application'
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.2'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 302
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.4-dev.0'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 304
android {
namespace = "io.webspeak.client"
+2 -2
View File
@@ -25,7 +25,7 @@
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
},
"version": "0.3.2"
"version": "0.3.4-dev.0"
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
@@ -2952,5 +2952,5 @@
}
}
},
"version": "0.3.2"
"version": "0.3.4-dev.0"
}
+1 -1
View File
@@ -27,5 +27,5 @@
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
},
"version": "0.3.2"
"version": "0.3.4-dev.0"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+25 -4
View File
@@ -3,8 +3,11 @@ import { deflateSync } from "node:zlib";
import { zipSync, strToU8 } from "fflate";
const source = new URL("../../docs/examples/host-chrome-demo/", import.meta.url);
const toolbarSource = new URL("../../docs/examples/host-chrome-toolbar/", import.meta.url);
const examples = new URL("../../docs/examples/", import.meta.url);
const publicDir = new URL("../public/", import.meta.url);
// Keep rebuilt archives byte-stable when their inputs do not change.
const archiveMtime = new Date(2026, 10, 15, 16, 33, 0);
const crcTable = (() => {
const table = new Uint32Array(256);
@@ -66,12 +69,20 @@ const icons = {
"assets/icons/status.png": iconPng([150, 60, 90], [84, 28, 52]),
};
const [manifestText, cssText, chromeText] = await Promise.all([
const [manifestText, cssText, chromeText, toolbarManifestText, toolbarCssText, toolbarChromeText] = await Promise.all([
readFile(new URL("manifest.json", source), "utf8"),
readFile(new URL("skin.css", source)),
readFile(new URL("chrome.json", source), "utf8"),
readFile(new URL("manifest.json", toolbarSource), "utf8"),
readFile(new URL("skin.css", toolbarSource)),
readFile(new URL("chrome.json", toolbarSource), "utf8"),
]);
const toolbarManifest = JSON.parse(toolbarManifestText);
if (toolbarManifest.author !== "WebSpeak Community") {
throw new Error("host-chrome-toolbar manifest author must be WebSpeak Community");
}
const chrome = JSON.parse(chromeText);
const sharedFiles = {
"skin.css": new Uint8Array(cssText),
@@ -85,20 +96,30 @@ const themed = zipSync({
"manifest.json": strToU8(themedManifest),
"chrome.json": strToU8(themedChrome),
...sharedFiles,
}, { level: 9 });
}, { level: 9, mtime: archiveMtime });
// 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 });
}, { level: 9, mtime: archiveMtime });
// Minimal toolbar-mode sample: host-owned recovery buttons docked into the
// header, with page-wide anchor candidates and toolbar tokens.
const toolbar = zipSync({
"manifest.json": strToU8(toolbarManifestText),
"chrome.json": strToU8(toolbarChromeText),
"skin.css": new Uint8Array(toolbarCssText),
}, { level: 9, mtime: archiveMtime });
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-toolbar.wskin", examples), toolbar),
writeFile(new URL("host-chrome-themed.wskin", publicDir), themed),
writeFile(new URL("host-chrome-demo.wskin", publicDir), hidden),
writeFile(new URL("host-chrome-toolbar.wskin", publicDir), toolbar),
]);
console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} bytes) into docs/examples and web/public.`);
console.log(`Built host chrome demo skins (${themed.byteLength} / ${hidden.byteLength} / ${toolbar.byteLength} bytes) into docs/examples and web/public.`);
+461 -64
View File
@@ -28,8 +28,125 @@
<!-- 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. -->
`data-ws-part`: there is intentionally no skin hook for this control.
With an explicit `chrome.json` `mode: "toolbar"` the host paints plain
host buttons instead of the capsule shell. The buttons are still owned,
labelled, focusable and clickable by the host; the skin only supplies
an anchor and style tokens. -->
<Teleport v-if="layer" :to="layer.container">
<!-- One grouped toolbar entry: both actions share an anchor. -->
<div
v-if="groupToolbarConfig"
ref="groupToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="built-in"
:aria-label="copy.useBuiltIn"
:title="copy.shortcut"
@click="useBuiltInSkin"
>
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
</svg>
</span>
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
</button>
<button
v-if="pluginLibraryAvailable"
type="button"
class="ws-host-toolbar-action"
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="library"
:aria-label="copy.library"
:title="copy.library"
@click="openLibrary"
>
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
</svg>
</span>
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
</button>
</div>
<!-- Per-action toolbar entries: each action has its own anchor. -->
<div
v-if="builtInToolbarConfig"
ref="builtInToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
:class="{ 'ws-host-toolbar-action-icon': builtInToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="built-in"
:aria-label="copy.useBuiltIn"
:title="copy.shortcut"
@click="useBuiltInSkin"
>
<span v-if="builtInToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
</svg>
</span>
<span v-if="builtInToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
</button>
</div>
<div
v-if="libraryToolbarConfig"
ref="libraryToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
:class="{ 'ws-host-toolbar-action-icon': libraryToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="library"
:aria-label="copy.library"
:title="copy.library"
@click="openLibrary"
>
<span v-if="libraryToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
</svg>
</span>
<span v-if="libraryToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
</button>
</div>
<div
ref="recoveryPopover"
popover="manual"
@@ -38,7 +155,7 @@
@focusout="onRecoveryFocusOut"
class="ws-host-recovery"
:class="{ 'ws-host-recovery-compact': compact }"
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
:data-ws-float="capsuleSlotConfig && slotMode === 'slotted' ? undefined : floatPosition"
:tabindex="compact || compactPinned ? 0 : undefined"
data-ws-host-recovery
role="region"
@@ -46,6 +163,7 @@
>
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
<button
v-if="capsuleActions.includes('built-in')"
type="button"
class="ws-host-recovery-action"
data-ws-recovery-action="built-in"
@@ -53,9 +171,9 @@
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
v-if="capsuleActions.includes('library') && pluginLibraryAvailable"
type="button"
class="ws-host-recovery-action"
v-if="pluginLibraryAvailable"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
@@ -65,8 +183,9 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, watchEffect, type Ref } from "vue";
import type { SiteLanguage } from "../../../src/site-copy.js";
import type { SkinChromeSlot } from "../../../src/shared/skin-chrome.js";
import { hostChromeCopy } from "../i18n/host-chrome.js";
import {
activeHostSlot,
@@ -77,6 +196,7 @@ import {
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
setInlineLibraryEntryVisible,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
@@ -89,13 +209,16 @@ import {
type FloatingAvoidance,
type FloatingPosition,
} from "../services/host-floating-placement.js";
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
import { shouldShowRecovery, type HostPartRect } from "../services/host-chrome-visibility.js";
import { thirdPartyAllowed } from "../services/instance-authorization.js";
import {
RECOVERY_CONTROL_DEFAULTS,
bindHostControlTheme,
findSkinRoot,
} from "../services/host-control-tokens.js";
import {
resolveHostRecoveryPresentation,
} from "../services/host-recovery-presentation.js";
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
@@ -164,8 +287,70 @@ const RECOVERY_LAYER_CSS = `
min-height: var(--ws-control-hit, 28px);
}
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
/* Toolbar mode: no capsule shell, margin, border or fixed shadow. The wrapper
only lays the host buttons out; every visible surface comes from the
--ws-toolbar-* variables resolved from the skin's validated tokens. */
.ws-host-toolbar {
position: fixed;
inset: auto;
margin: 0;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
gap: var(--ws-toolbar-gap, 4px);
max-width: calc(100vw - 8px);
pointer-events: auto;
}
.ws-host-toolbar:popover-open { display: flex; }
.ws-host-toolbar-action {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
box-sizing: border-box;
min-height: var(--ws-toolbar-min-height, var(--ws-control-hit, 28px));
max-width: min(320px, calc(100vw - 8px));
padding: var(--ws-toolbar-padding-y, 6px) var(--ws-toolbar-padding-x, 12px);
border: 1px solid var(--ws-toolbar-border, #9db6b2);
border-radius: var(--ws-toolbar-radius, 6px);
background: var(--ws-toolbar-background, #fff);
color: var(--ws-toolbar-foreground, #31524f);
box-shadow: var(--ws-toolbar-shadow, none);
font-family: var(--ws-toolbar-font, ui-sans-serif, system-ui, sans-serif);
font-size: var(--ws-toolbar-font-size, 11px);
line-height: 1.25;
text-align: center;
white-space: normal;
overflow-wrap: anywhere;
cursor: pointer;
touch-action: manipulation;
}
.ws-host-toolbar-action:hover {
border-color: var(--ws-toolbar-hover-border, var(--ws-toolbar-border, #9db6b2));
background: var(--ws-toolbar-hover-background, var(--ws-toolbar-background, #fff));
}
.ws-host-toolbar-action:focus-visible {
outline: 2px solid var(--ws-toolbar-focus, var(--ws-control-accent, #4c8f88));
outline-offset: 2px;
}
.ws-host-toolbar-icon {
display: block;
flex: 0 0 auto;
width: var(--ws-toolbar-icon-size, 16px);
height: var(--ws-toolbar-icon-size, 16px);
}
.ws-host-toolbar-icon svg { display: block; width: 100%; height: 100%; }
.ws-host-toolbar-action-icon {
width: max(24px, calc(var(--ws-toolbar-icon-size, 16px) + 8px));
padding: 0;
}
@media (prefers-reduced-motion: reduce) {
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
.ws-host-recovery, .ws-host-recovery button, .ws-host-toolbar-action { transition: none !important; }
}
`;
@@ -190,14 +375,32 @@ const showRecovery = computed(() => shouldShowRecovery({
// already reset). It never renders decoration on its own.
const shortcutOpen = ref(false);
const recoveryPopover = ref<HTMLElement | null>(null);
const groupToolbarElement = ref<HTMLElement | null>(null);
const builtInToolbarElement = ref<HTMLElement | null>(null);
const libraryToolbarElement = ref<HTMLElement | null>(null);
let slotBinding: HostSlotBinding | undefined;
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
/**
* Theme the capsule even when the skin does not declare a slot. While a slot
* binding exists it reads the anchor first and owns the tokens; this
* root-level pass covers the slot-less capsule and refreshes itself when the
* skin stylesheet arrives after the stored skin id.
* Optional anchor from the active skin's chrome.json. Only third-party skins
* can declare it; the host still owns the controls and the module falls back
* to the default corner whenever an anchor stops being usable.
*/
const slotConfig = computed(() => activeHostSlot("host.recovery"));
const builtInSlotConfig = computed(() => activeHostSlot("host.recovery.built-in"));
const librarySlotConfig = computed(() => activeHostSlot("host.recovery.library"));
const groupToolbarConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? slotConfig.value : undefined);
const capsuleSlotConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? undefined : slotConfig.value);
const builtInToolbarConfig = computed<SkinChromeSlot | undefined>(() => builtInSlotConfig.value?.mode === "toolbar" ? builtInSlotConfig.value : undefined);
const libraryToolbarConfig = computed<SkinChromeSlot | undefined>(() => librarySlotConfig.value?.mode === "toolbar" ? librarySlotConfig.value : undefined);
/**
* Theme the capsule even when the skin does not declare a slot. While a
* capsule slot binding exists it reads the anchor first and owns the tokens;
* this root-level pass covers the slot-less capsule and refreshes itself when
* the skin stylesheet arrives after the stored skin id. Toolbar bindings keep
* their own `--ws-toolbar-*` variables and do not disable this pass, so the
* floating fallback keeps the capsule palette.
*/
const recoveryTheme = layer ? bindHostControlTheme({
layer,
@@ -205,19 +408,43 @@ const recoveryTheme = layer ? bindHostControlTheme({
part: "host.recovery",
defaults: RECOVERY_CONTROL_DEFAULTS,
source: () => findSkinRoot(hostChromeActiveSkinId.value),
// While a slot binding exists it owns the capsule tokens (anchor first).
active: () => !slotBinding,
active: () => !capsuleBinding,
}) : null;
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
/**
* Optional anchor from the active skin's chrome.json. Only third-party skins
* can declare it; the host still owns the capsule and the module falls back to
* the default corner whenever the anchor stops being usable.
*/
const slotConfig = computed(() => activeHostSlot("host.recovery"));
const slotMode = ref<"floating" | "slotted">("floating");
const groupToolbarMode = ref<"floating" | "slotted">("floating");
const builtInToolbarMode = ref<"floating" | "slotted">("floating");
const libraryToolbarMode = ref<"floating" | "slotted">("floating");
const builtInActionState = computed(() => ({
available: Boolean(groupToolbarConfig.value || builtInToolbarConfig.value),
docked: groupToolbarConfig.value
? groupToolbarMode.value === "slotted"
: builtInToolbarMode.value === "slotted",
}));
const libraryActionState = computed(() => ({
available: Boolean(props.pluginLibraryAvailable) && Boolean(groupToolbarConfig.value || libraryToolbarConfig.value),
docked: groupToolbarConfig.value
? groupToolbarMode.value === "slotted"
: libraryToolbarMode.value === "slotted",
}));
const presentation = computed(() => resolveHostRecoveryPresentation({
visible: recoveryVisible.value,
shortcutOpen: shortcutOpen.value,
libraryAvailable: Boolean(props.pluginLibraryAvailable),
builtIn: builtInActionState.value,
library: libraryActionState.value,
}));
const capsuleActions = computed(() => presentation.value.capsuleActions);
// Exactly one application-library entry per page: the host toolbar button is
// the library entry while a toolbar slot exists, so PluginPanel hides its
// ordinary launcher (including while the capsule fallback shows the button).
watchEffect(() => {
setInlineLibraryEntryVisible(presentation.value.suppressLauncher);
});
const compactHold = ref(true);
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
@@ -255,11 +482,15 @@ let floatingElement: HTMLElement | null = null;
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
const compact = computed(() => !shortcutExpanded.value
&& !compactPinned.value
&& (slotMode.value === "slotted"
? Boolean(slotConfig.value?.compact) && !compactHold.value
: floatCompact.value));
const compact = computed(() => {
if (shortcutExpanded.value || compactPinned.value) return false;
const config = capsuleSlotConfig.value;
if (config) return Boolean(config.compact) && !compactHold.value;
// A toolbar-mode capsule is the fallback entry, not the target look: never
// fold it, otherwise a failed anchor could leave only a small mark.
if (groupToolbarConfig.value || builtInToolbarConfig.value || libraryToolbarConfig.value) return false;
return floatCompact.value;
});
function onRecoveryEscape() {
shortcutOpen.value = false;
@@ -267,40 +498,145 @@ function onRecoveryEscape() {
compactPinned.value = false;
}
/** Unpin when the pointer goes down anywhere outside the host layer. */
/** Dismiss shortcut expansion and unpin on pointer down outside the host layer. */
function onDocumentPointerDown(event: PointerEvent) {
if (!compactPinned.value || !layer) return;
if (!layer) return;
// Events from inside the closed shadow root are retargeted to its host.
if (event.composedPath().includes(layer.host)) return;
shortcutOpen.value = false;
shortcutExpanded.value = false;
compactPinned.value = false;
}
function onRecoveryFocusOut(event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
shortcutOpen.value = false;
shortcutExpanded.value = false;
compactPinned.value = false;
}
function syncSlotBinding() {
slotBinding?.dispose();
slotBinding = undefined;
// Disposing a slot clears its inline tokens; restore the root-level theme
// before deciding whether a new anchor should override it.
recoveryTheme?.apply();
// A fresh binding starts floating and reports its first successful dock.
slotMode.value = "floating";
const control = recoveryPopover.value;
const config = slotConfig.value;
if (!control || !config || !layer) return;
slotBinding = bindHostSlot({
let capsuleBinding: HostSlotBinding | undefined;
let toolbarBindings: HostSlotBinding[] = [];
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, presentation.value.capsuleVisible);
}
function syncToolbarPopovers() {
const visible = presentation.value.toolbar.visible;
syncRecoveryPopover(
groupToolbarElement.value,
Boolean(groupToolbarConfig.value) && visible && groupToolbarMode.value === "slotted",
);
syncRecoveryPopover(
builtInToolbarElement.value,
Boolean(builtInToolbarConfig.value) && visible && builtInToolbarMode.value === "slotted",
);
syncRecoveryPopover(
libraryToolbarElement.value,
Boolean(libraryToolbarConfig.value) && Boolean(props.pluginLibraryAvailable)
&& visible && libraryToolbarMode.value === "slotted",
);
}
/** A toolbar that is currently displayed (top layer or display fallback). */
function isToolbarShown(control: HTMLElement | null): boolean {
if (!control) return false;
if (control.matches?.(":popover-open")) return true;
const rect = control.getBoundingClientRect();
return getComputedStyle(control).display !== "none" && rect.width > 0 && rect.height > 0;
}
function rectOf(control: HTMLElement): HostPartRect {
const rect = control.getBoundingClientRect();
return {
left: rect.left, top: rect.top, width: rect.width, height: rect.height,
right: rect.right, bottom: rect.bottom,
};
}
/** Every recovery toolbar currently docked in the top layer. */
function dockedToolbarRects(): HostPartRect[] {
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
.filter((element): element is HTMLElement => Boolean(element) && isToolbarShown(element))
.map(rectOf);
}
/** Other docked recovery toolbars this entry must not cover on a narrow screen. */
function otherToolbarRects(control: HTMLElement): HostPartRect[] {
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
.filter((element): element is HTMLElement => Boolean(element)
&& element !== control && isToolbarShown(element))
.map(rectOf);
}
function bindToolbarEntry(
control: HTMLElement | null,
config: SkinChromeSlot | undefined,
mode: Ref<"floating" | "slotted">,
) {
if (!layer || !control || !config) return;
toolbarBindings.push(bindHostSlot({
layer,
control,
anchor: config.anchor,
skinId: hostChromeActiveSkinId.value,
align: config.align,
onModeChange: change => { slotMode.value = change.mode; },
});
presentation: "toolbar",
otherControls: () => otherToolbarRects(control),
// A floating toolbar is a closed popover (display:none). Show it for the
// synchronous measurement/hit test and hide it again unless it docked.
prepare: () => syncRecoveryPopover(control, true),
settle: slotted => {
if (!slotted || !presentation.value.toolbar.visible) syncRecoveryPopover(control, false);
},
onModeChange: change => {
mode.value = change.mode;
syncPopover();
syncToolbarPopovers();
},
}));
}
function syncSlotBindings() {
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
// Disposing a slot clears its inline tokens; restore the root-level theme
// before deciding whether a new anchor should override it.
recoveryTheme?.apply();
// A fresh binding starts floating and reports its first successful dock.
slotMode.value = "floating";
groupToolbarMode.value = "floating";
builtInToolbarMode.value = "floating";
libraryToolbarMode.value = "floating";
const capsuleConfig = capsuleSlotConfig.value;
if (recoveryPopover.value && capsuleConfig && layer) {
capsuleBinding = bindHostSlot({
layer,
control: recoveryPopover.value,
anchor: capsuleConfig.anchor,
skinId: hostChromeActiveSkinId.value,
align: capsuleConfig.align,
// A slotted capsule must not cover a still-docked split toolbar either.
otherControls: () => dockedToolbarRects(),
onModeChange: change => { slotMode.value = change.mode; },
});
}
bindToolbarEntry(groupToolbarElement.value, groupToolbarConfig.value, groupToolbarMode);
bindToolbarEntry(builtInToolbarElement.value, builtInToolbarConfig.value, builtInToolbarMode);
if (props.pluginLibraryAvailable) {
bindToolbarEntry(libraryToolbarElement.value, libraryToolbarConfig.value, libraryToolbarMode);
}
syncPopover();
syncToolbarPopovers();
}
function revalidateBindings() {
capsuleBinding?.revalidate();
for (const binding of toolbarBindings) binding.revalidate();
}
function bindFloating() {
@@ -331,6 +667,11 @@ function bindFloating() {
return { width: hit + 10, height: hit + 10 };
},
onCompactChange: next => { floatCompact.value = next; },
// Docked toolbars are inside the closed shadow root, so the light-DOM
// obstacle scan cannot see them. In split mode the library toolbar falls
// back to this capsule while the built-in toolbar stays docked; without
// this exclusion the capsule could cover it (320px GUI failure).
avoidRects: () => dockedToolbarRects(),
// Never move the capsule under the user's pointer or focus, and leave a
// docked capsule to the slot binding.
paused: () => slotMode.value === "slotted"
@@ -341,10 +682,6 @@ function bindFloating() {
});
}
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
}
function useBuiltInSkin() {
shortcutOpen.value = false;
requestBuiltInSkin();
@@ -364,8 +701,11 @@ function onKeydown(event: KeyboardEvent) {
shortcutOpen.value = true;
shortcutExpanded.value = true;
void nextTick(() => {
// The shortcut always brings back the complete capsule, even while a
// toolbar anchor is healthy.
syncPopover();
slotBinding?.revalidate();
syncToolbarPopovers();
revalidateBindings();
recoveryPopover.value?.querySelector("button")?.focus();
});
}
@@ -376,30 +716,66 @@ function refreshLauncherReachability() {
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
}
watch([recoveryVisible, recoveryPopover], () => {
void nextTick(() => {
syncPopover();
slotBinding?.revalidate();
bindFloating();
floatingAvoidance?.revalidate();
});
}, { flush: "post" });
watch(
[recoveryVisible, recoveryPopover, groupToolbarElement, builtInToolbarElement, libraryToolbarElement],
() => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
bindFloating();
floatingAvoidance?.revalidate();
});
},
{ flush: "post" },
);
watch([recoveryPopover, hostChromeActiveSkinId], () => {
void nextTick(() => recoveryTheme?.apply());
}, { flush: "post", immediate: true });
watch([slotConfig, hostChromeActiveSkinId], () => {
void nextTick(() => {
syncPopover();
syncSlotBinding();
});
}, { flush: "post" });
watch(
[
slotConfig,
builtInSlotConfig,
librarySlotConfig,
hostChromeActiveSkinId,
groupToolbarElement,
builtInToolbarElement,
libraryToolbarElement,
() => props.pluginLibraryAvailable,
],
() => {
void nextTick(() => {
syncSlotBindings();
bindFloating();
});
},
{ flush: "post" },
);
// Home <-> voice page and skin switches replace the controls the floating
// capsule was avoiding; re-place it promptly (and back to its default corner
// when that is free) instead of leaving it where the previous screen needed it.
watch([() => props.connected, hostChromeActiveSkinId], () => {
void nextTick(() => floatingAvoidance?.screenChanged());
void nextTick(() => {
revalidateBindings();
floatingAvoidance?.screenChanged();
});
}, { flush: "post" });
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
// Opening or closing the shortcut changes which presentation is active; docked
// toolbar buttons must hide while the complete capsule is summoned, and come
// back (if their anchor is still valid) when it closes.
watch(shortcutOpen, () => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
});
}, { flush: "post" });
// A page switch can mount a new `.ws-skin-root` with a different
// `data-ws-page` without changing the skin id. Re-resolve the declared anchor
// candidates promptly instead of waiting for the periodic safety check.
let pageObserver: MutationObserver | undefined;
onMounted(() => {
refreshLauncherReachability();
@@ -407,16 +783,37 @@ onMounted(() => {
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown, true);
window.addEventListener("pointerdown", onDocumentPointerDown, true);
if (typeof MutationObserver === "function") {
pageObserver = new MutationObserver(() => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
floatingAvoidance?.screenChanged();
});
});
pageObserver.observe(document.documentElement, {
subtree: true,
attributes: true,
attributeFilter: ["data-ws-page", "data-ws-skin"],
});
}
void nextTick(() => {
syncPopover();
syncSlotBinding();
syncSlotBindings();
bindFloating();
});
});
onBeforeUnmount(() => {
if (reachabilityTimer) clearInterval(reachabilityTimer);
if (compactHoldTimer) clearTimeout(compactHoldTimer);
slotBinding?.dispose();
pageObserver?.disconnect();
pageObserver = undefined;
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
setInlineLibraryEntryVisible(false);
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
floatingElement = null;
+5 -2
View File
@@ -1,7 +1,7 @@
<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-float="toolbarTarget ? undefined : fallbackPosition" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
<button v-if="!isHostPartHidden('host.plugins.launcher') && !inlineLibraryEntry" 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>
@@ -68,7 +68,7 @@ import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
import type { SiteLanguage } from '../../../src/site-copy.js';
import { thirdPartyAllowed } from '../services/instance-authorization.js';
import { isHostPartHidden, isHostPartVisuallyReachable, pluginLibraryRequests } from '../services/host-chrome.js';
import { isHostPartHidden, isHostPartVisuallyReachable, isInlineLibraryEntryVisible, pluginLibraryRequests } from '../services/host-chrome.js';
import type { SkinPluginWidgetOptions } from '../../../src/shared/skin-plugin.js';
import { bindFloatingAvoidance, type FloatingAvoidance, type FloatingPosition } from '../services/host-floating-placement.js';
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null; presentation: NonNullable<SkinPluginWidgetOptions['pluginPresentation']> }>();
@@ -77,6 +77,9 @@ 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);
// A toolbar-mode recovery slot already renders the host-owned application
// library button; do not render a second launcher on the same page.
const inlineLibraryEntry = computed(() => isInlineLibraryEntryVisible());
// The fallback toolbar floats in a viewport corner the skin knows nothing
// about; move it off any skin control it would cover (runtime only).
const fallbackPosition = ref<FloatingPosition>('bottom-right');
@@ -299,6 +299,53 @@
><small class="field-help">{{ tr("relayManagedHint") }}</small></section
>
</div></article>
<article v-show="activeSection === 'voice'" class="settings-card admin-setting-card admin-settings-section" data-admin-section="voice">
<header class="admin-card-heading"><h3>{{ tr('voiceSettings') }}</h3><p>{{ tr('voiceSettingsLead') }}</p></header>
<div class="advanced-settings-grid">
<section class="settings-subsection voice-profile-card">
<header class="settings-subsection-heading"><div><h4>{{ tr('voiceProfile') }}</h4><p class="card-help">{{ tr('voiceProfileLead') }}</p></div></header>
<div class="voice-profile-options">
<label class="choice" :class="{ selected: serverForm.voiceProfile === 'auto' }">
<input v-model="serverForm.voiceProfile" type="radio" value="auto" />
<span><strong>{{ tr('voiceProfileAuto') }}</strong><small>{{ tr('voiceProfileAutoLead') }}</small></span>
</label>
<label class="choice" :class="{ selected: serverForm.voiceProfile === 'legacy' }">
<input v-model="serverForm.voiceProfile" type="radio" value="legacy" />
<span><strong>{{ tr('voiceProfileLegacy') }}</strong><small>{{ tr('voiceProfileLegacyLead') }}</small></span>
</label>
<label class="choice" :class="{ selected: serverForm.voiceProfile === 'adaptive' }">
<input v-model="serverForm.voiceProfile" type="radio" value="adaptive" />
<span><strong>{{ tr('voiceProfileAdaptive') }}</strong><small>{{ tr('voiceProfileAdaptiveLead') }}</small></span>
</label>
</div>
<label class="choice toggle-choice" :class="{ selected: serverForm.voiceOpusWs }">
<input v-model="serverForm.voiceOpusWs" type="checkbox" :disabled="serverForm.voiceProfile === 'legacy'" />
<span><strong>{{ tr('voiceOpusWs') }}</strong><small>{{ tr('voiceOpusWsLead') }}</small></span>
</label>
<div class="voice-fields">
<label><span>{{ tr('voiceJitterMaxMs') }}</span><input v-model.number="serverForm.voiceJitterMaxMs" type="number" inputmode="numeric" min="80" max="500" :disabled="serverForm.voiceProfile === 'legacy'" /><small class="field-help">{{ tr('voiceJitterLead') }}</small></label>
</div>
<small class="field-help">{{ tr('voiceApplyHint') }}</small>
</section>
<section class="settings-subsection turn-card">
<header class="settings-subsection-heading"><div><h4>{{ tr('turnSettings') }}</h4><p class="card-help">{{ tr('turnLead') }}</p></div></header>
<label class="webrtc-network-field">
<span>{{ tr('turnUrls') }}</span>
<textarea v-model="serverForm.voiceTurnUrls" rows="3" maxlength="4096" spellcheck="false" autocomplete="off" placeholder="turn:turn.example.com:3478&#10;turns:turn.example.com:5349"></textarea>
<small class="field-help">{{ tr('turnUrlsLead') }}</small>
</label>
<div class="password-row">
<label><span>{{ tr('turnSecret') }}</span><input v-model="serverForm.voiceTurnSecret" type="password" autocomplete="off" :disabled="serverForm.voiceTurnSecretAction !== 'replace'" :placeholder="serverForm.hasVoiceTurnSecret ? tr('turnSecretConfigured') : tr('turnSecretPlaceholder')" /></label>
<div class="password-actions"><button type="button" :class="{ active: serverForm.voiceTurnSecretAction === 'replace' }" @click="serverForm.voiceTurnSecretAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasVoiceTurnSecret" type="button" :class="{ danger: serverForm.voiceTurnSecretAction === 'remove' }" @click="serverForm.voiceTurnSecretAction = 'remove'">{{ tr('remove') }}</button></div>
</div>
<small class="field-help">{{ tr('turnSecretLead') }}</small>
<div class="voice-fields">
<label><span>{{ tr('turnTtl') }}</span><input v-model.number="serverForm.voiceTurnTtlSeconds" type="number" inputmode="numeric" min="300" max="86400" /><small class="field-help">{{ tr('turnTtlLead') }}</small></label>
</div>
<small class="field-help">{{ tr('turnApplyHint') }}</small>
</section>
</div>
</article>
<p class="admin-save-scope"><Icon name="info" :size="15"/>{{ tr('adminSaveScope') }}</p>
</section>
</template>
@@ -323,14 +370,15 @@ const emit = defineEmits<{ webrtcToggle: [] }>();
// The page owns one stable feature controller across route changes.
const { serverForm, serverSaving, testing, testResult, saveServerSettings, testServerConnection, addRelayNode, removeRelayNode } = props.model;
const { tr, formatDate, connectionFailureText } = props.i18n;
type SettingsSection = 'access' | 'site' | 'network';
const normalizeSection = (value?: string): SettingsSection => value === 'site' || value === 'network' ? value : 'access';
type SettingsSection = 'access' | 'site' | 'network' | 'voice';
const normalizeSection = (value?: string): SettingsSection => value === 'site' || value === 'network' || value === 'voice' ? value : 'access';
const activeSection = ref<SettingsSection>(normalizeSection(props.initialSection));
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
const sections = computed(() => [
{ id: 'access' as const, label: tr('adminAccessSection') },
{ id: 'site' as const, label: tr('adminSiteSection') },
{ id: 'network' as const, label: tr('adminNetworkSection') },
{ id: 'voice' as const, label: tr('adminVoiceSection') },
]);
function handleWebRtcToggle() { emit("webrtcToggle"); }
+3
View File
@@ -37,6 +37,9 @@ const errorLabels: Record<string, AdminTranslationKey> = {
INVALID_PASSWORD: "invalidPassword", INVALID_ADMIN_PASSWORD: "setupPasswordShort", PASSWORD_CHANGE_REQUIRED: "changePasswordLead", RATE_LIMITED: "rateLimited",
INVALID_WEBRTC_PUBLIC_HOST: "invalidWebRtcNetworkError", INVALID_WEBRTC_STUN_SERVER: "invalidWebRtcNetworkError", INVALID_WEBRTC_IPV6: "invalidWebRtcNetworkError",
INVALID_WEBRTC_PORT_RANGE: "invalidWebRtcPortRangeError", WEBRTC_PORT_LOCKED: "webRtcPortLockedError",
INVALID_VOICE_PROFILE: "invalidVoiceProfileError", INVALID_VOICE_TURN_URLS: "invalidVoiceTurnUrlsError",
INVALID_VOICE_TURN_SECRET: "invalidVoiceTurnSecretError", INVALID_VOICE_TURN_TTL: "invalidVoiceTurnTtlError",
INVALID_VOICE_OPUS: "invalidVoiceSettingsError", INVALID_VOICE_JITTER_MAX: "invalidVoiceJitterError",
INVALID_RELAY_NAME: "invalidRelayNameError", INVALID_RELAY_TARGET: "invalidRelayTargetError", INVALID_RELAY_VOICE_ENDPOINT: "invalidRelayVoiceEndpointError", INVALID_RELAY_TOKEN: "invalidRelayTokenError",
INVALID_TARGET: "invalidTargetError", PING_UNAVAILABLE: "icmpUnavailableError", HOST_NOT_FOUND: "probeHostNotFoundError",
UNREACHABLE: "probeUnreachableError", TIMEOUT: "probeTimeoutError", PROTOCOL_NEGOTIATION_FAILED: "probeProtocolError",
+22 -3
View File
@@ -1,6 +1,7 @@
import { onScopeDispose, reactive, ref, watch, type Ref } from "vue";
import { DEFAULT_WELCOME_TEXTS } from "../../../src/site-copy.js";
import type { AdminSettings } from "../../../src/shared/admin-responses.js";
import type { AdminSettingsInput } from "../../../src/shared/admin-inputs.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { createAdminRequests } from "../services/admin-requests.js";
import { combineTeamSpeakTarget, splitTeamSpeakTarget, suggestedTeamSpeakPort } from "../services/teamspeak-target.js";
@@ -14,10 +15,12 @@ function emptyForm() {
return { address: "", port: "9987", serverPassword: "", passwordAction: "keep" as SecretAction, hasPassword: false,
accessMode: "fixed" as "fixed" | "open", siteName: "WebSpeak", welcomeText: "", welcomeTextEn: "", welcomeTextDe: "", welcomeTextRu: "", welcomeTextJa: "",
welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS }, webRtcPublicHost: "", webRtcIpv6Enabled: false, webRtcStunServer: "", webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099,
voiceProfile: "auto" as "auto" | "legacy" | "adaptive", voiceTurnUrls: "", voiceTurnSecret: "", voiceTurnSecretAction: "keep" as SecretAction,
hasVoiceTurnSecret: false, voiceTurnTtlSeconds: 21600, voiceOpusWs: false, voiceJitterMaxMs: 300,
relayNodes: [] as RelayNodeForm[], lastTestAt: null as string | null, lastTestLatencyMs: null as number | null };
}
type ServerForm = ReturnType<typeof emptyForm>;
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd"] as const;
const editable = ["address", "port", "accessMode", "siteName", "welcomeText", "welcomeTextEn", "welcomeTextDe", "welcomeTextRu", "welcomeTextJa", "webRtcEnabled", "webRtcPublicHost", "webRtcIpv6Enabled", "webRtcStunServer", "webRtcUdpStart", "webRtcUdpEnd", "voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs"] as const;
const snapshot = (form: ServerForm): ServerForm => JSON.parse(JSON.stringify(form));
export function useAdminServerSettings(options: Options) {
@@ -73,6 +76,11 @@ export function useAdminServerSettings(options: Options) {
serverForm.passwordAction = "keep";
}
serverForm.hasPassword = next.hasPassword;
if (serverForm.voiceTurnSecret === baseline.voiceTurnSecret && serverForm.voiceTurnSecretAction === baseline.voiceTurnSecretAction) {
serverForm.voiceTurnSecret = "";
serverForm.voiceTurnSecretAction = "keep";
}
serverForm.hasVoiceTurnSecret = next.hasVoiceTurnSecret;
serverForm.welcomeDefaults = next.welcomeDefaults;
if (applyProbeMetadata && serverForm.address === next.address && serverForm.port === next.port) {
serverForm.lastTestAt = next.lastTestAt;
@@ -99,13 +107,24 @@ export function useAdminServerSettings(options: Options) {
} finally { applyingSettings = false; }
}
function serverPayload() {
return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined,
function serverPayload(): AdminSettingsInput {
const payload: AdminSettingsInput = { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined,
passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName,
welcomeText: serverForm.welcomeText, welcomeTextEn: serverForm.welcomeTextEn, welcomeTextDe: serverForm.welcomeTextDe, welcomeTextRu: serverForm.welcomeTextRu, welcomeTextJa: serverForm.welcomeTextJa,
webRtcPublicHost: serverForm.webRtcPublicHost, webRtcIpv6Enabled: serverForm.webRtcIpv6Enabled, webRtcStunServer: serverForm.webRtcStunServer,
webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd,
relayNodes: serverForm.relayNodes.map(node => ({ id: node.id, name: node.name, target: node.target, voiceEndpoint: node.voiceEndpoint, enabled: node.enabled, tokenAction: node.tokenAction, ...(node.tokenAction === "replace" ? { token: node.token } : {}) })) };
const saved = savedSettings.value;
if (saved) {
for (const key of ["voiceProfile", "voiceTurnUrls", "voiceTurnTtlSeconds", "voiceOpusWs", "voiceJitterMaxMs"] as const) {
if (serverForm[key] !== saved[key]) Object.assign(payload, { [key]: serverForm[key] });
}
}
if (serverForm.voiceTurnSecretAction !== "keep") {
payload.voiceTurnSecretAction = serverForm.voiceTurnSecretAction;
if (serverForm.voiceTurnSecretAction === "replace") payload.voiceTurnSecret = serverForm.voiceTurnSecret;
}
return payload;
}
function report(error: unknown) {
if (!isAdminRequestCancelled(error)) options.errorMessage.value = options.errorText((error as { code?: string }).code);
+147 -22
View File
@@ -14,6 +14,8 @@ 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";
import type { VoiceIceServer, VoiceIceTransportPolicy } from "../../../src/shared/voice-ice.js";
import { createOpusUplink } from "../voice/opus-uplink.js";
import { requestMediaBeforeAudioResume } from "../services/microphone-start.js";
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
import { parseServerMessage } from "../../../src/shared/server-messages.js";
@@ -42,6 +44,7 @@ export interface VoiceState {
microphoneErrorCode: string;
audioNotice: string;
audioNoticeCode: string;
webrtcReconnecting: boolean;
channelSwitchedChannelId: string;
}
@@ -201,7 +204,7 @@ 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: "" });
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", webrtcReconnecting: false, channelSwitchedChannelId: "" });
const pluginSession = ref("");
const sessionState = createVoiceSessionState({
selfId: () => state.tsClientId,
@@ -332,23 +335,37 @@ export function useVoiceWebSocket() {
const SPEAKING_HOLD_MS = 360;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const MAX_AUDIO_BUFFERED_FRAMES = 10;
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
const LEGACY_AUDIO_BUFFERED_FRAMES = 10;
const ADAPTIVE_AUDIO_BUFFERED_FRAMES = 15;
let maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
let maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
const MAX_OPUS_BUFFERED_BYTES = 4_096;
let voiceProfile: "legacy" | "adaptive" = "legacy";
let audioJitterMaxMs = 80;
let audioFrameVersion = 1;
let audioUplinkCodecs: ("pcm" | "opus")[] = ["pcm"];
const remotePlayback = createRemotePlayback({
getContext: getAudioCtx,
getVolume: clientId => (volumes[clientId] ?? 1) * effectiveOutputVolume(),
onDecodeError: () => audioDiagnostics.count("decodeErrors"),
onDrop: () => audioDiagnostics.count("framesDropped"),
mode: () => voiceProfile,
maxBufferAheadMs: () => audioJitterMaxMs,
});
let webRtcStunServer = "";
let webRtcAvailable = false;
let webRtcFailed = false;
let voiceIceServers: VoiceIceServer[] = [];
let voiceIceTransportPolicy: VoiceIceTransportPolicy = "all";
const webrtc = createWebRtcTransport({
stunServer: () => webRtcStunServer,
iceServers: () => voiceIceServers,
iceTransportPolicy: () => voiceIceTransportPolicy,
prepareMicrophone: async () => {
await ensureMicrophone();
return micStream ? { context: getAudioCtx(), stream: micStream,
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
},
stopPcm: stopCaptureGraph,
muted: () => microphoneMuted.value,
inputVolume: () => inputVolume.value,
accompanimentActive: () => accompanimentActive.value,
@@ -359,16 +376,29 @@ export function useVoiceWebSocket() {
else if (state.tsClientId) clearSpeaking(state.tsClientId);
},
onReady() {
const switchingFromCompatibility = webRtcFailed;
webRtcFailed = false;
state.webrtcReconnecting = false;
stopCaptureGraph();
if (switchingFromCompatibility) remotePlayback.clearAll();
clearAudioNotice("WEBRTC_FAILED");
sessionTrace.record("webrtc.media", { state: "active" });
syncWebRtcMemberVolumes();
},
onConnectionState(stateName) { sessionTrace.record("webrtc.connection", { state: stateName }); },
async onFallback(reason, isCurrent) {
onIceCandidateError(errorCode, url) {
sessionTrace.record("webrtc.icecandidateerror", { errorCode, ...(url ? { url: url.slice(0, 300) } : {}) });
},
async onFailure(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); }
const switchingFromWebRtc = !webRtcFailed;
webRtcFailed = true;
state.webrtcReconnecting = false;
const code = safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE";
sessionTrace.record("webrtc.failed", { code });
if (switchingFromWebRtc) remotePlayback.clearAll();
resumeCompatibilityCapture();
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage(code));
},
playback: {
context: () => audioCtx,
@@ -387,25 +417,41 @@ export function useVoiceWebSocket() {
onPlaying: syncAudioContextNotice,
},
});
function webRtcCarriesAudio(): boolean {
return webrtc.active && !webRtcFailed;
}
const audioDiagnostics = createAudioDiagnostics({
source() {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN || !state.connected) return null;
const peer = webrtc.peer;
return { socket, connection: voiceConnection.generation, transportGeneration: webrtc.generation, peer,
transport: webrtc.active ? "webrtc" : peer ? "negotiating" : "websocket" };
transport: webRtcFailed ? "websocket" : webrtc.active ? "webrtc" : peer ? "negotiating" : "websocket" };
},
presentation({ peer }) {
return {
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
microphonePermission: audioPermission.value,
playbackState: peer
playbackState: peer && !webRtcFailed
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null,
};
},
send: (source, sequence) => source.socket.send(JSON.stringify({ type: "audioStatsProbe", payload: { sequence } })),
bufferStats: () => remotePlayback.getStats(),
});
let opusStreamOpen = false;
const opusUplink = createOpusUplink({
send(frame) {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > MAX_OPUS_BUFFERED_BYTES) return false;
try { socket.send(frame); return true; } catch { return false; }
},
onDrop: () => audioDiagnostics.count("framesDropped"),
onFallback: reason => sessionTrace.record("audio.opus.fallback", { reason: reason.slice(0, 120) }),
});
async function saveAudioPreferences(): Promise<void> {
@@ -535,7 +581,11 @@ export function useVoiceWebSocket() {
state.microphoneErrorCode = "";
}
/** Non-fatal audio notice (WebRTC fallback, blocked autoplay, device list failure...). */
/** Non-fatal audio notice (WebRTC failure, blocked autoplay, device list failure...). */
function webRtcFailureMessage(reason: string): string {
return `实时语音(WebRTC)不可用(错误代码:${reason})。已自动切换到兼容传输(PCM/Opus over WebSocket)保通话;你仍在当前语音会话中,可点击“重新连接 WebRTC”重试`;
}
function setAudioNotice(code: string, message: string): void {
state.audioNoticeCode = safeClientErrorCode(code) || "AUDIO_NOTICE";
state.audioNotice = message;
@@ -655,11 +705,15 @@ export function useVoiceWebSocket() {
const socket = ws.value;
const shouldSend = !microphoneMuted.value
&& !microphoneTestActive.value
&& !webrtc.active
&& !webRtcCarriesAudio()
&& socket?.readyState === WebSocket.OPEN
&& voxGate(input);
if (!shouldSend) {
accumLen = 0;
if (opusStreamOpen) {
opusUplink.resetStream();
opusStreamOpen = false;
}
if (microphoneMuted.value) {
voxAttack = 0;
voxRelease = 0;
@@ -668,10 +722,20 @@ export function useVoiceWebSocket() {
}
if (!socket) {
accumLen = 0;
if (opusStreamOpen) {
opusUplink.resetStream();
opusStreamOpen = false;
}
return;
}
if (opusUplink.active) {
if (!opusStreamOpen) opusStreamOpen = true;
accumLen = 0;
if (opusUplink.push(input)) markSpeaking(state.tsClientId);
return;
}
const bufferedBytes = socket.bufferedAmount;
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
if (bufferedBytes > maxAudioBufferedBytes) {
accumLen = 0;
return;
}
@@ -688,7 +752,7 @@ export function useVoiceWebSocket() {
accumLen = need;
let offset = 0;
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= maxAudioBufferedBytes) {
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
offset += AUDIO_FRAME_SAMPLES;
}
@@ -810,12 +874,19 @@ export function useVoiceWebSocket() {
function stopCaptureGraph(): void {
accumLen = 0;
opusStreamOpen = false;
opusUplink.resetStream();
voxAttack = 0;
voxRelease = 0;
micLevel.value = 0;
microphoneCapture?.stopCapture();
}
function resumeCompatibilityCapture(): void {
try { microphoneCapture?.activate(); }
catch (error) { setMicrophoneError(error); }
}
function stopMicrophone(closeContext = true): void {
if (closeContext) {
microphoneGeneration++;
@@ -854,7 +925,7 @@ export function useVoiceWebSocket() {
const sequence = voiceConnection.generation;
const socket = ws.value;
const isCurrent = () => generation === inputDeviceGeneration && sequence === voiceConnection.generation;
const shouldRestartWebRtc = webrtc.active && Boolean(ws.value);
const shouldRestartWebRtc = Boolean(webrtc.peer) && Boolean(ws.value);
try {
// Keep the current peer alive until the replacement microphone is ready.
if (micStream) await startMicrophone();
@@ -1068,6 +1139,19 @@ export function useVoiceWebSocket() {
screenShare.stopTransport(sendScreenStop);
webrtc.stop();
remotePlayback.clearAll();
webRtcAvailable = false;
webRtcFailed = false;
state.webrtcReconnecting = false;
voiceIceServers = [];
voiceIceTransportPolicy = "all";
voiceProfile = "legacy";
maxAudioBufferedFrames = LEGACY_AUDIO_BUFFERED_FRAMES;
maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
audioJitterMaxMs = 80;
audioFrameVersion = 1;
audioUplinkCodecs = ["pcm"];
opusUplink.disable();
opusStreamOpen = false;
stopMicrophone();
clearSpeakingState();
whisperTargetIds.clear();
@@ -1098,6 +1182,9 @@ export function useVoiceWebSocket() {
state.errorCode = "";
state.channelSwitchedChannelId = "";
state.tsClientId = Number(msg.tsClientId) || 0;
webRtcAvailable = msg.webrtcAvailable === true;
state.webrtcReconnecting = false;
clearAudioNotice("WEBRTC_FAILED");
pluginSession.value = msg.pluginSession ?? "";
// The mute preference is local to the browser, while TeamSpeak shows
// the gateway's own client_input_muted flag to other clients. Send it
@@ -1106,6 +1193,22 @@ export function useVoiceWebSocket() {
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
screenShare.setIceServers(msg.screenShareIceServers);
webRtcStunServer = msg.webRtcStunServer ?? "";
voiceIceServers = msg.voiceIceServers ?? [];
voiceIceTransportPolicy = msg.voiceIceTransportPolicy ?? "all";
voiceProfile = msg.voiceProfile ?? "legacy";
const adaptiveProfile = voiceProfile === "adaptive";
maxAudioBufferedFrames = adaptiveProfile ? ADAPTIVE_AUDIO_BUFFERED_FRAMES : LEGACY_AUDIO_BUFFERED_FRAMES;
maxAudioBufferedBytes = AUDIO_FRAME_BYTES * maxAudioBufferedFrames;
audioJitterMaxMs = adaptiveProfile ? (msg.audioJitterMaxMs ?? 300) : 80;
audioFrameVersion = msg.audioFrameVersion ?? 1;
audioUplinkCodecs = adaptiveProfile ? (msg.audioUplinkCodecs ?? ["pcm"]) : ["pcm"];
if (adaptiveProfile && audioUplinkCodecs.includes("opus")) {
void opusUplink.init().then(active => sessionTrace.record("audio.opus", { state: active ? "active" : "pcm-fallback" }));
} else {
opusUplink.disable();
opusStreamOpen = false;
}
if (msg.webrtcUnavailableReason) sessionTrace.record("webrtc.unavailable", { reason: msg.webrtcUnavailableReason });
sessionState.connected(msg);
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
@@ -1188,7 +1291,7 @@ export function useVoiceWebSocket() {
void webrtc.applyAnswer(msg.payload?.sdp);
break;
case "webrtcError":
if (ws.value) void webrtc.fallback(safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED");
if (ws.value) void webrtc.fail(safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED");
break;
case "audioError": {
// The gateway could not encode our microphone audio (for example its Opus
@@ -1228,10 +1331,9 @@ export function useVoiceWebSocket() {
}
function handleAudioFrame(data: Uint8Array): void {
// WebRTC carries the realtime downlink after negotiation. Ignore any
// in-flight fallback WebSocket packets so a transport switch cannot
// produce duplicate or delayed playback.
if (webrtc.active) return;
// Ignore in-flight fallback packets only while WebRTC actually carries
// audio; a failed or reconnecting attempt must keep the WebSocket downlink.
if (webRtcCarriesAudio()) return;
if (data.length < 4) {
audioDiagnostics.count("framesDropped");
return;
@@ -1356,12 +1458,34 @@ export function useVoiceWebSocket() {
connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword, lastConnection.rememberIdentity ? identityMaterial.value || lastConnection.identity : "", lastConnection.rememberIdentity, "", lastConnection.accelerated, lastConnection.accelerationRelayId);
}
async function reconnectWebRtc(): Promise<void> {
const socket = ws.value;
if (state.webrtcReconnecting || !state.connected || !socket || socket.readyState !== WebSocket.OPEN) return;
if (!webRtcAvailable || typeof RTCPeerConnection === "undefined") {
webRtcFailed = true;
resumeCompatibilityCapture();
setAudioNotice("WEBRTC_FAILED", webRtcFailureMessage("WEBRTC_UNAVAILABLE"));
return;
}
const sequence = voiceConnection.generation;
state.webrtcReconnecting = true;
clearMicrophoneError();
if (webRtcFailed) resumeCompatibilityCapture();
try {
await startWebRtcTransport(sequence, socket);
} catch (error) {
if (sequence !== voiceConnection.generation || ws.value !== socket || !state.connected) return;
state.webrtcReconnecting = false;
setMicrophoneError(error);
}
}
function setMicrophoneMuted(muted: boolean): void {
microphoneMuted.value = muted;
voxAttack = 0;
voxRelease = 0;
accumLen = 0;
if (webrtc.active) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
if (webrtc.peer) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
webrtc.input?.setVolume(muted ? 0 : inputVolume.value);
sendCmd("setMicrophoneMuted", { muted });
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
@@ -1538,6 +1662,7 @@ export function useVoiceWebSocket() {
playNotification,
connect,
reconnectNow,
reconnectWebRtc,
createInvite,
disconnect,
switchChannel,
+8 -5
View File
@@ -228,12 +228,15 @@ function localizedMessage(message: string) {
function localizedAudioNotice(code: string, message: string) {
if (language.value === "zh") return message;
const normalizedCode = visibleErrorCode(code || "AUDIO_NOTICE");
const webRtcReason = code === "WEBRTC_FAILED"
? message.match(/错误代码:([A-Z0-9_-]{1,64})/)?.[1] ?? normalizedCode
: normalizedCode;
const messages: Record<string, { en: string; de: string; ru: string; ja: string }> = {
WEBRTC_FALLBACK: {
en: `WebRTC realtime voice is unavailable (error code: ${normalizedCode}). Compatibility transport is active; latency and audio quality may be lower`,
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${normalizedCode}). Der Kompatibilitätstransport ist aktiv; Latenz und Audioqualität können schlechter sein`,
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${normalizedCode}). Используется совместимый транспорт; задержка и качество звука могут быть ниже`,
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${normalizedCode})。互換トランスポートを使用するため、遅延や音質が低下する場合があります`,
WEBRTC_FAILED: {
en: `WebRTC realtime voice is unavailable (error code: ${webRtcReason}). Compatibility audio (PCM/Opus over WebSocket) is active to keep this voice session working; use “Reconnect WebRTC” to try again`,
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${webRtcReason}). Der kompatible Audioweg (PCM/Opus über WebSocket) ist aktiv, damit diese Sprachsitzung bestehen bleibt; klicke auf „WebRTC neu verbinden“, um es erneut zu versuchen`,
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${webRtcReason}). Включён совместимый аудиоканал (PCM/Opus через WebSocket), чтобы сохранить текущую голосовую сессию; нажмите «Переподключить WebRTC», чтобы повторить попытку`,
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${webRtcReason})。現在のボイスセッションを維持するため、互換オーディオ(PCM/Opus over WebSocket)が有効です。「WebRTC を再接続」から再試行できます`,
},
PLAYBACK_BLOCKED: {
en: "The browser blocked automatic audio playback. Click the page or allow audio playback for this site",
+170 -5
View File
@@ -209,7 +209,7 @@ export const copy = {
webrtcPortEnd: "结束端口",
webrtcApplyHint: "端口范围仅可在 WebRTC 关闭时修改;开启后会锁定,保存后对新连接生效。",
webrtcPublicHost: "公网媒体地址",
webrtcPublicHostLead: "填写网关可被 UDP 访问的 IP 或域名,不含协议或端口。留空按网页入口推断;反向代理或 TCP 隧道部署应单独指定媒体地址。保存后重新连接生效。",
webrtcPublicHostLead: "填写网关可被 UDP 直达的 IP 或域名,不含协议或端口。有公网 IP 时优先填它,WebRTC 会先尝试直连;Cloudflare Tunnel 等纯 TCP 入口不要填 CF 代理域名,留空会禁用直连,需另行配置 TURN。保存后重新连接生效。",
webrtcIpv6: "启用 IPv6 候选",
webrtcIpv6Lead: "服务器需具备可达的 IPv6 和已放行的 UDP 端口;默认关闭。",
webrtcStunServer: "语音 STUN 服务",
@@ -217,6 +217,39 @@ export const copy = {
invalidWebRtcNetworkError: "WebRTC 网络配置无效:媒体地址不含协议和端口,STUN 使用 stun:host:port,IPv6 必须为开关值。",
webrtcPortNoticeTitle: "请先放行 WebRTC 端口",
webrtcPortNotice: "需要开启端口,范围是 {{range}}(UDP)。请先在主机防火墙、安全组和 Docker 端口映射中放行该范围。",
adminVoiceSection: "语音",
voiceSettings: "语音传输",
voiceSettingsLead: "按部署方式选择兼容或自适应音频,并为 Cloudflare Tunnel / 受限网络配置 TURN 后备。保存后对新连接生效。",
voiceProfile: "语音模式",
voiceProfileLead: "自动模式按入口选择:直连连接保持旧版兼容路径,Cloudflare 请求走自适应路径。",
voiceProfileAuto: "自动(推荐)",
voiceProfileAutoLead: "直连 → 兼容模式;Cloudflare Tunnel → 自适应。无需按入口手动切换。",
voiceProfileLegacy: "兼容模式",
voiceProfileLegacyLead: "恢复旧版 80ms 播放窗口、PCM over WebSocket 与固定发送节奏。适合需要与旧客户端行为完全一致的部署。",
voiceProfileAdaptive: "自适应",
voiceProfileAdaptiveLead: "启用自适应 jitter buffer、20ms pacer 和新帧协议。Cloudflare Tunnel 或明显抖动的网络优先使用。",
voiceOpusWs: "兼容模式使用 Opus",
voiceOpusWsLead: "仅在自适应模式生效;显式启用后浏览器可上传 Opus,减少带宽。默认关闭。",
voiceJitterMaxMs: "自适应 jitter 上限",
voiceJitterLead: "80–500 ms。只限制缓冲上限;调低不能恢复旧版超限 clear() 行为。",
voiceApplyHint: "语音模式与 TURN 配置保存后对新的语音连接生效,不需要重启网关。",
turnSettings: "TURN 后备",
turnLead: "直连 UDP 不通时,浏览器再使用 TURN 中继;不要把它当作默认路径。",
turnUrls: "TURN 服务地址",
turnUrlsLead: "每行一个 turn: 或 turns: URL,最多 8 个。Cloudflare Tunnel 的纯 TCP 入口没有直连媒体路径时必须配置 TURN。",
turnSecret: "TURN 共享密钥",
turnSecretLead: "与 coturn 的 static-auth-secret / use-auth-secret 保持一致,至少 16 个字符。密钥加密保存,不会回传到浏览器。移除密钥会同时清空 TURN 地址并停用 TURN。",
turnSecretConfigured: "已配置,点击“更改”替换",
turnSecretPlaceholder: "至少 16 个字符",
turnTtl: "凭证有效期(秒)",
turnTtlLead: "300–86400 秒。浏览器每次连接都会获取短期 TURN 凭证。",
turnApplyHint: "TURN 仅在直连失败时使用;保存后对新连接生效。留空 TURN 地址即可关闭控制台配置。",
invalidVoiceProfileError: "语音模式无效,请选择自动、兼容或自适应。",
invalidVoiceTurnUrlsError: "TURN 地址无效:每行一个 turn:/turns: URL,最多 8 个。",
invalidVoiceTurnSecretError: "TURN 共享密钥无效:至少 16 个字符,且配置 TURN 地址时必须填写。",
invalidVoiceTurnTtlError: "TURN 凭证有效期应为 300–86400 秒。",
invalidVoiceJitterError: "自适应 jitter 上限应为 80–500 毫秒。",
invalidVoiceSettingsError: "语音高级设置无效,请检查 Opus 开关和 jitter 上限。",
relaySettings: "中继服务器",
relaySettingsLead: "配置访客连接使用的中继节点;名称会显示在首页加速选项中。",
relayEnabled: "启用中继加速",
@@ -550,7 +583,7 @@ export const copy = {
webrtcPortEnd: "End port",
webrtcApplyHint: "The range can only be edited while WebRTC is off. It is locked while enabled and applies to new connections after saving.",
webrtcPublicHost: "Public media address",
webrtcPublicHostLead: "Gateway IP or hostname reachable over UDP, without a scheme or port. Empty uses the web entry address; reverse proxies and TCP tunnels may need a separate media address. Reconnect after saving.",
webrtcPublicHostLead: "Gateway IP or hostname reachable directly over UDP, without a scheme or port. Prefer the public IP so WebRTC tries direct UDP first. Behind Cloudflare Tunnel or another TCP-only entry, do not use the CF-proxied hostname; leaving it empty disables direct candidates and requires TURN. Reconnect after saving.",
webrtcIpv6: "Enable IPv6 candidates",
webrtcIpv6Lead: "Requires reachable server IPv6 and open UDP ports. Disabled by default.",
webrtcStunServer: "Voice STUN server",
@@ -558,6 +591,39 @@ export const copy = {
invalidWebRtcNetworkError: "Invalid WebRTC network settings: media host must have no scheme or port, STUN must be stun:host:port, and IPv6 must be a boolean.",
webrtcPortNoticeTitle: "Allow WebRTC ports first",
webrtcPortNotice: "Ports must be opened: {{range}} (UDP). Allow this range in the host firewall, security group, and Docker port mapping first.",
adminVoiceSection: "Voice",
voiceSettings: "Voice transport",
voiceSettingsLead: "Choose compatibility or adaptive audio for this deployment and configure TURN fallback for Cloudflare Tunnel or restricted networks. Applies to new connections after saving.",
voiceProfile: "Voice mode",
voiceProfileLead: "Automatic picks by entry path: direct connections keep the legacy compatibility path, while Cloudflare requests use the adaptive path.",
voiceProfileAuto: "Automatic (recommended)",
voiceProfileAutoLead: "Direct → compatibility mode; Cloudflare Tunnel → adaptive. No need to switch manually per entry.",
voiceProfileLegacy: "Compatibility mode",
voiceProfileLegacyLead: "Restores the legacy 80 ms playback window, PCM over WebSocket, and fixed send cadence. Use when behavior must match older clients exactly.",
voiceProfileAdaptive: "Adaptive",
voiceProfileAdaptiveLead: "Enables the adaptive jitter buffer, 20 ms pacer, and new frame protocol. Prefer it for Cloudflare Tunnel or networks with noticeable jitter.",
voiceOpusWs: "Use Opus in compatibility mode",
voiceOpusWsLead: "Only effective in adaptive mode. When explicitly enabled, browsers may upload Opus to reduce bandwidth. Off by default.",
voiceJitterMaxMs: "Adaptive jitter limit",
voiceJitterLead: "80–500 ms. This only caps buffering; lowering it does not restore the legacy clear() overrun behavior.",
voiceApplyHint: "Voice mode and TURN settings apply to new voice connections after saving; no gateway restart is required.",
turnSettings: "TURN fallback",
turnLead: "Browsers use TURN relay only when direct UDP fails; do not treat it as the default path.",
turnUrls: "TURN service URLs",
turnUrlsLead: "One turn: or turns: URL per line, up to eight. A TCP-only Cloudflare Tunnel entry with no direct media path requires TURN.",
turnSecret: "TURN shared secret",
turnSecretLead: "Must match coturn's static-auth-secret / use-auth-secret and contain at least 16 characters. The secret is stored encrypted and never returned to browsers. Removing the secret also clears the TURN URLs and disables TURN.",
turnSecretConfigured: "Configured; choose Change to replace",
turnSecretPlaceholder: "At least 16 characters",
turnTtl: "Credential lifetime (seconds)",
turnTtlLead: "300–86400 seconds. Browsers receive short-lived TURN credentials for each connection.",
turnApplyHint: "TURN is used only after direct connection fails; changes apply to new connections. Leave the TURN URL field empty to disable console TURN.",
invalidVoiceProfileError: "Invalid voice mode. Choose automatic, compatibility, or adaptive.",
invalidVoiceTurnUrlsError: "Invalid TURN URL list: one turn:/turns: URL per line, up to eight.",
invalidVoiceTurnSecretError: "Invalid TURN shared secret: at least 16 characters, and required when TURN URLs are configured.",
invalidVoiceTurnTtlError: "TURN credential lifetime must be between 300 and 86400 seconds.",
invalidVoiceJitterError: "Adaptive jitter limit must be between 80 and 500 ms.",
invalidVoiceSettingsError: "Invalid advanced voice settings. Check the Opus switch and jitter limit.",
relaySettings: "Relay server",
relaySettingsLead: "Configure the relay used by accelerated guest connections; its name is shown on the welcome page.",
relayEnabled: "Enable relay acceleration",
@@ -699,7 +765,7 @@ export const germanCopy = {
webrtcPortRangeLead: "Gib den gesamten Bereich in der Host-Firewall und der Sicherheitsgruppe frei.",
webrtcApplyHint: "Der Bereich kann nur bei deaktiviertem WebRTC geändert werden. Bei aktiviertem WebRTC ist er gesperrt; gespeicherte Änderungen gelten für neue Verbindungen.",
webrtcPublicHost: "Öffentliche Medienadresse",
webrtcPublicHostLead: "Über UDP erreichbare IP oder Hostname des Gateways ohne Protokoll oder Port. Leer: Webadresse verwenden. Reverse-Proxys und TCP-Tunnel benötigen eventuell eine separate Adresse. Nach dem Speichern neu verbinden.",
webrtcPublicHostLead: "Direkt per UDP erreichbare IP oder Hostname des Gateways, ohne Protokoll oder Port. Bevorzuge die öffentliche IP, damit WebRTC zuerst direktes UDP versucht. Hinter Cloudflare Tunnel oder einem reinen TCP-Eingang niemals den CF-Proxy-Hostnamen eintragen; leer deaktiviert direkte Kandidaten und erfordert TURN. Nach dem Speichern neu verbinden.",
webrtcIpv6: "IPv6-Kandidaten aktivieren",
webrtcIpv6Lead: "Erfordert erreichbares IPv6 und offene UDP-Ports am Server. Standardmäßig deaktiviert.",
webrtcStunServer: "STUN-Server für Sprache",
@@ -707,6 +773,39 @@ export const germanCopy = {
invalidWebRtcNetworkError: "Ungültige WebRTC-Netzwerkeinstellungen: Medienadresse ohne Protokoll oder Port, STUN als stun:host:port und IPv6 als Schalter.",
webrtcPortNoticeTitle: "Zuerst WebRTC-Ports freigeben",
webrtcPortNotice: "Erforderliche Ports: {{range}} (UDP). Gib diesen Bereich zuerst in der Host-Firewall, der Sicherheitsgruppe und der Docker-Portzuordnung frei.",
adminVoiceSection: "Sprache",
voiceSettings: "Sprachtransport",
voiceSettingsLead: "Wähle je nach Betriebsart den Kompatibilitäts- oder adaptiven Audiopfad und konfiguriere TURN als Ausweichweg für Cloudflare Tunnel oder eingeschränkte Netze. Änderungen gelten nach dem Speichern für neue Verbindungen.",
voiceProfile: "Sprachmodus",
voiceProfileLead: "Automatisch entscheidet nach Eingang: direkte Verbindungen behalten den bisherigen Kompatibilitätsweg, Cloudflare-Anfragen nutzen den adaptiven Weg.",
voiceProfileAuto: "Automatisch (empfohlen)",
voiceProfileAutoLead: "Direkt → Kompatibilitätsmodus; Cloudflare Tunnel → adaptiv. Kein manuelles Umschalten je Eingang nötig.",
voiceProfileLegacy: "Kompatibilitätsmodus",
voiceProfileLegacyLead: "Stellt das bisherige 80-ms-Wiedergabefenster, PCM over WebSocket und den festen Sendetakt wieder her. Für Deployments, die sich exakt wie ältere Clients verhalten müssen.",
voiceProfileAdaptive: "Adaptiv",
voiceProfileAdaptiveLead: "Aktiviert adaptiven Jitter-Puffer, 20-ms-Pacer und das neue Frame-Protokoll. Bevorzugt für Cloudflare Tunnel oder Netze mit merklichem Jitter.",
voiceOpusWs: "Opus im Kompatibilitätsmodus",
voiceOpusWsLead: "Nur im adaptiven Modus wirksam. Wenn ausdrücklich aktiviert, können Browser Opus hochladen, um Bandbreite zu sparen. Standardmäßig aus.",
voiceJitterMaxMs: "Adaptives Jitter-Limit",
voiceJitterLead: "80–500 ms. Begrenzt nur den Puffer; ein niedrigerer Wert stellt das alte clear()-Verhalten bei Überlauf nicht wieder her.",
voiceApplyHint: "Sprachmodus und TURN-Einstellungen gelten nach dem Speichern für neue Sprachverbindungen; ein Neustart des Gateways ist nicht erforderlich.",
turnSettings: "TURN-Ausweichweg",
turnLead: "Browser nutzen TURN nur, wenn direkter UDP-Verkehr fehlschlägt; nicht als Standardweg verwenden.",
turnUrls: "TURN-Dienst-URLs",
turnUrlsLead: "Eine turn:- oder turns:-URL pro Zeile, höchstens acht. Ein reiner TCP-Eingang über Cloudflare Tunnel ohne direkten Medienpfad benötigt TURN.",
turnSecret: "TURN-Shared-Secret",
turnSecretLead: "Muss mit static-auth-secret / use-auth-secret von coturn übereinstimmen und mindestens 16 Zeichen enthalten. Das Secret wird verschlüsselt gespeichert und nie an Browser zurückgegeben. Beim Entfernen werden auch die TURN-URLs gelöscht und TURN deaktiviert.",
turnSecretConfigured: "Konfiguriert; zum Ersetzen „Ändern“ wählen",
turnSecretPlaceholder: "Mindestens 16 Zeichen",
turnTtl: "Gültigkeit der Zugangsdaten (Sekunden)",
turnTtlLead: "300–86400 Sekunden. Browser erhalten bei jeder Verbindung kurzlebige TURN-Zugangsdaten.",
turnApplyHint: "TURN wird nur nach fehlgeschlagener Direktverbindung verwendet; Änderungen gelten für neue Verbindungen. Leeres TURN-URL-Feld deaktiviert TURN aus der Konsole.",
invalidVoiceProfileError: "Ungültiger Sprachmodus. Wähle Automatisch, Kompatibel oder Adaptiv.",
invalidVoiceTurnUrlsError: "Ungültige TURN-URL-Liste: eine turn:/turns:-URL pro Zeile, höchstens acht.",
invalidVoiceTurnSecretError: "Ungültiges TURN-Shared-Secret: mindestens 16 Zeichen und erforderlich, wenn TURN-URLs konfiguriert sind.",
invalidVoiceTurnTtlError: "Die Gültigkeit der TURN-Zugangsdaten muss zwischen 300 und 86400 Sekunden liegen.",
invalidVoiceJitterError: "Das adaptive Jitter-Limit muss zwischen 80 und 500 ms liegen.",
invalidVoiceSettingsError: "Ungültige erweiterte Spracheinstellungen. Prüfe Opus-Schalter und Jitter-Limit.",
fixedModeLead: "Gäste geben nur einen Namen ein; WebSpeak verwaltet Ziel und Passwort.",
openModeLead: "Gäste können öffentliche TeamSpeak-Adressen eingeben; private und reservierte Netze sind gesperrt.",
legacyImported: "Die bisherige config.json wurde importiert. WebSpeak wird jetzt hier verwaltet; Änderungen an der alten Datei wirken sich nicht mehr auf die laufende Konfiguration aus.",
@@ -1041,7 +1140,7 @@ export const russianCopy = {
webrtcPortRangeLead: "Разрешите весь диапазон в брандмауэре сервера и группе безопасности.",
webrtcApplyHint: "Диапазон можно изменить только при выключенном WebRTC. При включённом WebRTC он заблокирован; после сохранения изменения применяются к новым подключениям.",
webrtcPublicHost: "Публичный адрес медиаданных",
webrtcPublicHostLead: "IP или имя шлюза, доступное по UDP, без протокола и порта. Пусто: адрес веб-сайта. Для обратного прокси или TCP-туннеля может потребоваться отдельный адрес. После сохранения подключитесь заново.",
webrtcPublicHostLead: "IP или имя шлюза, доступное напрямую по UDP, без протокола и порта. Укажите публичный IP, чтобы WebRTC сначала пробовал прямое UDP. За Cloudflare Tunnel или другим TCP-входом не используйте прокси-домен CF; пустое поле отключает прямые кандидаты и требует TURN. После сохранения подключитесь заново.",
webrtcIpv6: "Включить кандидаты IPv6",
webrtcIpv6Lead: "Нужны доступный IPv6 сервера и открытые порты UDP. По умолчанию выключено.",
webrtcStunServer: "STUN-сервер голосовой связи",
@@ -1049,6 +1148,39 @@ export const russianCopy = {
invalidWebRtcNetworkError: "Неверные настройки WebRTC: адрес без протокола и порта, STUN в формате stun:host:port, IPv6 — логическое значение.",
webrtcPortNoticeTitle: "Сначала откройте порты WebRTC",
webrtcPortNotice: "Необходимо открыть порты {{range}} (UDP). Сначала разрешите этот диапазон в брандмауэре, группе безопасности и настройках проброса портов Docker.",
adminVoiceSection: "Голос",
voiceSettings: "Голосовой транспорт",
voiceSettingsLead: "Выберите режим совместимости или адаптивный звук для этого развертывания и настройте TURN как резерв для Cloudflare Tunnel или ограниченных сетей. Изменения применяются к новым подключениям после сохранения.",
voiceProfile: "Голосовой режим",
voiceProfileLead: "Автоматический режим выбирает по входу: прямые подключения сохраняют прежний путь совместимости, запросы Cloudflare используют адаптивный путь.",
voiceProfileAuto: "Автоматически (рекомендуется)",
voiceProfileAutoLead: "Прямое подключение → режим совместимости; Cloudflare Tunnel → адаптивный. Переключать вручную для каждого входа не нужно.",
voiceProfileLegacy: "Режим совместимости",
voiceProfileLegacyLead: "Возвращает прежнее 80-мс окно воспроизведения, PCM over WebSocket и фиксированный темп отправки. Подходит, если поведение должно точно совпадать со старыми клиентами.",
voiceProfileAdaptive: "Адаптивный",
voiceProfileAdaptiveLead: "Включает адаптивный jitter buffer, пейсер 20 мс и новый протокол кадров. Предпочтителен для Cloudflare Tunnel или сетей с заметным джиттером.",
voiceOpusWs: "Opus в режиме совместимости",
voiceOpusWsLead: "Действует только в адаптивном режиме. При явном включении браузеры могут отправлять Opus, снижая трафик. По умолчанию выключено.",
voiceJitterMaxMs: "Предел адаптивного jitter",
voiceJitterLead: "80–500 мс. Ограничивает только буфер; снижение не возвращает прежнее поведение clear() при переполнении.",
voiceApplyHint: "Режим и настройки TURN применяются к новым голосовым подключениям после сохранения; перезапуск шлюза не требуется.",
turnSettings: "Резервный TURN",
turnLead: "Браузер использует TURN только при неудачном прямом UDP-подключении; не делайте его основным путём.",
turnUrls: "URL TURN-сервиса",
turnUrlsLead: "Один URL turn: или turns: в строке, не более восьми. Чистый TCP-вход Cloudflare Tunnel без прямого медиапути требует TURN.",
turnSecret: "Общий секрет TURN",
turnSecretLead: "Должен совпадать с static-auth-secret / use-auth-secret в coturn и содержать не менее 16 символов. Секрет хранится в зашифрованном виде и не возвращается браузерам. Удаление секрета также очищает URL TURN и отключает TURN.",
turnSecretConfigured: "Настроен; нажмите «Изменить», чтобы заменить",
turnSecretPlaceholder: "Не менее 16 символов",
turnTtl: "Срок действия учётных данных (с)",
turnTtlLead: "300–86400 секунд. Браузер получает краткосрочные учётные данные TURN при каждом подключении.",
turnApplyHint: "TURN используется только после неудачного прямого подключения; изменения применяются к новым подключениям. Пустое поле URL отключает TURN из консоли.",
invalidVoiceProfileError: "Неверный голосовой режим. Выберите автоматический, совместимый или адаптивный.",
invalidVoiceTurnUrlsError: "Неверный список URL TURN: один turn:/turns: URL в строке, не более восьми.",
invalidVoiceTurnSecretError: "Неверный общий секрет TURN: не менее 16 символов и обязателен при настроенных URL TURN.",
invalidVoiceTurnTtlError: "Срок действия учётных данных TURN должен быть от 300 до 86400 секунд.",
invalidVoiceJitterError: "Предел адаптивного jitter должен быть от 80 до 500 мс.",
invalidVoiceSettingsError: "Неверные расширенные настройки звука. Проверьте переключатель Opus и предел jitter.",
fixedModeLead: "Гости вводят только имя; адрес сервера и пароль задаются в WebSpeak.",
openModeLead: "Гости могут вводить публичные адреса TeamSpeak; частные и зарезервированные сети заблокированы.",
legacyImported: "Прежний файл config.json импортирован. Теперь WebSpeak настраивается здесь; изменения старого файла больше не влияют на текущую конфигурацию.",
@@ -1383,7 +1515,7 @@ export const japaneseCopy = {
webrtcPortRangeLead: "ホストのファイアウォールとセキュリティグループで範囲全体を許可してください。",
webrtcApplyHint: "ポート範囲は WebRTC が無効なときのみ変更できます。有効中はロックされ、保存後の新しい接続に適用されます。",
webrtcPublicHost: "公開メディアアドレス",
webrtcPublicHostLead: "UDP で到達できるゲートウェイの IP またはホスト名。スキームやポートは不要です。空欄では Web のアドレスを使用します。リバースプロキシや TCP トンネルでは別のアドレスが必要な場合があります。保存後に再接続してください。",
webrtcPublicHostLead: "UDP で直接到達できるゲートウェイの IP またはホスト名。スキームやポートは不要です。公開 IP を優先すると WebRTC は直連 UDP を先に試します。Cloudflare Tunnel などの TCP のみの入口では CF 代理ホスト名を入れないでください。空欄では直連候補が無効になり TURN が必要です。保存後に再接続してください。",
webrtcIpv6: "IPv6 候補を有効化",
webrtcIpv6Lead: "サーバーの IPv6 到達性と UDP ポートの開放が必要です。初期設定は無効です。",
webrtcStunServer: "音声 STUN サーバー",
@@ -1391,6 +1523,39 @@ export const japaneseCopy = {
invalidWebRtcNetworkError: "WebRTC 設定が無効です。メディアアドレスにはスキームやポートを含めず、STUN は stun:host:port、IPv6 は真偽値にしてください。",
webrtcPortNoticeTitle: "先に WebRTC のポートを開放してください",
webrtcPortNotice: "開放が必要なポートは {{range}}(UDP)です。先にホストのファイアウォール、セキュリティグループ、Docker のポートマッピングで許可してください。",
adminVoiceSection: "音声",
voiceSettings: "音声伝送",
voiceSettingsLead: "デプロイに応じて互換モードまたは適応型音声を選び、Cloudflare Tunnel や制限されたネットワーク向けに TURN フォールバックを設定します。保存後の新規接続に適用されます。",
voiceProfile: "音声モード",
voiceProfileLead: "自動では入口に応じて選択します。直連は従来の互換パス、Cloudflare リクエストは適応パスを使用します。",
voiceProfileAuto: "自動(推奨)",
voiceProfileAutoLead: "直連 → 互換モード、Cloudflare Tunnel → 適応型。入口ごとに手動で切り替える必要はありません。",
voiceProfileLegacy: "互換モード",
voiceProfileLegacyLead: "従来の 80ms 再生ウィンドウ、PCM over WebSocket、固定送信ペースを復元します。旧クライアントと完全に同じ動作が必要な場合に使用します。",
voiceProfileAdaptive: "適応型",
voiceProfileAdaptiveLead: "適応型 jitter buffer、20ms ペーサー、新しいフレームプロトコルを有効にします。Cloudflare Tunnel やジッターの目立つネットワークに適しています。",
voiceOpusWs: "互換モードで Opus を使用",
voiceOpusWsLead: "適応モードでのみ有効です。明示的に有効にするとブラウザーが Opus を送信でき、帯域を節約できます。既定では無効です。",
voiceJitterMaxMs: "適応型 jitter 上限",
voiceJitterLead: "80〜500 ms。バッファ上限のみを制限します。下げても旧版の clear() オーバーラン動作は復元されません。",
voiceApplyHint: "音声モードと TURN 設定は保存後の新規音声接続に適用され、ゲートウェイの再起動は不要です。",
turnSettings: "TURN フォールバック",
turnLead: "直連 UDP が失敗した場合にのみ TURN 中継を使用します。既定の経路にしないでください。",
turnUrls: "TURN サービス URL",
turnUrlsLead: "1 行に 1 つの turn: または turns: URL、最大 8 個。直連メディアパスがない Cloudflare Tunnel の TCP のみの入口では TURN が必要です。",
turnSecret: "TURN 共有シークレット",
turnSecretLead: "coturn の static-auth-secret / use-auth-secret と一致し、16 文字以上必要です。シークレットは暗号化して保存され、ブラウザーには返されません。シークレットを削除すると TURN URL も消去され、TURN が無効になります。",
turnSecretConfigured: "設定済み。「変更」で置き換えます",
turnSecretPlaceholder: "16 文字以上",
turnTtl: "資格情報の有効期間(秒)",
turnTtlLead: "300〜86400 秒。ブラウザーは接続ごとに短期 TURN 資格情報を受け取ります。",
turnApplyHint: "TURN は直連失敗時のみ使用されます。保存後は新規接続に適用されます。TURN URL を空にするとコンソール設定の TURN が無効になります。",
invalidVoiceProfileError: "音声モードが無効です。自動、互換、適応型のいずれかを選択してください。",
invalidVoiceTurnUrlsError: "TURN URL が無効です。1 行に 1 つの turn:/turns: URL、最大 8 個にしてください。",
invalidVoiceTurnSecretError: "TURN 共有シークレットが無効です。16 文字以上必要で、TURN URL 設定時は必須です。",
invalidVoiceTurnTtlError: "TURN 資格情報の有効期間は 300〜86400 秒にしてください。",
invalidVoiceJitterError: "適応型 jitter 上限は 80〜500 ミリ秒にしてください。",
invalidVoiceSettingsError: "音声の詳細設定が無効です。Opus スイッチと jitter 上限を確認してください。",
fixedModeLead: "ゲストはニックネームのみを入力します。接続先とパスワードは WebSpeak が管理します。",
openModeLead: "ゲストは公開 TeamSpeak アドレスを入力できます。プライベートネットワークと予約済みネットワークへの接続は制限されます。",
legacyImported: "旧 config.json をインポートしました。WebSpeak はこの画面で管理され、旧ファイルの変更は現在の設定に反映されません。",
+10
View File
@@ -299,6 +299,8 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
reconnectingAttempt: "第 {{attempt}} 次重连",
reconnectFailed: "无法恢复连接",
reconnectNow: "立即重连",
reconnectWebRtc: "重新连接 WebRTC",
reconnectingWebRtc: "正在重新连接 WebRTC…",
back: "返回",
volumeToast: "成员音量可以在列表中单独调整",
copiedToast: "邀请链接已复制",
@@ -731,6 +733,8 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
reconnectingAttempt: "Reconnecting… Attempt {{attempt}}",
reconnectFailed: "Could not restore the connection",
reconnectNow: "Reconnect now",
reconnectWebRtc: "Reconnect WebRTC",
reconnectingWebRtc: "Reconnecting WebRTC…",
back: "Back",
volumeToast: "Adjust each member's volume from the list",
copiedToast: "Invite link copied",
@@ -1156,6 +1160,8 @@ webClientTranslations.de = {
reconnectingAttempt: "Verbindungsversuch {{attempt}}",
reconnectFailed: "Verbindung konnte nicht wiederhergestellt werden",
reconnectNow: "Jetzt neu verbinden",
reconnectWebRtc: "WebRTC neu verbinden",
reconnectingWebRtc: "WebRTC wird neu verbunden…",
back: "Zurück",
volumeToast: "Die Lautstärke jedes Mitglieds kann separat angepasst werden.",
copiedToast: "Einladungslink kopiert",
@@ -1448,6 +1454,8 @@ webClientTranslations.ru = {
favoriteConnectionFailed: "Не удалось подключиться к {{server}}",
quickConnectFailed: "Не удалось подключиться. Проверьте адрес сервера и имя.",
reconnectNow: "Подключиться снова",
reconnectWebRtc: "Переподключить WebRTC",
reconnectingWebRtc: "Переподключение WebRTC…",
removeFavorite: "Удалить из избранного",
cancel: "Отмена",
close: "Закрыть",
@@ -1681,6 +1689,8 @@ webClientTranslations.ja = {
voiceStatus: "音声状態",
voiceStatusHint: "実音声フレームを表示。WebRTC ではブラウザー統計、互換モードではフレーム数を計測。テスト音は送信しません",
reconnectNow: "今すぐ再接続",
reconnectWebRtc: "WebRTC を再接続",
reconnectingWebRtc: "WebRTC を再接続中…",
voiceHealthDisconnected: "音声セッション未接続",
voiceHealthSampling: "メディア情報を取得中",
voiceHealthConnecting: "音声経路を接続中",
@@ -85,6 +85,41 @@ test("the recovery entry is persistent for third-party skins only", () => {
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
});
test("toolbar and per-action recovery slots are exposed for third-party skins", () => {
const document = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery.built-in": {
mode: "toolbar",
anchor: ["skin.home.topbar.part-host-actions", "skin.voice.topbar.part-host-actions"],
},
"host.recovery.library": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-host-library",
},
},
}));
setSkinHostChromeParts(document);
setHostChromeActiveSkin("community.toolbar");
try {
assert.deepEqual(activeHostSlot("host.recovery.built-in")?.anchor, [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
]);
assert.equal(activeHostSlot("host.recovery.built-in")?.mode, "toolbar");
assert.equal(activeHostSlot("host.recovery.library")?.mode, "toolbar");
assert.equal(activeHostSlot("host.recovery"), undefined);
// Bundled skins never see the toolbar declaration; their launcher stays.
setHostChromeActiveSkin("builtin.light");
assert.equal(activeHostSlot("host.recovery.built-in"), undefined);
assert.equal(activeHostSlot("host.recovery.library"), undefined);
} finally {
setSkinHostChromeParts(undefined);
setHostChromeActiveSkin(undefined);
}
});
test("slot declarations are honoured for third-party skins only", () => {
const document = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
@@ -97,9 +132,12 @@ test("slot declarations are honoured for third-party skins only", () => {
anchor: "voice.audio-dock",
align: "end",
compact: false,
mode: "capsule",
appearance: "label",
});
// A part that is not slottable cannot be selected through chrome.json.
assert.equal(activeHostSlot("host.permission"), undefined);
assert.equal(activeHostSlot("host.recovery.library"), undefined);
// Bundled/official skins keep the default floating placement.
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
+23 -4
View File
@@ -104,6 +104,23 @@ export function openPluginLibrary(): void {
libraryRequests.value += 1;
}
/**
* True while a toolbar-mode recovery slot provides the application library.
* PluginPanel then hides its ordinary `host.plugins.launcher` so the same page
* has exactly one application-library entry. The state is host-only: a skin
* can request the slot through chrome.json, but cannot set this flag or click
* the host button.
*/
const inlineLibraryEntry = ref(false);
export function setInlineLibraryEntryVisible(visible: boolean): void {
inlineLibraryEntry.value = visible;
}
export function isInlineLibraryEntryVisible(): boolean {
return inlineLibraryEntry.value;
}
/**
* Recovery's guaranteed escape hatch: reset to the built-in Day/Night skin.
* `usePublicSkin` watches this counter, so it works even when the skinnable
@@ -116,16 +133,18 @@ export function requestBuiltInSkin(): void {
builtInSkinRequests.value += 1;
}
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key">;
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key" | "code">;
/**
* The documented recovery shortcut: Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS.
* The letter is matched case-insensitively, but every modifier is required so
* ordinary app shortcuts (Ctrl+R, Alt+R, Ctrl+Shift+R) keep their meaning.
* On macOS, Option/Shift turn the letter key into a derived character (US
* layout: ®), so `event.key` is not "r". Match the physical `code` as well;
* every modifier is still required so ordinary app shortcuts (Ctrl+R, Alt+R,
* Ctrl+Shift+R) keep their meaning.
*/
export function isRecoveryShortcut(event: RecoveryShortcutEvent): boolean {
return (event.ctrlKey || event.metaKey)
&& event.altKey
&& event.shiftKey
&& event.key.toLowerCase() === "r";
&& (event.key?.toLowerCase() === "r" || event.code === "KeyR");
}
@@ -9,19 +9,38 @@ import {
HOST_CONTROL_MIN_FOREGROUND_CONTRAST,
HOST_CONTROL_MIN_HIT_TARGET,
HOST_CONTROL_SIZE_METRICS,
HOST_TOOLBAR_APPLIED_VARIABLES,
PERMISSION_CONTROL_DEFAULTS,
RECOVERY_CONTROL_DEFAULTS,
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
TOOLBAR_DEFAULT_GAP,
TOOLBAR_DEFAULT_ICON_SIZE,
TOOLBAR_DEFAULT_PADDING_X,
TOOLBAR_DEFAULT_PADDING_Y,
TOOLBAR_DEFAULT_RADIUS,
TOOLBAR_MAX_FONT_SIZE,
TOOLBAR_MAX_GAP,
TOOLBAR_MAX_HEIGHT,
TOOLBAR_MAX_ICON_SIZE,
TOOLBAR_MAX_PADDING,
TOOLBAR_MIN_HEIGHT,
TOOLBAR_MIN_ICON_SIZE,
applyHostControlTokens,
applyHostControlToolbarTokens,
compositeRgb,
contrastRatio,
fontFamilyNames,
formatRgb,
hasHostControlTokens,
hasHostToolbarTokens,
hostControlTokenKey,
hostControlTokenProperty,
hostToolbarTokenProperty,
parseCssColor,
parseCssColorWithAlpha,
relativeLuminance,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlRawTokens,
} from "./host-control-tokens.js";
@@ -254,6 +273,13 @@ test("CSS colours parse to RGB and ignore alpha for contrast", () => {
}
});
test("alpha colours parse and composite over opaque toolbar surfaces", () => {
assert.deepEqual(parseCssColorWithAlpha("transparent"), { r: 0, g: 0, b: 0, a: 0 });
assert.deepEqual(parseCssColorWithAlpha("#10203080"), { r: 16, g: 32, b: 48, a: 128 / 255 });
assert.deepEqual(parseCssColorWithAlpha("rgb(255 0 0 / 50%)"), { r: 255, g: 0, b: 0, a: 0.5 });
assert.deepEqual(compositeRgb({ r: 0, g: 0, b: 0, a: 0.5 }, { r: 255, g: 255, b: 255 }), { r: 128, g: 128, b: 128 });
});
test("WCAG contrast follows the relative-luminance formula", () => {
assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
@@ -281,3 +307,260 @@ test("host controls ignore fonts registered by a skin @font-face", () => {
assert.equal(resolve('"ws-community-evil-blank", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
assert.equal(resolve("Tahoma, ws-community-evil-blank"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
});
const resolveToolbar = (tokens: TokenMap = {}, global: TokenMap = {}, sampledSurface?: { r: number; g: number; b: number }) =>
resolveHostControlToolbarTokens(
style({ ...tokens, ...global }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
undefined,
sampledSurface,
);
test("toolbar tokens are independent of the capsule shell and keep host floors", () => {
const defaults = resolveToolbar();
assert.equal(defaults.background, "rgb(255, 255, 255)");
assert.equal(defaults.foreground, "rgb(49, 82, 79)");
assert.equal(defaults.border, "rgb(49, 82, 79)");
assert.ok(contrastRatio(parseCssColor(defaults.border)!, parseCssColor(defaults.background)!) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
assert.equal(defaults.radius, TOOLBAR_DEFAULT_RADIUS, "a capsule radius must not leak into toolbar mode");
assert.equal(defaults.paddingX, TOOLBAR_DEFAULT_PADDING_X);
assert.equal(defaults.paddingY, TOOLBAR_DEFAULT_PADDING_Y);
assert.equal(defaults.minHeight, HOST_CONTROL_MIN_HIT_TARGET);
assert.equal(defaults.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
assert.equal(defaults.shadow, "none", "the capsule shadow must not be copied into toolbar mode");
const custom = resolveToolbar({
"--skin-recovery-toolbar-background": "#102030",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-border": "#47dcc4",
"--skin-recovery-toolbar-radius": "10px",
"--skin-recovery-toolbar-font": "Tahoma, sans-serif",
"--skin-recovery-toolbar-font-size": "15px",
"--skin-recovery-toolbar-padding": "8px 18px",
"--skin-recovery-toolbar-height": "40px",
"--skin-recovery-toolbar-shadow": "0 2px 6px #00000033",
});
assert.equal(custom.background, "rgb(16, 32, 48)");
assert.equal(custom.foreground, "rgb(255, 255, 255)");
assert.equal(custom.border, "rgb(71, 220, 196)");
assert.equal(custom.radius, 10);
assert.equal(custom.font, "Tahoma, sans-serif");
assert.equal(custom.fontSize, 15);
assert.equal(custom.paddingX, 18);
assert.equal(custom.paddingY, 8);
assert.equal(custom.minHeight, 40);
assert.equal(custom.shadow, "0 2px 6px #00000033");
// Global toolbar tokens lose to the per-part set, but still override defaults.
const global = resolveToolbar({}, { "--skin-host-toolbar-background": "#222222", "--skin-host-toolbar-foreground": "#ffffff" });
assert.equal(global.background, "rgb(34, 34, 34)");
assert.equal(global.foreground, "rgb(255, 255, 255)");
});
test("toolbar colours preserve transparency and check text against an opaque surface", () => {
const classic = resolveToolbar({
"--skin-recovery-toolbar-background": "transparent",
"--skin-recovery-toolbar-foreground": "#1a1a1a",
"--skin-recovery-toolbar-border": "transparent",
"--skin-recovery-toolbar-hover-background": "#eaf2fd",
"--skin-recovery-toolbar-hover-border": "#b8cfe8",
}, {}, { r: 255, g: 255, b: 255 });
assert.equal(classic.background, "transparent");
assert.equal(classic.border, "transparent");
assert.equal(classic.foreground, "rgb(26, 26, 26)");
assert.equal(classic.hoverBackground, "rgb(234, 242, 253)");
assert.equal(classic.hoverBorder, "rgb(184, 207, 232)");
const explicitDarkSurface = resolveToolbar({
"--skin-recovery-toolbar-background": "#00000000",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-surface": "#102030",
}, {}, { r: 255, g: 255, b: 255 });
assert.equal(explicitDarkSurface.background, "transparent");
assert.equal(explicitDarkSurface.foreground, "rgb(255, 255, 255)");
const sampledDarkSurface = resolveToolbar({
"--skin-recovery-toolbar-background": "transparent",
"--skin-recovery-toolbar-foreground": "#ffffff",
}, {}, { r: 16, g: 32, b: 48 });
assert.equal(sampledDarkSurface.background, "transparent");
assert.equal(sampledDarkSurface.foreground, "rgb(255, 255, 255)");
const globalSurface = resolveToolbar({
"--skin-recovery-toolbar-background": "transparent",
"--skin-recovery-toolbar-foreground": "#ffffff",
}, { "--skin-host-toolbar-surface": "#102030" }, { r: 255, g: 255, b: 255 });
assert.equal(globalSurface.foreground, "rgb(255, 255, 255)");
});
test("toolbar border and focus colours are rechecked against the final surface", () => {
const palette = {
"--skin-recovery-background": "#000000",
"--skin-recovery-foreground": "#ffffff",
"--skin-recovery-border": "#ffffff",
"--skin-recovery-accent": "#ffffff",
"--skin-recovery-toolbar-foreground": "#000000",
"--skin-recovery-toolbar-surface": "#ffffff",
};
for (const background of ["#ffffff", "transparent"]) {
for (const border of [undefined, "#ffffff"]) {
const toolbar = resolveToolbar({
...palette,
"--skin-recovery-toolbar-background": background,
...(border ? { "--skin-recovery-toolbar-border": border } : {}),
});
const surface = parseCssColor(background === "transparent" ? palette["--skin-recovery-toolbar-surface"] : background)!;
assert.ok(contrastRatio(parseCssColor(toolbar.border)!, surface) >= HOST_CONTROL_MIN_BORDER_CONTRAST,
`${background} background with ${border ?? "inherited"} border produced ${toolbar.border}`);
assert.ok(contrastRatio(parseCssColor(toolbar.focus)!, surface) >= HOST_CONTROL_MIN_ACCENT_CONTRAST,
`${background} background produced ${toolbar.focus} focus ring`);
}
}
});
test("toolbar hover colours and Classic geometry are sanitized independently", () => {
const classic = resolveToolbar({
"--skin-recovery-toolbar-height": "22px",
"--skin-recovery-toolbar-padding": "0 4px",
"--skin-recovery-toolbar-radius": "2px",
"--skin-recovery-toolbar-font-size": "11px",
"--skin-recovery-toolbar-gap": "1px",
"--skin-recovery-toolbar-icon-size": "16px",
});
assert.equal(classic.minHeight, 22);
assert.equal(classic.paddingX, 4);
assert.equal(classic.paddingY, 0);
assert.equal(classic.radius, 2);
assert.equal(classic.fontSize, 11);
assert.equal(classic.gap, 1);
assert.equal(classic.iconSize, 16);
const unreadableHover = resolveToolbar({
"--skin-recovery-toolbar-background": "#ffffff",
"--skin-recovery-toolbar-foreground": "#757575",
"--skin-recovery-toolbar-hover-background": "#eeeeee",
"--skin-recovery-toolbar-hover-border": "not-a-colour",
});
assert.equal(unreadableHover.hoverBackground, "rgb(255, 255, 255)");
assert.equal(unreadableHover.hoverBorder, "rgb(49, 82, 79)");
const clamped = resolveToolbar({
"--skin-recovery-toolbar-gap": "100px",
"--skin-recovery-toolbar-icon-size": "2px",
});
assert.equal(clamped.gap, TOOLBAR_MAX_GAP);
assert.equal(clamped.iconSize, TOOLBAR_MIN_ICON_SIZE);
const oversized = resolveToolbar({ "--skin-recovery-toolbar-icon-size": "100px" });
assert.equal(oversized.iconSize, TOOLBAR_MAX_ICON_SIZE);
assert.equal(resolveToolbar().gap, TOOLBAR_DEFAULT_GAP);
assert.equal(resolveToolbar().iconSize, TOOLBAR_DEFAULT_ICON_SIZE);
});
test("capsule tokens keep their opaque palette and 28px hit target", () => {
const capsule = resolveHostControlTokens(style({
"--skin-recovery-background": "transparent",
"--skin-recovery-foreground": "#1a1a1a",
"--skin-recovery-toolbar-height": "22px",
}), "host.recovery", raw => raw, RECOVERY_CONTROL_DEFAULTS);
assert.equal(capsule.background, "rgb(255, 255, 255)");
assert.equal(capsule.hitTarget, 28);
});
test("unreadable or invalid toolbar tokens fall back to a visible, readable button", () => {
const transparentUnreadable = resolveToolbar({
"--skin-recovery-toolbar-background": "rgba(0, 0, 0, 0)",
"--skin-recovery-toolbar-foreground": "#ffffff",
}, {}, { r: 255, g: 255, b: 255 });
assert.equal(transparentUnreadable.background, "rgb(255, 255, 255)");
assert.equal(transparentUnreadable.foreground, "rgb(49, 82, 79)");
assert.ok(contrastRatio(parseCssColor(transparentUnreadable.foreground)!, parseCssColor(transparentUnreadable.background)!) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST);
const lowContrast = resolveToolbar({
"--skin-recovery-toolbar-background": "#777777",
"--skin-recovery-toolbar-foreground": "#888888",
});
assert.equal(lowContrast.background, "rgb(255, 255, 255)");
assert.equal(lowContrast.foreground, "rgb(49, 82, 79)");
const invalid = resolveToolbar({
"--skin-recovery-toolbar-background": "not-a-colour",
"--skin-recovery-toolbar-foreground": "not-a-colour",
"--skin-recovery-toolbar-radius": "999px",
"--skin-recovery-toolbar-font": "url(https://example.invalid/font.woff2)",
"--skin-recovery-toolbar-font-size": "2px",
"--skin-recovery-toolbar-padding": "100px",
"--skin-recovery-toolbar-height": "2px",
"--skin-recovery-toolbar-shadow": "url(https://example.invalid/pixel)",
});
assert.equal(invalid.background, "rgb(255, 255, 255)");
assert.equal(invalid.foreground, "rgb(49, 82, 79)");
assert.equal(invalid.radius, 24, "the toolbar radius is clamped to its own maximum");
assert.equal(invalid.font, RECOVERY_CONTROL_DEFAULTS.font);
assert.equal(invalid.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
// A syntactically valid but oversized padding is clamped, not applied raw.
assert.equal(invalid.paddingX, TOOLBAR_MAX_PADDING);
assert.equal(invalid.paddingY, TOOLBAR_MAX_PADDING);
assert.equal(invalid.minHeight, TOOLBAR_MIN_HEIGHT);
assert.equal(invalid.shadow, "none");
const oversized = resolveToolbar({
"--skin-recovery-toolbar-font-size": "64px",
"--skin-recovery-toolbar-height": "200px",
"--skin-recovery-toolbar-padding": "100px 100px",
});
assert.equal(oversized.fontSize, TOOLBAR_MAX_FONT_SIZE);
assert.equal(oversized.minHeight, TOOLBAR_MAX_HEIGHT);
assert.equal(oversized.paddingX, TOOLBAR_MAX_PADDING);
assert.equal(oversized.paddingY, TOOLBAR_MAX_PADDING);
});
test("toolbar tokens reject skin fonts and detect declarations", () => {
assert.equal(hostToolbarTokenProperty("host.recovery", "background"), "--skin-recovery-toolbar-background");
assert.equal(hostToolbarTokenProperty("host.recovery", "font-size"), "--skin-recovery-toolbar-font-size");
assert.equal(hasHostToolbarTokens(style({}), "host.recovery"), false);
assert.equal(hasHostToolbarTokens(style({ "--skin-host-toolbar-shadow": "none" }), "host.recovery"), true);
assert.equal(hasHostToolbarTokens(style({ "--skin-recovery-toolbar-padding": "4px" }), "host.recovery"), true);
const webFonts = new Set(["blank glyphs"]);
const font = resolveHostControlToolbarTokens(
style({ "--skin-recovery-toolbar-font": '"Blank Glyphs", sans-serif' }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
family => webFonts.has(family),
).font;
assert.equal(font, RECOVERY_CONTROL_DEFAULTS.font);
});
test("applying and clearing toolbar tokens writes only toolbar variables", () => {
const values = new Map<string, string>();
const control = {
style: {
setProperty: (name: string, value: string) => { values.set(name, value); },
removeProperty: (name: string) => { values.delete(name); },
},
} as unknown as HTMLElement;
applyHostControlToolbarTokens(control, resolveToolbar({
"--skin-recovery-toolbar-background": "#ffffff",
"--skin-recovery-toolbar-foreground": "#1a1a1a",
"--skin-recovery-toolbar-padding": "6px 14px",
"--skin-recovery-toolbar-height": "36px",
"--skin-recovery-toolbar-hover-background": "#eaf2fd",
"--skin-recovery-toolbar-hover-border": "#b8cfe8",
"--skin-recovery-toolbar-gap": "1px",
"--skin-recovery-toolbar-icon-size": "16px",
}));
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.background), "rgb(255, 255, 255)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.foreground), "rgb(26, 26, 26)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.paddingX), "14px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.paddingY), "6px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.minHeight), "36px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBackground), "rgb(234, 242, 253)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBorder), "rgb(184, 207, 232)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.gap), "1px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.iconSize), "16px");
applyHostControlToolbarTokens(control, null);
assert.equal(values.size, 0);
});
+359 -5
View File
@@ -44,6 +44,42 @@ export const HOST_CONTROL_TOKEN_NAMES = [
export type HostControlTokenName = (typeof HOST_CONTROL_TOKEN_NAMES)[number];
/**
* Extra tokens read only for `mode: "toolbar"` recovery buttons. They make a
* host-owned button able to match a neighbouring top-bar button without
* giving the skin any DOM control:
*
* --skin-recovery-toolbar-<token> (per-part)
* --skin-host-toolbar-<token> (global fallback)
*
* Colours fall back to the normal `--skin-recovery-*` / `--skin-host-*` set;
* radius, padding, height, font size and shadow use toolbar defaults so a
* capsule radius (999px) or the fixed pale built-in button never leaks in.
*/
export const HOST_TOOLBAR_TOKEN_NAMES = [
"background", "foreground", "border", "radius", "font", "font-size", "padding", "height", "shadow",
"hover-background", "hover-border", "surface", "gap", "icon-size",
] as const;
export type HostToolbarTokenName = (typeof HOST_TOOLBAR_TOKEN_NAMES)[number];
export const HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES: Readonly<Record<HostToolbarTokenName, string>> = {
background: "--skin-host-toolbar-background",
foreground: "--skin-host-toolbar-foreground",
border: "--skin-host-toolbar-border",
radius: "--skin-host-toolbar-radius",
font: "--skin-host-toolbar-font",
"font-size": "--skin-host-toolbar-font-size",
padding: "--skin-host-toolbar-padding",
height: "--skin-host-toolbar-height",
shadow: "--skin-host-toolbar-shadow",
"hover-background": "--skin-host-toolbar-hover-background",
"hover-border": "--skin-host-toolbar-hover-border",
surface: "--skin-host-toolbar-surface",
gap: "--skin-host-toolbar-gap",
"icon-size": "--skin-host-toolbar-icon-size",
};
/** Global token set read from the active skin root (or a slot anchor). */
export const HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES: Readonly<Record<HostControlTokenName, string>> = {
accent: "--skin-host-accent",
@@ -74,6 +110,10 @@ export function hostControlTokenProperty(part: string, token: HostControlTokenNa
return `--skin-${hostControlTokenKey(part)}-${token}`;
}
export function hostToolbarTokenProperty(part: string, token: HostToolbarTokenName): string {
return `--skin-${hostControlTokenKey(part)}-toolbar-${token}`;
}
/** Host-owned variables written inside the closed shadow root. */
export const HOST_CONTROL_APPLIED_VARIABLES = {
accent: "--ws-control-accent",
@@ -88,6 +128,25 @@ export const HOST_CONTROL_APPLIED_VARIABLES = {
builtInBorder: "--ws-control-builtin-border",
} as const;
/** Host-owned variables read by the toolbar-mode button CSS. */
export const HOST_TOOLBAR_APPLIED_VARIABLES = {
background: "--ws-toolbar-background",
foreground: "--ws-toolbar-foreground",
border: "--ws-toolbar-border",
radius: "--ws-toolbar-radius",
font: "--ws-toolbar-font",
fontSize: "--ws-toolbar-font-size",
paddingX: "--ws-toolbar-padding-x",
paddingY: "--ws-toolbar-padding-y",
minHeight: "--ws-toolbar-min-height",
shadow: "--ws-toolbar-shadow",
focus: "--ws-toolbar-focus",
hoverBackground: "--ws-toolbar-hover-background",
hoverBorder: "--ws-toolbar-hover-border",
gap: "--ws-toolbar-gap",
iconSize: "--ws-toolbar-icon-size",
} as const;
export interface HostControlRawTokens {
/** Computed-style colour values; unresolved values are rejected. */
accent?: string;
@@ -130,12 +189,39 @@ export interface HostControlTokens {
builtInBorder?: string;
}
/** Resolved style of a toolbar-mode recovery button (applied to its wrapper). */
export interface HostControlToolbarTokens {
background: string;
foreground: string;
border: string;
radius: number;
font: string;
fontSize: number;
paddingX: number;
paddingY: number;
/** Minimum button height; defaults to the size tier and may reach 22px in toolbar mode. */
minHeight: number;
shadow: string;
hoverBackground: string;
hoverBorder: string;
/** Space between grouped host buttons. */
gap: number;
/** Size of the host-owned toolbar icon. */
iconSize: number;
/** Focus ring colour, from the readable accent of the control palette. */
focus: string;
}
export interface RgbColor {
r: number;
g: number;
b: number;
}
export interface RgbaColor extends RgbColor {
a: number;
}
const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
@@ -147,6 +233,29 @@ const ON_ACCENT_DARK: RgbColor = { r: 17, g: 24, b: 39 };
const MAX_RADIUS = 999;
const MAX_FONT_LENGTH = 120;
const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
/** Toolbar-mode geometry limits; only an explicit height may reach 22px. */
export const TOOLBAR_MIN_HEIGHT = 22;
export const TOOLBAR_DEFAULT_RADIUS = 6;
export const TOOLBAR_MAX_RADIUS = 24;
export const TOOLBAR_DEFAULT_PADDING_X = 12;
export const TOOLBAR_DEFAULT_PADDING_Y = 6;
export const TOOLBAR_MAX_PADDING = 48;
export const TOOLBAR_MAX_HEIGHT = 72;
export const TOOLBAR_MAX_FONT_SIZE = 20;
export const TOOLBAR_DEFAULT_GAP = 4;
export const TOOLBAR_MAX_GAP = 16;
export const TOOLBAR_DEFAULT_ICON_SIZE = 16;
export const TOOLBAR_MIN_ICON_SIZE = 12;
export const TOOLBAR_MAX_ICON_SIZE = 24;
const MAX_SHADOW_LENGTH = 160;
const LENGTH_PX_PATTERN = /^(-?\d+(?:\.\d+)?)px$/i;
const PADDING_PATTERN = /^(0|\d+(?:\.\d+)?px)(?:\s+(0|\d+(?:\.\d+)?px))?$/i;
/**
* A single box-shadow value: optional `inset`, two to four px offsets/sizes
* and one simple colour. `url()`, `var()`, extra shadows and declarations are
* rejected so a token can never load a resource or escape the inline value.
*/
const SHADOW_PATTERN = /^(?:none|(?:inset\s+)?(?:-?(?:0|(?:\d+(?:\.\d+)?)px)\s+){2,4}(?:#[0-9a-f]{3,8}|rgba?\([^()]*\)|[a-z]+))$/i;
/**
* The skin compiler renames every skin/plugin `@font-face` family to
* `ws-<skin id>[-<plugin id>]-<name>` (see `compileSkinCss` in
@@ -206,10 +315,11 @@ export const PERMISSION_CONTROL_DEFAULTS: HostControlDefaults = {
},
};
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
export function parseCssColor(value: string | undefined | null): RgbColor | null {
/** Parse CSS colours to sRGB channels plus alpha for toolbar transparency checks. */
export function parseCssColorWithAlpha(value: string | undefined | null): RgbaColor | null {
if (!value) return null;
const text = value.trim().toLowerCase();
if (text === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
const hex = /^#([0-9a-f]{3,8})$/.exec(text);
if (hex) {
const digits = hex[1];
@@ -218,6 +328,7 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
r: Number.parseInt(digits[0] + digits[0], 16),
g: Number.parseInt(digits[1] + digits[1], 16),
b: Number.parseInt(digits[2] + digits[2], 16),
a: digits.length === 4 ? Number.parseInt(digits[3] + digits[3], 16) / 255 : 1,
};
}
if (digits.length === 6 || digits.length === 8) {
@@ -225,6 +336,7 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
r: Number.parseInt(digits.slice(0, 2), 16),
g: Number.parseInt(digits.slice(2, 4), 16),
b: Number.parseInt(digits.slice(4, 6), 16),
a: digits.length === 8 ? Number.parseInt(digits.slice(6, 8), 16) / 255 : 1,
};
}
return null;
@@ -242,7 +354,30 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
const channel = percent ? parsed * 2.55 : parsed;
channels.push(Math.round(Math.min(255, Math.max(0, channel))));
}
return { r: channels[0], g: channels[1], b: channels[2] };
let alpha = 1;
if (parts.length === 4) {
const rawAlpha = Number.parseFloat(parts[3]);
if (!Number.isFinite(rawAlpha)) return null;
alpha = parts[3].endsWith("%") ? rawAlpha / 100 : rawAlpha;
alpha = Math.min(1, Math.max(0, alpha));
}
return { r: channels[0], g: channels[1], b: channels[2], a: alpha };
}
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
export function parseCssColor(value: string | undefined | null): RgbColor | null {
const color = parseCssColorWithAlpha(value);
return color ? { r: color.r, g: color.g, b: color.b } : null;
}
/** Composite a possibly translucent colour over an opaque sRGB surface. */
export function compositeRgb(foreground: RgbaColor, background: RgbColor): RgbColor {
const alpha = Math.min(1, Math.max(0, foreground.a));
return {
r: Math.round(foreground.r * alpha + background.r * (1 - alpha)),
g: Math.round(foreground.g * alpha + background.g * (1 - alpha)),
b: Math.round(foreground.b * alpha + background.b * (1 - alpha)),
};
}
export function formatRgb(color: RgbColor): string {
@@ -449,6 +584,225 @@ export function applyHostControlTokens(control: HTMLElement, tokens: HostControl
if (tokens.builtInBorder) style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
}
function readToolbarTokenSet(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
resolveProperty: (token: HostToolbarTokenName) => string,
): Partial<Record<HostToolbarTokenName, string>> {
if (!style) return {};
const tokens: Partial<Record<HostToolbarTokenName, string>> = {};
for (const token of HOST_TOOLBAR_TOKEN_NAMES) {
const value = style.getPropertyValue(resolveProperty(token)).trim();
if (value) tokens[token] = value;
}
return tokens;
}
function sanitizeToolbarFontSize(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const size = Number.parseFloat(match[1]);
return Number.isFinite(size)
? Math.min(TOOLBAR_MAX_FONT_SIZE, Math.max(HOST_CONTROL_MIN_FONT_SIZE, fallback, size))
: fallback;
}
function sanitizeToolbarPadding(value: string | undefined): { x: number; y: number } | undefined {
if (!value) return undefined;
const match = PADDING_PATTERN.exec(value.trim());
if (!match) return undefined;
const first = Number.parseFloat(match[1]);
const second = match[2] === undefined ? first : Number.parseFloat(match[2]);
if (!Number.isFinite(first) || !Number.isFinite(second)) return undefined;
const clamp = (size: number) => Math.min(TOOLBAR_MAX_PADDING, Math.max(0, size));
return { x: clamp(second), y: clamp(first) };
}
function sanitizeToolbarHeight(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const height = Number.parseFloat(match[1]);
return Number.isFinite(height)
? Math.min(TOOLBAR_MAX_HEIGHT, Math.max(TOOLBAR_MIN_HEIGHT, height))
: fallback;
}
function sanitizeToolbarLength(value: string | undefined, fallback: number, min: number, max: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const length = Number.parseFloat(match[1]);
return Number.isFinite(length) ? Math.min(max, Math.max(min, length)) : fallback;
}
function sanitizeToolbarShadow(value: string | undefined): string | undefined {
if (!value) return undefined;
const shadow = value.trim().replace(/\s+/g, " ");
if (!shadow || shadow.length > MAX_SHADOW_LENGTH || !SHADOW_PATTERN.test(shadow)) return undefined;
return shadow;
}
/** True when the skin declares at least one toolbar-mode token. */
export function hasHostToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
): boolean {
if (!style) return false;
return HOST_TOOLBAR_TOKEN_NAMES.some((token) =>
Boolean(style.getPropertyValue(hostToolbarTokenProperty(part, token)).trim())
|| Boolean(style.getPropertyValue(HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES[token]).trim())
);
}
function parseToolbarColor(raw: string | undefined, probeColor: ColorProbe): RgbaColor | null {
return parseCssColorWithAlpha(raw ? probeColor(raw) : undefined);
}
function formatToolbarColor(color: RgbaColor): string {
return color.a === 0 ? "transparent" : formatRgb(color);
}
function resolveToolbarSurface(
partTokens: Partial<Record<HostToolbarTokenName, string>>,
globalTokens: Partial<Record<HostToolbarTokenName, string>>,
probeColor: ColorProbe,
sampledSurface: RgbColor | null | undefined,
defaults: HostControlDefaults,
): RgbColor {
for (const raw of [partTokens.surface, globalTokens.surface]) {
const color = parseToolbarColor(raw, probeColor);
if (color?.a === 1) return { r: color.r, g: color.g, b: color.b };
}
return sampledSurface ?? defaults.background;
}
function readableColorOn(candidates: readonly RgbColor[], background: RgbColor): RgbColor {
const readable = candidates.find((color) => contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
if (readable) return readable;
return contrastRatio(ON_ACCENT_DARK, background) >= contrastRatio(ON_ACCENT_LIGHT, background)
? ON_ACCENT_DARK
: ON_ACCENT_LIGHT;
}
function resolveToolbarBorder(
raw: string | undefined,
background: RgbColor,
fallbacks: readonly RgbColor[],
probeColor: ColorProbe,
): string {
const color = parseToolbarColor(raw, probeColor);
if (!color) return formatRgb(readableColorOn(fallbacks, background));
if (color.a === 0) return "transparent";
return contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST
? formatRgb(color)
: formatRgb(readableColorOn(fallbacks, background));
}
function resolveToolbarHoverBorder(raw: string | undefined, fallback: string, probeColor: ColorProbe): string {
const color = parseToolbarColor(raw, probeColor);
if (!color) return fallback;
// Classic's subtle #b8cfe8 hover edge is intentionally below the 3:1
// non-text contrast floor; validate syntax without rejecting that design.
return formatToolbarColor(color);
}
/**
* Resolve the toolbar button palette and geometry.
*
* Transparent backgrounds and borders are valid. Text is checked against an
* explicit opaque `surface` token, or the caller's sampled anchor/ancestor
* surface, never against transparent black. Opaque colours keep the existing
* capsule contrast floors. Hover colours fall back independently to the normal
* button colours, and only an explicit toolbar height may reach the 22px
* Classic toolbar floor; the size-tier default remains 28/32/36px.
*/
export function resolveHostControlToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
probeColor: ColorProbe,
defaults: HostControlDefaults,
isWebFont: WebFontCheck = NO_WEB_FONTS,
sampledSurface?: RgbColor | null,
): HostControlToolbarTokens {
const base = resolveHostControlTokens(style, part, probeColor, defaults, isWebFont);
const globalTokens = readToolbarTokenSet(style, (token) => HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES[token]);
const partTokens = readToolbarTokenSet(style, (token) => hostToolbarTokenProperty(part, token));
const merged = { ...globalTokens, ...partTokens };
const baseBackground = parseCssColor(base.background) ?? defaults.background;
const baseForeground = parseCssColor(base.foreground) ?? defaults.foreground;
const baseBorder = parseCssColor(base.border) ?? defaults.border;
const baseAccent = parseCssColor(base.accent) ?? defaults.accent;
const surface = resolveToolbarSurface(partTokens, globalTokens, probeColor, sampledSurface, defaults);
let background = parseToolbarColor(merged.background, probeColor) ?? { ...baseBackground, a: 1 };
let foreground = parseToolbarColor(merged.foreground, probeColor) ?? { ...baseForeground, a: 1 };
let effectiveBackground = background.a === 0 ? surface : background;
if (contrastRatio(foreground, effectiveBackground) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
background = { ...baseBackground, a: 1 };
foreground = { ...baseForeground, a: 1 };
effectiveBackground = baseBackground;
}
const border = resolveToolbarBorder(merged.border, effectiveBackground, [baseBorder, baseForeground], probeColor);
let hoverBackground = parseToolbarColor(merged["hover-background"], probeColor) ?? background;
let effectiveHoverBackground = hoverBackground.a === 0 ? surface : hoverBackground;
if (contrastRatio(foreground, effectiveHoverBackground) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
hoverBackground = background;
effectiveHoverBackground = effectiveBackground;
}
const hoverBorder = resolveToolbarHoverBorder(merged["hover-border"], border, probeColor);
const padding = sanitizeToolbarPadding(merged.padding);
return {
background: formatToolbarColor(background),
foreground: formatRgb(foreground),
border,
radius: sanitizeRadius(merged.radius, TOOLBAR_DEFAULT_RADIUS, TOOLBAR_MAX_RADIUS),
font: sanitizeFont(merged.font, base.font, isWebFont),
fontSize: sanitizeToolbarFontSize(merged["font-size"], base.fontSize),
paddingX: padding?.x ?? TOOLBAR_DEFAULT_PADDING_X,
paddingY: padding?.y ?? TOOLBAR_DEFAULT_PADDING_Y,
minHeight: sanitizeToolbarHeight(merged.height, base.hitTarget),
shadow: sanitizeToolbarShadow(merged.shadow) ?? "none",
hoverBackground: formatToolbarColor(hoverBackground),
hoverBorder,
gap: sanitizeToolbarLength(merged.gap, TOOLBAR_DEFAULT_GAP, 0, TOOLBAR_MAX_GAP),
iconSize: sanitizeToolbarLength(
merged["icon-size"],
TOOLBAR_DEFAULT_ICON_SIZE,
TOOLBAR_MIN_ICON_SIZE,
TOOLBAR_MAX_ICON_SIZE,
),
focus: formatRgb(readableColorOn([baseAccent, baseForeground], effectiveBackground)),
};
}
/** Apply (or clear) toolbar-mode variables on the button wrapper. */
export function applyHostControlToolbarTokens(
control: HTMLElement,
tokens: HostControlToolbarTokens | null,
): void {
const style = control.style;
for (const property of Object.values(HOST_TOOLBAR_APPLIED_VARIABLES)) style.removeProperty(property);
if (!tokens) return;
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.background, tokens.background);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.foreground, tokens.foreground);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.border, tokens.border);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.font, tokens.font);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.paddingX, `${tokens.paddingX}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.paddingY, `${tokens.paddingY}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.minHeight, `${tokens.minHeight}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.shadow, tokens.shadow);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.focus, tokens.focus);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBackground, tokens.hoverBackground);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBorder, tokens.hoverBorder);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.gap, `${tokens.gap}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.iconSize, `${tokens.iconSize}px`);
}
export interface HostControlThemeBindingOptions {
layer: HostOwnedLayer;
/** The host-owned element whose inline `--ws-control-*` variables are set. */
@@ -584,8 +938,8 @@ export function createHostControlProbe(shadow: ShadowRoot): HostControlProbe {
canvas.fillStyle = "#000";
canvas.fillStyle = computed;
canvas.fillRect(0, 0, 1, 1);
const [r, g, b] = canvas.getImageData(0, 0, 1, 1).data;
return formatRgb({ r, g, b });
const [r, g, b, a] = canvas.getImageData(0, 0, 1, 1).data;
return a === 255 ? formatRgb({ r, g, b }) : `rgba(${r}, ${g}, ${b}, ${a / 255})`;
};
return {
@@ -6,6 +6,7 @@ import {
FLOATING_WEIGHT_PROTECTED,
FLOATING_WEIGHT_POINTER,
chooseFloatingPosition,
floatingHitsAvoidRect,
floatingRect,
shouldFold,
floatingScore,
@@ -33,6 +34,23 @@ test("floating rects follow the corner margins and stay inside the viewport", ()
assert.ok(narrow.bottom <= 844);
});
test("a docked host toolbar is an excluded floating spot, not just a weighted obstacle", () => {
// 318px stage from the GUI retest: a 218x36 built-in toolbar docked at the
// top-left; the fallback capsule is 169x38. Top corners overlap it, so a
// capsule pushed off the bottom dock must not land there.
const narrow = { width: 318, height: 638 };
const cap = { width: 169, height: 38 };
const dockedToolbar = rect(20, 10, 218, 36);
assert.equal(floatingHitsAvoidRect("top-left", cap, narrow, margins, [dockedToolbar]), true);
assert.equal(floatingHitsAvoidRect("top-right", cap, narrow, margins, [dockedToolbar]), true);
assert.equal(floatingHitsAvoidRect("top-center", cap, narrow, margins, [dockedToolbar]), true);
assert.equal(floatingHitsAvoidRect("middle-left", cap, narrow, margins, [dockedToolbar]), false);
assert.equal(floatingHitsAvoidRect("middle-right", cap, narrow, margins, [dockedToolbar]), false);
assert.equal(floatingHitsAvoidRect("bottom-left", cap, narrow, margins, [dockedToolbar]), false);
// A one-pixel brush against the footprint is not a cover.
assert.equal(floatingHitsAvoidRect("top-left", cap, narrow, margins, [rect(180, 50, 10, 10)]), false);
});
test("score is zero without overlap, ignores 1px brushes and weights dialog and (above all) protected controls", () => {
const footprint = rect(12, 724, 200, 38);
assert.equal(floatingScore(footprint, [{ rect: rect(400, 400, 40, 40), weight: 1 }]), 0);
@@ -108,6 +126,21 @@ test("a move never lands on the pointer or the focused control, but the current
assert.equal(stay.position, "top-left");
});
test("an externally excluded current position is scored like every replacement candidate", () => {
const pointerAndFocus: FloatingObstacle = { rect: rect(84, 15, 32, 32), weight: FLOATING_WEIGHT_POINTER };
const choice = chooseFloatingPosition({
current: "bottom-left",
currentEligible: false,
size: capsule,
viewport,
margins,
obstacles: [],
moveObstacles: [pointerAndFocus],
positions: ["top-left", "top-right"],
});
assert.deepEqual(choice, { position: "top-right", score: 0 });
});
test("folding needs to free at least one control; a full-screen click-away layer does not fold the capsule", () => {
const backdrop: FloatingObstacle[] = [{ rect: rect(0, 0, 1280, 800), weight: FLOATING_WEIGHT_CONTROL }];
const full = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles: backdrop });
+54 -10
View File
@@ -165,10 +165,13 @@ export interface FloatingChoice {
* modal dialog's backdrop, a toast) and going back there would cover it.
* `moveObstacles` (the user's pointer and focused control) only count against
* positions the control would move to, so it never jumps under the cursor or
* onto the field being typed in.
* onto the field being typed in. Set `currentEligible` false when an external
* hard exclusion removes the real current position; it must then be scored like
* every other candidate instead of being replaced by a synthetic current spot.
*/
export function chooseFloatingPosition(input: {
current: FloatingPosition;
currentEligible?: boolean;
size: FloatingSize;
viewport: FloatingViewport;
margins: FloatingMargins;
@@ -179,17 +182,19 @@ export function chooseFloatingPosition(input: {
}): FloatingChoice {
const positions = input.positions ?? FLOATING_POSITIONS;
const moveObstacles = input.moveObstacles ?? [];
const currentEligible = input.currentEligible ?? true;
const scoreAt = (position: FloatingPosition) => {
const footprint = floatingRect(position, input.size, input.viewport, input.margins);
const score = floatingScore(footprint, input.obstacles);
return position === input.current || !moveObstacles.length ? score : score + floatingScore(footprint, moveObstacles);
const keepCurrent = currentEligible && position === input.current;
return keepCurrent || !moveObstacles.length ? score : score + floatingScore(footprint, moveObstacles);
};
const currentScore = scoreAt(input.current);
if (currentScore === 0) {
if (currentEligible && currentScore === 0) {
if (input.home && input.home !== input.current && scoreAt(input.home) === 0) return { position: input.home, score: 0 };
return { position: input.current, score: 0 };
}
let best: FloatingChoice = { position: input.current, score: currentScore };
let best: FloatingChoice = { position: input.current, score: currentEligible ? currentScore : Number.POSITIVE_INFINITY };
for (const position of positions) {
if (position === input.current) continue;
const score = scoreAt(position);
@@ -228,6 +233,22 @@ function rectsIntersect(first: HostPartRect, second: HostPartRect): boolean {
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
}
/**
* Whether a candidate corner would put the control on top of a docked host
* control. Used to exclude such spots outright; scoring alone can still pick
* one when the other corners cover skin controls.
*/
export function floatingHitsAvoidRect(
position: FloatingPosition,
size: FloatingSize,
viewport: FloatingViewport,
margins: FloatingMargins,
avoidRects: readonly HostPartRect[],
): boolean {
const footprint = floatingRect(position, size, viewport, margins);
return avoidRects.some(rect => rectsIntersect(footprint, rect));
}
/* ------------------------------------------------------------------ *
* DOM binding
* ------------------------------------------------------------------ */
@@ -358,6 +379,14 @@ export interface FloatingAvoidanceOptions {
onCompactChange?: (compact: boolean) => void;
/** Skip re-evaluation (hovered, focused, slotted, drawer open…). */
paused?: () => boolean;
/**
* Footprints of host controls that are docked in the top layer. They are
* invisible to `collectFloatingObstacles` (which scans the light DOM), but a
* floating fallback must never sit on them: a covered button loses its
* label and its click lands on the wrong action. Positions that intersect
* one of these rects are skipped whenever any free position exists.
*/
avoidRects?: () => readonly HostPartRect[];
}
export interface FloatingAvoidance {
@@ -457,13 +486,28 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
}
const now = Date.now();
const urgent = now < urgentUntil;
// Return home only after a screen change (see chooseFloatingPosition).
const home = urgent ? defaultPosition : undefined;
const full = chooseFloatingPosition({ current: position, size, viewport, margins, obstacles, moveObstacles, home });
// Docked recovery toolbars live in the closed shadow root, so the light-DOM
// obstacle scan above cannot see them. Exclude their footprints outright:
// scoring alone could still park the fallback where a docked button sits
// (GUI reproduced this at 320px: the library capsule covered the built-in
// toolbar and its centre click hit the built-in action). If every corner
// is docked, fall back to scoring over all positions rather than trapping
// the capsule off-screen.
const avoid = options.avoidRects?.() ?? [];
const forbiddenAt = (candidate: FloatingPosition) =>
floatingHitsAvoidRect(candidate, size, viewport, margins, avoid);
const freePositions = FLOATING_POSITIONS.filter(candidate => !forbiddenAt(candidate));
const positions = freePositions.length ? freePositions : FLOATING_POSITIONS;
const currentEligible = !forbiddenAt(position);
const park = forbiddenAt(defaultPosition) && freePositions.length ? freePositions[0] : defaultPosition;
// Return home only after a screen change (see chooseFloatingPosition), and
// only when the default corner is not one of the docked footprints.
const home = urgent && !forbiddenAt(defaultPosition) ? defaultPosition : undefined;
const full = chooseFloatingPosition({ current: position, currentEligible, size, viewport, margins, obstacles, moveObstacles, positions, home });
let next = full;
let nextCompact = false;
if (full.score > 0 && small && small.width > 0 && small.height > 0) {
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles });
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles, positions });
if (shouldFold(full, reduced)) {
next = reduced;
nextCompact = true;
@@ -514,8 +558,8 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
moveTimes = [];
frozenUntil = now + HOST_FLOATING_FLAP_FREEZE_MS;
frozenEscaped = false;
if (position !== defaultPosition) {
position = defaultPosition;
if (position !== park) {
position = park;
apply(position);
}
setCompact(false);
+7 -3
View File
@@ -103,17 +103,21 @@ const popoverFallbacks = new WeakSet<HTMLElement>();
* assigning `display`. The same path is used when the Popover API is missing
* or when top-layer promotion throws (for example in a constrained embed).
*/
export function syncRecoveryPopover(element: HTMLElement | null | undefined, visible: boolean): void {
export function syncRecoveryPopover(
element: HTMLElement | null | undefined,
visible: boolean,
display: "flex" | "inline-flex" = "flex",
): void {
if (!element) return;
const enterFallback = (): void => {
popoverFallbacks.add(element);
element.removeAttribute("popover");
element.style.display = visible ? "flex" : "none";
element.style.display = visible ? display : "none";
};
if (popoverFallbacks.has(element)) {
element.style.display = visible ? "flex" : "none";
element.style.display = visible ? display : "none";
return;
}
@@ -9,6 +9,7 @@ type ShortcutEvent = {
altKey: boolean;
shiftKey: boolean;
key: string;
code: string;
};
const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
@@ -17,6 +18,7 @@ const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
altKey: false,
shiftKey: false,
key: "",
code: "",
...overrides,
});
@@ -24,16 +26,28 @@ test("the recovery shortcut requires the full Ctrl/Cmd+Alt+Shift+R chord", () =>
assert.equal(isRecoveryShortcut(shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "r" })), true);
// macOS uses the Meta/Command key in place of Ctrl.
assert.equal(isRecoveryShortcut(shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "R" })), true);
// Option/Shift turn the letter into a derived character (US layout: ®) on
// macOS; the physical key code must still match.
assert.equal(isRecoveryShortcut(shortcut({
metaKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyR",
})), true);
assert.equal(isRecoveryShortcut(shortcut({
ctrlKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyR",
})), true);
for (const rejected of [
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "x" }),
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "Enter" }),
// A derived character alone is not enough: the physical key must be R.
shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyX" }),
// Ordinary app/browser shortcuts must stay available.
shortcut({ ctrlKey: true, key: "r" }),
shortcut({ altKey: true, key: "r" }),
shortcut({ ctrlKey: true, shiftKey: true, key: "r" }),
shortcut({ ctrlKey: true, altKey: true, key: "r" }),
shortcut({ ctrlKey: false, altKey: true, shiftKey: true, key: "r" }),
// Incomplete modifiers stay rejected even when the physical code matches.
shortcut({ ctrlKey: true, altKey: true, key: "®", code: "KeyR" }),
]) {
assert.equal(isRecoveryShortcut(rejected), false, JSON.stringify(rejected));
}
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveHostRecoveryPresentation } from "./host-recovery-presentation.js";
const base = {
visible: true,
shortcutOpen: false,
libraryAvailable: true,
builtIn: { available: false, docked: false },
library: { available: false, docked: false },
};
test("a capsule-only skin keeps both actions in the capsule", () => {
const result = resolveHostRecoveryPresentation(base);
assert.deepEqual(result.capsuleActions, ["built-in", "library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.suppressLauncher, false);
assert.equal(result.toolbar.docked, false);
});
test("a docked toolbar group removes both actions from the capsule", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.docked, { builtIn: true, library: true });
assert.deepEqual(result.capsuleActions, []);
assert.equal(result.capsuleVisible, false);
assert.equal(result.suppressLauncher, true, "the toolbar library is the only library entry");
});
test("a failed anchor returns its action to the capsule without duplicating the other", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: true, docked: false },
});
assert.deepEqual(result.docked, { builtIn: true, library: false });
assert.deepEqual(result.capsuleActions, ["library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.suppressLauncher, true, "the floating capsule now carries the only library entry");
});
test("the shortcut forces the complete capsule and hides the toolbar", () => {
const result = resolveHostRecoveryPresentation({
...base,
shortcutOpen: true,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.docked, { builtIn: false, library: false });
assert.deepEqual(result.capsuleActions, ["built-in", "library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.toolbar.visible, false);
});
test("no recovery entry means no capsule, no toolbar and no launcher suppression", () => {
const result = resolveHostRecoveryPresentation({
...base,
visible: false,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.capsuleActions, []);
assert.equal(result.capsuleVisible, false);
assert.equal(result.toolbar.visible, false);
assert.equal(result.suppressLauncher, false);
});
test("an unavailable library never renders or suppresses anything", () => {
const result = resolveHostRecoveryPresentation({
...base,
libraryAvailable: false,
library: { available: false, docked: true },
});
assert.deepEqual(result.capsuleActions, ["built-in"]);
assert.equal(result.suppressLauncher, false);
});
test("a docked built-in toolbar button leaves only the library in the capsule", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: false, docked: false },
});
assert.deepEqual(result.capsuleActions, ["library"]);
assert.equal(result.capsuleVisible, true);
});
@@ -0,0 +1,87 @@
/**
* Pure presentation decisions for the trusted recovery entry.
*
* The recovery entry has two host buttons ("use built-in skin" and
* "application library"). A skin may dock them as one capsule (the historical
* `host.recovery` slot), as one chrome-less toolbar group, or as two separate
* toolbar buttons (`host.recovery.built-in` / `host.recovery.library`).
*
* This module keeps the duplicate and fallback rules in one testable place:
* - an action is only "in the toolbar" when its anchor is currently slotted,
* so a missing/hidden anchor immediately returns it to the floating capsule;
* - the capsule renders only the actions that are not currently in the
* toolbar, so the same page never shows two copies of an action;
* - the shortcut forces every action back into the capsule (and hides the
* toolbar) so one keystroke still summons the complete recovery entry;
* - a toolbar-mode application-library action suppresses the ordinary
* `host.plugins.launcher`, because the host button is now the only library
* entry on that page (docked or floating, the capsule still offers it).
*/
export type HostRecoveryAction = "built-in" | "library";
export interface HostRecoveryToolbarActionState {
/** The slot declaration exists and the action is usable on this page. */
available: boolean;
/** The slot binding currently reports a valid, docked anchor. */
docked: boolean;
}
export interface HostRecoveryPresentationInput {
/** The recovery entry should be visible at all (third-party skin / shortcut). */
visible: boolean;
/** The recovery shortcut is currently holding the entry open. */
shortcutOpen: boolean;
/** The application library is usable (connected with a plugin session). */
libraryAvailable: boolean;
builtIn: HostRecoveryToolbarActionState;
library: HostRecoveryToolbarActionState;
}
export interface HostRecoveryPresentation {
/** Toolbar entries the host should paint (and bind) on this page. */
toolbar: HostRecoveryToolbarActionState & { visible: boolean };
/** Whether each action is currently painted by a docked toolbar button. */
docked: HostRecoveryDockedState;
/** Actions still shown by the floating capsule, in render order. */
capsuleActions: HostRecoveryAction[];
capsuleVisible: boolean;
/** Hide the ordinary plugin launcher to keep exactly one library entry. */
suppressLauncher: boolean;
}
export interface HostRecoveryDockedState {
builtIn: boolean;
library: boolean;
}
export function resolveHostRecoveryPresentation(
input: HostRecoveryPresentationInput,
): HostRecoveryPresentation {
const toolbarVisible = input.visible && !input.shortcutOpen;
const docked: HostRecoveryDockedState = {
builtIn: toolbarVisible && input.builtIn.available && input.builtIn.docked,
library: toolbarVisible && input.libraryAvailable && input.library.available && input.library.docked,
};
const capsuleActions: HostRecoveryAction[] = [];
if (input.visible && !docked.builtIn) capsuleActions.push("built-in");
if (input.visible && input.libraryAvailable && !docked.library) capsuleActions.push("library");
return {
toolbar: {
available: toolbarVisible && (input.builtIn.available || input.library.available),
docked: docked.builtIn || docked.library,
visible: toolbarVisible,
},
docked,
capsuleActions,
capsuleVisible: capsuleActions.length > 0,
// A toolbar-mode library button replaces the normal launcher even while
// its anchor is invalid, because the fallback capsule would otherwise add
// a second library entry next to that launcher.
suppressLauncher: input.visible
&& input.libraryAvailable
&& input.library.available,
};
}
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
HOST_SLOT_VIEWPORT_INSET,
INITIAL_SLOT_MODE_STATE,
computeSlotPlacement,
evaluateSlottedControl,
@@ -160,9 +161,68 @@ test("a slotted capsule that would cover a protected control falls back", () =>
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, coversProtected: false }), { ok: true });
});
test("a toolbar that would cover another docked host control falls back", () => {
assert.deepEqual(
evaluateSlottedControl({
...baseEvaluation,
otherControls: [rect(160, 105, 120, 30)],
}),
{ ok: false, reason: "covers-host-control" },
);
// Edge contact is not a collision; both toolbars can still dock side by side.
assert.deepEqual(
evaluateSlottedControl({
...baseEvaluation,
otherControls: [rect(60, 105, 120, 30)],
}),
{ ok: true },
);
assert.deepEqual(
evaluateSlottedControl({ ...baseEvaluation, otherControls: [] }),
{ ok: true },
);
});
test("rect overlap ignores edge contact and sub-pixel slivers", () => {
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(50, 10, 100, 40)), true);
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(100, 0, 50, 40)), false);
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(99.5, 0, 50, 40)), false);
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(0, 60, 100, 40)), false);
});
test("toolbar buttons with long localised labels stay inside a narrow viewport", () => {
// German "Integrierten Skin verwenden" / Russian / Japanese labels make a
// toolbar button much wider than the capsule's short actions. The placement
// clamps it into the viewport; when the control is wider than the viewport
// the slot rejects it and the caller falls back to the capsule.
const viewport = { width: 320, height: 640 };
const wide = { width: 300, height: 64 };
const placement = computeSlotPlacement(rect(280, 8, 32, 32), wide, viewport, "end");
assert.ok(placement.left >= HOST_SLOT_VIEWPORT_INSET);
assert.ok(placement.left + wide.width <= viewport.width - HOST_SLOT_VIEWPORT_INSET);
const tooWide = rect(4, 8, 340, 64);
assert.deepEqual(
evaluateSlottedControl({
anchor: anchor({ rect: rect(0, 0, 320, 48) }),
controlRect: tooWide,
viewport,
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
hitTestOk: true,
}),
{ ok: false, reason: "control-offscreen" },
"an oversized toolbar must fall back to the visible capsule, not disappear",
);
// A wrapped two-line button (64px high) still passes the minimum hit target.
assert.deepEqual(
evaluateSlottedControl({
anchor: anchor({ rect: rect(0, 0, 320, 120) }),
controlRect: rect(4, 8, 300, 64),
viewport,
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
hitTestOk: true,
}),
{ ok: true },
);
});
+110 -19
View File
@@ -20,11 +20,17 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
import {
RECOVERY_CONTROL_DEFAULTS,
applyHostControlTokens,
applyHostControlToolbarTokens,
compositeRgb,
createHostControlProbe,
findSkinRoot,
parseCssColorWithAlpha,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlTokens,
type HostControlProbe,
type RgbColor,
type RgbaColor,
} from "./host-control-tokens.js";
export interface SlotViewport {
@@ -81,6 +87,7 @@ export type SlotFailureReason =
| "control-too-small"
| "control-offscreen"
| "covers-protected"
| "covers-host-control"
| "hit-test";
export interface SlotAnchorSnapshot {
@@ -107,6 +114,8 @@ export interface SlotEvaluationInput {
* capsule is top layer, so it would block those controls for the pointer.
*/
coversProtected?: boolean;
/** Footprints of other docked host controls this one must not cover. */
otherControls?: readonly HostPartRect[];
}
export type SlotEvaluation = { ok: true } | { ok: false; reason: SlotFailureReason };
@@ -161,6 +170,13 @@ export function evaluateSlottedControl(input: SlotEvaluationInput): SlotEvaluati
return { ok: false, reason: "control-too-small" };
}
if (!fullyInsideViewport(controlRect, viewport)) return { ok: false, reason: "control-offscreen" };
// Two independently anchored recovery toolbars can converge on the same
// narrow anchor (for example at 320px). Covering a sibling host control
// would make one of the buttons unreachable, so that action returns to the
// visible floating capsule instead of pretending to be docked.
if (input.otherControls?.some((rect) => rectsOverlap(controlRect, rect))) {
return { ok: false, reason: "covers-host-control" };
}
if (input.coversProtected) return { ok: false, reason: "covers-protected" };
if (!hitTestOk) return { ok: false, reason: "hit-test" };
return { ok: true };
@@ -214,6 +230,22 @@ function rectOf(rect: DOMRect | HostPartRect): HostPartRect {
};
}
/** Composite the anchor and top-bar ancestor backgrounds over the page canvas. */
export function sampleOpaqueSurface(element: Element | null, doc: Document = document): RgbColor {
const view = doc.defaultView;
const layers: RgbaColor[] = [];
for (let current: Element | null = element; current && view; current = current.parentElement) {
const color = parseCssColorWithAlpha(view.getComputedStyle(current).backgroundColor);
if (color && color.a > 0) layers.push(color);
if (color?.a === 1) break;
}
let surface: RgbColor = { r: 255, g: 255, b: 255 };
for (let index = layers.length - 1; index >= 0; index -= 1) {
surface = compositeRgb(layers[index], surface);
}
return surface;
}
/** Overlap of two rects in CSS pixels on both axes (more than 1px each). */
export function rectsOverlap(first: HostPartRect, second: HostPartRect): boolean {
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
@@ -271,22 +303,31 @@ function isVisibleAnchor(element: HTMLElement): boolean {
}
/**
* Resolve the first visible `[data-ws-part="<anchor>"]` inside the active
* skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
* Resolve the first visible candidate `[data-ws-part="<anchor>"]` inside the
* active skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
* (runtime plugins may Teleport to a `data-ws-skin-mount` slot, but every
* mount slot is part of the skin root), so a skin cannot point the recovery
* control at host chrome outside its own subtree.
*
* A candidate list lets one declaration cover several pages: the home and
* voice surfaces render different prefixed parts, but only one page is visible
* at a time, so the first visible candidate is the deterministic one. The
* binding re-resolves on every check, which is what makes a page switch (or a
* skin reload) fall back and re-dock without a rebind.
*/
export function resolveSkinAnchor(
anchor: string,
anchor: string | readonly string[],
doc: Document = document,
skinId?: string,
): HTMLElement | null {
const selector = `[data-ws-part="${anchor}"]`;
for (const root of doc.querySelectorAll(".ws-skin-root")) {
if (skinId && root.getAttribute("data-ws-skin") !== skinId) continue;
for (const element of root.querySelectorAll<HTMLElement>(selector)) {
if (isVisibleAnchor(element)) return element;
const anchors = typeof anchor === "string" ? [anchor] : anchor;
for (const candidate of anchors) {
const selector = `[data-ws-part="${candidate}"]`;
for (const root of doc.querySelectorAll(".ws-skin-root")) {
if (skinId && root.getAttribute("data-ws-skin") !== skinId) continue;
for (const element of root.querySelectorAll<HTMLElement>(selector)) {
if (isVisibleAnchor(element)) return element;
}
}
}
return null;
@@ -300,11 +341,30 @@ export interface HostSlotModeChange {
export interface HostSlotBindingOptions {
layer: HostOwnedLayer;
control: HTMLElement;
anchor: string;
/** One anchor name, or ordered candidates (first visible one wins). */
anchor: string | readonly string[];
/** Restricts anchor resolution and token fallback to this active skin. */
skinId?: string;
align?: SkinChromeSlotAlign;
resolveAnchor?: (anchor: string) => HTMLElement | null;
/**
* `toolbar` also applies `--skin-recovery-toolbar-*` / `--skin-host-toolbar-*`
* tokens for background, foreground, border, hover, radius, font, font size,
* padding, height, shadow, surface, gap and icon size. The capsule mode keeps
* the historical control tokens only.
*/
presentation?: "capsule" | "toolbar";
/**
* Called before measuring. A toolbar popover is closed while it floats, so
* its box would be 0×0 and the control could never re-dock after a fallback.
* The callback shows it for the synchronous check; `settle` hides it again
* in the same task when the anchor is still unusable, so nothing paints.
*/
prepare?: () => void;
/** Called after each evaluation with the resulting docked state. */
settle?: (slotted: boolean) => void;
resolveAnchor?: (anchor: string | readonly string[]) => HTMLElement | null;
/** Live footprints of other docked host controls; overlaps force a fallback. */
otherControls?: () => readonly HostPartRect[];
onModeChange?: (change: HostSlotModeChange) => void;
}
@@ -332,11 +392,12 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
if (!view) return NOOP_BINDING;
const win = view;
const resolveAnchor = options.resolveAnchor
?? ((name: string) => resolveSkinAnchor(name, doc, options.skinId));
?? ((name: string | readonly string[]) => resolveSkinAnchor(name, doc, options.skinId));
let state = INITIAL_SLOT_MODE_STATE;
let lastReason: SlotFailureReason | undefined;
let currentAnchor: HTMLElement | null = null;
let observingControl = false;
let observer: ResizeObserver | null = null;
const probe: HostControlProbe = createHostControlProbe(layer.shadow);
let frame: number | undefined;
@@ -348,9 +409,9 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
function readTokens(source: Element | null): HostControlTokens {
function readTokens(style: CSSStyleDeclaration | null): HostControlTokens {
return resolveHostControlTokens(
source ? win.getComputedStyle(source) : null,
style,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
@@ -387,27 +448,51 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
}
function observe(anchorElement: HTMLElement | null): void {
if (currentAnchor === anchorElement) return;
// Measurement-only display changes must not feed back into observer scheduling.
const watchControl = !options.prepare || (state.slotted && control.getClientRects().length > 0);
if (currentAnchor === anchorElement && observingControl === watchControl) return;
currentAnchor = anchorElement;
observingControl = watchControl;
if (!observer && typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(() => schedule());
}
if (!observer) return;
observer.disconnect();
observer.observe(control);
if (watchControl) observer.observe(control);
if (anchorElement) observer.observe(anchorElement);
}
function evaluate(): void {
if (disposed) return;
// A floating toolbar popover is closed; show it for this synchronous
// measurement. `settle` hides it again before paint on any failure.
options.prepare?.();
const anchorElement = resolveAnchor(anchorName);
observe(anchorElement);
// The fallback keeps the skin palette: read tokens from the anchor, or
// from the skin root when the anchor is missing or hidden.
const tokenSource = anchorElement
?? (options.skinId ? findSkinRoot(options.skinId, doc) : null);
const tokens = readTokens(tokenSource);
applyHostControlTokens(control, tokenSource ? tokens : null);
const tokenStyle = tokenSource ? win.getComputedStyle(tokenSource) : null;
const tokens = readTokens(tokenStyle);
applyHostControlTokens(control, tokenStyle ? tokens : null);
let toolbarMinHeight: number | undefined;
if (options.presentation === "toolbar") {
// Toolbar buttons get a second, independent token set so they can match
// a neighbouring top-bar button instead of the capsule palette. A
// transparent button is checked against the surface behind its anchor.
const toolbarTokens = tokenStyle
? resolveHostControlToolbarTokens(
tokenStyle,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
probe.isWebFont,
sampleOpaqueSurface(tokenSource, doc),
)
: null;
toolbarMinHeight = toolbarTokens?.minHeight;
applyHostControlToolbarTokens(control, toolbarTokens);
}
const controlBox = control.getBoundingClientRect();
maxSize = {
@@ -462,8 +547,9 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
anchor: anchorSnapshot,
controlRect: intendedRect,
viewport,
minHitTarget: tokens.hitTarget,
minHitTarget: toolbarMinHeight ?? tokens.hitTarget,
coversProtected,
otherControls: options.otherControls?.(),
hitTestOk: placement
? hitTestAt(placement.left, placement.top, { width: controlBox.width, height: controlBox.height })
: false,
@@ -481,6 +567,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
lastReason = reason;
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
}
options.settle?.(state.slotted);
observe(anchorElement);
}
/** Any unexpected error returns the capsule to the default corner. */
@@ -488,6 +576,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const wasSlotted = state.slotted;
state = nextSlotModeState(state, false);
clearPlacement();
options.settle?.(false);
observe(currentAnchor);
if (wasSlotted) onModeChange?.({ mode: "floating" });
}
@@ -535,6 +625,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
win.removeEventListener("scroll", schedule, { capture: true });
clearPlacement();
applyHostControlTokens(control, null);
applyHostControlToolbarTokens(control, null);
probe.dispose();
},
};
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more