Compare 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
illusia 6273185afa fix(updater): guard supervised installs and recover interrupted updates 2026-11-25 13:22:39 +08:00
ILLUSIA 0bc2e6cec8 Merge pull request #61 from OddTurtleHead/feat/console-self-update
feat: add verified console self-update for release packages
2026-11-25 13:16:51 +08:00
OddTurtleHead 82b58dbd61 fix(updater): recover interrupted swaps reliably across deployments
- Ship one POSIX launcher that repairs an interrupted code swap before Node
  starts, install it atomically before the swap, and keep it out of
  CODE_ENTRIES so it always survives at the install root.
- Restore from the in-progress task backup (state.json task.id ->
  backups/<id>) first, then the newest complete backup, so a leftover older
  backup never resurrects an obsolete build.
- Add exact-window SIGKILL recovery tests, including the stale-backup case.
- Gate Linux arm64 apply behind a capability check; add five-language copy
  and i18n labels for arm64, lock and unavailable errors.
- Harden the L2 runner handshake and recheck runner health before exit.
2026-11-24 03:13:32 +08:00
OddTurtleHead 699e606da5 fix: harden console self-update for real release packages
- Copy the restart runner with every runtime import (restart-runner.js,
  code-swap.js, version.js, update-state.js) and fail the apply when the
  runner exits during the startup grace window instead of reporting a task
  that never restarted.
- Accept official tar/zip relative symlinks that stay inside the extraction
  root while still refusing absolute, drive-qualified, escaping and hard-link
  entries.
- Have the restart runner take over the update lock for the same task, keep
  live or unreadable locks, and copy EXDEV entries into a temporary name
  before renaming so a partial copy cannot replace the previous tree.
- Disable console apply for Windows release packages with
  WINDOWS_APPLY_UNVERIFIED while still reporting available versions.
- Clarify in zh/en docs and five-language console copy that SHA256SUMS.txt is
  an integrity checksum, not a signature, and that verification targets the
  official Linux x64 build-release.yml package.
- Add tests for the failing EXDEV copy, live/unreadable/dead locks, same-task
  lock takeover, a real spawned runner compiled from source, and
  initialization leaving another live process's task untouched.
2026-11-24 02:40:08 +08:00
OddTurtleHead eb6c4ba857 fix: harden console self-update rollback and deployment checks
Recovered after the original 04bd82e object was lost from the worktree history; the working tree still contained the same ten-file fix (249 insertions).
2026-11-24 02:06:26 +08:00
OddTurtleHead 2de2e23fd3 feat: add verified console self-update for release packages
Check official GitHub Releases, require SHA256SUMS, safely extract and swap release-package code, roll back on failed health checks, and persist task state across restarts. Docker and source deployments stay check-only. Add updater tests, route security tests and five-language admin copy.
2026-11-24 01:44:24 +08:00
illusia ae6788a796 fix: correct recovery placement and quoted skin animations 2026-11-22 17:16:36 +08:00
ILLUSIA 9812a28e5f Merge pull request #60 from OddTurtleHead/fix/skin-css-hardening
feat: integrate host recovery controls with skins and improve compatibility
2026-11-22 17:12:32 +08:00
OddTurtleHead cc36bc4c64 fix: return floating host controls home only after a screen change
Live re-test of a1c8329 on open-voice-surface desktop: toasts no longer pull
the application-library launcher back, but opening the audio-settings modal
did. Its backdrop hid "Share accompaniment", the default bottom-right corner
looked free, the launcher went home, and right after Esc it still covered the
button.

854a488's return-home rule is meant for a stale spot picked for the previous
screen, so apply it only within the screen-change window (home <-> voice page,
skin switch); on the same screen a free-looking default corner may just be
hidden for a moment. The ts3-classic home-return case still passes (it goes
through screenChanged()).

Browser fixture: modal dialog over the corner (fails on a1c8329 and 854a488).
2026-11-16 00:37:46 +08:00
OddTurtleHead 8ca33fd77d fix: look through toasts when placing floating host controls
A toast passing over a skin control hid it from the hit test, so its corner
looked free: with 854a488's return-home rule the application-library launcher
jumped back to its default bottom-right corner on open-voice-surface desktop,
flapped as toasts came and went, and the flap freeze then parked it on
"Share accompaniment" for 10 s.

- Obstacle hit tests look through transient overlays (app.toast) and the other
  host floating control (elementsFromPoint); a modal backdrop or skin layer
  still hides a control.
- While frozen by the anti-flap guard, a control parked on a skin control may
  step off it once per freeze (confirm delay and 1 s interval still apply),
  then holds still.
- Tests: reachableThrough unit test; browser fixture replaying the toast
  sequence and the freeze escape (both fail on 854a488).
2026-11-16 00:24:20 +08:00
OddTurtleHead 99d7b86d09 fix: re-place floating host controls promptly on screen changes
Return to the default corner once it and the current spot are free, and
skip the move confirmation/minimum interval for ~1.5 s after the home <->
voice page switch or a skin switch, so a spot picked for the previous
screen no longer covers controls on the next one (e.g. Export identity).
2026-11-15 23:04:31 +08:00
OddTurtleHead 2b019d82ff fix: harden floating host-control avoidance after review
Independent review of 16e25ea (DeepSeek v4.1 Flash, Qwen4 Max) found the
runtime avoidance could flap, park on protected controls and drift from the
CSS on notched phones. Runtime only; still no skin.css restriction.

- Anti-flap: a move needs the collision to persist ~250 ms, moves are at least
  1 s apart, and more than 6 moves in 10 s park the control at its default
  corner for 10 s (an animated/hostile skin can no longer keep it moving).
- Protected parts now outweigh dialogs and the other host control; ordinary
  buttons inside the protected `app` root (or `home.footer`) are no longer
  weighted as protected.
- Never move onto the last pointer position or the focused control.
- Fold to the compact mark only when that frees at least one control (a
  full-screen click-away layer no longer hides the recovery buttons).
- Score with the live expanded size (language switch) and reset on resize;
  model margins include env(safe-area-inset-*) like the CSS.
- Skip invisible (opacity 0) controls; also count [tabindex], option/switch/
  checkbox/radio roles, iframes and media controls; count the other host
  control once; prefilter by candidate rects (cheap on 3 000-control skins);
  re-check after scrolls; ignore sticky :hover on touch; bind idempotently.
- Tests: weights, fold threshold, pointer, safe area, protected-vs-dialog,
  stability over repeated ticks, two host controls, anti-flap.
2026-11-15 21:38:39 +08:00
OddTurtleHead e46d7a0eb7 fix: move floating host controls off skin controls at runtime
The recovery capsule and the fallback application-library launcher float in
fixed viewport corners. In v0.3.2 that already covered the microphone in the
Persona/host-chrome skins, the whole Harbor audio dock, the Cancel/Create
buttons of mobile bottom sheets and a Send button behind the launcher.

Add host-floating-placement: every 400 ms (and shortly after each click) the
host samples the skin's visible, topmost interactive controls and moves the
floating control to the least-covering corner/edge position, weighting
protected parts and open dialogs higher, avoiding the other host floating
control, and folding the capsule to its mark when every position collides.
It never moves under the pointer or focus and leaves a docked (slotted)
capsule to the slot binding. Runtime only: no new skin.css restriction.
2026-11-15 20:59:48 +08:00
OddTurtleHead 0df25e4892 fix: close review gaps in host-control fonts, on-accent contrast and protected filter values
- Host-owned controls refuse font tokens naming the compiler's scoped skin
  font prefix (ws-), so a skin @font-face gated behind a non-matching @media
  (absent from document.fonts) cannot blank labels after a resize; the theme
  binding also re-reads tokens on viewport resize for @media-scoped tokens.
- A token palette is accepted only if black or white text reaches 4.5:1 on its
  accent; mid-tone accents (~4.23:1) now fall back as a group.
- Protected app-DOM controls reject var()/attr() for filter, clip and
  content-visibility, which could smuggle opacity(0)/rect(0,0,0,0)/hidden past
  the literal hide checks; literal filters and other parts are unchanged.
- Docs and tests updated (unit + headless-Chrome fixture).
2026-11-15 18:04:25 +08:00
OddTurtleHead a353c32892 fix: refresh host-control tokens on late skin CSS, resolve modern colours and refuse skin fonts
- bindHostControlTheme re-applies when <head> stylesheets or root attributes
  change, so a stored skin id themes the floating recovery capsule, skin-load
  banner and authorization dialog once its CSS actually arrives; the recovery
  root pass stands down while a slot binding owns the capsule tokens.
- The shadow-root probe converts oklch()/color-mix() results to sRGB via a
  1x1 canvas instead of silently dropping them to the default palette.
- Host-owned controls ignore font tokens naming a document @font-face, which
  could ship blank glyphs and erase the recovery/consent labels.
- Authorization body text uses the full sanitized foreground (the 76% mix
  could fall under the 4.5 contrast floor); theme refreshes before showModal.
- Browser fixture covers late CSS, oklch and font refusal; docs updated.
2026-11-15 17:14:42 +08:00
OddTurtleHead c1187d12d2 feat: let skins theme every protected control through skin.css and shared host tokens
App-DOM protected parts keep only hide/off-screen/disable guards; host-owned recovery capsule, skin-load banner and authorization dialog read one sanitized --skin-host-* token set with per-part overrides (--skin-recovery-*, --skin-load-recovery-*, --skin-permission-*) via the new host-control-tokens module.
2026-11-15 17:03:07 +08:00
OddTurtleHead 93d221c3ef fix: keep docked recovery capsule off protected controls and address slot review
- Fall back to the default corner when the docked capsule's footprint
  (largest observed size) overlaps a visible protected control; runtime
  check only, no new chrome.json or skin.css restriction.
- Demo skin docks at align:start, away from the audio dock buttons.
- Compact mode: tap/click pins it open (touch), shortcut expansion clears
  when focus leaves; the 5 s full-display hold starts on first dock.
- Built-in button border uses the skin accent only when visible on #fff7ed.
- probeColor no longer misreads a token equal to its sentinel.
- Periodic re-check survives an exception and fails safe to floating.
- Browser fixture exercises bindHostSlot: dock, fallback, anti-flap,
  protected cover, offscreen, unreadable tokens, dispose.
2026-11-15 15:43:08 +08:00
OddTurtleHead aefa0bc163 feat: let skins dock the recovery capsule into their layout with runtime fallback
- chrome.json#slots names an existing skin data-ws-part as anchor for host.recovery
  (align start/center/end, optional compact); host/trusted parts rejected as anchors
- reusable host-slot-placement module: positions the closed-shadow top-layer
  capsule over the anchor, re-checks visibility/size/on-screen/elementFromPoint,
  snaps back to the default corner on any failure with anti-flap re-slotting
- --skin-recovery-* tokens (accent/background/foreground/radius/font/size tier)
  sanitized with 28px minimum hit target and WCAG contrast fallback
- compact mode only after 5s full display post-activation; shortcut always full
- no new skin CSS compile-time restrictions; docs and host-chrome-demo updated
2026-11-15 15:00:24 +08:00
OddTurtleHead fa720bf260 fix: allow protected-part entrance animations and close remaining hide bypasses
Only inspect keyframe frames an animation can rest on, parse animation names correctly, and close remaining hide-selector and value bypasses while still allowing large layout restyles.
2026-11-15 12:13:18 +08:00
OddTurtleHead a4ae4de82f fix: close keyframe bypasses on protected controls without policing skin layout
Hold @keyframes to the same hide/yeet checks as regular declarations,
including escaped and namespaced animation names. Loosen decorative
host-chrome layout locks so open skins can restyle layout freely.
Listen for the recovery shortcut in the capture phase, move the
load-failure banner into the host-owned layer, and fix recovery
aria-labels.
2026-11-15 01:09:42 +08:00
152 changed files with 18739 additions and 660 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
+36 -8
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:
@@ -182,12 +182,9 @@ jobs:
cp "$runtime_root/bin/node" "$package_root/runtime/node"
cp "$runtime_root/LICENSE" "$package_root/runtime/NODE-LICENSE"
chmod 0755 "$package_root/runtime/node"
cat > "$package_root/start-webspeak.sh" <<'LAUNCHER'
#!/usr/bin/env sh
set -eu
cd -- "$(dirname -- "$0")"
exec "$PWD/runtime/node" "$PWD/dist/index.js"
LAUNCHER
# Ship the exact launcher the self-update installer and recovery
# tests use; never maintain a second launcher body in the workflow.
cp "$GITHUB_WORKSPACE/scripts/start-webspeak.sh" "$package_root/start-webspeak.sh"
chmod 0755 "$package_root/start-webspeak.sh"
smoke_root="$RUNNER_TEMP/${package_name}-smoke"
@@ -217,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 }}
+6 -3
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,10 +82,11 @@ 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,升级时保留它。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
数据保存在 `webspeak-data` volume,升级时保留它。Docker 控制台只能检查版本;升级请在宿主机执行 `docker compose pull && docker compose up -d`,且不要执行 `docker compose down -v`。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
Data persists in the `webspeak-data` volume. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
Data persists in the `webspeak-data` volume. On Docker, the console only checks versions; upgrade on the host with `docker compose pull && docker compose up -d` and never run `docker compose down -v`. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
<a id="documentation"></a>
@@ -96,6 +97,8 @@ Data persists in the `webspeak-data` volume. The Compose file uses host networki
- [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).
+28 -6
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.
@@ -103,7 +103,7 @@ docker compose ps
docker compose logs -f webspeak
```
Upgrade:
Upgrade from the host. The administration console can check for newer stable releases on Docker, but it cannot replace the container image from inside the container:
```bash
git pull --ff-only
@@ -111,12 +111,16 @@ docker compose pull
docker compose up -d
```
Do not run `docker compose down -v`; it removes the database and administrator settings.
Do not run `docker compose down -v`; it removes the `webspeak-data` volume, including the database and administrator settings.
### Release package
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
Linux x64 release packages that match the official `build-release.yml` layout can be upgraded from the administration console. It checks the official GitHub Releases, refuses a package without a matching `SHA256SUMS.txt` entry, replaces only application code and restarts the process. `SHA256SUMS.txt` is an integrity checksum only, not a digital signature. `data/`, `config.json`, `certs/`, installed skins and plugins are preserved. Export a backup before starting. Windows release packages can check for versions, but console apply is disabled until it is verified on a real Windows install; download the new package and replace it manually. Linux arm64 packages can be checked, but console apply is disabled because the in-place swap has not been verified on real arm64 hardware; download the new package and replace it manually. Docker and source deployments cannot apply an update from the console.
Console installation is limited to foreground Linux x64 packages. Instances managed by systemd, PM2 or Supervisor can still check releases and open release notes, but cannot apply them in the console. Stop the service, replace application files from the new package, and start the service again; preserve `data/`, `config.json` and `certs/`. A detached updater is not independent of the service manager.
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
### From source
@@ -134,6 +138,8 @@ npm start
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
The administration console can check for newer stable versions when running from source, but one-click apply is unavailable because the tree has no bundled Node.js runtime. Pull the source and rebuild after reviewing the release notes. The console never downloads or swaps source-tree files.
### First-time setup
1. Open `http://<your-host>:3040/admin`.
@@ -189,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
@@ -302,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`
@@ -341,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).
+30 -8
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) · 控制台一键更新、升级恢复与皮肤兼容性改进。
@@ -120,7 +120,7 @@ docker compose ps
docker compose logs -f webspeak
```
升级:
升级在宿主机执行。管理控制台在 Docker 部署中只能检查新版本,不能从容器内部替换镜像:
```bash
git pull --ff-only
@@ -128,12 +128,16 @@ docker compose pull
docker compose up -d
```
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
不要执行 `docker compose down -v`,否则会删除 `webspeak-data` volume,包括数据库和管理员设置。
### 发布包
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
Linux x64 发布包(已按官方 `build-release.yml` 产物形态验证)可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`SHA256SUMS.txt` 只是 SHA-256 校验和,不是数字签名。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Windows 发布包可以检查版本,但控制台应用更新尚未经真实 Windows 环境验证,因此已禁用,请下载新包后手动替换。Linux arm64 发布包可以检查版本,但由于原地替换尚未在真实 arm64 硬件验证,控制台应用已禁用;请下载新版发布包后手动替换。Docker 和源码运行不能在控制台应用更新。
控制台安装仅限前台运行的 Linux x64 发布包。通过 systemd、PM2 或 Supervisor 托管的实例仍可检查版本和查看发行说明,但不能在控制台直接安装。请停止服务,替换新发布包中的程序文件后再启动,并保留 `data/`、`config.json` 和 `certs/`。升级助手即使以独立子进程启动,也仍受服务管理器控制。
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
### 源码运行
@@ -151,6 +155,8 @@ npm start
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
源码运行时,管理控制台可以检查新的正式版本,但目录中没有捆绑的 Node.js 运行时,因此不能一键应用更新。请查看发行说明后拉取源码并重新构建;控制台不会下载或替换源码目录中的文件。
### 首次配置
1. 打开 `http://<你的主机>:3040/admin`。
@@ -208,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 候选
@@ -323,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`
@@ -360,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 的配置表单。插件页面可以打开对应仓库。
+251 -11
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 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
@@ -96,7 +98,7 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可
assets/background.webp # 可选:页面艺术素材
assets/brand.woff2 # 可选:自带字体
components.json # v3 可选:声明式组件或完整页面 surface
chrome.json # v3/v4 可选:宿主装饰隐藏与图标位图覆盖(见「chrome.json」章节)
chrome.json # v3/v4 可选:宿主装饰、图标位图与可信控件停靠(见「chrome.json」章节)
assets/icons/language.png # v3/v4 可选:工具栏图标位图覆盖素材
plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件
plugins/<plugin-id>/index.js # v4 插件代码,目前只校验和缓存
@@ -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`、`app.skin-load-recovery`、`skin.library`;`host.recovery` / `host.permission` 仅为概念标识(闭合 Shadow DOM + 顶层,无 CSS 钩子,见下文) |
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
@@ -435,10 +437,10 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
- 皮肤激活时,宿主在 `documentElement` 上设置 `data-ws-host-skin="<皮肤 ID>"`;停用或回退到内置皮肤时立即移除。
- 编译 `skin.css` 时,**只**命中下列宿主部件的单个选择器会被限定到 `:root[data-ws-host-skin="<皮肤 ID>"] …`,其余规则仍限定到 `.ws-skin-root[data-ws-skin="…"]`。宿主部件的选择器必须**以可主题化的 `[data-ws-part="host.…"]` 开头**,不能把 `:root`、`html`、`body` 或 `*:has(…)` 作为规则主体;`:root:has([data-ws-part="host.watermark"])` 一类写法会被拒绝。皮肤作者不能自己写 `html`、`body`、`data-ws-host-skin`、`data-ws-route`、`data-theme` 或 `data-ws-skin` 选择器,也不能在同一选择器里混用宿主部件与页面部件;宿主部件只对 schema v3/v4 开放皮肤生效。
- 宿主外壳的布局与层级由 WebSpeak 拥有:皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform` 等把 `host.plugins.overlay` 之类控件变成全屏遮罩。
- 宿主外壳的布局与层级:应用库外壳 `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,20 +455,231 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
### 恢复入口与授权对话框:结构上不可被皮肤触及
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或主题化的 CSS 钩子:当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们:
`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`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 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 现有快捷键或浏览器常用快捷键冲突。
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;无论胶囊是停靠、浮动还是被 `mode: "toolbar"` 替换,快捷键都会临时隐藏工具栏并显示完整胶囊。macOS 上 ⌥ 会把字母键变成派生字符(美式为 `®`),宿主同时按物理键码 `KeyR` 判定,所以该组合键仍然生效。它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅使用独立部件 `app.skin-load-recovery`(「切换到内置皮肤」),与恢复胶囊不是同一个钩子。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复入口停靠在皮肤界面里,而不是固定盖在左下角。默认仍是带胶囊壳的恢复胶囊;显式写 `mode: "toolbar"` 时改为无胶囊壳的宿主按钮,可直接并入皮肤顶栏。两种形态都是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它们的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
```json
"slots": {
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "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:
- v3 `components.json` 组件根:`skin.<page>.<componentId>`。
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊或 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-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。这些胶囊令牌也是 toolbar 颜色的最终回退;toolbar 的圆角、内边距、高度和阴影使用下一节自己的默认值,不会继承胶囊的 999px 圆角或浮动阴影。
| 令牌 | 规则 |
| --- | --- |
| `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 |
| `--skin-recovery-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 |
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 |
| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停、键盘聚焦或点按/轻触 ◈ 时展开为完整按钮;点按展开会保持到焦点离开胶囊、在胶囊外按下指针或按 Escape。新皮肤激活后、胶囊首次成功停靠起的约 5 秒内始终显示完整胶囊(从停靠时刻开始计时,皮肤加载慢也不会提前收起),避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
#### 工具栏模式:把恢复按钮并进皮肤顶栏(`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` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`(字面值)、`outline` 等纯视觉属性都可以写:
```css
[data-ws-part="voice.audio-dock.microphone"],
[data-ws-part="auth.password.dialog"],
[data-ws-part="home.footer.clear"] {
color: var(--skin-ink);
background: linear-gradient(135deg, #0f172a, #1e3a5f);
border: 2px solid var(--skin-accent);
border-radius: 16px;
font: 600 14px/1.4 Tahoma, "Segoe UI", sans-serif;
padding: 10px 16px;
min-width: 56px;
min-height: 56px;
box-shadow: 0 8px 24px #0006;
}
```
以下规则仍会被拒绝,因为它们会隐藏、禁用或把控件移出视口:`display:none`、`visibility:hidden/collapse`、`opacity:0`、`pointer-events:none`、使 `clip`/`clip-path`/`mask` 完全裁掉内容、`transform`/`scale` 缩到 0、`inset`/`top`/`left`/`margin` 等把控件推到视口外,以及在这些隐藏/移动属性上使用 `var()`/`attr()`。`margin` 仍算移动属性,所以 `margin: var(--skin-gap)` 会被拒绝;普通的小 `margin` 数值可以写。自定义变量仍然只能使用 `--skin-` 前缀。
个别受保护部件的子元素(例如音频面板和音频设置里的 `<input type="range">`)由 Vue 写入内联 `style`;要给滑轨本身换肤,用视觉属性的 `!important` 覆盖即可,受保护的外壳不受影响。
**宿主自有的受保护控件。** `host.recovery`、`app.skin-load-recovery` 横幅和授权对话框在闭合 Shadow DOM 内,皮肤 CSS 不能命中。宿主提供一组统一的令牌;皮肤把变量写在活动皮肤根(`:root`,编译后就是皮肤根)上即可,恢复胶囊也接受写在锚点或其祖先上的值:
| 控件 | 每部件前缀 | 说明 |
| --- | --- | --- |
| `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 |
| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠。令牌取自横幅出现时的**活动**皮肤:加载失败后宿主会退回内置皮肤(内置皮肤不声明令牌),所以失败皮肤自己的值通常不会作用在自己的横幅上,横幅保持默认琥珀色 |
| 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 |
每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如:
```css
:root {
--skin-host-accent: #47dcc4;
--skin-host-background: #0b1418;
--skin-host-foreground: #edf8f5;
--skin-host-border: #2a5a54;
--skin-host-radius: 10px;
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
--skin-host-size: medium;
/* 只覆盖恢复胶囊,其他宿主控件继续使用全局值 */
--skin-recovery-background: #102030;
}
```
宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式、窗口尺寸变化让 `@media` 里的令牌生效时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
- 背景强制不透明(alpha 视为 1)。
- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`,或带有编译器给皮肤字体加的 `ws-` 作用域前缀(包括放在暂未生效的 `@media` 里的字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白;如果黑白两种文字在强调色上都达不到 4.5,这组颜色同样整体回退到宿主默认。
- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。
`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
示例(v3 `skin.css`):
@@ -494,7 +707,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
| `home.toolbar.settings` | 首页工具栏设置图标 |
| `voice.performance` | 语音页 Voice status / 性能触发器图标 |
### `chrome.json`:声明式显示 / 隐藏与图标位图覆盖
### `chrome.json`:声明式显示 / 隐藏、图标位图覆盖与控件停靠
v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB:
@@ -507,6 +720,9 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
"language.trigger": "assets/icons/language.png",
"skin.trigger": "assets/icons/skin.png",
"host.plugins.launcher": "assets/icons/apps.png"
},
"slots": {
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
}
}
```
@@ -516,6 +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`(整组)或 `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()` 仍走包内资源解析,无法引用外部地址。
@@ -618,9 +856,11 @@ v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显
[data-ws-part="host.plugins.launcher"]
```
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名;受保护控件上的 `filter` / `-webkit-filter`、`clip` 与 `content-visibility` 同样只接受字面值,不能用 `var()` / `attr()`(否则变量可以绕过上面的隐藏检查),其他部件不受影响。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
+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.
@@ -8,5 +8,8 @@
"host.plugins.launcher": "assets/icons/apps.png",
"home.toolbar.settings": "assets/icons/settings.png",
"voice.performance": "assets/icons/status.png"
},
"slots": {
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
"version": "1.0.0",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "Minimal open skin demonstrating host chrome theming, declarative hiding and bitmap icon overrides.",
"description": "Minimal open skin demonstrating host chrome theming, protected-control theming, declarative hiding and bitmap icon overrides.",
"entry": "skin.css",
"chrome": "chrome.json",
"minAppVersion": "0.3.2"
+64
View File
@@ -7,6 +7,26 @@
--skin-panel: #ffffff;
--skin-border: #c9c9c9;
--skin-text: #141414;
/* Host-owned protected controls: one global set, per-part overrides below. */
--skin-host-accent: #1d4f9c;
--skin-host-background: #ffffff;
--skin-host-foreground: #141414;
--skin-host-border: #9db6b2;
--skin-host-radius: 10px;
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
--skin-host-size: medium;
--skin-recovery-accent: #1d4f9c;
--skin-recovery-background: #ffffff;
--skin-recovery-foreground: #141414;
--skin-recovery-border: #9db6b2;
--skin-recovery-radius: 999px;
--skin-load-recovery-accent: #b45309;
--skin-load-recovery-background: #fff7ed;
--skin-load-recovery-foreground: #7c2d12;
--skin-permission-accent: #1d4f9c;
--skin-permission-background: #ffffff;
--skin-permission-foreground: #141414;
}
[data-ws-page] {
@@ -25,6 +45,50 @@
[data-ws-part="voice.audio-dock"] {
border-top: 1px solid var(--skin-border);
background: #f7f9fb;
/* Fold the trusted recovery capsule into the audio dock (chrome.json#slots). */
--skin-recovery-accent: #1d4f9c;
--skin-recovery-background: #ffffff;
--skin-recovery-foreground: #141414;
--skin-recovery-radius: 999px;
--skin-recovery-font: Tahoma, "Segoe UI", sans-serif;
--skin-recovery-size: small;
}
/* --- Protected app-DOM controls: purely visual theming is allowed --- */
[data-ws-part="voice.audio-dock.microphone"] button,
[data-ws-part="voice.audio-dock.output"] button,
[data-ws-part="voice.connection-status.reconnect"],
[data-ws-part="home.footer.clear"] {
color: #141414;
background: linear-gradient(180deg, #ffffff, #eef3fa);
border: 1px solid var(--skin-accent);
border-radius: 8px;
font-family: Tahoma, "Segoe UI", sans-serif;
font-size: 12px;
padding: 8px 12px;
min-height: 44px;
box-shadow: 0 2px 6px #1d4f9c22;
}
[data-ws-part="voice.audio-dock.microphone"] button:hover,
[data-ws-part="voice.audio-dock.output"] button:hover,
[data-ws-part="voice.connection-status.reconnect"]:hover,
[data-ws-part="home.footer.clear"]:hover {
background: #e7eefb;
}
[data-ws-part="auth.password.dialog"],
[data-ws-part="voice.audio-settings"] {
background: #ffffff;
border: 2px solid var(--skin-accent);
border-radius: 18px;
box-shadow: 0 18px 48px #1d4f9c33;
}
[data-ws-part="auth.password.dialog"] h2,
[data-ws-part="voice.audio-settings"] h2 {
color: var(--skin-accent);
letter-spacing: .01em;
}
/* --- Host chrome (outside .ws-skin-root) --- */
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/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/test/host-chrome-recovery.test.mjs",
"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",
+209
View File
@@ -0,0 +1,209 @@
#!/usr/bin/env sh
# WebSpeak official release launcher.
#
# This file is the single source of truth for the launcher shipped in release
# packages: .github/workflows/build-release.yml copies it verbatim, and the
# self-update pre-swap installer copies the same file from the staged package.
# Keep it a plain POSIX shell script: it must be able to repair an interrupted
# code swap before Node (dist/index.js) is available at all.
set -eu
cd -- "$(dirname -- "$0")"
# Mirrors src/index.ts: a custom data directory is the only supported override.
data_dir="${WEBSPEAK_DATA_DIR:-$PWD/data}"
backups="$data_dir/updates/backups"
# Only executable code is swapped by the updater. data/, config.json, certs/,
# identities, skins and plugins are deliberately never listed here.
code_entries="dist web/dist node_modules runtime package.json package-lock.json README.md LICENSE config.example.json start-webspeak.cmd"
required_entries="dist/index.js web/dist/index.html node_modules package.json runtime/node"
code_missing() {
for entry in $required_entries; do
if [ ! -e "$entry" ]; then
return 0
fi
done
return 1
}
# A backup can only repair 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
[ -e "$1/$entry" ] || return 1
done
return 0
}
# During the first phase of a swap, only some old entries have been moved.
# The rest still live at the install root. The current task can be recovered
# from that union, including a kill between rename and manifest persistence.
# Never combine a stale task's partial backup with this install.
task_backup_can_repair() {
[ -f "$1/.webspeak-swap.json" ] || return 1
for entry in $required_entries; do
if [ ! -e "$1/$entry" ] && [ ! -e "$entry" ]; then
return 1
fi
done
return 0
}
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
# root aside, so a later restore never mistakes it for the old tree.
for entry in $code_entries; do
if [ -e "$entry" ] && [ -e "$backup/$entry" ]; then
rejected="$backup/rejected/$entry"
rejected_parent="${rejected%/*}"
mkdir -p "$rejected_parent"
if [ -e "$rejected" ]; then
rm -rf -- "$entry"
else
mv -- "$entry" "$rejected"
fi
fi
done
# Put back every complete entry recorded by the swap manifest.
for entry in $code_entries; do
if [ ! -e "$entry" ] && [ -e "$backup/$entry" ]; then
parent="${entry%/*}"
if [ "$parent" != "$entry" ]; then
mkdir -p "$parent"
fi
mv -- "$backup/$entry" "$entry"
fi
done
}
if 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. 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
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}"
backup_is_complete "$backup" || continue
if [ -z "$restore_backup" ] || [ "$backup" -nt "$restore_backup" ]; then
restore_backup="$backup"
fi
done
fi
if [ -z "$restore_backup" ]; then
echo "WebSpeak update was interrupted and automatic recovery from $backups failed." >&2
exit 1
fi
restore_from_backup "$restore_backup"
if code_missing; then
echo "WebSpeak update was interrupted and automatic recovery from $restore_backup failed." >&2
exit 1
fi
fi
release_recovery_lock
exec "$PWD/runtime/node" "$PWD/dist/index.js"
+80
View File
@@ -12,6 +12,7 @@ import { createPluginAdminRouter } from "../plugins/admin-router.js";
import type { PluginRegistry } from "../plugins/registry.js";
import type { PluginStore } from "../plugins/store.js";
import type { PluginRuntime } from "../plugins/runtime.js";
import { UpdateError, type UpdateService } from "../updater/update-service.js";
export interface AdminConnectionRecord {
id: string;
@@ -45,6 +46,9 @@ export interface AdminRouterOptions {
pluginRegistry?: PluginRegistry;
pluginStore?: PluginStore;
pluginRuntime?: PluginRuntime;
updateService?: UpdateService;
/** Stops the current process after the update response has been flushed. */
restartAfterUpdate?: () => void;
startedAt: number;
clientIp?: (request: Request) => string;
}
@@ -414,6 +418,63 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
}
});
router.get("/update", (_request, response) => {
if (!options.updateService) {
response.json({
currentVersion: options.version ?? "0.0.0",
deployment: {
mode: "source",
platform: process.platform,
architecture: process.arch,
applyAllowed: false,
reasonCode: "UPDATE_UNAVAILABLE",
upgradePath: "source",
},
task: null,
});
return;
}
response.json(options.updateService.getStatus());
});
router.post("/update/check", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
if (!options.updateService) {
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
return;
}
try {
response.json(await options.updateService.checkForUpdates());
} catch (error: unknown) {
sendUpdateError(response, error);
}
});
router.post("/update/apply", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
if (!options.updateService) {
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
return;
}
if (!options.restartAfterUpdate) {
response.status(503).json({ ok: false, code: "UPDATE_RESTART_UNAVAILABLE" });
return;
}
try {
const body = asRecord(request.body);
const version = readString(body, "version", 32);
const confirmVersion = readString(body, "confirmVersion", 32);
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
const task = await options.updateService.applyUpdate(version, confirmVersion);
options.service.database.addAudit("ADMIN_UPDATE_STARTED", { version });
response.status(202).json({ ok: true, task });
// Do not wait for the response to finish: a reverse proxy or a client
// that disconnects early must not leave the restart runner waiting for
// this process until its timeout expires.
setTimeout(() => options.restartAfterUpdate?.(), 250).unref();
} catch (error: unknown) {
sendUpdateError(response, error);
}
});
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
@@ -554,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,
@@ -814,3 +882,15 @@ function sendAdminError(response: Response, error: unknown): void {
}
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
}
function sendUpdateError(response: Response, error: unknown): void {
if (error instanceof UpdateError) {
response.status(error.statusCode).json({ ok: false, code: error.code, message: error.message });
return;
}
if (error instanceof AdminInputError) {
response.status(400).json({ ok: false, code: error.code });
return;
}
response.status(500).json({ ok: false, code: "UPDATE_FAILED" });
}
+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,
+202
View File
@@ -0,0 +1,202 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { mkdtempSync, rmSync } from "node:fs";
import http from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import express from "express";
import type { Logger } from "../logger.js";
import { AdminService } from "./admin-service.js";
import { AdminSessionStore } from "./admin-session.js";
import { createAdminRouter } from "./admin-router.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { UpdateError, type UpdateService } from "../updater/update-service.js";
import type { UpdateCheckView, UpdateStatusView, UpdateTaskView } from "../shared/update.js";
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
const statusView: UpdateStatusView = {
currentVersion: "0.3.2",
deployment: {
mode: "release-package", platform: "linux", architecture: "x64",
applyAllowed: true, reasonCode: null, upgradePath: "release-package",
},
task: null,
};
const taskView: UpdateTaskView = {
id: "upd_route_test", status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
};
const checkView: UpdateCheckView = {
currentVersion: "0.3.2",
releases: [{
version: "0.4.0", tag: "v0.4.0", publishedAt: "2026-01-01T00:00:00.000Z",
releaseUrl: "https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.4.0",
assetName: "webspeak-webclient-v0.4.0-linux-x64.tar.gz", assetSize: 10,
assetAvailable: true, hasChecksums: true, digest: null, canApply: true, blockedReason: null,
}],
};
interface Fixture {
origin: string;
service: AdminService;
database: WebSpeakDatabase;
applyCalls: Array<[string, string]>;
restarted: () => boolean;
login(): Promise<{ cookie: string; csrf: string }>;
post(route: string, body: unknown, headers?: Record<string, string>): Promise<Response>;
}
async function fixture(t: TestContext, options: { updateService?: boolean } = {}): Promise<Fixture> {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-routes-"));
const database = new WebSpeakDatabase(path.join(directory, "test.db"));
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"), undefined, "0.3.2");
await service.initialize();
await service.changePassword("test-only-admin-password");
const applyCalls: Array<[string, string]> = [];
let restarted = false;
const updateService = {
getStatus: () => statusView,
checkForUpdates: async () => checkView,
applyUpdate: async (version: string, confirmVersion: string) => {
applyCalls.push([version, confirmVersion]);
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "confirmation mismatch");
return taskView;
},
} as unknown as UpdateService;
const app = express();
app.use(express.json());
app.use("/api/admin", createAdminRouter({
service, sessions: new AdminSessionStore(), logger,
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now(), version: "0.3.2",
...(options.updateService === false ? {} : { updateService, restartAfterUpdate: () => { restarted = true; } }),
}));
const server = app.listen(0, "127.0.0.1");
await new Promise<void>((resolve) => server.once("listening", resolve));
const address = server.address();
assert.ok(address && typeof address !== "string");
const origin = `http://127.0.0.1:${address.port}`;
t.after(async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
database.close();
rmSync(directory, { recursive: true, force: true });
});
const post = (route: string, body: unknown, headers: Record<string, string> = {}) => fetch(`${origin}/api/admin${route}`, {
method: "POST", headers: { origin, "content-type": "application/json", ...headers }, body: JSON.stringify(body),
});
const login = async () => {
const response = await post("/login", { username: "admin", password: "test-only-admin-password" });
assert.equal(response.status, 200);
const body = await response.json() as { csrfToken: string };
return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
};
return { origin, service, database, applyCalls, restarted: () => restarted, login, post };
}
test("update routes require an authenticated session", async t => {
const f = await fixture(t);
assert.equal((await fetch(`${f.origin}/api/admin/update`)).status, 401);
assert.equal((await f.post("/update/check", {})).status, 401);
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" })).status, 401);
});
test("update routes reject missing CSRF tokens and cross-origin requests", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const noCsrf = await f.post("/update/check", {}, { cookie });
assert.equal(noCsrf.status, 403);
assert.equal((await noCsrf.json() as { code: string }).code, "CSRF_REJECTED");
const crossOrigin = await fetch(`${f.origin}/api/admin/update/apply`, {
method: "POST",
headers: { origin: "https://evil.example", cookie, "x-csrf-token": csrf, "content-type": "application/json" },
body: JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" }),
});
assert.equal(crossOrigin.status, 403);
assert.equal((await crossOrigin.json() as { code: string }).code, "ORIGIN_REJECTED");
const wrongType = await fetch(`${f.origin}/api/admin/update/check`, {
method: "POST",
headers: { origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "text/plain" },
body: "{}",
});
assert.equal(wrongType.status, 415);
assert.equal((await wrongType.json() as { code: string }).code, "JSON_REQUIRED");
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 200);
});
test("apply requires version and confirmVersion to match before touching the service", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.1" }, { cookie, "x-csrf-token": csrf });
assert.equal(response.status, 400);
assert.equal((await response.json() as { code: string }).code, "UPDATE_CONFIRMATION_REQUIRED");
assert.deepEqual(f.applyCalls, []);
const missing = await f.post("/update/apply", { version: "0.4.0" }, { cookie, "x-csrf-token": csrf });
assert.equal(missing.status, 400);
assert.deepEqual(f.applyCalls, []);
});
test("a confirmed apply returns the task and stops the process after the response", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf });
assert.equal(response.status, 202);
const body = await response.json() as { ok: boolean; task: UpdateTaskView };
assert.equal(body.ok, true);
assert.equal(body.task.id, "upd_route_test");
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
assert.ok(f.database.recentAudit(10).some((event) => event.event === "ADMIN_UPDATE_STARTED"));
await new Promise<void>((resolve) => setTimeout(resolve, 400));
assert.equal(f.restarted(), true);
});
test("a client that disconnects before the response still schedules the restart", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const body = JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" });
const url = new URL(`${f.origin}/api/admin/update/apply`);
const request = http.request({
hostname: url.hostname, port: url.port, path: url.pathname, method: "POST",
headers: {
origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "application/json",
"content-length": Buffer.byteLength(body),
},
});
request.on("error", () => { /* Expected once the socket is destroyed. */ });
request.end(body);
const deadline = Date.now() + 2_000;
while (f.applyCalls.length === 0 && Date.now() < deadline) await new Promise<void>((resolve) => setTimeout(resolve, 20));
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
// Close the connection without consuming the response. The restart must not
// depend on the response finish event.
request.destroy();
await new Promise<void>((resolve) => setTimeout(resolve, 700));
assert.equal(f.restarted(), true);
});
test("update status and check return the service projections", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
assert.equal(status.status, 200);
assert.deepEqual(await status.json(), statusView);
const check = await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf });
assert.equal(check.status, 200);
assert.deepEqual(await check.json(), checkView);
});
test("deployments without an update service expose a read-only source status", async t => {
const f = await fixture(t, { updateService: false });
const { cookie, csrf } = await f.login();
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
assert.equal(status.status, 200);
const body = await status.json() as UpdateStatusView;
assert.equal(body.deployment.mode, "source");
assert.equal(body.deployment.applyAllowed, false);
assert.equal(body.deployment.reasonCode, "UPDATE_UNAVAILABLE");
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 503);
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf })).status, 503);
});
+38 -1
View File
@@ -3,8 +3,10 @@ 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";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -17,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") {
@@ -42,6 +45,8 @@ async function main() {
CONFIG_PATH,
undefined,
APP_VERSION,
undefined,
VOICE_ICE_CONFIG,
);
await adminService.initialize();
removeObsoleteBootstrapFile();
@@ -52,17 +57,48 @@ async function main() {
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
const updateService = new UpdateService({
rootDir: ROOT_DIR,
dataDir: DATA_DIR,
currentVersion: APP_VERSION,
logger,
port: APP_PORT,
https: hasCert,
});
updateService.initialize();
const webServer = createWebServer({
let webServer: ReturnType<typeof createWebServer> | undefined;
webServer = createWebServer({
port: APP_PORT,
version: APP_VERSION,
logFile: path.join(LOG_DIR, "webspeak.log"),
staticDir: STATIC_DIR,
certDir: hasCert ? CERT_DIR : undefined,
updateService,
restartAfterUpdate: () => {
void (async () => {
if (!updateService.runnerStillHealthy()) {
// 202 already promised a restart, but the helper died before this
// process left. Stay up and reconcile instead of reporting success
// and silently abandoning the update.
logger.warn("The restart runner is no longer healthy; keeping this process and reconciling the update state");
try { updateService.initialize(); }
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Update state could not be reconciled"); }
return;
}
logger.info("Stopping for scheduled update");
try { await webServer?.stop(); }
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); }
database.close();
process.exit(0);
})();
},
voiceBridgeOptions: {
joinTickets,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
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
@@ -133,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,
+5
View File
@@ -22,6 +22,7 @@ import type { PluginRegistry } from "../plugins/registry.js";
import { PluginRuntime } from "../plugins/runtime.js";
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
import { parseHiddenHostParts } from "../shared/skin-chrome.js";
import type { UpdateService } from "../updater/update-service.js";
export interface WebServerOptions {
port: number;
@@ -37,6 +38,8 @@ export interface WebServerOptions {
logger: Logger;
nextVisitorNumber?: () => number;
visitorCount?: () => number;
updateService?: UpdateService;
restartAfterUpdate?: () => void;
}
export interface WebServer {
@@ -301,6 +304,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
skinRegistry: options.skinRegistry,
pluginRegistry: options.pluginRegistry,
pluginRuntime,
updateService: options.updateService,
restartAfterUpdate: options.restartAfterUpdate,
version: options.version,
logFile: options.logFile,
startedAt,
+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;
+59
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,
});
@@ -93,6 +99,52 @@ const tsAdminOverview = object({
});
const savedTsAdminSettings = object({ ok: choice(true), settings: tsAdminSettings });
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
const updateStep = object({
name: text,
status: choice("running", "succeeded", "failed"),
at: text,
detail: optional(text),
});
const updateTask = object({
id: text,
status: choice("downloading", "verifying", "extracting", "staging", "restarting", "succeeded", "failed"),
fromVersion: text,
targetVersion: text,
startedAt: text,
updatedAt: text,
finishedAt: nullable(text),
errorCode: nullable(text),
errorMessage: nullable(text),
rolledBack: boolean,
steps: array(updateStep),
});
const updateDeployment = object({
mode: choice("docker", "release-package", "source"),
platform: text,
architecture: text,
applyAllowed: boolean,
reasonCode: nullable(text),
upgradePath: choice("docker-compose", "release-package", "source"),
});
const updateStatus = object({
currentVersion: text,
deployment: updateDeployment,
task: nullable(updateTask),
});
const updateRelease = object({
version: text,
tag: text,
publishedAt: text,
releaseUrl: text,
assetName: text,
assetSize: number,
assetAvailable: boolean,
hasChecksums: boolean,
digest: nullable(text),
canApply: boolean,
blockedReason: nullable(text),
});
const updateCheck = object({ currentVersion: text, releases: array(updateRelease) });
export const adminResponses = {
session(value: unknown) {
@@ -127,6 +179,9 @@ export const adminResponses = {
latencyMs: number, serverName: nullable(text), requiresPassword: boolean,
packetLossPercent: optional(number), attempts: optional(number), successfulAttempts: optional(number), errorCode: optional(text),
}),
updateStatus,
updateCheck,
updateApplied: object({ ok: choice(true), task: updateTask }),
};
export type AdminSettings = ReturnType<typeof settings>;
@@ -135,3 +190,7 @@ export type AdminSession = ReturnType<typeof session>;
export type ManagedInvite = ReturnType<typeof invite>;
export type AdminLog = ReturnType<typeof logEntry>;
export type AdminConnectionRecord = ReturnType<typeof connection>;
export type AdminUpdateTask = ReturnType<typeof updateTask>;
export type AdminUpdateStatus = ReturnType<typeof updateStatus>;
export type AdminUpdateCheck = ReturnType<typeof updateCheck>;
export type AdminUpdateRelease = ReturnType<typeof updateRelease>;
+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") {
+186 -5
View File
@@ -1,15 +1,26 @@
import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js";
import {
DECORATIVE_PART_IDS,
HOST_SKIN_ATTRIBUTE,
HOST_SLOTTABLE_PART_IDS,
SKIN_ICON_SLOT_IDS,
TRUSTED_PART_IDS,
isHostPart,
} from "./skin-visual-parts.js";
/**
* `chrome.json` is an optional, declarative companion to an open skin.
*
* It describes two host-chrome capabilities that CSS alone cannot express
* safely:
* It describes host-chrome capabilities that CSS alone cannot express safely:
* - `visibleParts`: decorations the skin asks the host to render. This is the
* only opt-in; official and built-in skins stay clean.
* - `hiddenParts`: non-critical decorations the skin wants collapsed by
* default. Only explicitly optional parts are accepted.
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
* - `slots`: declarative anchors for trusted host controls. A skin never
* receives the control; it only names a part it already renders so the
* host can position its own top-layer capsule (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
* document, so a package accepted by one is accepted by the other.
@@ -18,10 +29,22 @@ import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./
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/";
/**
* Anchor names are `data-ws-part` values, including host-rendered v3 component
* parts (`skin.<page>.<component>.part-<name>`) and v4 runtime plugin parts
* (`skin.<page>.runtime_plugin_<plugin>__<component>.part-<name>`). Each
* dot-separated segment follows the same identifier grammar as other part
* names; the generous overall limit covers a namespaced runtime plugin.
*/
export const SKIN_SLOT_ANCHOR_MAX_LENGTH = 240;
const PART_NAME_SEGMENT = /^[-_a-z][-_a-z0-9]*$/i;
const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]);
/**
@@ -45,6 +68,45 @@ export interface SkinChromeDocument {
*/
visibleParts?: string[];
icons: Record<string, string>;
/** Protected host controls folded into skin-owned layout anchors. */
slots?: Partial<Record<string, SkinChromeSlot>>;
}
export type SkinChromeSlotAlign = "start" | "center" | "end";
/**
* 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.
* 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 (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 {
@@ -94,6 +156,55 @@ export function normalizeSkinIconPath(raw: unknown): string {
return path;
}
/**
* A slot anchor is an existing part name, never host-owned UI: a skin must not
* be able to park a protected control on the launcher, the authorization
* dialog or another trusted element it could then cover or remove.
*/
function normalizeSlotAnchor(raw: unknown): string {
if (typeof raw !== "string" || !raw || raw.length > SKIN_SLOT_ANCHOR_MAX_LENGTH) {
return reject(`A slot anchor must be a part name of at most ${SKIN_SLOT_ANCHOR_MAX_LENGTH} characters.`, "SKIN_CHROME_SLOT_INVALID");
}
const segments = raw.split(".");
if (segments.some((segment) => !PART_NAME_SEGMENT.test(segment))) {
return reject(`A slot anchor is not a valid part name: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
}
if (isHostPart(raw) || TRUSTED_PART_IDS.has(raw)) {
return reject(`A slot anchor cannot point at trusted host UI: ${raw}.`, "SKIN_CHROME_SLOT_INVALID");
}
return raw;
}
/**
* 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) {
@@ -104,7 +215,7 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); }
if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID");
for (const key of Object.keys(raw)) {
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") {
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons" && key !== "slots") {
return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID");
}
}
@@ -151,7 +262,77 @@ export function parseSkinChromeDocument(source: string): SkinChromeDocument {
icons[slot] = normalizeSkinIconPath(path);
}
}
return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons };
let slots: Partial<Record<string, SkinChromeSlot>> | undefined;
if (raw.slots !== undefined) {
if (!isRecord(raw.slots)) {
return reject("slots must be an object mapping protected part names to anchors.", "SKIN_CHROME_SLOT_INVALID");
}
const entries = Object.entries(raw.slots);
if (entries.length > SKIN_CHROME_MAX_SLOTS) {
return reject(`A skin may declare at most ${SKIN_CHROME_MAX_SLOTS} slots.`, "SKIN_CHROME_SLOT_INVALID");
}
slots = Object.create(null) as Partial<Record<string, SkinChromeSlot>>;
for (const [part, value] of entries) {
if (!HOST_SLOTTABLE_PART_IDS.has(part)) {
return reject(`Unknown slottable host part: ${part}.`, "SKIN_CHROME_SLOT_INVALID");
}
if (!isRecord(value)) {
return reject(`Slot ${part} must be an object.`, "SKIN_CHROME_SLOT_INVALID");
}
for (const key of Object.keys(value)) {
if (key !== "anchor" && key !== "align" && key !== "compact" && key !== "mode" && key !== "appearance") {
return reject(`Slot ${part} contains an unsupported field: ${key}.`, "SKIN_CHROME_SLOT_INVALID");
}
}
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");
}
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",
);
}
}
return {
schemaVersion: 1,
hiddenParts,
...(visibleParts ? { visibleParts } : {}),
icons,
...(slots ? { slots } : {}),
};
}
/**
+526 -6
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js";
import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js";
import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js";
import { DECORATIVE_PART_IDS, HOST_SLOTTABLE_PART_IDS } from "./skin-visual-parts.js";
import {
compileSkinChromeCss,
DEFAULT_HIDDEN_HOST_PARTS,
@@ -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",
@@ -196,6 +214,142 @@ test("chrome.json declares hidden parts and icon bitmaps, with path and size val
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/);
});
test("chrome.json slots accept skin-owned anchors and reject trusted host UI", () => {
assert.deepEqual([...HOST_SLOTTABLE_PART_IDS], [
"host.recovery",
"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, appearance: "label" },
},
}));
assert.deepEqual(explicit.slots?.["host.recovery"], {
anchor: "voice.audio-dock",
align: "start",
compact: true,
mode: "capsule",
appearance: "label",
});
// 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: {
"host.recovery": { anchor: "skin.voice.harbor-dock.part-anchor" },
},
}));
assert.deepEqual(defaults.slots?.["host.recovery"], {
anchor: "skin.voice.harbor-dock.part-anchor",
align: "end",
compact: false,
mode: "capsule",
appearance: "label",
});
assert.doesNotThrow(() => parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: { "host.recovery": { anchor: "skin.voice.runtime_plugin_voice-surface__dock.part-anchor" } },
})));
// Slot declarations are runtime input, not compiled CSS: the generated host
// stylesheet must stay exactly as empty as before.
assert.equal(compileSkinChromeCss(explicit, "demo-skin"), "");
const invalidDocuments: Array<[unknown, RegExp]> = [
[{ schemaVersion: 1, slots: [] }, /must be an object/],
[{ schemaVersion: 1, slots: { "host.permission": { anchor: "voice.audio-dock" } } }, /Unknown slottable host part/],
[{ schemaVersion: 1, slots: { "host.recovery": "voice.audio-dock" } }, /must be an object/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "host.plugins.launcher" } } }, /trusted host UI/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.connection-status" } } }, /trusted host UI/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "app" } } }, /trusted host UI/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", align: "left" } } }, /invalid align/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", compact: "yes" } } }, /compact must be a boolean/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "voice.audio-dock", extra: true } } }, /unsupported field/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "../escape" } } }, /not a valid part name/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "Voice Audio Dock" } } }, /not a valid part name/],
[{ schemaVersion: 1, slots: { "host.recovery": { anchor: "" } } }, /at most 240 characters/],
[{ 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));
}
});
test("instance-level hidden parts ignore unknown and protected names", () => {
assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]);
assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]);
@@ -247,10 +401,12 @@ test("protected controls cannot be hidden through variables or moved off-screen"
'[data-ws-part="voice.audio-dock"] { margin-left: -9999px; }',
'[data-ws-part="voice.audio-dock"] { margin-inline: -9999px; }',
'[data-ws-part="voice.audio-dock"] { margin-block-start: -1200px; }',
'[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }',
'[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -1000px; }',
'[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }',
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }',
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 5000px); }',
'[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }',
'[data-ws-part="voice.audio-dock"] { margin-left: -1e4px; }',
'[data-ws-part="voice.audio-dock"] { transform: translateX(calc(2px*-1000)); }',
]) {
assert.throws(() => compile(css), /must remain on screen/, css);
}
@@ -263,8 +419,18 @@ test("protected controls cannot be hidden through variables or moved off-screen"
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { background: var(--skin-panel); }'));
assert.doesNotThrow(() => compile(':root { --skin-hide: none; } [data-ws-part="host.watermark"] { display: var(--skin-hide); }'));
// A small margin on a protected control and a decorative dock child are still
// legitimate v3 theming.
// legitimate v3 theming. Ordinary placement is no longer mistaken for a
// yeet: only values clearly beyond a viewport are rejected.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin-top: 120px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: 0 auto 120px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { top: 100%; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { scale: 100%; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { rotate: 4deg; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { transform: rotate(8deg); }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }'));
// The off-screen guard only protects the subject, not decorative or
// non-protected parts.
@@ -272,12 +438,76 @@ test("protected controls cannot be hidden through variables or moved off-screen"
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }'));
});
test("protected controls accept every purely visual property", () => {
const themed = compileSkinCss(`
:root {
--skin-ink: #f8fafc;
--skin-card: #0f172a;
--skin-line: #38bdf8;
--skin-pad: 14px;
--skin-size: 56px;
--skin-shadow: 0 10px 30px #0006;
}
[data-ws-part="voice.audio-dock.microphone"],
[data-ws-part="voice.connection-status.reconnect"],
[data-ws-part="home.footer.clear"],
[data-ws-part="auth.password.dialog"] {
color: var(--skin-ink);
background-color: var(--skin-card);
background-image: linear-gradient(135deg, #123456, #654321), url("assets/protected-pattern.png");
border: 2px solid var(--skin-line);
border-radius: 18px;
font-family: var(--skin-font, Tahoma, "Segoe UI", sans-serif);
font-size: 15px;
padding: var(--skin-pad);
width: var(--skin-size);
height: var(--skin-size);
box-shadow: var(--skin-shadow);
text-shadow: 0 1px 2px #0008;
}
[data-ws-part="voice.audio-dock.microphone-panel"]::before,
[data-ws-part="auth.password.actions"] > button {
background: var(--skin-line);
border-color: var(--skin-line);
border-radius: 12px;
}
`, "demo-skin", new Set(["assets/protected-pattern.png"]), 3);
assert.match(themed.css, /\[data-ws-part="voice\.audio-dock\.microphone"\]/);
assert.match(themed.css, /wskin-asset:assets%2Fprotected-pattern\.png/);
// The hide/move guarantees are unchanged.
for (const css of [
'[data-ws-part="voice.audio-dock.microphone"] { display: none; }',
'[data-ws-part="voice.audio-dock.microphone"] { visibility: hidden; }',
'[data-ws-part="voice.audio-dock.microphone"] { opacity: 0; }',
'[data-ws-part="voice.audio-dock.microphone"] { pointer-events: none; }',
'[data-ws-part="voice.audio-dock.microphone"] { clip-path: inset(100%); }',
'[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }',
':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock.microphone"] { margin-left: var(--skin-pull); }',
// Literal filter/clip/content-visibility hiding is rejected, so a variable
// must not smuggle the same value past the check.
':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { filter: var(--skin-x); }',
':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { -webkit-filter: var(--skin-x); }',
':root { --skin-x: rect(0, 0, 0, 0); } [data-ws-part="voice.audio-dock.microphone"] { clip: var(--skin-x); }',
':root { --skin-x: hidden; } [data-ws-part="voice.audio-dock.microphone"] { content-visibility: var(--skin-x); }',
]) {
assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css);
}
});
test("indirect filter values stay free outside protected controls", () => {
for (const version of [2, 3] as const) {
assert.doesNotThrow(() => compileSkinCss(':root { --skin-glow: drop-shadow(0 0 4px #0ff); } [data-ws-part="voice.header"] { filter: var(--skin-glow); }', "demo-skin", new Set(), version));
}
// Literal visual filters remain allowed on protected controls.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock.microphone"] { filter: drop-shadow(0 0 4px #0ff) saturate(1.2); }'));
});
test("host chrome cannot be restyled into a viewport-sized overlay", () => {
assert.throws(
() => compile('[data-ws-part="host.plugins.overlay"] { position: fixed; inset: 0; z-index: 2147483647; }'),
/layout is owned by WebSpeak/,
);
assert.throws(() => compile('[data-ws-part="host.watermark"] { position: fixed; }'), /layout is owned by WebSpeak/);
assert.throws(() => compile('[data-ws-part="host.plugins.overlay"] { width: 100vw; height: 100vh; }'), /fullscreen overlay/);
// Descendant rules are the same escape: `*` can turn the library contents
@@ -286,7 +516,6 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => {
'[data-ws-part="host.plugins.overlay"] * { position: fixed; inset: 0; z-index: 2147483647; }',
'[data-ws-part="host.plugins.overlay"] * { width: 100vw; height: 100vh; }',
'[data-ws-part="host.plugins.overlay"] .ws-plugin-library { position: fixed; top: 0; left: 0; }',
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
]) {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
@@ -299,12 +528,303 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
// Decorative host chrome is not on the recovery path: it may be repositioned,
// resized, restacked and animated, at most with a warning.
for (const css of [
'[data-ws-part="host.watermark"] { position: fixed; }',
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
'[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; }',
'[data-ws-part="host.plugins.launcher"] { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; }',
'[data-ws-part="host.hint"] { position: absolute; transform: translateX(-10px); }',
'[data-ws-part="host.voice-status-decoration"] { position: fixed; inset: 0; pointer-events: none; }',
]) {
assert.doesNotThrow(() => compile(css), css);
}
// Colors, borders, radius, shadows and artwork stay available, including on
// descendants of the overlay.
const themed = compile('[data-ws-part="host.plugins.overlay"] { border: 2px solid #1d4f9c; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px #0003; }');
assert.match(themed.css, /data-ws-part="host\.plugins\.overlay"/);
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { color: #fff; border-color: #1d4f9c; border-radius: 6px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }'));
// Overlay contents may use normal sizing and margins; only a viewport-sized
// box would turn the library contents into a fullscreen mask.
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] button { min-width: 44px; min-height: 44px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { margin: 0; }'));
});
test("keyframes follow the same protected-control rules as regular declarations", () => {
const rejected: Array<[string, RegExp]> = [
['@keyframes k { to { display: none; opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
['@keyframes k { to { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
['@keyframes k { to { transform: translateX(-9999px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
['@keyframes k { to { inset: 0 0 0 -120vw; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
['@keyframes k { to { filter: opacity(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/],
['@keyframes k { to { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain available/],
// A variable animation name must not hide the name from the walk.
[':root { --skin-anim: k; } @keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: var(--skin-anim) 1s forwards; }', /cannot use indirect values/],
['@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { --skin-anim: k; } [data-ws-part="voice.audio-dock"] { animation-name: var(--skin-anim); }', /cannot use indirect values/],
];
for (const [css, message] of rejected) {
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
}
// A keyframe shared by a protected and a non-protected part is judged by the
// protected reference.
assert.throws(
() => compile('@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation: k 1s; }'),
/must remain available/,
);
// Harmless fades, color tweens and gentle motion on non-protected parts, and
// visual / motion keyframes on decorative host parts, still compile.
for (const css of [
'@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: fade 2s ease; }',
'@keyframes tint { from { color: #fff; } to { color: #1d4f9c; } } [data-ws-part="home.header"] { animation: tint 1.2s; }',
'@keyframes drift { from { transform: translateY(0); } to { transform: translateY(-6px); } } [data-ws-part="home.hero.eyebrow"] { animation: drift 3s infinite alternate; }',
'@keyframes wm { from { opacity: .1; color: #8ab9cf; transform: translateX(0); } to { opacity: .3; color: #2b6d8a; transform: translateX(20px); } } [data-ws-part="host.watermark"] { animation: wm 4s infinite alternate; }',
'@keyframes big { to { width: 100vw; height: 100vh; opacity: .2; } } [data-ws-part="host.watermark"] { animation: big 1s forwards; }',
'@keyframes hide { to { display: none; } } [data-ws-part="host.hint"] { animation: hide 1s forwards; }',
]) {
assert.doesNotThrow(() => compile(css), css);
}
});
test("keyframes hide protected parts only when the animation can rest there", () => {
// Entrances and pulses that merely pass through a hidden/intermediate state
// are legitimate: only `to`/`100%` (and a genuinely resting `from`) count.
for (const css of [
'@keyframes in { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="app"] { animation: in .3s; }',
'@keyframes toastIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } [data-ws-part="app.toast"] { animation: toastIn .3s; }',
'@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: fade .4s; }',
'@keyframes slide { from { transform: translateX(-100%); } to { transform: none; } } [data-ws-part="voice.mobile-nav"] { animation: slide .25s; }',
'@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="app.toast"] { animation: pop .2s; }',
'@keyframes pulse { 50% { opacity: 0; } 100% { opacity: 1; } } [data-ws-part="voice.connection-status"] { animation: pulse 2s infinite; }',
'@keyframes in { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } } [data-ws-part="host.plugins.overlay"] { animation: in .2s; }',
'@keyframes pop { from { scale: 0; } to { scale: 1; } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }',
'@keyframes pop { from { transform: scale(0); } to { transform: scale(1); } } [data-ws-part="host.plugins.overlay"] { animation: pop .2s; }',
'@keyframes slide { from { transform: translateY(8px); } to { transform: translateY(0); } } [data-ws-part="host.plugins.overlay"] { animation: slide .2s; }',
// A keyframe without a `to` frame ends on the element's own style.
'@keyframes tint { 50% { opacity: 0; } } [data-ws-part="voice.connection-status"] { animation: tint 2s; }',
]) {
assert.doesNotThrow(() => compile(css), css);
}
const rejected: Array<[string, RegExp]> = [
['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
['@keyframes k { 100% { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
['@keyframes k { to { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
// Reverse/alternate/fill-backwards animations can end (or hold) on `from`.
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation: k 1s alternate; }', /must remain available/],
['@keyframes k { from { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-direction: alternate-reverse; }', /must remain available/],
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; animation-fill-mode: both; }', /must remain available/],
['@keyframes k { 0% { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
// Declaration order cannot hide a reverse direction behind a longhand.
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-direction: normal; animation: k 1s reverse; }', /must remain available/],
// A variable fill mode is unknowable, so the start frame is treated as resting.
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-fill-mode: var(--skin-fill); }', /must remain available/],
// A paused animation renders its start frame from the first paint.
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s paused; }', /must remain available/],
['@keyframes k { from { display: none; } } [data-ws-part="voice.audio-dock"] { animation-name: k; animation-play-state: paused; }', /must remain available/],
// Escaped `to`/`from` and `1e2%` must still be recognised as resting steps.
['@keyframes k { \\74 o { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
['@keyframes k { t\\6f { transform: translateX(-5000px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/],
['@keyframes k { \\66 rom { opacity: 0; } to { opacity: 1; } } [data-ws-part="voice.audio-dock"] { animation: k 1s reverse; }', /must remain available/],
['@keyframes k { 1e2% { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/],
// Direction/fill longhands in a sibling rule on the same subject still rest on `from`.
['@keyframes k { from { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation-direction: reverse; animation-fill-mode: both; }', /must remain available/],
];
for (const [css, message] of rejected) {
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
}
});
test("escaped animation names are matched and rewritten", () => {
const escaped = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation-name: p\\75 lse; }');
assert.match(escaped.css, /animation-name: ws-demo-skin-pulse/);
assert.doesNotMatch(escaped.css, /p\\75 lse/);
const shorthand = compile('@keyframes pulse { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: p\\75 lse .3s ease; }');
assert.match(shorthand.css, /animation: ws-demo-skin-pulse \.3s ease/);
// Only the name slot is rewritten: a keyframe named like a timing keyword
// must not turn the timing function into a keyframe reference.
const timing = compile('@keyframes linear { from { opacity: 1; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: linear 1s linear; }');
assert.match(timing.css, /animation: linear 1s ws-demo-skin-linear/);
});
test("keyword-shaped animation tokens do not become keyframe references", () => {
const named = compile('@keyframes alternate { from { opacity: 1; } to { opacity: 1; } } @keyframes bob { from { transform: translateY(0); } to { transform: translateY(4px); } } [data-ws-part="voice.audio-dock"] { animation: bob 2s alternate; }');
assert.match(named.css, /@keyframes ws-demo-skin-alternate/);
assert.match(named.css, /animation: ws-demo-skin-bob 2s alternate/);
assert.doesNotMatch(named.css, /animation: bob 2s ws-demo-skin-alternate/);
});
test("normalised hidden values cannot hide protected parts", () => {
const hidden: Array<[string, string]> = [
["display", "none"],
["visibility", "hidden"],
["visibility", "collapse"],
["opacity", ".0"],
["opacity", "+0"],
["opacity", "-1"],
["opacity", "0%"],
["opacity", "0.5%"],
["opacity", "0.001"],
["opacity", "calc(0)"],
["filter", "opacity(0.0)"],
["filter", "brightness(0)"],
["-webkit-filter", "opacity(0)"],
["pointer-events", "none"],
["transform", "scale(0)"],
["transform", "scaleX(0)"],
["transform", "scaleY(0)"],
["transform", "scale3d(0, 1, 1)"],
["transform", "scale(0 0)"],
["scale", "0"],
["scale", "0%"],
["scale", "0 0"],
["content-visibility", "hidden"],
["clip-path", "inset(50%)"],
["clip-path", "inset(60% 0)"],
["clip-path", "inset(0 60%)"],
["clip-path", "circle(0)"],
["clip-path", "ellipse(0 10px)"],
["clip", "rect(0,0,0,0)"],
["clip", "rect(0 0 0 0)"],
["mask", "alpha(0)"],
["mask-image", "luminance(0)"],
["mask-image", "linear-gradient(transparent, transparent)"],
["mask-image", "linear-gradient(#0000, #0000)"],
["mask-image", "linear-gradient(rgb(0 0 0 / 0), rgb(0 0 0 / 0))"],
["mask-image", "conic-gradient(from 0deg, transparent, transparent)"],
["opacity", "0e0"],
["opacity", "1e-3"],
["filter", "opacity(1e-2)"],
["transform", "scale(0e0)"],
["scale", "1e-9"],
];
for (const [property, value] of hidden) {
const direct = `[data-ws-part="voice.audio-dock"] { ${property}: ${value}; }`;
assert.throws(() => compile(direct), /must remain available/, direct);
const frame = `@keyframes k { to { ${property}: ${value}; } } [data-ws-part="voice.audio-dock"] { animation: k 1s; }`;
assert.throws(() => compile(frame), /must remain available/, frame);
}
// Partial effects and artwork clipping remain legitimate.
for (const css of [
'[data-ws-part="voice.audio-dock"] { opacity: .5; }',
'[data-ws-part="voice.audio-dock"] { filter: opacity(.4); }',
'[data-ws-part="voice.audio-dock"] { transform: scale(.5); }',
'[data-ws-part="voice.audio-dock"] { scale: .8; }',
'[data-ws-part="voice.audio-dock"] { clip-path: polygon(0 0, 100% 0, 100% 80%, 0 100%); }',
'[data-ws-part="voice.audio-dock"] { clip-path: inset(20%); }',
'[data-ws-part="voice.audio-dock"] { mask-image: linear-gradient(transparent, red); }',
]) {
assert.doesNotThrow(() => compile(css), css);
}
});
test("selector variants cannot disguise a protected subject", () => {
for (const css of [
'[data-ws-part="VOICE.AUDIO-DOCK" i] { display: none; }',
'[data-ws-part="voice.audio-dock" I] { opacity: 0; }',
':not(:not([data-ws-part="voice.audio-dock"])) { display: none; }',
':not(:not([data-ws-part="voice.audio-dock"]):hover) { visibility: hidden; }',
':nth-child(2n of [data-ws-part="voice.audio-dock"]) { display: none; }',
':nth-last-child(odd of .member, [data-ws-part="voice.audio-dock"]) { pointer-events: none; }',
':not(:not([data-ws-part="voice.audio-dock"]), [data-ws-part="home.title"]) { display: none; }',
':not(:is(:not([data-ws-part="voice.audio-dock"]))) { display: none; }',
]) {
assert.throws(() => compile(css), /must remain available/, css);
}
// The `s` flag keeps matching case-sensitive, so this selects nothing.
assert.doesNotThrow(() => compile('[data-ws-part="VOICE.AUDIO-DOCK" s] { display: none; }'));
// A single :not() still means "every other element".
assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }'));
});
test("escaped, namespaced and :is()/:where() animation names cannot bypass the protected-control locks", () => {
const rejected: Array<[string, RegExp]> = [
// Escaped property name used to skip the keyframe mapping walk.
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { anim\\61 tion: k 1s forwards; }', /must remain available/],
// A pack can predict the namespace and reference the already-renamed keyframe.
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-k 1s forwards; }', /must remain available/],
// The protected subject can be wrapped in a functional pseudo-class.
[':is([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/],
[':where([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/],
['@keyframes k { to { opacity: 0; } } :is([data-ws-part="voice.audio-dock"]) { animation: k 1s forwards; }', /must remain available/],
// -webkit-* animation longhands participate in the same walks.
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation: k 1s forwards; }', /must remain available/],
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation-name: k; }', /must remain available/],
['[data-ws-part="voice.audio-dock"] { -webkit-animation: var(--skin-a); }', /cannot use indirect values/],
// Escaped *values* used to bail out of the mapping walk on a backslash and
// still resolve to the renamed keyframe in the browser.
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\6b 1s forwards; }', /must remain available/],
['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\00006b 1s forwards; }', /must remain available/],
['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: \\6b; }', /must remain available/],
// Prefixed visual-removal properties must use the same checks as the unprefixed form.
['[data-ws-part="voice.audio-dock"] { -webkit-filter: opacity(0); }', /must remain available/],
['[data-ws-part="voice.audio-dock"] { -webkit-transform: scale(0); }', /must remain available/],
];
for (const [css, message] of rejected) {
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
}
// `:not()` does not make the protected part the subject; only a v3 warning.
assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }'));
// A harmless -webkit-animation on a non-protected part still compiles and its
// keyframe name is rewritten into the skin namespace.
const webkit = compile('@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { -webkit-animation: fade 2s ease; }');
assert.match(webkit.css, /@keyframes ws-demo-skin-fade/);
assert.match(webkit.css, /-webkit-animation: ws-demo-skin-fade 2s ease/);
});
test("quoted animation names stay names even when they match shorthand keywords", () => {
for (const name of ["linear", "ease", "reverse", "paused", "infinite", "none", "initial"]) {
const frames = `@keyframes ${name} { from { opacity: .5; } to { opacity: 1; } }`;
const shorthand = compile(`${frames} [data-ws-part="home.feature"] { animation: "${name}" 2s ease-in-out infinite; }`);
assert.ok(shorthand.css.includes(`animation: "ws-demo-skin-${name}" 2s ease-in-out infinite`), shorthand.css);
const longhand = compile(`${frames} [data-ws-part="home.feature"] { animation-name: "${name}"; }`);
assert.ok(longhand.css.includes(`animation-name: "ws-demo-skin-${name}"`), longhand.css);
assert.throws(() => compile(`@keyframes ${name} { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: "${name}" 1s ease; }`), /must remain available/);
}
const layers = compile('@keyframes linear { to { opacity: 1; } } @keyframes paused { to { opacity: 1; } } [data-ws-part="home.feature"] { animation: "linear" 2s ease, "paused" 3s linear; }');
assert.ok(layers.css.includes('animation: "ws-demo-skin-linear" 2s ease, "ws-demo-skin-paused" 3s linear'), layers.css);
});
test("keyframes cannot turn the plugin overlay into a fullscreen layer", () => {
for (const css of [
'@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }',
'@keyframes k { to { width: 100vw; height: 100vh; } } [data-ws-part="host.plugins.overlay"] * { animation: k 1s forwards; }',
'@keyframes k { to { zoom: 10; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }',
'@keyframes k { to { transform: scale(10); } } [data-ws-part="host.plugins.overlay"] { animation-name: k; }',
'@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { --skin-a: ws-demo-skin-k; animation: var(--skin-a) 1s forwards; }',
'[data-ws-part="host.plugins.overlay"] * { width: calc(50vw * 2); }',
'[data-ws-part="host.plugins.overlay"] * { width: calc(99vw + 1vw); }',
]) {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
// The same animation is harmless on decorative host chrome.
assert.doesNotThrow(() => compile('@keyframes k { to { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; } } [data-ws-part="host.watermark"] { animation: k 1s forwards; }'));
});
test("large layout restyles of non-protected parts and decorative host chrome compile", () => {
for (const css of [
'[data-ws-part="home.header"] { display: grid; grid-template-columns: 1fr 2fr; gap: 16px; position: relative; width: 80vw; height: 50vh; }',
'[data-ws-part="home.header"] { display: flex; flex-direction: column; align-items: stretch; translate: 24px 0; }',
'[data-ws-part="voice.audio-dock"] > div:first-child { position: absolute; width: 100vw; height: 100vh; }',
// Whole-page and protected-part layout rewrites are the owner's explicit
// use case; placement is no longer mistaken for a yeet.
'[data-ws-part="app"] { display: grid; grid-template-areas: "rail main"; grid-template-columns: 72px 1fr; position: relative; }',
'[data-ws-part="voice.audio-dock"] { position: fixed; top: 140px; left: 260px; display: flex; flex-direction: column; gap: 10px; }',
'[data-ws-part="home"] { display: flex; flex-direction: column; align-items: stretch; min-height: 100vh; }',
// Official example skins (harbor, kaak) clip their own artwork.
'[data-ws-part="home.header"] { clip-path: polygon(0 0, 100% 0, 100% 82%, 0 100%); }',
'[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; transform: rotate(-8deg); }',
]) {
assert.doesNotThrow(() => compile(css), css);
}
});
test("official and built-in skins hide host decorations unless the active skin opts in", () => {
+610 -129
View File
@@ -1,6 +1,6 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import selectorParser, { type Node as SelectorNode, type Pseudo as SelectorPseudo } from "postcss-selector-parser";
import valueParser, { type Node as ValueNode } from "postcss-value-parser";
import {
DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS,
HOST_CHROME_PART_IDS,
@@ -67,7 +67,12 @@ const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([
"aspect-ratio", "margin", "margin-block", "margin-inline", "margin-block-start", "margin-block-end",
"margin-inline-start", "margin-inline-end",
]);
/** Properties whose indirect values could smuggle a hidden or moved control past the static checks. */
/**
* Properties whose indirect values could smuggle a hidden or moved control past
* the static checks. Purely visual properties (colour, background, border,
* radius, font, shadow, padding, width/height) are deliberately absent: a
* protected control may theme them with `var()`.
*/
const INDIRECT_VALUE_PROPERTIES = new Set([
"all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image",
"position", "top", "right", "bottom", "left", "inset",
@@ -79,6 +84,14 @@ const INDIRECT_VALUE_PROPERTIES = new Set([
"margin-block", "margin-block-start", "margin-block-end",
"margin-inline", "margin-inline-start", "margin-inline-end",
]);
/**
* Visual properties whose literal hiding values (`filter: opacity(0)`,
* `clip: rect(0 0 0 0)`, `content-visibility: hidden`) are rejected on
* protected controls. They stay free on every other part, but a protected
* control may not take them from `var()`/`attr()`, which would hide the
* same value from the static check.
*/
const PROTECTED_INDIRECT_HIDE_PROPERTIES = new Set(["filter", "clip", "content-visibility"]);
/** Attributes a skin author must never use to reach outside the public hooks. */
const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
HOST_SKIN_ATTRIBUTE,
@@ -91,9 +104,24 @@ 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. */
const ANIMATION_KEYWORD_CATEGORIES = new Map<string, string>([
["linear", "timing"], ["ease", "timing"], ["ease-in", "timing"], ["ease-out", "timing"],
["ease-in-out", "timing"], ["step-start", "timing"], ["step-end", "timing"],
["normal", "direction"], ["reverse", "direction"], ["alternate", "direction"], ["alternate-reverse", "direction"],
["none", "fill"], ["forwards", "fill"], ["backwards", "fill"], ["both", "fill"],
["running", "play"], ["paused", "play"], ["infinite", "iteration"],
]);
/** Words that let an animation hold its `from`/`0%` frame. */
const RESTING_START_KEYWORDS = new Set(["reverse", "alternate", "alternate-reverse", "backwards", "both", "paused"]);
export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
if (!size || size > MAX_CSS_BYTES) throw new SkinCssValidationError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
@@ -105,10 +133,8 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
// Host chrome is Teleported outside `.ws-skin-root`. Rules that target only
// registered host parts use a second, document-level scope anchored to an
// attribute the host sets while this exact skin is active. Author CSS never
// names html/body: the host generates the scope itself.
// Host chrome is Teleported outside `.ws-skin-root`; these rules get their own
// document-level scope, which the host anchors to the active skin attribute.
const hostSkinScope = `:root[${HOST_SKIN_ATTRIBUTE}="${id}"]`;
const hostScopeNodes = selectorParser().astSync(hostSkinScope).first!.nodes.map((node) => node.clone());
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
@@ -180,48 +206,100 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const referencedKeyframes = new Set<string>();
const nonOptionalKeyframes = new Set<string>();
// Keyframes inherit the protected/locked status of their referencing rules;
// params are namespaced here, and `from`/`0%` only rests for some rules.
const protectedKeyframeParts = new Map<string, string>();
const lockedHostKeyframeParts = new Map<string, Set<string>>();
const restingFromKeyframes = new Set<string>();
// Direction/fill/play-state longhands may sit in a sibling rule on the same
// subject; collect names per subject, then mark resting-from afterwards.
const subjectKeyframes = new Map<string, Set<string>>();
const restingSubjects = new Set<string>();
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
const optionalTarget = hideableRules.has(rule);
const protectedTarget = selectorSubjectProtectedPart(rule.selector);
const lockedHostParts = selectorLockedHostParts(rule.selector);
const subjects = [
...selectorSubjectParts(rule.selector, PROTECTED_PART_IDS),
...selectorSubjectParts(rule.selector, HOST_CHROME_PART_IDS).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part)),
];
const restsAtStart = subjects.length > 0 && ruleCanRestAtStart(rule);
if (restsAtStart) for (const subject of subjects) restingSubjects.add(subject);
rule.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
// Decode the property like the enforcement walk (`anim\61 tion`), and the
// value so escaped identifiers match their declared names.
const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase());
if (property !== "animation" && property !== "animation-name") return;
const value = declaration.value;
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
const decodedValue = decodeCssEscapes(declaration.value);
if (/\b(?:var|attr)\s*\(/i.test(decodedValue)) {
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
return;
}
for (const name of keyframeNames.keys()) {
if (!referencesCssIdentifier(value, name)) continue;
referencedKeyframes.add(name);
if (!optionalTarget) nonOptionalKeyframes.add(name);
const { names } = parseAnimationLayers(decodedValue, property);
for (const nameNode of names) {
if (!nameNode) continue;
const name = nameNode.value;
for (const [original, scopedName] of keyframeNames) {
if (name !== original && name !== scopedName) continue;
referencedKeyframes.add(original);
if (!optionalTarget) nonOptionalKeyframes.add(original);
if (protectedTarget && !protectedKeyframeParts.has(scopedName)) {
protectedKeyframeParts.set(scopedName, protectedTarget);
}
if (lockedHostParts.length) {
const parts = lockedHostKeyframeParts.get(scopedName) ?? new Set<string>();
for (const part of lockedHostParts) parts.add(part);
lockedHostKeyframeParts.set(scopedName, parts);
}
if (restsAtStart) restingFromKeyframes.add(scopedName);
for (const subject of subjects) {
const names = subjectKeyframes.get(subject) ?? new Set<string>();
names.add(scopedName);
subjectKeyframes.set(subject, names);
}
}
}
});
});
for (const subject of restingSubjects) {
for (const name of subjectKeyframes.get(subject) ?? []) restingFromKeyframes.add(name);
}
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
.filter((name) => !nonOptionalKeyframes.has(name))
.map((name) => keyframeNames.get(name)!));
root.walkDecls((declaration: Declaration) => {
const property = decodeCssEscapes(declaration.prop).toLowerCase();
const unprefixedProperty = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
const unprefixedProperty = unprefixed(property);
const value = declaration.value.trim();
const decodedValue = decodeCssEscapes(value);
const owningRule = findOwningRule(declaration);
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
const keyframeScope = keyframesRule?.params.trim() ?? null;
// `to`/`100%` always rest, and `from`/`0%` when the rule can rest at start.
const restingFrame = !keyframesRule
|| (keyframeScope !== null && keyframeStepCanRest(owningRule!.selector, restingFromKeyframes.has(keyframeScope)));
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
// Trusted UI and essential audio/recovery controls stay available even for
// open skins. The host also draws authorization and recovery UI outside the
// skin root, so a container-level hide cannot remove them either.
const protectedTarget = owningRule && !keyframesRule ? selectorSubjectProtectedPart(owningRule.selector) : null;
// Every themeable host part referenced anywhere in the selector. A rule may
// target a descendant of the overlay (for example with `*`), so the subject
// alone is not enough to decide whether host chrome layout is at stake.
const hostChromeParts = owningRule && !keyframesRule ? selectorHostChromeParts(owningRule.selector) : [];
// A keyframe inherits the protected status of its referencing rules.
const protectedTarget = owningRule
? keyframesRule
? (keyframeScope ? protectedKeyframeParts.get(keyframeScope) ?? null : null)
: selectorSubjectProtectedPart(owningRule.selector)
: null;
// Every locked host part in the selector, not just the subject: `*` under
// the overlay is still host chrome. Decorative parts are excluded.
const hostChromeParts = owningRule
? keyframesRule
? (keyframeScope ? [...(lockedHostKeyframeParts.get(keyframeScope) ?? [])] : [])
: selectorLockedHostParts(owningRule.selector)
: [];
const inHostChromeScope = hostChromeParts.length > 0;
const inOverlayScope = hostChromeParts.includes("host.plugins.overlay");
const overlaySubject = Boolean(!keyframesRule && owningRule
&& selectorSubjectPart(owningRule.selector, HOST_CHROME_PART_IDS) === "host.plugins.overlay");
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
@@ -231,55 +309,60 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
}
// Host chrome lives outside the skin root and owns its own placement. A
// skin may repaint it (colors, borders, radius, artwork) but must not turn
// it — or any of its descendants — into a viewport-sized overlay above
// authorization/recovery UI.
if (inHostChromeScope && HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls.");
}
if (inOverlayScope && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
// Host chrome keeps its placement and footprint; decorative host parts skip
// this lock. Overlay contents may size themselves unless viewport-sized.
if (inHostChromeScope && !keyframesRule) {
if (HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls.");
}
if (overlaySubject && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
}
// Overlay contents may size themselves, but not to the viewport.
if (inOverlayScope && !overlaySubject && OVERLAY_SIZE_PROPERTIES.has(unprefixedProperty) && valueIsViewportSized(decodedValue)) {
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
}
} else if (inHostChromeScope && restingFrame && keyframeEscapesHostLock(unprefixedProperty, decodedValue)) {
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition, restack or resize host controls into a fullscreen layer.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
throw declaration.error("Executable CSS values are not allowed.");
}
const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase();
if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
const indirectValue = restingFrame && /\b(?:var|attr)\s*\(/i.test(decodedValue);
if (indirectValue && protectedTarget
&& (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) || PROTECTED_INDIRECT_HIDE_PROPERTIES.has(unprefixedProperty))) {
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
}
if (indirectValue && !protectedTarget && INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
}
// An indirect animation name is checked at the declaration site. Locked
// host chrome (the plugin overlay) uses the same rule, otherwise a
// variable could point at a fullscreen keyframe.
if (!keyframesRule && (unprefixedProperty === "animation" || unprefixedProperty === "animation-name")
&& /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
if (protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
}
if (!canHideTarget && schemaVersion < 3) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
if (inHostChromeScope) {
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls through an indirect animation name.");
}
}
const removesVisual = property === "all"
|| (property === "display" && compactValue === "none")
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|| (property === "pointer-events" && compactValue === "none")
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
if (removesVisual && protectedTarget) {
// One predicate for every way a declaration can hide or disable a part.
const hidesVisual = restingFrame && hidesVisually(unprefixedProperty, decodedValue);
if (hidesVisual && protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`);
}
if (removesVisual && !canHideTarget && schemaVersion < 3) {
if (hidesVisual && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
}
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue))
|| (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue))
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue));
if (visuallyRemoves && protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" must remain visible.`);
}
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
}
if (protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
if (restingFrame && protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`);
}
if (schemaVersion >= 3 && removesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (schemaVersion >= 3 && hidesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
const withScopedNames = rewriteScopedNames(value, unprefixedProperty, keyframeNames, fontFamilyNames);
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
return `wskin-asset:${encodeURIComponent(assetPath)}`;
@@ -375,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, ""));
}
@@ -427,24 +513,87 @@ function assertHostChromeSubject(parsed: selectorParser.Root): void {
}
}
/** Find a protected part in the subject (last compound) of any selector in a rule. */
function selectorSubjectProtectedPart(selector: string): string | null {
/** Functional pseudo-classes whose arguments keep the subject role. */
const SUBJECT_PSEUDO_CLASSES = new Set([":is", ":where", ":matches", ":-webkit-any", ":-moz-any"]);
/** The nodes after the last combinator, i.e. the subject compound. */
function lastCompound(nodes: SelectorNode[]): SelectorNode[] {
let start = 0;
for (let index = nodes.length - 1; index >= 0; index -= 1) {
if (nodes[index].type === "combinator") { start = index + 1; break; }
}
return nodes.slice(start);
}
/** Find a part in a compound; `:is()`/`:where()`/`:nth-child(… of S)` and
* `:not(:not(X))` keep the subject role, a single `:not()` does not. */
function compoundPart(nodes: SelectorNode[], parts: ReadonlySet<string>): string | null {
for (const node of nodes) {
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
const value = node.value.replace(/^['"]|['"]$/g, "");
if (node.insensitive) {
const lower = value.toLowerCase();
for (const part of parts) if (part.toLowerCase() === lower) return part;
} else if (parts.has(value)) {
return value;
}
}
if (node.type !== "pseudo" || !node.nodes) continue;
const pseudo = node.value.toLowerCase();
if (SUBJECT_PSEUDO_CLASSES.has(pseudo) || pseudo === ":nth-child" || pseudo === ":nth-last-child") {
for (const nested of node.nodes) {
const part = compoundPart(lastCompound(nested.nodes), parts);
if (part) return part;
}
} else if (pseudo === ":not") {
// `:not(:not(X))` and `:not(:not(X), Y)` are `X`; wrappers like
// `:not(:is(:not(X)))` unwrap the same way. A single `:not(X)` is skipped.
for (const argument of node.nodes) {
const inner = nestedNegation(lastCompound(argument.nodes));
if (!inner) continue;
for (const nested of inner.nodes) {
const part = compoundPart(lastCompound(nested.nodes), parts);
if (part) return part;
}
}
}
}
return null;
}
/** A `:not(...)` argument that is itself a `:not`, possibly wrapped in `:is()`. */
function nestedNegation(nodes: SelectorNode[]): SelectorPseudo | null {
const direct = nodes.find((node): node is SelectorPseudo => node.type === "pseudo" && node.value.toLowerCase() === ":not");
if (direct) return direct;
for (const node of nodes) {
if (node.type !== "pseudo" || !node.nodes || !SUBJECT_PSEUDO_CLASSES.has(node.value.toLowerCase())) continue;
for (const nested of node.nodes) {
const found = nestedNegation(lastCompound(nested.nodes));
if (found) return found;
}
}
return null;
}
/** Every matching part in the subject of any selector in a rule. */
function selectorSubjectParts(selector: string, parts: ReadonlySet<string>): string[] {
const found: string[] = [];
try {
const parsed = selectorParser().astSync(selector);
for (const item of parsed.nodes) {
let start = 0;
for (let index = item.nodes.length - 1; index >= 0; index -= 1) {
if (item.nodes[index].type === "combinator") { start = index + 1; break; }
}
for (let index = start; index < item.nodes.length; index += 1) {
const node = item.nodes[index];
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) continue;
const part = node.value.replace(/^['"]|['"]$/g, "");
if (PROTECTED_PART_IDS.has(part)) return part;
}
const part = compoundPart(lastCompound(item.nodes), parts);
if (part && !found.includes(part)) found.push(part);
}
} catch { /* A malformed selector is rejected elsewhere. */ }
return null;
return found;
}
function selectorSubjectPart(selector: string, parts: ReadonlySet<string>): string | null {
return selectorSubjectParts(selector, parts)[0] ?? null;
}
function selectorSubjectProtectedPart(selector: string): string | null {
return selectorSubjectPart(selector, PROTECTED_PART_IDS);
}
/** Find every themeable host part referenced by a selector, in any compound. */
@@ -460,71 +609,400 @@ function selectorHostChromeParts(selector: string): string[] {
return parts;
}
/** Host parts whose layout stays locked; decorative chrome is excluded. */
function selectorLockedHostParts(selector: string): string[] {
return selectorHostChromeParts(selector).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part));
}
function unprefixed(property: string): string {
return property.replace(/^-(?:webkit|moz|ms|o)-/, "");
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
const local = unprefixed(property);
if (LAYOUT_AFFECTING_PROPERTIES.has(local)) return true;
if (/^(?:margin|padding)(?:-|$)/.test(local)) return true;
if (/^border(?:-|$)/.test(local) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(local)) return true;
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(local)) return true;
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(local);
}
/**
* True when a positioning/margin/transform value can push a protected control
* off-screen. Thresholds are deliberately low: a protected control has a
* minimum 44 px hit target, so an offset of a hundred pixels is already enough
* to make it unreachable. Percentages and viewport units are compared against a
* full viewport/containing block.
* clearly off-screen: -1000 px / -100 % or +2000 px / +200 %. Ordinary layout
* moves are legitimate, so only viewport-ejecting values are rejected.
*/
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform|scale|rotate)(?:-|$)/;
const ABSOLUTE_OFFSET_LIMIT_PX = 100;
const RELATIVE_OFFSET_LIMIT = 100;
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform)(?:-|$)/;
const OFFSET_LIMITS = { negativePx: 1000, positivePx: 2000, negativePercent: 100, positivePercent: 200 };
function absoluteLengthToPixels(magnitude: number, unit: string): number | null {
switch (unit) {
case "px": return magnitude;
case "rem": case "em": return magnitude * 16;
case "ex": case "rex": case "ch": return magnitude * 8;
case "cm": return magnitude * 37.8;
case "mm": return magnitude * 3.78;
case "q": return magnitude * 0.945;
case "in": return magnitude * 96;
case "pt": return magnitude * 1.333;
case "pc": return magnitude * 16;
default: return null;
type Dimension = { value: number; unit: string };
const ABSOLUTE_UNIT_PIXELS: Record<string, number> = { px: 1, rem: 16, em: 16, ex: 8, rex: 8, ch: 8, cm: 37.8, mm: 3.78, q: 0.945, in: 96, pt: 1.333, pc: 16 };
function absoluteLengthToPixels(value: number, unit: string): number | null {
const factor = ABSOLUTE_UNIT_PIXELS[unit];
return factor ? value * factor : null;
}
type OffsetMeasurement = { kind: "pixels" | "percent"; value: number };
const VIEWPORT_UNIT_PATTERN = /^(?:s|l|d)?v(?:w|h|i|min|max)$|^cq(?:w|h|min|max|i|b)$/;
/** CSS `<number>` including a scientific-notation exponent. */
const CSS_NUMBER_PATTERN = "[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?";
/** One CSS number, percentage or length, including a flat `calc()`. */
function parseDimension(text: string): Dimension | null {
const compact = text.trim().toLowerCase();
const calc = /^calc\(([\s\S]*)\)$/.exec(compact);
if (calc) return evaluateCalc(calc[1]);
const match = new RegExp(`^(${CSS_NUMBER_PATTERN})([a-z%]*)$`).exec(compact);
return match ? { value: Number(match[1]), unit: match[2] } : null;
}
/** Flat `calc()`: sums of products over numbers and one unit; nested or mixed
* input is unknown (`null` → allowed). A sign after `*`/`/` is a factor,
* so `calc(2px*-1000)` is -2000px, not 2px + -1000. */
function evaluateCalc(text: string): Dimension | null {
const compact = text.replace(/\s+/g, "");
const tokens = compact.match(new RegExp(`[*/]|${CSS_NUMBER_PATTERN}(?:[a-z%]+)?`, "g"));
if (!tokens || tokens.join("") !== compact) return null;
const total: Dimension = { value: 0, unit: "" };
let term: Dimension | null = null;
let pending: "*" | "/" | null = null;
const addTerm = (): boolean => {
if (!term || (total.unit && term.unit && total.unit !== term.unit)) return false;
total.value += term.value;
total.unit ||= term.unit;
return true;
};
for (const token of tokens) {
if (token === "*" || token === "/") { pending = token; continue; }
const factor = parseDimension(token);
if (!factor) return null;
if (pending && term) {
if (factor.unit && (term.unit || pending === "/")) return null;
term = { value: pending === "/" ? term.value / factor.value : term.value * factor.value, unit: term.unit || factor.unit };
pending = null;
continue;
}
if (term && !addTerm()) return null;
term = factor;
pending = null;
}
return !pending && addTerm() ? total : null;
}
/** Normalise one length for comparison; a bare number is not a length. */
function lengthMeasurement(value: string): OffsetMeasurement | null {
const dimension = parseDimension(value);
if (!dimension?.unit) return null;
if (dimension.unit === "%" || VIEWPORT_UNIT_PATTERN.test(dimension.unit)) return { kind: "percent", value: dimension.value };
const pixels = absoluteLengthToPixels(dimension.value, dimension.unit);
return pixels === null ? null : { kind: "pixels", value: pixels };
}
function exceedsOffset(measurement: OffsetMeasurement | null): boolean {
if (!measurement) return false;
const [negative, positive] = measurement.kind === "percent"
? [OFFSET_LIMITS.negativePercent, OFFSET_LIMITS.positivePercent]
: [OFFSET_LIMITS.negativePx, OFFSET_LIMITS.positivePx];
return measurement.value <= -negative || measurement.value >= positive;
}
function valueMovesOffscreen(property: string, value: string): boolean {
if (!OFFSET_PROPERTY_PATTERN.test(property)) return false;
let offscreen = false;
valueParser(value).walk((node) => {
if (node.type !== "word") return;
const match = /^(-?(?:\d+|\d*\.\d+))(px|rem|em|r?ex|ch|%|cm|mm|q|in|pt|pc|(?:s|l|d)?v(?:w|h|min|max)|cq(?:w|h|min|max|i|b))$/i.exec(node.value);
if (!match) return;
const magnitude = Math.abs(Number(match[1]));
const unit = match[2].toLowerCase();
if (unit === "%" || /^(?:s|l|d)?v(?:w|h|min|max)$/.test(unit) || /^cq(?:w|h|min|max|i|b)$/.test(unit)) {
if (magnitude >= RELATIVE_OFFSET_LIMIT) offscreen = true;
return;
const name = node.type === "function" ? node.value.toLowerCase() : "";
if (node.type === "word") offscreen ||= exceedsOffset(lengthMeasurement(node.value));
else if (name === "calc") {
offscreen ||= exceedsOffset(lengthMeasurement(valueParser.stringify(node)));
return false;
} else if (node.type === "function" && (name === "matrix" || name === "matrix3d")) {
// A matrix can smuggle a large translation in unitless numbers.
const items = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
offscreen ||= (name === "matrix" ? [items[4], items[5]] : [items[12], items[13]])
.some((item) => item <= -OFFSET_LIMITS.negativePx || item >= OFFSET_LIMITS.positivePx);
return false;
}
const pixels = absoluteLengthToPixels(magnitude, unit);
if (pixels !== null && pixels >= ABSOLUTE_OFFSET_LIMIT_PX) offscreen = true;
return undefined;
});
// A matrix transform can smuggle a large translation in unitless numbers.
if (property === "transform") {
valueParser(value).walk((node) => {
if (node.type !== "function") return;
const name = node.value.toLowerCase();
if (name !== "matrix" && name !== "matrix3d") return;
const numbers = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
const translations = name === "matrix" ? [numbers[4], numbers[5]] : [numbers[12], numbers[13]];
if (translations.some((translation) => Number.isFinite(translation) && Math.abs(translation) >= ABSOLUTE_OFFSET_LIMIT_PX)) offscreen = true;
});
}
return offscreen;
}
/** This declaration removes the element from view; partial effects stay allowed. */
function hidesVisually(property: string, value: string): boolean {
if (property === "all") return true;
const text = decodeCssEscapes(value).trim().toLowerCase();
if ((property === "display" && text === "none") || (property === "visibility" && /^(?:hidden|collapse)$/.test(text))
|| (property === "pointer-events" && text === "none") || (property === "content-visibility" && text === "hidden")) return true;
if (property === "opacity") return (numericValue(text) ?? 1) <= 0.01;
if (property === "filter") return filterHides(text);
if (property === "transform") return transformHides(text);
if (property === "scale") return scalePropertyHides(text);
if (property === "clip-path") return clipPathHides(text);
if (property === "clip") return clipHides(text);
return property === "mask" || property === "mask-image" ? maskHides(text) : false;
}
/** Visit every function node; `test` gets the lower-cased name and its arguments. */
function anyFunction(value: string, test: (name: string, args: string) => boolean): boolean {
let hit = false;
valueParser(value).walk((node) => {
if (node.type === "function" && test(node.value.toLowerCase(), valueParser.stringify(node.nodes))) hit = true;
});
return hit;
}
/** A number, a percentage as 0–1, or a flat `calc()` of numbers. */
function numericValue(value: string): number | null {
const dimension = parseDimension(value);
if (!dimension) return null;
return dimension.unit === "%" ? dimension.value / 100 : dimension.unit === "" ? dimension.value : null;
}
function filterHides(value: string): boolean {
return anyFunction(value, (name, args) => {
const amount = numericValue(args);
return amount !== null && (name === "opacity" ? amount <= 0.01 : name === "brightness" && amount <= 0);
});
}
function numbers(text: string): number[] {
return text.split(/[\s,]+/).map(numericValue).filter((item): item is number => item !== null);
}
function isZeroFactor(value: number): boolean {
return Math.abs(value) <= 0.001;
}
function transformHides(value: string): boolean {
return anyFunction(value, (name, args) => {
const factors = numbers(args);
if (name === "scale" || name === "scale3d") return factors.slice(0, 2).some(isZeroFactor);
return (name === "scalex" || name === "scaley") && isZeroFactor(factors[0] ?? 1);
});
}
function scalePropertyHides(value: string): boolean {
const factors = numbers(value);
return factors.length > 0 && (isZeroFactor(factors[0]) || (factors.length > 1 && isZeroFactor(factors[1])));
}
function zeroLength(value: string | undefined): boolean {
const dimension = value ? parseDimension(value) : null;
return dimension !== null && isZeroFactor(dimension.value);
}
function insetHides(args: string): boolean {
const sides = args.split(/\bround\b/i)[0].trim().split(/\s+/).map(parseDimension);
if (sides.some((side) => !side || (side.unit !== "" && side.unit !== "%"))) return false;
const values = sides.map((side) => side!.value);
const [top, right = top, bottom = top, left = right] = values;
return top + bottom >= 100 || left + right >= 100;
}
function clipPathHides(value: string): boolean {
return anyFunction(value, (name, args) => {
const shape = args.split(/\bat\b/i)[0].trim();
if (name === "inset") return insetHides(args);
if (name === "circle") return zeroLength(shape.split(/\s+/)[0]);
return name === "ellipse" && shape.split(/\s+/).filter(Boolean).slice(0, 2).some(zeroLength);
});
}
function clipHides(value: string): boolean {
const match = /^rect\(([\s\S]*)\)$/i.exec(value.trim());
if (!match) return false;
const sides = match[1].split(/[\s,]+/).filter(Boolean);
return sides.length === 4 && sides.every(zeroLength);
}
const GRADIENT_PRELUDE_KEYWORDS = new Set([
"from", "to", "left", "right", "top", "bottom", "center", "at", "circle", "ellipse",
"closest-side", "closest-corner", "farthest-side", "farthest-corner", "in",
]);
/** `#rgb0` / `#rrggbb00`, `transparent`, or a colour function with alpha ≤ 0.01. */
function colorIsTransparent(text: string): boolean {
const value = text.trim().toLowerCase();
if (value === "transparent" || /^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(value)) return true;
return anyFunction(value, (name, args) => {
if (!/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)$/.test(name)) return false;
const slash = args.split("/");
if (slash.length > 1) return (numericValue(slash[slash.length - 1].trim()) ?? 1) <= 0.01;
const channels = numbers(args);
return (name === "rgba" || name === "hsla") && channels.length >= 4 && channels[3] <= 0.01;
});
}
/** A gradient is a full mask only when every colour stop is fully transparent. */
function gradientIsAllTransparent(args: string): boolean {
let transparent = false;
for (const segment of args.split(/,(?![^(]*\))/)) {
const text = segment.trim().toLowerCase();
if (!text) continue;
const first = valueParser(text).nodes.find((node) => node.type !== "space" && node.type !== "comment");
if (!first) continue;
if (first.type === "function" ? colorIsTransparent(valueParser.stringify([first])) : colorIsTransparent(first.value)) {
transparent = true;
continue;
}
if (first.type === "word" && (GRADIENT_PRELUDE_KEYWORDS.has(first.value.toLowerCase()) || parseDimension(first.value)?.unit)) continue;
return false;
}
return transparent;
}
function maskHides(value: string): boolean {
return anyFunction(value, (name, args) =>
name === "alpha" || name === "luminance"
? (numericValue(args) ?? 1) <= 0
: name.endsWith("gradient") && gradientIsAllTransparent(args));
}
/**
* Name token per layer. In the shorthand a keyword fills the first slot of its
* category; a repeated category (or any other word) is the name, so
* `bob 2s alternate` references `bob`. Times, numbers and functions are skipped.
*/
function parseAnimationLayers(value: string, property: string): { parsed: ReturnType<typeof valueParser>; names: Array<ValueNode | null> } {
const parsed = valueParser(value);
const groups: ValueNode[][] = [[]];
for (const node of parsed.nodes) {
if (node.type === "div" && node.value === ",") groups.push([]);
else if (node.type !== "space" && node.type !== "comment") groups[groups.length - 1].push(node);
}
const names = groups.map((nodes) => {
const words = nodes.filter((node) => node.type === "word" || node.type === "string");
if (property === "animation-name") {
if (words[0]?.type === "string") return words[0];
const name = words[0] ? decodeCssEscapes(words[0].value).toLowerCase() : "";
return words[0] && name !== "none" && !CSS_WIDE_KEYWORDS.has(name) ? words[0] : null;
}
const used = new Set<string>();
for (const node of words) {
// Quoted strings always name keyframes, even "linear" or "none";
// only unquoted words may fill the shorthand's keyword slots.
if (node.type === "string") return node;
const token = decodeCssEscapes(node.value).toLowerCase();
const dimension = parseDimension(token);
if (dimension && ["", "s", "ms"].includes(dimension.unit)) continue;
const category = ANIMATION_KEYWORD_CATEGORIES.get(token);
if (category && used.has(category)) return node;
if (category) used.add(category);
else if (node.type === "word" && CSS_WIDE_KEYWORDS.has(token)) continue;
else return node;
}
return null;
});
return { parsed, names };
}
/** Any restart/alternate/fill keyword or indirect value can hold the start frame.
* Multi-layer rules are judged as a whole, which errs towards checking `from`. */
function ruleCanRestAtStart(rule: Rule): boolean {
let resting = false;
rule.walkDecls((declaration: Declaration) => {
const property = unprefixed(decodeCssEscapes(declaration.prop).toLowerCase());
if (!["animation", "animation-direction", "animation-fill-mode", "animation-play-state"].includes(property)) return;
const value = decodeCssEscapes(declaration.value).toLowerCase();
resting ||= /\b(?:var|attr)\s*\(/.test(value)
|| valueParser(value).nodes.some((node) => node.type === "word" && RESTING_START_KEYWORDS.has(node.value));
});
return resting;
}
/** `to`/`100%` always rest; `from`/`0%` rest for reverse/alternate, a
* backwards/both fill, or a paused start. A long animation or a pause mid-way
* (negative delay) can linger on an unchecked intermediate frame — accepted,
* because recovery lives in a closed-shadow top-layer capsule. */
function keyframeStepCanRest(selector: string, restsAtStart: boolean): boolean {
return selector.split(",").some((step) => {
const value = decodeCssEscapes(step).trim().toLowerCase();
if (value === "to") return true;
if (value === "from") return restsAtStart;
const position = parseDimension(value);
return position?.unit === "%" && (position.value >= 100 || (restsAtStart && position.value <= 0));
});
}
const OVERLAY_SIZE_PROPERTIES = new Set([
"width", "height", "min-width", "min-height", "max-width", "max-height",
"inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio",
]);
function isViewportSizedDimension(dimension: Dimension | null): boolean {
return Boolean(dimension && VIEWPORT_UNIT_PATTERN.test(dimension.unit) && Math.abs(dimension.value) >= 100);
}
function valueIsViewportSized(value: string): boolean {
let sized = false;
valueParser(value).walk((node) => {
if (node.type === "word") sized ||= isViewportSizedDimension(parseDimension(node.value));
else if (node.type === "function" && node.value.toLowerCase() === "calc") {
sized ||= isViewportSizedDimension(parseDimension(valueParser.stringify(node)));
return false;
}
return undefined;
});
return sized;
}
function isIdentityNumber(value: number): boolean {
return Math.abs(value - 1) <= 0.001;
}
function isZeroAngleOrLength(value: string): boolean {
return zeroLength(value);
}
/** Identity transforms (`none`, `scale(1)`, `translate(0)`, `rotate(0deg)`). */
function transformIsIdentity(value: string): boolean {
const compact = value.trim().toLowerCase();
if (compact === "none") return true;
let seen = false;
let identity = true;
valueParser(compact).walk((node) => {
if (node.type !== "function") return;
seen = true;
const name = node.value.toLowerCase();
const args = valueParser.stringify(node.nodes);
const factors = numbers(args);
if (name === "scale" || name === "scale3d") identity &&= factors.length > 0 && factors.every(isIdentityNumber);
else if (name === "scalex" || name === "scaley" || name === "scalez") identity &&= factors.length > 0 && isIdentityNumber(factors[0]);
else if (/^translate(?:3d|[xyz])?$/.test(name)) identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength);
else if (/^rotate(?:3d|[xyz])?$/.test(name) || name === "skew" || name === "skewx" || name === "skewy") {
identity &&= args.split(/[,\s]+/).filter(Boolean).every(isZeroAngleOrLength);
} else identity = false;
});
return seen && identity;
}
function isNeutralLockValue(property: string, value: string): boolean {
const compact = value.trim().toLowerCase();
if (["none", "auto", "static"].includes(compact) || CSS_WIDE_KEYWORDS.has(compact)) return true;
if (property === "scale" || property === "zoom") {
const factors = numbers(compact);
return factors.length > 0 && factors.every(isIdentityNumber);
}
if (property === "rotate") return isZeroAngleOrLength(compact);
if (property === "transform") return transformIsIdentity(compact);
if (property === "translate" || property.startsWith("inset") || /^(?:top|right|bottom|left)$/.test(property)) {
return compact.split(/\s+/).every((token) => token === "auto" || isZeroAngleOrLength(token));
}
return compact === "0" || isZeroAngleOrLength(compact);
}
/** Resting host-chrome keyframes reuse the direct lock per property: locked
* properties only accept identity/neutral values; sizes only reject viewport sizes. */
function keyframeEscapesHostLock(property: string, value: string): boolean {
const compact = decodeCssEscapes(value).trim().toLowerCase();
if (isNeutralLockValue(property, compact)) return false;
if (OVERLAY_SIZE_PROPERTIES.has(property)) return valueIsViewportSized(value);
return HOST_CHROME_LOCKED_PROPERTIES.has(property);
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
@@ -543,11 +1021,6 @@ function findKeyframesRule(rule: Rule): AtRule | null {
return null;
}
function referencesCssIdentifier(value: string, identifier: string): boolean {
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
}
export function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
const parsed = valueParser(value);
const resolvePackageAsset = (rawValue: string): string => {
@@ -605,16 +1078,24 @@ function parseSingleFontFamily(value: string): string {
}
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
const parsed = valueParser(value);
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
parsed.walk((node) => {
if (node.type !== "word" && node.type !== "string") return;
const keyframe = keyframes.get(node.value);
if (keyframe) node.value = keyframe;
const family = fontFamilies.get(node.value.toLowerCase());
if (family) node.value = family;
});
if (!["animation", "animation-name", "font", "font-family"].includes(property)) return value;
// Rewrite against the decoded value: `p\75 lse` must become the scoped name
// of `@keyframes pulse`, exactly like the matching walk above.
const decoded = decodeCssEscapes(value);
if (property === "animation" || property === "animation-name") {
const { parsed, names } = parseAnimationLayers(decoded, property);
for (const node of names) {
const scoped = node ? keyframes.get(node.value) : undefined;
if (node && scoped) node.value = scoped;
}
return parsed.toString();
}
const parsed = valueParser(decoded);
parsed.walk((node) => {
if (node.type !== "word" && node.type !== "string") return;
const family = fontFamilies.get(node.value.toLowerCase());
if (family) node.value = family;
});
return parsed.toString();
}
+18
View File
@@ -43,6 +43,24 @@ export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
"host.permission",
]);
/**
* Trusted host controls that an open skin may fold into its own layout through
* `chrome.json#slots`. The key names the protected part, not a CSS hook: the
* skin only declares an anchor rectangle, the host still owns, paints and
* hit-tests the control.
*
* `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). */
export const HOST_PART_IDS: ReadonlySet<string> = new Set([
...HOST_CHROME_PART_IDS,
+78
View File
@@ -0,0 +1,78 @@
/**
* Browser-safe projections of the administrator update API.
*
* The console never receives download URLs or local paths. It selects a
* version, and the server re-resolves the official GitHub release asset
* before doing any work.
*/
export type UpdateDeploymentMode = "docker" | "release-package" | "source";
export type UpdateUpgradePath = "docker-compose" | "release-package" | "source";
export type UpdateTaskStatus =
| "downloading"
| "verifying"
| "extracting"
| "staging"
| "restarting"
| "succeeded"
| "failed";
export type UpdateStepStatus = "running" | "succeeded" | "failed";
export interface UpdateStepView {
name: string;
status: UpdateStepStatus;
at: string;
detail?: string;
}
export interface UpdateTaskView {
id: string;
status: UpdateTaskStatus;
fromVersion: string;
targetVersion: string;
startedAt: string;
updatedAt: string;
finishedAt: string | null;
errorCode: string | null;
errorMessage: string | null;
rolledBack: boolean;
steps: UpdateStepView[];
}
export interface UpdateDeploymentView {
mode: UpdateDeploymentMode;
platform: string;
architecture: string;
applyAllowed: boolean;
reasonCode: string | null;
upgradePath: UpdateUpgradePath;
}
export interface UpdateStatusView {
currentVersion: string;
deployment: UpdateDeploymentView;
task: UpdateTaskView | null;
}
export interface UpdateReleaseView {
version: string;
tag: string;
publishedAt: string;
releaseUrl: string;
assetName: string;
assetSize: number;
assetAvailable: boolean;
hasChecksums: boolean;
digest: string | null;
canApply: boolean;
blockedReason: string | null;
}
export interface UpdateCheckView {
currentVersion: string;
releases: UpdateReleaseView[];
}
export interface UpdateApplyInput {
version: string;
confirmVersion: string;
}
+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);
}
+130
View File
@@ -0,0 +1,130 @@
import assert from "node:assert/strict";
import test from "node:test";
import { existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { createTarGz, createZip } from "./test-support.js";
function fixture(t: test.TestContext, name: string, data: Buffer): { directory: string; archive: string; destination: string } {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-archive-"));
const archive = path.join(directory, name);
writeFileSync(archive, data);
t.after(() => rmSync(directory, { recursive: true, force: true }));
return { directory, archive, destination: path.join(directory, "out") };
}
function rejectsWith(code: string) {
return (error: unknown) => error instanceof ArchiveError && error.code === code;
}
test("tar.gz release archives extract files and directories", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "webspeak/", type: "directory", mode: 0o755 },
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
{ name: "webspeak/dist/index.js", data: "console.log('ok');\n", mode: 0o755 },
]));
await extractReleaseArchive(archive, destination, "release.tar.gz");
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(destination, "webspeak/dist/index.js"), "utf8"), "console.log('ok');\n");
});
test("zip release archives extract stored entries", async t => {
const { archive, destination } = fixture(t, "release.zip", createZip([
{ name: "webspeak/", directory: true },
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>" },
]));
await extractReleaseArchive(archive, destination, "release.zip");
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(destination, "webspeak/web/dist/index.html"), "utf8"), "<!doctype html>");
});
test("tar entries that traverse or use absolute paths are rejected before writing", async t => {
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:/escape.txt"]) {
const { directory, archive, destination } = fixture(t, "release.tar.gz", createTarGz([{ name, data: "owned" }]));
await assert.rejects(extractReleaseArchive(archive, destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
}
});
test("zip entries that traverse or use absolute paths are rejected before writing", async t => {
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:\\escape.txt"]) {
const { directory, archive, destination } = fixture(t, "release.zip", createZip([{ name, data: "owned" }]));
await assert.rejects(extractReleaseArchive(archive, destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
}
});
test("official relative .bin symlinks are accepted and resolve inside the package", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "webspeak/", type: "directory" },
{ name: "webspeak/node_modules/nanoid/bin/nanoid.cjs", data: "#!/usr/bin/env node\nconsole.log('nanoid');\n", mode: 0o755 },
{ name: "webspeak/node_modules/.bin/nanoid", type: "symlink", linkname: "../nanoid/bin/nanoid.cjs" },
]));
await extractReleaseArchive(archive, destination, "release.tar.gz");
const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
assert.equal(lstatSync(link).isSymbolicLink(), true);
assert.equal(readlinkSync(link), path.normalize("../nanoid/bin/nanoid.cjs"));
assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
});
test("zip relative symlinks are accepted while absolute targets are refused", async t => {
const accepted = fixture(t, "release.zip", createZip([
{ name: "webspeak/real.txt", data: "payload" },
{ name: "webspeak/link.txt", data: "real.txt", mode: 0o120777 },
]));
await extractReleaseArchive(accepted.archive, accepted.destination, "release.zip");
const link = path.join(accepted.destination, "webspeak/link.txt");
assert.equal(lstatSync(link).isSymbolicLink(), true);
assert.equal(readlinkSync(link), "real.txt");
assert.equal(readFileSync(link, "utf8"), "payload");
const refused = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
await assert.rejects(extractReleaseArchive(refused.archive, refused.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
});
test("absolute, escaping, empty and hard-link entries are refused", async t => {
const absoluteTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "/etc/passwd" }]));
await assert.rejects(extractReleaseArchive(absoluteTar.archive, absoluteTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
const driveTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "C:\\Windows\\system32" }]));
await assert.rejects(extractReleaseArchive(driveTar.archive, driveTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
const hardlink = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "hardlink", linkname: "target" }]));
await assert.rejects(extractReleaseArchive(hardlink.archive, hardlink.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
for (const linkname of ["", "..", "../outside", "a/../../../outside", "\\etc\\passwd"]) {
const escaping = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname }]));
await assert.rejects(extractReleaseArchive(escaping.archive, escaping.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(escaping.directory, "outside")), false);
}
const zipAbsolute = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
await assert.rejects(extractReleaseArchive(zipAbsolute.archive, zipAbsolute.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
});
test("unsupported archive formats and malformed archives are rejected", async t => {
const unsupported = fixture(t, "release.rar", Buffer.from("not an archive"));
await assert.rejects(extractReleaseArchive(unsupported.archive, unsupported.destination, "release.rar"), rejectsWith("UPDATE_ARCHIVE_UNSUPPORTED"));
const truncated = fixture(t, "release.tar.gz", Buffer.from("short"));
await assert.rejects(extractReleaseArchive(truncated.archive, truncated.destination, "release.tar.gz"));
const brokenZip = fixture(t, "release.zip", Buffer.alloc(64));
await assert.rejects(extractReleaseArchive(brokenZip.archive, brokenZip.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_INVALID"));
const invalidName = fixture(t, "release.tar.gz", createTarGz([{ name: "", data: "x" }]));
await assert.rejects(extractReleaseArchive(invalidName.archive, invalidName.destination, "release.tar.gz"));
});
test("declared extraction limits stop archive bombs", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "one.txt", data: "one" },
{ name: "two.txt", data: "two" },
]));
await assert.rejects(
extractReleaseArchive(archive, destination, "release.tar.gz", { maxEntries: 1 }),
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
);
const fileLimit = fixture(t, "release.zip", createZip([{ name: "big.txt", data: "1234567890" }]));
await assert.rejects(
extractReleaseArchive(fileLimit.archive, fileLimit.destination, "release.zip", { maxFileBytes: 4 }),
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
);
});
+460
View File
@@ -0,0 +1,460 @@
import { createReadStream, createWriteStream, type Stats } from "node:fs";
import { chmod, mkdir, open, stat, symlink, writeFile, type FileHandle } from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { createGunzip, createInflateRaw } from "node:zlib";
import { Transform as StreamTransform } from "node:stream";
import { pipeline } from "node:stream/promises";
export type ArchiveErrorCode =
| "UPDATE_ARCHIVE_INVALID"
| "UPDATE_ARCHIVE_UNSAFE"
| "UPDATE_ARCHIVE_LIMIT"
| "UPDATE_ARCHIVE_UNSUPPORTED";
export class ArchiveError extends Error {
constructor(readonly code: ArchiveErrorCode, message: string) {
super(message);
this.name = "ArchiveError";
}
}
export interface ExtractLimits {
maxEntries: number;
maxTotalBytes: number;
maxFileBytes: number;
}
const DEFAULT_LIMITS: ExtractLimits = {
maxEntries: 50_000,
maxTotalBytes: 4 * 1024 ** 3,
maxFileBytes: 2 * 1024 ** 3,
};
export async function extractReleaseArchive(
archivePath: string,
destination: string,
archiveName: string,
limits: Partial<ExtractLimits> = {},
): Promise<void> {
const effective = { ...DEFAULT_LIMITS, ...limits };
await mkdir(destination, { recursive: true });
if (/\.zip$/i.test(archiveName)) {
await extractZip(archivePath, destination, effective);
return;
}
if (/\.(?:tar\.gz|tgz)$/i.test(archiveName)) {
await extractTarGz(archivePath, destination, effective);
return;
}
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "Only .tar.gz and .zip release packages are supported.");
}
function unsafe(message: string): never {
throw new ArchiveError("UPDATE_ARCHIVE_UNSAFE", message);
}
function invalid(message: string): never {
throw new ArchiveError("UPDATE_ARCHIVE_INVALID", message);
}
function limitExceeded(message: string): never {
throw new ArchiveError("UPDATE_ARCHIVE_LIMIT", message);
}
/** Reject absolute paths, drive letters, parent traversal and NUL bytes. */
export function safeArchivePath(raw: string): string {
if (!raw || raw.includes("\0")) unsafe("Archive entry has an invalid name.");
const normalized = raw.replaceAll("\\", "/");
if (normalized.startsWith("/")) unsafe("Archive entry uses an absolute path.");
if (/^[A-Za-z]:/.test(normalized)) unsafe("Archive entry uses a drive-qualified path.");
const parts = normalized.split("/").filter((part) => part !== "" && part !== ".");
if (parts.some((part) => part === "..")) unsafe("Archive entry escapes the extraction directory.");
return parts.join("/");
}
function resolveEntry(destination: string, relative: string): string {
const target = path.resolve(destination, relative);
const root = path.resolve(destination);
if (target !== root && !target.startsWith(root + path.sep)) unsafe("Archive entry escapes the extraction directory.");
return target;
}
const SYMLINK_ROOT = "/__webspeak_extract_root__";
/**
* Official release packages use relative links inside node_modules/.bin
* (for example `nanoid -> ../nanoid/bin/nanoid.cjs`). A link is accepted only
* when its target is relative and, after lexical normalization, still points
* strictly inside the extraction root. Absolute paths, drive letters, parent
* traversal, empty targets and links that resolve to the root itself are
* rejected before anything is created.
*/
export function safeSymlinkTarget(entryRelative: string, rawTarget: string): string {
if (!rawTarget) unsafe("Archive symbolic link has an empty target.");
if (rawTarget.includes("\0")) unsafe("Archive symbolic link target is invalid.");
const normalized = rawTarget.replaceAll("\\", "/");
if (normalized.startsWith("/")) unsafe("Archive symbolic link uses an absolute target.");
if (/^[A-Za-z]:/.test(normalized)) unsafe("Archive symbolic link target is drive-qualified.");
const entryDirectory = path.posix.dirname(entryRelative);
const resolved = path.posix.resolve(SYMLINK_ROOT, entryDirectory === "." ? "" : entryDirectory, normalized);
if (!resolved.startsWith(`${SYMLINK_ROOT}/`)) {
unsafe("Archive symbolic link escapes the extraction directory.");
}
return normalized;
}
async function createSymlink(destination: string, relative: string, linkTarget: string): Promise<void> {
const root = path.resolve(destination);
const target = resolveEntry(destination, relative);
// Second boundary check against the real destination, not only the
// archive-relative form. The link is never dereferenced while validating.
const lexicallyResolved = path.resolve(destination, path.posix.dirname(relative), linkTarget);
if (lexicallyResolved === root || !lexicallyResolved.startsWith(root + path.sep)) {
unsafe("Archive symbolic link escapes the extraction directory.");
}
try {
await symlink(linkTarget, target);
} catch (error) {
if (error instanceof ArchiveError) throw error;
throw new ArchiveError("UPDATE_ARCHIVE_INVALID", `Archive symbolic link ${relative} could not be created.`);
}
}
function isZeroBlock(buffer: Buffer): boolean {
for (const byte of buffer) if (byte !== 0) return false;
return true;
}
function readCString(buffer: Buffer): string {
const end = buffer.indexOf(0);
return (end >= 0 ? buffer.subarray(0, end) : buffer).toString("utf8");
}
function readOctal(buffer: Buffer): number {
const text = readCString(buffer).trim();
if (!text) return 0;
if (!/^[0-7]+$/.test(text)) invalid("Archive header has an invalid numeric field.");
return Number.parseInt(text, 8);
}
function verifyTarChecksum(header: Buffer): void {
const expected = readOctal(header.subarray(148, 156));
if (!expected) return;
let sum = 0;
for (let index = 0; index < header.length; index++) {
sum += index >= 148 && index < 156 ? 0x20 : header[index];
}
if (sum !== expected) invalid("Archive header checksum does not match.");
}
interface PaxFields {
path?: string;
linkpath?: string;
}
function parsePax(buffer: Buffer): PaxFields {
const fields: PaxFields = {};
let offset = 0;
while (offset < buffer.length) {
const space = buffer.indexOf(0x20, offset);
if (space < 0) break;
const length = Number.parseInt(buffer.subarray(offset, space).toString("ascii"), 10);
if (!Number.isFinite(length) || length <= 0 || offset + length > buffer.length) break;
const record = buffer.subarray(space + 1, offset + length - 1).toString("utf8");
const equals = record.indexOf("=");
if (equals > 0) {
const key = record.slice(0, equals);
const value = record.slice(equals + 1);
if (key === "path") fields.path = value;
else if (key === "linkpath") fields.linkpath = value;
}
offset += length;
}
return fields;
}
class TarReader {
private buffer: Buffer = Buffer.alloc(0);
private readonly iterator: AsyncIterator<Buffer>;
constructor(stream: NodeJS.ReadableStream) {
this.iterator = (stream as AsyncIterable<Buffer>)[Symbol.asyncIterator]();
}
async readExact(size: number): Promise<Buffer> {
while (this.buffer.length < size) {
const next = await this.iterator.next();
if (next.done) invalid("Release archive ended unexpectedly.");
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, next.value]) : next.value;
}
const result = this.buffer.subarray(0, size);
this.buffer = this.buffer.subarray(size);
return result;
}
async skip(size: number): Promise<void> {
let remaining = size;
while (remaining > 0) {
const current = this.buffer.length ? this.buffer : undefined;
if (current) {
const take = Math.min(current.length, remaining);
this.buffer = current.subarray(take);
remaining -= take;
} else {
const next = await this.iterator.next();
if (next.done) invalid("Release archive ended unexpectedly.");
this.buffer = next.value;
}
}
}
}
async function writeAll(stream: ReturnType<typeof createWriteStream>, chunk: Buffer): Promise<void> {
if (!stream.write(chunk)) await once(stream, "drain");
}
async function extractTarGz(file: string, destination: string, limits: ExtractLimits): Promise<void> {
const reader = new TarReader(createReadStream(file).pipe(createGunzip()));
let entries = 0;
let total = 0;
let longName: string | undefined;
let pax: PaxFields = {};
for (;;) {
const header = await reader.readExact(512);
if (isZeroBlock(header)) break;
verifyTarChecksum(header);
let name = readCString(header.subarray(0, 100));
const prefix = readCString(header.subarray(345, 500));
if (prefix) name = `${prefix}/${name}`;
const size = readOctal(header.subarray(124, 136));
if (size > limits.maxFileBytes) limitExceeded("Archive entry exceeds the file size limit.");
const mode = readOctal(header.subarray(100, 108)) & 0o777;
const type = header[156] === 0 ? "0" : String.fromCharCode(header[156]);
const padded = Math.ceil(size / 512) * 512;
if (type === "L") {
if (size > 1024 * 1024) limitExceeded("Archive long-name header is too large.");
longName = (await reader.readExact(size)).toString("utf8").replace(/\0+$/, "");
await reader.skip(padded - size);
continue;
}
if (type === "x" || type === "X") {
if (size > 1024 * 1024) limitExceeded("Archive extended header is too large.");
pax = { ...pax, ...parsePax(await reader.readExact(size)) };
await reader.skip(padded - size);
continue;
}
if (type === "g") {
await reader.skip(padded);
continue;
}
const entryName = pax.path ?? longName ?? name;
const linkName = pax.linkpath ?? readCString(header.subarray(157, 257));
longName = undefined;
pax = {};
if (!entryName) invalid("Archive entry has no name.");
if (type === "1") unsafe(`Archive entry ${entryName} is a hard link; hard links are not accepted.`);
if (type !== "0" && type !== "2" && type !== "7" && type !== "5") {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `Archive entry ${entryName} has unsupported type ${type}.`);
}
entries++;
if (entries > limits.maxEntries) limitExceeded("Archive contains too many entries.");
total += size;
if (total > limits.maxTotalBytes) limitExceeded("Archive expands beyond the size limit.");
const relative = safeArchivePath(entryName);
const target = resolveEntry(destination, relative);
if (type === "5") {
await mkdir(target, { recursive: true, mode: mode || 0o755 });
await reader.skip(padded);
continue;
}
if (type === "2") {
if (size !== 0) invalid(`Archive symbolic link ${entryName} has unexpected content.`);
const linkTarget = safeSymlinkTarget(relative, linkName);
await mkdir(path.dirname(target), { recursive: true });
await createSymlink(destination, relative, linkTarget);
await reader.skip(padded);
continue;
}
await mkdir(path.dirname(target), { recursive: true });
const stream = createWriteStream(target, { mode: mode || 0o644, flags: "wx" });
try {
let remaining = size;
while (remaining > 0) {
const chunk = await reader.readExact(Math.min(remaining, 64 * 1024));
remaining -= chunk.length;
await writeAll(stream, chunk);
}
stream.end();
await once(stream, "finish");
} catch (error) {
stream.destroy();
throw error;
}
await reader.skip(padded - size);
}
}
interface ZipEntry {
name: string;
flags: number;
method: number;
compressedSize: number;
uncompressedSize: number;
localOffset: number;
mode: number;
directory: boolean;
symlink: boolean;
}
const EOCD_SIGNATURE = 0x06054b50;
const CENTRAL_SIGNATURE = 0x02014b50;
const LOCAL_SIGNATURE = 0x04034b50;
async function readZipEntryBuffer(
handle: FileHandle,
entry: ZipEntry,
file: string,
archiveSize: number,
limit: number,
): Promise<Buffer> {
const header = Buffer.alloc(30);
await handle.read(header, 0, 30, entry.localOffset);
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) invalid(`ZIP entry ${entry.name} has an invalid local header.`);
const nameLength = header.readUInt16LE(26);
const extraLength = header.readUInt16LE(28);
const dataStart = entry.localOffset + 30 + nameLength + extraLength;
if (dataStart + entry.compressedSize > archiveSize) invalid(`ZIP entry ${entry.name} is truncated.`);
if (entry.compressedSize === 0) return Buffer.alloc(0);
const chunks: Buffer[] = [];
let total = 0;
const collector = new StreamTransform({
transform(chunk: Buffer, _encoding, callback) {
total += chunk.length;
if (total > limit) {
callback(new ArchiveError("UPDATE_ARCHIVE_UNSAFE", `ZIP symbolic link ${entry.name} has an oversized target.`));
return;
}
chunks.push(chunk);
callback();
},
});
const source = createReadStream(file, { start: dataStart, end: dataStart + entry.compressedSize - 1 });
if (entry.method === 8) await pipeline(source, createInflateRaw(), collector);
else await pipeline(source, collector);
return Buffer.concat(chunks);
}
async function extractZip(file: string, destination: string, limits: ExtractLimits): Promise<void> {
const handle = await open(file, "r");
try {
const info: Stats = await handle.stat();
if (info.size < 22) invalid("ZIP archive is truncated.");
const tailSize = Math.min(info.size, 65_557);
const tail = Buffer.alloc(tailSize);
await handle.read(tail, 0, tailSize, info.size - tailSize);
let eocd = -1;
for (let index = tail.length - 22; index >= 0; index--) {
if (tail.readUInt32LE(index) === EOCD_SIGNATURE) {
const commentLength = tail.readUInt16LE(index + 20);
if (index + 22 + commentLength === tail.length) { eocd = index; break; }
}
}
if (eocd < 0) invalid("ZIP end-of-directory record was not found.");
const entryCount = tail.readUInt16LE(eocd + 10);
const directorySize = tail.readUInt32LE(eocd + 12);
const directoryOffset = tail.readUInt32LE(eocd + 16);
if (entryCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "ZIP64 release packages are not supported.");
}
if (entryCount > limits.maxEntries) limitExceeded("Archive contains too many entries.");
if (directoryOffset + directorySize > info.size) invalid("ZIP central directory is outside the archive.");
const directory = Buffer.alloc(directorySize);
await handle.read(directory, 0, directorySize, directoryOffset);
const entries: ZipEntry[] = [];
let offset = 0;
let total = 0;
for (let index = 0; index < entryCount; index++) {
if (offset + 46 > directory.length || directory.readUInt32LE(offset) !== CENTRAL_SIGNATURE) {
invalid("ZIP central directory is malformed.");
}
const versionMadeBy = directory.readUInt16LE(offset + 4);
const flags = directory.readUInt16LE(offset + 8);
const method = directory.readUInt16LE(offset + 10);
const compressedSize = directory.readUInt32LE(offset + 20);
const uncompressedSize = directory.readUInt32LE(offset + 24);
const nameLength = directory.readUInt16LE(offset + 28);
const extraLength = directory.readUInt16LE(offset + 30);
const commentLength = directory.readUInt16LE(offset + 32);
const externalAttributes = directory.readUInt32LE(offset + 38);
const localOffset = directory.readUInt32LE(offset + 42);
const nameStart = offset + 46;
if (nameStart + nameLength > directory.length) invalid("ZIP entry name is truncated.");
const name = directory.subarray(nameStart, nameStart + nameLength).toString("utf8");
offset = nameStart + nameLength + extraLength + commentLength;
if (flags & 0x1) unsafe(`ZIP entry ${name} is encrypted.`);
if (method !== 0 && method !== 8) throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `ZIP entry ${name} uses unsupported compression.`);
if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localOffset === 0xffffffff) {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "ZIP64 release packages are not supported.");
}
const unixMode = versionMadeBy >> 8 === 3 ? externalAttributes >>> 16 : 0;
const fileType = unixMode & 0o170000;
if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000 && fileType !== 0o120000) {
unsafe(`ZIP entry ${name} has an unsupported file type.`);
}
const symlinkEntry = fileType === 0o120000;
if (symlinkEntry && uncompressedSize > 64 * 1024) {
unsafe(`ZIP symbolic link ${name} has an oversized target.`);
}
const directoryEntry = !symlinkEntry && (name.endsWith("/") || fileType === 0o040000);
if (!directoryEntry && uncompressedSize > limits.maxFileBytes) limitExceeded("Archive entry exceeds the file size limit.");
total += directoryEntry ? 0 : uncompressedSize;
if (total > limits.maxTotalBytes) limitExceeded("Archive expands beyond the size limit.");
entries.push({
name, flags, method, compressedSize, uncompressedSize, localOffset,
mode: unixMode & 0o777, directory: directoryEntry, symlink: symlinkEntry,
});
}
for (const entry of entries) {
const relative = safeArchivePath(entry.name);
if (!relative) invalid("ZIP entry has an empty path.");
const target = resolveEntry(destination, relative);
if (entry.directory) {
await mkdir(target, { recursive: true, mode: entry.mode || 0o755 });
continue;
}
await mkdir(path.dirname(target), { recursive: true });
if (entry.symlink) {
const rawTarget = (await readZipEntryBuffer(handle, entry, file, info.size, 64 * 1024)).toString("utf8");
const linkTarget = safeSymlinkTarget(relative, rawTarget);
await createSymlink(destination, relative, linkTarget);
continue;
}
if (entry.compressedSize === 0) {
await writeFile(target, Buffer.alloc(0), { mode: entry.mode || 0o644, flag: "wx" });
continue;
}
const header = Buffer.alloc(30);
await handle.read(header, 0, 30, entry.localOffset);
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) invalid(`ZIP entry ${entry.name} has an invalid local header.`);
const nameLength = header.readUInt16LE(26);
const extraLength = header.readUInt16LE(28);
const dataStart = entry.localOffset + 30 + nameLength + extraLength;
if (dataStart + entry.compressedSize > info.size) invalid(`ZIP entry ${entry.name} is truncated.`);
const source = createReadStream(file, { start: dataStart, end: dataStart + entry.compressedSize - 1 });
let writtenBytes = 0;
const limiter = new StreamTransform({
transform(chunk: Buffer, _encoding, callback) {
writtenBytes += chunk.length;
if (writtenBytes > entry.uncompressedSize) callback(new ArchiveError("UPDATE_ARCHIVE_INVALID", `ZIP entry ${entry.name} exceeds its declared size.`));
else callback(null, chunk);
},
});
const sink = createWriteStream(target, { mode: entry.mode || 0o644, flags: "wx" });
if (entry.method === 8) await pipeline(source, createInflateRaw(), limiter, sink);
else await pipeline(source, limiter, sink);
const written = await stat(target);
if (written.size !== entry.uncompressedSize) invalid(`ZIP entry ${entry.name} has an unexpected size.`);
if (entry.mode) await chmod(target, entry.mode);
}
} finally {
await handle.close();
}
}
+188
View File
@@ -0,0 +1,188 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
CodeSwapError, locatePackageRoot, restoreCode, setCodeSwapCopyForTests, swapCode, validateStagedPackage,
} from "./code-swap.js";
import { createPackageFiles } from "./test-support.js";
function workspace(t: TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function packageInvalid(error: unknown): boolean {
return error instanceof CodeSwapError && error.code === "UPDATE_PACKAGE_INVALID";
}
function persistentState(root: string): void {
writeFileSync(path.join(root, "config.json"), JSON.stringify({ siteName: "kept" }));
for (const [directory, file] of [["data", "webspeak.db"], ["certs", "cert.pem"], ["skins", "skin.json"], ["plugins", "plugin.json"]]) {
mkdirSync(path.join(root, directory), { recursive: true });
writeFileSync(path.join(root, directory, file), `${directory}-content`);
}
}
test("staged packages must be complete, regular files and version-matched", t => {
const root = workspace(t);
createPackageFiles(root, "0.4.0");
assert.doesNotThrow(() => validateStagedPackage(root, { version: "0.4.0", platform: "linux" }));
assert.throws(() => validateStagedPackage(root, { version: "0.4.1", platform: "linux" }), packageInvalid);
const missing = workspace(t);
createPackageFiles(missing, "0.4.0");
rmSync(path.join(missing, "runtime", "node"));
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
const 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"));
symlinkSync(process.execPath, path.join(linked, "runtime", "node"));
assert.throws(() => validateStagedPackage(linked, { version: "0.4.0", platform: "linux" }), packageInvalid);
});
test("locatePackageRoot accepts both bare and single-wrapper layouts", t => {
const bare = workspace(t);
createPackageFiles(bare, "0.4.0");
assert.equal(locatePackageRoot(bare, "0.4.0", "linux"), bare);
const wrapped = workspace(t);
createPackageFiles(path.join(wrapped, "webspeak"), "0.4.0");
assert.equal(locatePackageRoot(wrapped, "0.4.0", "linux"), path.join(wrapped, "webspeak"));
const missing = workspace(t);
assert.throws(() => locatePackageRoot(missing, "0.4.0", "linux"), packageInvalid);
});
test("code swap replaces only code and preserves data, config, certs, skins and plugins", t => {
const root = workspace(t), staged = path.join(workspace(t), "staged"), backup = path.join(workspace(t), "backup");
mkdirSync(path.join(root, "dist"), { recursive: true });
mkdirSync(path.join(root, "node_modules"), { recursive: true });
writeFileSync(path.join(root, "dist", "index.js"), "old code");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
writeFileSync(path.join(root, "node_modules", "old.txt"), "old dependency");
persistentState(root);
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code", "node_modules/new.txt": "new dependency" });
swapCode(root, staged, backup);
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "new code");
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(root, "node_modules", "new.txt"), "utf8"), "new dependency");
assert.equal(readFileSync(path.join(backup, "dist", "index.js"), "utf8"), "old code");
assert.equal(readFileSync(path.join(backup, "node_modules", "old.txt"), "utf8"), "old dependency");
for (const [directory, file, contents] of [
["data", "webspeak.db", "data-content"], ["certs", "cert.pem", "certs-content"],
["skins", "skin.json", "skins-content"], ["plugins", "plugin.json", "plugins-content"],
]) {
assert.equal(readFileSync(path.join(root, directory, file), "utf8"), contents);
assert.equal(existsSync(path.join(backup, directory)), false);
}
assert.deepEqual(JSON.parse(readFileSync(path.join(root, "config.json"), "utf8")), { siteName: "kept" });
assert.equal(existsSync(path.join(backup, "config.json")), false);
});
test("code swap copies across filesystems when rename reports EXDEV", t => {
const shared = "/dev/shm";
if (!existsSync(shared)) {
t.skip("no separate filesystem available for the EXDEV test");
return;
}
const root = path.join(workspace(t), "root"), backup = path.join(workspace(t), "backup");
const stagedBase = mkdtempSync(path.join(shared, "webspeak-swap-xdev-"));
t.after(() => rmSync(stagedBase, { recursive: true, force: true }));
const staged = path.join(stagedBase, "staged");
mkdirSync(path.join(root, "dist"), { recursive: true });
writeFileSync(path.join(root, "dist", "index.js"), "old code");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code", "node_modules/new.txt": "new dependency" });
if (statSync(root).dev === statSync(staged).dev) {
t.skip("tmp and /dev/shm share a device on this system");
return;
}
swapCode(root, staged, backup);
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "new code");
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(root, "node_modules", "new.txt"), "utf8"), "new dependency");
assert.equal(readFileSync(path.join(backup, "dist", "index.js"), "utf8"), "old code");
// The copy fallback removes the source only after a successful copy.
assert.equal(existsSync(path.join(staged, "dist")), false);
assert.equal(existsSync(path.join(staged, "package.json")), false);
});
test("a cross-device copy that fails halfway leaves the complete previous tree in place", t => {
const shared = "/dev/shm";
if (!existsSync(shared)) {
t.skip("no separate filesystem available for the EXDEV test");
return;
}
const root = path.join(workspace(t), "root"), backup = path.join(workspace(t), "backup");
const stagedBase = mkdtempSync(path.join(shared, "webspeak-swap-fail-"));
t.after(() => {
setCodeSwapCopyForTests(null);
rmSync(stagedBase, { recursive: true, force: true });
});
const staged = path.join(stagedBase, "staged");
mkdirSync(path.join(root, "dist"), { recursive: true });
writeFileSync(path.join(root, "dist", "index.js"), "old code");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
persistentState(root);
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code" });
if (statSync(root).dev === statSync(staged).dev) {
t.skip("tmp and /dev/shm share a device on this system");
return;
}
let copies = 0;
setCodeSwapCopyForTests((_from, to) => {
copies += 1;
// Simulate the fallback copy dying after it has written part of the
// entry, which is exactly the state that must never reach the root.
mkdirSync(to, { recursive: true });
writeFileSync(path.join(to, "index.js"), "half");
throw new Error("simulated copy failure");
});
assert.throws(() => swapCode(root, staged, backup), (error: unknown) =>
error instanceof CodeSwapError && error.code === "UPDATE_SWAP_FAILED");
assert.equal(copies, 1);
// The previous tree was restored completely, with no half-copied entry.
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "old code");
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.3.2");
assert.equal(readFileSync(path.join(root, "data", "webspeak.db"), "utf8"), "data-content");
assert.deepEqual(readdirSync(root).filter((entry) => entry.includes(".copy-")), []);
// The backup was not turned into a half-copied source for a later restore.
assert.equal(existsSync(path.join(backup, "dist", "index.js")), false);
// A failed copy leaves the staged package untouched for diagnosis/retry.
assert.equal(readFileSync(path.join(staged, "dist", "index.js"), "utf8"), "new code");
});
test("restoreCode returns the previous code and keeps rejected code for inspection", t => {
const root = workspace(t), staged = path.join(workspace(t), "staged"), backup = path.join(workspace(t), "backup");
mkdirSync(path.join(root, "dist"), { recursive: true });
writeFileSync(path.join(root, "dist", "index.js"), "old code");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
persistentState(root);
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code" });
swapCode(root, staged, backup);
restoreCode(root, backup);
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "old code");
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.3.2");
assert.equal(readFileSync(path.join(backup, "rejected", "dist", "index.js"), "utf8"), "new code");
assert.equal(readFileSync(path.join(root, "data", "webspeak.db"), "utf8"), "data-content");
assert.throws(() => restoreCode(root, path.join(root, "absent-backup")), (error: unknown) =>
error instanceof CodeSwapError && error.code === "UPDATE_ROLLBACK_FAILED");
});
+259
View File
@@ -0,0 +1,259 @@
import { randomBytes } from "node:crypto";
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { parseStableVersion } from "./version.js";
/**
* Only package code is ever moved. Persistent state (data/, config.json,
* certs/) is deliberately absent from this list.
*/
export const CODE_ENTRIES = [
"dist",
"web/dist",
"node_modules",
"runtime",
"package.json",
"package-lock.json",
"README.md",
"LICENSE",
"config.example.json",
// start-webspeak.sh is deliberately absent: the launcher must stay at the
// install root for the whole swap so an interrupted update can still be
// recovered by running ./start-webspeak.sh. It is installed atomically by
// the updater before the runner swaps any code.
"start-webspeak.cmd",
] as const;
export type CodeSwapErrorCode = "UPDATE_PACKAGE_INVALID" | "UPDATE_SWAP_FAILED" | "UPDATE_ROLLBACK_FAILED";
export class CodeSwapError extends Error {
constructor(readonly code: CodeSwapErrorCode, message: string) {
super(message);
this.name = "CodeSwapError";
}
}
export interface StagedPackageOptions {
version: string;
platform?: NodeJS.Platform;
}
function requireEntry(root: string, relative: string, kind: "file" | "directory"): void {
const target = path.join(root, relative);
let stats;
try { stats = lstatSync(target); }
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package is missing ${relative}.`); }
if (stats.isSymbolicLink()) throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package entry ${relative} is a symbolic link.`);
if (kind === "file" ? !stats.isFile() : !stats.isDirectory()) {
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package entry ${relative} has the wrong type.`);
}
}
/** The extracted package must be a complete runnable release for this platform. */
export function validateStagedPackage(root: string, options: StagedPackageOptions): void {
requireEntry(root, "dist/index.js", "file");
requireEntry(root, "web/dist/index.html", "file");
requireEntry(root, "node_modules", "directory");
requireEntry(root, "package.json", "file");
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
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."); }
const version = manifest && typeof manifest === "object" && !Array.isArray(manifest)
? (manifest as Record<string, unknown>).version
: undefined;
if (!parseStableVersion(version) || version !== options.version) {
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package version does not match the selected release.");
}
}
/** Archives usually contain one wrapper directory; accept both layouts. */
export function locatePackageRoot(extractedDir: string, version: string, platform?: NodeJS.Platform): string {
const entries = readdirSync(extractedDir, { withFileTypes: true });
const root = entries.length === 1 && entries[0].isDirectory()
? path.join(extractedDir, entries[0].name)
: extractedDir;
if (!existsSync(path.join(root, "package.json"))) {
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package root was not found after extraction.");
}
validateStagedPackage(root, { version, platform });
return root;
}
function moveEntry(from: string, to: string): void {
try {
renameSync(from, to);
return;
} catch (error) {
// Staging and backups may live on another filesystem than the install
// directory. A rename cannot cross devices, so fall back to a copy.
if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
}
// Copy into a temporary sibling first: a failure halfway through must
// never leave a partial entry at `to`, because rollback would otherwise
// mistake it for the complete previous version.
const temporary = `${to}.copy-${process.pid}-${randomBytes(6).toString("hex")}`;
try {
copyEntry(from, temporary);
renameSync(temporary, to);
} catch (error) {
rmSync(temporary, { recursive: true, force: true });
throw error;
}
// The copy is committed at `to`. Removing the source is cleanup only.
try { rmSync(from, { recursive: true, force: true }); } catch { /* Source remains for later cleanup. */ }
}
type CopyEntry = (from: string, to: string) => void;
const defaultCopyEntry: CopyEntry = (from, to) => {
cpSync(from, to, { recursive: true, force: false, errorOnExist: true, preserveTimestamps: true });
};
let copyEntry: CopyEntry = defaultCopyEntry;
/** Test seam for exercising a cross-device copy that fails halfway through. */
export function setCodeSwapCopyForTests(copy: CopyEntry | null): void {
copyEntry = copy ?? defaultCopyEntry;
}
/**
* Test-only fault-injection seam. When the named directory exists, the swap
* pauses in the exact window between "old code moved aside" and "new code
* moved in" so a test can SIGKILL the runner. Production never sets this
* variable; it is a local barrier directory, not a URL or network switch.
*/
const SWAP_BARRIER_ENV = "WEBSPEAK_TEST_SWAP_BARRIER_DIR";
function swapWindowBarrier(entry?: string): void {
const directory = process.env[SWAP_BARRIER_ENV];
if (!directory || !existsSync(directory)) return;
if ((process.env.WEBSPEAK_TEST_SWAP_BARRIER_AFTER_ENTRY ?? "") !== (entry ?? "")) return;
writeFileSync(path.join(directory, "swap-window-reached"), String(process.pid));
const resume = path.join(directory, "resume");
const deadline = Date.now() + 30_000;
const waiter = new Int32Array(new SharedArrayBuffer(4));
while (!existsSync(resume) && Date.now() < deadline) {
Atomics.wait(waiter, 0, 0, 20);
}
}
function moveIfPresent(from: string, to: string): void {
if (!existsSync(from)) return;
mkdirSync(path.dirname(to), { recursive: true });
moveEntry(from, to);
}
/**
* Backups written by this version 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";
function writeSwapManifest(backupDir: string, entries: string[]): void {
const target = path.join(backupDir, SWAP_MANIFEST);
const temporary = `${target}.${process.pid}.tmp`;
writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, entries }, null, 2), "utf8");
renameSync(temporary, target);
}
function readSwapManifest(backupDir: string): Set<string> | null {
try {
const parsed: unknown = JSON.parse(readFileSync(path.join(backupDir, SWAP_MANIFEST), "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
const record = parsed as Record<string, unknown>;
if (record.schemaVersion !== 1 || !Array.isArray(record.entries)) return null;
return new Set(record.entries.filter((entry): entry is string => typeof entry === "string"));
} catch {
return null;
}
}
/**
* Undo only the entries that this swap actually moved. The entry whose move
* failed is left untouched: its source is still intact and no partial
* destination exists.
*/
function restoreMovedEntries(rootDir: string, backupDir: string, movedToBackup: string[], movedToRoot: string[]): void {
const rejected = path.join(backupDir, "rejected");
for (const entry of [...movedToRoot].reverse()) {
moveIfPresent(path.join(rootDir, entry), path.join(rejected, entry));
}
for (const entry of [...movedToBackup].reverse()) {
const saved = path.join(backupDir, entry);
if (!existsSync(saved)) continue;
const current = path.join(rootDir, entry);
if (existsSync(current)) moveIfPresent(current, path.join(rejected, entry));
moveIfPresent(saved, current);
}
}
/**
* Move the previous code aside, then move the verified side-by-side package
* into place. `data/`, `config.json` and `certs/` are never in CODE_ENTRIES.
*/
export function swapCode(rootDir: string, stagedRoot: string, backupDir: string): void {
const movedToBackup: string[] = [];
const movedToRoot: string[] = [];
try {
if (existsSync(backupDir)) throw new Error("Backup directory already exists.");
mkdirSync(backupDir, { recursive: true });
writeSwapManifest(backupDir, []);
for (const entry of CODE_ENTRIES) {
if (!existsSync(path.join(rootDir, entry))) continue;
movedToBackup.push(entry);
writeSwapManifest(backupDir, movedToBackup);
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
swapWindowBarrier(entry);
}
swapWindowBarrier();
for (const entry of CODE_ENTRIES) {
if (!existsSync(path.join(stagedRoot, entry))) continue;
moveIfPresent(path.join(stagedRoot, entry), path.join(rootDir, entry));
movedToRoot.push(entry);
}
} catch (error) {
try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
catch (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.");
}
}
/**
* Restore the previous code. New code is moved aside instead of deleted so it
* remains available for diagnostics. When a swap manifest exists, only
* entries it proves were moved completely are considered.
*/
export function restoreCode(rootDir: string, backupDir: string): void {
if (!existsSync(backupDir)) throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", "Code backup directory is missing.");
const manifest = readSwapManifest(backupDir);
const rejected = path.join(backupDir, "rejected");
try {
for (const entry of CODE_ENTRIES) {
if (manifest && !manifest.has(entry)) continue;
const current = path.join(rootDir, entry);
if (existsSync(current) && existsSync(path.join(backupDir, entry))) {
moveIfPresent(current, path.join(rejected, entry));
}
}
for (const entry of CODE_ENTRIES) {
if (manifest && !manifest.has(entry)) continue;
moveIfPresent(path.join(backupDir, entry), path.join(rootDir, entry));
}
} catch (error) {
throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", error instanceof Error ? error.message : "Code rollback failed.");
}
}
export function removeStagingDirectory(directory: string): void {
try { rmSync(directory, { recursive: true, force: true }); } catch { /* Best-effort cleanup. */ }
}
+182
View File
@@ -0,0 +1,182 @@
import assert from "node:assert/strict";
import test from "node:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
assetKindFor, detectDeployment as detectRealDeployment, isReleasePackageRoot, releaseAssetName, runningUnderSupervisor, upgradePathFor,
} from "./deployment.js";
import type { DeploymentDetectionOptions } from "./deployment.js";
// Tests may themselves run inside the CI runner's systemd service.
function detectDeployment(options: DeploymentDetectionOptions) {
return detectRealDeployment({ isSupervised: false, ...options });
}
function temporary(t: test.TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-deployment-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function releasePackageRoot(t: test.TestContext, platform: "linux" | "win32" = "linux"): string {
const root = temporary(t);
const runtime = platform === "win32" ? "node.exe" : "node";
for (const directory of ["runtime", "dist", "web/dist"]) mkdirSync(path.join(root, directory), { recursive: true });
writeFileSync(path.join(root, "runtime", runtime), "");
writeFileSync(path.join(root, "dist", "index.js"), "");
writeFileSync(path.join(root, "web", "dist", "index.html"), "");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "1.0.0" }));
return root;
}
test("an explicit release-package override cannot bypass container detection", () => {
const env = { WEBSPEAK_DEPLOYMENT_MODE: "release-package" };
const info = detectDeployment({ rootDir: "/does/not/exist", env, isDocker: true, platform: "linux", architecture: "x64" });
assert.equal(info.mode, "docker");
assert.equal(info.applyAllowed, false);
assert.equal(info.reasonCode, "DEPLOYMENT_DOCKER");
assert.equal(info.upgradePath, "docker-compose");
});
test("an explicit release-package override requires a complete package tree", t => {
const missing = detectDeployment({
rootDir: "/does/not/exist",
env: { WEBSPEAK_DEPLOYMENT_MODE: "release-package" },
isDocker: false,
platform: "linux",
architecture: "x64",
});
assert.equal(missing.mode, "source");
assert.equal(missing.applyAllowed, false);
assert.equal(missing.reasonCode, "DEPLOYMENT_SOURCE");
const root = releasePackageRoot(t);
const complete = detectDeployment({
rootDir: root,
env: { WEBSPEAK_DEPLOYMENT_MODE: "release-package" },
isDocker: false,
platform: "linux",
architecture: "x64",
});
assert.equal(complete.mode, "release-package");
assert.equal(complete.applyAllowed, true);
assert.equal(complete.reasonCode, null);
});
test("docker and source deployments never allow an in-console apply", () => {
const docker = detectDeployment({ rootDir: "/does/not/exist", env: {}, isDocker: true, platform: "linux", architecture: "x64" });
assert.deepEqual(
{ mode: docker.mode, applyAllowed: docker.applyAllowed, reasonCode: docker.reasonCode, upgradePath: docker.upgradePath },
{ mode: "docker", applyAllowed: false, reasonCode: "DEPLOYMENT_DOCKER", upgradePath: "docker-compose" },
);
const source = detectDeployment({ rootDir: "/does/not/exist", env: {}, isDocker: false, platform: "linux", architecture: "x64" });
assert.deepEqual(
{ mode: source.mode, applyAllowed: source.applyAllowed, reasonCode: source.reasonCode, upgradePath: source.upgradePath },
{ mode: "source", applyAllowed: false, reasonCode: "DEPLOYMENT_SOURCE", upgradePath: "source" },
);
});
test("a complete packaged tree is detected as a release package", t => {
const root = releasePackageRoot(t);
assert.equal(isReleasePackageRoot(root, "linux"), true);
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
assert.equal(info.mode, "release-package");
assert.equal(info.assetKind, "linux-arm64");
assert.equal(info.applyAllowed, false);
assert.equal(info.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
assert.equal(detectDeployment({ rootDir: root, env: { WEBSPEAK_DEPLOYMENT_MODE: "docker" }, isDocker: false, platform: "linux" }).mode, "docker");
});
test("incomplete trees stay in source mode", t => {
const root = temporary(t);
assert.equal(isReleasePackageRoot(root, "linux"), false);
mkdirSync(path.join(root, "runtime"), { recursive: true });
writeFileSync(path.join(root, "runtime", "node"), "");
assert.equal(isReleasePackageRoot(root, "linux"), false);
});
test("asset names and platform support are pinned to official release shapes", () => {
assert.equal(assetKindFor("linux", "x64"), "linux-x64");
assert.equal(assetKindFor("linux", "arm64"), "linux-arm64");
assert.equal(assetKindFor("win32", "x64"), "windows-x64");
assert.equal(assetKindFor("linux", "riscv64"), null);
assert.equal(assetKindFor("darwin", "arm64"), null);
assert.equal(releaseAssetName("0.4.0", "linux-x64"), "webspeak-webclient-v0.4.0-linux-x64.tar.gz");
assert.equal(releaseAssetName("0.4.0", "linux-arm64"), "webspeak-webclient-v0.4.0-linux-arm64.tar.gz");
assert.equal(releaseAssetName("0.4.0", "windows-x64"), "webspeak-webclient-v0.4.0-windows-x64.zip");
assert.equal(upgradePathFor("docker"), "docker-compose");
assert.equal(upgradePathFor("release-package"), "release-package");
assert.equal(upgradePathFor("source"), "source");
});
test("windows release packages are visible but apply stays disabled", t => {
const root = releasePackageRoot(t, "win32");
const windows = detectDeployment({
rootDir: root,
env: {},
isDocker: false,
platform: "win32",
architecture: "x64",
});
assert.equal(windows.mode, "release-package");
assert.equal(windows.assetKind, "windows-x64");
assert.equal(windows.applyAllowed, false);
assert.equal(windows.reasonCode, "WINDOWS_APPLY_UNVERIFIED");
assert.equal(windows.upgradePath, "release-package");
const linux = detectDeployment({
rootDir: releasePackageRoot(t),
env: {},
isDocker: false,
platform: "linux",
architecture: "x64",
});
assert.equal(linux.applyAllowed, true);
assert.equal(linux.reasonCode, null);
});
test("linux arm64 release packages are checkable but apply is gated off", t => {
const root = releasePackageRoot(t);
const arm64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
assert.equal(arm64.mode, "release-package");
assert.equal(arm64.assetKind, "linux-arm64");
assert.equal(arm64.applyAllowed, false);
assert.equal(arm64.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
assert.equal(arm64.upgradePath, "release-package");
const x64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "x64" });
assert.equal(x64.applyAllowed, true);
assert.equal(x64.reasonCode, null);
});
test("unsupported platforms are visible but cannot apply", t => {
const root = releasePackageRoot(t);
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "s390x" });
assert.equal(info.mode, "release-package");
assert.equal(info.applyAllowed, false);
assert.equal(info.reasonCode, "ARCH_UNSUPPORTED");
const darwin = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "darwin", architecture: "arm64" });
assert.equal(darwin.applyAllowed, false);
assert.equal(darwin.reasonCode, "PLATFORM_UNSUPPORTED");
});
test("supervised packages cannot apply even with a release-package override", t => {
const root = releasePackageRoot(t);
for (const env of [{ INVOCATION_ID: "unit-invocation" }, { pm_id: "0" }, { SUPERVISOR_PROCESS_NAME: "webspeak" }]) {
assert.equal(runningUnderSupervisor(env, ""), true);
const deployment = detectDeployment({ rootDir: root, platform: "linux", architecture: "x64", isDocker: false,
isSupervised: undefined, env: { ...env, WEBSPEAK_DEPLOYMENT_MODE: "release-package" } });
assert.equal(deployment.mode, "release-package");
assert.equal(deployment.applyAllowed, false);
assert.equal(deployment.reasonCode, "DEPLOYMENT_SUPERVISED");
assert.equal(deployment.assetKind, "linux-x64");
}
});
test("service cgroups are detected without blocking interactive user scopes", () => {
assert.equal(runningUnderSupervisor({}, "0::/system.slice/webspeak.service\n"), true);
assert.equal(runningUnderSupervisor({}, "0::/user.slice/user-1000.slice/user@1000.service/app.slice/webspeak.service\n"), true);
assert.equal(runningUnderSupervisor({}, "0::/user.slice/user-1000.slice/user@1000.service/app.slice/terminal.scope\n"), false);
assert.equal(runningUnderSupervisor({}, "0::/\n"), false);
});
+121
View File
@@ -0,0 +1,121 @@
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import type { UpdateDeploymentMode, UpdateDeploymentView, UpdateUpgradePath } from "../shared/update.js";
export interface DeploymentDetectionOptions {
rootDir: string;
platform?: NodeJS.Platform;
architecture?: string;
env?: NodeJS.ProcessEnv;
/** Test seam; omitted means inspect the real container markers. */
isDocker?: boolean;
/** Test seam; omitted means inspect service-manager environment and cgroups. */
isSupervised?: boolean;
}
export interface DeploymentInfo extends UpdateDeploymentView {
platform: NodeJS.Platform;
assetKind: "linux-x64" | "linux-arm64" | "windows-x64" | null;
}
export function detectDeployment(options: DeploymentDetectionOptions): DeploymentInfo {
const platform = options.platform ?? process.platform;
const architecture = options.architecture ?? process.arch;
const env = options.env ?? process.env;
const explicit = env.WEBSPEAK_DEPLOYMENT_MODE?.trim().toLowerCase();
const packaged = isReleasePackageRoot(options.rootDir, platform);
let mode: UpdateDeploymentMode;
// Container detection always wins: an explicit "release-package" override
// must never make an image replaceable from inside the container.
if (explicit === "docker" || (options.isDocker ?? runningInContainer(env))) {
mode = "docker";
} else if (explicit === "source") {
mode = "source";
} else {
// An explicit "release-package" only counts when the tree really is a
// complete release package; otherwise applying would be unsafe.
mode = packaged ? "release-package" : "source";
}
const assetKind = mode === "release-package" ? assetKindFor(platform, architecture) : null;
let applyAllowed = mode === "release-package" && assetKind !== null;
let reasonCode: string | null = null;
if (mode === "docker") reasonCode = "DEPLOYMENT_DOCKER";
else if (mode === "source") reasonCode = "DEPLOYMENT_SOURCE";
else if (!assetKind) reasonCode = platform !== "linux" && platform !== "win32" ? "PLATFORM_UNSUPPORTED" : "ARCH_UNSUPPORTED";
else if (platform === "win32") {
// The copy-node.exe-then-swap approach has not been verified against a
// real Windows release package. Report versions, but never fake an apply.
applyAllowed = false;
reasonCode = "WINDOWS_APPLY_UNVERIFIED";
} else if (platform === "linux" && architecture === "arm64") {
// arm64 packages are built and can be checked, but the in-place swap has
// only been exercised on x64. Gate on the detected capability itself so
// "unverified" is never rendered as "can apply" in the UI.
applyAllowed = false;
reasonCode = "LINUX_ARM64_APPLY_UNVERIFIED";
} else if (options.isSupervised ?? runningUnderSupervisor(env)) {
// A detached child stays inside its systemd cgroup, and other supervisors
// can restart the old app while the runner is swapping it. Until there is
// a supervisor-aware handoff, only foreground packages may apply updates.
applyAllowed = false;
reasonCode = "DEPLOYMENT_SUPERVISED";
}
return {
mode,
platform,
architecture,
applyAllowed,
reasonCode,
upgradePath: upgradePathFor(mode),
assetKind,
};
}
export function runningUnderSupervisor(env: NodeJS.ProcessEnv = process.env, cgroup?: string): boolean {
if (["INVOCATION_ID", "JOURNAL_STREAM", "NOTIFY_SOCKET", "SYSTEMD_EXEC_PID", "pm_id", "PM2_HOME", "SUPERVISOR_ENABLED", "SUPERVISOR_PROCESS_NAME"]
.some((name) => Boolean(env[name]?.trim()))) return true;
if (cgroup === undefined) {
try { cgroup = readFileSync("/proc/self/cgroup", "utf8"); }
catch { return false; }
}
// The user manager itself is not the app's supervisor: interactive shells
// also run below user@UID.service. App-specific services still count.
return cgroup.split(/[\n/]/).some((part) => part.endsWith(".service") && !/^user@\d+\.service$/.test(part));
}
export function runningInContainer(env: NodeJS.ProcessEnv = process.env): boolean {
if (env.WEBSPEAK_DEPLOYMENT_MODE?.trim().toLowerCase() === "docker") return true;
if (existsSync("/.dockerenv")) return true;
if (env.container) return true;
try {
const cgroup = readFileSync("/proc/1/cgroup", "utf8");
return /(?:docker|kubepods|containerd|libpod|podman)/i.test(cgroup);
} catch {
return false;
}
}
export function isReleasePackageRoot(rootDir: string, platform: NodeJS.Platform = process.platform): boolean {
const runtime = platform === "win32" ? path.join(rootDir, "runtime", "node.exe") : path.join(rootDir, "runtime", "node");
return existsSync(runtime)
&& existsSync(path.join(rootDir, "dist", "index.js"))
&& existsSync(path.join(rootDir, "web", "dist", "index.html"))
&& existsSync(path.join(rootDir, "package.json"));
}
export function assetKindFor(platform: NodeJS.Platform, architecture: string): DeploymentInfo["assetKind"] {
if (platform === "win32" && architecture === "x64") return "windows-x64";
if (platform === "linux" && architecture === "x64") return "linux-x64";
if (platform === "linux" && architecture === "arm64") return "linux-arm64";
return null;
}
export function releaseAssetName(version: string, assetKind: NonNullable<DeploymentInfo["assetKind"]>): string {
return assetKind === "windows-x64"
? `webspeak-webclient-v${version}-windows-x64.zip`
: `webspeak-webclient-v${version}-${assetKind}.tar.gz`;
}
export function upgradePathFor(mode: UpdateDeploymentMode): UpdateUpgradePath {
return mode === "docker" ? "docker-compose" : mode === "release-package" ? "release-package" : "source";
}
+161
View File
@@ -0,0 +1,161 @@
import { compareVersions, parseReleaseTag } from "./version.js";
export const OFFICIAL_REPOSITORY = "EchoSixHIYA/WebSpeak-client-for-TeamSpeak";
export const CHECKSUM_ASSET_NAME = "SHA256SUMS.txt";
export interface ReleaseAsset {
name: string;
size: number;
url: string;
digest: string | null;
}
export interface OfficialRelease {
version: string;
tag: string;
publishedAt: string;
releaseUrl: string;
assets: ReleaseAsset[];
}
export type ReleaseSourceErrorCode = "UPDATE_RELEASE_UNAVAILABLE";
export class ReleaseSourceError extends Error {
readonly code: ReleaseSourceErrorCode = "UPDATE_RELEASE_UNAVAILABLE";
constructor(message: string) {
super(message);
this.name = "ReleaseSourceError";
}
}
export interface ReleaseSourceOptions {
fetch?: typeof fetch;
apiBaseUrl?: string;
repository?: string;
userAgent?: string;
timeoutMs?: number;
}
const ALLOWED_DOWNLOAD_HOSTS = new Set([
"github.com",
"api.github.com",
"objects.githubusercontent.com",
"release-assets.githubusercontent.com",
]);
export class GitHubReleaseSource {
private readonly fetcher: typeof fetch;
private readonly apiBaseUrl: string;
private readonly repository: string;
private readonly userAgent: string;
private readonly timeoutMs: number;
constructor(options: ReleaseSourceOptions = {}) {
this.fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
this.apiBaseUrl = (options.apiBaseUrl ?? "https://api.github.com").replace(/\/+$/, "");
this.repository = options.repository ?? OFFICIAL_REPOSITORY;
this.userAgent = options.userAgent ?? "WebSpeak-Console-Updater";
this.timeoutMs = options.timeoutMs ?? 12_000;
}
private get owner(): string {
return this.repository.split("/")[0];
}
private get repo(): string {
return this.repository.split("/")[1];
}
async listStableReleases(): Promise<OfficialRelease[]> {
let response: Response;
try {
response = await this.fetcher(`${this.apiBaseUrl}/repos/${this.repository}/releases?per_page=30`, {
headers: {
accept: "application/vnd.github+json",
"user-agent": this.userAgent,
"x-github-api-version": "2022-11-28",
},
signal: AbortSignal.timeout(this.timeoutMs),
redirect: "error",
});
} catch {
throw new ReleaseSourceError("The official release list could not be reached.");
}
if (!response.ok) throw new ReleaseSourceError(`The official release list returned HTTP ${response.status}.`);
let value: unknown;
try { value = await response.json(); }
catch { throw new ReleaseSourceError("The official release list is not valid JSON."); }
if (!Array.isArray(value)) throw new ReleaseSourceError("The official release list is not an array.");
const releases: OfficialRelease[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
if (record.draft === true || record.prerelease === true) continue;
const tag = typeof record.tag_name === "string" ? record.tag_name : "";
const version = parseReleaseTag(tag)?.text;
if (!version || seen.has(version)) continue;
const releaseUrl = typeof record.html_url === "string" ? record.html_url : "";
if (!isOfficialReleasePage(releaseUrl, this.owner, this.repo)) continue;
const assets: ReleaseAsset[] = [];
if (Array.isArray(record.assets)) {
for (const asset of record.assets) {
if (!asset || typeof asset !== "object" || Array.isArray(asset)) continue;
const item = asset as Record<string, unknown>;
const name = typeof item.name === "string" ? item.name : "";
const url = typeof item.browser_download_url === "string" ? item.browser_download_url : "";
if (!name || !url) continue;
try { assertOfficialDownloadUrl(url, this.owner, this.repo); }
catch { continue; }
assets.push({
name,
size: typeof item.size === "number" && Number.isFinite(item.size) ? item.size : 0,
url,
digest: typeof item.digest === "string" && item.digest ? item.digest : null,
});
}
}
seen.add(version);
releases.push({
version,
tag,
publishedAt: typeof record.published_at === "string" ? record.published_at : "",
releaseUrl,
assets,
});
}
return releases.sort((left, right) => compareVersions(right.version, left.version));
}
async findRelease(version: string): Promise<OfficialRelease | null> {
const releases = await this.listStableReleases();
return releases.find((release) => release.version === version) ?? null;
}
}
export function isOfficialReleasePage(value: string, owner: string, repo: string): boolean {
try {
const url = new URL(value);
return url.protocol === "https:"
&& !url.username && !url.password
&& url.hostname === "github.com"
&& url.pathname.startsWith(`/${owner}/${repo}/releases/`);
} catch {
return false;
}
}
/**
* Only GitHub-owned hosts are accepted. For the release download path the
* repository prefix is pinned so a tampered asset URL cannot point elsewhere.
*/
export function assertOfficialDownloadUrl(value: string, owner: string, repo: string): void {
let url: URL;
try { url = new URL(value); }
catch { throw new ReleaseSourceError("The release asset URL is invalid."); }
if (url.protocol !== "https:" || url.username || url.password || !ALLOWED_DOWNLOAD_HOSTS.has(url.hostname)) {
throw new ReleaseSourceError("The release asset is not hosted on an official GitHub domain.");
}
if (url.hostname === "github.com" && !url.pathname.startsWith(`/${owner}/${repo}/releases/download/`)) {
throw new ReleaseSourceError("The release asset is not part of the official repository.");
}
}
+243
View File
@@ -0,0 +1,243 @@
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));
async function availablePort(): Promise<number> {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
assert.ok(address && typeof address !== "string");
const port = address.port;
await new Promise<void>((resolve) => server.close(() => resolve()));
return port;
}
async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!check()) {
if (Date.now() > deadline) throw new Error("timed out waiting for condition");
await sleep(50);
}
}
function appScript(version: string, port: number, pidFile: string, 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: ${JSON.stringify(status)}, version: ${JSON.stringify(version)} }));
return;
}
response.statusCode = 404;
response.end();
});
server.listen(${port}, "127.0.0.1", () => writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)));
process.on("SIGTERM", () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 1000).unref(); });
`;
}
interface RunnerFixture {
directory: string;
rootDir: string;
stagedRoot: string;
backupDir: string;
planPath: string;
statePath: string;
lockPath: string;
pidFile: string;
taskId: string;
}
function runnerFixture(t: TestContext): RunnerFixture {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-runner-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const rootDir = path.join(directory, "app");
const stagedRoot = path.join(directory, "staged");
const backupDir = path.join(directory, "backup");
const statePath = path.join(directory, "data", "updates", "state.json");
const lockPath = path.join(directory, "data", "updates", "update.lock");
const taskId = "upd_runner_test";
for (const directoryName of ["data", "config.json", "certs", "skins", "plugins"]) {
const target = path.join(rootDir, directoryName);
if (directoryName === "config.json") writeFileSync(target, JSON.stringify({ kept: true }));
else {
mkdirSync(target, { recursive: true });
writeFileSync(path.join(target, "marker.txt"), `${directoryName} preserved`);
}
}
for (const [root, version] of [[rootDir, "1.0.0"], [stagedRoot, "2.0.0"]] as const) {
mkdirSync(path.join(root, "dist"), { recursive: true });
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version }));
writeFileSync(path.join(root, "dist", "index.js"), `// version marker ${version}\n`);
}
return {
directory, rootDir, stagedRoot, backupDir, statePath, lockPath, taskId,
pidFile: path.join(directory, "app.pid"),
planPath: path.join(directory, "plan.json"),
};
}
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; 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, options.reportedStatus));
writeFileSync(fixture.planPath, JSON.stringify({
schemaVersion: 1,
taskId: fixture.taskId,
rootDir: fixture.rootDir,
statePath: fixture.statePath,
lockPath: fixture.lockPath,
stagedRoot: fixture.stagedRoot,
backupDir: fixture.backupDir,
fromVersion: "1.0.0",
targetVersion: options.targetVersion,
nodePath: process.execPath,
appEntry: path.join(fixture.rootDir, "dist", "index.js"),
health: { protocol: "http", port, path: "/api/health" },
waitForPid: null,
parentTimeoutMs: 2_000,
healthTimeoutMs: options.healthTimeoutMs ?? 1_500,
pollIntervalMs: 50,
appLogPath: path.join(fixture.directory, "app.log"),
}, null, 2));
}
async function stopPidFile(pidFile: string): Promise<void> {
if (!existsSync(pidFile)) return;
const pid = Number(readFileSync(pidFile, "utf8"));
if (Number.isInteger(pid) && pid > 0) {
try { process.kill(pid, "SIGTERM"); } catch { /* Already gone. */ }
for (let attempt = 0; attempt < 40; attempt++) {
try { process.kill(pid, 0); await sleep(50); }
catch { return; }
}
try { process.kill(pid, "SIGKILL"); } catch { /* Already gone. */ }
}
}
test("a 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();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
t.after(() => stopPidFile(fixture.pidFile));
assert.equal(await runRestartPlan(fixture.planPath), 0);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "succeeded");
assert.equal(state.task.finishedAt === null, false);
assert.deepEqual(state.task.steps.map((step: { name: string; status: string }) => [step.name, step.status]), [
["restart", "succeeded"],
["swap", "succeeded"],
]);
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "2\.0\.0"/);
assert.match(readFileSync(path.join(fixture.backupDir, "dist", "index.js"), "utf8"), /version marker 1\.0\.0/);
for (const directoryName of ["data", "certs", "skins", "plugins"]) {
assert.equal(readFileSync(path.join(fixture.rootDir, directoryName, "marker.txt"), "utf8"), `${directoryName} preserved`);
}
assert.deepEqual(JSON.parse(readFileSync(path.join(fixture.rootDir, "config.json"), "utf8")), { kept: true });
assert.equal(existsSync(fixture.lockPath), false);
assert.equal(existsSync(fixture.stagedRoot), false);
await waitFor(() => existsSync(fixture.pidFile));
});
test("a failed 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();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "9.9.9", healthTimeoutMs: 800 });
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
// Simulate the previous process still serving while the runner takes over.
const previous = spawn(process.execPath, [path.join(fixture.rootDir, "dist", "index.js")], { stdio: "ignore", detached: true });
previous.unref();
t.after(async () => { await stopPidFile(fixture.pidFile); try { previous.kill("SIGKILL"); } catch { /* Exited. */ } });
await waitFor(() => existsSync(fixture.pidFile) && Number(readFileSync(fixture.pidFile, "utf8")) === previous.pid);
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, true);
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
assert.match(readFileSync(path.join(fixture.backupDir, "rejected", "dist", "index.js"), "utf8"), /version: "9\.9\.9"/);
for (const directoryName of ["data", "certs", "skins", "plugins"]) {
assert.equal(readFileSync(path.join(fixture.rootDir, directoryName, "marker.txt"), "utf8"), `${directoryName} preserved`);
}
assert.deepEqual(JSON.parse(readFileSync(path.join(fixture.rootDir, "config.json"), "utf8")), { kept: true });
assert.equal(existsSync(fixture.lockPath), false);
});
+360
View File
@@ -0,0 +1,360 @@
import { spawn, type ChildProcess } from "node:child_process";
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import http from "node:http";
import https from "node:https";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { CodeSwapError, restoreCode, swapCode } from "./code-swap.js";
import { takeOverUpdateLock } from "./update-state.js";
import type { PersistedUpdateState } from "./update-state.js";
import type { UpdateTaskView } from "../shared/update.js";
export interface RestartPlan {
schemaVersion: 1;
taskId: string;
rootDir: string;
statePath: string;
lockPath: string;
stagedRoot: string;
backupDir: string;
fromVersion: string;
targetVersion: string;
/** Absolute path to the runtime bundled with the package (or a test stub). */
nodePath: string;
/** Absolute path to dist/index.js after the swap. */
appEntry: string;
health: { protocol: "http" | "https"; port: number; path: string };
waitForPid: number | null;
parentTimeoutMs: number;
healthTimeoutMs: number;
pollIntervalMs: number;
appLogPath: string;
}
class RunnerError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "RunnerError";
}
}
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
function readPlan(planPath: string): RestartPlan {
const parsed: unknown = JSON.parse(readFileSync(planPath, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new RunnerError("UPDATE_PLAN_INVALID", "Restart plan is invalid.");
const plan = parsed as Record<string, unknown>;
if (plan.schemaVersion !== 1
|| typeof plan.taskId !== "string"
|| typeof plan.rootDir !== "string"
|| typeof plan.statePath !== "string"
|| typeof plan.lockPath !== "string"
|| typeof plan.stagedRoot !== "string"
|| typeof plan.backupDir !== "string"
|| typeof plan.fromVersion !== "string"
|| typeof plan.targetVersion !== "string"
|| typeof plan.nodePath !== "string"
|| typeof plan.appEntry !== "string"
|| !plan.health || typeof plan.health !== "object") {
throw new RunnerError("UPDATE_PLAN_INVALID", "Restart plan is incomplete.");
}
const health = plan.health as Record<string, unknown>;
return {
schemaVersion: 1,
taskId: plan.taskId,
rootDir: plan.rootDir,
statePath: plan.statePath,
lockPath: plan.lockPath,
stagedRoot: plan.stagedRoot,
backupDir: plan.backupDir,
fromVersion: plan.fromVersion,
targetVersion: plan.targetVersion,
nodePath: plan.nodePath,
appEntry: plan.appEntry,
health: {
protocol: health.protocol === "https" ? "https" : "http",
port: typeof health.port === "number" ? health.port : 3040,
path: typeof health.path === "string" ? health.path : "/api/health",
},
waitForPid: typeof plan.waitForPid === "number" && Number.isFinite(plan.waitForPid) ? plan.waitForPid : null,
parentTimeoutMs: typeof plan.parentTimeoutMs === "number" ? plan.parentTimeoutMs : 60_000,
healthTimeoutMs: typeof plan.healthTimeoutMs === "number" ? plan.healthTimeoutMs : 90_000,
pollIntervalMs: typeof plan.pollIntervalMs === "number" ? plan.pollIntervalMs : 500,
appLogPath: typeof plan.appLogPath === "string" ? plan.appLogPath : path.join(path.dirname(plan.statePath), "app.log"),
};
}
function loadState(plan: RestartPlan): PersistedUpdateState {
try {
const parsed: unknown = JSON.parse(readFileSync(plan.statePath, "utf8"));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)
&& (parsed as Record<string, unknown>).schemaVersion === 1
&& (parsed as Record<string, unknown>).task
&& typeof (parsed as Record<string, unknown>).task === "object"
&& ((parsed as { task: { id?: unknown } }).task.id === plan.taskId)) {
return parsed as PersistedUpdateState;
}
} catch { /* Build a task below. */ }
return {
schemaVersion: 1,
task: {
id: plan.taskId,
status: "restarting",
fromVersion: plan.fromVersion,
targetVersion: plan.targetVersion,
startedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
finishedAt: null,
errorCode: null,
errorMessage: null,
rolledBack: false,
steps: [],
},
};
}
class StateWriter {
private state: PersistedUpdateState;
constructor(private readonly plan: RestartPlan) {
this.state = loadState(plan);
}
private write(): void {
const task = this.state.task!;
task.updatedAt = new Date().toISOString();
mkdirSync(path.dirname(this.plan.statePath), { recursive: true });
const temporary = `${this.plan.statePath}.${process.pid}.tmp`;
writeFileSync(temporary, JSON.stringify(this.state, null, 2), "utf8");
renameSync(temporary, this.plan.statePath);
}
get task(): UpdateTaskView {
return this.state.task!;
}
step(name: string, status: UpdateTaskView["steps"][number]["status"], detail?: string): void {
const task = this.state.task!;
const existing = task.steps.find((step) => step.name === name);
const at = new Date().toISOString();
if (existing) {
existing.status = status;
existing.at = at;
if (detail) existing.detail = detail;
} else {
task.steps.push({ name, status, at, ...(detail ? { detail } : {}) });
}
this.write();
}
status(status: UpdateTaskView["status"], error?: { code: string; message: string }): void {
const task = this.state.task!;
task.status = status;
if (error) {
task.errorCode = error.code;
task.errorMessage = error.message;
}
if (status === "succeeded" || status === "failed") task.finishedAt = new Date().toISOString();
this.write();
}
rolledBack(value: boolean): void {
this.state.task!.rolledBack = value;
this.write();
}
}
function processAlive(pid: number | null): boolean {
if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
async function waitForParent(pid: number | null, timeoutMs: number): Promise<void> {
if (!pid) return;
const deadline = Date.now() + timeoutMs;
while (processAlive(pid)) {
if (Date.now() > deadline) throw new RunnerError("UPDATE_RESTART_TIMEOUT", "The previous process did not stop in time.");
await sleep(100);
}
}
interface HealthResponse {
status?: string;
version?: string;
}
function probeHealth(plan: RestartPlan): Promise<HealthResponse | null> {
return new Promise((resolve) => {
const client = plan.health.protocol === "https" ? https : http;
const request = client.get({
hostname: "127.0.0.1",
port: plan.health.port,
path: plan.health.path,
timeout: 2_000,
...(plan.health.protocol === "https" ? { rejectUnauthorized: false } : {}),
}, (response) => {
if (response.statusCode !== 200) { response.resume(); resolve(null); return; }
let body = "";
response.setEncoding("utf8");
response.on("data", (chunk: string) => { if (body.length < 64 * 1024) body += chunk; });
response.on("end", () => {
try {
const parsed: unknown = JSON.parse(body);
resolve(parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as HealthResponse : null);
} catch { resolve(null); }
});
response.on("error", () => resolve(null));
});
request.on("timeout", () => request.destroy());
request.on("error", () => resolve(null));
});
}
async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: number): Promise<HealthResponse | null> {
const deadline = Date.now() + timeoutMs;
let last: HealthResponse | null = null;
while (Date.now() < deadline) {
last = await probeHealth(plan);
if (last?.status === "ok" && last.version === version) return last;
await sleep(plan.pollIntervalMs);
}
return null;
}
function startApp(plan: RestartPlan): ChildProcess {
mkdirSync(path.dirname(plan.appLogPath), { recursive: true });
const log = openSync(plan.appLogPath, "a");
try {
const child = spawn(plan.nodePath, [plan.appEntry], {
cwd: plan.rootDir,
env: process.env,
detached: true,
windowsHide: true,
stdio: ["ignore", log, log],
});
child.unref();
return child;
} finally {
closeSync(log);
}
}
async function ensureApp(plan: RestartPlan, expectedVersion: string): Promise<boolean> {
let healthy = await waitForVersion(plan, expectedVersion, Math.min(5_000, plan.healthTimeoutMs));
if (healthy) return true;
let child: ChildProcess | undefined;
try {
child = startApp(plan);
healthy = await waitForVersion(plan, expectedVersion, plan.healthTimeoutMs);
if (healthy) return true;
await stopApp(child);
return false;
} finally {
child?.unref();
}
}
function exited(child: ChildProcess): boolean {
return child.exitCode !== null || child.signalCode !== null;
}
async function stopApp(child: ChildProcess | undefined): Promise<void> {
if (!child || exited(child)) return;
try { child.kill("SIGTERM"); } catch { /* Already gone. */ }
const deadline = Date.now() + 6_000;
while (!exited(child) && Date.now() < deadline) await sleep(100);
if (exited(child)) return;
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
const hardDeadline = Date.now() + 2_000;
while (!exited(child) && Date.now() < hardDeadline) await sleep(100);
}
export async function runRestartPlan(planPath: string): Promise<number> {
const plan = readPlan(planPath);
const state = new StateWriter(plan);
let swapped = false;
let newApp: ChildProcess | undefined;
// Take over the update lock before doing anything else. The parent process
// is about to exit and its lock would otherwise have a dead pid, letting a
// second instance starting in this window roll the healthy code back.
let releaseLock: (() => void) | null = null;
try {
try {
releaseLock = takeOverUpdateLock(plan.lockPath, plan.taskId);
} catch (error) {
throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over.");
}
state.status("restarting");
state.step("restart", "running");
await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
state.step("swap", "running");
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
swapped = true;
state.step("swap", "succeeded");
let healthy = await waitForVersion(plan, plan.targetVersion, Math.min(5_000, plan.healthTimeoutMs));
if (!healthy) {
newApp = startApp(plan);
healthy = await waitForVersion(plan, plan.targetVersion, plan.healthTimeoutMs);
}
if (!healthy) throw new RunnerError("UPDATE_HEALTH_CHECK_FAILED", `The updated version did not report ${plan.targetVersion} on /api/health.`);
state.step("restart", "succeeded");
state.status("succeeded");
releaseLock();
releaseLock = null;
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
return 0;
} catch (error) {
// 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");
try {
restoreCode(plan.rootDir, plan.backupDir);
state.step("rollback", "succeeded");
rolledBack = true;
} catch (rollbackError) {
state.step("rollback", "failed", rollbackError instanceof Error ? rollbackError.message : "Code rollback failed.");
state.rolledBack(false);
state.status("failed", { code: "UPDATE_ROLLBACK_FAILED", message: `${message} Code rollback also failed.` });
releaseLock?.();
return 1;
}
}
const healthy = await ensureApp(plan, plan.fromVersion);
state.rolledBack(rolledBack);
if (!healthy) {
state.status("failed", { code: "UPDATE_ROLLBACK_HEALTH_FAILED", message: `${message} The previous version did not become healthy.` });
} else {
state.status("failed", { code, message });
}
releaseLock?.();
return 1;
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const planPath = process.argv[2];
if (!planPath) {
console.error("Usage: restart-runner <plan.json>");
process.exit(2);
}
runRestartPlan(planPath)
.then((code) => process.exit(code))
.catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
}
+511
View File
@@ -0,0 +1,511 @@
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, 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, 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, "..", "..");
const LAUNCHER_SOURCE = path.join(REPO_ROOT, "scripts", "start-webspeak.sh");
const RUNNER_SOURCE = path.join(SOURCE_DIR, "restart-runner.ts");
const TASK_ID = "upd_sigkill_window";
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
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) {
test(`launcher recovers a SIGKILL immediately after moving old ${entry}`, { timeout: 30_000, skip: process.platform !== "linux" }, async t => {
const port = await availablePort();
const fixture = buildFixture(t, port, true);
// The Linux package need not contain the Windows launcher, but include it
// here so the entire code-entry list has a tested interruption point.
writeFileSync(path.join(fixture.rootDir, "start-webspeak.cmd"), "old launcher");
const runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
cwd: REPO_ROOT,
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir, WEBSPEAK_TEST_SWAP_BARRIER_AFTER_ENTRY: entry },
stdio: "ignore",
});
let app: ChildProcess | undefined;
t.after(() => { stop(app); stop(runner); });
await waitFor(() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")), `runner never reached ${entry}`);
stop(runner);
await waitFor(() => !processAlive(runner.pid), "runner did not stop", 5_000);
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir, env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir }, stdio: "ignore",
});
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), `launcher failed after ${entry}`);
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
for (const [key, file] of Object.entries(fixture.markerFiles)) {
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`);
}
const stale = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup", "package.json");
assert.equal(JSON.parse(readFileSync(stale, "utf8")).version, "0.1.0");
stop(app);
await waitFor(() => !processAlive(app?.pid), "app did not stop", 5_000);
});
}
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
async function availablePort(): Promise<number> {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
assert.ok(address && typeof address !== "string");
await new Promise<void>((resolve) => server.close(() => resolve()));
return address.port;
}
async function waitFor(check: () => boolean | Promise<boolean>, message: string, timeoutMs = 15_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!(await check())) {
if (Date.now() > deadline) throw new Error(message);
await sleep(25);
}
}
async function healthVersion(port: number): Promise<string | null> {
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1_000) });
if (!response.ok) return null;
const body = await response.json() as { status?: string; version?: string };
return body.status === "ok" ? body.version ?? null : null;
} catch {
return null;
}
}
function 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; }
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
}
function stop(child: ChildProcess | undefined): void {
if (!child || !processAlive(child.pid)) return;
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
}
/** The stub reports the version from package.json, as the real app does. */
function appScript(): string {
return `const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const config = JSON.parse(fs.readFileSync(path.join(process.cwd(), "config.json"), "utf8"));
const version = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")).version;
http.createServer((request, response) => {
if (request.url === "/api/health") {
response.setHeader("content-type", "application/json");
response.end(JSON.stringify({ status: "ok", version }));
return;
}
response.statusCode = 404;
response.end();
}).listen(config.port, "127.0.0.1", () => fs.writeFileSync(config.startedFile, version));
`;
}
interface Fixture {
directory: string;
rootDir: string;
dataDir: string;
stagedRoot: string;
backupDir: string;
barrierDir: string;
port: number;
markerFiles: Record<string, string>;
}
function buildFixture(t: TestContext, port: number, withStaleBackup = false): Fixture {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-recovery-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const rootDir = path.join(directory, "app");
const dataDir = path.join(rootDir, "data");
const updatesDir = path.join(dataDir, "updates");
const stagedRoot = path.join(updatesDir, "tasks", TASK_ID, "staged");
const backupDir = path.join(updatesDir, "backups", TASK_ID);
const barrierDir = path.join(directory, "barrier");
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
mkdirSync(path.join(rootDir, relative), { recursive: true });
}
writeFileSync(path.join(rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
writeFileSync(path.join(rootDir, "package-lock.json"), "{}");
writeFileSync(path.join(rootDir, "README.md"), "old readme");
writeFileSync(path.join(rootDir, "LICENSE"), "old license");
writeFileSync(path.join(rootDir, "config.example.json"), "{}");
writeFileSync(path.join(rootDir, "web", "dist", "index.html"), "<!doctype html>\n");
writeFileSync(path.join(rootDir, "node_modules", ".keep"), "");
writeFileSync(path.join(rootDir, "dist", "index.js"), appScript());
copyFileSync(process.execPath, path.join(rootDir, "runtime", "node"));
chmodSync(path.join(rootDir, "runtime", "node"), 0o755);
// This is the same file CI ships and applyUpdate installs before the swap.
copyFileSync(LAUNCHER_SOURCE, path.join(rootDir, "start-webspeak.sh"));
chmodSync(path.join(rootDir, "start-webspeak.sh"), 0o755);
const markerFiles: Record<string, string> = {
config: path.join(rootDir, "config.json"),
database: path.join(dataDir, "webspeak.db"),
identity: path.join(dataDir, "identity.key"),
cert: path.join(rootDir, "certs", "cert.pem"),
skin: path.join(dataDir, "skins", "skin.json"),
plugin: path.join(dataDir, "plugins", "plugin.json"),
};
mkdirSync(path.dirname(markerFiles.database), { recursive: true });
mkdirSync(path.dirname(markerFiles.identity), { recursive: true });
mkdirSync(path.dirname(markerFiles.cert), { recursive: true });
mkdirSync(path.dirname(markerFiles.skin), { recursive: true });
mkdirSync(path.dirname(markerFiles.plugin), { recursive: true });
writeFileSync(markerFiles.config, JSON.stringify({ port, startedFile: path.join(directory, "started.txt") }));
for (const [key, value] of Object.entries(markerFiles)) {
if (key !== "config") writeFileSync(value, `${key} preserved`);
}
mkdirSync(updatesDir, { recursive: true });
mkdirSync(stagedRoot, { recursive: true });
mkdirSync(path.join(stagedRoot, "dist"), { recursive: true });
mkdirSync(path.join(stagedRoot, "web", "dist"), { recursive: true });
mkdirSync(path.join(stagedRoot, "node_modules"), { recursive: true });
mkdirSync(path.join(stagedRoot, "runtime"), { recursive: true });
writeFileSync(path.join(stagedRoot, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
writeFileSync(path.join(stagedRoot, "package-lock.json"), "{}");
writeFileSync(path.join(stagedRoot, "README.md"), "new readme");
writeFileSync(path.join(stagedRoot, "LICENSE"), "new license");
writeFileSync(path.join(stagedRoot, "config.example.json"), "{}");
writeFileSync(path.join(stagedRoot, "dist", "index.js"), "// new code marker\n");
writeFileSync(path.join(stagedRoot, "web", "dist", "index.html"), "<!doctype html>\n");
writeFileSync(path.join(stagedRoot, "node_modules", ".keep"), "");
writeFileSync(path.join(stagedRoot, "runtime", "node"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
copyFileSync(LAUNCHER_SOURCE, path.join(stagedRoot, "start-webspeak.sh"));
writeFileSync(path.join(updatesDir, "state.json"), JSON.stringify({
schemaVersion: 1,
task: {
id: TASK_ID, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
}));
writeFileSync(path.join(updatesDir, "update.lock"), JSON.stringify({ pid: 0, taskId: TASK_ID, createdAt: "2026-01-01T00:00:00.000Z" }));
writeFileSync(path.join(updatesDir, "plan.json"), JSON.stringify({
schemaVersion: 1,
taskId: TASK_ID,
rootDir,
statePath: path.join(updatesDir, "state.json"),
lockPath: path.join(updatesDir, "update.lock"),
stagedRoot,
backupDir,
fromVersion: "0.3.2",
targetVersion: "0.4.0",
nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
health: { protocol: "http", port, path: "/api/health" },
waitForPid: null,
parentTimeoutMs: 2_000,
healthTimeoutMs: 300,
pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
if (withStaleBackup) {
// A complete backup from an earlier, already successful update. Its name
// sorts before the in-progress task's id, so the old "first complete
// backup wins" launcher logic would wrongly restore this older build.
const staleDir = path.join(updatesDir, "backups", "aaa_stale_backup");
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
mkdirSync(path.join(staleDir, relative), { recursive: true });
}
writeFileSync(path.join(staleDir, "dist", "index.js"), appScript());
writeFileSync(path.join(staleDir, "web", "dist", "index.html"), "<!doctype html>\n");
writeFileSync(path.join(staleDir, "node_modules", ".keep"), "");
writeFileSync(path.join(staleDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.1.0" }));
writeFileSync(path.join(staleDir, "package-lock.json"), "{}");
writeFileSync(path.join(staleDir, "README.md"), "stale readme");
writeFileSync(path.join(staleDir, "LICENSE"), "stale license");
writeFileSync(path.join(staleDir, "config.example.json"), "{}");
copyFileSync(process.execPath, path.join(staleDir, "runtime", "node"));
chmodSync(path.join(staleDir, "runtime", "node"), 0o755);
writeFileSync(path.join(staleDir, ".webspeak-swap.json"), JSON.stringify({
schemaVersion: 1,
entries: ["dist", "web/dist", "node_modules", "runtime", "package.json", "package-lock.json", "README.md", "LICENSE", "config.example.json"],
}, null, 2));
}
mkdirSync(barrierDir, { recursive: true });
return { directory, rootDir, dataDir, stagedRoot, backupDir, barrierDir, port, markerFiles };
}
test(
"SIGKILL in the exact swap window is recovered by the official launcher with data intact",
{ timeout: 40_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
let runner: ChildProcess | undefined;
let app: ChildProcess | undefined;
t.after(() => { stop(app); stop(runner); });
let runnerOutput = "";
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
cwd: REPO_ROOT,
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
stdio: ["ignore", "pipe", "pipe"],
});
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
await waitFor(
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
`runner never reached the exact swap window: ${runnerOutput}`,
);
// Precisely the failure state: old dist moved aside, new dist not yet in.
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
assert.equal(existsSync(path.join(fixture.rootDir, "start-webspeak.sh")), true, "official launcher survived the swap");
stop(runner);
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
// Restart through the shipped launcher itself, not a harness wrapper.
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "official launcher did not restore a healthy install");
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
for (const [key, file] of Object.entries(fixture.markerFiles)) {
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
}
assert.equal(existsSync(path.join(fixture.backupDir, "rejected", "dist")), false, "no partial new code in the install root");
// Once Node is up, the existing initialize() path records the real failure.
stop(app);
await waitFor(() => !processAlive(app?.pid), "app did not stop", 5_000);
const service = new UpdateService({
rootDir: fixture.rootDir,
dataDir: fixture.dataDir,
currentVersion: "0.3.2",
logger,
platform: "linux",
architecture: "x64",
env: {},
isDocker: false,
});
service.initialize();
const status = service.getStatus();
assert.equal(status.task?.status, "failed");
assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
assert.equal(status.task?.rolledBack, true);
},
);
test(
"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 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port, true);
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
let runner: ChildProcess | undefined;
let app: ChildProcess | undefined;
t.after(() => { stop(app); stop(runner); });
let runnerOutput = "";
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
cwd: REPO_ROOT,
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
stdio: ["ignore", "pipe", "pipe"],
});
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
await waitFor(
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
`runner never reached the exact swap window: ${runnerOutput}`,
);
// Old code is only in the current task's backup; the stale backup is
// untouched and still sitting under a lexicographically earlier name.
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
stop(runner);
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "launcher did not restore the current task's 0.3.2 build");
// The current task's version, not the stale 0.1.0 build, is back in place.
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0", "stale backup was not consumed");
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true, "stale backup is still intact");
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
for (const [key, file] of Object.entries(fixture.markerFiles)) {
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
}
},
);
+152
View File
@@ -0,0 +1,152 @@
import { createHash } from "node:crypto";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { gzipSync } from "node:zlib";
/** Test-only archive builders. Not imported by production code. */
export interface TarFixtureEntry {
name: string;
data?: Buffer | string;
type?: "file" | "directory" | "symlink" | "hardlink";
linkname?: string;
mode?: number;
}
function octal(value: number, width: number): string {
return value.toString(8).padStart(width, "0");
}
function tarHeader(entry: TarFixtureEntry): Buffer {
const buffer = Buffer.alloc(512);
const directory = entry.type === "directory";
const link = entry.type === "symlink" || entry.type === "hardlink";
const data = entry.data === undefined ? Buffer.alloc(0) : Buffer.from(entry.data);
const size = directory || link ? 0 : data.length;
buffer.write(entry.name, 0, 100, "utf8");
buffer.write(`${octal(entry.mode ?? (directory ? 0o755 : 0o644), 7)}\0`, 100, 8, "ascii");
buffer.write("0000000\0", 108, 8, "ascii");
buffer.write("0000000\0", 116, 8, "ascii");
buffer.write(`${octal(size, 11)}\0`, 124, 12, "ascii");
buffer.write("00000000000\0", 136, 12, "ascii");
buffer.write(" ", 148, 8, "ascii");
buffer.write(entry.type === "directory" ? "5" : entry.type === "symlink" ? "2" : entry.type === "hardlink" ? "1" : "0", 156, 1, "ascii");
if (entry.linkname) buffer.write(entry.linkname, 157, 100, "utf8");
buffer.write("ustar\0", 257, 6, "ascii");
buffer.write("00", 263, 2, "ascii");
buffer.write("root", 265, 32, "ascii");
buffer.write("root", 297, 32, "ascii");
buffer.write("0000000\0", 329, 8, "ascii");
buffer.write("0000000\0", 337, 8, "ascii");
let checksum = 0;
for (const byte of buffer) checksum += byte;
buffer.write(`${octal(checksum, 6)}\0 `, 148, 8, "ascii");
return buffer;
}
export function createTarGz(entries: TarFixtureEntry[]): Buffer {
const chunks: Buffer[] = [];
for (const entry of entries) {
const data = entry.type === "directory" || entry.type === "symlink" || entry.type === "hardlink"
? Buffer.alloc(0)
: Buffer.from(entry.data ?? "");
chunks.push(tarHeader(entry));
if (data.length) {
chunks.push(data, Buffer.alloc((512 - (data.length % 512)) % 512));
}
}
chunks.push(Buffer.alloc(1024));
return gzipSync(Buffer.concat(chunks));
}
export interface ZipFixtureEntry {
name: string;
data?: Buffer | string;
mode?: number;
directory?: boolean;
}
function crc32(buffer: Buffer): number {
let crc = 0xffffffff;
for (const byte of buffer) {
crc ^= byte;
for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
}
return (crc ^ 0xffffffff) >>> 0;
}
export function createZip(entries: ZipFixtureEntry[]): Buffer {
const locals: Buffer[] = [];
const central: Buffer[] = [];
let offset = 0;
for (const entry of entries) {
const directory = entry.directory === true || entry.name.endsWith("/");
const data = directory ? Buffer.alloc(0) : Buffer.from(entry.data ?? "");
const name = Buffer.from(entry.name, "utf8");
const mode = entry.mode ?? (directory ? 0o040755 : 0o100644);
const crc = crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0, 6);
local.writeUInt16LE(0, 8);
local.writeUInt32LE(0, 10);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(data.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
locals.push(local, name, data);
const entryCentral = Buffer.alloc(46);
entryCentral.writeUInt32LE(0x02014b50, 0);
entryCentral.writeUInt16LE(0x0314, 4);
entryCentral.writeUInt16LE(20, 6);
entryCentral.writeUInt16LE(0, 8);
entryCentral.writeUInt16LE(0, 10);
entryCentral.writeUInt32LE(0, 12);
entryCentral.writeUInt32LE(crc, 16);
entryCentral.writeUInt32LE(data.length, 20);
entryCentral.writeUInt32LE(data.length, 24);
entryCentral.writeUInt16LE(name.length, 28);
entryCentral.writeUInt16LE(0, 30);
entryCentral.writeUInt16LE(0, 32);
entryCentral.writeUInt16LE(0, 34);
entryCentral.writeUInt16LE(0, 36);
entryCentral.writeUInt32LE((mode << 16) >>> 0, 38);
entryCentral.writeUInt32LE(offset, 42);
central.push(entryCentral, name);
offset += 30 + name.length + data.length;
}
const directory = Buffer.concat(central);
const eocd = Buffer.alloc(22);
eocd.writeUInt32LE(0x06054b50, 0);
eocd.writeUInt16LE(0, 4);
eocd.writeUInt16LE(0, 6);
eocd.writeUInt16LE(entries.length, 8);
eocd.writeUInt16LE(entries.length, 10);
eocd.writeUInt32LE(directory.length, 12);
eocd.writeUInt32LE(offset, 16);
eocd.writeUInt16LE(0, 20);
return Buffer.concat([...locals, directory, eocd]);
}
export function sha256Hex(value: Buffer): string {
return createHash("sha256").update(value).digest("hex");
}
/** Minimal runnable release-package layout accepted by validateStagedPackage. */
export function createPackageFiles(root: string, version: string, extra: Record<string, string> = {}): void {
for (const directory of ["dist", "web/dist", "node_modules", "runtime"]) {
mkdirSync(path.join(root, directory), { recursive: true });
}
writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "webspeak-webclient", version }), "utf8");
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
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 });
writeFileSync(target, contents, "utf8");
}
}
+894
View File
@@ -0,0 +1,894 @@
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";
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";
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
const ASSET_NAME = "webspeak-webclient-v0.4.0-linux-x64.tar.gz";
const RELEASE_LIST_URL = `https://api.github.com/repos/${OFFICIAL_REPOSITORY}/releases?per_page=30`;
interface AssetFixture { name: string; data: Buffer; digest?: string | null; url?: string }
interface ReleaseFixture {
version: string;
assets: AssetFixture[];
prerelease?: boolean;
draft?: boolean;
releaseUrl?: string;
}
function workspace(t: TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-service-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function releaseJson(fixture: ReleaseFixture) {
return {
tag_name: `v${fixture.version}`,
draft: fixture.draft === true,
prerelease: fixture.prerelease === true,
html_url: fixture.releaseUrl ?? `https://github.com/${OFFICIAL_REPOSITORY}/releases/tag/v${fixture.version}`,
published_at: "2026-01-01T00:00:00.000Z",
assets: fixture.assets.map((asset) => ({
name: asset.name,
size: asset.data.length,
browser_download_url: asset.url ?? `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v${fixture.version}/${asset.name}`,
digest: asset.digest ?? null,
})),
};
}
function fakeFetch(releases: ReleaseFixture[], downloads: Map<string, Buffer>) {
return (async (input: string | URL | Request) => {
const url = String(input);
if (url === RELEASE_LIST_URL) {
return new Response(JSON.stringify(releases.map(releaseJson)), { status: 200, headers: { "content-type": "application/json" } });
}
const body = downloads.get(url);
if (body) return new Response(body as unknown as BodyInit, { status: 200, headers: { "content-type": "application/octet-stream" } });
return new Response("not found", { status: 404 });
}) as typeof fetch;
}
function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer {
return createTarGz([
{ name: "webspeak/", type: "directory" },
{ name: "webspeak/package.json", data: JSON.stringify({ name: "webspeak-webclient", version }) },
{ name: "webspeak/dist/index.js", data: "// package entry\n" },
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
{ name: "webspeak/node_modules/.keep", data: "" },
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
{ name: "webspeak/start-webspeak.sh", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
...extra,
]);
}
function checksumText(assetName: string, archive: Buffer): string {
return `${sha256Hex(archive)} ${assetName}\n`;
}
interface ServiceFixture {
service: UpdateService;
launched: string[];
dataDir: string;
rootDir: string;
}
function createService(
t: TestContext,
releases: ReleaseFixture[],
downloads: Map<string, Buffer>,
options: Partial<UpdateServiceOptions> = {},
): ServiceFixture {
const directory = workspace(t);
const rootDir = options.rootDir ?? path.join(directory, "app");
if (!options.rootDir) createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const launched: string[] = [];
const service = new UpdateService({
rootDir,
dataDir,
currentVersion: "0.3.2",
logger,
platform: "linux",
architecture: "x64",
env: {},
isDocker: false,
isSupervised: false,
fetch: fakeFetch(releases, downloads),
now: () => new Date("2026-01-01T00:00:00.000Z"),
launchRunner: async (planPath) => { launched.push(planPath); },
healthTimeoutMs: 100,
downloadTimeoutMs: 2_000,
...options,
});
service.initialize();
return { service, launched, dataDir, rootDir };
}
function updateErrorCode(code: UpdateErrorCode) {
return (error: unknown) => error instanceof UpdateError && error.code === code;
}
function digest(archive: Buffer): string {
return `sha256:${sha256Hex(archive)}`;
}
test("release checks list only official stable versions and expose blocked reasons", async t => {
const archive = packageArchive("0.4.0");
const downloads = new Map<string, Buffer>();
const assetUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`;
const checksumUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`;
downloads.set(assetUrl, archive);
downloads.set(checksumUrl, Buffer.from(checksumText(ASSET_NAME, archive)));
const { service } = createService(t, [
{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive, digest: digest(archive) },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)), digest: digest(Buffer.from(checksumText(ASSET_NAME, archive))) },
],
},
{ version: "0.4.1", assets: [{ name: "webspeak-webclient-v0.4.1-linux-x64.tar.gz", data: archive }] },
{
version: "0.4.2",
assets: [{ name: ASSET_NAME, data: archive }],
releaseUrl: "https://evil.example/releases/tag/v0.4.2",
},
{
version: "0.4.3",
assets: [{ name: "webspeak-webclient-v0.4.3-linux-x64.tar.gz", data: archive, url: "https://evil.example/package.tar.gz" }],
},
{ version: "0.5.0", assets: [], prerelease: true },
{ version: "0.6.0", assets: [], draft: true },
{ version: "0.3.2", assets: [] },
], downloads);
const check = await service.checkForUpdates();
assert.deepEqual(check.releases.map((release) => release.version), ["0.4.3", "0.4.1", "0.4.0"]);
const ready = check.releases.find((release) => release.version === "0.4.0")!;
assert.equal(ready.assetName, ASSET_NAME);
assert.equal(ready.assetAvailable, true);
assert.equal(ready.hasChecksums, true);
assert.equal(ready.canApply, true);
assert.equal(ready.blockedReason, null);
assert.equal(ready.digest, digest(archive));
const noChecksum = check.releases.find((release) => release.version === "0.4.1")!;
assert.equal(noChecksum.canApply, false);
assert.equal(noChecksum.blockedReason, "UPDATE_CHECKSUM_MISSING");
const maliciousAsset = check.releases.find((release) => release.version === "0.4.3")!;
assert.equal(maliciousAsset.assetAvailable, false);
assert.equal(maliciousAsset.canApply, false);
assert.equal(maliciousAsset.blockedReason, "UPDATE_ASSET_UNAVAILABLE");
});
test("apply requires a matching confirmation and a supported deployment", async t => {
const archive = packageArchive("0.4.0");
const { service, launched } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
}], new Map());
await assert.rejects(service.applyUpdate("0.4.0", "0.4.1"), updateErrorCode("UPDATE_CONFIRMATION_REQUIRED"));
await assert.rejects((service.applyUpdate as unknown as (version: string) => Promise<unknown>)("0.4.0"), updateErrorCode("UPDATE_CONFIRMATION_REQUIRED"));
await assert.rejects(service.applyUpdate("not-a-version", "not-a-version"), updateErrorCode("UPDATE_VERSION_INVALID"));
await assert.rejects(service.applyUpdate("0.3.2", "0.3.2"), updateErrorCode("UPDATE_VERSION_NOT_NEWER"));
assert.equal(launched.length, 0);
const sourceDirectory = workspace(t);
const source = createService(t, [], new Map(), { rootDir: sourceDirectory });
assert.equal(source.service.getStatus().deployment.mode, "source");
await assert.rejects(source.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
assert.equal(source.launched.length, 0);
const docker = createService(t, [], new Map(), { isDocker: true });
assert.equal(docker.service.getStatus().deployment.mode, "docker");
await assert.rejects(docker.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
assert.equal(docker.launched.length, 0);
});
test("a missing SHA256SUMS entry refuses the update and persists a failed task", async t => {
const archive = packageArchive("0.4.0");
const assetName = "webspeak-webclient-v0.4.1-linux-x64.tar.gz";
const { service, launched, dataDir } = createService(t, [{
version: "0.4.1",
assets: [{ name: assetName, data: archive }],
}], new Map([[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.1/${assetName}`, archive]]));
const check = await service.checkForUpdates();
assert.equal(check.releases[0].blockedReason, "UPDATE_CHECKSUM_MISSING");
await assert.rejects(service.applyUpdate("0.4.1", "0.4.1"), updateErrorCode("UPDATE_CHECKSUM_MISSING"));
assert.equal(launched.length, 0);
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
assert.equal(state.task?.status, "failed");
assert.equal(state.task?.errorCode, "UPDATE_CHECKSUM_MISSING");
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false);
assert.equal(existsSync(path.join(dataDir, "updates", "tasks", state.task!.id)), false);
});
test("a wrong checksum, digest mismatch or unsupported digest refuses the package", async t => {
const archive = packageArchive("0.4.0");
const baseRelease = (digestValue: string | null): ReleaseFixture => ({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive, digest: digestValue },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
});
const archiveUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`;
const checksumUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`;
const downloads = new Map<string, Buffer>([
[archiveUrl, archive],
[checksumUrl, Buffer.from(checksumText(ASSET_NAME, archive))],
]);
const badChecksum = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(`${"0".repeat(64)} ${ASSET_NAME}\n`) },
],
}], new Map([[archiveUrl, archive], [checksumUrl, Buffer.from(`${"0".repeat(64)} ${ASSET_NAME}\n`)]]));
await assert.rejects(badChecksum.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_CHECKSUM_MISMATCH"));
assert.equal(badChecksum.launched.length, 0);
const wrongDigest = createService(t, [baseRelease(`sha256:${"0".repeat(64)}`)], new Map(downloads));
await assert.rejects(wrongDigest.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DIGEST_MISMATCH"));
const unsupportedDigest = createService(t, [baseRelease("md5:abc")], new Map(downloads));
await assert.rejects(unsupportedDigest.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DIGEST_UNSUPPORTED"));
});
test("unsafe archives are refused before any code is staged", async t => {
const archive = packageArchive("0.4.0", [{ name: "webspeak/../../escape.txt", data: "owned" }]);
const { service, launched, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
}], new Map([
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, Buffer.from(checksumText(ASSET_NAME, archive))],
]));
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(launched.length, 0);
assert.equal(existsSync(path.join(dataDir, "..", "escape.txt")), false);
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
});
test("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));
const { service, launched, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive, digest: digest(archive) },
{ name: CHECKSUM_ASSET_NAME, data: checksums, digest: digest(checksums) },
],
}], new Map([
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, checksums],
]));
const task = await service.applyUpdate("0.4.0", "0.4.0");
assert.equal(task.status, "restarting");
assert.equal(task.targetVersion, "0.4.0");
assert.deepEqual(task.steps.map((step) => [step.name, step.status]), [
["download", "succeeded"],
["checksum", "succeeded"],
["extract", "succeeded"],
["stage", "succeeded"],
["restart", "running"],
]);
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
assert.equal(state.task?.id, task.id);
assert.equal(state.task?.status, "restarting");
assert.equal(launched.length, 1);
const plan = JSON.parse(readFileSync(launched[0], "utf8"));
assert.equal(plan.taskId, task.id);
assert.equal(plan.targetVersion, "0.4.0");
assert.equal(plan.fromVersion, "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(plan.stagedRoot, "package.json"), "utf8")).version, "0.4.0");
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), true);
// The old process is gone once the restarted instance reads the state.
writeFileSync(path.join(dataDir, "updates", "update.lock"), JSON.stringify({ pid: 0, taskId: task.id, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: path.dirname(plan.rootDir),
dataDir,
currentVersion: "0.4.0",
logger,
platform: "linux",
architecture: "x64",
env: {},
isDocker: false,
fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:00:00.000Z"),
});
restarted.initialize();
assert.equal(restarted.getStatus().task?.status, "succeeded");
assert.equal(restarted.getStatus().task?.finishedAt, "2026-01-01T00:00:00.000Z");
});
test("a concurrent lock leaves the running task state untouched", async t => {
const archive = packageArchive("0.4.0");
const { service, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
}], new Map());
mkdirSync(path.join(dataDir, "updates"), { recursive: true });
writeFileSync(path.join(dataDir, "updates", "update.lock"), JSON.stringify({ pid: process.pid, taskId: "upd_running", createdAt: "2026-01-01T00:00:00.000Z" }));
writeFileSync(path.join(dataDir, "updates", "state.json"), JSON.stringify({ schemaVersion: 1, task: null }));
service.initialize();
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_IN_PROGRESS"));
assert.equal(readUpdateState(path.join(dataDir, "updates", "state.json")).task, null);
assert.equal(service.getStatus().task, null);
});
test("getStatus reports the task the restart runner persisted, not stale memory", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const { service, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
}], new Map([
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, checksums],
]));
const task = await service.applyUpdate("0.4.0", "0.4.0");
assert.equal(service.getStatus().task?.status, "restarting");
// The runner rolls the task back in another process, after this one
// already returned the prepared task.
writeUpdateState(path.join(dataDir, "updates", "state.json"), {
schemaVersion: 1,
task: {
...task, status: "failed", finishedAt: "2026-01-01T00:05:00.000Z", updatedAt: "2026-01-01T00:05:00.000Z",
errorCode: "UPDATE_HEALTH_CHECK_FAILED", errorMessage: "health check failed", rolledBack: true,
},
});
const status = service.getStatus();
assert.equal(status.task?.status, "failed");
assert.equal(status.task?.rolledBack, true);
assert.equal(status.task?.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
});
test("initialization restores the previous code from an interrupted swap backup", t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_interrupted_swap";
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
// The process died after moving the previous code aside and only part of
// the new package had been moved in.
mkdirSync(path.join(backupDir, "dist"), { recursive: true });
writeFileSync(path.join(backupDir, "dist", "index.js"), "// old code\n");
writeFileSync(path.join(backupDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), "// new code\n");
writeFileSync(path.join(fixture.rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
writeUpdateState(statePath, {
schemaVersion: 1,
task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
});
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
restarted.initialize();
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// old code\n");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
const status = restarted.getStatus();
assert.equal(status.task?.status, "failed");
assert.equal(status.task?.rolledBack, true);
assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
assert.equal(existsSync(lockPath), false);
});
test("initialization keeps a 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 = {
schemaVersion: 1 as const,
task: {
id: "upd_live", status: "downloading" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
};
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
mkdirSync(path.dirname(statePath), { recursive: true });
writeFileSync(statePath, JSON.stringify(running));
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_live", createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:00:00.000Z"),
});
restarted.initialize();
assert.equal(restarted.getStatus().task?.status, "downloading");
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId: "upd_live", createdAt: "2026-01-01T00:00:00.000Z" }));
restarted.initialize();
assert.equal(restarted.getStatus().task?.status, "failed");
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
});
test("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");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
const task = {
id: "upd_completed_runner", status: "restarting" as const, fromVersion: "0.3.1", targetVersion: "0.3.2",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
};
const release = acquireUpdateLock(lockPath, task.id);
t.after(release);
writeUpdateState(statePath, { schemaVersion: 1, task });
fixture.service.initialize();
assert.equal(fixture.service.getStatus().task?.status, "restarting");
writeUpdateState(statePath, { schemaVersion: 1, task: { ...task, status: "succeeded", finishedAt: "2026-01-01T00:01:00.000Z" } });
release();
assert.equal(fixture.service.getStatus().task?.status, "succeeded");
// It reaches release lookup instead of being rejected by a stale active task.
await assert.rejects(fixture.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_VERSION_NOT_FOUND"));
});
test("supervised packages can check releases but cannot download or launch an update", async t => {
const fixture = createService(t, [{ version: "0.4.0", assets: [] }], new Map(), { isSupervised: true });
const checked = await fixture.service.checkForUpdates();
assert.equal(checked.releases[0]?.blockedReason, "DEPLOYMENT_SUPERVISED");
assert.equal(checked.releases[0]?.canApply, false);
await assert.rejects(fixture.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
assert.deepEqual(fixture.launched, []);
assert.equal(fixture.service.getStatus().task, null);
});
test("initialization does not roll back a task whose lock belongs to another live process", async t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_other_process";
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
const owner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
t.after(() => { try { owner.kill("SIGKILL"); } catch { /* Already gone. */ } });
await once(owner, "spawn");
assert.ok(owner.pid);
writeUpdateState(statePath, {
schemaVersion: 1,
task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
});
writeFileSync(lockPath, JSON.stringify({ pid: owner.pid, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
restarted.initialize();
const status = restarted.getStatus();
assert.equal(status.task?.status, "restarting");
assert.equal(status.task?.errorCode, null);
assert.equal(status.task?.rolledBack, false);
assert.equal(existsSync(lockPath), true);
});
/** Every module the detached runner imports, compiled side by side. */
const RUNNER_RUNTIME_FILES = ["restart-runner.js", "code-swap.js", "version.js", "update-state.js"];
async function compileRunnerSources(destination: string): Promise<void> {
const { build } = await import("esbuild");
const sourceDirectory = path.dirname(fileURLToPath(import.meta.url));
await build({
entryPoints: RUNNER_RUNTIME_FILES.map((file) => path.join(sourceDirectory, file.replace(/\.js$/, ".ts"))),
outdir: destination,
bundle: false,
format: "esm",
platform: "node",
target: "node22",
logLevel: "silent",
});
}
function processIsAlive(pid: number): boolean {
try { process.kill(pid, 0); return true; }
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
}
async function stopProcess(pid: number): Promise<void> {
try { process.kill(pid, "SIGKILL"); } catch { /* Already gone. */ }
const deadline = Date.now() + 5_000;
while (Date.now() < deadline && processIsAlive(pid)) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
}
test("the real restart runner starts with every runtime module and survives the grace window", async t => {
const directory = workspace(t);
const compiled = path.join(directory, "compiled");
await compileRunnerSources(compiled);
const rootDir = path.join(directory, "app");
createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const updatesDir = path.join(dataDir, "updates");
mkdirSync(updatesDir, { recursive: true });
const taskId = "upd_real_runner";
const statePath = path.join(updatesDir, "state.json");
writeUpdateState(statePath, {
schemaVersion: 1,
task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
});
const planPath = path.join(updatesDir, "plan.json");
const runnerDirectory = path.join(updatesDir, "runner");
const lockPath = path.join(updatesDir, "update.lock");
writeFileSync(planPath, JSON.stringify({
schemaVersion: 1,
taskId,
rootDir,
statePath,
lockPath,
stagedRoot: path.join(updatesDir, "staged"),
backupDir: path.join(updatesDir, "backups", taskId),
fromVersion: "0.3.2",
targetVersion: "0.4.0",
nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
// Deliberately not 3040 so the test cannot collide with a real server.
health: { protocol: "http", port: 39999, path: "/api/health" },
// The test process stays alive, so the runner waits instead of swapping.
waitForPid: process.pid,
parentTimeoutMs: 60_000,
healthTimeoutMs: 100,
pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
const service = new UpdateService({
rootDir, dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false,
fetch: fakeFetch([], new Map()),
runnerSourceDir: compiled,
runnerStartupTimeoutMs: 600,
});
// Call the real launcher: no spawn mock, the compiled runner is executed.
const pid = await service.launchRunner(planPath, runnerDirectory);
t.after(() => stopProcess(pid));
assert.ok(Number.isInteger(pid) && pid > 0, "the runner reported a pid");
for (const file of RUNNER_RUNTIME_FILES) {
assert.equal(existsSync(path.join(runnerDirectory, file)), true, `${file} was copied next to the runner`);
}
assert.doesNotThrow(() => process.kill(pid, 0), "the runner is still alive after the grace window");
const lock = JSON.parse(readFileSync(lockPath, "utf8"));
assert.equal(lock.taskId, taskId);
assert.equal(lock.pid, pid);
const log = readFileSync(path.join(updatesDir, "runner.log"), "utf8");
assert.ok(!log.includes("ERR_MODULE_NOT_FOUND"), `runner log has no missing module: ${log}`);
});
test("the runner handshake requires lock takeover and a later death is caught before exit", async t => {
const directory = workspace(t);
const compiled = path.join(directory, "compiled");
await compileRunnerSources(compiled);
const rootDir = path.join(directory, "app");
createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const updatesDir = path.join(dataDir, "updates");
mkdirSync(updatesDir, { recursive: true });
const taskId = "upd_handshake";
const statePath = path.join(updatesDir, "state.json");
const lockPath = path.join(updatesDir, "update.lock");
const planPath = path.join(updatesDir, "plan.json");
const makeTask = () => ({
id: taskId, status: "restarting" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
});
const writePlan = () => writeFileSync(planPath, JSON.stringify({
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
stagedRoot: path.join(updatesDir, "staged"),
backupDir: path.join(updatesDir, "backups", taskId),
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
health: { protocol: "http", port: 39998, path: "/api/health" },
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
writeUpdateState(statePath, { schemaVersion: 1, task: makeTask() });
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
writePlan();
const service = new UpdateService({
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
});
const pid = await service.launchRunner(planPath, path.join(updatesDir, "runner"));
t.after(() => stopProcess(pid));
assert.equal(service.runnerStillHealthy(), true, "runner owns the lock right after the handshake");
await stopProcess(pid);
assert.equal(service.runnerStillHealthy(), false, "a runner that died after 202 is caught before process.exit");
});
test("a runner that cannot take over the lock never passes the handshake", async t => {
const directory = workspace(t);
const compiled = path.join(directory, "compiled");
await compileRunnerSources(compiled);
const rootDir = path.join(directory, "app");
createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const updatesDir = path.join(dataDir, "updates");
mkdirSync(updatesDir, { recursive: true });
const taskId = "upd_bad_lock";
const statePath = path.join(updatesDir, "state.json");
const lockPath = path.join(updatesDir, "update.lock");
const planPath = path.join(updatesDir, "plan.json");
writeUpdateState(statePath, {
schemaVersion: 1,
task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
});
// A different task owns the lock: the runner must refuse to steal it.
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_other", createdAt: "2026-01-01T00:00:00.000Z" }));
writeFileSync(planPath, JSON.stringify({
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
stagedRoot: path.join(updatesDir, "staged"),
backupDir: path.join(updatesDir, "backups", taskId),
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
health: { protocol: "http", port: 39997, path: "/api/health" },
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
const service = new UpdateService({
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
});
await assert.rejects(
service.launchRunner(planPath, path.join(updatesDir, "runner")),
updateErrorCode("UPDATE_RUNNER_FAILED"),
);
assert.equal(service.runnerStillHealthy(), true, "no runner was recorded, so the guard is a no-op");
});
+700
View File
@@ -0,0 +1,700 @@
import { createHash, randomBytes } from "node:crypto";
import { spawn, type ChildProcess } from "node:child_process";
import {
chmodSync, closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync,
} from "node:fs";
import { rename, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { CodeSwapError, locatePackageRoot, restoreCode, validateStagedPackage } from "./code-swap.js";
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
import {
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
type OfficialRelease, type ReleaseAsset,
} from "./releases.js";
import {
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
reconcileInterruptedState, updateLockIsHeld, UpdateLockedError, writeUpdateState, type PersistedUpdateState,
} from "./update-state.js";
import { compareVersions, isNewerVersion, isValidVersion } from "./version.js";
export type UpdateErrorCode =
| "UPDATE_IN_PROGRESS"
| "UPDATE_NOT_SUPPORTED"
| "UPDATE_VERSION_INVALID"
| "UPDATE_VERSION_NOT_NEWER"
| "UPDATE_VERSION_NOT_FOUND"
| "UPDATE_CONFIRMATION_REQUIRED"
| "UPDATE_ASSET_UNAVAILABLE"
| "UPDATE_CHECKSUM_MISSING"
| "UPDATE_CHECKSUM_MISMATCH"
| "UPDATE_DIGEST_MISMATCH"
| "UPDATE_DIGEST_UNSUPPORTED"
| "UPDATE_DOWNLOAD_FAILED"
| "UPDATE_DOWNLOAD_TOO_LARGE"
| "UPDATE_ARCHIVE_UNSAFE"
| "UPDATE_ARCHIVE_INVALID"
| "UPDATE_ARCHIVE_LIMIT"
| "UPDATE_ARCHIVE_UNSUPPORTED"
| "UPDATE_PACKAGE_INVALID"
| "UPDATE_SWAP_FAILED"
| "UPDATE_ROLLBACK_FAILED"
| "UPDATE_RELEASE_UNAVAILABLE"
| "UPDATE_RUNNER_MISSING"
| "UPDATE_RUNNER_FAILED"
| "UPDATE_FAILED";
export class UpdateError extends Error {
constructor(readonly code: UpdateErrorCode, message: string, readonly statusCode = 400) {
super(message);
this.name = "UpdateError";
}
}
export interface UpdateServiceOptions {
rootDir: string;
dataDir: string;
currentVersion: string;
logger: Logger;
port?: number;
https?: boolean;
platform?: NodeJS.Platform;
architecture?: string;
env?: NodeJS.ProcessEnv;
isDocker?: boolean;
isSupervised?: boolean;
fetch?: typeof fetch;
apiBaseUrl?: string;
repository?: string;
now?: () => Date;
/** Compiled directory containing the restart runner and its runtime imports. */
runnerSourceDir?: string;
/** Test seam replacing the detached runner spawn. */
launchRunner?: (planPath: string, runnerDir: string) => Promise<void>;
/** How long a freshly spawned runner must stay alive before apply succeeds. */
runnerStartupTimeoutMs?: number;
healthTimeoutMs?: number;
downloadTimeoutMs?: number;
}
const CHECKSUM_LIMIT = 1024 * 1024;
const DOWNLOAD_LIMIT = 512 * 1024 * 1024;
/**
* Install the recovery-capable launcher before the runner tears down dist/
* and runtime/. The staged package ships the canonical script (same file CI
* generates), so even the first upgrade from the old four-line launcher has
* a self-healing ./start-webspeak.sh on the official path at all times.
*/
function installRecoveryLauncher(rootDir: string, stagedRoot: string): void {
const source = path.join(stagedRoot, "start-webspeak.sh");
// Source installs and hand-built test packages have no launcher; real
// release packages always do.
if (!existsSync(source)) return;
const target = path.join(rootDir, "start-webspeak.sh");
const temporary = `${target}.${process.pid}.tmp`;
try {
copyFileSync(source, temporary);
chmodSync(temporary, 0o755);
renameSync(temporary, target);
} catch (error) {
try { rmSync(temporary, { force: true }); } catch { /* Preserve the original error. */ }
throw error;
}
}
/**
* Every local module the restart runner imports at runtime. The runner is
* copied into an isolated directory under data/updates, so any omission here
* makes Node fail with ERR_MODULE_NOT_FOUND before the helper can swap code.
*/
const RUNNER_RUNTIME_FILES = ["restart-runner.js", "code-swap.js", "version.js", "update-state.js"] as const;
interface DownloadResult {
sha256: string;
bytes: number;
}
export class UpdateService {
readonly deployment: DeploymentInfo;
private readonly source: GitHubReleaseSource;
private readonly updatesDir: string;
private readonly statePath: string;
private readonly lockPath: string;
private readonly tasksDir: string;
private readonly backupsDir: string;
private readonly fetcher: typeof fetch;
private readonly now: () => Date;
private state: PersistedUpdateState = emptyUpdateState();
private applying = false;
private releaseLock: (() => void) | null = null;
private runnerPid: number | null = null;
constructor(private readonly options: UpdateServiceOptions) {
this.deployment = detectDeployment({
rootDir: options.rootDir,
platform: options.platform,
architecture: options.architecture,
env: options.env,
isDocker: options.isDocker,
isSupervised: options.isSupervised,
});
this.source = new GitHubReleaseSource({
fetch: options.fetch,
apiBaseUrl: options.apiBaseUrl,
repository: options.repository,
});
this.fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
this.now = options.now ?? (() => new Date());
this.updatesDir = path.join(options.dataDir, "updates");
this.statePath = path.join(this.updatesDir, "state.json");
this.lockPath = path.join(this.updatesDir, "update.lock");
this.tasksDir = path.join(this.updatesDir, "tasks");
this.backupsDir = path.join(this.updatesDir, "backups");
}
initialize(): void {
mkdirSync(this.updatesDir, { recursive: true });
this.state = readUpdateState(this.statePath);
const task = this.state.task;
// A live lock owner (for example a second process starting by mistake)
// must not have its in-flight task reconciled as interrupted.
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath)) {
const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null;
const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
if (changed) writeUpdateState(this.statePath, this.state);
}
clearStaleUpdateLock(this.lockPath);
this.options.logger.info({
deployment: this.deployment.mode,
version: this.options.currentVersion,
task: this.state.task?.status ?? "idle",
}, "Update service initialized");
}
/**
* A crash during the swap leaves the previous code in the backup directory
* and possibly only partial new code in the install directory. Restore the
* previous code before reporting the task, rather than trusting a version
* whose files may be incomplete.
*/
private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null {
const backupDir = path.join(this.backupsDir, task.id);
if (!existsSync(backupDir)) return null;
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 {
restoreCode(this.options.rootDir, backupDir);
restored = true;
} catch (error) {
this.options.logger.warn({
taskId: task.id,
err: error instanceof Error ? error.message : String(error),
}, "Interrupted update code could not be restored from backup");
}
task.status = "failed";
task.finishedAt = now;
task.updatedAt = now;
task.rolledBack = restored;
if (restored) {
task.errorCode = "UPDATE_INTERRUPTED";
task.errorMessage = "The process stopped during the update. The previous version was restored from the backup.";
} else {
task.errorCode = "UPDATE_ROLLBACK_FAILED";
task.errorMessage = "The process stopped during the update and the code could not be restored automatically. Restore the previous version from the backup.";
}
return true;
}
getStatus(): UpdateStatusView {
// The restart runner updates the persisted task after this process has
// already returned a response, so always report the on-disk state. Do not
// replace the in-memory state: an apply in progress still writes to it.
const state = readUpdateState(this.statePath);
return {
currentVersion: this.options.currentVersion,
deployment: {
mode: this.deployment.mode,
platform: this.deployment.platform,
architecture: this.deployment.architecture,
applyAllowed: this.deployment.applyAllowed,
reasonCode: this.deployment.reasonCode,
upgradePath: this.deployment.upgradePath,
},
task: state.task,
};
}
async checkForUpdates(): Promise<UpdateCheckView> {
let releases: OfficialRelease[];
try { releases = await this.source.listStableReleases(); }
catch (error) { throw mapError(error); }
const newer = releases
.filter((release) => isNewerVersion(release.version, this.options.currentVersion))
.sort((left, right) => compareVersions(right.version, left.version));
return {
currentVersion: this.options.currentVersion,
releases: newer.map((release) => this.toReleaseView(release)),
};
}
private toReleaseView(release: OfficialRelease): UpdateReleaseView {
const assetName = this.deployment.assetKind ? releaseAssetName(release.version, this.deployment.assetKind) : "";
const asset = assetName ? release.assets.find((item) => item.name === assetName) ?? null : null;
const checksums = release.assets.find((item) => item.name === CHECKSUM_ASSET_NAME) ?? null;
let blockedReason: string | null = null;
if (!this.deployment.applyAllowed) blockedReason = this.deployment.reasonCode ?? "DEPLOYMENT_SOURCE";
else if (!asset) blockedReason = "UPDATE_ASSET_UNAVAILABLE";
else if (!checksums) blockedReason = "UPDATE_CHECKSUM_MISSING";
return {
version: release.version,
tag: release.tag,
publishedAt: release.publishedAt,
releaseUrl: release.releaseUrl,
assetName,
assetSize: asset?.size ?? 0,
assetAvailable: Boolean(asset),
hasChecksums: Boolean(checksums),
digest: asset?.digest ?? null,
canApply: blockedReason === null,
blockedReason,
};
}
async applyUpdate(version: string, confirmVersion: string): Promise<UpdateTaskView> {
if (version !== confirmVersion) {
throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
}
if (!this.deployment.applyAllowed) {
throw new UpdateError("UPDATE_NOT_SUPPORTED", this.deployment.reasonCode ?? "Updates cannot be applied from this deployment.", 409);
}
if (!isValidVersion(version)) throw new UpdateError("UPDATE_VERSION_INVALID", "The selected version is invalid.");
if (!isNewerVersion(version, this.options.currentVersion)) {
throw new UpdateError("UPDATE_VERSION_NOT_NEWER", "The selected version is not newer than the running version.", 409);
}
if (this.applying) {
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
}
// The runner finishes after the replacement app has initialized. Its
// terminal state on disk must replace that app's cached "restarting"
// state before the next update; never reload during our own active apply.
this.state = readUpdateState(this.statePath);
if (this.state.task && isActiveTaskStatus(this.state.task.status)) {
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
}
this.applying = true;
this.runnerPid = null;
const taskId = `upd_${Date.now().toString(36)}_${randomBytes(6).toString("hex")}`;
const startedAt = this.now().toISOString();
const task: UpdateTaskView = {
id: taskId,
status: "downloading",
fromVersion: this.options.currentVersion,
targetVersion: version,
startedAt,
updatedAt: startedAt,
finishedAt: null,
errorCode: null,
errorMessage: null,
rolledBack: false,
steps: [],
};
const taskDirectory = path.join(this.tasksDir, taskId);
try {
this.releaseLock = acquireUpdateLock(this.lockPath, taskId);
this.state = { schemaVersion: 1, task };
writeUpdateState(this.statePath, this.state);
mkdirSync(taskDirectory, { recursive: true });
const release = await this.source.findRelease(version);
if (!release) throw new UpdateError("UPDATE_VERSION_NOT_FOUND", "The selected stable release is no longer published.", 404);
if (!this.deployment.assetKind) throw new UpdateError("UPDATE_NOT_SUPPORTED", "This platform has no release package.", 409);
const assetName = releaseAssetName(version, this.deployment.assetKind);
const asset = release.assets.find((item) => item.name === assetName);
if (!asset) throw new UpdateError("UPDATE_ASSET_UNAVAILABLE", "The official release has no package for this platform.", 404);
const checksumAsset = release.assets.find((item) => item.name === CHECKSUM_ASSET_NAME);
if (!checksumAsset) throw new UpdateError("UPDATE_CHECKSUM_MISSING", "The official release has no SHA256SUMS.txt; updates are refused.", 409);
const downloadDirectory = path.join(taskDirectory, "download");
mkdirSync(downloadDirectory, { recursive: true });
const archivePath = path.join(downloadDirectory, assetName);
const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME);
this.startStep(task, "download");
const 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");
this.verifyChecksums(checksumPath, assetName, archive.sha256, checksumFile.sha256, asset, checksumAsset);
this.finishStep(task, "checksum", "succeeded");
this.updateTaskStatus(task, "extracting");
this.startStep(task, "extract");
const extractedDirectory = path.join(taskDirectory, "extracted");
try {
await extractReleaseArchive(archivePath, extractedDirectory, assetName);
} catch (error) {
if (error instanceof ArchiveError) throw new UpdateError(error.code, error.message, 422);
throw error;
}
this.finishStep(task, "extract", "succeeded");
this.updateTaskStatus(task, "staging");
this.startStep(task, "stage");
let stagedRoot: string;
try {
if (!existsSync(archivePath)) throw new Error("Downloaded release package is missing.");
stagedRoot = locatePackageRoot(extractedDirectory, version, this.deployment.platform);
} catch (error) {
if (error instanceof CodeSwapError) throw new UpdateError("UPDATE_PACKAGE_INVALID", error.message, 422);
throw error;
}
this.finishStep(task, "stage", "succeeded");
installRecoveryLauncher(this.options.rootDir, stagedRoot);
const planPath = path.join(taskDirectory, "plan.json");
const runnerDirectory = path.join(taskDirectory, "runner");
const plan = {
schemaVersion: 1,
taskId,
rootDir: this.options.rootDir,
statePath: this.statePath,
lockPath: this.lockPath,
stagedRoot,
backupDir: path.join(this.backupsDir, taskId),
fromVersion: this.options.currentVersion,
targetVersion: version,
nodePath: path.join(this.options.rootDir, this.deployment.platform === "win32" ? "runtime/node.exe" : "runtime/node"),
appEntry: path.join(this.options.rootDir, "dist", "index.js"),
health: {
protocol: this.options.https ? "https" : "http",
port: this.options.port ?? 3040,
path: "/api/health",
},
waitForPid: process.pid,
parentTimeoutMs: 60_000,
healthTimeoutMs: this.options.healthTimeoutMs ?? 90_000,
pollIntervalMs: 500,
appLogPath: path.join(taskDirectory, "app.log"),
};
writeFileSync(planPath, JSON.stringify(plan, null, 2), { encoding: "utf8", mode: 0o600 });
this.updateTaskStatus(task, "restarting");
this.startStep(task, "restart");
writeUpdateState(this.statePath, this.state);
try {
if (this.options.launchRunner) await this.options.launchRunner(planPath, runnerDirectory);
else await this.launchRunner(planPath, runnerDirectory);
} catch (error) {
if (error instanceof UpdateError) throw error;
throw new UpdateError("UPDATE_RUNNER_FAILED", error instanceof Error ? error.message : "The restart runner could not be started.");
}
this.releaseLock = null;
this.options.logger.info({ taskId, from: task.fromVersion, to: version }, "Update prepared; restart runner started");
return task;
} catch (error) {
const updateError = mapError(error);
// A lock conflict belongs to another task. Never overwrite its persisted
// state just because this request was rejected.
const ownsTask = this.releaseLock !== null || this.state.task?.id === taskId;
task.status = "failed";
task.updatedAt = this.now().toISOString();
task.finishedAt = task.updatedAt;
task.errorCode = updateError.code;
task.errorMessage = updateError.message;
const runningStep = [...task.steps].reverse().find((step) => step.status === "running");
this.finishStep(task, runningStep?.name ?? "prepare", "failed", updateError.message);
if (ownsTask) {
this.state = { schemaVersion: 1, task };
try { writeUpdateState(this.statePath, this.state); } catch { /* Preserve the original error. */ }
}
try { rmSync(taskDirectory, { recursive: true, force: true }); } catch { /* Best effort. */ }
this.releaseLock?.();
this.releaseLock = null;
this.runnerPid = null;
// A runner that died after taking over leaves its own pid in the lock.
// Only a provably dead owner is removed; a live lock is left alone.
clearStaleUpdateLock(this.lockPath);
throw updateError;
} finally {
this.applying = false;
}
}
private updateTaskStatus(task: UpdateTaskView, status: UpdateTaskStatus): void {
task.status = status;
task.updatedAt = this.now().toISOString();
writeUpdateState(this.statePath, this.state);
}
private startStep(task: UpdateTaskView, name: string, detail?: string): void {
const at = this.now().toISOString();
const existing = task.steps.find((step) => step.name === name);
if (existing) { existing.status = "running"; existing.at = at; if (detail) existing.detail = detail; }
else task.steps.push({ name, status: "running", at, ...(detail ? { detail } : {}) });
task.updatedAt = at;
}
private finishStep(task: UpdateTaskView, name: string, status: "succeeded" | "failed", detail?: string): void {
const at = this.now().toISOString();
const existing = task.steps.find((step) => step.name === name);
if (existing) { existing.status = status; existing.at = at; if (detail) existing.detail = detail; }
else task.steps.push({ name, status, at, ...(detail ? { detail } : {}) });
task.updatedAt = at;
}
private verifyChecksums(
checksumPath: string,
assetName: string,
archiveSha256: string,
checksumSha256: string,
asset: ReleaseAsset,
checksumAsset: ReleaseAsset,
): void {
const text = readFileSync(checksumPath, "utf8");
const expected = parseChecksumFile(text).get(assetName);
if (!expected) throw new UpdateError("UPDATE_CHECKSUM_MISSING", "SHA256SUMS.txt has no entry for the selected package; the update is refused.", 409);
if (expected !== archiveSha256) throw new UpdateError("UPDATE_CHECKSUM_MISMATCH", "The downloaded package does not match SHA256SUMS.txt.", 422);
this.crossCheckDigest(asset, archiveSha256);
this.crossCheckDigest(checksumAsset, checksumSha256);
}
private crossCheckDigest(asset: ReleaseAsset, actual: string): void {
if (!asset.digest) return;
const [algorithm, value] = asset.digest.split(":", 2);
if (algorithm?.toLowerCase() !== "sha256" || !/^[a-f0-9]{64}$/i.test(value ?? "")) {
throw new UpdateError("UPDATE_DIGEST_UNSUPPORTED", "GitHub supplied an unsupported asset digest.", 409);
}
if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422);
}
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number, 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,
});
} catch (error) {
controller.abort();
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502);
}
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
let stream: ReturnType<typeof createWriteStream> | undefined;
let temporary: string | undefined;
let onAbort: (() => void) | undefined;
try {
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)) {
const drained = await Promise.race([streamFailure, new Promise<void>((resolve) => { writer.once("drain", resolve); })]);
if (drained instanceof Error) throw drained;
}
}
stream.end();
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) {
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();
}
}
/**
* Copy the runner and all of its runtime imports into an isolated directory,
* start it detached, and wait until it has taken over the update lock.
* A successful spawn alone is not enough: Node resolves the whole ESM module
* graph before executing the helper, so a missing file only shows up as an
* early exit. Ownership of the lock also proves the runner is alive after
* its startup window and really controls this task before we promise 202.
*/
async launchRunner(planPath: string, runnerDirectory: string): Promise<number> {
const sourceDirectory = this.options.runnerSourceDir ?? path.dirname(fileURLToPath(import.meta.url));
const missing = RUNNER_RUNTIME_FILES.filter((file) => !existsSync(path.join(sourceDirectory, file)));
if (missing.length > 0) {
throw new UpdateError(
"UPDATE_RUNNER_MISSING",
`The compiled restart runner is incomplete (missing ${missing.join(", ")}); rebuild the application before updating.`,
500,
);
}
mkdirSync(runnerDirectory, { recursive: true });
for (const file of RUNNER_RUNTIME_FILES) {
copyFileSync(path.join(sourceDirectory, file), path.join(runnerDirectory, file));
}
writeFileSync(path.join(runnerDirectory, "package.json"), JSON.stringify({ type: "module" }), "utf8");
let nodePath: string;
if (this.deployment.platform === "win32") {
nodePath = path.join(runnerDirectory, "node.exe");
copyFileSync(process.execPath, nodePath);
} else {
nodePath = process.execPath;
}
const log = path.join(path.dirname(planPath), "runner.log");
const graceMs = this.options.runnerStartupTimeoutMs ?? 1_500;
return new Promise<number>((resolve, reject) => {
let child: ChildProcess;
let fd: number | null = null;
try {
fd = openSync(log, "a");
child = spawn(nodePath, [path.join(runnerDirectory, "restart-runner.js"), planPath], {
cwd: this.options.rootDir,
env: process.env,
detached: true,
windowsHide: true,
stdio: ["ignore", fd, fd],
});
} catch (error) {
reject(error);
return;
} finally {
if (fd !== null) closeSync(fd);
}
let settled = false;
let poll: NodeJS.Timeout | undefined;
const fail = (message: string) => {
if (settled) return;
settled = true;
if (poll) clearInterval(poll);
reject(new UpdateError("UPDATE_RUNNER_FAILED", message, 500));
};
child.once("error", (error) => fail(error.message));
child.once("exit", (code, signal) => {
fail(`The restart runner exited before taking over (code ${code ?? "none"}, signal ${signal ?? "none"}).`);
});
child.once("spawn", () => {
child.unref();
const deadline = Date.now() + graceMs;
poll = setInterval(() => {
if (settled) return;
const pid = child.pid;
if (!pid) {
fail("The restart runner did not report a process id.");
return;
}
if (Date.now() > deadline) {
fail("The restart runner did not take over the update lock in time.");
return;
}
if (!pidIsAlive(pid) || !lockOwnedBy(this.lockPath, pid)) return;
settled = true;
if (poll) clearInterval(poll);
this.runnerPid = pid;
resolve(pid);
}, 25);
});
});
}
/**
* Last chance guard for the promise made with 202. The parent still exists
* for a short window after the handshake, so re-check that the runner is
* alive and still owns the lock before the caller exits the process.
*/
runnerStillHealthy(): boolean {
const pid = this.runnerPid;
// No runner was launched through this instance (source install, mocked
// route test): there is nothing extra to verify.
if (pid === null) return true;
return pidIsAlive(pid) && lockOwnedBy(this.lockPath, pid);
}
}
function pidIsAlive(pid: number): boolean {
try { process.kill(pid, 0); return true; }
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
}
function lockOwnedBy(lockPath: string, pid: number): boolean {
try {
const record = JSON.parse(readFileSync(lockPath, "utf8")) as { pid?: unknown };
return record?.pid === pid;
} catch {
return false;
}
}
function repositoryParts(repository: string | undefined): [string, string] {
const [owner, repo] = (repository ?? "EchoSixHIYA/WebSpeak-client-for-TeamSpeak").split("/");
return [owner, repo];
}
export function parseChecksumFile(text: string): Map<string, string> {
const entries = new Map<string, string>();
for (const line of text.split(/\r?\n/)) {
const match = /^([a-fA-F0-9]{64})\s+\*?(.+?)\s*$/.exec(line.trim());
if (!match) continue;
const name = match[2].replace(/^\.\//, "");
if (!entries.has(name)) entries.set(name, match[1].toLowerCase());
}
return entries;
}
function mapError(error: unknown): UpdateError {
if (error instanceof UpdateError) return error;
if (error instanceof UpdateLockedError) return new UpdateError("UPDATE_IN_PROGRESS", error.message, 409);
if (error instanceof ReleaseSourceError) return new UpdateError("UPDATE_RELEASE_UNAVAILABLE", error.message, 502);
if (error instanceof ArchiveError) return new UpdateError(error.code, error.message, 422);
if (error instanceof CodeSwapError) return new UpdateError(error.code, error.message, 422);
return new UpdateError("UPDATE_FAILED", error instanceof Error ? error.message : "The update failed.", 500);
}
+159
View File
@@ -0,0 +1,159 @@
import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import test, { type TestContext } from "node:test";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { UpdateTaskView } from "../shared/update.js";
import {
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
reconcileInterruptedState, takeOverUpdateLock, UpdateLockedError, updateLockIsHeld, writeUpdateState,
} from "./update-state.js";
function workspace(t: TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-state-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function task(overrides: Partial<UpdateTaskView> = {}): UpdateTaskView {
return {
id: "upd_test",
status: "restarting",
fromVersion: "0.3.2",
targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
finishedAt: null,
errorCode: null,
errorMessage: null,
rolledBack: false,
steps: [{ name: "swap", status: "running", at: "2026-01-01T00:00:00.000Z" }],
...overrides,
};
}
/** A second process that stays alive while a lock records its pid. */
async function liveProcess(t: TestContext): Promise<ChildProcess> {
const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
t.after(() => { try { child.kill("SIGKILL"); } catch { /* Already gone. */ } });
await once(child, "spawn");
return child;
}
test("state files round-trip and malformed files fall back to idle", t => {
const directory = workspace(t), filename = path.join(directory, "state.json");
assert.deepEqual(readUpdateState(filename), emptyUpdateState());
writeUpdateState(filename, { schemaVersion: 1, task: task() });
const loaded = readUpdateState(filename);
assert.equal(loaded.task?.id, "upd_test");
assert.deepEqual(loaded.task?.steps, [{ name: "swap", status: "running", at: "2026-01-01T00:00:00.000Z" }]);
for (const contents of ["not json", "{}", JSON.stringify({ schemaVersion: 2, task: task() }), JSON.stringify({ schemaVersion: 1, task: { id: 42 } })]) {
writeFileSync(filename, contents);
assert.deepEqual(readUpdateState(filename), emptyUpdateState());
}
});
test("interrupted tasks reconcile against the version that is actually running", () => {
const completed = { schemaVersion: 1 as const, task: task({ targetVersion: "0.4.0" }) };
assert.equal(reconcileInterruptedState(completed, "0.4.0", "2026-01-01T01:00:00.000Z"), true);
assert.equal(completed.task?.status, "succeeded");
assert.equal(completed.task?.finishedAt, "2026-01-01T01:00:00.000Z");
const interrupted = { schemaVersion: 1 as const, task: task({ targetVersion: "0.4.0" }) };
assert.equal(reconcileInterruptedState(interrupted, "0.3.2", "2026-01-01T01:00:00.000Z"), true);
assert.equal(interrupted.task?.status, "failed");
assert.equal(interrupted.task?.errorCode, "UPDATE_INTERRUPTED");
const finished = { schemaVersion: 1 as const, task: task({ status: "succeeded" as const }) };
assert.equal(reconcileInterruptedState(finished, "0.3.2", "2026-01-01T01:00:00.000Z"), false);
assert.equal(isActiveTaskStatus("downloading"), true);
assert.equal(isActiveTaskStatus("failed"), false);
});
test("the update lock is exclusive and safe to release", t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
const release = acquireUpdateLock(lock, "task-one");
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "task-one");
assert.throws(() => acquireUpdateLock(lock, "task-two"), (error: unknown) => error instanceof UpdateLockedError);
release();
assert.equal(existsSync(lock), false);
const second = acquireUpdateLock(lock, "task-two");
second();
assert.equal(existsSync(lock), false);
});
test("locks left by dead processes are reclaimed while live locks are preserved", t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
const release = acquireUpdateLock(lock, "new-task");
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "new-task");
release();
writeFileSync(lock, JSON.stringify({ pid: process.pid, taskId: "live-task", createdAt: "2026-01-01T00:00:00.000Z" }));
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), true);
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), false);
});
test("a live lock and an unreadable lock are never cleared, and count as held", async t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
const owner = await liveProcess(t);
writeFileSync(lock, JSON.stringify({ pid: owner.pid, taskId: "live-task", createdAt: "2026-01-01T00:00:00.000Z" }));
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), true);
assert.equal(updateLockIsHeld(lock), true);
assert.equal(updateLockIsHeld(lock, "live-task"), true);
assert.equal(updateLockIsHeld(lock, "other-task"), false);
assert.throws(() => acquireUpdateLock(lock, "new-task"), (error: unknown) => error instanceof UpdateLockedError);
// A lock that cannot be parsed may belong to a live owner, so it must not
// be deleted and must conservatively block new updates.
writeFileSync(lock, "not a lock record");
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), true);
assert.equal(updateLockIsHeld(lock), true);
assert.throws(() => acquireUpdateLock(lock, "new-task"), (error: unknown) => error instanceof UpdateLockedError);
});
test("a lock left by a dead process is reported free and reclaimed", t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
assert.equal(updateLockIsHeld(lock), false);
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), false);
const release = acquireUpdateLock(lock, "new-task");
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "new-task");
release();
});
test("the restart runner can take over its own task but never another task's lock", async t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
const previousOwner = await liveProcess(t);
writeFileSync(lock, JSON.stringify({ pid: previousOwner.pid, taskId: "task-shared", createdAt: "2026-01-01T00:00:00.000Z" }));
assert.doesNotThrow(() => process.kill(previousOwner.pid!, 0), "the original owner is still alive");
const release = takeOverUpdateLock(lock, "task-shared");
const record = JSON.parse(readFileSync(lock, "utf8"));
assert.equal(record.pid, process.pid);
assert.equal(record.taskId, "task-shared");
assert.equal(updateLockIsHeld(lock, "task-shared"), true);
release();
assert.equal(existsSync(lock), false);
writeFileSync(lock, JSON.stringify({ pid: previousOwner.pid, taskId: "task-other", createdAt: "2026-01-01T00:00:00.000Z" }));
assert.throws(() => takeOverUpdateLock(lock, "task-shared"), (error: unknown) => error instanceof UpdateLockedError);
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "task-other");
assert.equal(updateLockIsHeld(lock, "task-other"), true);
});
test("state writes replace the destination atomically", t => {
const directory = workspace(t), filename = path.join(directory, "nested", "state.json");
writeUpdateState(filename, { schemaVersion: 1, task: task({ id: "first" }) });
writeUpdateState(filename, { schemaVersion: 1, task: task({ id: "second" }) });
assert.equal(readUpdateState(filename).task?.id, "second");
assert.equal(existsSync(`${filename}.${process.pid}.tmp`), false);
});
+311
View File
@@ -0,0 +1,311 @@
import { randomBytes } from "node:crypto";
import { mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
export interface PersistedUpdateState {
schemaVersion: 1;
task: UpdateTaskView | null;
}
export interface UpdateLockRecord {
pid: number;
taskId: string;
createdAt: string;
/** Opaque process start marker; guards against PID reuse where available. */
processStart?: string | null;
}
export class UpdateLockedError extends Error {
readonly code = "UPDATE_IN_PROGRESS";
constructor(message = "Another update task is already running.") {
super(message);
this.name = "UpdateLockedError";
}
}
const ACTIVE_STATUSES: UpdateTaskStatus[] = ["downloading", "verifying", "extracting", "staging", "restarting"];
export function isActiveTaskStatus(status: UpdateTaskStatus | string): boolean {
return (ACTIVE_STATUSES as string[]).includes(status);
}
export function emptyUpdateState(): PersistedUpdateState {
return { schemaVersion: 1, task: null };
}
export function readUpdateState(filename: string): PersistedUpdateState {
try {
const parsed: unknown = JSON.parse(readFileSync(filename, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return emptyUpdateState();
const record = parsed as Record<string, unknown>;
if (record.schemaVersion !== 1) return emptyUpdateState();
return { schemaVersion: 1, task: parseTask(record.task) };
} catch {
return emptyUpdateState();
}
}
function parseTask(value: unknown): UpdateTaskView | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const task = value as Record<string, unknown>;
if (typeof task.id !== "string" || !task.id
|| typeof task.status !== "string"
|| typeof task.fromVersion !== "string"
|| typeof task.targetVersion !== "string"
|| typeof task.startedAt !== "string"
|| typeof task.updatedAt !== "string") return null;
return {
id: task.id,
status: task.status as UpdateTaskStatus,
fromVersion: task.fromVersion,
targetVersion: task.targetVersion,
startedAt: task.startedAt,
updatedAt: task.updatedAt,
finishedAt: typeof task.finishedAt === "string" ? task.finishedAt : null,
errorCode: typeof task.errorCode === "string" ? task.errorCode : null,
errorMessage: typeof task.errorMessage === "string" ? task.errorMessage : null,
rolledBack: task.rolledBack === true,
steps: Array.isArray(task.steps)
? task.steps.filter((step): step is UpdateTaskView["steps"][number] => Boolean(step)
&& typeof step === "object"
&& !Array.isArray(step)
&& typeof (step as Record<string, unknown>).name === "string"
&& typeof (step as Record<string, unknown>).status === "string"
&& typeof (step as Record<string, unknown>).at === "string")
.map((step) => ({
name: step.name,
status: step.status,
at: step.at,
...(typeof step.detail === "string" ? { detail: step.detail } : {}),
}))
: [],
};
}
export function writeUpdateState(filename: string, state: PersistedUpdateState): void {
mkdirSync(path.dirname(filename), { recursive: true });
const temporary = `${filename}.${process.pid}.tmp`;
writeFileSync(temporary, JSON.stringify(state, null, 2), { encoding: "utf8", mode: 0o600 });
renameSync(temporary, filename);
}
/**
* Reconcile a task that was active when the previous process stopped. If the
* running version already matches the target the update completed; otherwise
* it failed and is reported as interrupted.
*/
export function reconcileInterruptedState(state: PersistedUpdateState, currentVersion: string, now: string): boolean {
const task = state.task;
if (!task || !isActiveTaskStatus(task.status)) return false;
if (task.targetVersion === currentVersion) {
task.status = "succeeded";
task.finishedAt = now;
task.updatedAt = now;
return true;
}
task.status = "failed";
task.finishedAt = now;
task.updatedAt = now;
task.errorCode = "UPDATE_INTERRUPTED";
task.errorMessage = "The process stopped before the update completed. The previous version is still running.";
return true;
}
function processIsAlive(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
/**
* Linux exposes the process start time in /proc/<pid>/stat. It is used only
* as an extra guard against PID reuse: when it is unavailable (Windows,
* macOS, restricted /proc) liveness falls back to the pid check alone and
* never throws.
*/
function processStartMarker(pid: number): string | null {
try {
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
const close = stat.lastIndexOf(")");
if (close < 0) return null;
const fields = stat.slice(close + 2).trim().split(/\s+/);
// Field 3 is the state; starttime is field 22, i.e. index 19 here.
return fields[19] ?? null;
} catch {
return null;
}
}
function parseLockRecord(raw: string): UpdateLockRecord | null {
try {
const parsed: unknown = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
const record = parsed as Record<string, unknown>;
const pid = Number(record.pid);
if (!Number.isInteger(pid) || pid < 0 || typeof record.taskId !== "string" || !record.taskId) return null;
return {
pid,
taskId: record.taskId,
createdAt: typeof record.createdAt === "string" ? record.createdAt : "",
processStart: typeof record.processStart === "string" ? record.processStart : null,
};
} catch {
return null;
}
}
interface LockFile {
raw: string;
record: UpdateLockRecord | null;
}
/**
* Missing lock => null. A lock that exists but cannot be read or parsed is
* reported with `record: null`; callers must treat it as potentially held
* rather than deleting a lock another process may still own.
*/
function readLockFile(lockPath: string): LockFile | null {
try {
const raw = readFileSync(lockPath, "utf8");
return { raw, record: parseLockRecord(raw) };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
return { raw: "", record: null };
}
}
function lockOwnerIsAlive(record: UpdateLockRecord): boolean {
if (!processIsAlive(record.pid)) return false;
if (!record.processStart) return true;
const current = processStartMarker(record.pid);
// If the platform cannot report a start marker, keep the pid-only answer.
return current === null || current === record.processStart;
}
function lockPayload(taskId: string): string {
return JSON.stringify({
pid: process.pid,
taskId,
createdAt: new Date().toISOString(),
processStart: processStartMarker(process.pid),
} satisfies UpdateLockRecord);
}
function releaseLock(lockPath: string, payload: string, taskId: string): () => void {
return () => {
const file = readLockFile(lockPath);
// Never delete a lock that became unreadable or was replaced by another
// process; only remove the exact record this process wrote.
if (!file || !file.record || file.raw !== payload) return;
if (file.record.taskId !== taskId || file.record.pid !== process.pid) return;
try { unlinkSync(lockPath); } catch { /* Another process reclaimed it. */ }
};
}
/** Remove a lock only after proving the observed record is dead and unchanged. */
function reclaimDeadLock(lockPath: string, observed: LockFile): void {
const current = readLockFile(lockPath);
if (!current || current.raw !== observed.raw) return;
try { unlinkSync(lockPath); } catch { /* Another process reclaimed it. */ }
}
/**
* Cross-process mutex. Lock files written by a dead process are reclaimed so
* a crash cannot permanently block the maintenance page. A lock that cannot
* be parsed is treated as held: refusing an update is safer than deleting a
* live lock.
*/
export function acquireUpdateLock(lockPath: string, taskId: string): () => void {
mkdirSync(path.dirname(lockPath), { recursive: true });
const payload = lockPayload(taskId);
for (let attempt = 0; attempt < 4; attempt++) {
try {
writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
return releaseLock(lockPath, payload, taskId);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
const file = readLockFile(lockPath);
if (!file) continue;
if (!file.record) {
throw new UpdateLockedError("An unreadable update lock is present; refusing to start an update.");
}
if (file.record.pid === process.pid && file.record.taskId === taskId) {
return releaseLock(lockPath, file.raw, taskId);
}
if (lockOwnerIsAlive(file.record)) throw new UpdateLockedError();
reclaimDeadLock(lockPath, file);
}
}
throw new UpdateLockedError();
}
/**
* The restart runner inherits an update that its parent process started but
* cannot finish. It must own the lock while it swaps and health-checks the
* new code, otherwise a second instance starting in that window would see a
* dead parent pid and roll the healthy code back.
*
* Only the same task may be taken over. A live lock for another task is
* never stolen, and an unreadable lock is refused.
*/
export function takeOverUpdateLock(lockPath: string, taskId: string): () => void {
mkdirSync(path.dirname(lockPath), { recursive: true });
const payload = lockPayload(taskId);
for (let attempt = 0; attempt < 4; attempt++) {
const file = readLockFile(lockPath);
if (!file) {
try {
writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
return releaseLock(lockPath, payload, taskId);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
throw error;
}
}
if (!file.record) {
throw new UpdateLockedError("The update lock is unreadable; the restart runner will not take over.");
}
if (file.record.taskId !== taskId) {
throw new UpdateLockedError("A different update task holds the lock; the restart runner will not steal it.");
}
const temporary = `${lockPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
try {
writeFileSync(temporary, payload, { encoding: "utf8", mode: 0o600 });
renameSync(temporary, lockPath);
return releaseLock(lockPath, payload, taskId);
} catch (error) {
try { rmSync(temporary, { force: true }); } catch { /* Best effort. */ }
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
throw error;
}
}
throw new UpdateLockedError("The update lock could not be taken over.");
}
/**
* Remove a lock only when its owner is provably dead. Unreadable locks are
* left in place so a live owner is never deleted by mistake.
*/
export function clearStaleUpdateLock(lockPath: string): void {
const file = readLockFile(lockPath);
if (!file || !file.record) return;
if (lockOwnerIsAlive(file.record)) return;
reclaimDeadLock(lockPath, file);
}
/**
* True when a live process still owns the lock, optionally for a specific
* task. An unreadable lock is conservatively reported as held.
*/
export function updateLockIsHeld(lockPath: string, taskId?: string): boolean {
const file = readLockFile(lockPath);
if (!file) return false;
if (!file.record) return true;
if (!lockOwnerIsAlive(file.record)) return false;
return taskId === undefined || file.record.taskId === taskId;
}
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { compareVersions, isNewerVersion, isValidVersion, parseReleaseTag, parseStableVersion } from "./version.js";
test("stable versions require exactly three numeric segments", () => {
assert.deepEqual(parseStableVersion(" 01.002.0003 "), { major: 1, minor: 2, patch: 3, text: "1.2.3" });
for (const value of ["1.2", "1.2.3-beta", "v1.2.3", "1.2.3.4", "", null, 1.2]) {
assert.equal(parseStableVersion(value), null);
}
});
test("release tags accept only the v-prefixed stable shape", () => {
assert.equal(parseReleaseTag("v0.3.2")?.text, "0.3.2");
assert.equal(parseReleaseTag("0.3.2"), null);
assert.equal(parseReleaseTag("v0.3.2-rc.1"), null);
assert.equal(parseReleaseTag("vv0.3.2"), null);
});
test("version comparison and newer checks are numeric", () => {
assert.ok(compareVersions("0.10.0", "0.9.9") > 0);
assert.ok(compareVersions("1.0.0", "1.0.0") === 0);
assert.ok(compareVersions("1.0.0", "1.0.1") < 0);
assert.equal(isNewerVersion("0.3.3", "0.3.2"), true);
assert.equal(isNewerVersion("0.3.2", "0.3.2"), false);
assert.equal(isNewerVersion("not-a-version", "0.3.2"), false);
assert.equal(isValidVersion("2.0.0"), true);
assert.equal(isValidVersion("2.0"), false);
});
+38
View File
@@ -0,0 +1,38 @@
/** Stable semantic versions only. Pre-release/rolling channels are deliberate non-goals. */
export interface StableVersion {
major: number;
minor: number;
patch: number;
text: string;
}
const STABLE = /^(\d{1,6})\.(\d{1,6})\.(\d{1,6})$/;
export function parseStableVersion(value: unknown): StableVersion | null {
if (typeof value !== "string") return null;
const match = STABLE.exec(value.trim());
if (!match) return null;
const [, major, minor, patch] = match;
return { major: Number(major), minor: Number(minor), patch: Number(patch), text: `${Number(major)}.${Number(minor)}.${Number(patch)}` };
}
/** `v1.2.3` is the only accepted release tag shape. */
export function parseReleaseTag(value: unknown): StableVersion | null {
if (typeof value !== "string" || !value.startsWith("v")) return null;
return parseStableVersion(value.slice(1));
}
export function isValidVersion(value: unknown): value is string {
return parseStableVersion(value) !== null;
}
export function compareVersions(left: string, right: string): number {
const a = parseStableVersion(left);
const b = parseStableVersion(right);
if (!a || !b) return 0;
return a.major - b.major || a.minor - b.minor || a.patch - b.patch;
}
export function isNewerVersion(candidate: string, current: string): boolean {
return compareVersions(candidate, current) > 0;
}
+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.`);
+655 -25
View File
@@ -28,26 +28,152 @@
<!-- 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"
@keydown.escape="onRecoveryEscape"
@click="compactPinned = compact || compactPinned"
@focusout="onRecoveryFocusOut"
class="ws-host-recovery"
:class="{ 'ws-host-recovery-compact': compact }"
:data-ws-float="capsuleSlotConfig && slotMode === 'slotted' ? undefined : floatPosition"
:tabindex="compact || compactPinned ? 0 : undefined"
data-ws-host-recovery
role="region"
:aria-label="copy.recovery"
>
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
<button
v-if="capsuleActions.includes('built-in')"
type="button"
class="ws-host-recovery-action"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
v-if="capsuleActions.includes('library') && pluginLibraryAvailable"
type="button"
v-if="pluginLibraryAvailable"
class="ws-host-recovery-action"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
@@ -57,24 +183,42 @@
</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,
hostChromeActiveSkinId,
isHostPartHidden,
isHostPartVisuallyReachable,
isRecoveryShortcut,
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
setInlineLibraryEntryVisible,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
syncRecoveryPopover,
type HostOwnedLayer,
} from "../services/host-owned-layer.js";
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
import {
bindFloatingAvoidance,
type FloatingAvoidance,
type FloatingPosition,
} from "../services/host-floating-placement.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);
@@ -92,36 +236,122 @@ const RECOVERY_LAYER_CSS = `
gap: 4px;
max-width: calc(100vw - 24px);
padding: 4px 5px 4px 9px;
border: 1px solid #9db6b2;
border-radius: 999px;
background: color-mix(in srgb, #ffffff 92%, transparent);
color: #31524f;
border: 1px solid var(--ws-control-border, #9db6b2);
border-radius: var(--ws-control-radius, 999px);
background: var(--ws-control-background, color-mix(in srgb, #ffffff 92%, transparent));
color: var(--ws-control-foreground, #31524f);
font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
font-size: var(--ws-control-font-size, 11px);
box-shadow: 0 6px 18px #0f2a2626;
pointer-events: auto;
}
.ws-host-recovery:popover-open { display: flex; }
.ws-host-recovery-mark { font-size: 12px; line-height: 1; }
/* Runtime collision avoidance (host-floating-placement.ts): when the default
corner would cover a skin control, the floating capsule moves. A docked
(slotted) capsule carries no data-ws-float and uses inline placement. */
.ws-host-recovery[data-ws-float$="right"] { left: auto; right: max(12px, env(safe-area-inset-right)); }
.ws-host-recovery[data-ws-float^="top"] { bottom: auto; top: max(12px, env(safe-area-inset-top)); }
.ws-host-recovery[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
.ws-host-recovery[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
.ws-host-recovery-mark {
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 12px;
line-height: 1;
}
.ws-host-recovery button {
display: inline-flex;
align-items: center;
min-height: 28px;
min-height: var(--ws-control-hit, 28px);
padding: 4px 9px;
border: 1px solid #9db6b2;
border-radius: 999px;
background: #fff;
color: #31524f;
border: 1px solid var(--ws-control-border, #9db6b2);
border-radius: var(--ws-control-radius, 999px);
background: var(--ws-control-background, #fff);
color: var(--ws-control-foreground, #31524f);
font: inherit;
cursor: pointer;
white-space: nowrap;
}
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
border-color: #b45309;
border-color: var(--ws-control-builtin-border, #b45309);
background: #fff7ed;
color: #7c2d12;
}
.ws-host-recovery button:hover { filter: brightness(.96); }
.ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { .ws-host-recovery button { transition: none; } }
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) { gap: 0; padding: 4px; }
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-action { display: none; }
.ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-mark {
min-width: var(--ws-control-hit, 28px);
min-height: var(--ws-control-hit, 28px);
}
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
/* 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, .ws-host-toolbar-action { transition: none !important; }
}
`;
const layer: HostOwnedLayer | null = createHostOwnedLayer("recovery", RECOVERY_LAYER_CSS);
@@ -145,10 +375,311 @@ 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);
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 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,
control: () => recoveryPopover.value,
part: "host.recovery",
defaults: RECOVERY_CONTROL_DEFAULTS,
source: () => findSkinRoot(hostChromeActiveSkinId.value),
active: () => !capsuleBinding,
}) : null;
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;
// Keep the full capsule visible for a moment after it first docks into a
// newly activated skin, so the entry stays discoverable before it folds into
// the skin's layout. The skin id is known from localStorage before the skin
// (and its anchor) has loaded, so the 5 s window starts on the first
// floating -> slotted transition for that skin, not on the id change.
let compactHoldStarted = false;
watch(hostChromeActiveSkinId, () => {
compactHold.value = true;
compactHoldStarted = false;
if (compactHoldTimer) clearTimeout(compactHoldTimer);
compactHoldTimer = undefined;
}, { immediate: true });
watch(slotMode, (mode) => {
if (mode !== "slotted" || compactHoldStarted) return;
compactHoldStarted = true;
compactHoldTimer = setTimeout(() => { compactHold.value = false; }, 5000);
});
/** Set by the shortcut; cleared once focus leaves the capsule. */
const shortcutExpanded = ref(false);
/** A tap/click on the compact mark keeps it expanded (no hover on touch). */
const compactPinned = ref(false);
/**
* Floating (not docked) capsule: corner chosen at runtime so it does not cover
* skin controls, and folded to its mark when every corner collides.
*/
const floatPosition = ref<FloatingPosition>("bottom-left");
const floatCompact = ref(false);
let floatingAvoidance: FloatingAvoidance | undefined;
let floatingElement: HTMLElement | null = null;
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
const compact = computed(() => {
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;
shortcutExpanded.value = false;
compactPinned.value = false;
}
/** Dismiss shortcut expansion and unpin on pointer down outside the host layer. */
function onDocumentPointerDown(event: PointerEvent) {
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;
}
let capsuleBinding: HostSlotBinding | undefined;
let toolbarBindings: HostSlotBinding[] = [];
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
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,
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() {
const control = recoveryPopover.value;
// Idempotent: called on mount and whenever the popover element appears.
if (floatingAvoidance && floatingElement === control) return;
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
floatingElement = null;
if (!control || !layer) return;
const host = layer.host;
floatingElement = control;
floatingAvoidance = bindFloatingAvoidance({
element: control,
isSelf: node => node === host || host.contains(node),
// Same numbers as RECOVERY_LAYER_CSS, including env(safe-area-inset-*).
margins: insets => ({
top: Math.max(12, insets.top),
right: Math.max(12, insets.right),
bottom: 38 + insets.bottom,
left: Math.max(12, insets.left),
}),
insetsParent: layer.shadow,
defaultPosition: "bottom-left",
apply: next => { floatPosition.value = next; },
compactSize: () => {
const hit = Number.parseFloat(getComputedStyle(control).getPropertyValue("--ws-control-hit")) || 28;
return { width: hit + 10, height: hit + 10 };
},
onCompactChange: next => { floatCompact.value = next; },
// 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"
|| shortcutExpanded.value
|| compactPinned.value
|| (canHover() && control.matches(":hover"))
|| Boolean(layer.shadow.activeElement),
});
}
function useBuiltInSkin() {
@@ -162,14 +693,22 @@ function openLibrary() {
}
function onKeydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.repeat || !thirdPartyAllowed.value) return;
if (event.repeat || !thirdPartyAllowed.value) return;
// The recovery chord must survive a capture-phase preventDefault() from a
// skin or plugin, so it is handled before anything else.
if (isRecoveryShortcut(event)) {
event.preventDefault();
shortcutOpen.value = true;
void nextTick(() => recoveryPopover.value?.querySelector("button")?.focus());
return;
shortcutExpanded.value = true;
void nextTick(() => {
// The shortcut always brings back the complete capsule, even while a
// toolbar anchor is healthy.
syncPopover();
syncToolbarPopovers();
revalidateBindings();
recoveryPopover.value?.querySelector("button")?.focus();
});
}
if (event.key === "Escape" && shortcutOpen.value) shortcutOpen.value = false;
}
let reachabilityTimer: ReturnType<typeof setInterval> | undefined;
@@ -177,20 +716,111 @@ function refreshLauncherReachability() {
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
}
watch([recoveryVisible, recoveryPopover], () => { void nextTick(syncPopover); }, { 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,
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(() => {
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();
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown);
void nextTick(syncPopover);
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();
syncSlotBindings();
bindFloating();
});
});
onBeforeUnmount(() => {
if (reachabilityTimer) clearInterval(reachabilityTimer);
if (compactHoldTimer) clearTimeout(compactHoldTimer);
pageObserver?.disconnect();
pageObserver = undefined;
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
setInlineLibraryEntryVisible(false);
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
floatingElement = null;
recoveryTheme?.dispose();
window.removeEventListener("resize", refreshLauncherReachability);
window.removeEventListener("keydown", onKeydown);
window.removeEventListener("keydown", onKeydown, true);
window.removeEventListener("pointerdown", onDocumentPointerDown, true);
layer?.dispose();
});
</script>
+22 -4
View File
@@ -25,13 +25,19 @@ import type { SiteLanguage } from '../../../src/site-copy.js';
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
import { createHostOwnedLayer, type HostOwnedLayer } from '../services/host-owned-layer.js';
import { hostChromeActiveSkinId } from '../services/host-chrome.js';
import {
PERMISSION_CONTROL_DEFAULTS,
bindHostControlTheme,
findSkinRoot,
} from '../services/host-control-tokens.js';
const AUTHORIZATION_LAYER_CSS = `
:host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:inherit;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid var(--ws-control-border,#dbe3f1);border-radius:var(--ws-control-radius,20px);background:var(--ws-control-background,#fff);color:var(--ws-control-foreground,#25324b);font-family:var(--ws-control-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--ws-control-font-size,14px);line-height:1.75;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:var(--ws-control-foreground,#526079)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));border:1px solid var(--ws-control-border,#dce3f3);border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:var(--ws-control-hit,42px);padding:9px 16px;border:1px solid var(--ws-control-border,#d9e1ef);border-radius:var(--ws-control-radius,10px);background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));color:var(--ws-control-foreground,#43516d);font:600 var(--ws-control-font-size,14px)/1.5 var(--ws-control-font,system-ui);cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:var(--ws-control-accent,#5265df);color:var(--ws-control-on-accent,#fff);border-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid var(--ws-control-accent,#5265df);outline-offset:3px}
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
`;
@@ -39,9 +45,21 @@ const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHO
const props = defineProps<{ language: SiteLanguage }>();
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
const copy = computed(() => instanceAuthorizationCopy[props.language]);
/** The authorization dialog is host-owned; only sanitized tokens can theme it. */
const theme = layer ? bindHostControlTheme({
layer,
control: () => dialog.value,
part: 'host.permission',
defaults: PERMISSION_CONTROL_DEFAULTS,
source: () => findSkinRoot(hostChromeActiveSkinId.value),
}) : null;
watch([dialog, hostChromeActiveSkinId], () => { theme?.apply(); }, { flush: 'post', immediate: true });
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
watch([dialog, authorizationRequested, authorizationDecision], () => {
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
theme?.apply();
firstVisit.value = authorizationDecision.value === null;
checked.value = authorizationDecision.value === true;
dialog.value.showModal();
@@ -50,5 +68,5 @@ function finish() { authorizationRequested.value = false; dialog.value?.close();
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
function decline() { setInstanceAuthorization(false); finish(); }
function cancel() { if (firstVisit.value) decline(); else finish(); }
onBeforeUnmount(() => { dialog.value?.close(); layer?.dispose(); });
onBeforeUnmount(() => { dialog.value?.close(); theme?.dispose(); layer?.dispose(); });
</script>
+30 -3
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-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">
<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') && !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,14 +68,22 @@ 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']> }>();
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
const ui = computed(() => pluginWindowTranslations[props.language]);
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
const toolbar = ref<HTMLElement | null>(null);
// 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');
let fallbackAvoidance: FloatingAvoidance | undefined;
const drawerOpen = ref(false);
const drawer = ref<HTMLElement | null>(null);
const drawerSearch = ref<HTMLInputElement | null>(null);
@@ -227,6 +235,25 @@ watch(pluginLibraryRequests, () => {
if (props.presentation !== 'dialog' && isHostPartVisuallyReachable('host.plugins.launcher')) openDrawer();
else openLibraryDialog();
});
watch([toolbar, () => props.toolbarTarget], ([element, target]) => {
fallbackAvoidance?.dispose();
fallbackAvoidance = undefined;
fallbackPosition.value = 'bottom-right';
if (!element || target) return;
fallbackAvoidance = bindFloatingAvoidance({
element,
isSelf: node => element.contains(node),
// Same numbers as .ws-plugin-toolbar-fallback in plugin-overlay.css.
margins: insets => ({ top: 16 + insets.top, right: 16, bottom: 16 + insets.bottom, left: 16 }),
defaultPosition: 'bottom-right',
apply: next => { fallbackPosition.value = next; },
// Sticky :hover after a tap on touch screens must not pause avoidance.
paused: () => drawerOpen.value
|| (matchMedia('(hover: hover)').matches && element.matches(':hover'))
|| element.contains(document.activeElement),
});
}, { flush: 'post' });
onBeforeUnmount(() => { fallbackAvoidance?.dispose(); fallbackAvoidance = undefined; });
onMounted(() => {
document.addEventListener('pointerdown', closeDrawerOutside, true);
window.addEventListener('resize', fitDrawer);
+52 -14
View File
@@ -1,6 +1,6 @@
<template>
<Teleport to="body">
<section v-if="error" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
<Teleport v-if="layer" :to="layer.container">
<section v-if="error" ref="banner" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
<p>{{ labels.skinLoadError(error.skinId) }}</p>
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
</section>
@@ -8,9 +8,16 @@
</template>
<script setup lang="ts">
import { computed } from "vue";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import type { Language } from "../i18n/web-client.js";
import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js";
import { createHostOwnedLayer, type HostOwnedLayer } from "../services/host-owned-layer.js";
import { hostChromeActiveSkinId } from "../services/host-chrome.js";
import {
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
bindHostControlTheme,
findSkinRoot,
} from "../services/host-control-tokens.js";
defineEmits<{ "use-built-in": [] }>();
@@ -19,9 +26,11 @@ const props = defineProps<{
language: Language;
}>();
const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.language)]);
</script>
<style scoped>
// The banner is trusted host UI: render it in a closed shadow root so compiled
// skin CSS cannot restyle it (or hide it) from the document. The layer's fixed
// wrapper is pointer-transparent, so the banner re-enables pointer events.
const SKIN_LOAD_LAYER_CSS = `
.skin-load-recovery {
position: fixed;
z-index: 2147482500;
@@ -32,21 +41,50 @@ const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.l
justify-content: center;
gap: 12px;
width: min(720px, calc(100vw - 24px));
box-sizing: border-box;
padding: 10px 12px;
transform: translateX(-50%);
border: 1px solid #f59e0b;
border-radius: 12px;
color: #78350f;
background: #fffbeb;
border: 1px solid var(--ws-control-border, #f59e0b);
border-radius: var(--ws-control-radius, 12px);
color: var(--ws-control-foreground, #78350f);
background: var(--ws-control-background, #fffbeb);
box-shadow: 0 8px 28px #0f172a33;
font: 14px/1.45 ui-sans-serif, system-ui, sans-serif;
font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
font-size: var(--ws-control-font-size, 14px);
line-height: 1.45;
pointer-events: auto;
}
.skin-load-recovery p { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
.skin-load-recovery button { flex: 0 0 auto; min-height: 44px; max-width: 100%; padding: 7px 10px; border: 1px solid #b45309; border-radius: 8px; color: #78350f; background: #fff; cursor: pointer; white-space: normal; }
.skin-load-recovery button:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; }
.skin-load-recovery button { flex: 0 0 auto; min-height: var(--ws-control-hit, 44px); max-width: 100%; padding: 7px 10px; border: 1px solid var(--ws-control-accent, #b45309); border-radius: var(--ws-control-radius, 8px); color: var(--ws-control-foreground, #78350f); background: var(--ws-control-background, #fff); font: inherit; cursor: pointer; white-space: normal; }
.skin-load-recovery button:focus-visible { outline: 3px solid var(--ws-control-accent, #1d4ed8); outline-offset: 2px; }
@media (max-width: 520px) {
.skin-load-recovery { align-items: stretch; flex-direction: column; gap: 7px; }
.skin-load-recovery button { width: 100%; }
}
</style>
`;
const layer: HostOwnedLayer | null = createHostOwnedLayer("skin-load", SKIN_LOAD_LAYER_CSS);
const banner = ref<HTMLElement | null>(null);
/**
* Tokens come from the active skin root, never from the document. The banner
* appears when a skin failed to load, so a missing root simply keeps the
* built-in amber surface; an unreadable palette reverts the same way.
*/
const theme = layer ? bindHostControlTheme({
layer,
control: () => banner.value,
part: "app.skin-load-recovery",
defaults: SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
source: () => findSkinRoot(hostChromeActiveSkinId.value),
}) : null;
watch([() => props.error, banner, hostChromeActiveSkinId], () => {
void nextTick(() => theme?.apply());
}, { flush: "post", immediate: true });
onBeforeUnmount(() => {
theme?.dispose();
layer?.dispose();
});
</script>
+89 -4
View File
@@ -273,7 +273,51 @@
>{{ tr("exportBackup") }}</button
></article
>
<div class="alert info system-notice"><Icon name="info" :size="16"/><span>{{ tr('updateNotice', {version: operations.diagnostics.version || '—'}) }}</span></div>
<article class="operation-card update-card" data-admin-update="version">
<header>
<div><h3>{{ tr('updateTitle') }}</h3><p>{{ tr('updateLead') }}</p></div>
<span :class="['state-pill', canApplyUpdates ? 'active' : '']">{{ canApplyUpdates ? tr('updateCanApply') : tr('updateCannotApply') }}</span>
</header>
<dl class="diagnostic-list">
<div><dt>{{ tr('updateCurrentVersion') }}</dt><dd>{{ operations.update.currentVersion || operations.diagnostics.version || '—' }}</dd></div>
<div><dt>{{ tr('updateDeploymentMode') }}</dt><dd>{{ deploymentLabel }}</dd></div>
<div><dt>{{ tr('updateArchitecture') }}</dt><dd>{{ operations.update.deployment.platform || '—' }} / {{ operations.update.deployment.architecture || '—' }}</dd></div>
</dl>
<div v-if="operations.update.task" class="update-task" data-admin-update-task>
<strong>{{ tr('updateTaskTitle') }}: {{ updateTaskStatusLabel }}</strong>
<small v-if="updateTaskErrorText">{{ updateTaskErrorText }}</small>
<small v-else-if="operations.update.task.status === 'succeeded'">{{ tr('updateRestartHint') }}</small>
<small v-if="operations.update.task.rolledBack">{{ tr('updateRolledBack') }}</small>
<small v-if="operations.update.task.finishedAt">{{ formatDate(operations.update.task.finishedAt) }}</small>
</div>
<div v-if="!canApplyUpdates" class="alert info system-notice">
<Icon name="info" :size="16"/><span>{{ blockedUpdateText }}</span>
</div>
<div>
<p v-if="canApplyUpdates" class="field-help">{{ tr('updateBackupHint') }}</p>
<div class="update-actions">
<button class="secondary-button" type="button" data-admin-update="check" :disabled="updateChecking" @click="checkForUpdates">
<span v-if="updateChecking" class="spinner small"></span><Icon v-else name="refresh" :size="17"/>
{{ updateChecking ? tr('updateChecking') : tr('updateCheckAction') }}
</button>
</div>
<div v-if="availableUpdates.length" class="update-release-list">
<strong v-if="canApplyUpdates">{{ tr('updateSelectRelease') }}</strong>
<p v-if="canApplyUpdates" class="field-help">{{ tr('updateChecksumNotice') }}</p>
<label v-for="release in availableUpdates" :key="release.version" class="update-release-row">
<input v-if="canApplyUpdates" v-model="selectedVersion" type="radio" :value="release.version" :disabled="!release.canApply || updateApplying" />
<span><strong>v{{ release.version }}</strong> <small>{{ formatDate(release.publishedAt) }}</small></span>
<a v-if="release.releaseUrl" :href="release.releaseUrl" target="_blank" rel="noreferrer">{{ tr('updateReleaseNotes') }}</a>
<small v-if="!release.canApply" class="muted-label">{{ releaseBlockedText(release) }}</small>
</label>
<button v-if="canApplyUpdates" class="primary-button" type="button" data-admin-update="apply" :disabled="!selectedRelease || updateApplying" @click="applySelectedUpdate">
<span v-if="updateApplying" class="spinner small"></span>
{{ updateApplying ? tr('updateApplying') : tr('updateApplyAction') }}
</button>
</div>
<p v-else-if="updateChecked" class="field-help">{{ tr('updateUpToDate') }}</p>
</div>
</article>
</div>
</section>
</template>
@@ -288,13 +332,54 @@ import type { AdminConnectionRecord } from "../../../../src/shared/admin-respons
const props = defineProps<{
model: ReturnType<typeof useAdminOperations>;
initialSection?: string;
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText">;
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText" | "errorText">;
}>();
// Request ownership, cancellation and drafts remain in the page's controller.
const { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup } = props.model;
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText } = props.i18n;
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup,
updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion, checkForUpdates, applyUpdate } = props.model;
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText, errorText } = props.i18n;
type OperationsSection = 'sessions' | 'invites' | 'logs' | 'audit' | 'maintenance';
const canApplyUpdates = computed(() => operations.update.deployment.applyAllowed);
const deploymentLabel = computed(() => {
const mode = operations.update.deployment.mode;
return mode === 'docker' ? tr('updateModeDocker') : mode === 'release-package' ? tr('updateModeReleasePackage') : tr('updateModeSource');
});
function blockedReasonText(code: string | null) {
switch (code) {
case 'DEPLOYMENT_DOCKER': return tr('updateBlockedDocker');
case 'DEPLOYMENT_SOURCE': return tr('updateBlockedSource');
case 'DEPLOYMENT_SUPERVISED': return tr('updateBlockedSupervised');
case 'PLATFORM_UNSUPPORTED': return tr('updateBlockedPlatform');
case 'ARCH_UNSUPPORTED': return tr('updateBlockedArch');
case 'WINDOWS_APPLY_UNVERIFIED': return tr('updateBlockedWindows');
case 'LINUX_ARM64_APPLY_UNVERIFIED': return tr('updateBlockedArm64');
case 'UPDATE_ASSET_UNAVAILABLE': return tr('updateAssetMissing');
case 'UPDATE_CHECKSUM_MISSING': return tr('updateChecksumMissing');
default: return tr('updateBlockedUnavailable');
}
}
const blockedUpdateText = computed(() => blockedReasonText(operations.update.deployment.reasonCode));
const releaseBlockedText = (release: { blockedReason: string | null }) => blockedReasonText(release.blockedReason);
function updateStatusText(status: string | undefined) {
switch (status) {
case 'downloading': return tr('updateStatusDownloading');
case 'verifying': return tr('updateStatusVerifying');
case 'extracting': return tr('updateStatusExtracting');
case 'staging': return tr('updateStatusStaging');
case 'restarting': return tr('updateStatusRestarting');
case 'succeeded': return tr('updateStatusSucceeded');
case 'failed': return tr('updateStatusFailed');
default: return '';
}
}
const updateTaskStatusLabel = computed(() => updateStatusText(operations.update.task?.status));
const updateTaskErrorText = computed(() => operations.update.task?.errorCode ? errorText(operations.update.task.errorCode) : '');
const selectedRelease = computed(() => availableUpdates.value.find(release => release.version === selectedVersion.value && release.canApply) ?? null);
function applySelectedUpdate() {
const release = selectedRelease.value;
if (release) void applyUpdate(release);
}
const normalizeSection = (value?: string): OperationsSection => value === 'invites' || value === 'logs' || value === 'audit' || value === 'maintenance' ? value : 'sessions';
const activeSection = ref<OperationsSection>(normalizeSection(props.initialSection));
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
@@ -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"); }
+16
View File
@@ -27,6 +27,7 @@ const eventLabels: Record<string, AdminTranslationKey> = {
ADMIN_SKIN_INSTALLED: "skinInstalledEvent", ADMIN_SKIN_REMOVED: "skinRemovedEvent",
ADMIN_SKIN_ENABLED: "skinEnabledEvent", ADMIN_SKIN_DISABLED: "skinDisabledEvent",
INVITE_CREATED: "inviteCreatedEvent", INVITE_REVOKED: "inviteRevokedEvent", INVITE_CONSUMED: "inviteConsumedEvent",
ADMIN_UPDATE_STARTED: "updateStartedEvent",
TS_ADMIN_SETTINGS_UPDATED: "tsAdminSaved",
TS_ADMIN_OVERVIEW_READ: "tsAdminReadEvent",
TS_ADMIN_OVERVIEW_FAILED: "tsAdminReadFailedEvent",
@@ -36,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",
@@ -51,6 +55,18 @@ const errorLabels: Record<string, AdminTranslationKey> = {
TS_ADMIN_CLIENT_CHANGED: "tsAdminClientChanged", TS_ADMIN_CONFIG_CHANGED: "tsAdminConfigChanged", TS_ADMIN_PARTIAL_SUCCESS: "tsAdminPartialError",
TS_ADMIN_RATE_LIMITED: "tsAdminRateError", TS_ADMIN_TLS_FAILED: "tsAdminTlsError",
TS_ADMIN_READ_FAILED: "tsAdminReadError", TS_ADMIN_TIMEOUT: "tsAdminTimeoutError",
UPDATE_IN_PROGRESS: "updateErrorInProgress", UPDATE_CHECKSUM_MISSING: "updateErrorChecksum",
UPDATE_CHECKSUM_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_UNSUPPORTED: "updateErrorChecksum",
UPDATE_ARCHIVE_UNSAFE: "updateErrorArchive", UPDATE_ARCHIVE_INVALID: "updateErrorArchive", UPDATE_ARCHIVE_LIMIT: "updateErrorArchive", UPDATE_ARCHIVE_UNSUPPORTED: "updateErrorArchive",
UPDATE_PACKAGE_INVALID: "updateErrorPackage", UPDATE_DOWNLOAD_FAILED: "updateErrorDownload", UPDATE_DOWNLOAD_TOO_LARGE: "updateErrorDownload",
UPDATE_FAILED: "updateErrorApply", UPDATE_ROLLBACK_FAILED: "updateErrorRollbackFailed", UPDATE_INTERRUPTED: "updateErrorInterrupted",
UPDATE_SWAP_FAILED: "updateErrorSwap", UPDATE_LOCK_FAILED: "updateErrorLockFailed",
UPDATE_UNAVAILABLE: "updateErrorUnavailable", UPDATE_RESTART_UNAVAILABLE: "updateErrorUnavailable",
UPDATE_HEALTH_CHECK_FAILED: "updateErrorApply", UPDATE_ROLLBACK_HEALTH_FAILED: "updateErrorGeneric",
UPDATE_RESTART_FAILED: "updateErrorGeneric", UPDATE_RESTART_TIMEOUT: "updateErrorGeneric", UPDATE_PLAN_INVALID: "updateErrorGeneric",
UPDATE_NOT_SUPPORTED: "updateErrorGeneric", UPDATE_RELEASE_UNAVAILABLE: "updateErrorGeneric", UPDATE_ASSET_UNAVAILABLE: "updateErrorGeneric",
UPDATE_CONFIRMATION_REQUIRED: "updateErrorGeneric", UPDATE_VERSION_INVALID: "updateErrorGeneric", UPDATE_VERSION_NOT_NEWER: "updateErrorGeneric",
UPDATE_VERSION_NOT_FOUND: "updateErrorGeneric", UPDATE_RUNNER_MISSING: "updateErrorGeneric", UPDATE_RUNNER_FAILED: "updateErrorGeneric",
};
const connectionErrors: Record<string, AdminTranslationKey> = {
PASSWORD_REQUIRED: "serverPasswordRequiredError", SERVER_PASSWORD_REQUIRED: "serverPasswordRequiredError",
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more