mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cc43bb336 | ||
|
|
42d15c6d32 | ||
|
|
360126b14f | ||
|
|
047a40ac4b | ||
|
|
3430a8a753 | ||
|
|
275e27c4ac | ||
|
|
37f5b86b52 | ||
|
|
8bca848c21 | ||
|
|
ce681f749d |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: webspeak-plugin-development
|
||||
description: Build, review and package WebSpeak API v2 functional applications with standard browser code and optional Node services, including GitHub distribution. Use for .wplugin applications rather than .wskin skins or their presentation components.
|
||||
---
|
||||
|
||||
# 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.
|
||||
|
||||
For distribution use schema v2 catalog entries, matching manifest, raw-package SHA-256 and fixed refs. Publishing and deployment follow the user's task authorization; this skill does not itself authorize either.
|
||||
|
||||
## Floating host workspace
|
||||
|
||||
The host owns a skin-independent draggable launcher, application library and non-modal app window. Do not add launch controls to a particular skin or inspect its DOM. Apps render their responsive light/dark UI inside the supplied iframe; the host supplies dragging, minimize/maximize/restore and close controls. The host window uses the standard `color-scheme` for its light/dark fallback without inheriting skin component styles. Do not duplicate host window chrome or block the workspace with a page-wide modal backdrop.
|
||||
|
||||
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."
|
||||
@@ -29,3 +29,7 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
|
||||
|
||||
- `docs/SKIN_DEVELOPMENT.md` — the single current reference for skin formats, runtime APIs, permissions, data, actions, CSS hooks, security, and QA.
|
||||
- `docs/examples/ILLUSIA-VOICE.md` and `docs/examples/OPEN-VOICE-SURFACE.md` — full skin and surface examples.
|
||||
|
||||
## 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.0
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
|
||||
+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,145 @@
|
||||
<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.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0)** · [更新内容 / 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)
|
||||
- 日间、夜间、ILLUSIA、KAAK 与社区皮肤 / Day, Night, ILLUSIA, KAAK and community skins
|
||||
|
||||
</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,升级时保留它。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
|
||||
|
||||
Data persists in the `webspeak-data` volume. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
|
||||
|
||||
<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.0 中,提供独立于皮肤的悬浮应用入口。
|
||||
|
||||
Skins own appearance, layout and attached widgets. Functional plugin API v2 is included in v0.3.0 with a skin-independent floating application workspace.
|
||||
|
||||
## 社区 · 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` 分支重新实现并修复。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 · Лицензия · ライセンス
|
||||
</details>
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
## 许可证 · License
|
||||
|
||||
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.
|
||||
WebSpeak 使用 [AGPL-3.0-only](./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 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>
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
<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>
|
||||
|
||||
## Star History
|
||||
</details>
|
||||
|
||||
<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>
|
||||
|
||||
<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,152 @@
|
||||
# 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 为包原始字节哈希。宿主限制 GitHub 内容来源、核验哈希与 manifest;目录或安装修订改变会拒绝覆盖,需重新加载。空目录不默认安装插件。
|
||||
|
||||
验证实际构建包的导入、审核、启用、自定义 HTTP/WS、依赖加载、持久化和关闭/断线/禁用/更新撤销;检查明暗、语言、窄屏。协作另测两位真实参与者及并发/离开/重连。区分模拟身份、真实 TS、浏览器交互与跨网络证据。宿主回归:`npm run verify`。
|
||||
|
||||
## 悬浮应用窗口 / Floating application workspace
|
||||
|
||||
功能插件入口由宿主的独立悬浮层提供,不属于默认主题或任何皮肤插槽。入口可拖动,避免遮挡工作台控件。应用库和应用内容使用非模态窗口:打开后仍可操作工作台;标题栏可拖动,支持最小化、最大化、还原和关闭,小屏幕自动限制在可视区域内。宿主窗口优先读取标准 `color-scheme` 来选择日间/夜间配色,不继承皮肤组件样式。
|
||||
|
||||
最小化、切换到应用库、再返回当前应用均保留同一个 iframe 与会话,传输、播放等任务不会因收起窗口而重置。关闭窗口、切换至另一个应用或语音会话撤销时,宿主结束当前应用会话。当前同时承载一个前端应用;不要把窗口最小化当成退出事件。
|
||||
|
||||
应用只负责 iframe 内部内容,使用自身响应式日间/夜间样式和上下文中的主题、语言。不读取或改写皮肤 DOM,不绘制覆盖宿主的全屏遮罩,不自行重复宿主的标题栏、最小化和关闭按钮。需要自有导航时可在内容区实现。应用界面优先显示功能与实际状态,不重复运行环境、权限或免责说明;管理员启用时的信任与权限信息保留在管理流程中。
|
||||
|
||||
## 实例级用户授权
|
||||
|
||||
首次访问时,宿主统一征求第三方皮肤与功能应用的使用授权;决定按浏览器源保存,不迁移旧的逐皮肤授权。拒绝或未选择时,只显示日间、夜间、ILLUSIA 三款官方皮肤,KAAK 和功能应用入口均隐藏。皮肤菜单最后的“授权”可随时更改。撤回会关闭 iframe 并撤销当前打开操作/应用会话,不停止管理员启用的全实例后台服务。应用不得以入口以外的方式绕过宿主授权,也无需重复询问同一份宿主上下文授权;相机、麦克风等浏览器原生许可仍由浏览器处理。
|
||||
+260
-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.0](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Mit Plugin-API v2, schwebenden Anwendungen und gemeinsamer Instanzberechtigung.
|
||||
|
||||
|
||||
|
||||
[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,91 @@ 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.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 +393,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 +485,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>
|
||||
+252
-128
@@ -1,50 +1,165 @@
|
||||
# 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.0 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Includes plugin API v2, floating applications and unified instance authorization.
|
||||
|
||||
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:
|
||||
|
||||
```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.
|
||||
|
||||
### 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 +170,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 +209,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 +286,91 @@ 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.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 +393,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 +485,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>
|
||||
+269
-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.0 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。API v2、フローティングアプリ、インスタンス単位の許可に対応。
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
| **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,45 @@ 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.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 +328,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 +400,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>
|
||||
+267
-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.0](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). API v2, плавающие приложения и единое разрешение для экземпляра.
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
| **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,45 @@ 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.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 +328,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 +400,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>
|
||||
+252
-128
@@ -1,50 +1,165 @@
|
||||
# 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.0 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。包含功能插件 API v2、悬浮应用界面和实例统一授权。
|
||||
|
||||
## 在线 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>
|
||||
|
||||
<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
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```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 范围。
|
||||
|
||||
### 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 +170,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 +211,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 +290,91 @@ 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.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 +397,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 +489,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>
|
||||
@@ -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 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
|
||||
|
||||
## 目标:皮肤是可移植的外挂包
|
||||
|
||||
@@ -522,3 +522,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.
+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.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"version": "0.3.0",
|
||||
"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.0",
|
||||
"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.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.9",
|
||||
"version": "0.3.0",
|
||||
"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"
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.9",
|
||||
"version": "0.3.0",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test 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/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts",
|
||||
"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",
|
||||
@@ -26,11 +26,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}`);
|
||||
+28
-11
@@ -8,6 +8,10 @@ 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";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
@@ -38,7 +42,11 @@ export interface AdminRouterOptions {
|
||||
logFile?: string;
|
||||
skinRegistry?: SkinRegistry;
|
||||
skinStore?: SkinStore;
|
||||
pluginRegistry?: PluginRegistry;
|
||||
pluginStore?: PluginStore;
|
||||
pluginRuntime?: PluginRuntime;
|
||||
startedAt: number;
|
||||
clientIp?: (request: Request) => string;
|
||||
}
|
||||
|
||||
export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
@@ -85,25 +93,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 +125,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 +139,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(
|
||||
@@ -792,7 +809,7 @@ 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" });
|
||||
|
||||
@@ -45,6 +45,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 +76,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 +86,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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,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);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -45,6 +46,8 @@ 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");
|
||||
|
||||
@@ -70,6 +73,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(),
|
||||
|
||||
+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,
|
||||
|
||||
@@ -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,98 @@
|
||||
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);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'&&manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
|
||||
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
|
||||
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
|
||||
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
|
||||
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
|
||||
}
|
||||
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,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,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,78 @@
|
||||
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); pluginAssert(JSON.stringify(pack.manifest) === JSON.stringify(metadata.manifest), "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 {
|
||||
|
||||
@@ -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";
|
||||
|
||||
+27
-10
@@ -3,7 +3,7 @@ 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 { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
|
||||
@@ -18,6 +18,9 @@ import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import { 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";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -28,6 +31,8 @@ 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;
|
||||
@@ -55,11 +60,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, 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) => {
|
||||
@@ -160,7 +171,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;
|
||||
}
|
||||
@@ -273,9 +284,12 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
skinRegistry: options.skinRegistry,
|
||||
pluginRegistry: options.pluginRegistry,
|
||||
pluginRuntime,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
clientIp,
|
||||
}));
|
||||
|
||||
// Serve static frontend
|
||||
@@ -289,15 +303,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) => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 } : {}),
|
||||
|
||||
@@ -595,9 +595,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 {
|
||||
|
||||
@@ -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,7 @@ function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>):
|
||||
}
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
pluginRuntimeEnabled?: boolean;
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
|
||||
@@ -107,6 +109,7 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
lastAudioStatsProbeAt: number;
|
||||
connectionFailureCode?: string;
|
||||
screenPeerId: string;
|
||||
pluginSession?: string;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
@@ -319,6 +322,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 +334,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 });
|
||||
@@ -492,7 +497,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({
|
||||
@@ -700,6 +707,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 +1005,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;
|
||||
|
||||
@@ -172,7 +172,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
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/** Portable application runtime v2. Independent of skins and their component APIs. */
|
||||
export const PLUGIN_API_VERSION = 2;
|
||||
export const PLUGIN_STORE_REPOSITORY = "https://github.com/Huddle-Up-Forge/webspeak-plugin";
|
||||
export const PLUGIN_STORE_INDEX = "https://raw.githubusercontent.com/Huddle-Up-Forge/webspeak-plugin/main/index.json";
|
||||
export const PLUGIN_LIMIT_BYTES = 48 * 1024 * 1024;
|
||||
export const PLUGIN_CONTENT_LIMIT_BYTES = 32 * 1024 * 1024;
|
||||
export const PLUGIN_FILE_LIMIT_BYTES = 16 * 1024 * 1024;
|
||||
export const pluginId = (v: unknown): v is string => typeof v === "string" && /^[a-z0-9][a-z0-9.-]{0,79}$/.test(v);
|
||||
export const pluginRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
export type PluginScope = "server" | "instance";
|
||||
export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
|
||||
export interface PluginManifest {
|
||||
apiVersion: 2; id: string; name: string; version: string; author: string; license: string; description: string;
|
||||
scopes: PluginScope[]; client: { entry: string }; server?: { entry: string };
|
||||
}
|
||||
export interface PluginFile { encoding: "utf8" | "base64"; data: string }
|
||||
export interface PluginPackage { manifest: PluginManifest; files: Record<string, PluginFile> }
|
||||
export interface PluginSettings { enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
|
||||
export interface PluginSettingsInput {
|
||||
enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
|
||||
serverConfigAction?: "keep" | "replace" | "remove"; serverConfig?: JsonValue;
|
||||
}
|
||||
export interface PluginRuntimeStatus { state: "disabled" | "client" | "stopped" | "starting" | "running" | "failed"; error?: string }
|
||||
export interface InstalledPlugin { manifest: PluginManifest; settings: PluginSettings; revision: string; installedAt: number; runtime?: PluginRuntimeStatus }
|
||||
export interface PluginStoreEntry { id: string; repository: string; metadataPath: string; manifest: PluginManifest | null; revision: string; error: string | null }
|
||||
export interface PluginCatalog { repository: string; entries: PluginStoreEntry[] }
|
||||
/** Public context, never a TS private identity, voice socket or administrator credential. */
|
||||
export interface PluginParticipant {
|
||||
id: string; nickname: string; uid?: string; target: string; channelId: string;
|
||||
members: { id: number; nickname: string; uid?: string }[];
|
||||
}
|
||||
export interface PluginRequestContext {
|
||||
apiVersion: 2; appId: string; self: { id: string; nickname: string; uid?: string };
|
||||
connection: { target: string; channelId: string };
|
||||
scope: { type: PluginScope; key: string };
|
||||
}
|
||||
export interface PluginAppContext extends PluginRequestContext {
|
||||
plugin: PluginManifest;
|
||||
connection: PluginRequestContext["connection"] & { members: PluginParticipant["members"] };
|
||||
config: JsonValue;
|
||||
theme: "light" | "dark"; language: "zh" | "en" | "de" | "ru" | "ja";
|
||||
serverUrl: string | null; socketUrl: string | null; contextUrl: string;
|
||||
}
|
||||
export interface PluginAppLaunch { id: string; url: string; manifest: PluginManifest }
|
||||
export interface PluginRuntimeSettings { publicOrigin: string; port: number; available: boolean; revision: string }
|
||||
export class PluginError extends Error { constructor(readonly code: string) { super(code); this.name = "PluginError"; } }
|
||||
export function pluginAssert(v: unknown, code = "PLUGIN_INVALID"): asserts v { if (!v) throw new PluginError(code); }
|
||||
export function pluginPath(v: unknown): v is string {
|
||||
return typeof v === "string" && v.length > 0 && v.length <= 500 && v.split("/").every(s =>
|
||||
/^[A-Za-z0-9._@+~-]+$/.test(s) && s !== "." && s !== ".." && !s.endsWith(".") && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(s));
|
||||
}
|
||||
export function parsePluginManifest(v: unknown): PluginManifest {
|
||||
pluginAssert(pluginRecord(v)); pluginAssert(v.apiVersion === PLUGIN_API_VERSION, "PLUGIN_API_UNSUPPORTED"); pluginAssert(pluginId(v.id));
|
||||
for (const [key,max] of [["name",80],["author",80],["license",80],["description",400],["version",32]] as const)
|
||||
pluginAssert(typeof v[key] === "string" && v[key].trim().length > 0 && v[key].length <= max && !/[\u0000-\u001f\u007f]/.test(v[key]));
|
||||
pluginAssert(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(v.version as string));
|
||||
pluginAssert(Array.isArray(v.scopes) && v.scopes.length > 0 && v.scopes.length <= 2 && new Set(v.scopes).size === v.scopes.length && v.scopes.every(s => s === "server" || s === "instance"));
|
||||
pluginAssert(v.permissions === undefined, "PLUGIN_API_UNSUPPORTED");
|
||||
pluginAssert(pluginRecord(v.client) && pluginPath(v.client.entry) && v.client.entry.startsWith("client/") && v.client.entry.endsWith(".html"));
|
||||
let server: { entry: string } | undefined;
|
||||
if (v.server !== undefined) { pluginAssert(pluginRecord(v.server) && pluginPath(v.server.entry) && v.server.entry.startsWith("server/") && /\.(?:mjs|cjs)$/.test(v.server.entry)); server = {entry:v.server.entry}; }
|
||||
return {apiVersion:2,id:v.id,name:v.name as string,version:v.version as string,author:v.author as string,license:v.license as string,description:v.description as string,scopes:[...v.scopes],client:{entry:v.client.entry},...(server?{server}:{})};
|
||||
}
|
||||
export function pluginFileSize(file: PluginFile): number {
|
||||
return file.encoding === "utf8" ? new TextEncoder().encode(file.data).length : file.data.length / 4 * 3 - (file.data.endsWith("==") ? 2 : file.data.endsWith("=") ? 1 : 0);
|
||||
}
|
||||
export function pluginFileBytes(file: PluginFile): Uint8Array { return file.encoding === "utf8" ? new TextEncoder().encode(file.data) : Uint8Array.from(atob(file.data), c => c.charCodeAt(0)); }
|
||||
export function parsePluginPackage(v: unknown): PluginPackage {
|
||||
pluginAssert(pluginRecord(v)); const manifest = parsePluginManifest(v.manifest); pluginAssert(pluginRecord(v.files)); const entries = Object.entries(v.files);
|
||||
pluginAssert(entries.length > 0 && entries.length <= 4096);
|
||||
const files: Record<string,PluginFile> = Object.create(null), names = new Set<string>(); let total = 0;
|
||||
for (const [name,file] of entries) {
|
||||
pluginAssert(pluginPath(name) && (name.startsWith("client/") || name.startsWith("server/")) && !names.has(name.toLowerCase())); names.add(name.toLowerCase());
|
||||
pluginAssert(pluginRecord(file) && (file.encoding === "utf8" || file.encoding === "base64") && typeof file.data === "string" && file.data.length <= PLUGIN_LIMIT_BYTES);
|
||||
if (file.encoding === "base64") pluginAssert(file.data.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(file.data));
|
||||
const content: PluginFile = {encoding:file.encoding,data:file.data}; const size = pluginFileSize(content);
|
||||
pluginAssert(size <= PLUGIN_FILE_LIMIT_BYTES && (total += size) <= PLUGIN_CONTENT_LIMIT_BYTES,"PLUGIN_TOO_LARGE"); files[name] = content;
|
||||
}
|
||||
for (const name of names) for (let i=name.indexOf("/");i>=0;i=name.indexOf("/",i+1)) pluginAssert(!names.has(name.slice(0,i)));
|
||||
pluginAssert(files[manifest.client.entry]?.encoding === "utf8"); if (manifest.server) pluginAssert(files[manifest.server.entry]?.encoding === "utf8");
|
||||
const result = {manifest,files}; pluginAssert(new TextEncoder().encode(JSON.stringify(result)).length <= PLUGIN_LIMIT_BYTES,"PLUGIN_TOO_LARGE"); return result;
|
||||
}
|
||||
export function parsePluginJson(v: unknown, maxBytes = 64 * 1024): JsonValue {
|
||||
let count = 0;
|
||||
function visit(item: unknown, depth: number): void {
|
||||
pluginAssert(depth <= 64 && ++count <= 100000);
|
||||
if (item === null || typeof item === "boolean" || typeof item === "string") return;
|
||||
if (typeof item === "number") { pluginAssert(Number.isFinite(item)); return; }
|
||||
pluginAssert(Array.isArray(item) || pluginRecord(item));
|
||||
if (Array.isArray(item)) item.forEach(child=>visit(child,depth+1));
|
||||
else for (const [key,child] of Object.entries(item)) { pluginAssert(!["__proto__","prototype","constructor"].includes(key)); visit(child,depth+1); }
|
||||
}
|
||||
visit(v,0); const json=JSON.stringify(v); pluginAssert(new TextEncoder().encode(json).length <= maxBytes,"PLUGIN_TOO_LARGE"); return JSON.parse(json) as JsonValue;
|
||||
}
|
||||
export function readInstalledPlugin(v: unknown): InstalledPlugin {
|
||||
pluginAssert(pluginRecord(v) && pluginRecord(v.settings) && typeof v.revision === "string" && /^[a-f0-9]{64}$/.test(v.revision) && typeof v.installedAt === "number" && Number.isFinite(v.installedAt));
|
||||
const manifest=parsePluginManifest(v.manifest),s=v.settings;
|
||||
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
|
||||
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
|
||||
if(v.runtime!==undefined){pluginAssert(pluginRecord(v.runtime) && ["disabled","client","stopped","starting","running","failed"].includes(String(v.runtime.state)) && (v.runtime.error===undefined||typeof v.runtime.error==="string"));result.runtime={state:v.runtime.state as PluginRuntimeStatus["state"],...(v.runtime.error?{error:v.runtime.error as string}:{})};}
|
||||
return result;
|
||||
}
|
||||
export const pluginResponses = {
|
||||
runtime(v:unknown):{runtime:PluginRuntimeSettings}{
|
||||
pluginAssert(pluginRecord(v)&&pluginRecord(v.runtime));const r=v.runtime;
|
||||
pluginAssert(typeof r.publicOrigin==='string'&&r.publicOrigin.length<=300&&typeof r.available==='boolean'&&typeof r.port==='number'&&Number.isInteger(r.port)&&r.port>=0&&r.port<=65535&&typeof r.revision==='string'&&/^[a-f0-9]{64}$/.test(r.revision));
|
||||
return {runtime:{publicOrigin:r.publicOrigin,port:r.port,available:r.available,revision:r.revision}};
|
||||
},
|
||||
installed(v: unknown): {plugins:InstalledPlugin[]} {pluginAssert(pluginRecord(v)&&Array.isArray(v.plugins)&&v.plugins.length<=50);return {plugins:v.plugins.map(readInstalledPlugin)};},
|
||||
saved(v: unknown): {plugin:InstalledPlugin} {pluginAssert(pluginRecord(v));return {plugin:readInstalledPlugin(v.plugin)};},
|
||||
catalog(v: unknown): PluginCatalog {
|
||||
pluginAssert(pluginRecord(v)&&v.repository===PLUGIN_STORE_REPOSITORY&&Array.isArray(v.entries)&&v.entries.length<=50);
|
||||
const entries=v.entries.map(e=>{pluginAssert(pluginRecord(e)&&pluginId(e.id)&&typeof e.repository==="string"&&/^https:\/\/github\.com\/[a-zA-Z0-9-]+\/[a-zA-Z0-9_.-]+$/.test(e.repository)&&typeof e.metadataPath==="string"&&typeof e.revision==="string"&&(e.error===null||typeof e.error==="string"));return {id:e.id,repository:e.repository,metadataPath:e.metadataPath,revision:e.revision,error:e.error,manifest:e.manifest===null?null:parsePluginManifest(e.manifest)};});return {repository:v.repository,entries};
|
||||
},
|
||||
};
|
||||
@@ -12,7 +12,7 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
|
||||
|
||||
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
|
||||
export type ServerMessage =
|
||||
| Message<"connected", { tsClientId: number; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
|
||||
| Message<"memberEnter", ChannelMember>
|
||||
| Message<"memberLeave", { id: number }>
|
||||
@@ -135,7 +135,7 @@ export function parseScreenShareStream(value: unknown): ScreenShareStreamDescrip
|
||||
}
|
||||
|
||||
const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> = {
|
||||
connected: m => clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
|
||||
connected: m => optional(m.pluginSession, v => text(v) && /^[A-Za-z0-9_-]{43}$/.test(v)) && clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
|
||||
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
|
||||
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
|
||||
serverInfo: m => text(m.name) && m.name.length <= 256
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.2.9'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 209
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.0'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 300
|
||||
|
||||
android {
|
||||
namespace = "io.webspeak.client"
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content" />
|
||||
<meta name="theme-color" content="#006a64" />
|
||||
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
||||
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
|
||||
<link rel="icon" type="image/jpeg" href="/webspeak-icon.jpg" />
|
||||
<title>WebSpeak · TeamSpeak Web Client</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Generated
+4
-2
@@ -24,7 +24,8 @@
|
||||
"typescript": "~5.7.0",
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
},
|
||||
"version": "0.3.0"
|
||||
},
|
||||
"node_modules/@babel/helper-string-parser": {
|
||||
"version": "7.27.1",
|
||||
@@ -2950,5 +2951,6 @@
|
||||
"fd-slicer": "~1.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "0.3.0"
|
||||
}
|
||||
+2
-1
@@ -26,5 +26,6 @@
|
||||
"typescript": "~5.7.0",
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
},
|
||||
"version": "0.3.0"
|
||||
}
|
||||
File renamed without changes.
@@ -18,6 +18,9 @@
|
||||
<rect x="4" y="14" width="16" height="7" rx="1.5" />
|
||||
<path d="M8 6.5h.01M8 17.5h.01M11 6.5h5M11 17.5h5" />
|
||||
</template>
|
||||
<template v-else-if="name === 'grid'">
|
||||
<rect x="3" y="3" width="7" height="7" rx="1.5" /><rect x="14" y="3" width="7" height="7" rx="1.5" /><rect x="3" y="14" width="7" height="7" rx="1.5" /><rect x="14" y="14" width="7" height="7" rx="1.5" />
|
||||
</template>
|
||||
<template v-else-if="name === 'compass'">
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="m15.5 8.5-2.2 4.8-4.8 2.2 2.2-4.8z" />
|
||||
@@ -69,6 +72,7 @@
|
||||
<path v-else-if="name === 'paperclip'" d="m20 11-7.5 7.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-7.5 7.5a2 2 0 0 1-3-3L14 7" />
|
||||
<path v-else-if="name === 'share'" d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7M16 6l-4-4-4 4m4-4v13" />
|
||||
<path v-else-if="name === 'copy'" d="M8 8V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3M6 8h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2Z" />
|
||||
<path v-else-if="name === 'trash'" d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7" />
|
||||
<path v-else-if="name === 'close'" d="m6 6 12 12M18 6 6 18" />
|
||||
<path v-else-if="name === 'more'" d="M5 12h.01M12 12h.01M19 12h.01" stroke-width="3" />
|
||||
<path v-else-if="name === 'menu'" d="M4 6h16M4 12h16M4 18h16" />
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<dialog ref="dialog" class="ws-instance-authorization" @cancel.prevent="cancel" @close="authorizationRequested = false">
|
||||
<form @submit.prevent="save">
|
||||
<div class="ws-authorization-mark" aria-hidden="true">◈</div>
|
||||
<h2>{{ copy.title }}</h2>
|
||||
<p>{{ copy.description }}</p>
|
||||
<p>{{ copy.alternative }}</p>
|
||||
<label><input v-model="checked" type="checkbox" /><span>{{ copy.choice }}</span></label>
|
||||
<footer>
|
||||
<button type="button" @click="decline">{{ copy.decline }}</button>
|
||||
<button class="ws-authorization-primary" type="submit" :disabled="firstVisit && !checked">{{ firstVisit ? copy.accept : copy.save }}</button>
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
const props = defineProps<{ language: SiteLanguage }>();
|
||||
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
|
||||
const copy = computed(() => instanceAuthorizationCopy[props.language]);
|
||||
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
|
||||
watch([dialog, authorizationRequested, authorizationDecision], () => {
|
||||
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
|
||||
firstVisit.value = authorizationDecision.value === null;
|
||||
checked.value = authorizationDecision.value === true;
|
||||
dialog.value.showModal();
|
||||
}, { flush: 'post' });
|
||||
function finish() { authorizationRequested.value = false; dialog.value?.close(); }
|
||||
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
|
||||
function decline() { setInstanceAuthorization(false); finish(); }
|
||||
function cancel() { if (firstVisit.value) decline(); else finish(); }
|
||||
onBeforeUnmount(() => dialog.value?.close());
|
||||
</script>
|
||||
<style>
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:14px/1.75 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto}
|
||||
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
|
||||
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
|
||||
</style>
|
||||
@@ -0,0 +1,163 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
|
||||
<button ref="launcher" class="ws-plugin-launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<span>{{ tr('title') }}</span><i v-if="current" />
|
||||
</button>
|
||||
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
|
||||
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
|
||||
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
|
||||
<div class="ws-plugin-window-title"><strong>{{ current && appView ? current.manifest.name : tr('title') }}</strong><small>WebSpeak</small></div>
|
||||
<div class="ws-plugin-window-controls" @pointerdown.stop @dblclick.stop>
|
||||
<button type="button" :title="ui.minimize" :aria-label="ui.minimize" @click="minimize"><svg viewBox="0 0 24 24"><path d="M5 17h14" /></svg></button>
|
||||
<button type="button" :title="maximized ? ui.restore : ui.maximize" :aria-label="maximized ? ui.restore : ui.maximize" @click="toggleMaximize"><svg viewBox="0 0 24 24"><path :d="maximized ? 'M8 4h12v12M4 8h12v12H4z' : 'M5 5h14v14H5z'" /></svg></button>
|
||||
<button class="ws-plugin-close" type="button" :title="tr('close')" :aria-label="tr('close')" @click="close"><svg viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" /></svg></button>
|
||||
</div>
|
||||
</header>
|
||||
<nav class="ws-plugin-navigation" :aria-label="tr('title')">
|
||||
<button type="button" :class="{ active: !appView }" @click="appView = false">{{ ui.workspace }}</button>
|
||||
<button v-if="current" type="button" :class="{ active: appView }" @click="appView = true">{{ current.manifest.name }}</button>
|
||||
<span v-if="current && appView" class="ws-plugin-version">v{{ current.manifest.version }}</span>
|
||||
</nav>
|
||||
<p v-if="error" role="alert" class="ws-plugin-error">{{ error }}</p>
|
||||
<div v-show="!appView" class="ws-plugin-library">
|
||||
<div class="ws-plugin-library-heading"><div><h2>{{ tr('title') }}</h2><span>{{ available.length }} {{ ui.count }}</span></div><button type="button" :disabled="busy" @click="refresh">{{ busy ? tr('loading') : tr('refresh') }}</button></div>
|
||||
<input v-model="search" class="ws-plugin-search" type="search" :placeholder="ui.search" :aria-label="ui.search" />
|
||||
<p v-if="!busy && !filtered.length" class="ws-plugin-empty">{{ available.length ? ui.noResults : tr('empty') }}</p>
|
||||
<div class="ws-plugin-grid">
|
||||
<article v-for="entry in filtered" :key="entry.manifest.id" class="ws-plugin-entry">
|
||||
<div class="ws-plugin-app-mark" aria-hidden="true">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</div>
|
||||
<div class="ws-plugin-entry-copy"><h3>{{ entry.manifest.name }}</h3><small>v{{ entry.manifest.version }} · {{ entry.scope === 'server' ? tr('server') : tr('instance') }}</small><p>{{ entry.manifest.description }}</p></div>
|
||||
<p v-if="entry.runtime.state === 'failed'" class="ws-plugin-entry-error">{{ entry.runtime.error }}</p>
|
||||
<button type="button" :disabled="busy || entry.runtime.state === 'failed'" @click="launch(entry.manifest.id)">{{ tr('open') }} <span aria-hidden="true">↗</span></button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="appView && current" class="ws-plugin-browser">
|
||||
<iframe v-if="current" ref="frame" :key="current.id" :title="current.manifest.name" :src="current.url" :allow="browserFeatures" referrerpolicy="no-referrer"></iframe>
|
||||
</div>
|
||||
<div v-if="dragging" class="ws-plugin-drag-shield" />
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
|
||||
import { createPluginAppClient, type AvailablePluginApp, type PluginAppClient } from '../services/plugin-app-client.js';
|
||||
import { type PluginAppLaunch, pluginRecord } from '../../../src/shared/plugins.js';
|
||||
import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
|
||||
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage }>();
|
||||
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
|
||||
const ui = computed(() => pluginWindowTranslations[props.language]);
|
||||
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
|
||||
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
|
||||
const busy = ref(false), error = ref(''), theme = ref<'light' | 'dark'>('light');
|
||||
const visible = ref(false), maximized = ref(false), appView = ref(false), dragging = ref(false), search = ref('');
|
||||
const position = ref<Record<string, string>>({});
|
||||
const launcherPosition = ref<Record<string, string>>({});
|
||||
const filtered = computed(() => available.value.filter(entry => `${entry.manifest.name} ${entry.manifest.description}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())));
|
||||
let epoch = 0, pending: AbortController | undefined, opening: { client: PluginAppClient; key: string } | undefined, observer: MutationObserver | undefined;
|
||||
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; kind: 'window' | 'launcher'; moved: boolean } | undefined;
|
||||
let suppressLauncherClick = false, resizeObserver: ResizeObserver | undefined;
|
||||
const browserFeatures = computed(() => {
|
||||
const policy = (document as Document & { featurePolicy?: { features(): string[] } }).featurePolicy;
|
||||
const features = policy?.features() ?? ['fullscreen', 'autoplay', 'camera', 'microphone', 'display-capture', 'clipboard-read', 'clipboard-write', 'geolocation', 'screen-wake-lock'];
|
||||
return features.filter(feature => /^[a-z0-9-]+$/.test(feature)).map(feature => feature + ' *').join('; ');
|
||||
});
|
||||
function detectTheme() {
|
||||
const root = document.querySelector('.ws-skin-root');
|
||||
const style = getComputedStyle(root ?? document.documentElement);
|
||||
if (style.colorScheme === 'dark' || style.colorScheme === 'light') { theme.value = style.colorScheme; return; }
|
||||
const color = root ? style.color.match(/[\d.]+/g)?.map(Number) : null;
|
||||
theme.value = color && color.length >= 3 ? (color[0] * .2126 + color[1] * .7152 + color[2] * .0722 > 140 ? 'dark' : 'light') : matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
function client() { return createPluginAppClient(props.gatewayUrl, props.sessionToken); }
|
||||
async function refresh() {
|
||||
if (!thirdPartyAllowed.value) return;
|
||||
const owner = ++epoch; pending?.abort(); const controller = new AbortController(); pending = controller; busy.value = true; error.value = '';
|
||||
try { const entries = await client().list(controller.signal); if (owner === epoch) available.value = entries; }
|
||||
catch (e) { if (owner === epoch && !controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
|
||||
}
|
||||
function toggle() {
|
||||
if (suppressLauncherClick) { suppressLauncherClick = false; return; }
|
||||
if (visible.value) { minimize(); return; }
|
||||
detectTheme(); visible.value = true;
|
||||
if (!current.value) { appView.value = false; void refresh(); }
|
||||
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
|
||||
}
|
||||
function minimize() { endDrag(); visible.value = false; launcher.value?.focus(); }
|
||||
function close() { stop(); error.value = ''; available.value = []; search.value = ''; minimize(); }
|
||||
function stop() {
|
||||
++epoch; pending?.abort(); pending = undefined; const old = opening; opening = undefined; current.value = null; appView.value = false; busy.value = false;
|
||||
if (old) void old.client.cancelOpen(old.key).catch(() => undefined);
|
||||
}
|
||||
async function launch(id: string) {
|
||||
if (!thirdPartyAllowed.value) return;
|
||||
if (current.value?.manifest.id === id) { appView.value = true; return; }
|
||||
stop(); const owner = ++epoch, controller = new AbortController(), service = client(), key = crypto.randomUUID(); pending = controller; opening = { client: service, key }; busy.value = true; error.value = '';
|
||||
try {
|
||||
const app = await service.open(id, { openId: key, theme: theme.value, language: props.language }, controller.signal);
|
||||
if (owner !== epoch) return;
|
||||
if (new URL(app.url).origin === location.origin) throw new Error('PLUGIN_SEPARATE_ORIGIN_REQUIRED');
|
||||
current.value = app; appView.value = true;
|
||||
} catch (e) {
|
||||
if (owner === epoch) { const old = opening; opening = undefined; if (old) void old.client.cancelOpen(old.key).catch(() => undefined); if (!controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
} finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
|
||||
}
|
||||
function message(event: MessageEvent) {
|
||||
if (!current.value || event.source !== frame.value?.contentWindow || event.origin !== new URL(current.value.url).origin || !pluginRecord(event.data)) return;
|
||||
if (event.data.type === 'webspeak-app-closed' && event.data.id === current.value.id) { stop(); error.value = tr('context'); }
|
||||
}
|
||||
function appearance() { if (current.value && opening) void opening.client.appearance(current.value.id, theme.value, props.language).catch(() => undefined); }
|
||||
function fitWindow() {
|
||||
if (launcher.value && launcherPosition.value.left) {
|
||||
const box = launcher.value.getBoundingClientRect();
|
||||
launcherPosition.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, right: 'auto', bottom: 'auto' };
|
||||
}
|
||||
if (!visible.value || maximized.value || !windowElement.value) return;
|
||||
const box = windowElement.value.getBoundingClientRect();
|
||||
position.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, transform: 'none' };
|
||||
}
|
||||
function toggleMaximize() { endDrag(); maximized.value = !maximized.value; if (!maximized.value) void nextTick(fitWindow); }
|
||||
function startDrag(event: PointerEvent) {
|
||||
if (event.button !== 0 || maximized.value || (event.target as HTMLElement).closest('button')) return;
|
||||
const box = windowElement.value?.getBoundingClientRect(); if (!box) return;
|
||||
event.preventDefault(); const handle = event.currentTarget as HTMLElement;
|
||||
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, kind: 'window', moved: false }; dragging.value = true;
|
||||
handle.setPointerCapture(event.pointerId);
|
||||
}
|
||||
function startLauncherDrag(event: PointerEvent) {
|
||||
if (event.button !== 0 || !launcher.value) return;
|
||||
const box = launcher.value.getBoundingClientRect(); suppressLauncherClick = false;
|
||||
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle: launcher.value, kind: 'launcher', moved: false };
|
||||
launcher.value.setPointerCapture(event.pointerId);
|
||||
}
|
||||
function moveDrag(event: PointerEvent) {
|
||||
if (!drag || drag.id !== event.pointerId) return;
|
||||
const target = drag.kind === 'launcher' ? launcher.value : windowElement.value; if (!target) return;
|
||||
if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5 && !drag.moved) return;
|
||||
drag.moved = true; const box = target.getBoundingClientRect();
|
||||
const next = { left: `${Math.max(8, Math.min(drag.left + event.clientX - drag.x, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(drag.top + event.clientY - drag.y, innerHeight - box.height - 8))}px`, transform: 'none' };
|
||||
if (drag.kind === 'launcher') launcherPosition.value = { ...next, right: 'auto', bottom: 'auto' }; else position.value = next;
|
||||
}
|
||||
function endDrag() {
|
||||
const old = drag; drag = undefined; dragging.value = false;
|
||||
if (old?.kind === 'launcher' && old.moved) suppressLauncherClick = true;
|
||||
if (old?.handle.hasPointerCapture(old.id)) old.handle.releasePointerCapture(old.id);
|
||||
}
|
||||
watch(windowElement, element => { resizeObserver?.disconnect(); if (element) { resizeObserver = new ResizeObserver(fitWindow); resizeObserver.observe(element); } });
|
||||
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, close);
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) close(); }, { flush: 'sync' });
|
||||
watch(() => props.language, appearance); watch(theme, appearance);
|
||||
onMounted(() => {
|
||||
detectTheme(); window.addEventListener('message', message); window.addEventListener('resize', fitWindow); window.addEventListener('pointermove', moveDrag); window.addEventListener('pointerup', endDrag); window.addEventListener('pointercancel', endDrag); window.addEventListener('blur', endDrag);
|
||||
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
|
||||
});
|
||||
onBeforeUnmount(() => { stop(); endDrag(); observer?.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('message', message); window.removeEventListener('resize', fitWindow); window.removeEventListener('pointermove', moveDrag); window.removeEventListener('pointerup', endDrag); window.removeEventListener('pointercancel', endDrag); window.removeEventListener('blur', endDrag); });
|
||||
</script>
|
||||
<style src="../styles/plugin-overlay.css"></style>
|
||||
@@ -20,6 +20,7 @@ import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui
|
||||
import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js";
|
||||
import { createSkinPluginAssetUrlCache } from "../services/skin-plugin-asset-urls.js";
|
||||
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
|
||||
import { canUseSkin, openInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
|
||||
type Scalar = string | number | boolean;
|
||||
@@ -108,14 +109,14 @@ export default defineComponent({
|
||||
const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page));
|
||||
const pendingApproval = computed(() => {
|
||||
refresh.value;
|
||||
return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
return denied.value || !canUseSkin(props.skinId) ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
});
|
||||
const accessComponents = computed(() => pendingApproval.value.length
|
||||
? pendingApproval.value
|
||||
: matchingComponents.value.filter((component) => component.permissions.length > 0));
|
||||
const activeComponents = computed(() => {
|
||||
refresh.value;
|
||||
return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component));
|
||||
return canUseSkin(props.skinId) ? matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) : [];
|
||||
});
|
||||
const surfaceCandidate = computed(() => activeComponents.value.find((component) => component.mode === "surface") ?? null);
|
||||
const activeSurface = computed(() => surfaceSuppressed.value ? null : surfaceCandidate.value);
|
||||
@@ -220,7 +221,7 @@ export default defineComponent({
|
||||
|
||||
function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record<string, Scalar>): void {
|
||||
const definition = component.actions[actionId];
|
||||
if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
if (!definition || !canUseSkin(props.skinId) || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
const args = resolveActionArgs(definition, context, state);
|
||||
if (definition.type === "ui.setState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) {
|
||||
@@ -244,7 +245,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function dispatchRuntimeCallback(component: SkinPluginComponent, handlerId: string, eventName: string, event: Event, state: Record<string, Scalar>): void {
|
||||
if (!component.runtimeCallbacks) return;
|
||||
if (!canUseSkin(props.skinId) || !component.runtimeCallbacks) return;
|
||||
const callbackEvent: Record<string, unknown> = { componentId: component.id, handlerId, eventName };
|
||||
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) callbackEvent.key = event.key;
|
||||
const mayReadUserInput = props.extensionPermissions.includes("ui.input.read");
|
||||
@@ -419,8 +420,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function openAccessManager(): void {
|
||||
denied.value = false;
|
||||
manageOpen.value = true;
|
||||
openInstanceAuthorization();
|
||||
}
|
||||
|
||||
function closeOrDisable(): void {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-r
|
||||
import SkinPluginOutlet from "./SkinPluginOutlet.js";
|
||||
import { approveSkinRuntimePlugin, getSkinRuntimePluginApproval, revokeSkinRuntimePluginApprovals } from "../services/skin-runtime-plugin-approval.js";
|
||||
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
|
||||
import { canUseSkin, openInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
import { createSkinRuntimePluginSession } from "../services/skin-runtime-plugin-session.js";
|
||||
import { createSkinRuntimePluginWasmSandbox } from "../services/skin-runtime-plugin-wasm.js";
|
||||
@@ -63,6 +64,7 @@ function createRun(
|
||||
skinVersion,
|
||||
plugin,
|
||||
approval,
|
||||
signal: abortController.signal,
|
||||
files,
|
||||
uiInput: input,
|
||||
context,
|
||||
@@ -133,6 +135,7 @@ export default defineComponent({
|
||||
|
||||
const pagePlugins = computed(() => props.plugins?.plugins.filter((plugin) => plugin.page === props.page) ?? []);
|
||||
const approved = (plugin: SkinRuntimePlugin): SkinRuntimePluginApproval | null => {
|
||||
if (!canUseSkin(props.skinId)) return null;
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) return null;
|
||||
const memoryGrant = inMemoryApprovals.get(plugin.id);
|
||||
@@ -243,6 +246,7 @@ export default defineComponent({
|
||||
await handler(action.args);
|
||||
},
|
||||
onOutput: () => {
|
||||
if (!canUseSkin(props.skinId) || disposed || sessions.get(plugin.id) !== session) return;
|
||||
installStyle(plugin);
|
||||
outputs.value = { ...outputs.value, [plugin.id]: session.output };
|
||||
digestErrors.value = { ...digestErrors.value, [plugin.id]: "" };
|
||||
@@ -257,6 +261,7 @@ export default defineComponent({
|
||||
|
||||
function reconcile(): void {
|
||||
if (disposed) return;
|
||||
if (!canUseSkin(props.skinId)) { stopAll('instance-authorization-revoked'); return; }
|
||||
const currentIds = new Set(pagePlugins.value.map((plugin) => plugin.id));
|
||||
for (const pluginId of [...sessions.keys()]) if (!currentIds.has(pluginId)) stopPlugin(pluginId, "page-changed");
|
||||
for (const plugin of pagePlugins.value) {
|
||||
@@ -266,6 +271,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function approvePending(): void {
|
||||
if (!canUseSkin(props.skinId)) return;
|
||||
for (const plugin of pending.value) {
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) continue;
|
||||
@@ -294,7 +300,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function openManager(): void {
|
||||
managerOpen.value = true;
|
||||
openInstanceAuthorization();
|
||||
}
|
||||
|
||||
function dispatch(pluginId: string, value: unknown): void {
|
||||
@@ -342,6 +348,10 @@ export default defineComponent({
|
||||
}, { immediate: true });
|
||||
|
||||
watch(() => [props.page, digests.value, revision.value], reconcile, { deep: true });
|
||||
watch(() => canUseSkin(props.skinId), allowed => {
|
||||
if (!allowed) { stopAll('instance-authorization-revoked'); managerOpen.value = false; }
|
||||
else approvePending();
|
||||
}, { flush: 'sync' });
|
||||
watch(editorMode.isEnabled, (enabled) => { if (!enabled) managerOpen.value = false; });
|
||||
watch(() => props.context, () => {
|
||||
if (disposed) return;
|
||||
|
||||
@@ -35,6 +35,9 @@
|
||||
<span>{{ option.label }}</span>
|
||||
<Icon v-if="modelValue === option.value" name="check" :size="14" />
|
||||
</button>
|
||||
<button type="button" class="skin-option skin-authorization" role="option" :aria-selected="false" @click="authorization">
|
||||
<Icon name="shield" :size="16" /><span>{{ authorizationCopy.menu }}</span><small>{{ thirdPartyAllowed ? authorizationCopy.enabled : authorizationCopy.disabled }}</small>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -42,6 +45,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
import { authorizationLanguage, canUseSkin, openInstanceAuthorization, thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
|
||||
export interface SkinOption {
|
||||
value: string;
|
||||
@@ -60,7 +65,9 @@ const emit = defineEmits<{
|
||||
change: [value: string];
|
||||
}>();
|
||||
|
||||
const options = computed(() => props.options);
|
||||
const options = computed(() => props.options.filter(option => canUseSkin(option.value)));
|
||||
const authorizationCopy = computed(() => instanceAuthorizationCopy[authorizationLanguage.value]);
|
||||
function authorization() { close(); openInstanceAuthorization(); }
|
||||
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0] ?? {
|
||||
value: props.modelValue,
|
||||
label: props.menuLabel,
|
||||
@@ -92,6 +99,8 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
|
||||
flex: 0 0 auto;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.skin-authorization{margin-top:6px;border-top:1px solid #8bdad8!important}
|
||||
.skin-authorization small{margin-left:auto;font-size:10px;opacity:.75}
|
||||
|
||||
.skin-trigger {
|
||||
display: inline-flex;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<template>
|
||||
<section class="page-content plugin-admin">
|
||||
<header class="plugin-hero">
|
||||
<div><span class="plugin-eyebrow"><Icon name="grid" :size="14" /> APPS</span><h2>{{ tr('store') }}</h2><p>{{ tr('lead') }}</p><div class="plugin-metrics"><span><b>{{ model.catalog.value?.entries.length ?? '—' }}</b>{{ text('available') }}</span><i></i><span><b>{{ model.installed.value.length }}</b>{{ tr('installed') }}</span><i></i><span><b>{{ enabledCount }}</b>{{ text('active') }}</span></div></div>
|
||||
<div class="plugin-hero-art" aria-hidden="true"><i></i><i></i><i></i><i></i><b>+</b></div>
|
||||
</header>
|
||||
<details class="plugin-runtime-settings"><summary><Icon name="server" :size="16" />{{ tr('runtime') }}<span class="plugin-status" :class="{active:model.runtime.value?.available}"><i></i>{{ tr(model.runtime.value?.available?'running':'stopped') }} · {{ model.runtime.value?.port ?? '—' }}</span></summary><p>{{ tr('originHelp') }}</p><form @submit.prevent="model.saveRuntime"><label>{{ tr('origin') }}<input v-model="model.origin.value" type="url" placeholder="https://apps.example.com" :disabled="model.busy.value" /></label><button class="plugin-button primary" type="submit" :disabled="model.busy.value || !model.runtime.value">{{ tr('save') }}</button></form></details>
|
||||
<div class="plugin-toolbar">
|
||||
<nav class="plugin-tabs" :aria-label="tr('store')"><button type="button" :aria-current="tab==='store'?'page':undefined" @click="tab='store'"><Icon name="compass" :size="16" />{{ text('discover') }}</button><button type="button" :aria-current="tab==='installed'?'page':undefined" @click="tab='installed'"><Icon name="grid" :size="16" />{{ tr('installed') }}<span>{{ model.installed.value.length }}</span></button></nav>
|
||||
<div class="plugin-tools"><label class="plugin-search"><Icon name="search" :size="16" /><input v-model="search" type="search" :aria-label="text('search')" :placeholder="text('search')" /></label><button class="plugin-refresh" type="button" :disabled="model.busy.value" :title="tr('refresh')" :aria-label="tr('refresh')" @click="model.load"><Icon name="refresh" :size="17" /></button></div>
|
||||
</div>
|
||||
<p v-if="model.error.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('error') }}: {{ model.error.value }}</p>
|
||||
<p v-if="tab==='store' && model.catalogError.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('catalogError') }} · {{ model.catalogError.value }}</p>
|
||||
<p v-if="notice" class="plugin-feedback" role="status"><Icon name="check" :size="17" />{{ notice }}</p>
|
||||
<div class="plugin-section-heading"><div><h3>{{ tab==='store'?text('discover'):tr('installed') }}</h3><span v-if="tab==='store'" class="plugin-source"><i></i>{{ text('source') }}</span></div><a v-if="tab==='store'" :href="PLUGIN_STORE_REPOSITORY" target="_blank" rel="noopener noreferrer"><Icon name="github" :size="16" />GitHub ↗</a><button v-else class="plugin-button" type="button" :disabled="model.busy.value" @click="fileInput?.click()"><Icon name="share" :size="15" />{{ tr('upload') }}</button></div>
|
||||
<input ref="fileInput" class="plugin-file-input" type="file" accept=".wplugin,application/json" @change="upload" />
|
||||
<p v-if="model.busy.value" class="plugin-loading" role="status"><span class="spinner small"></span>{{ tr('loading') }}</p>
|
||||
<div v-if="tab==='store'" class="plugin-store-grid">
|
||||
<article v-for="entry in catalogEntries" :key="entry.id" class="plugin-market-card">
|
||||
<div class="plugin-card-visual"><div class="plugin-card-symbol"><Icon name="grid" :size="38" /></div><span>API {{ entry.manifest?.apiVersion ?? '—' }}</span><i aria-hidden="true"></i></div>
|
||||
<div class="plugin-card-body"><div class="plugin-card-title"><h4>{{ entry.manifest?.name ?? entry.id }}</h4><small>v{{ entry.manifest?.version ?? '—' }}</small></div><p class="plugin-author">{{ entry.manifest?.author }} · {{ entry.manifest?.license }}</p><p class="plugin-description">{{ entry.manifest?.description }}</p><div class="plugin-tags"><span v-for="scope in entry.manifest?.scopes" :key="scope"><Icon name="server" :size="12" />{{ tr(scope) }}</span></div><div class="plugin-permissions"><span>{{ tr('client') }}</span><span v-if="entry.manifest?.server">{{ tr('backend') }}</span></div><p v-if="entry.error" class="is-error">{{ entry.error }}</p></div>
|
||||
<footer><a :href="entry.repository" target="_blank" rel="noopener noreferrer" :aria-label="`${entry.manifest?.name ?? entry.id} · GitHub`"><Icon name="github" :size="16" />GitHub ↗</a><button class="plugin-button primary" type="button" :disabled="model.busy.value || !entry.manifest || !!entry.error" @click="install(entry)"><Icon name="download" :size="15" />{{ installLabel(entry) }}</button></footer>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else class="plugin-installed-list">
|
||||
<article v-for="plugin in installedEntries" :key="plugin.manifest.id" class="plugin-installed-card">
|
||||
<header><div class="plugin-installed-icon"><Icon name="grid" :size="23" /></div><div class="plugin-installed-name"><h4>{{ plugin.manifest.name }}</h4><p>v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}</p></div><span class="plugin-status" :class="{active:plugin.settings.enabled}"><i></i>{{ tr(plugin.runtime?.state ?? 'disabled') }}</span></header>
|
||||
<p class="plugin-description">{{ plugin.manifest.description }}</p><p v-if="plugin.runtime?.error" class="is-error" role="alert">{{ plugin.runtime.error }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span></div>
|
||||
<details :open="expanded===plugin.manifest.id" @toggle="onToggle($event,plugin.manifest.id)"><summary><Icon name="settings" :size="16" />{{ text('configure') }}<Icon class="plugin-chevron" name="chevron-down" :size="15" /></summary><fieldset :disabled="model.busy.value">
|
||||
<div class="plugin-enable-row"><div><strong>{{ tr('enabled') }}</strong><p>{{ text('review') }}</p></div><label class="plugin-switch"><input v-model="model.drafts[plugin.manifest.id].enabled" type="checkbox" :aria-label="tr('enabled')" /><span></span></label></div>
|
||||
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].trusted" type="checkbox" />{{ tr('trust') }}</label><p class="plugin-trust-note">{{ tr('enableNote') }}</p>
|
||||
<label>{{ tr('scope') }}<select v-model="model.drafts[plugin.manifest.id].scope"><option v-for="scope in plugin.manifest.scopes" :key="scope" :value="scope">{{ tr(scope) }}</option></select></label>
|
||||
<label v-if="model.drafts[plugin.manifest.id].scope==='server'">{{ tr('targets') }}<textarea v-model="model.drafts[plugin.manifest.id].targets" rows="3" maxlength="15000" placeholder="voice.example.com:9987"></textarea></label>
|
||||
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="65536" spellcheck="false"></textarea></label><template v-if="plugin.manifest.server"><label>{{ tr('privateConfig') }}<small>{{ tr(plugin.settings.hasServerConfig?'secretSaved':'secretEmpty') }}</small><select v-model="model.drafts[plugin.manifest.id].serverConfigAction"><option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option></select><textarea v-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace'" v-model="model.drafts[plugin.manifest.id].serverConfig" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" autocapitalize="off" autocorrect="off"></textarea></label></template></details>
|
||||
<div class="plugin-settings-actions"><button v-if="plugin.manifest.server" class="plugin-button" type="button" :disabled="!plugin.settings.enabled" @click="model.restart(plugin)">{{ tr('restart') }}</button><button class="plugin-button danger" type="button" @click="remove(plugin)"><Icon name="trash" :size="14" />{{ tr('remove') }}</button><button class="plugin-button primary" type="button" @click="save(plugin)"><Icon name="check" :size="15" />{{ tr('save') }}</button></div>
|
||||
</fieldset></details>
|
||||
</article>
|
||||
</div>
|
||||
<div v-if="!model.busy.value && !(tab==='store'?catalogEntries.length:installedEntries.length)" class="plugin-empty"><Icon name="grid" :size="32" /><h4>{{ search?text('empty'):tr('empty') }}</h4></div>
|
||||
<details class="plugin-scope-help"><summary><Icon name="info" :size="16" />{{ text('scopeHelp') }}<Icon name="chevron-down" :size="14" /></summary><p>{{ tr('note') }}</p><p>{{ tr('enableNote') }}</p></details>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import Icon from '../Icon.vue';
|
||||
import type { SiteLanguage } from '../../../../src/site-copy.js';
|
||||
import { PLUGIN_STORE_REPOSITORY, type InstalledPlugin, type PluginStoreEntry, type PluginManifest } from '../../../../src/shared/plugins.js';
|
||||
import type { useAdminPlugins } from '../../composables/useAdminPlugins.js';
|
||||
import { pluginTranslations, type PluginTextKey } from '../../i18n/plugins.js';
|
||||
import { pluginStoreTranslations, type PluginStoreTextKey } from '../../i18n/plugin-store.js';
|
||||
const props=defineProps<{model:ReturnType<typeof useAdminPlugins>;language:SiteLanguage}>();
|
||||
const tr=(key:PluginTextKey)=>pluginTranslations[props.language][key],text=(key:PluginStoreTextKey)=>pluginStoreTranslations[props.language][key];
|
||||
const tab=ref<'store'|'installed'>('store'),search=ref(''),expanded=ref(''),notice=ref(''),fileInput=ref<HTMLInputElement|null>(null);
|
||||
const enabledCount=computed(()=>props.model.installed.value.filter(p=>p.settings.enabled).length);
|
||||
const matches=(manifest:PluginManifest|null,id:string)=>[manifest?.name,manifest?.author,manifest?.description,id].join(' ').toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase());
|
||||
const catalogEntries=computed(()=>(props.model.catalog.value?.entries??[]).filter(e=>matches(e.manifest,e.id)));
|
||||
const installedEntries=computed(()=>props.model.installed.value.filter(p=>matches(p.manifest,p.manifest.id)));
|
||||
function installLabel(entry:PluginStoreEntry){const local=props.model.installed.value.find(p=>p.manifest.id===entry.id);return !local?text('add'):local.manifest.version===entry.manifest?.version?text('reinstall'):text('update');}
|
||||
async function install(entry:PluginStoreEntry){notice.value='';await props.model.install(entry);if(!props.model.error.value){tab.value='installed';expanded.value=entry.id;notice.value=text('installedNotice');}}
|
||||
async function upload(event:Event){const input=event.target as HTMLInputElement,file=input.files?.[0];if(file){notice.value='';await props.model.upload(file);if(!props.model.error.value){tab.value='installed';notice.value=text('installedNotice');}}input.value='';}
|
||||
async function save(plugin:InstalledPlugin){notice.value='';await props.model.save(plugin);}
|
||||
function remove(plugin:InstalledPlugin){if(window.confirm(tr('removed'))){notice.value='';void props.model.remove(plugin);}}
|
||||
function onToggle(event:Event,id:string){if((event.target as HTMLDetailsElement).open)expanded.value=id;else if(expanded.value===id)expanded.value='';}
|
||||
</script>
|
||||
<style scoped>
|
||||
section.page-content.plugin-admin{display:grid;grid-template-columns:minmax(0,1fr);grid-auto-rows:max-content;align-content:start;gap:24px;color:var(--admin-text);min-width:0}
|
||||
.plugin-admin :is(h2,h3,h4,p){margin:0}.plugin-admin :is(button,input,select,textarea){font:inherit}.plugin-admin button{cursor:pointer}.plugin-admin button:disabled{opacity:.5;cursor:wait}
|
||||
.plugin-hero{position:relative;display:flex;align-items:center;justify-content:space-between;gap:28px;overflow:hidden;padding:32px;border:1px solid var(--admin-border);border-radius:20px;background:radial-gradient(ellipse at 100% 0,color-mix(in srgb,var(--admin-accent) 12%,transparent),transparent 65%),var(--admin-surface)}
|
||||
.plugin-hero>div:first-child{z-index:1;max-width:640px}.plugin-eyebrow{display:flex;align-items:center;gap:8px;font-size:10px;font-weight:800;letter-spacing:.16em;color:var(--admin-accent);margin-bottom:14px}.plugin-hero h2{font-size:30px;letter-spacing:-.04em}.plugin-hero p{font-size:13px;line-height:1.8;color:var(--admin-muted);max-width:560px;margin-top:12px}
|
||||
.plugin-metrics{display:flex;align-items:center;gap:20px;margin-top:24px;flex-wrap:wrap}.plugin-metrics>span{display:flex;align-items:center;gap:9px;font-size:11px;color:var(--admin-muted)}.plugin-metrics b{font-size:20px;color:var(--admin-text);font-variant-numeric:tabular-nums}.plugin-metrics>i{height:17px;width:1px;background:var(--admin-border)}
|
||||
.plugin-hero-art{position:relative;display:grid;grid-template-columns:1fr 1fr;gap:10px;width:130px;flex:0 0 130px;transform:rotate(-8deg);margin:8px 12px}.plugin-hero-art i{aspect-ratio:1;border-radius:15px;border:1px solid color-mix(in srgb,var(--admin-accent) 22%,var(--admin-border));background:var(--admin-accent-soft);box-shadow:0 8px 18px #0001}.plugin-hero-art i:nth-child(2){transform:translate(10px,-10px);background:var(--admin-accent);opacity:.8}.plugin-hero-art i:nth-child(3){opacity:.5}.plugin-hero-art b{position:absolute;right:-15px;bottom:-12px;display:grid;place-items:center;width:44px;height:44px;border-radius:50%;font-size:25px;background:var(--admin-surface);color:var(--admin-accent)}
|
||||
.plugin-toolbar,.plugin-tools,.plugin-tabs{display:flex;align-items:center;gap:12px;min-width:0}.plugin-toolbar{justify-content:space-between;flex-wrap:wrap}.plugin-tabs{gap:4px;padding:4px;background:var(--admin-raised);border:1px solid var(--admin-border);border-radius:12px}.plugin-tabs button{display:flex;align-items:center;gap:8px;min-height:40px;border:0;border-radius:8px;padding:9px 15px;background:transparent;color:var(--admin-muted);font-size:12px;font-weight:650}.plugin-tabs button[aria-current]{color:var(--admin-accent);background:var(--admin-surface);box-shadow:0 1px 5px #0001}.plugin-tabs button>span{min-width:18px;border-radius:5px;padding:0 5px;background:var(--admin-accent-soft);font-size:10px}
|
||||
.plugin-search{display:flex;gap:8px;align-items:center;padding:0 12px;border:1px solid var(--admin-border);border-radius:10px;background:var(--admin-surface);color:var(--admin-muted)}.plugin-search input{width:200px;min-width:0;border:0!important;outline:none;background:transparent!important;color:var(--admin-text);height:42px;font-size:12px;padding:0!important;box-shadow:none!important}.plugin-search:focus-within{outline:2px solid color-mix(in srgb,var(--admin-accent) 35%,transparent)}.plugin-refresh{display:grid;place-items:center;width:44px;height:44px;padding:0;border:1px solid var(--admin-border);border-radius:10px;background:var(--admin-surface);color:var(--admin-muted)}
|
||||
.plugin-section-heading,.plugin-section-heading>div{display:flex;align-items:center;gap:14px;justify-content:space-between;flex-wrap:wrap}.plugin-section-heading h3{font-size:15px}.plugin-section-heading a,.plugin-market-card footer a{display:flex;gap:7px;align-items:center;font-size:11px;color:var(--admin-muted);text-decoration:none}.plugin-source{display:flex;align-items:center;gap:6px;font-size:10px;color:var(--admin-muted)}.plugin-source i,.plugin-status i{height:6px;width:6px;flex:none;border-radius:50%;background:#7c9790}.plugin-source i{background:var(--admin-accent)}
|
||||
.plugin-store-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(300px,100%),1fr));gap:20px;align-items:start}.plugin-market-card{display:flex;flex-direction:column;max-width:460px;min-width:0;border:1px solid var(--admin-border);border-radius:16px;background:var(--admin-surface);overflow:hidden;transition:border-color .2s,transform .2s}.plugin-market-card:hover{transform:translateY(-3px);border-color:color-mix(in srgb,var(--admin-accent) 50%,var(--admin-border))}
|
||||
.plugin-card-visual{position:relative;display:grid;place-items:center;height:142px;overflow:hidden;background:linear-gradient(130deg,var(--admin-accent-soft),var(--admin-raised))}.plugin-card-symbol{display:grid;place-items:center;width:76px;height:76px;border:1px solid color-mix(in srgb,var(--admin-accent) 20%,var(--admin-border));background:var(--admin-surface);border-radius:21px;color:var(--admin-accent);transform:rotate(-8deg);box-shadow:0 8px 20px #0001;z-index:1}.plugin-card-visual>span{position:absolute;top:14px;right:14px;padding:4px 7px;border:1px solid var(--admin-border);border-radius:6px;font-size:9px;font-weight:700;background:var(--admin-surface);color:var(--admin-muted)}.plugin-card-visual>i{position:absolute;border:1px solid color-mix(in srgb,var(--admin-accent) 15%,transparent);border-radius:50%;width:260px;height:260px;left:-65px;top:-95px}.plugin-card-visual>i:after{content:'';position:absolute;inset:24px;border:inherit;border-radius:inherit}
|
||||
.plugin-card-body{padding:22px;display:grid;gap:12px}.plugin-card-title{display:flex;align-items:start;justify-content:space-between;gap:10px}.plugin-card-title h4{font-size:16px;line-height:1.4;letter-spacing:-.025em;overflow-wrap:anywhere}.plugin-card-title small{flex:none;font-size:10px;color:var(--admin-muted);padding-top:3px}.plugin-author{color:var(--admin-muted);font-size:10px}.plugin-description{font-size:12px;line-height:1.75;color:var(--admin-muted);overflow-wrap:anywhere}.plugin-tags,.plugin-permissions{display:flex;gap:7px;flex-wrap:wrap}.plugin-tags>span{display:inline-flex;align-items:center;gap:5px;padding:5px 7px;font-size:9px;border:1px solid var(--admin-border);border-radius:6px;color:var(--admin-muted)}.plugin-permissions>span{display:inline-flex;align-items:center;gap:5px;font-size:10px;color:var(--admin-accent)}.plugin-market-card footer{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:15px 22px;border-top:1px solid var(--admin-border);background:var(--admin-raised)}
|
||||
.plugin-button{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:38px;border:1px solid var(--admin-border);border-radius:8px;padding:9px 13px;font-size:11px;font-weight:650;color:var(--admin-text);background:var(--admin-surface)}.plugin-button.primary{border-color:transparent;color:var(--admin-surface);background:var(--admin-accent)}.plugin-button.danger{color:#c95c5c;background:transparent;border-color:transparent}.plugin-file-input{display:none}.plugin-feedback{display:flex;gap:10px;align-items:center;border:1px solid var(--admin-border);border-radius:10px;padding:12px 16px;color:var(--admin-accent);background:var(--admin-accent-soft);font-size:12px;overflow-wrap:anywhere}.plugin-admin .is-error{color:#cf6565}.plugin-loading{display:flex;gap:10px;align-items:center;color:var(--admin-muted);font-size:12px}
|
||||
.plugin-installed-list{display:grid;gap:16px}.plugin-installed-card{background:var(--admin-surface);border:1px solid var(--admin-border);border-radius:16px;overflow:hidden;min-width:0}.plugin-installed-card>header{display:flex;align-items:center;gap:13px;padding:22px 24px 12px}.plugin-installed-icon{display:grid;place-items:center;flex:none;width:48px;height:48px;background:var(--admin-accent-soft);color:var(--admin-accent);border:1px solid var(--admin-border);border-radius:13px}.plugin-installed-name{flex:1;min-width:0}.plugin-installed-name h4{font-size:15px;overflow-wrap:anywhere}.plugin-installed-name p{color:var(--admin-muted);font-size:10px;margin-top:5px}.plugin-status{display:flex;align-items:center;gap:6px;padding:5px 8px;font-size:10px;border:1px solid var(--admin-border);border-radius:20px;color:var(--admin-muted);flex:none}.plugin-status.active{background:var(--admin-accent-soft);color:var(--admin-accent)}.plugin-status.active i{background:var(--admin-accent)}.plugin-installed-card>.plugin-description{padding:0 24px}.plugin-installed-meta{display:flex;gap:14px;flex-wrap:wrap;padding:14px 24px 20px;font-size:10px;color:var(--admin-muted)}.plugin-installed-meta>span{display:flex;align-items:center;gap:6px}
|
||||
.plugin-installed-card>details{border-top:1px solid var(--admin-border)}.plugin-installed-card>details>summary{display:flex;gap:8px;align-items:center;padding:15px 24px;list-style:none;cursor:pointer;color:var(--admin-muted);font-size:12px}.plugin-chevron{margin-left:auto;transition:transform .2s}details[open]>summary .plugin-chevron{transform:rotate(180deg)}summary::-webkit-details-marker{display:none}.plugin-installed-card fieldset{display:grid;gap:18px;min-width:0;margin:0;padding:6px 24px 24px;border:0}.plugin-enable-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:16px;background:var(--admin-raised);border:1px solid var(--admin-border);border-radius:10px}.plugin-enable-row strong{font-size:12px}.plugin-enable-row p{font-size:10px;color:var(--admin-muted);margin-top:4px}
|
||||
.plugin-switch{position:relative;flex:none;display:block;width:36px;height:21px}.plugin-switch input{position:absolute;inset:0;opacity:0;margin:0;z-index:1;cursor:pointer;width:100%;height:100%}.plugin-switch>span{display:block;height:21px;border-radius:20px;background:var(--admin-border);transition:background .2s}.plugin-switch>span:after{content:'';display:block;position:absolute;left:3px;top:3px;width:15px;height:15px;border-radius:50%;background:white;transition:transform .2s}.plugin-switch input:checked+span{background:var(--admin-accent)}.plugin-switch input:checked+span:after{transform:translateX(15px)}.plugin-switch input:focus-visible+span{outline:3px solid color-mix(in srgb,var(--admin-accent) 35%,transparent);outline-offset:3px}
|
||||
.plugin-installed-card fieldset>label,.plugin-advanced label{display:grid;gap:8px;color:var(--admin-muted);font-size:11px}.plugin-installed-card textarea,.plugin-installed-card select{width:100%;min-width:0;max-width:100%;border:1px solid var(--admin-border);padding:10px 12px;border-radius:8px;background:var(--admin-field);color:var(--admin-text);font-size:12px}.plugin-installed-card textarea{resize:vertical;line-height:1.7}.plugin-advanced{border:1px solid var(--admin-border);border-radius:9px;padding:0 12px}.plugin-advanced summary{display:flex;align-items:center;justify-content:space-between;font-size:11px;color:var(--admin-muted);padding:12px 0;cursor:pointer}.plugin-advanced label{padding-bottom:12px}.plugin-advanced textarea{font-family:ui-monospace,monospace}.plugin-settings-actions{display:flex;justify-content:space-between;gap:12px;padding-top:4px}.plugin-scope-help{margin-top:8px;border-top:1px solid var(--admin-border);padding-top:20px;color:var(--admin-muted);font-size:11px}.plugin-scope-help summary{display:flex;gap:8px;align-items:center;cursor:pointer;width:fit-content}.plugin-scope-help p{line-height:1.8;margin-top:12px;max-width:850px}.plugin-empty{display:grid;justify-items:center;gap:16px;padding:60px 20px;color:var(--admin-muted);text-align:center;border:1px dashed var(--admin-border);border-radius:16px}.plugin-empty h4{font-size:14px}.plugin-admin :is(button,a,input,textarea,select,summary):focus-visible{outline:3px solid color-mix(in srgb,var(--admin-accent) 35%,transparent);outline-offset:3px}
|
||||
@media(max-width:1100px){.plugin-hero-art{width:100px;flex-basis:100px;margin-right:0}.plugin-hero{padding:26px}.plugin-tools{flex:1;justify-content:end}.plugin-search{flex:1;max-width:320px}.plugin-search input{width:100%}}
|
||||
@media(max-width:600px){.plugin-admin{gap:18px}.plugin-hero{padding:24px 20px;border-radius:16px}.plugin-hero h2{font-size:25px}.plugin-hero p{font-size:12px}.plugin-hero-art{position:absolute;width:110px;right:-28px;top:-35px;opacity:.12}.plugin-metrics{gap:12px}.plugin-metrics>span{gap:6px;font-size:10px}.plugin-metrics b{font-size:18px}.plugin-tabs,.plugin-tools{width:100%}.plugin-tabs button{flex:1;justify-content:center;padding:8px 10px}.plugin-search{max-width:none}.plugin-section-heading>div{gap:8px}.plugin-section-heading h3{font-size:14px}.plugin-source{font-size:9px}.plugin-card-body{padding:18px}.plugin-market-card{max-width:none}.plugin-installed-card>header{padding:18px 16px 12px;flex-wrap:wrap;gap:10px}.plugin-installed-icon{width:40px;height:40px}.plugin-installed-name h4{font-size:13px}.plugin-status{font-size:9px}.plugin-installed-card>.plugin-description,.plugin-installed-meta{padding-left:16px;padding-right:16px}.plugin-installed-card>details>summary{padding:14px 16px}.plugin-installed-card fieldset{padding:4px 16px 16px}.plugin-enable-row{padding:12px}}
|
||||
.plugin-runtime-settings{border:1px solid var(--admin-border);border-radius:14px;background:var(--admin-surface);padding:18px}.plugin-runtime-settings>summary{display:flex;align-items:center;gap:12px;cursor:pointer;font-weight:650}.plugin-runtime-settings>p{margin:16px 0;color:var(--admin-muted);font-size:12px;line-height:1.7}.plugin-runtime-settings form{display:flex;align-items:end;gap:14px;flex-wrap:wrap}.plugin-runtime-settings label{display:grid;flex:1;gap:8px;font-size:12px;min-width:min(100%,260px)}.plugin-runtime-settings input{width:100%;box-sizing:border-box;border:1px solid var(--admin-border);border-radius:9px;padding:10px;background:var(--admin-raised);color:var(--admin-text)}.plugin-trust{display:flex!important;align-items:start!important;gap:10px!important;font-weight:650}.plugin-trust input{width:auto!important;margin-top:3px;flex:none}.plugin-trust-note{font-size:12px;color:var(--admin-muted);line-height:1.7}.plugin-advanced label>small{color:var(--admin-muted);font-weight:400}.plugin-settings-actions{flex-wrap:wrap}
|
||||
</style>
|
||||
@@ -9,7 +9,7 @@
|
||||
>
|
||||
<img
|
||||
class="brand-mark"
|
||||
src="/网站图标.jpg"
|
||||
src="/webspeak-icon.jpg"
|
||||
alt="WebSpeak"
|
||||
/>
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { reactive, ref, shallowRef } from 'vue';
|
||||
import { createAdminRequests } from '../services/admin-requests.js';
|
||||
import { isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js';
|
||||
import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js';
|
||||
|
||||
export function useAdminPlugins(api: AdminApi) {
|
||||
const installed=shallowRef<InstalledPlugin[]>([]),catalog=shallowRef<PluginCatalog|null>(null),runtime=shallowRef<PluginRuntimeSettings|null>(null);
|
||||
const origin=ref(''),busy=ref(false),error=ref(''),catalogError=ref(''),requests=createAdminRequests();
|
||||
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string}>>({});
|
||||
function apply(records:InstalledPlugin[]){
|
||||
installed.value=records;
|
||||
for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''};
|
||||
for(const id of Object.keys(drafts))if(!records.some(r=>r.manifest.id===id))delete drafts[id];
|
||||
}
|
||||
async function work(run:(signal:AbortSignal,current:()=>boolean)=>Promise<void>){
|
||||
if(busy.value)return;const request=requests.begin('plugins');busy.value=true;error.value='';
|
||||
const timer=setTimeout(()=>{if(request.isCurrent()){error.value='PLUGIN_TIMEOUT';requests.cancel('plugins');busy.value=false;}},90_000);
|
||||
try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof Error?e.message:'PLUGIN_FAILED';}
|
||||
finally{clearTimeout(timer);if(request.isCurrent())busy.value=false;request.finish();}
|
||||
}
|
||||
function load(){return work(async(signal,current)=>{
|
||||
const records=await api.plugins(signal);if(current())apply(records.plugins);
|
||||
const settings=await api.pluginRuntime(signal);if(current()){runtime.value=settings.runtime;origin.value=settings.runtime.publicOrigin;}
|
||||
try{const store=await api.pluginStore(signal);if(current()){catalog.value=store;catalogError.value='';}}catch(e){if(current()&&!isAdminRequestCancelled(e)){catalog.value=null;catalogError.value=e instanceof Error?e.message:'PLUGIN_STORE_UNAVAILABLE';}}
|
||||
});}
|
||||
function install(entry:PluginStoreEntry){return work(async(signal,current)=>{
|
||||
const result=await api.installPlugin({id:entry.id,revision:entry.revision,installedRevision:installed.value.find(p=>p.manifest.id===entry.id)?.revision??null},signal);
|
||||
if(current()){delete drafts[entry.id];apply([...installed.value.filter(p=>p.manifest.id!==entry.id),result.plugin]);}
|
||||
});}
|
||||
function save(record:InstalledPlugin){return work(async(signal,current)=>{
|
||||
const draft=drafts[record.manifest.id],captured=JSON.stringify(draft);
|
||||
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})};
|
||||
const result=await api.configurePlugin(record.manifest.id,record.revision,settings,signal);
|
||||
if(current()){if(JSON.stringify(drafts[record.manifest.id])===captured)delete drafts[record.manifest.id];apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));}
|
||||
});}
|
||||
function restart(record:InstalledPlugin){return work(async(signal,current)=>{const result=await api.restartPlugin(record.manifest.id,record.revision,signal);if(current())apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));});}
|
||||
function saveRuntime(){return work(async(signal,current)=>{if(!runtime.value)return;const captured=origin.value,result=await api.configurePluginRuntime(captured,runtime.value.revision,signal);if(current()){runtime.value=result.runtime;if(origin.value===captured)origin.value=result.runtime.publicOrigin;}});}
|
||||
function remove(record:InstalledPlugin){return work(async(signal,current)=>{await api.removePlugin(record.manifest.id,record.revision,signal);if(current())apply(installed.value.filter(p=>p.manifest.id!==record.manifest.id));});}
|
||||
function upload(file:File){return work(async(signal,current)=>{
|
||||
if(file.size>PLUGIN_LIMIT_BYTES)throw new Error('PLUGIN_TOO_LARGE');const pack=parsePluginPackage(JSON.parse(await file.text()));if(!current())return;
|
||||
const result=await api.uploadPlugin(pack,installed.value.find(p=>p.manifest.id===pack.manifest.id)?.revision??null,signal);
|
||||
if(current()){delete drafts[pack.manifest.id];apply([...installed.value.filter(p=>p.manifest.id!==pack.manifest.id),result.plugin]);}
|
||||
});}
|
||||
function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';}}
|
||||
function reset(){cancelRequests();installed.value=[];catalog.value=null;runtime.value=null;origin.value='';error.value='';catalogError.value='';for(const id of Object.keys(drafts))delete drafts[id];}
|
||||
return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { onScopeDispose, ref, shallowRef, type Ref } from "vue";
|
||||
import { computed, onScopeDispose, ref, shallowRef, watch, type Ref } from "vue";
|
||||
import { canUseSkin, thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
import { BUILTIN_SKIN_CATALOG, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
|
||||
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
|
||||
@@ -19,7 +20,8 @@ const fallbackId = () => isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUI
|
||||
/** One page owns initialization, choices and their late responses, including persistence. */
|
||||
export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
const activeSkin = options.activeSkin ?? shallowRef<InstalledSkin | null>(null);
|
||||
const stored = getStoredSkinId();
|
||||
const candidate = getStoredSkinId();
|
||||
const stored = candidate && canUseSkin(candidate) ? candidate : null;
|
||||
const activeSkinId = ref(stored ?? fallbackId());
|
||||
const skinReady = ref(Boolean(stored && builtin(stored)));
|
||||
const skinLoadError = shallowRef<{ skinId: string } | null>(null);
|
||||
@@ -37,6 +39,7 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
|
||||
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false, clearLoadError = true) {
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) id = fallbackId();
|
||||
const entry = catalogSkins.value.find(skin => skin.id === id);
|
||||
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal }));
|
||||
if (!owns(operation)) return;
|
||||
@@ -119,5 +122,19 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
await select(fallbackId());
|
||||
}
|
||||
|
||||
return { activeSkin, activeSkinId, skinReady, skinLoadError, installedSkins, catalogSkins, initialize, select, cancel, reset, switchToBuiltIn, switchToBuiltInAfterLoadError };
|
||||
watch(thirdPartyAllowed, allowed => {
|
||||
if (disposed) return;
|
||||
if (allowed) { void initialize(); return; }
|
||||
cancel();
|
||||
activeSkin.value = null;
|
||||
skinLoadError.value = null;
|
||||
clearCustomSkinStyle();
|
||||
activeSkinId.value = fallbackId();
|
||||
skinReady.value = true;
|
||||
void select(fallbackId());
|
||||
}, { flush: 'sync' });
|
||||
return { activeSkin, activeSkinId, skinReady, skinLoadError,
|
||||
installedSkins: computed(() => installedSkins.value.filter(skin => canUseSkin(skin.id))),
|
||||
catalogSkins: computed(() => catalogSkins.value.filter(skin => canUseSkin(skin.id))),
|
||||
initialize, select, cancel, reset, switchToBuiltIn, switchToBuiltInAfterLoadError };
|
||||
}
|
||||
@@ -200,6 +200,7 @@ export function useVoiceWebSocket() {
|
||||
const ws = shallowRef<WebSocket | null>(null);
|
||||
const serverInfo = shallowRef<VoiceServerInfo | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
|
||||
const pluginSession = ref("");
|
||||
const sessionState = createVoiceSessionState({
|
||||
selfId: () => state.tsClientId,
|
||||
onMemberRemoved(id) {
|
||||
@@ -1023,6 +1024,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** All ways a session ends release the same owned media and pending work. */
|
||||
function releaseSessionResources(sendScreenStop = false): void {
|
||||
pluginSession.value = "";
|
||||
chatGeneration++;
|
||||
inputDeviceGeneration++;
|
||||
outputDeviceGeneration++;
|
||||
@@ -1065,6 +1067,7 @@ export function useVoiceWebSocket() {
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
state.tsClientId = Number(msg.tsClientId) || 0;
|
||||
pluginSession.value = msg.pluginSession ?? "";
|
||||
// The mute preference is local to the browser, while TeamSpeak shows
|
||||
// the gateway's own client_input_muted flag to other clients. Send it
|
||||
// as soon as the session is ready so a muted reconnect is visible to
|
||||
@@ -1416,6 +1419,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
return {
|
||||
pluginSession,
|
||||
...screenShare.api,
|
||||
ws,
|
||||
state,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { computed, reactive, ref, type Ref } from "vue";
|
||||
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { APP_VERSION } from "../services/app-version.js";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
|
||||
interface RelayOption {
|
||||
@@ -28,7 +29,7 @@ export function useWebClientPublicConfig({
|
||||
const initialized = ref(false);
|
||||
const mobileMode = ref(false);
|
||||
const siteName = ref("WebSpeak");
|
||||
const appVersion = ref("0.2.7");
|
||||
const appVersion = ref(APP_VERSION);
|
||||
const visitorNumber = ref<number | null>(null);
|
||||
const visitorTotal = ref<number | null>(null);
|
||||
const accelerationRelays = ref<RelayOption[]>([]);
|
||||
|
||||
@@ -184,5 +184,5 @@ export function useWebClientServerHistory({
|
||||
}
|
||||
|
||||
function serverKey(address: string): string {
|
||||
return address.trim().toLocaleLowerCase();
|
||||
return address.trim().toLowerCase();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
const en = {
|
||||
menu: 'Authorization', title: 'Skins & plugins',
|
||||
description: 'To provide customization and plugin features, third-party skins and plugins supplied by this WebSpeak instance may access information displayed in your channels, such as member names, channel details and chat messages. Connection credentials are excluded. Each WebSpeak instance is maintained by its own service provider.',
|
||||
choice: 'I allow this instance’s third-party skins and plugins to use this information.',
|
||||
alternative: 'If you decline, you can still use the three official skins: Day, Night and ILLUSIA. Other skins (including KAAK) and plugins will be hidden. You can change this choice in the skin menu at any time.',
|
||||
accept: 'Agree and continue', decline: 'Use official skins only', save: 'Save', enabled: 'On', disabled: 'Off',
|
||||
};
|
||||
export const instanceAuthorizationCopy: Record<SiteLanguage, typeof en> = {
|
||||
en,
|
||||
zh: { menu: '授权', title: '皮肤与插件授权', description: '为了正常提供美化与插件功能,当前 WebSpeak 实例提供的第三方皮肤及插件可能需要读取频道中显示的信息,例如成员昵称、频道信息和聊天内容,不包括连接凭据。每个 WebSpeak 实例由各自的服务提供者维护。', choice: '我同意当前实例提供的第三方皮肤与插件使用上述信息。', alternative: '若不同意,仍可使用日间、夜间、ILLUSIA 三款官方皮肤;其他皮肤(包括 KAAK)及插件将被隐藏。你可以随时在皮肤菜单的“授权”中更改选择。', accept: '同意并继续', decline: '仅使用官方皮肤', save: '保存', enabled: '已开启', disabled: '已关闭' },
|
||||
de: { menu: 'Berechtigung', title: 'Designs & Plugins', description: 'Designs und Plugins von Drittanbietern dieser WebSpeak-Instanz können für ihre Funktionen auf angezeigte Kanalinformationen zugreifen, etwa Mitgliedsnamen, Kanaldetails und Chatnachrichten. Verbindungszugangsdaten sind ausgeschlossen. Jede Instanz wird von ihrem eigenen Dienstanbieter betrieben.', choice: 'Ich erlaube den Designs und Plugins dieser Instanz die Nutzung dieser Informationen.', alternative: 'Ohne Zustimmung bleiben die drei offiziellen Designs Tag, Nacht und ILLUSIA verfügbar. Andere Designs (einschließlich KAAK) und Plugins werden ausgeblendet. Die Auswahl lässt sich jederzeit im Designmenü ändern.', accept: 'Zustimmen und fortfahren', decline: 'Nur offizielle Designs', save: 'Speichern', enabled: 'An', disabled: 'Aus' },
|
||||
ru: { menu: 'Разрешение', title: 'Темы и плагины', description: 'Сторонние темы и плагины этого экземпляра WebSpeak могут использовать сведения, отображаемые в каналах: имена участников, данные каналов и сообщения чата. Учётные данные подключения исключены. Каждый экземпляр обслуживает собственный поставщик услуг.', choice: 'Я разрешаю сторонним темам и плагинам этого экземпляра использовать эти сведения.', alternative: 'Без согласия доступны три официальные темы: дневная, ночная и ILLUSIA. Другие темы (включая KAAK) и плагины будут скрыты. Выбор можно изменить в меню тем.', accept: 'Разрешить и продолжить', decline: 'Только официальные темы', save: 'Сохранить', enabled: 'Включено', disabled: 'Выключено' },
|
||||
ja: { menu: '許可', title: 'スキンとプラグイン', description: 'この WebSpeak インスタンスが提供するサードパーティ製スキンとプラグインは、機能の提供のためにメンバー名、チャンネル情報、チャットなどの表示情報を利用する場合があります。接続用の認証情報は含まれません。各インスタンスはそれぞれのサービス提供者が管理しています。', choice: 'このインスタンスのスキンとプラグインによる上記情報の利用に同意します。', alternative: '同意しない場合も、公式の昼・夜・ILLUSIA の3つのスキンを使用できます。その他のスキン(KAAK を含む)とプラグインは非表示になります。スキンメニューからいつでも変更できます。', accept: '同意して続ける', decline: '公式スキンのみ使用', save: '保存', enabled: '有効', disabled: '無効' },
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
const en={available:'Available plugins',discover:'Discover',search:'Search plugins or authors',active:'Enabled',inactive:'Disabled',configure:'Configure plugin',advanced:'Advanced configuration',add:'Install plugin',update:'Update',reinstall:'Reinstall',empty:'No matching plugins',review:'Review the source and dependencies before enabling',installedNotice:'Installed. Review settings and enable the plugin.',source:'Distributed through GitHub',scopeHelp:'About plugin scopes'};
|
||||
export type PluginStoreTextKey=keyof typeof en;
|
||||
export const pluginStoreTranslations:Record<SiteLanguage,Record<PluginStoreTextKey,string>>={
|
||||
en,
|
||||
zh:{available:'可用插件',discover:'发现插件',search:'搜索插件名称或作者',active:'已启用',inactive:'未启用',configure:'配置插件',advanced:'高级配置',add:'安装插件',update:'更新插件',reinstall:'重新安装',empty:'没有找到匹配的插件',review:'启用前请审核源码和依赖',installedNotice:'安装成功,请检查设置后启用插件。',source:'通过 GitHub 分发',scopeHelp:'了解插件作用域'},
|
||||
de:{available:'Verfügbare Plugins',discover:'Entdecken',search:'Plugins oder Autoren suchen',active:'Aktiviert',inactive:'Deaktiviert',configure:'Plugin konfigurieren',advanced:'Erweiterte Konfiguration',add:'Plugin installieren',update:'Aktualisieren',reinstall:'Neu installieren',empty:'Keine passenden Plugins',review:'Quellcode und Abhängigkeiten vor der Aktivierung prüfen',installedNotice:'Installiert. Einstellungen prüfen und Plugin aktivieren.',source:'Verteilung über GitHub',scopeHelp:'Geltungsbereiche verstehen'},
|
||||
ru:{available:'Доступные плагины',discover:'Обзор',search:'Поиск плагинов или авторов',active:'Включён',inactive:'Выключен',configure:'Настроить плагин',advanced:'Дополнительные настройки',add:'Установить плагин',update:'Обновить',reinstall:'Переустановить',empty:'Подходящих плагинов нет',review:'Проверьте код и зависимости перед включением',installedNotice:'Установлено. Проверьте настройки и включите плагин.',source:'Распространение через GitHub',scopeHelp:'Области действия плагинов'},
|
||||
ja:{available:'利用可能',discover:'見つける',search:'プラグイン名・作者を検索',active:'有効',inactive:'無効',configure:'プラグイン設定',advanced:'詳細設定',add:'インストール',update:'更新',reinstall:'再インストール',empty:'一致するプラグインがありません',review:'有効化する前にコードと依存関係を確認してください',installedNotice:'インストールしました。設定を確認して有効にしてください。',source:'GitHub で配布',scopeHelp:'スコープについて'},
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
|
||||
const en = { minimize: 'Minimize', maximize: 'Maximize', restore: 'Restore', search: 'Find a plugin…', resume: 'Return to app', workspace: 'Application library', count: 'available', move: 'Drag to move', noResults: 'No matching plugins' };
|
||||
export const pluginWindowTranslations: Record<SiteLanguage, typeof en> = {
|
||||
en,
|
||||
zh: { minimize: '最小化', maximize: '最大化', restore: '还原', search: '搜索插件…', resume: '返回应用', workspace: '应用库', count: '个可用', move: '拖动窗口', noResults: '没有匹配的插件' },
|
||||
de: { minimize: 'Minimieren', maximize: 'Maximieren', restore: 'Wiederherstellen', search: 'Plugin suchen…', resume: 'Zur Anwendung', workspace: 'Anwendungen', count: 'verfügbar', move: 'Zum Verschieben ziehen', noResults: 'Keine passenden Plugins' },
|
||||
ru: { minimize: 'Свернуть', maximize: 'Развернуть', restore: 'Восстановить', search: 'Найти плагин…', resume: 'Вернуться к приложению', workspace: 'Библиотека приложений', count: 'доступно', move: 'Перетащите окно', noResults: 'Плагины не найдены' },
|
||||
ja: { minimize: '最小化', maximize: '最大化', restore: '元に戻す', search: 'プラグインを検索…', resume: 'アプリに戻る', workspace: 'アプリライブラリ', count: '件利用可能', move: 'ドラッグして移動', noResults: '一致するプラグインはありません' },
|
||||
};
|
||||
@@ -0,0 +1,245 @@
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
const en = {
|
||||
"panelNote":"Applications reviewed and enabled by this instance’s administrator. Browser permission prompts still apply.",
|
||||
"catalogError":"The application catalog is unavailable or requires API v2. Local import remains available.",
|
||||
"title": "Plugins",
|
||||
"store": "Plugin store",
|
||||
"installed": "Installed plugins",
|
||||
"refresh": "Refresh",
|
||||
"install": "Install / update",
|
||||
"upload": "Import .wplugin",
|
||||
"remove": "Remove",
|
||||
"save": "Save settings",
|
||||
"server": "TS server scope",
|
||||
"instance": "WebSpeak instance scope",
|
||||
"targets": "Allowed TS targets (one host:port per line)",
|
||||
"config": "Public configuration (JSON; visible to users)",
|
||||
"enabled": "Enable plugin",
|
||||
"lead": "Reviewed applications with standard browser capabilities and optional Node services. Updates require renewed trust.",
|
||||
"empty": "No plugins available",
|
||||
"open": "Open",
|
||||
"close": "Close",
|
||||
"back": "Back to plugins",
|
||||
"scope": "Scope",
|
||||
"source": "Distribution repository",
|
||||
"loading": "Loading…",
|
||||
"error": "Plugin operation failed",
|
||||
"removed": "Remove this application? Open sessions will close; its backend data is retained.",
|
||||
"context": "The connection or application changed. Open it again.",
|
||||
"note": "Scope controls admission and supplies a context key. Authors implement their own collaboration and routes. Server scope follows the actual TS target and channel; instance scope spans this gateway.",
|
||||
"enableNote": "These are trusted applications on a separate origin. Node backends run with the WebSpeak service account’s OS privileges. Review the source and dependencies before enabling.",
|
||||
"runtime": "Application runtime",
|
||||
"origin": "Public runtime origin",
|
||||
"originHelp": "Use a separate HTTPS origin, such as https://apps.example.com, proxying to the runtime port. Blank enables local automatic addressing only.",
|
||||
"trust": "I have reviewed and trust this application and its dependencies",
|
||||
"privateConfig": "Private backend configuration (JSON; encrypted at rest)",
|
||||
"keep": "Keep existing secret configuration",
|
||||
"replace": "Replace secret configuration",
|
||||
"erase": "Remove secret configuration",
|
||||
"secretSaved": "Private configuration is stored",
|
||||
"secretEmpty": "No private configuration stored",
|
||||
"restart": "Restart backend",
|
||||
"client": "Browser application",
|
||||
"backend": "Node backend",
|
||||
"disabled": "Disabled",
|
||||
"stopped": "Stopped",
|
||||
"starting": "Starting",
|
||||
"running": "Running",
|
||||
"failed": "Failed"
|
||||
};
|
||||
export type PluginTextKey = keyof typeof en;
|
||||
export const pluginTranslations: Record<SiteLanguage, Record<PluginTextKey,string>> = {
|
||||
en,
|
||||
zh:{
|
||||
"panelNote":"这里只显示实例管理员已审核并启用的应用,使用时仍需遵守浏览器的权限提示。",
|
||||
"catalogError":"应用目录暂不可用或需要升级为 API v2,仍可导入本地应用包。",
|
||||
"title": "插件功能",
|
||||
"store": "插件商店",
|
||||
"installed": "已安装插件",
|
||||
"refresh": "刷新",
|
||||
"install": "安装 / 更新",
|
||||
"upload": "导入 .wplugin",
|
||||
"remove": "移除",
|
||||
"save": "保存设置",
|
||||
"server": "TS 服务器范围",
|
||||
"instance": "WebSpeak 实例范围",
|
||||
"targets": "允许的 TS 地址(每行一个 host:port)",
|
||||
"config": "公开配置(JSON;用户可见)",
|
||||
"enabled": "启用插件",
|
||||
"lead": "经审核的应用,可使用标准浏览器能力和可选的 Node 服务。更新后需要重新信任。",
|
||||
"empty": "暂无可用插件",
|
||||
"open": "打开",
|
||||
"close": "关闭",
|
||||
"back": "返回插件列表",
|
||||
"scope": "作用域",
|
||||
"source": "分发仓库",
|
||||
"loading": "加载中…",
|
||||
"error": "插件操作失败",
|
||||
"removed": "移除此应用?已打开的会话将关闭,后端数据会保留。",
|
||||
"context": "连接或应用已变化,请重新打开。",
|
||||
"note": "作用域负责准入并提供上下文标识,协作逻辑和路由由作者编写。服务器范围跟随实际 TS 目标和频道;实例范围覆盖当前网关。",
|
||||
"enableNote": "插件是运行于独立源的受信任应用。Node 后端拥有 WebSpeak 服务账户的操作系统权限。启用前请审核源码和依赖。",
|
||||
"runtime": "应用运行时",
|
||||
"origin": "运行时公开源地址",
|
||||
"originHelp": "配置独立的 HTTPS 源,如 https://apps.example.com,并反向代理到运行时端口。留空仅支持本地自动地址。",
|
||||
"trust": "我已审核并信任此应用及其依赖",
|
||||
"privateConfig": "后端私密配置(JSON;加密存储)",
|
||||
"keep": "保留现有私密配置",
|
||||
"replace": "替换私密配置",
|
||||
"erase": "删除私密配置",
|
||||
"secretSaved": "已保存私密配置",
|
||||
"secretEmpty": "尚无私密配置",
|
||||
"restart": "重启后端",
|
||||
"client": "浏览器应用",
|
||||
"backend": "Node 后端",
|
||||
"disabled": "未启用",
|
||||
"stopped": "已停止",
|
||||
"starting": "启动中",
|
||||
"running": "运行中",
|
||||
"failed": "失败"
|
||||
},
|
||||
de:{
|
||||
"panelNote":"Von der Instanzadministration geprüfte und aktivierte Anwendungen. Browser-Berechtigungsabfragen gelten weiterhin.",
|
||||
"catalogError":"Der Katalog ist nicht verfügbar oder benötigt API v2. Lokaler Import bleibt möglich.",
|
||||
"title": "Plugins",
|
||||
"store": "Plugin-Store",
|
||||
"installed": "Installierte Plugins",
|
||||
"refresh": "Aktualisieren",
|
||||
"install": "Installieren / aktualisieren",
|
||||
"upload": ".wplugin importieren",
|
||||
"remove": "Entfernen",
|
||||
"save": "Einstellungen speichern",
|
||||
"server": "TS-Server-Bereich",
|
||||
"instance": "WebSpeak-Instanz-Bereich",
|
||||
"targets": "Erlaubte TS-Ziele (host:port pro Zeile)",
|
||||
"config": "Öffentliche Konfiguration (JSON; für Nutzer sichtbar)",
|
||||
"enabled": "Plugin aktivieren",
|
||||
"lead": "Geprüfte Anwendungen mit Browserfunktionen und optionalen Node-Diensten. Updates erfordern erneutes Vertrauen.",
|
||||
"empty": "Keine Plugins verfügbar",
|
||||
"open": "Öffnen",
|
||||
"close": "Schließen",
|
||||
"back": "Zur Plugin-Liste",
|
||||
"scope": "Bereich",
|
||||
"source": "Verteilungsrepository",
|
||||
"loading": "Wird geladen…",
|
||||
"error": "Plugin-Vorgang fehlgeschlagen",
|
||||
"removed": "Anwendung entfernen? Sitzungen werden geschlossen; Backend-Daten bleiben erhalten.",
|
||||
"context": "Verbindung oder Anwendung geändert. Erneut öffnen.",
|
||||
"note": "Der Bereich steuert den Zugang und liefert einen Kontextschlüssel. Zusammenarbeit und Routen implementiert der Autor. Server-Bereiche folgen TS-Ziel und Kanal; Instanz-Bereiche gelten für dieses Gateway.",
|
||||
"enableNote": "Vertrauenswürdige Anwendungen auf einer separaten Origin. Node-Backends haben die Betriebssystemrechte des WebSpeak-Dienstkontos. Quellcode und Abhängigkeiten vor der Aktivierung prüfen.",
|
||||
"runtime": "Anwendungslaufzeit",
|
||||
"origin": "Öffentliche Runtime-Origin",
|
||||
"originHelp": "Separate HTTPS-Origin, z. B. https://apps.example.com, auf den Runtime-Port weiterleiten. Leer nur für lokale automatische Adressen.",
|
||||
"trust": "Ich habe diese Anwendung und ihre Abhängigkeiten geprüft und vertraue ihnen",
|
||||
"privateConfig": "Private Backend-Konfiguration (JSON; verschlüsselt gespeichert)",
|
||||
"keep": "Vorhandene private Konfiguration behalten",
|
||||
"replace": "Private Konfiguration ersetzen",
|
||||
"erase": "Private Konfiguration löschen",
|
||||
"secretSaved": "Private Konfiguration gespeichert",
|
||||
"secretEmpty": "Keine private Konfiguration gespeichert",
|
||||
"restart": "Backend neu starten",
|
||||
"client": "Browseranwendung",
|
||||
"backend": "Node-Backend",
|
||||
"disabled": "Deaktiviert",
|
||||
"stopped": "Gestoppt",
|
||||
"starting": "Startet",
|
||||
"running": "Läuft",
|
||||
"failed": "Fehlgeschlagen"
|
||||
},
|
||||
ru:{
|
||||
"panelNote":"Приложения проверены и включены администратором экземпляра. Разрешения браузера по-прежнему применяются.",
|
||||
"catalogError":"Каталог недоступен или требует API v2. Локальный импорт по-прежнему доступен.",
|
||||
"title": "Плагины",
|
||||
"store": "Магазин плагинов",
|
||||
"installed": "Установленные плагины",
|
||||
"refresh": "Обновить",
|
||||
"install": "Установить / обновить",
|
||||
"upload": "Импорт .wplugin",
|
||||
"remove": "Удалить",
|
||||
"save": "Сохранить настройки",
|
||||
"server": "Область TS-сервера",
|
||||
"instance": "Область экземпляра WebSpeak",
|
||||
"targets": "Разрешённые адреса TS (host:port, по одному в строке)",
|
||||
"config": "Публичные настройки (JSON; видны пользователям)",
|
||||
"enabled": "Включить плагин",
|
||||
"lead": "Проверенные приложения с возможностями браузера и необязательными сервисами Node. Обновления требуют повторного доверия.",
|
||||
"empty": "Нет доступных плагинов",
|
||||
"open": "Открыть",
|
||||
"close": "Закрыть",
|
||||
"back": "К списку плагинов",
|
||||
"scope": "Область действия",
|
||||
"source": "Репозиторий распространения",
|
||||
"loading": "Загрузка…",
|
||||
"error": "Ошибка операции плагина",
|
||||
"removed": "Удалить приложение? Сеансы закроются; данные сервиса сохранятся.",
|
||||
"context": "Соединение или приложение изменились. Откройте снова.",
|
||||
"note": "Область определяет доступ и ключ контекста. Автор реализует совместную работу и маршруты. Область сервера следует фактическому адресу TS и каналу, экземпляра — всему шлюзу.",
|
||||
"enableNote": "Это доверенные приложения на отдельном источнике. Сервисы Node обладают правами учётной записи WebSpeak в ОС. До включения проверьте код и зависимости.",
|
||||
"runtime": "Среда приложений",
|
||||
"origin": "Публичный источник среды",
|
||||
"originHelp": "Отдельный HTTPS-источник, например https://apps.example.com, с проксированием на порт среды. Пустое поле — только для локальных адресов.",
|
||||
"trust": "Я проверил приложение и зависимости и доверяю им",
|
||||
"privateConfig": "Приватные настройки сервиса (JSON; хранятся зашифрованными)",
|
||||
"keep": "Сохранить текущие приватные настройки",
|
||||
"replace": "Заменить приватные настройки",
|
||||
"erase": "Удалить приватные настройки",
|
||||
"secretSaved": "Приватные настройки сохранены",
|
||||
"secretEmpty": "Приватных настроек нет",
|
||||
"restart": "Перезапустить сервис",
|
||||
"client": "Браузерное приложение",
|
||||
"backend": "Сервис Node",
|
||||
"disabled": "Выключен",
|
||||
"stopped": "Остановлен",
|
||||
"starting": "Запускается",
|
||||
"running": "Работает",
|
||||
"failed": "Ошибка"
|
||||
},
|
||||
ja:{
|
||||
"panelNote":"インスタンス管理者が審査して有効にしたアプリです。ブラウザーの権限確認は引き続き必要です。",
|
||||
"catalogError":"カタログが利用できないか API v2 が必要です。ローカル読み込みは利用できます。",
|
||||
"title": "プラグイン",
|
||||
"store": "プラグインストア",
|
||||
"installed": "インストール済み",
|
||||
"refresh": "更新",
|
||||
"install": "インストール / 更新",
|
||||
"upload": ".wplugin を読み込む",
|
||||
"remove": "削除",
|
||||
"save": "設定を保存",
|
||||
"server": "TS サーバー範囲",
|
||||
"instance": "WebSpeak インスタンス範囲",
|
||||
"targets": "許可する TS アドレス(1行に host:port)",
|
||||
"config": "公開設定(JSON、ユーザーに公開)",
|
||||
"enabled": "有効にする",
|
||||
"lead": "標準ブラウザー機能と任意の Node サービスを使う審査済みアプリです。更新後は再度信頼を確認します。",
|
||||
"empty": "利用できるプラグインがありません",
|
||||
"open": "開く",
|
||||
"close": "閉じる",
|
||||
"back": "一覧に戻る",
|
||||
"scope": "範囲",
|
||||
"source": "配布リポジトリ",
|
||||
"loading": "読み込み中…",
|
||||
"error": "プラグイン操作に失敗しました",
|
||||
"removed": "削除しますか?セッションは閉じますが、バックエンドのデータは保持します。",
|
||||
"context": "接続またはアプリが変わりました。開き直してください。",
|
||||
"note": "範囲はアクセスとコンテキストキーを提供します。共同作業やルートは作者が実装します。サーバー範囲は実際の TS 接続先とチャンネル、インスタンス範囲は現在のゲートウェイに適用します。",
|
||||
"enableNote": "別オリジンで動く信頼済みアプリです。Node バックエンドは WebSpeak サービスアカウントの OS 権限で動作します。有効化前にコードと依存関係を確認してください。",
|
||||
"runtime": "アプリ実行環境",
|
||||
"origin": "公開ランタイムオリジン",
|
||||
"originHelp": "https://apps.example.com のような別 HTTPS オリジンを実行ポートへ転送します。空欄はローカル自動アドレス専用です。",
|
||||
"trust": "アプリと依存関係を審査し、信頼します",
|
||||
"privateConfig": "バックエンドの秘密設定(JSON、暗号化して保存)",
|
||||
"keep": "現在の秘密設定を保持",
|
||||
"replace": "秘密設定を置換",
|
||||
"erase": "秘密設定を削除",
|
||||
"secretSaved": "秘密設定を保存済み",
|
||||
"secretEmpty": "秘密設定なし",
|
||||
"restart": "バックエンドを再起動",
|
||||
"client": "ブラウザーアプリ",
|
||||
"backend": "Node バックエンド",
|
||||
"disabled": "無効",
|
||||
"stopped": "停止",
|
||||
"starting": "起動中",
|
||||
"running": "動作中",
|
||||
"failed": "失敗"
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
|
||||
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
|
||||
import { pluginResponses, type PluginPackage, type PluginSettingsInput } from "../../../src/shared/plugins.js";
|
||||
|
||||
export class AdminApiError extends Error {
|
||||
constructor(readonly code: string, readonly status = 0, message = code) {
|
||||
@@ -100,6 +101,15 @@ export function createAdminApi(options: AdminApiOptions) {
|
||||
|
||||
return {
|
||||
invalidate() { generation++; for (const controller of pending) controller.abort(); },
|
||||
plugins: (signal?: AbortSignal) => request("/plugins", pluginResponses.installed, "GET", undefined, true, signal),
|
||||
pluginStore: (signal?: AbortSignal) => request("/plugins/store", pluginResponses.catalog, "GET", undefined, true, signal),
|
||||
pluginRuntime: (signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "GET", undefined, true, signal),
|
||||
configurePluginRuntime: (publicOrigin: string, revision: string, signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "PUT", { publicOrigin, revision }, true, signal),
|
||||
restartPlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/restart`, pluginResponses.saved, "POST", { revision }, true, signal),
|
||||
installPlugin: (body: { id: string; revision: string; installedRevision: string | null }, signal?: AbortSignal) => request("/plugins/store/install", pluginResponses.saved, "POST", body, true, signal),
|
||||
uploadPlugin: (pack: PluginPackage, installedRevision: string | null, signal?: AbortSignal) => request("/plugins/upload", pluginResponses.saved, "POST", { package: pack, installedRevision }, true, signal),
|
||||
configurePlugin: (id: string, revision: string, settings: PluginSettingsInput, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
|
||||
removePlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}`, adminResponses.ok, "DELETE", { revision }, true, signal),
|
||||
session: (signal?: AbortSignal) => request("/session", adminResponses.session, "GET", undefined, true, signal),
|
||||
login: (username: string, password: string, signal?: AbortSignal) => request("/login", adminResponses.login, "POST", { username, password }, false, signal),
|
||||
changePassword: (newPassword: string, signal?: AbortSignal) => request("/change-password", adminResponses.ok, "POST", { newPassword }, true, signal),
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import appPackage from "../../../package.json";
|
||||
|
||||
// Available before the public config request completes, including on the demo page.
|
||||
export const APP_VERSION = appPackage.version;
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createInstanceAuthorization, INSTANCE_AUTHORIZATION_KEY, canUseSkin, setInstanceAuthorization } from './instance-authorization.js';
|
||||
|
||||
function storage() {
|
||||
const values = new Map<string, string>();
|
||||
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
|
||||
}
|
||||
test('new instances require an explicit decision; legacy package approvals do not imply consent', () => {
|
||||
const data = storage(); data.values.set('webspeak:skin-plugin-approvals', '{"grants":{"old":true}}');
|
||||
const state = createInstanceAuthorization(data);
|
||||
assert.equal(state.decision.value, null); assert.equal(state.allowed.value, false);
|
||||
state.set(false); assert.equal(createInstanceAuthorization(data).decision.value, false);
|
||||
state.set(true); assert.equal(createInstanceAuthorization(data).allowed.value, true);
|
||||
assert.deepEqual([...data.values.keys()].sort(), [INSTANCE_AUTHORIZATION_KEY, 'webspeak:skin-plugin-approvals'].sort());
|
||||
});
|
||||
test('separate instance storage stays independent; revocation and clearing propagate on reload', () => {
|
||||
const first = storage(), second = storage(), tab = createInstanceAuthorization(first), otherTab = createInstanceAuthorization(first);
|
||||
tab.set(true); otherTab.reload(); assert.equal(otherTab.allowed.value, true);
|
||||
assert.equal(createInstanceAuthorization(second).decision.value, null);
|
||||
tab.set(false); otherTab.reload(); assert.equal(otherTab.allowed.value, false);
|
||||
first.values.clear(); otherTab.reload(); assert.equal(otherTab.decision.value, null);
|
||||
});
|
||||
test('malformed or inaccessible storage never grants access; explicit choices survive in memory', () => {
|
||||
const data = storage();
|
||||
for (const value of ['true', '{}', '{"schemaVersion":1,"allowed":"true"}', '{"schemaVersion":2,"allowed":true}', 'broken']) {
|
||||
data.setItem(INSTANCE_AUTHORIZATION_KEY, value); assert.equal(createInstanceAuthorization(data).allowed.value, false);
|
||||
}
|
||||
const unavailable = createInstanceAuthorization({ getItem() { throw Error(); }, setItem() { throw Error(); } });
|
||||
assert.equal(unavailable.allowed.value, false); unavailable.set(true); assert.equal(unavailable.allowed.value, true);
|
||||
unavailable.set(false); assert.equal(unavailable.allowed.value, false);
|
||||
});
|
||||
test('only the three official IDs bypass consent, including when KAAK is shipped as built-in', () => {
|
||||
setInstanceAuthorization(false);
|
||||
for (const id of ['builtin.light', 'builtin.dark', 'community.illusia-voice']) assert.equal(canUseSkin(id), true);
|
||||
for (const id of ['community.kaak-voice', 'community.discord-voice', 'builtin.other']) assert.equal(canUseSkin(id), false);
|
||||
setInstanceAuthorization(true); assert.equal(canUseSkin('community.kaak-voice'), true);
|
||||
setInstanceAuthorization(false);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { computed, readonly, ref } from 'vue';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
|
||||
export const INSTANCE_AUTHORIZATION_KEY = 'webspeak:instance-authorization:v1';
|
||||
export const OFFICIAL_SKIN_IDS = new Set(['builtin.light', 'builtin.dark', 'community.illusia-voice']);
|
||||
type AuthorizationStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
|
||||
/** A decision belongs to this browser origin, never to a skin package or a TS account. */
|
||||
export function createInstanceAuthorization(storage: AuthorizationStorage) {
|
||||
function read(): boolean | null {
|
||||
try {
|
||||
const value = JSON.parse(storage.getItem(INSTANCE_AUTHORIZATION_KEY) ?? 'null');
|
||||
return value?.schemaVersion === 1 && typeof value.allowed === 'boolean' ? value.allowed : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
const decision = ref<boolean | null>(read());
|
||||
return {
|
||||
decision: readonly(decision),
|
||||
allowed: computed(() => decision.value === true),
|
||||
set(allowed: boolean) {
|
||||
// Notify consumers synchronously so revocation also retires in-flight loads.
|
||||
decision.value = allowed;
|
||||
try { storage.setItem(INSTANCE_AUTHORIZATION_KEY, JSON.stringify({ schemaVersion: 1, allowed })); } catch { /* Keep this page's explicit decision when storage is unavailable. */ }
|
||||
},
|
||||
reload() { decision.value = read(); },
|
||||
};
|
||||
}
|
||||
|
||||
const store = createInstanceAuthorization({
|
||||
getItem: key => typeof window === 'undefined' ? null : window.localStorage.getItem(key),
|
||||
setItem: (key, value) => { if (typeof window !== 'undefined') window.localStorage.setItem(key, value); },
|
||||
});
|
||||
export const authorizationDecision = store.decision;
|
||||
export const thirdPartyAllowed = store.allowed;
|
||||
export const authorizationRequested = ref(false);
|
||||
export const authorizationLanguage = ref<SiteLanguage>('zh');
|
||||
export const setInstanceAuthorization = store.set;
|
||||
export const canUseSkin = (id: string) => OFFICIAL_SKIN_IDS.has(id) || thirdPartyAllowed.value;
|
||||
export function openInstanceAuthorization() { authorizationRequested.value = true; }
|
||||
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') window.addEventListener('storage', event => {
|
||||
if (event.key === INSTANCE_AUTHORIZATION_KEY || event.key === null) store.reload();
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPluginAppClient } from './plugin-app-client.js';
|
||||
const token='a'.repeat(43),id='b'.repeat(43);
|
||||
const manifest={apiVersion:2,id:'test.app',name:'Test',version:'1.0.0',author:'Test',license:'MIT',description:'App',scopes:['instance'],client:{entry:'client/index.html'}};
|
||||
test('plugin control uses the connected gateway origin and never sends its voice query or cookies',async()=>{
|
||||
const seen:Array<{url:string;init:RequestInit|undefined}>=[];
|
||||
const client=createPluginAppClient('wss://relay.example/voice?credential=private',token,async(url,init)=>{seen.push({url:String(url),init});return Response.json({plugins:[{manifest,scope:'instance',runtime:{state:'client'}}]});});
|
||||
assert.equal((await client.list())[0].manifest.id,'test.app');assert.equal(seen[0].url,'https://relay.example/api/plugins');assert.equal(seen[0].init?.credentials,'omit');assert.equal(new Headers(seen[0].init?.headers).get('authorization'),'Bearer '+token);
|
||||
assert.throws(()=>createPluginAppClient('https://x','invalid'));assert.throws(()=>createPluginAppClient('https://user:secret@example.com',token));
|
||||
});
|
||||
test('launch validation rejects mismatched IDs, unsafe URLs and invalid runtime responses',async()=>{
|
||||
for(const value of [{id,url:`https://apps.example/apps/${id}/client/index.html`,manifest:{...manifest,id:'another.app'}},{id,url:`https://user:secret@apps.example/apps/${id}/client/index.html`,manifest},{id,url:'javascript:alert(1)',manifest},{id,url:`https://apps.example/apps/${id}/client/index.html?ticket=x`,manifest}]){
|
||||
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json(value));await assert.rejects(client.open('test.app',{openId:'operation-123',theme:'light',language:'en'}));
|
||||
}
|
||||
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json({plugins:[{manifest,scope:'anything',runtime:{state:'unknown'}}]}));await assert.rejects(client.list());
|
||||
});
|
||||
test('control requests time out through response body parsing and support caller cancellation',async()=>{
|
||||
const slow:typeof fetch=async(_url,init)=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))));
|
||||
const client=createPluginAppClient('http://localhost:3040',token,slow,15);await assert.rejects(client.list(),/PLUGIN_TIMEOUT/);
|
||||
const controller=new AbortController(),request=client.list(controller.signal);controller.abort();await assert.rejects(request,/PLUGIN_REQUEST_CANCELLED/);
|
||||
const body:typeof fetch=async(_url,init)=>({ok:true,json:()=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))))}) as Response;
|
||||
await assert.rejects(createPluginAppClient('http://localhost:3040',token,body,15).list(),/PLUGIN_TIMEOUT/);
|
||||
});
|
||||
test('pending open cancellation remains a separate operation and status errors are bounded codes',async()=>{
|
||||
const requests:string[]=[];const client=createPluginAppClient('http://localhost:3040',token,async(url,init)=>{requests.push(`${init?.method} ${url}`);return Response.json({ok:true});});
|
||||
await client.cancelOpen('operation-123');assert.match(requests[0],/^DELETE .*\/opening\/operation-123$/);
|
||||
await assert.rejects(createPluginAppClient('http://localhost:3040',token,async()=>Response.json({code:'<secret error body>'},{status:500})).list(),/PLUGIN_RUNTIME_FAILED/);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { parsePluginManifest, pluginAssert, pluginRecord, type PluginManifest, type PluginAppLaunch, type PluginScope, type PluginRuntimeStatus } from '../../../src/shared/plugins.js';
|
||||
|
||||
export interface AvailablePluginApp { manifest: PluginManifest; scope: PluginScope; runtime: PluginRuntimeStatus }
|
||||
export function createPluginAppClient(gatewayUrl:string,token:string,fetcher:typeof fetch=fetch,timeoutMs=15000){
|
||||
pluginAssert(/^[A-Za-z0-9_-]{43}$/.test(token),'PLUGIN_NOT_CONNECTED');
|
||||
const gateway=new URL(gatewayUrl);pluginAssert(['ws:','wss:','http:','https:'].includes(gateway.protocol)&&!gateway.username&&!gateway.password);
|
||||
gateway.protocol=gateway.protocol==='wss:'||gateway.protocol==='https:'?'https:':'http:';
|
||||
const base=gateway.origin+'/api/plugins';
|
||||
async function request(route:string,method='GET',body?:unknown,signal?:AbortSignal):Promise<unknown>{
|
||||
const controller=new AbortController();let timedOut=false;
|
||||
const abort=()=>controller.abort();if(signal?.aborted)abort();else signal?.addEventListener('abort',abort,{once:true});
|
||||
const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeoutMs);
|
||||
try{
|
||||
const response=await fetcher(base+route,{method,headers:{authorization:'Bearer '+token,...(body===undefined?{}:{'content-type':'application/json'})},credentials:'omit',redirect:'error',signal:controller.signal,...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
const value:unknown=await response.json();
|
||||
if(!response.ok)throw new Error(pluginRecord(value)&&typeof value.code==='string'&&/^[A-Z0-9_]{1,80}$/.test(value.code)?value.code:'PLUGIN_RUNTIME_FAILED');
|
||||
return value;
|
||||
}catch(error){if(timedOut)throw new Error('PLUGIN_TIMEOUT');if(signal?.aborted)throw new Error('PLUGIN_REQUEST_CANCELLED');throw error;}
|
||||
finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);}
|
||||
}
|
||||
return {
|
||||
async list(signal?:AbortSignal):Promise<AvailablePluginApp[]>{
|
||||
const value=await request('','GET',undefined,signal);pluginAssert(pluginRecord(value)&&Array.isArray(value.plugins)&&value.plugins.length<=50,'PLUGIN_INVALID_RESPONSE');
|
||||
return value.plugins.map(entry=>{
|
||||
pluginAssert(pluginRecord(entry)&&(entry.scope==='server'||entry.scope==='instance')&&pluginRecord(entry.runtime)&&['disabled','client','stopped','starting','running','failed'].includes(String(entry.runtime.state)),'PLUGIN_INVALID_RESPONSE');
|
||||
return {manifest:parsePluginManifest(entry.manifest),scope:entry.scope,runtime:{state:entry.runtime.state as PluginRuntimeStatus['state'],...(typeof entry.runtime.error==='string'?{error:entry.runtime.error}:{})}};
|
||||
});
|
||||
},
|
||||
async open(id:string,options:{openId:string;theme:'light'|'dark';language:string},signal?:AbortSignal):Promise<PluginAppLaunch>{
|
||||
const value=await request('/'+encodeURIComponent(id)+'/open','POST',options,signal);
|
||||
pluginAssert(pluginRecord(value)&&typeof value.id==='string'&&/^[A-Za-z0-9_-]{43}$/.test(value.id)&&typeof value.url==='string','PLUGIN_INVALID_RESPONSE');
|
||||
const manifest=parsePluginManifest(value.manifest),url=new URL(value.url);
|
||||
pluginAssert(manifest.id===id&&['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&url.pathname==='/apps/'+value.id+'/'+manifest.client.entry&&!url.hash&&!url.search,'PLUGIN_INVALID_RESPONSE');
|
||||
return {id:value.id,url:url.href,manifest};
|
||||
},
|
||||
cancelOpen:(openId:string)=>request('/opening/'+encodeURIComponent(openId),'DELETE'),
|
||||
appearance:(id:string,theme:'light'|'dark',language:string)=>request('/apps/'+encodeURIComponent(id),'PATCH',{theme,language}),
|
||||
};
|
||||
}
|
||||
export type PluginAppClient=ReturnType<typeof createPluginAppClient>;
|
||||
@@ -90,12 +90,12 @@ export function mergeQuickServers(
|
||||
}
|
||||
|
||||
function serverKey(address: string): string {
|
||||
return address.trim().toLocaleLowerCase();
|
||||
return address.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function comparableServerKey(address: string): string {
|
||||
const target = splitTeamSpeakTarget(address);
|
||||
const host = target.address.trim().toLocaleLowerCase();
|
||||
const host = target.address.trim().toLowerCase();
|
||||
const port = target.port.trim() || "9987";
|
||||
return host ? `${host}:${port}` : "";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import test, { beforeEach } from "node:test";
|
||||
import { setInstanceAuthorization } from './instance-authorization.js';
|
||||
import { createRenderer, createSSRApp, defineComponent, h, nextTick, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
SkinExtensionUiOutputError,
|
||||
} from "../../../src/shared/skin-extension-ui.js";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
beforeEach(() => setInstanceAuthorization(true));
|
||||
|
||||
function outputDocument(componentId = "runtime-ui", root?: Record<string, unknown>, permissions: string[] = [], actions: Record<string, unknown> = {}, state?: Record<string, unknown>): string {
|
||||
return JSON.stringify({
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
/** Temporary development policy. Re-enable consent before public skin distribution. */
|
||||
/** Per-package dialogs are replaced by the explicit, revocable instance authorization.
|
||||
* Hosts must check canUseSkin before issuing/using internal manifest-bound grants. */
|
||||
export const PROMPT_FOR_SKIN_PERMISSIONS = false;
|
||||
@@ -51,7 +51,7 @@ export function getSkinRuntimePluginApproval(
|
||||
return grant && isSkinRuntimePluginApproved(grant, skinId, skinVersion, plugin, digest) ? grant : null;
|
||||
}
|
||||
|
||||
/** Called only by the host consent UI after a user explicitly approves this exact package. */
|
||||
/** Internal digest-bound record. The host must first allow this skin through instance authorization. */
|
||||
export function approveSkinRuntimePlugin(
|
||||
skinId: string,
|
||||
skinVersion: string,
|
||||
|
||||
@@ -35,6 +35,19 @@ async function approvedFiles(source = createSkinExtensionWasmPrefixByteImmediate
|
||||
return { files, digest, approval: createSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest) };
|
||||
}
|
||||
|
||||
test('revocation while package bytes are being verified prevents worker startup', async () => {
|
||||
const { files, approval } = await approvedFiles();
|
||||
const controller = new AbortController(), original = files[plugin.entry];
|
||||
class RevokedBlob extends Blob {
|
||||
override async arrayBuffer(): Promise<ArrayBuffer> { controller.abort(); return super.arrayBuffer(); }
|
||||
}
|
||||
await assert.rejects(createSkinRuntimePluginWasmSandbox({
|
||||
skinId: 'community.sample', skinVersion: '2.0.0', plugin, approval,
|
||||
files: { [plugin.entry]: new RevokedBlob([original]) }, signal: controller.signal,
|
||||
readSessionStatus: async () => ({ connected: true, channelName: 'Test', memberCount: 1 }),
|
||||
}), { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test("Wasm plugin startup rechecks the exact digest approval before creating a Worker", async () => {
|
||||
const { files, approval } = await approvedFiles();
|
||||
const staleApproval = { ...approval, digest: "0".repeat(64) };
|
||||
|
||||
@@ -26,6 +26,7 @@ export class SkinRuntimePluginWasmError extends Error {
|
||||
}
|
||||
|
||||
export interface SkinRuntimePluginWasmOptions {
|
||||
signal?: AbortSignal;
|
||||
skinId: string;
|
||||
skinVersion: string;
|
||||
plugin: SkinRuntimePlugin;
|
||||
@@ -43,6 +44,7 @@ const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSI
|
||||
export async function createSkinRuntimePluginWasmSandbox(
|
||||
options: SkinRuntimePluginWasmOptions,
|
||||
): Promise<SkinExtensionWasmSandboxHandle> {
|
||||
options.signal?.throwIfAborted();
|
||||
const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [options.plugin] }).plugins[0];
|
||||
if (plugin.runtime !== "wasm") throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "Only a Wasm plugin entry can use the bounded Wasm runner.");
|
||||
|
||||
@@ -52,6 +54,7 @@ export async function createSkinRuntimePluginWasmSandbox(
|
||||
}
|
||||
|
||||
const digest = await computeSkinRuntimePluginDigest(plugin, options.files);
|
||||
options.signal?.throwIfAborted();
|
||||
let approval: SkinRuntimePluginApproval;
|
||||
try { approval = parseSkinRuntimePluginApproval(options.approval); }
|
||||
catch { throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_APPROVAL_INVALID", "The Wasm plugin does not have a valid local approval."); }
|
||||
@@ -62,6 +65,7 @@ export async function createSkinRuntimePluginWasmSandbox(
|
||||
const entry = options.files[plugin.entry];
|
||||
if (!(entry instanceof Blob)) throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "The approved Wasm entry is unavailable.");
|
||||
const wasmBytes = new Uint8Array(await entry.arrayBuffer());
|
||||
options.signal?.throwIfAborted();
|
||||
const baseInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
|
||||
const uiInput = parseSkinExtensionUiInput({
|
||||
...baseInput,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
|
||||
import { APP_VERSION } from "./app-version.js";
|
||||
import type { InstalledSkin } from "./skin-pack.js";
|
||||
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
|
||||
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
|
||||
import { setSkinLayoutPackage } from "./skin-layout-runtime.js";
|
||||
import { canUseSkin } from './instance-authorization.js';
|
||||
|
||||
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
|
||||
export const BUILTIN_LIGHT_SKIN = "builtin.light";
|
||||
@@ -34,7 +36,7 @@ export async function activateStoredSkin(): Promise<InstalledSkin | null> {
|
||||
return activateSkin(selectedId);
|
||||
}
|
||||
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.7", options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = APP_VERSION, options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
|
||||
// An already retired page must not cancel a newer page's activation.
|
||||
options.signal?.throwIfAborted();
|
||||
pendingActivation?.cancel();
|
||||
@@ -51,6 +53,7 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
|
||||
async function prepareAndActivate(id: string, expectedVersion: string | undefined, appVersion: string,
|
||||
operation: ReturnType<typeof createSkinOperation>): Promise<InstalledSkin | null> {
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) return fallBackToBuiltin();
|
||||
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
|
||||
removeCustomSkinStyle();
|
||||
setSkinLayoutPackage(id, null);
|
||||
@@ -92,6 +95,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
|
||||
candidateUrls = compiled.objectUrls;
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) { candidateUrls.forEach(url => URL.revokeObjectURL(url)); return fallBackToBuiltin(); }
|
||||
// A community skin is a complete appearance choice, not an overlay on the
|
||||
// previously selected day/night skin. Keep the document theme (used by the
|
||||
// independent admin appearance) but give unstyled public parts a light,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
.ws-plugin-overlay{--po-bg:#f5f7fc;--po-surface:#fff;--po-raised:#edf1f9;--po-line:#dae1ef;--po-text:#233049;--po-muted:#65728b;--po-accent:#5265df;--po-tint:#e9edff;position:fixed;inset:0;z-index:10000;pointer-events:none;color:var(--po-text);font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;color-scheme:light;text-align:left}
|
||||
.ws-plugin-overlay[data-plugin-theme="dark"]{--po-bg:#171c27;--po-surface:#202736;--po-raised:#2a3345;--po-line:#364158;--po-text:#edf2ff;--po-muted:#a5b1ca;--po-accent:#a4b0ff;--po-tint:#333e64;color-scheme:dark}
|
||||
.ws-plugin-overlay *{box-sizing:border-box}
|
||||
.ws-plugin-overlay button{appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:8px;margin:0;min-width:0;width:auto;height:auto;font:inherit;letter-spacing:normal;text-transform:none;border:1px solid var(--po-line);border-radius:9px;padding:8px 14px;background:var(--po-surface);color:var(--po-text);box-shadow:none;cursor:pointer;white-space:normal}
|
||||
.ws-plugin-overlay button:hover{background:var(--po-raised);border-color:var(--po-accent)}
|
||||
.ws-plugin-overlay button:disabled{opacity:.5;cursor:wait}
|
||||
.ws-plugin-overlay button:focus-visible,.ws-plugin-search:focus-visible{outline:2px solid var(--po-accent);outline-offset:3px}
|
||||
.ws-plugin-overlay svg{display:block;width:19px;height:19px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
|
||||
.ws-plugin-overlay .ws-plugin-launcher{position:absolute;pointer-events:auto;right:max(20px,env(safe-area-inset-right));bottom:calc(22px + env(safe-area-inset-bottom));padding:13px 18px;border:1px solid #ffffff35;border-radius:18px;background:#303f78;color:#fff;box-shadow:0 8px 30px #101a4240;font-weight:650;transition:background .15s,box-shadow .15s}
|
||||
.ws-plugin-overlay .ws-plugin-launcher:hover{background:#405496;box-shadow:0 10px 35px #101a4260}
|
||||
.ws-plugin-launcher i{width:7px;height:7px;border-radius:50%;background:#9ee7b5}
|
||||
.ws-plugin-window{position:absolute;pointer-events:auto;left:50%;top:10dvh;transform:translateX(-50%);display:flex;flex-direction:column;width:min(1080px,calc(100vw - 32px));height:min(760px,80dvh);min-width:320px;min-height:240px;max-width:calc(100vw - 16px);max-height:calc(100dvh - 16px);overflow:hidden;resize:both;border:1px solid var(--po-line);border-radius:17px;background:var(--po-bg);box-shadow:0 30px 100px #080e3540,0 4px 20px #080e3520;isolation:isolate}
|
||||
.ws-plugin-window:focus{outline:none}
|
||||
.ws-plugin-window.is-maximized{inset:8px!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 16px)!important;transform:none!important;resize:none}
|
||||
.ws-plugin-titlebar{display:flex;align-items:center;gap:12px;flex:none;min-height:62px;margin:0;padding:8px 10px 8px 20px;border-bottom:1px solid var(--po-line);background:var(--po-surface);cursor:grab;touch-action:none;user-select:none}
|
||||
.is-dragging .ws-plugin-titlebar{cursor:grabbing}
|
||||
.ws-plugin-mark{display:grid;place-items:center;width:32px;height:32px;flex:none;border-radius:10px;background:var(--po-tint);color:var(--po-accent);font-size:23px}
|
||||
.ws-plugin-window-title{display:flex;align-items:baseline;gap:12px;min-width:0;flex:1}
|
||||
.ws-plugin-window-title strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:650}
|
||||
.ws-plugin-window-title small{color:var(--po-muted);font-size:11px;flex:none}
|
||||
.ws-plugin-window-controls{display:flex;gap:3px;flex:none}
|
||||
.ws-plugin-overlay .ws-plugin-window-controls button{padding:9px;border:0;border-radius:8px;background:transparent;color:var(--po-muted)}
|
||||
.ws-plugin-overlay .ws-plugin-window-controls button:hover{background:var(--po-raised);color:var(--po-text)}
|
||||
.ws-plugin-overlay .ws-plugin-window-controls .ws-plugin-close:hover{background:#d44354;color:white}
|
||||
.ws-plugin-navigation{display:flex;align-items:center;gap:6px;min-height:52px;flex:none;padding:8px 16px;border-bottom:1px solid var(--po-line);overflow-x:auto}
|
||||
.ws-plugin-overlay .ws-plugin-navigation button{flex:none;padding:7px 12px;border:0;background:transparent;color:var(--po-muted);font-size:12px}
|
||||
.ws-plugin-overlay .ws-plugin-navigation button.active{background:var(--po-tint);color:var(--po-accent);font-weight:650}
|
||||
.ws-plugin-version{margin-left:auto;white-space:nowrap;color:var(--po-muted);font-size:11px}
|
||||
.ws-plugin-library{flex:1;min-height:0;padding:26px;overflow:auto;overscroll-behavior:contain}
|
||||
.ws-plugin-library-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:20px}
|
||||
.ws-plugin-library-heading h2{margin:0 0 3px;color:var(--po-text);font-size:24px;font-weight:700;line-height:1.3}
|
||||
.ws-plugin-library-heading span{font-size:12px;color:var(--po-muted)}
|
||||
.ws-plugin-overlay .ws-plugin-search{display:block;width:100%;height:42px;margin:0 0 22px;padding:10px 14px;background:var(--po-surface);color:var(--po-text);font:inherit;border:1px solid var(--po-line);border-radius:10px;box-shadow:none}
|
||||
.ws-plugin-search::placeholder{color:var(--po-muted)}
|
||||
.ws-plugin-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,270px),1fr));align-items:start;gap:16px}
|
||||
.ws-plugin-entry{display:grid;grid-template-columns:44px minmax(0,1fr);gap:14px;padding:20px;background:var(--po-surface);border:1px solid var(--po-line);border-radius:13px}
|
||||
.ws-plugin-app-mark{display:grid;place-items:center;width:44px;height:44px;border-radius:13px;background:var(--po-tint);color:var(--po-accent);font-size:22px;font-weight:700}
|
||||
.ws-plugin-entry h3{margin:0 0 4px;font-size:15px;font-weight:650;overflow-wrap:anywhere;color:var(--po-text)}
|
||||
.ws-plugin-entry small{display:block;color:var(--po-muted);font-size:11px}
|
||||
.ws-plugin-entry p{margin:12px 0 0;color:var(--po-muted);font-size:13px;overflow-wrap:anywhere}
|
||||
.ws-plugin-overlay .ws-plugin-entry button{grid-column:1/-1;justify-content:space-between;width:100%;background:var(--po-tint);border-color:transparent;color:var(--po-accent);font-weight:600}
|
||||
.ws-plugin-entry-error{grid-column:1/-1;color:#d1495b!important}
|
||||
.ws-plugin-empty{text-align:center;color:var(--po-muted);padding:50px 12px}
|
||||
.ws-plugin-error{flex:none;margin:0;padding:12px 20px;background:#dc50541a;color:#d1495b;overflow-wrap:anywhere;max-height:100px;overflow:auto}
|
||||
.ws-plugin-browser{flex:1;min-height:0;display:flex;background:var(--po-surface)}
|
||||
.ws-plugin-browser iframe{display:block;flex:1;width:100%;height:100%;min-height:0;border:0;border-radius:0;background:var(--po-surface)}
|
||||
.ws-plugin-drag-shield{position:absolute;inset:62px 0 0;z-index:1;cursor:grabbing}
|
||||
@media(max-width:600px){.ws-plugin-window{left:8px!important;top:8px!important;transform:none!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 92px);min-width:0;resize:none;border-radius:13px}.ws-plugin-titlebar{padding-left:12px;gap:8px}.ws-plugin-window-title small{display:none}.ws-plugin-library{padding:18px}.ws-plugin-overlay .ws-plugin-launcher{bottom:calc(16px + env(safe-area-inset-bottom));right:12px;padding:12px 14px}.ws-plugin-library-heading h2{font-size:21px}.ws-plugin-entry{padding:16px}.ws-plugin-navigation{padding-inline:10px}}
|
||||
@media(prefers-reduced-motion:reduce){.ws-plugin-overlay .ws-plugin-launcher{transition:none}}
|
||||
.ws-plugin-launcher{touch-action:none;user-select:none}
|
||||
@@ -151,6 +151,7 @@
|
||||
<RouterLink to="/admin/server" active-class="active"><Icon name="server" :size="18" />{{ tr('adminInstanceSettings') }}</RouterLink>
|
||||
<RouterLink to="/admin/operations" active-class="active"><Icon name="users" :size="18" />{{ tr('adminInstanceOperations') }}</RouterLink>
|
||||
<RouterLink to="/admin/skins" active-class="active"><Icon name="compass" :size="18" />{{ tr('skinLibrary') }}</RouterLink>
|
||||
<RouterLink to="/admin/plugins" active-class="active"><Icon name="grid" :size="18" />{{ pluginTranslations[language].store }}</RouterLink>
|
||||
</div>
|
||||
<div class="admin-nav-group">
|
||||
<span class="admin-nav-heading">{{ tr('adminTsGroup') }}<span class="admin-optional">{{ tr('adminOptional') }}</span></span>
|
||||
@@ -241,6 +242,7 @@
|
||||
:model="adminSkins"
|
||||
:i18n="i18n"
|
||||
/>
|
||||
<AdminPlugins v-else-if="route.path === '/admin/plugins'" :model="adminPlugins" :language="language" />
|
||||
<AdminTsAdmin
|
||||
v-else-if="route.path === '/admin/ts-admin'"
|
||||
:model="adminTsAdmin"
|
||||
@@ -399,6 +401,9 @@ import Icon from "../components/Icon.vue";
|
||||
import AdminServerSettings from "../components/admin/AdminServerSettings.vue";
|
||||
import AdminOperations from "../components/admin/AdminOperations.vue";
|
||||
import AdminSkins from "../components/admin/AdminSkins.vue";
|
||||
import AdminPlugins from "../components/admin/AdminPlugins.vue";
|
||||
import { useAdminPlugins } from "../composables/useAdminPlugins.js";
|
||||
import { pluginTranslations } from "../i18n/plugins.js";
|
||||
import AdminTsAdmin from "../components/admin/AdminTsAdmin.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
@@ -454,12 +459,13 @@ const currentScope = computed(() => route.path === "/admin/ts-admin" ? tr("admin
|
||||
const adminOperations = useAdminOperations({ api: adminApi, errorMessage, errorText, tr, refreshOverview: loadOverview });
|
||||
const { loadOperations } = adminOperations;
|
||||
const adminSkins = useAdminSkins({ api: adminApi, tr });
|
||||
const adminPlugins = useAdminPlugins(adminApi);
|
||||
const { loadSkinCatalog } = adminSkins;
|
||||
const adminTsAdmin = useAdminTsAdmin({ api: adminApi, errorMessage, errorText, tr });
|
||||
const { loadSettings: loadTsAdminSettings } = adminTsAdmin;
|
||||
|
||||
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
|
||||
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('adminInstanceSettings') : route.path === "/admin/operations" ? tr('adminInstanceOperations') : route.path === "/admin/skins" ? tr('skinLibrary') : route.path === "/admin/ts-admin" ? tr('tsAdminTitle') : tr('overview'));
|
||||
const currentPageTitle = computed(() => route.path === "/admin/plugins" ? pluginTranslations[language.value].store : route.path === "/admin/server" ? tr('adminInstanceSettings') : route.path === "/admin/operations" ? tr('adminInstanceOperations') : route.path === "/admin/skins" ? tr('skinLibrary') : route.path === "/admin/ts-admin" ? tr('tsAdminTitle') : tr('overview'));
|
||||
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
|
||||
const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${serverForm.webRtcUdpEnd}`);
|
||||
|
||||
@@ -471,10 +477,12 @@ watch(() => route.path, (path, previous) => {
|
||||
if (previous === "/admin/server") serverSettings.cancelRequests();
|
||||
if (previous === "/admin/operations") adminOperations.cancelRequests();
|
||||
if (previous === "/admin/skins") adminSkins.cancelRequests();
|
||||
if (previous === "/admin/plugins") adminPlugins.cancelRequests();
|
||||
if (previous === "/admin/ts-admin") adminTsAdmin.cancelRequests();
|
||||
if (screen.value !== "admin" || loading.value || submitting.value || loggingOut.value) return;
|
||||
if (path === "/admin/operations") void loadOperations();
|
||||
else if (path === "/admin/skins") void loadSkinCatalog();
|
||||
else if (path === "/admin/plugins") void adminPlugins.load();
|
||||
else if (path === "/admin/ts-admin") void loadTsAdminSettings();
|
||||
else if (path === "/admin") void loadOverview();
|
||||
});
|
||||
@@ -485,6 +493,7 @@ function cancelPendingWork() {
|
||||
serverSettings.cancelRequests();
|
||||
adminOperations.cancelRequests();
|
||||
adminSkins.cancelRequests();
|
||||
adminPlugins.cancelRequests();
|
||||
adminTsAdmin.cancelRequests();
|
||||
loading.value = false;
|
||||
submitting.value = false;
|
||||
@@ -492,6 +501,7 @@ function cancelPendingWork() {
|
||||
}
|
||||
function resetPrivateState() {
|
||||
serverSettings.reset(); adminOperations.reset(); adminSkins.reset(); adminTsAdmin.reset();
|
||||
adminPlugins.reset();
|
||||
Object.assign(overview, emptyOverview());
|
||||
loginPassword.value = ""; newPassword.value = ""; confirmNewPassword.value = "";
|
||||
errorMessage.value = "";
|
||||
@@ -505,6 +515,7 @@ async function loadAdminData(request: { isCurrent(): boolean }) {
|
||||
if (!request.isCurrent()) return;
|
||||
if (route.path === "/admin/operations") await loadOperations();
|
||||
else if (route.path === "/admin/skins") await loadSkinCatalog();
|
||||
else if (route.path === "/admin/plugins") await adminPlugins.load();
|
||||
else if (route.path === "/admin/ts-admin") await loadTsAdminSettings();
|
||||
}
|
||||
async function loadAdminView() {
|
||||
|
||||
@@ -58,11 +58,13 @@
|
||||
<div v-if="poke" class="demo-poke" data-ws-part="demo.poke-notification" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" data-ws-part="demo.poke.dismiss" @click="poke = false"><Icon name="close" :size="14" /></button></div>
|
||||
</div>
|
||||
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
|
||||
<InstanceAuthorization :language="language" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
|
||||
import "../styles/skin-plugin.css";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user