mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a12e2ee7b | ||
|
|
3e4be94ae7 | ||
|
|
3339d09936 | ||
|
|
462bab57d2 | ||
|
|
6bbc292056 | ||
|
|
e3c71f07b1 | ||
|
|
cf1cc9fb94 | ||
|
|
6273185afa | ||
|
|
0bc2e6cec8 | ||
|
|
82b58dbd61 | ||
|
|
699e606da5 | ||
|
|
eb6c4ba857 | ||
|
|
2de2e23fd3 | ||
|
|
ae6788a796 | ||
|
|
9812a28e5f | ||
|
|
cc36bc4c64 | ||
|
|
8ca33fd77d | ||
|
|
99d7b86d09 | ||
|
|
2b019d82ff | ||
|
|
e46d7a0eb7 | ||
|
|
0df25e4892 | ||
|
|
a353c32892 | ||
|
|
c1187d12d2 | ||
|
|
93d221c3ef | ||
|
|
aefa0bc163 | ||
|
|
fa720bf260 | ||
|
|
a4ae4de82f | ||
|
|
a84f66b47d | ||
|
|
af1d1f8a88 | ||
|
|
2cb8b8d161 | ||
|
|
12a37fc26f | ||
|
|
f20a372f4b | ||
|
|
15ca32b7a8 | ||
|
|
274bd81dc3 | ||
|
|
6a35d9be3d | ||
|
|
ed752a5a6f | ||
|
|
9012448544 | ||
|
|
a5cf3eeb0c | ||
|
|
e82116239a | ||
|
|
f8d61d22ef | ||
|
|
72d7e6e013 | ||
|
|
33ba062686 | ||
|
|
7cc43bb336 | ||
|
|
42d15c6d32 | ||
|
|
360126b14f | ||
|
|
047a40ac4b | ||
|
|
3430a8a753 | ||
|
|
275e27c4ac | ||
|
|
37f5b86b52 | ||
|
|
8bca848c21 | ||
|
|
ce681f749d |
No files matched your search
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: webspeak-plugin-development
|
||||
description: Build, review and package WebSpeak API v2 applications with standard browser code and optional Node services, and automatically submit completed releases to the official catalog by pull request. Use for .wplugin applications rather than .wskin skins.
|
||||
---
|
||||
|
||||
# WebSpeak Application Development
|
||||
|
||||
Read the current [application runtime guide](../../../docs/PLUGIN_DEVELOPMENT.md). In a standalone checkout, use `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/PLUGIN_DEVELOPMENT.md`. Require WebSpeak v0.3.0 or later for API v2. API v1 and its shared-room examples are removed.
|
||||
|
||||
Develop an independent application, not a list of host business RPC calls. Use ordinary HTML/CSS/JavaScript, browser APIs and optional Node services with author-defined routes, dependencies and state. The host provides authenticated context, configuration, package/lifecycle management and a separate origin. It supplies no room API or feature permission list. Keep application business logic in its package; a host defect or missing general runtime primitive is a separate host change.
|
||||
|
||||
Start with `docs/templates/plugin-app/` or the distribution repository's `template/`. Put frontend output under `client/` with relative assets and optional `.mjs/.cjs` activation code under `server/`. Include audited dependencies or bundle them; the host does not run package installers. Native dependencies must match target OS and Node ABI. Build with `node scripts/build-plugin.mjs SOURCE_DIR OUTPUT.wplugin`, or the standalone distribution builder, then import the actual output.
|
||||
|
||||
Use `webspeak.ready`, `getContext()`, `onContextChange()` and `signal` for generic context; implement functionality through native browser/Node code. Scope provides admission and a grouping key, not synchronization. Server logic must enforce scope and business access. Prefer host-verified `req.webspeak` over browser-supplied identities or channels. Temporary runtime URLs are credentials: do not persist, broadcast or log them. Backend private configuration is encrypted at rest and omitted from admin reads; public configuration is user-visible.
|
||||
|
||||
Treat applications as trusted code. Node services have the WebSpeak OS account's privileges; process separation and heap limits are not a hostile-code sandbox. Frontends use a separate origin with standard browser capabilities. Browser permission, secure-context, user-gesture, CORS and network requirements apply. The shared application origin does not isolate mutually hostile plugins. Explain these boundaries accurately and review dependencies rather than inventing host feature permissions.
|
||||
|
||||
Provide responsive light/dark styles and suitable language handling using context. Keep UI in the application panel without relying on skin DOM. Clean timers, subscriptions, media and sockets on exit/revocation. Persist backend state in `dataDir`, never extracted code directories. Implement concurrency and atomic writes appropriate to the application.
|
||||
|
||||
Verify import, trust, enable, update, failure/restart, custom routes, persistence and revocation. Collaborative apps need two real browser participants and late-join/concurrent-change/channel-boundary/disconnect tests. Distinguish mocked HTTP, actual processes, browser interactions and independent networks. Claim only demonstrated capabilities. Keep credentials and diagnostics out of artifacts.
|
||||
|
||||
After completing development and verification, automatically finish the distribution workflow below; do not stop at a local archive or ask the user to submit it later. Honor explicit local-only/no-push instructions. Review-only, inspection and planning tasks do not trigger publishing. This workflow does not authorize deployment or automatic merging.
|
||||
|
||||
## Administrator configuration
|
||||
|
||||
- Document each supported field in the plugin repository with its key, input type, required status, default and accepted range or choices. Provide a copyable `config.example.json` with separate `config` (public) and `serverConfig` (private) objects. Mark placeholder credentials and explain where administrators obtain them. Use defaults for optional keys and validate the actual values in the plugin.
|
||||
- The 0.3.2 admin console has a generic typed editor for objects, lists and primitive values. P2P File Transfer, Watch Together and TSMusicBot have dedicated forms in the admin frontend. A repository example is documentation and does not register a custom form automatically. Keep app-specific form behavior out of the runtime, registry and package validation.
|
||||
- Verify setting, saving and reloading a configuration in `/admin/plugins`. Test that secret values are masked in inputs and omitted from admin reads, and that keeping a saved secret does not require re-entry. P2P File Transfer exposes `maxFileMiB` and optional `iceServers`. TURN credentials sent to authorized browsers must be client credentials. Watch Together exposes `control` (`everyone` or `host`) and has no private settings.
|
||||
|
||||
## Public runtime deployment
|
||||
|
||||
A public gateway needs a separate HTTPS origin for apps. Set it in **Plugins → Application runtime** (persisted setting takes precedence) or with `WEBSPEAK_PLUGIN_PUBLIC_ORIGIN`. Proxy that origin to the plugin listener (port `3042` by default), preserving WebSocket upgrades and unbuffered SSE. Loopback development can use the built-in alternate host. If every app reports `PLUGIN_PUBLIC_ORIGIN_REQUIRED`, check the gateway origin setting, DNS, certificate and proxy before rebuilding packages. Verify by opening a real app in a connected voice room and checking that the iframe loads from the configured origin. A bare GET to the origin can return `PLUGIN_NOT_OPEN`; opening an app creates the scoped URL.
|
||||
|
||||
## Automatic distribution PR
|
||||
|
||||
1. Read the current [application catalog](https://github.com/Huddle-Up-Forge/webspeak-plugin), its default branch, contribution rules, `index.json`, JSON schema, validators and any PR template. Follow the actual repository contract.
|
||||
2. Maintain source, license, dependencies, build instructions, tests and `.wplugin` in an independent public application repository. Use the task's selected destination; ask only for a genuinely missing owner/name when it cannot be discovered. Commit and push the final package first, then generate and publish default-branch `plugin.json` with the complete API v2 `manifest` and `package.ref/path/sha256`. The catalog requires a full 40-character package commit SHA, not a branch, mutable label, future commit or self-reference. Hash the raw package bytes and follow the catalog's manifest checks. WebSpeak 0.3.2 compares the ID, version, scope set and entry points after API v2 and package validation. Display name, description, author and license may differ at install time. Keep that information accurate and run the catalog's own checks before submission.
|
||||
3. Fetch the public metadata and pinned package, check identity/manifest/hash and real import, then run the catalog's current checks (currently `npm run verify` and `npm run verify:remote`). Fix failures before marking the submission ready. Bundle audited dependencies in the application package. Never copy business code, archives, secrets or diagnostics into the catalog.
|
||||
4. For a new listing, add one `{ "id": "<plugin-id>", "repository": "https://github.com/<owner>/<repo>", "metadataPath": "plugin.json" }` under `plugins` in schema 2 `index.json`. Update an existing ID when catalog fields change; never duplicate it or edit unrelated entries. Version-only releases already discoverable through the listed metadata need no empty index PR; report their published metadata and existing listing instead.
|
||||
5. Open the PR automatically from a focused branch against the actual default branch, or from a fork if needed. Reuse an existing open PR for this contribution. Titles: `feat(plugins): add <plugin-id> v<version>` or `chore(plugins): update <plugin-id> v<version>`. Apply any existing PR template.
|
||||
|
||||
Use the catalog's PR template, or `Summary`, `Package`, `Validation` and `Preview` sections when none exists. Include purpose and ID/version; source, author/license, required WebSpeak/API version and scopes; a published UI preview; immutable package commit/path/raw URL and SHA-256; backend presence/dependencies and external configuration; and validation commands with actual results. Cover import/trust/enable/update, persistence, minimize/resume, disconnect/revocation and relevant two-participant tests. Distinguish real independent-network P2P/collaboration testing from same-host browser tests. Confirm that no credentials or temporary runtime URLs are included.
|
||||
|
||||
Return and attach the real PR URL when supported, with validation results. Do not auto-merge. If authentication or repository policy blocks submission, retain the reviewable branch/diff, identify the precise blocker and request only what is missing; do not substitute a generic permission question or claim success without a submitted PR.
|
||||
|
||||
## Host launcher and application window
|
||||
|
||||
WebSpeak owns the launcher, library, pinning and non-modal app window. In 0.3.2 a skin can place the host launcher in a toolbar or sidebar with `voice.plugin-launcher`. The host falls back to its library entry for layouts without a usable slot. The app uses the same iframe and lifecycle contract in all layouts. Apps render their responsive light/dark UI inside the supplied iframe; the host supplies dragging, minimize/maximize/restore and close controls. The host window uses the standard `color-scheme` for its light/dark fallback without inheriting skin component styles. Do not duplicate host window chrome or block the workspace with a page-wide modal backdrop.
|
||||
|
||||
Minimizing or switching to the library retains the same iframe and app session. Transfers and playback must survive those actions. Closing the window, replacing the active app or host context revocation ends that session; only one frontend app is currently hosted at a time. Do not equate a hidden iframe with app exit. Verify resize, narrow screens, theme changes, minimize/resume without reload and close/revocation cleanup. Keep the user-facing window focused on functionality and actionable status; omit repeated runtime/permission disclaimers. Administrator trust and security review remain part of enablement.
|
||||
|
||||
## Instance authorization
|
||||
|
||||
The public host asks once per browser origin for third-party skins and functional applications together. No decision or refusal allows only Day, Night and ILLUSIA; KAAK also requires consent. The last item in the skin menu reopens this setting. Revocation must close/revoke the active frontend application while preserving independently enabled backend services. Do not add per-app copies of the same host authorization prompt, bypass the host gate or confuse this user decision with administrator package trust or browser-native permission prompts.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "WebSpeak Plugin Development"
|
||||
short_description: "Build portable WebSpeak functional plugins"
|
||||
default_prompt: "Use $webspeak-plugin-development to build and verify a portable WebSpeak plugin."
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: webspeak-skin-development
|
||||
description: Develop, review, package, or validate portable WebSpeak .wskin skins. Keep skin UI and implementation inside the package and use only released runtime APIs.
|
||||
description: Develop, review, package, or validate portable WebSpeak .wskin skins, and automatically submit completed releases to the official catalog by pull request. Keep implementation inside the package and use released runtime APIs.
|
||||
metadata:
|
||||
short-description: Develop portable WebSpeak skins
|
||||
---
|
||||
@@ -11,6 +11,8 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
|
||||
|
||||
## Workflow
|
||||
|
||||
When a WebSpeak checkout is unavailable, read the [published skin guide](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/SKIN_DEVELOPMENT.md) and its examples.
|
||||
|
||||
1. Locate the `webspeak-webclient` repository root, then read the single current contract and workflow in `docs/SKIN_DEVELOPMENT.md`. It covers package schemas, runtime data, permissions, actions, security boundaries, and validation. If a request needs an undocumented capability, identify the missing public contract before editing and treat that work as a separate platform change. Inspect the closest example under `docs/examples/`; do not copy unrelated product-specific content.
|
||||
2. Choose the least complex supported package format that can express the request: CSS/assets for appearance, `content.json` for localized copy, `layout.json` for author defaults, `components.json` for declarative structure and supported interactions, and the documented v4 Wasm plugin path only when local logic is required. JavaScript files in a package are not executed by the current runtime.
|
||||
3. Keep all skin-authored implementation in the package. Use stable public skin parts, component schema, published context fields, existing host widgets, and permission-gated actions. Do not add a widget, data field, action, CSS hook, or branch to core code for one skin. If a reusable platform capability is missing, identify the exact contract gap and treat it as separate platform work: define a generic, versioned API and compatibility behavior first; only then use that released API from the package.
|
||||
@@ -18,6 +20,27 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
|
||||
5. Build the `.wskin` from its source directory while including only files declared by the manifest. Validate the finished archive with the repository importer and keep any distributable built-in archive synchronized with its example source. An example README or other undeclared file belongs beside the package, not inside it.
|
||||
6. Verify the package at the scope of the change: run the skin package and component-schema tests; run the relevant type/build checks; import the exact archive in a compatible WebSpeak runtime. Check desktop and narrow layouts, all supported interface languages, long text, keyboard focus, reduced motion, contrast, and every interaction the skin replaces. For a portability claim, install the same archive (compare its SHA-256) in two instances with the same compatible runtime/API version; do not treat a successful build alone as proof.
|
||||
|
||||
## WebSpeak 0.3.2 host controls
|
||||
|
||||
- Use component schema v3 and set `minAppVersion` to at least `0.3.2` when using `voice.plugin-launcher`. Place it once in the voice surface, inside a visible slot. Set `options.pluginPresentation` to `drawer-side` for a sidebar, `drawer-below` for a header button, or `dialog` for the default library. The built-in Day, Night and ILLUSIA skins use the header drawer. The KAAK and Discord examples use the sidebar drawer.
|
||||
- Style `voice.plugin-launcher`, `voice.plugin-drawer` and `voice.plugin-drawer.app` through the published parts. WebSpeak owns app availability, pinning, authorization and the app window. Layouts without a usable mount can fall back to the host library. In a connected, authorized voice session verify that the launcher mounts in the intended slot, that the drawer stays within desktop and narrow viewports, and that both pinned and unpinned apps open. For KAAK, verify the rail itself and check the package version served by the instance if the launcher still floats.
|
||||
- For a compact rail, `home.social-links` accepts `options.communityLinks: false` to keep the admin entry and hide community links. The admin console uses host styling. Use `chrome.json#visibleParts` only for documented host decorations. Confirm that the host-owned recovery action remains usable after applying the skin.
|
||||
- Test changes to the public home and voice surfaces with the same released archive. Check cold load for a theme flash, long translations for clipping, and live/shared media for artwork layering. Use a real voice session for interaction claims.
|
||||
|
||||
## Automatic distribution PR
|
||||
|
||||
After completing a skin development or update task and its verification, automatically finish the contribution workflow below; do not wait for another instruction to submit the validated contribution. Honor explicit local-only/no-push instructions. Review-only, inspection and planning tasks do not trigger publishing. This workflow does not authorize deployment or automatic merging.
|
||||
|
||||
1. Read the current [skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins), its default branch, `index.json`, contribution rules, and any PR template or checks that exist. Follow the actual catalog contract rather than inventing fields.
|
||||
2. Keep source, license, build instructions and the validated `.wskin` in an independent public skin repository. Use the destination selected for the task; ask only for a genuinely missing owner/name when it cannot be discovered. Commit and push the package first. Then publish default-branch `skin.json` pointing to its existing full package commit SHA/path with the SHA-256 of the exact archive bytes. Match the package ID, version and `minAppVersion` to the catalog. Keep names, author credits and licenses accurate in both places. WebSpeak 0.3.2 permits display metadata to differ, and catalog publication checks may impose additional requirements. Do not move a published package tag or make metadata reference its own not-yet-created commit.
|
||||
3. Fetch public metadata and the pinned package as the store would; verify hash, identity, version, compatibility and actual import, and run catalog checks when supplied. The catalog contains an index, not skin source or archives. Exclude credentials, captures, diagnostic reports and unrelated development documents.
|
||||
4. For a new listing, add exactly one `{ "id": "<skin-id>", "repository": "https://github.com/<owner>/<repo>" }` under `skins` in schema 1 `index.json`. Update an existing ID rather than duplicating it. Under the catalog's current policy, a version-only update is discovered through the skin repository's metadata; if there is no real catalog diff, report the published update and existing listing instead of creating an empty PR.
|
||||
5. Create a focused branch against the catalog's actual default branch, using a fork if necessary, and open the PR automatically. Reuse an existing open PR for the same contribution. Titles: `feat(skins): add <skin-id> v<version>` or `chore(skins): update <skin-id> v<version>`. Follow the repository's PR template when present.
|
||||
|
||||
Use the catalog's PR template, or `Summary`, `Package`, `Validation` and `Preview` sections when none exists. Include purpose and skin ID/version; source, author/license and minimum WebSpeak version; a published screenshot/preview; immutable package commit/path/raw URL and SHA-256; validation commands and actual results, including runtime/browser, desktop/narrow layouts and languages checked. Confirm independent installation and no duplicate ID. State material gaps without claiming unperformed tests.
|
||||
|
||||
Return the actual PR URL and validation outcome, and attach the PR to the chat when supported. If authentication or repository policy blocks submission, preserve the reviewable branch/diff, identify the concrete blocker and request only the missing destination or access. Do not claim a PR was submitted when it exists only locally, and do not auto-merge.
|
||||
|
||||
## Compatibility and truthfulness
|
||||
|
||||
- `minAppVersion` is a lower compatibility bound, not a guarantee that an older or unrelated runtime implements every API. Read the current schema and runtime documentation before using a capability.
|
||||
@@ -29,3 +52,8 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
|
||||
|
||||
- `docs/SKIN_DEVELOPMENT.md` — the single current reference for skin formats, runtime APIs, permissions, data, actions, CSS hooks, security, and QA.
|
||||
- `docs/examples/ILLUSIA-VOICE.md` and `docs/examples/OPEN-VOICE-SURFACE.md` — full skin and surface examples.
|
||||
- `docs/examples/KAAK-VOICE.md` and `docs/examples/DISCORD-VOICE.md` — complete layouts with a sidebar app library.
|
||||
|
||||
## Instance authorization
|
||||
|
||||
WebSpeak v0.3.0 replaces per-skin consent dialogs with one origin-scoped user decision covering third-party skins and functional apps. Without consent only the fixed official Day, Night and ILLUSIA skins are available; bundled KAAK also requires consent. The host skin switcher owns the final authorization item. Packages must not duplicate or bypass it. Revocation must cancel pending activation, remove third-party CSS/components and stop workers. Continue enforcing manifest permissions, credential redaction, trusted action validation and package digests internally; one-time consent does not extend the public API. See the current guide for release compatibility.
|
||||
@@ -9,7 +9,7 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.2.9
|
||||
default: 0.3.3
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -182,12 +182,9 @@ jobs:
|
||||
cp "$runtime_root/bin/node" "$package_root/runtime/node"
|
||||
cp "$runtime_root/LICENSE" "$package_root/runtime/NODE-LICENSE"
|
||||
chmod 0755 "$package_root/runtime/node"
|
||||
cat > "$package_root/start-webspeak.sh" <<'LAUNCHER'
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
cd -- "$(dirname -- "$0")"
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
LAUNCHER
|
||||
# Ship the exact launcher the self-update installer and recovery
|
||||
# tests use; never maintain a second launcher body in the workflow.
|
||||
cp "$GITHUB_WORKSPACE/scripts/start-webspeak.sh" "$package_root/start-webspeak.sh"
|
||||
chmod 0755 "$package_root/start-webspeak.sh"
|
||||
|
||||
smoke_root="$RUNNER_TEMP/${package_name}-smoke"
|
||||
@@ -217,7 +214,38 @@ jobs:
|
||||
grep -q '"status":"ok"' <<<"$health"
|
||||
grep -q "\"version\":\"$release_version\"" <<<"$health"
|
||||
)
|
||||
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
|
||||
# Native rebuilds can leave hard-linked objects and Python/toolchain
|
||||
# symlinks in scratch directories. Ship independent files and keep
|
||||
# build-only scratch paths out of the portable runtime archive.
|
||||
tar --hard-dereference \
|
||||
--exclude='*/@discordjs/opus/build-tmp-*' \
|
||||
--exclude='*/node_gyp_bins' \
|
||||
-czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
|
||||
# Verify the shipped tarball is accepted by the same extractor and
|
||||
# package validator used by console updates, including .bin links.
|
||||
node --input-type=module - "$GITHUB_WORKSPACE/${package_name}.tar.gz" "$RUNNER_TEMP/${package_name}-updater-check" "$release_version" <<'NODE'
|
||||
import path from 'node:path';
|
||||
import { rm } from 'node:fs/promises';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { extractReleaseArchive } from './dist/updater/archive.js';
|
||||
import { locatePackageRoot } from './dist/updater/code-swap.js';
|
||||
const [archive, destination, version] = process.argv.slice(2);
|
||||
try {
|
||||
await extractReleaseArchive(archive, destination, path.basename(archive));
|
||||
const root = locatePackageRoot(destination, version, 'linux');
|
||||
const nativeSmoke = spawnSync(path.join(root, 'runtime', 'node'), ['--input-type=commonjs', '-e', `
|
||||
const { OpusEncoder } = require('@discordjs/opus');
|
||||
const encoder = new OpusEncoder(48000, 2);
|
||||
const packet = encoder.encode(Buffer.alloc(3840));
|
||||
if (encoder.decode(packet).length !== 3840) throw new Error('Packaged Opus codec failed');
|
||||
`], { cwd: root, encoding: 'utf8', timeout: 15000 });
|
||||
if (nativeSmoke.error) throw nativeSmoke.error;
|
||||
if (nativeSmoke.status !== 0) throw new Error(nativeSmoke.stderr || 'Packaged Opus runtime failed');
|
||||
console.log(`Console updater accepts ${path.basename(archive)}`);
|
||||
} finally {
|
||||
await rm(destination, { recursive: true, force: true });
|
||||
}
|
||||
NODE
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-${{ matrix.arch }}
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ COPY --from=build --chown=node:node /app/scripts/docker-healthcheck.mjs ./script
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 3041/tcp 39087/udp 40000-40099/udp
|
||||
EXPOSE 3040/tcp 3041/tcp 3042/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["node", "scripts/docker-healthcheck.mjs"]
|
||||
|
||||
|
||||
@@ -1,105 +1,170 @@
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
|
||||
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak"><img src="./docs/assets/webspeak-banner.png" alt="WebSpeak — TeamSpeak in your browser" width="100%" /></a>
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
<p><strong>让 TeamSpeak 自然地进入浏览器。</strong></p>
|
||||
<p>A self-hosted browser voice client for TeamSpeak 3 and TeamSpeak 6.</p>
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
|
||||
[](./LICENSE)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
|
||||
<br />
|
||||
[](https://www.teamspeak.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
|
||||
<p><strong>打开浏览器,就能加入你的 TeamSpeak。</strong></p>
|
||||
<p>A self-hosted browser voice client for TeamSpeak 3 & TeamSpeak 6.</p>
|
||||
<p>
|
||||
<a href="./docs/README.zh-CN.md">简体中文文档</a> ·
|
||||
<a href="./docs/README.en.md">English documentation</a> ·
|
||||
<a href="./docs/README.de.md">Deutsche Dokumentation</a> ·
|
||||
<a href="./docs/README.ru.md">Русская документация</a> ·
|
||||
<a href="./docs/README.ja.md">日本語ドキュメント</a>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?sort=semver&display_name=tag&style=flat-square&color=0f766e" alt="Latest release" /></a>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/ci.yml"><img src="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/ci.yml/badge.svg?branch=master" alt="CI — master" /></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers"><img src="https://img.shields.io/github/stars/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&logo=github&color=0f766e" alt="GitHub stars" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="./docs/README.zh-CN.md">简体中文</a> · <a href="./docs/README.en.md">English</a> · <a href="./docs/README.de.md">Deutsch</a> · <a href="./docs/README.ru.md">Русский</a> · <a href="./docs/README.ja.md">日本語</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="#live-demo">在线演示 · Live demo</a> · <a href="#quick-start">快速部署 · Quick start</a> · <a href="#documentation">文档 · Docs</a> · <a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues">反馈 · Issues</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 项目简介 · Overview
|
||||
当前版本 / 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)
|
||||
|
||||
| 逻辑 | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. |
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
## 关于 WebSpeak · Overview
|
||||
|
||||
## 在线演示 · Live Demo
|
||||
WebSpeak 将 TeamSpeak 3 / TeamSpeak 6 带到浏览器:无需安装桌面客户端,即可加入语音频道、发送消息和分享屏幕。你可以自行部署网关,并通过网页后台管理服务器、访问策略、皮肤和运行数据。
|
||||
|
||||
- 上海节点 / Shanghai: <https://shanghai.webspeak.online>
|
||||
- 香港节点 / Hong Kong: <https://webspeak.online>
|
||||
Join voice channels, chat and share your screen from a browser. Deploy your own gateway and keep control of your TeamSpeak targets, access policy, skins and data through the web administration console.
|
||||
|
||||
| 能力 · Capability | 说明 · Highlights |
|
||||
| --- | --- |
|
||||
| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、降噪与成员音量 / Opus, optional WebRTC, fallback, noise suppression and per-member volume |
|
||||
| 💬 频道与聊天 · Channels & chat | 实时频道树、成员状态、私聊与本地历史 / Live channel tree, member state, private chat and local history |
|
||||
| 🖥️ 屏幕共享 · Screen sharing | 浏览器之间及与受支持的 TS6 客户端互通 / Between browsers and supported native TS6 clients |
|
||||
| 🎨 皮肤 · Skins | `.wskin` 外观、布局和小组件,支持 GitHub 分发 / Portable appearance, layouts and widgets, distributed through GitHub |
|
||||
| 🛠️ 管理 · Administration | 目标、邀请、中继、备份和可选 TS 管理 / Targets, invites, relays, backups and optional TS management |
|
||||
| 🌍 自托管 · Self-hosting | 五种语言、响应式界面、多架构部署 / Five languages, responsive layouts and multi-architecture deployment |
|
||||
|
||||
<a id="live-demo"></a>
|
||||
|
||||
## 在线演示 · Live demo
|
||||
|
||||
| 节点 · Region | 地址 · Address |
|
||||
| --- | --- |
|
||||
| 上海 · Shanghai | [shanghai.webspeak.online](https://shanghai.webspeak.online) |
|
||||
| 香港 · Hong Kong | [webspeak.online](https://webspeak.online) |
|
||||
|
||||

|
||||
|
||||
<details>
|
||||
<summary>更多界面与语言 · More screenshots & languages</summary>
|
||||
|
||||
- [简体中文](./docs/README.zh-CN.md#screenshots) · [English](./docs/README.en.md#screenshots) · [Deutsch](./docs/README.de.md#screenshots) · [Русский](./docs/README.ru.md#screenshots) · [日本語](./docs/README.ja.md#screenshots)
|
||||
|
||||
以下皮肤截图拍摄于已连接的 TeamSpeak 语音房间。 / The skin screenshots below were captured in a connected TeamSpeak voice room.
|
||||
|
||||
| 日间 · Day | 夜间 · Night |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||
| ILLUSIA | KAAK |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
<a id="quick-start"></a>
|
||||
|
||||
## 快速部署 · Quick start
|
||||
|
||||
在 Linux Docker 主机上运行 / On a Linux Docker host:
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
1. 打开 `http://127.0.0.1:3040/admin`,使用 `admin` / `admin` 登录并设置至少 12 位新密码。Open the console, sign in and replace the default password.
|
||||
2. 配置 TeamSpeak 目标和访问模式;公网使用 HTTPS。Set the TeamSpeak target and access mode; use HTTPS for public access.
|
||||
3. 启用 WebRTC 时放行配置的 UDP 范围,默认 `40000–40099`。Allow the configured UDP range when enabling WebRTC.
|
||||
|
||||
数据保存在 `webspeak-data` volume,升级时保留它。Docker 控制台只能检查版本;升级请在宿主机执行 `docker compose pull && docker compose up -d`,且不要执行 `docker compose down -v`。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
|
||||
|
||||
Data persists in the `webspeak-data` volume. On Docker, the console only checks versions; upgrade on the host with `docker compose pull && docker compose up -d` and never run `docker compose down -v`. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
|
||||
|
||||
<a id="documentation"></a>
|
||||
|
||||
## 文档 · Documentation
|
||||
|
||||
- [简体中文](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.zh-CN.md)
|
||||
- [English](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.en.md)
|
||||
- [Deutsch](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.de.md)
|
||||
- [Русский](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.ru.md)
|
||||
- [日本語](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.ja.md)
|
||||
- [皮肤开发指南 / Skin development guide](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/SKIN_DEVELOPMENT.md)
|
||||
- [皮肤开发 Agent Skill / Skin Development Agent Skill](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
- [皮肤开发指南 / Skin development guide](./docs/SKIN_DEVELOPMENT.md)
|
||||
- [皮肤开发 Agent Skill / Skin Development Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
|
||||
## 扩展生态 · Extensions
|
||||
|
||||
| 类型 · Type | 入口 · Resources |
|
||||
| --- | --- |
|
||||
| 皮肤包 · Skin packages | [皮肤索引 · Catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) |
|
||||
| 功能插件 · Functional plugins | [应用目录与开发起点 · Catalog & application starter](https://github.com/Huddle-Up-Forge/webspeak-plugin) · [开发指南 · Guide](./docs/PLUGIN_DEVELOPMENT.md) · [Agent Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) |
|
||||
|
||||
皮肤包负责界面、布局及其附属小组件;功能插件使用标准浏览器环境和可选 Node 后端,自行实现业务功能。功能插件 API v2 已包含在 v0.3.1 中,从语音工作区的应用库启动,支持工具栏和皮肤侧栏入口。
|
||||
|
||||
Skins own appearance, layout and attached widgets. Functional plugin API v2 is included in v0.3.1 and opens applications from the voice workspace library, available in the toolbar or a skin sidebar.
|
||||
|
||||
### 开发与收录 · Develop & contribute
|
||||
|
||||
| 扩展 · Extension | 开发 Skill · Development skill | 收录 PR · Catalog PR |
|
||||
| --- | --- | --- |
|
||||
| 皮肤及附属小组件 · Skins & attached widgets | [Skin Development Skill](./.agents/skills/webspeak-skin-development/SKILL.md) | [webspeak-skins](https://github.com/Huddle-Up-Forge/webspeak-skins) |
|
||||
| 独立功能应用 · Functional applications | [Plugin Development Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) | [webspeak-plugin](https://github.com/Huddle-Up-Forge/webspeak-plugin) |
|
||||
|
||||
使用对应 Skill 开发时,Agent 会在完成构建与验证后,发布独立仓库中的源码、包及校验元数据,并自动向相应分发仓库提交规范的收录 PR。PR 包含用途、版本与兼容性、许可证、界面预览、不可变包地址、SHA-256 和实际验证结果;完成后返回 PR 链接,交由维护者审查。已收录包的纯版本更新遵循目录的元数据更新规则,不重复添加索引或制造空 PR。
|
||||
|
||||
The skills complete the contribution workflow automatically: publish validated source, packages and integrity metadata in an independent repository, then submit a focused catalog PR with compatibility, license, preview, immutable package reference, SHA-256 and test evidence. They return the PR for maintainer review. Version-only updates follow the catalog's metadata policy instead of duplicating entries or creating empty PRs.
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
<div align="center">
|
||||
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ 群 · QQ group `869500475`](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475">
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
<details>
|
||||
<summary>QQ群二维码 · QQ group QR code</summary>
|
||||
|
||||
**QQ群 / QQ group:`869500475`**
|
||||
<p align="center"><a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475"><img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ group 869500475" width="260" /></a></p>
|
||||
|
||||
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
</details>
|
||||
|
||||
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
### 相关项目 · Related projects
|
||||
|
||||
</div>
|
||||
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — 面向 TeamSpeak 3/6 的音乐机器人,支持网易云音乐、QQ 音乐、Bilibili 和 Web 控制台。A TeamSpeak music bot with Netease Cloud Music, QQ Music, Bilibili and a web console.
|
||||
|
||||
## 友链项目 · Friend projects
|
||||
## 贡献者 · Contributors
|
||||
|
||||
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
|
||||
感谢协议 SDK 作者、代码与文档贡献者,以及独立皮肤的原始作者。Thanks to the SDK author, code and documentation contributors, and original skin authors.
|
||||
|
||||
面向 TeamSpeak 3/6 的多平台音乐点播机器人,支持网易云音乐、QQ 音乐和 Bilibili 音频播放,并提供 Web 控制台。<br />
|
||||
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
|
||||
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
|
||||
|
||||
## Contributors · 贡献者
|
||||
|
||||
感谢上游 SDK 作者及通过 PR 改进 WebSpeak 的贡献者。以下列出上游基础项目、已合并的 PR,以及已移植为独立皮肤包的原始贡献。
|
||||
<details>
|
||||
<summary>查看贡献说明 · View contribution credits</summary>
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
|
||||
- [ph1gros](https://github.com/ph1gros) — 在 [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 中报告并提供公开目标 IPv6 校验、管理员认证与会话、代理限流和 PCM 上行边界的安全审查、补丁及回归测试;相关问题由项目在 `dev` 分支重新实现并修复。[PR #46](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/46) 提供 TS3 版本识别修复及兼容性文档建议。Security findings, proposed fixes and regression tests; reimplemented on `dev`.
|
||||
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
|
||||
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
- [Jh_Harry](https://github.com/JhHarry) — [Persona 3](https://github.com/JhHarry/webspeak-skin-persona3)、[Persona 4](https://github.com/JhHarry/webspeak-skin-persona4) 和 [Persona 5](https://github.com/JhHarry/webspeak-skin-persona5) 的皮肤样式、构建脚本与打包。Theme styles, build scripts, and packaging for the three Persona skins.
|
||||
- [OddTurtleHead](https://github.com/OddTurtleHead) — [PR #57](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/57) 为皮肤开放宿主装饰的定制接口,完善独立皮肤恢复入口,并提供两套示例皮肤。Host chrome theming, a protected skin recovery control, and two example skins.
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
</details>
|
||||
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). If a modified version is offered to users over a network, its corresponding source code must be offered under AGPL-3.0.
|
||||
## 许可证 · License
|
||||
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
|
||||
WebSpeak 使用 [AGPL-3.0-only](./LICENSE) 发布。第三方依赖的许可与归属见各自项目。
|
||||
|
||||
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
|
||||
WebSpeak is distributed under [AGPL-3.0-only](./LICENSE). Third-party dependencies retain their respective licenses and attribution.
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
<details>
|
||||
<summary>Star History</summary>
|
||||
|
||||
## Star History
|
||||
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date"><img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak star history" width="100%" /></a>
|
||||
|
||||
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak Star History" width="100%" />
|
||||
</a>
|
||||
</details>
|
||||
|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
<p align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></p>
|
||||
@@ -0,0 +1,154 @@
|
||||
# WebSpeak 功能应用开发 / Functional application development
|
||||
|
||||
WebSpeak **v0.3.0** 使用应用运行时 **API v2**。`.wplugin` 与 `.wskin` 完全独立;旧 API v1、共享房间协议及其两个示例已移除,不兼容旧包。
|
||||
|
||||
插件是作者自己的应用:标准 HTML/CSS/JavaScript 前端,加上可选的 Node 后端。可以使用框架、浏览器原生 API、自己的 HTTP/WebSocket 协议、网络客户端和数据模型。宿主不提供按音乐、文件、视频等功能划分的业务 API,也不提供 `room.read/write` 或下载权限表。浏览器原有的安全上下文、用户手势、权限许可、跨域及网络可达性要求仍然适用。
|
||||
|
||||
## 管理与部署
|
||||
|
||||
管理员在 `/admin/plugins` 从 GitHub 安装或导入包,审核代码和依赖,配置作用域,勾选信任后启用。每次安装、更新均撤销信任并禁用,需要重新审核。审核是人工准入流程,校验包哈希不等于审核代码。写操作继续使用管理员认证、同源检查、CSRF 和审计。
|
||||
|
||||
**信任边界:** 前端运行在独立源,和工作台 DOM 分离,使用真实浏览器环境。Node 后端运行于独立子进程,拥有 WebSpeak 服务账户的操作系统权限,能够访问该账户可访问的网络和文件。独立进程、目录和 JS 堆上限用于生命周期与故障控制,不是恶意代码安全沙箱。仅安装审核且信任的应用。
|
||||
|
||||
运行时默认监听 `0.0.0.0:3042`:
|
||||
|
||||
| 环境变量 | 用途 |
|
||||
| --- | --- |
|
||||
| `WEBSPEAK_PLUGIN_PORT` | 应用端口,默认 3042 |
|
||||
| `WEBSPEAK_PLUGIN_HOST` | 监听地址,默认 0.0.0.0 |
|
||||
| `WEBSPEAK_PLUGIN_PUBLIC_ORIGIN` | 初始公开源,例如 `https://apps.example.com` |
|
||||
|
||||
本地工作台为 `127.0.0.1` 时自动使用 `localhost:3042`,反向亦然,以保持源分离。公网部署必须给应用配置独立 HTTPS 源,在管理页“应用运行时”保存;该设置优先于环境变量。代理应将该源的全部路径转发至应用端口,支持 WebSocket 升级和 SSE 长连接,关闭 SSE 缓冲。不要让代理记录 `/apps/…` 中的访问凭证,也不要与主站共用域 Cookie。
|
||||
|
||||
```caddyfile
|
||||
apps.example.com {
|
||||
reverse_proxy 127.0.0.1:3042
|
||||
}
|
||||
```
|
||||
|
||||
容器需映射应用端口,或让代理接入相同容器网络。端口/监听地址改变需重启;公开源可在后台更新,会撤销已有应用会话。主站直接使用 TLS 时,运行端口使用相同证书;TLS 在代理终止时,上游使用 HTTP。监听失败会保留主站和语音服务,后台显示不可用,修复后需重启。配置为主站自身源时拒绝打开应用。
|
||||
|
||||
## 作用域与身份
|
||||
|
||||
`server`:管理员配置允许的实际 TS `host:port`,用户按真实 TS 目标和频道获得作用域标识。`instance`:当前语音网关的已连接用户获得同一实例标识。作用域负责宿主准入和提供上下文,**不会替作者创建共享房间或自动同步数据**。应用后端应按 `request.webspeak.scope.key` 分组,并自行实现业务授权和同步。
|
||||
|
||||
TS 目标由实际语音连接解析,插件不能自报身份或频道。目标支持 `host:port`、`host#port`、`[IPv6]:port`,保存时规范化;SRV/Nickname 场景应核对实际目标。服务器范围切换频道后需重开;实例范围的频道变更通过上下文更新。断开、重连、更新、禁用、重启、配置修改或卸载会撤销旧凭证并关闭连接。服务端可以在没有打开面板时执行后台任务,直到禁用或停止。
|
||||
|
||||
入口属于实际语音网关;浏览器直连另一中继网关时,在那个网关安装配置。原生 TS 客户端不会执行网页应用,不同网关不会自动共享状态。作者可自行实现跨实例服务。
|
||||
|
||||
## 包格式与构建
|
||||
|
||||
复制 [通用起点](templates/plugin-app/manifest.json),修改 ID、元数据和业务代码。它只展示上下文及自定义计数路由,不是商店预装插件。
|
||||
|
||||
```text
|
||||
my-app/
|
||||
manifest.json
|
||||
client/index.html
|
||||
client/main.js
|
||||
client/style.css
|
||||
server/main.mjs # 可选
|
||||
server/node_modules/ # 可选,已审核的运行依赖
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 2,
|
||||
"id": "community.my-app",
|
||||
"name": "My application",
|
||||
"version": "1.0.0",
|
||||
"author": "Author",
|
||||
"license": "MIT",
|
||||
"description": "An independently implemented application",
|
||||
"scopes": ["server", "instance"],
|
||||
"client": { "entry": "client/index.html" },
|
||||
"server": { "entry": "server/main.mjs" }
|
||||
}
|
||||
```
|
||||
|
||||
纯前端应用删除 `server` 声明。前端框架产物放入 `client/`,静态引用使用相对路径,不能假设根路径为 `/`。后端入口支持 `.mjs/.cjs`,依赖放在 `server/` 内或打包为自包含文件。宿主不会执行 `npm install`、安装脚本或原生编译;原生依赖需匹配目标 Node ABI/操作系统,不一定跨平台。运行环境为宿主 Node,当前项目要求 Node 22 或更高。
|
||||
|
||||
```sh
|
||||
node scripts/build-plugin.mjs docs/templates/plugin-app /tmp/application.wplugin
|
||||
```
|
||||
|
||||
构建器是独立 Node 脚本,可复制到插件仓库,无需导入 WebSpeak 源码。`.wplugin` 是 UTF-8 JSON:`{manifest,files}`;`files` 是路径到 `{encoding:"utf8"|"base64",data:string}` 的映射。支持普通 `client/`、`server/` 文件;禁止越界路径、符号链接、Windows 设备名、大小写冲突及文件/目录别名。入口必须是 UTF-8。封装上限 48 MiB、解码内容 32 MiB、单文件 16 MiB、4096 个文件,安装上限 50 个。宿主导入时完整校验。
|
||||
|
||||
## 浏览器上下文
|
||||
|
||||
宿主在入口 HTML 注入外部脚本,在应用模块运行前提供:
|
||||
|
||||
```js
|
||||
const context = await window.webspeak.ready;
|
||||
const unsubscribe = webspeak.onContextChange(next => render(next));
|
||||
const latest = webspeak.getContext();
|
||||
const response = await fetch(context.serverUrl + '/my-route', {
|
||||
method: 'POST', body: JSON.stringify({anything: 'defined by the application'}),
|
||||
signal: webspeak.signal
|
||||
});
|
||||
const socket = new WebSocket(context.socketUrl + '/my-socket');
|
||||
```
|
||||
|
||||
| 上下文字段 | 内容 |
|
||||
| --- | --- |
|
||||
| `apiVersion` | 2 |
|
||||
| `plugin` | manifest |
|
||||
| `self` | 当前公开 `id/nickname/uid?` |
|
||||
| `connection` | 真实 `target/channelId` 和当前频道公开 `members`(`id/nickname/uid?`) |
|
||||
| `scope` | `{type:"server"|"instance",key:string}`;分组标识不能直接当文件路径 |
|
||||
| `config` | 管理员公开 JSON,所有参与者可读 |
|
||||
| `theme/language` | `light/dark` 和 `zh/en/de/ru/ja`,同步到 `<html data-theme>` 与 `lang` |
|
||||
| `appId` | 本次打开的公开标识,不是长期身份或认证凭据 |
|
||||
| `serverUrl/socketUrl` | 此会话的后端 HTTP/WS 根;纯前端为 `null` |
|
||||
| `contextUrl` | 此会话最新上下文地址 |
|
||||
|
||||
运行时 URL 含临时凭证,不应持久化、广播或记录。`webspeak.signal` 在撤销或退出时中止,仍需清理自己的定时器、网络、媒体和订阅。应用应提供两种基础配色及适合的语言回退。
|
||||
|
||||
用原生 `fetch`、`WebSocket`、`RTCPeerConnection`、文件选择/下载、IndexedDB、Canvas 等编写功能。独立源存储遵循原生规则;同一运行源的应用共享该源存储,请按插件 ID 命名,不能把此设计当作互不信任插件间的隔离。服务端持久化使用 `dataDir`。
|
||||
|
||||
关闭面板会销毁 iframe 并取消未完成的打开操作。宿主每秒检查会话有效性,撤销后终止 HTTP、SSE、WS 和旧页面。控制平面只传上下文与生命周期;业务数据使用独立应用服务,不经过语音 WebSocket。
|
||||
|
||||
## 可选 Node 后端
|
||||
|
||||
```js
|
||||
export default async function activate({ dataDir, config, publicConfig, events, signal, log }) {
|
||||
return {
|
||||
handle(req, res) {
|
||||
// req.webspeak is verified by the host; req.url is your own route.
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({participant: req.webspeak.self.id}));
|
||||
},
|
||||
upgrade(req, socket, head) { /* your WebSocket protocol */ },
|
||||
async stop() { /* flush data and release resources */ }
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
也可直接返回 `(req,res)=>…`。这是 Node 原生请求/响应,可适配 Express、WS 等库。`req.webspeak` 含 `apiVersion/appId/self/connection/scope`,不含临时 URL 或管理凭据;服务端 `connection` 只有目标和频道。代理剥离主站 Cookie、Authorization 和伪造的 `x-webspeak-*` 头;应用自行认证可使用自定义头或自己的外部服务。后端不会收到主站管理员/Query 密钥,除非管理员主动在插件配置中提供。
|
||||
|
||||
`dataDir` 为本插件持久目录,更新/重启/卸载保留。代码提取目录会清理,不可持久化。包文件没有可执行位;额外子程序需作者自行处理权限和平台。Node 网络、文件、子程序和第三方服务同样属于审核范围。
|
||||
|
||||
`config` 是后端私密 JSON,`publicConfig` 是公开 JSON。私密配置在管理页仅显示是否已保存,支持保留/替换/删除,用实例主密钥加密存储;启用的 Node 代码获得明文。它不是针对恶意插件的秘密保险箱。不要把私密配置写入响应或日志。
|
||||
|
||||
`events` 为 Node `EventEmitter`:`participantJoined/contextChanged` 提供服务端公开上下文,`participantLeft` 为 `{appId,selfId,scopeKey}`。加入指打开应用面板,不是全体 TS 成员。`signal` 在停止时中止;`log(level,message)` 提供限流日志,宿主当前以 debug 级别记录。
|
||||
|
||||
每个后端一个进程,默认最多 8 个;启动超时 10 秒、停止宽限 2 秒、JS 堆上限 256 MiB(不是总 RSS 限额)。失败显示错误、撤销会话,可手动重启,无无限重试。每个语音连接最多 8 个打开会话,全局 800 个,每会话最多 32 条代理连接及 4 条上下文 SSE。普通 HTTP 空闲超时 120 秒,无上下文 SSE 且 90 秒无活动的会话回收。作者负责消息大小、业务授权、并发、存储一致性和依赖资源用量。
|
||||
|
||||
## 分发与验证
|
||||
|
||||
[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。实例安装时校验包哈希、API 版本、插件 ID、版本、作用域集合与前后端入口。商店展示 `plugin.json` 里的名称、描述、作者和许可证,实例安装后展示包内清单里的值。目录或安装修订改变时需重新加载。空目录不默认安装插件。
|
||||
|
||||
需要后台配置的插件应在仓库 README 写明公开与私密字段的用途、必填项、默认值、取值范围和凭据获取方式,并提供含占位符的 `config.example.json`。管理员可从已安装插件打开仓库,并使用后台的通用字段编辑器。P2P 文件传输、视频同看和 TSMusicBot 有专用表单,由管理前端提供。仓库示例文件供管理员参考,当前运行时没有自动注册表单的接口。
|
||||
|
||||
验证实际构建包的导入、审核、启用、自定义 HTTP/WS、依赖加载、持久化和关闭/断线/禁用/更新撤销;检查明暗、语言、窄屏。协作另测两位真实参与者及并发/离开/重连。区分模拟身份、真实 TS、浏览器交互与跨网络证据。宿主回归:`npm run verify`。
|
||||
|
||||
## 插件入口与应用窗口 / Plugin launcher and application window
|
||||
|
||||
插件入口由宿主管理。WebSpeak 0.3.2 起,完整语音皮肤可以把 `voice.plugin-launcher` 放到工具栏或侧栏,并选择抽屉或对话框。布局缺少可用插槽时会显示宿主的应用库入口。应用库和应用内容使用非模态窗口:打开后仍可操作工作台;标题栏可拖动,支持最小化、最大化、还原和关闭,小屏幕自动限制在可视区域内。宿主窗口优先读取标准 `color-scheme` 来选择日间/夜间配色,不继承皮肤组件样式。
|
||||
|
||||
最小化、切换到应用库、再返回当前应用均保留同一个 iframe 与会话,传输、播放等任务不会因收起窗口而重置。关闭窗口、切换至另一个应用或语音会话撤销时,宿主结束当前应用会话。当前同时承载一个前端应用;不要把窗口最小化当成退出事件。
|
||||
|
||||
应用只负责 iframe 内部内容,使用自身响应式日间/夜间样式和上下文中的主题、语言。不读取或改写皮肤 DOM,不绘制覆盖宿主的全屏遮罩,不自行重复宿主的标题栏、最小化和关闭按钮。需要自有导航时可在内容区实现。应用界面优先显示功能与实际状态,不重复运行环境、权限或免责说明;管理员启用时的信任与权限信息保留在管理流程中。
|
||||
|
||||
## 实例级用户授权
|
||||
|
||||
首次访问时,宿主统一征求第三方皮肤与功能应用的使用授权;决定按浏览器源保存,不迁移旧的逐皮肤授权。拒绝或未选择时,只显示日间、夜间、ILLUSIA 三款官方皮肤,KAAK 和功能应用入口均隐藏。皮肤菜单最后的“授权”可随时更改。撤回会关闭 iframe 并撤销当前打开操作/应用会话,不停止管理员启用的全实例后台服务。应用不得以入口以外的方式绕过宿主授权,也无需重复询问同一份宿主上下文授权;相机、麦克风等浏览器原生许可仍由浏览器处理。
|
||||
+290
-126
@@ -1,48 +1,165 @@
|
||||
# WebSpeak · Deutsch
|
||||
<a id="readme-top"></a>
|
||||
|
||||
[Projektstartseite](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
<div align="center">
|
||||
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
|
||||
<h1>WebSpeak · Deutsch</h1>
|
||||
<p><strong>Deiner TeamSpeak-Community im Browser beitreten.</strong></p>
|
||||
<p><a href="../README.md">Projektstartseite</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.en.md">English</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.ja.md">日本語</a></p>
|
||||
<p>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&color=0f766e" alt="Release" /></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
|
||||
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.
|
||||
|
||||
Aktuelle Version: [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9).
|
||||
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.
|
||||
|
||||
|
||||
|
||||
[Live-Demo](#demo) · [Funktionen](#features) · [Screenshots](#screenshots) · [Bereitstellung](#deployment) · [Verwaltung](#administration) · [Erweiterte Einstellungen](#advanced) · [Skins & Plugins](#extensions) · [Problemlösung](#troubleshooting) · [Änderungsprotokoll](#changelog)
|
||||
|
||||
<a id="demo"></a>
|
||||
|
||||
## Live-Demo
|
||||
|
||||
- Shanghai: <https://shanghai.webspeak.online>
|
||||
- Hongkong: <https://webspeak.online>
|
||||
- [Shanghai · shanghai.webspeak.online](https://shanghai.webspeak.online)
|
||||
- [Hongkong · webspeak.online](https://webspeak.online)
|
||||
|
||||
Netzwerkbedingungen und Auslastung können bei beiden Demos schwanken; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
Willkommensseite und Sprachbereich direkt ausprobieren. Netzwerk, Auslastung und Verfügbarkeit der Demo-Knoten können schwanken.
|
||||
|
||||
## ✨ Funktionen
|
||||
<a id="features"></a>
|
||||
|
||||
## Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll anhand der gemeldeten Version automatisch. |
|
||||
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
|
||||
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
|
||||
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke regeln, testen, stummschalten, VOX und individuelle Mitgliedslautstärke. |
|
||||
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
|
||||
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
|
||||
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele, widerrufbare Einladungen sowie Import, Konvertierung, Prüfung und Export von TeamSpeak-3-Identitäten. |
|
||||
| Administration | Ziele, Zugriff, öffentliche Medienadresse, IPv6-Kandidaten, Sprach-STUN, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
|
||||
| Projektstruktur | In 0.2.6 wurden Sprach-Gateway, Sitzungsereignisse, Audio und Bildschirmfreigabe in Module aufgeteilt; Sprach- und Admin-Oberflächen in Komponenten, Composables und Dienste zerlegt und um Lebenszyklus- und Wiederverbindungstests ergänzt. |
|
||||
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Pakete für Windows x64 und Linux x64/ARM64, Docker für amd64/arm64 und Android-APKs für arm64-v8a, armeabi-v7a und x86_64. |
|
||||
| Echtzeit-Sprache | Opus, optionales WebRTC und WebSocket-Fallback; Stummschaltung, VOX, Geräteauswahl, Browser-Geräuschunterdrückung und Lautstärke je Mitglied. |
|
||||
| Kanäle & Nachrichten | Kanalbaum und TeamSpeak-Trenner, Mitgliedsstatus, Kanalwechsel, Kanal-/Server-/Privatchat, Anstupsen, Flüstern und lokaler Chatverlauf. |
|
||||
| Bildschirm & Audio | Bildschirmfreigabe zwischen Browsern und unterstützten nativen TeamSpeak-6-Clients mit Qualitäts-, Bitraten- und Statistikoptionen; Fenster-/Tab-Audio auf dem Desktop. |
|
||||
| Identität & Verbindungen | Gespeicherte Identitäten, TS3-Identitätsimport/-export, Favoriten und Verlauf, SRV-/Nickname-Auflösung, IPv4/IPv6 und Einladungen. |
|
||||
| Instanzverwaltung | Feste oder offene Ziele, Zugriffsregeln, Einladungen, Sitzungen, Logs, Diagnosen, Backups und optionale TeamSpeak-Verwaltung. |
|
||||
| Skins & Oberfläche | Tag, Nacht, ILLUSIA und KAAK, `.wskin`-Pakete über GitHub, fünf Sprachen und responsive Ansichten. |
|
||||
| Verteilte Sprache | Der Browser verbindet sich direkt mit dem gewählten Relay-Sprach-Gateway; die URL der Eingangsinstanz bleibt erhalten. |
|
||||
| Bereitstellung | Docker amd64/arm64, Serverpakete für Windows x64 und Linux x64/ARM64 sowie Android-Vorschau-APKs. |
|
||||
|
||||
## TeamSpeak-Versionskompatibilität
|
||||
### TeamSpeak-Versionskompatibilität
|
||||
|
||||
Sprachverbindungen verwenden das TeamSpeak-Clientprotokoll und benötigen keine Query-Zugangsdaten. Die optionale TS-Verwaltung verwendet eigene WebQuery-/ServerQuery-Zugangsdaten.
|
||||
|
||||
- **TeamSpeak 3**: Die Erkennung wertet die führende `3.x`-Versionsnummer aus. Ältere Serverversionen sollten in der jeweiligen Umgebung geprüft werden, da nicht jede historische Version separat getestet wurde.
|
||||
- **TeamSpeak 6**: Unterstützt, einschließlich Bildschirmfreigabe mit nativen TeamSpeak-6-Clients.
|
||||
- **Automatische Erkennung**: Das Gateway liest die `version`-Antwort des Servers und hält das erkannte Protokoll in der Verbindungsdiagnose fest.
|
||||
- Das Gateway verwendet das Upstream-SDK 1.0 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak richtet sich an TeamSpeak 3 und 6.
|
||||
- Das Gateway verwendet das Upstream-SDK `1.0.0-beta.23` [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak richtet sich an TeamSpeak 3 und 6.
|
||||
|
||||
## Optionale TeamSpeak-Verwaltung
|
||||
<a id="screenshots"></a>
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
|
||||
<details>
|
||||
<summary>Willkommensseite, Audiosteuerung und Mitgliedermenü anzeigen</summary>
|
||||
|
||||
### Willkommensseite
|
||||
|
||||

|
||||
|
||||
### Audiosteuerung
|
||||
|
||||

|
||||
|
||||
### Mitgliedermenü
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
<a id="deployment"></a>
|
||||
|
||||
## Bereitstellung & erste Konfiguration
|
||||
|
||||
Die Compose-Konfiguration verwendet `network_mode: host` für Linux-Docker-Hosts. Für einen Windows-Server das Release-Paket verwenden.
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64/ARM64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.12+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip`, `linux-x64.tar.gz` oder `linux-arm64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und den enthaltenen Starter ausführen. Die Pakete enthalten Node.js und Produktionsabhängigkeiten. Docker unterstützt amd64/arm64.
|
||||
|
||||
Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfügbar. Sie sind für Tests per Sideload debug-signiert, keine Google-Play-Pakete; echte TeamSpeak-Sprachtests auf Geräten stehen noch aus.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
|
||||
|
||||
### Erste Konfiguration
|
||||
|
||||
1. `http://<dein-host>:3040/admin` öffnen.
|
||||
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
|
||||
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
|
||||
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
|
||||
|
||||
### HTTPS & persistente Daten
|
||||
|
||||
Öffentliche Webseite und WebSocket über HTTPS bereitstellen. Beispielsweise die eigene Domain auf den Host zeigen lassen und Caddy als Reverse Proxy einrichten:
|
||||
|
||||
```caddyfile
|
||||
webspeak.example.com {
|
||||
reverse_proxy 127.0.0.1:3040
|
||||
}
|
||||
```
|
||||
|
||||
Die Beispieldomain durch die eigene ersetzen. Ein erreichbarer Reverse Proxy oder Tunnel garantiert keine UDP-Medienverbindung; siehe [Erweiterte Einstellungen](#advanced). Release- und Quellcode-Installationen verwenden `data/`, Docker das Volume `webspeak-data`. Bei Backup und Umzug `webspeak.db` und den zugehörigen `master.key` gemeinsam aufbewahren.
|
||||
|
||||
<a id="administration"></a>
|
||||
|
||||
## Administration
|
||||
|
||||
Unter `/admin` werden Server, Zugriff, WebRTC, Relays, Einladungen, aktive Sitzungen, Logs und Backups verwaltet. Der Skin-Store liegt unter `/admin/skins`, der Store für funktionale Plugins unter `/admin/plugins`.
|
||||
|
||||
### Optionale TeamSpeak-Verwaltung
|
||||
|
||||
WebSpeak-Verwaltung und Sprachverbindungen sind davon unabhängig. Im Modus mit festem Server die TS-Verbindung unter `/admin/ts-admin` einrichten.
|
||||
|
||||
@@ -53,31 +170,13 @@ WebSpeak-Verwaltung und Sprachverbindungen sind davon unabhängig. Im Modus mit
|
||||
|
||||
Zugangsdaten werden serverseitig verschlüsselt und nie von der API zurückgegeben. Datenbank und `master.key` gemeinsam sichern. Verbindungsfehler beeinflussen weder WebSpeak-Verwaltung noch Sprache. Sperren verwenden die Benutzer-UID, damit andere Nutzer derselben Gateway-IP nicht betroffen sind.
|
||||
|
||||
## 🖼️ Screenshots
|
||||
<a id="advanced"></a>
|
||||
|
||||
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
|
||||
|
||||
### Willkommensseite
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" /></p>
|
||||
|
||||
### Sprachbereich
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" /></p>
|
||||
|
||||
### Audiosteuerung
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" /></p>
|
||||
|
||||
### Mitgliedermenü
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitgliedermenü" width="100%" /></p>
|
||||
|
||||
## 🧩 Erweiterte Funktionen
|
||||
## Erweiterte Einstellungen
|
||||
|
||||
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
|
||||
|
||||
### 1. WebRTC-Sprache mit niedriger Latenz
|
||||
### WebRTC-Sprache mit niedriger Latenz
|
||||
|
||||
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Das aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
|
||||
|
||||
@@ -88,6 +187,14 @@ WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
|
||||
|
||||
### Sprach-WebRTC hinter Reverse Proxy oder TCP-Tunnel
|
||||
|
||||
Unter **Server → Erweiterte Einstellungen** die **öffentliche Medienadresse** als per UDP erreichbare IP oder Domain des Sprach-Gateways eintragen, ohne Schema, Pfad oder Port. Sie ersetzt die aus dem Webseitenaufruf abgeleitete Adresse. Ein Proxy-Hostname ist nicht automatisch eine erreichbare Medienadresse.
|
||||
|
||||
**IPv6-Kandidaten** sind optional und behalten IPv4 bei; IPv6-Routing und Firewall müssen passen. Als **Sprach-STUN** kann `stun:turn.teamspeak.com:3478` eingetragen werden. Browser und Gateway verwenden dann denselben Dienst. Leer behält das bisherige Verhalten bei: STUN des Gateway-SDKs, kein Browser-STUN. Zulässig sind IPv4-erreichbare UDP-STUN-Domains oder IPv4-Adressen, keine IPv6-Literale oder TURN-Zugangsdaten.
|
||||
|
||||
Speichern und neu verbinden. Den gesamten UDP-Portbereich öffnen und bei statischer Weiterleitung die Portnummern erhalten. STUN findet Adressabbildungen, leitet aber keine Audiodaten weiter. Ein reiner TCP-Tunnel ohne nutzbaren UDP-/IPv6-Pfad führt weiter zum kompatiblen Transport.
|
||||
|
||||
### ICE-Kandidaten für Bildschirmfreigabe
|
||||
|
||||
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
|
||||
@@ -102,18 +209,22 @@ Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niem
|
||||
|
||||
Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegenseitig erkennen, starten und ansehen. Zwischen Browsern sowie zwischen Browser und nativem Client werden die Bildschirmmedien möglichst über eine direkte WebRTC/ICE-Peer-to-Peer-Verbindung übertragen; WebSpeak übernimmt Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung, transportiert aber keine Bildschirmmedien. Die Oberfläche zeigt Live-Status und Zuschauerzahl und bietet Lautstärke-, Vollbild- und Beenden-Steuerung. Für die Aufnahme stehen bis zu 1080p und 60 FPS sowie WebRTC-Statistiken zur Verfügung.
|
||||
|
||||
### 2. Relay-Modus
|
||||
### Relay-Modus
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
|
||||
Eine Relay-Instanz betreibt sowohl die ältere UDP-Kompatibilitätsweiterleitung als auch ein separates Sprach-Gateway, jedoch keine Besucher- oder Administrationsseite. Das Eingangs-Gateway signiert mit dem gemeinsamen Token ein einmaliges Sprach-Ticket und delegiert es; anschließend verbindet sich der Browser direkt mit dem Relay, das seinerseits TeamSpeak erreicht. Die Seite bleibt unter der URL des Eingangs-Gateways. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
|
||||
|
||||
<details>
|
||||
<summary>Start- und Konfigurationsbeispiele für Relays anzeigen</summary>
|
||||
|
||||
#### Aus dem Quellcode starten
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
@@ -175,16 +286,121 @@ In den Relay-Einstellungen des Eingangs-Gateways als **Voice gateway address** d
|
||||
|
||||
Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entfernen.
|
||||
|
||||
### 3. Abhängigkeiten und Hinweise zur Herkunft
|
||||
</details>
|
||||
|
||||
### Abhängigkeiten und Hinweise zur Herkunft
|
||||
|
||||
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
|
||||
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
|
||||
- Die TeamSpeak-Verbindung verwendet das Upstream-SDK [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), veröffentlicht als `@honeybbq/teamspeak@1.0.0-beta.19`; der SDK-Fork des Projekts muss nicht mehr gebaut werden.
|
||||
- TeamSpeak verwendet das Upstream-Paket [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) `@honeybbq/teamspeak@1.0.0-beta.23`; ein eigener SDK-Fork muss nicht gebaut werden.
|
||||
|
||||
## 🧾 Änderungsprotokoll
|
||||
<a id="extensions"></a>
|
||||
|
||||
## Skins & funktionale Plugins
|
||||
|
||||
### Skin-Pakete `.wskin`
|
||||
|
||||
Skins gestalten Aussehen, Layout und zugehörige Widgets. Administratoren installieren, aktivieren und wählen den Standard-Skin. Autoren verwenden öffentliche Schnittstellen ohne Änderungen am WebSpeak-Quellcode.
|
||||
|
||||
[Entwicklungsleitfaden](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin-Katalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord-Voice-Beispiel](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
|
||||
### Funktionale Plugins `.wplugin`
|
||||
|
||||
Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und optionalen Node-Backends, eigenen Routen, Daten und Zusammenarbeit. Administratoren prüfen Code und Abhängigkeiten vor der Aktivierung; Updates erfordern erneutes Vertrauen. Anwendungen unterstützen TS-Server- oder Instanz-Bereiche und eine separate Origin. API v2 ist ab v0.3.0 enthalten.
|
||||
|
||||
[Entwicklungsleitfaden](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Verteilungskatalog & Beispiel](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
|
||||
## Problemlösung
|
||||
|
||||
| Symptom | Prüfen |
|
||||
| --- | --- |
|
||||
| WebRTC fällt trotz Aktivierung zurück | Fehlercode im Sprachstatus, HTTPS, vollständigen UDP-Portbereich und öffentliche Medienadresse prüfen. Ein TCP-Tunnel transportiert diese UDP-Medien nicht. |
|
||||
| Ziel wird als lokale Adresse blockiert | Der offene Modus beschränkt Loopback-/Privatadressen. Für einen TS-Server auf demselben Host den administrativ konfigurierten festen Servermodus verwenden. |
|
||||
| Bildschirmfreigabe läuft ab oder bleibt schwarz | Sie verwendet eine eigene WebRTC-Verbindung. Aushandlung, ICE und Codec-Statistik prüfen; verbundenes Sprach-WebRTC bestätigt nicht die Bildschirmverbindung. |
|
||||
| Daten fehlen oder lassen sich nach dem Update nicht entschlüsseln | Dasselbe Datenverzeichnis bzw. Volume mit passendem `master.key` verwenden. Nicht mit `docker compose down -v` aktualisieren. |
|
||||
|
||||
### ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
|
||||
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
|
||||
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
|
||||
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Bis zu 100 aktive Browser-Sitzungen pro Instanz; dies ist ein Anwendungslimit, keine Leistungszusage oder TS-Lizenzgrenze. |
|
||||
|
||||
<a id="changelog"></a>
|
||||
|
||||
## Änderungsprotokoll
|
||||
|
||||
<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).
|
||||
- Tag, Nacht und ILLUSIA öffnen die App-Bibliothek über die obere Leiste. KAAK 3.1.134 platziert den Button in der linken Symbolleiste und gleicht ihn den Nachbarbuttons an. Angeheftete Apps stehen oben.
|
||||
- Die Plugin-Verwaltung bietet einen Feldeditor, Formulare für P2P-Dateitransfer, gemeinsames Ansehen und TSMusicBot sowie Links zu den Repositories.
|
||||
- Die Stores tolerieren Unterschiede bei Anzeigedaten und prüfen SHA-256, Paketformat und für Installation oder Ausführung nötige Felder.
|
||||
- Die Entwicklungsleitfäden und Agent Skills erklären die Platzierung des App-Buttons, die Konfigurationsfelder und den separaten HTTPS-Ursprung für öffentliche Plugins.
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- Die WebSocket-Wiedergabe berücksichtigt jetzt die Opus-Kanalzahl und die tatsächliche Paketdauer. Der WebRTC-Downlink-Mix erhält Stereo. Siehe #54.
|
||||
- Die Rauschunterdrückung bietet jetzt Aus, Standard und Stark. Stark kombiniert die Browserfunktion mit RNNoise. Siehe #53.
|
||||
- Das Sprachstatusfenster exportiert die letzten zwei Minuten der Gateway-, Sprach- und Mikrofondiagnose. Die Aufnahme im Hintergrund hängt vom Browser und Betriebssystem ab. Siehe #49 und #55.
|
||||
- Der Plugin-Einstieg befindet sich in der Werkzeugleiste des Sprachbereichs. Administratoren können Plugin-Kurzbefehle anheften. Siehe #56.
|
||||
- Private Arbeitsbereichseinladungen können ablaufen. Die KAAK-Willkommensseite wurde wiederhergestellt, das überdeckte Skin-Menü in der Demo und zu kurze Wartezeiten bei großen Downloads wurden korrigiert. Die README zeigt fünf Skins.
|
||||
|
||||
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
|
||||
|
||||
#### Plugin-Anwendungen
|
||||
|
||||
- Plugin-API v2 für eigenständige Browser-Anwendungen und optionale Node-Backends mit eigenen Routen, Zuständen, Kommunikationswegen und Funktionen.
|
||||
- Installation über den GitHub-Store oder lokale `.wplugin`-Pakete. Administratoren verwalten öffentliche/private Konfigurationen, prüfen und aktivieren Anwendungen; Updates erfordern erneutes Vertrauen.
|
||||
- Ein vom Design unabhängiger schwebender Einstieg und eine Anwendungsbibliothek. Fenster lassen sich verschieben, skalieren, minimieren, maximieren und wiederherstellen; Minimieren oder der Wechsel zur Bibliothek lädt die Anwendung nicht neu.
|
||||
- Anwendungsvorlage, Entwicklungsanleitung und Agent Skill; P2P-Dateiübertragung und gemeinsames Videoschauen werden in eigenen Repositories verteilt.
|
||||
|
||||
#### Designs und Berechtigung
|
||||
|
||||
- Beim ersten Besuch wird gemeinsam nach der Berechtigung für Designs und Plugins dieser Instanz gefragt; Verbindungszugangsdaten sind ausgeschlossen. Der letzte Eintrag im Designmenü öffnet diese Einstellung erneut.
|
||||
- Ohne Zustimmung bleiben nur Tag, Nacht und ILLUSIA verfügbar. KAAK, andere Designs und der Plugin-Einstieg werden ausgeblendet. Ein Widerruf stellt ein integriertes Design wieder her, bricht laufende Ladevorgänge ab und beendet zugehörige Komponenten und Anwendungsseiten.
|
||||
- Manifest-Berechtigungen, Datenprojektion, Paketprüfsummen und Prüfungen von Host-Aktionen bleiben erhalten. Die Prüfung durch den Administrator gilt weiterhin separat.
|
||||
|
||||
#### Korrekturen und Aktualisierungen
|
||||
|
||||
- Native TS-Clients beantworteten reine Videoangebote bei Fenster-, Bildschirm- oder Freigaben ohne Ton nicht. Die erforderliche Audiosektion wird jetzt ausgehandelt, ohne ein Mikrofon aufzunehmen oder Ton zu erzeugen. Fenster- und Bildschirmvideo wurden im Benutzertest bestätigt.
|
||||
- SDK auf `@honeybbq/teamspeak@1.0.0-beta.23` aktualisiert; optionale Mitgliedsfelder werden berücksichtigt und leere Pakete am Sprachende übersprungen.
|
||||
- Upstream-Korrekturen für TSDNS, Query-Wiederholungen nach Flooding, Dateiübertragungen und Verbindungsabbau übernommen.
|
||||
- Korrekturen für IPv6-Zielprüfung, begrenzte parallele Anmeldungen, Sitzungswiderruf nach Passwortwechsel, vertrauenswürdige Proxys und PCM-Uplink-Schutz übernommen.
|
||||
- Der Kaltstart von Designs verwendet weiterhin die tatsächliche Build-Version. Desktop, Web und Android verwenden eine einheitliche Anwendungsversion.
|
||||
|
||||
#### Aktualisierung
|
||||
|
||||
- Plugin-API v2 ist nicht mit v1-Paketen kompatibel. Ersatzanwendungen aktualisieren, prüfen und aktivieren.
|
||||
- Öffentliche Plugins benötigen einen separaten HTTPS-Ursprung, der im Administrationsbereich konfiguriert und an den Laufzeitport (Standard `3042`) weitergeleitet wird. Hauptseite und Anwendungen dürfen keinen Ursprung teilen.
|
||||
- Die Instanzberechtigung muss neu gewählt werden; frühere Einzelberechtigungen gelten nicht als Zustimmung.
|
||||
|
||||
|
||||
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
|
||||
|
||||
#### Erweiterungen
|
||||
@@ -207,6 +423,9 @@ Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entf
|
||||
|
||||
- Die in [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) beschriebene Sicherheitsabsicherung ist nicht enthalten; das Schließen des PRs bedeutet nicht, dass die gemeldeten Probleme behoben sind.
|
||||
|
||||
<details>
|
||||
<summary>v0.2.8 und frühere Versionen anzeigen</summary>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### Bildschirmfreigabe und Verbindungsstabilität
|
||||
@@ -296,88 +515,33 @@ WebRTC und Kanalchat korrigiert sowie Administration, Protokolle und Mobilansich
|
||||
|
||||
Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung und Sprachpufferung.
|
||||
|
||||
</details>
|
||||
|
||||
## 🚀 Bereitstellung
|
||||
<a id="contributors"></a>
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64/ARM64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.12+, Git und native Build-Werkzeuge |
|
||||
## Mitwirkende & Herkunft
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip`, `linux-x64.tar.gz` oder `linux-arm64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und den enthaltenen Starter ausführen. Die Pakete enthalten Node.js und Produktionsabhängigkeiten. Docker unterstützt amd64/arm64.
|
||||
|
||||
Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfügbar. Sie sind für Tests per Sideload debug-signiert, keine Google-Play-Pakete; echte TeamSpeak-Sprachtests auf Geräten stehen noch aus.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
|
||||
|
||||
### Erste Konfiguration
|
||||
|
||||
1. `http://<dein-host>:3040/admin` öffnen.
|
||||
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
|
||||
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
|
||||
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
|
||||
|
||||
## ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
|
||||
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
|
||||
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
|
||||
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
|
||||
|
||||
## Mitwirkende und Beiträge
|
||||
<details>
|
||||
<summary>Upstream-Autoren und PR-Beiträge anzeigen</summary>
|
||||
|
||||
Diese Liste würdigt den Autor des zugrunde liegenden SDKs, Beiträge aus zusammengeführten GitHub-PRs sowie ursprüngliche Arbeiten, die in eigenständig verteilte Skin-Pakete übernommen wurden.
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — Autor des [teamspeak-js-SDKs (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), das den von WebSpeak verwendeten TeamSpeak-Protokollclient bereitstellt.
|
||||
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) meldete Sicherheitsprobleme und lieferte Korrekturvorschläge sowie Regressionstests für IPv6-Zielprüfung, Admin-Anmeldung und Sitzungen, Proxy-Ratenlimits und PCM-Uplink. Der ursprüngliche Patch wurde nicht direkt übernommen; die Korrekturen wurden auf `dev` neu implementiert.
|
||||
- [LainHE](https://github.com/LainHE) — [zusammengeführte PRs #2, #8, #28, #31–#35, #37, #38 und #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): Browser-Fehlerübersetzungen, Skalierung und Startseitenlayout, Bildschirmfreigabe-Bitrate und Zuschaueravatare, Relay-Zielprüfung und Wiederverbindung, vertrauenswürdige Proxys, Weitergabe von Verbindungsfehlern, Audio-Fehlermeldungen und Ressourcenfreigabe bei WebRTC-Fehlern.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [zusammengeführte PRs #13 und #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep) zu vorhandenen TS6-Freigaben, Seitenverhältnis, mobiler Sprache/Bildschirm-Wachhalten/Skin-Menü, Kanaloptionen der Identität, PWA/Design, Chatverlauf, Mitglieder-Audiozuständen und Mikrofonberechtigungen.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) verbesserte das Beibehalten des KAAK-Arbeitsbereichs und die Wiederverbindung nach der ersten Verbindung. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) und [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) lieferten das ursprüngliche Design und die Implementierung des Discord-Skins (Commit-Autor **yumi**), die das WebSpeak-Projekt in einen [eigenständig verteilten `.wskin`-Skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) überführte.
|
||||
|
||||
</details>
|
||||
|
||||
## Community & verwandte Projekte
|
||||
|
||||
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ-Gruppe 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot): TeamSpeak-Musikbot mit plattformübergreifender Wiedergabe und Webkonsole.
|
||||
|
||||
## Lizenz
|
||||
|
||||
WebSpeak wird unter [AGPL-3.0-only](../LICENSE) veröffentlicht. Lizenzen und Herkunft von Abhängigkeiten stehen in den jeweiligen Upstream-Projekten.
|
||||
|
||||
<p align="right"><a href="#readme-top">Nach oben ↑</a></p>
|
||||
+288
-128
@@ -1,50 +1,171 @@
|
||||
# WebSpeak · English
|
||||
<a id="readme-top"></a>
|
||||
|
||||
[Project home](../README.md) · [简体中文](./README.zh-CN.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
<div align="center">
|
||||
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
|
||||
<h1>WebSpeak · English</h1>
|
||||
<p><strong>Join your TeamSpeak community from a browser.</strong></p>
|
||||
<p><a href="../README.md">Project home</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.ja.md">日本語</a></p>
|
||||
<p>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&color=0f766e" alt="Release" /></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
|
||||
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.
|
||||
|
||||
Latest release: [read the 0.2.9 changelog on this page](#latest-release-notes).
|
||||
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.
|
||||
|
||||
Skin authors should start with the [current skin development guide](./SKIN_DEVELOPMENT.md), which combines the `.wskin` package format, current runtime APIs, permission boundaries, and authoring workflow. The repository also includes the [WebSpeak skin development skill for agents](../.agents/skills/webspeak-skin-development/SKILL.md).
|
||||
|
||||
|
||||
[Live demo](#demo) · [Features](#features) · [Screenshots](#screenshots) · [Deployment](#deployment) · [Administration](#administration) · [Advanced settings](#advanced) · [Skins & plugins](#extensions) · [Troubleshooting](#troubleshooting) · [Changelog](#changelog)
|
||||
|
||||
<a id="demo"></a>
|
||||
|
||||
## Live demo
|
||||
|
||||
- Shanghai: <https://shanghai.webspeak.online>
|
||||
- Hong Kong: <https://webspeak.online>
|
||||
- [Shanghai · shanghai.webspeak.online](https://shanghai.webspeak.online)
|
||||
- [Hong Kong · webspeak.online](https://webspeak.online)
|
||||
|
||||
Network conditions and load may vary at either demo. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
Try the welcome page and voice workspace. Network conditions, load and availability vary between demo nodes.
|
||||
|
||||
## ✨ Features
|
||||
<a id="features"></a>
|
||||
|
||||
| Capability | Description |
|
||||
## Features
|
||||
|
||||
| Capability | What it provides |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6, automatically detecting the target protocol from the reported version. |
|
||||
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
|
||||
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
|
||||
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
|
||||
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust volume, test the microphone, mute, use VOX, and control member volume. |
|
||||
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
|
||||
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
|
||||
| Identity and access | Remembered identity, visitor-defined targets, revocable expiring invite links, and TeamSpeak 3 identity import, conversion, validation, and export. |
|
||||
| Administration | Manage targets, access policy, public media address, IPv6 candidates, voice STUN, relays, invites, sessions, logs, diagnostics, and backups. |
|
||||
| Engineering structure | In 0.2.6, gateway voice, session events, audio, and screen-share coordination were split into modules; frontend voice and admin pages were decomposed into components, composables, and services, with lifecycle and reconnect tests. |
|
||||
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; packages include Windows x64 and Linux x64/ARM64, Docker supports amd64/arm64, and Android APKs target arm64-v8a, armeabi-v7a, and x86_64. |
|
||||
| Realtime voice | Opus, optional WebRTC and WebSocket fallback; mute, VOX, device selection, browser noise suppression and per-member volume. |
|
||||
| Channels & messaging | Channel tree and TeamSpeak spacers, member state, channel switching, channel/server/private chat, pokes, whispers and local chat history. |
|
||||
| Screen & audio sharing | Screen sharing between browsers and supported native TeamSpeak 6 clients, with quality, bitrate and statistics controls; desktop window or tab audio sharing. |
|
||||
| Identity & connections | Remembered identities, TS3 identity import/export, favorites and history, SRV and Nickname resolution, IPv4/IPv6 and invitation links. |
|
||||
| Instance administration | Fixed or open targets, access policy, invitations, sessions, logs, diagnostics, backups and optional TeamSpeak management connections. |
|
||||
| Skins & interface | Day, Night, ILLUSIA and KAAK, plus GitHub distribution of `.wskin` packages, five interface languages and responsive layouts. |
|
||||
| Distributed voice | Browsers connect directly to the selected relay voice gateway while the page stays on the ingress instance URL. |
|
||||
| Deployment | Docker amd64/arm64, Windows x64 and Linux x64/ARM64 server packages, plus Android preview APKs. |
|
||||
|
||||
## TeamSpeak version compatibility
|
||||
### TeamSpeak version compatibility
|
||||
|
||||
Voice uses the standard TeamSpeak client protocol and needs no Query credentials. Optional TeamSpeak administration uses separate WebQuery / ServerQuery credentials.
|
||||
|
||||
- **TeamSpeak 3**: protocol detection recognizes the leading `3.x` version. Older server releases should be validated with the specific deployment because not every historical release has been independently tested.
|
||||
- **TeamSpeak 6**: supported, including screen sharing with native TeamSpeak 6 clients.
|
||||
- **Auto-detection**: the gateway reads the server's `version` response and records the detected protocol in connection diagnostics.
|
||||
- The gateway uses the upstream [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) 1.0 SDK; WebSpeak targets TeamSpeak 3 and TeamSpeak 6.
|
||||
- The gateway uses the upstream [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) `1.0.0-beta.23` SDK; WebSpeak targets TeamSpeak 3 and TeamSpeak 6.
|
||||
|
||||
## Optional TeamSpeak administration
|
||||
<a id="screenshots"></a>
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
|
||||
<details>
|
||||
<summary>Show the welcome page, audio controls and member menu</summary>
|
||||
|
||||
### Welcome page
|
||||
|
||||

|
||||
|
||||
### Audio controls
|
||||
|
||||

|
||||
|
||||
### Member menu
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
<a id="deployment"></a>
|
||||
|
||||
## Deployment & first-time setup
|
||||
|
||||
The Compose configuration uses `network_mode: host` and targets Linux Docker hosts. Use the release package for a Windows server.
|
||||
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64/ARM64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.12+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
|
||||
|
||||
```bash
|
||||
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:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
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.
|
||||
|
||||
### 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
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
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`.
|
||||
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
|
||||
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
|
||||
|
||||
### HTTPS & persistent data
|
||||
|
||||
Expose the public page and WebSocket over HTTPS. For example, point your hostname to the host and configure Caddy to reverse-proxy WebSpeak:
|
||||
|
||||
```caddyfile
|
||||
webspeak.example.com {
|
||||
reverse_proxy 127.0.0.1:3040
|
||||
}
|
||||
```
|
||||
|
||||
Replace the example hostname with your own. A working reverse proxy or Tunnel does not make WebRTC UDP media reachable; see [Advanced settings](#advanced). Release/source installs use `data/`, while Docker uses the `webspeak-data` volume. Keep `webspeak.db` and its matching `master.key` together when backing up or moving an instance.
|
||||
|
||||
<a id="administration"></a>
|
||||
|
||||
## Administration
|
||||
|
||||
Open `/admin` to manage servers and access, WebRTC and relays, invitations, active sessions, logs and backups. The skin store is at `/admin/skins`; the functional plugin store is at `/admin/plugins`.
|
||||
|
||||
### Optional TeamSpeak administration
|
||||
|
||||
WebSpeak administration and visitor voice do not depend on this feature. In fixed-server mode, open `/admin/ts-admin` to configure the TS management connection.
|
||||
|
||||
@@ -55,31 +176,13 @@ WebSpeak administration and visitor voice do not depend on this feature. In fixe
|
||||
|
||||
Credentials are encrypted on the server and never returned by the API. Back up both the database and `master.key`. A failed management connection does not affect WebSpeak administration or ordinary voice. UID bans avoid banning other users sharing the gateway IP.
|
||||
|
||||
## 🖼️ Screenshots
|
||||
<a id="advanced"></a>
|
||||
|
||||
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
|
||||
|
||||
### Welcome page
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" /></p>
|
||||
|
||||
### Voice workspace
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" /></p>
|
||||
|
||||
### Audio controls
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" /></p>
|
||||
|
||||
### Member menu
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-menu.png" alt="WebSpeak English member menu" width="100%" /></p>
|
||||
|
||||
## 🧩 Advanced features
|
||||
## Advanced settings
|
||||
|
||||
These features are optional. WebSpeak continues to work with the compatibility voice transport when they are disabled. Configure them under **Administration → Servers**; saved changes apply to new connections.
|
||||
|
||||
### 1. WebRTC low-latency voice
|
||||
### WebRTC low-latency voice
|
||||
|
||||
WebRTC moves browser voice to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
|
||||
|
||||
@@ -112,18 +215,22 @@ With TURN configured, media may use that external TURN service but never the Web
|
||||
|
||||
Browser users and native TeamSpeak 6 clients can discover, start, and watch each other's screen shares. Screen media between browsers, and between a browser and a native client, is sent over a WebRTC/ICE peer-to-peer path whenever possible; WebSpeak handles session authorization, share state, and SDP/ICE signaling, but does not carry the screen media. The UI includes live status, viewer count, player volume, fullscreen, and exit controls. Share settings support up to 1080p and 60 FPS, with live WebRTC statistics for diagnosis.
|
||||
|
||||
### 2. Relay mode
|
||||
### Relay mode
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
|
||||
A relay instance runs both the legacy UDP compatibility forwarder and a separate voice gateway, with no visitor page or administration console. The ingress gateway signs and delegates a one-time voice ticket with the shared token; the browser then connects directly to the relay, and the relay connects to TeamSpeak. The page stays on the ingress gateway URL. Use a random token of at least 16 characters.
|
||||
|
||||
<details>
|
||||
<summary>Show relay startup and configuration examples</summary>
|
||||
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
@@ -185,16 +292,121 @@ In the ingress gateway's relay settings, set **Voice gateway address** to that H
|
||||
|
||||
Disable and save the relay configuration to remove the relay option from the welcome page.
|
||||
|
||||
### 3. Dependencies and attribution
|
||||
</details>
|
||||
|
||||
### Dependencies and attribution
|
||||
|
||||
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
|
||||
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
|
||||
- TeamSpeak connectivity uses upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), published as `@honeybbq/teamspeak@1.0.0-beta.19`; building the project's SDK fork is no longer required.
|
||||
- TeamSpeak connectivity uses the upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) package `@honeybbq/teamspeak@1.0.0-beta.23`; a project SDK fork build is not required.
|
||||
|
||||
## 🧾 Changelog
|
||||
<a id="extensions"></a>
|
||||
|
||||
## Skins & functional plugins
|
||||
|
||||
### Skin packages `.wskin`
|
||||
|
||||
Skins own appearance, layout and their attached widgets. Administrators install, enable and choose the default skin. Authors use the public contract without changing WebSpeak source code.
|
||||
|
||||
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
|
||||
### Functional plugins `.wplugin`
|
||||
|
||||
Functional plugins are independent applications using standard browser capabilities and optional Node backends with their own routes, state and collaboration. Administrators review code and dependencies before enabling; updates require renewed trust. Applications support TS server or instance scope and run on a separate origin. API v2 is included starting with v0.3.0.
|
||||
|
||||
[Development guide](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Distribution catalog & example](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | What to check |
|
||||
| --- | --- |
|
||||
| WebRTC falls back after being enabled | Check the voice-status error code, HTTPS, the complete UDP firewall range and the public media address. A TCP Tunnel does not carry this UDP media path. |
|
||||
| A target is blocked as a local address | Open mode restricts loopback/private targets. Use the administrator-configured fixed-server mode for a co-located TS server; visitor-defined targets need a reachable address. |
|
||||
| Screen sharing times out or stays black | Screen sharing has a separate WebRTC connection. Inspect its negotiation, ICE and codec statistics; connected voice WebRTC does not prove screen-media reachability. |
|
||||
| Data is missing or cannot be decrypted after upgrading | Reuse the data directory or volume and its matching `master.key`. Do not upgrade with `docker compose down -v`. |
|
||||
|
||||
### ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
|
||||
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
|
||||
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
|
||||
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
|
||||
| Session limit | One instance admits up to 100 active browser sessions; this is an application limit, not a performance guarantee or TS license allowance. |
|
||||
|
||||
<a id="changelog"></a>
|
||||
|
||||
## Changelog
|
||||
|
||||
<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).
|
||||
- Day, Night and ILLUSIA open the app library from the top toolbar. KAAK 3.1.134 puts it in the leftmost icon rail and aligns its button with neighboring controls. Pinned apps appear first.
|
||||
- The plugin console adds a field editor, forms for P2P File Transfer, Watch Together and TSMusicBot, and links to plugin repositories.
|
||||
- Skin and plugin stores accept differences in display metadata while checking SHA-256, package format, and fields required for installation or execution.
|
||||
- Updated the skin and plugin development guides and Agent Skills for launcher layouts, configuration fields, and the separate HTTPS origin required for public plugin hosting.
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- Fixed lost Opus channel information and fixed 20 ms packet durations in WebSocket playback. WebRTC downlink mixing now preserves stereo. See #54.
|
||||
- Added Off, Standard and Strong noise suppression. Strong combines browser suppression with RNNoise. See #53.
|
||||
- The voice performance panel can export two minutes of gateway, voice and microphone diagnostics for disconnects and interrupted background capture. Background capture still depends on browser and OS policies. See #49 and #55.
|
||||
- Moved the plugin launcher into the voice workspace toolbar. Administrators can pin plugin shortcuts. See #56.
|
||||
- Added expiring private workspace invites and restored the KAAK welcome page. Fixed an obscured skin menu in the demo and premature timeouts on large skin downloads. The README now shows five skins.
|
||||
|
||||
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
|
||||
|
||||
#### Plugin applications
|
||||
|
||||
- Release plugin API v2 for independent browser applications and optional Node backends, with author-defined routes, state, communication and business logic.
|
||||
- Install applications from the GitHub store or local `.wplugin` packages. Administrators manage public/private configuration, review and enable applications; updates require renewed trust.
|
||||
- Add a skin-independent floating launcher and application library. Windows support dragging, resizing, minimize, maximize and restore; minimizing or returning to the library keeps the active application loaded.
|
||||
- Provide an application template, development guide and Agent Skill. P2P file transfer and Watch Together are distributed from separate repositories.
|
||||
|
||||
#### Skins and authorization
|
||||
|
||||
- Ask once on first entry for this instance’s third-party skins and plugins together, excluding connection credentials. The final Authorization item in the skin menu allows changes at any time.
|
||||
- Without consent, offer only Day, Night and ILLUSIA; hide KAAK, other third-party skins and plugin access. Revocation restores a built-in skin, cancels pending loads and stops related components and application pages.
|
||||
- Retain manifest permissions, data projection, package digests and host action checks. Administrator application review and trust remain independent.
|
||||
|
||||
#### Fixes and upgrades
|
||||
|
||||
- Fix native TS clients not answering video-only offers when sharing an application window, the entire screen or without shared audio. Negotiate the required audio section without capturing a microphone or fabricating shared sound. Window and full-screen video were confirmed by user retesting.
|
||||
- Upgrade to `@honeybbq/teamspeak@1.0.0-beta.23`, handle optional member fields and skip empty audio packets that mark the end of speech.
|
||||
- Include upstream TSDNS resolution, Query flooding retries, file transfer and disconnect cleanup fixes.
|
||||
- Include IPv6 target validation, bounded concurrent login, password-change session revocation, trusted-proxy rate limiting and PCM uplink protection fixes.
|
||||
- Retain and verify the skin cold-start fix that uses the real build version. Align application versions across desktop, web and Android.
|
||||
|
||||
#### Upgrading
|
||||
|
||||
- Plugin API v2 is incompatible with API v1 packages. Update, review and enable replacement applications.
|
||||
- Public plugin deployment requires a separate HTTPS application origin configured in administration and proxied to the runtime port (default `3042`). The application and main site must not share an origin.
|
||||
- Users must make a new instance authorization choice; old per-skin approvals do not imply consent.
|
||||
|
||||
|
||||
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
|
||||
|
||||
#### Enhancements
|
||||
@@ -217,6 +429,9 @@ Disable and save the relay configuration to remove the relay option from the wel
|
||||
|
||||
- The security hardening described in [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) is not included in this release; closing that PR does not mean the reported issues are fixed.
|
||||
|
||||
<details>
|
||||
<summary>Show v0.2.8 and earlier releases</summary>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### Screen sharing and connection reliability
|
||||
@@ -306,88 +521,33 @@ Fixed WebRTC and channel chat and refined administration, logs, and mobile layou
|
||||
|
||||
Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchronization and voice buffering.
|
||||
|
||||
</details>
|
||||
|
||||
## 🚀 Deployment
|
||||
<a id="contributors"></a>
|
||||
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64/ARM64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.12+, Git, and native build tools |
|
||||
## Contributors & attribution
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
|
||||
### First-time setup
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
|
||||
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
|
||||
|
||||
## ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
|
||||
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
|
||||
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
|
||||
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
|
||||
## Contributors and contributions
|
||||
<details>
|
||||
<summary>Show upstream authors and PR contributions</summary>
|
||||
|
||||
This list acknowledges the upstream SDK author, contributions through merged GitHub PRs, and original work adapted into independently distributed skin packages.
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — Author of the upstream [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK, which provides the TeamSpeak protocol client used by WebSpeak.
|
||||
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) reported security issues and supplied proposed fixes and regression tests for open-target IPv6 validation, admin authentication/sessions, proxy-aware limits and PCM uplink boundaries. The original patch was not merged directly; the fixes were reimplemented on `dev`.
|
||||
- [LainHE](https://github.com/LainHE) — [merged PRs #2, #8, #28, #31–#35, #37, #38 and #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE), covering browser error translations, scaling and home layout, screen-share bitrate and viewer avatars, relay target validation and recovery, trusted proxy handling, connection-failure propagation, audio fault reporting, and WebRTC failure cleanup.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [merged PRs #13 and #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep), covering existing TS6 share discovery, share aspect ratio, mobile voice/wake/skin-menu behavior, identity channel options, PWA/theme work, chat history, member audio states, and microphone permission.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added registered TeamSpeak nickname connections and preserved nickname targets; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) improved KAAK workspace retention and reconnection after the first connection. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) and [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) supplied the original Discord skin design and implementation (commit author **yumi**), later adapted by the WebSpeak project into an [independently distributed `.wskin` skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
|
||||
|
||||
</details>
|
||||
|
||||
## Community & related projects
|
||||
|
||||
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ group 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot): a TeamSpeak music bot with multi-platform playback and a web console.
|
||||
|
||||
## License
|
||||
|
||||
WebSpeak is distributed under [AGPL-3.0-only](../LICENSE). See each upstream project for third-party licenses and attribution.
|
||||
|
||||
<p align="right"><a href="#readme-top">Back to top ↑</a></p>
|
||||
+299
-82
@@ -1,111 +1,85 @@
|
||||
# WebSpeak · 日本語
|
||||
<a id="readme-top"></a>
|
||||
|
||||
[プロジェクトトップ](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md)
|
||||
<div align="center">
|
||||
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
|
||||
<h1>WebSpeak · 日本語</h1>
|
||||
<p><strong>ブラウザーから、いつもの TeamSpeak へ。</strong></p>
|
||||
<p><a href="../README.md">プロジェクトトップ</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.en.md">English</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ru.md">Русский</a></p>
|
||||
<p>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&color=0f766e" alt="Release" /></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## プロジェクト概要
|
||||
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
|
||||
|
||||
最新リリース:[v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9)。
|
||||
安定版:[v0.3.3 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · コンソール更新、復元処理、スキン互換性の改善。
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak は TeamSpeak 3 / TeamSpeak 6 向けのセルフホスト型ブラウザクライアント兼音声ゲートウェイです。 |
|
||||
| **WHY** | デスクトップクライアントをインストールせず、ブラウザからチャンネルに参加できます。運用者はサーバーとデータを管理できます。 |
|
||||
| **HOW** | 起動後、管理コンソールで TeamSpeak の接続先とアクセス方針を設定します。ブラウザが画面と音声を担当し、WebSpeak がゲートウェイとして接続します。 |
|
||||
|
||||
|
||||
[オンラインデモ](#demo) · [機能](#features) · [画面プレビュー](#screenshots) · [デプロイ](#deployment) · [管理](#administration) · [詳細設定](#advanced) · [スキンとプラグイン](#extensions) · [トラブル対処](#troubleshooting) · [更新履歴](#changelog)
|
||||
|
||||
<a id="demo"></a>
|
||||
|
||||
## オンラインデモ
|
||||
|
||||
- 上海: <https://shanghai.webspeak.online>
|
||||
- 香港: <https://webspeak.online>
|
||||
- [上海 · shanghai.webspeak.online](https://shanghai.webspeak.online)
|
||||
- [香港 · webspeak.online](https://webspeak.online)
|
||||
|
||||
各デモのネットワークや負荷は変動する場合があります。遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
ホームと音声ワークスペースを体験できます。デモのネットワーク、負荷、稼働状況は変動します。
|
||||
|
||||
## ✨ 機能
|
||||
<a id="features"></a>
|
||||
|
||||
| 機能 | 説明 |
|
||||
## 主な機能
|
||||
|
||||
| 機能 | 内容 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、サーバーのバージョンから対象プロトコルを自動検出します。 |
|
||||
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
|
||||
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
|
||||
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
|
||||
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
|
||||
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
|
||||
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンクに加え、TeamSpeak 3 ID のインポート、変換、検証、エクスポート。 |
|
||||
| 管理コンソール | 接続先、アクセス、公開メディアアドレス、IPv6 候補、音声 STUN、中継、招待、セッション、ログ、診断、バックアップ。 |
|
||||
| プロジェクト構造 | 0.2.6 では音声ゲートウェイ、セッションイベント、音声処理、画面共有調整を分割し、音声・管理画面をコンポーネント、composable、サービスに整理しました。ライフサイクルと再接続のテストも追加しました。 |
|
||||
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
|
||||
| デプロイ | Windows x64、Linux x64/ARM64 パッケージ、Docker amd64/arm64、Android arm64-v8a・armeabi-v7a・x86_64 APK。 |
|
||||
| リアルタイム音声 | Opus、任意の WebRTC、WebSocket へのフォールバック。ミュート、VOX、デバイス選択、ブラウザー側ノイズ抑制、メンバー別音量に対応。 |
|
||||
| チャンネルとメッセージ | チャンネルツリーと TeamSpeak 区切り、メンバー状態、移動、チャンネル・サーバー・個人チャット、Poke、ささやき、ローカル履歴。 |
|
||||
| 画面と音声の共有 | ブラウザー間および対応する TeamSpeak 6 クライアントとの画面共有。品質、ビットレート、統計を設定でき、デスクトップではウィンドウやタブの音声も共有可能。 |
|
||||
| ID と接続 | ID 保持、TS3 ID インポート・エクスポート、お気に入りと履歴、SRV・Nickname 名前解決、IPv4/IPv6、招待リンク。 |
|
||||
| インスタンス管理 | 固定・公開接続先、アクセス方針、招待、セッション、ログ、診断、バックアップ、任意の TeamSpeak 管理接続。 |
|
||||
| スキンと画面 | 昼・夜・ILLUSIA・KAAK、GitHub 経由の `.wskin` 配布、5 言語、レスポンシブ表示。 |
|
||||
| 分散音声 | ブラウザーが選択した中継の音声ゲートウェイに直接接続し、ページの URL は入口インスタンスのまま維持。 |
|
||||
| デプロイ方法 | Docker amd64/arm64、Windows x64・Linux x64/ARM64 サーバーパッケージ、Android プレビュー APK。 |
|
||||
|
||||
## TeamSpeak のバージョン互換性
|
||||
### TeamSpeak のバージョン互換性
|
||||
|
||||
音声接続には標準の TeamSpeak クライアントプロトコルを使い、Query の認証情報は不要です。任意の TS 管理機能では、別途 WebQuery / ServerQuery の認証情報を使用します。
|
||||
|
||||
- **TeamSpeak 3**: 先頭の `3.x` バージョンを使ってプロトコルを判定します。すべての旧バージョンを個別に検証しているわけではないため、古いサーバーは実際の環境で確認してください。
|
||||
- **TeamSpeak 6**: 対応しています。TeamSpeak 6 ネイティブクライアントとの画面共有も可能です。
|
||||
- **自動検出**: ゲートウェイはサーバーの `version` 応答を読み取り、接続診断に判定結果を記録します。
|
||||
- ゲートウェイは上流 SDK 1.0 の [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) を使用し、WebSpeak は TeamSpeak 3 と 6 を対象とします。
|
||||
- ゲートウェイは上流 SDK `1.0.0-beta.23` の [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) を使用し、WebSpeak は TeamSpeak 3 と 6 を対象とします。
|
||||
|
||||
## 任意の TeamSpeak 管理
|
||||
<a id="screenshots"></a>
|
||||
|
||||
WebSpeak 管理画面と音声接続は、この機能に依存しません。固定サーバーモードで `/admin/ts-admin` を開き、TS 管理用の接続を設定します。
|
||||
## 画面プレビュー
|
||||
|
||||
1. TS サーバーで WebQuery を有効にし、権限のある TS 管理者に API キーを作成してもらいます。WebQuery の HTTP/HTTPS URL とキーを入力します。WebSpeak のサイトではなく、TS Query サービスの URL です。TS3(3.12 以降)と TS6 に対応します。
|
||||
2. 仮想サーバー ID `0` は固定接続先の音声ポートから選択します。制限付きキーでは許可された ID を入力してください。読み取りキーでは閲覧ができ、変更には書き込み可能なスコープと対応する TS 権限が必要です。
|
||||
3. ServerQuery SSH、または TS3 の ServerQuery TCP も選べます。Query ホスト(空欄は固定接続先)、ポート、ユーザー名、パスワードを入力し、SSH では信頼できるホストキーのフィンガープリントも指定します。OS への SSH ログインではありません。TCP は暗号化されないため信頼できるネットワークで使用します。HTTPS 証明書はゲートウェイで信頼されている必要があります。
|
||||
4. 保存して接続または更新します。サーバー設定、チャンネル管理、メンバーの移動・退出・ID による BAN、グループ割り当て、BAN 解除に対応します。操作には確認が必要で、TS が権限を検証します。リストは手動更新します。
|
||||

|
||||
|
||||
認証情報はサーバーで暗号化され、API から返されません。データベースと `master.key` を一緒にバックアップしてください。管理接続の失敗は WebSpeak 管理画面や音声に影響しません。UID による BAN で同じゲートウェイ IP を使う他のユーザーへの影響を避けます。
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
<details>
|
||||
<summary>ホーム、オーディオ設定、メンバーメニューを表示</summary>
|
||||
|
||||
### ホーム
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
|
||||
|
||||
### 音声ワークスペース
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
|
||||

|
||||
|
||||
### オーディオ設定
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
|
||||

|
||||
|
||||
### メンバーメニュー
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
|
||||

|
||||
|
||||
## 🧩 高度な機能
|
||||
</details>
|
||||
|
||||
### WebRTC
|
||||
<a id="deployment"></a>
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
## デプロイと初期設定
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
|
||||
|
||||
### クロスプラットフォーム P2P 画面共有
|
||||
|
||||
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
|
||||
|
||||
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続は上流の [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) が公開する `@honeybbq/teamspeak@1.0.0-beta.19` を使用します。SDK フォークのビルドは不要になりました。
|
||||
|
||||
## 🚀 デプロイ
|
||||
Compose は `network_mode: host` を使う Linux Docker ホスト向けの構成です。Windows サーバーには Release パッケージを使用してください。
|
||||
|
||||
| 方法 | 用途 |
|
||||
| --- | --- |
|
||||
@@ -124,6 +98,19 @@ docker compose up -d
|
||||
|
||||
起動後に `http://<your-host>:3040/admin` を開き、`admin` / `admin` でログインして直ちにパスワードを変更し、TeamSpeak を設定します。データは `webspeak-data` volume に保存されます。データベースを消さない場合は `docker compose down -v` を実行しないでください。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
データを保持して更新:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Release パッケージ
|
||||
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から `windows-x64.zip`、`linux-x64.tar.gz`、`linux-arm64.tar.gz` のいずれかを取得し、同梱ランチャーを実行します。Docker は amd64/arm64 に対応します。`arm64-v8a`、`armeabi-v7a`、`x86_64` の Android APK もあります。APK は手動インストールとテスト向けのデバッグ署名で、Google Play 用ではありません。実機 TeamSpeak 音声は未検証です。
|
||||
@@ -131,15 +118,146 @@ docker compose up -d
|
||||
### ソースから
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run web:build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ 要件と注意
|
||||
ビルドには Node.js `>=22.12`、Python、Make、C/C++ コンパイラーが必要です。
|
||||
|
||||
### 初期設定
|
||||
|
||||
1. `http://<your-host>:3040/admin` を開きます。
|
||||
2. `admin` / `admin` でログインし、直ちに 12 文字以上の新しいパスワードに変更します。
|
||||
3. **サーバー**で `voice.example.com#9987` などの接続先とアクセスモードを設定します。
|
||||
4. 公開時は HTTPS を設定し、WebRTC 有効時は指定した UDP 範囲全体を許可します。
|
||||
|
||||
### HTTPS とデータ保持
|
||||
|
||||
公開ページと WebSocket は HTTPS で提供してください。例えば、自分のドメインをホストに向け、Caddy から WebSpeak へ転送します。
|
||||
|
||||
```caddyfile
|
||||
webspeak.example.com {
|
||||
reverse_proxy 127.0.0.1:3040
|
||||
}
|
||||
```
|
||||
|
||||
例のドメインは自分のものに置き換えてください。リバースプロキシや Tunnel でページが開けても、WebRTC の UDP が到達可能とは限りません。[詳細設定](#advanced)を確認してください。パッケージとソースは `data/`、Docker は `webspeak-data` volume を使用します。移行・バックアップ時は `webspeak.db` と対応する `master.key` を一緒に保存します。
|
||||
|
||||
<a id="administration"></a>
|
||||
|
||||
## 管理コンソール
|
||||
|
||||
`/admin` で接続先、アクセス、WebRTC、中継、招待、アクティブセッション、ログ、バックアップを管理します。スキンストアは `/admin/skins`、機能プラグインストアは `/admin/plugins` です。
|
||||
|
||||
### 任意の TeamSpeak 管理
|
||||
|
||||
WebSpeak 管理画面と音声接続は、この機能に依存しません。固定サーバーモードで `/admin/ts-admin` を開き、TS 管理用の接続を設定します。
|
||||
|
||||
1. TS サーバーで WebQuery を有効にし、権限のある TS 管理者に API キーを作成してもらいます。WebQuery の HTTP/HTTPS URL とキーを入力します。WebSpeak のサイトではなく、TS Query サービスの URL です。TS3(3.12 以降)と TS6 に対応します。
|
||||
2. 仮想サーバー ID `0` は固定接続先の音声ポートから選択します。制限付きキーでは許可された ID を入力してください。読み取りキーでは閲覧ができ、変更には書き込み可能なスコープと対応する TS 権限が必要です。
|
||||
3. ServerQuery SSH、または TS3 の ServerQuery TCP も選べます。Query ホスト(空欄は固定接続先)、ポート、ユーザー名、パスワードを入力し、SSH では信頼できるホストキーのフィンガープリントも指定します。OS への SSH ログインではありません。TCP は暗号化されないため信頼できるネットワークで使用します。HTTPS 証明書はゲートウェイで信頼されている必要があります。
|
||||
4. 保存して接続または更新します。サーバー設定、チャンネル管理、メンバーの移動・退出・ID による BAN、グループ割り当て、BAN 解除に対応します。操作には確認が必要で、TS が権限を検証します。リストは手動更新します。
|
||||
|
||||
認証情報はサーバーで暗号化され、API から返されません。データベースと `master.key` を一緒にバックアップしてください。管理接続の失敗は WebSpeak 管理画面や音声に影響しません。UID による BAN で同じゲートウェイ IP を使う他のユーザーへの影響を避けます。
|
||||
|
||||
<a id="advanced"></a>
|
||||
|
||||
## 詳細設定
|
||||
|
||||
### WebRTC
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
|
||||
### リバースプロキシ・TCP Tunnel 経由の音声 WebRTC
|
||||
|
||||
**サーバー → 詳細設定** の**公開メディアアドレス**には、UDP で到達可能な音声ゲートウェイの IP またはドメインを入力します。スキーム、パス、ポートは含めません。ページのリクエストから推測する接続先より優先され、プロキシのドメインが音声にも到達可能とは限りません。
|
||||
|
||||
**IPv6 候補**は任意で、IPv4 も維持します。IPv6 の経路とファイアウォール許可が必要です。**音声 STUN** に `stun:turn.teamspeak.com:3478` を設定すると、ブラウザーとゲートウェイが同じサービスを使います。空欄では従来どおり、ゲートウェイのライブラリ内蔵 STUN を使い、ブラウザーには設定しません。IPv4 で到達可能な UDP STUN ドメイン・IPv4 アドレスに対応し、IPv6 リテラルや TURN 認証情報は指定できません。
|
||||
|
||||
保存後に再接続してください。UDP 範囲全体を許可し、固定ポート転送では番号を維持します。STUN はアドレスを検出するだけで音声を中継しません。利用可能な UDP/IPv6 経路のない TCP Tunnel だけでは、互換転送に戻ります。
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
|
||||
|
||||
### クロスプラットフォーム P2P 画面共有
|
||||
|
||||
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
入口ゲートウェイが署名付きの一度限りのチケットを発行し、ブラウザーは中継の音声ゲートウェイに直接接続します。中継が TeamSpeak に接続し、ページの URL はそのままです。中継ノードはホームや管理コンソールを提供しません。
|
||||
|
||||
<details>
|
||||
<summary>中継の起動と設定</summary>
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
-e WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST='relay.example.com' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
共通トークンはランダムな 16 文字以上にします。音声ゲートウェイは `127.0.0.1:3041` で待ち受けるため、Caddy などで HTTPS/WSS ドメインから転送します。
|
||||
|
||||
```caddyfile
|
||||
relay.example.com {
|
||||
reverse_proxy 127.0.0.1:3041
|
||||
}
|
||||
```
|
||||
|
||||
入口側の**サーバー → 中継**で、名前、UDP 接続先 `relay.example.com#39087`、音声接続先 `https://relay.example.com`、同じトークンを設定して保存します。ユーザーは直接接続か中継を選べます。UDP `39087` と WebRTC の `40000–40099` を許可してください。公開メディアアドレスは HTTP プロキシではなく、中継に直接到達できる必要があります。
|
||||
|
||||
ソースや Release パッケージでも同じ環境変数を指定します。ビルド後は `node dist/index.js`、パッケージでは `./runtime/node ./dist/index.js`(Windows:`.\runtime\node.exe .\dist\index.js`)で起動します。
|
||||
|
||||
</details>
|
||||
|
||||
### 依存ライブラリ
|
||||
|
||||
中継は WebSpeak に組み込まれ、Node.js 標準ライブラリを使います。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`、TeamSpeak は上流 [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) の `@honeybbq/teamspeak@1.0.0-beta.23` を使用し、fork のビルドは不要です。
|
||||
|
||||
<a id="extensions"></a>
|
||||
|
||||
## スキンと機能プラグイン
|
||||
|
||||
### スキンパッケージ `.wskin`
|
||||
|
||||
スキンは外観、配置、付属ウィジェットを扱います。管理者がインストール、有効化、デフォルト選択を行い、開発者は WebSpeak のソースを変更せず公開 API で制作します。
|
||||
|
||||
[開発ガイド](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [スキン一覧](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice サンプル](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
|
||||
### 機能プラグイン `.wplugin`
|
||||
|
||||
機能プラグインは標準ブラウザー機能と任意の Node バックエンドを使う独立アプリです。ルート、状態、共同作業は作者が実装します。管理者はコードと依存関係を審査して有効化し、更新後は再び信頼を確認します。TS サーバーまたはインスタンス範囲に対応し、別オリジンで動作します。API v2 は v0.3.0 から利用できます。
|
||||
|
||||
[開発ガイド](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [配布一覧とサンプル](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
|
||||
## トラブル対処
|
||||
|
||||
| 症状 | 確認する内容 |
|
||||
| --- | --- |
|
||||
| WebRTC を有効にしてもフォールバックする | 音声状態のエラーコード、HTTPS、UDP 範囲全体、公開メディアアドレスを確認します。TCP Tunnel はこの UDP メディア経路を転送しません。 |
|
||||
| ローカルアドレス保護で接続先が拒否される | 公開モードはループバック・プライベートアドレスを制限します。同じホストの TS には、管理者が設定する固定サーバーモードを使います。 |
|
||||
| 画面共有がタイムアウトする・黒いまま | 画面共有は独立した WebRTC 接続です。共有統計のネゴシエーション、ICE、コーデックを確認します。音声の接続成功だけでは画面の到達性を確認できません。 |
|
||||
| 更新後にデータがない・復号できない | 元のデータディレクトリまたは volume と対応する `master.key` を使います。`docker compose down -v` で更新しないでください。 |
|
||||
|
||||
### ⚠️ 要件と注意
|
||||
|
||||
- ソースからのビルドには Node.js `>=22.12` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
|
||||
@@ -149,16 +267,75 @@ npm start
|
||||
- 保存したブラウザ ID は同じブラウザで同時に1接続だけ使用できます。
|
||||
- BGM共有はデスクトップのみで、WebRTC が必要です。
|
||||
|
||||
## コミュニティと関連プロジェクト
|
||||
- WebRTC の初期範囲は UDP `40000–40099` です。全体を許可し、変更前に WebRTC を無効化して保存します。
|
||||
- アプリケーションの上限は 1 インスタンス 100 ブラウザーセッションです。性能保証や TS ライセンス上限を示すものではありません。
|
||||
|
||||
- [QQ グループ](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram グループ](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — Web コンソール付き TeamSpeak 音楽ボット。
|
||||
<a id="changelog"></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
|
||||
|
||||
- サードパーティースキンでホストの装飾を変更できます。復元と許可の操作は WebSpeak が管理し、組み込みスキンに戻せます。TS3 判定と互換性情報の ph1gros(#46)、ホスト装飾と復元機能の OddTurtleHead(#57)に感謝します。
|
||||
- 日間、夜間、ILLUSIA では上部バーからアプリライブラリを開けます。KAAK 3.1.134 では左端のアイコン列に移動し、隣のボタンとサイズを揃えました。固定したアプリは先頭に表示されます。
|
||||
- 管理画面にフィールドエディター、P2P ファイル転送・動画の同時視聴・TSMusicBot の設定フォーム、各リポジトリへのリンクを追加しました。
|
||||
- ストアでは表示情報の差異を許容し、SHA-256、パッケージ形式、インストールや実行に必要な項目を検証します。
|
||||
- 開発ガイドと Agent Skill に、アプリ入口の配置、設定項目、公開プラグインに必要な独立した HTTPS オリジンを記載しました。
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- WebSocket 再生で Opus のチャンネル情報と実際のパケット長を扱うよう修正しました。WebRTC の下りミックスでもステレオを維持します。関連 #54。
|
||||
- ノイズ抑制にオフ・標準・強の3段階を追加しました。強ではブラウザーのノイズ抑制と RNNoise を併用します。関連 #53。
|
||||
- 音声パネルから直近2分間のゲートウェイ、音声、マイクの診断をエクスポートできます。バックグラウンドでの録音はブラウザーと OS の制約を受けます。関連 #49、#55。
|
||||
- プラグインの入口を音声ワークスペースのツールバーに移動し、管理者がショートカットを固定できるようにしました。関連 #56。
|
||||
- 有効期限付きの非公開招待を追加し、KAAK のウェルカム画面を復元しました。デモのスキンメニューが隠れる問題と、大きなスキンのダウンロードが早くタイムアウトする問題を修正しました。README に5種類のスキン画像を追加しました。
|
||||
|
||||
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
|
||||
|
||||
#### プラグインアプリ
|
||||
|
||||
- 独立したブラウザアプリと任意の Node バックエンドに対応するプラグイン API v2 を公開。作者がルート、状態、通信、機能を実装できます。
|
||||
- GitHub ストアまたはローカルの `.wplugin` からインストール。管理者が公開・非公開設定を管理し、確認して有効化します。更新後は再度信頼の確認が必要です。
|
||||
- スキンに依存しないフローティング起動ボタンとアプリライブラリを追加。ウィンドウの移動、サイズ変更、最小化、最大化、復元に対応し、最小化やライブラリへの移動でもアプリを再読み込みしません。
|
||||
- アプリテンプレート、開発ガイド、Agent Skill を提供。P2P ファイル転送と動画の同時視聴は独立リポジトリで配布します。
|
||||
|
||||
#### スキンと許可
|
||||
|
||||
- 初回アクセス時に、インスタンスのサードパーティ製スキンとプラグインをまとめて確認します。接続用の認証情報は含みません。スキンメニュー末尾の「許可」から変更できます。
|
||||
- 同意しない場合は昼・夜・ILLUSIA のみ利用でき、KAAK、その他のスキン、プラグイン入口は非表示になります。許可を取り消すと内蔵スキンに戻り、読み込み処理、関連コンポーネント、アプリページを停止します。
|
||||
- マニフェストの権限、データ投影、ファイルハッシュ、ホスト操作の検証は維持します。管理者による確認と信頼は別途必要です。
|
||||
|
||||
#### 修正と更新
|
||||
|
||||
- ウィンドウ、画面全体、音声なしの共有で、映像のみの offer にネイティブ TS クライアントが応答しない問題を修正。必要な音声セクションを交渉しますが、マイクの収録や音声の生成は行いません。ウィンドウと画面全体での表示はユーザーの再テストで確認済みです。
|
||||
- SDK を `@honeybbq/teamspeak@1.0.0-beta.23` に更新。省略可能なメンバーフィールドに対応し、発話終了を表す空の音声パケットを除外します。
|
||||
- upstream の TSDNS、Query の制限時リトライ、ファイル転送、切断処理の修正を取り込みました。
|
||||
- IPv6 の接続先検証、並列ログイン制限、パスワード変更時のセッション失効、信頼済みプロキシの制限、PCM 送信保護を修正しました。
|
||||
- スキンの初回読み込みに実際のビルドバージョンを使用する修正を維持。デスクトップ、Web、Android のアプリバージョンを統一しました。
|
||||
|
||||
#### アップグレード
|
||||
|
||||
- API v2 は v1 のプラグインと互換性がありません。対応アプリへ更新し、確認後に有効化してください。
|
||||
- 公開環境のプラグインには、管理画面で設定した独立 HTTPS オリジンと実行ポート(既定 `3042`)へのプロキシが必要です。メインサイトと同じオリジンは使用できません。
|
||||
- インスタンス単位の許可を改めて選択してください。旧スキン単位の許可は同意として引き継がれません。
|
||||
|
||||
|
||||
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
|
||||
|
||||
#### 機能追加
|
||||
@@ -181,6 +358,9 @@ npm start
|
||||
|
||||
- [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) のセキュリティ強化は本リリースに含まれません。PR のクローズは、報告された問題の修正完了を意味しません。
|
||||
|
||||
<details>
|
||||
<summary>v0.2.8 以前の履歴を表示</summary>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### 画面共有と接続の安定性
|
||||
@@ -250,16 +430,53 @@ npm start
|
||||
|
||||
Docker 起動を簡略化し、15秒の接続タイムアウトと継続的なネットワーク監視を追加しました。
|
||||
|
||||
### [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) · 2026-09-06
|
||||
|
||||
## ライセンス
|
||||
ドイツ語、Telegram、ネットワーク統計、全体音量を追加し、BGM 音量の変動を修正しました。
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
|
||||
### [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) · 2026-09-04
|
||||
|
||||
ウィンドウ・タブ音声の共有、ID 保持の案内、サイトアイコンを追加し、WebRTC のメンバー別音量を修正しました。
|
||||
|
||||
### [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) · 2026-09-04
|
||||
|
||||
ID 保存処理を修正し、テーマ切り替えを改善しました。
|
||||
|
||||
### [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) · 2026-09-03
|
||||
|
||||
WebRTC とチャンネルチャットを修正し、管理画面、ログ、モバイル配置を改善しました。
|
||||
|
||||
### [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) · 2026-09-03
|
||||
|
||||
内蔵 WebRTC を追加し、TeamSpeak SDK を移行しました。メンバー同期と音声バッファーを改善しました。
|
||||
|
||||
</details>
|
||||
|
||||
<a id="contributors"></a>
|
||||
|
||||
## 貢献者と主な貢献
|
||||
|
||||
<details>
|
||||
<summary>上流作者と PR の貢献を表示</summary>
|
||||
|
||||
上流 SDK の作者、マージ済みの GitHub PR、および独立配布のスキンパッケージへ移植された原作の貢献を記載しています。
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上流 SDK [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) の作者。WebSpeak の TeamSpeak プロトコル通信を支えるクライアントライブラリを提供。
|
||||
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) で IPv6 接続先検証、管理者認証とセッション、プロキシ配下の制限、PCM 送信境界の問題を報告し、修正案と回帰テストを提供。元のパッチは直接マージせず、`dev` で改めて修正を実装しました。
|
||||
- [LainHE](https://github.com/LainHE) — [マージ済み PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE)。ブラウザのエラー翻訳、拡大縮小とホームのレイアウト、画面共有のビットレートと視聴者アバター、中継先の検証と再接続、信頼済みプロキシの扱い、接続失敗の通知、音声エラー報告、WebRTC 失敗時のリソース解放を改善。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [マージ済み PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep)。既存 TS6 共有の検出、画面比率、モバイル音声・画面点灯・スキンメニュー、ID のチャンネル設定、PWA/テーマ、チャット履歴、メンバー音声状態、マイク権限などに貢献。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネーム接続と接続先の保持に対応し、[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) で初回接続後の KAAK ワークスペース保持と再接続を改善。[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) と [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) では Discord スキンの原作デザインと実装を提供(コミット名義 **yumi**)。その後、WebSpeak プロジェクトが[独立配布の `.wskin` スキン](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)へ移植。
|
||||
|
||||
</details>
|
||||
|
||||
## コミュニティと関連プロジェクト
|
||||
|
||||
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ グループ 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot):複数サービスの再生と Web コンソールに対応した TeamSpeak 音楽ボット。
|
||||
|
||||
## ライセンス
|
||||
|
||||
WebSpeak は [AGPL-3.0-only](../LICENSE) で公開しています。依存ライブラリのライセンスと帰属は各上流プロジェクトを参照してください。
|
||||
|
||||
<p align="right"><a href="#readme-top">先頭へ ↑</a></p>
|
||||
+297
-82
@@ -1,113 +1,85 @@
|
||||
# WebSpeak · Русский
|
||||
<a id="readme-top"></a>
|
||||
|
||||
[Главная проекта](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [日本語](./README.ja.md)
|
||||
<div align="center">
|
||||
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
|
||||
<h1>WebSpeak · Русский</h1>
|
||||
<p><strong>Ваше сообщество TeamSpeak — прямо в браузере.</strong></p>
|
||||
<p><a href="../README.md">Главная проекта</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.en.md">English</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ja.md">日本語</a></p>
|
||||
<p>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&color=0f766e" alt="Release" /></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## О проекте
|
||||
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
|
||||
|
||||
Последний выпуск: [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9).
|
||||
Стабильный выпуск: [изменения v0.3.3](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Обновление из консоли, восстановление и улучшенная совместимость скинов.
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak — самостоятельно размещаемый веб-клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. |
|
||||
| **WHY** | Пользователям не нужно устанавливать настольный клиент: достаточно открыть браузер, а оператор сохраняет контроль над сервером и данными. |
|
||||
| **HOW** | После запуска настройте цель TeamSpeak и политику доступа в панели администратора. Браузер отвечает за интерфейс и аудио, WebSpeak — за шлюз. |
|
||||
|
||||
|
||||
[Онлайн-демо](#demo) · [Возможности](#features) · [Скриншоты](#screenshots) · [Развёртывание](#deployment) · [Управление](#administration) · [Расширенные настройки](#advanced) · [Скины и плагины](#extensions) · [Решение проблем](#troubleshooting) · [История изменений](#changelog)
|
||||
|
||||
<a id="demo"></a>
|
||||
|
||||
## Онлайн-демо
|
||||
|
||||
Адреса:
|
||||
- [Шанхай · shanghai.webspeak.online](https://shanghai.webspeak.online)
|
||||
- [Гонконг · webspeak.online](https://webspeak.online)
|
||||
|
||||
- Шанхай: <https://shanghai.webspeak.online>
|
||||
- Гонконг: <https://webspeak.online>
|
||||
Попробуйте главную страницу и голосовое пространство. Сеть, нагрузка и доступность демонстрационных узлов могут меняться.
|
||||
|
||||
Сеть и нагрузка на обоих демо-серверах могут быть нестабильными. Задержки, разрывы или временная недоступность не характеризуют самостоятельное развертывание.
|
||||
<a id="features"></a>
|
||||
|
||||
## ✨ Возможности
|
||||
## Возможности
|
||||
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола по версии сервера. |
|
||||
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
|
||||
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
|
||||
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
|
||||
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
|
||||
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
|
||||
| Идентичность и доступ | Сохранение идентичности, собственные цели, приглашения с ограничением срока и числа использований, а также импорт, преобразование, проверка и экспорт идентификаторов TeamSpeak 3. |
|
||||
| Панель администратора | Цели, доступ, публичный адрес медиа, IPv6-кандидаты, голосовой STUN, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
|
||||
| Структура проекта | В 0.2.6 голосовой шлюз, события сессий, аудио и координация демонстрации разделены на модули; голосовые и административные страницы — на компоненты, composables и сервисы. Добавлены тесты жизненного цикла и переподключения. |
|
||||
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
|
||||
| Развёртывание | Пакеты Windows x64 и Linux x64/ARM64, Docker amd64/arm64, Android APK для arm64-v8a, armeabi-v7a и x86_64. |
|
||||
| Голос | Opus, необязательный WebRTC и резервный WebSocket; отключение микрофона, VOX, выбор устройств, шумоподавление в браузере и громкость участников. |
|
||||
| Каналы и сообщения | Дерево и разделители каналов TeamSpeak, состояние участников, переходы, чат канала/сервера/личный чат, толчки, шёпот и локальная история. |
|
||||
| Экран и аудио | Обмен экраном между браузерами и поддерживаемыми нативными клиентами TeamSpeak 6, настройки качества, битрейта и статистика; звук окна или вкладки на компьютере. |
|
||||
| Идентичность и подключения | Сохранение идентичности, импорт/экспорт TS3, избранное и история, разрешение SRV и Nickname, IPv4/IPv6 и приглашения. |
|
||||
| Управление экземпляром | Фиксированные или открытые цели, доступ, приглашения, сессии, журналы, диагностика, резервные копии и необязательное управление TeamSpeak. |
|
||||
| Скины и интерфейс | Дневная, ночная, ILLUSIA и KAAK, пакеты `.wskin` через GitHub, пять языков и адаптивная вёрстка. |
|
||||
| Распределённый голос | Браузер подключается напрямую к выбранному голосовому ретранслятору, сохраняя URL входного экземпляра. |
|
||||
| Развёртывание | Docker amd64/arm64, серверные пакеты Windows x64 и Linux x64/ARM64, а также предварительные Android APK. |
|
||||
|
||||
## Совместимость версий TeamSpeak
|
||||
### Совместимость версий TeamSpeak
|
||||
|
||||
Голосовые соединения используют стандартный клиентский протокол TeamSpeak и не требуют учётных данных Query. Необязательное управление TS использует отдельные данные WebQuery / ServerQuery.
|
||||
|
||||
- **TeamSpeak 3**: определение распознаёт ведущую версию `3.x`. Старые версии сервера следует проверять отдельно в конкретной среде: не каждая историческая версия тестировалась независимо.
|
||||
- **TeamSpeak 6**: поддерживается, включая демонстрацию экрана с нативными клиентами TeamSpeak 6.
|
||||
- **Автоопределение**: шлюз читает ответ сервера `version` и записывает распознанный протокол в диагностику подключения.
|
||||
- Шлюз использует upstream SDK 1.0 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak рассчитан на TeamSpeak 3 и 6.
|
||||
- Шлюз использует upstream SDK `1.0.0-beta.23` [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak рассчитан на TeamSpeak 3 и 6.
|
||||
|
||||
## Необязательное управление TeamSpeak
|
||||
<a id="screenshots"></a>
|
||||
|
||||
Панель WebSpeak и голосовые соединения работают независимо от этой функции. В режиме фиксированного сервера откройте `/admin/ts-admin` для настройки управления TS.
|
||||
## Скриншоты
|
||||
|
||||
1. Включите WebQuery на сервере TS и попросите уполномоченного администратора TS создать API-ключ. Укажите HTTP/HTTPS-адрес WebQuery и ключ. Это Query-служба TS, а не сайт WebSpeak. Поддерживаются TS3 начиная с 3.12 и TS6.
|
||||
2. ID виртуального сервера `0` выбирает сервер по голосовому порту фиксированной цели. Для ограниченного ключа укажите разрешённый ID. Ключ чтения позволяет просматривать данные; изменения требуют области с правом записи и соответствующих прав TS.
|
||||
3. Можно выбрать ServerQuery SSH или ServerQuery TCP для TS3. Укажите Query-хост (пустое поле использует фиксированную цель), порт, имя пользователя и пароль; SSH также требует доверенный отпечаток ключа хоста. Это не SSH-вход в операционную систему. TCP не шифруется и подходит только для доверенных сетей. HTTPS-сертификат должен быть доверенным для шлюза.
|
||||
4. Сохраните и подключитесь или обновите данные. Доступны настройки сервера, управление каналами, перемещение/исключение/блокировка участников, назначение групп и снятие блокировок. Действия требуют подтверждения и проверяются TS; списки обновляются вручную.
|
||||

|
||||
|
||||
Учётные данные хранятся на сервере в зашифрованном виде и не возвращаются API. Сохраняйте базу данных вместе с `master.key`. Ошибка управления не влияет на панель WebSpeak и голос. Блокировка по UID не затрагивает других пользователей с общим IP шлюза.
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
<details>
|
||||
<summary>Показать главную страницу, настройки аудио и меню участника</summary>
|
||||
|
||||
### Главная страница
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Голосовое пространство
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
|
||||

|
||||
|
||||
### Настройки аудио
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
|
||||

|
||||
|
||||
### Меню участника
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
|
||||

|
||||
|
||||
## 🧩 Расширенные функции
|
||||
</details>
|
||||
|
||||
### WebRTC
|
||||
<a id="deployment"></a>
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
## Развёртывание и первый запуск
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
|
||||
|
||||
### Кроссплатформенная P2P-трансляция экрана
|
||||
|
||||
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
|
||||
|
||||
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), пакет `@honeybbq/teamspeak@1.0.0-beta.19`. Сборка форка SDK больше не требуется.
|
||||
|
||||
## 🚀 Развертывание
|
||||
Compose использует `network_mode: host` и рассчитан на Linux-хосты Docker. Для сервера Windows используйте пакет Release.
|
||||
|
||||
| Способ | Подходит для |
|
||||
| --- | --- |
|
||||
@@ -126,6 +98,19 @@ docker compose up -d
|
||||
|
||||
После запуска откройте `http://<ваш-хост>:3040/admin`, войдите с `admin` / `admin`, сразу смените пароль и настройте TeamSpeak. Данные хранятся в volume `webspeak-data`. Не используйте `docker compose down -v`, если не хотите удалить базу и настройки.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Обновление с сохранением данных:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Пакет Release
|
||||
|
||||
Скачайте подходящий пакет `windows-x64.zip`, `linux-x64.tar.gz` или `linux-arm64.tar.gz` из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) и запустите приложенный скрипт. Docker поддерживает amd64/arm64. Также доступны Android APK для `arm64-v8a`, `armeabi-v7a` и `x86_64`; они подписаны отладочным ключом для ручной установки и тестирования, а не для Google Play. Голос TeamSpeak на реальных устройствах пока не проверен.
|
||||
@@ -133,15 +118,146 @@ docker compose up -d
|
||||
### Из исходников
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run web:build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ Требования и замечания
|
||||
Для сборки нужны Node.js `>=22.12`, Python, Make и компилятор C/C++.
|
||||
|
||||
### Первый запуск
|
||||
|
||||
1. Откройте `http://<your-host>:3040/admin`.
|
||||
2. Войдите с `admin` / `admin` и сразу задайте новый пароль длиной не менее 12 символов.
|
||||
3. В разделе **Сервер** настройте цель, например `voice.example.com#9987`, и режим доступа.
|
||||
4. Для публичного доступа настройте HTTPS; при включении WebRTC откройте весь указанный диапазон UDP.
|
||||
|
||||
### HTTPS и постоянные данные
|
||||
|
||||
Публичную страницу и WebSocket следует предоставлять по HTTPS. Например, направьте свой домен на хост и настройте Caddy как обратный прокси:
|
||||
|
||||
```caddyfile
|
||||
webspeak.example.com {
|
||||
reverse_proxy 127.0.0.1:3040
|
||||
}
|
||||
```
|
||||
|
||||
Замените домен примера своим. Рабочий обратный прокси или Tunnel не гарантирует доступность UDP-медиа; см. [расширенные настройки](#advanced). Пакеты и исходники используют `data/`, Docker — volume `webspeak-data`. При переносе и резервном копировании сохраняйте вместе `webspeak.db` и соответствующий `master.key`.
|
||||
|
||||
<a id="administration"></a>
|
||||
|
||||
## Панель администратора
|
||||
|
||||
Откройте `/admin` для управления серверами, доступом, WebRTC, ретрансляторами, приглашениями, активными сессиями, журналами и резервными копиями. Магазин скинов: `/admin/skins`; магазин функциональных плагинов: `/admin/plugins`.
|
||||
|
||||
### Необязательное управление TeamSpeak
|
||||
|
||||
Панель WebSpeak и голосовые соединения работают независимо от этой функции. В режиме фиксированного сервера откройте `/admin/ts-admin` для настройки управления TS.
|
||||
|
||||
1. Включите WebQuery на сервере TS и попросите уполномоченного администратора TS создать API-ключ. Укажите HTTP/HTTPS-адрес WebQuery и ключ. Это Query-служба TS, а не сайт WebSpeak. Поддерживаются TS3 начиная с 3.12 и TS6.
|
||||
2. ID виртуального сервера `0` выбирает сервер по голосовому порту фиксированной цели. Для ограниченного ключа укажите разрешённый ID. Ключ чтения позволяет просматривать данные; изменения требуют области с правом записи и соответствующих прав TS.
|
||||
3. Можно выбрать ServerQuery SSH или ServerQuery TCP для TS3. Укажите Query-хост (пустое поле использует фиксированную цель), порт, имя пользователя и пароль; SSH также требует доверенный отпечаток ключа хоста. Это не SSH-вход в операционную систему. TCP не шифруется и подходит только для доверенных сетей. HTTPS-сертификат должен быть доверенным для шлюза.
|
||||
4. Сохраните и подключитесь или обновите данные. Доступны настройки сервера, управление каналами, перемещение/исключение/блокировка участников, назначение групп и снятие блокировок. Действия требуют подтверждения и проверяются TS; списки обновляются вручную.
|
||||
|
||||
Учётные данные хранятся на сервере в зашифрованном виде и не возвращаются API. Сохраняйте базу данных вместе с `master.key`. Ошибка управления не влияет на панель WebSpeak и голос. Блокировка по UID не затрагивает других пользователей с общим IP шлюза.
|
||||
|
||||
<a id="advanced"></a>
|
||||
|
||||
## Расширенные настройки
|
||||
|
||||
### WebRTC
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
|
||||
### Голосовой WebRTC за обратным прокси или TCP Tunnel
|
||||
|
||||
В **Сервер → Расширенные настройки** задайте **публичный адрес медиа**: доступный по UDP IP или домен голосового шлюза без схемы, пути и порта. Он заменяет адрес, определяемый по запросу страницы. Домен прокси не обязательно доступен для медиатрафика.
|
||||
|
||||
**IPv6-кандидаты** включаются отдельно и сохраняют IPv4; необходимы маршрутизация IPv6 и правила firewall. В поле **голосовой STUN** можно указать `stun:turn.teamspeak.com:3478`: браузер и шлюз используют один сервис. Пустое поле сохраняет прежнее поведение: встроенный STUN библиотеки шлюза и отсутствие STUN в браузере. Поле принимает доступный по IPv4 UDP STUN с доменом или IPv4, но не IPv6-литералы и не учётные данные TURN.
|
||||
|
||||
Сохраните настройки и подключитесь заново. Откройте весь диапазон UDP и сохраняйте номера портов при статическом пробросе. STUN обнаруживает отображения адресов, но не ретранслирует звук. Один TCP Tunnel без доступного UDP/IPv6 не предотвращает переход на совместимый транспорт.
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
|
||||
|
||||
### Кроссплатформенная P2P-трансляция экрана
|
||||
|
||||
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Входной шлюз выдаёт подписанный одноразовый билет, после чего браузер подключается прямо к голосовому шлюзу ретранслятора, а тот — к TeamSpeak. URL страницы остаётся прежним. Узел не предоставляет главную страницу и панель администратора.
|
||||
|
||||
<details>
|
||||
<summary>Запуск и настройка ретранслятора</summary>
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
-e WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST='relay.example.com' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Используйте случайный общий токен длиной не менее 16 символов. Голосовой шлюз слушает `127.0.0.1:3041`; направьте на него HTTPS/WSS-домен через Caddy:
|
||||
|
||||
```caddyfile
|
||||
relay.example.com {
|
||||
reverse_proxy 127.0.0.1:3041
|
||||
}
|
||||
```
|
||||
|
||||
В **Сервер → Ретрансляторы** входного экземпляра задайте имя, UDP-адрес `relay.example.com#39087`, голосовой адрес `https://relay.example.com` и тот же токен. После сохранения посетитель выбирает прямое подключение или узел. Откройте UDP `39087` и WebRTC `40000–40099`; публичный адрес медиа должен разрешаться непосредственно в доступный ретранслятор, а не в HTTP-прокси.
|
||||
|
||||
Для запуска из исходников или пакета задайте те же переменные. После сборки выполните `node dist/index.js`, а в пакете — `./runtime/node ./dist/index.js` (Windows: `.\runtime\node.exe .\dist\index.js`).
|
||||
|
||||
</details>
|
||||
|
||||
### Зависимости
|
||||
|
||||
Ретранслятор встроен в WebSpeak и использует стандартные библиотеки Node.js. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`. TeamSpeak использует upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), пакет `@honeybbq/teamspeak@1.0.0-beta.23`; сборка форка не нужна.
|
||||
|
||||
<a id="extensions"></a>
|
||||
|
||||
## Скины и функциональные плагины
|
||||
|
||||
### Пакеты скинов `.wskin`
|
||||
|
||||
Скины задают оформление, компоновку и связанные виджеты. Администратор устанавливает, включает и выбирает скин по умолчанию. Авторы используют публичный интерфейс без изменения исходников WebSpeak.
|
||||
|
||||
[Руководство](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Каталог скинов](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Пример Discord Voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
|
||||
### Функциональные плагины `.wplugin`
|
||||
|
||||
Функциональные плагины — самостоятельные приложения с API браузера, необязательными сервисами Node, своими маршрутами, данными и совместной работой. Администратор проверяет код и зависимости перед включением; обновления требуют повторного доверия. Приложения работают на отдельном источнике в области TS-сервера или экземпляра. API v2 доступен начиная с v0.3.0.
|
||||
|
||||
[Руководство](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Каталог распространения и пример](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
|
||||
## Решение проблем
|
||||
|
||||
| Проблема | Что проверить |
|
||||
| --- | --- |
|
||||
| WebRTC включён, но используется резервный транспорт | Код ошибки голосового статуса, HTTPS, весь диапазон UDP и публичный адрес медиа. TCP Tunnel не переносит этот UDP-трафик. |
|
||||
| Цель заблокирована как локальный адрес | Открытый режим ограничивает loopback и частные адреса. Для TS на том же хосте используйте настроенный администратором режим фиксированного сервера. |
|
||||
| Тайм-аут или чёрный экран трансляции | Экран использует отдельное WebRTC-соединение. Проверьте согласование, ICE и кодек в статистике трансляции; работающий голос не подтверждает доступность видео. |
|
||||
| После обновления нет данных или они не расшифровываются | Используйте прежний каталог/volume и соответствующий `master.key`. Не обновляйте через `docker compose down -v`. |
|
||||
|
||||
### ⚠️ Требования и замечания
|
||||
|
||||
- Node.js `>=22.12` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
|
||||
@@ -151,16 +267,75 @@ npm start
|
||||
- Одна сохранённая браузерная идентичность может использоваться только одним активным подключением.
|
||||
- Фоновая музыка доступна только на компьютере и требует WebRTC.
|
||||
|
||||
## Сообщество и проекты
|
||||
- WebRTC использует UDP `40000–40099` по умолчанию; откройте весь диапазон. Для смены диапазона сначала выключите WebRTC и сохраните.
|
||||
- Лимит приложения — 100 активных браузерных сессий на экземпляр; это не гарантия производительности и не лимит лицензии TS.
|
||||
|
||||
- [QQ-группа](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram-группа](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот для TeamSpeak с веб-консолью.
|
||||
<a id="changelog"></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
|
||||
|
||||
- Сторонние темы могут оформлять декоративные элементы. WebSpeak управляет восстановлением и разрешениями, чтобы пользователи могли вернуться к встроенной теме. Спасибо ph1gros за определение TS3 и сведения о совместимости (#46), а OddTurtleHead за оформление интерфейса и восстановление темы (#57).
|
||||
- Дневная, ночная и ILLUSIA открывают библиотеку из верхней панели. В KAAK 3.1.134 кнопка расположена на крайней левой панели и совпадает по размеру с соседними. Закреплённые приложения отображаются первыми.
|
||||
- В управлении плагинами появились редактор полей, формы для передачи файлов P2P, совместного просмотра и TSMusicBot, а также ссылки на репозитории.
|
||||
- Магазины допускают различия в отображаемых данных. SHA-256, формат пакета и поля, необходимые для установки или запуска, проверяются.
|
||||
- Руководства и Agent Skills обновлены с учётом размещения кнопки, полей настройки и отдельного HTTPS-адреса для публичных плагинов.
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- При воспроизведении через WebSocket учитываются каналы Opus и фактическая длительность пакета. Микшер WebRTC сохраняет стерео. См. #54.
|
||||
- Доступны три уровня шумоподавления: выключено, стандартное и усиленное. Усиленный режим сочетает обработку браузера и RNNoise. См. #53.
|
||||
- Панель состояния голоса экспортирует последние две минуты диагностики шлюза, голоса и микрофона. Запись в фоне зависит от браузера и ОС. См. #49 и #55.
|
||||
- Кнопка плагинов перенесена на панель инструментов голосового пространства. Администраторы могут закреплять ярлыки плагинов. См. #56.
|
||||
- Добавлены личные приглашения с ограниченным сроком действия и восстановлена страница приветствия KAAK. Исправлено перекрытие меню скинов в демо и преждевременное истечение времени загрузки больших скинов. В README добавлены снимки пяти скинов.
|
||||
|
||||
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
|
||||
|
||||
#### Приложения-плагины
|
||||
|
||||
- Выпущен API v2 для самостоятельных браузерных приложений и необязательных Node-бэкендов со своими маршрутами, состоянием, обменом данными и логикой.
|
||||
- Установка через магазин GitHub или локальные `.wplugin`. Администратор проверяет приложения, задаёт публичные/закрытые настройки и включает их; обновление требует повторного подтверждения доверия.
|
||||
- Добавлены независимые от темы плавающий вход и библиотека приложений. Окна можно перемещать, изменять в размере, сворачивать и разворачивать; сворачивание и возврат в библиотеку не перезагружают приложение.
|
||||
- Добавлены шаблон, руководство и Agent Skill. P2P-передача файлов и совместный просмотр видео распространяются в отдельных репозиториях.
|
||||
|
||||
#### Темы и разрешение
|
||||
|
||||
- При первом входе запрашивается единое разрешение для сторонних тем и плагинов экземпляра, без учётных данных подключения. Последний пункт меню тем позволяет изменить решение.
|
||||
- Без согласия доступны только дневная, ночная и ILLUSIA; KAAK, другие сторонние темы и вход в плагины скрыты. Отзыв разрешения возвращает встроенную тему, отменяет загрузки и останавливает связанные компоненты и страницы приложений.
|
||||
- Сохраняются права манифеста, фильтрация данных, проверка хешей и действий хоста. Проверка и доверие администратора остаются отдельными.
|
||||
|
||||
#### Исправления и обновления
|
||||
|
||||
- Исправлено отсутствие ответа нативного TS-клиента на offer только с видео при показе окна, всего экрана или без звука. Добавляется необходимая аудиосекция без захвата микрофона и создания звука. Пользователь подтвердил изображение при показе окна и экрана.
|
||||
- SDK обновлён до `@honeybbq/teamspeak@1.0.0-beta.23`; учтены необязательные поля участников и пустые пакеты конца речи.
|
||||
- Включены исправления TSDNS, повторов Query при ограничении частоты, передачи файлов и завершения соединений из upstream.
|
||||
- Включены исправления проверки IPv6-целей, параллельных входов, отзыва сеансов после смены пароля, ограничений через доверенные прокси и защиты PCM-входа.
|
||||
- Сохранено исправление первой загрузки темы с фактической версией сборки. Версии приложения для настольных платформ, веба и Android согласованы.
|
||||
|
||||
#### Обновление
|
||||
|
||||
- API v2 несовместим с пакетами v1. Обновите приложения, проверьте и включите их заново.
|
||||
- Для публичных плагинов нужен отдельный HTTPS-origin, настроенный в панели администратора и направленный на порт среды выполнения (по умолчанию `3042`). Основной сайт и приложения не должны использовать один origin.
|
||||
- Пользователю нужно заново выбрать разрешение для экземпляра; старые разрешения отдельных тем не считаются согласием.
|
||||
|
||||
|
||||
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
|
||||
|
||||
#### Новые возможности
|
||||
@@ -183,6 +358,9 @@ npm start
|
||||
|
||||
- Усиление безопасности из [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) не вошло в выпуск; закрытие PR не означает исправления описанных проблем.
|
||||
|
||||
<details>
|
||||
<summary>Показать v0.2.8 и более ранние версии</summary>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### Демонстрация экрана и стабильность соединения
|
||||
@@ -252,16 +430,53 @@ npm start
|
||||
|
||||
Упрощён Docker-запуск, добавлен тайм-аут подключения 15 секунд и непрерывный сетевой мониторинг.
|
||||
|
||||
### [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) · 2026-09-06
|
||||
|
||||
## Лицензия
|
||||
Добавлены немецкий язык, Telegram, панель сетевой статистики и общая громкость; исправлены колебания громкости фоновой музыки.
|
||||
|
||||
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
|
||||
### [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) · 2026-09-04
|
||||
|
||||
Добавлены передача звука окна/вкладки, напоминание о сохранении идентичности и значок сайта; исправлена индивидуальная громкость в WebRTC.
|
||||
|
||||
### [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) · 2026-09-04
|
||||
|
||||
Исправлено сохранение идентичности и улучшено переключение тем.
|
||||
|
||||
### [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) · 2026-09-03
|
||||
|
||||
Исправлены WebRTC и чат канала, улучшены панель управления, журналы и мобильная компоновка.
|
||||
|
||||
### [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) · 2026-09-03
|
||||
|
||||
Добавлен встроенный WebRTC, заменён TeamSpeak SDK, улучшены синхронизация участников и буферизация голоса.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="contributors"></a>
|
||||
|
||||
## Участники и вклад в проект
|
||||
|
||||
<details>
|
||||
<summary>Показать авторов SDK и вклад через PR</summary>
|
||||
|
||||
Список отмечает автора SDK, используемого в основе проекта, вклад через объединённые PR на GitHub и исходные работы, перенесённые в отдельно распространяемые пакеты скинов.
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — Автор SDK [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), который предоставляет используемый WebSpeak клиент протокола TeamSpeak.
|
||||
- [ph1gros](https://github.com/ph1gros) — В [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) сообщил о проблемах безопасности и предложил исправления с регрессионными тестами для проверки IPv6, входа и сессий администратора, лимитов за прокси и PCM-аудио. Исходный патч не объединён напрямую; исправления реализованы заново в `dev`.
|
||||
- [LainHE](https://github.com/LainHE) — [объединённые PR #2, #8, #28, #31–#35, #37, #38 и #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): переводы ошибок браузера, масштабирование и компоновка главной страницы, битрейт трансляции и аватары зрителей, проверка целей и восстановление ретранслятора, доверенные прокси, передача ошибок подключения, сообщения об ошибках аудио и освобождение ресурсов при сбоях WebRTC.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [объединённые PR #13 и #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep): обнаружение активных трансляций TS6, пропорции экрана, мобильное аудио/подсветка экрана/меню скинов, канал в настройках идентичности, PWA/темы, история чата, состояние аудио участников и разрешение микрофона.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak с сохранением имени цели; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) улучшил сохранение рабочего пространства KAAK и повторное подключение после первого соединения. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) и [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) содержали исходный дизайн и реализацию скина Discord (автор коммитов **yumi**), которые проект WebSpeak перенёс в [отдельно распространяемый скин `.wskin`](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
|
||||
|
||||
</details>
|
||||
|
||||
## Сообщество и проекты
|
||||
|
||||
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ-группа 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот TeamSpeak с поддержкой разных платформ и веб-консолью.
|
||||
|
||||
## Лицензия
|
||||
|
||||
WebSpeak распространяется по [AGPL-3.0-only](../LICENSE). Лицензии и авторство сторонних зависимостей указаны в соответствующих проектах.
|
||||
|
||||
<p align="right"><a href="#readme-top">Наверх ↑</a></p>
|
||||
+307
-128
@@ -1,50 +1,188 @@
|
||||
# WebSpeak · 简体中文
|
||||
<a id="readme-top"></a>
|
||||
|
||||
[返回项目首页](../README.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
<div align="center">
|
||||
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
|
||||
<h1>WebSpeak · 简体中文</h1>
|
||||
<p><strong>打开浏览器,就能加入你的 TeamSpeak。</strong></p>
|
||||
<p><a href="../README.md">项目首页</a> · <a href="./README.en.md">English</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.ja.md">日本語</a></p>
|
||||
<p>
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&color=0f766e" alt="Release" /></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
|
||||
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
|
||||
|
||||
皮肤开发请从[当前皮肤开发指南](./SKIN_DEVELOPMENT.md)开始。它整合 `.wskin` 包格式、当前运行时接口、权限边界和制作验收流程。Agent 工作流见[WebSpeak Skin Development Skill](../.agents/skills/webspeak-skin-development/SKILL.md)。
|
||||
稳定版:[v0.3.3 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 控制台一键更新、升级恢复与皮肤兼容性改进。
|
||||
|
||||
## 在线 Demo
|
||||
|
||||
- 上海节点:<https://shanghai.webspeak.online>
|
||||
- 香港节点:<https://webspeak.online>
|
||||
|
||||
演示站点的网络和负载可能不稳定;延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
[在线演示](#demo) · [功能](#features) · [界面预览](#screenshots) · [部署](#deployment) · [管理](#administration) · [高级配置](#advanced) · [皮肤与插件](#extensions) · [常见问题](#troubleshooting) · [更新日志](#changelog)
|
||||
|
||||
最新版本:[查看本页的 0.2.9 更新日志](#latest-release-notes)。
|
||||
<a id="demo"></a>
|
||||
|
||||
## ✨ 特性
|
||||
## 在线演示
|
||||
|
||||
- [上海 · shanghai.webspeak.online](https://shanghai.webspeak.online)
|
||||
- [香港 · webspeak.online](https://webspeak.online)
|
||||
|
||||
可直接体验欢迎页与语音工作区。演示节点的网络、负载和可用性会变化。
|
||||
|
||||
<a id="features"></a>
|
||||
|
||||
## 主要功能
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并根据服务器报告的版本自动探测协议。 |
|
||||
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
|
||||
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
|
||||
| 身份与访问 | 支持身份保持、访客自定义目标、可撤销/可过期邀请链接,以及 TeamSpeak 3 身份导入、转换、校验与导出。 |
|
||||
| 工程结构 | 0.2.6 将网关语音、会话事件、音频和屏幕共享拆分为独立模块;前端语音与管理页拆分为组件、composables 和服务,并补充生命周期与重连测试。 |
|
||||
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
|
||||
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,支持 Docker amd64/arm64、Windows x64、Linux x64/ARM64 服务端包和 Android 客户端。 |
|
||||
| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、浏览器降噪和成员独立音量。 |
|
||||
| 频道与消息 | 频道树、TeamSpeak 频道分隔栏、成员状态、频道切换、频道/服务器/私聊消息、戳一戳、耳语及本地聊天历史。 |
|
||||
| 屏幕与音频共享 | 浏览器之间及与受支持的 TeamSpeak 6 原生客户端共享屏幕;提供采集质量、码率和统计面板,桌面端还可分享窗口或标签页音频。 |
|
||||
| 身份与连接 | 身份保持、TS3 身份导入/导出、收藏和历史连接、SRV 与 Nickname 地址解析、IPv4/IPv6 及邀请链接。 |
|
||||
| 实例管理 | 固定或公开目标、访问策略、邀请、会话、日志、诊断、备份及可选的 TeamSpeak 管理连接。 |
|
||||
| 皮肤与界面 | 日间、夜间、ILLUSIA 和 KAAK;可通过 GitHub 皮肤商店管理 `.wskin` 包,支持五种语言和响应式布局。 |
|
||||
| 分布式语音 | 配置中继后,浏览器直接连接所选中继的语音网关,网页地址仍保留在入口实例。 |
|
||||
| 部署方式 | Docker amd64/arm64、Windows x64 与 Linux x64/ARM64 发布包;另有 Android 预览 APK。 |
|
||||
|
||||
## TeamSpeak 版本兼容性
|
||||
### TeamSpeak 版本兼容性
|
||||
|
||||
语音连接使用标准 TeamSpeak 客户端协议,无需 Query 凭据。可选的 TS 管理功能使用独立的 WebQuery / ServerQuery 凭据。
|
||||
|
||||
- **TeamSpeak 3**:协议识别会读取版本号开头的 `3.x`。并非所有历史服务器版本都经过独立验证,部署旧版本时请针对实际服务器进行测试。
|
||||
- **TeamSpeak 6**:支持,也支持与 TeamSpeak 6 原生客户端进行屏幕共享。
|
||||
- **自动探测**:网关读取服务器的 `version` 响应并在连接诊断中记录识别到的协议。
|
||||
- 网关使用上游 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) 1.0 SDK;WebSpeak 面向 TeamSpeak 3 和 TeamSpeak 6。
|
||||
- 网关使用上游 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) `1.0.0-beta.23` SDK;WebSpeak 面向 TeamSpeak 3 和 TeamSpeak 6。
|
||||
|
||||
## 可选的 TeamSpeak 管理
|
||||
<a id="screenshots"></a>
|
||||
|
||||
## 界面预览
|
||||
|
||||

|
||||
|
||||
<details>
|
||||
<summary>展开欢迎页、音频设置与成员菜单</summary>
|
||||
|
||||
### 欢迎页
|
||||
|
||||

|
||||
|
||||
### 音频设置
|
||||
|
||||

|
||||
|
||||
### 成员菜单
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>展开日间、夜间、ILLUSIA、KAAK 与 Discord Voice 皮肤预览</summary>
|
||||
|
||||
以下截图拍摄于已连接的 TeamSpeak 语音房间。
|
||||
|
||||
| 日间 | 夜间 |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||
| ILLUSIA | KAAK |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
<a id="deployment"></a>
|
||||
|
||||
## 部署与首次配置
|
||||
|
||||
以下 Compose 配置使用 `network_mode: host`,适用于 Linux Docker 主机。Windows 服务端可使用发布包。
|
||||
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.12+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级在宿主机执行。管理控制台在 Docker 部署中只能检查新版本,不能从容器内部替换镜像:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除 `webspeak-data` volume,包括数据库和管理员设置。
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
|
||||
|
||||
Linux x64 发布包(已按官方 `build-release.yml` 产物形态验证)可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`SHA256SUMS.txt` 只是 SHA-256 校验和,不是数字签名。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Windows 发布包可以检查版本,但控制台应用更新尚未经真实 Windows 环境验证,因此已禁用,请下载新包后手动替换。Linux arm64 发布包可以检查版本,但由于原地替换尚未在真实 arm64 硬件验证,控制台应用已禁用;请下载新版发布包后手动替换。Docker 和源码运行不能在控制台应用更新。
|
||||
|
||||
控制台安装仅限前台运行的 Linux x64 发布包。通过 systemd、PM2 或 Supervisor 托管的实例仍可检查版本和查看发行说明,但不能在控制台直接安装。请停止服务,替换新发布包中的程序文件后再启动,并保留 `data/`、`config.json` 和 `certs/`。升级助手即使以独立子进程启动,也仍受服务管理器控制。
|
||||
|
||||
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
|
||||
|
||||
### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
源码运行时,管理控制台可以检查新的正式版本,但目录中没有捆绑的 Node.js 运行时,因此不能一键应用更新。请查看发行说明后拉取源码并重新构建;控制台不会下载或替换源码目录中的文件。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
|
||||
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
|
||||
|
||||
### HTTPS 与持久化
|
||||
|
||||
公网部署应通过 HTTPS 提供网页和 WebSocket。例如,将已解析到主机的域名配置到 Caddy,反向代理到 WebSpeak:
|
||||
|
||||
```caddyfile
|
||||
webspeak.example.com {
|
||||
reverse_proxy 127.0.0.1:3040
|
||||
}
|
||||
```
|
||||
|
||||
以上域名仅为配置示例,请替换成自己的域名。网页能通过反向代理或 Tunnel 打开,并不表示 WebRTC 的 UDP 媒体可达;相关配置见[高级配置](#advanced)。发布包和源码的数据默认位于 `data/`,Docker 位于 `webspeak-data` volume;备份和迁移时同时保留 `webspeak.db` 与 `master.key`。
|
||||
|
||||
<a id="administration"></a>
|
||||
|
||||
## 管理员控制台
|
||||
|
||||
实例配置位于 `/admin`:管理服务器与访问策略、WebRTC 与中继、邀请、活动会话、运行日志和备份。皮肤商店位于 `/admin/skins`;功能插件商店位于 `/admin/plugins`。
|
||||
|
||||
### 可选的 TeamSpeak 管理
|
||||
|
||||
WebSpeak 后台和访客语音不依赖此功能。在固定服务器模式下,打开 `/admin/ts-admin`,可集中配置 TS 管理连接。
|
||||
|
||||
@@ -55,31 +193,13 @@ WebSpeak 后台和访客语音不依赖此功能。在固定服务器模式下
|
||||
|
||||
凭据仅加密保存在服务端,接口不返回密码或 API Key;备份时同时保留数据库和 `master.key`。管理连接失败不影响 WebSpeak 后台和普通语音。封禁按 UID 创建,避免误封共用网关 IP 的其他用户。
|
||||
|
||||
## 🖼️ 界面截图
|
||||
<a id="advanced"></a>
|
||||
|
||||
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
### 欢迎页
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" /></p>
|
||||
|
||||
### 语音工作区
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" /></p>
|
||||
|
||||
### 音量控制
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" /></p>
|
||||
|
||||
### 成员菜单
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员菜单" width="100%" /></p>
|
||||
|
||||
## 🧩 高级功能
|
||||
## 高级配置
|
||||
|
||||
高级功能均为可选项;关闭时仍可使用兼容语音传输。配置入口在管理员控制台的“服务器”页,保存后对新连接生效。
|
||||
|
||||
### 1. WebRTC 低延迟语音
|
||||
### WebRTC 低延迟语音
|
||||
|
||||
WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏。媒体服务由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
|
||||
|
||||
@@ -114,18 +234,22 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
|
||||
|
||||
浏览器用户与 TeamSpeak 6 原生客户端可以互相发现、发起和观看屏幕共享。浏览器之间以及浏览器与原生客户端之间的屏幕媒体优先通过 WebRTC/ICE 端到端传输;WebSpeak 负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。页面提供直播状态、观众人数、播放器音量、全屏和退出控制,也可在共享设置窗口中选择最高 1080p 与 60 FPS,并查看 WebRTC 统计。
|
||||
|
||||
### 2. 中继模式
|
||||
### 中继模式
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例同时运行 UDP 兼容转发和独立语音网关,不提供访客首页或管理员后台。网关收到用户的入场请求后,会用共享令牌签名并转交一次性语音票据;浏览器随后直接连接中继节点,语音网关再从中继节点连接 TeamSpeak。网页地址仍保持在入口网关,不需要跳转。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
<details>
|
||||
<summary>展开中继启动与配置示例</summary>
|
||||
|
||||
#### 源码启动
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
@@ -189,16 +313,123 @@ relay.example.com {
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
|
||||
### 3. 依赖与归属
|
||||
</details>
|
||||
|
||||
### 依赖与归属
|
||||
|
||||
- 中继服务是 WebSpeak 自带实现,使用 Node.js 标准库,不依赖 GOST、sing-box 或其他代理框架。
|
||||
- WebRTC 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,上游采用 MIT 许可证。
|
||||
- TeamSpeak 协议使用上游 [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) 发布的 `@honeybbq/teamspeak@1.0.0-beta.19`,不再需要构建项目 SDK fork。
|
||||
- TeamSpeak 协议使用上游 [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) 发布的 `@honeybbq/teamspeak@1.0.0-beta.23`,无需构建项目 SDK fork。
|
||||
|
||||
## 🧾 更新日志
|
||||
<a id="extensions"></a>
|
||||
|
||||
## 皮肤与功能插件
|
||||
|
||||
### 皮肤包 `.wskin`
|
||||
|
||||
皮肤包负责外观、布局及其附属小组件。管理员可安装、启用和设置默认皮肤;开发时遵循公开接口,无需修改 WebSpeak 源码。
|
||||
|
||||
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
|
||||
|
||||
### 功能插件 `.wplugin`
|
||||
|
||||
功能插件是独立应用,使用标准浏览器能力和可选 Node 后端,自行实现路由、状态与协作。管理员审核代码和依赖后启用;更新须重新信任。支持 TS 服务器或实例范围,运行于独立源。v0.3.0 起提供 API v2。
|
||||
|
||||
[开发指南](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [分发索引与示例](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
|
||||
## 常见问题
|
||||
|
||||
| 现象 | 检查方向 |
|
||||
| --- | --- |
|
||||
| WebRTC 启用后仍回退 | 检查语音状态中的错误代码、HTTPS、整段 UDP 防火墙规则和公网媒体地址。TCP Tunnel 不能转发这条 UDP 媒体路径。 |
|
||||
| 连接目标被本地地址保护拦截 | 公开模式限制回环和私网目标。连接同机 TS 时使用管理员配置的固定服务器模式;面向访客的目标应填实际可访问的地址。 |
|
||||
| 屏幕共享超时或黑屏 | 屏幕共享使用独立的 WebRTC 连接;检查共享统计中的协商、ICE 和编码信息。语音 WebRTC 已连接不代表屏幕媒体可达。 |
|
||||
| 升级后数据丢失或无法解密 | 复用原数据目录或 volume,并保留匹配的 `master.key`;不要用 `docker compose down -v` 升级。 |
|
||||
|
||||
### ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话;这是应用准入上限,不是性能保证或 TS 许可证额度。 |
|
||||
|
||||
<a id="changelog"></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 的配置表单。插件页面可以打开对应仓库。
|
||||
- 皮肤和插件商店允许目录与包内的展示信息有所不同,继续校验 SHA-256、包格式和影响安装或运行的字段。
|
||||
- 更新皮肤及插件开发指南和 Agent Skill,说明入口布局、配置字段和公网插件所需的独立 HTTPS 地址。
|
||||
|
||||
### [v0.3.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.1) · 2026-11-13
|
||||
|
||||
- 修复 WebSocket 播放丢失 Opus 声道信息、固定按 20 毫秒处理音频包的问题,并保留 WebRTC 下行混音的立体声。关联 #54。
|
||||
- 新增关闭、标准和强三档降噪。强档在浏览器降噪基础上使用 RNNoise。关联 #53。
|
||||
- 语音性能面板可导出最近两分钟的网关、语音和麦克风诊断,帮助定位掉线和后台采音中断。后台采音仍受浏览器和操作系统限制。关联 #49、#55。
|
||||
- 将插件入口移至语音工作区顶部工具栏,管理员可固定插件快捷入口。关联 #56。
|
||||
- 支持有有效期的私密工作区邀请,恢复 KAAK 欢迎页,并修复演示页皮肤菜单被遮挡及首次下载较大皮肤时容易超时的问题。README 补齐五款皮肤截图。
|
||||
|
||||
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
|
||||
|
||||
#### 插件系统
|
||||
|
||||
- 发布功能插件 API v2:支持独立浏览器应用和可选 Node 后端,作者可自行实现路由、状态、通信和业务逻辑。
|
||||
- 管理员可通过 GitHub 插件商店或本地 `.wplugin` 包安装应用,配置公开/私密设置并审核启用;更新后需要重新信任。
|
||||
- 新增独立于皮肤的悬浮入口和应用库。插件窗口支持拖动、调整大小、最小化、最大化与还原,最小化或返回应用库不会重载当前应用。
|
||||
- 提供应用模板、插件开发指南与 Agent Skill;P2P 文件传输和视频同看通过独立仓库分发。
|
||||
|
||||
#### 皮肤与授权
|
||||
|
||||
- 首次进入时统一确认当前实例第三方皮肤与插件的授权,不包含连接凭据;皮肤菜单末尾增加“授权”,可随时更改。
|
||||
- 未同意时仅显示日间、夜间、ILLUSIA 三款官方皮肤,隐藏 KAAK 等其他皮肤及插件入口。撤回后切回内置皮肤、取消待完成加载并停止相关组件和插件页面。
|
||||
- 保留皮肤清单权限、数据投影、文件摘要及宿主动作校验,管理员的应用审核与信任设置仍独立生效。
|
||||
|
||||
#### 修复与升级
|
||||
|
||||
- 修复窗口、整个屏幕及关闭共享音频时,TS 原生客户端不应答纯视频 offer 的问题:补充必要的音频协商段,不采集麦克风,也不伪造共享声音。窗口与全屏已由用户复测出画面。
|
||||
- SDK 升级至 `@honeybbq/teamspeak@1.0.0-beta.23`,适配可选成员字段,并跳过代表说话结束的空音频数据包。
|
||||
- 纳入上游 TSDNS 解析、查询限流重试、文件传输及断开连接清理等修复。
|
||||
- 纳入 IPv6 目标校验、并发登录限制、改密后的会话撤销、可信代理限流与 PCM 上行保护修复。
|
||||
- 保留并验证皮肤首次加载使用真实构建版本的修复,统一桌面、网页及 Android 的应用版本号。
|
||||
|
||||
#### 升级说明
|
||||
|
||||
- 插件 API v2 不兼容旧 API v1 应用包,请更新插件后重新审核并启用。
|
||||
- 公网使用功能插件时,需要在管理员面板配置独立的 HTTPS 应用源并代理运行端口(默认 `3042`);主站与应用不能使用同一个源。
|
||||
- 本次统一授权需要用户重新选择,旧的逐皮肤授权记录不会自动视为同意。
|
||||
|
||||
|
||||
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
|
||||
|
||||
#### 功能增强
|
||||
@@ -221,6 +452,9 @@ relay.example.com {
|
||||
|
||||
- [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 记录的安全加固尚未纳入本版本,关闭该 PR 不代表相关问题已修复。
|
||||
|
||||
<details>
|
||||
<summary>展开 v0.2.8 及更早版本</summary>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### 屏幕共享与连接稳定性
|
||||
@@ -310,88 +544,33 @@ relay.example.com {
|
||||
|
||||
引入内置 WebRTC、迁移 TeamSpeak SDK 并改善成员同步和语音缓冲。
|
||||
|
||||
</details>
|
||||
|
||||
## 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.12+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `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。
|
||||
|
||||
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
|
||||
|
||||
### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
|
||||
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
|
||||
|
||||
## ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
<a id="contributors"></a>
|
||||
|
||||
## 贡献者与贡献来源
|
||||
|
||||
<details>
|
||||
<summary>查看上游作者与 PR 贡献说明</summary>
|
||||
|
||||
以下列出上游 SDK 作者、已合并的 GitHub PR,以及已移植为独立皮肤包的原始贡献。
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
|
||||
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 提供公开目标 IPv6 校验、管理员认证与会话、代理限流及 PCM 上行边界的安全审查、补丁和回归测试;原补丁未直接合并,相关修复已在 `dev` 中重新实现。
|
||||
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
|
||||
|
||||
</details>
|
||||
|
||||
## 社区与相关项目
|
||||
|
||||
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ 群 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot):支持多平台点歌和 Web 控制台的 TeamSpeak 音乐机器人。
|
||||
|
||||
## 许可证
|
||||
|
||||
WebSpeak 按 [AGPL-3.0-only](../LICENSE) 发布。第三方依赖的许可与归属见各自项目。
|
||||
|
||||
<p align="right"><a href="#readme-top">返回顶部 ↑</a></p>
|
||||
+261
-15
@@ -1,6 +1,6 @@
|
||||
# WebSpeak 0.2.8 皮肤系统开发指南
|
||||
|
||||
本文是 WebSpeak 0.2.8 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 v1/v2 兼容皮肤、v3 声明式开放皮肤和 v4 插件包,以及当前公开数据、宿主动作、授权、校验与开发流程。v4 有界 Wasm 已在生产构建开放;皮肤 JavaScript 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
|
||||
本文是 WebSpeak 0.3.0 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 v1/v2 兼容皮肤、v3 声明式开放皮肤和 v4 插件包,以及当前公开数据、宿主动作、授权、校验与开发流程。v4 有界 Wasm 已在生产构建开放;皮肤 JavaScript 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
|
||||
|
||||
## 目标:皮肤是可移植的外挂包
|
||||
|
||||
@@ -68,7 +68,7 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
|
||||
}
|
||||
```
|
||||
|
||||
`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、名称、版本、作者、许可证和最低应用版本一致。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。
|
||||
`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、版本和最低应用版本一致。商店展示 `skin.json` 中的名称、作者和许可证,安装后的实例皮肤展示归档清单中的值。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。
|
||||
|
||||
发布步骤:先构建并用客户端和服务端导入器验证最终归档;计算 SHA-256;提交源码、归档、许可证和 `skin.json`;为这个提交创建版本 tag;最后提交中央索引条目。后续更新只需在皮肤仓库发布新版本并更新默认分支的 `skin.json`,无需同步修改中央索引。安装时服务端重新检查索引及元数据,核对摘要并运行普通 `.wskin` 校验;校验失败不替换实例皮肤。同 ID 已安装且版本相同或更新时,不提供覆盖或降级操作。多个管理员同时修改实例皮肤时,过期的安装请求会被拒绝,需刷新后重试。
|
||||
|
||||
@@ -96,6 +96,8 @@ assets/preview.jpg # 可选:管理后台显示的预览图,也可
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
components.json # v3 可选:声明式组件或完整页面 surface
|
||||
chrome.json # v3/v4 可选:宿主装饰、图标位图与可信控件停靠(见「chrome.json」章节)
|
||||
assets/icons/language.png # v3/v4 可选:工具栏图标位图覆盖素材
|
||||
plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件
|
||||
plugins/<plugin-id>/index.js # v4 插件代码,目前只校验和缓存
|
||||
plugins/<plugin-id>/index.wasm # v4 有界 Wasm 插件入口
|
||||
@@ -130,6 +132,7 @@ plugins/<plugin-id>/assets/ # v4 插件专属的本地图片或字体素材
|
||||
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
|
||||
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
|
||||
| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 |
|
||||
| `chrome` | v3/v4 可选,包内 `chrome.json` 路径,最多 120 个字符;v1/v2 声明该字段会被拒绝。 |
|
||||
| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 |
|
||||
| `description` | 可选,最多 400 个字符。 |
|
||||
|
||||
@@ -218,11 +221,20 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s
|
||||
}
|
||||
```
|
||||
|
||||
当前可选宿主控件 ID:`home.connection-form`、`home.connection-status`、`home.visitor-count`、`home.server-announcement`、`home.social-links`、`home.identity-provider`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`、`voice.server-header`、`voice.server-banner`、`voice.server-switcher`、`voice.channel-tree`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。`home.identity-provider` 是通用身份提供方入口,需用 `options.identityProviderId` 和 `options.identityProviderLabel` 指定稳定提供方标识与显示名;宿主会把点击转交给应用代码的 `registerIdentityProviderAdapter` 分发接口,皮肤只能发起请求、不能注册适配器。当前没有 MyTS 适配器,所以 MyTS 入口仍提示开发中;这不代表已经实现登录认证。schema v3 会检查受保护控件所需权限:音频控件需 `audio.status.read`、`audio.microphone.control` 和 `audio.output.control`;聊天需 `chat.channel.read` 与 `chat.channel.send`;成员卡片始终需 `session.members.read` 和 `session.memberAvatars.read`;schema v3 可为成员卡片设置 `options.memberActions: true`,在非本人卡片上显示可信宿主成员操作入口(包含现有个人音量控件);也可为 `voice.channel-tree` 设置该选项,在非本人频道树成员行上启用右键菜单;菜单仍由 WebSpeak 宿主处理,皮肤不获得额外动作或数据接口。频道树还可单独设置 `options.memberDragDrop: true`,将非本人成员拖到另一频道行时复用 WebSpeak 现有移动成员操作;悬停和拖入高亮由皮肤样式控制,此选项默认关闭且只适用于频道树。成员卡片或性能卡片可设置 `options.screenShare: false`,同时隐藏共享 UI/指标并免除成员卡片所需的屏幕共享权限;默认成员共享操作仍需屏幕共享读取/控制权限;头像只在可信宿主控件内显示,不暴露给皮肤代码;屏幕共享播放器需 `voice.screenShare.read` 与 `voice.screenShare.control`;悄悄话控件需对应状态读取和控制权限;断开/连接控件需 `voice.disconnect`。既有 v2 包维持旧校验行为,`voice.screen-share-start` 仍像此前一样要求 `voice.screenShare.control`。该控件仅能放在语音页;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、噪声抑制、伴奏、离开状态、悄悄话、断开连接和屏幕共享动作;噪声抑制使用 `audio.toggleNoiseSuppression` 与 `audio.microphone.control`,伴奏使用 `audio.toggleAccompaniment` 与 `audio.output.control`。它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
|
||||
当前可选宿主控件 ID:`home.connection-form`、`home.connection-status`、`home.visitor-count`、`home.server-announcement`、`home.social-links`、`home.identity-provider`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`、`voice.plugin-launcher`、`voice.server-header`、`voice.server-banner`、`voice.server-switcher`、`voice.channel-tree`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。`home.identity-provider` 是通用身份提供方入口,需用 `options.identityProviderId` 和 `options.identityProviderLabel` 指定稳定提供方标识与显示名;宿主会把点击转交给应用代码的 `registerIdentityProviderAdapter` 分发接口,皮肤只能发起请求、不能注册适配器。当前没有 MyTS 适配器,所以 MyTS 入口仍提示开发中;这不代表已经实现登录认证。schema v3 会检查受保护控件所需权限:音频控件需 `audio.status.read`、`audio.microphone.control` 和 `audio.output.control`;聊天需 `chat.channel.read` 与 `chat.channel.send`;成员卡片始终需 `session.members.read` 和 `session.memberAvatars.read`;schema v3 可为成员卡片设置 `options.memberActions: true`,在非本人卡片上显示可信宿主成员操作入口(包含现有个人音量控件);也可为 `voice.channel-tree` 设置该选项,在非本人频道树成员行上启用右键菜单;菜单仍由 WebSpeak 宿主处理,皮肤不获得额外动作或数据接口。频道树还可单独设置 `options.memberDragDrop: true`,将非本人成员拖到另一频道行时复用 WebSpeak 现有移动成员操作;悬停和拖入高亮由皮肤样式控制,此选项默认关闭且只适用于频道树。成员卡片或性能卡片可设置 `options.screenShare: false`,同时隐藏共享 UI/指标并免除成员卡片所需的屏幕共享权限;默认成员共享操作仍需屏幕共享读取/控制权限;头像只在可信宿主控件内显示,不暴露给皮肤代码;屏幕共享播放器需 `voice.screenShare.read` 与 `voice.screenShare.control`;悄悄话控件需对应状态读取和控制权限;断开/连接控件需 `voice.disconnect`。既有 v2 包维持旧校验行为,`voice.screen-share-start` 仍像此前一样要求 `voice.screenShare.control`。该控件仅能放在语音页;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、噪声抑制、伴奏、离开状态、悄悄话、断开连接和屏幕共享动作;噪声抑制使用 `audio.toggleNoiseSuppression` 与 `audio.microphone.control`,伴奏使用 `audio.toggleAccompaniment` 与 `audio.output.control`。它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
|
||||
|
||||
从 WebSpeak 0.3.2 起,完整语音布局可以放置宿主小组件 `voice.plugin-launcher`。组件 schema v3 支持 `options.pluginPresentation`,省略时使用 `dialog`。可选 `drawer-below` 在按钮下方展开,或用 `drawer-side` 在侧栏内展开。固定应用排在列表前面,未固定的可用应用仍可搜索。WebSpeak 管理插件授权、可用性与应用窗口,皮肤只声明入口的位置和呈现方式。
|
||||
|
||||
```json
|
||||
{ "widget": "voice.plugin-launcher", "part": "plugin-launcher", "options": { "pluginPresentation": "drawer-side" } }
|
||||
```
|
||||
|
||||
皮肤可用 `voice.plugin-launcher`、`voice.plugin-drawer` 和 `voice.plugin-drawer.app` 调整外观。没有放置此组件的完整语音布局会获得默认应用库入口。可为 `home.social-links` 设置 `options.communityLinks: false`,只保留管理控制台入口。
|
||||
|
||||
|
||||
首页访客统计使用公开宿主控件 `home.visitor-count`:它展示当前访客序号与累计访客数,文本跟随当前界面语言,并在统计数据尚不可用时隐藏;不需声明权限。该控件复用 WebSpeak 日间首页的同一结构与基础样式,皮肤通过包内 CSS 定位,不需要自建统计逻辑。组件节点可用稳定的 `part` 名称(例如 `visitor-stats`)控制位置;内部 `home.visitors`、`home.visitors.orbit`、`home.visitors.icon`、`home.visitors.label`、`home.visitors.divider`、`home.visitors.total` 和 `home.visitors.spark` 是稳定样式部件。控件只能放在 `home` 页面。
|
||||
|
||||
可信语音导航控件包括 `voice.channel-tree`、`voice.server-switcher` 和 `voice.server-header`。频道树要求 `session.channels.read`、`session.members.read`、`session.memberAvatars.read` 与 `session.channel.join`;头像只由宿主读取并在频道树中绘制。它可选 `layout: "server-sidebar"` 展示频道成员并让频道行与成员行分别控制折叠;未指定时保留默认呈现。独立服务器切换器要求 `servers.quickList.read` 与 `servers.quickList.switch`。服务器头部还要求 `session.status.read`,并在同一可信部件中组合服务器身份、状态、频道搜索和快速切换。两种入口都只接收不透明本地标识,点击后复用 WebSpeak 当前连接流程。v3 还可用 `session.invite.copy` 授权 `session.copyInviteLink`,让宿主复制当前公开服务器与频道的邀请链接并排除连接凭据。语音状态投影中的 `serverLabel` 会在看起来像 IP、域名或连接目标时省略,避免把地址显示为服务器名称。
|
||||
可信语音导航控件包括 `voice.channel-tree`、`voice.server-switcher` 和 `voice.server-header`。频道树要求 `session.channels.read`、`session.members.read`、`session.memberAvatars.read` 与 `session.channel.join`;头像只由宿主读取并在频道树中绘制。它可选 `layout: "server-sidebar"` 展示频道成员并让频道行与成员行分别控制折叠;未指定时保留默认呈现。独立服务器切换器要求 `servers.quickList.read` 与 `servers.quickList.switch`。服务器头部还要求 `session.status.read`,并在同一可信部件中组合服务器身份、状态、频道搜索和快速切换。两种入口都只接收不透明本地标识,点击后复用 WebSpeak 当前连接流程。v3 还可用 `session.invite.copy` 授权 `session.copyInviteLink`,让宿主打开当前会话的邀请对话框,生成限时票据链接;皮肤不能读取票据或连接凭据。语音状态投影中的 `serverLabel` 会在看起来像 IP、域名或连接目标时省略,避免把地址显示为服务器名称。
|
||||
|
||||
示例包见 [KAAK voice 示例](./examples/KAAK-VOICE.md),其 components.json 使用完整首页与语音工作区 surface,展示收藏服务器、频道树、在线成员、聊天和可信语音控制的组合;[Open Voice Surface](./examples/OPEN-VOICE-SURFACE.md) 保留为通用格式验证脚手架。KAAK 的语音视觉参考来自用户授权进入的前两个语音房间;只记录布局,不保留服务器/房间标识、成员名或聊天内容。组件按本地用户授权后才渲染;权限对每个皮肤版本、页面和组件分别保存,可在宿主权限入口撤销。页面替换时,宿主会额外显示“返回标准界面”和“恢复内置皮肤”入口;拒绝授权或离开 surface 后,普通页面可立即恢复。
|
||||
|
||||
@@ -287,7 +299,8 @@ widget 的可选 `mount` 只接受这些公开锚点:`home.header.after`、`ho
|
||||
|
||||
宿主动作只允许从公开运行时 API 中选择,并在调用时重新核对权限、参数和当前会话:
|
||||
|
||||
- `session.copyInviteLink`(`session.invite.copy`)复制不含连接凭据的当前服务器/频道邀请链接。
|
||||
- `session.copyInviteLink`(`session.invite.copy`)打开宿主邀请对话框,生成并复制当前服务器/频道的限时票据链接。有效期为 1–43200 分钟;服务器密码及已成功使用的频道密码仅由服务端加密保存和使用,不传给皮肤或受邀浏览器。若本次会话尚未提供所需服务器密码或当前上锁频道密码,由宿主对话框向创建者收集。邀请凭据失效时提示受邀者联系创建者,不要求受邀者补输服务器密码。受邀者只需输入昵称,不能用链接参数覆盖票据绑定的服务器和频道。
|
||||
邀请对话框公开样式部件:`voice.invite.backdrop`、`voice.invite.dialog`、`voice.invite.form`、`voice.invite.create`、`voice.invite.copy`。这些钩子仅用于外观;输入值与票据不进入皮肤数据投影。
|
||||
- `voice.joinChannel`(`session.channel.join`)仅请求加入当前公开可见的频道,继续使用宿主的频道密码和权限流程。
|
||||
- `favorites.switch`(`favorites.switch`)与 `quickServers.switch`(`servers.quickList.switch`)使用不透明令牌选择本机已有目标,并复用宿主连接流程。
|
||||
- `chat.sendMessage`(`chat.channel.send`)只向当前公开文字频道发送消息,不包括私聊。
|
||||
@@ -387,12 +400,14 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
| --- | --- |
|
||||
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
|
||||
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.visitors.orbit`、`home.visitors.icon`、`home.visitors.label`、`home.visitors.divider`、`home.visitors.total`、`home.visitors.spark`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.server-history.item`、`home.server-history.select`、`home.server-history.favorite-toggle`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-provider.button`、`home.identity-provider.label`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.server-announcement`、`home.server-announcement.title`、`home.server-announcement.body`、`home.social-links`、`home.connection-status`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.plugin-toolbar`、`voice.plugin-launcher`、`voice.plugin-drawer`、`voice.plugin-drawer.app`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| KOOK 频道树与服务器切换 | `voice.server-switcher`、`voice.server-switcher.trigger`、`voice.server-switcher.menu`、`voice.server-switcher.item`、`voice.server-switcher.icon`、`voice.server-switcher.label`、`voice.server-switcher.current`、`voice.server-switcher.empty`、`voice.channel-tree.list`、`voice.channel-tree.empty`、`voice.channel-tree.node`、`voice.channel-tree.line`、`voice.channel-tree.expander`、`voice.channel-tree.row`、`voice.channel-tree.icon`、`voice.channel-tree.join-hint`、`voice.channel-tree.name`、`voice.channel-tree.count`、`voice.channel-tree.branch`、`voice.channel-tree.member`、`voice.channel-tree.avatar`、`voice.channel-tree.member-name`、`voice.channel-tree.member-muted`、`voice.channel-tree.member-screen-share`、`voice.channel-tree.member-speaking`、`voice.channel-tree.member-away` |
|
||||
| 快速服务器 | `voice.favorite-servers.rail`、`voice.favorite-servers.rail.list`、`voice.favorite-servers.rail.item`、`voice.favorite-servers.server`、`voice.favorite-servers.avatar`、`voice.favorite-servers.tooltip`、`voice.favorite-servers.favorite-toggle`、`voice.favorite-servers.add`、`voice.favorite-servers.strip`、`voice.favorite-servers.strip.item`、`voice.favorite-servers.strip.server`、`voice.favorite-servers.strip.favorite-toggle`、`voice.favorite-servers.strip.add`、`voice.favorite-servers.switch-status`、`voice.favorite-servers.current-toggle`、`voice.favorite-servers.dialog-backdrop`、`voice.favorite-servers.dialog`、`voice.favorite-servers.dialog.header`、`voice.favorite-servers.dialog.close`、`voice.favorite-servers.dialog.form`、`voice.favorite-servers.dialog.field`、`voice.favorite-servers.dialog.input`、`voice.favorite-servers.dialog.target`、`voice.favorite-servers.dialog.hint`、`voice.favorite-servers.dialog.actions`、`voice.favorite-servers.dialog.cancel`、`voice.favorite-servers.dialog.submit` |
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
|
||||
| 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
|
||||
@@ -414,6 +429,213 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
}
|
||||
```
|
||||
|
||||
### 宿主外壳主题化(v3 / v4 开放皮肤)
|
||||
|
||||
应用库窗口、水印、非关键提示与空状态装饰绘制在皮肤根之外;插件入口保留在语音工作区顶部工具栏。宿主提供第二个文档级作用域来主题化这些部件:
|
||||
|
||||
- 皮肤激活时,宿主在 `documentElement` 上设置 `data-ws-host-skin="<皮肤 ID>"`;停用或回退到内置皮肤时立即移除。
|
||||
- 编译 `skin.css` 时,**只**命中下列宿主部件的单个选择器会被限定到 `:root[data-ws-host-skin="<皮肤 ID>"] …`,其余规则仍限定到 `.ws-skin-root[data-ws-skin="…"]`。宿主部件的选择器必须**以可主题化的 `[data-ws-part="host.…"]` 开头**,不能把 `:root`、`html`、`body` 或 `*:has(…)` 作为规则主体;`:root:has([data-ws-part="host.watermark"])` 一类写法会被拒绝。皮肤作者不能自己写 `html`、`body`、`data-ws-host-skin`、`data-ws-route`、`data-theme` 或 `data-ws-skin` 选择器,也不能在同一选择器里混用宿主部件与页面部件;宿主部件只对 schema v3/v4 开放皮肤生效。
|
||||
- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。
|
||||
- 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。
|
||||
- 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。
|
||||
- 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。
|
||||
- 无 Popover API 或顶层提升被拒绝时,恢复胶囊会退回固定宿主层并使用 32 位最大 `z-index: 2147483647`。宿主层在 `#app` 之后追加到 `document.body`;与树内皮肤层同为最大层级时,后绘制的宿主层仍在上面。顶层(top layer)路径的 `showPopover()` / `showModal()` 仍高于两者。
|
||||
|
||||
可主题化的宿主部件:
|
||||
|
||||
| 部件 | 内容 |
|
||||
| --- | --- |
|
||||
| `host.plugins.launcher` | 语音工作区顶部的插件按钮(颜色、尺寸、圆角、背景图均可改;也可声明式隐藏) |
|
||||
| `host.plugins.overlay` | 应用库浮层窗口外壳;**不含**权限对话框里的批准/拒绝(`host.permission`) |
|
||||
| `host.watermark` | 页面大淡 WebSpeak 品牌水印 |
|
||||
| `host.hint` | 非关键提示文案(「音频控制始终保留…」一类) |
|
||||
| `host.voice-status-decoration` | 右栏空的 Voice status 装饰条;与必要状态 `voice.connection-status`、`voice.audio-status` 完全分开 |
|
||||
|
||||
### 恢复入口与授权对话框:结构上不可被皮肤触及
|
||||
|
||||
`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
|
||||
|
||||
1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
|
||||
2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `<dialog>` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
|
||||
3. **不依赖可主题化浮层**:恢复面板的「使用内置皮肤」直接重置到内置 Day/Night 皮肤,不经过 `host.plugins.overlay`;即使皮肤把该浮层写成 `display: none !important` 或 `pointer-events: none`,重置仍然生效。「应用库」按钮只是一条便利路径,会走常规应用库浮层,因此不是兜底路径。
|
||||
|
||||
**显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角(皮肤可通过下文的 `chrome.json#slots` 申请停靠到自己的锚点);它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。
|
||||
|
||||
**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
|
||||
|
||||
`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
|
||||
|
||||
恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
|
||||
|
||||
#### 将恢复入口停靠到皮肤布局(`chrome.json#slots`)
|
||||
|
||||
第三方皮肤可以在 `chrome.json` 中用 `slots` 声明一个自己已经拥有的布局锚点,让恢复胶囊停靠在皮肤界面里,而不是固定盖在左下角。胶囊仍然是宿主控件:皮肤只提供锚点部件名和视觉令牌,无法取得它的 DOM、点击处理或 CSS 选择器;未知的 `data-ws-*` 属性仍由生成界面拒绝。内置/官方皮肤没有 `chrome.json`,行为完全不变。
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| 键名 | 目前只接受 `host.recovery`(`src/shared/skin-visual-parts.ts` 的 `HOST_SLOTTABLE_PART_IDS`;后续可加入其他受保护控件)。未知键或未开放控件会被拒绝,错误码为 `SKIN_CHROME_SLOT_INVALID`。 |
|
||||
| `anchor` | 必填,必须是 `.ws-skin-root` 内已存在的 `data-ws-part` 名称。不能是 `host.*`,也不能是任何可信宿主部件(如 `app`、`voice.connection-status`、`auth.password.*`)。宿主只取第一个可见匹配;锚点不存在、`display:none`、`visibility:hidden`、完全透明、被裁剪、尺寸过小或大部分移出视口时都会回退。 |
|
||||
| `align` | 可选,`start`、`center` 或 `end`,默认 `end`;胶囊在锚点矩形内按此水平对齐,并垂直居中。 |
|
||||
| `compact` | 可选布尔值;为 `true` 时停靠后的胶囊折叠为 ◈ 标记,悬停或聚焦后展开。 |
|
||||
|
||||
`anchor` 写的是宿主渲染后的完整部件名,而不是组件 id:
|
||||
|
||||
- v3 `components.json` 组件根:`skin.<page>.<componentId>`。
|
||||
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
|
||||
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
|
||||
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;同一页面内,当前位置不遮挡时不会为了回到默认角落而移动(默认角落“看起来空”可能只是被模态对话框的遮罩或提示条暂时挡住);进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,并在默认角落和当前位置都空闲(鼠标也不在那里)时回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
|
||||
|
||||
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
| --- | --- |
|
||||
| `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 |
|
||||
| `--skin-recovery-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 |
|
||||
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
|
||||
| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
|
||||
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
|
||||
| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 |
|
||||
| `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
|
||||
|
||||
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
|
||||
|
||||
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停、键盘聚焦或点按/轻触 ◈ 时展开为完整按钮;点按展开会保持到焦点离开胶囊、在胶囊外按下指针或按 Escape。新皮肤激活后、胶囊首次成功停靠起的约 5 秒内始终显示完整胶囊(从停靠时刻开始计时,皮肤加载慢也不会提前收起),避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
#### 受保护控件的主题化
|
||||
|
||||
28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
|
||||
|
||||
**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`(字面值)、`outline` 等纯视觉属性都可以写:
|
||||
|
||||
```css
|
||||
[data-ws-part="voice.audio-dock.microphone"],
|
||||
[data-ws-part="auth.password.dialog"],
|
||||
[data-ws-part="home.footer.clear"] {
|
||||
color: var(--skin-ink);
|
||||
background: linear-gradient(135deg, #0f172a, #1e3a5f);
|
||||
border: 2px solid var(--skin-accent);
|
||||
border-radius: 16px;
|
||||
font: 600 14px/1.4 Tahoma, "Segoe UI", sans-serif;
|
||||
padding: 10px 16px;
|
||||
min-width: 56px;
|
||||
min-height: 56px;
|
||||
box-shadow: 0 8px 24px #0006;
|
||||
}
|
||||
```
|
||||
|
||||
以下规则仍会被拒绝,因为它们会隐藏、禁用或把控件移出视口:`display:none`、`visibility:hidden/collapse`、`opacity:0`、`pointer-events:none`、使 `clip`/`clip-path`/`mask` 完全裁掉内容、`transform`/`scale` 缩到 0、`inset`/`top`/`left`/`margin` 等把控件推到视口外,以及在这些隐藏/移动属性上使用 `var()`/`attr()`。`margin` 仍算移动属性,所以 `margin: var(--skin-gap)` 会被拒绝;普通的小 `margin` 数值可以写。自定义变量仍然只能使用 `--skin-` 前缀。
|
||||
|
||||
个别受保护部件的子元素(例如音频面板和音频设置里的 `<input type="range">`)由 Vue 写入内联 `style`;要给滑轨本身换肤,用视觉属性的 `!important` 覆盖即可,受保护的外壳不受影响。
|
||||
|
||||
**宿主自有的受保护控件。** `host.recovery`、`app.skin-load-recovery` 横幅和授权对话框在闭合 Shadow DOM 内,皮肤 CSS 不能命中。宿主提供一组统一的令牌;皮肤把变量写在活动皮肤根(`:root`,编译后就是皮肤根)上即可,恢复胶囊也接受写在锚点或其祖先上的值:
|
||||
|
||||
| 控件 | 每部件前缀 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 |
|
||||
| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠。令牌取自横幅出现时的**活动**皮肤:加载失败后宿主会退回内置皮肤(内置皮肤不声明令牌),所以失败皮肤自己的值通常不会作用在自己的横幅上,横幅保持默认琥珀色 |
|
||||
| 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 |
|
||||
|
||||
每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-host-accent: #47dcc4;
|
||||
--skin-host-background: #0b1418;
|
||||
--skin-host-foreground: #edf8f5;
|
||||
--skin-host-border: #2a5a54;
|
||||
--skin-host-radius: 10px;
|
||||
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-size: medium;
|
||||
|
||||
/* 只覆盖恢复胶囊,其他宿主控件继续使用全局值 */
|
||||
--skin-recovery-background: #102030;
|
||||
}
|
||||
```
|
||||
|
||||
宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式、窗口尺寸变化让 `@media` 里的令牌生效时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
|
||||
|
||||
- 背景强制不透明(alpha 视为 1)。
|
||||
- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
|
||||
- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
|
||||
- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
|
||||
- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`,或带有编译器给皮肤字体加的 `ws-` 作用域前缀(包括放在暂未生效的 `@media` 里的字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
|
||||
- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
|
||||
- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白;如果黑白两种文字在强调色上都达不到 4.5,这组颜色同样整体回退到宿主默认。
|
||||
- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
|
||||
|
||||
`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。
|
||||
|
||||
`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
|
||||
|
||||
示例(v3 `skin.css`):
|
||||
|
||||
```css
|
||||
/* 只命中宿主部件,编译后进入文档级宿主作用域 */
|
||||
[data-ws-part="host.plugins.launcher"] {
|
||||
background: #1d4f9c;
|
||||
color: #fff;
|
||||
border-radius: 4px;
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
[data-ws-part="host.watermark"] { color: #dbe8f7; opacity: .08; }
|
||||
[data-ws-part="host.hint"] { display: none; }
|
||||
```
|
||||
|
||||
宿主图标槽用 `data-ws-icon-slot` 标记,槽名即部件名,可在 CSS 中直接换背景位图;也可用下面的 `chrome.json` 声明式覆盖。可用槽名:
|
||||
|
||||
| 槽名 | 位置 |
|
||||
| --- | --- |
|
||||
| `host.plugins.launcher` | 顶部工具栏插件按钮图标 |
|
||||
| `language.trigger` | 语言下拉触发器图标 |
|
||||
| `skin.trigger` | 皮肤下拉触发器图标 |
|
||||
| `home.toolbar.settings` | 首页工具栏设置图标 |
|
||||
| `voice.performance` | 语音页 Voice status / 性能触发器图标 |
|
||||
|
||||
### `chrome.json`:声明式显示 / 隐藏、图标位图覆盖与控件停靠
|
||||
|
||||
v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根目录,最多 32 KiB:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"visibleParts": ["host.watermark", "host.hint", "host.voice-status-decoration"],
|
||||
"hiddenParts": ["home.footer.decoration"],
|
||||
"icons": {
|
||||
"language.trigger": "assets/icons/language.png",
|
||||
"skin.trigger": "assets/icons/skin.png",
|
||||
"host.plugins.launcher": "assets/icons/apps.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `visibleParts` | 可选,最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的宿主装饰名。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认隐藏;皮肤需在这里明确列出才会渲染。省略该字段时装饰保持隐藏,即使包内已有 `hiddenParts` 或 `icons`(宿主不再根据生成的 CSS 猜测旧包意图)。内置皮肤没有 `chrome.json`,因此始终不显示这些装饰。实例级 `hiddenParts` 与皮肤 `hiddenParts` 仍然优先。 |
|
||||
| `hiddenParts` | 最多 32 项,只能是本文档「可隐藏的装饰部件」白名单中的名字;编译成 `display:none` 并写入皮肤 CSS。可信控件、恢复入口与必要音频路径(如 `voice.audio-dock`、`voice.connection-status`、`home.footer.clear`)永不允许出现,皮肤 CSS 直接隐藏它们也会被拒绝。 |
|
||||
| `icons` | 最多 16 项;键必须是上表的图标槽名;值必须是包内 `assets/icons/<文件名>` 的位图相对路径。 |
|
||||
| `slots` | 可选,最多 8 项;键名目前只能是 `host.recovery`,值只能包含 `anchor`、`align`、`compact`。详见上文「将恢复入口停靠到皮肤布局」。未知键、指向 `host.*` 或可信宿主部件的锚点会被拒绝。 |
|
||||
|
||||
图标文件约定:仅 PNG / JPG / WebP / AVIF / GIF(**不接受 SVG**),路径必须位于 `assets/icons/` 下且只有一层文件名(不允许 `..`、绝对路径、`\`、`%`、空格或外部 URL)。导入端与服务端登记时都会校验路径、文件是否存在、MIME 是否为位图、单张不超过 64 KiB、总量不超过 512 KiB。宿主把位图编译进皮肤 CSS 的 `background-image`,并隐藏槽内的矢量图形;`url()` 仍走包内资源解析,无法引用外部地址。
|
||||
|
||||
实例级默认值:启动网关时设置环境变量 `WEBSPEAK_HOST_CHROME_HIDDEN_PARTS`(逗号或空格分隔,例如 `host.watermark,host.hint`)。`/api/public-config` 会返回校验后的 `hiddenHostParts`,宿主据此默认折叠这些非关键装饰;未知或受保护的名字会被忽略。宿主的三个装饰部件默认就是隐藏的;皮肤通过 `chrome.json` 的 `visibleParts` 开启,实例默认值与皮肤 `hiddenParts` 取并集并优先于 `visibleParts`。
|
||||
|
||||
`home.footer` 是容器,包含必要的「清除本地数据」链接 `home.footer.clear`,因此**不在**可隐藏列表;纯装饰文案被拆分为 `home.footer.decoration`,只隐藏它不会破坏恢复路径。
|
||||
|
||||
### 令牌、字体、动效和图片
|
||||
|
||||
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
|
||||
@@ -476,28 +698,44 @@ v1/v2 外观可以因窄屏而更换图片裁切或装饰,但 @media 规则也
|
||||
|
||||
v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显示状态,因此皮肤开发者必须保留语音操作路径;授权界面、皮肤选择和恢复入口由宿主在皮肤作用域之外提供。以下选择器是旧格式对可选装饰部件的透明度白名单:
|
||||
|
||||
下面这份清单是**唯一**的可隐藏装饰部件白名单,由 `src/shared/skin-visual-parts.ts` 的 `DECORATIVE_PART_IDS` 定义;CSS 校验器(`OPTIONAL_VISUAL_PARTS`)、布局编辑器(`DECORATIVE_PART_IDS`)与 `chrome.json` 的 `hiddenParts` 共用它,三者永远一致:
|
||||
|
||||
```css
|
||||
[data-ws-part="demo.avatar"]
|
||||
[data-ws-part="demo.badge"]
|
||||
[data-ws-part="demo.note"]
|
||||
[data-ws-part="demo.poke-notification"]
|
||||
[data-ws-part="demo.wave"]
|
||||
[data-ws-part="demo.member-status"]
|
||||
[data-ws-part="home.feature"]
|
||||
[data-ws-part="home.features"]
|
||||
[data-ws-part="home.footer.decoration"]
|
||||
[data-ws-part="home.hero.eyebrow"]
|
||||
[data-ws-part="home.gateway-status"]
|
||||
[data-ws-part="home.features"]
|
||||
[data-ws-part="home.feature"]
|
||||
[data-ws-part="home.join-card.sonar"]
|
||||
[data-ws-part="home.join-card.waveform"]
|
||||
[data-ws-part="home.visitors"]
|
||||
[data-ws-part="voice.activity.artwork"]
|
||||
[data-ws-part="voice.activity-heading"]
|
||||
[data-ws-part="voice.member.avatar"]
|
||||
[data-ws-part="voice.member.avatar-wrap"]
|
||||
[data-ws-part="voice.member.live-indicator"]
|
||||
[data-ws-part="voice.member-row.avatar"]
|
||||
[data-ws-part="voice.performance.metrics"]
|
||||
[data-ws-part="voice.performance.webrtc-stats"]
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"]
|
||||
[data-ws-part="voice.screen-player.live"]
|
||||
[data-ws-part="demo.badge"]
|
||||
[data-ws-part="demo.wave"]
|
||||
[data-ws-part="demo.avatar"]
|
||||
[data-ws-part="demo.member-status"]
|
||||
[data-ws-part="demo.note"]
|
||||
[data-ws-part="host.watermark"]
|
||||
[data-ws-part="host.hint"]
|
||||
[data-ws-part="host.voice-status-decoration"]
|
||||
[data-ws-part="host.plugins.launcher"]
|
||||
```
|
||||
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。
|
||||
|
||||
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
|
||||
关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名;受保护控件上的 `filter` / `-webkit-filter`、`clip` 与 `content-visibility` 同样只接受字面值,不能用 `var()` / `attr()`(否则变量可以绕过上面的隐藏检查),其他部件不受影响。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
@@ -522,3 +760,11 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删
|
||||
自绘成员列表时,`session.members` 可读取 `screenSharing` 与 `screenShareStreamId`;这两个成员字段和 `screenShare.streams` 一样要求 `voice.screenShare.read`。用 `member.screenSharing` 显示共享标记,再将 `member.screenShareStreamId` 绑定到 `voice.joinScreenShare`(还需 `voice.screenShare.control`)即可让用户观看。未声明/未获共享读取权限的皮肤不会收到这两个字段;整页替换皮肤仍须在自己的成员列表中绘制标记或观看入口。
|
||||
|
||||
\n
|
||||
|
||||
## 实例级用户授权(v0.3.0)
|
||||
|
||||
用户首次访问公开页面时,由宿主统一询问是否允许当前实例的第三方皮肤和功能插件使用已公开的频道/成员/聊天等上下文;不包含连接凭据。不再逐个皮肤弹窗确认。选择按浏览器源(协议、域名、端口)保存,旧版本的逐包授权记录不会自动替代这次选择。管理员对应用的审核与信任仍单独保留。
|
||||
|
||||
未作选择或拒绝时,仅可使用固定三款官方皮肤:`builtin.light`、`builtin.dark`、`community.illusia-voice`;KAAK 即使随包分发也不在免授权名单中,其他第三方皮肤及功能插件入口隐藏。缓存、直接激活、进行中的加载也必须经过同一授权检查,不能仅过滤菜单。皮肤菜单末尾的“授权”可以随时修改选择。撤回时立即退回内置皮肤、停止第三方皮肤组件/worker,并关闭与撤销当前功能应用会话;服务端由管理员启用的后台应用不因此停机。
|
||||
|
||||
清单权限、数据投影、宿主动作校验和 Wasm 文件摘要校验继续保留,统一授权不是扩大皮肤 API 的理由。作者不应再自行增加重复授权弹窗。原文中的逐包授权记录与 SHA-256 绑定描述指内部校验记录,其创建必须在实例授权允许之后(或固定官方皮肤之内)。
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -2,7 +2,7 @@
|
||||
|
||||
This example turns the Discord-inspired voice interface into a portable WebSpeak `open-skin` v3 package. Its page structure is declared in `components.json`; its palette and layout are in `skin.css`; localized skin copy lives in `content.json`.
|
||||
|
||||
The independent distribution repository is [Huddle-Up-Forge/webspeak-skin-discord-voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice). It is the first entry in the [WebSpeak skin store index](https://github.com/Huddle-Up-Forge/webspeak-skins). Administrators can install it from **Skins → Skin store**, then manage availability and the instance default under **Instance skins**. Version 1.0.11 requires WebSpeak 0.2.8 with the current public skin API.
|
||||
The independent distribution repository is [Huddle-Up-Forge/webspeak-skin-discord-voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice). It is the first entry in the [WebSpeak skin store index](https://github.com/Huddle-Up-Forge/webspeak-skins). Administrators can install it from **Skins → Skin store**, then manage availability and the instance default under **Instance skins**. Version 1.0.12 requires WebSpeak 0.3.2 with the current public skin API.
|
||||
|
||||
The package uses WebSpeak's public TeamSpeak widgets for channel navigation, member cards, chat, audio controls, screen sharing, performance status, server switching and invite links. That keeps connection logic and trusted actions in WebSpeak while the skin controls the visible layout. The Discord visual language and color palette are retained, while host-owned controls keep their supported behavior and accessibility.
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ The owner authorized inspection of the first two voice rooms in the KOOK server.
|
||||
|
||||
## Returning to the workspace
|
||||
|
||||
KAAK 3.1.127 requires WebSpeak 0.2.8 with workspace API v1. Its manifest opts into the generic persistent workspace policy: first-time visitors keep the connection home until a successful voice connection; returning visitors and disconnected users retain the workspace and server rail. Restoring the workspace never starts a connection or captures the microphone. The host restores the recent target only for ordinary visits, preserving explicit invitation and target links. Clearing browser data resets this history.
|
||||
KAAK 3.1.132 uses the normal connection home on every visit. It no longer opts into persistent workspace entry. The connection-status and explicit reconnect controls remain available inside the voice workspace.
|
||||
|
||||
The permission-gated `voice.connection-status` host widget provides the connection state, nickname and explicit reconnect button beside server navigation at desktop and narrow widths. Open-mode server switching and adding servers reuse the host connection flow, including saved-password lookup and trusted password prompts; fixed mode retains its restrictions. All KAAK layout and styling remain in the package.
|
||||
|
||||
@@ -52,3 +52,5 @@ Member cards are rendered by WebSpeak's trusted `voice.member-cards` widget. It
|
||||
- Shared format and safety rules: [SKIN_DEVELOPMENT.md](../SKIN_DEVELOPMENT.md)
|
||||
|
||||
KAAK is included in the public skin selector and its `.wskin` archive is also available as a standalone package. After changing the source, run `npm run skin:kaak:build` to rebuild both copies, then run the package tests and verify the connection page, approval, denial, revoke, desktop, and narrow-screen paths in the local browser. The connected voice surface can be verified when a TeamSpeak session is available.
|
||||
|
||||
KAAK 3.1.133 places the application library icon in the server rail, alongside the skin and language controls. It opens the drawer beside the rail.
|
||||
Binary file not shown.
@@ -263,6 +263,7 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{"widget":"voice.plugin-launcher","part":"plugin-launcher","options":{"pluginPresentation":"drawer-side"}},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-sidebar-scroll",
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.discord-voice",
|
||||
"name": "Discord Voice",
|
||||
"version": "1.0.11",
|
||||
"version": "1.0.12",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A Discord-inspired dark voice workspace built with WebSpeak's portable open-skin interface.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"minAppVersion": "0.2.8"
|
||||
"minAppVersion": "0.3.2"
|
||||
}
|
||||
@@ -2149,3 +2149,20 @@
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] {
|
||||
flex: 0 0 auto;
|
||||
padding: 4px 8px;
|
||||
--skin-plugin-app-accent: #c9cdfc;
|
||||
}
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"] > button {
|
||||
color: var(--skin-plugin-app-accent);
|
||||
}
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer"] {
|
||||
background: #242529;
|
||||
color: #e8e9ed;
|
||||
border-color: #3f4148;
|
||||
}
|
||||
[data-ws-plugin-part="discord-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer.app"]:hover {
|
||||
background: #383a44;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"hiddenParts": ["host.plugins.launcher"],
|
||||
"visibleParts": ["host.watermark", "host.hint", "host.voice-status-decoration"],
|
||||
"icons": {
|
||||
"language.trigger": "assets/icons/language.png",
|
||||
"skin.trigger": "assets/icons/skin.png",
|
||||
"host.plugins.launcher": "assets/icons/apps.png",
|
||||
"home.toolbar.settings": "assets/icons/settings.png",
|
||||
"voice.performance": "assets/icons/status.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"packageType": "open-skin",
|
||||
"id": "community.host-chrome-demo",
|
||||
"name": "Host Chrome Demo",
|
||||
"version": "1.0.0",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "Minimal open skin demonstrating host chrome theming, protected-control theming, declarative hiding and bitmap icon overrides.",
|
||||
"entry": "skin.css",
|
||||
"chrome": "chrome.json",
|
||||
"minAppVersion": "0.3.2"
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/* Host chrome demo — v3 open skin (schemaVersion 3).
|
||||
Every selector uses :root, [data-ws-page] or [data-ws-part].
|
||||
Host-only selectors are compiled into :root[data-ws-host-skin="…"]. */
|
||||
|
||||
:root {
|
||||
--skin-accent: #1d4f9c;
|
||||
--skin-panel: #ffffff;
|
||||
--skin-border: #c9c9c9;
|
||||
--skin-text: #141414;
|
||||
|
||||
/* Host-owned protected controls: one global set, per-part overrides below. */
|
||||
--skin-host-accent: #1d4f9c;
|
||||
--skin-host-background: #ffffff;
|
||||
--skin-host-foreground: #141414;
|
||||
--skin-host-border: #9db6b2;
|
||||
--skin-host-radius: 10px;
|
||||
--skin-host-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-host-size: medium;
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-border: #9db6b2;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-load-recovery-accent: #b45309;
|
||||
--skin-load-recovery-background: #fff7ed;
|
||||
--skin-load-recovery-foreground: #7c2d12;
|
||||
--skin-permission-accent: #1d4f9c;
|
||||
--skin-permission-background: #ffffff;
|
||||
--skin-permission-foreground: #141414;
|
||||
}
|
||||
|
||||
[data-ws-page] {
|
||||
color-scheme: light;
|
||||
font-family: Tahoma, "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
font-size: 12px;
|
||||
color: #141414;
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] ,
|
||||
[data-ws-part="voice.header"] {
|
||||
background: linear-gradient(180deg, #fbfbfb, #e9e9e9);
|
||||
border-bottom: 1px solid var(--skin-border);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
border-top: 1px solid var(--skin-border);
|
||||
background: #f7f9fb;
|
||||
/* Fold the trusted recovery capsule into the audio dock (chrome.json#slots). */
|
||||
--skin-recovery-accent: #1d4f9c;
|
||||
--skin-recovery-background: #ffffff;
|
||||
--skin-recovery-foreground: #141414;
|
||||
--skin-recovery-radius: 999px;
|
||||
--skin-recovery-font: Tahoma, "Segoe UI", sans-serif;
|
||||
--skin-recovery-size: small;
|
||||
}
|
||||
|
||||
/* --- Protected app-DOM controls: purely visual theming is allowed --- */
|
||||
[data-ws-part="voice.audio-dock.microphone"] button,
|
||||
[data-ws-part="voice.audio-dock.output"] button,
|
||||
[data-ws-part="voice.connection-status.reconnect"],
|
||||
[data-ws-part="home.footer.clear"] {
|
||||
color: #141414;
|
||||
background: linear-gradient(180deg, #ffffff, #eef3fa);
|
||||
border: 1px solid var(--skin-accent);
|
||||
border-radius: 8px;
|
||||
font-family: Tahoma, "Segoe UI", sans-serif;
|
||||
font-size: 12px;
|
||||
padding: 8px 12px;
|
||||
min-height: 44px;
|
||||
box-shadow: 0 2px 6px #1d4f9c22;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone"] button:hover,
|
||||
[data-ws-part="voice.audio-dock.output"] button:hover,
|
||||
[data-ws-part="voice.connection-status.reconnect"]:hover,
|
||||
[data-ws-part="home.footer.clear"]:hover {
|
||||
background: #e7eefb;
|
||||
}
|
||||
|
||||
[data-ws-part="auth.password.dialog"],
|
||||
[data-ws-part="voice.audio-settings"] {
|
||||
background: #ffffff;
|
||||
border: 2px solid var(--skin-accent);
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 18px 48px #1d4f9c33;
|
||||
}
|
||||
|
||||
[data-ws-part="auth.password.dialog"] h2,
|
||||
[data-ws-part="voice.audio-settings"] h2 {
|
||||
color: var(--skin-accent);
|
||||
letter-spacing: .01em;
|
||||
}
|
||||
|
||||
/* --- Host chrome (outside .ws-skin-root) --- */
|
||||
[data-ws-part="host.plugins.launcher"] {
|
||||
background: #1d4f9c;
|
||||
color: #ffffff;
|
||||
border: 1px solid #163c78;
|
||||
border-radius: 3px;
|
||||
padding: 7px 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: .02em;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
[data-ws-part="host.plugins.launcher"]:hover {
|
||||
background: #2a63bb;
|
||||
}
|
||||
|
||||
[data-ws-part="host.plugins.overlay"] {
|
||||
border: 2px solid #1d4f9c;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
[data-ws-part="host.watermark"] {
|
||||
color: #1d4f9c;
|
||||
opacity: .12;
|
||||
font-family: Tahoma, sans-serif;
|
||||
}
|
||||
|
||||
[data-ws-part="host.hint"] {
|
||||
color: #1d4f9c;
|
||||
border-left: 2px solid #1d4f9c;
|
||||
padding-left: 6px;
|
||||
}
|
||||
|
||||
[data-ws-part="host.voice-status-decoration"] {
|
||||
opacity: .45;
|
||||
}
|
||||
|
||||
/* Icon slots can also be addressed directly from CSS. */
|
||||
[data-ws-part="host.plugins.launcher"] [data-ws-icon-slot="host.plugins.launcher"] {
|
||||
background-color: transparent;
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -582,9 +582,11 @@
|
||||
"widget": "app.language-switcher",
|
||||
"part": "rail-language"
|
||||
},
|
||||
{"widget":"voice.plugin-launcher","part":"plugin-launcher","options":{"pluginPresentation":"drawer-side"}},
|
||||
{
|
||||
"widget": "home.social-links",
|
||||
"part": "rail-links"
|
||||
"part": "rail-links",
|
||||
"options": { "communityLinks": false }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -3,16 +3,12 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.kaak-voice",
|
||||
"name": "KAAK",
|
||||
"version": "3.1.127",
|
||||
"version": "3.1.134",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"minAppVersion": "0.2.8",
|
||||
"workspace": {
|
||||
"apiVersion": 1,
|
||||
"mode": "persistent"
|
||||
}
|
||||
"minAppVersion": "0.3.2"
|
||||
}
|
||||
@@ -3896,6 +3896,7 @@
|
||||
[data-ws-plugin-part="kaak-workspace.server-banner"] [data-ws-part="voice.server-banner.body"] { margin-top: 3px; font-size: 10px; line-height: 14px; }
|
||||
}
|
||||
|
||||
[data-ws-part="voice.invite.backdrop"],
|
||||
[data-ws-part="auth.password.backdrop"] {
|
||||
padding: 16px;
|
||||
background: rgba(10, 11, 13, .54);
|
||||
@@ -3904,6 +3905,7 @@
|
||||
[data-ws-part="auth.password.backdrop"][data-ws-state="server-password"] {
|
||||
background: rgba(29, 40, 34, .3);
|
||||
}
|
||||
[data-ws-part="voice.invite.dialog"],
|
||||
[data-ws-part="auth.password.dialog"] {
|
||||
position: relative;
|
||||
display: flex;
|
||||
@@ -4698,8 +4700,68 @@
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-switcher,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-trigger,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-switcher,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-trigger { width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-trigger { width: 44px; min-width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a { transition: none; }
|
||||
}
|
||||
|
||||
[data-ws-part="voice.invite.create"], [data-ws-part="voice.invite.copy"] {
|
||||
color: #172008;
|
||||
background: var(--skin-kaak-accent);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.invite.dialog"] {
|
||||
height: auto;
|
||||
max-height: calc(100dvh - 32px);
|
||||
}
|
||||
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] {
|
||||
order: 6;
|
||||
flex: 0 0 var(--skin-kaak-app-button-size);
|
||||
width: var(--skin-kaak-app-button-size);
|
||||
--skin-kaak-app-button-size: 58px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
width: var(--skin-kaak-app-button-size);
|
||||
height: var(--skin-kaak-app-button-size);
|
||||
border: 1px solid #3d4048;
|
||||
border-radius: 18px;
|
||||
color: #d1d5dc;
|
||||
background: var(--skin-kaak-rail-item-bg);
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button svg {
|
||||
flex: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button > span {
|
||||
display: none;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button:is(:hover, :focus-visible, [aria-expanded="true"]) {
|
||||
border-color: #699b32;
|
||||
color: #a8ed50;
|
||||
background: #2b3524;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer"] {
|
||||
position: fixed;
|
||||
inset: auto auto max(76px, env(safe-area-inset-bottom)) 86px;
|
||||
box-sizing: border-box;
|
||||
width: min(280px, calc(100vw - 98px));
|
||||
background: #24272a;
|
||||
color: #e8e9ed;
|
||||
border-color: #3d4048;
|
||||
box-shadow: 0 12px 32px #0006;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-drawer.app"]:is(:hover, :focus-visible) {
|
||||
background: #2b3524;
|
||||
}
|
||||
@media (max-height: 620px) {
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] { --skin-kaak-app-button-size: 44px; }
|
||||
[data-ws-plugin-part="kaak-workspace.plugin-launcher"] [data-ws-part="voice.plugin-launcher"][data-presentation="drawer-side"] > button { border-radius: 14px; }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 63 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
+3
@@ -0,0 +1,3 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Application starter</title><link rel="stylesheet" href="./style.css"><script type="module" src="./main.js"></script></head>
|
||||
<body><main><span class="eyebrow">WEBSPEAK · APPLICATION RUNTIME 2</span><h1 id="title"></h1><p id="intro"></p><section><div class="status"><i></i><span id="status"></span></div><dl><div><dt id="user-label"></dt><dd id="user"></dd></div><div><dt id="scope-label"></dt><dd id="scope"></dd></div></dl><button id="request" type="button"></button><output id="result" aria-live="polite"></output></section></main></body></html>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
const host=window.webspeak;
|
||||
let context=await host.ready;
|
||||
const copy={
|
||||
en:['Your application starts here','Standard browser APIs, your own routes and an optional Node backend.','Connected application context','Participant','Scope','Call my backend','Persisted requests','Frontend only'],
|
||||
zh:['从这里构建你的应用','使用标准浏览器 API、自定义路由和可选的 Node 后端。','应用上下文已连接','参与者','作用域','调用自己的后端','已保存的请求次数','仅前端模式'],
|
||||
de:['Hier beginnt deine Anwendung','Browser-APIs, eigene Routen und ein optionales Node-Backend.','Anwendungskontext verbunden','Teilnehmer','Bereich','Backend aufrufen','Gespeicherte Anfragen','Nur Frontend'],
|
||||
ru:['Начните своё приложение здесь','API браузера, собственные маршруты и необязательный сервис Node.','Контекст приложения подключён','Участник','Область','Вызвать свой сервис','Сохранённые запросы','Только браузер'],
|
||||
ja:['ここからアプリを作成','標準ブラウザー API、独自ルート、任意の Node バックエンド。','アプリの接続情報を取得済み','参加者','範囲','バックエンドを呼び出す','保存したリクエスト数','フロントエンドのみ']};
|
||||
const element=id=>document.getElementById(id);
|
||||
function render(){const t=copy[context.language]??copy.en;for(const [id,index]of [['title',0],['intro',1],['status',2],['user-label',3],['scope-label',4],['request',5]])element(id).textContent=t[index];element('user').textContent=context.self.nickname;element('scope').textContent=context.scope.type;element('request').disabled=!context.serverUrl;if(!context.serverUrl)element('result').textContent=t[7];}
|
||||
host.onContextChange(next=>{context=next;render();});render();
|
||||
element('request').addEventListener('click',async()=>{element('request').disabled=true;try{const response=await fetch(context.serverUrl+'/my-counter',{method:'POST',signal:host.signal});if(!response.ok)throw new Error(String(response.status));const result=await response.json();element('result').textContent=(copy[context.language]??copy.en)[6]+': '+result.count;}catch(error){element('result').textContent=error.message;}finally{element('request').disabled=!context.serverUrl;}});
|
||||
+1
@@ -0,0 +1 @@
|
||||
:root{color-scheme:light;--bg:#f1f5f4;--surface:#fff;--text:#183d39;--muted:#5b7671;--border:#d4e3df;--accent:#126b60;--soft:#e8f4ef}html[data-theme=dark]{color-scheme:dark;--bg:#161c21;--surface:#202a30;--text:#e4efec;--muted:#9eb6b0;--border:#37474c;--accent:#8ee2be;--soft:#293e37}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.6 system-ui,sans-serif}main{max-width:800px;margin:0 auto;padding:clamp(24px,6vw,64px)}.eyebrow{color:var(--accent);font-size:11px;font-weight:750;letter-spacing:.14em}h1{font-size:clamp(25px,4vw,38px);letter-spacing:-.04em;line-height:1.2;margin:20px 0 14px}p{color:var(--muted);max-width:550px}section{margin-top:30px;padding:26px;border:1px solid var(--border);border-radius:18px;background:var(--surface)}.status{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--accent)}.status i{width:8px;height:8px;border-radius:50%;background:var(--accent)}dl{display:flex;gap:32px;flex-wrap:wrap;margin:22px 0 30px}dt{font-size:12px;color:var(--muted)}dd{margin:4px 0 0;font-weight:650;overflow-wrap:anywhere}button{font:600 14px system-ui;padding:12px 18px;border-radius:10px;border:1px solid var(--border);color:var(--accent);background:var(--soft);cursor:pointer}button:disabled{opacity:.5;cursor:default}output{display:block;margin-top:16px;color:var(--muted);font-size:13px}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"apiVersion": 2,
|
||||
"id": "community.application-starter",
|
||||
"name": "Application starter",
|
||||
"version": "1.0.0",
|
||||
"author": "Your community",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A starting point for an independent browser application and optional Node service.",
|
||||
"scopes": [
|
||||
"server",
|
||||
"instance"
|
||||
],
|
||||
"client": {
|
||||
"entry": "client/index.html"
|
||||
},
|
||||
"server": {
|
||||
"entry": "server/main.mjs"
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { readFile, writeFile, rename } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
// Ordinary trusted Node code: use your own modules, network clients and routes.
|
||||
export default async function activate({ dataDir, signal }) {
|
||||
const filename=path.join(dataDir,'counter.json');
|
||||
let count=JSON.parse(await readFile(filename,'utf8').catch(()=> '0'));
|
||||
let writes=Promise.resolve();
|
||||
return {
|
||||
async handle(request,response) {
|
||||
if(request.method!=='POST'||new URL(request.url,'http://app.local').pathname!=='/my-counter'){response.writeHead(404);response.end();return;}
|
||||
// req.webspeak is host-authenticated context; it is not supplied by the browser.
|
||||
writes=writes.then(async()=>{count++;await writeFile(filename+'.tmp',JSON.stringify(count));await rename(filename+'.tmp',filename);});
|
||||
try{await writes;response.setHeader('content-type','application/json');response.end(JSON.stringify({count,participant:request.webspeak.self.id}));}
|
||||
catch{response.writeHead(500);response.end();}
|
||||
},
|
||||
async stop(){await writes.catch(()=>undefined);}
|
||||
};
|
||||
}
|
||||
Generated
+6
-6
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"version": "0.3.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"version": "0.3.3",
|
||||
"dependencies": {
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^4.21.2",
|
||||
"opusscript": "^0.1.1",
|
||||
"pino": "^10.3.1",
|
||||
@@ -39,9 +39,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.19",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.19.tgz",
|
||||
"integrity": "sha512-5srWgwbcMx1j4JpwYonxKkOYla8hx7ojX+dYOC0hiv5NCjozMRsy8aIYzwSpzHr2y3q/aKljnPyM426DTRekrA==",
|
||||
"version": "1.0.0-beta.23",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.23.tgz",
|
||||
"integrity": "sha512-Y0fV4NOdvaU3Df4231XZkFOfSgm7G4xN50x5hglxVV+HtYlxx5sS+G3vAF0rvOcW80qUy20nfnD/Sxx+JgQ1TA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"version": "0.3.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
"dependencies": {
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^4.21.2",
|
||||
"opusscript": "^0.1.1",
|
||||
"pino": "^10.3.1",
|
||||
|
||||
Generated
+6
-6
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.9",
|
||||
"version": "0.3.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.9",
|
||||
"version": "0.3.3",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
@@ -530,9 +530,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.19",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.19.tgz",
|
||||
"integrity": "sha512-5srWgwbcMx1j4JpwYonxKkOYla8hx7ojX+dYOC0hiv5NCjozMRsy8aIYzwSpzHr2y3q/aKljnPyM426DTRekrA==",
|
||||
"version": "1.0.0-beta.23",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.23.tgz",
|
||||
"integrity": "sha512-Y0fV4NOdvaU3Df4231XZkFOfSgm7G4xN50x5hglxVV+HtYlxx5sS+G3vAF0rvOcW80qUy20nfnD/Sxx+JgQ1TA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
+6
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.9",
|
||||
"version": "0.3.3",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,10 +11,11 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
|
||||
"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",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
"skin:host-chrome:build": "node web/scripts/build-host-chrome-demo-skin.mjs",
|
||||
"skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs",
|
||||
"skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs",
|
||||
"start": "node dist/index.js",
|
||||
@@ -26,11 +27,12 @@
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
"acceleration:relay": "node dist/relay.js"
|
||||
"acceleration:relay": "node dist/relay.js",
|
||||
"plugin:build": "node scripts/build-plugin.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { BlockList, isIP, SocketAddress } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, parseJsonPayload, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
function endpointKey(address, port) {
|
||||
@@ -19,27 +19,28 @@ function endpointKey(address, port) {
|
||||
* Keep this an exact mirror: fail closed on anything that is not a literal
|
||||
* public address.
|
||||
*/
|
||||
const restrictedIpv6 = new BlockList();
|
||||
for (const [network, prefix] of [
|
||||
["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
|
||||
["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
|
||||
["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
|
||||
["fec0::", 10], ["ff00::", 8],
|
||||
]) restrictedIpv6.addSubnet(network, prefix, "ipv6");
|
||||
|
||||
export function isRestrictedAddress(host) {
|
||||
if (host.includes("%")) return true;
|
||||
const version = isIP(host);
|
||||
if (version === 4) return isRestrictedIpv4(host);
|
||||
if (version !== 6) return true;
|
||||
|
||||
const normalized = host.toLowerCase();
|
||||
if (normalized === "::" || normalized === "::1") return true;
|
||||
const normalized = new SocketAddress({ address: host, family: "ipv6" }).address;
|
||||
if (normalized.startsWith("::ffff:")) {
|
||||
// IPv4-mapped addresses must be unwrapped before the IPv4 rules apply:
|
||||
// ::ffff:10.0.0.1 is private traffic in IPv6 clothing.
|
||||
const mapped = normalized.slice("::ffff:".length);
|
||||
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
|
||||
}
|
||||
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
|
||||
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
|
||||
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
|
||||
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
|
||||
if (normalized.startsWith("2001:db8:")) return true; // documentation range
|
||||
return false;
|
||||
return restrictedIpv6.check(normalized, "ipv6");
|
||||
}
|
||||
|
||||
function isRestrictedIpv4(host) {
|
||||
|
||||
@@ -60,6 +60,28 @@ const CASES = [
|
||||
["::ffff:127.0.0.1", true],
|
||||
["::ffff:10.0.0.1", true],
|
||||
["::ffff:8.8.8.8", false],
|
||||
["0:0:0:0:0:ffff:808:808", false],
|
||||
["2001:4860:0:0:0:0:0:8888", false],
|
||||
["0:0:0:0:0:0:0:1", true],
|
||||
["0::1", true],
|
||||
["0:1234::1", true],
|
||||
["0:0:0:0:0:0:0:0", true],
|
||||
["::ffff:7f00:1", true],
|
||||
["0::ffff:a00:1", true],
|
||||
["::127.0.0.1", true],
|
||||
["fe80::1%eth0", true],
|
||||
["64:ff9b::808:808", true],
|
||||
["64:ff9b:1:1234::1", true],
|
||||
["64:ff9b:2::1", false],
|
||||
["100::1", true],
|
||||
["100:0:0:1::1", true],
|
||||
["100:0:1::1", false],
|
||||
["2001:0::1", true],
|
||||
["2002:808:808::1", true],
|
||||
["2001:0db8::1", true],
|
||||
["2001:db9::1", false],
|
||||
["3fff:fff::1", true],
|
||||
["3fff:1000::1", false],
|
||||
// Anything that is not a literal address fails closed.
|
||||
["localhost", true],
|
||||
["public.example.invalid", true],
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { readFile, readdir, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
const [input, output] = process.argv.slice(2);
|
||||
if (!input || !output) throw new Error('Usage: node scripts/build-plugin.mjs APPLICATION_DIR OUTPUT.wplugin');
|
||||
const root=path.resolve(input),manifest=JSON.parse(await readFile(path.join(root,'manifest.json'),'utf8'));
|
||||
if(manifest.apiVersion!==2||manifest.permissions!==undefined)throw new Error('Application runtime v2 manifest required');
|
||||
const validPath=value=>typeof value==='string'&&value.length<=500&&value.split('/').every(s=>/^[A-Za-z0-9._@+~-]+$/.test(s)&&!['.','..'].includes(s)&&!s.endsWith('.')&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(s));
|
||||
const files=Object.create(null);let total=0;
|
||||
async function collect(directory){
|
||||
for(const entry of(await readdir(path.join(root,directory),{withFileTypes:true})).sort((a,b)=>a.name<b.name?-1:1)){
|
||||
const name=directory+'/'+entry.name;if(!validPath(name)||entry.isSymbolicLink())throw new Error('Invalid package path: '+name);
|
||||
if(entry.isDirectory())await collect(name);
|
||||
else if(entry.isFile()){
|
||||
const bytes=await readFile(path.join(root,name));total+=bytes.length;
|
||||
if(bytes.length>16*1024*1024||total>32*1024*1024||Object.keys(files).length>=4096)throw new Error('Package size limit');
|
||||
try{files[name]={encoding:'utf8',data:new TextDecoder('utf-8',{fatal:true}).decode(bytes)};}
|
||||
catch{files[name]={encoding:'base64',data:bytes.toString('base64')};}
|
||||
}else throw new Error('Only ordinary files are supported: '+name);
|
||||
}
|
||||
}
|
||||
await collect('client');if(manifest.server)await collect('server');
|
||||
if(!validPath(manifest.client?.entry)||!manifest.client.entry.startsWith('client/')||files[manifest.client.entry]?.encoding!=='utf8')throw new Error('Missing HTML client entry');
|
||||
if(manifest.server&&(!validPath(manifest.server.entry)||!manifest.server.entry.startsWith('server/')||files[manifest.server.entry]?.encoding!=='utf8'))throw new Error('Missing bundled server entry');
|
||||
const bytes=JSON.stringify({manifest,files});if(Buffer.byteLength(bytes)>48*1024*1024)throw new Error('Package size limit');
|
||||
await writeFile(output,bytes);console.log(`${manifest.id} v${manifest.version} -> ${output}`);
|
||||
Executable
+209
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env sh
|
||||
# WebSpeak official release launcher.
|
||||
#
|
||||
# This file is the single source of truth for the launcher shipped in release
|
||||
# packages: .github/workflows/build-release.yml copies it verbatim, and the
|
||||
# self-update pre-swap installer copies the same file from the staged package.
|
||||
# Keep it a plain POSIX shell script: it must be able to repair an interrupted
|
||||
# code swap before Node (dist/index.js) is available at all.
|
||||
set -eu
|
||||
|
||||
cd -- "$(dirname -- "$0")"
|
||||
|
||||
# Mirrors src/index.ts: a custom data directory is the only supported override.
|
||||
data_dir="${WEBSPEAK_DATA_DIR:-$PWD/data}"
|
||||
backups="$data_dir/updates/backups"
|
||||
|
||||
# Only executable code is swapped by the updater. data/, config.json, certs/,
|
||||
# identities, skins and plugins are deliberately never listed here.
|
||||
code_entries="dist web/dist node_modules runtime package.json package-lock.json README.md LICENSE config.example.json start-webspeak.cmd"
|
||||
required_entries="dist/index.js web/dist/index.html node_modules package.json runtime/node"
|
||||
|
||||
code_missing() {
|
||||
for entry in $required_entries; do
|
||||
if [ ! -e "$entry" ]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A backup can only repair a missing-code install if it is complete. Partial
|
||||
# backups are still resumable when they belong to the active task.
|
||||
backup_is_complete() {
|
||||
[ -f "$1/.webspeak-swap.json" ] || return 1
|
||||
for entry in $required_entries; do
|
||||
[ -e "$1/$entry" ] || return 1
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
# During the first phase of a swap, only some old entries have been moved.
|
||||
# The rest still live at the install root. The current task can be recovered
|
||||
# from that union, including a kill between rename and manifest persistence.
|
||||
# Never combine a stale task's partial backup with this install.
|
||||
task_backup_can_repair() {
|
||||
[ -f "$1/.webspeak-swap.json" ] || return 1
|
||||
for entry in $required_entries; do
|
||||
if [ ! -e "$1/$entry" ] && [ ! -e "$entry" ]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
state_file="$data_dir/updates/state.json"
|
||||
lock_file="$data_dir/updates/update.lock"
|
||||
read_update_task() {
|
||||
task_id=""
|
||||
task_status=""
|
||||
if [ -f "$state_file" ]; then
|
||||
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
fi
|
||||
case "$task_id" in
|
||||
""|*[!A-Za-z0-9_-]*) task_id="" ;;
|
||||
esac
|
||||
}
|
||||
read_update_task
|
||||
|
||||
process_start() {
|
||||
# After the last ')' field 3 is first; starttime (field 22) is twentieth.
|
||||
if [ -r "/proc/$1/stat" ]; then
|
||||
sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}'
|
||||
fi
|
||||
}
|
||||
|
||||
release_recovery_lock() {
|
||||
if [ "${lock_owned:-0}" = 1 ] && [ "$(cat "$lock_file" 2>/dev/null)" = "$lock_payload" ]; then
|
||||
rm -f -- "$lock_file"
|
||||
fi
|
||||
lock_owned=0
|
||||
}
|
||||
|
||||
acquire_recovery_lock() {
|
||||
# Share the updater's exclusive-create JSON lock. A distinct task id stops
|
||||
# a delayed restart runner from taking this recovery lock over. Keep it for
|
||||
# the entire restore, and only reclaim a proven-dead, unchanged owner.
|
||||
mkdir -p "$data_dir/updates"
|
||||
lock_owned=0
|
||||
start=$(process_start "$$")
|
||||
lock_payload="{\"pid\":$$,\"taskId\":\"recovery_$$\",\"createdAt\":\"\",\"processStart\":\"$start\"}"
|
||||
for attempt in 1 2 3 4; do
|
||||
if (umask 077; set -C; printf '%s\n' "$lock_payload" > "$lock_file") 2>/dev/null; then
|
||||
lock_owned=1
|
||||
trap 'release_recovery_lock' 0
|
||||
trap 'exit 1' HUP INT TERM
|
||||
return 0
|
||||
fi
|
||||
observed=$(cat "$lock_file" 2>/dev/null) || return 1
|
||||
owner=$(printf '%s\n' "$observed" | sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\)[[:space:]]*[,}].*/\1/p' | head -n 1)
|
||||
owner_task=$(printf '%s\n' "$observed" | sed -n 's/.*"taskId"[[:space:]]*:[[:space:]]*"\([^"]\{1,\}\)".*/\1/p' | head -n 1)
|
||||
case "$owner" in ""|*[!0-9]*) return 1 ;; esac
|
||||
[ -n "$owner_task" ] || return 1
|
||||
if [ "$owner" != 0 ]; then
|
||||
if kill -0 "$owner" 2>/dev/null || [ -d "/proc/$owner" ]; then
|
||||
saved_start=$(printf '%s\n' "$observed" | sed -n 's/.*"processStart"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
|
||||
current_start=$(process_start "$owner")
|
||||
# Unknown markers and inaccessible processes are conservatively live.
|
||||
if [ -z "$saved_start" ] || [ -z "$current_start" ] || [ "$saved_start" = "$current_start" ]; then
|
||||
return 1
|
||||
fi
|
||||
elif [ ! -d /proc ]; then
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
[ "$(cat "$lock_file" 2>/dev/null)" = "$observed" ] || continue
|
||||
rm -f -- "$lock_file" || return 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
recovery_needed() {
|
||||
if code_missing; then
|
||||
return 0
|
||||
fi
|
||||
case "$task_status" in
|
||||
downloading|verifying|extracting|staging|restarting)
|
||||
[ -n "$task_id" ] && [ -d "$backups/$task_id" ] && [ -f "$backups/$task_id/.webspeak-swap.json" ]
|
||||
return $?
|
||||
;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
restore_from_backup() {
|
||||
backup="$1"
|
||||
# Move whatever partial new code the interrupted swap left in the install
|
||||
# root aside, so a later restore never mistakes it for the old tree.
|
||||
for entry in $code_entries; do
|
||||
if [ -e "$entry" ] && [ -e "$backup/$entry" ]; then
|
||||
rejected="$backup/rejected/$entry"
|
||||
rejected_parent="${rejected%/*}"
|
||||
mkdir -p "$rejected_parent"
|
||||
if [ -e "$rejected" ]; then
|
||||
rm -rf -- "$entry"
|
||||
else
|
||||
mv -- "$entry" "$rejected"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
# Put back every complete entry recorded by the swap manifest.
|
||||
for entry in $code_entries; do
|
||||
if [ ! -e "$entry" ] && [ -e "$backup/$entry" ]; then
|
||||
parent="${entry%/*}"
|
||||
if [ "$parent" != "$entry" ]; then
|
||||
mkdir -p "$parent"
|
||||
fi
|
||||
mv -- "$backup/$entry" "$entry"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
if recovery_needed; then
|
||||
if ! acquire_recovery_lock; then
|
||||
echo "WebSpeak update or recovery is already running, or its lock cannot be verified; refusing to change application files." >&2
|
||||
exit 75
|
||||
fi
|
||||
# The runner may have completed between the first state read and the lock.
|
||||
read_update_task
|
||||
fi
|
||||
|
||||
if [ "${lock_owned:-0}" = 1 ] && recovery_needed; then
|
||||
restore_backup=""
|
||||
|
||||
# The interrupted task is the source of truth. Its backup may be partial
|
||||
# while the old tree is being saved or while a previous recovery is still
|
||||
# consuming it, but it must never be replaced by an older complete backup.
|
||||
if [ -n "$task_id" ] && [ -d "$backups/$task_id" ]; then
|
||||
candidate="$backups/$task_id"
|
||||
if task_backup_can_repair "$candidate"; then
|
||||
restore_backup="$candidate"
|
||||
fi
|
||||
else
|
||||
# No current task backup (e.g. state.json was lost): use the most recently
|
||||
# modified complete backup rather than whichever name happens to sort first.
|
||||
for manifest in "$backups"/*/.webspeak-swap.json; do
|
||||
[ -f "$manifest" ] || continue
|
||||
backup="${manifest%/.webspeak-swap.json}"
|
||||
backup_is_complete "$backup" || continue
|
||||
if [ -z "$restore_backup" ] || [ "$backup" -nt "$restore_backup" ]; then
|
||||
restore_backup="$backup"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [ -z "$restore_backup" ]; then
|
||||
echo "WebSpeak update was interrupted and automatic recovery from $backups failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
restore_from_backup "$restore_backup"
|
||||
if code_missing; then
|
||||
echo "WebSpeak update was interrupted and automatic recovery from $restore_backup failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
release_recovery_lock
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
+101
-11
@@ -8,6 +8,11 @@ import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
import { SkinStore } from "./skin-store.js";
|
||||
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;
|
||||
@@ -38,7 +43,14 @@ export interface AdminRouterOptions {
|
||||
logFile?: string;
|
||||
skinRegistry?: SkinRegistry;
|
||||
skinStore?: SkinStore;
|
||||
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;
|
||||
}
|
||||
|
||||
export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
@@ -85,25 +97,29 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.status(409).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
const peer = request.socket.remoteAddress ?? "unknown";
|
||||
const retryAfterMs = limiter.retryAfterMs(peer);
|
||||
if (retryAfterMs > 0) {
|
||||
response.setHeader("Retry-After", String(Math.ceil(retryAfterMs / 1000)));
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs });
|
||||
return;
|
||||
}
|
||||
const peer = options.clientIp?.(request) ?? request.socket.remoteAddress ?? "unknown";
|
||||
const body = asRecord(request.body);
|
||||
const username = readString(body, "username", 64).trim();
|
||||
const password = readOptionalString(body, "password", 1024);
|
||||
if (!await options.service.verifyPassword(username, password)) {
|
||||
const delayMs = limiter.recordFailure(peer);
|
||||
const reservation = limiter.reserve(peer);
|
||||
if (!reservation.allowed) {
|
||||
response.setHeader("Retry-After", String(Math.ceil(reservation.retryAfterMs / 1000)));
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs: reservation.retryAfterMs });
|
||||
return;
|
||||
}
|
||||
const revision = options.service.credentialRevision;
|
||||
let verified: boolean;
|
||||
try { verified = await options.service.verifyPassword(username, password); }
|
||||
catch (error) { reservation.finish("cancelled"); sendAdminError(response, error); return; }
|
||||
if (!verified || revision !== options.service.credentialRevision) {
|
||||
const delayMs = reservation.finish("failure");
|
||||
await waitFor(delayMs);
|
||||
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
|
||||
logger.warn("Administrator login failed");
|
||||
response.status(401).json({ ok: false, code: "INVALID_PASSWORD" });
|
||||
return;
|
||||
}
|
||||
limiter.recordSuccess(peer);
|
||||
reservation.finish("success");
|
||||
options.service.database.addAudit("ADMIN_LOGIN_SUCCEEDED");
|
||||
const session = options.sessions.create(response, isSecureRequest(request));
|
||||
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt, mustChangePassword: options.service.isPasswordChangeRequired() });
|
||||
@@ -113,6 +129,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
await options.service.changePassword(readString(body, "newPassword", 1024));
|
||||
options.sessions.revokeOthers(request);
|
||||
response.json({ ok: true, mustChangePassword: false });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
@@ -126,6 +143,10 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
});
|
||||
|
||||
router.use(requireAdmin(options.sessions, options.service));
|
||||
router.use("/plugins", createPluginAdminRouter({ registry: options.pluginRegistry, store: options.pluginStore, runtime: options.pluginRuntime,
|
||||
protect: [requireSameOrigin, requireCsrf(options.sessions)],
|
||||
audit: (event, data) => options.service.database.addAudit(event, data),
|
||||
}));
|
||||
|
||||
router.get("/overview", (_request, response) => {
|
||||
response.json(options.service.getOverview(
|
||||
@@ -397,6 +418,63 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/update", (_request, response) => {
|
||||
if (!options.updateService) {
|
||||
response.json({
|
||||
currentVersion: options.version ?? "0.0.0",
|
||||
deployment: {
|
||||
mode: "source",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
applyAllowed: false,
|
||||
reasonCode: "UPDATE_UNAVAILABLE",
|
||||
upgradePath: "source",
|
||||
},
|
||||
task: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
response.json(options.updateService.getStatus());
|
||||
});
|
||||
|
||||
router.post("/update/check", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
|
||||
if (!options.updateService) {
|
||||
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
response.json(await options.updateService.checkForUpdates());
|
||||
} catch (error: unknown) {
|
||||
sendUpdateError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/update/apply", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
if (!options.updateService) {
|
||||
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
if (!options.restartAfterUpdate) {
|
||||
response.status(503).json({ ok: false, code: "UPDATE_RESTART_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
const version = readString(body, "version", 32);
|
||||
const confirmVersion = readString(body, "confirmVersion", 32);
|
||||
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
|
||||
const task = await options.updateService.applyUpdate(version, confirmVersion);
|
||||
options.service.database.addAudit("ADMIN_UPDATE_STARTED", { version });
|
||||
response.status(202).json({ ok: true, task });
|
||||
// Do not wait for the response to finish: a reverse proxy or a client
|
||||
// that disconnects early must not leave the restart runner waiting for
|
||||
// this process until its timeout expires.
|
||||
setTimeout(() => options.restartAfterUpdate?.(), 250).unref();
|
||||
} catch (error: unknown) {
|
||||
sendUpdateError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
|
||||
@@ -792,8 +870,20 @@ function logLevelName(level: unknown): string {
|
||||
|
||||
function sendAdminError(response: Response, error: unknown): void {
|
||||
if (error instanceof AdminInputError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
response.status(error.code === "AUTH_REQUIRED" ? 401 : 400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
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" });
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { WorkspaceInvites, type WorkspaceInviteCredentials } from "../server/workspace-invites.js";
|
||||
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
|
||||
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
|
||||
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
|
||||
@@ -45,6 +46,8 @@ type ProbeFunction = typeof probeTeamSpeak;
|
||||
|
||||
export class AdminService {
|
||||
private readonly tsAdmin: TsAdminService;
|
||||
private revision = 0;
|
||||
get credentialRevision(): number { return this.revision; }
|
||||
constructor(
|
||||
readonly database: WebSpeakDatabase,
|
||||
private readonly masterSecret: Buffer,
|
||||
@@ -74,8 +77,9 @@ export class AdminService {
|
||||
}
|
||||
|
||||
async verifyPassword(username: string, password: string): Promise<boolean> {
|
||||
const revision = this.revision;
|
||||
const credential = this.database.getAdminCredential();
|
||||
return credential?.username === username && await verifyAdminPassword(password, credential);
|
||||
return credential?.username === username && await verifyAdminPassword(password, credential) && revision === this.revision;
|
||||
}
|
||||
|
||||
isPasswordChangeRequired(): boolean {
|
||||
@@ -83,12 +87,15 @@ export class AdminService {
|
||||
}
|
||||
|
||||
async changePassword(password: string): Promise<void> {
|
||||
const revision = this.revision;
|
||||
const credential = this.database.getAdminCredential();
|
||||
if (!credential) throw new AdminInputError("NOT_INITIALIZED", "The administrator account is not initialized");
|
||||
const passwordError = validateAdminPassword(password);
|
||||
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
|
||||
const replacement = await hashAdminPassword(password, { username: credential.username, mustChangePassword: false });
|
||||
if (revision !== this.revision) throw new AdminInputError("AUTH_REQUIRED", "Administrator credentials changed during the request");
|
||||
this.database.updateAdminCredential(replacement);
|
||||
this.revision++;
|
||||
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
|
||||
}
|
||||
|
||||
@@ -289,6 +296,14 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
createWorkspaceInvite(credentials: WorkspaceInviteCredentials, expiresInMinutes: number, now = Date.now()) {
|
||||
return new WorkspaceInvites(this.database, this.masterSecret).create(credentials, expiresInMinutes, now);
|
||||
}
|
||||
|
||||
getWorkspaceInvite(token: string, now = Date.now()) {
|
||||
return new WorkspaceInvites(this.database, this.masterSecret).get(token, now);
|
||||
}
|
||||
|
||||
createManagedInvite(input: ManagedInviteInput): { invite: ManagedInviteView; token: string } {
|
||||
const channel = input.channel.trim();
|
||||
if (channel.length > 100) throw new AdminInputError("INVALID_INVITE_CHANNEL", "Invite channel cannot exceed 100 characters");
|
||||
|
||||
@@ -50,6 +50,13 @@ export class AdminSessionStore {
|
||||
clear(): void {
|
||||
this.sessions.clear();
|
||||
}
|
||||
|
||||
/** A credential change retains only the authenticated session that performed it. */
|
||||
revokeOthers(request: Request): void {
|
||||
const token = readCookie(request.headers.cookie, COOKIE_NAME);
|
||||
const keep = token ? hashToken(token) : null;
|
||||
for (const key of this.sessions.keys()) if (key !== keep) this.sessions.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function isSecureRequest(request: Request): boolean {
|
||||
|
||||
@@ -1,51 +1,54 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
const WINDOW_MS = 5 * 60 * 1000;
|
||||
const MAX_FAILURES = 5;
|
||||
|
||||
interface LoginAttempt {
|
||||
failures: number;
|
||||
pending: number;
|
||||
firstFailureAt: number;
|
||||
}
|
||||
|
||||
type Reservation = { allowed: false; retryAfterMs: number }
|
||||
| { allowed: true; finish(result: "success" | "failure" | "cancelled"): number };
|
||||
|
||||
export class AdminLoginRateLimiter {
|
||||
private readonly attempts = new Map<string, LoginAttempt>();
|
||||
private pending = 0;
|
||||
|
||||
constructor(private readonly maxTrackedPeers = 1024) {}
|
||||
constructor(private readonly maxTrackedPeers = 1024, private readonly maxConcurrentChecks = 8) {}
|
||||
|
||||
retryAfterMs(peer: string, now = Date.now()): number {
|
||||
const attempt = this.attempts.get(peer);
|
||||
if (!attempt) return 0;
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) {
|
||||
this.attempts.delete(peer);
|
||||
return 0;
|
||||
}
|
||||
if (attempt.failures < MAX_FAILURES) return 0;
|
||||
return WINDOW_MS - (now - attempt.firstFailureAt);
|
||||
}
|
||||
|
||||
recordFailure(peer: string, now = Date.now()): number {
|
||||
/** Reserve before hashing; pending checks count against capacity, successes are not failures. */
|
||||
reserve(peer: string, now = performance.now()): Reservation {
|
||||
this.pruneExpired(now);
|
||||
const current = this.attempts.get(peer);
|
||||
if (!current) {
|
||||
this.pruneExpired(now);
|
||||
while (this.attempts.size >= this.maxTrackedPeers) {
|
||||
const oldestPeer = this.attempts.keys().next().value;
|
||||
if (!oldestPeer) break;
|
||||
this.attempts.delete(oldestPeer);
|
||||
}
|
||||
if (current && current.failures + current.pending >= MAX_FAILURES) {
|
||||
return { allowed: false, retryAfterMs: Math.max(1000, WINDOW_MS - (now - current.firstFailureAt)) };
|
||||
}
|
||||
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
|
||||
? { failures: 1, firstFailureAt: now }
|
||||
: { ...current, failures: current.failures + 1 };
|
||||
if (this.pending >= this.maxConcurrentChecks || (!current && this.attempts.size >= this.maxTrackedPeers)) {
|
||||
// Never evict another visitor's lockout or pending check to admit a new address.
|
||||
return { allowed: false, retryAfterMs: 1000 };
|
||||
}
|
||||
const attempt = current ?? { failures: 0, pending: 0, firstFailureAt: now };
|
||||
this.attempts.set(peer, attempt);
|
||||
return Math.min(2000, 250 * (2 ** Math.min(3, attempt.failures - 1)));
|
||||
}
|
||||
|
||||
recordSuccess(peer: string): void {
|
||||
this.attempts.delete(peer);
|
||||
attempt.pending++;
|
||||
this.pending++;
|
||||
let finished = false;
|
||||
return { allowed: true, finish: result => {
|
||||
if (finished) return 0;
|
||||
finished = true;
|
||||
this.pending--;
|
||||
attempt.pending--;
|
||||
if (result === "success") attempt.failures = 0;
|
||||
else if (result === "failure") attempt.failures++;
|
||||
if (!attempt.failures && !attempt.pending) this.attempts.delete(peer);
|
||||
return result === "failure" ? Math.min(2000, 250 * 2 ** Math.min(3, attempt.failures - 1)) : 0;
|
||||
} };
|
||||
}
|
||||
|
||||
private pruneExpired(now: number): void {
|
||||
for (const [peer, attempt] of this.attempts) {
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
|
||||
if (!attempt.pending && now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createServer } from "node:net";
|
||||
import express from "express";
|
||||
import { AdminLoginRateLimiter } from "./login-rate-limit.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 { createWebServer } from "../server/server.js";
|
||||
import { JoinTicketStore } from "../server/join-ticket.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(yes => { resolve = yes; }); return { promise, resolve }; };
|
||||
|
||||
test("login reservations bound pending work, count only failures and preserve other lockouts", () => {
|
||||
const limiter = new AdminLoginRateLimiter(2, 8);
|
||||
const reserved = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
|
||||
assert.ok(reserved.every(value => value.allowed));
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
for (const item of reserved) if (item.allowed) item.finish("failure");
|
||||
const b = limiter.reserve("b", 0); assert.ok(b.allowed); b.finish("failure");
|
||||
assert.equal(limiter.reserve("c", 0).allowed, false, "new IPs cannot evict an existing lockout");
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
assert.equal(limiter.reserve("a", 300_001).allowed, true);
|
||||
const successes = new AdminLoginRateLimiter(1);
|
||||
for (let i = 0; i < 20; i++) { const item = successes.reserve("a", 0); assert.ok(item.allowed); item.finish("success"); }
|
||||
const cap = new AdminLoginRateLimiter(10, 2);
|
||||
const first = cap.reserve("a", 0), second = cap.reserve("b", 0);
|
||||
assert.ok(first.allowed && second.allowed);
|
||||
assert.equal(cap.reserve("c", 0).allowed, false, "different IPs share the hash concurrency ceiling");
|
||||
first.finish("cancelled"); first.finish("cancelled");
|
||||
const third = cap.reserve("c", 0); assert.ok(third.allowed);
|
||||
assert.equal(cap.reserve("d", 0).allowed, false, "finishing twice cannot release another request's slot");
|
||||
second.finish("success"); third.finish("success");
|
||||
});
|
||||
|
||||
test("a pending check cannot expire out of the reservation count", () => {
|
||||
const limiter = new AdminLoginRateLimiter(1);
|
||||
const checks = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
|
||||
assert.ok(checks.every(item => item.allowed));
|
||||
assert.equal(limiter.reserve("a", 400_000).allowed, false);
|
||||
for (const item of checks) if (item.allowed) item.finish("cancelled");
|
||||
assert.equal(limiter.reserve("b", 400_000).allowed, true);
|
||||
});
|
||||
|
||||
test("a successful concurrent login cannot erase another request's reservation", () => {
|
||||
const limiter = new AdminLoginRateLimiter(1);
|
||||
const slow = limiter.reserve("a", 0), success = limiter.reserve("a", 0);
|
||||
assert.ok(slow.allowed && success.allowed);
|
||||
success.finish("success");
|
||||
const additional = Array.from({ length: 4 }, () => limiter.reserve("a", 0));
|
||||
assert.ok(additional.every(item => item.allowed));
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
slow.finish("failure");
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
});
|
||||
|
||||
async function availablePort() {
|
||||
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;
|
||||
}
|
||||
|
||||
for (const trusted of [true, false]) test(`HTTP login and join limits ${trusted ? "separate trusted proxy clients" : "ignore spoofed headers from an untrusted peer"}`, async t => {
|
||||
let checks = 0;
|
||||
const gate = deferred();
|
||||
const service = { credentialRevision: 0, isInitialized: () => true,
|
||||
verifyPassword: async () => { checks++; await gate.promise; return false; },
|
||||
database: { addAudit() {} },
|
||||
getConnectionPolicy: () => ({ accessMode: "fixed", defaultTarget: "8.8.8.8#9987", serverPassword: "" }),
|
||||
isPasswordChangeRequired: () => false,
|
||||
} as unknown as AdminService;
|
||||
const port = await availablePort(), origin = `http://127.0.0.1:${port}`;
|
||||
const gateway = createWebServer({ port, logger, adminService: service, voiceBridgeOptions: {
|
||||
joinTickets: new JoinTicketStore(), trustedProxies: trusted ? ["127.0.0.1", "::1"] : ["192.0.2.1"],
|
||||
} });
|
||||
await gateway.start();
|
||||
t.after(async () => { gate.resolve(); await gateway.stop(); });
|
||||
const post = (route: string, client: string, body: unknown) => fetch(origin + route, {
|
||||
method: "POST", headers: { origin, "content-type": "application/json", "x-forwarded-for": client }, body: JSON.stringify(body),
|
||||
});
|
||||
const a = "203.0.113.9", b = "198.51.100.4";
|
||||
const logins = Array.from({ length: 12 }, () => post("/api/admin/login", a, { username: "admin", password: "bad" }));
|
||||
const results = Promise.all(logins);
|
||||
gate.resolve();
|
||||
const responses = await results;
|
||||
const statuses = responses.map(r => r.status);
|
||||
assert.equal(checks, 5);
|
||||
assert.equal(statuses.filter(s => s === 401).length, 5);
|
||||
assert.equal(statuses.filter(s => s === 429).length, 7);
|
||||
assert.ok(Number(responses.find(r => r.status === 429)!.headers.get("retry-after")) > 0);
|
||||
assert.equal((await post("/api/admin/login", b, { username: "admin", password: "bad" })).status, trusted ? 401 : 429);
|
||||
for (let i = 0; i < 30; i++) assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 201);
|
||||
assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 429);
|
||||
assert.equal((await post("/api/join-ticket", b, { nickname: "Test" })).status, trusted ? 201 : 429);
|
||||
});
|
||||
|
||||
test("password-verifier exceptions release reservations without leaking their details", async t => {
|
||||
const app = express(); app.use(express.json());
|
||||
const service = { credentialRevision: 0, isInitialized: () => true,
|
||||
verifyPassword: async () => { throw new Error("secret verifier failure detail"); },
|
||||
} as unknown as AdminService;
|
||||
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
|
||||
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
|
||||
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())); });
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const response = await fetch(origin + "/api/admin/login", { method: "POST", headers: { origin, "content-type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "irrelevant" }) });
|
||||
assert.equal(response.status, 500);
|
||||
assert.deepEqual(await response.json(), { ok: false, code: "INTERNAL_ERROR" });
|
||||
}
|
||||
});
|
||||
|
||||
async function adminFixture(t: TestContext) {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "webspeak-auth-race-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"));
|
||||
await service.initialize(); // Intentionally keep the default password for the bootstrap race.
|
||||
const app = express(); app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
|
||||
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
|
||||
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(); await rm(directory, { recursive: true }); });
|
||||
const post = (route: string, body: unknown, cookie = "", csrf = "") => fetch(origin + "/api/admin" + route, {
|
||||
method: "POST", headers: { origin, cookie, "content-type": "application/json", "x-csrf-token": csrf }, body: JSON.stringify(body),
|
||||
});
|
||||
const login = async (password: string) => {
|
||||
const response = await post("/login", { username: "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 };
|
||||
};
|
||||
const authenticated = async (cookie: string) => (await (await fetch(origin + "/api/admin/session", { headers: { cookie } })).json() as { authenticated: boolean }).authenticated;
|
||||
return { service, database, post, login, authenticated };
|
||||
}
|
||||
|
||||
test("password rotation revokes other default-password sessions and a login finishing after rotation", { timeout: 15_000 }, async t => {
|
||||
const f = await adminFixture(t);
|
||||
const current = await f.login("admin"), other = await f.login("admin");
|
||||
const verified = deferred(), release = deferred();
|
||||
const verify = f.service.verifyPassword.bind(f.service);
|
||||
t.mock.method(f.service, "verifyPassword", async (username: string, password: string) => {
|
||||
const result = await verify(username, password);
|
||||
if (password === "admin") { verified.resolve(); await release.promise; }
|
||||
return result;
|
||||
});
|
||||
const pending = f.post("/login", { username: "admin", password: "admin" });
|
||||
await verified.promise;
|
||||
try {
|
||||
const changed = await f.post("/change-password", { newPassword: "new-password-for-test" }, current.cookie, current.csrf);
|
||||
assert.equal(changed.status, 200);
|
||||
assert.equal(await f.authenticated(current.cookie), true);
|
||||
assert.equal(await f.authenticated(other.cookie), false);
|
||||
} finally { release.resolve(); }
|
||||
const stale = await pending;
|
||||
assert.equal(stale.status, 401);
|
||||
assert.equal(stale.headers.get("set-cookie"), null, "an old verification cannot mint a new session");
|
||||
await f.login("new-password-for-test");
|
||||
});
|
||||
|
||||
test("failed password updates keep other sessions and concurrent rotations cannot overwrite a winner", { timeout: 15_000 }, async t => {
|
||||
const f = await adminFixture(t);
|
||||
const current = await f.login("admin"), other = await f.login("admin");
|
||||
assert.equal((await f.post("/change-password", { newPassword: "short" }, current.cookie, current.csrf)).status, 400);
|
||||
assert.equal(await f.authenticated(other.cookie), true);
|
||||
const results = await Promise.all([
|
||||
f.post("/change-password", { newPassword: "first-possible-password" }, current.cookie, current.csrf),
|
||||
f.post("/change-password", { newPassword: "second-possible-password" }, other.cookie, other.csrf),
|
||||
]);
|
||||
assert.deepEqual(results.map(r => r.status).sort(), [200, 401]);
|
||||
const winner = results[0]!.status === 200 ? current : other;
|
||||
const loser = winner === current ? other : current;
|
||||
assert.equal(await f.authenticated(winner.cookie), true);
|
||||
assert.equal(await f.authenticated(loser.cookie), false);
|
||||
});
|
||||
@@ -449,3 +449,55 @@ function crc32(bytes: Buffer): number {
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
test("the registry validates chrome.json hidden parts and icon bitmaps without executing skin code", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-chrome-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const chromeManifest = {
|
||||
...manifest,
|
||||
schemaVersion: 3,
|
||||
packageType: "open-skin",
|
||||
content: undefined,
|
||||
preview: undefined,
|
||||
chrome: "chrome.json",
|
||||
};
|
||||
const chrome = (hiddenParts: string[], iconPath = "assets/icons/language.png") => JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
hiddenParts,
|
||||
icons: { "language.trigger": iconPath },
|
||||
});
|
||||
const goodFiles: Array<[string, Buffer]> = [
|
||||
["manifest.json", Buffer.from(JSON.stringify(chromeManifest))],
|
||||
["skin.css", Buffer.from('[data-ws-part="host.plugins.launcher"] { color: teal; }')],
|
||||
["chrome.json", Buffer.from(chrome(["host.watermark", "host.hint"]))],
|
||||
["assets/icons/language.png", Buffer.from([137, 80, 78, 71, 1, 2, 3])],
|
||||
];
|
||||
const saved = await registry.save(createZip(goodFiles), "sample-skin");
|
||||
assert.equal((saved as unknown as { chrome?: string }).chrome, "chrome.json");
|
||||
|
||||
const protectedChrome = [...goodFiles];
|
||||
protectedChrome[2] = ["chrome.json", Buffer.from(chrome(["voice.audio-dock"]))];
|
||||
await assert.rejects(registry.save(createZip(protectedChrome), "sample-skin"),
|
||||
(error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_CHROME_HIDDEN_INVALID");
|
||||
|
||||
const missingIcon = goodFiles.filter(([name]) => name !== "assets/icons/language.png");
|
||||
await assert.rejects(registry.save(createZip(missingIcon), "sample-skin"),
|
||||
(error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ICON_MISSING");
|
||||
|
||||
const badIconPath = [...goodFiles];
|
||||
badIconPath[2] = ["chrome.json", Buffer.from(chrome(["host.hint"], "../../escape.png"))];
|
||||
await assert.rejects(registry.save(createZip(badIconPath), "sample-skin"),
|
||||
(error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ICON_PATH");
|
||||
|
||||
const oversizedIcon = [...goodFiles];
|
||||
oversizedIcon[3] = ["assets/icons/language.png", Buffer.alloc(64 * 1024 + 1)];
|
||||
await assert.rejects(registry.save(createZip(oversizedIcon), "sample-skin"),
|
||||
(error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ICON_SIZE");
|
||||
|
||||
// v1/v2 packages cannot declare host chrome options.
|
||||
const legacy = [...goodFiles];
|
||||
legacy[0] = ["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined, chrome: "chrome.json" }))];
|
||||
await assert.rejects(registry.save(createZip(legacy), "sample-skin"),
|
||||
(error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_SCHEMA_VERSION");
|
||||
});
|
||||
@@ -2,6 +2,12 @@ import { parseSkinWorkspacePolicy, type SkinWorkspacePolicy } from "../shared/sk
|
||||
import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js";
|
||||
import { compileSkinCss, SkinCssValidationError, type SkinCssSchemaVersion } from "../shared/skin-css.js";
|
||||
import { parseSkinLayoutJson } from "../shared/skin-layout.js";
|
||||
import {
|
||||
parseSkinChromeDocument,
|
||||
SKIN_CHROME_MAX_BYTES,
|
||||
SkinChromeError,
|
||||
validateSkinChromeAssets,
|
||||
} from "../shared/skin-chrome.js";
|
||||
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../shared/skin-plugin.js";
|
||||
import {
|
||||
listSkinRuntimePluginFilePaths,
|
||||
@@ -59,6 +65,7 @@ type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" |
|
||||
content?: string;
|
||||
components?: string;
|
||||
plugins?: string;
|
||||
chrome?: string;
|
||||
workspace?: SkinWorkspacePolicy;
|
||||
preview?: string;
|
||||
};
|
||||
@@ -248,7 +255,7 @@ export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manif
|
||||
}
|
||||
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
|
||||
const runtimePluginPathSet = new Set(runtimePluginPaths.map((packagePath) => packagePath.toLowerCase()));
|
||||
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
|
||||
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome, manifest.preview]
|
||||
.filter((packagePath): packagePath is string => Boolean(packagePath)).map((packagePath) => packagePath.toLowerCase());
|
||||
if (runtimePluginPaths.some((packagePath) => manifestPathSet.includes(packagePath))) {
|
||||
throw new SkinRegistryError("Plugin files cannot reuse skin manifest, CSS, content, component, or preview paths.", "SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE");
|
||||
@@ -276,7 +283,7 @@ export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manif
|
||||
let previewBytes: Buffer | undefined;
|
||||
let previewMime: string | undefined;
|
||||
for (const [packagePath, data] of fileBytes) {
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview].includes(packagePath)
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome, manifest.preview].includes(packagePath)
|
||||
|| runtimePluginPathSet.has(packagePath.toLowerCase())) continue;
|
||||
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
|
||||
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
|
||||
@@ -286,6 +293,27 @@ export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manif
|
||||
const cssAssets = new Set([...fileBytes.keys()].filter((packagePath) =>
|
||||
imageMime(packagePath) !== null || packagePath.toLowerCase().endsWith(".woff2")));
|
||||
validateSkinCss(cssSource, manifest.id, cssAssets, manifest.schemaVersion);
|
||||
if (manifest.chrome) {
|
||||
const chromeBytes = fileBytes.get(manifest.chrome);
|
||||
if (!chromeBytes || !chromeBytes.byteLength || chromeBytes.byteLength > SKIN_CHROME_MAX_BYTES) {
|
||||
throw new SkinRegistryError("chrome.json is missing or exceeds 32 KiB.", "SKIN_CHROME_SIZE");
|
||||
}
|
||||
try {
|
||||
const chrome = parseSkinChromeDocument(decodeUtf8(chromeBytes, "chrome.json is not valid UTF-8."));
|
||||
// The registry only stores the archive; CSS is compiled by the browser
|
||||
// importer from the same bytes. Verify every referenced bitmap here too
|
||||
// so an incomplete package can never be enabled on an instance.
|
||||
validateSkinChromeAssets(chrome, (packagePath) => {
|
||||
const data = fileBytes.get(packagePath);
|
||||
return data ? { bytes: data.byteLength, mime: imageMime(packagePath) ?? "" } : undefined;
|
||||
});
|
||||
} catch (error) {
|
||||
const chromeError = error instanceof SkinChromeError
|
||||
? error
|
||||
: new SkinChromeError(error instanceof Error ? error.message : "Invalid chrome.json.", "SKIN_CHROME_INVALID");
|
||||
throw new SkinRegistryError(chromeError.message, chromeError.code);
|
||||
}
|
||||
}
|
||||
for (const plugin of runtimePlugins?.plugins ?? []) {
|
||||
if (!plugin.style) continue;
|
||||
const styleBytes = fileBytes.get(plugin.style);
|
||||
@@ -474,7 +502,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion >= 2) {
|
||||
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
|
||||
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); }
|
||||
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); fields.add("chrome"); }
|
||||
if (schemaVersion === 4) fields.add("plugins");
|
||||
const unknown = Object.keys(value).find((key) => !fields.has(key));
|
||||
if (unknown) throw new SkinRegistryError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
|
||||
@@ -494,8 +522,8 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
}
|
||||
if (schemaVersion === 3 && value.packageType !== "open-skin") throw new SkinRegistryError("Version 3 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
|
||||
if (schemaVersion === 4 && value.packageType !== "open-skin") throw new SkinRegistryError("Version 4 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
|
||||
if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined || value.components !== undefined || value.plugins !== undefined)) {
|
||||
throw new SkinRegistryError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined || value.components !== undefined || value.plugins !== undefined || value.chrome !== undefined)) {
|
||||
throw new SkinRegistryError("Version 1 skin packages cannot declare layout, chrome or plugin fields.", "SKIN_SCHEMA_VERSION");
|
||||
}
|
||||
const version = read("version", 32);
|
||||
const minAppVersion = read("minAppVersion", 32);
|
||||
@@ -506,13 +534,14 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
const content = readOptional("content", 120);
|
||||
const components = schemaVersion >= 3 && value.components != null ? read("components", 120) : undefined;
|
||||
const plugins = schemaVersion === 4 ? read("plugins", 120) : undefined;
|
||||
const chrome = schemaVersion >= 3 && value.chrome != null ? read("chrome", 120) : undefined;
|
||||
const preview = readOptional("preview", 120);
|
||||
for (const candidate of [entry, layout, content, components, plugins, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
for (const candidate of [entry, layout, content, components, plugins, chrome, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (chrome && !chrome.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, chrome, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(chrome ? [chrome] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
const description = readOptional("description", 400);
|
||||
return { schemaVersion, ...(workspace ? { workspace } : {}), ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
return { schemaVersion, ...(workspace ? { workspace } : {}), ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(chrome ? { chrome } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
}
|
||||
|
||||
function singleRootPrefix(paths: string[]): string {
|
||||
|
||||
@@ -134,8 +134,8 @@ export class SkinStore {
|
||||
const bytes = await this.download(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/${metadata.package.ref}/${metadata.package.path}`, MAX_PACK_BYTES);
|
||||
if (createHash("sha256").update(bytes).digest("hex") !== metadata.package.sha256) return fail("SKIN_STORE_CHECKSUM");
|
||||
const { manifest } = validateSkinArchive(bytes, input.id);
|
||||
for (const key of ["id", "name", "version", "author", "license", "minAppVersion"] as const) {
|
||||
if (manifest[key] !== metadata[key]) return fail("SKIN_STORE_PACKAGE_MISMATCH");
|
||||
if (manifest.version !== metadata.version || manifest.minAppVersion !== metadata.minAppVersion) {
|
||||
return fail("SKIN_STORE_PACKAGE_MISMATCH");
|
||||
}
|
||||
return registry.save(bytes, input.id);
|
||||
}
|
||||
|
||||
@@ -94,9 +94,9 @@ export class TsAdminService {
|
||||
welcomeMessage: server.virtualserver_welcomemessage ?? "", maxClients: numeric(server.virtualserver_maxclients),
|
||||
uptimeSeconds: numeric(server.virtualserver_uptime), channelCount: channels.length, clientCount: voiceClients.length,
|
||||
channels: channels.map(channel => ({ id: String(channel.id), parentID: String(channel.parentID), name: channel.name,
|
||||
description: channel.description, totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid, nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
serverGroups: entry.serverGroups.map(String), away: entry.isAway, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
|
||||
description: channel.description ?? "", totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid ?? "", nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
serverGroups: (entry.serverGroups ?? []).map(String), away: entry.isAway ?? false, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
|
||||
groups: groups.status === "fulfilled" ? groups.value.filter(group => group.type === 1).map(group => ({ id: String(group.id), name: group.name })) : [],
|
||||
bans: bans.status === "fulfilled" ? bans.value.map(ban => ({ id: String(ban.id), name: ban.name || ban.lastNickname,
|
||||
uid: ban.uid, reason: ban.reason, durationSeconds: ban.durationMs / 1000, createdAt: ban.createdAt?.toISOString() ?? null })) : [],
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import express from "express";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminService } from "./admin-service.js";
|
||||
import { AdminSessionStore } from "./admin-session.js";
|
||||
import { createAdminRouter } from "./admin-router.js";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { UpdateError, type UpdateService } from "../updater/update-service.js";
|
||||
import type { UpdateCheckView, UpdateStatusView, UpdateTaskView } from "../shared/update.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
const statusView: UpdateStatusView = {
|
||||
currentVersion: "0.3.2",
|
||||
deployment: {
|
||||
mode: "release-package", platform: "linux", architecture: "x64",
|
||||
applyAllowed: true, reasonCode: null, upgradePath: "release-package",
|
||||
},
|
||||
task: null,
|
||||
};
|
||||
|
||||
const taskView: UpdateTaskView = {
|
||||
id: "upd_route_test", status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
};
|
||||
|
||||
const checkView: UpdateCheckView = {
|
||||
currentVersion: "0.3.2",
|
||||
releases: [{
|
||||
version: "0.4.0", tag: "v0.4.0", publishedAt: "2026-01-01T00:00:00.000Z",
|
||||
releaseUrl: "https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.4.0",
|
||||
assetName: "webspeak-webclient-v0.4.0-linux-x64.tar.gz", assetSize: 10,
|
||||
assetAvailable: true, hasChecksums: true, digest: null, canApply: true, blockedReason: null,
|
||||
}],
|
||||
};
|
||||
|
||||
interface Fixture {
|
||||
origin: string;
|
||||
service: AdminService;
|
||||
database: WebSpeakDatabase;
|
||||
applyCalls: Array<[string, string]>;
|
||||
restarted: () => boolean;
|
||||
login(): Promise<{ cookie: string; csrf: string }>;
|
||||
post(route: string, body: unknown, headers?: Record<string, string>): Promise<Response>;
|
||||
}
|
||||
|
||||
async function fixture(t: TestContext, options: { updateService?: boolean } = {}): Promise<Fixture> {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-routes-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "test.db"));
|
||||
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"), undefined, "0.3.2");
|
||||
await service.initialize();
|
||||
await service.changePassword("test-only-admin-password");
|
||||
const applyCalls: Array<[string, string]> = [];
|
||||
let restarted = false;
|
||||
const updateService = {
|
||||
getStatus: () => statusView,
|
||||
checkForUpdates: async () => checkView,
|
||||
applyUpdate: async (version: string, confirmVersion: string) => {
|
||||
applyCalls.push([version, confirmVersion]);
|
||||
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "confirmation mismatch");
|
||||
return taskView;
|
||||
},
|
||||
} as unknown as UpdateService;
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({
|
||||
service, sessions: new AdminSessionStore(), logger,
|
||||
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now(), version: "0.3.2",
|
||||
...(options.updateService === false ? {} : { updateService, restartAfterUpdate: () => { restarted = true; } }),
|
||||
}));
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise<void>((resolve) => server.once("listening", resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
t.after(async () => {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
database.close();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
const post = (route: string, body: unknown, headers: Record<string, string> = {}) => fetch(`${origin}/api/admin${route}`, {
|
||||
method: "POST", headers: { origin, "content-type": "application/json", ...headers }, body: JSON.stringify(body),
|
||||
});
|
||||
const login = async () => {
|
||||
const response = await post("/login", { username: "admin", password: "test-only-admin-password" });
|
||||
assert.equal(response.status, 200);
|
||||
const body = await response.json() as { csrfToken: string };
|
||||
return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
|
||||
};
|
||||
return { origin, service, database, applyCalls, restarted: () => restarted, login, post };
|
||||
}
|
||||
|
||||
test("update routes require an authenticated session", async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await fetch(`${f.origin}/api/admin/update`)).status, 401);
|
||||
assert.equal((await f.post("/update/check", {})).status, 401);
|
||||
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" })).status, 401);
|
||||
});
|
||||
|
||||
test("update routes reject missing CSRF tokens and cross-origin requests", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const noCsrf = await f.post("/update/check", {}, { cookie });
|
||||
assert.equal(noCsrf.status, 403);
|
||||
assert.equal((await noCsrf.json() as { code: string }).code, "CSRF_REJECTED");
|
||||
const crossOrigin = await fetch(`${f.origin}/api/admin/update/apply`, {
|
||||
method: "POST",
|
||||
headers: { origin: "https://evil.example", cookie, "x-csrf-token": csrf, "content-type": "application/json" },
|
||||
body: JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" }),
|
||||
});
|
||||
assert.equal(crossOrigin.status, 403);
|
||||
assert.equal((await crossOrigin.json() as { code: string }).code, "ORIGIN_REJECTED");
|
||||
const wrongType = await fetch(`${f.origin}/api/admin/update/check`, {
|
||||
method: "POST",
|
||||
headers: { origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "text/plain" },
|
||||
body: "{}",
|
||||
});
|
||||
assert.equal(wrongType.status, 415);
|
||||
assert.equal((await wrongType.json() as { code: string }).code, "JSON_REQUIRED");
|
||||
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 200);
|
||||
});
|
||||
|
||||
test("apply requires version and confirmVersion to match before touching the service", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.1" }, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(response.status, 400);
|
||||
assert.equal((await response.json() as { code: string }).code, "UPDATE_CONFIRMATION_REQUIRED");
|
||||
assert.deepEqual(f.applyCalls, []);
|
||||
const missing = await f.post("/update/apply", { version: "0.4.0" }, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(missing.status, 400);
|
||||
assert.deepEqual(f.applyCalls, []);
|
||||
});
|
||||
|
||||
test("a confirmed apply returns the task and stops the process after the response", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(response.status, 202);
|
||||
const body = await response.json() as { ok: boolean; task: UpdateTaskView };
|
||||
assert.equal(body.ok, true);
|
||||
assert.equal(body.task.id, "upd_route_test");
|
||||
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
|
||||
assert.ok(f.database.recentAudit(10).some((event) => event.event === "ADMIN_UPDATE_STARTED"));
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 400));
|
||||
assert.equal(f.restarted(), true);
|
||||
});
|
||||
|
||||
test("a client that disconnects before the response still schedules the restart", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const body = JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" });
|
||||
const url = new URL(`${f.origin}/api/admin/update/apply`);
|
||||
const request = http.request({
|
||||
hostname: url.hostname, port: url.port, path: url.pathname, method: "POST",
|
||||
headers: {
|
||||
origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "application/json",
|
||||
"content-length": Buffer.byteLength(body),
|
||||
},
|
||||
});
|
||||
request.on("error", () => { /* Expected once the socket is destroyed. */ });
|
||||
request.end(body);
|
||||
const deadline = Date.now() + 2_000;
|
||||
while (f.applyCalls.length === 0 && Date.now() < deadline) await new Promise<void>((resolve) => setTimeout(resolve, 20));
|
||||
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
|
||||
// Close the connection without consuming the response. The restart must not
|
||||
// depend on the response finish event.
|
||||
request.destroy();
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 700));
|
||||
assert.equal(f.restarted(), true);
|
||||
});
|
||||
|
||||
test("update status and check return the service projections", async t => {
|
||||
const f = await fixture(t);
|
||||
const { cookie, csrf } = await f.login();
|
||||
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
|
||||
assert.equal(status.status, 200);
|
||||
assert.deepEqual(await status.json(), statusView);
|
||||
const check = await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf });
|
||||
assert.equal(check.status, 200);
|
||||
assert.deepEqual(await check.json(), checkView);
|
||||
});
|
||||
|
||||
test("deployments without an update service expose a read-only source status", async t => {
|
||||
const f = await fixture(t, { updateService: false });
|
||||
const { cookie, csrf } = await f.login();
|
||||
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
|
||||
assert.equal(status.status, 200);
|
||||
const body = await status.json() as UpdateStatusView;
|
||||
assert.equal(body.deployment.mode, "source");
|
||||
assert.equal(body.deployment.applyAllowed, false);
|
||||
assert.equal(body.deployment.reasonCode, "UPDATE_UNAVAILABLE");
|
||||
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 503);
|
||||
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf })).status, 503);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
test("protocol identifiers and favorite addresses keep ASCII casing under a Turkish locale", () => {
|
||||
const child = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", `
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseTeamSpeakTarget, teamSpeakTargetKey } from './src/domain/teamspeak-target.ts';
|
||||
import { quickServerTargetsEqual, mergeQuickServers } from './web/src/services/quick-servers.ts';
|
||||
import { normalizeTeamSpeakError } from './src/errors.ts';
|
||||
// Windows ignores LANG for ICU's default locale; isolate the Turkish default in this child.
|
||||
const localeLower = String.prototype.toLocaleLowerCase;
|
||||
String.prototype.toLocaleLowerCase = function(...locales) {
|
||||
return localeLower.call(this, ...(locales.length ? locales : ['tr']));
|
||||
};
|
||||
assert.equal('I'.toLocaleLowerCase(), 'ı', 'the child must actually run under Turkish casing');
|
||||
const target = parseTeamSpeakTarget('VOICE.EXAMPLE.IO#9987');
|
||||
assert.equal(target.host, 'voice.example.io');
|
||||
assert.equal(teamSpeakTargetKey({host:'VOICE.EXAMPLE.IO',port:9987}), 'voice.example.io:9987');
|
||||
assert.equal(quickServerTargetsEqual('VOICE.EXAMPLE.IO:9987', 'voice.example.io#9987'), true);
|
||||
assert.equal(mergeQuickServers([{id:'a',label:'a',address:'VOICE.EXAMPLE.IO:9987'}],
|
||||
[{id:'b',address:'voice.example.io:9987',lastConnectedAt:1}]).length, 1);
|
||||
const upper=normalizeTeamSpeakError(new Error('INVALID IDENTITY'));
|
||||
const lower=normalizeTeamSpeakError(new Error('invalid identity'));
|
||||
assert.equal(upper.code, lower.code);
|
||||
`], { env: { ...process.env, LANG: "tr_TR.UTF-8", LC_ALL: "tr_TR.UTF-8" }, encoding: "utf8" });
|
||||
assert.equal(child.status, 0, child.stderr || child.stdout);
|
||||
});
|
||||
@@ -72,11 +72,11 @@ export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
|
||||
}
|
||||
|
||||
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
|
||||
return formatTeamSpeakTarget(target).toLocaleLowerCase();
|
||||
return formatTeamSpeakTarget(target).toLowerCase();
|
||||
}
|
||||
|
||||
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
|
||||
const host = hostValue.trim().toLocaleLowerCase();
|
||||
const host = hostValue.trim().toLowerCase();
|
||||
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
|
||||
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
|
||||
}
|
||||
|
||||
+3
-3
@@ -186,7 +186,7 @@ function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnosti
|
||||
*/
|
||||
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
|
||||
if (id === undefined || id === null) return null;
|
||||
const text = String(id).trim().toLocaleLowerCase();
|
||||
const text = String(id).trim().toLowerCase();
|
||||
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
|
||||
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
|
||||
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
|
||||
@@ -199,7 +199,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
if (error instanceof WebSpeakError) return error;
|
||||
|
||||
const diagnostics = collectDiagnostics(error);
|
||||
const text = diagnosticText(error).toLocaleLowerCase();
|
||||
const text = diagnosticText(error).toLowerCase();
|
||||
|
||||
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
|
||||
// keyword heuristic below. The inline scan keeps the `id=515` shape
|
||||
@@ -258,7 +258,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
|
||||
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
|
||||
// the class name before falling back to the message text.
|
||||
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
|
||||
const errorName = (diagnostics.name ?? "").toLowerCase();
|
||||
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
|
||||
+43
-2
@@ -4,6 +4,8 @@ import { fileURLToPath } from "node:url";
|
||||
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, "..");
|
||||
@@ -45,17 +47,48 @@ async function main() {
|
||||
await adminService.initialize();
|
||||
removeObsoleteBootstrapFile();
|
||||
const joinTickets = new JoinTicketStore();
|
||||
const pluginRegistry = new PluginRegistry(path.join(DATA_DIR, "plugins"), masterSecret);
|
||||
await pluginRegistry.initialize();
|
||||
|
||||
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
|
||||
|
||||
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
|
||||
const updateService = new UpdateService({
|
||||
rootDir: ROOT_DIR,
|
||||
dataDir: DATA_DIR,
|
||||
currentVersion: APP_VERSION,
|
||||
logger,
|
||||
port: APP_PORT,
|
||||
https: hasCert,
|
||||
});
|
||||
updateService.initialize();
|
||||
|
||||
const webServer = createWebServer({
|
||||
let webServer: ReturnType<typeof createWebServer> | undefined;
|
||||
webServer = createWebServer({
|
||||
port: APP_PORT,
|
||||
version: APP_VERSION,
|
||||
logFile: path.join(LOG_DIR, "webspeak.log"),
|
||||
staticDir: STATIC_DIR,
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
updateService,
|
||||
restartAfterUpdate: () => {
|
||||
void (async () => {
|
||||
if (!updateService.runnerStillHealthy()) {
|
||||
// 202 already promised a restart, but the helper died before this
|
||||
// process left. Stay up and reconcile instead of reporting success
|
||||
// and silently abandoning the update.
|
||||
logger.warn("The restart runner is no longer healthy; keeping this process and reconciling the update state");
|
||||
try { updateService.initialize(); }
|
||||
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Update state could not be reconciled"); }
|
||||
return;
|
||||
}
|
||||
logger.info("Stopping for scheduled update");
|
||||
try { await webServer?.stop(); }
|
||||
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); }
|
||||
database.close();
|
||||
process.exit(0);
|
||||
})();
|
||||
},
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
|
||||
@@ -70,6 +103,8 @@ async function main() {
|
||||
},
|
||||
adminService,
|
||||
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
|
||||
pluginRegistry,
|
||||
pluginRuntime: { port: parsePort(process.env.WEBSPEAK_PLUGIN_PORT, 3042), host: process.env.WEBSPEAK_PLUGIN_HOST?.trim() || "0.0.0.0", publicOrigin: process.env.WEBSPEAK_PLUGIN_PUBLIC_ORIGIN?.trim() },
|
||||
logger,
|
||||
nextVisitorNumber: () => database.nextVisitorNumber(),
|
||||
visitorCount: () => database.getVisitorCount(),
|
||||
@@ -104,7 +139,13 @@ async function runRelayMode(): Promise<void> {
|
||||
import("./server/voice-gateway.js"),
|
||||
]);
|
||||
const logger = createLogger(LOG_DIR);
|
||||
const [{ WebSpeakDatabase }, { loadOrCreateMasterSecret }, { WorkspaceInvites }] = await Promise.all([
|
||||
import("./persistence/database.js"), import("./security/master-secret.js"), import("./server/workspace-invites.js"),
|
||||
]);
|
||||
const inviteDatabase = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db"));
|
||||
const workspaceInvites = new WorkspaceInvites(inviteDatabase, loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key")));
|
||||
const voiceGateway = createVoiceGatewayServer({
|
||||
workspaceInvites,
|
||||
host: voiceHost,
|
||||
port: voicePort,
|
||||
sharedToken: token,
|
||||
@@ -139,7 +180,7 @@ async function runRelayMode(): Promise<void> {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
relay.close();
|
||||
void voiceGateway.stop().finally(() => process.exit(0));
|
||||
void voiceGateway.stop().finally(() => { inviteDatabase.close(); process.exit(0); });
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ app.get("/api/health", (_request, response) => response.json({ status: "ok", eng
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.json({
|
||||
version: process.env.WEBSPEAK_VERSION ?? "0.2.6",
|
||||
version: process.env.WEBSPEAK_VERSION ?? "0.3.0",
|
||||
initialized: true,
|
||||
siteName: "WebSpeak",
|
||||
welcomeText: DEFAULT_WELCOME_TEXTS.zh,
|
||||
|
||||
@@ -15,7 +15,7 @@ test("relay voice endpoint is stored by the current database migration", (contex
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
assert.equal(DATABASE_SCHEMA_VERSION, 12);
|
||||
assert.equal(DATABASE_SCHEMA_VERSION, 13);
|
||||
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
|
||||
assert.equal(database.getTsAdminSettings().transport, "web");
|
||||
assert.equal(database.getTsAdminSettings().enabled, false);
|
||||
@@ -38,13 +38,13 @@ test("schema 11 migration preserves encrypted SSH credentials and does not silen
|
||||
const original = new WebSpeakDatabase(filename);
|
||||
original.close();
|
||||
const old = new DatabaseSync(filename);
|
||||
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; PRAGMA user_version = 11;");
|
||||
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; DROP TABLE workspace_invites; PRAGMA user_version = 11;");
|
||||
old.prepare("UPDATE ts_admin_settings SET enabled=1, query_port=10222, username='query-owner', password_encrypted=?, host_key_fingerprint=?").run(encrypted, `SHA256:${"A".repeat(43)}`);
|
||||
old.close();
|
||||
const migrated = new WebSpeakDatabase(filename);
|
||||
t.after(() => { migrated.close(); rmSync(directory, { recursive: true, force: true }); });
|
||||
const settings = migrated.getTsAdminSettings();
|
||||
assert.equal(migrated.schemaVersion, 12);
|
||||
assert.equal(migrated.schemaVersion, 13);
|
||||
assert.equal(settings.transport, "ssh"); assert.equal(settings.enabled, true);
|
||||
assert.equal(settings.queryPort, 10222); assert.equal(settings.username, "query-owner");
|
||||
assert.equal(settings.passwordEncrypted, encrypted);
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 12;
|
||||
export const DATABASE_SCHEMA_VERSION = 13;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -190,6 +190,18 @@ export class WebSpeakDatabase {
|
||||
this.migrate(existed);
|
||||
}
|
||||
|
||||
saveWorkspaceInvite(tokenHash: string, encrypted: string, expiresAt: number, now = Date.now()): void {
|
||||
this.database.prepare("DELETE FROM workspace_invites WHERE expires_at <= ?").run(now);
|
||||
const count = this.database.prepare("SELECT COUNT(*) AS n FROM workspace_invites").get() as { n: number };
|
||||
if (count.n >= 4096) throw new Error("INVITE_LIMIT_REACHED");
|
||||
this.database.prepare("INSERT INTO workspace_invites(token_hash, payload_encrypted, expires_at) VALUES (?, ?, ?)").run(tokenHash, encrypted, expiresAt);
|
||||
}
|
||||
|
||||
getWorkspaceInvite(tokenHash: string, now = Date.now()): string | null {
|
||||
const row = this.database.prepare("SELECT payload_encrypted FROM workspace_invites WHERE token_hash = ? AND expires_at > ?").get(tokenHash, now) as { payload_encrypted: string } | undefined;
|
||||
return row?.payload_encrypted ?? null;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.database.close();
|
||||
}
|
||||
@@ -731,6 +743,17 @@ export class WebSpeakDatabase {
|
||||
PRAGMA user_version = 12;
|
||||
`);
|
||||
});
|
||||
version = 12;
|
||||
}
|
||||
if (version === 12) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`CREATE TABLE workspace_invites (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
payload_encrypted TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
); CREATE INDEX workspace_invites_expiry ON workspace_invites(expires_at);
|
||||
PRAGMA user_version = 13;`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import express, { Router, type RequestHandler } from "express";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PluginStore } from "./store.js";
|
||||
import type { PluginRuntime } from "./runtime.js";
|
||||
import { pluginAssert, pluginRecord, PluginError, parsePluginPackage } from "../shared/plugins.js";
|
||||
|
||||
export function createPluginAdminRouter(options: {
|
||||
registry?: PluginRegistry; store?: PluginStore; runtime?: PluginRuntime; protect: RequestHandler[];
|
||||
audit(event: string, data: { id: string; version?: string }): void;
|
||||
}) {
|
||||
const router = Router(), store = options.store ?? new PluginStore();
|
||||
const writeGuard = Router(); writeGuard.use(...options.protect);
|
||||
router.use((request, response, next) => {
|
||||
if (request.method === "GET") return next();
|
||||
// Reuse the admin session's same-origin and CSRF rules for every write.
|
||||
writeGuard(request, response, next);
|
||||
});
|
||||
// The parent authenticates before parsing a potentially large application bundle.
|
||||
router.use(express.json({limit:"50mb"}));
|
||||
const registry = () => { pluginAssert(options.registry, "PLUGIN_STORAGE_UNAVAILABLE"); return options.registry; };
|
||||
const project=(plugin:ReturnType<PluginRegistry["list"]>[number])=>({...plugin,runtime:options.runtime?.status(plugin.manifest.id)??{state:plugin.settings.enabled?(plugin.manifest.server?"stopped":"client"):"disabled"}});
|
||||
router.get("/", (_request, response) => response.json({ plugins: registry().list().map(project) }));
|
||||
router.get("/runtime",(_request,response)=>{pluginAssert(options.runtime,"PLUGIN_RUNTIME_UNAVAILABLE");response.json({runtime:options.runtime.settings()});});
|
||||
router.put("/runtime",async(request,response)=>{
|
||||
pluginAssert(options.runtime&&pluginRecord(request.body));const runtime=await options.runtime.configureOrigin(request.body.publicOrigin,request.body.revision);
|
||||
options.audit("ADMIN_PLUGIN_RUNTIME_CONFIGURED",{id:"runtime"});response.json({runtime});
|
||||
});
|
||||
router.get("/store", async (_request, response) => { response.json(await store.list()); });
|
||||
router.post("/store/install", async (request, response) => {
|
||||
const plugin = await store.install(registry(), request.body);
|
||||
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
|
||||
response.status(201).json({ plugin:project(plugin) });
|
||||
});
|
||||
router.post("/upload", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body));
|
||||
const expected = request.body.installedRevision;
|
||||
pluginAssert(expected === null || typeof expected === "string");
|
||||
const plugin = await registry().install(parsePluginPackage(request.body.package), expected);
|
||||
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
|
||||
response.status(201).json({ plugin:project(plugin) });
|
||||
});
|
||||
router.put("/:id/settings", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
|
||||
const plugin = await registry().configure(String(request.params.id), request.body.settings, request.body.revision);
|
||||
await options.runtime?.synchronize(plugin.manifest.id);
|
||||
options.audit("ADMIN_PLUGIN_CONFIGURED", { id: plugin.manifest.id });
|
||||
response.json({ plugin:project(plugin) });
|
||||
});
|
||||
router.post("/:id/restart",async(request,response)=>{
|
||||
pluginAssert(options.runtime&&pluginRecord(request.body));const id=String(request.params.id),plugin=registry().policy(id);
|
||||
pluginAssert(plugin,"PLUGIN_NOT_FOUND");pluginAssert(plugin.revision===request.body.revision,"PLUGIN_CHANGED");pluginAssert(plugin.settings.enabled&&plugin.settings.trusted,"PLUGIN_DISABLED");
|
||||
await options.runtime.restart(id);options.audit("ADMIN_PLUGIN_RESTARTED",{id});response.json({plugin:project(plugin)});
|
||||
});
|
||||
router.delete("/:id", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
|
||||
await registry().remove(String(request.params.id), request.body.revision);
|
||||
await options.runtime?.synchronize(String(request.params.id));
|
||||
options.audit("ADMIN_PLUGIN_REMOVED", { id: String(request.params.id) }); response.json({ ok: true });
|
||||
});
|
||||
router.use((error: unknown, _request: unknown, response: import("express").Response, _next: unknown) => {
|
||||
const tooLarge=pluginRecord(error)&&error.type==="entity.too.large";
|
||||
const code = tooLarge?"PLUGIN_TOO_LARGE":error instanceof PluginError ? error.code : "PLUGIN_FAILED";
|
||||
response.status(tooLarge?413:code === "PLUGIN_STORE_UNAVAILABLE" ? 502 : code === "PLUGIN_NOT_FOUND" ? 404 : code === "PLUGIN_CHANGED" ? 409 : 400).json({ ok: false, code });
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { mkdtemp, rm, readFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { PluginRegistry } from './registry.js';
|
||||
import { PluginProcess } from './process.js';
|
||||
import { parsePluginPackage, parsePluginJson, pluginPath, pluginFileBytes, type PluginPackage, type PluginAppContext } from '../shared/plugins.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
|
||||
export const fixturePackage = (server?:string):PluginPackage => parsePluginPackage({manifest:{apiVersion:2,id:'test.application',name:'Application',version:'1.0.0',author:'Tests',license:'MIT',description:'Independent application fixture',scopes:['server','instance'],client:{entry:'client/index.html'},...(server?{server:{entry:'server/main.mjs'}}:{})},files:{'client/index.html':{encoding:'utf8',data:'<!doctype html><html><head></head><body><script type="module" src="./app.js"></script></body></html>'},'client/app.js':{encoding:'utf8',data:'document.body.dataset.ready="yes"'},...(server?{'server/main.mjs':{encoding:'utf8',data:server}}:{})}});
|
||||
async function registry(t:test.TestContext){const directory=await mkdtemp(path.join(tmpdir(),'webspeak-app-v2-'));const cleanup:Array<()=>Promise<unknown>>=[];t.after(async()=>{for(const dispose of cleanup)await dispose();assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});const value=new PluginRegistry(directory,Buffer.alloc(32,7));await value.initialize();return {value,directory,cleanup};}
|
||||
|
||||
test('v2 accepts ordinary application assets and rejects the obsolete room protocol',()=>{
|
||||
const pack=fixturePackage();assert.equal(pack.manifest.apiVersion,2);assert.ok(pack.files['client/app.js']);
|
||||
assert.throws(()=>parsePluginPackage({manifest:{...pack.manifest,apiVersion:1},html:'x',script:'x',styles:{light:'x',dark:'x'}}),/PLUGIN_API_UNSUPPORTED/);
|
||||
assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,permissions:['room.read']}}),/PLUGIN_API_UNSUPPORTED/);
|
||||
const binary=parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'AAEC/w=='}}});assert.deepEqual([...pluginFileBytes(binary.files['client/asset.bin'])],[0,1,2,255]);
|
||||
assert.throws(()=>parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'!notbase64'}}}));
|
||||
});
|
||||
test('package paths reject traversal, Windows special names, case collisions and file-directory aliases',()=>{
|
||||
for(const name of ['../a','client/../a','client/a\\b','client/CON.txt','client/aux','client/a.','/client/a'])assert.equal(pluginPath(name),false,name);
|
||||
const pack=fixturePackage();
|
||||
for(const files of [{...pack.files,'client/APP.js':{encoding:'utf8',data:'x'}},{...pack.files,'client/folder':{encoding:'utf8',data:'x'},'client/folder/file.js':{encoding:'utf8',data:'x'}}])assert.throws(()=>parsePluginPackage({...pack,files}));
|
||||
assert.throws(()=>parsePluginJson(JSON.parse('{"__proto__":{"value":1}}')));assert.throws(()=>parsePluginJson({n:Infinity}));
|
||||
});
|
||||
test('install and update require explicit trust, encrypt private config and preserve CAS/persistence',async t=>{
|
||||
const {value:r,directory}=await registry(t),pack=fixturePackage();const first=await r.install(pack,null);
|
||||
assert.equal(first.settings.enabled,false);assert.equal(first.settings.trusted,false);
|
||||
await assert.rejects(r.configure(pack.manifest.id,{enabled:true,trusted:false,scope:'instance',targets:[],config:{}},first.revision),/PLUGIN_TRUST_REQUIRED/);
|
||||
const enabled=await r.configure(pack.manifest.id,{enabled:true,trusted:true,scope:'server',targets:['EXAMPLE.com#9987'],config:{public:'value'},serverConfigAction:'replace',serverConfig:{secret:'private-fixture-value'}},first.revision);
|
||||
assert.deepEqual(enabled.settings.targets,['example.com:9987']);assert.equal(enabled.settings.hasServerConfig,true);assert.equal(JSON.stringify(enabled).includes('private-fixture-value'),false);
|
||||
const record=await readFile(path.join(directory,'installed',pack.manifest.id+'.json'),'utf8');assert.equal(record.includes('private-fixture-value'),false);assert.deepEqual(r.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
|
||||
await assert.rejects(r.configure(pack.manifest.id,enabled.settings,first.revision),/PLUGIN_CHANGED/);
|
||||
const reloaded=new PluginRegistry(directory,Buffer.alloc(32,7));await reloaded.initialize();assert.deepEqual(reloaded.list(),r.list());assert.deepEqual(reloaded.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
|
||||
const update=await r.install({...pack,manifest:{...pack.manifest,version:'1.1.0'}},enabled.revision);assert.equal(update.settings.enabled,false);assert.equal(update.settings.trusted,false);assert.equal(update.settings.hasServerConfig,true);
|
||||
const cleared=await r.configure(pack.manifest.id,{...update.settings,serverConfigAction:'remove'},update.revision);assert.equal(cleared.settings.hasServerConfig,false);
|
||||
await r.remove(pack.manifest.id,cleared.revision);assert.equal(r.list().length,0);
|
||||
});
|
||||
test('materialized applications contain their own files and package integrity is checked',async t=>{
|
||||
const {value:r}=await registry(t),pack=fixturePackage();const installed=await r.install(pack,null);const directory=await r.materialize(pack.manifest.id,installed.revision);
|
||||
assert.match(await readFile(path.join(directory,'client/index.html'),'utf8'),/type="module"/);
|
||||
await assert.rejects(r.releaseCode(path.resolve(directory,'../../../../unrelated')),/PLUGIN_INVALID/);
|
||||
await r.releaseCode(directory);await assert.rejects(readFile(path.join(directory,'client/index.html')));
|
||||
});
|
||||
|
||||
test('a backend runs native Node filesystem and arbitrary HTTP handlers in an independent process',async t=>{
|
||||
const {value:r,cleanup}=await registry(t);
|
||||
const source=`import {writeFile,readFile} from 'node:fs/promises';import path from 'node:path';export default async ({dataDir,config})=>{let count=Number(await readFile(path.join(dataDir,'counter.txt'),'utf8').catch(()=>0));return {handle:async(req,res)=>{count++;await writeFile(path.join(dataDir,'counter.txt'),String(count));res.setHeader('content-type','application/json');res.end(JSON.stringify({path:req.url,user:req.webspeak.self.id,configured:config.secret==='private',count,pid:process.pid}));}};};`;
|
||||
const pack=fixturePackage(source),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision),data=await r.dataDirectory(pack.manifest.id);
|
||||
const processes:PluginProcess[]=[];cleanup.push(async()=>{await Promise.all(processes.map(p=>p.close()));});
|
||||
const run=()=>{const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:data,config:{secret:'private'},publicConfig:{},logger:createLogger(),onExit:()=>{}});processes.push(child);return child;};
|
||||
const child=run();await child.ready;assert.ok(child.child.pid&&child.child.pid!==process.pid);
|
||||
const context={apiVersion:2,self:{id:'participant-a'},scope:{key:'instance'}} as PluginAppContext;
|
||||
const request=()=>fetch(`http://127.0.0.1:${child.port}/author-defined/path`,{headers:{'x-webspeak-runtime':child.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});
|
||||
assert.equal((await fetch(`http://127.0.0.1:${child.port}/author-defined/path`)).status,403);
|
||||
const value=await(await request()).json();assert.equal(value.path,'/author-defined/path');assert.equal(value.user,'participant-a');assert.equal(value.configured,true);assert.equal(value.count,1);
|
||||
await child.close();const replacement=run();await replacement.ready;
|
||||
const next=await fetch(`http://127.0.0.1:${replacement.port}/another-route`,{headers:{'x-webspeak-runtime':replacement.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});assert.equal((await next.json()).count,2);
|
||||
});
|
||||
test('a failed or hung plugin activation is bounded and does not execute in the gateway process',async t=>{
|
||||
const {value:r,cleanup}=await registry(t),pack=fixturePackage('export default async()=>new Promise(()=>{});'),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision);
|
||||
const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:await r.dataDirectory(pack.manifest.id),config:{},publicConfig:{},logger:createLogger(),onExit:()=>{},startupMs:1000});
|
||||
cleanup.push(()=>child.close());await assert.rejects(child.ready,/PLUGIN_START_TIMEOUT/);await child.close();assert.notEqual(child.child.exitCode,null);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { PluginError, pluginRecord, type JsonValue } from "../shared/plugins.js";
|
||||
|
||||
export class PluginProcess {
|
||||
readonly token = randomBytes(32).toString("base64url");
|
||||
readonly child: ChildProcess;
|
||||
readonly ready: Promise<number>;
|
||||
readonly exited: Promise<void>;
|
||||
port = 0;
|
||||
private stopping = false;
|
||||
private finished = false;
|
||||
private closePromise?: Promise<void>;
|
||||
constructor(options: {
|
||||
entry: string; codeDirectory: string; dataDirectory: string; config: JsonValue; publicConfig: JsonValue;
|
||||
logger: Logger; onExit(): void; startupMs?: number;
|
||||
}) {
|
||||
const typescript = import.meta.url.endsWith(".ts");
|
||||
const worker = fileURLToPath(new URL(typescript ? "./worker.ts" : "./worker.js", import.meta.url));
|
||||
const execArgv = [...(typescript ? ["--import", import.meta.resolve("tsx")] : []), "--max-old-space-size=256"];
|
||||
// Separate process and reduced environment; reviewed backend code still has the OS user's permissions.
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const key of ["PATH", "Path", "SystemRoot", "WINDIR", "TEMP", "TMP", "LANG", "NODE_EXTRA_CA_CERTS"]) if (process.env[key]) env[key] = process.env[key];
|
||||
this.child = spawn(process.execPath, [...execArgv, worker], { cwd: options.codeDirectory, env, windowsHide: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
|
||||
let resolveExit!: () => void;
|
||||
this.exited = new Promise(resolve => { resolveExit = resolve; });
|
||||
let resolveReady!: (port: number) => void, rejectReady!: (error: Error) => void;
|
||||
this.ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const timer = setTimeout(() => { rejectReady(new PluginError("PLUGIN_START_TIMEOUT")); void this.close(); }, options.startupMs ?? 10000);
|
||||
let logWindow = Date.now(), logs = 0;
|
||||
this.child.on("message", value => {
|
||||
if (!pluginRecord(value) || this.stopping) return;
|
||||
if (value.type === "ready" && Number.isInteger(value.port) && Number(value.port) > 0 && Number(value.port) <= 65535) {
|
||||
clearTimeout(timer); this.port = Number(value.port); resolveReady(this.port);
|
||||
} else if (value.type === "failed") {
|
||||
clearTimeout(timer); rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close();
|
||||
} else if (value.type === "log" && typeof value.message === "string") {
|
||||
if (Date.now() - logWindow > 1000) { logWindow = Date.now(); logs = 0; }
|
||||
if (++logs <= 20) options.logger.debug({ message: value.message.slice(0, 1000) }, "Plugin application log");
|
||||
}
|
||||
});
|
||||
const finish = () => {
|
||||
if (this.finished) return; this.finished = true; clearTimeout(timer);
|
||||
rejectReady(new PluginError(this.stopping ? "PLUGIN_STOPPED" : "PLUGIN_PROCESS_EXITED"));
|
||||
resolveExit(); if (!this.stopping) options.onExit();
|
||||
};
|
||||
this.child.once("error", finish); this.child.once("exit", finish);
|
||||
this.child.send({ type: "initialize", entry: options.entry, dataDir: options.dataDirectory, config: options.config, publicConfig: options.publicConfig, token: this.token }, error => {
|
||||
if (error) { rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close(); }
|
||||
});
|
||||
}
|
||||
event(name: string, payload: unknown): void {
|
||||
if (this.stopping || this.finished || !this.child.connected) return;
|
||||
try { this.child.send({ type: "event", name, payload }, () => undefined); } catch { /* Retired worker. */ }
|
||||
}
|
||||
close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.stopping = true;
|
||||
this.closePromise = (async () => {
|
||||
if (this.finished) return;
|
||||
if (this.child.connected) { try { this.child.send({ type: "stop" }, () => undefined); } catch {} }
|
||||
const killer = setTimeout(() => this.child.kill("SIGKILL"), 2000);
|
||||
try { await this.exited; } finally { clearTimeout(killer); }
|
||||
})();
|
||||
return this.closePromise;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { mkdir, readFile, readdir, writeFile, rename, unlink, mkdtemp, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
|
||||
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
|
||||
import { loadOrCreateMasterSecret } from "../security/master-secret.js";
|
||||
import { parsePluginPackage, parsePluginManifest, parsePluginJson, pluginAssert, pluginId, pluginRecord, pluginFileBytes, PluginError, PLUGIN_LIMIT_BYTES,
|
||||
type InstalledPlugin, type PluginPackage, type PluginSettings, type JsonValue } from "../shared/plugins.js";
|
||||
|
||||
interface StoredPlugin extends InstalledPlugin { schemaVersion: 2; packageDigest: string; serverConfigCiphertext: string }
|
||||
export class PluginRegistry {
|
||||
private readonly records = new Map<string, StoredPlugin>();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private readonly masterKey: Buffer;
|
||||
readonly listeners = new Set<(id: string) => void>();
|
||||
readonly directory: string;
|
||||
constructor(directory: string, masterKey?: Buffer) {
|
||||
this.directory = path.resolve(directory);
|
||||
this.masterKey = masterKey ?? loadOrCreateMasterSecret(path.join(this.directory,"master.key"));
|
||||
}
|
||||
async initialize(): Promise<void> {
|
||||
await mkdir(path.join(this.directory,"installed"),{recursive:true});
|
||||
for (const file of await readdir(path.join(this.directory,"installed"))) {
|
||||
if (!file.endsWith('.json')) continue;
|
||||
try {
|
||||
const bytes=await readFile(path.join(this.directory,"installed",file)); pluginAssert(bytes.length<=256*1024);
|
||||
const v:unknown=JSON.parse(bytes.toString('utf8'));pluginAssert(pluginRecord(v)&&v.schemaVersion===2);
|
||||
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
|
||||
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
|
||||
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
|
||||
this.readSecret(record);
|
||||
if (pluginRecord(v.settings) && v.settings.toolbarPinned === undefined) {
|
||||
const legacyHash=createHash("sha256").update(JSON.stringify({manifest,settings:v.settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt})).digest("hex");
|
||||
pluginAssert(legacyHash===v.revision);
|
||||
record.revision="";
|
||||
this.records.set(manifest.id,record);
|
||||
try { await this.commit(record); }
|
||||
catch { /* keep the migrated record usable in memory if disk replacement fails */ }
|
||||
} else {
|
||||
record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
|
||||
}
|
||||
} catch { /* Invalid or obsolete packages are never executed. */ }
|
||||
}
|
||||
}
|
||||
private public(record: StoredPlugin): InstalledPlugin {
|
||||
return structuredClone({manifest:record.manifest,settings:record.settings,revision:record.revision,installedAt:record.installedAt});
|
||||
}
|
||||
list(): InstalledPlugin[] { return [...this.records.values()].map(record=>this.public(record)); }
|
||||
policy(id: string): InstalledPlugin | undefined { const record=this.records.get(id);return record?this.public(record):undefined; }
|
||||
private hash(record: Omit<StoredPlugin,'revision'> | StoredPlugin): string {
|
||||
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
|
||||
}
|
||||
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
|
||||
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&(value.toolbarPinned===undefined||typeof value.toolbarPinned==='boolean')&&manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
|
||||
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
|
||||
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
|
||||
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
|
||||
return {enabled:value.enabled,trusted:value.trusted,toolbarPinned:value.toolbarPinned===true,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
|
||||
}
|
||||
private readSecret(record: StoredPlugin): JsonValue {
|
||||
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
|
||||
return text?parsePluginJson(JSON.parse(text)):null;
|
||||
}
|
||||
serverConfig(id: string): JsonValue { const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');return this.readSecret(record); }
|
||||
private mutate<T>(run:()=>Promise<T>):Promise<T>{const next=this.queue.then(run,run);this.queue=next.catch(()=>undefined);return next;}
|
||||
private async commit(record:StoredPlugin):Promise<InstalledPlugin>{
|
||||
record.revision=this.hash(record);const directory=path.join(this.directory,'installed'),temporary=path.join(directory,`.${randomUUID()}.tmp`);
|
||||
try{await writeFile(temporary,JSON.stringify(record),{flag:'wx',mode:0o600});await rename(temporary,path.join(directory,`${record.manifest.id}.json`));}finally{await unlink(temporary).catch(()=>undefined);}
|
||||
this.records.set(record.manifest.id,record);for(const listener of this.listeners){try{listener(record.manifest.id);}catch{}}
|
||||
return this.public(record);
|
||||
}
|
||||
install(input:PluginPackage,expectedRevision:string|null):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
const pack=parsePluginPackage(input),previous=this.records.get(pack.manifest.id);pluginAssert((previous?.revision??null)===expectedRevision,'PLUGIN_CHANGED');pluginAssert(previous||this.records.size<50,'PLUGIN_LIMIT');
|
||||
const bytes=JSON.stringify(pack),digest=createHash('sha256').update(bytes).digest('hex'),directory=path.join(this.directory,'packages',pack.manifest.id);
|
||||
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
|
||||
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
|
||||
const old=previous?.settings;
|
||||
const settings={enabled:false,trusted:false,toolbarPinned:old?.toolbarPinned??false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
|
||||
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
|
||||
});}
|
||||
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');pluginAssert(pluginRecord(input));
|
||||
let secret=record.serverConfigCiphertext;const action=input.serverConfigAction??'keep';pluginAssert(['keep','replace','remove'].includes(String(action)));
|
||||
if(action==='remove')secret='';else if(action==='replace')secret=encryptSecret(JSON.stringify(parsePluginJson(input.serverConfig)),this.masterKey,`webspeak:plugin-config:v2:${id}`);
|
||||
const settings=this.settings(input,record.manifest,!!secret);return this.commit({...record,settings,serverConfigCiphertext:secret});
|
||||
});}
|
||||
async getPackage(id:string):Promise<PluginPackage>{
|
||||
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');
|
||||
const bytes=await readFile(path.join(this.directory,'packages',id,`${record.packageDigest}.wplugin`));pluginAssert(bytes.length<=PLUGIN_LIMIT_BYTES,'PLUGIN_TOO_LARGE');
|
||||
pluginAssert(createHash('sha256').update(bytes).digest('hex')===record.packageDigest,'PLUGIN_CHECKSUM');
|
||||
const pack=parsePluginPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes)));pluginAssert(JSON.stringify(pack.manifest)===JSON.stringify(record.manifest),'PLUGIN_PACKAGE_MISMATCH');return pack;
|
||||
}
|
||||
async materialize(id:string,revision:string):Promise<string>{
|
||||
const record=this.records.get(id);pluginAssert(record?.revision===revision,'PLUGIN_CHANGED');const pack=await this.getPackage(id);pluginAssert(this.records.get(id)?.revision===revision,'PLUGIN_CHANGED');
|
||||
const parent=path.join(this.directory,'code',id);await mkdir(parent,{recursive:true});const root=await mkdtemp(path.join(parent,'run-'));
|
||||
try{for(const [name,file]of Object.entries(pack.files)){const target=path.resolve(root,name);pluginAssert(target.startsWith(root+path.sep));await mkdir(path.dirname(target),{recursive:true});await writeFile(target,pluginFileBytes(file),{flag:'wx',mode:0o600});}return root;}
|
||||
catch(error){await this.releaseCode(root);throw error;}
|
||||
}
|
||||
async releaseCode(directory:string):Promise<void>{
|
||||
const root=path.resolve(this.directory,'code');pluginAssert(path.resolve(directory).startsWith(root+path.sep));await rm(directory,{recursive:true,force:true});
|
||||
}
|
||||
async dataDirectory(id:string):Promise<string>{pluginAssert(pluginId(id));const directory=path.join(this.directory,'data',id);await mkdir(directory,{recursive:true});return directory;}
|
||||
remove(id:string,revision:string):Promise<void>{return this.mutate(async()=>{
|
||||
pluginAssert(pluginId(id));const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');
|
||||
await unlink(path.join(this.directory,'installed',`${id}.json`));this.records.delete(id);for(const listener of this.listeners){try{listener(id);}catch{}}
|
||||
});}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Router } from "express";
|
||||
import { PluginRuntime } from "./runtime.js";
|
||||
import { pluginAssert, PluginError, pluginRecord } from "../shared/plugins.js";
|
||||
|
||||
/** Control plane only. Application HTTP/WebSocket traffic lives on the independent origin. */
|
||||
export function createPluginRuntimeRouter(runtime?: PluginRuntime) {
|
||||
const router=Router();
|
||||
router.use((_request,response,next)=>{
|
||||
response.setHeader("access-control-allow-origin","*");
|
||||
response.setHeader("access-control-allow-headers","authorization, content-type");
|
||||
response.setHeader("access-control-allow-methods","GET, POST, PATCH, DELETE, OPTIONS");
|
||||
response.setHeader("cache-control","no-store");next();
|
||||
});
|
||||
router.options(/.*/,(_request,response)=>{response.sendStatus(204);});
|
||||
const token=(authorization:string|undefined)=>{pluginAssert(typeof authorization==="string"&&authorization.startsWith("Bearer "),"PLUGIN_NOT_CONNECTED");return authorization.slice(7);};
|
||||
const service=()=>{pluginAssert(runtime,"PLUGIN_RUNTIME_UNAVAILABLE");return runtime;};
|
||||
router.get("/",(request,response)=>{response.json({plugins:service().directory(token(request.header("authorization")))});});
|
||||
router.post("/:id/open",async(request,response)=>{
|
||||
const origin=request.header("origin")??`${request.protocol}://${request.header("host")}`;
|
||||
response.status(201).json(await service().open(token(request.header("authorization")),String(request.params.id),request.body,origin));
|
||||
});
|
||||
router.delete("/opening/:id",(request,response)=>{service().cancelOpen(token(request.header("authorization")),String(request.params.id));response.json({ok:true});});
|
||||
router.patch("/apps/:id",(request,response)=>{
|
||||
pluginAssert(pluginRecord(request.body));service().appearance(String(request.params.id),token(request.header("authorization")),request.body);response.json({ok:true});
|
||||
});
|
||||
router.delete("/apps/:id",(request,response)=>{
|
||||
const instance=service(),id=String(request.params.id);pluginAssert(instance.authorizeApp(id,token(request.header("authorization"))),"PLUGIN_NOT_OPEN");instance.closeApp(id);response.json({ok:true});
|
||||
});
|
||||
router.use((error:unknown,_request:unknown,response:import("express").Response,_next:unknown)=>{
|
||||
const code=error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED";
|
||||
response.status(code==="PLUGIN_NOT_CONNECTED"?401:code==="PLUGIN_NOT_FOUND"?404:code==="PLUGIN_RUNTIME_UNAVAILABLE"?503:403).json({ok:false,code});
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse, type Server } from "node:http";
|
||||
import { createServer as createHttpsServer, type ServerOptions } from "node:https";
|
||||
import { readFile, writeFile, rename } from "node:fs/promises";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Socket } from "node:net";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PluginProcess } from "./process.js";
|
||||
import { PluginError, pluginAssert, pluginPath, pluginRecord, type InstalledPlugin, type PluginAppContext, type PluginAppLaunch, type PluginParticipant, type PluginRequestContext, type PluginRuntimeStatus } from "../shared/plugins.js";
|
||||
|
||||
interface ApplicationEntry { policy: InstalledPlugin; directory: string; assets: Set<string>; process?: PluginProcess; status: PluginRuntimeStatus; stale: boolean }
|
||||
interface AppSession {
|
||||
id: string; publicId: string; participantId: string; openKey: string; pluginId: string; revision: string; voiceToken: string; scopeKey: string;
|
||||
theme: "light" | "dark"; language: PluginAppContext["language"]; origin: string; lastActivity: number; lastContext: string;
|
||||
streams: Set<ServerResponse>; connections: Set<() => void>;
|
||||
}
|
||||
interface RuntimeOptions {
|
||||
registry: PluginRegistry; participant(token: string): PluginParticipant | null; logger: Logger;
|
||||
port?: number; host?: string; publicOrigin?: string; tls?: ServerOptions; maxWorkers?: number;
|
||||
}
|
||||
const contentTypes: Record<string, string> = { ".html":"text/html; charset=utf-8", ".js":"text/javascript; charset=utf-8", ".mjs":"text/javascript; charset=utf-8", ".css":"text/css; charset=utf-8", ".json":"application/json; charset=utf-8", ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".jpeg":"image/jpeg", ".webp":"image/webp", ".gif":"image/gif", ".ico":"image/x-icon", ".woff":"font/woff", ".woff2":"font/woff2", ".wasm":"application/wasm", ".mp4":"video/mp4", ".webm":"video/webm" };
|
||||
|
||||
/** App traffic uses its own HTTP origin and child processes, never the voice WebSocket. */
|
||||
export class PluginRuntime {
|
||||
private readonly entries = new Map<string, ApplicationEntry>();
|
||||
private readonly queues = new Map<string, Promise<unknown>>();
|
||||
private readonly sessions = new Map<string, AppSession>();
|
||||
private readonly openings = new Map<string, {cancelled:boolean; expires:number; appId?:string}>();
|
||||
private readonly server: Server | ReturnType<typeof createHttpsServer>;
|
||||
private readonly sockets = new Set<Socket>();
|
||||
private timer?: ReturnType<typeof setInterval>;
|
||||
private origin = "";
|
||||
private listening = false;
|
||||
private closed = false;
|
||||
private configQueue: Promise<unknown> = Promise.resolve();
|
||||
private readonly changed = (id: string) => {
|
||||
this.revokePlugin(id, "PLUGIN_CHANGED");
|
||||
const entry = this.entries.get(id); if (entry) { entry.stale = true; void entry.process?.close(); }
|
||||
void this.synchronize(id).catch(() => undefined);
|
||||
};
|
||||
constructor(private readonly options: RuntimeOptions) {
|
||||
this.server = options.tls ? createHttpsServer(options.tls, (req,res) => void this.handle(req,res)) : createServer((req,res) => void this.handle(req,res));
|
||||
this.server.on("connection", socket => { this.sockets.add(socket); socket.once("close", () => this.sockets.delete(socket)); });
|
||||
this.server.on("upgrade", (req,socket,head) => void this.upgrade(req,socket as Socket,head));
|
||||
options.registry.listeners.add(this.changed);
|
||||
}
|
||||
get port(): number { const address=this.server.address(); return address&&typeof address!=="string"?address.port:0; }
|
||||
settings() { return { publicOrigin:this.origin, port:this.port, available:this.listening, revision:createHash("sha256").update(this.origin).digest("hex") }; }
|
||||
async configureOrigin(input: unknown, revision: unknown): Promise<ReturnType<PluginRuntime["settings"]>> {
|
||||
const next=this.configQueue.then(async()=>{
|
||||
pluginAssert(typeof input==="string"&&input.length<=300&&typeof revision==="string");
|
||||
pluginAssert(revision===this.settings().revision,"PLUGIN_CHANGED");
|
||||
const origin=normalizeOrigin(input);
|
||||
const directory=this.options.registry.directory, temporary=path.join(directory,`.runtime-${randomUUID()}.tmp`);
|
||||
await writeFile(temporary,JSON.stringify({publicOrigin:origin}),{flag:"wx",mode:0o600}); await rename(temporary,path.join(directory,"runtime.json"));
|
||||
this.origin=origin;for(const app of [...this.sessions.values()])this.closeApp(app.id,"PLUGIN_CHANGED");return this.settings();
|
||||
});this.configQueue=next.catch(()=>undefined);return next;
|
||||
}
|
||||
async start(): Promise<void> {
|
||||
try { const value=JSON.parse(await readFile(path.join(this.options.registry.directory,"runtime.json"),"utf8"));this.origin=normalizeOrigin(value.publicOrigin); }
|
||||
catch { this.origin=normalizeOrigin(this.options.publicOrigin??""); }
|
||||
await new Promise<void>((resolve,reject)=>{
|
||||
const failed=(error:Error)=>{this.server.off("listening",ready);reject(error);};
|
||||
const ready=()=>{this.server.off("error",failed);this.listening=true;resolve();};
|
||||
this.server.once("error",failed);this.server.once("listening",ready);this.server.listen(this.options.port??3042,this.options.host??"0.0.0.0");
|
||||
});
|
||||
this.timer=setInterval(()=>this.reconcileSessions(),1000);
|
||||
// Applications may provide background integrations even without an open browser panel.
|
||||
await Promise.allSettled(this.options.registry.list().filter(p=>p.settings.enabled).map(p=>this.synchronize(p.manifest.id)));
|
||||
}
|
||||
status(id: string): PluginRuntimeStatus {
|
||||
const policy=this.options.registry.policy(id);if(!policy?.settings.enabled)return {state:"disabled"};
|
||||
return this.entries.get(id)?.status??{state:policy.manifest.server?"stopped":"client"};
|
||||
}
|
||||
private async stopEntry(entry: ApplicationEntry): Promise<void> {
|
||||
await entry.process?.close();if(entry.directory){await this.options.registry.releaseCode(entry.directory);entry.directory="";}
|
||||
}
|
||||
synchronize(id: string): Promise<void> {
|
||||
const next=(this.queues.get(id)??Promise.resolve()).then(async()=>{
|
||||
const policy=this.options.registry.policy(id),previous=this.entries.get(id);
|
||||
if(previous&&!previous.stale&&previous.policy.revision===policy?.revision)return;
|
||||
if(previous){await this.stopEntry(previous);this.entries.delete(id);}
|
||||
if(this.closed||!policy?.settings.enabled||!policy.settings.trusted)return;
|
||||
const entry:ApplicationEntry={policy,directory:"",assets:new Set(),status:{state:"starting"},stale:false};this.entries.set(id,entry);
|
||||
try {
|
||||
if(policy.manifest.server)pluginAssert([...this.entries.values()].filter(p=>p.policy.manifest.server&&["starting","running"].includes(p.status.state)).length<=(this.options.maxWorkers??8),"PLUGIN_WORKER_LIMIT");
|
||||
entry.assets=new Set(Object.keys((await this.options.registry.getPackage(id)).files).filter(name=>name.startsWith("client/")));
|
||||
entry.directory=await this.options.registry.materialize(id,policy.revision);
|
||||
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
|
||||
if(policy.manifest.server){
|
||||
entry.process=new PluginProcess({entry:path.join(entry.directory,policy.manifest.server.entry),codeDirectory:entry.directory,dataDirectory:await this.options.registry.dataDirectory(id),config:this.options.registry.serverConfig(id),publicConfig:policy.settings.config,logger:this.options.logger.child({pluginId:id}),onExit:()=>{
|
||||
if(this.entries.get(id)===entry&&!entry.stale&&!this.closed){entry.status={state:"failed",error:"PLUGIN_PROCESS_EXITED"};this.revokePlugin(id,"PLUGIN_PROCESS_EXITED");}
|
||||
}});await entry.process.ready;
|
||||
}
|
||||
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
|
||||
entry.status={state:policy.manifest.server?"running":"client"};
|
||||
} catch(error) {
|
||||
entry.status={state:"failed",error:error instanceof PluginError?error.code:"PLUGIN_START_FAILED"};
|
||||
await this.stopEntry(entry);this.options.logger.warn({pluginId:id,code:entry.status.error},"Plugin application failed to start");
|
||||
}
|
||||
});this.queues.set(id,next.catch(()=>undefined));return next;
|
||||
}
|
||||
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
|
||||
directory(voiceToken:string) {
|
||||
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
|
||||
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,toolbarPinned:policy.settings.toolbarPinned,runtime:this.status(policy.manifest.id)}));
|
||||
}
|
||||
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
|
||||
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
|
||||
if(policy.settings.scope==="instance")return "instance";
|
||||
pluginAssert(policy.settings.targets.includes(participant.target),"PLUGIN_NOT_ALLOWED");return `${participant.target}#${participant.channelId}`;
|
||||
}
|
||||
private appOrigin(mainOrigin:string):string{
|
||||
pluginAssert(this.listening,"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
if(this.origin){pluginAssert(this.origin!==new URL(mainOrigin).origin,"PLUGIN_SEPARATE_ORIGIN_REQUIRED");return this.origin;}
|
||||
const source=new URL(mainOrigin);pluginAssert(["127.0.0.1","localhost","[::1]"].includes(source.hostname),"PLUGIN_PUBLIC_ORIGIN_REQUIRED");
|
||||
source.hostname=source.hostname==="localhost"?"127.0.0.1":"localhost";source.port=String(this.port);source.protocol=this.options.tls?"https:":"http:";return source.origin;
|
||||
}
|
||||
async open(voiceToken:string,id:string,input:unknown,mainOrigin:string):Promise<PluginAppLaunch>{
|
||||
const participant=this.options.participant(voiceToken),policy=this.options.registry.policy(id);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");pluginAssert(policy,"PLUGIN_NOT_FOUND");
|
||||
const preferences=pluginRecord(input)?input:{},openId=preferences.openId??randomUUID();
|
||||
pluginAssert(typeof openId==="string"&&/^[a-zA-Z0-9-]{8,80}$/.test(openId));const openKey=voiceToken+":"+openId,previous=this.openings.get(openKey);
|
||||
if(previous?.appId){const app=this.sessions.get(previous.appId);if(app&&this.validate(app)){pluginAssert(app.pluginId===id,"PLUGIN_OPEN_CONFLICT");return {id:app.id,url:`${app.origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};}}
|
||||
pluginAssert(!previous,previous?.cancelled?"PLUGIN_CANCELLED":"PLUGIN_OPEN_PENDING");
|
||||
pluginAssert([...this.openings.keys()].filter(key=>key.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
|
||||
const operation={cancelled:false,expires:Date.now()+90000,appId:undefined as string|undefined};this.openings.set(openKey,operation);
|
||||
const scopeKey=this.scopeKey(policy,participant),origin=this.appOrigin(mainOrigin);
|
||||
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
|
||||
await this.synchronize(id);const entry=this.entries.get(id);pluginAssert(entry&&["running","client"].includes(entry.status.state),entry?.status.error??"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
pluginAssert(!operation.cancelled,"PLUGIN_CANCELLED");
|
||||
const current=this.options.participant(voiceToken);pluginAssert(current&&this.options.registry.policy(id)?.revision===policy.revision&&this.scopeKey(policy,current)===scopeKey,"PLUGIN_CONTEXT_CHANGED");
|
||||
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
|
||||
const app:AppSession={id:randomBytes(32).toString("base64url"),publicId:randomUUID(),participantId:current.id,openKey,pluginId:id,revision:policy.revision,voiceToken,scopeKey,origin,theme:preferences.theme==="dark"?"dark":"light",language:["zh","en","de","ru","ja"].includes(String(preferences.language))?preferences.language as PluginAppContext["language"]:"en",lastActivity:Date.now(),lastContext:"",streams:new Set(),connections:new Set()};
|
||||
operation.appId=app.id;
|
||||
this.sessions.set(app.id,app);entry.process?.event("participantJoined",this.requestContext(app,current));
|
||||
return {id:app.id,url:`${origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};
|
||||
}
|
||||
authorizeApp(id:string,voiceToken:string):boolean{return this.sessions.get(id)?.voiceToken===voiceToken;}
|
||||
cancelOpen(voiceToken:string,openId:string):void{
|
||||
pluginAssert(/^[a-zA-Z0-9-]{8,80}$/.test(openId));const key=voiceToken+":"+openId,operation=this.openings.get(key);
|
||||
if(operation){operation.cancelled=true;if(operation.appId)this.closeApp(operation.appId);return;}
|
||||
pluginAssert(this.options.participant(voiceToken),"PLUGIN_NOT_CONNECTED");
|
||||
pluginAssert([...this.openings.keys()].filter(item=>item.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
|
||||
this.openings.set(key,{cancelled:true,expires:Date.now()+90000});
|
||||
}
|
||||
appearance(id:string,voiceToken:string,input:unknown):void{
|
||||
pluginAssert(this.authorizeApp(id,voiceToken)&&pluginRecord(input),"PLUGIN_NOT_OPEN");const app=this.sessions.get(id)!;
|
||||
if(input.theme==="light"||input.theme==="dark")app.theme=input.theme;
|
||||
if(["zh","en","de","ru","ja"].includes(String(input.language)))app.language=input.language as PluginAppContext["language"];
|
||||
this.publishContext(app);
|
||||
}
|
||||
closeApp(id:string,code="PLUGIN_CLOSED"):void{
|
||||
const app=this.sessions.get(id);if(!app)return;this.sessions.delete(id);
|
||||
const opening=this.openings.get(app.openKey);if(opening){opening.cancelled=true;opening.appId=undefined;opening.expires=Date.now()+90000;}
|
||||
for(const response of app.streams){if(!response.destroyed)response.end(`event: closed\ndata: ${JSON.stringify({code})}\n\n`);}
|
||||
for(const close of app.connections){try{close();}catch{}}
|
||||
this.entries.get(app.pluginId)?.process?.event("participantLeft",{appId:app.publicId,selfId:app.participantId,scopeKey:app.scopeKey});
|
||||
}
|
||||
private revokePlugin(id:string,code:string):void{for(const app of [...this.sessions.values()])if(app.pluginId===id)this.closeApp(app.id,code);}
|
||||
private context(app:AppSession,participant:PluginParticipant):PluginAppContext{
|
||||
const policy=this.options.registry.policy(app.pluginId)!;
|
||||
const base=`${app.origin}/apps/${app.id}`;
|
||||
return {...this.requestContext(app,participant),plugin:policy.manifest,connection:{target:participant.target,channelId:participant.channelId,members:participant.members},config:policy.settings.config,theme:app.theme,language:app.language,
|
||||
serverUrl:policy.manifest.server?`${base}/server`:null,socketUrl:policy.manifest.server?`${base.replace(/^http/,"ws")}/server`:null,contextUrl:`${base}/_runtime/context`};
|
||||
}
|
||||
private requestContext(app:AppSession,participant:PluginParticipant):PluginRequestContext{
|
||||
return {apiVersion:2,appId:app.publicId,self:{id:participant.id,nickname:participant.nickname,...(participant.uid?{uid:participant.uid}:{})},connection:{target:participant.target,channelId:participant.channelId},scope:{type:this.options.registry.policy(app.pluginId)!.settings.scope,key:app.scopeKey}};
|
||||
}
|
||||
private validate(app:AppSession):PluginParticipant|null{
|
||||
const policy=this.options.registry.policy(app.pluginId),participant=this.options.participant(app.voiceToken);
|
||||
try{return policy&&policy.revision===app.revision&&participant&&this.scopeKey(policy,participant)===app.scopeKey?participant:null;}catch{return null;}
|
||||
}
|
||||
private publishContext(app:AppSession):void{
|
||||
const participant=this.validate(app);if(!participant){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");return;}
|
||||
const context=this.context(app,participant),json=JSON.stringify(context);
|
||||
if(json!==app.lastContext){app.lastContext=json;for(const response of app.streams)if(!response.destroyed)response.write(`event: context\ndata: ${json}\n\n`);this.entries.get(app.pluginId)?.process?.event("contextChanged",{...this.requestContext(app,participant),connection:context.connection});}
|
||||
}
|
||||
private reconcileSessions():void{
|
||||
for(const [key,operation]of this.openings)if(!operation.appId&&operation.expires<Date.now())this.openings.delete(key);
|
||||
for(const app of [...this.sessions.values()]){
|
||||
if(!this.validate(app)||(!app.streams.size&&Date.now()-app.lastActivity>90000)){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");continue;}
|
||||
this.publishContext(app);for(const response of app.streams){if(response.destroyed)app.streams.delete(response);else if(response.writableLength>256*1024){response.destroy();app.streams.delete(response);}else response.write(": keepalive\n\n");}
|
||||
}
|
||||
}
|
||||
private locate(request:IncomingMessage):{app:AppSession;route:string;query:string;participant:PluginParticipant}{
|
||||
const url=new URL(request.url??"/","http://runtime.invalid"),match=/^\/apps\/([A-Za-z0-9_-]{43})\/(.*)$/.exec(url.pathname);
|
||||
pluginAssert(match,"PLUGIN_NOT_OPEN");const app=this.sessions.get(match[1]);pluginAssert(app,"PLUGIN_NOT_OPEN");
|
||||
const participant=this.validate(app);pluginAssert(participant,"PLUGIN_CONTEXT_CHANGED");app.lastActivity=Date.now();
|
||||
return {app,route:decodeURIComponent(match[2]),query:url.search,participant};
|
||||
}
|
||||
private async handle(request:IncomingMessage,response:ServerResponse):Promise<void>{
|
||||
response.setHeader("referrer-policy","no-referrer");response.setHeader("x-content-type-options","nosniff");response.setHeader("cache-control","no-store");
|
||||
try{
|
||||
const {app,route,query,participant}=this.locate(request),entry=this.entries.get(app.pluginId);pluginAssert(entry?.directory,"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
if(route.startsWith("server/")||route==="server"){this.proxy(request,response,app,participant,"/"+route.slice(7)+query);return;}
|
||||
pluginAssert(request.method==="GET"||request.method==="HEAD","PLUGIN_METHOD_NOT_ALLOWED");
|
||||
if(route==="_runtime/context"){response.setHeader("content-type","application/json");response.end(JSON.stringify(this.context(app,participant)));return;}
|
||||
if(route==="_runtime/events"){
|
||||
pluginAssert(app.streams.size<4,"PLUGIN_LIMIT");response.writeHead(200,{"content-type":"text/event-stream","x-accel-buffering":"no"});response.flushHeaders();app.streams.add(response);
|
||||
response.write(`event: context\ndata: ${JSON.stringify(this.context(app,participant))}\n\n`);response.once("close",()=>app.streams.delete(response));return;
|
||||
}
|
||||
if(route==="_runtime/sdk.js"){response.setHeader("content-type","text/javascript; charset=utf-8");response.end(applicationSdk(this.context(app,participant),`${app.origin}/apps/${app.id}/_runtime/events`,app.id));return;}
|
||||
pluginAssert(route.startsWith("client/")&&pluginPath(route),"PLUGIN_ASSET_NOT_FOUND");
|
||||
pluginAssert(this.validate(app)&&entry.assets.has(route),"PLUGIN_ASSET_NOT_FOUND");
|
||||
const file=path.resolve(entry.directory,route);pluginAssert(file.startsWith(entry.directory+path.sep),"PLUGIN_ASSET_NOT_FOUND");
|
||||
response.setHeader("content-type",contentTypes[path.extname(route)]??"application/octet-stream");
|
||||
if(route===entry.policy.manifest.client.entry){
|
||||
let html=await readFile(file,"utf8");pluginAssert(this.validate(app),"PLUGIN_CONTEXT_CHANGED");
|
||||
const script=`<script src="/apps/${app.id}/_runtime/sdk.js"></script>`;
|
||||
if(/<head(?:\s[^>]*)?>/i.test(html))html=html.replace(/<head(?:\s[^>]*)?>/i,head=>head+script);
|
||||
else if(/<!doctype[^>]*>/i.test(html))html=html.replace(/<!doctype[^>]*>/i,doctype=>doctype+script);
|
||||
else html=script+html;
|
||||
response.end(request.method==="HEAD"?undefined:html);return;
|
||||
}
|
||||
if(request.method==="HEAD"){response.end();return;}
|
||||
const stream=createReadStream(file);stream.once("error",()=>{if(!response.headersSent)response.writeHead(404);response.end();});response.once("close",()=>stream.destroy());stream.pipe(response);
|
||||
}catch(error){if(!response.headersSent)response.writeHead(error instanceof PluginError&&error.code==="PLUGIN_ASSET_NOT_FOUND"?404:403,{"content-type":"application/json"});response.end(JSON.stringify({error:error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED"}));}
|
||||
}
|
||||
private headers(request:IncomingMessage,app:AppSession,participant:PluginParticipant):Record<string,string|string[]>{
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");
|
||||
const headers:Record<string,string|string[]>={};
|
||||
for(const [key,value]of Object.entries(request.headers))if(value!==undefined&&!['cookie','authorization','host','connection','proxy-authorization'].includes(key)&&!key.startsWith('x-webspeak-'))headers[key]=value;
|
||||
const context=this.requestContext(app,participant);
|
||||
headers['x-webspeak-runtime']=worker.token;headers['x-webspeak-context']=Buffer.from(JSON.stringify(context),'utf8').toString('base64url');return headers;
|
||||
}
|
||||
private proxy(request:IncomingMessage,response:ServerResponse,app:AppSession,participant:PluginParticipant,route:string):void{
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");pluginAssert(app.connections.size<32,"PLUGIN_BUSY");
|
||||
const upstream=httpRequest({hostname:"127.0.0.1",port:worker.port,path:route,method:request.method,headers:this.headers(request,app,participant)},incoming=>{
|
||||
if(response.destroyed||!this.sessions.has(app.id)){incoming.destroy();return;}
|
||||
const headers={...incoming.headers};delete headers['set-cookie'];response.writeHead(incoming.statusCode??502,headers);incoming.once('error',()=>response.destroy());incoming.pipe(response);
|
||||
});
|
||||
const close=()=>{upstream.destroy();if(!response.writableFinished)response.destroy();};app.connections.add(close);
|
||||
upstream.setTimeout(120000,()=>upstream.destroy());upstream.once('error',()=>{if(!response.headersSent)response.writeHead(502,{'content-type':'application/json'});response.end('{"error":"PLUGIN_BACKEND_UNAVAILABLE"}');});
|
||||
response.once('close',()=>{app.connections.delete(close);upstream.destroy();});request.once('aborted',close);request.pipe(upstream);
|
||||
}
|
||||
private async upgrade(request:IncomingMessage,socket:Socket,head:Buffer):Promise<void>{
|
||||
try{
|
||||
const {app,route,query,participant}=this.locate(request);pluginAssert(route==='server'||route.startsWith('server/'),"PLUGIN_NOT_ALLOWED");
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port&&app.connections.size<32,"PLUGIN_BACKEND_UNAVAILABLE");
|
||||
const headers=this.headers(request,app,participant);headers.connection='Upgrade';headers.upgrade=String(request.headers.upgrade??'websocket');
|
||||
const upstream=httpRequest({hostname:'127.0.0.1',port:worker.port,path:'/'+route.slice(7)+query,headers});
|
||||
const close=()=>{upstream.destroy();socket.destroy();};app.connections.add(close);socket.once('close',()=>{app.connections.delete(close);upstream.destroy();});
|
||||
upstream.once('upgrade',(response,peer,upstreamHead)=>{
|
||||
socket.write(`HTTP/1.1 ${response.statusCode??101} Switching Protocols\r\n`);for(const [key,value]of Object.entries(response.headers))if(value!==undefined&&key!=='set-cookie')socket.write(`${key}: ${Array.isArray(value)?value.join(', '):value}\r\n`);socket.write('\r\n');
|
||||
if(head.length)peer.write(head);if(upstreamHead.length)socket.write(upstreamHead);peer.pipe(socket);socket.pipe(peer);peer.once('error',()=>socket.destroy());socket.once('error',()=>peer.destroy());
|
||||
app.connections.delete(close);const closePeer=()=>{peer.destroy();socket.destroy();};app.connections.add(closePeer);socket.once('close',()=>{app.connections.delete(closePeer);peer.destroy();});peer.once('close',()=>socket.destroy());
|
||||
});
|
||||
upstream.once('error',close);upstream.once('response',()=>close());upstream.end();
|
||||
}catch{socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');}
|
||||
}
|
||||
async close():Promise<void>{
|
||||
if(this.closed)return;this.closed=true;this.listening=false;clearInterval(this.timer);this.options.registry.listeners.delete(this.changed);
|
||||
for(const app of [...this.sessions.values()])this.closeApp(app.id);
|
||||
this.openings.clear();
|
||||
await Promise.allSettled([...this.entries.values()].map(entry=>entry.process?.close()));
|
||||
await Promise.allSettled(this.queues.values());await Promise.allSettled([...this.entries.values()].map(entry=>this.stopEntry(entry)));this.entries.clear();
|
||||
for(const socket of this.sockets)socket.destroy();await new Promise<void>(resolve=>this.server.close(()=>resolve()));
|
||||
}
|
||||
}
|
||||
function normalizeOrigin(value:unknown):string{
|
||||
pluginAssert(typeof value==='string'&&value.length<=300);if(!value.trim())return '';
|
||||
const url=new URL(value.trim());pluginAssert(['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash&&url.pathname==='/');
|
||||
pluginAssert(url.protocol==='https:'||['localhost','127.0.0.1','[::1]'].includes(url.hostname),'PLUGIN_HTTPS_REQUIRED');return url.origin;
|
||||
}
|
||||
function applicationSdk(context:PluginAppContext,eventsUrl:string,id:string):string{
|
||||
// No expression evaluator, business RPC, shared rooms, dependency loader, or network allowlist.
|
||||
return `(()=>{let context=${JSON.stringify(context).replace(/</g,'\\u003c')};const listeners=new Set(),closed=new AbortController();document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;
|
||||
const events=new EventSource(${JSON.stringify(eventsUrl)});events.addEventListener('context',event=>{try{context=JSON.parse(event.data);document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;for(const fn of listeners){try{fn(context)}catch{}}}catch{}});
|
||||
events.addEventListener('closed',()=>{closed.abort();events.close();parent.postMessage({type:'webspeak-app-closed',id:${JSON.stringify(id)}},'*')});
|
||||
window.webspeak=Object.freeze({apiVersion:2,ready:Promise.resolve(context),getContext:()=>context,onContextChange(fn){listeners.add(fn);return()=>listeners.delete(fn)},signal:closed.signal});
|
||||
addEventListener('pagehide',()=>{closed.abort();events.close();listeners.clear()},{once:true});})();`;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PLUGIN_STORE_INDEX, PLUGIN_STORE_REPOSITORY, PLUGIN_LIMIT_BYTES, pluginAssert, pluginId, pluginRecord,
|
||||
parsePluginManifest, parsePluginPackage, PluginError, type PluginCatalog, type PluginStoreEntry } from "../shared/plugins.js";
|
||||
|
||||
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
||||
const SHA = /^[a-f0-9]{64}$/;
|
||||
export class PluginStore {
|
||||
constructor(private readonly fetcher: typeof fetch = fetch) {}
|
||||
private async read(url: string, limit: number): Promise<Buffer> {
|
||||
pluginAssert(new URL(url).origin === "https://raw.githubusercontent.com");
|
||||
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000);
|
||||
try {
|
||||
const response = await this.fetcher(url, { signal: controller.signal, redirect: "error", credentials: "omit" });
|
||||
pluginAssert(response.ok && response.body, "PLUGIN_STORE_UNAVAILABLE");
|
||||
const reader = response.body.getReader(), chunks: Uint8Array[] = []; let size = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const part = await reader.read(); if (part.done) break;
|
||||
size += part.value.byteLength;
|
||||
if (size > limit) { await reader.cancel(); throw new PluginError("PLUGIN_TOO_LARGE"); }
|
||||
chunks.push(part.value);
|
||||
}
|
||||
} finally { reader.releaseLock(); }
|
||||
return Buffer.concat(chunks, size);
|
||||
} catch (error) { if (error instanceof PluginError) throw error; throw new PluginError("PLUGIN_STORE_UNAVAILABLE"); }
|
||||
finally { clearTimeout(timer); }
|
||||
}
|
||||
private async json(url: string): Promise<unknown> {
|
||||
try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await this.read(url, 128 * 1024))); }
|
||||
catch (e) { if (e instanceof PluginError) throw e; throw new PluginError("PLUGIN_INVALID"); }
|
||||
}
|
||||
private async sources() {
|
||||
const root = await this.json(PLUGIN_STORE_INDEX);
|
||||
pluginAssert(pluginRecord(root) && root.schemaVersion === 2 && Array.isArray(root.plugins) && root.plugins.length <= 50,"PLUGIN_CATALOG_UNSUPPORTED");
|
||||
const seen = new Set<string>();
|
||||
return root.plugins.map(item => {
|
||||
pluginAssert(pluginRecord(item) && pluginId(item.id) && !seen.has(item.id)); seen.add(item.id);
|
||||
pluginAssert(typeof item.repository === "string" && /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,99}$/.test(item.repository) && !item.repository.endsWith(".git"));
|
||||
const metadataPath = item.metadataPath ?? "plugin.json";
|
||||
pluginAssert(typeof metadataPath === "string" && /^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.json$/.test(metadataPath) && metadataPath.length <= 160);
|
||||
return { id: item.id, repository: item.repository, metadataPath };
|
||||
});
|
||||
}
|
||||
private async metadata(source: { id: string; repository: string; metadataPath: string }) {
|
||||
const rawBase = source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/");
|
||||
const value = await this.json(`${rawBase}/HEAD/${source.metadataPath}`);
|
||||
pluginAssert(pluginRecord(value) && pluginRecord(value.package));
|
||||
const manifest = parsePluginManifest(value.manifest), pack = value.package;
|
||||
pluginAssert(manifest.id === source.id && typeof pack.ref === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/.test(pack.ref));
|
||||
pluginAssert(typeof pack.path === "string" && /^(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+\.wplugin$/.test(pack.path) && pack.path.length <= 160);
|
||||
pluginAssert(typeof pack.sha256 === "string" && SHA.test(pack.sha256));
|
||||
const descriptor = { ref: pack.ref, path: pack.path, sha256: pack.sha256 };
|
||||
return { manifest, descriptor, revision: hash({ source, manifest, package: descriptor }), url: `${rawBase}/${pack.ref}/${pack.path}` };
|
||||
}
|
||||
async list(): Promise<PluginCatalog> {
|
||||
const sources = await this.sources(), entries = new Array<PluginStoreEntry>(sources.length); let cursor = 0;
|
||||
await Promise.all(Array.from({ length: Math.min(4, sources.length) }, async () => {
|
||||
while (cursor < sources.length) { const i = cursor++, source = sources[i];
|
||||
try { const meta = await this.metadata(source); entries[i] = { ...source, manifest: meta.manifest, revision: meta.revision, error: null }; }
|
||||
catch (e) { entries[i] = { ...source, manifest: null, revision: "", error: e instanceof PluginError ? e.code : "PLUGIN_STORE_UNAVAILABLE" }; }
|
||||
}
|
||||
}));
|
||||
return { repository: PLUGIN_STORE_REPOSITORY, entries };
|
||||
}
|
||||
async install(registry: PluginRegistry, input: unknown) {
|
||||
pluginAssert(pluginRecord(input) && pluginId(input.id) && typeof input.revision === "string" && SHA.test(input.revision));
|
||||
pluginAssert(input.installedRevision === null || typeof input.installedRevision === "string" && SHA.test(input.installedRevision));
|
||||
const source = (await this.sources()).find(s => s.id === input.id); pluginAssert(source, "PLUGIN_NOT_FOUND");
|
||||
const metadata = await this.metadata(source); pluginAssert(metadata.revision === input.revision, "PLUGIN_CHANGED");
|
||||
const bytes = await this.read(metadata.url, PLUGIN_LIMIT_BYTES);
|
||||
pluginAssert(createHash("sha256").update(bytes).digest("hex") === metadata.descriptor.sha256, "PLUGIN_CHECKSUM");
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { throw new PluginError("PLUGIN_INVALID"); }
|
||||
const pack = parsePluginPackage(value);
|
||||
const actual = pack.manifest, listed = metadata.manifest;
|
||||
pluginAssert(actual.id === listed.id && actual.version === listed.version
|
||||
&& actual.client.entry === listed.client.entry && actual.server?.entry === listed.server?.entry
|
||||
&& actual.scopes.length === listed.scopes.length && actual.scopes.every(scope => listed.scopes.includes(scope)),
|
||||
"PLUGIN_PACKAGE_MISMATCH");
|
||||
return registry.install(pack, input.installedRevision as string | null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/** Child-process entrypoint. Reviewed applications run normal Node.js, not a JS sandbox. */
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { type Socket } from "node:net";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import type { JsonValue, PluginRequestContext } from "../shared/plugins.js";
|
||||
|
||||
interface RequestContext extends IncomingMessage { webspeak?: PluginRequestContext }
|
||||
interface Application {
|
||||
handle(request: RequestContext, response: ServerResponse): unknown;
|
||||
upgrade?(request: RequestContext, socket: Socket, head: Buffer): unknown;
|
||||
stop?(): unknown;
|
||||
}
|
||||
interface Initialization { type: "initialize"; entry: string; dataDir: string; config: JsonValue; publicConfig: JsonValue; token: string }
|
||||
const events = new EventEmitter(), abort = new AbortController(), sockets = new Set<Socket>();
|
||||
let application: Application | undefined, initialized = false, stopping = false, secret = "";
|
||||
const server = createServer((request: RequestContext, response) => {
|
||||
if (!authorize(request)) { response.writeHead(403).end(); return; }
|
||||
Promise.resolve().then(() => application!.handle(request, response)).catch(() => {
|
||||
if (!response.headersSent) response.writeHead(500, { "content-type": "application/json" });
|
||||
if (!response.destroyed) response.end('{"error":"PLUGIN_HANDLER_FAILED"}');
|
||||
});
|
||||
});
|
||||
function authorize(request: RequestContext): boolean {
|
||||
if (!secret || request.headers["x-webspeak-runtime"] !== secret) return false;
|
||||
delete request.headers["x-webspeak-runtime"];
|
||||
try {
|
||||
const context = JSON.parse(Buffer.from(String(request.headers["x-webspeak-context"]), "base64url").toString("utf8"));
|
||||
if (context?.apiVersion !== 2 || !context.self?.id || !context.scope?.key) return false;
|
||||
request.webspeak = context;
|
||||
delete request.headers["x-webspeak-context"];
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); });
|
||||
server.on("upgrade", (request: RequestContext, socket: Socket, head) => {
|
||||
if (!authorize(request) || !application?.upgrade) { socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); return; }
|
||||
Promise.resolve().then(() => application!.upgrade!(request, socket, head)).catch(() => socket.destroy());
|
||||
});
|
||||
server.on("error", () => { process.send?.({ type: "failed", code: "PLUGIN_LISTEN_FAILED" }); void stop(); });
|
||||
async function initialize(value: Initialization): Promise<void> {
|
||||
if (initialized) return;
|
||||
initialized = true; secret = value.token;
|
||||
try {
|
||||
const module = await import(pathToFileURL(value.entry).href);
|
||||
if (typeof module.default !== "function") throw new Error("Expected a default activation function");
|
||||
const result = await module.default({
|
||||
dataDir: value.dataDir, config: value.config, publicConfig: value.publicConfig, events, signal: abort.signal,
|
||||
log(level: string, message: unknown) { process.send?.({ type: "log", level, message: String(message).slice(0, 1000) }); },
|
||||
});
|
||||
if (stopping) return;
|
||||
application = typeof result === "function" ? { handle: result } : result;
|
||||
if (!application || typeof application.handle !== "function") throw new Error("Expected a Node HTTP request handler");
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (address && typeof address !== "string") process.send?.({ type: "ready", port: address.port });
|
||||
});
|
||||
} catch { process.send?.({ type: "failed", code: "PLUGIN_START_FAILED" }); await stop(); }
|
||||
}
|
||||
async function stop(): Promise<void> {
|
||||
if (stopping) return;
|
||||
stopping = true; abort.abort();
|
||||
for (const socket of sockets) socket.destroy();
|
||||
server.close();
|
||||
try { await application?.stop?.(); } catch { /* Disposal cannot keep the worker alive. */ }
|
||||
events.removeAllListeners();
|
||||
if (process.connected) process.disconnect();
|
||||
process.exit(0);
|
||||
}
|
||||
process.on("message", (value: unknown) => {
|
||||
if (!value || typeof value !== "object" || !("type" in value)) return;
|
||||
if (value.type === "initialize") void initialize(value as Initialization);
|
||||
else if (value.type === "stop") void stop();
|
||||
else if (value.type === "event" && "name" in value && typeof value.name === "string" && !stopping) {
|
||||
try { events.emit(value.name, "payload" in value ? value.payload : undefined); } catch { /* App event failure is local to this worker. */ }
|
||||
}
|
||||
});
|
||||
process.once("disconnect", () => void stop());
|
||||
process.once("SIGTERM", () => void stop());
|
||||
process.once("SIGINT", () => void stop());
|
||||
@@ -12,6 +12,25 @@ const resolved = (...addresses: string[]) => async () => addresses.map((address)
|
||||
family: address.includes(":") ? 6 : 4,
|
||||
}));
|
||||
|
||||
test("open targets classify equivalent IPv6 spellings and embedded IPv4 before DNS pinning", async () => {
|
||||
const blocked = ["0:0:0:0:0:0:0:1", "0::1", "0:1234::1", "0:0:0:0:0:0:0:0", "0:0:0:0:0:ffff:a00:1",
|
||||
"::ffff:7f00:1", "0::ffff:192.168.1.1", "0:0:0:0:0:0:7f00:1", "fe80::1%1",
|
||||
"64:ff9b::808:808", "64:ff9b:1:abcd::1", "2002:0808:0808::1", "2001:0:4136:e378::1",
|
||||
"0100:0000:0:0:ffff::1", "100:0:0:1::1", "2001:0db8::1", "3fff::1"];
|
||||
for (const host of blocked) {
|
||||
assert.equal(isRestrictedAddress(host), true, host);
|
||||
await assert.rejects(resolveSafeOpenTarget({ host, port: 9987 }), { name: "UnsafeTeamSpeakTargetError" });
|
||||
await assert.rejects(resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
|
||||
resolveSrv: async () => [], lookup: resolved("8.8.8.8", host),
|
||||
}), { name: "UnsafeTeamSpeakTargetError" });
|
||||
}
|
||||
for (const host of ["0:0:0:0:0:ffff:808:808", "::ffff:1.1.1.1", "2001:4860:0000:0:0:0:0:8888",
|
||||
"64:ff9b:2::1", "100:0:1::1", "2001:db9::1", "2003::1"]) {
|
||||
assert.equal(isRestrictedAddress(host), false, host);
|
||||
assert.deepEqual(await resolveSafeOpenTarget({ host, port: 9987 }), { host, port: 9987 });
|
||||
}
|
||||
});
|
||||
|
||||
test("Mihomo fake-IP DNS answers remain connectable without allowing literal or mixed fake-IP targets", async () => {
|
||||
const target = { host: "ts.twilightly.top", port: 9987 };
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isIP } from "node:net";
|
||||
import { BlockList, isIP, SocketAddress } from "node:net";
|
||||
import { lookup, resolveSrv } from "node:dns/promises";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -108,25 +108,28 @@ export async function isSafeOpenTargetForPrefill(
|
||||
}
|
||||
}
|
||||
|
||||
const restrictedIpv6 = new BlockList();
|
||||
// Match address bits, not textual compression or the case/width of hex groups.
|
||||
for (const [network, prefix] of [
|
||||
["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
|
||||
["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
|
||||
["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
|
||||
["fec0::", 10], ["ff00::", 8],
|
||||
] as const) restrictedIpv6.addSubnet(network, prefix, "ipv6");
|
||||
|
||||
export function isRestrictedAddress(address: string): boolean {
|
||||
// Scoped destinations refer to a gateway-local interface and are never public targets.
|
||||
if (address.includes("%")) return true;
|
||||
const version = isIP(address);
|
||||
if (version === 4) return isRestrictedIpv4(address);
|
||||
if (version !== 6) return true;
|
||||
|
||||
const normalized = address.toLocaleLowerCase();
|
||||
if (normalized === "::" || normalized === "::1") return true;
|
||||
const normalized = new SocketAddress({ address, family: "ipv6" }).address;
|
||||
if (normalized.startsWith("::ffff:")) {
|
||||
const mapped = normalized.slice("::ffff:".length);
|
||||
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
|
||||
}
|
||||
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
|
||||
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
|
||||
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
|
||||
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
|
||||
if (normalized.startsWith("2001:db8:")) return true; // documentation range
|
||||
return false;
|
||||
return restrictedIpv6.check(normalized, "ipv6");
|
||||
}
|
||||
|
||||
function isMihomoFakeIpv4(address: string): boolean {
|
||||
|
||||
@@ -49,3 +49,10 @@ test("expired tickets do not evict a still-valid join when capacity is reclaimed
|
||||
assert.deepEqual(tickets.consume(live, 100), payload);
|
||||
assert.deepEqual(tickets.consume(latest, 100), payload);
|
||||
});
|
||||
|
||||
|
||||
test("invitation expiry also bounds a previously issued one-use join ticket", () => {
|
||||
const store = new JoinTicketStore();
|
||||
const token = store.create({ target: { host: "1.1.1.1", port: 9987 }, serverPassword: "secret", nickname: "Guest", inviteExpiresAt: 2000 }, 1000);
|
||||
assert.equal(store.consume(token,2000),null);
|
||||
});
|
||||
@@ -3,9 +3,13 @@ import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export interface JoinTicketPayload {
|
||||
target: TeamSpeakTarget;
|
||||
invitationTarget?: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
nickname: string;
|
||||
channel?: string;
|
||||
channelId?: string;
|
||||
channelPassword?: string;
|
||||
inviteExpiresAt?: number;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
accelerated?: boolean;
|
||||
@@ -30,7 +34,7 @@ export class JoinTicketStore {
|
||||
this.tickets.delete(oldest);
|
||||
}
|
||||
const token = randomBytes(24).toString("base64url");
|
||||
this.tickets.set(token, { payload, expiresAt: now + this.ttlMs });
|
||||
this.tickets.set(token, { payload, expiresAt: Math.min(now + this.ttlMs, payload.inviteExpiresAt ?? Infinity) });
|
||||
return token;
|
||||
}
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempt
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
const lower = text.toLowerCase();
|
||||
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { WorkspaceInvites } from "./workspace-invites.js";
|
||||
import { createVoiceGatewayAuthHeaders } from "./voice-gateway-auth.js";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer as createPortProbe } from "node:net";
|
||||
@@ -17,11 +19,14 @@ const logger: Logger = { debug: noop, info: noop, warn: noop, error: noop, child
|
||||
test("ingress keeps the page origin and delegates the voice ticket to the selected relay", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-relay-delegation-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const relayDatabase = new WebSpeakDatabase(path.join(directory, "relay.db"));
|
||||
const workspaceInvites = new WorkspaceInvites(relayDatabase, Buffer.alloc(32, 9));
|
||||
const relayPort = await availablePort();
|
||||
const ingressPort = await availablePort();
|
||||
const relayToken = "integration-test-relay-token";
|
||||
const relayEndpoint = `http://127.0.0.1:${relayPort}`;
|
||||
const relay = createVoiceGatewayServer({
|
||||
workspaceInvites,
|
||||
host: "127.0.0.1",
|
||||
port: relayPort,
|
||||
sharedToken: relayToken,
|
||||
@@ -46,6 +51,7 @@ test("ingress keeps the page origin and delegates the voice ticket to the select
|
||||
await ingress.stop();
|
||||
await relay.stop();
|
||||
database.close();
|
||||
relayDatabase.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -82,6 +88,31 @@ test("ingress keeps the page origin and delegates the voice ticket to the select
|
||||
assert.ok(result.ticket);
|
||||
assert.equal(result.voiceEndpoint, relayEndpoint);
|
||||
assert.equal(localTickets.consume(result.ticket!), null);
|
||||
const credentials = { target: {host:"203.0.113.20",port:9987}, serverPassword:"relay-server-secret", channelId:"42", channelPassword:"relay-channel-secret" };
|
||||
const invite = workspaceInvites.create(credentials,60);
|
||||
const lookup = {token:invite.token,purpose:"workspace-invite"};
|
||||
const lookupUrl = relayEndpoint+"/api/relay/workspace-invite";
|
||||
const unsigned = await fetch(lookupUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(lookup)});
|
||||
assert.equal(unsigned.status,401,"relay credentials must never be public");
|
||||
const authHeaders = createVoiceGatewayAuthHeaders(relayToken,lookup);
|
||||
const requestLookup = () => fetch(lookupUrl,{method:"POST",headers:{"content-type":"application/json",...authHeaders},body:JSON.stringify(lookup)});
|
||||
const authorized = await requestLookup();
|
||||
assert.equal(authorized.status,200);
|
||||
assert.equal(authorized.headers.get("cache-control"),"no-store");
|
||||
assert.deepEqual((await authorized.json() as {access:unknown}).access,{...credentials,expiresAt:invite.expiresAt});
|
||||
assert.equal((await requestLookup()).status,401,"relay invitation requests cannot be replayed");
|
||||
const invited = await fetch(origin+"/api/join-ticket", {method:"POST",headers:{origin,"content-type":"application/json"},body:JSON.stringify({nickname:"Invitee",invite:invite.token,target:"127.0.0.1:1",channel:"other"})});
|
||||
assert.equal(invited.status,201);
|
||||
const invitedBody = await invited.json() as {ticket:string};
|
||||
assert.deepEqual(Object.keys(invitedBody).sort(),["ok","ticket"]);
|
||||
const invitedPayload = localTickets.consume(invitedBody.ticket)!;
|
||||
assert.deepEqual(invitedPayload.target,credentials.target);
|
||||
assert.equal(invitedPayload.serverPassword,credentials.serverPassword);
|
||||
assert.equal(invitedPayload.channelId,credentials.channelId);
|
||||
assert.equal(invitedPayload.channelPassword,credentials.channelPassword);
|
||||
assert.equal(invitedPayload.inviteExpiresAt,invite.expiresAt);
|
||||
assert.equal(invitedPayload.channel,undefined);
|
||||
|
||||
});
|
||||
|
||||
async function availablePort(): Promise<number> {
|
||||
|
||||
+73
-19
@@ -3,9 +3,9 @@ import { createServer as createHttpsServer } from "node:https";
|
||||
import { createServer as createHttpServer } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
|
||||
import { resolveTeamSpeakTarget, TeamSpeakAliasLookupError } from "./teamspeak-alias.js";
|
||||
import { createAdminRouter } from "../admin/admin-router.js";
|
||||
@@ -15,9 +15,14 @@ import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget, TeamSpeakTargetResol
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import { createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voice-gateway-auth.js";
|
||||
import { parseDelegatedVoiceSession, createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voice-gateway-auth.js";
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
import type { PluginRegistry } from "../plugins/registry.js";
|
||||
import { PluginRuntime } from "../plugins/runtime.js";
|
||||
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
|
||||
import { parseHiddenHostParts } from "../shared/skin-chrome.js";
|
||||
import type { UpdateService } from "../updater/update-service.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -28,9 +33,13 @@ export interface WebServerOptions {
|
||||
voiceBridgeOptions: VoiceBridgeOptions;
|
||||
adminService: AdminService;
|
||||
skinRegistry?: SkinRegistry;
|
||||
pluginRegistry?: PluginRegistry;
|
||||
pluginRuntime?: { port?: number; host?: string; publicOrigin?: string; maxWorkers?: number };
|
||||
logger: Logger;
|
||||
nextVisitorNumber?: () => number;
|
||||
visitorCount?: () => number;
|
||||
updateService?: UpdateService;
|
||||
restartAfterUpdate?: () => void;
|
||||
}
|
||||
|
||||
export interface WebServer {
|
||||
@@ -55,11 +64,17 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
server = createHttpServer(app);
|
||||
}
|
||||
|
||||
app.use(express.json({ limit: "100kb" }));
|
||||
const json = express.json({ limit: "100kb" });
|
||||
app.use((request, response, next) => request.path.startsWith("/api/admin/plugins") ? next() : json(request, response, next));
|
||||
|
||||
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
|
||||
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, createWorkspaceInvite: (credentials, minutes) => options.adminService.createWorkspaceInvite(credentials, minutes), pluginRuntimeEnabled: !!options.pluginRegistry }, logger);
|
||||
const pluginRuntime = options.pluginRegistry ? new PluginRuntime({ registry: options.pluginRegistry, participant: token => voiceBridge.resolvePluginParticipant(token), logger,
|
||||
...options.pluginRuntime, ...(options.certDir ? { tls: { cert: readFileSync(path.join(options.certDir,"cert.pem")), key: readFileSync(path.join(options.certDir,"key.pem")) } } : {}) }) : undefined;
|
||||
app.use("/api/plugins", createPluginRuntimeRouter(pluginRuntime));
|
||||
const adminSessions = new AdminSessionStore();
|
||||
const joinRateLimiter = new JoinRateLimiter();
|
||||
const trustedProxies = createTrustedProxies(options.voiceBridgeOptions.trustedProxies);
|
||||
const clientIp = (request: express.Request) => resolveClientIp(request, trustedProxies);
|
||||
const startedAt = Date.now();
|
||||
|
||||
const healthHandler: express.RequestHandler = (_request, response) => {
|
||||
@@ -112,6 +127,9 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
...(visitorTotal === null ? {} : { visitorTotal }),
|
||||
accelerationAvailable: acceleration.length > 0,
|
||||
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
|
||||
// Instance-level default for non-critical host decorations. Unknown or
|
||||
// protected names are ignored by the shared validator.
|
||||
hiddenHostParts: parseHiddenHostParts(process.env.WEBSPEAK_HOST_CHROME_HIDDEN_PARTS),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -160,7 +178,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
|
||||
if (!joinRateLimiter.allow(clientIp(request))) {
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
|
||||
return;
|
||||
}
|
||||
@@ -184,15 +202,23 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
}
|
||||
|
||||
const policy = options.adminService.getConnectionPolicy();
|
||||
const managedInvite = inviteToken ? options.adminService.getManagedInvite(inviteToken) : null;
|
||||
if (inviteToken && !managedInvite) {
|
||||
const isWorkspaceInvite = /^wi_[A-Za-z0-9_-]{43}$/.test(inviteToken);
|
||||
let workspaceInvite = isWorkspaceInvite ? options.adminService.getWorkspaceInvite(inviteToken) : null;
|
||||
if (!workspaceInvite && isWorkspaceInvite) {
|
||||
const relays = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration).filter(relay => relay.voiceEndpoint);
|
||||
const accesses = await Promise.all(relays.map(relay => resolveRemoteWorkspaceInvite(relay, inviteToken)));
|
||||
workspaceInvite = accesses.find(access => access !== null) ?? null;
|
||||
}
|
||||
const managedInvite = inviteToken && !isWorkspaceInvite ? options.adminService.getManagedInvite(inviteToken) : null;
|
||||
if (inviteToken && !managedInvite && !workspaceInvite) {
|
||||
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
|
||||
return;
|
||||
}
|
||||
let targetText = managedInvite?.target ?? policy.defaultTarget;
|
||||
let targetText = workspaceInvite ? formatTeamSpeakTarget(workspaceInvite.target) : managedInvite?.target ?? policy.defaultTarget;
|
||||
let target: TeamSpeakTarget;
|
||||
let serverPassword = policy.serverPassword;
|
||||
const channel = requestedChannel || managedInvite?.channel || "";
|
||||
let invitationTarget: TeamSpeakTarget;
|
||||
let serverPassword = workspaceInvite?.serverPassword ?? policy.serverPassword;
|
||||
const channel = workspaceInvite ? "" : requestedChannel || managedInvite?.channel || "";
|
||||
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
|
||||
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
@@ -205,7 +231,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!managedInvite) {
|
||||
if (!managedInvite && !workspaceInvite) {
|
||||
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
|
||||
targetText = formatTeamSpeakConnectionTarget(parseTeamSpeakConnectionTarget(body.target));
|
||||
const isDefault = targetText === policy.defaultTarget;
|
||||
@@ -219,6 +245,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
}
|
||||
}
|
||||
target = await resolveTeamSpeakTarget(targetText);
|
||||
invitationTarget = { ...target };
|
||||
// Open-mode defaults are user targets too; validate the resolved address
|
||||
// and pass that exact IP to the voice connection to prevent DNS rebinding.
|
||||
if (!managedInvite && policy.accessMode === "open") target = await resolveSafeOpenTarget(target);
|
||||
@@ -227,7 +254,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
return;
|
||||
}
|
||||
|
||||
if (inviteToken) {
|
||||
if (managedInvite) {
|
||||
const consumedInvite = options.adminService.consumeManagedInvite(inviteToken);
|
||||
if (!consumedInvite) {
|
||||
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
|
||||
@@ -238,9 +265,11 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
|
||||
const sessionPayload: DelegatedVoiceSession = {
|
||||
target,
|
||||
invitationTarget,
|
||||
serverPassword,
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
...(workspaceInvite ? { channelId: workspaceInvite.channelId, channelPassword: workspaceInvite.channelPassword, inviteExpiresAt: workspaceInvite.expiresAt } : {}),
|
||||
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
};
|
||||
const selectedRelay = accelerationRequested
|
||||
@@ -273,9 +302,14 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
skinRegistry: options.skinRegistry,
|
||||
pluginRegistry: options.pluginRegistry,
|
||||
pluginRuntime,
|
||||
updateService: options.updateService,
|
||||
restartAfterUpdate: options.restartAfterUpdate,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
clientIp,
|
||||
}));
|
||||
|
||||
// Serve static frontend
|
||||
@@ -289,15 +323,18 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
voiceBridge.attach(server);
|
||||
|
||||
return {
|
||||
start(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
server.listen(options.port, () => {
|
||||
logger.info({ port: options.port }, "Web server started");
|
||||
resolve();
|
||||
});
|
||||
async start(): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(options.port, () => { server.off("error", reject); logger.info({ port: options.port }, "Web server started"); resolve(); });
|
||||
});
|
||||
if (pluginRuntime) {
|
||||
try { await pluginRuntime.start(); }
|
||||
catch { logger.warn({code:"PLUGIN_RUNTIME_UNAVAILABLE"},"Plugin application origin could not start; voice and administration remain available"); }
|
||||
}
|
||||
},
|
||||
async stop(): Promise<void> {
|
||||
await pluginRuntime?.close();
|
||||
await voiceBridge.shutdown();
|
||||
adminSessions.clear();
|
||||
return new Promise((resolve) => {
|
||||
@@ -315,6 +352,23 @@ function resolveAccelerationOptions(
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
async function resolveRemoteWorkspaceInvite(relay: ConfiguredAccelerationRelay, token: string): Promise<import("./workspace-invites.js").WorkspaceInviteAccess | null> {
|
||||
const body = { token, purpose: "workspace-invite" };
|
||||
try {
|
||||
const response = await fetch(new URL("/api/relay/workspace-invite", relay.voiceEndpoint), {
|
||||
method: "POST", headers: { "content-type": "application/json", ...createVoiceGatewayAuthHeaders(relay.token, body) },
|
||||
body: JSON.stringify(body), signal: AbortSignal.timeout(4000), cache: "no-store", redirect: "error",
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const result: unknown = await response.json();
|
||||
if (!isRecord(result) || result.ok !== true || !isRecord(result.access)) return null;
|
||||
const value = result.access;
|
||||
const session = parseDelegatedVoiceSession({ ...value, nickname: "Invite validation", inviteExpiresAt: value.expiresAt });
|
||||
if (!session?.channelId || session.channelPassword === undefined || typeof value.expiresAt !== "number") return null;
|
||||
return { target: session.target, serverPassword: session.serverPassword, channelId: session.channelId, channelPassword: session.channelPassword, expiresAt: value.expiresAt };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async function createRemoteVoiceTicket(relay: ConfiguredAccelerationRelay, payload: DelegatedVoiceSession): Promise<string> {
|
||||
const endpoint = new URL("/api/relay/voice-ticket", relay.voiceEndpoint);
|
||||
const response = await fetch(endpoint, {
|
||||
|
||||
@@ -35,11 +35,45 @@ function fixture() {
|
||||
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
}, encoder, () => state.now);
|
||||
}, encoder, () => state.now, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
|
||||
}
|
||||
|
||||
test("PCM flooding is bounded before encoding while real-time, jitter and recovery remain usable", t => {
|
||||
const realtime = fixture();
|
||||
for (let i = 0; i < 1_000; i++) { realtime.state.now = i * 20; realtime.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(realtime.encoded.length, 1_000);
|
||||
const flood = fixture();
|
||||
t.mock.method(flood.encoder, "encode", () => { flood.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
|
||||
for (let i = 0; i < 1_000; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.ok(flood.encoded.length <= 50);
|
||||
assert.equal(flood.audio.ingressDroppedFrames, 1_000 - flood.encoded.length);
|
||||
assert.equal(flood.warnings.filter(w => w.code === "AUDIO_RATE_EXCEEDED").length, 1);
|
||||
assert.equal(flood.notices.length, 0);
|
||||
flood.state.now = 10_000;
|
||||
const before = flood.forwarded.length;
|
||||
for (let i = 0; i < 50; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(flood.forwarded.length - before, 50, "one-second backlog after a stall is allowed");
|
||||
const recovered = flood.forwarded.length;
|
||||
for (let i = 1; i <= 100; i++) { flood.state.now = 10_000 + i * 20; flood.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(flood.forwarded.length - recovered, 100, "flood drops do not lock out subsequent real-time audio");
|
||||
});
|
||||
|
||||
test("PCM budget uses a separate monotonic clock and cannot refill twice after a clock rollback", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { f.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
|
||||
for (let i = 0; i < 50; i++) f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = -1_000;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = 0;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 50);
|
||||
f.state.now = 100;
|
||||
for (let i = 0; i < 20; i++) f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 56);
|
||||
});
|
||||
|
||||
test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WebSocket } from "ws";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
@@ -12,6 +13,8 @@ const MAX_BUFFERED_BYTES = 4_096;
|
||||
// frame: the reply is roughly 100x the offending payload, and the browser only
|
||||
// ever shows the first one because it writes the same error string.
|
||||
const AUDIO_ISSUE_REPORT_MS = 5_000;
|
||||
const PCM_BURST_FRAMES = 50; // One second of buffered 20 ms capture after a stall.
|
||||
const PCM_FRAMES_PER_MS = 60 / 1_000; // 50 fps capture plus 20% scheduling headroom.
|
||||
|
||||
export interface VoiceEncoder {
|
||||
encode(frame: Buffer): Buffer;
|
||||
@@ -39,8 +42,11 @@ export class SessionAudioTransport {
|
||||
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
|
||||
private readonly reportedAt = new Map<string, number>();
|
||||
private readonly logger: LoggerType | null;
|
||||
private pcmTokens = PCM_BURST_FRAMES;
|
||||
private pcmRefilledAt: number | null = null;
|
||||
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now,
|
||||
private readonly rateClock: () => number = performance.now.bind(performance)) {
|
||||
this.encoder = encoder;
|
||||
this.logger = options.logger ?? null;
|
||||
}
|
||||
@@ -127,6 +133,19 @@ export class SessionAudioTransport {
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
}
|
||||
const now = this.rateClock();
|
||||
if (this.pcmRefilledAt !== null) {
|
||||
this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS);
|
||||
}
|
||||
this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now);
|
||||
if (this.pcmTokens < 1) {
|
||||
stats.ingressDroppedFrames++;
|
||||
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.pcmTokens--;
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
@@ -130,11 +131,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
|
||||
});
|
||||
database.close();
|
||||
const legacy = new DatabaseSync(file);
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; PRAGMA user_version = 8;");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(file);
|
||||
try {
|
||||
assert.equal(migrated.schemaVersion, 12);
|
||||
assert.equal(migrated.schemaVersion, 13);
|
||||
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
|
||||
assert.equal(migrated.getSettings().tsTarget, null);
|
||||
const invite = migrated.consumeManagedInvite("legacy-token");
|
||||
@@ -162,3 +163,56 @@ async function availablePort(): Promise<number> {
|
||||
await new Promise<void>((resolve, reject) => socket.close((error) => error ? reject(error) : resolve()));
|
||||
return address.port;
|
||||
}
|
||||
|
||||
|
||||
test("workspace invite credentials persist encrypted and redeem as opaque channel-bound join tickets", async context => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-workspace-invite-"));
|
||||
const file = path.join(directory, "webspeak.db"), key = Buffer.alloc(32, 7);
|
||||
let database = new WebSpeakDatabase(file);
|
||||
let service = new AdminService(database, key, logger, path.join(directory, "missing.json"));
|
||||
await service.initialize();
|
||||
const credentials = { target: { host: "1.1.1.1", port: 9987 }, serverPassword: "private-server-password", channelId: "123", channelPassword: "private-channel-password" };
|
||||
const now = Date.now();
|
||||
const created = service.createWorkspaceInvite(credentials, 60, now);
|
||||
assert.ok(!JSON.stringify(created).includes("private-"));
|
||||
assert.deepEqual(service.getWorkspaceInvite(created.token, now), { ...credentials, expiresAt: now+3600000 });
|
||||
assert.equal(service.getWorkspaceInvite(created.token, now+3600000), null);
|
||||
assert.equal(service.getWorkspaceInvite(created.token.slice(0,-1)+"!", now), null);
|
||||
for (const expiry of [0, -1, 0.5, 43201, NaN]) assert.throws(() => service.createWorkspaceInvite(credentials, expiry));
|
||||
const legacyToken = "wi_" + "z".repeat(29);
|
||||
const legacyAdminInvite = service.createManagedInvite({ channel: "Lobby", expiresInHours: 1, maxUses: 0 });
|
||||
const raw = new DatabaseSync(file);
|
||||
raw.prepare("UPDATE managed_invites SET token_hash = ? WHERE id = ?").run(createHash("sha256").update(legacyToken).digest("hex"), legacyAdminInvite.invite.id);
|
||||
const row = raw.prepare("SELECT payload_encrypted, token_hash FROM workspace_invites").get()!;
|
||||
assert.ok(!String(row.payload_encrypted).includes("private-"));
|
||||
assert.notEqual(row.token_hash, created.token);
|
||||
raw.close();
|
||||
database.close();
|
||||
database = new WebSpeakDatabase(file);
|
||||
service = new AdminService(database, key, logger, path.join(directory, "missing.json"));
|
||||
await service.initialize();
|
||||
assert.deepEqual(service.getWorkspaceInvite(created.token, now), { ...credentials, expiresAt: now+3600000 });
|
||||
const tickets = new JoinTicketStore(), port = await availablePort(), origin = `http://127.0.0.1:${port}`;
|
||||
const server = createWebServer({ port, adminService: service, voiceBridgeOptions: { joinTickets: tickets }, logger });
|
||||
context.after(async () => { await server.stop(); database.close(); await rm(directory, {recursive:true,force:true}); });
|
||||
await server.start();
|
||||
const response = await fetch(origin+"/api/join-ticket", { method: "POST", headers: {origin,"content-type":"application/json"}, body: JSON.stringify({nickname:"Invitee", invite:created.token, target:"127.0.0.1:9987", channel:"other-channel", serverPassword:"attacker-password"}) });
|
||||
assert.equal(response.status,201);
|
||||
const result = await response.json() as {ok: boolean; ticket:string};
|
||||
assert.deepEqual(Object.keys(result).sort(),["ok","ticket"]);
|
||||
assert.ok(!JSON.stringify(result).includes("private-"));
|
||||
const payload = tickets.consume(result.ticket)!;
|
||||
assert.deepEqual(payload.target,credentials.target);
|
||||
assert.equal(payload.serverPassword,credentials.serverPassword);
|
||||
assert.equal(payload.channelId,credentials.channelId);
|
||||
assert.equal(payload.channelPassword,credentials.channelPassword);
|
||||
assert.equal(payload.channel,undefined);
|
||||
assert.equal(payload.inviteExpiresAt,created.expiresAt);
|
||||
assert.equal(tickets.consume(result.ticket),null);
|
||||
const expired = service.createWorkspaceInvite(credentials,1,now-120000);
|
||||
const denied = await fetch(origin+"/api/join-ticket",{method:"POST",headers:{origin,"content-type":"application/json"},body:JSON.stringify({nickname:"Invitee",invite:expired.token})});
|
||||
assert.equal(denied.status,400);
|
||||
assert.equal((await denied.json() as {code:string}).code,"INVITE_INVALID");
|
||||
const legacy = await fetch(origin+"/api/join-ticket", {method:"POST",headers:{origin,"content-type":"application/json"},body:JSON.stringify({nickname:"Legacy invitee",invite:legacyToken})});
|
||||
assert.equal(legacy.status,201,"an administrator token that happens to start with wi_ must remain valid");
|
||||
});
|
||||
@@ -99,7 +99,7 @@ export async function probeTeamSpeak(
|
||||
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
|
||||
if (error instanceof TeamSpeakProbeError) return error;
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLowerCase();
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
|
||||
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import test from "node:test";
|
||||
import { asChannelGroupID, asChannelID, asClientID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
|
||||
import { asChannelGroupID, asChannelID, asClientID, asClientDBID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
|
||||
import { Client, generateIdentitySync, type ServerView } from "@honeybbq/teamspeak/client";
|
||||
import { TeamSpeakSdkClient, type DirectorySnapshot } from "./teamspeak-sdk.js";
|
||||
|
||||
@@ -13,7 +13,7 @@ function channel(id = 1): Channel {
|
||||
description: "", hasPassword: true, isPermanent: true, maxClients: 12, isMaxClientsUnlimited: false } as Channel;
|
||||
}
|
||||
function member(id = 1): ClientEntry {
|
||||
return { id: asClientID(id), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
|
||||
return { id: asClientID(id), databaseID: asClientDBID(BigInt(id)), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
|
||||
serverGroups: [], isAway: true, awayMessage: "Away", isInputMuted: true, isOutputMuted: false,
|
||||
isChannelCommander: true, avatar: "avatar-hash", isRecording: false, isTalker: false,
|
||||
channelGroupID: asChannelGroupID(0n), createdAt: undefined, lastConnectedAt: undefined, idleTimeMs: undefined };
|
||||
@@ -53,6 +53,28 @@ test("ordinary-client directories and avatar metadata use the live view without
|
||||
assert.deepEqual(native.queries, []);
|
||||
});
|
||||
|
||||
test('partial SDK records preserve unknown status and channel descriptions without querying', async () => {
|
||||
const { sdk, native } = fixture();
|
||||
const { uid: _uid, serverGroups: _groups, isAway: _away, awayMessage: _message,
|
||||
isInputMuted: _input, isOutputMuted: _output, isChannelCommander: _commander, ...partial } = member();
|
||||
native.view.clients.set(partial.id, partial);
|
||||
const { description: _description, ...room } = channel(); native.view.channels.set(room.id, room);
|
||||
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: 'Member 1', uid: '', serverGroups: [], channelID: 1n, type: 0 }]);
|
||||
assert.equal((await sdk.listDirectoryChannels())[0].description, undefined);
|
||||
assert.equal(await sdk.getClientAvatarMetadata(1), null);
|
||||
assert.deepEqual(native.queries, []);
|
||||
});
|
||||
|
||||
test('SDK end-of-speech markers are not sent into the audio decoder or browser transport', () => {
|
||||
const { sdk, native } = fixture(), received: unknown[] = [];
|
||||
sdk.on('voiceData', frame => received.push(frame));
|
||||
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data: new Uint8Array() });
|
||||
assert.deepEqual(received, []);
|
||||
const data = Uint8Array.of(1, 2);
|
||||
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data });
|
||||
assert.deepEqual(received, [{ clientId: 1, codec: 4, data }]);
|
||||
});
|
||||
|
||||
test("live-view snapshots include channel edits and remove clients that went out of view", () => {
|
||||
const { sdk, native } = fixture();
|
||||
const snapshots: DirectorySnapshot[] = [];
|
||||
|
||||
@@ -46,7 +46,7 @@ export interface DirectoryChannelInfo {
|
||||
parentID: bigint;
|
||||
order: bigint;
|
||||
name: string;
|
||||
description: string;
|
||||
description?: string;
|
||||
passwordProtected?: boolean;
|
||||
isPermanent?: boolean;
|
||||
maxClients?: number;
|
||||
@@ -230,7 +230,8 @@ export class TeamSpeakSdkClient extends EventEmitter implements CommandExecutor
|
||||
client.on("viewReady", () => this.publishDirectory(client));
|
||||
client.on("viewChanged", () => this.publishDirectory(client));
|
||||
client.on("voiceData", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
// beta.20+ reports an empty payload for end-of-speech, not an Opus frame.
|
||||
if (!isCurrent() || event.data.byteLength === 0) return;
|
||||
this.emit("voiceData", { clientId: Number(event.clientID), codec: event.codec, data: event.data } satisfies VoiceData);
|
||||
});
|
||||
client.on("textMessage", (event) => {
|
||||
@@ -328,8 +329,8 @@ function toDirectoryClient(entry: ClientEntry): DirectoryClientInfo {
|
||||
return {
|
||||
id: Number(entry.id),
|
||||
nickname: entry.nickname,
|
||||
uid: entry.uid,
|
||||
serverGroups: entry.serverGroups.map(String),
|
||||
uid: entry.uid ?? "",
|
||||
serverGroups: (entry.serverGroups ?? []).map(String),
|
||||
channelID: BigInt(entry.channelID),
|
||||
type: entry.type,
|
||||
...(entry.isAway !== undefined ? { away: entry.isAway } : {}),
|
||||
|
||||
@@ -526,3 +526,19 @@ test("a live relay tunnel survives the reconnect guard untouched", () => {
|
||||
assert.notEqual(f.state.adapter, null, "an open tunnel's adapter stays usable");
|
||||
assert.notEqual(f.state.client, null, "an open tunnel's SDK client stays usable");
|
||||
});
|
||||
|
||||
|
||||
test("reconnecting to a protected channel uses its successful password rather than a failed attempt", async () => {
|
||||
const f=fixture();
|
||||
await f.client.switchChannel(10n,"correct-secret");
|
||||
const first=f.sdk.inputCommands.find(c=>c.startsWith("clientmove "))!;
|
||||
f.sdk.inputUpdate=async command=>{if(command.includes("cid=20"))throw new Error("invalid channel password");};
|
||||
await assert.rejects(f.client.switchChannel(20n,"wrong-password"));
|
||||
(f.client as unknown as {adapter:unknown}).adapter={connect:async()=>{}};
|
||||
await f.client.connect();
|
||||
const moves=f.sdk.inputCommands.filter(c=>c.startsWith("clientmove "));
|
||||
assert.equal(moves.length,3);
|
||||
assert.match(moves[2],/cid=10(?:\s|$)/);
|
||||
assert.equal(moves[2].match(/cpw=([^\s]+)/)?.[1],first.match(/cpw=([^\s]+)/)?.[1]);
|
||||
assert.ok(first.includes("cpw="));
|
||||
});
|
||||
@@ -118,6 +118,7 @@ export class TSClient extends EventEmitter {
|
||||
private inputStateQueue: Promise<void> = Promise.resolve();
|
||||
private channelSwitchQueue: Promise<void> = Promise.resolve();
|
||||
private preferredChannelId = 0n;
|
||||
private readonly channelPasswords = new Map<bigint, string>();
|
||||
private accelerationClient: AccelerationRelayClient | null = null;
|
||||
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
|
||||
private readonly channelPasswordProtection = new Map<bigint, boolean>();
|
||||
@@ -219,7 +220,7 @@ export class TSClient extends EventEmitter {
|
||||
this.preferredChannelId = connectedChannelId;
|
||||
} else if (connectedChannelId !== this.preferredChannelId) {
|
||||
try {
|
||||
await tsClientMove(client, this.clientId, this.preferredChannelId);
|
||||
await tsClientMove(client, this.clientId, this.preferredChannelId, this.channelPasswords.get(this.preferredChannelId));
|
||||
} catch (error: unknown) {
|
||||
// The old channel may have been deleted or become inaccessible. The
|
||||
// SDK has already left us in the server/default channel, which is the
|
||||
@@ -530,6 +531,7 @@ export class TSClient extends EventEmitter {
|
||||
await tsClientMove(client, clientId, channelId, password);
|
||||
if (!isCurrent()) throw new Error("TeamSpeak session changed while switching channels");
|
||||
this.preferredChannelId = channelId;
|
||||
if (password) this.channelPasswords.set(channelId, password);
|
||||
};
|
||||
|
||||
// Rapid clicks used to issue overlapping clientmove commands. The SDK and
|
||||
@@ -595,9 +597,7 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
getChannelId(): bigint {
|
||||
if (!this.client) return 0n;
|
||||
const sdkClient = this.client as unknown as { channelID?: () => bigint };
|
||||
return sdkClient.channelID?.() ?? 0n;
|
||||
return this.client?.channelID() ?? 0n;
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
|
||||
@@ -27,7 +27,10 @@ class TeamSpeakStub extends EventEmitter {
|
||||
async connect() { this.connectCalls++; this.disconnected = false; if (this.emitDirectorySnapshotOnConnect) this.emit("directorySnapshot", this.directory); }
|
||||
async disconnect() { this.disconnected = true; }
|
||||
getClientId() { return 1; }
|
||||
getChannelId() { return 1n; }
|
||||
channelId = 1n;
|
||||
lastChannelPassword = "";
|
||||
async switchChannel(id: bigint, password?: string) { this.channelId = id; this.lastChannelPassword = password ?? ""; }
|
||||
getChannelId() { return this.channelId; }
|
||||
isConnected() { return !this.disconnected; }
|
||||
async getServerInfo() { this.serverInfoCalls++; return { name: "兄弟们的teamspeak", iconId: null }; }
|
||||
async getServerPresentation() {
|
||||
@@ -43,15 +46,17 @@ class TeamSpeakStub extends EventEmitter {
|
||||
}
|
||||
|
||||
async function fixture(t: TestContext, overrides: {
|
||||
createTeamSpeakClient?: () => TSClient;
|
||||
createTeamSpeakClient?: (options: import("./ts-client.js").TSClientOptions) => TSClient;
|
||||
createEncoder?: () => Pick<OpusEncoder, "encode" | "dispose">;
|
||||
configureSdk?: (sdk: TeamSpeakStub) => void;
|
||||
waitForFirstMessage?: boolean;
|
||||
createWorkspaceInvite?: import("./voice-bridge.js").VoiceBridgeOptions["createWorkspaceInvite"];
|
||||
connection?: Partial<import("./join-ticket.js").JoinTicketPayload>;
|
||||
} = {}) {
|
||||
const sdk = new TeamSpeakStub();
|
||||
overrides.configureSdk?.(sdk);
|
||||
const tickets = new JoinTicketStore();
|
||||
const bridge = new VoiceBridge({ joinTickets: tickets }, pino({ enabled: false }), undefined, {
|
||||
const bridge = new VoiceBridge({ joinTickets: tickets, createWorkspaceInvite: overrides.createWorkspaceInvite }, pino({ enabled: false }), undefined, {
|
||||
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
|
||||
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
|
||||
});
|
||||
@@ -62,7 +67,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
await once(server, "listening");
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "" });
|
||||
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "", ...overrides.connection });
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);
|
||||
const messages: Array<{ data: Buffer; binary: boolean }> = [];
|
||||
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
|
||||
@@ -80,6 +85,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
const entries = (bridge as unknown as { entries: Map<string, {
|
||||
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
|
||||
isAlive: boolean; lastPongAt: number; missedHeartbeats: number; avatarCache: Map<string, string | null>;
|
||||
channelTree: import("../shared/voice-models.js").ChannelInfo[];
|
||||
members: Map<number, { id: number; uid: string }>; eventLog: unknown[];
|
||||
}> }).entries;
|
||||
return { bridge, sdk, socket, messages, entries, wss };
|
||||
@@ -428,3 +434,53 @@ for (const order of ["kick-first", "disconnect-first"] as const) {
|
||||
assert.match(failures[0].detail, /Removed by operator/);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
test("workspace invitations use authenticated session credentials and remember only successful channel passwords", async t => {
|
||||
let credentials: unknown;
|
||||
const f = await fixture(t, { connection: { serverPassword: "server-secret", invitationTarget: { host: "original.example.com", port: 9987 } },
|
||||
createWorkspaceInvite: (value, minutes) => { credentials = value; assert.equal(minutes, 60); return { token: "wi_" + "x".repeat(43), expiresAt: Date.now()+3600000 }; },
|
||||
});
|
||||
while (!messageTypes(f.messages).includes("connected")) await nextTurn();
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
entry.channelTree.push({ id: "1", parentID: "0", name: "Locked", passwordProtected: true });
|
||||
let reply = waitForMessage(f.socket, "error");
|
||||
f.socket.send(JSON.stringify({ type: "createInvite", requestId: "missing-password", payload: { expiresInMinutes: 60 } }));
|
||||
assert.equal(((await reply).error as { code: string }).code, "CHANNEL_PASSWORD_REQUIRED");
|
||||
const switched = waitForMessage(f.socket, "channelSwitched");
|
||||
f.socket.send(JSON.stringify({ type: "switchChannel", requestId: "switch", payload: { channelId: "1", password: "channel-secret" } }));
|
||||
await switched;
|
||||
reply = waitForMessage(f.socket, "inviteCreated");
|
||||
f.socket.send(JSON.stringify({ type: "createInvite", requestId: "invite", payload: { expiresInMinutes: 60, target: "127.0.0.1", channelId: "999" } }));
|
||||
const result = await reply;
|
||||
assert.equal(result.requestId, "invite");
|
||||
assert.deepEqual(credentials, { target: { host: "original.example.com", port: 9987 }, serverPassword: "server-secret", channelId: "1", channelPassword: "channel-secret" });
|
||||
assert.ok(!JSON.stringify(f.messages).includes("server-secret"));
|
||||
assert.ok(!JSON.stringify(f.messages).includes("channel-secret"));
|
||||
});
|
||||
|
||||
test("an invited connection joins its bound channel using server-only credentials before reporting connected", async t => {
|
||||
let sdk: TeamSpeakStub;
|
||||
const f = await fixture(t, { connection: { serverPassword: "private-server", channelId: "9", channelPassword: "private-channel" },
|
||||
configureSdk: value => { sdk = value; },
|
||||
createTeamSpeakClient: options => { assert.equal(options.serverPassword, "private-server"); return sdk as unknown as TSClient; },
|
||||
});
|
||||
while (!messageTypes(f.messages).includes("connected")) await nextTurn();
|
||||
assert.equal(f.sdk.channelId, 9n);
|
||||
assert.equal(f.sdk.lastChannelPassword, "private-channel");
|
||||
assert.ok(!JSON.stringify(f.messages).includes("private-channel"));
|
||||
assert.ok(!JSON.stringify(f.messages).includes("private-server"));
|
||||
});
|
||||
|
||||
|
||||
test("an authenticated creator may supply a missing server password without disclosing it to the recipient", async t => {
|
||||
const f=await fixture(t,{createWorkspaceInvite: credentials=>{
|
||||
assert.equal(credentials.serverPassword,"creator-provided");
|
||||
return {token:"wi_"+"a".repeat(43),expiresAt:Date.now()+60000};
|
||||
}});
|
||||
while(!messageTypes(f.messages).includes("connected"))await nextTurn();
|
||||
const reply=waitForMessage(f.socket,"inviteCreated");
|
||||
f.socket.send(JSON.stringify({type:"createInvite",requestId:"provided",payload:{expiresInMinutes:1,serverPassword:"creator-provided"}}));
|
||||
assert.equal((await reply).requestId,"provided");
|
||||
assert.ok(!JSON.stringify(f.messages).includes("creator-provided"));
|
||||
});
|
||||
@@ -238,6 +238,14 @@ function ipRequest(remoteAddress: string | undefined, headers: Record<string, st
|
||||
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
|
||||
}
|
||||
|
||||
test("equivalent forwarded IPv6 spellings share one canonical client and rate-limit key", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
const resolve = (value: string) => resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": value }), trusted);
|
||||
assert.equal(resolve("2001:0DB9:0000:0000:0000:0000:0000:0001"), resolve("2001:db9::1"));
|
||||
assert.equal(resolve("0:0:0:0:0:ffff:cb00:7109"), "203.0.113.9");
|
||||
assert.equal(resolve("::ffff:203.0.113.9"), "203.0.113.9");
|
||||
});
|
||||
|
||||
test("a direct client cannot choose the address recorded for it", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "192.0.2.7");
|
||||
|
||||
@@ -10,8 +10,8 @@ import { resolveVoiceMediaAddresses } from "./webrtc-config.js";
|
||||
import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js";
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { randomUUID, randomBytes } from "node:crypto";
|
||||
import { BlockList, isIP, SocketAddress } from "node:net";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
@@ -27,6 +27,7 @@ import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./ac
|
||||
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
import type { PluginParticipant } from "../shared/plugins.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const MAX_MISSED_HEARTBEATS = 2;
|
||||
@@ -49,6 +50,8 @@ function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>):
|
||||
}
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
createWorkspaceInvite?: (credentials: import("./workspace-invites.js").WorkspaceInviteCredentials, minutes: number) => { token: string; expiresAt: number };
|
||||
pluginRuntimeEnabled?: boolean;
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
|
||||
@@ -81,6 +84,7 @@ export interface AdminSessionSummary {
|
||||
type ServerEvent = SharedServerEvent & { kind: "joined" | "left" | "moved" | "poke" | "connection" };
|
||||
|
||||
interface WebClientEntry extends SessionDirectoryState {
|
||||
rememberChannelPassword?: (id: string, password: string) => void;
|
||||
id: string;
|
||||
session: ManagedSession;
|
||||
tsClient: TSClient;
|
||||
@@ -107,6 +111,7 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
lastAudioStatsProbeAt: number;
|
||||
connectionFailureCode?: string;
|
||||
screenPeerId: string;
|
||||
pluginSession?: string;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
@@ -165,6 +170,8 @@ export class VoiceBridge {
|
||||
|
||||
const { target, serverPassword, nickname } = connection;
|
||||
const channelName = connection.channel;
|
||||
const channelPasswords = new Map<string, string>();
|
||||
let lastInviteAt = 0;
|
||||
const acceleration = connection.accelerated ? this.getAccelerationOptions(connection.accelerationRelayId) : undefined;
|
||||
if (connection.accelerated && !acceleration) {
|
||||
ws.close(4006, "ACCELERATION_UNAVAILABLE");
|
||||
@@ -228,6 +235,7 @@ export class VoiceBridge {
|
||||
}
|
||||
entry = {
|
||||
id: entryId,
|
||||
rememberChannelPassword: (id, password) => channelPasswords.set(id, password),
|
||||
session,
|
||||
tsClient,
|
||||
ws,
|
||||
@@ -319,6 +327,7 @@ export class VoiceBridge {
|
||||
}, "Web client connected to TeamSpeak");
|
||||
}
|
||||
session.transition("connected");
|
||||
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
|
||||
sendJson({
|
||||
type: "connected",
|
||||
tsClientId: events.selfId,
|
||||
@@ -330,6 +339,7 @@ export class VoiceBridge {
|
||||
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
|
||||
screenShareIceServers: this.getScreenShareIceServers(),
|
||||
accelerated: Boolean(entry!.acceleration),
|
||||
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
|
||||
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
|
||||
});
|
||||
sendJson({ type: "channelList", channels: entry!.channelTree });
|
||||
@@ -445,6 +455,11 @@ export class VoiceBridge {
|
||||
const connectTeamSpeak = async (isReconnect: boolean): Promise<void> => {
|
||||
try {
|
||||
await tsClient.connect();
|
||||
if (connection.channelId && !isReconnect) {
|
||||
if (tsClient.getChannelId().toString() !== connection.channelId) await tsClient.switchChannel(BigInt(connection.channelId), connection.channelPassword || undefined);
|
||||
if (tsClient.getChannelId().toString() !== connection.channelId) throw new Error("Invited channel could not be joined");
|
||||
if (connection.channelPassword) channelPasswords.set(connection.channelId, connection.channelPassword);
|
||||
}
|
||||
if (session.state !== "authenticating") return;
|
||||
session.transition("syncing");
|
||||
tsReady = true;
|
||||
@@ -492,7 +507,9 @@ export class VoiceBridge {
|
||||
this.screenShares.onClientLeave(entry!, id);
|
||||
entry!.webrtc?.removeClient(id);
|
||||
},
|
||||
onClientMove: (id, channelId) => this.screenShares.onClientMove(entry!, id, channelId),
|
||||
onClientMove: (id, channelId) => {
|
||||
this.screenShares.onClientMove(entry!, id, channelId);
|
||||
},
|
||||
onNotification: notification => this.screenShares.handleNotification(entry!, notification),
|
||||
onVoice: data => entry!.audioTransport?.receiveTeamSpeak(data),
|
||||
onAvatarError: (clientId, uid, error) => this.logger.debug({
|
||||
@@ -605,6 +622,19 @@ export class VoiceBridge {
|
||||
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪", command.requestId);
|
||||
return;
|
||||
}
|
||||
if (command.type === "createInvite") {
|
||||
if (!this.options.createWorkspaceInvite) { sendProtocolError(sendJson, "INVITE_UNAVAILABLE", "Invitations are unavailable on this gateway", command.requestId); return; }
|
||||
if (Date.now() - lastInviteAt < 1000) { sendProtocolError(sendJson, "RATE_LIMITED", "Please wait before creating another invitation", command.requestId); return; }
|
||||
const channelId = tsClient.getChannelId().toString();
|
||||
const password = command.payload.channelPassword || channelPasswords.get(channelId) || "";
|
||||
if (entry!.channelTree.find(c => c.id === channelId)?.passwordProtected && !password) { sendProtocolError(sendJson, "CHANNEL_PASSWORD_REQUIRED", "Enter the current channel password to share access", command.requestId); return; }
|
||||
try {
|
||||
const result = this.options.createWorkspaceInvite({ target: connection.invitationTarget ?? target, serverPassword: command.payload.serverPassword ?? serverPassword, channelId, channelPassword: password }, command.payload.expiresInMinutes);
|
||||
lastInviteAt = Date.now();
|
||||
sendJson({ type: "inviteCreated", requestId: command.requestId, ...result });
|
||||
} catch { sendProtocolError(sendJson, "INVITE_CREATE_FAILED", "Could not create invitation", command.requestId); }
|
||||
return;
|
||||
}
|
||||
void handleCommand(entry!, command, sendJson);
|
||||
});
|
||||
|
||||
@@ -700,6 +730,21 @@ export class VoiceBridge {
|
||||
});
|
||||
}
|
||||
|
||||
resolvePluginParticipant(token: string): PluginParticipant | null {
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
|
||||
for (const entry of this.entries.values()) {
|
||||
if (entry.pluginSession !== token || entry.session.state !== "connected" || entry.ws.readyState !== WebSocket.OPEN) continue;
|
||||
try {
|
||||
const selfId = entry.tsClient.getClientId(), channelId = entry.tsClient.getChannelId().toString();
|
||||
const uid = entry.members.get(selfId)?.uid;
|
||||
const members = entry.channelTree.find(channel => channel.id === channelId)?.members ?? [];
|
||||
return { id: entry.id, nickname: entry.nickname, ...(uid ? { uid } : {}), target: teamSpeakTargetKey(entry.target), channelId,
|
||||
members: members.map(member => ({ id: member.id, nickname: member.nickname, ...(member.uid ? { uid: member.uid } : {}) })) };
|
||||
} catch { return null; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async terminateSession(entryId: string): Promise<boolean> {
|
||||
if (!this.entries.has(entryId)) return false;
|
||||
await this.sessionManager.teardown(entryId, "admin-terminated");
|
||||
@@ -983,6 +1028,9 @@ function normalizeClientIp(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
let trimmed = value.trim();
|
||||
if (trimmed.startsWith("[") && trimmed.endsWith("]")) trimmed = trimmed.slice(1, -1);
|
||||
const family = isIP(trimmed);
|
||||
if (!family) return undefined;
|
||||
if (family === 6) trimmed = new SocketAddress({ address: trimmed, family: "ipv6" }).address;
|
||||
if (trimmed.toLowerCase().startsWith("::ffff:")) {
|
||||
const mapped = trimmed.slice("::ffff:".length);
|
||||
if (isIP(mapped) === 4) trimmed = mapped;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { teamSpeakServerErrorCode } from "../errors.js";
|
||||
export interface VoiceCommandContext extends AudioStatsSource {
|
||||
tsClient: Pick<TSClient, "execCommandWithResponse" | "switchChannel" | "getClientId" | "getChannelId" | "moveClient" | "sendTextMessage" | "poke" | "setAway" | "setInputMuted" | "setAccompanimentActive">;
|
||||
channelTree: ChannelInfo[];
|
||||
rememberChannelPassword?: (id: string, password: string) => void;
|
||||
members: ReadonlyMap<number, { uid?: string }>;
|
||||
whisperTargetIds: Set<number>;
|
||||
whisperActive: boolean;
|
||||
@@ -63,6 +64,7 @@ export async function handleCommand(
|
||||
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
|
||||
try {
|
||||
await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined);
|
||||
if (channelPassword) entry.rememberChannelPassword?.(rawId, channelPassword);
|
||||
} catch (error: unknown) {
|
||||
const rawMessage = error instanceof Error ? error.message : String(error);
|
||||
if (/already member/i.test(rawMessage)) {
|
||||
@@ -172,7 +174,7 @@ export async function handleCommand(
|
||||
|
||||
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const normalized = text.toLocaleLowerCase();
|
||||
const normalized = text.toLowerCase();
|
||||
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
|
||||
// is consulted before the keyword rules: 781 (channel password), 2568
|
||||
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
|
||||
|
||||
@@ -45,3 +45,14 @@ test("delegated voice session parser accepts only bounded TeamSpeak session data
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, nickname: "" }), null);
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, serverPassword: "x".repeat(513) }), null);
|
||||
});
|
||||
|
||||
|
||||
test("relay sessions retain invitation channel credentials and reject expired authorization", () => {
|
||||
const inviteExpiresAt=Date.now()+60000;
|
||||
const session={...payload,invitationTarget:{host:"original.example.com",port:9987},channelId:"9",channelPassword:"private",inviteExpiresAt};
|
||||
assert.deepEqual(parseDelegatedVoiceSession(session),session);
|
||||
assert.equal(parseDelegatedVoiceSession({...session,inviteExpiresAt:Date.now()-1}),null);
|
||||
assert.equal(parseDelegatedVoiceSession({...session,channelPassword:"x".repeat(513)}),null);
|
||||
assert.equal(parseDelegatedVoiceSession({...session,channelId:"0"}),null);
|
||||
assert.equal(parseDelegatedVoiceSession({...session,invitationTarget:{host:"http://bad",port:9987}}),null);
|
||||
});
|
||||
@@ -7,9 +7,13 @@ const MAX_NONCES = 10_000;
|
||||
|
||||
export interface DelegatedVoiceSession {
|
||||
target: TeamSpeakTarget;
|
||||
invitationTarget?: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
nickname: string;
|
||||
channel?: string;
|
||||
channelId?: string;
|
||||
channelPassword?: string;
|
||||
inviteExpiresAt?: number;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
}
|
||||
@@ -72,17 +76,29 @@ export function parseDelegatedVoiceSession(value: unknown): DelegatedVoiceSessio
|
||||
const { host, port } = value.target;
|
||||
if (typeof host !== "string" || host.length < 1 || host.length > 253 || /[\s\u0000-\u001f\u007f\/#@?]/.test(host)) return null;
|
||||
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
if (value.invitationTarget !== undefined) {
|
||||
const original = value.invitationTarget;
|
||||
if (!isRecord(original) || typeof original.host !== "string" || !original.host || original.host.length > 253 || /[\s\u0000-\u001f\u007f\/#@?]/.test(original.host)
|
||||
|| typeof original.port !== "number" || !Number.isInteger(original.port) || original.port < 1 || original.port > 65535) return null;
|
||||
}
|
||||
if (typeof value.serverPassword !== "string" || value.serverPassword.length > 512) return null;
|
||||
if (typeof value.nickname !== "string" || !value.nickname.trim() || value.nickname.length > 30) return null;
|
||||
if (value.channel !== undefined && (typeof value.channel !== "string" || value.channel.length > 100)) return null;
|
||||
if (value.inviteExpiresAt !== undefined && (typeof value.inviteExpiresAt !== "number" || !Number.isSafeInteger(value.inviteExpiresAt) || value.inviteExpiresAt <= Date.now())) return null;
|
||||
if (value.channelId !== undefined && (typeof value.channelId !== "string" || !/^[1-9]\d{0,19}$/.test(value.channelId))) return null;
|
||||
if (value.channelPassword !== undefined && (typeof value.channelPassword !== "string" || value.channelPassword.length > 512)) return null;
|
||||
if (value.identity !== undefined && (typeof value.identity !== "string" || value.identity.length > 8192)) return null;
|
||||
if (value.rememberIdentity !== undefined && typeof value.rememberIdentity !== "boolean") return null;
|
||||
|
||||
return {
|
||||
target: { host, port },
|
||||
...(isRecord(value.invitationTarget) ? { invitationTarget: { host: value.invitationTarget.host as string, port: value.invitationTarget.port as number } } : {}),
|
||||
serverPassword: value.serverPassword,
|
||||
nickname: value.nickname.trim(),
|
||||
...(typeof value.channel === "string" && value.channel ? { channel: value.channel } : {}),
|
||||
...(typeof value.inviteExpiresAt === "number" ? { inviteExpiresAt: value.inviteExpiresAt } : {}),
|
||||
...(typeof value.channelId === "string" ? { channelId: value.channelId } : {}),
|
||||
...(typeof value.channelPassword === "string" ? { channelPassword: value.channelPassword } : {}),
|
||||
...(typeof value.identity === "string" && value.identity ? { identity: value.identity } : {}),
|
||||
...(value.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { ScreenShareIceServer } from "./screen-share.js";
|
||||
|
||||
export interface VoiceGatewayServerOptions {
|
||||
workspaceInvites?: import("./workspace-invites.js").WorkspaceInvites;
|
||||
host: string;
|
||||
port: number;
|
||||
sharedToken: string;
|
||||
@@ -30,6 +31,7 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
|
||||
const verifier = new VoiceGatewayRequestVerifier();
|
||||
const voiceBridgeOptions: VoiceBridgeOptions = {
|
||||
joinTickets: tickets,
|
||||
...(options.workspaceInvites ? { createWorkspaceInvite: (credentials, minutes) => options.workspaceInvites!.create(credentials, minutes) } : {}),
|
||||
webRtc: options.webRtc,
|
||||
screenShareIceServers: options.screenShareIceServers,
|
||||
trustedProxies: options.trustedProxies,
|
||||
@@ -61,6 +63,19 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
|
||||
response.status(201).json({ ok: true, ticket: tickets.create(session) });
|
||||
});
|
||||
|
||||
app.post("/api/relay/workspace-invite", (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
const authenticated = verifier.verify(options.sharedToken, {
|
||||
timestamp: request.get("x-webspeak-relay-timestamp"), nonce: request.get("x-webspeak-relay-nonce"), signature: request.get("x-webspeak-relay-signature"),
|
||||
}, request.body);
|
||||
if (!authenticated) { response.status(401).json({ ok: false, code: "RELAY_AUTH_REJECTED" }); return; }
|
||||
const body = request.body;
|
||||
if (body?.purpose !== "workspace-invite" || typeof body.token !== "string" || !/^wi_[A-Za-z0-9_-]{43}$/.test(body.token)) { response.status(400).json({ ok: false }); return; }
|
||||
const access = options.workspaceInvites?.get(body.token);
|
||||
if (!access) { response.status(404).json({ ok: false }); return; }
|
||||
response.json({ ok: true, access });
|
||||
});
|
||||
|
||||
bridge.attach(server);
|
||||
|
||||
return {
|
||||
|
||||
@@ -116,6 +116,7 @@ function fixture() {
|
||||
closed: false, closePromise: null, audioTimer: null, activityTimer: undefined,
|
||||
pendingFrames: new Map([[1, []]]), memberVolumes: new Map([[1, 1]]),
|
||||
partialPcmByClient: new Map([[1, Buffer.alloc(2)]]), activeSpeakerIds: new Set([1]),
|
||||
decoderCodecByClient: new Map([[1, 4], [2, 5]]),
|
||||
decoderByClient: new Map([
|
||||
[1, { dispose() { released.push("decoder-1"); throw new Error("Decoder failed"); } }],
|
||||
[2, { dispose() { released.push("decoder-2"); } }],
|
||||
|
||||
+40
-10
@@ -11,13 +11,15 @@ import type { TSVoiceData } from "./ts-client.js";
|
||||
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
|
||||
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
const AUDIO_SAMPLE_RATE = 48_000;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const AUDIO_CHANNELS = 2;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
@@ -102,6 +104,7 @@ export class WebRtcAudioSession {
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private readonly decoderByClient = new Map<number, OpusEncoder>();
|
||||
private readonly decoderCodecByClient = new Map<number, 4 | 5>();
|
||||
private readonly partialPcmByClient = new Map<number, Buffer>();
|
||||
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
|
||||
private readonly memberVolumes = new Map<number, number>();
|
||||
@@ -198,7 +201,7 @@ export class WebRtcAudioSession {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
|
||||
});
|
||||
|
||||
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1));
|
||||
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, AUDIO_CHANNELS));
|
||||
try {
|
||||
this.encoder = createEncoder();
|
||||
} catch (error: unknown) {
|
||||
@@ -240,22 +243,37 @@ export class WebRtcAudioSession {
|
||||
this.outgoingPayloadType = opus[0]!.payloadType;
|
||||
await transceiver.sender.replaceTrack(this.outgoingTrack);
|
||||
const answer = await this.peer.createAnswer();
|
||||
await this.peer.setLocalDescription(answer);
|
||||
await this.peer.setLocalDescription({
|
||||
...answer,
|
||||
sdp: addOpusFmtpParameters(answer.sdp ?? "", ["stereo=1", "sprop-stereo=1"]),
|
||||
});
|
||||
const description = this.peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC answer was not created");
|
||||
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
|
||||
return { type: description.type, sdp: description.sdp };
|
||||
return {
|
||||
type: description.type,
|
||||
sdp: addOpusFmtpParameters(description.sdp, ["stereo=1", "sprop-stereo=1"]),
|
||||
};
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (decoder && this.decoderCodecByClient.get(data.clientId) !== data.codec) {
|
||||
try { decoder.dispose(); } catch { /* a codec transition must still reset queued PCM */ }
|
||||
this.decoderByClient.delete(data.clientId);
|
||||
this.decoderCodecByClient.delete(data.clientId);
|
||||
this.partialPcmByClient.delete(data.clientId);
|
||||
this.pendingFrames.delete(data.clientId);
|
||||
decoder = undefined;
|
||||
}
|
||||
if (!decoder) {
|
||||
try {
|
||||
// @discordjs/opus exposes decoding on OpusEncoder instances too;
|
||||
// there is no separate OpusDecoder constructor in that package.
|
||||
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, data.codec === 4 ? 1 : 2);
|
||||
this.decoderByClient.set(data.clientId, decoder);
|
||||
this.decoderCodecByClient.set(data.clientId, data.codec);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
|
||||
return;
|
||||
@@ -264,16 +282,26 @@ export class WebRtcAudioSession {
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
this.stats.webrtcDownlinkDecodedFrames++;
|
||||
if (pcm.length < 2) {
|
||||
const inputChannels = data.codec === 4 ? 1 : 2;
|
||||
if (pcm.length < inputChannels * 2 || pcm.length % (inputChannels * 2) !== 0) {
|
||||
this.stats.webrtcDownlinkShortFrames++;
|
||||
return;
|
||||
}
|
||||
let stereoPcm = pcm;
|
||||
if (inputChannels === 1) {
|
||||
stereoPcm = Buffer.allocUnsafe(pcm.length * AUDIO_CHANNELS);
|
||||
for (let inputOffset = 0, outputOffset = 0; inputOffset < pcm.length; inputOffset += 2, outputOffset += 4) {
|
||||
const sample = pcm.readInt16LE(inputOffset);
|
||||
stereoPcm.writeInt16LE(sample, outputOffset);
|
||||
stereoPcm.writeInt16LE(sample, outputOffset + 2);
|
||||
}
|
||||
}
|
||||
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||
// decoded frame per speaker and split every decoded buffer into the
|
||||
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
|
||||
// anything after the first 20 ms.
|
||||
const pendingPcm = this.partialPcmByClient.get(data.clientId);
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, stereoPcm]) : stereoPcm;
|
||||
const rms = this.calculateRms(pcm);
|
||||
// RMS is used only for the UI speaking indicator. Every decoded frame,
|
||||
// including quiet/comfort-noise frames, continues into the queue so the
|
||||
@@ -326,6 +354,7 @@ export class WebRtcAudioSession {
|
||||
this.closePromise = Promise.resolve().then(async () => {
|
||||
const decoders = [...this.decoderByClient.values()];
|
||||
this.decoderByClient.clear();
|
||||
this.decoderCodecByClient.clear();
|
||||
for (const decoder of decoders) {
|
||||
try { decoder.dispose(); } catch { /* continue releasing other resources */ }
|
||||
}
|
||||
@@ -368,13 +397,13 @@ export class WebRtcAudioSession {
|
||||
this.stats.webrtcQueueUnderrunTicks++;
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
if (!frame) continue;
|
||||
const volume = this.memberVolumes.get(clientId) ?? 1;
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
|
||||
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
|
||||
}
|
||||
}
|
||||
@@ -383,7 +412,7 @@ export class WebRtcAudioSession {
|
||||
// source packets with our encoded silence/mixes corrupts decoder history
|
||||
// and can suppress otherwise valid speech without any packet loss.
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
|
||||
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
|
||||
// the waveform's apparent loudness as the source level changes, which
|
||||
// is especially noticeable on music. Only clip actual overflow caused
|
||||
@@ -450,6 +479,7 @@ export class WebRtcAudioSession {
|
||||
const decoder = this.decoderByClient.get(clientId);
|
||||
if (!decoder) return;
|
||||
this.decoderByClient.delete(clientId);
|
||||
this.decoderCodecByClient.delete(clientId);
|
||||
try { decoder.dispose(); } catch { /* continue after codec cleanup failures */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import type { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export interface WorkspaceInviteCredentials {
|
||||
target: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
channelId: string;
|
||||
channelPassword: string;
|
||||
}
|
||||
export type WorkspaceInviteAccess = WorkspaceInviteCredentials & { expiresAt: number };
|
||||
const purpose = "webspeak:workspace-invite:v1";
|
||||
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
|
||||
/** Both normal and relay gateways keep invitation credentials in their own persistent data directory. */
|
||||
export class WorkspaceInvites {
|
||||
constructor(private readonly database: WebSpeakDatabase, private readonly key: Buffer) {}
|
||||
|
||||
create(credentials: WorkspaceInviteCredentials, expiresInMinutes: number, now = Date.now()): { token: string; expiresAt: number } {
|
||||
if (!Number.isInteger(expiresInMinutes) || expiresInMinutes < 1 || expiresInMinutes > 43200) throw new Error("INVALID_INVITE_EXPIRY");
|
||||
const token = "wi_" + randomBytes(32).toString("base64url");
|
||||
const expiresAt = now + expiresInMinutes * 60000;
|
||||
this.database.saveWorkspaceInvite(hash(token), encryptSecret(JSON.stringify({ ...credentials, expiresAt }), this.key, purpose), expiresAt, now);
|
||||
return { token, expiresAt };
|
||||
}
|
||||
|
||||
get(token: string, now = Date.now()): WorkspaceInviteAccess | null {
|
||||
if (!/^wi_[A-Za-z0-9_-]{43}$/.test(token)) return null;
|
||||
const encrypted = this.database.getWorkspaceInvite(hash(token), now);
|
||||
if (!encrypted) return null;
|
||||
try { return JSON.parse(decryptSecret(encrypted, this.key, purpose)) as WorkspaceInviteAccess; }
|
||||
catch { return null; }
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,52 @@ const tsAdminOverview = object({
|
||||
});
|
||||
const savedTsAdminSettings = object({ ok: choice(true), settings: tsAdminSettings });
|
||||
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
|
||||
const updateStep = object({
|
||||
name: text,
|
||||
status: choice("running", "succeeded", "failed"),
|
||||
at: text,
|
||||
detail: optional(text),
|
||||
});
|
||||
const updateTask = object({
|
||||
id: text,
|
||||
status: choice("downloading", "verifying", "extracting", "staging", "restarting", "succeeded", "failed"),
|
||||
fromVersion: text,
|
||||
targetVersion: text,
|
||||
startedAt: text,
|
||||
updatedAt: text,
|
||||
finishedAt: nullable(text),
|
||||
errorCode: nullable(text),
|
||||
errorMessage: nullable(text),
|
||||
rolledBack: boolean,
|
||||
steps: array(updateStep),
|
||||
});
|
||||
const updateDeployment = object({
|
||||
mode: choice("docker", "release-package", "source"),
|
||||
platform: text,
|
||||
architecture: text,
|
||||
applyAllowed: boolean,
|
||||
reasonCode: nullable(text),
|
||||
upgradePath: choice("docker-compose", "release-package", "source"),
|
||||
});
|
||||
const updateStatus = object({
|
||||
currentVersion: text,
|
||||
deployment: updateDeployment,
|
||||
task: nullable(updateTask),
|
||||
});
|
||||
const updateRelease = object({
|
||||
version: text,
|
||||
tag: text,
|
||||
publishedAt: text,
|
||||
releaseUrl: text,
|
||||
assetName: text,
|
||||
assetSize: number,
|
||||
assetAvailable: boolean,
|
||||
hasChecksums: boolean,
|
||||
digest: nullable(text),
|
||||
canApply: boolean,
|
||||
blockedReason: nullable(text),
|
||||
});
|
||||
const updateCheck = object({ currentVersion: text, releases: array(updateRelease) });
|
||||
|
||||
export const adminResponses = {
|
||||
session(value: unknown) {
|
||||
@@ -127,6 +173,9 @@ export const adminResponses = {
|
||||
latencyMs: number, serverName: nullable(text), requiresPassword: boolean,
|
||||
packetLossPercent: optional(number), attempts: optional(number), successfulAttempts: optional(number), errorCode: optional(text),
|
||||
}),
|
||||
updateStatus,
|
||||
updateCheck,
|
||||
updateApplied: object({ ok: choice(true), task: updateTask }),
|
||||
};
|
||||
|
||||
export type AdminSettings = ReturnType<typeof settings>;
|
||||
@@ -135,3 +184,7 @@ export type AdminSession = ReturnType<typeof session>;
|
||||
export type ManagedInvite = ReturnType<typeof invite>;
|
||||
export type AdminLog = ReturnType<typeof logEntry>;
|
||||
export type AdminConnectionRecord = ReturnType<typeof connection>;
|
||||
export type AdminUpdateTask = ReturnType<typeof updateTask>;
|
||||
export type AdminUpdateStatus = ReturnType<typeof updateStatus>;
|
||||
export type AdminUpdateCheck = ReturnType<typeof updateCheck>;
|
||||
export type AdminUpdateRelease = ReturnType<typeof updateRelease>;
|
||||
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user