diff --git a/.agents/skills/webspeak-plugin-development/SKILL.md b/.agents/skills/webspeak-plugin-development/SKILL.md new file mode 100644 index 0000000..982a988 --- /dev/null +++ b/.agents/skills/webspeak-plugin-development/SKILL.md @@ -0,0 +1,20 @@ +--- +name: webspeak-plugin-development +description: Develop, review, package, and validate portable WebSpeak functional .wplugin plugins through the public API. Use for server or instance plugins and GitHub plugin distribution, not .wskin appearance packages or their internal components. +--- + +# WebSpeak Plugin Development + +Build a functional package without editing WebSpeak runtime, SDK, skins, or administration code. A missing host capability needs a separate API change authorized by the user; do not invent methods or reach into Vue instances. + +Read the current [plugin development guide](../../../docs/PLUGIN_DEVELOPMENT.md) before implementing. In a standalone checkout, use the guide at `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/dev/docs/PLUGIN_DEVELOPMENT.md`. Confirm that the target instance supports API v1; released v0.2.9 does not. + +Choose the scope that matches the user's intent: `server` uses actual TS target + channel rooms; `instance` shares a room across connected users of one gateway. Neither synchronizes separate gateways or TS native clients. Public plugin config is not secret storage. Do not repurpose TS administration credentials. + +Keep UI/behavior in `.wplugin` JSON: validated manifest, HTML, script, complete light and dark styles. Use only `window.webspeak.ready` and the documented `room` API. Never assume a particular skin DOM or CSS selector. Use an independent panel, responsive layout, translated labels, and accessible controls. Media autoplay needs participant action when blocked. + +Represent collaboration as small JSON state. Use revision CAS, recover conflicts from a fresh snapshot, reject old room IDs/versions, and derive playback progress from gateway time rather than sending frames or high-frequency ticks. Clean timers, subscriptions and media on pagehide. The example is `docs/examples/watch-together/` in the host repo and `examples/watch-together/` in the distribution repo. + +Build with `node --import tsx scripts/build-plugin.mjs SOURCE_DIR OUTPUT.wplugin` in a host checkout (the provided template reads manifest.json, panel.html, player.js, light.css and dark.css), or use the standalone distribution repo builder. Validate the actual resulting package through host import. For GitHub distribution provide real package SHA-256 and a fixed commit/tag, then add the repository to the catalog. Publishing or deploying requires the user's task authorization; do not infer it from this skill. + +Verify two independent participants: load/play/pause/seek, late join, concurrent writes, target/channel isolation, disconnect, close, administrator disable/update and re-open. Check both themes and narrow layout. Distinguish mocked gateway tests from a real browser playback test and real TS connectivity. Only claim capabilities the evidence demonstrates. Keep private credentials and diagnostic recordings outside published artifacts. diff --git a/.agents/skills/webspeak-plugin-development/agents/openai.yaml b/.agents/skills/webspeak-plugin-development/agents/openai.yaml new file mode 100644 index 0000000..f7757af --- /dev/null +++ b/.agents/skills/webspeak-plugin-development/agents/openai.yaml @@ -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." diff --git a/docs/PLUGIN_DEVELOPMENT.md b/docs/PLUGIN_DEVELOPMENT.md new file mode 100644 index 0000000..ee5f248 --- /dev/null +++ b/docs/PLUGIN_DEVELOPMENT.md @@ -0,0 +1,158 @@ +# WebSpeak 功能插件开发 / Functional plugin development + +本文描述 dev 分支的功能插件 API v1。实例需要包含插件商店;正式版 v0.2.9 尚无此接口。功能包 `.wplugin` 与外观包 `.wskin`、皮肤内部组件及其 API 独立。 + +## 使用与作用域 + +管理员进入 `/admin/plugins`,从 [GitHub 分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 安装或导入本地 `.wplugin`。检查作者、许可证和权限后,选择作用域、保存公开配置并启用。安装、更新后默认禁用,不能静默获取新权限。管理写操作受管理员会话、同源和 CSRF 保护,并记录审计。 + +用户连接语音工作台后,通过独立的“插件功能”入口打开隔离面板,不依赖皮肤的挂载位置。关闭面板或返回列表会退出插件房间、销毁 iframe 并停止媒体;插件不修改原生工作台 DOM。 + +| 类型 | 配置和房间边界 | +| --- | --- | +| `server` 服务器插件 | 配置允许的 TS `host:port`,用户按实际 TS 目标及频道进入各自房间 | +| `instance` WebSpeak 实例插件 | 同一网关的已连接用户共享一个插件房间,跨 TS 服务器和频道 | + +服务器绑定使用网关解析后的实际连接地址,不接受插件或浏览器自报的目标。使用 SRV、Nickname 或别名时,在实例连接列表核对实际目标。配置支持 `host:port`、`host#port`、`[IPv6]:port`,保存时规范化。服务器插件未配置目标时不能启用。切频道会退出旧服务器插件房间,实例插件保留房间。断线、重连、卸载、更新或管理员修改配置会关闭旧上下文,需重新打开。 + +“所有人”指打开插件的 WebSpeak 浏览器参与者,TS 原生客户端不会运行网页插件。不同 WebSpeak 网关目前不共享插件房间。使用浏览器直连中继网关时,插件目录和房间属于实际连接的语音网关,需要在那里安装配置;只使用 UDP 加速不会改变房间归属。 + +## 包格式 + +`.wplugin` 是 UTF-8 JSON,最多 512 KiB,不是 ZIP;不包含服务端可执行文件、原生模块或任意路径。 + +```json +{ + "manifest": { + "apiVersion": 1, "id": "community.example", "name": "Example", + "version": "1.0.0", "author": "Author", "license": "MIT", + "description": "Collaborative panel", + "scopes": ["server", "instance"], + "permissions": ["room.read", "room.write"] + }, + "html": "
", + "script": "(async () => { const context = await webspeak.ready; })();", + "styles": { + "light": "body { background: #fff; color: #16332e; }", + "dark": "body { background: #20242b; color: #edf5f2; }" + } +} +``` + +两个基础样式都必须提供。宿主根据当前皮肤文字明暗推断基础配色,发送 `context.theme`,一次只启用一个样式表。iframe 不继承皮肤 CSS,无需适配每款皮肤的组件位置。语言为 `zh/en/de/ru/ja`,建议五种文案和英文回退。每段 HTML、脚本或样式最多 256 KiB,总包仍受 512 KiB 限制。ID 为小写字母、数字、点和连字符,最长 80 字符。 + +完整示例源文件在 [watch-together](examples/watch-together/manifest.json):`manifest.json`、`panel.html`、`player.js`、`light.css`、`dark.css`。 + +```sh +node --import tsx scripts/build-plugin.mjs docs/examples/watch-together docs/examples/watch-together.wplugin +node --import tsx --test src/plugins/plugins.test.ts +``` + +构建器读取上述五个文件。其他工具链只需生成同格式 JSON。独立插件仓库不需要 WebSpeak 源码即可生成包;宿主导入时也会校验。 + +## 公共浏览器 API + +脚本开始前,宿主提供只读 `window.webspeak`,不需要导入内部 Vue 组件。 + +```ts +type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; +interface Snapshot { + roomId: string; + revision: number; + state: JsonValue; // 空房间初始为 null + serverTime: number; // 网关 Unix 毫秒时间 + participants: { id: string; nickname: string }[]; +} +interface Context { + self: { id: string; nickname: string }; // 临时会话 ID,不是 TS 私钥或 UID + config: JsonValue; // 管理员提供的公开配置 + scope: "server" | "instance"; + snapshot: Snapshot; + theme: "light" | "dark"; + language: "zh" | "en" | "de" | "ru" | "ja"; +} +interface WebSpeakPluginAPI { + apiVersion: 1; + ready: Promise; + room: { + snapshot(): Promise; + update(expectedRevision: number, state: JsonValue): Promise; + subscribe(listener: (snapshot: Snapshot) => void): () => void; + }; +} +``` + +`room.read` 允许读房间和订阅状态;`room.write` 允许替换共享状态,必须同时声明读权限。不需要共享数据的独立功能面板可声明空权限数组:仍可打开并获得公开配置,但上下文仅含空快照,不能读写或订阅其他参与者。当前所有已加入且拥有写权限的参与者都能操作,没有隐含主持人角色或 TS 管理权限。API 不提供 TS Query、宿主 DOM、系统文件、管理员凭据或任意宿主方法。需要新能力时另行提议接口,不能访问内部实现绕过。 + +更新使用比较并交换:读取 N 后提交 N,成功返回 N+1;冲突返回 `PLUGIN_REVISION_CONFLICT`。重新读取,让用户重试或基于新状态重算,不能盲目覆盖。 + +```js +const api = window.webspeak; +const context = await api.ready; +let snapshot = context.snapshot; +const unsubscribe = api.room.subscribe(next => { + if (next.roomId !== snapshot.roomId || next.revision < snapshot.revision) return; + snapshot = next; + render(next.state); +}); +async function update(next) { + try { snapshot = await api.room.update(snapshot.revision, next); } + catch (error) { + if (error.message === "PLUGIN_REVISION_CONFLICT") snapshot = await api.room.snapshot(); + else throw error; + } +} +addEventListener("pagehide", unsubscribe, { once: true }); +``` + +共享状态上限 16 KiB、16 层嵌套、4096 个节点,只接受 JSON,不接受非有限数、原型键或二进制媒体。公开配置上限 8 KiB。每会话每秒最多 20 个插件请求,每个房间每秒最多 10 次共享写入,关闭操作不受频率限制。最多 8 个已打开插件(当前面板一次打开一个);每网关最多 800 个非空房间、50 个已安装插件。读取快照不触发广播。不要通过高频写状态传视频帧。服务端只保存通用状态与成员,不执行插件代码。 + +最后一位参与者离开立即销毁房间,重启也会丢失临时房间。安装和配置持久化于数据目录 `plugins/*.json`,原子替换;实例备份应包含此目录。需要持久业务数据或外部适配器时,应定义额外能力协议。 + +主要错误:`PLUGIN_NOT_CONNECTED`、`PLUGIN_NOT_ALLOWED`、`PLUGIN_DISABLED`、`PLUGIN_NOT_OPEN`、`PLUGIN_PERMISSION_DENIED`、`PLUGIN_REVISION_CONFLICT`、`PLUGIN_RATE_LIMITED`、`PLUGIN_TOO_LARGE`、`PLUGIN_TIMEOUT`。配置或包变化会关闭旧上下文并提示重新打开。 + +为避免可选插件消息挤占语音连接的内存,出站队列超过 512 KiB 时跳过插件消息。恢复连接质量后可请求快照或重新打开插件;请求无响应会超时,不代表共享写入一定没有执行。 + +## 同步观影示例 + +状态为 `{ url, position, playing, updatedAt }`。加载、播放、暂停、跳转共享;音量、全屏与播放许可仅影响自己。使用快照 `serverTime` 估算网关时钟,推算播放 elapsed time,定时校正漂移,大偏移跳转、小偏移暂调速。后来加入读取同一快照追上进度,不依赖过去的操作事件。 + +视频由每个浏览器直接从 URL 加载,不经过 WebSpeak 中转。支持浏览器可解码的 MP4/WebM 等直链,不支持播放网页、DRM、登录后 URL 或嵌入式平台播放器。HTTPS 实例一般需要 HTTPS 视频。自动播放受浏览器策略限制,可能需要点击“允许播放”。源端带宽、网络和缓冲会影响误差,不承诺逐帧同步。 + +## 隔离与清理 + +使用 opaque-origin `sandbox="allow-scripts"` iframe,不授予 `allow-same-origin`、顶部导航、弹窗、表单、麦克风或摄像头。宿主 RPC 校验 `event.source`、随机通道和面板生命周期;插件不能选择另一个 ID 或房间。CSP 禁止 fetch/WebSocket、外部脚本、嵌套 iframe,仅允许直接媒体及 HTTPS 图片。媒体源仍会收到浏览器请求,配置、共享状态和视频 URL 都不能包含管理员密钥。 + +隔离不是恶意代码审核、CPU/内存配额的替代品。管理员应审查来源。插件在 `pagehide` 清理计时器、订阅和媒体;宿主关闭时销毁 iframe,后端移除房间成员,迟到响应不能重开已关闭面板。 + +## GitHub 分发协议 + +根仓库 `main/index.json`: + +```json +{ + "schemaVersion": 1, + "plugins": [{ + "id": "community.example", + "repository": "https://github.com/OWNER/REPOSITORY", + "metadataPath": "plugin.json" + }] +} +``` + +`metadataPath` 默认 `plugin.json`,也支持子目录。同一个仓库可以分发多个插件。对应仓库默认分支的元数据: + +```json +{ + "manifest": { "apiVersion": 1, "id": "community.example", "name": "Example", "version": "1.0.0", "author": "Author", "license": "MIT", "description": "Example", "scopes": ["server"], "permissions": ["room.read", "room.write"] }, + "package": { "ref": "IMMUTABLE_COMMIT_OR_TAG", "path": "example.wplugin", "sha256": "64_lowercase_hex_digits" } +} +``` + +使用真实 SHA-256,推荐固定提交或发布标签;不要上传占位值。只访问 `raw.githubusercontent.com`,拒绝重定向、非法地址/路径、超时和超限数据。安装时重读目录和元数据,核对管理员看到的 revision,再下载校验摘要及清单;installedRevision 也作并发保护。失败保留旧包。摘要是内容一致性校验,不是作者签名或安全认证。 + +## English quick start + +Functional plugins are portable UTF-8 `.wplugin` JSON bundles, independent of skins. Install under `/admin/plugins`, review permissions, select `server` (target + channel) or `instance` (one room across connected users of this gateway), and explicitly enable. Open the common Plugins panel after joining voice. Native TS clients and separate WebSpeak gateways do not share this runtime. + +Await `window.webspeak.ready`, subscribe with `webspeak.room.subscribe`, and write with revision-checked `room.update`. The API types, limits and distribution schemas above are normative. Both light/dark styles are required. The [Watch Together example](examples/watch-together/player.js) implements clock-based progress, late joining, conflict recovery, autoplay handling and cleanup without host-specific player code. Build using the command above and import into an isolated development instance. Develop plugins without modifying WebSpeak runtime files; propose missing capabilities separately. diff --git a/docs/README.de.md b/docs/README.de.md index 5b111e0..fd8ef34 100644 --- a/docs/README.de.md +++ b/docs/README.de.md @@ -359,3 +359,10 @@ Diese Liste würdigt den Autor des zugrunde liegenden SDKs, Beiträge aus zusamm - [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. + +## Funktionale Plugins entwickeln (dev) + +Plugin-API, Server-/Instanzbereiche, gemeinsamer Videoplayer und GitHub-Verteilung: + +- [Plugin-Entwicklungsleitfaden](PLUGIN_DEVELOPMENT.md) +- [Agent Skill für Plugin-Entwicklung](../.agents/skills/webspeak-plugin-development/SKILL.md) diff --git a/docs/README.en.md b/docs/README.en.md index 811464d..2ed79bd 100644 --- a/docs/README.en.md +++ b/docs/README.en.md @@ -369,3 +369,10 @@ This list acknowledges the upstream SDK author, contributions through merged Git - [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). + +## Functional plugin development (dev) + +Plugin API, server/instance scopes, Watch Together example, and GitHub distribution: + +- [Plugin development guide](PLUGIN_DEVELOPMENT.md) +- [Plugin development Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) diff --git a/docs/README.ja.md b/docs/README.ja.md index 68fd695..5bf667b 100644 --- a/docs/README.ja.md +++ b/docs/README.ja.md @@ -241,3 +241,10 @@ WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で - [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)へ移植。 + +## 機能プラグイン開発(dev) + +プラグイン API、サーバー/インスタンススコープ、同期プレーヤー、GitHub 配布: + +- [プラグイン開発ガイド](PLUGIN_DEVELOPMENT.md) +- [プラグイン開発 Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) diff --git a/docs/README.ru.md b/docs/README.ru.md index ead9099..22d9473 100644 --- a/docs/README.ru.md +++ b/docs/README.ru.md @@ -243,3 +243,10 @@ WebSpeak распространяется по [GNU Affero General Public Licens - [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). + +## Разработка функциональных плагинов (dev) + +API плагинов, области сервера/экземпляра, совместный видеоплеер и распространение через GitHub: + +- [Руководство по разработке плагинов](PLUGIN_DEVELOPMENT.md) +- [Agent Skill для разработки плагинов](../.agents/skills/webspeak-plugin-development/SKILL.md) diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index 48262da..e9a0a3d 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -373,3 +373,10 @@ npm start - [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)。 + +## 功能插件开发(dev) + +功能插件系统的开发指南、服务器与实例作用域、同步观影示例和 GitHub 分发: + +- [插件开发指南](PLUGIN_DEVELOPMENT.md) +- [插件开发 Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) diff --git a/docs/examples/watch-together.wplugin b/docs/examples/watch-together.wplugin new file mode 100644 index 0000000..6ae5365 --- /dev/null +++ b/docs/examples/watch-together.wplugin @@ -0,0 +1 @@ +{"manifest":{"apiVersion":1,"id":"community.watch-together","name":"Watch Together / 一起观看","version":"1.0.0","author":"Huddle-Up-Forge","license":"AGPL-3.0-only","description":"A shared video player with synchronized playback, pause and seeking. / 同步播放、暂停与跳转的视频播放器。","scopes":["server","instance"],"permissions":["room.read","room.write"]},"html":"
\n

Watch Together

\n

\n
\n \n
\n \n

\n

\n
\n","script":"/* Uses only the public plugin API. Nothing here imports WebSpeak internals. */\n(async () => {\n const api = window.webspeak, context = await api.ready;\n const $ = id => document.getElementById(id), video = $('video');\n const language = context.language, zh = language === 'zh';\n const texts = {\n zh: ['一起观看','所有参与者共享播放、暂停和进度;音量仅影响自己。','视频直链','载入视频','允许播放','请使用浏览器支持的 MP4 / WebM 视频直链。不会把视频经过 WebSpeak 服务器转发。','浏览器阻止自动播放,请点击“允许播放”。','视频无法加载,请检查地址、格式与 HTTPS。','有人同时操作,已获取最新进度,请重试。'],\n en: ['Watch Together','Playback, pause and seeking are shared; volume is local.','Direct video URL','Load video','Enable playback','Use a browser-compatible MP4 / WebM URL. Video is fetched directly, never relayed by WebSpeak.','Autoplay was blocked. Click Enable playback.','Video could not load. Check URL, format and HTTPS.','Another participant changed playback. Refreshed; please try again.'],\n de: ['Gemeinsam ansehen','Wiedergabe, Pause und Position sind gemeinsam; Lautstärke ist lokal.','Direkte Video-URL','Video laden','Wiedergabe erlauben','Browserkompatible MP4-/WebM-URL verwenden. Video wird direkt geladen.','Autoplay blockiert. Wiedergabe erlauben anklicken.','Video nicht ladbar. URL, Format und HTTPS prüfen.','Gleichzeitige Änderung. Aktualisiert; erneut versuchen.'],\n ru: ['Смотреть вместе','Воспроизведение, пауза и позиция общие; громкость локальная.','Прямая ссылка на видео','Загрузить видео','Разрешить воспроизведение','Используйте прямую ссылку MP4 / WebM. Видео загружается напрямую.','Автовоспроизведение заблокировано. Нажмите Разрешить воспроизведение.','Не удалось загрузить видео. Проверьте адрес, формат и HTTPS.','Другой участник изменил состояние. Обновлено; повторите.'],\n ja: ['一緒に見る','再生・停止・位置を共有します。音量は自分の端末のみです。','動画の直接 URL','動画を読み込む','再生を許可','ブラウザー対応の MP4 / WebM URL を使用します。動画は直接取得されます。','自動再生がブロックされました。「再生を許可」を押してください。','動画を読み込めません。URL・形式・HTTPS を確認してください。','他の参加者が操作しました。最新状態で再試行してください。'],\n };\n const t = texts[language] || texts.en;\n ['title','lead','url-label','load','unlock','note'].forEach((id,i) => $(id).textContent=t[i]);\n $('play').ariaLabel=zh?'同步播放':'Play for everyone'; $('pause').ariaLabel=zh?'同步暂停':'Pause for everyone';\n $('fullscreen').ariaLabel=zh?'全屏':'Fullscreen';\n let snapshot=context.snapshot, offset=snapshot.serverTime-Date.now(), source='', busy=false, seeking=false, playingAttempt=false;\n video.volume=.7;\n function validState(value) {\n if(!value || typeof value.url!=='string' || value.url.length>2048 || typeof value.playing!=='boolean' || !Number.isFinite(value.position) || value.position<0 || value.position>604800 || !Number.isFinite(value.updatedAt)) return null;\n try {const u=new URL(value.url);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)return null;}catch{return null;}\n return value;\n }\n function targetPosition(state) {return Math.max(0,Math.min(604800,state.position+(state.playing?Math.max(0,(Date.now()+offset-state.updatedAt)/1000):0)));}\n function status(message='') {$('status').textContent=message;}\n async function apply() {\n const state=validState(snapshot.state); if(!state)return;\n if(source!==state.url){source=state.url;video.src=source;$('url').value=source;video.load();}\n const desired=targetPosition(state);\n if(Number.isFinite(video.duration)&&video.duration>0&&desired>=video.duration){video.pause();video.playbackRate=1;return;}\n if(video.readyState>=1 && !seeking){const diff=desired-video.currentTime;\n if(Math.abs(diff)>(state.playing?.7:.04))video.currentTime=Math.min(desired,Number.isFinite(video.duration)?video.duration:desired);\n video.playbackRate=state.playing&&Math.abs(diff)>.15&&Math.abs(diff)<=.7?(diff>0?1.03:.97):1;\n }\n if(state.playing&&video.paused&&!playingAttempt){playingAttempt=true;try{await video.play();status();}catch{status(t[6]);}finally{playingAttempt=false;}}\n else if(!state.playing&&!video.paused)video.pause();\n }\n function receive(next) {if(next.roomId!==snapshot.roomId || next.revision{if($('url').checkValidity())void update({url:$('url').value.trim(),position:0,playing:false});else $('url').reportValidity();};\n $('load').addEventListener('click',load);\n $('source').addEventListener('submit',event=>event.preventDefault());\n $('url').addEventListener('keydown',event=>{if(event.key==='Enter'){event.preventDefault();load();}});\n $('play').addEventListener('click',()=>{void video.play().catch(()=>status(t[6]));void update({playing:true});});\n $('pause').addEventListener('click',()=>void update({playing:false,position:video.currentTime}));\n $('unlock').addEventListener('click',()=>{void video.play().then(()=>{if(!snapshot.state?.playing)video.pause();status();}).catch(()=>status(t[6]));});\n $('fullscreen').addEventListener('click',()=>void video.requestFullscreen?.().catch(()=>undefined));\n $('volume').addEventListener('input',()=>video.volume=Number($('volume').value));\n $('seek').addEventListener('input',()=>{seeking=true;});\n $('seek').addEventListener('change',()=>{seeking=false;void update({position:Number($('seek').value)});});\n video.addEventListener('loadedmetadata',()=>void apply()); video.addEventListener('error',()=>status(t[7]));\n video.addEventListener('ended',()=>{video.playbackRate=1;});\n const time=value=>`${Math.floor(value/60)}:${Math.floor(value%60).toString().padStart(2,'0')}`;\n const timer=setInterval(()=>{void apply();const duration=Number.isFinite(video.duration)?video.duration:0;$('seek').max=String(duration||1);if(!seeking)$('seek').value=String(video.currentTime);$('time').textContent=`${time(video.currentTime)} / ${time(duration)}`;},1000);\n const unsubscribe=api.room.subscribe(receive);receive(snapshot);\n addEventListener('pagehide',()=>{clearInterval(timer);unsubscribe();video.pause();video.removeAttribute('src');video.load();},{once:true});\n})();\n","styles":{"light":"body{background:#f2f7f6;color:#183c38}main{max-width:850px;margin:auto}header{display:flex;gap:16px;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0}p{line-height:1.5}form{display:flex;gap:10px;margin:16px 0;align-items:end}label{display:grid;gap:6px;flex:1;min-width:0}input[type=url]{width:100%;padding:10px;border:1px solid #83aaa4;border-radius:8px;background:#fff;color:#183c38;font:inherit}button{padding:10px 15px;border:1px solid #739e96;border-radius:8px;background:#e0f1eb;color:#174d41;font:inherit;cursor:pointer}button:disabled{opacity:.5}video{display:block;width:100%;max-height:50vh;min-height:180px;background:#101719;border-radius:12px}.controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0}.volume{display:flex;align-items:center;max-width:150px}.volume input{min-width:0;width:100%}.seek{display:grid;grid-template-columns:100px 1fr;align-items:center}.seek input{width:100%}.note,#members{font-size:13px;opacity:.75}#status{min-height:1.5em;color:#a33c24}input[type=range]{accent-color:#168575}@media(max-width:500px){form{flex-wrap:wrap}form label{flex-basis:100%}.seek{grid-template-columns:1fr}}\n","dark":"body{background:#20242b;color:#e9eeee}main{max-width:850px;margin:auto}header{display:flex;gap:16px;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0}p{line-height:1.5}form{display:flex;gap:10px;margin:16px 0;align-items:end}label{display:grid;gap:6px;flex:1;min-width:0}input[type=url]{width:100%;padding:10px;border:1px solid #58676b;border-radius:8px;background:#303840;color:#e9eeee;font:inherit}button{padding:10px 15px;border:1px solid #588579;border-radius:8px;background:#254c43;color:#dcfff4;font:inherit;cursor:pointer}button:disabled{opacity:.5}video{display:block;width:100%;max-height:50vh;min-height:180px;background:#080c0e;border-radius:12px}.controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0}.volume{display:flex;align-items:center;max-width:150px}.volume input{min-width:0;width:100%}.seek{display:grid;grid-template-columns:100px 1fr;align-items:center}.seek input{width:100%}.note,#members{font-size:13px;opacity:.75}#status{min-height:1.5em;color:#ffaf91}input[type=range]{accent-color:#7cdbc2}@media(max-width:500px){form{flex-wrap:wrap}form label{flex-basis:100%}.seek{grid-template-columns:1fr}}\n"}} \ No newline at end of file diff --git a/docs/examples/watch-together/dark.css b/docs/examples/watch-together/dark.css new file mode 100644 index 0000000..871b04a --- /dev/null +++ b/docs/examples/watch-together/dark.css @@ -0,0 +1 @@ +body{background:#20242b;color:#e9eeee}main{max-width:850px;margin:auto}header{display:flex;gap:16px;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0}p{line-height:1.5}form{display:flex;gap:10px;margin:16px 0;align-items:end}label{display:grid;gap:6px;flex:1;min-width:0}input[type=url]{width:100%;padding:10px;border:1px solid #58676b;border-radius:8px;background:#303840;color:#e9eeee;font:inherit}button{padding:10px 15px;border:1px solid #588579;border-radius:8px;background:#254c43;color:#dcfff4;font:inherit;cursor:pointer}button:disabled{opacity:.5}video{display:block;width:100%;max-height:50vh;min-height:180px;background:#080c0e;border-radius:12px}.controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0}.volume{display:flex;align-items:center;max-width:150px}.volume input{min-width:0;width:100%}.seek{display:grid;grid-template-columns:100px 1fr;align-items:center}.seek input{width:100%}.note,#members{font-size:13px;opacity:.75}#status{min-height:1.5em;color:#ffaf91}input[type=range]{accent-color:#7cdbc2}@media(max-width:500px){form{flex-wrap:wrap}form label{flex-basis:100%}.seek{grid-template-columns:1fr}} diff --git a/docs/examples/watch-together/light.css b/docs/examples/watch-together/light.css new file mode 100644 index 0000000..25685aa --- /dev/null +++ b/docs/examples/watch-together/light.css @@ -0,0 +1 @@ +body{background:#f2f7f6;color:#183c38}main{max-width:850px;margin:auto}header{display:flex;gap:16px;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0}p{line-height:1.5}form{display:flex;gap:10px;margin:16px 0;align-items:end}label{display:grid;gap:6px;flex:1;min-width:0}input[type=url]{width:100%;padding:10px;border:1px solid #83aaa4;border-radius:8px;background:#fff;color:#183c38;font:inherit}button{padding:10px 15px;border:1px solid #739e96;border-radius:8px;background:#e0f1eb;color:#174d41;font:inherit;cursor:pointer}button:disabled{opacity:.5}video{display:block;width:100%;max-height:50vh;min-height:180px;background:#101719;border-radius:12px}.controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0}.volume{display:flex;align-items:center;max-width:150px}.volume input{min-width:0;width:100%}.seek{display:grid;grid-template-columns:100px 1fr;align-items:center}.seek input{width:100%}.note,#members{font-size:13px;opacity:.75}#status{min-height:1.5em;color:#a33c24}input[type=range]{accent-color:#168575}@media(max-width:500px){form{flex-wrap:wrap}form label{flex-basis:100%}.seek{grid-template-columns:1fr}} diff --git a/docs/examples/watch-together/manifest.json b/docs/examples/watch-together/manifest.json new file mode 100644 index 0000000..dc9580c --- /dev/null +++ b/docs/examples/watch-together/manifest.json @@ -0,0 +1,11 @@ +{ + "apiVersion": 1, + "id": "community.watch-together", + "name": "Watch Together / 一起观看", + "version": "1.0.0", + "author": "Huddle-Up-Forge", + "license": "AGPL-3.0-only", + "description": "A shared video player with synchronized playback, pause and seeking. / 同步播放、暂停与跳转的视频播放器。", + "scopes": ["server", "instance"], + "permissions": ["room.read", "room.write"] +} diff --git a/docs/examples/watch-together/panel.html b/docs/examples/watch-together/panel.html new file mode 100644 index 0000000..7f18578 --- /dev/null +++ b/docs/examples/watch-together/panel.html @@ -0,0 +1,10 @@ +
+

Watch Together

+

+
+ +
+ +

+

+
diff --git a/docs/examples/watch-together/player.js b/docs/examples/watch-together/player.js new file mode 100644 index 0000000..0f39305 --- /dev/null +++ b/docs/examples/watch-together/player.js @@ -0,0 +1,65 @@ +/* Uses only the public plugin API. Nothing here imports WebSpeak internals. */ +(async () => { + const api = window.webspeak, context = await api.ready; + const $ = id => document.getElementById(id), video = $('video'); + const language = context.language, zh = language === 'zh'; + const texts = { + zh: ['一起观看','所有参与者共享播放、暂停和进度;音量仅影响自己。','视频直链','载入视频','允许播放','请使用浏览器支持的 MP4 / WebM 视频直链。不会把视频经过 WebSpeak 服务器转发。','浏览器阻止自动播放,请点击“允许播放”。','视频无法加载,请检查地址、格式与 HTTPS。','有人同时操作,已获取最新进度,请重试。'], + en: ['Watch Together','Playback, pause and seeking are shared; volume is local.','Direct video URL','Load video','Enable playback','Use a browser-compatible MP4 / WebM URL. Video is fetched directly, never relayed by WebSpeak.','Autoplay was blocked. Click Enable playback.','Video could not load. Check URL, format and HTTPS.','Another participant changed playback. Refreshed; please try again.'], + de: ['Gemeinsam ansehen','Wiedergabe, Pause und Position sind gemeinsam; Lautstärke ist lokal.','Direkte Video-URL','Video laden','Wiedergabe erlauben','Browserkompatible MP4-/WebM-URL verwenden. Video wird direkt geladen.','Autoplay blockiert. Wiedergabe erlauben anklicken.','Video nicht ladbar. URL, Format und HTTPS prüfen.','Gleichzeitige Änderung. Aktualisiert; erneut versuchen.'], + ru: ['Смотреть вместе','Воспроизведение, пауза и позиция общие; громкость локальная.','Прямая ссылка на видео','Загрузить видео','Разрешить воспроизведение','Используйте прямую ссылку MP4 / WebM. Видео загружается напрямую.','Автовоспроизведение заблокировано. Нажмите Разрешить воспроизведение.','Не удалось загрузить видео. Проверьте адрес, формат и HTTPS.','Другой участник изменил состояние. Обновлено; повторите.'], + ja: ['一緒に見る','再生・停止・位置を共有します。音量は自分の端末のみです。','動画の直接 URL','動画を読み込む','再生を許可','ブラウザー対応の MP4 / WebM URL を使用します。動画は直接取得されます。','自動再生がブロックされました。「再生を許可」を押してください。','動画を読み込めません。URL・形式・HTTPS を確認してください。','他の参加者が操作しました。最新状態で再試行してください。'], + }; + const t = texts[language] || texts.en; + ['title','lead','url-label','load','unlock','note'].forEach((id,i) => $(id).textContent=t[i]); + $('play').ariaLabel=zh?'同步播放':'Play for everyone'; $('pause').ariaLabel=zh?'同步暂停':'Pause for everyone'; + $('fullscreen').ariaLabel=zh?'全屏':'Fullscreen'; + let snapshot=context.snapshot, offset=snapshot.serverTime-Date.now(), source='', busy=false, seeking=false, playingAttempt=false; + video.volume=.7; + function validState(value) { + if(!value || typeof value.url!=='string' || value.url.length>2048 || typeof value.playing!=='boolean' || !Number.isFinite(value.position) || value.position<0 || value.position>604800 || !Number.isFinite(value.updatedAt)) return null; + try {const u=new URL(value.url);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)return null;}catch{return null;} + return value; + } + function targetPosition(state) {return Math.max(0,Math.min(604800,state.position+(state.playing?Math.max(0,(Date.now()+offset-state.updatedAt)/1000):0)));} + function status(message='') {$('status').textContent=message;} + async function apply() { + const state=validState(snapshot.state); if(!state)return; + if(source!==state.url){source=state.url;video.src=source;$('url').value=source;video.load();} + const desired=targetPosition(state); + if(Number.isFinite(video.duration)&&video.duration>0&&desired>=video.duration){video.pause();video.playbackRate=1;return;} + if(video.readyState>=1 && !seeking){const diff=desired-video.currentTime; + if(Math.abs(diff)>(state.playing?.7:.04))video.currentTime=Math.min(desired,Number.isFinite(video.duration)?video.duration:desired); + video.playbackRate=state.playing&&Math.abs(diff)>.15&&Math.abs(diff)<=.7?(diff>0?1.03:.97):1; + } + if(state.playing&&video.paused&&!playingAttempt){playingAttempt=true;try{await video.play();status();}catch{status(t[6]);}finally{playingAttempt=false;}} + else if(!state.playing&&!video.paused)video.pause(); + } + function receive(next) {if(next.roomId!==snapshot.roomId || next.revision{if($('url').checkValidity())void update({url:$('url').value.trim(),position:0,playing:false});else $('url').reportValidity();}; + $('load').addEventListener('click',load); + $('source').addEventListener('submit',event=>event.preventDefault()); + $('url').addEventListener('keydown',event=>{if(event.key==='Enter'){event.preventDefault();load();}}); + $('play').addEventListener('click',()=>{void video.play().catch(()=>status(t[6]));void update({playing:true});}); + $('pause').addEventListener('click',()=>void update({playing:false,position:video.currentTime})); + $('unlock').addEventListener('click',()=>{void video.play().then(()=>{if(!snapshot.state?.playing)video.pause();status();}).catch(()=>status(t[6]));}); + $('fullscreen').addEventListener('click',()=>void video.requestFullscreen?.().catch(()=>undefined)); + $('volume').addEventListener('input',()=>video.volume=Number($('volume').value)); + $('seek').addEventListener('input',()=>{seeking=true;}); + $('seek').addEventListener('change',()=>{seeking=false;void update({position:Number($('seek').value)});}); + video.addEventListener('loadedmetadata',()=>void apply()); video.addEventListener('error',()=>status(t[7])); + video.addEventListener('ended',()=>{video.playbackRate=1;}); + const time=value=>`${Math.floor(value/60)}:${Math.floor(value%60).toString().padStart(2,'0')}`; + const timer=setInterval(()=>{void apply();const duration=Number.isFinite(video.duration)?video.duration:0;$('seek').max=String(duration||1);if(!seeking)$('seek').value=String(video.currentTime);$('time').textContent=`${time(video.currentTime)} / ${time(duration)}`;},1000); + const unsubscribe=api.room.subscribe(receive);receive(snapshot); + addEventListener('pagehide',()=>{clearInterval(timer);unsubscribe();video.pause();video.removeAttribute('src');video.load();},{once:true}); +})(); diff --git a/package.json b/package.json index d094158..6bb2939 100644 --- a/package.json +++ b/package.json @@ -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 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-transport.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,7 +26,8 @@ "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:example:build": "node --import tsx scripts/build-plugin.mjs docs/examples/watch-together docs/examples/watch-together.wplugin" }, "dependencies": { "@discordjs/opus": "^0.10.0", diff --git a/scripts/build-plugin.mjs b/scripts/build-plugin.mjs new file mode 100644 index 0000000..4b07d8d --- /dev/null +++ b/scripts/build-plugin.mjs @@ -0,0 +1,9 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { parsePluginPackage } from '../src/shared/plugins.ts'; +const [input, output] = process.argv.slice(2); +if (!input || !output) throw new Error('Usage: node --import tsx scripts/build-plugin.mjs SOURCE_DIR OUTPUT.wplugin'); +const read = file => readFile(path.join(input, file), 'utf8'); +const pack = parsePluginPackage({manifest:JSON.parse(await read('manifest.json')),html:await read('panel.html'),script:await read('player.js'),styles:{light:await read('light.css'),dark:await read('dark.css')}}); +await writeFile(output, JSON.stringify(pack)); +console.log(`${pack.manifest.id} v${pack.manifest.version} -> ${output}`); diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts index b6a5ec9..74faf65 100644 --- a/src/admin/admin-router.ts +++ b/src/admin/admin-router.ts @@ -8,6 +8,9 @@ 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"; export interface AdminConnectionRecord { id: string; @@ -38,6 +41,8 @@ export interface AdminRouterOptions { logFile?: string; skinRegistry?: SkinRegistry; skinStore?: SkinStore; + pluginRegistry?: PluginRegistry; + pluginStore?: PluginStore; startedAt: number; } @@ -126,6 +131,10 @@ export function createAdminRouter(options: AdminRouterOptions): Router { }); router.use(requireAdmin(options.sessions, options.service)); + router.use("/plugins", createPluginAdminRouter({ registry: options.pluginRegistry, store: options.pluginStore, + protect: [requireSameOrigin, requireCsrf(options.sessions)], + audit: (event, data) => options.service.database.addAudit(event, data), + })); router.get("/overview", (_request, response) => { response.json(options.service.getOverview( diff --git a/src/index.ts b/src/index.ts index bd1046e..1b82b9a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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")); + await pluginRegistry.initialize(); logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server"); @@ -70,6 +73,7 @@ async function main() { }, adminService, skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")), + pluginRegistry, logger, nextVisitorNumber: () => database.nextVisitorNumber(), visitorCount: () => database.getVisitorCount(), diff --git a/src/plugins/admin-router.ts b/src/plugins/admin-router.ts new file mode 100644 index 0000000..a68b68b --- /dev/null +++ b/src/plugins/admin-router.ts @@ -0,0 +1,49 @@ +import { Router, type RequestHandler } from "express"; +import { PluginRegistry } from "./registry.js"; +import { PluginStore } from "./store.js"; +import { pluginAssert, pluginRecord, PluginError, parsePluginPackage } from "../shared/plugins.js"; + +export function createPluginAdminRouter(options: { + registry?: PluginRegistry; store?: PluginStore; 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); + }); + const registry = () => { pluginAssert(options.registry, "PLUGIN_STORAGE_UNAVAILABLE"); return options.registry; }; + router.get("/", (_request, response) => response.json({ plugins: registry().list() })); + 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 }); + }); + 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 }); + }); + 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); + options.audit("ADMIN_PLUGIN_CONFIGURED", { id: plugin.manifest.id }); + response.json({ 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); + 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 code = error instanceof PluginError ? error.code : "PLUGIN_FAILED"; + response.status(code === "PLUGIN_STORE_UNAVAILABLE" ? 502 : code === "PLUGIN_NOT_FOUND" ? 404 : code === "PLUGIN_CHANGED" ? 409 : 400).json({ ok: false, code }); + }); + return router; +} diff --git a/src/plugins/coordinator.ts b/src/plugins/coordinator.ts new file mode 100644 index 0000000..733f109 --- /dev/null +++ b/src/plugins/coordinator.ts @@ -0,0 +1,107 @@ +import { randomUUID } from "node:crypto"; +import { teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js"; +import { PluginRegistry } from "./registry.js"; +import { parsePluginRequest, pluginAssert, PluginError, type PluginMessage, type JsonValue, type PluginRequest, type PluginRoomSnapshot } from "../shared/plugins.js"; + +export interface PluginParticipant { + id: string; nickname: string; target: TeamSpeakTarget; + session: { state: string }; + tsClient: { getChannelId(): bigint; isConnected(): boolean }; +} +interface Membership { room: string; packageRevision: string } +interface Room { id: string; state: JsonValue; revision: number; members: Set; writeWindow: number; writes: number } +/** Generic bounded JSON rooms. No package code or video-specific behavior runs on the server. */ +export class PluginCoordinator { + private readonly rooms = new Map(); + private readonly memberships = new Map>(); + private readonly limits = new Map(); + private readonly changed = (id: string) => { + for (const [entryId, memberships] of [...this.memberships]) if (memberships.has(id)) this.leave(entryId, id, "PLUGIN_CHANGED"); + }; + constructor(private readonly registry: PluginRegistry | undefined, private readonly entries: ReadonlyMap, + private readonly send: (entryId: string, message: PluginMessage) => void) { registry?.listeners.add(this.changed); } + private key(entry: PluginParticipant, id: string): string { + const plugin = this.registry?.policy(id); pluginAssert(plugin?.settings.enabled, "PLUGIN_DISABLED"); + pluginAssert(entry.session.state === "connected" && entry.tsClient.isConnected(), "PLUGIN_NOT_CONNECTED"); + if (plugin.settings.scope === "instance") return `${id}\u0000instance`; + const target = teamSpeakTargetKey(entry.target); + pluginAssert(plugin.settings.targets.includes(target), "PLUGIN_NOT_ALLOWED"); + return `${id}\u0000${target}\u0000${entry.tsClient.getChannelId()}`; + } + private snapshot(room: Room): PluginRoomSnapshot { + return { roomId: room.id, revision: room.revision, state: structuredClone(room.state), serverTime: Date.now(), + participants: [...room.members].flatMap(id => { const e = this.entries.get(id); return e ? [{ id, nickname: e.nickname }] : []; }) }; + } + private broadcast(key: string, id: string): void { + const room = this.rooms.get(key); if (!room) return; + for (const entryId of [...room.members]) { + const entry = this.entries.get(entryId); let valid = false; + try { valid = !!entry && this.key(entry, id) === key; } catch { /* stale scope */ } + if (!valid) this.leave(entryId, id, "PLUGIN_CONTEXT_CHANGED", false); + } + const snapshot = this.snapshot(room); + if (this.registry?.policy(id)?.manifest.permissions.includes("room.read")) + for (const entryId of room.members) this.send(entryId, { type: "pluginEvent", pluginId: id, snapshot }); + } + handle(entry: PluginParticipant, value: unknown): void { + let request: PluginRequest; + try { request = parsePluginRequest(value); } + catch { return; } + const reply = (ok: boolean, result?: unknown, code?: string) => this.send(entry.id, { type: "pluginReply", requestId: request.requestId, ok, ...(ok ? { result } : { code }) }); + try { + const limit = this.limits.get(entry.id), now = Date.now(); + if (!limit || now - limit.time > 1000) this.limits.set(entry.id, { time: now, count: 1 }); + else if (request.action !== "close") pluginAssert(++limit.count <= 20, "PLUGIN_RATE_LIMITED"); + pluginAssert(entry.session.state === "connected" && entry.tsClient.isConnected(), "PLUGIN_NOT_CONNECTED"); + if (request.action === "list") { + const plugins = (this.registry?.list() ?? []).filter(p => { try { this.key(entry, p.manifest.id); return true; } catch { return false; } }); + reply(true, plugins.map(p => ({ manifest: p.manifest, revision: p.revision, scope: p.settings.scope }))); return; + } + const id = request.pluginId!; + if (request.action === "close") { this.leave(entry.id, id); reply(true, null); return; } + const key = this.key(entry, id), plugin = this.registry!.policy(id)!; + const memberships = this.memberships.get(entry.id) ?? new Map(); + const previous = memberships.get(id); + if (previous && (previous.room !== key || previous.packageRevision !== plugin.revision)) this.leave(entry.id, id, "PLUGIN_CONTEXT_CHANGED"); + if (request.action === "open") { + pluginAssert(memberships.size < 8 || memberships.has(id), "PLUGIN_LIMIT"); + let room = this.rooms.get(key); + if (!room) { pluginAssert(this.rooms.size < 800, "PLUGIN_LIMIT"); room = { id: randomUUID(), state: null, revision: 0, members: new Set(), writeWindow: 0, writes: 0 }; this.rooms.set(key, room); } + const current = this.memberships.get(entry.id) ?? new Map(); + current.set(id, { room: key, packageRevision: plugin.revision }); this.memberships.set(entry.id, current); room.members.add(entry.id); + const snapshot = plugin.manifest.permissions.includes("room.read") ? this.snapshot(room) + : { roomId: room.id, revision: 0, state: null, serverTime: Date.now(), participants: [] }; + reply(true, { package: this.registry!.get(id)!.package, config: plugin.settings.config, self: { id: entry.id, nickname: entry.nickname }, scope: plugin.settings.scope, snapshot }); + this.broadcast(key, id); return; + } + const membership = this.memberships.get(entry.id)?.get(id); + pluginAssert(membership?.room === key && membership.packageRevision === plugin.revision, "PLUGIN_NOT_OPEN"); + const room = this.rooms.get(key)!; + pluginAssert(plugin.manifest.permissions.includes("room.read"), "PLUGIN_PERMISSION_DENIED"); + if (request.action === "update") { + pluginAssert(plugin.manifest.permissions.includes("room.write"), "PLUGIN_PERMISSION_DENIED"); + pluginAssert(request.revision === room.revision, "PLUGIN_REVISION_CONFLICT"); + if (now - room.writeWindow >= 1000) { room.writeWindow = now; room.writes = 0; } + pluginAssert(++room.writes <= 10, "PLUGIN_RATE_LIMITED"); + room.state = request.state!; room.revision++; + } + reply(true, this.snapshot(room)); if (request.action === "update") this.broadcast(key, id); + } catch (error) { reply(false, undefined, error instanceof PluginError ? error.code : "PLUGIN_FAILED"); } + } + private leave(entryId: string, id: string, code?: string, broadcast = true): void { + const memberships = this.memberships.get(entryId), membership = memberships?.get(id); if (!membership) return; + memberships!.delete(id); if (!memberships!.size) this.memberships.delete(entryId); + const room = this.rooms.get(membership.room); room?.members.delete(entryId); + if (!room?.members.size) this.rooms.delete(membership.room); + if (code) this.send(entryId, { type: "pluginEvent", pluginId: id, snapshot: null, code }); + if (broadcast) this.broadcast(membership.room, id); + } + remove(entryId: string): void { for (const id of [...(this.memberships.get(entryId)?.keys() ?? [])]) this.leave(entryId, id, "PLUGIN_CONTEXT_CHANGED"); this.limits.delete(entryId); } + reconcile(entry: PluginParticipant): void { + for (const [id, membership] of [...(this.memberships.get(entry.id) ?? [])]) { + try { if (this.key(entry, id) !== membership.room) this.leave(entry.id, id, "PLUGIN_CONTEXT_CHANGED"); } + catch { this.leave(entry.id, id, "PLUGIN_CONTEXT_CHANGED"); } + } + } + dispose(): void { this.registry?.listeners.delete(this.changed); this.memberships.clear(); this.rooms.clear(); this.limits.clear(); } +} diff --git a/src/plugins/plugins.test.ts b/src/plugins/plugins.test.ts new file mode 100644 index 0000000..5731944 --- /dev/null +++ b/src/plugins/plugins.test.ts @@ -0,0 +1,115 @@ +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 { createHash } from 'node:crypto'; +import { PluginRegistry } from './registry.js'; +import { PluginCoordinator, type PluginParticipant } from './coordinator.js'; +import { PluginStore } from './store.js'; +import { parsePluginPackage, parsePluginJson, parsePluginRequest, PLUGIN_STORE_INDEX, type PluginMessage } from '../shared/plugins.js'; + +const example = () => readFile(new URL('../../docs/examples/watch-together.wplugin',import.meta.url),'utf8').then(t => parsePluginPackage(JSON.parse(t))); +async function registry(t: test.TestContext) { + const directory = await mkdtemp(path.join(tmpdir(),'webspeak-plugins-')); + t.after(async () => { assert.equal(path.dirname(directory), tmpdir()); await rm(directory,{recursive:true,force:true}); }); + const value = new PluginRegistry(directory); await value.initialize(); return { value, directory }; +} +function participant(id: string, host='one.example', channel=1n): PluginParticipant { + return {id,nickname:id,target:{host,port:9987},session:{state:'connected'},tsClient:{getChannelId:()=>channel,isConnected:()=>true}}; +} +test('package and state validators reject unsupported APIs, capabilities, prototype keys and excessive nesting',async () => { + const pack = await example(); assert.equal(pack.manifest.apiVersion,1); + assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,apiVersion:2}})); + assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,permissions:['admin.query']}})); + assert.throws(()=>parsePluginPackage({...pack,styles:{light:'x',dark:''}})); + assert.throws(()=>parsePluginJson(JSON.parse('{"__proto__":{"x":1}}'))); + assert.throws(()=>parsePluginJson(Array.from({length:5000},()=>1))); + assert.throws(()=>parsePluginJson({number:Infinity})); + assert.throws(()=>parsePluginRequest({type:'pluginRequest',requestId:'a',action:'update',pluginId:'a',revision:-1,state:null})); +}); +test('atomic persistence retains settings, requires CAS and disables code updates until reviewed',async t => { + const {value:r,directory} = await registry(t); const pack=await example(); + const first=await r.install(pack,null); assert.equal(first.settings.enabled,false); + const enabled=await r.configure(pack.manifest.id,{enabled:true,scope:'server',targets:['ONE.example#9987'],config:{title:'Public'}},first.revision); + assert.deepEqual(enabled.settings.targets,['one.example:9987']); + await assert.rejects(r.configure(pack.manifest.id,enabled.settings,first.revision),/PLUGIN_CHANGED/); + const reload=new PluginRegistry(directory); await reload.initialize(); assert.deepEqual(reload.list(),r.list()); + const updated=await r.install({...pack,script:'throw new Error("must never run on server")'},enabled.revision); + assert.equal(updated.settings.enabled,false); assert.deepEqual(updated.settings.config,{title:'Public'}); + await assert.rejects(r.remove(pack.manifest.id,enabled.revision),/PLUGIN_CHANGED/); + await r.remove(pack.manifest.id,updated.revision); assert.equal(r.list().length,0); + await assert.rejects(r.install({...pack,manifest:{...pack.manifest,id:'../../escape'}},null)); +}); +test('server rooms synchronize state with CAS, isolate target/channel, expire on moves and revoke on disable',async t => { + const {value:r}=await registry(t), pack=await example(), p=await r.install(pack,null); + const enabled=await r.configure(pack.manifest.id,{enabled:true,scope:'server',targets:['one.example:9987','two.example:9987'],config:{}},p.revision); + const entries=new Map([participant('a'),participant('b'),participant('c','one.example',2n),participant('d','two.example')].map(e=>[e.id,e])); + const messages:{id:string;message:PluginMessage}[]=[]; + const c=new PluginCoordinator(r,entries,(id,message)=>messages.push({id,message})); t.after(()=>c.dispose()); + let seq=0; const send=(id:string,action:string,fields={})=>{c.handle(entries.get(id)!,{type:'pluginRequest',requestId:`r-${++seq}`,action,pluginId:pack.manifest.id,...fields}); return messages.filter(v=>v.id===id&&v.message.type==='pluginReply').at(-1)!.message as Extract;}; + const a=send('a','open').result as any, b=send('b','open').result as any; + assert.equal(a.snapshot.roomId,b.snapshot.roomId); assert.notEqual((send('c','open').result as any).snapshot.roomId,a.snapshot.roomId); + assert.notEqual((send('d','open').result as any).snapshot.roomId,a.snapshot.roomId); + const state={url:'https://video.example/a.mp4',position:5,playing:true,updatedAt:Date.now()}; + assert.equal(send('a','update',{revision:0,state}).ok,true); + assert.equal(send('b','update',{revision:0,state:{position:9}}).code,'PLUGIN_REVISION_CONFLICT'); + assert.deepEqual((send('b','snapshot').result as any).state,state); + assert.equal(messages.some(v=>v.id==='c'&&v.message.type==='pluginEvent'&&v.message.snapshot?.state && (v.message.snapshot.state as any).url),false); + entries.get('a')!.tsClient.getChannelId=()=>2n; c.reconcile(entries.get('a')!); + assert.equal(send('a','snapshot').code,'PLUGIN_NOT_OPEN'); + assert.equal((send('b','snapshot').result as any).participants.length,1); + await r.configure(pack.manifest.id,{...enabled.settings,enabled:false},enabled.revision); + assert.equal(send('b','open').code,'PLUGIN_DISABLED'); + assert.ok(messages.some(v=>v.id==='b'&&v.message.type==='pluginEvent'&&v.message.snapshot===null)); +}); +test('instance rooms span targets but session readiness, write permission, quotas and teardown are enforced',async t => { + const {value:r}=await registry(t), pack=await example(), p=await r.install(pack,null); + const enabled=await r.configure(pack.manifest.id,{enabled:true,scope:'instance',targets:[],config:{}},p.revision); + const a=participant('a'),b=participant('b','another.example',5n), entries=new Map([[a.id,a],[b.id,b]]); + const messages:PluginMessage[]=[];const c=new PluginCoordinator(r,entries,(_id,m)=>messages.push(m));t.after(()=>c.dispose()); + let sequence=0;function send(e:PluginParticipant,action:string,fields={}){c.handle(e,{type:'pluginRequest',requestId:`r-${++sequence}`,pluginId:pack.manifest.id,action,...fields});return messages.filter(m=>m.type==='pluginReply').at(-1) as Extract;} + const first=send(a,'open').result as any;assert.equal((send(b,'open').result as any).snapshot.roomId,first.snapshot.roomId); + send(a,'update',{revision:0,state:{progress:30}});c.remove(a.id); + assert.deepEqual((send(b,'snapshot').result as any).state,{progress:30}); c.remove(b.id); + assert.equal((send(a,'open').result as any).snapshot.state,null); + a.session.state='reconnecting';assert.equal(send(a,'update',{revision:0,state:0}).code,'PLUGIN_NOT_CONNECTED');a.session.state='connected'; + const next=await r.install({...pack,manifest:{...pack.manifest,permissions:['room.read']}},enabled.revision); + await r.configure(pack.manifest.id,{...next.settings,enabled:true},next.revision);send(a,'open');assert.equal(send(a,'update',{revision:0,state:0}).code,'PLUGIN_PERMISSION_DENIED'); + for(let i=0;i<30;i++)send(a,'list');assert.equal((messages.filter(m=>m.type==='pluginReply').at(-1) as any).code,'PLUGIN_RATE_LIMITED'); +}); +test('GitHub distribution checks package hashes and reviewed metadata; redirects/arbitrary sources are rejected',async t => { + const {value:r}=await registry(t), pack=await example(), bytes=Buffer.from(JSON.stringify(pack)); + const repository='https://github.com/Huddle-Up-Forge/webspeak-plugin';let corrupt=false; + const metadata={manifest:pack.manifest,package:{ref:'main',path:'watch-together.wplugin',sha256:createHash('sha256').update(bytes).digest('hex')}}; + const visited:string[]=[]; + const store=new PluginStore(async(input,init)=>{ + const url=String(input);visited.push(url);assert.equal(init?.redirect,'error');assert.equal(init?.credentials,'omit'); + if(url===PLUGIN_STORE_INDEX)return Response.json({schemaVersion:1,plugins:[{id:pack.manifest.id,repository}]}); + if(url.endsWith('/HEAD/plugin.json'))return Response.json(metadata); + return new Response(corrupt?'{}':bytes); + }); + const entry=(await store.list()).entries[0];assert.equal(entry.error,null); + const installed=await store.install(r,{id:entry.id,revision:entry.revision,installedRevision:null});assert.equal(installed.settings.enabled,false); + corrupt=true;await assert.rejects(store.install(r,{id:entry.id,revision:entry.revision,installedRevision:installed.revision}),/PLUGIN_CHECKSUM/); + await assert.rejects(store.install(r,{id:entry.id,revision:'a'.repeat(64),installedRevision:installed.revision}),/PLUGIN_CHANGED/); + const bad=new PluginStore(async()=>Response.json({schemaVersion:1,plugins:[{id:'evil',repository:'http://127.0.0.1:3040'}]})); + await assert.rejects(bad.list(),/PLUGIN_INVALID/);assert.ok(visited.every(u=>u.startsWith('https://raw.githubusercontent.com/'))); +}); + +test('a UI-only plugin opens without shared data access, and read snapshots never broadcast to others',async t=>{ + const {value:r}=await registry(t),examplePack=await example(); + const pack={...examplePack,manifest:{...examplePack.manifest,permissions:[]}}; + const p=await r.install(pack,null);await r.configure(pack.manifest.id,{enabled:true,scope:'instance',targets:[],config:{}},p.revision); + const a=participant('a'),b=participant('b'),entries=new Map([[a.id,a],[b.id,b]]);const messages:{id:string;message:PluginMessage}[]=[]; + const c=new PluginCoordinator(r,entries,(id,message)=>messages.push({id,message}));t.after(()=>c.dispose()); + let seq=0;const send=(id:string,action:string,fields={})=>{c.handle(entries.get(id)!,{type:'pluginRequest',requestId:`r-${++seq}`,pluginId:pack.manifest.id,action,...fields});return messages.filter(m=>m.id===id&&m.message.type==='pluginReply').at(-1)!.message as Extract;}; + const open=send('a','open');assert.equal(open.ok,true);assert.deepEqual((open.result as any).snapshot.participants,[]); + assert.equal(send('a','snapshot').code,'PLUGIN_PERMISSION_DENIED');assert.equal(send('a','update',{revision:0,state:1}).code,'PLUGIN_PERMISSION_DENIED'); + const updated=await r.install(examplePack,r.list()[0].revision);await r.configure(pack.manifest.id,{...updated.settings,enabled:true},updated.revision); + send('a','open');send('b','open');const before=messages.length;send('a','snapshot');assert.equal(messages.length,before+1); + for(let revision=0;revision<10;revision++)assert.equal(send('a','update',{revision,state:revision}).ok,true); + assert.equal(send('b','update',{revision:10,state:11}).code,'PLUGIN_RATE_LIMITED'); + for(let i=0;i<20;i++)send('a','list');assert.equal(send('a','close').ok,true); + assert.equal((send('b','snapshot').result as any).participants.length,1); +}); diff --git a/src/plugins/registry.ts b/src/plugins/registry.ts new file mode 100644 index 0000000..2a4191b --- /dev/null +++ b/src/plugins/registry.ts @@ -0,0 +1,84 @@ +import { mkdir, readFile, readdir, writeFile, rename, unlink } from "node:fs/promises"; +import path from "node:path"; +import { createHash, randomUUID } from "node:crypto"; +import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js"; +import { parsePluginPackage, parsePluginJson, pluginAssert, pluginId, pluginRecord, PluginError, PLUGIN_LIMIT_BYTES, + type InstalledPlugin, type PluginPackage, type PluginSettings } from "../shared/plugins.js"; + +interface StoredPlugin extends InstalledPlugin { package: PluginPackage } +export class PluginRegistry { + private records = new Map(); + private queue: Promise = Promise.resolve(); + readonly listeners = new Set<(id: string) => void>(); + constructor(private readonly directory: string) {} + async initialize(): Promise { + await mkdir(this.directory, { recursive: true }); + for (const file of await readdir(this.directory)) { + if (!file.endsWith(".json")) continue; + try { + const raw = await readFile(path.join(this.directory, file)); + pluginAssert(raw.length <= PLUGIN_LIMIT_BYTES + 32 * 1024); + const value = JSON.parse(raw.toString("utf8")); + const pack = parsePluginPackage(value.package); + pluginAssert(file === `${pack.manifest.id}.json` && typeof value.installedAt === "number"); + const settings = this.settings(value.settings, pack); + this.records.set(pack.manifest.id, { package: pack, manifest: pack.manifest, settings, installedAt: value.installedAt, revision: this.hash(pack, settings) }); + } catch { /* An invalid package is never executed or exposed. */ } + } + } + list(): InstalledPlugin[] { return [...this.records.values()].map(({ package: _, ...value }) => structuredClone(value)); } + get(id: string): StoredPlugin | undefined { const r = this.records.get(id); return r ? structuredClone(r) : undefined; } + policy(id: string): InstalledPlugin | undefined { + const record = this.records.get(id); if (!record) return undefined; + const { package: _, ...policy } = record; return structuredClone(policy); + } + private hash(pack: PluginPackage, settings: PluginSettings): string { return createHash("sha256").update(JSON.stringify({ pack, settings })).digest("hex"); } + private settings(value: unknown, pack: PluginPackage): PluginSettings { + pluginAssert(pluginRecord(value) && typeof value.enabled === "boolean" && pack.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.scope !== "server" || !value.enabled || targets.length > 0, "PLUGIN_TARGET_REQUIRED"); + return { enabled: value.enabled, scope: value.scope as PluginSettings["scope"], targets, config: parsePluginJson(value.config, 8192) }; + } + private mutate(run: () => Promise): Promise { const next = this.queue.then(run, run); this.queue = next.catch(() => undefined); return next; } + private async commit(record: StoredPlugin): Promise { + const temporary = path.join(this.directory, `.${randomUUID()}.tmp`); + try { + await writeFile(temporary, JSON.stringify(record), { flag: "wx", mode: 0o600 }); + await rename(temporary, path.join(this.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 { /* Commit already succeeded. */ } } + const { package: _, ...result } = record; return structuredClone(result); + } + install(pack: PluginPackage, expectedRevision: string | null): Promise { + return this.mutate(async () => { + pack = parsePluginPackage(pack); + const previous = this.records.get(pack.manifest.id); + pluginAssert((previous?.revision ?? null) === expectedRevision, "PLUGIN_CHANGED"); + pluginAssert(previous || this.records.size < 50, "PLUGIN_LIMIT"); + // Updates require an explicit enable/review of the new permission set. + const settings = { ...(previous?.settings ?? { scope: pack.manifest.scopes[0], targets: [], config: {} }), enabled: false }; + if (!pack.manifest.scopes.includes(settings.scope)) settings.scope = pack.manifest.scopes[0]; + return this.commit({ package: pack, manifest: pack.manifest, settings, revision: this.hash(pack, settings), installedAt: previous?.installedAt ?? Date.now() }); + }); + } + configure(id: string, input: unknown, revision: string): Promise { + return this.mutate(async () => { + const record = this.records.get(id); pluginAssert(record, "PLUGIN_NOT_FOUND"); + pluginAssert(record.revision === revision, "PLUGIN_CHANGED"); + const settings = this.settings(input, record.package); + return this.commit({ ...record, settings, revision: this.hash(record.package, settings) }); + }); + } + remove(id: string, revision: string): Promise { + 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, `${id}.json`)); this.records.delete(id); + for (const listener of this.listeners) { try { listener(id); } catch { /* Removal already succeeded. */ } } + }); + } +} diff --git a/src/plugins/store.ts b/src/plugins/store.ts new file mode 100644 index 0000000..8925e6b --- /dev/null +++ b/src/plugins/store.ts @@ -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 { + 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 { + 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 === 1 && Array.isArray(root.plugins) && root.plugins.length <= 50); + const seen = new Set(); + 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 { + const sources = await this.sources(), entries = new Array(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); + } +} diff --git a/src/server/server.ts b/src/server/server.ts index 73e2bdb..c005470 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -18,6 +18,7 @@ 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"; export interface WebServerOptions { port: number; @@ -28,6 +29,7 @@ export interface WebServerOptions { voiceBridgeOptions: VoiceBridgeOptions; adminService: AdminService; skinRegistry?: SkinRegistry; + pluginRegistry?: PluginRegistry; logger: Logger; nextVisitorNumber?: () => number; visitorCount?: () => number; @@ -55,9 +57,10 @@ export function createWebServer(options: WebServerOptions): WebServer { server = createHttpServer(app); } + app.use("/api/admin/plugins/upload", express.json({ limit: "600kb" })); app.use(express.json({ limit: "100kb" })); - const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger); + const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRegistry: options.pluginRegistry }, logger); const adminSessions = new AdminSessionStore(); const joinRateLimiter = new JoinRateLimiter(); const startedAt = Date.now(); @@ -273,6 +276,7 @@ export function createWebServer(options: WebServerOptions): WebServer { getSessionSummaries: () => voiceBridge.getSessionSummaries(), terminateSession: (id) => voiceBridge.terminateSession(id), skinRegistry: options.skinRegistry, + pluginRegistry: options.pluginRegistry, version: options.version, logFile: options.logFile, startedAt, diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index a24d1a2..500b39b 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -27,6 +27,8 @@ 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 { PluginCoordinator } from "../plugins/coordinator.js"; +import type { PluginRegistry } from "../plugins/registry.js"; const HEARTBEAT_INTERVAL_MS = 30_000; const MAX_MISSED_HEARTBEATS = 2; @@ -49,6 +51,7 @@ function publicFailureDetail(error: ReturnType): } export interface VoiceBridgeOptions { + pluginRegistry?: PluginRegistry; joinTickets: JoinTicketStore; webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions); screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]); @@ -113,6 +116,7 @@ export class VoiceBridge { private readonly sessionManager = new SessionManager(); private readonly entries = new Map(); private readonly screenShares: ScreenShareCoordinator; + private readonly plugins: PluginCoordinator; private readonly identityLeases = new IdentityLeaseStore(); private wss: WebSocketServer | null = null; private heartbeatTimer: ReturnType | null = null; @@ -127,6 +131,14 @@ export class VoiceBridge { ) { this.logger = logger.child({ component: "voice-bridge" }); this.trustedProxies = createTrustedProxies(options.trustedProxies); + this.plugins = new PluginCoordinator(options.pluginRegistry, this.entries, (id, message) => { + const ws = this.entries.get(id)?.ws; + // Optional plugin traffic must not build an unbounded queue on the voice socket. + // A slow participant can request a fresh snapshot or reopen after draining. + if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount <= 512 * 1024) { + try { ws.send(JSON.stringify(message)); } catch { /* retired socket */ } + } + }); this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => { const entry = this.entries.get(entryId); if (entry?.ws.readyState === WebSocket.OPEN) { @@ -492,7 +504,10 @@ 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); + if (id === entry!.tsClient.getClientId()) queueMicrotask(() => this.plugins.reconcile(entry!)); + }, onNotification: notification => this.screenShares.handleNotification(entry!, notification), onVoice: data => entry!.audioTransport?.receiveTeamSpeak(data), onAvatarError: (clientId, uid, error) => this.logger.debug({ @@ -544,6 +559,7 @@ export class VoiceBridge { } if (session.state !== "connected") return; this.screenShares.removePeer(entryId); + this.plugins.remove(entryId); resetDirectoryForReconnect(); sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) }); scheduleReconnect(normalized); @@ -565,6 +581,12 @@ export class VoiceBridge { } const rawMessage = typeof data === "string" ? data : data.toString("utf-8"); + try { + const value: unknown = JSON.parse(rawMessage); + if (value && typeof value === "object" && "type" in value && value.type === "pluginRequest") { + this.plugins.reconcile(entry!); this.plugins.handle(entry!, value); return; + } + } catch { /* Existing command parser owns malformed messages. */ } const webRtcMessage = parseWebRtcClientMessage(rawMessage); if (webRtcMessage?.type === "webrtcOffer") { if (this.getWebRtcOptions()?.enabled !== true) { @@ -648,6 +670,7 @@ export class VoiceBridge { } async shutdown(): Promise { + this.plugins.dispose(); if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; @@ -712,6 +735,7 @@ export class VoiceBridge { private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise { this.screenShares.removePeer(entry.id); + this.plugins.remove(entry.id); if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id); entry.events?.close(); entry.events = null; diff --git a/src/shared/plugins.ts b/src/shared/plugins.ts new file mode 100644 index 0000000..f42af43 --- /dev/null +++ b/src/shared/plugins.ts @@ -0,0 +1,101 @@ +/** Versioned, browser-safe functional plugin contract; independent of .wskin. */ +export const PLUGIN_API_VERSION = 1; +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 = 512 * 1024; +export const PLUGIN_STATE_LIMIT_BYTES = 16 * 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 => !!v && typeof v === "object" && !Array.isArray(v); +export type PluginScope = "server" | "instance"; +export type PluginPermission = "room.read" | "room.write"; +export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; +export interface PluginManifest { + apiVersion: 1; id: string; name: string; version: string; author: string; license: string; description: string; + scopes: PluginScope[]; permissions: PluginPermission[]; +} +/** UTF-8 JSON package; code executes only in an opaque-origin browser iframe. */ +export interface PluginPackage { manifest: PluginManifest; html: string; script: string; styles: { light: string; dark: string } } +export interface PluginSettings { enabled: boolean; scope: PluginScope; targets: string[]; config: JsonValue } +export interface InstalledPlugin { manifest: PluginManifest; settings: PluginSettings; revision: string; installedAt: number } +export interface PluginStoreEntry { id: string; repository: string; metadataPath: string; manifest: PluginManifest | null; revision: string; error: string | null } +export interface PluginCatalog { repository: string; entries: PluginStoreEntry[] } +export interface PluginRoomSnapshot { roomId: string; revision: number; state: JsonValue; serverTime: number; participants: { id: string; nickname: string }[] } +export interface PluginRequest { type: "pluginRequest"; requestId: string; action: "list" | "open" | "snapshot" | "update" | "close"; pluginId?: string; revision?: number; state?: JsonValue } +export type PluginMessage = + | { type: "pluginReply"; requestId: string; ok: boolean; result?: unknown; code?: string } + | { type: "pluginEvent"; pluginId: string; snapshot: PluginRoomSnapshot | null; code?: string }; + +export class PluginError extends Error { + constructor(readonly code: string) { super(code); this.name = "PluginError"; } +} +export function pluginAssert(value: unknown, code = "PLUGIN_INVALID"): asserts value { + if (!value) throw new PluginError(code); +} +export function parsePluginManifest(value: unknown): PluginManifest { + pluginAssert(pluginRecord(value)); + pluginAssert(value.apiVersion === 1 && pluginId(value.id)); + for (const [key, max] of [["name",80],["author",80],["license",80],["description",400],["version",32]] as const) + pluginAssert(typeof value[key] === "string" && value[key].trim().length > 0 && value[key].length <= max && !/[\u0000-\u001f\u007f]/.test(value[key])); + pluginAssert(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(value.version as string)); + pluginAssert(Array.isArray(value.scopes) && value.scopes.length > 0 && value.scopes.length <= 2 && new Set(value.scopes).size === value.scopes.length && value.scopes.every(s => s === "server" || s === "instance")); + pluginAssert(Array.isArray(value.permissions) && value.permissions.length <= 2 && new Set(value.permissions).size === value.permissions.length && value.permissions.every(p => p === "room.read" || p === "room.write")); + pluginAssert(!value.permissions.includes("room.write") || value.permissions.includes("room.read")); + return { apiVersion: 1, id: value.id, name: value.name as string, version: value.version as string, author: value.author as string, + license: value.license as string, description: value.description as string, scopes: [...value.scopes], permissions: [...value.permissions] }; +} +export function parsePluginPackage(value: unknown): PluginPackage { + pluginAssert(pluginRecord(value) && pluginRecord(value.styles)); + for (const s of [value.html, value.script, value.styles.light, value.styles.dark]) pluginAssert(typeof s === "string" && s.trim().length > 0 && s.length <= 256 * 1024); + const result = { manifest: parsePluginManifest(value.manifest), html: value.html as string, script: value.script as string, + styles: { light: value.styles.light as string, dark: value.styles.dark as string } }; + pluginAssert(new TextEncoder().encode(JSON.stringify(result)).length <= PLUGIN_LIMIT_BYTES, "PLUGIN_TOO_LARGE"); + return result; +} +export function parsePluginJson(value: unknown, maxBytes = PLUGIN_STATE_LIMIT_BYTES): JsonValue { + let count = 0; + function visit(v: unknown, depth: number): void { + pluginAssert(depth <= 16 && ++count <= 4096); + if (v === null || typeof v === "boolean" || typeof v === "string") return; + if (typeof v === "number") { pluginAssert(Number.isFinite(v)); return; } + pluginAssert(Array.isArray(v) || pluginRecord(v)); + if (Array.isArray(v)) v.forEach(x => visit(x, depth + 1)); + else for (const [key, item] of Object.entries(v)) { pluginAssert(!["__proto__", "prototype", "constructor"].includes(key)); visit(item, depth + 1); } + } + visit(value, 0); + const json = JSON.stringify(value); + pluginAssert(new TextEncoder().encode(json).length <= maxBytes, "PLUGIN_TOO_LARGE"); + return JSON.parse(json) as JsonValue; +} +export function parsePluginRequest(value: unknown): PluginRequest { + pluginAssert(pluginRecord(value) && value.type === "pluginRequest" && typeof value.requestId === "string" && /^[a-zA-Z0-9-]{1,80}$/.test(value.requestId)); + pluginAssert(["list", "open", "snapshot", "update", "close"].includes(String(value.action))); + pluginAssert(value.action === "list" || pluginId(value.pluginId)); + if (value.action === "update") pluginAssert(Number.isSafeInteger(value.revision) && (value.revision as number) >= 0); + return { type: "pluginRequest", requestId: value.requestId, action: value.action as PluginRequest["action"], + ...(value.action === "list" ? {} : { pluginId: value.pluginId as string }), + ...(value.action === "update" ? { revision: value.revision as number, state: parsePluginJson(value.state) } : {}) }; +} + +export function readInstalledPlugin(value: unknown): InstalledPlugin { + pluginAssert(pluginRecord(value) && pluginRecord(value.settings) && typeof value.revision === "string" && /^[a-f0-9]{64}$/.test(value.revision) && typeof value.installedAt === "number" && Number.isFinite(value.installedAt)); + const manifest = parsePluginManifest(value.manifest), s = value.settings; + pluginAssert(typeof s.enabled === "boolean" && manifest.scopes.includes(s.scope as never) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t => typeof t === "string" && t.length <= 300)); + return { manifest, revision: value.revision, installedAt: value.installedAt, + settings: { enabled: s.enabled, scope: s.scope as PluginScope, targets: [...s.targets], config: parsePluginJson(s.config, 8192) } }; +} +export const pluginResponses = { + installed(value: unknown): { plugins: InstalledPlugin[] } { + pluginAssert(pluginRecord(value) && Array.isArray(value.plugins) && value.plugins.length <= 50); + return { plugins: value.plugins.map(readInstalledPlugin) }; + }, + saved(value: unknown): { plugin: InstalledPlugin } { pluginAssert(pluginRecord(value)); return { plugin: readInstalledPlugin(value.plugin) }; }, + catalog(value: unknown): PluginCatalog { + pluginAssert(pluginRecord(value) && value.repository === PLUGIN_STORE_REPOSITORY && Array.isArray(value.entries) && value.entries.length <= 50); + const entries = value.entries.map(v => { + pluginAssert(pluginRecord(v) && pluginId(v.id) && typeof v.repository === "string" && /^https:\/\/github\.com\/[a-zA-Z0-9-]+\/[a-zA-Z0-9_.-]+$/.test(v.repository) + && typeof v.metadataPath === "string" && typeof v.revision === "string" && (v.error === null || typeof v.error === "string")); + return { id: v.id, repository: v.repository, metadataPath: v.metadataPath, revision: v.revision, error: v.error, manifest: v.manifest === null ? null : parsePluginManifest(v.manifest) }; + }); + return { repository: value.repository, entries }; + }, +}; diff --git a/web/src/components/Icon.vue b/web/src/components/Icon.vue index d38b30d..078b39b 100644 --- a/web/src/components/Icon.vue +++ b/web/src/components/Icon.vue @@ -18,6 +18,9 @@ +