Compare commits

..
1 Commits
Author SHA1 Message Date
illusia 34cee80302 feat: experiment with native lock-screen voice calls 2026-11-24 08:11:45 +08:00
60 changed files with 636 additions and 6070 deletions

No files matched your search

+8 -36
View File
@@ -9,7 +9,7 @@ on:
version:
description: Release version without the v prefix
required: true
default: 0.3.3
default: 0.3.2
type: string
permissions:
@@ -182,9 +182,12 @@ 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"
# 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"
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
chmod 0755 "$package_root/start-webspeak.sh"
smoke_root="$RUNNER_TEMP/${package_name}-smoke"
@@ -214,38 +217,7 @@ jobs:
grep -q '"status":"ok"' <<<"$health"
grep -q "\"version\":\"$release_version\"" <<<"$health"
)
# 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
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
- uses: actions/upload-artifact@v4
with:
name: linux-${{ matrix.arch }}
+5 -3
View File
@@ -19,7 +19,9 @@
</p>
</div>
当前版本 / 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)
当前版本 / Current version: **[v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
dev 实验功能 / dev experiment: [锁屏通话 / Lock-screen calls](./docs/EXPERIMENTAL_BACKGROUND_CALLS.md)(默认关闭,尚未通过真机锁屏验收 / off by default; physical-device validation pending)。
## 关于 WebSpeak · Overview
@@ -83,9 +85,9 @@ docker compose up -d
2. 配置 TeamSpeak 目标和访问模式;公网使用 HTTPS。Set the TeamSpeak target and access mode; use HTTPS for public access.
3. 启用 WebRTC 时放行配置的 UDP 范围,默认 `40000–40099`。Allow the configured UDP range when enabling WebRTC.
数据保存在 `webspeak-data` volume,升级时保留它。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)。
数据保存在 `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)。
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.
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.
<a id="documentation"></a>
+43
View File
@@ -0,0 +1,43 @@
# 锁屏通话实验 / Experimental lock-screen calls
此功能目前只用于 dev 分支实验,默认关闭。它改善浏览器的音频路径,不能保证浏览器或操作系统允许锁屏后一直录音、联网或播放。尚未完成 Android/iOS 真机锁屏验收。
## 使用
在音频配置中开启“锁屏通话(实验性)”,然后断开并重新进入语音房间。设置只在下次连接生效,通话中修改不会突然更换麦克风路径。需要网关及浏览器支持 WebRTC。没有 WebRTC 或协商失败时,回退到原有兼容传输,音频配置中的原生模式提示会消失。
原生模式直接发送系统麦克风音轨,并用浏览器原生 `<audio srcObject>` 接收。浏览器的回声消除、标准降噪仍可使用;RNNoise 强降噪、软件输入增益、客户端音量计、语音阈值和伴奏不参与这条路径。非零输入增益不会缩放声音,0% 仍禁止发送。此模式持续发送未静音的麦克风,请在不需要说话时静音。静音同时控制音轨与网关的麦克风状态。关闭实验选项并重新连接可恢复普通处理。
支持的浏览器会显示系统媒体控制。Pause 同时静音麦克风及接收声音;Play 只恢复接收,不解除麦克风静音。麦克风切换需要明确操作,Stop/Hang up 会结束连接并释放采集。在支持 Audio Session API 的平台上声明 `play-and-record`,离开时恢复之前的类型。系统暂停或结束音轨时,音频配置会显示中断提示。
## 实现与边界
- 普通模式保留现有 Web Audio、WebRTC 与 PCM 回退。原生模式不创建麦克风的 AudioContext、AudioWorklet、分析器或混音节点。
- 远端原生音频的 `play()` 不再等待采集 AudioContext 的 `resume()`;未完成的恢复请求不会连带阻塞收听。
- 返回前台和系统 Play 只重试当前会话的播放。它们不会重新申请麦克风、取消静音或重新建立已结束的通话。
- Media Session 是系统控制接口,不是后台保活权限。PWA、Service Worker、屏幕常亮都不能绕过系统限制;不播放静音文件或伪造音乐来保活。
- WebSocket 兼容模式仍依赖 JavaScript 解码与 Web Audio,不作锁屏持续通话保证。真实语音需要持续网络连接,不能像音乐文件那样提前缓冲。
- Android APK 目前仍为 WebView 与嵌入式网关。这次未添加原生前台音频服务,也未完成 APK 后台双向语音验收。
## 验证
自动化测试覆盖原始音轨发送、静音、权限请求取消、WebRTC 失败/缺失后的回退、系统 API 缺失/部分支持、旧系统动作隔离、采集恢复不阻塞播放,以及前台恢复不自动开麦。
2026-11-24 本地验证:`npm run verify` 的 1023 项测试全部通过,前后端构建成功。Windows Edge 使用模拟麦克风、两个真实浏览器 RTCPeerConnection 做回环,确认原生轨道收发 RTP、播放不等待采集恢复、静音切换及资源释放;1440px 与 390px 视口检查了全部五种语言的设置界面。该回环未连接 TeamSpeak,移动视口也不是手机系统锁屏测试。
真机验收应连接真实 TeamSpeak 房间,用第二个独立客户端双向监听,并分别记录:
1. Android Chrome、iPhone Safari、已安装 PWA 和 APK 的版本、系统版本、网络与省电设置。
2. 普通模式与实验模式下,前台、切应用、锁屏各 1/5/15 分钟的收听和发送;每次恢复说话前后都检查第二端实际听感及媒体收发计数。
3. 开麦/静音/输入音量 0%、系统 Play/Pause/麦克风控制、蓝牙切换、电话打断、网络切换和网关重连。
4. 断开或撤销权限后系统录音指示消失;旧权限请求或系统按钮不能重新启动采集。关闭实验并重连后强降噪、伴奏和普通音量控制恢复。
桌面模拟移动视口、无头浏览器和单元测试不代表通过真机锁屏验收。
## References
- HollyMusic [`useAudioPlayer.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/hooks/useAudioPlayer.ts) and [`audio-analysis.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/lib/client/audio-analysis.ts): native playback separated from optional Web Audio processing. This implementation uses the same architectural idea; no HollyMusic source was copied.
- [Media Session API](https://web.dev/articles/media-session) and [Audio Session draft](https://www.w3.org/TR/audio-session/).
- [Android foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types).
The experiment is off by default and applies on the next connection. It uses native WebRTC microphone tracks and native remote playback, while keeping mute, hangup and compatibility fallback. Optional Web Audio processing and accompaniment are unavailable in the native route. OS playback controls never unmute the microphone implicitly. Browser/OS restrictions still apply; physical-device background calling and native Android foreground audio services remain unverified/unimplemented respectively.
+1 -15
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.3](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Konsolen-Updates, Wiederherstellung und bessere Skin-Kompatibilität.
Stabile Version: [Hinweise zu v0.3.2](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin-Wiederherstellung, App-Bibliothek und Plugin-Formulare.
@@ -341,20 +341,6 @@ 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).
+3 -23
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.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.
Stable release: [v0.3.2 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin recovery, app library layouts, and plugin settings forms.
@@ -103,7 +103,7 @@ docker compose ps
docker compose logs -f webspeak
```
Upgrade 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:
Upgrade:
```bash
git pull --ff-only
@@ -111,16 +111,12 @@ docker compose pull
docker compose up -d
```
Do not run `docker compose down -v`; it removes the `webspeak-data` volume, including the database and administrator settings.
Do not run `docker compose down -v`; it removes 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
@@ -138,8 +134,6 @@ 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`.
@@ -347,20 +341,6 @@ 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).
+1 -15
View File
@@ -13,7 +13,7 @@
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
安定版:[v0.3.3 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · コンソール更新、復元処理、スキン互換性の改善。
安定版:[v0.3.2 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · スキンの復元、アプリライブラリの配置、プラグイン設定フォーム。
@@ -276,20 +276,6 @@ 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)に感謝します。
+1 -15
View File
@@ -13,7 +13,7 @@
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
Стабильный выпуск: [изменения v0.3.3](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Обновление из консоли, восстановление и улучшенная совместимость скинов.
Стабильный выпуск: [изменения v0.3.2](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Восстановление темы, библиотека приложений и формы настройки плагинов.
@@ -276,20 +276,6 @@ 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).
+5 -25
View File
@@ -13,7 +13,7 @@
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
稳定版:[v0.3.3 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 控制台一键更新、升级恢复与皮肤兼容性改进。
稳定版:[v0.3.2 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 皮肤恢复入口、应用库布局和插件配置表单。
@@ -120,7 +120,7 @@ docker compose ps
docker compose logs -f webspeak
```
升级在宿主机执行。管理控制台在 Docker 部署中只能检查新版本,不能从容器内部替换镜像:
升级:
```bash
git pull --ff-only
@@ -128,16 +128,12 @@ docker compose pull
docker compose up -d
```
不要执行 `docker compose down -v`,否则会删除 `webspeak-data` volume,包括数据库和管理员设置。
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
### 发布包
从 [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 真机语音仍需验收。
### 源码运行
@@ -155,8 +151,6 @@ npm start
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
源码运行时,管理控制台可以检查新的正式版本,但目录中没有捆绑的 Node.js 运行时,因此不能一键应用更新。请查看发行说明后拉取源码并重新构建;控制台不会下载或替换源码目录中的文件。
### 首次配置
1. 打开 `http://<你的主机>:3040/admin`。
@@ -366,26 +360,12 @@ 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 的配置表单。插件页面可以打开对应仓库。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-android-gateway",
"version": "0.3.3",
"version": "0.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-android-gateway",
"version": "0.3.3",
"version": "0.3.2",
"dependencies": {
"@honeybbq/teamspeak": "1.0.0-beta.23",
"express": "^4.21.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-android-gateway",
"version": "0.3.3",
"version": "0.3.2",
"private": true,
"type": "module",
"main": "index.cjs",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "webspeak-webclient",
"version": "0.3.3",
"version": "0.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.3.3",
"version": "0.3.2",
"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.3",
"version": "0.3.2",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/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/call-media-session.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",
"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
@@ -1,209 +0,0 @@
#!/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"
-73
View File
@@ -12,7 +12,6 @@ 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;
@@ -46,9 +45,6 @@ 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;
}
@@ -418,63 +414,6 @@ 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)));
@@ -875,15 +814,3 @@ 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" });
}
-202
View File
@@ -1,202 +0,0 @@
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);
});
+1 -31
View File
@@ -5,7 +5,6 @@ import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
import { SkinRegistry } from "./admin/skin-registry.js";
import { PluginRegistry } from "./plugins/registry.js";
import { UpdateService } from "./updater/update-service.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -53,42 +52,13 @@ 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();
let webServer: ReturnType<typeof createWebServer> | undefined;
webServer = createWebServer({
const 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),
-5
View File
@@ -22,7 +22,6 @@ 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;
@@ -38,8 +37,6 @@ export interface WebServerOptions {
logger: Logger;
nextVisitorNumber?: () => number;
visitorCount?: () => number;
updateService?: UpdateService;
restartAfterUpdate?: () => void;
}
export interface WebServer {
@@ -304,8 +301,6 @@ 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,
-53
View File
@@ -93,52 +93,6 @@ 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) {
@@ -173,9 +127,6 @@ 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>;
@@ -184,7 +135,3 @@ 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>;
-78
View File
@@ -1,78 +0,0 @@
/**
* 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;
}
-130
View File
@@ -1,130 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { createTarGz, createZip } from "./test-support.js";
function fixture(t: test.TestContext, name: string, data: Buffer): { directory: string; archive: string; destination: string } {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-archive-"));
const archive = path.join(directory, name);
writeFileSync(archive, data);
t.after(() => rmSync(directory, { recursive: true, force: true }));
return { directory, archive, destination: path.join(directory, "out") };
}
function rejectsWith(code: string) {
return (error: unknown) => error instanceof ArchiveError && error.code === code;
}
test("tar.gz release archives extract files and directories", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "webspeak/", type: "directory", mode: 0o755 },
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
{ name: "webspeak/dist/index.js", data: "console.log('ok');\n", mode: 0o755 },
]));
await extractReleaseArchive(archive, destination, "release.tar.gz");
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(destination, "webspeak/dist/index.js"), "utf8"), "console.log('ok');\n");
});
test("zip release archives extract stored entries", async t => {
const { archive, destination } = fixture(t, "release.zip", createZip([
{ name: "webspeak/", directory: true },
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>" },
]));
await extractReleaseArchive(archive, destination, "release.zip");
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(destination, "webspeak/web/dist/index.html"), "utf8"), "<!doctype html>");
});
test("tar entries that traverse or use absolute paths are rejected before writing", async t => {
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:/escape.txt"]) {
const { directory, archive, destination } = fixture(t, "release.tar.gz", createTarGz([{ name, data: "owned" }]));
await assert.rejects(extractReleaseArchive(archive, destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
}
});
test("zip entries that traverse or use absolute paths are rejected before writing", async t => {
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:\\escape.txt"]) {
const { directory, archive, destination } = fixture(t, "release.zip", createZip([{ name, data: "owned" }]));
await assert.rejects(extractReleaseArchive(archive, destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
}
});
test("official relative .bin symlinks are accepted and resolve inside the package", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "webspeak/", type: "directory" },
{ name: "webspeak/node_modules/nanoid/bin/nanoid.cjs", data: "#!/usr/bin/env node\nconsole.log('nanoid');\n", mode: 0o755 },
{ name: "webspeak/node_modules/.bin/nanoid", type: "symlink", linkname: "../nanoid/bin/nanoid.cjs" },
]));
await extractReleaseArchive(archive, destination, "release.tar.gz");
const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
assert.equal(lstatSync(link).isSymbolicLink(), true);
assert.equal(readlinkSync(link), "../nanoid/bin/nanoid.cjs");
assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
});
test("zip relative symlinks are accepted while absolute targets are refused", async t => {
const accepted = fixture(t, "release.zip", createZip([
{ name: "webspeak/real.txt", data: "payload" },
{ name: "webspeak/link.txt", data: "real.txt", mode: 0o120777 },
]));
await extractReleaseArchive(accepted.archive, accepted.destination, "release.zip");
const link = path.join(accepted.destination, "webspeak/link.txt");
assert.equal(lstatSync(link).isSymbolicLink(), true);
assert.equal(readlinkSync(link), "real.txt");
assert.equal(readFileSync(link, "utf8"), "payload");
const refused = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
await assert.rejects(extractReleaseArchive(refused.archive, refused.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
});
test("absolute, escaping, empty and hard-link entries are refused", async t => {
const absoluteTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "/etc/passwd" }]));
await assert.rejects(extractReleaseArchive(absoluteTar.archive, absoluteTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
const driveTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "C:\\Windows\\system32" }]));
await assert.rejects(extractReleaseArchive(driveTar.archive, driveTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
const hardlink = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "hardlink", linkname: "target" }]));
await assert.rejects(extractReleaseArchive(hardlink.archive, hardlink.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
for (const linkname of ["", "..", "../outside", "a/../../../outside", "\\etc\\passwd"]) {
const escaping = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname }]));
await assert.rejects(extractReleaseArchive(escaping.archive, escaping.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(escaping.directory, "outside")), false);
}
const zipAbsolute = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
await assert.rejects(extractReleaseArchive(zipAbsolute.archive, zipAbsolute.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
});
test("unsupported archive formats and malformed archives are rejected", async t => {
const unsupported = fixture(t, "release.rar", Buffer.from("not an archive"));
await assert.rejects(extractReleaseArchive(unsupported.archive, unsupported.destination, "release.rar"), rejectsWith("UPDATE_ARCHIVE_UNSUPPORTED"));
const truncated = fixture(t, "release.tar.gz", Buffer.from("short"));
await assert.rejects(extractReleaseArchive(truncated.archive, truncated.destination, "release.tar.gz"));
const brokenZip = fixture(t, "release.zip", Buffer.alloc(64));
await assert.rejects(extractReleaseArchive(brokenZip.archive, brokenZip.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_INVALID"));
const invalidName = fixture(t, "release.tar.gz", createTarGz([{ name: "", data: "x" }]));
await assert.rejects(extractReleaseArchive(invalidName.archive, invalidName.destination, "release.tar.gz"));
});
test("declared extraction limits stop archive bombs", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "one.txt", data: "one" },
{ name: "two.txt", data: "two" },
]));
await assert.rejects(
extractReleaseArchive(archive, destination, "release.tar.gz", { maxEntries: 1 }),
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
);
const fileLimit = fixture(t, "release.zip", createZip([{ name: "big.txt", data: "1234567890" }]));
await assert.rejects(
extractReleaseArchive(fileLimit.archive, fileLimit.destination, "release.zip", { maxFileBytes: 4 }),
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
);
});
-460
View File
@@ -1,460 +0,0 @@
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
@@ -1,188 +0,0 @@
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
@@ -1,259 +0,0 @@
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
@@ -1,182 +0,0 @@
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
@@ -1,121 +0,0 @@
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
@@ -1,161 +0,0 @@
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
@@ -1,243 +0,0 @@
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
@@ -1,360 +0,0 @@
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
@@ -1,511 +0,0 @@
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
@@ -1,152 +0,0 @@
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
@@ -1,894 +0,0 @@
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
@@ -1,700 +0,0 @@
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
@@ -1,159 +0,0 @@
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
@@ -1,311 +0,0 @@
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
@@ -1,28 +0,0 @@
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
@@ -1,38 +0,0 @@
/** 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.3'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 303
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.2'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 302
android {
namespace = "io.webspeak.client"
+2 -2
View File
@@ -25,7 +25,7 @@
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
},
"version": "0.3.3"
"version": "0.3.2"
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
@@ -2952,5 +2952,5 @@
}
}
},
"version": "0.3.3"
"version": "0.3.2"
}
+1 -1
View File
@@ -27,5 +27,5 @@
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
},
"version": "0.3.3"
"version": "0.3.2"
}
+4 -89
View File
@@ -273,51 +273,7 @@
>{{ tr("exportBackup") }}</button
></article
>
<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 class="alert info system-notice"><Icon name="info" :size="16"/><span>{{ tr('updateNotice', {version: operations.diagnostics.version || '—'}) }}</span></div>
</div>
</section>
</template>
@@ -332,54 +288,13 @@ 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" | "errorText">;
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText">;
}>();
// 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,
updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion, checkForUpdates, applyUpdate } = props.model;
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText, errorText } = props.i18n;
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup } = props.model;
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText } = 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); });
+5 -4
View File
@@ -47,15 +47,16 @@
:value="inputVolume * 100"
:style="rangeStyle(inputVolume, 1)"
:aria-label="t('inputVolume')"
:disabled="backgroundCallActive"
@input="onInputVolume"
/>
<div class="dock-panel-divider"></div>
<label class="dock-switch-row">
<span><strong>{{ t("noiseSuppression") }}</strong></span>
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label>
</div>
@@ -131,12 +132,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
const props = defineProps<{
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive" | "backgroundCallActive">;
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
t: (key: string) => string;
rangeStyle: (value: number, max: number) => Record<string, string>;
}>();
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive } = props.model;
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
const emit = defineEmits<{ settings: []; outputMute: [] }>();
</script>
@@ -25,6 +25,15 @@
:size="19" /></button></header
><div class="settings-content">
<div class="settings-audio-card">
<section class="settings-section">
<label class="settings-form-row background-call-setting">
<span><strong>{{ t("backgroundCallTitle") }}</strong><small>{{ t("backgroundCallHint") }}</small></span>
<input type="checkbox" :checked="backgroundCallEnabled" @change="onBackgroundCallChange" />
</label>
<p v-if="backgroundCallActive" class="settings-hint background-call-note">{{ t("backgroundCallProcessingHint") }}</p>
<p v-if="backgroundCallActive && backgroundCallInterrupted" class="settings-error background-call-note">{{ t("backgroundCallInterrupted") }}</p>
<p v-else-if="!backgroundCallActive && backgroundCallEnabled" class="settings-hint background-call-note">{{ t("backgroundCallPending") }}</p>
</section>
<section class="settings-section"
><h3
><Icon
@@ -78,10 +87,10 @@
></div
><label class="settings-form-row">
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
<option value="off">{{ t("noiseSuppressionOff") }}</option>
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
</select>
</label
><div class="settings-form-row settings-range-form-row"
@@ -97,6 +106,7 @@
:value="inputVolume * 100"
:style="rangeStyle(inputVolume, 1)"
:aria-label="t('inputVolume')"
:disabled="backgroundCallActive"
@input="onInputVolume"
/></div
></div
@@ -113,12 +123,13 @@
:value="voxThreshold * 1000"
:style="rangeStyle(voxThreshold, 0.08)"
:aria-label="t('voxThreshold')"
:disabled="backgroundCallActive"
@input="onVoxThreshold"
/></div
></div
><div class="audio-level-row"
><span>{{ t("micLevel") }}</span
><strong>{{ Math.round(micLevel * 100) }}%</strong></div
><strong>{{ backgroundCallActive ? t('backgroundCallNative') : `${Math.round(micLevel * 100)}%` }}</strong></div
><div class="audio-level-track"
><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div
><div class="mic-test"
@@ -214,7 +225,9 @@
><div class="audio-diagnostic"
><span>{{ t("audioStatus") }}</span
><strong>{{
audioContextState === "running"
backgroundCallActive && backgroundCallInterrupted
? t("audioSuspended")
: backgroundCallActive || audioContextState === "running"
? microphoneError
? t("audioUnavailable")
: t("audioReady")
@@ -255,6 +268,10 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
| "backgroundCallEnabled"
| "backgroundCallActive"
| "backgroundCallInterrupted"
| "setBackgroundCallEnabled"
| "inputDevices"
| "outputDevices"
| "selectedInputDeviceId"
@@ -300,6 +317,10 @@ const { onDialogKeydown } = useDialogFocus(dialog, () => emit("close"));
// The page owns the stable voice refs and audio controller; this dialog only presents them.
const {
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
inputDevices,
outputDevices,
selectedInputDeviceId,
@@ -332,6 +353,10 @@ const {
toggleMicrophone,
} = props.controls;
function onBackgroundCallChange(event: Event): void {
setBackgroundCallEnabled((event.target as HTMLInputElement).checked);
}
const inputDeviceOptions = computed(() => [
{ value: "", label: props.t("defaultMicrophone") },
...inputDevices.map((device, index) => ({
@@ -347,3 +372,12 @@ const outputDeviceOptions = computed(() => [
})),
]);
</script>
<style scoped>
.background-call-setting { display: flex; align-items: flex-start; gap: 16px; }
.background-call-setting span { flex: 1; min-width: 0; }
.background-call-setting strong, .background-call-setting small { display: block; }
.background-call-setting small { margin-top: 6px; font-size: 12px; line-height: 1.65; color: var(--text-muted); }
.background-call-setting input { flex: none; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); }
.background-call-note { font-size: 12px; line-height: 1.65; }
</style>
-13
View File
@@ -27,7 +27,6 @@ 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",
@@ -52,18 +51,6 @@ 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",
+4 -47
View File
@@ -1,5 +1,5 @@
import { onScopeDispose, reactive, ref, type Ref } from "vue";
import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord, AdminUpdateRelease, AdminUpdateStatus } from "../../../src/shared/admin-responses.js";
import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord } from "../../../src/shared/admin-responses.js";
import type { copy } from "../i18n/admin.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { createAdminRequests } from "../services/admin-requests.js";
@@ -12,31 +12,19 @@ interface Options {
refreshOverview(): Promise<void>;
}
function emptyUpdateStatus(): AdminUpdateStatus {
return {
currentVersion: "",
deployment: { mode: "source", platform: "", architecture: "", applyAllowed: false, reasonCode: "UPDATE_UNAVAILABLE", upgradePath: "source" },
task: null,
};
}
export function useAdminOperations(options: Options) {
const requests = createAdminRequests();
const operationsLoading = ref(false), terminatingSession = ref(""), inviteSubmitting = ref(false);
const updateChecking = ref(false), updateApplying = ref(false), updateChecked = ref(false);
const availableUpdates = ref<AdminUpdateRelease[]>([]), selectedVersion = ref("");
const revokingInvites = reactive(new Set<string>());
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
const createdInvite = ref<{ token: string; link: string } | null>(null);
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[],
diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 },
update: emptyUpdateStatus(),
logs: { available: false, entries: [] as AdminLog[], sessions: [] as AdminConnectionRecord[] }, audit: [] as Array<{ event: string; createdAt: string }> });
let noticeTimer: number | undefined;
function cancelRequests() {
requests.reset();
operationsLoading.value = false; terminatingSession.value = ""; inviteSubmitting.value = false;
updateChecking.value = false; updateApplying.value = false;
revokingInvites.clear();
if (noticeTimer !== undefined) window.clearTimeout(noticeTimer);
noticeTimer = undefined;
@@ -47,8 +35,6 @@ export function useAdminOperations(options: Options) {
operations.sessions = []; operations.invites = []; operations.audit = [];
operations.logs = { available: false, entries: [], sessions: [] };
operations.diagnostics = { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 };
operations.update = emptyUpdateStatus();
availableUpdates.value = []; selectedVersion.value = ""; updateChecked.value = false;
Object.assign(inviteForm, { channel: "", expiresInHours: 24, maxUses: 0 });
}
onScopeDispose(reset);
@@ -59,15 +45,13 @@ export function useAdminOperations(options: Options) {
const request = requests.begin("load");
operationsLoading.value = true;
try {
const [sessions, invites, diagnostics, update, logs, audit] = await Promise.all([
options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal),
options.api.updateStatus(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
const [sessions, invites, diagnostics, logs, audit] = await Promise.all([
options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
]);
if (!request.isCurrent()) return;
operations.sessions = sessions.sessions;
operations.invites = invites.invites;
operations.diagnostics = { ...diagnostics.gateway, schemaVersion: diagnostics.database.schemaVersion, createdSessions: diagnostics.sessions.created };
operations.update = update;
operations.logs = logs;
operations.audit = audit.events;
} catch (error) { if (request.isCurrent()) report(error); }
@@ -119,31 +103,6 @@ export function useAdminOperations(options: Options) {
} catch (error) { if (request.isCurrent()) report(error); }
finally { request.finish(); }
}
async function checkForUpdates() {
if (updateChecking.value) return;
const request = requests.begin("update-check");
updateChecking.value = true; updateChecked.value = false; availableUpdates.value = []; options.errorMessage.value = "";
try {
const result = await options.api.checkUpdates(request.signal);
if (!request.isCurrent()) return;
availableUpdates.value = result.releases;
selectedVersion.value = result.releases.find(release => release.canApply)?.version ?? "";
updateChecked.value = true;
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) updateChecking.value = false; request.finish(); }
}
async function applyUpdate(release: AdminUpdateRelease) {
if (updateApplying.value) return;
if (!window.confirm(options.tr("updateConfirmApply", { version: release.version }))) return;
const request = requests.begin("update-apply");
updateApplying.value = true; options.errorMessage.value = "";
try {
const result = await options.api.applyUpdate({ version: release.version, confirmVersion: release.version }, request.signal);
if (!request.isCurrent()) return;
operations.update = { ...operations.update, task: result.task, deployment: { ...operations.update.deployment, applyAllowed: false } };
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) updateApplying.value = false; request.finish(); }
}
async function downloadBackup() {
const request = requests.begin("backup");
try {
@@ -159,7 +118,5 @@ export function useAdminOperations(options: Options) {
finally { request.finish(); }
}
return { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion,
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, checkForUpdates, applyUpdate,
cancelRequests, reset };
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, cancelRequests, reset };
}
+91 -16
View File
@@ -5,6 +5,8 @@ export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.j
import { createAudioSinkRouter } from "../voice/audio-sink.js";
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
import { createNativeMicrophoneCapture } from "../voice/native-microphone.js";
import { createCallMediaSession } from "../services/call-media-session.js";
import { createVoiceConnection } from "../voice/connection.js";
import { createVoiceCommands } from "../voice/commands.js";
import { createVoiceSessionState } from "../voice/session-state.js";
@@ -21,7 +23,7 @@ import type { ChatMessage } from "../../../src/shared/voice-models.js";
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
import { computed, onScopeDispose, reactive, ref, shallowRef, watch } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
export interface VoiceState {
@@ -257,6 +259,11 @@ export function useVoiceWebSocket() {
let micStream: MediaStream | null = null;
const microphoneCaptureFactory = createMicrophoneCaptureFactory();
let microphoneCapture: MicrophoneCapture | null = null;
let microphoneNative = false;
const backgroundCallEnabled = ref(false);
const backgroundCallActive = ref(false);
const backgroundCallInterrupted = ref(false);
let backgroundCallTouched = false;
let pendingMicrophoneCapture: AbortController | null = null;
const accompanimentActive = ref(false);
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
@@ -345,7 +352,7 @@ export function useVoiceWebSocket() {
stunServer: () => webRtcStunServer,
prepareMicrophone: async () => {
await ensureMicrophone();
return micStream ? { context: getAudioCtx(), stream: micStream,
return micStream ? { context: microphoneNative ? null : getAudioCtx(), stream: micStream,
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
},
stopPcm: stopCaptureGraph,
@@ -366,6 +373,7 @@ export function useVoiceWebSocket() {
async onFallback(reason, isCurrent) {
if (!isCurrent()) return;
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
backgroundCallActive.value = false;
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
try { await startMicrophone(); }
catch (error) { if (isCurrent()) setMicrophoneError(error); }
@@ -387,6 +395,38 @@ export function useVoiceWebSocket() {
onPlaying: syncAudioContextNotice,
},
});
const callMediaSession = createCallMediaSession({
resume() {
// A media Play command resumes listening only. Unmuting needs an explicit
// microphone action, never a page visibility or system playback event.
outputMuted.value = false;
applyOutputVolume();
webrtc.resumePlayback();
},
pause() {
setMicrophoneMuted(true);
outputMuted.value = true;
applyOutputVolume();
},
toggleMicrophone: () => setMicrophoneMuted(!microphoneMuted.value),
hangup: () => disconnect(),
});
function syncCallMediaSession(): void {
callMediaSession.sync({ active: state.connected && backgroundCallActive.value,
muted: microphoneMuted.value, outputMuted: outputMuted.value, title: serverInfo.value?.name || "WebSpeak" });
}
watch([() => state.connected, backgroundCallActive, microphoneMuted, outputMuted, serverInfo], syncCallMediaSession);
const resumeVisibleCall = () => {
if (!state.connected || !backgroundCallActive.value || document.visibilityState !== "visible") return;
webrtc.resumePlayback();
};
document.addEventListener("visibilitychange", resumeVisibleCall);
window.addEventListener("pageshow", resumeVisibleCall);
onScopeDispose(() => {
callMediaSession.dispose();
document.removeEventListener("visibilitychange", resumeVisibleCall);
window.removeEventListener("pageshow", resumeVisibleCall);
});
const audioDiagnostics = createAudioDiagnostics({
source() {
const socket = ws.value;
@@ -398,7 +438,7 @@ export function useVoiceWebSocket() {
presentation({ peer }) {
return {
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live" && !track.muted)),
microphonePermission: audioPermission.value,
playbackState: peer
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
@@ -414,6 +454,7 @@ export function useVoiceWebSocket() {
preferredInputDeviceId: committedInputDeviceId,
inputDeviceId: committedInputDeviceId,
microphoneMuted: microphoneMuted.value,
backgroundCallEnabled: backgroundCallEnabled.value,
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
noiseSuppressionLevel: committedNoiseSuppressionLevel,
voxThreshold: voxThreshold.value,
@@ -433,6 +474,7 @@ export function useVoiceWebSocket() {
}
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
if (!backgroundCallTouched) backgroundCallEnabled.value = preferences.backgroundCallEnabled === true;
if (!inputDeviceTouched) {
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
committedInputDeviceId = selectedInputDeviceId.value;
@@ -549,7 +591,7 @@ export function useVoiceWebSocket() {
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
function syncAudioContextNotice(): void {
if (audioCtx && audioCtx.state === "suspended") {
if (!microphoneNative && audioCtx && audioCtx.state === "suspended") {
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
} else {
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
@@ -702,9 +744,10 @@ export function useVoiceWebSocket() {
pendingMicrophoneCapture?.abort();
const controller = new AbortController();
pendingMicrophoneCapture = controller;
const ctx = getAudioCtx();
const native = backgroundCallActive.value;
const ctx = native ? null : getAudioCtx();
const assertCurrent = (): void => {
if (generation !== microphoneGeneration || audioCtx !== ctx || controller.signal.aborted) throw new CancelledMediaOperation();
if (generation !== microphoneGeneration || (ctx && audioCtx !== ctx) || controller.signal.aborted) throw new CancelledMediaOperation();
};
let nextStream: MediaStream | null = null;
let nextCapture: MicrophoneCapture | null = null;
@@ -712,24 +755,35 @@ export function useVoiceWebSocket() {
try {
nextStream = await requestMediaBeforeAudioResume(
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }),
() => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(),
() => ctx?.state === "suspended" ? ctx.resume() : Promise.resolve(),
);
assertCurrent();
audioPermission.value = "granted";
factoryOwnsStream = true;
nextCapture = await microphoneCaptureFactory.prepare({
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
});
if (native) {
nextCapture = createNativeMicrophoneCapture(nextStream);
factoryOwnsStream = true;
} else {
factoryOwnsStream = true;
nextCapture = await microphoneCaptureFactory.prepare({
context: ctx!, stream: nextStream, signal: controller.signal, assertCurrent,
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
});
}
assertCurrent();
// Commit only a complete graph. Permission and node failures leave the
// previous stream, PCM route and WebRTC peer untouched.
stopMicrophone(false);
micStream = nextStream;
microphoneCapture = nextCapture;
microphoneNative = native;
backgroundCallInterrupted.value = false;
sessionTrace.record("microphone.route", { native });
const microphoneTrack = nextStream.getAudioTracks()[0];
if (microphoneTrack) {
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
const recordTrack = (stateName: string) => {
sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
if (micStream === nextStream && native) backgroundCallInterrupted.value = microphoneTrack.muted || microphoneTrack.readyState !== "live";
};
recordTrack(microphoneTrack.readyState);
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
@@ -759,8 +813,8 @@ export function useVoiceWebSocket() {
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
async function ensureMicrophone(): Promise<void> {
if (microphoneStartPromise) return microphoneStartPromise;
if (micStream) return;
if (microphoneStartPromise) await microphoneStartPromise;
if (micStream && microphoneNative === backgroundCallActive.value) return;
if (!microphoneStartPromise) {
const generation = microphoneGeneration + 1;
const pending = startMicrophone().then(async () => {
@@ -793,6 +847,10 @@ export function useVoiceWebSocket() {
}
async function startAccompaniment(): Promise<void> {
if (backgroundCallActive.value) {
accompanimentErrorCode.value = "backgroundMode";
throw new DOMException("Accompaniment is unavailable in native call mode", "NotSupportedError");
}
await accompaniment.start();
}
@@ -827,6 +885,8 @@ export function useVoiceWebSocket() {
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
microphoneCapture?.dispose();
microphoneCapture = null;
microphoneNative = false;
backgroundCallInterrupted.value = false;
webrtc.releaseInput();
micStream = null;
if (closeContext) {
@@ -1067,6 +1127,8 @@ export function useVoiceWebSocket() {
commands.clear(new Error("语音连接已关闭"));
screenShare.stopTransport(sendScreenStop);
webrtc.stop();
backgroundCallActive.value = false;
callMediaSession.dispose();
remotePlayback.clearAll();
stopMicrophone();
clearSpeakingState();
@@ -1106,6 +1168,9 @@ export function useVoiceWebSocket() {
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
screenShare.setIceServers(msg.screenShareIceServers);
webRtcStunServer = msg.webRtcStunServer ?? "";
backgroundCallActive.value = backgroundCallEnabled.value && msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined";
sessionTrace.record("call.background", { requested: backgroundCallEnabled.value, native: backgroundCallActive.value });
syncCallMediaSession();
sessionState.connected(msg);
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
@@ -1441,6 +1506,12 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
function setBackgroundCallEnabled(enabled: boolean): void {
backgroundCallTouched = true;
backgroundCallEnabled.value = enabled;
void saveAudioPreferences();
}
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
if (noiseSuppressionLevel.value === level) return;
noiseSuppressionTouched = true;
@@ -1479,7 +1550,7 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
onBeforeUnmount(() => sessionTrace.dispose());
onScopeDispose(() => { disconnect(); sessionTrace.dispose(); });
return {
pluginSession,
@@ -1495,6 +1566,10 @@ export function useVoiceWebSocket() {
serverEvents,
pokeNotifications,
microphoneMuted,
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
@@ -166,7 +166,9 @@ export function useWebClientAudioControls({
await startAccompaniment();
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
} catch {
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
const messageKey = accompanimentErrorCode.value === "backgroundMode"
? "backgroundCallProcessingHint"
: accompanimentErrorCode.value === "needsWebRtc"
? "accompanimentNeedsWebRtc"
: accompanimentErrorCode.value === "noAudio"
? "accompanimentNoAudio"
-140
View File
@@ -10,34 +10,6 @@ const zh = {
adminBrowserSessions: "浏览器会话", adminBrowserSessionsLead: "这里只显示通过此 WebSpeak 实例连接的用户;结束会话会断开对应浏览器。完整 TS 成员列表见 TeamSpeak 服务管理。",
adminInviteScope: "这些邀请链接由当前 WebSpeak 实例生成和管理。",
adminLogsSection: "连接与日志", adminMaintenanceSection: "诊断与备份",
updateTitle: "版本更新", updateLead: "检查官方 GitHub Releases 中的正式版本。Linux x64 发布包(已按官方包形态验证)可在控制台校验并切换版本;Docker 和源码运行只显示检查结果。",
updateCurrentVersion: "当前版本", updateDeploymentMode: "部署模式", updateArchitecture: "平台与架构",
updateModeDocker: "Docker Compose", updateModeReleasePackage: "发布包", updateModeSource: "源码运行",
updateCanApply: "可在此控制台更新", updateCannotApply: "此部署不能在此应用更新",
updateCheckAction: "检查正式版", updateChecking: "正在检查…", updateUpToDate: "没有比当前版本更新的正式版。",
updateSelectRelease: "选择目标版本", updateApplyAction: "应用更新", updateApplying: "正在准备更新…",
updateConfirmApply: "将把 WebSpeak 更新到 v{{version}}。更新前建议先导出备份;进程会重启,页面会短暂断开。继续吗?",
updateBackupHint: "建议先使用上方的“导出备份”。控制台只替换程序代码,不会改动 data/、config.json 或 certs/。",
updateChecksumMissing: "该版本缺少 SHA256SUMS.txt,已拒绝更新。", updateAssetMissing: "该版本没有适用于当前平台和架构的发布包。",
updateBlockedDocker: "容器内不能替换镜像。请保留 webspeak-data volume,在宿主机执行 docker compose pull && docker compose up -d;不要执行 docker compose down -v。",
updateBlockedSource: "源码运行没有捆绑运行时,控制台无法安全切换版本。请拉取源码后自行构建(npm ci && npm run build && npm run web:build),或改用发布包/Docker Compose。",
updateBlockedSupervised: "此实例由 systemd、PM2 等进程管理器托管,目前只能检查版本。请停止服务,手动替换发布包中的程序文件后再启动,并保留 data/、config.json 和 certs/。",
updateBlockedPlatform: "当前平台没有官方发布包,只能检查版本。", updateBlockedArch: "当前架构没有官方发布包,只能检查版本。",
updateBlockedWindows: "Windows 发布包的控制台更新尚未在真实 Windows 环境验证,已禁用;请下载新版发布包后手动替换。",
updateBlockedArm64: "Linux arm64 发布包的控制台更新尚未在真实硬件实测,已禁用;请下载新版发布包后手动替换。",
updateChecksumNotice: "SHA256SUMS.txt 只用于 SHA-256 完整性校验和,不是数字签名。",
updateBlockedUnavailable: "此实例未启用控制台更新。", updateTaskTitle: "更新任务",
updateStatusDownloading: "正在下载", updateStatusVerifying: "正在校验", updateStatusExtracting: "正在解包", updateStatusStaging: "正在暂存",
updateStatusRestarting: "正在重启", updateStatusSucceeded: "更新成功", updateStatusFailed: "更新失败",
updateRolledBack: "已恢复上一版本。", updateRestartHint: "更新成功后进程会自动重启;页面断开时请稍后刷新。",
updateReleaseNotes: "发行说明",
updateErrorChecksum: "校验和缺失或不匹配,已拒绝安装该发布包。", updateErrorArchive: "发布包未通过安全解包检查。",
updateErrorDownload: "无法从官方 Release 下载或保存资源。", updateErrorPackage: "发布包内容与所选正式版不匹配。",
updateErrorApply: "更新失败,请查看日志。", updateErrorInterrupted: "更新被中断,未确认完成。",
updateErrorRollbackFailed: "更新失败且自动回滚也失败。请按备份手动恢复上一版本。",
updateErrorSwap: "替换程序文件失败,已尝试恢复上一版本;请查看日志。",
updateErrorInProgress: "已有更新任务正在进行。", updateErrorGeneric: "更新未能完成,请查看日志。", updateStartedEvent: "已开始更新",
updateErrorLockFailed: "无法接管更新锁,请确认没有其他更新任务在运行后重试。", updateErrorUnavailable: "此实例未启用控制台更新。",
adminWsOverviewTitle: "WebSpeak 管理服务已就绪", adminWsOverviewLead: "先管理实例接入与访客体验;需要管理 TS 服务时,再按需配置独立连接。",
adminWsManageLead: "接入策略、站点公告、语音传输、皮肤商店和浏览器会话。",
adminTsManageLead: "服务器设置、频道、在线成员、服务器组和封禁。需单独配置 Query 凭据,常规语音连接不需要。",
@@ -60,34 +32,6 @@ const en = {
adminBrowserSessions: "Browser sessions", adminBrowserSessionsLead: "Only users connected through this WebSpeak instance are listed here. Ending a session disconnects that browser. Use TeamSpeak service management for the full TS client list.",
adminInviteScope: "These invite links are created and managed by this WebSpeak instance.",
adminLogsSection: "Connections & logs", adminMaintenanceSection: "Diagnostics & backups",
updateTitle: "Version update", updateLead: "Check stable versions in the official GitHub Releases. On verified Linux x64 release packages the console can verify and switch versions; Docker and source installs only show check results.",
updateCurrentVersion: "Current version", updateDeploymentMode: "Deployment", updateArchitecture: "Platform & architecture",
updateModeDocker: "Docker Compose", updateModeReleasePackage: "Release package", updateModeSource: "From source",
updateCanApply: "Update from this console", updateCannotApply: "This deployment cannot apply updates here",
updateCheckAction: "Check stable releases", updateChecking: "Checking…", updateUpToDate: "No stable release is newer than the running version.",
updateSelectRelease: "Select target version", updateApplyAction: "Apply update", updateApplying: "Preparing update…",
updateConfirmApply: "WebSpeak will be updated to v{{version}}. Export a backup first; the process restarts and this page disconnects briefly. Continue?",
updateBackupHint: "Export a backup above first. The console replaces application code only and never touches data/, config.json or certs/.",
updateChecksumMissing: "This release has no SHA256SUMS.txt; the update is refused.", updateAssetMissing: "This release has no package for the current platform and architecture.",
updateBlockedDocker: "An image cannot be replaced from inside the container. Keep the webspeak-data volume and run docker compose pull && docker compose up -d on the host. Never run docker compose down -v.",
updateBlockedSource: "Source installs have no bundled runtime, so the console cannot switch versions safely. Pull the source and rebuild (npm ci && npm run build && npm run web:build), or use a release package/Docker Compose.",
updateBlockedSupervised: "This instance runs under a process manager such as systemd or PM2; only version checks are available. Stop the service, replace the package's application files manually, then start it again. Preserve data/, config.json and certs/.",
updateBlockedPlatform: "No official package exists for this platform; only version checks are available.", updateBlockedArch: "No official package exists for this architecture; only version checks are available.",
updateBlockedWindows: "Console updates for Windows release packages are disabled until they are verified on a real Windows install. Download the new package and replace it manually.",
updateBlockedArm64: "Console updates for Linux arm64 release packages are disabled until they are verified on real hardware. Download the new package and replace it manually.",
updateChecksumNotice: "SHA256SUMS.txt is an integrity checksum only, not a digital signature.",
updateBlockedUnavailable: "Console updates are not enabled for this instance.", updateTaskTitle: "Update task",
updateStatusDownloading: "Downloading", updateStatusVerifying: "Verifying", updateStatusExtracting: "Extracting", updateStatusStaging: "Staging",
updateStatusRestarting: "Restarting", updateStatusSucceeded: "Update succeeded", updateStatusFailed: "Update failed",
updateRolledBack: "The previous version was restored.", updateRestartHint: "The process restarts after a successful update; refresh shortly if this page disconnects.",
updateReleaseNotes: "Release notes",
updateErrorChecksum: "The checksum is missing or does not match; the package was refused.", updateErrorArchive: "The package failed the safe-extraction checks.",
updateErrorDownload: "The official release asset could not be downloaded or saved.", updateErrorPackage: "The package does not match the selected stable release.",
updateErrorApply: "The update failed; check the logs.", updateErrorInterrupted: "The update was interrupted before completion was confirmed.",
updateErrorRollbackFailed: "The update failed and automatic rollback also failed. Restore the previous version manually from the backup.",
updateErrorSwap: "Replacing application files failed; the previous version was restored where possible. Check the logs.",
updateErrorInProgress: "Another update task is already running.", updateErrorGeneric: "The update could not be completed; check the logs.", updateStartedEvent: "Update started",
updateErrorLockFailed: "The update lock could not be taken over; make sure no other update is running and try again.", updateErrorUnavailable: "Console updates are not enabled for this instance.",
adminWsOverviewTitle: "WebSpeak management is ready", adminWsOverviewLead: "Manage instance access and the guest experience first. Configure an independent TS management connection when you need it.",
adminWsManageLead: "Access policy, site announcements, voice transport, the skin store and browser sessions.",
adminTsManageLead: "Server settings, channels, clients, server groups and bans. Separate Query credentials are required; ordinary voice connections do not need them.",
@@ -109,34 +53,6 @@ const de = {
adminBrowserSessions: "Browsersitzungen", adminBrowserSessionsLead: "Hier stehen nur Nutzer dieser WebSpeak-Instanz. Beenden trennt den jeweiligen Browser. Die vollständige TS-Mitgliederliste befindet sich in der TeamSpeak-Verwaltung.",
adminInviteScope: "Diese Einladungslinks werden von dieser WebSpeak-Instanz erstellt und verwaltet.",
adminLogsSection: "Verbindungen & Protokolle", adminMaintenanceSection: "Diagnose & Sicherungen",
updateTitle: "Versionsaktualisierung", updateLead: "Stabile Versionen aus den offiziellen GitHub Releases prüfen. Verifizierte Linux-x64-Release-Pakete können hier geprüft und gewechselt werden; Docker- und Quellinstallationen zeigen nur Prüfergebnisse.",
updateCurrentVersion: "Aktuelle Version", updateDeploymentMode: "Bereitstellung", updateArchitecture: "Plattform & Architektur",
updateModeDocker: "Docker Compose", updateModeReleasePackage: "Release-Paket", updateModeSource: "Aus Quellen",
updateCanApply: "In dieser Konsole aktualisieren", updateCannotApply: "Diese Bereitstellung kann hier nicht aktualisiert werden",
updateCheckAction: "Stabile Versionen prüfen", updateChecking: "Wird geprüft…", updateUpToDate: "Keine stabile Version ist neuer als die laufende.",
updateSelectRelease: "Zielversion wählen", updateApplyAction: "Update anwenden", updateApplying: "Update wird vorbereitet…",
updateConfirmApply: "WebSpeak wird auf v{{version}} aktualisiert. Vorher eine Sicherung exportieren; der Prozess startet neu und die Seite trennt kurz. Fortfahren?",
updateBackupHint: "Zuerst oben eine Sicherung exportieren. Die Konsole ersetzt nur Anwendungscode und ändert data/, config.json oder certs/ nicht.",
updateChecksumMissing: "Diesem Release fehlt SHA256SUMS.txt; das Update wird abgelehnt.", updateAssetMissing: "Dieses Release hat kein Paket für Plattform und Architektur.",
updateBlockedDocker: "Ein Image kann nicht im Container ersetzt werden. Das Volume webspeak-data behalten und auf dem Host docker compose pull && docker compose up -d ausführen. Niemals docker compose down -v verwenden.",
updateBlockedSource: "Quellinstallationen haben keine mitgelieferte Laufzeit; die Konsole kann Versionen nicht sicher wechseln. Quellen aktualisieren und neu bauen (npm ci && npm run build && npm run web:build) oder Release-Paket/Docker Compose verwenden.",
updateBlockedSupervised: "Diese Instanz wird etwa von systemd oder PM2 verwaltet; nur Versionsprüfungen sind verfügbar. Dienst stoppen, Programmdateien manuell ersetzen und wieder starten. data/, config.json und certs/ behalten.",
updateBlockedPlatform: "Für diese Plattform gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.", updateBlockedArch: "Für diese Architektur gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.",
updateBlockedWindows: "Konsolen-Updates für Windows-Release-Pakete sind deaktiviert, bis sie auf einer echten Windows-Installation geprüft wurden. Laden Sie das neue Paket herunter und ersetzen Sie es manuell.",
updateBlockedArm64: "Konsolen-Updates für Linux-arm64-Release-Pakete sind deaktiviert, bis sie auf echter Hardware geprüft wurden. Laden Sie das neue Paket herunter und ersetzen Sie es manuell.",
updateChecksumNotice: "SHA256SUMS.txt ist nur eine Integritätsprüfsumme, keine digitale Signatur.",
updateBlockedUnavailable: "Konsolen-Updates sind für diese Instanz nicht aktiviert.", updateTaskTitle: "Update-Aufgabe",
updateStatusDownloading: "Wird heruntergeladen", updateStatusVerifying: "Wird geprüft", updateStatusExtracting: "Wird entpackt", updateStatusStaging: "Wird bereitgestellt",
updateStatusRestarting: "Neustart", updateStatusSucceeded: "Update erfolgreich", updateStatusFailed: "Update fehlgeschlagen",
updateRolledBack: "Die vorherige Version wurde wiederhergestellt.", updateRestartHint: "Nach erfolgreichem Update startet der Prozess neu; die Seite bei Trennung später neu laden.",
updateReleaseNotes: "Release-Notizen",
updateErrorChecksum: "Prüfsumme fehlt oder stimmt nicht; das Paket wurde abgelehnt.", updateErrorArchive: "Das Paket hat die sichere Entpackprüfung nicht bestanden.",
updateErrorDownload: "Das offizielle Release-Artefakt konnte nicht geladen oder gespeichert werden.", updateErrorPackage: "Das Paket passt nicht zum gewählten stabilen Release.",
updateErrorApply: "Das Update ist fehlgeschlagen; Protokolle prüfen.", updateErrorInterrupted: "Das Update wurde vor der Bestätigung unterbrochen.",
updateErrorRollbackFailed: "Das Update ist fehlgeschlagen und auch die automatische Wiederherstellung. Stellen Sie die vorherige Version manuell aus der Sicherung wieder her.",
updateErrorSwap: "Das Ersetzen der Anwendungsdateien ist fehlgeschlagen; die vorherige Version wurde nach Möglichkeit wiederhergestellt. Protokolle prüfen.",
updateErrorInProgress: "Eine andere Update-Aufgabe läuft bereits.", updateErrorGeneric: "Das Update konnte nicht abgeschlossen werden; Protokolle prüfen.", updateStartedEvent: "Update gestartet",
updateErrorLockFailed: "Die Update-Sperre konnte nicht übernommen werden. Stellen Sie sicher, dass keine andere Update-Aufgabe läuft, und versuchen Sie es erneut.", updateErrorUnavailable: "Konsolen-Updates sind für diese Instanz nicht aktiviert.",
adminWsOverviewTitle: "WebSpeak-Verwaltung ist bereit", adminWsOverviewLead: "Zuerst Instanzzugang und Gastoberfläche verwalten. Eine separate TS-Verbindung nur bei Bedarf einrichten.",
adminWsManageLead: "Zugriffsregeln, Website-Ankündigungen, Sprachtransport, Skin-Store und Browsersitzungen.",
adminTsManageLead: "Servereinstellungen, Kanäle, Mitglieder, Servergruppen und Sperren. Separate Query-Zugangsdaten sind nötig; normale Sprachverbindungen benötigen sie nicht.",
@@ -158,34 +74,6 @@ const ru = {
adminBrowserSessions: "Сеансы браузеров", adminBrowserSessionsLead: "Здесь только пользователи этого экземпляра WebSpeak. Завершение сеанса отключает соответствующий браузер. Полный список участников TS доступен в управлении TeamSpeak.",
adminInviteScope: "Эти ссылки-приглашения создаются и управляются текущим экземпляром WebSpeak.",
adminLogsSection: "Подключения и журналы", adminMaintenanceSection: "Диагностика и копии",
updateTitle: "Обновление версии", updateLead: "Проверка стабильных версий в официальных GitHub Releases. Для проверенных релизных пакетов Linux x64 консоль может проверить и сменить версию; Docker и исходники показывают только результат проверки.",
updateCurrentVersion: "Текущая версия", updateDeploymentMode: "Развёртывание", updateArchitecture: "Платформа и архитектура",
updateModeDocker: "Docker Compose", updateModeReleasePackage: "Пакет релиза", updateModeSource: "Из исходников",
updateCanApply: "Можно обновить из консоли", updateCannotApply: "Это развёртывание нельзя обновить здесь",
updateCheckAction: "Проверить стабильные версии", updateChecking: "Проверка…", updateUpToDate: "Нет стабильной версии новее текущей.",
updateSelectRelease: "Выберите целевую версию", updateApplyAction: "Применить обновление", updateApplying: "Подготовка обновления…",
updateConfirmApply: "WebSpeak будет обновлён до v{{version}}. Сначала экспортируйте резервную копию; процесс перезапустится, страница кратко отключится. Продолжить?",
updateBackupHint: "Сначала используйте «Экспорт резервной копии» выше. Консоль заменяет только код приложения и не изменяет data/, config.json или certs/.",
updateChecksumMissing: "В релизе нет SHA256SUMS.txt; обновление отклонено.", updateAssetMissing: "В релизе нет пакета для текущей платформы и архитектуры.",
updateBlockedDocker: "Образ нельзя заменить изнутри контейнера. Сохраните том webspeak-data и выполните на хосте docker compose pull && docker compose up -d. Никогда не запускайте docker compose down -v.",
updateBlockedSource: "В установке из исходников нет встроенной среды выполнения, поэтому консоль не может безопасно сменить версию. Обновите исходники и пересоберите (npm ci && npm run build && npm run web:build) или используйте пакет релиза/Docker Compose.",
updateBlockedSupervised: "Экземпляр управляется systemd, PM2 или другим менеджером процессов; доступна только проверка версий. Остановите службу, вручную замените файлы программы и запустите её снова. Сохраните data/, config.json и certs/.",
updateBlockedPlatform: "Для этой платформы нет официального пакета; доступна только проверка версий.", updateBlockedArch: "Для этой архитектуры нет официального пакета; доступна только проверка версий.",
updateBlockedWindows: "Обновление из консоли для релизных пакетов Windows отключено до проверки на реальной установке Windows. Скачайте новый пакет и замените его вручную.",
updateBlockedArm64: "Обновление из консоли для релизных пакетов Linux arm64 отключено до проверки на реальном оборудовании. Скачайте новый пакет и замените его вручную.",
updateChecksumNotice: "SHA256SUMS.txt — только контрольная сумма целостности, а не цифровая подпись.",
updateBlockedUnavailable: "Обновление из консоли для этого экземпляра не включено.", updateTaskTitle: "Задача обновления",
updateStatusDownloading: "Скачивание", updateStatusVerifying: "Проверка", updateStatusExtracting: "Распаковка", updateStatusStaging: "Подготовка",
updateStatusRestarting: "Перезапуск", updateStatusSucceeded: "Обновление выполнено", updateStatusFailed: "Обновление не удалось",
updateRolledBack: "Предыдущая версия восстановлена.", updateRestartHint: "После успешного обновления процесс перезапустится; обновите страницу позже, если она отключилась.",
updateReleaseNotes: "Примечания к релизу",
updateErrorChecksum: "Контрольная сумма отсутствует или не совпадает; пакет отклонён.", updateErrorArchive: "Пакет не прошёл проверку безопасной распаковки.",
updateErrorDownload: "Не удалось скачать или сохранить официальный ресурс релиза.", updateErrorPackage: "Пакет не соответствует выбранному стабильному релизу.",
updateErrorApply: "Обновление не удалось; проверьте журналы.", updateErrorInterrupted: "Обновление прервано до подтверждения завершения.",
updateErrorRollbackFailed: "Обновление не удалось, и автоматический откат тоже не удался. Восстановите предыдущую версию вручную из резервной копии.",
updateErrorSwap: "Не удалось заменить файлы приложения; предыдущая версия восстановлена по возможности. Проверьте журналы.",
updateErrorInProgress: "Другая задача обновления уже выполняется.", updateErrorGeneric: "Не удалось завершить обновление; проверьте журналы.", updateStartedEvent: "Обновление начато",
updateErrorLockFailed: "Не удалось перехватить блокировку обновления. Убедитесь, что другая задача обновления не выполняется, и повторите попытку.", updateErrorUnavailable: "Обновление из консоли для этого экземпляра не включено.",
adminWsOverviewTitle: "Управление WebSpeak готово", adminWsOverviewLead: "Настройте доступ и гостевой интерфейс. Отдельное управление TS подключайте по мере необходимости.",
adminWsManageLead: "Политика доступа, объявления сайта, голосовой транспорт, магазин тем и сеансы браузеров.",
adminTsManageLead: "Настройки сервера, каналы, участники, серверные группы и блокировки. Нужны отдельные данные Query; для обычного голосового подключения они не требуются.",
@@ -207,34 +95,6 @@ const ja = {
adminBrowserSessions: "ブラウザーセッション", adminBrowserSessionsLead: "この WebSpeak 経由の利用者だけを表示します。終了すると該当のブラウザーが切断されます。TS の全メンバーは TeamSpeak サービス管理で確認できます。",
adminInviteScope: "この招待リンクは現在の WebSpeak インスタンスが発行・管理します。",
adminLogsSection: "接続とログ", adminMaintenanceSection: "診断とバックアップ",
updateTitle: "バージョン更新", updateLead: "公式 GitHub Releases の安定版を確認します。検証済みの Linux x64 リリースパッケージではここで検証して切り替えられます。Docker とソース実行は確認結果のみ表示します。",
updateCurrentVersion: "現在のバージョン", updateDeploymentMode: "デプロイ", updateArchitecture: "プラットフォームとアーキテクチャ",
updateModeDocker: "Docker Compose", updateModeReleasePackage: "リリースパッケージ", updateModeSource: "ソース実行",
updateCanApply: "このコンソールから更新できます", updateCannotApply: "このデプロイではここから更新できません",
updateCheckAction: "安定版を確認", updateChecking: "確認中…", updateUpToDate: "現在より新しい安定版はありません。",
updateSelectRelease: "対象バージョンを選択", updateApplyAction: "更新を適用", updateApplying: "更新を準備中…",
updateConfirmApply: "WebSpeak を v{{version}} に更新します。先にバックアップを書き出してください。プロセスが再起動し、ページが一時的に切断されます。続行しますか?",
updateBackupHint: "先に上の「バックアップを書き出す」を使用してください。コンソールはプログラムコードのみを置き換え、data/、config.json、certs/ は変更しません。",
updateChecksumMissing: "このリリースには SHA256SUMS.txt がないため、更新を拒否しました。", updateAssetMissing: "このリリースには現在のプラットフォームとアーキテクチャ向けのパッケージがありません。",
updateBlockedDocker: "コンテナ内からイメージは置き換えられません。webspeak-data ボリュームを保持し、ホストで docker compose pull && docker compose up -d を実行してください。docker compose down -v は実行しないでください。",
updateBlockedSource: "ソース実行には同梱ランタイムがないため、安全にバージョンを切り替えられません。ソースを取得して再ビルドする(npm ci && npm run build && npm run web:build)か、リリースパッケージ/Docker Compose を使用してください。",
updateBlockedSupervised: "このインスタンスは systemd や PM2 などで管理されているため、バージョン確認のみ可能です。サービスを停止し、プログラムファイルを手動で置き換えて再起動してください。data/、config.json、certs/ は保持してください。",
updateBlockedPlatform: "このプラットフォーム向けの公式パッケージがないため、バージョン確認のみ可能です。", updateBlockedArch: "このアーキテクチャ向けの公式パッケージがないため、バージョン確認のみ可能です。",
updateBlockedWindows: "Windows リリースパッケージのコンソール更新は、実際の Windows 環境で検証するまで無効です。新しいパッケージをダウンロードして手動で置き換えてください。",
updateBlockedArm64: "Linux arm64 リリースパッケージのコンソール更新は、実機で検証するまで無効です。新しいパッケージをダウンロードして手動で置き換えてください。",
updateChecksumNotice: "SHA256SUMS.txt は整合性確認用のチェックサムであり、デジタル署名ではありません。",
updateBlockedUnavailable: "このインスタンスではコンソール更新が有効になっていません。", updateTaskTitle: "更新タスク",
updateStatusDownloading: "ダウンロード中", updateStatusVerifying: "検証中", updateStatusExtracting: "展開中", updateStatusStaging: "ステージング中",
updateStatusRestarting: "再起動中", updateStatusSucceeded: "更新成功", updateStatusFailed: "更新失敗",
updateRolledBack: "以前のバージョンに戻しました。", updateRestartHint: "更新成功後にプロセスが再起動します。ページが切断された場合はしばらくしてから再読み込みしてください。",
updateReleaseNotes: "リリースノート",
updateErrorChecksum: "チェックサムがないか一致しないため、パッケージを拒否しました。", updateErrorArchive: "パッケージは安全な展開チェックに合格しませんでした。",
updateErrorDownload: "公式リリースの資産をダウンロードまたは保存できませんでした。", updateErrorPackage: "パッケージが選択した安定版と一致しません。",
updateErrorApply: "更新に失敗しました。ログを確認してください。", updateErrorInterrupted: "完了確認前に更新が中断されました。",
updateErrorRollbackFailed: "更新に失敗し、自動ロールバックも失敗しました。バックアップから以前のバージョンを手動で復元してください。",
updateErrorSwap: "アプリケーションのファイル置き換えに失敗しました。可能な範囲で以前のバージョンに戻しました。ログを確認してください。",
updateErrorInProgress: "別の更新タスクが実行中です。", updateErrorGeneric: "更新を完了できませんでした。ログを確認してください。", updateStartedEvent: "更新を開始",
updateErrorLockFailed: "更新ロックを引き継げませんでした。ほかの更新タスクが実行中でないことを確認して再試行してください。", updateErrorUnavailable: "このインスタンスではコンソール更新が有効になっていません。",
adminWsOverviewTitle: "WebSpeak 管理を利用できます", adminWsOverviewLead: "まず接続方針と訪問者向け画面を管理します。必要な場合だけ、独立した TS 管理接続を設定します。",
adminWsManageLead: "アクセス方針、サイトのお知らせ、音声転送、スキンストア、ブラウザー接続。",
adminTsManageLead: "サーバー設定、チャンネル、メンバー、サーバーグループ、禁止リスト。専用 Query 認証情報が必要ですが、通常の音声接続には不要です。",
+30
View File
@@ -347,6 +347,12 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
exportAudioTrace: "导出最近两分钟的音频诊断",
audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。",
backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。",
backgroundCallTitle: "锁屏通话(实验性)",
backgroundCallHint: "默认关闭,下次连接生效。尝试使用系统原生语音链路;锁屏或后台通话仍受浏览器与系统限制。",
backgroundCallProcessingHint: "本次通话使用系统麦克风处理并持续开麦(可手动静音)。强降噪、输入增益、音量计、语音阈值和伴奏不可用;关闭此选项后重新连接可恢复。",
backgroundCallPending: "等待下次连接启用;需要网关与浏览器支持 WebRTC,不可用时仍使用兼容传输。",
backgroundCallNative: "系统原生语音",
backgroundCallInterrupted: "系统已暂停或结束麦克风采集。返回页面后检查权限,必要时重新连接;不会自动取消静音。",
rnnoise: "RNNoise 降噪",
echoCancellation: "回声消除",
autoGainControl: "自动增益",
@@ -779,6 +785,12 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
exportAudioTrace: "Export the last two minutes of audio diagnostics",
audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.",
backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.",
backgroundCallTitle: "Lock-screen calls (experimental)",
backgroundCallHint: "Off by default; applies on the next connection. Tries the native audio path. Browser and OS background restrictions still apply.",
backgroundCallProcessingHint: "This call uses system microphone processing with continuous transmission unless muted. Strong denoising, input gain, level meters, voice threshold and accompaniment are unavailable. Disable this option and reconnect to restore them.",
backgroundCallPending: "Waiting for the next connection. Requires browser and gateway WebRTC support; otherwise compatibility transport is used.",
backgroundCallNative: "Native system audio",
backgroundCallInterrupted: "The system paused or ended microphone capture. Return to the page, check permission and reconnect if needed. Your microphone will not be unmuted automatically.",
rnnoise: "RNNoise suppression",
echoCancellation: "Echo cancellation",
autoGainControl: "Automatic gain control",
@@ -1204,6 +1216,12 @@ webClientTranslations.de = {
exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren",
audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.",
backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.",
backgroundCallTitle: "Telefonieren bei gesperrtem Bildschirm (experimentell)",
backgroundCallHint: "Standardmäßig aus; gilt ab der nächsten Verbindung. Verwendet nach Möglichkeit den nativen Audiopfad. Browser- und Systembeschränkungen gelten weiterhin.",
backgroundCallProcessingHint: "Dieser Anruf nutzt die Mikrofonverarbeitung des Systems und sendet dauerhaft, sofern nicht stummgeschaltet. Starke Rauschunterdrückung, Eingangsverstärkung, Pegelanzeige, Sprachschwelle und Begleitung sind nicht verfügbar. Zum Wiederherstellen deaktivieren und neu verbinden.",
backgroundCallPending: "Wartet auf die nächste Verbindung. Erfordert WebRTC im Browser und Gateway; andernfalls wird der Kompatibilitätsmodus verwendet.",
backgroundCallNative: "Natives Systemaudio",
backgroundCallInterrupted: "Das System hat die Mikrofonaufnahme unterbrochen oder beendet. Zur Seite zurückkehren, Berechtigung prüfen und bei Bedarf neu verbinden. Das Mikrofon wird nicht automatisch eingeschaltet.",
rnnoise: "RNNoise-Geräuschunterdrückung",
echoCancellation: "Echounterdrückung",
autoGainControl: "Automatische Verstärkungsregelung",
@@ -1379,6 +1397,12 @@ webClientTranslations.ru = {
exportAudioTrace: "Экспортировать диагностику звука за последние две минуты",
audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.",
backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.",
backgroundCallTitle: "Звонки при блокировке экрана (эксперимент)",
backgroundCallHint: "По умолчанию выключено; применяется при следующем подключении. Использует системный аудиотракт, когда возможно. Ограничения браузера и ОС сохраняются.",
backgroundCallProcessingHint: "Используется системная обработка микрофона с непрерывной передачей, пока микрофон не выключен. Сильное шумоподавление, усиление входа, индикаторы уровня, порог голоса и аккомпанемент недоступны. Для восстановления выключите опцию и подключитесь заново.",
backgroundCallPending: "Ожидание следующего подключения. Нужна поддержка WebRTC браузером и шлюзом; иначе используется совместимый режим.",
backgroundCallNative: "Системный аудиотракт",
backgroundCallInterrupted: "Система приостановила или завершила запись. Вернитесь на страницу, проверьте разрешение и при необходимости подключитесь заново. Микрофон не включается автоматически.",
highQuality: "Качественный звук",
opusAudio: "Передача Opus с низкой задержкой",
secureJoin: "Безопасное подключение",
@@ -1598,6 +1622,12 @@ webClientTranslations.ja = {
exportAudioTrace: "直近 2 分間の音声診断をエクスポート",
audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。",
backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。",
backgroundCallTitle: "ロック画面で通話(試験機能)",
backgroundCallHint: "初期設定はオフ。次回接続時に適用されます。システムの音声経路を試しますが、ブラウザーと OS のバックグラウンド制限は適用されます。",
backgroundCallProcessingHint: "システムのマイク処理を使い、ミュートするまで連続送信します。強いノイズ抑制、入力ゲイン、レベル表示、音声しきい値、伴奏は使えません。元に戻すにはオフにして再接続してください。",
backgroundCallPending: "次回接続を待っています。ブラウザーとゲートウェイの WebRTC 対応が必要です。非対応の場合は互換モードになります。",
backgroundCallNative: "システム音声",
backgroundCallInterrupted: "システムがマイク収録を一時停止または終了しました。ページに戻り権限を確認し、必要なら再接続してください。ミュートは自動解除されません。",
highQuality: "高品質な音声",
opusAudio: "低遅延 Opus 転送",
secureJoin: "安全に参加",
-4
View File
@@ -1,7 +1,6 @@
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
import type { UpdateApplyInput } from "../../../src/shared/update.js";
import { pluginResponses, type PluginPackage, type PluginSettingsInput } from "../../../src/shared/plugins.js";
export class AdminApiError extends Error {
@@ -129,9 +128,6 @@ export function createAdminApi(options: AdminApiOptions) {
createInvite: (body: ManagedInviteInput, signal?: AbortSignal) => request("/invites", adminResponses.createdInvite, "POST", body, true, signal),
revokeInvite: (id: string, signal?: AbortSignal) => request(`/invites/${encodeURIComponent(id)}/revoke`, adminResponses.ok, "POST", {}, true, signal),
diagnostics: (signal?: AbortSignal) => request("/diagnostics", adminResponses.diagnostics, "GET", undefined, true, signal),
updateStatus: (signal?: AbortSignal) => request("/update", adminResponses.updateStatus, "GET", undefined, true, signal),
checkUpdates: (signal?: AbortSignal) => request("/update/check", adminResponses.updateCheck, "POST", {}, true, signal),
applyUpdate: (body: UpdateApplyInput, signal?: AbortSignal) => request("/update/apply", adminResponses.updateApplied, "POST", body, true, signal),
logs: (signal?: AbortSignal) => request("/logs?limit=100", adminResponses.logs, "GET", undefined, true, signal),
audit: (signal?: AbortSignal) => request("/audit?limit=50", adminResponses.audit, "GET", undefined, true, signal),
skins: (signal?: AbortSignal) => request("/skins", adminResponses.skins, "GET", undefined, true, signal),
@@ -0,0 +1,77 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { createCallMediaSession } from "./call-media-session.js";
function fixture(t: TestContext, unsupported = false) {
const original = Object.getOwnPropertyDescriptor(globalThis, "MediaMetadata");
Object.defineProperty(globalThis, "MediaMetadata", { configurable: true, value: class {
title: string;
constructor(init: { title: string }) { this.title = init.title; }
} });
t.after(() => {
if (original) Object.defineProperty(globalThis, "MediaMetadata", original);
else Reflect.deleteProperty(globalThis, "MediaMetadata");
});
const handlers = new Map<string, (() => void) | null>();
const events: string[] = [];
const session = {
metadata: null as MediaMetadata | null, playbackState: "none" as MediaSessionPlaybackState,
setActionHandler(action: string, callback: (() => void) | null) {
if (unsupported && action === "togglemicrophone") throw new Error("Not supported");
handlers.set(action, callback);
},
setMicrophoneActive(active: boolean) { events.push(`mic:${active}`); },
};
const audioSession = { type: "auto" };
const controller = createCallMediaSession({ resume: () => events.push("play"), pause: () => events.push("pause"),
toggleMicrophone: () => events.push("toggle"), hangup: () => events.push("hangup") }, { mediaSession: session as unknown as MediaSession, audioSession });
t.after(() => controller.dispose());
const sync = (active = true, muted = false) => controller.sync({ active, muted, outputMuted: false, title: "Test room" });
return { controller, handlers, events, session, audioSession, sync };
}
test("call media controls are opt-in, reflect mute, and restore OS state on release", t => {
const f = fixture(t);
f.sync(false);
assert.equal(f.handlers.size, 0);
f.sync();
assert.equal(f.audioSession.type, "play-and-record");
assert.equal(f.session.metadata?.title, "Test room");
f.handlers.get("play")!();
f.handlers.get("pause")!();
f.handlers.get("togglemicrophone")!();
f.sync(true, true);
assert.ok(f.events.includes("mic:false"));
f.sync(false);
assert.equal(f.audioSession.type, "auto");
assert.equal(f.session.metadata, null);
assert.equal(f.session.playbackState, "none");
assert.ok([...f.handlers.values()].every(value => value === null));
});
test("a queued OS action cannot affect a disconnected or replacement call", t => {
const f = fixture(t);
f.sync();
const stale = f.handlers.get("togglemicrophone")!;
f.sync(false);
f.sync();
stale();
assert.ok(!f.events.includes("toggle"));
f.handlers.get("togglemicrophone")!();
assert.equal(f.events.filter(e => e === "toggle").length, 1);
});
test("partial API support leaves the other call controls functional", t => {
const f = fixture(t, true);
assert.doesNotThrow(() => f.sync());
f.handlers.get("hangup")!();
assert.ok(f.events.includes("hangup"));
assert.equal(f.handlers.has("togglemicrophone"), false);
assert.doesNotThrow(() => f.controller.dispose());
});
test("missing system APIs never prevent calling", () => {
const controller = createCallMediaSession({ resume() {}, pause() {}, toggleMicrophone() {}, hangup() {} }, {});
assert.doesNotThrow(() => controller.sync({ active: true, muted: false, outputMuted: false, title: "Room" }));
assert.doesNotThrow(() => controller.dispose());
});
+75
View File
@@ -0,0 +1,75 @@
interface CallSnapshot { active: boolean; muted: boolean; outputMuted: boolean; title: string }
interface AudioSession { type: string }
type CallAction = MediaSessionAction | "hangup" | "togglemicrophone";
type CallNavigator = Pick<Navigator, "mediaSession"> & { audioSession?: AudioSession };
interface CallActions {
resume(): void;
pause(): void;
toggleMicrophone(): void;
hangup(): void;
}
/** Optional OS integration, never a keepalive or permission to restart capture. */
export function createCallMediaSession(actions: CallActions, target: Partial<CallNavigator> = navigator) {
let active = false;
let generation = 0;
let metadata: MediaMetadata | null = null;
let oldMetadata: MediaMetadata | null = null;
let oldPlayback: MediaSessionPlaybackState = "none";
let oldAudioType: string | undefined;
const installed: CallAction[] = [];
const safely = (operation: () => void) => { try { operation(); } catch { /* platform may only implement part of the API */ } };
function stop(): void {
if (!active) return;
active = false;
generation++;
const session = target.mediaSession;
safely(() => (session as (MediaSession & { setMicrophoneActive?: (active: boolean) => void }) | undefined)?.setMicrophoneActive?.(false));
for (const action of installed.splice(0)) safely(() => session?.setActionHandler(action as MediaSessionAction, null));
if (session && session.metadata === metadata) {
safely(() => { session.metadata = oldMetadata; session.playbackState = oldPlayback; });
}
safely(() => {
if (target.audioSession?.type === "play-and-record" && oldAudioType !== undefined) target.audioSession.type = oldAudioType;
});
metadata = null;
}
return {
sync(snapshot: CallSnapshot): void {
if (!snapshot.active) { stop(); return; }
const session = target.mediaSession;
if (!active) {
active = true;
const currentGeneration = ++generation;
oldMetadata = session?.metadata ?? null;
oldPlayback = session?.playbackState ?? "none";
safely(() => {
oldAudioType = target.audioSession?.type;
if (target.audioSession) target.audioSession.type = "play-and-record";
});
if (session) {
const handlers: Partial<Record<CallAction, () => void>> = {
play: actions.resume, pause: actions.pause,
stop: actions.hangup, hangup: actions.hangup, togglemicrophone: actions.toggleMicrophone,
};
for (const [action, handler] of Object.entries(handlers)) safely(() => {
session.setActionHandler(action as MediaSessionAction, () => { if (active && generation === currentGeneration) handler(); });
installed.push(action as CallAction);
});
}
}
if (!session) return;
safely(() => {
if (!metadata || metadata.title !== snapshot.title) {
metadata = new MediaMetadata({ title: snapshot.title, artist: "WebSpeak" });
session.metadata = metadata;
}
session.playbackState = snapshot.outputMuted ? "paused" : "playing";
});
safely(() => (session as MediaSession & { setMicrophoneActive?: (active: boolean) => void }).setMicrophoneActive?.(!snapshot.muted));
},
dispose: stop,
};
}
+1
View File
@@ -145,6 +145,7 @@ export interface LocalPreferences {
theme?: "system" | "light" | "dark";
skinId?: string;
microphoneMuted?: boolean;
backgroundCallEnabled?: boolean;
noiseSuppressionEnabled?: boolean;
noiseSuppressionLevel?: "off" | "standard" | "strong";
voxThreshold?: number;
+9 -1
View File
@@ -1048,6 +1048,10 @@ const {
serverEvents,
pokeNotifications,
microphoneMuted,
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
noiseSuppressionEnabled,
noiseSuppressionLevel,
inputVolume,
@@ -1302,8 +1306,12 @@ function reconnectMobile(): void {
reconnectNow();
}
const { toggleMicrophone, stopWhisperTalk } = audioControls;
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive };
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive };
const audioSettingsState = {
backgroundCallEnabled,
backgroundCallActive,
backgroundCallInterrupted,
setBackgroundCallEnabled,
inputDevices,
outputDevices,
selectedInputDeviceId,
+1 -1
View File
@@ -1,4 +1,4 @@
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio";
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio" | "backgroundMode";
interface AccompanimentTarget {
setAccompaniment(stream: MediaStream | null): void;
+28
View File
@@ -0,0 +1,28 @@
import type { MicrophoneCapture } from "./microphone-capture.js";
/** Native browser processing only: no RNNoise, PCM worklet, analyser or gain graph. */
export function createNativeMicrophoneCapture(stream: MediaStream): MicrophoneCapture {
const track = stream.getAudioTracks()[0];
if (!track || track.readyState !== "live") throw new DOMException("No live microphone", "NotReadableError");
const settings = track.getSettings();
let disposed = false;
return {
processedStream: stream,
processing: {
echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null,
noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null,
autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null,
rnnoise: false,
},
activate() {},
setVolume() {},
stopCapture() {},
dispose() {
if (disposed) return;
disposed = true;
for (const item of stream.getTracks()) {
try { item.stop(); } catch { /* release the other tracks too */ }
}
},
};
}
+17
View File
@@ -5,6 +5,23 @@ export interface WebRtcInput {
dispose(): void;
}
/** The capture owner releases this stream; no Web Audio graph or clone owns it. */
export function createNativeWebRtcInput(stream: MediaStream, volume: number): WebRtcInput {
const track = stream.getAudioTracks()[0];
if (!track || track.readyState !== "live") throw new Error("No live native microphone track");
let disposed = false;
const setVolume = (value: number) => { if (!disposed) track.enabled = value > 0; };
setVolume(volume);
return {
stream,
setVolume,
setAccompaniment(source) {
if (source) throw new DOMException("Native call input does not mix accompaniment", "NotSupportedError");
},
dispose() { disposed = true; },
};
}
// Own only the mixing nodes and their output. Capture controllers own the input
// streams. Keep the sender track alive when accompaniment starts/stops/changes.
export function createWebRtcInput(context: AudioContext, microphone: MediaStream, volume: number): WebRtcInput {
+4 -1
View File
@@ -58,7 +58,9 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
const task = (async () => {
const context = options.context();
if (context?.state === "suspended") {
try { await context.resume(); } catch { /* a real user gesture may still be required */ }
// Capture may never resume while locked. Native remote playback must
// not wait on that independent graph, including on a retry gesture.
try { void context.resume().catch(() => undefined); } catch { /* retry on a user gesture */ }
}
if (!isCurrent(record)) return;
try {
@@ -108,6 +110,7 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
return {
attach, stop,
resume(): void { if (current) void play(current); },
get output(): SinkAudioElement | null { return current?.output ?? null; },
setVolume(value: number): void { if (current) current.output.volume = value; },
};
+6 -4
View File
@@ -1,11 +1,11 @@
import { isSessionDescription, type WebRtcClientMessage } from "../../../src/shared/webrtc.js";
import { createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
import { createNativeWebRtcInput, createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
import { createMicrophoneMeter, type MicrophoneMeter } from "./microphone-meter.js";
import { createWebRtcPlayback, type WebRtcPlaybackOptions } from "./webrtc-playback.js";
import { addOpusFmtpParameters } from "../../../src/shared/opus-sdp.js";
interface Microphone {
context: AudioContext;
context: AudioContext | null;
stream: MediaStream;
processedStream: MediaStream;
}
@@ -134,7 +134,8 @@ export function createWebRtcTransport(options: TransportOptions) {
const peer = new RTCPeerConnection({ iceServers: stunServer ? [{ urls: stunServer }] : [] });
record.peer = peer;
track.enabled = !options.muted();
const input = createWebRtcInput(context, processedStream, options.muted() ? 0 : options.inputVolume());
const volume = options.muted() ? 0 : options.inputVolume();
const input = context ? createWebRtcInput(context, processedStream, volume) : createNativeWebRtcInput(stream, volume);
record.input = input;
peer.addTrack(input.stream.getAudioTracks()[0]!, input.stream);
peer.ontrack = event => {
@@ -142,7 +143,7 @@ export function createWebRtcTransport(options: TransportOptions) {
try { playback.attach(event.streams[0] ?? new MediaStream([event.track])); }
catch { void fail(record, "WEBRTC_PLAYBACK_FAILED"); }
};
record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
if (context) record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
peer.onconnectionstatechange = () => {
options.onConnectionState?.(peer.connectionState);
if (isCurrent(record) && peer.connectionState === "failed") void fail(record, "WEBRTC_CONNECTION_FAILED");
@@ -196,5 +197,6 @@ export function createWebRtcTransport(options: TransportOptions) {
get active(): boolean { return current?.active ?? false; },
get output() { return playback.output; },
setOutputVolume: playback.setVolume,
resumePlayback: playback.resume,
};
}
-52
View File
@@ -45,7 +45,6 @@ const defaults = path => ({
"/session": { authenticated: true, mustChangePassword: false, csrfToken: "test-csrf" },
"/server": settings(), "/overview": overview, "/sessions": { sessions: [] }, "/invites": { invites: [] },
"/diagnostics": { gateway: { version: "test", node: "test", platform: "test", arch: "test" }, database: { schemaVersion: 1 }, sessions: { created: 0 } },
"/update": { currentVersion: "test", deployment: { mode: "source", platform: "test", architecture: "test", applyAllowed: false, reasonCode: "DEPLOYMENT_SOURCE", upgradePath: "source" }, task: null },
"/logs?limit=100": { available: false, entries: [], sessions: [] }, "/audit?limit=50": { events: [] },
"/skins": { skins: [], defaultSkinId: "builtin.light" },
"/ts-admin/settings": tsSettings(), "/ts-admin/overview": tsOverview(),
@@ -454,15 +453,6 @@ test("store install submits the reviewed revision once and reloads the instance
});
function manifestForStoreTest() { return { id: "store-test", name: "Fixture", version: "1.0.0", author: "Fixture", license: "MIT", minAppVersion: "0.2.8", installedAt: 1 }; }
test("all update maintenance copy is explicit in each supported language", async () => {
const { adminOrganizationCopy } = await vite.ssrLoadModule("/src/i18n/admin-organization.ts");
const keys = Object.keys(adminOrganizationCopy.zh).filter(key => key.startsWith("update")).sort();
assert.ok(keys.length >= 30);
for (const language of ["zh", "en", "de", "ru", "ja"]) {
for (const key of keys) assert.ok(adminOrganizationCopy[language][key]?.trim(), `${language}.${key}`);
}
});
test("all store translations are explicit in each supported language", async () => {
const { skinStoreCopy } = await vite.ssrLoadModule("/src/i18n/skin-store.ts");
const keys = Object.keys(skinStoreCopy.zh).sort();
@@ -725,48 +715,6 @@ test("settings and operations render explicit localized sections with valid deep
}
});
test("check-only deployments retain release checks and notes without install controls", async () => {
const { createSSRApp } = await import("vue");
const { renderToString } = await import("vue/server-renderer");
const { default: Operations } = await vite.ssrLoadModule("/src/components/admin/AdminOperations.vue");
await mount("/admin/operations?section=maintenance");
const model = reactive(state.adminOperations);
for (const [mode, reasonCode] of [["source", "DEPLOYMENT_SOURCE"], ["docker", "DEPLOYMENT_DOCKER"],
["release-package", "WINDOWS_APPLY_UNVERIFIED"], ["release-package", "LINUX_ARM64_APPLY_UNVERIFIED"], ["release-package", "DEPLOYMENT_SUPERVISED"]]) {
model.operations.update.deployment = { mode, platform: "linux", architecture: "x64", applyAllowed: false, reasonCode, upgradePath: "release-package" };
let checked = false;
handler = path => {
assert.equal(path, "/update/check"); checked = true;
return Promise.resolve(json({ currentVersion: "0.3.2", releases: [{ version: "0.4.0", canApply: false, blockedReason: reasonCode,
tag: "v0.4.0", assetName: "webspeak-webclient-v0.4.0-linux-x64.tar.gz", assetSize: 100,
assetAvailable: true, hasChecksums: true, digest: null,
publishedAt: "2026-11-25T00:00:00.000Z", releaseUrl: "https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.4.0" }] }));
};
await model.checkForUpdates();
assert.equal(checked, true);
assert.equal(state.errorMessage, "");
const html = await renderToString(createSSRApp(Operations, { model: state.adminOperations, i18n: state.i18n, initialSection: "maintenance" }));
assert.ok(html.includes(state.i18n.tr("updateCheckAction")), reasonCode);
assert.ok(html.includes("/releases/tag/v0.4.0"), reasonCode);
assert.ok(html.includes('data-admin-update="check"'), reasonCode);
assert.ok(!html.includes('data-admin-update="apply"'), reasonCode);
if (reasonCode === "DEPLOYMENT_SUPERVISED") assert.ok(html.includes(state.i18n.tr("updateBlockedSupervised")));
}
});
test("update error codes resolve to their dedicated five-language labels", async () => {
const { adminOrganizationCopy } = await vite.ssrLoadModule("/src/i18n/admin-organization.ts");
await mount("/admin/server");
for (const language of ["zh", "en", "de", "ru", "ja"]) {
state.language = language;
const copy = adminOrganizationCopy[language];
assert.equal(state.i18n.errorText("UPDATE_LOCK_FAILED"), copy.updateErrorLockFailed);
assert.equal(state.i18n.errorText("UPDATE_UNAVAILABLE"), copy.updateErrorUnavailable);
assert.equal(state.i18n.errorText("UPDATE_RESTART_UNAVAILABLE"), copy.updateErrorUnavailable);
assert.notEqual(state.i18n.errorText("UPDATE_LOCK_FAILED"), copy.updateErrorGeneric);
}
});
test("loading saved custom Query ports never treats them as unsaved transport defaults", async () => {
for (const [transport, queryPort] of [["ssh", 10011], ["tcp", 10022]]) {
+163 -1
View File
@@ -156,6 +156,7 @@ let useWebClientChat;
let useWebClientChannels;
let webClientTranslations;
let voice;
let voiceScope;
const savedGlobals = new Map();
function replaceGlobal(name, value) {
if (!savedGlobals.has(name)) savedGlobals.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
@@ -224,12 +225,14 @@ beforeEach(() => {
getUserMedia: async () => microphoneStream(),
enumerateDevices: async () => [],
} });
voice = useVoiceWebSocket();
voiceScope = effectScope();
voice = voiceScope.run(() => useVoiceWebSocket());
});
afterEach(() => {
voice?.stopMicrophoneTest();
voice?.disconnect();
voiceScope?.stop();
for (const timer of browserTimers) clearTimeout(timer);
browserTimers.clear();
});
@@ -733,6 +736,165 @@ async function connectWebRtc() {
return { socket, peer: TestPeer.instances.at(-1) };
}
test("experimental calls send the native mic without creating a Web Audio graph and preserve mute", async () => {
const stream = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => stream;
assert.equal(voice.backgroundCallEnabled.value, false);
voice.setBackgroundCallEnabled(true);
const { peer, socket } = await connectWebRtc();
assert.equal(voice.backgroundCallActive.value, true);
assert.equal(peer.sender.track, stream.track);
assert.equal(AudioContextStub.instances.length, 0);
assert.equal(voice.microphoneProcessing.rnnoise, false);
voice.setMicrophoneMuted(true);
assert.equal(stream.track.enabled, false);
assert.ok(socket.messages.some(m => m.type === "setMicrophoneMuted" && m.payload.muted));
voice.setMicrophoneMuted(false);
assert.equal(stream.track.enabled, true);
await assert.rejects(voice.startAccompaniment(), /unavailable/);
assert.equal(voice.accompanimentErrorCode.value, "backgroundMode");
voice.disconnect();
assert.equal(stream.track.readyState, "ended");
assert.equal(peer.connectionState, "closed");
assert.equal(voice.backgroundCallActive.value, false);
});
test("changing the experiment applies only to the next connection", async () => {
await connectWebRtc();
voice.setBackgroundCallEnabled(true);
assert.equal(voice.backgroundCallActive.value, false);
const { peer } = await connectWebRtc();
const track = peer.sender.track;
voice.setBackgroundCallEnabled(false);
assert.equal(voice.backgroundCallActive.value, true);
assert.equal(track.readyState, "live");
await connectWebRtc();
assert.equal(voice.backgroundCallActive.value, false);
});
test("native input at zero gain stays silent and scope disposal releases the microphone", async () => {
voice.setBackgroundCallEnabled(true);
voice.setInputVolume(0);
const { peer } = await connectWebRtc();
assert.equal(peer.sender.track.enabled, false);
voice.setMicrophoneMuted(true);
voice.setMicrophoneMuted(false);
assert.equal(peer.sender.track.enabled, false, "unmute must preserve a zero input level");
voiceScope.stop();
assert.equal(peer.sender.track.readyState, "ended");
assert.equal(peer.connectionState, "closed");
});
test("native system microphone interruption is reported without changing user mute", async () => {
voice.setBackgroundCallEnabled(true);
const { peer } = await connectWebRtc();
const track = peer.sender.track;
track.muted = true;
track.dispatchEvent(new Event("mute"));
assert.equal(voice.backgroundCallInterrupted.value, true);
voice.setMicrophoneMuted(true);
track.muted = false;
track.dispatchEvent(new Event("unmute"));
assert.equal(voice.backgroundCallInterrupted.value, false);
assert.equal(voice.microphoneMuted.value, true);
assert.equal(track.enabled, false);
});
test("an experimental connection replaces a processing preview still waiting on permission", async () => {
const permission = deferred();
const preview = microphoneStream();
const native = microphoneStream();
let requests = 0;
navigator.mediaDevices.getUserMedia = () => ++requests === 1 ? permission.promise : Promise.resolve(native);
const preparation = voice.prepareInputDevices();
voice.setBackgroundCallEnabled(true);
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
permission.resolve(preview);
await preparation.catch(() => {});
await nextTurn();
assert.equal(preview.track.readyState, "ended");
assert.equal(TestPeer.instances.at(-1).sender.track, native.track);
assert.equal(voice.backgroundCallActive.value, true);
});
test("native mode falls back to processed PCM after WebRTC failure", async () => {
const streams = [];
navigator.mediaDevices.getUserMedia = async () => { const stream = microphoneStream(); streams.push(stream); return stream; };
voice.setBackgroundCallEnabled(true);
const { peer } = await connectWebRtc();
peer.connectionState = "failed";
peer.onconnectionstatechange();
await nextTurn();
assert.equal(voice.backgroundCallActive.value, false);
assert.equal(streams[0].track.readyState, "ended");
assert.equal(streams.at(-1).track.readyState, "live");
assert.ok(AudioContextStub.processors.length > 0);
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
});
test("a gateway without WebRTC keeps compatibility capture with the experiment enabled", async () => {
voice.setBackgroundCallEnabled(true);
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
assert.equal(voice.backgroundCallActive.value, false);
assert.ok(AudioContextStub.processors.length > 0);
assert.equal(TestPeer.instances.length, 0);
});
test("disconnect retires a pending native microphone permission request", async () => {
const pending = deferred();
navigator.mediaDevices.getUserMedia = () => pending.promise;
voice.setBackgroundCallEnabled(true);
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
await nextTurn();
voice.disconnect();
const stream = microphoneStream();
pending.resolve(stream);
await nextTurn();
assert.equal(stream.track.readyState, "ended");
assert.equal(TestPeer.instances.length, 0);
assert.equal(voice.backgroundCallActive.value, false);
});
test("native remote playback does not wait for a suspended capture context to resume", async () => {
const { peer } = await connectWebRtc();
const context = AudioContextStub.instances.at(-1);
context.state = "suspended";
context.resume = () => new Promise(() => {});
let plays = 0;
const output = new TestAudioElement();
output.play = async () => { plays++; };
document.createElement = () => output;
peer.ontrack({ streams: [microphoneStream()] });
await nextTurn();
assert.equal(plays, 1);
});
test("OS playback resume and page restoration never unmute a native call", async () => {
const handlers = new Map();
navigator.mediaSession = { metadata: null, playbackState: "none", setActionHandler: (action, handler) => handlers.set(action, handler) };
navigator.audioSession = { type: "auto" };
voice.setBackgroundCallEnabled(true);
const { peer } = await connectWebRtc();
handlers.get("pause")();
await nextTurn();
assert.equal(peer.sender.track.enabled, false);
handlers.get("play")();
document.visibilityState = "visible";
document.dispatchEvent(new Event("visibilitychange"));
await nextTurn();
assert.equal(voice.microphoneMuted.value, true);
assert.equal(peer.sender.track.enabled, false);
handlers.get("togglemicrophone")();
assert.equal(peer.sender.track.enabled, true);
handlers.get("hangup")();
assert.equal(peer.connectionState, "closed");
assert.equal(navigator.audioSession.type, "auto");
});
function enableMicrophoneMeter(t) {
const analysers = [];
const intervals = [];