mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-11-30 18:42:49 +08:00
feat: add plugin application runtime and unified instance authorization
This commit is contained in:
1 parent
8bca848c21
commit
3430a8a753
80 files changed
+2133
-1004
No files matched your search
@@ -1,20 +1,32 @@
|
||||
---
|
||||
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.
|
||||
description: Build, review and package WebSpeak API v2 functional applications with standard browser code and optional Node services, including GitHub distribution. Use for .wplugin applications rather than .wskin skins or their presentation components.
|
||||
---
|
||||
|
||||
# WebSpeak Plugin Development
|
||||
# WebSpeak Application 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 [application runtime guide](../../../docs/PLUGIN_DEVELOPMENT.md). In a standalone checkout, use `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/dev/docs/PLUGIN_DEVELOPMENT.md`. Confirm API v2 support on the target instance; stable v0.2.9 has none. API v1 and its shared-room examples are removed.
|
||||
|
||||
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.
|
||||
Develop an independent application, not a list of host business RPC calls. Use ordinary HTML/CSS/JavaScript, browser APIs and optional Node services with author-defined routes, dependencies and state. The host provides authenticated context, configuration, package/lifecycle management and a separate origin. It supplies no room API or feature permission list. Keep application business logic in its package; a host defect or missing general runtime primitive is a separate host change.
|
||||
|
||||
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.
|
||||
Start with `docs/templates/plugin-app/` or the distribution repository's `template/`. Put frontend output under `client/` with relative assets and optional `.mjs/.cjs` activation code under `server/`. Include audited dependencies or bundle them; the host does not run package installers. Native dependencies must match target OS and Node ABI. Build with `node scripts/build-plugin.mjs SOURCE_DIR OUTPUT.wplugin`, or the standalone distribution builder, then import the actual output.
|
||||
|
||||
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.
|
||||
Use `webspeak.ready`, `getContext()`, `onContextChange()` and `signal` for generic context; implement functionality through native browser/Node code. Scope provides admission and a grouping key, not synchronization. Server logic must enforce scope and business access. Prefer host-verified `req.webspeak` over browser-supplied identities or channels. Temporary runtime URLs are credentials: do not persist, broadcast or log them. Backend private configuration is encrypted at rest and omitted from admin reads; public configuration is user-visible.
|
||||
|
||||
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.
|
||||
Treat applications as trusted code. Node services have the WebSpeak OS account's privileges; process separation and heap limits are not a hostile-code sandbox. Frontends use a separate origin with standard browser capabilities. Browser permission, secure-context, user-gesture, CORS and network requirements apply. The shared application origin does not isolate mutually hostile plugins. Explain these boundaries accurately and review dependencies rather than inventing host feature permissions.
|
||||
|
||||
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.
|
||||
Provide responsive light/dark styles and suitable language handling using context. Keep UI in the application panel without relying on skin DOM. Clean timers, subscriptions, media and sockets on exit/revocation. Persist backend state in `dataDir`, never extracted code directories. Implement concurrency and atomic writes appropriate to the application.
|
||||
|
||||
Verify 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.
|
||||
Verify import, trust, enable, update, failure/restart, custom routes, persistence and revocation. Collaborative apps need two real browser participants and late-join/concurrent-change/channel-boundary/disconnect tests. Distinguish mocked HTTP, actual processes, browser interactions and independent networks. Claim only demonstrated capabilities. Keep credentials and diagnostics out of artifacts.
|
||||
|
||||
For distribution use schema v2 catalog entries, matching manifest, raw-package SHA-256 and fixed refs. Publishing and deployment follow the user's task authorization; this skill does not itself authorize either.
|
||||
|
||||
## Floating host workspace
|
||||
|
||||
The host owns a skin-independent draggable launcher, application library and non-modal app window. Do not add launch controls to a particular skin or inspect its DOM. Apps render their responsive light/dark UI inside the supplied iframe; the host supplies dragging, minimize/maximize/restore and close controls. The host window uses the standard `color-scheme` for its light/dark fallback without inheriting skin component styles. Do not duplicate host window chrome or block the workspace with a page-wide modal backdrop.
|
||||
|
||||
Minimizing or switching to the library retains the same iframe and app session. Transfers and playback must survive those actions. Closing the window, replacing the active app or host context revocation ends that session; only one frontend app is currently hosted at a time. Do not equate a hidden iframe with app exit. Verify resize, narrow screens, theme changes, minimize/resume without reload and close/revocation cleanup. Keep the user-facing window focused on functionality and actionable status; omit repeated runtime/permission disclaimers. Administrator trust and security review remain part of enablement.
|
||||
|
||||
## Instance authorization
|
||||
|
||||
The public host asks once per browser origin for third-party skins and functional applications together. No decision or refusal allows only Day, Night and ILLUSIA; KAAK also requires consent. The last item in the skin menu reopens this setting. Revocation must close/revoke the active frontend application while preserving independently enabled backend services. Do not add per-app copies of the same host authorization prompt, bypass the host gate or confuse this user decision with administrator package trust or browser-native permission prompts.
|
||||
@@ -29,3 +29,7 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
|
||||
|
||||
- `docs/SKIN_DEVELOPMENT.md` — the single current reference for skin formats, runtime APIs, permissions, data, actions, CSS hooks, security, and QA.
|
||||
- `docs/examples/ILLUSIA-VOICE.md` and `docs/examples/OPEN-VOICE-SURFACE.md` — full skin and surface examples.
|
||||
|
||||
## Instance authorization
|
||||
|
||||
Current development builds replace per-skin consent dialogs with one origin-scoped user decision covering third-party skins and functional apps. Without consent only the fixed official Day, Night and ILLUSIA skins are available; bundled KAAK also requires consent. The host skin switcher owns the final authorization item. Packages must not duplicate or bypass it. Revocation must cancel pending activation, remove third-party CSS/components and stop workers. Continue enforcing manifest permissions, credential redaction, trusted action validation and package digests internally; one-time consent does not extend the public API. See the current guide for release compatibility.
|
||||
+1
-1
@@ -37,7 +37,7 @@ COPY --from=build --chown=node:node /app/scripts/docker-healthcheck.mjs ./script
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 3041/tcp 39087/udp 40000-40099/udp
|
||||
EXPOSE 3040/tcp 3041/tcp 3042/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["node", "scripts/docker-healthcheck.mjs"]
|
||||
|
||||
|
||||
@@ -91,9 +91,9 @@ Data persists in the `webspeak-data` volume. The Compose file uses host networki
|
||||
| 类型 · Type | 入口 · Resources |
|
||||
| --- | --- |
|
||||
| 皮肤包 · Skin packages | [皮肤索引 · Catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) |
|
||||
| 功能插件 · Functional plugins **(dev)** | [分发仓库与一起观看示例 · Catalog & Watch Together](https://github.com/Huddle-Up-Forge/webspeak-plugin) · [开发指南 · Guide](./docs/PLUGIN_DEVELOPMENT.md) · [Agent Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) |
|
||||
| 功能插件 · Functional plugins **(dev)** | [应用目录与开发起点 · Catalog & application starter](https://github.com/Huddle-Up-Forge/webspeak-plugin) · [开发指南 · Guide](./docs/PLUGIN_DEVELOPMENT.md) · [Agent Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) |
|
||||
|
||||
皮肤包负责界面、布局及其附属小组件;功能插件在独立面板中提供协作能力。功能插件需要当前 `dev` 运行时,尚未包含在 v0.2.9 中。
|
||||
皮肤包负责界面、布局及其附属小组件;功能插件使用标准浏览器环境和可选 Node 后端,自行实现业务功能。功能插件需要当前 `dev` 运行时,尚未包含在 v0.2.9 中。
|
||||
|
||||
Skins own appearance, layout and attached widgets. Functional plugins provide collaboration in an independent panel and currently require the `dev` runtime; they are not included in v0.2.9.
|
||||
|
||||
|
||||
+112
-118
@@ -1,158 +1,152 @@
|
||||
# WebSpeak 功能插件开发 / Functional plugin development
|
||||
# WebSpeak 功能应用开发 / Functional application development
|
||||
|
||||
本文描述 dev 分支的功能插件 API v1。实例需要包含插件商店;正式版 v0.2.9 尚无此接口。功能包 `.wplugin` 与外观包 `.wskin`、皮肤内部组件及其 API 独立。
|
||||
当前 `dev` 使用应用运行时 **API v2**。正式版 v0.2.9 不包含该能力。`.wplugin` 与 `.wskin` 完全独立;旧 API v1、共享房间协议及其两个示例已移除,不兼容旧包。
|
||||
|
||||
## 使用与作用域
|
||||
插件是作者自己的应用:标准 HTML/CSS/JavaScript 前端,加上可选的 Node 后端。可以使用框架、浏览器原生 API、自己的 HTTP/WebSocket 协议、网络客户端和数据模型。宿主不提供按音乐、文件、视频等功能划分的业务 API,也不提供 `room.read/write` 或下载权限表。浏览器原有的安全上下文、用户手势、权限许可、跨域及网络可达性要求仍然适用。
|
||||
|
||||
管理员进入 `/admin/plugins`,从 [GitHub 分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 安装或导入本地 `.wplugin`。检查作者、许可证和权限后,选择作用域、保存公开配置并启用。安装、更新后默认禁用,不能静默获取新权限。管理写操作受管理员会话、同源和 CSRF 保护,并记录审计。
|
||||
## 管理与部署
|
||||
|
||||
用户连接语音工作台后,通过独立的“插件功能”入口打开隔离面板,不依赖皮肤的挂载位置。关闭面板或返回列表会退出插件房间、销毁 iframe 并停止媒体;插件不修改原生工作台 DOM。
|
||||
管理员在 `/admin/plugins` 从 GitHub 安装或导入包,审核代码和依赖,配置作用域,勾选信任后启用。每次安装、更新均撤销信任并禁用,需要重新审核。审核是人工准入流程,校验包哈希不等于审核代码。写操作继续使用管理员认证、同源检查、CSRF 和审计。
|
||||
|
||||
| 类型 | 配置和房间边界 |
|
||||
**信任边界:** 前端运行在独立源,和工作台 DOM 分离,使用真实浏览器环境。Node 后端运行于独立子进程,拥有 WebSpeak 服务账户的操作系统权限,能够访问该账户可访问的网络和文件。独立进程、目录和 JS 堆上限用于生命周期与故障控制,不是恶意代码安全沙箱。仅安装审核且信任的应用。
|
||||
|
||||
运行时默认监听 `0.0.0.0:3042`:
|
||||
|
||||
| 环境变量 | 用途 |
|
||||
| --- | --- |
|
||||
| `server` 服务器插件 | 配置允许的 TS `host:port`,用户按实际 TS 目标及频道进入各自房间 |
|
||||
| `instance` WebSpeak 实例插件 | 同一网关的已连接用户共享一个插件房间,跨 TS 服务器和频道 |
|
||||
| `WEBSPEAK_PLUGIN_PORT` | 应用端口,默认 3042 |
|
||||
| `WEBSPEAK_PLUGIN_HOST` | 监听地址,默认 0.0.0.0 |
|
||||
| `WEBSPEAK_PLUGIN_PUBLIC_ORIGIN` | 初始公开源,例如 `https://apps.example.com` |
|
||||
|
||||
服务器绑定使用网关解析后的实际连接地址,不接受插件或浏览器自报的目标。使用 SRV、Nickname 或别名时,在实例连接列表核对实际目标。配置支持 `host:port`、`host#port`、`[IPv6]:port`,保存时规范化。服务器插件未配置目标时不能启用。切频道会退出旧服务器插件房间,实例插件保留房间。断线、重连、卸载、更新或管理员修改配置会关闭旧上下文,需重新打开。
|
||||
本地工作台为 `127.0.0.1` 时自动使用 `localhost:3042`,反向亦然,以保持源分离。公网部署必须给应用配置独立 HTTPS 源,在管理页“应用运行时”保存;该设置优先于环境变量。代理应将该源的全部路径转发至应用端口,支持 WebSocket 升级和 SSE 长连接,关闭 SSE 缓冲。不要让代理记录 `/apps/…` 中的访问凭证,也不要与主站共用域 Cookie。
|
||||
|
||||
“所有人”指打开插件的 WebSpeak 浏览器参与者,TS 原生客户端不会运行网页插件。不同 WebSpeak 网关目前不共享插件房间。使用浏览器直连中继网关时,插件目录和房间属于实际连接的语音网关,需要在那里安装配置;只使用 UDP 加速不会改变房间归属。
|
||||
```caddyfile
|
||||
apps.example.com {
|
||||
reverse_proxy 127.0.0.1:3042
|
||||
}
|
||||
```
|
||||
|
||||
## 包格式
|
||||
容器需映射应用端口,或让代理接入相同容器网络。端口/监听地址改变需重启;公开源可在后台更新,会撤销已有应用会话。主站直接使用 TLS 时,运行端口使用相同证书;TLS 在代理终止时,上游使用 HTTP。监听失败会保留主站和语音服务,后台显示不可用,修复后需重启。配置为主站自身源时拒绝打开应用。
|
||||
|
||||
`.wplugin` 是 UTF-8 JSON,最多 512 KiB,不是 ZIP;不包含服务端可执行文件、原生模块或任意路径。
|
||||
## 作用域与身份
|
||||
|
||||
`server`:管理员配置允许的实际 TS `host:port`,用户按真实 TS 目标和频道获得作用域标识。`instance`:当前语音网关的已连接用户获得同一实例标识。作用域负责宿主准入和提供上下文,**不会替作者创建共享房间或自动同步数据**。应用后端应按 `request.webspeak.scope.key` 分组,并自行实现业务授权和同步。
|
||||
|
||||
TS 目标由实际语音连接解析,插件不能自报身份或频道。目标支持 `host:port`、`host#port`、`[IPv6]:port`,保存时规范化;SRV/Nickname 场景应核对实际目标。服务器范围切换频道后需重开;实例范围的频道变更通过上下文更新。断开、重连、更新、禁用、重启、配置修改或卸载会撤销旧凭证并关闭连接。服务端可以在没有打开面板时执行后台任务,直到禁用或停止。
|
||||
|
||||
入口属于实际语音网关;浏览器直连另一中继网关时,在那个网关安装配置。原生 TS 客户端不会执行网页应用,不同网关不会自动共享状态。作者可自行实现跨实例服务。
|
||||
|
||||
## 包格式与构建
|
||||
|
||||
复制 [通用起点](templates/plugin-app/manifest.json),修改 ID、元数据和业务代码。它只展示上下文及自定义计数路由,不是商店预装插件。
|
||||
|
||||
```text
|
||||
my-app/
|
||||
manifest.json
|
||||
client/index.html
|
||||
client/main.js
|
||||
client/style.css
|
||||
server/main.mjs # 可选
|
||||
server/node_modules/ # 可选,已审核的运行依赖
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"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": "<main id='app'></main>",
|
||||
"script": "(async () => { const context = await webspeak.ready; })();",
|
||||
"styles": {
|
||||
"light": "body { background: #fff; color: #16332e; }",
|
||||
"dark": "body { background: #20242b; color: #edf5f2; }"
|
||||
}
|
||||
"apiVersion": 2,
|
||||
"id": "community.my-app",
|
||||
"name": "My application",
|
||||
"version": "1.0.0",
|
||||
"author": "Author",
|
||||
"license": "MIT",
|
||||
"description": "An independently implemented application",
|
||||
"scopes": ["server", "instance"],
|
||||
"client": { "entry": "client/index.html" },
|
||||
"server": { "entry": "server/main.mjs" }
|
||||
}
|
||||
```
|
||||
|
||||
两个基础样式都必须提供。宿主根据当前皮肤文字明暗推断基础配色,发送 `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`。
|
||||
纯前端应用删除 `server` 声明。前端框架产物放入 `client/`,静态引用使用相对路径,不能假设根路径为 `/`。后端入口支持 `.mjs/.cjs`,依赖放在 `server/` 内或打包为自包含文件。宿主不会执行 `npm install`、安装脚本或原生编译;原生依赖需匹配目标 Node ABI/操作系统,不一定跨平台。运行环境为宿主 Node,当前项目要求 Node 22 或更高。
|
||||
|
||||
```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
|
||||
node scripts/build-plugin.mjs docs/templates/plugin-app /tmp/application.wplugin
|
||||
```
|
||||
|
||||
构建器读取上述五个文件。其他工具链只需生成同格式 JSON。独立插件仓库不需要 WebSpeak 源码即可生成包;宿主导入时也会校验。
|
||||
构建器是独立 Node 脚本,可复制到插件仓库,无需导入 WebSpeak 源码。`.wplugin` 是 UTF-8 JSON:`{manifest,files}`;`files` 是路径到 `{encoding:"utf8"|"base64",data:string}` 的映射。支持普通 `client/`、`server/` 文件;禁止越界路径、符号链接、Windows 设备名、大小写冲突及文件/目录别名。入口必须是 UTF-8。封装上限 48 MiB、解码内容 32 MiB、单文件 16 MiB、4096 个文件,安装上限 50 个。宿主导入时完整校验。
|
||||
|
||||
## 公共浏览器 API
|
||||
## 浏览器上下文
|
||||
|
||||
脚本开始前,宿主提供只读 `window.webspeak`,不需要导入内部 Vue 组件。
|
||||
宿主在入口 HTML 注入外部脚本,在应用模块运行前提供:
|
||||
|
||||
```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<Context>;
|
||||
room: {
|
||||
snapshot(): Promise<Snapshot>;
|
||||
update(expectedRevision: number, state: JsonValue): Promise<Snapshot>;
|
||||
subscribe(listener: (snapshot: Snapshot) => void): () => void;
|
||||
```js
|
||||
const context = await window.webspeak.ready;
|
||||
const unsubscribe = webspeak.onContextChange(next => render(next));
|
||||
const latest = webspeak.getContext();
|
||||
const response = await fetch(context.serverUrl + '/my-route', {
|
||||
method: 'POST', body: JSON.stringify({anything: 'defined by the application'}),
|
||||
signal: webspeak.signal
|
||||
});
|
||||
const socket = new WebSocket(context.socketUrl + '/my-socket');
|
||||
```
|
||||
|
||||
| 上下文字段 | 内容 |
|
||||
| --- | --- |
|
||||
| `apiVersion` | 2 |
|
||||
| `plugin` | manifest |
|
||||
| `self` | 当前公开 `id/nickname/uid?` |
|
||||
| `connection` | 真实 `target/channelId` 和当前频道公开 `members`(`id/nickname/uid?`) |
|
||||
| `scope` | `{type:"server"|"instance",key:string}`;分组标识不能直接当文件路径 |
|
||||
| `config` | 管理员公开 JSON,所有参与者可读 |
|
||||
| `theme/language` | `light/dark` 和 `zh/en/de/ru/ja`,同步到 `<html data-theme>` 与 `lang` |
|
||||
| `appId` | 本次打开的公开标识,不是长期身份或认证凭据 |
|
||||
| `serverUrl/socketUrl` | 此会话的后端 HTTP/WS 根;纯前端为 `null` |
|
||||
| `contextUrl` | 此会话最新上下文地址 |
|
||||
|
||||
运行时 URL 含临时凭证,不应持久化、广播或记录。`webspeak.signal` 在撤销或退出时中止,仍需清理自己的定时器、网络、媒体和订阅。应用应提供两种基础配色及适合的语言回退。
|
||||
|
||||
用原生 `fetch`、`WebSocket`、`RTCPeerConnection`、文件选择/下载、IndexedDB、Canvas 等编写功能。独立源存储遵循原生规则;同一运行源的应用共享该源存储,请按插件 ID 命名,不能把此设计当作互不信任插件间的隔离。服务端持久化使用 `dataDir`。
|
||||
|
||||
关闭面板会销毁 iframe 并取消未完成的打开操作。宿主每秒检查会话有效性,撤销后终止 HTTP、SSE、WS 和旧页面。控制平面只传上下文与生命周期;业务数据使用独立应用服务,不经过语音 WebSocket。
|
||||
|
||||
## 可选 Node 后端
|
||||
|
||||
```js
|
||||
export default async function activate({ dataDir, config, publicConfig, events, signal, log }) {
|
||||
return {
|
||||
handle(req, res) {
|
||||
// req.webspeak is verified by the host; req.url is your own route.
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({participant: req.webspeak.self.id}));
|
||||
},
|
||||
upgrade(req, socket, head) { /* your WebSocket protocol */ },
|
||||
async stop() { /* flush data and release resources */ }
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
`room.read` 允许读房间和订阅状态;`room.write` 允许替换共享状态,必须同时声明读权限。不需要共享数据的独立功能面板可声明空权限数组:仍可打开并获得公开配置,但上下文仅含空快照,不能读写或订阅其他参与者。当前所有已加入且拥有写权限的参与者都能操作,没有隐含主持人角色或 TS 管理权限。API 不提供 TS Query、宿主 DOM、系统文件、管理员凭据或任意宿主方法。需要新能力时另行提议接口,不能访问内部实现绕过。
|
||||
也可直接返回 `(req,res)=>…`。这是 Node 原生请求/响应,可适配 Express、WS 等库。`req.webspeak` 含 `apiVersion/appId/self/connection/scope`,不含临时 URL 或管理凭据;服务端 `connection` 只有目标和频道。代理剥离主站 Cookie、Authorization 和伪造的 `x-webspeak-*` 头;应用自行认证可使用自定义头或自己的外部服务。后端不会收到主站管理员/Query 密钥,除非管理员主动在插件配置中提供。
|
||||
|
||||
更新使用比较并交换:读取 N 后提交 N,成功返回 N+1;冲突返回 `PLUGIN_REVISION_CONFLICT`。重新读取,让用户重试或基于新状态重算,不能盲目覆盖。
|
||||
`dataDir` 为本插件持久目录,更新/重启/卸载保留。代码提取目录会清理,不可持久化。包文件没有可执行位;额外子程序需作者自行处理权限和平台。Node 网络、文件、子程序和第三方服务同样属于审核范围。
|
||||
|
||||
```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 });
|
||||
```
|
||||
`config` 是后端私密 JSON,`publicConfig` 是公开 JSON。私密配置在管理页仅显示是否已保存,支持保留/替换/删除,用实例主密钥加密存储;启用的 Node 代码获得明文。它不是针对恶意插件的秘密保险箱。不要把私密配置写入响应或日志。
|
||||
|
||||
共享状态上限 16 KiB、16 层嵌套、4096 个节点,只接受 JSON,不接受非有限数、原型键或二进制媒体。公开配置上限 8 KiB。每会话每秒最多 20 个插件请求,每个房间每秒最多 10 次共享写入,关闭操作不受频率限制。最多 8 个已打开插件(当前面板一次打开一个);每网关最多 800 个非空房间、50 个已安装插件。读取快照不触发广播。不要通过高频写状态传视频帧。服务端只保存通用状态与成员,不执行插件代码。
|
||||
`events` 为 Node `EventEmitter`:`participantJoined/contextChanged` 提供服务端公开上下文,`participantLeft` 为 `{appId,selfId,scopeKey}`。加入指打开应用面板,不是全体 TS 成员。`signal` 在停止时中止;`log(level,message)` 提供限流日志,宿主当前以 debug 级别记录。
|
||||
|
||||
最后一位参与者离开立即销毁房间,重启也会丢失临时房间。安装和配置持久化于数据目录 `plugins/*.json`,原子替换;实例备份应包含此目录。需要持久业务数据或外部适配器时,应定义额外能力协议。
|
||||
每个后端一个进程,默认最多 8 个;启动超时 10 秒、停止宽限 2 秒、JS 堆上限 256 MiB(不是总 RSS 限额)。失败显示错误、撤销会话,可手动重启,无无限重试。每个语音连接最多 8 个打开会话,全局 800 个,每会话最多 32 条代理连接及 4 条上下文 SSE。普通 HTTP 空闲超时 120 秒,无上下文 SSE 且 90 秒无活动的会话回收。作者负责消息大小、业务授权、并发、存储一致性和依赖资源用量。
|
||||
|
||||
主要错误:`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 时跳过插件消息。恢复连接质量后可请求快照或重新打开插件;请求无响应会超时,不代表共享写入一定没有执行。
|
||||
[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含同一 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。宿主限制 GitHub 内容来源、核验哈希与 manifest;目录或安装修订改变会拒绝覆盖,需重新加载。空目录不默认安装插件。
|
||||
|
||||
## 同步观影示例
|
||||
验证实际构建包的导入、审核、启用、自定义 HTTP/WS、依赖加载、持久化和关闭/断线/禁用/更新撤销;检查明暗、语言、窄屏。协作另测两位真实参与者及并发/离开/重连。区分模拟身份、真实 TS、浏览器交互与跨网络证据。宿主回归:`npm run verify`。
|
||||
|
||||
状态为 `{ url, position, playing, updatedAt }`。加载、播放、暂停、跳转共享;音量、全屏与播放许可仅影响自己。使用快照 `serverTime` 估算网关时钟,推算播放 elapsed time,定时校正漂移,大偏移跳转、小偏移暂调速。后来加入读取同一快照追上进度,不依赖过去的操作事件。
|
||||
## 悬浮应用窗口 / Floating application workspace
|
||||
|
||||
视频由每个浏览器直接从 URL 加载,不经过 WebSpeak 中转。支持浏览器可解码的 MP4/WebM 等直链,不支持播放网页、DRM、登录后 URL 或嵌入式平台播放器。HTTPS 实例一般需要 HTTPS 视频。自动播放受浏览器策略限制,可能需要点击“允许播放”。源端带宽、网络和缓冲会影响误差,不承诺逐帧同步。
|
||||
功能插件入口由宿主的独立悬浮层提供,不属于默认主题或任何皮肤插槽。入口可拖动,避免遮挡工作台控件。应用库和应用内容使用非模态窗口:打开后仍可操作工作台;标题栏可拖动,支持最小化、最大化、还原和关闭,小屏幕自动限制在可视区域内。宿主窗口优先读取标准 `color-scheme` 来选择日间/夜间配色,不继承皮肤组件样式。
|
||||
|
||||
## 隔离与清理
|
||||
最小化、切换到应用库、再返回当前应用均保留同一个 iframe 与会话,传输、播放等任务不会因收起窗口而重置。关闭窗口、切换至另一个应用或语音会话撤销时,宿主结束当前应用会话。当前同时承载一个前端应用;不要把窗口最小化当成退出事件。
|
||||
|
||||
使用 opaque-origin `sandbox="allow-scripts"` iframe,不授予 `allow-same-origin`、顶部导航、弹窗、表单、麦克风或摄像头。宿主 RPC 校验 `event.source`、随机通道和面板生命周期;插件不能选择另一个 ID 或房间。CSP 禁止 fetch/WebSocket、外部脚本、嵌套 iframe,仅允许直接媒体及 HTTPS 图片。媒体源仍会收到浏览器请求,配置、共享状态和视频 URL 都不能包含管理员密钥。
|
||||
应用只负责 iframe 内部内容,使用自身响应式日间/夜间样式和上下文中的主题、语言。不读取或改写皮肤 DOM,不绘制覆盖宿主的全屏遮罩,不自行重复宿主的标题栏、最小化和关闭按钮。需要自有导航时可在内容区实现。应用界面优先显示功能与实际状态,不重复运行环境、权限或免责说明;管理员启用时的信任与权限信息保留在管理流程中。
|
||||
|
||||
隔离不是恶意代码审核、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.
|
||||
首次访问时,宿主统一征求第三方皮肤与功能应用的使用授权;决定按浏览器源保存,不迁移旧的逐皮肤授权。拒绝或未选择时,只显示日间、夜间、ILLUSIA 三款官方皮肤,KAAK 和功能应用入口均隐藏。皮肤菜单最后的“授权”可随时更改。撤回会关闭 iframe 并撤销当前打开操作/应用会话,不停止管理员启用的全实例后台服务。应用不得以入口以外的方式绕过宿主授权,也无需重复询问同一份宿主上下文授权;相机、麦克风等浏览器原生许可仍由浏览器处理。
|
||||
+1
-1
@@ -304,7 +304,7 @@ Skins gestalten Aussehen, Layout und zugehörige Widgets. Administratoren instal
|
||||
|
||||
### Funktionale Plugins `.wplugin` (dev)
|
||||
|
||||
Funktionale Plugins laufen getrennt von Skins in einem eigenen Panel. Administratoren wählen Server-Geltungsbereich (gleiches TS-Ziel und gleicher Kanal) oder Instanz-Geltungsbereich (ein Sprach-Gateway). Watch Together zeigt synchrones Abspielen, Pausieren, Springen und spätes Beitreten. Erforderlich ist die aktuelle dev-Laufzeit; v0.2.9 enthält diese Funktion nicht.
|
||||
Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und optionalen Node-Backends, eigenen Routen, Daten und Zusammenarbeit. Administratoren prüfen Code und Abhängigkeiten vor der Aktivierung; Updates erfordern erneutes Vertrauen. Anwendungen unterstützen TS-Server- oder Instanz-Bereiche und eine separate Origin. API v2 benötigt die aktuelle dev-Version und ist nicht in v0.2.9 enthalten.
|
||||
|
||||
[Entwicklungsleitfaden](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Verteilungskatalog & Beispiel](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
|
||||
+1
-1
@@ -304,7 +304,7 @@ Skins own appearance, layout and their attached widgets. Administrators install,
|
||||
|
||||
### Functional plugins `.wplugin` (dev)
|
||||
|
||||
Functional plugins run in an independent panel, separately from skins. Administrators choose server scope (the same TS target and channel) or instance scope (one voice gateway). The Watch Together example demonstrates synchronized play, pause, seek and late joining. This requires the current dev runtime and is not included in v0.2.9.
|
||||
Functional plugins are independent applications using standard browser capabilities and optional Node backends with their own routes, state and collaboration. Administrators review code and dependencies before enabling; updates require renewed trust. Applications support TS server or instance scope and run on a separate origin. API v2 requires current dev and is not included in v0.2.9.
|
||||
|
||||
[Development guide](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Distribution catalog & example](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
|
||||
+1
-1
@@ -240,7 +240,7 @@ relay.example.com {
|
||||
|
||||
### 機能プラグイン `.wplugin`(dev)
|
||||
|
||||
機能プラグインはスキンと分離した専用パネルで動作します。管理者はサーバー単位(同じ TS 接続先とチャンネル)かインスタンス単位(1 つの音声ゲートウェイ)を選択できます。Watch Together は再生、一時停止、シーク、途中参加の同期例です。現在の dev ランタイムが必要で、v0.2.9 には含まれません。
|
||||
機能プラグインは標準ブラウザー機能と任意の Node バックエンドを使う独立アプリです。ルート、状態、共同作業は作者が実装します。管理者はコードと依存関係を審査して有効化し、更新後は再び信頼を確認します。TS サーバーまたはインスタンス範囲に対応し、別オリジンで動作します。API v2 は現在の dev が必要で、v0.2.9 には含まれません。
|
||||
|
||||
[開発ガイド](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [配布一覧とサンプル](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
|
||||
+1
-1
@@ -240,7 +240,7 @@ relay.example.com {
|
||||
|
||||
### Функциональные плагины `.wplugin` (dev)
|
||||
|
||||
Функциональные плагины работают в отдельной панели независимо от скинов. Администратор выбирает область сервера (одна цель TS и канал) или экземпляра (один голосовой шлюз). Watch Together демонстрирует синхронные воспроизведение, паузу, перемотку и позднее подключение. Нужна текущая среда dev; в v0.2.9 функции нет.
|
||||
Функциональные плагины — самостоятельные приложения с API браузера, необязательными сервисами Node, своими маршрутами, данными и совместной работой. Администратор проверяет код и зависимости перед включением; обновления требуют повторного доверия. Приложения работают на отдельном источнике в области TS-сервера или экземпляра. API v2 требует текущую dev-версию и не входит в v0.2.9.
|
||||
|
||||
[Руководство](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Каталог распространения и пример](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
|
||||
@@ -308,7 +308,7 @@ relay.example.com {
|
||||
|
||||
### 功能插件 `.wplugin`(dev)
|
||||
|
||||
功能插件在独立面板中运行,与皮肤包分开。管理员可配置服务器作用域(同一 TS 目标与频道)或实例作用域(同一语音网关);“一起观看”示例验证播放、暂停、跳转和中途加入的同步。需要当前 dev 运行时,不属于 v0.2.9。
|
||||
功能插件是独立应用,使用标准浏览器能力和可选 Node 后端,自行实现路由、状态与协作。管理员审核代码和依赖后启用;更新须重新信任。支持 TS 服务器或实例范围,运行于独立源。当前 dev 使用 API v2,不属于 v0.2.9。
|
||||
|
||||
[开发指南](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [分发索引与示例](https://github.com/Huddle-Up-Forge/webspeak-plugin)
|
||||
|
||||
|
||||
@@ -522,3 +522,11 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删
|
||||
自绘成员列表时,`session.members` 可读取 `screenSharing` 与 `screenShareStreamId`;这两个成员字段和 `screenShare.streams` 一样要求 `voice.screenShare.read`。用 `member.screenSharing` 显示共享标记,再将 `member.screenShareStreamId` 绑定到 `voice.joinScreenShare`(还需 `voice.screenShare.control`)即可让用户观看。未声明/未获共享读取权限的皮肤不会收到这两个字段;整页替换皮肤仍须在自己的成员列表中绘制标记或观看入口。
|
||||
|
||||
\n
|
||||
|
||||
## 实例级用户授权(当前开发版)
|
||||
|
||||
用户首次访问公开页面时,由宿主统一询问是否允许当前实例的第三方皮肤和功能插件使用已公开的频道/成员/聊天等上下文;不包含连接凭据。不再逐个皮肤弹窗确认。选择按浏览器源(协议、域名、端口)保存,旧版本的逐包授权记录不会自动替代这次选择。管理员对应用的审核与信任仍单独保留。
|
||||
|
||||
未作选择或拒绝时,仅可使用固定三款官方皮肤:`builtin.light`、`builtin.dark`、`community.illusia-voice`;KAAK 即使随包分发也不在免授权名单中,其他第三方皮肤及功能插件入口隐藏。缓存、直接激活、进行中的加载也必须经过同一授权检查,不能仅过滤菜单。皮肤菜单末尾的“授权”可以随时修改选择。撤回时立即退回内置皮肤、停止第三方皮肤组件/worker,并关闭与撤销当前功能应用会话;服务端由管理员启用的后台应用不因此停机。
|
||||
|
||||
清单权限、数据投影、宿主动作校验和 Wasm 文件摘要校验继续保留,统一授权不是扩大皮肤 API 的理由。作者不应再自行增加重复授权弹窗。原文中的逐包授权记录与 SHA-256 绑定描述指内部校验记录,其创建必须在实例授权允许之后(或固定官方皮肤之内)。
|
||||
@@ -1 +0,0 @@
|
||||
{"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":"<main>\n <header><h1 id=\"title\">Watch Together</h1><span id=\"members\"></span></header>\n <p id=\"lead\"></p>\n <form id=\"source\"><label><span id=\"url-label\">Video URL</span><input id=\"url\" type=\"url\" maxlength=\"2048\" placeholder=\"https://…/video.mp4\" required></label><button id=\"load\" type=\"button\">Load</button></form>\n <video id=\"video\" playsinline preload=\"metadata\"></video>\n <div class=\"controls\"><button id=\"play\" type=\"button\">▶</button><button id=\"pause\" type=\"button\">Ⅱ</button><button id=\"unlock\" type=\"button\">Enable playback</button><button id=\"fullscreen\" type=\"button\">⛶</button><label class=\"volume\">♫ <input id=\"volume\" type=\"range\" min=\"0\" max=\"1\" step=\".05\" value=\".7\" aria-label=\"Volume\"></label></div>\n <label class=\"seek\"><span id=\"time\">0:00 / 0:00</span><input id=\"seek\" type=\"range\" min=\"0\" max=\"1\" step=\".1\" value=\"0\" aria-label=\"Seek\"></label>\n <p id=\"status\" role=\"status\"></p>\n <p id=\"note\" class=\"note\"></p>\n</main>\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 || Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
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}}
|
||||
@@ -1 +0,0 @@
|
||||
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}}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"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"]
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<main>
|
||||
<header><h1 id="title">Watch Together</h1><span id="members"></span></header>
|
||||
<p id="lead"></p>
|
||||
<form id="source"><label><span id="url-label">Video URL</span><input id="url" type="url" maxlength="2048" placeholder="https://…/video.mp4" required></label><button id="load" type="button">Load</button></form>
|
||||
<video id="video" playsinline preload="metadata"></video>
|
||||
<div class="controls"><button id="play" type="button">▶</button><button id="pause" type="button">Ⅱ</button><button id="unlock" type="button">Enable playback</button><button id="fullscreen" type="button">⛶</button><label class="volume">♫ <input id="volume" type="range" min="0" max="1" step=".05" value=".7" aria-label="Volume"></label></div>
|
||||
<label class="seek"><span id="time">0:00 / 0:00</span><input id="seek" type="range" min="0" max="1" step=".1" value="0" aria-label="Seek"></label>
|
||||
<p id="status" role="status"></p>
|
||||
<p id="note" class="note"></p>
|
||||
</main>
|
||||
@@ -1,65 +0,0 @@
|
||||
/* 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<snapshot.revision)return;snapshot=next;offset=next.serverTime-Date.now();$('members').textContent=(zh?'参与者:':'Participants: ')+next.participants.length;void apply();}
|
||||
async function update(patch) {
|
||||
if(busy)return;busy=true;
|
||||
try {
|
||||
const state=validState(snapshot.state), next={url:state?.url||source,position:state?targetPosition(state):0,playing:state?.playing||false,updatedAt:Date.now()+offset,...patch};
|
||||
if(!validState(next))throw new Error(t[7]);
|
||||
receive(await api.room.update(snapshot.revision,next)); status();
|
||||
} catch(error){if(error.message==='PLUGIN_REVISION_CONFLICT'){receive(await api.room.snapshot());status(t[8]);}else status(error.message);}
|
||||
finally{busy=false;}
|
||||
}
|
||||
const load=()=>{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});
|
||||
})();
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Application starter</title><link rel="stylesheet" href="./style.css"><script type="module" src="./main.js"></script></head>
|
||||
<body><main><span class="eyebrow">WEBSPEAK · APPLICATION RUNTIME 2</span><h1 id="title"></h1><p id="intro"></p><section><div class="status"><i></i><span id="status"></span></div><dl><div><dt id="user-label"></dt><dd id="user"></dd></div><div><dt id="scope-label"></dt><dd id="scope"></dd></div></dl><button id="request" type="button"></button><output id="result" aria-live="polite"></output></section></main></body></html>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
const host=window.webspeak;
|
||||
let context=await host.ready;
|
||||
const copy={
|
||||
en:['Your application starts here','Standard browser APIs, your own routes and an optional Node backend.','Connected application context','Participant','Scope','Call my backend','Persisted requests','Frontend only'],
|
||||
zh:['从这里构建你的应用','使用标准浏览器 API、自定义路由和可选的 Node 后端。','应用上下文已连接','参与者','作用域','调用自己的后端','已保存的请求次数','仅前端模式'],
|
||||
de:['Hier beginnt deine Anwendung','Browser-APIs, eigene Routen und ein optionales Node-Backend.','Anwendungskontext verbunden','Teilnehmer','Bereich','Backend aufrufen','Gespeicherte Anfragen','Nur Frontend'],
|
||||
ru:['Начните своё приложение здесь','API браузера, собственные маршруты и необязательный сервис Node.','Контекст приложения подключён','Участник','Область','Вызвать свой сервис','Сохранённые запросы','Только браузер'],
|
||||
ja:['ここからアプリを作成','標準ブラウザー API、独自ルート、任意の Node バックエンド。','アプリの接続情報を取得済み','参加者','範囲','バックエンドを呼び出す','保存したリクエスト数','フロントエンドのみ']};
|
||||
const element=id=>document.getElementById(id);
|
||||
function render(){const t=copy[context.language]??copy.en;for(const [id,index]of [['title',0],['intro',1],['status',2],['user-label',3],['scope-label',4],['request',5]])element(id).textContent=t[index];element('user').textContent=context.self.nickname;element('scope').textContent=context.scope.type;element('request').disabled=!context.serverUrl;if(!context.serverUrl)element('result').textContent=t[7];}
|
||||
host.onContextChange(next=>{context=next;render();});render();
|
||||
element('request').addEventListener('click',async()=>{element('request').disabled=true;try{const response=await fetch(context.serverUrl+'/my-counter',{method:'POST',signal:host.signal});if(!response.ok)throw new Error(String(response.status));const result=await response.json();element('result').textContent=(copy[context.language]??copy.en)[6]+': '+result.count;}catch(error){element('result').textContent=error.message;}finally{element('request').disabled=!context.serverUrl;}});
|
||||
+1
@@ -0,0 +1 @@
|
||||
:root{color-scheme:light;--bg:#f1f5f4;--surface:#fff;--text:#183d39;--muted:#5b7671;--border:#d4e3df;--accent:#126b60;--soft:#e8f4ef}html[data-theme=dark]{color-scheme:dark;--bg:#161c21;--surface:#202a30;--text:#e4efec;--muted:#9eb6b0;--border:#37474c;--accent:#8ee2be;--soft:#293e37}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.6 system-ui,sans-serif}main{max-width:800px;margin:0 auto;padding:clamp(24px,6vw,64px)}.eyebrow{color:var(--accent);font-size:11px;font-weight:750;letter-spacing:.14em}h1{font-size:clamp(25px,4vw,38px);letter-spacing:-.04em;line-height:1.2;margin:20px 0 14px}p{color:var(--muted);max-width:550px}section{margin-top:30px;padding:26px;border:1px solid var(--border);border-radius:18px;background:var(--surface)}.status{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--accent)}.status i{width:8px;height:8px;border-radius:50%;background:var(--accent)}dl{display:flex;gap:32px;flex-wrap:wrap;margin:22px 0 30px}dt{font-size:12px;color:var(--muted)}dd{margin:4px 0 0;font-weight:650;overflow-wrap:anywhere}button{font:600 14px system-ui;padding:12px 18px;border-radius:10px;border:1px solid var(--border);color:var(--accent);background:var(--soft);cursor:pointer}button:disabled{opacity:.5;cursor:default}output{display:block;margin-top:16px;color:var(--muted);font-size:13px}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"apiVersion": 2,
|
||||
"id": "community.application-starter",
|
||||
"name": "Application starter",
|
||||
"version": "1.0.0",
|
||||
"author": "Your community",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A starting point for an independent browser application and optional Node service.",
|
||||
"scopes": [
|
||||
"server",
|
||||
"instance"
|
||||
],
|
||||
"client": {
|
||||
"entry": "client/index.html"
|
||||
},
|
||||
"server": {
|
||||
"entry": "server/main.mjs"
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { readFile, writeFile, rename } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
// Ordinary trusted Node code: use your own modules, network clients and routes.
|
||||
export default async function activate({ dataDir, signal }) {
|
||||
const filename=path.join(dataDir,'counter.json');
|
||||
let count=JSON.parse(await readFile(filename,'utf8').catch(()=> '0'));
|
||||
let writes=Promise.resolve();
|
||||
return {
|
||||
async handle(request,response) {
|
||||
if(request.method!=='POST'||new URL(request.url,'http://app.local').pathname!=='/my-counter'){response.writeHead(404);response.end();return;}
|
||||
// req.webspeak is host-authenticated context; it is not supplied by the browser.
|
||||
writes=writes.then(async()=>{count++;await writeFile(filename+'.tmp',JSON.stringify(count));await rename(filename+'.tmp',filename);});
|
||||
try{await writes;response.setHeader('content-type','application/json');response.end(JSON.stringify({count,participant:request.webspeak.self.id}));}
|
||||
catch{response.writeHead(500);response.end();}
|
||||
},
|
||||
async stop(){await writes.catch(()=>undefined);}
|
||||
};
|
||||
}
|
||||
Generated
+4
-4
@@ -10,7 +10,7 @@
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
@@ -530,9 +530,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.19",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.19.tgz",
|
||||
"integrity": "sha512-5srWgwbcMx1j4JpwYonxKkOYla8hx7ojX+dYOC0hiv5NCjozMRsy8aIYzwSpzHr2y3q/aKljnPyM426DTRekrA==",
|
||||
"version": "1.0.0-beta.23",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.23.tgz",
|
||||
"integrity": "sha512-Y0fV4NOdvaU3Df4231XZkFOfSgm7G4xN50x5hglxVV+HtYlxx5sS+G3vAF0rvOcW80qUy20nfnD/Sxx+JgQ1TA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
+3
-3
@@ -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 src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-transport.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-app-client.test.ts web/src/services/instance-authorization.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
@@ -27,11 +27,11 @@
|
||||
"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",
|
||||
"plugin:example:build": "node --import tsx scripts/build-plugin.mjs docs/examples/watch-together docs/examples/watch-together.wplugin"
|
||||
"plugin:build": "node scripts/build-plugin.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { readFile, readdir, 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}`);
|
||||
if (!input || !output) throw new Error('Usage: node scripts/build-plugin.mjs APPLICATION_DIR OUTPUT.wplugin');
|
||||
const root=path.resolve(input),manifest=JSON.parse(await readFile(path.join(root,'manifest.json'),'utf8'));
|
||||
if(manifest.apiVersion!==2||manifest.permissions!==undefined)throw new Error('Application runtime v2 manifest required');
|
||||
const validPath=value=>typeof value==='string'&&value.length<=500&&value.split('/').every(s=>/^[A-Za-z0-9._@+~-]+$/.test(s)&&!['.','..'].includes(s)&&!s.endsWith('.')&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(s));
|
||||
const files=Object.create(null);let total=0;
|
||||
async function collect(directory){
|
||||
for(const entry of(await readdir(path.join(root,directory),{withFileTypes:true})).sort((a,b)=>a.name<b.name?-1:1)){
|
||||
const name=directory+'/'+entry.name;if(!validPath(name)||entry.isSymbolicLink())throw new Error('Invalid package path: '+name);
|
||||
if(entry.isDirectory())await collect(name);
|
||||
else if(entry.isFile()){
|
||||
const bytes=await readFile(path.join(root,name));total+=bytes.length;
|
||||
if(bytes.length>16*1024*1024||total>32*1024*1024||Object.keys(files).length>=4096)throw new Error('Package size limit');
|
||||
try{files[name]={encoding:'utf8',data:new TextDecoder('utf-8',{fatal:true}).decode(bytes)};}
|
||||
catch{files[name]={encoding:'base64',data:bytes.toString('base64')};}
|
||||
}else throw new Error('Only ordinary files are supported: '+name);
|
||||
}
|
||||
}
|
||||
await collect('client');if(manifest.server)await collect('server');
|
||||
if(!validPath(manifest.client?.entry)||!manifest.client.entry.startsWith('client/')||files[manifest.client.entry]?.encoding!=='utf8')throw new Error('Missing HTML client entry');
|
||||
if(manifest.server&&(!validPath(manifest.server.entry)||!manifest.server.entry.startsWith('server/')||files[manifest.server.entry]?.encoding!=='utf8'))throw new Error('Missing bundled server entry');
|
||||
const bytes=JSON.stringify({manifest,files});if(Buffer.byteLength(bytes)>48*1024*1024)throw new Error('Package size limit');
|
||||
await writeFile(output,bytes);console.log(`${manifest.id} v${manifest.version} -> ${output}`);
|
||||
@@ -11,6 +11,7 @@ import { SkinStore } from "./skin-store.js";
|
||||
import { createPluginAdminRouter } from "../plugins/admin-router.js";
|
||||
import type { PluginRegistry } from "../plugins/registry.js";
|
||||
import type { PluginStore } from "../plugins/store.js";
|
||||
import type { PluginRuntime } from "../plugins/runtime.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
@@ -43,6 +44,7 @@ export interface AdminRouterOptions {
|
||||
skinStore?: SkinStore;
|
||||
pluginRegistry?: PluginRegistry;
|
||||
pluginStore?: PluginStore;
|
||||
pluginRuntime?: PluginRuntime;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
@@ -131,7 +133,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
});
|
||||
|
||||
router.use(requireAdmin(options.sessions, options.service));
|
||||
router.use("/plugins", createPluginAdminRouter({ registry: options.pluginRegistry, store: options.pluginStore,
|
||||
router.use("/plugins", createPluginAdminRouter({ registry: options.pluginRegistry, store: options.pluginStore, runtime: options.pluginRuntime,
|
||||
protect: [requireSameOrigin, requireCsrf(options.sessions)],
|
||||
audit: (event, data) => options.service.database.addAudit(event, data),
|
||||
}));
|
||||
|
||||
@@ -94,9 +94,9 @@ export class TsAdminService {
|
||||
welcomeMessage: server.virtualserver_welcomemessage ?? "", maxClients: numeric(server.virtualserver_maxclients),
|
||||
uptimeSeconds: numeric(server.virtualserver_uptime), channelCount: channels.length, clientCount: voiceClients.length,
|
||||
channels: channels.map(channel => ({ id: String(channel.id), parentID: String(channel.parentID), name: channel.name,
|
||||
description: channel.description, totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid, nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
serverGroups: entry.serverGroups.map(String), away: entry.isAway, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
|
||||
description: channel.description ?? "", totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid ?? "", nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
serverGroups: (entry.serverGroups ?? []).map(String), away: entry.isAway ?? false, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
|
||||
groups: groups.status === "fulfilled" ? groups.value.filter(group => group.type === 1).map(group => ({ id: String(group.id), name: group.name })) : [],
|
||||
bans: bans.status === "fulfilled" ? bans.value.map(ban => ({ id: String(ban.id), name: ban.name || ban.lastNickname,
|
||||
uid: ban.uid, reason: ban.reason, durationSeconds: ban.durationMs / 1000, createdAt: ban.createdAt?.toISOString() ?? null })) : [],
|
||||
|
||||
+2
-1
@@ -46,7 +46,7 @@ async function main() {
|
||||
await adminService.initialize();
|
||||
removeObsoleteBootstrapFile();
|
||||
const joinTickets = new JoinTicketStore();
|
||||
const pluginRegistry = new PluginRegistry(path.join(DATA_DIR, "plugins"));
|
||||
const pluginRegistry = new PluginRegistry(path.join(DATA_DIR, "plugins"), masterSecret);
|
||||
await pluginRegistry.initialize();
|
||||
|
||||
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
|
||||
@@ -74,6 +74,7 @@ async function main() {
|
||||
adminService,
|
||||
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
|
||||
pluginRegistry,
|
||||
pluginRuntime: { port: parsePort(process.env.WEBSPEAK_PLUGIN_PORT, 3042), host: process.env.WEBSPEAK_PLUGIN_HOST?.trim() || "0.0.0.0", publicOrigin: process.env.WEBSPEAK_PLUGIN_PUBLIC_ORIGIN?.trim() },
|
||||
logger,
|
||||
nextVisitorNumber: () => database.nextVisitorNumber(),
|
||||
visitorCount: () => database.getVisitorCount(),
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Router, type RequestHandler } from "express";
|
||||
import express, { Router, type RequestHandler } from "express";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PluginStore } from "./store.js";
|
||||
import type { PluginRuntime } from "./runtime.js";
|
||||
import { pluginAssert, pluginRecord, PluginError, parsePluginPackage } from "../shared/plugins.js";
|
||||
|
||||
export function createPluginAdminRouter(options: {
|
||||
registry?: PluginRegistry; store?: PluginStore; protect: RequestHandler[];
|
||||
registry?: PluginRegistry; store?: PluginStore; runtime?: PluginRuntime; protect: RequestHandler[];
|
||||
audit(event: string, data: { id: string; version?: string }): void;
|
||||
}) {
|
||||
const router = Router(), store = options.store ?? new PluginStore();
|
||||
@@ -14,13 +15,21 @@ export function createPluginAdminRouter(options: {
|
||||
// Reuse the admin session's same-origin and CSRF rules for every write.
|
||||
writeGuard(request, response, next);
|
||||
});
|
||||
// The parent authenticates before parsing a potentially large application bundle.
|
||||
router.use(express.json({limit:"50mb"}));
|
||||
const registry = () => { pluginAssert(options.registry, "PLUGIN_STORAGE_UNAVAILABLE"); return options.registry; };
|
||||
router.get("/", (_request, response) => response.json({ plugins: registry().list() }));
|
||||
const project=(plugin:ReturnType<PluginRegistry["list"]>[number])=>({...plugin,runtime:options.runtime?.status(plugin.manifest.id)??{state:plugin.settings.enabled?(plugin.manifest.server?"stopped":"client"):"disabled"}});
|
||||
router.get("/", (_request, response) => response.json({ plugins: registry().list().map(project) }));
|
||||
router.get("/runtime",(_request,response)=>{pluginAssert(options.runtime,"PLUGIN_RUNTIME_UNAVAILABLE");response.json({runtime:options.runtime.settings()});});
|
||||
router.put("/runtime",async(request,response)=>{
|
||||
pluginAssert(options.runtime&&pluginRecord(request.body));const runtime=await options.runtime.configureOrigin(request.body.publicOrigin,request.body.revision);
|
||||
options.audit("ADMIN_PLUGIN_RUNTIME_CONFIGURED",{id:"runtime"});response.json({runtime});
|
||||
});
|
||||
router.get("/store", async (_request, response) => { response.json(await store.list()); });
|
||||
router.post("/store/install", async (request, response) => {
|
||||
const plugin = await store.install(registry(), request.body);
|
||||
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
|
||||
response.status(201).json({ plugin });
|
||||
response.status(201).json({ plugin:project(plugin) });
|
||||
});
|
||||
router.post("/upload", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body));
|
||||
@@ -28,22 +37,30 @@ export function createPluginAdminRouter(options: {
|
||||
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 });
|
||||
response.status(201).json({ plugin:project(plugin) });
|
||||
});
|
||||
router.put("/:id/settings", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
|
||||
const plugin = await registry().configure(String(request.params.id), request.body.settings, request.body.revision);
|
||||
await options.runtime?.synchronize(plugin.manifest.id);
|
||||
options.audit("ADMIN_PLUGIN_CONFIGURED", { id: plugin.manifest.id });
|
||||
response.json({ plugin });
|
||||
response.json({ plugin:project(plugin) });
|
||||
});
|
||||
router.post("/:id/restart",async(request,response)=>{
|
||||
pluginAssert(options.runtime&&pluginRecord(request.body));const id=String(request.params.id),plugin=registry().policy(id);
|
||||
pluginAssert(plugin,"PLUGIN_NOT_FOUND");pluginAssert(plugin.revision===request.body.revision,"PLUGIN_CHANGED");pluginAssert(plugin.settings.enabled&&plugin.settings.trusted,"PLUGIN_DISABLED");
|
||||
await options.runtime.restart(id);options.audit("ADMIN_PLUGIN_RESTARTED",{id});response.json({plugin:project(plugin)});
|
||||
});
|
||||
router.delete("/:id", async (request, response) => {
|
||||
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
|
||||
await registry().remove(String(request.params.id), request.body.revision);
|
||||
await options.runtime?.synchronize(String(request.params.id));
|
||||
options.audit("ADMIN_PLUGIN_REMOVED", { id: String(request.params.id) }); response.json({ ok: true });
|
||||
});
|
||||
router.use((error: unknown, _request: unknown, response: import("express").Response, _next: unknown) => {
|
||||
const 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 });
|
||||
const tooLarge=pluginRecord(error)&&error.type==="entity.too.large";
|
||||
const code = tooLarge?"PLUGIN_TOO_LARGE":error instanceof PluginError ? error.code : "PLUGIN_FAILED";
|
||||
response.status(tooLarge?413:code === "PLUGIN_STORE_UNAVAILABLE" ? 502 : code === "PLUGIN_NOT_FOUND" ? 404 : code === "PLUGIN_CHANGED" ? 409 : 400).json({ ok: false, code });
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
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<string>; 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<string, Room>();
|
||||
private readonly memberships = new Map<string, Map<string, Membership>>();
|
||||
private readonly limits = new Map<string, { time: number; count: number }>();
|
||||
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<string, PluginParticipant>,
|
||||
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<string, Membership>();
|
||||
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<string, Membership>();
|
||||
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(); }
|
||||
}
|
||||
+52
-102
@@ -3,113 +3,63 @@ 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';
|
||||
import { PluginProcess } from './process.js';
|
||||
import { parsePluginPackage, parsePluginJson, pluginPath, pluginFileBytes, type PluginPackage, type PluginAppContext } from '../shared/plugins.js';
|
||||
import { createLogger } from '../logger.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}));
|
||||
export const fixturePackage = (server?:string):PluginPackage => parsePluginPackage({manifest:{apiVersion:2,id:'test.application',name:'Application',version:'1.0.0',author:'Tests',license:'MIT',description:'Independent application fixture',scopes:['server','instance'],client:{entry:'client/index.html'},...(server?{server:{entry:'server/main.mjs'}}:{})},files:{'client/index.html':{encoding:'utf8',data:'<!doctype html><html><head></head><body><script type="module" src="./app.js"></script></body></html>'},'client/app.js':{encoding:'utf8',data:'document.body.dataset.ready="yes"'},...(server?{'server/main.mjs':{encoding:'utf8',data:server}}:{})}});
|
||||
async function registry(t:test.TestContext){const directory=await mkdtemp(path.join(tmpdir(),'webspeak-app-v2-'));const cleanup:Array<()=>Promise<unknown>>=[];t.after(async()=>{for(const dispose of cleanup)await dispose();assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});const value=new PluginRegistry(directory,Buffer.alloc(32,7));await value.initialize();return {value,directory,cleanup};}
|
||||
|
||||
test('v2 accepts ordinary application assets and rejects the obsolete room protocol',()=>{
|
||||
const pack=fixturePackage();assert.equal(pack.manifest.apiVersion,2);assert.ok(pack.files['client/app.js']);
|
||||
assert.throws(()=>parsePluginPackage({manifest:{...pack.manifest,apiVersion:1},html:'x',script:'x',styles:{light:'x',dark:'x'}}),/PLUGIN_API_UNSUPPORTED/);
|
||||
assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,permissions:['room.read']}}),/PLUGIN_API_UNSUPPORTED/);
|
||||
const binary=parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'AAEC/w=='}}});assert.deepEqual([...pluginFileBytes(binary.files['client/asset.bin'])],[0,1,2,255]);
|
||||
assert.throws(()=>parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'!notbase64'}}}));
|
||||
});
|
||||
test('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('package paths reject traversal, Windows special names, case collisions and file-directory aliases',()=>{
|
||||
for(const name of ['../a','client/../a','client/a\\b','client/CON.txt','client/aux','client/a.','/client/a'])assert.equal(pluginPath(name),false,name);
|
||||
const pack=fixturePackage();
|
||||
for(const files of [{...pack.files,'client/APP.js':{encoding:'utf8',data:'x'}},{...pack.files,'client/folder':{encoding:'utf8',data:'x'},'client/folder/file.js':{encoding:'utf8',data:'x'}}])assert.throws(()=>parsePluginPackage({...pack,files}));
|
||||
assert.throws(()=>parsePluginJson(JSON.parse('{"__proto__":{"value":1}}')));assert.throws(()=>parsePluginJson({n:Infinity}));
|
||||
});
|
||||
test('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<PluginMessage,{type:'pluginReply'}>;};
|
||||
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('install and update require explicit trust, encrypt private config and preserve CAS/persistence',async t=>{
|
||||
const {value:r,directory}=await registry(t),pack=fixturePackage();const first=await r.install(pack,null);
|
||||
assert.equal(first.settings.enabled,false);assert.equal(first.settings.trusted,false);
|
||||
await assert.rejects(r.configure(pack.manifest.id,{enabled:true,trusted:false,scope:'instance',targets:[],config:{}},first.revision),/PLUGIN_TRUST_REQUIRED/);
|
||||
const enabled=await r.configure(pack.manifest.id,{enabled:true,trusted:true,scope:'server',targets:['EXAMPLE.com#9987'],config:{public:'value'},serverConfigAction:'replace',serverConfig:{secret:'private-fixture-value'}},first.revision);
|
||||
assert.deepEqual(enabled.settings.targets,['example.com:9987']);assert.equal(enabled.settings.hasServerConfig,true);assert.equal(JSON.stringify(enabled).includes('private-fixture-value'),false);
|
||||
const record=await readFile(path.join(directory,'installed',pack.manifest.id+'.json'),'utf8');assert.equal(record.includes('private-fixture-value'),false);assert.deepEqual(r.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
|
||||
await assert.rejects(r.configure(pack.manifest.id,enabled.settings,first.revision),/PLUGIN_CHANGED/);
|
||||
const reloaded=new PluginRegistry(directory,Buffer.alloc(32,7));await reloaded.initialize();assert.deepEqual(reloaded.list(),r.list());assert.deepEqual(reloaded.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
|
||||
const update=await r.install({...pack,manifest:{...pack.manifest,version:'1.1.0'}},enabled.revision);assert.equal(update.settings.enabled,false);assert.equal(update.settings.trusted,false);assert.equal(update.settings.hasServerConfig,true);
|
||||
const cleared=await r.configure(pack.manifest.id,{...update.settings,serverConfigAction:'remove'},update.revision);assert.equal(cleared.settings.hasServerConfig,false);
|
||||
await r.remove(pack.manifest.id,cleared.revision);assert.equal(r.list().length,0);
|
||||
});
|
||||
test('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<PluginMessage,{type:'pluginReply'}>;}
|
||||
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('materialized applications contain their own files and package integrity is checked',async t=>{
|
||||
const {value:r}=await registry(t),pack=fixturePackage();const installed=await r.install(pack,null);const directory=await r.materialize(pack.manifest.id,installed.revision);
|
||||
assert.match(await readFile(path.join(directory,'client/index.html'),'utf8'),/type="module"/);
|
||||
await assert.rejects(r.releaseCode(path.resolve(directory,'../../../../unrelated')),/PLUGIN_INVALID/);
|
||||
await r.releaseCode(directory);await assert.rejects(readFile(path.join(directory,'client/index.html')));
|
||||
});
|
||||
|
||||
test('a 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<PluginMessage,{type:'pluginReply'}>;};
|
||||
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);
|
||||
test('a backend runs native Node filesystem and arbitrary HTTP handlers in an independent process',async t=>{
|
||||
const {value:r,cleanup}=await registry(t);
|
||||
const source=`import {writeFile,readFile} from 'node:fs/promises';import path from 'node:path';export default async ({dataDir,config})=>{let count=Number(await readFile(path.join(dataDir,'counter.txt'),'utf8').catch(()=>0));return {handle:async(req,res)=>{count++;await writeFile(path.join(dataDir,'counter.txt'),String(count));res.setHeader('content-type','application/json');res.end(JSON.stringify({path:req.url,user:req.webspeak.self.id,configured:config.secret==='private',count,pid:process.pid}));}};};`;
|
||||
const pack=fixturePackage(source),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision),data=await r.dataDirectory(pack.manifest.id);
|
||||
const processes:PluginProcess[]=[];cleanup.push(async()=>{await Promise.all(processes.map(p=>p.close()));});
|
||||
const run=()=>{const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:data,config:{secret:'private'},publicConfig:{},logger:createLogger(),onExit:()=>{}});processes.push(child);return child;};
|
||||
const child=run();await child.ready;assert.ok(child.child.pid&&child.child.pid!==process.pid);
|
||||
const context={apiVersion:2,self:{id:'participant-a'},scope:{key:'instance'}} as PluginAppContext;
|
||||
const request=()=>fetch(`http://127.0.0.1:${child.port}/author-defined/path`,{headers:{'x-webspeak-runtime':child.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});
|
||||
assert.equal((await fetch(`http://127.0.0.1:${child.port}/author-defined/path`)).status,403);
|
||||
const value=await(await request()).json();assert.equal(value.path,'/author-defined/path');assert.equal(value.user,'participant-a');assert.equal(value.configured,true);assert.equal(value.count,1);
|
||||
await child.close();const replacement=run();await replacement.ready;
|
||||
const next=await fetch(`http://127.0.0.1:${replacement.port}/another-route`,{headers:{'x-webspeak-runtime':replacement.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});assert.equal((await next.json()).count,2);
|
||||
});
|
||||
test('a failed or hung plugin activation is bounded and does not execute in the gateway process',async t=>{
|
||||
const {value:r,cleanup}=await registry(t),pack=fixturePackage('export default async()=>new Promise(()=>{});'),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision);
|
||||
const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:await r.dataDirectory(pack.manifest.id),config:{},publicConfig:{},logger:createLogger(),onExit:()=>{},startupMs:1000});
|
||||
cleanup.push(()=>child.close());await assert.rejects(child.ready,/PLUGIN_START_TIMEOUT/);await child.close();assert.notEqual(child.child.exitCode,null);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { PluginError, pluginRecord, type JsonValue } from "../shared/plugins.js";
|
||||
|
||||
export class PluginProcess {
|
||||
readonly token = randomBytes(32).toString("base64url");
|
||||
readonly child: ChildProcess;
|
||||
readonly ready: Promise<number>;
|
||||
readonly exited: Promise<void>;
|
||||
port = 0;
|
||||
private stopping = false;
|
||||
private finished = false;
|
||||
private closePromise?: Promise<void>;
|
||||
constructor(options: {
|
||||
entry: string; codeDirectory: string; dataDirectory: string; config: JsonValue; publicConfig: JsonValue;
|
||||
logger: Logger; onExit(): void; startupMs?: number;
|
||||
}) {
|
||||
const typescript = import.meta.url.endsWith(".ts");
|
||||
const worker = fileURLToPath(new URL(typescript ? "./worker.ts" : "./worker.js", import.meta.url));
|
||||
const execArgv = [...(typescript ? ["--import", import.meta.resolve("tsx")] : []), "--max-old-space-size=256"];
|
||||
// Separate process and reduced environment; reviewed backend code still has the OS user's permissions.
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const key of ["PATH", "Path", "SystemRoot", "WINDIR", "TEMP", "TMP", "LANG", "NODE_EXTRA_CA_CERTS"]) if (process.env[key]) env[key] = process.env[key];
|
||||
this.child = spawn(process.execPath, [...execArgv, worker], { cwd: options.codeDirectory, env, windowsHide: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
|
||||
let resolveExit!: () => void;
|
||||
this.exited = new Promise(resolve => { resolveExit = resolve; });
|
||||
let resolveReady!: (port: number) => void, rejectReady!: (error: Error) => void;
|
||||
this.ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const timer = setTimeout(() => { rejectReady(new PluginError("PLUGIN_START_TIMEOUT")); void this.close(); }, options.startupMs ?? 10000);
|
||||
let logWindow = Date.now(), logs = 0;
|
||||
this.child.on("message", value => {
|
||||
if (!pluginRecord(value) || this.stopping) return;
|
||||
if (value.type === "ready" && Number.isInteger(value.port) && Number(value.port) > 0 && Number(value.port) <= 65535) {
|
||||
clearTimeout(timer); this.port = Number(value.port); resolveReady(this.port);
|
||||
} else if (value.type === "failed") {
|
||||
clearTimeout(timer); rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close();
|
||||
} else if (value.type === "log" && typeof value.message === "string") {
|
||||
if (Date.now() - logWindow > 1000) { logWindow = Date.now(); logs = 0; }
|
||||
if (++logs <= 20) options.logger.debug({ message: value.message.slice(0, 1000) }, "Plugin application log");
|
||||
}
|
||||
});
|
||||
const finish = () => {
|
||||
if (this.finished) return; this.finished = true; clearTimeout(timer);
|
||||
rejectReady(new PluginError(this.stopping ? "PLUGIN_STOPPED" : "PLUGIN_PROCESS_EXITED"));
|
||||
resolveExit(); if (!this.stopping) options.onExit();
|
||||
};
|
||||
this.child.once("error", finish); this.child.once("exit", finish);
|
||||
this.child.send({ type: "initialize", entry: options.entry, dataDir: options.dataDirectory, config: options.config, publicConfig: options.publicConfig, token: this.token }, error => {
|
||||
if (error) { rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close(); }
|
||||
});
|
||||
}
|
||||
event(name: string, payload: unknown): void {
|
||||
if (this.stopping || this.finished || !this.child.connected) return;
|
||||
try { this.child.send({ type: "event", name, payload }, () => undefined); } catch { /* Retired worker. */ }
|
||||
}
|
||||
close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.stopping = true;
|
||||
this.closePromise = (async () => {
|
||||
if (this.finished) return;
|
||||
if (this.child.connected) { try { this.child.send({ type: "stop" }, () => undefined); } catch {} }
|
||||
const killer = setTimeout(() => this.child.kill("SIGKILL"), 2000);
|
||||
try { await this.exited; } finally { clearTimeout(killer); }
|
||||
})();
|
||||
return this.closePromise;
|
||||
}
|
||||
}
|
||||
+80
-66
@@ -1,84 +1,98 @@
|
||||
import { mkdir, readFile, readdir, writeFile, rename, unlink } from "node:fs/promises";
|
||||
import { mkdir, readFile, readdir, writeFile, rename, unlink, mkdtemp, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
|
||||
import { parsePluginPackage, parsePluginJson, pluginAssert, pluginId, pluginRecord, PluginError, PLUGIN_LIMIT_BYTES,
|
||||
type InstalledPlugin, type PluginPackage, type PluginSettings } from "../shared/plugins.js";
|
||||
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
|
||||
import { loadOrCreateMasterSecret } from "../security/master-secret.js";
|
||||
import { parsePluginPackage, parsePluginManifest, parsePluginJson, pluginAssert, pluginId, pluginRecord, pluginFileBytes, PluginError, PLUGIN_LIMIT_BYTES,
|
||||
type InstalledPlugin, type PluginPackage, type PluginSettings, type JsonValue } from "../shared/plugins.js";
|
||||
|
||||
interface StoredPlugin extends InstalledPlugin { package: PluginPackage }
|
||||
interface StoredPlugin extends InstalledPlugin { schemaVersion: 2; packageDigest: string; serverConfigCiphertext: string }
|
||||
export class PluginRegistry {
|
||||
private records = new Map<string, StoredPlugin>();
|
||||
private readonly records = new Map<string, StoredPlugin>();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private readonly masterKey: Buffer;
|
||||
readonly listeners = new Set<(id: string) => void>();
|
||||
constructor(private readonly directory: string) {}
|
||||
readonly directory: string;
|
||||
constructor(directory: string, masterKey?: Buffer) {
|
||||
this.directory = path.resolve(directory);
|
||||
this.masterKey = masterKey ?? loadOrCreateMasterSecret(path.join(this.directory,"master.key"));
|
||||
}
|
||||
async initialize(): Promise<void> {
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
for (const file of await readdir(this.directory)) {
|
||||
if (!file.endsWith(".json")) continue;
|
||||
await mkdir(path.join(this.directory,"installed"),{recursive:true});
|
||||
for (const file of await readdir(path.join(this.directory,"installed"))) {
|
||||
if (!file.endsWith('.json')) continue;
|
||||
try {
|
||||
const 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. */ }
|
||||
const bytes=await readFile(path.join(this.directory,"installed",file)); pluginAssert(bytes.length<=256*1024);
|
||||
const v:unknown=JSON.parse(bytes.toString('utf8'));pluginAssert(pluginRecord(v)&&v.schemaVersion===2);
|
||||
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
|
||||
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
|
||||
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
|
||||
this.readSecret(record);record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
|
||||
} catch { /* Invalid or obsolete packages are never executed. */ }
|
||||
}
|
||||
}
|
||||
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 public(record: StoredPlugin): InstalledPlugin {
|
||||
return structuredClone({manifest:record.manifest,settings:record.settings,revision:record.revision,installedAt:record.installedAt});
|
||||
}
|
||||
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) };
|
||||
list(): InstalledPlugin[] { return [...this.records.values()].map(record=>this.public(record)); }
|
||||
policy(id: string): InstalledPlugin | undefined { const record=this.records.get(id);return record?this.public(record):undefined; }
|
||||
private hash(record: Omit<StoredPlugin,'revision'> | StoredPlugin): string {
|
||||
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
|
||||
}
|
||||
private mutate<T>(run: () => Promise<T>): Promise<T> { const next = this.queue.then(run, run); this.queue = next.catch(() => undefined); return next; }
|
||||
private async commit(record: StoredPlugin): Promise<InstalledPlugin> {
|
||||
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);
|
||||
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
|
||||
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
|
||||
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
|
||||
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
|
||||
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
|
||||
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
|
||||
}
|
||||
install(pack: PluginPackage, expectedRevision: string | null): Promise<InstalledPlugin> {
|
||||
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() });
|
||||
});
|
||||
private readSecret(record: StoredPlugin): JsonValue {
|
||||
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
|
||||
return text?parsePluginJson(JSON.parse(text)):null;
|
||||
}
|
||||
configure(id: string, input: unknown, revision: string): Promise<InstalledPlugin> {
|
||||
return this.mutate(async () => {
|
||||
const record = this.records.get(id); pluginAssert(record, "PLUGIN_NOT_FOUND");
|
||||
pluginAssert(record.revision === revision, "PLUGIN_CHANGED");
|
||||
const settings = this.settings(input, record.package);
|
||||
return this.commit({ ...record, settings, revision: this.hash(record.package, settings) });
|
||||
});
|
||||
serverConfig(id: string): JsonValue { const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');return this.readSecret(record); }
|
||||
private mutate<T>(run:()=>Promise<T>):Promise<T>{const next=this.queue.then(run,run);this.queue=next.catch(()=>undefined);return next;}
|
||||
private async commit(record:StoredPlugin):Promise<InstalledPlugin>{
|
||||
record.revision=this.hash(record);const directory=path.join(this.directory,'installed'),temporary=path.join(directory,`.${randomUUID()}.tmp`);
|
||||
try{await writeFile(temporary,JSON.stringify(record),{flag:'wx',mode:0o600});await rename(temporary,path.join(directory,`${record.manifest.id}.json`));}finally{await unlink(temporary).catch(()=>undefined);}
|
||||
this.records.set(record.manifest.id,record);for(const listener of this.listeners){try{listener(record.manifest.id);}catch{}}
|
||||
return this.public(record);
|
||||
}
|
||||
remove(id: string, revision: string): Promise<void> {
|
||||
return this.mutate(async () => {
|
||||
pluginAssert(pluginId(id)); const record = this.records.get(id); pluginAssert(record, "PLUGIN_NOT_FOUND");
|
||||
pluginAssert(record.revision === revision, "PLUGIN_CHANGED");
|
||||
await unlink(path.join(this.directory, `${id}.json`)); this.records.delete(id);
|
||||
for (const listener of this.listeners) { try { listener(id); } catch { /* Removal already succeeded. */ } }
|
||||
});
|
||||
install(input:PluginPackage,expectedRevision:string|null):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
const pack=parsePluginPackage(input),previous=this.records.get(pack.manifest.id);pluginAssert((previous?.revision??null)===expectedRevision,'PLUGIN_CHANGED');pluginAssert(previous||this.records.size<50,'PLUGIN_LIMIT');
|
||||
const bytes=JSON.stringify(pack),digest=createHash('sha256').update(bytes).digest('hex'),directory=path.join(this.directory,'packages',pack.manifest.id);
|
||||
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
|
||||
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
|
||||
const old=previous?.settings;
|
||||
const settings={enabled:false,trusted:false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
|
||||
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
|
||||
});}
|
||||
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');pluginAssert(pluginRecord(input));
|
||||
let secret=record.serverConfigCiphertext;const action=input.serverConfigAction??'keep';pluginAssert(['keep','replace','remove'].includes(String(action)));
|
||||
if(action==='remove')secret='';else if(action==='replace')secret=encryptSecret(JSON.stringify(parsePluginJson(input.serverConfig)),this.masterKey,`webspeak:plugin-config:v2:${id}`);
|
||||
const settings=this.settings(input,record.manifest,!!secret);return this.commit({...record,settings,serverConfigCiphertext:secret});
|
||||
});}
|
||||
async getPackage(id:string):Promise<PluginPackage>{
|
||||
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');
|
||||
const bytes=await readFile(path.join(this.directory,'packages',id,`${record.packageDigest}.wplugin`));pluginAssert(bytes.length<=PLUGIN_LIMIT_BYTES,'PLUGIN_TOO_LARGE');
|
||||
pluginAssert(createHash('sha256').update(bytes).digest('hex')===record.packageDigest,'PLUGIN_CHECKSUM');
|
||||
const pack=parsePluginPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes)));pluginAssert(JSON.stringify(pack.manifest)===JSON.stringify(record.manifest),'PLUGIN_PACKAGE_MISMATCH');return pack;
|
||||
}
|
||||
async materialize(id:string,revision:string):Promise<string>{
|
||||
const record=this.records.get(id);pluginAssert(record?.revision===revision,'PLUGIN_CHANGED');const pack=await this.getPackage(id);pluginAssert(this.records.get(id)?.revision===revision,'PLUGIN_CHANGED');
|
||||
const parent=path.join(this.directory,'code',id);await mkdir(parent,{recursive:true});const root=await mkdtemp(path.join(parent,'run-'));
|
||||
try{for(const [name,file]of Object.entries(pack.files)){const target=path.resolve(root,name);pluginAssert(target.startsWith(root+path.sep));await mkdir(path.dirname(target),{recursive:true});await writeFile(target,pluginFileBytes(file),{flag:'wx',mode:0o600});}return root;}
|
||||
catch(error){await this.releaseCode(root);throw error;}
|
||||
}
|
||||
async releaseCode(directory:string):Promise<void>{
|
||||
const root=path.resolve(this.directory,'code');pluginAssert(path.resolve(directory).startsWith(root+path.sep));await rm(directory,{recursive:true,force:true});
|
||||
}
|
||||
async dataDirectory(id:string):Promise<string>{pluginAssert(pluginId(id));const directory=path.join(this.directory,'data',id);await mkdir(directory,{recursive:true});return directory;}
|
||||
remove(id:string,revision:string):Promise<void>{return this.mutate(async()=>{
|
||||
pluginAssert(pluginId(id));const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');
|
||||
await unlink(path.join(this.directory,'installed',`${id}.json`));this.records.delete(id);for(const listener of this.listeners){try{listener(id);}catch{}}
|
||||
});}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Router } from "express";
|
||||
import { PluginRuntime } from "./runtime.js";
|
||||
import { pluginAssert, PluginError, pluginRecord } from "../shared/plugins.js";
|
||||
|
||||
/** Control plane only. Application HTTP/WebSocket traffic lives on the independent origin. */
|
||||
export function createPluginRuntimeRouter(runtime?: PluginRuntime) {
|
||||
const router=Router();
|
||||
router.use((_request,response,next)=>{
|
||||
response.setHeader("access-control-allow-origin","*");
|
||||
response.setHeader("access-control-allow-headers","authorization, content-type");
|
||||
response.setHeader("access-control-allow-methods","GET, POST, PATCH, DELETE, OPTIONS");
|
||||
response.setHeader("cache-control","no-store");next();
|
||||
});
|
||||
router.options(/.*/,(_request,response)=>{response.sendStatus(204);});
|
||||
const token=(authorization:string|undefined)=>{pluginAssert(typeof authorization==="string"&&authorization.startsWith("Bearer "),"PLUGIN_NOT_CONNECTED");return authorization.slice(7);};
|
||||
const service=()=>{pluginAssert(runtime,"PLUGIN_RUNTIME_UNAVAILABLE");return runtime;};
|
||||
router.get("/",(request,response)=>{response.json({plugins:service().directory(token(request.header("authorization")))});});
|
||||
router.post("/:id/open",async(request,response)=>{
|
||||
const origin=request.header("origin")??`${request.protocol}://${request.header("host")}`;
|
||||
response.status(201).json(await service().open(token(request.header("authorization")),String(request.params.id),request.body,origin));
|
||||
});
|
||||
router.delete("/opening/:id",(request,response)=>{service().cancelOpen(token(request.header("authorization")),String(request.params.id));response.json({ok:true});});
|
||||
router.patch("/apps/:id",(request,response)=>{
|
||||
pluginAssert(pluginRecord(request.body));service().appearance(String(request.params.id),token(request.header("authorization")),request.body);response.json({ok:true});
|
||||
});
|
||||
router.delete("/apps/:id",(request,response)=>{
|
||||
const instance=service(),id=String(request.params.id);pluginAssert(instance.authorizeApp(id,token(request.header("authorization"))),"PLUGIN_NOT_OPEN");instance.closeApp(id);response.json({ok:true});
|
||||
});
|
||||
router.use((error:unknown,_request:unknown,response:import("express").Response,_next:unknown)=>{
|
||||
const code=error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED";
|
||||
response.status(code==="PLUGIN_NOT_CONNECTED"?401:code==="PLUGIN_NOT_FOUND"?404:code==="PLUGIN_RUNTIME_UNAVAILABLE"?503:403).json({ok:false,code});
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse, type Server } from "node:http";
|
||||
import { createServer as createHttpsServer, type ServerOptions } from "node:https";
|
||||
import { readFile, writeFile, rename } from "node:fs/promises";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Socket } from "node:net";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { PluginRegistry } from "./registry.js";
|
||||
import { PluginProcess } from "./process.js";
|
||||
import { PluginError, pluginAssert, pluginPath, pluginRecord, type InstalledPlugin, type PluginAppContext, type PluginAppLaunch, type PluginParticipant, type PluginRequestContext, type PluginRuntimeStatus } from "../shared/plugins.js";
|
||||
|
||||
interface ApplicationEntry { policy: InstalledPlugin; directory: string; assets: Set<string>; process?: PluginProcess; status: PluginRuntimeStatus; stale: boolean }
|
||||
interface AppSession {
|
||||
id: string; publicId: string; participantId: string; openKey: string; pluginId: string; revision: string; voiceToken: string; scopeKey: string;
|
||||
theme: "light" | "dark"; language: PluginAppContext["language"]; origin: string; lastActivity: number; lastContext: string;
|
||||
streams: Set<ServerResponse>; connections: Set<() => void>;
|
||||
}
|
||||
interface RuntimeOptions {
|
||||
registry: PluginRegistry; participant(token: string): PluginParticipant | null; logger: Logger;
|
||||
port?: number; host?: string; publicOrigin?: string; tls?: ServerOptions; maxWorkers?: number;
|
||||
}
|
||||
const contentTypes: Record<string, string> = { ".html":"text/html; charset=utf-8", ".js":"text/javascript; charset=utf-8", ".mjs":"text/javascript; charset=utf-8", ".css":"text/css; charset=utf-8", ".json":"application/json; charset=utf-8", ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".jpeg":"image/jpeg", ".webp":"image/webp", ".gif":"image/gif", ".ico":"image/x-icon", ".woff":"font/woff", ".woff2":"font/woff2", ".wasm":"application/wasm", ".mp4":"video/mp4", ".webm":"video/webm" };
|
||||
|
||||
/** App traffic uses its own HTTP origin and child processes, never the voice WebSocket. */
|
||||
export class PluginRuntime {
|
||||
private readonly entries = new Map<string, ApplicationEntry>();
|
||||
private readonly queues = new Map<string, Promise<unknown>>();
|
||||
private readonly sessions = new Map<string, AppSession>();
|
||||
private readonly openings = new Map<string, {cancelled:boolean; expires:number; appId?:string}>();
|
||||
private readonly server: Server | ReturnType<typeof createHttpsServer>;
|
||||
private readonly sockets = new Set<Socket>();
|
||||
private timer?: ReturnType<typeof setInterval>;
|
||||
private origin = "";
|
||||
private listening = false;
|
||||
private closed = false;
|
||||
private configQueue: Promise<unknown> = Promise.resolve();
|
||||
private readonly changed = (id: string) => {
|
||||
this.revokePlugin(id, "PLUGIN_CHANGED");
|
||||
const entry = this.entries.get(id); if (entry) { entry.stale = true; void entry.process?.close(); }
|
||||
void this.synchronize(id).catch(() => undefined);
|
||||
};
|
||||
constructor(private readonly options: RuntimeOptions) {
|
||||
this.server = options.tls ? createHttpsServer(options.tls, (req,res) => void this.handle(req,res)) : createServer((req,res) => void this.handle(req,res));
|
||||
this.server.on("connection", socket => { this.sockets.add(socket); socket.once("close", () => this.sockets.delete(socket)); });
|
||||
this.server.on("upgrade", (req,socket,head) => void this.upgrade(req,socket as Socket,head));
|
||||
options.registry.listeners.add(this.changed);
|
||||
}
|
||||
get port(): number { const address=this.server.address(); return address&&typeof address!=="string"?address.port:0; }
|
||||
settings() { return { publicOrigin:this.origin, port:this.port, available:this.listening, revision:createHash("sha256").update(this.origin).digest("hex") }; }
|
||||
async configureOrigin(input: unknown, revision: unknown): Promise<ReturnType<PluginRuntime["settings"]>> {
|
||||
const next=this.configQueue.then(async()=>{
|
||||
pluginAssert(typeof input==="string"&&input.length<=300&&typeof revision==="string");
|
||||
pluginAssert(revision===this.settings().revision,"PLUGIN_CHANGED");
|
||||
const origin=normalizeOrigin(input);
|
||||
const directory=this.options.registry.directory, temporary=path.join(directory,`.runtime-${randomUUID()}.tmp`);
|
||||
await writeFile(temporary,JSON.stringify({publicOrigin:origin}),{flag:"wx",mode:0o600}); await rename(temporary,path.join(directory,"runtime.json"));
|
||||
this.origin=origin;for(const app of [...this.sessions.values()])this.closeApp(app.id,"PLUGIN_CHANGED");return this.settings();
|
||||
});this.configQueue=next.catch(()=>undefined);return next;
|
||||
}
|
||||
async start(): Promise<void> {
|
||||
try { const value=JSON.parse(await readFile(path.join(this.options.registry.directory,"runtime.json"),"utf8"));this.origin=normalizeOrigin(value.publicOrigin); }
|
||||
catch { this.origin=normalizeOrigin(this.options.publicOrigin??""); }
|
||||
await new Promise<void>((resolve,reject)=>{
|
||||
const failed=(error:Error)=>{this.server.off("listening",ready);reject(error);};
|
||||
const ready=()=>{this.server.off("error",failed);this.listening=true;resolve();};
|
||||
this.server.once("error",failed);this.server.once("listening",ready);this.server.listen(this.options.port??3042,this.options.host??"0.0.0.0");
|
||||
});
|
||||
this.timer=setInterval(()=>this.reconcileSessions(),1000);
|
||||
// Applications may provide background integrations even without an open browser panel.
|
||||
await Promise.allSettled(this.options.registry.list().filter(p=>p.settings.enabled).map(p=>this.synchronize(p.manifest.id)));
|
||||
}
|
||||
status(id: string): PluginRuntimeStatus {
|
||||
const policy=this.options.registry.policy(id);if(!policy?.settings.enabled)return {state:"disabled"};
|
||||
return this.entries.get(id)?.status??{state:policy.manifest.server?"stopped":"client"};
|
||||
}
|
||||
private async stopEntry(entry: ApplicationEntry): Promise<void> {
|
||||
await entry.process?.close();if(entry.directory){await this.options.registry.releaseCode(entry.directory);entry.directory="";}
|
||||
}
|
||||
synchronize(id: string): Promise<void> {
|
||||
const next=(this.queues.get(id)??Promise.resolve()).then(async()=>{
|
||||
const policy=this.options.registry.policy(id),previous=this.entries.get(id);
|
||||
if(previous&&!previous.stale&&previous.policy.revision===policy?.revision)return;
|
||||
if(previous){await this.stopEntry(previous);this.entries.delete(id);}
|
||||
if(this.closed||!policy?.settings.enabled||!policy.settings.trusted)return;
|
||||
const entry:ApplicationEntry={policy,directory:"",assets:new Set(),status:{state:"starting"},stale:false};this.entries.set(id,entry);
|
||||
try {
|
||||
if(policy.manifest.server)pluginAssert([...this.entries.values()].filter(p=>p.policy.manifest.server&&["starting","running"].includes(p.status.state)).length<=(this.options.maxWorkers??8),"PLUGIN_WORKER_LIMIT");
|
||||
entry.assets=new Set(Object.keys((await this.options.registry.getPackage(id)).files).filter(name=>name.startsWith("client/")));
|
||||
entry.directory=await this.options.registry.materialize(id,policy.revision);
|
||||
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
|
||||
if(policy.manifest.server){
|
||||
entry.process=new PluginProcess({entry:path.join(entry.directory,policy.manifest.server.entry),codeDirectory:entry.directory,dataDirectory:await this.options.registry.dataDirectory(id),config:this.options.registry.serverConfig(id),publicConfig:policy.settings.config,logger:this.options.logger.child({pluginId:id}),onExit:()=>{
|
||||
if(this.entries.get(id)===entry&&!entry.stale&&!this.closed){entry.status={state:"failed",error:"PLUGIN_PROCESS_EXITED"};this.revokePlugin(id,"PLUGIN_PROCESS_EXITED");}
|
||||
}});await entry.process.ready;
|
||||
}
|
||||
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
|
||||
entry.status={state:policy.manifest.server?"running":"client"};
|
||||
} catch(error) {
|
||||
entry.status={state:"failed",error:error instanceof PluginError?error.code:"PLUGIN_START_FAILED"};
|
||||
await this.stopEntry(entry);this.options.logger.warn({pluginId:id,code:entry.status.error},"Plugin application failed to start");
|
||||
}
|
||||
});this.queues.set(id,next.catch(()=>undefined));return next;
|
||||
}
|
||||
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
|
||||
directory(voiceToken:string) {
|
||||
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
|
||||
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,runtime:this.status(policy.manifest.id)}));
|
||||
}
|
||||
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
|
||||
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
|
||||
if(policy.settings.scope==="instance")return "instance";
|
||||
pluginAssert(policy.settings.targets.includes(participant.target),"PLUGIN_NOT_ALLOWED");return `${participant.target}#${participant.channelId}`;
|
||||
}
|
||||
private appOrigin(mainOrigin:string):string{
|
||||
pluginAssert(this.listening,"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
if(this.origin){pluginAssert(this.origin!==new URL(mainOrigin).origin,"PLUGIN_SEPARATE_ORIGIN_REQUIRED");return this.origin;}
|
||||
const source=new URL(mainOrigin);pluginAssert(["127.0.0.1","localhost","[::1]"].includes(source.hostname),"PLUGIN_PUBLIC_ORIGIN_REQUIRED");
|
||||
source.hostname=source.hostname==="localhost"?"127.0.0.1":"localhost";source.port=String(this.port);source.protocol=this.options.tls?"https:":"http:";return source.origin;
|
||||
}
|
||||
async open(voiceToken:string,id:string,input:unknown,mainOrigin:string):Promise<PluginAppLaunch>{
|
||||
const participant=this.options.participant(voiceToken),policy=this.options.registry.policy(id);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");pluginAssert(policy,"PLUGIN_NOT_FOUND");
|
||||
const preferences=pluginRecord(input)?input:{},openId=preferences.openId??randomUUID();
|
||||
pluginAssert(typeof openId==="string"&&/^[a-zA-Z0-9-]{8,80}$/.test(openId));const openKey=voiceToken+":"+openId,previous=this.openings.get(openKey);
|
||||
if(previous?.appId){const app=this.sessions.get(previous.appId);if(app&&this.validate(app)){pluginAssert(app.pluginId===id,"PLUGIN_OPEN_CONFLICT");return {id:app.id,url:`${app.origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};}}
|
||||
pluginAssert(!previous,previous?.cancelled?"PLUGIN_CANCELLED":"PLUGIN_OPEN_PENDING");
|
||||
pluginAssert([...this.openings.keys()].filter(key=>key.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
|
||||
const operation={cancelled:false,expires:Date.now()+90000,appId:undefined as string|undefined};this.openings.set(openKey,operation);
|
||||
const scopeKey=this.scopeKey(policy,participant),origin=this.appOrigin(mainOrigin);
|
||||
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
|
||||
await this.synchronize(id);const entry=this.entries.get(id);pluginAssert(entry&&["running","client"].includes(entry.status.state),entry?.status.error??"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
pluginAssert(!operation.cancelled,"PLUGIN_CANCELLED");
|
||||
const current=this.options.participant(voiceToken);pluginAssert(current&&this.options.registry.policy(id)?.revision===policy.revision&&this.scopeKey(policy,current)===scopeKey,"PLUGIN_CONTEXT_CHANGED");
|
||||
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
|
||||
const app:AppSession={id:randomBytes(32).toString("base64url"),publicId:randomUUID(),participantId:current.id,openKey,pluginId:id,revision:policy.revision,voiceToken,scopeKey,origin,theme:preferences.theme==="dark"?"dark":"light",language:["zh","en","de","ru","ja"].includes(String(preferences.language))?preferences.language as PluginAppContext["language"]:"en",lastActivity:Date.now(),lastContext:"",streams:new Set(),connections:new Set()};
|
||||
operation.appId=app.id;
|
||||
this.sessions.set(app.id,app);entry.process?.event("participantJoined",this.requestContext(app,current));
|
||||
return {id:app.id,url:`${origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};
|
||||
}
|
||||
authorizeApp(id:string,voiceToken:string):boolean{return this.sessions.get(id)?.voiceToken===voiceToken;}
|
||||
cancelOpen(voiceToken:string,openId:string):void{
|
||||
pluginAssert(/^[a-zA-Z0-9-]{8,80}$/.test(openId));const key=voiceToken+":"+openId,operation=this.openings.get(key);
|
||||
if(operation){operation.cancelled=true;if(operation.appId)this.closeApp(operation.appId);return;}
|
||||
pluginAssert(this.options.participant(voiceToken),"PLUGIN_NOT_CONNECTED");
|
||||
pluginAssert([...this.openings.keys()].filter(item=>item.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
|
||||
this.openings.set(key,{cancelled:true,expires:Date.now()+90000});
|
||||
}
|
||||
appearance(id:string,voiceToken:string,input:unknown):void{
|
||||
pluginAssert(this.authorizeApp(id,voiceToken)&&pluginRecord(input),"PLUGIN_NOT_OPEN");const app=this.sessions.get(id)!;
|
||||
if(input.theme==="light"||input.theme==="dark")app.theme=input.theme;
|
||||
if(["zh","en","de","ru","ja"].includes(String(input.language)))app.language=input.language as PluginAppContext["language"];
|
||||
this.publishContext(app);
|
||||
}
|
||||
closeApp(id:string,code="PLUGIN_CLOSED"):void{
|
||||
const app=this.sessions.get(id);if(!app)return;this.sessions.delete(id);
|
||||
const opening=this.openings.get(app.openKey);if(opening){opening.cancelled=true;opening.appId=undefined;opening.expires=Date.now()+90000;}
|
||||
for(const response of app.streams){if(!response.destroyed)response.end(`event: closed\ndata: ${JSON.stringify({code})}\n\n`);}
|
||||
for(const close of app.connections){try{close();}catch{}}
|
||||
this.entries.get(app.pluginId)?.process?.event("participantLeft",{appId:app.publicId,selfId:app.participantId,scopeKey:app.scopeKey});
|
||||
}
|
||||
private revokePlugin(id:string,code:string):void{for(const app of [...this.sessions.values()])if(app.pluginId===id)this.closeApp(app.id,code);}
|
||||
private context(app:AppSession,participant:PluginParticipant):PluginAppContext{
|
||||
const policy=this.options.registry.policy(app.pluginId)!;
|
||||
const base=`${app.origin}/apps/${app.id}`;
|
||||
return {...this.requestContext(app,participant),plugin:policy.manifest,connection:{target:participant.target,channelId:participant.channelId,members:participant.members},config:policy.settings.config,theme:app.theme,language:app.language,
|
||||
serverUrl:policy.manifest.server?`${base}/server`:null,socketUrl:policy.manifest.server?`${base.replace(/^http/,"ws")}/server`:null,contextUrl:`${base}/_runtime/context`};
|
||||
}
|
||||
private requestContext(app:AppSession,participant:PluginParticipant):PluginRequestContext{
|
||||
return {apiVersion:2,appId:app.publicId,self:{id:participant.id,nickname:participant.nickname,...(participant.uid?{uid:participant.uid}:{})},connection:{target:participant.target,channelId:participant.channelId},scope:{type:this.options.registry.policy(app.pluginId)!.settings.scope,key:app.scopeKey}};
|
||||
}
|
||||
private validate(app:AppSession):PluginParticipant|null{
|
||||
const policy=this.options.registry.policy(app.pluginId),participant=this.options.participant(app.voiceToken);
|
||||
try{return policy&&policy.revision===app.revision&&participant&&this.scopeKey(policy,participant)===app.scopeKey?participant:null;}catch{return null;}
|
||||
}
|
||||
private publishContext(app:AppSession):void{
|
||||
const participant=this.validate(app);if(!participant){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");return;}
|
||||
const context=this.context(app,participant),json=JSON.stringify(context);
|
||||
if(json!==app.lastContext){app.lastContext=json;for(const response of app.streams)if(!response.destroyed)response.write(`event: context\ndata: ${json}\n\n`);this.entries.get(app.pluginId)?.process?.event("contextChanged",{...this.requestContext(app,participant),connection:context.connection});}
|
||||
}
|
||||
private reconcileSessions():void{
|
||||
for(const [key,operation]of this.openings)if(!operation.appId&&operation.expires<Date.now())this.openings.delete(key);
|
||||
for(const app of [...this.sessions.values()]){
|
||||
if(!this.validate(app)||(!app.streams.size&&Date.now()-app.lastActivity>90000)){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");continue;}
|
||||
this.publishContext(app);for(const response of app.streams){if(response.destroyed)app.streams.delete(response);else if(response.writableLength>256*1024){response.destroy();app.streams.delete(response);}else response.write(": keepalive\n\n");}
|
||||
}
|
||||
}
|
||||
private locate(request:IncomingMessage):{app:AppSession;route:string;query:string;participant:PluginParticipant}{
|
||||
const url=new URL(request.url??"/","http://runtime.invalid"),match=/^\/apps\/([A-Za-z0-9_-]{43})\/(.*)$/.exec(url.pathname);
|
||||
pluginAssert(match,"PLUGIN_NOT_OPEN");const app=this.sessions.get(match[1]);pluginAssert(app,"PLUGIN_NOT_OPEN");
|
||||
const participant=this.validate(app);pluginAssert(participant,"PLUGIN_CONTEXT_CHANGED");app.lastActivity=Date.now();
|
||||
return {app,route:decodeURIComponent(match[2]),query:url.search,participant};
|
||||
}
|
||||
private async handle(request:IncomingMessage,response:ServerResponse):Promise<void>{
|
||||
response.setHeader("referrer-policy","no-referrer");response.setHeader("x-content-type-options","nosniff");response.setHeader("cache-control","no-store");
|
||||
try{
|
||||
const {app,route,query,participant}=this.locate(request),entry=this.entries.get(app.pluginId);pluginAssert(entry?.directory,"PLUGIN_RUNTIME_UNAVAILABLE");
|
||||
if(route.startsWith("server/")||route==="server"){this.proxy(request,response,app,participant,"/"+route.slice(7)+query);return;}
|
||||
pluginAssert(request.method==="GET"||request.method==="HEAD","PLUGIN_METHOD_NOT_ALLOWED");
|
||||
if(route==="_runtime/context"){response.setHeader("content-type","application/json");response.end(JSON.stringify(this.context(app,participant)));return;}
|
||||
if(route==="_runtime/events"){
|
||||
pluginAssert(app.streams.size<4,"PLUGIN_LIMIT");response.writeHead(200,{"content-type":"text/event-stream","x-accel-buffering":"no"});response.flushHeaders();app.streams.add(response);
|
||||
response.write(`event: context\ndata: ${JSON.stringify(this.context(app,participant))}\n\n`);response.once("close",()=>app.streams.delete(response));return;
|
||||
}
|
||||
if(route==="_runtime/sdk.js"){response.setHeader("content-type","text/javascript; charset=utf-8");response.end(applicationSdk(this.context(app,participant),`${app.origin}/apps/${app.id}/_runtime/events`,app.id));return;}
|
||||
pluginAssert(route.startsWith("client/")&&pluginPath(route),"PLUGIN_ASSET_NOT_FOUND");
|
||||
pluginAssert(this.validate(app)&&entry.assets.has(route),"PLUGIN_ASSET_NOT_FOUND");
|
||||
const file=path.resolve(entry.directory,route);pluginAssert(file.startsWith(entry.directory+path.sep),"PLUGIN_ASSET_NOT_FOUND");
|
||||
response.setHeader("content-type",contentTypes[path.extname(route)]??"application/octet-stream");
|
||||
if(route===entry.policy.manifest.client.entry){
|
||||
let html=await readFile(file,"utf8");pluginAssert(this.validate(app),"PLUGIN_CONTEXT_CHANGED");
|
||||
const script=`<script src="/apps/${app.id}/_runtime/sdk.js"></script>`;
|
||||
if(/<head(?:\s[^>]*)?>/i.test(html))html=html.replace(/<head(?:\s[^>]*)?>/i,head=>head+script);
|
||||
else if(/<!doctype[^>]*>/i.test(html))html=html.replace(/<!doctype[^>]*>/i,doctype=>doctype+script);
|
||||
else html=script+html;
|
||||
response.end(request.method==="HEAD"?undefined:html);return;
|
||||
}
|
||||
if(request.method==="HEAD"){response.end();return;}
|
||||
const stream=createReadStream(file);stream.once("error",()=>{if(!response.headersSent)response.writeHead(404);response.end();});response.once("close",()=>stream.destroy());stream.pipe(response);
|
||||
}catch(error){if(!response.headersSent)response.writeHead(error instanceof PluginError&&error.code==="PLUGIN_ASSET_NOT_FOUND"?404:403,{"content-type":"application/json"});response.end(JSON.stringify({error:error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED"}));}
|
||||
}
|
||||
private headers(request:IncomingMessage,app:AppSession,participant:PluginParticipant):Record<string,string|string[]>{
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");
|
||||
const headers:Record<string,string|string[]>={};
|
||||
for(const [key,value]of Object.entries(request.headers))if(value!==undefined&&!['cookie','authorization','host','connection','proxy-authorization'].includes(key)&&!key.startsWith('x-webspeak-'))headers[key]=value;
|
||||
const context=this.requestContext(app,participant);
|
||||
headers['x-webspeak-runtime']=worker.token;headers['x-webspeak-context']=Buffer.from(JSON.stringify(context),'utf8').toString('base64url');return headers;
|
||||
}
|
||||
private proxy(request:IncomingMessage,response:ServerResponse,app:AppSession,participant:PluginParticipant,route:string):void{
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");pluginAssert(app.connections.size<32,"PLUGIN_BUSY");
|
||||
const upstream=httpRequest({hostname:"127.0.0.1",port:worker.port,path:route,method:request.method,headers:this.headers(request,app,participant)},incoming=>{
|
||||
if(response.destroyed||!this.sessions.has(app.id)){incoming.destroy();return;}
|
||||
const headers={...incoming.headers};delete headers['set-cookie'];response.writeHead(incoming.statusCode??502,headers);incoming.once('error',()=>response.destroy());incoming.pipe(response);
|
||||
});
|
||||
const close=()=>{upstream.destroy();if(!response.writableFinished)response.destroy();};app.connections.add(close);
|
||||
upstream.setTimeout(120000,()=>upstream.destroy());upstream.once('error',()=>{if(!response.headersSent)response.writeHead(502,{'content-type':'application/json'});response.end('{"error":"PLUGIN_BACKEND_UNAVAILABLE"}');});
|
||||
response.once('close',()=>{app.connections.delete(close);upstream.destroy();});request.once('aborted',close);request.pipe(upstream);
|
||||
}
|
||||
private async upgrade(request:IncomingMessage,socket:Socket,head:Buffer):Promise<void>{
|
||||
try{
|
||||
const {app,route,query,participant}=this.locate(request);pluginAssert(route==='server'||route.startsWith('server/'),"PLUGIN_NOT_ALLOWED");
|
||||
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port&&app.connections.size<32,"PLUGIN_BACKEND_UNAVAILABLE");
|
||||
const headers=this.headers(request,app,participant);headers.connection='Upgrade';headers.upgrade=String(request.headers.upgrade??'websocket');
|
||||
const upstream=httpRequest({hostname:'127.0.0.1',port:worker.port,path:'/'+route.slice(7)+query,headers});
|
||||
const close=()=>{upstream.destroy();socket.destroy();};app.connections.add(close);socket.once('close',()=>{app.connections.delete(close);upstream.destroy();});
|
||||
upstream.once('upgrade',(response,peer,upstreamHead)=>{
|
||||
socket.write(`HTTP/1.1 ${response.statusCode??101} Switching Protocols\r\n`);for(const [key,value]of Object.entries(response.headers))if(value!==undefined&&key!=='set-cookie')socket.write(`${key}: ${Array.isArray(value)?value.join(', '):value}\r\n`);socket.write('\r\n');
|
||||
if(head.length)peer.write(head);if(upstreamHead.length)socket.write(upstreamHead);peer.pipe(socket);socket.pipe(peer);peer.once('error',()=>socket.destroy());socket.once('error',()=>peer.destroy());
|
||||
app.connections.delete(close);const closePeer=()=>{peer.destroy();socket.destroy();};app.connections.add(closePeer);socket.once('close',()=>{app.connections.delete(closePeer);peer.destroy();});peer.once('close',()=>socket.destroy());
|
||||
});
|
||||
upstream.once('error',close);upstream.once('response',()=>close());upstream.end();
|
||||
}catch{socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');}
|
||||
}
|
||||
async close():Promise<void>{
|
||||
if(this.closed)return;this.closed=true;this.listening=false;clearInterval(this.timer);this.options.registry.listeners.delete(this.changed);
|
||||
for(const app of [...this.sessions.values()])this.closeApp(app.id);
|
||||
this.openings.clear();
|
||||
await Promise.allSettled([...this.entries.values()].map(entry=>entry.process?.close()));
|
||||
await Promise.allSettled(this.queues.values());await Promise.allSettled([...this.entries.values()].map(entry=>this.stopEntry(entry)));this.entries.clear();
|
||||
for(const socket of this.sockets)socket.destroy();await new Promise<void>(resolve=>this.server.close(()=>resolve()));
|
||||
}
|
||||
}
|
||||
function normalizeOrigin(value:unknown):string{
|
||||
pluginAssert(typeof value==='string'&&value.length<=300);if(!value.trim())return '';
|
||||
const url=new URL(value.trim());pluginAssert(['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash&&url.pathname==='/');
|
||||
pluginAssert(url.protocol==='https:'||['localhost','127.0.0.1','[::1]'].includes(url.hostname),'PLUGIN_HTTPS_REQUIRED');return url.origin;
|
||||
}
|
||||
function applicationSdk(context:PluginAppContext,eventsUrl:string,id:string):string{
|
||||
// No expression evaluator, business RPC, shared rooms, dependency loader, or network allowlist.
|
||||
return `(()=>{let context=${JSON.stringify(context).replace(/</g,'\\u003c')};const listeners=new Set(),closed=new AbortController();document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;
|
||||
const events=new EventSource(${JSON.stringify(eventsUrl)});events.addEventListener('context',event=>{try{context=JSON.parse(event.data);document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;for(const fn of listeners){try{fn(context)}catch{}}}catch{}});
|
||||
events.addEventListener('closed',()=>{closed.abort();events.close();parent.postMessage({type:'webspeak-app-closed',id:${JSON.stringify(id)}},'*')});
|
||||
window.webspeak=Object.freeze({apiVersion:2,ready:Promise.resolve(context),getContext:()=>context,onContextChange(fn){listeners.add(fn);return()=>listeners.delete(fn)},signal:closed.signal});
|
||||
addEventListener('pagehide',()=>{closed.abort();events.close();listeners.clear()},{once:true});})();`;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export class PluginStore {
|
||||
}
|
||||
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);
|
||||
pluginAssert(pluginRecord(root) && root.schemaVersion === 2 && Array.isArray(root.plugins) && root.plugins.length <= 50,"PLUGIN_CATALOG_UNSUPPORTED");
|
||||
const seen = new Set<string>();
|
||||
return root.plugins.map(item => {
|
||||
pluginAssert(pluginRecord(item) && pluginId(item.id) && !seen.has(item.id)); seen.add(item.id);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/** Child-process entrypoint. Reviewed applications run normal Node.js, not a JS sandbox. */
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { type Socket } from "node:net";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import type { JsonValue, PluginRequestContext } from "../shared/plugins.js";
|
||||
|
||||
interface RequestContext extends IncomingMessage { webspeak?: PluginRequestContext }
|
||||
interface Application {
|
||||
handle(request: RequestContext, response: ServerResponse): unknown;
|
||||
upgrade?(request: RequestContext, socket: Socket, head: Buffer): unknown;
|
||||
stop?(): unknown;
|
||||
}
|
||||
interface Initialization { type: "initialize"; entry: string; dataDir: string; config: JsonValue; publicConfig: JsonValue; token: string }
|
||||
const events = new EventEmitter(), abort = new AbortController(), sockets = new Set<Socket>();
|
||||
let application: Application | undefined, initialized = false, stopping = false, secret = "";
|
||||
const server = createServer((request: RequestContext, response) => {
|
||||
if (!authorize(request)) { response.writeHead(403).end(); return; }
|
||||
Promise.resolve().then(() => application!.handle(request, response)).catch(() => {
|
||||
if (!response.headersSent) response.writeHead(500, { "content-type": "application/json" });
|
||||
if (!response.destroyed) response.end('{"error":"PLUGIN_HANDLER_FAILED"}');
|
||||
});
|
||||
});
|
||||
function authorize(request: RequestContext): boolean {
|
||||
if (!secret || request.headers["x-webspeak-runtime"] !== secret) return false;
|
||||
delete request.headers["x-webspeak-runtime"];
|
||||
try {
|
||||
const context = JSON.parse(Buffer.from(String(request.headers["x-webspeak-context"]), "base64url").toString("utf8"));
|
||||
if (context?.apiVersion !== 2 || !context.self?.id || !context.scope?.key) return false;
|
||||
request.webspeak = context;
|
||||
delete request.headers["x-webspeak-context"];
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); });
|
||||
server.on("upgrade", (request: RequestContext, socket: Socket, head) => {
|
||||
if (!authorize(request) || !application?.upgrade) { socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); return; }
|
||||
Promise.resolve().then(() => application!.upgrade!(request, socket, head)).catch(() => socket.destroy());
|
||||
});
|
||||
server.on("error", () => { process.send?.({ type: "failed", code: "PLUGIN_LISTEN_FAILED" }); void stop(); });
|
||||
async function initialize(value: Initialization): Promise<void> {
|
||||
if (initialized) return;
|
||||
initialized = true; secret = value.token;
|
||||
try {
|
||||
const module = await import(pathToFileURL(value.entry).href);
|
||||
if (typeof module.default !== "function") throw new Error("Expected a default activation function");
|
||||
const result = await module.default({
|
||||
dataDir: value.dataDir, config: value.config, publicConfig: value.publicConfig, events, signal: abort.signal,
|
||||
log(level: string, message: unknown) { process.send?.({ type: "log", level, message: String(message).slice(0, 1000) }); },
|
||||
});
|
||||
if (stopping) return;
|
||||
application = typeof result === "function" ? { handle: result } : result;
|
||||
if (!application || typeof application.handle !== "function") throw new Error("Expected a Node HTTP request handler");
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (address && typeof address !== "string") process.send?.({ type: "ready", port: address.port });
|
||||
});
|
||||
} catch { process.send?.({ type: "failed", code: "PLUGIN_START_FAILED" }); await stop(); }
|
||||
}
|
||||
async function stop(): Promise<void> {
|
||||
if (stopping) return;
|
||||
stopping = true; abort.abort();
|
||||
for (const socket of sockets) socket.destroy();
|
||||
server.close();
|
||||
try { await application?.stop?.(); } catch { /* Disposal cannot keep the worker alive. */ }
|
||||
events.removeAllListeners();
|
||||
if (process.connected) process.disconnect();
|
||||
process.exit(0);
|
||||
}
|
||||
process.on("message", (value: unknown) => {
|
||||
if (!value || typeof value !== "object" || !("type" in value)) return;
|
||||
if (value.type === "initialize") void initialize(value as Initialization);
|
||||
else if (value.type === "stop") void stop();
|
||||
else if (value.type === "event" && "name" in value && typeof value.name === "string" && !stopping) {
|
||||
try { events.emit(value.name, "payload" in value ? value.payload : undefined); } catch { /* App event failure is local to this worker. */ }
|
||||
}
|
||||
});
|
||||
process.once("disconnect", () => void stop());
|
||||
process.once("SIGTERM", () => void stop());
|
||||
process.once("SIGINT", () => void stop());
|
||||
+19
-9
@@ -19,6 +19,8 @@ import { createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voi
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
import type { PluginRegistry } from "../plugins/registry.js";
|
||||
import { PluginRuntime } from "../plugins/runtime.js";
|
||||
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -30,6 +32,7 @@ export interface WebServerOptions {
|
||||
adminService: AdminService;
|
||||
skinRegistry?: SkinRegistry;
|
||||
pluginRegistry?: PluginRegistry;
|
||||
pluginRuntime?: { port?: number; host?: string; publicOrigin?: string; maxWorkers?: number };
|
||||
logger: Logger;
|
||||
nextVisitorNumber?: () => number;
|
||||
visitorCount?: () => number;
|
||||
@@ -57,10 +60,13 @@ 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 json = express.json({ limit: "100kb" });
|
||||
app.use((request, response, next) => request.path.startsWith("/api/admin/plugins") ? next() : json(request, response, next));
|
||||
|
||||
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRegistry: options.pluginRegistry }, logger);
|
||||
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRuntimeEnabled: !!options.pluginRegistry }, logger);
|
||||
const pluginRuntime = options.pluginRegistry ? new PluginRuntime({ registry: options.pluginRegistry, participant: token => voiceBridge.resolvePluginParticipant(token), logger,
|
||||
...options.pluginRuntime, ...(options.certDir ? { tls: { cert: readFileSync(path.join(options.certDir,"cert.pem")), key: readFileSync(path.join(options.certDir,"key.pem")) } } : {}) }) : undefined;
|
||||
app.use("/api/plugins", createPluginRuntimeRouter(pluginRuntime));
|
||||
const adminSessions = new AdminSessionStore();
|
||||
const joinRateLimiter = new JoinRateLimiter();
|
||||
const startedAt = Date.now();
|
||||
@@ -277,6 +283,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
skinRegistry: options.skinRegistry,
|
||||
pluginRegistry: options.pluginRegistry,
|
||||
pluginRuntime,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
@@ -293,15 +300,18 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
voiceBridge.attach(server);
|
||||
|
||||
return {
|
||||
start(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
server.listen(options.port, () => {
|
||||
logger.info({ port: options.port }, "Web server started");
|
||||
resolve();
|
||||
});
|
||||
async start(): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(options.port, () => { server.off("error", reject); logger.info({ port: options.port }, "Web server started"); resolve(); });
|
||||
});
|
||||
if (pluginRuntime) {
|
||||
try { await pluginRuntime.start(); }
|
||||
catch { logger.warn({code:"PLUGIN_RUNTIME_UNAVAILABLE"},"Plugin application origin could not start; voice and administration remain available"); }
|
||||
}
|
||||
},
|
||||
async stop(): Promise<void> {
|
||||
await pluginRuntime?.close();
|
||||
await voiceBridge.shutdown();
|
||||
adminSessions.clear();
|
||||
return new Promise((resolve) => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import test from "node:test";
|
||||
import { asChannelGroupID, asChannelID, asClientID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
|
||||
import { asChannelGroupID, asChannelID, asClientID, asClientDBID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
|
||||
import { Client, generateIdentitySync, type ServerView } from "@honeybbq/teamspeak/client";
|
||||
import { TeamSpeakSdkClient, type DirectorySnapshot } from "./teamspeak-sdk.js";
|
||||
|
||||
@@ -13,7 +13,7 @@ function channel(id = 1): Channel {
|
||||
description: "", hasPassword: true, isPermanent: true, maxClients: 12, isMaxClientsUnlimited: false } as Channel;
|
||||
}
|
||||
function member(id = 1): ClientEntry {
|
||||
return { id: asClientID(id), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
|
||||
return { id: asClientID(id), databaseID: asClientDBID(BigInt(id)), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
|
||||
serverGroups: [], isAway: true, awayMessage: "Away", isInputMuted: true, isOutputMuted: false,
|
||||
isChannelCommander: true, avatar: "avatar-hash", isRecording: false, isTalker: false,
|
||||
channelGroupID: asChannelGroupID(0n), createdAt: undefined, lastConnectedAt: undefined, idleTimeMs: undefined };
|
||||
@@ -53,6 +53,28 @@ test("ordinary-client directories and avatar metadata use the live view without
|
||||
assert.deepEqual(native.queries, []);
|
||||
});
|
||||
|
||||
test('partial SDK records preserve unknown status and channel descriptions without querying', async () => {
|
||||
const { sdk, native } = fixture();
|
||||
const { uid: _uid, serverGroups: _groups, isAway: _away, awayMessage: _message,
|
||||
isInputMuted: _input, isOutputMuted: _output, isChannelCommander: _commander, ...partial } = member();
|
||||
native.view.clients.set(partial.id, partial);
|
||||
const { description: _description, ...room } = channel(); native.view.channels.set(room.id, room);
|
||||
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: 'Member 1', uid: '', serverGroups: [], channelID: 1n, type: 0 }]);
|
||||
assert.equal((await sdk.listDirectoryChannels())[0].description, undefined);
|
||||
assert.equal(await sdk.getClientAvatarMetadata(1), null);
|
||||
assert.deepEqual(native.queries, []);
|
||||
});
|
||||
|
||||
test('SDK end-of-speech markers are not sent into the audio decoder or browser transport', () => {
|
||||
const { sdk, native } = fixture(), received: unknown[] = [];
|
||||
sdk.on('voiceData', frame => received.push(frame));
|
||||
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data: new Uint8Array() });
|
||||
assert.deepEqual(received, []);
|
||||
const data = Uint8Array.of(1, 2);
|
||||
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data });
|
||||
assert.deepEqual(received, [{ clientId: 1, codec: 4, data }]);
|
||||
});
|
||||
|
||||
test("live-view snapshots include channel edits and remove clients that went out of view", () => {
|
||||
const { sdk, native } = fixture();
|
||||
const snapshots: DirectorySnapshot[] = [];
|
||||
|
||||
@@ -46,7 +46,7 @@ export interface DirectoryChannelInfo {
|
||||
parentID: bigint;
|
||||
order: bigint;
|
||||
name: string;
|
||||
description: string;
|
||||
description?: string;
|
||||
passwordProtected?: boolean;
|
||||
isPermanent?: boolean;
|
||||
maxClients?: number;
|
||||
@@ -230,7 +230,8 @@ export class TeamSpeakSdkClient extends EventEmitter implements CommandExecutor
|
||||
client.on("viewReady", () => this.publishDirectory(client));
|
||||
client.on("viewChanged", () => this.publishDirectory(client));
|
||||
client.on("voiceData", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
// beta.20+ reports an empty payload for end-of-speech, not an Opus frame.
|
||||
if (!isCurrent() || event.data.byteLength === 0) return;
|
||||
this.emit("voiceData", { clientId: Number(event.clientID), codec: event.codec, data: event.data } satisfies VoiceData);
|
||||
});
|
||||
client.on("textMessage", (event) => {
|
||||
@@ -328,8 +329,8 @@ function toDirectoryClient(entry: ClientEntry): DirectoryClientInfo {
|
||||
return {
|
||||
id: Number(entry.id),
|
||||
nickname: entry.nickname,
|
||||
uid: entry.uid,
|
||||
serverGroups: entry.serverGroups.map(String),
|
||||
uid: entry.uid ?? "",
|
||||
serverGroups: (entry.serverGroups ?? []).map(String),
|
||||
channelID: BigInt(entry.channelID),
|
||||
type: entry.type,
|
||||
...(entry.isAway !== undefined ? { away: entry.isAway } : {}),
|
||||
|
||||
+21
-23
@@ -10,7 +10,7 @@ import { resolveVoiceMediaAddresses } from "./webrtc-config.js";
|
||||
import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js";
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { randomUUID, randomBytes } from "node:crypto";
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
@@ -27,8 +27,7 @@ import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./ac
|
||||
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
import { PluginCoordinator } from "../plugins/coordinator.js";
|
||||
import type { PluginRegistry } from "../plugins/registry.js";
|
||||
import type { PluginParticipant } from "../shared/plugins.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const MAX_MISSED_HEARTBEATS = 2;
|
||||
@@ -51,7 +50,7 @@ function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>):
|
||||
}
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
pluginRegistry?: PluginRegistry;
|
||||
pluginRuntimeEnabled?: boolean;
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
|
||||
@@ -110,13 +109,13 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
lastAudioStatsProbeAt: number;
|
||||
connectionFailureCode?: string;
|
||||
screenPeerId: string;
|
||||
pluginSession?: string;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
private readonly sessionManager = new SessionManager();
|
||||
private readonly entries = new Map<string, WebClientEntry>();
|
||||
private readonly screenShares: ScreenShareCoordinator;
|
||||
private readonly plugins: PluginCoordinator;
|
||||
private readonly identityLeases = new IdentityLeaseStore();
|
||||
private wss: WebSocketServer | null = null;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -131,14 +130,6 @@ 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) {
|
||||
@@ -331,6 +322,7 @@ export class VoiceBridge {
|
||||
}, "Web client connected to TeamSpeak");
|
||||
}
|
||||
session.transition("connected");
|
||||
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
|
||||
sendJson({
|
||||
type: "connected",
|
||||
tsClientId: events.selfId,
|
||||
@@ -342,6 +334,7 @@ export class VoiceBridge {
|
||||
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
|
||||
screenShareIceServers: this.getScreenShareIceServers(),
|
||||
accelerated: Boolean(entry!.acceleration),
|
||||
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
|
||||
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
|
||||
});
|
||||
sendJson({ type: "channelList", channels: entry!.channelTree });
|
||||
@@ -506,7 +499,6 @@ export class VoiceBridge {
|
||||
},
|
||||
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),
|
||||
@@ -559,7 +551,6 @@ 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);
|
||||
@@ -581,12 +572,6 @@ 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) {
|
||||
@@ -670,7 +655,6 @@ export class VoiceBridge {
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.plugins.dispose();
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
@@ -723,6 +707,21 @@ export class VoiceBridge {
|
||||
});
|
||||
}
|
||||
|
||||
resolvePluginParticipant(token: string): PluginParticipant | null {
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
|
||||
for (const entry of this.entries.values()) {
|
||||
if (entry.pluginSession !== token || entry.session.state !== "connected" || entry.ws.readyState !== WebSocket.OPEN) continue;
|
||||
try {
|
||||
const selfId = entry.tsClient.getClientId(), channelId = entry.tsClient.getChannelId().toString();
|
||||
const uid = entry.members.get(selfId)?.uid;
|
||||
const members = entry.channelTree.find(channel => channel.id === channelId)?.members ?? [];
|
||||
return { id: entry.id, nickname: entry.nickname, ...(uid ? { uid } : {}), target: teamSpeakTargetKey(entry.target), channelId,
|
||||
members: members.map(member => ({ id: member.id, nickname: member.nickname, ...(member.uid ? { uid: member.uid } : {}) })) };
|
||||
} catch { return null; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async terminateSession(entryId: string): Promise<boolean> {
|
||||
if (!this.entries.has(entryId)) return false;
|
||||
await this.sessionManager.teardown(entryId, "admin-terminated");
|
||||
@@ -735,7 +734,6 @@ export class VoiceBridge {
|
||||
|
||||
private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise<void> {
|
||||
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;
|
||||
|
||||
+96
-82
@@ -1,101 +1,115 @@
|
||||
/** Versioned, browser-safe functional plugin contract; independent of .wskin. */
|
||||
export const PLUGIN_API_VERSION = 1;
|
||||
/** Portable application runtime v2. Independent of skins and their component APIs. */
|
||||
export const PLUGIN_API_VERSION = 2;
|
||||
export const PLUGIN_STORE_REPOSITORY = "https://github.com/Huddle-Up-Forge/webspeak-plugin";
|
||||
export const PLUGIN_STORE_INDEX = "https://raw.githubusercontent.com/Huddle-Up-Forge/webspeak-plugin/main/index.json";
|
||||
export const PLUGIN_LIMIT_BYTES = 512 * 1024;
|
||||
export const PLUGIN_STATE_LIMIT_BYTES = 16 * 1024;
|
||||
export const PLUGIN_LIMIT_BYTES = 48 * 1024 * 1024;
|
||||
export const PLUGIN_CONTENT_LIMIT_BYTES = 32 * 1024 * 1024;
|
||||
export const PLUGIN_FILE_LIMIT_BYTES = 16 * 1024 * 1024;
|
||||
export const pluginId = (v: unknown): v is string => typeof v === "string" && /^[a-z0-9][a-z0-9.-]{0,79}$/.test(v);
|
||||
export const pluginRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
export type PluginScope = "server" | "instance";
|
||||
export type 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[];
|
||||
apiVersion: 2; id: string; name: string; version: string; author: string; license: string; description: string;
|
||||
scopes: PluginScope[]; client: { entry: string }; server?: { entry: string };
|
||||
}
|
||||
/** 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 PluginFile { encoding: "utf8" | "base64"; data: string }
|
||||
export interface PluginPackage { manifest: PluginManifest; files: Record<string, PluginFile> }
|
||||
export interface PluginSettings { enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
|
||||
export interface PluginSettingsInput {
|
||||
enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
|
||||
serverConfigAction?: "keep" | "replace" | "remove"; serverConfig?: JsonValue;
|
||||
}
|
||||
export interface PluginRuntimeStatus { state: "disabled" | "client" | "stopped" | "starting" | "running" | "failed"; error?: string }
|
||||
export interface InstalledPlugin { manifest: PluginManifest; settings: PluginSettings; revision: string; installedAt: number; runtime?: PluginRuntimeStatus }
|
||||
export interface PluginStoreEntry { id: string; repository: string; metadataPath: string; manifest: PluginManifest | null; revision: string; error: string | null }
|
||||
export interface PluginCatalog { repository: string; entries: PluginStoreEntry[] }
|
||||
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"; }
|
||||
/** Public context, never a TS private identity, voice socket or administrator credential. */
|
||||
export interface PluginParticipant {
|
||||
id: string; nickname: string; uid?: string; target: string; channelId: string;
|
||||
members: { id: number; nickname: string; uid?: string }[];
|
||||
}
|
||||
export function pluginAssert(value: unknown, code = "PLUGIN_INVALID"): asserts value {
|
||||
if (!value) throw new PluginError(code);
|
||||
export interface PluginRequestContext {
|
||||
apiVersion: 2; appId: string; self: { id: string; nickname: string; uid?: string };
|
||||
connection: { target: string; channelId: string };
|
||||
scope: { type: PluginScope; key: string };
|
||||
}
|
||||
export 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 interface PluginAppContext extends PluginRequestContext {
|
||||
plugin: PluginManifest;
|
||||
connection: PluginRequestContext["connection"] & { members: PluginParticipant["members"] };
|
||||
config: JsonValue;
|
||||
theme: "light" | "dark"; language: "zh" | "en" | "de" | "ru" | "ja";
|
||||
serverUrl: string | null; socketUrl: string | null; contextUrl: string;
|
||||
}
|
||||
export 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");
|
||||
export interface PluginAppLaunch { id: string; url: string; manifest: PluginManifest }
|
||||
export interface PluginRuntimeSettings { publicOrigin: string; port: number; available: boolean; revision: string }
|
||||
export class PluginError extends Error { constructor(readonly code: string) { super(code); this.name = "PluginError"; } }
|
||||
export function pluginAssert(v: unknown, code = "PLUGIN_INVALID"): asserts v { if (!v) throw new PluginError(code); }
|
||||
export function pluginPath(v: unknown): v is string {
|
||||
return typeof v === "string" && v.length > 0 && v.length <= 500 && v.split("/").every(s =>
|
||||
/^[A-Za-z0-9._@+~-]+$/.test(s) && s !== "." && s !== ".." && !s.endsWith(".") && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(s));
|
||||
}
|
||||
export function parsePluginManifest(v: unknown): PluginManifest {
|
||||
pluginAssert(pluginRecord(v)); pluginAssert(v.apiVersion === PLUGIN_API_VERSION, "PLUGIN_API_UNSUPPORTED"); pluginAssert(pluginId(v.id));
|
||||
for (const [key,max] of [["name",80],["author",80],["license",80],["description",400],["version",32]] as const)
|
||||
pluginAssert(typeof v[key] === "string" && v[key].trim().length > 0 && v[key].length <= max && !/[\u0000-\u001f\u007f]/.test(v[key]));
|
||||
pluginAssert(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(v.version as string));
|
||||
pluginAssert(Array.isArray(v.scopes) && v.scopes.length > 0 && v.scopes.length <= 2 && new Set(v.scopes).size === v.scopes.length && v.scopes.every(s => s === "server" || s === "instance"));
|
||||
pluginAssert(v.permissions === undefined, "PLUGIN_API_UNSUPPORTED");
|
||||
pluginAssert(pluginRecord(v.client) && pluginPath(v.client.entry) && v.client.entry.startsWith("client/") && v.client.entry.endsWith(".html"));
|
||||
let server: { entry: string } | undefined;
|
||||
if (v.server !== undefined) { pluginAssert(pluginRecord(v.server) && pluginPath(v.server.entry) && v.server.entry.startsWith("server/") && /\.(?:mjs|cjs)$/.test(v.server.entry)); server = {entry:v.server.entry}; }
|
||||
return {apiVersion:2,id:v.id,name:v.name as string,version:v.version as string,author:v.author as string,license:v.license as string,description:v.description as string,scopes:[...v.scopes],client:{entry:v.client.entry},...(server?{server}:{})};
|
||||
}
|
||||
export function pluginFileSize(file: PluginFile): number {
|
||||
return file.encoding === "utf8" ? new TextEncoder().encode(file.data).length : file.data.length / 4 * 3 - (file.data.endsWith("==") ? 2 : file.data.endsWith("=") ? 1 : 0);
|
||||
}
|
||||
export function pluginFileBytes(file: PluginFile): Uint8Array { return file.encoding === "utf8" ? new TextEncoder().encode(file.data) : Uint8Array.from(atob(file.data), c => c.charCodeAt(0)); }
|
||||
export function parsePluginPackage(v: unknown): PluginPackage {
|
||||
pluginAssert(pluginRecord(v)); const manifest = parsePluginManifest(v.manifest); pluginAssert(pluginRecord(v.files)); const entries = Object.entries(v.files);
|
||||
pluginAssert(entries.length > 0 && entries.length <= 4096);
|
||||
const files: Record<string,PluginFile> = Object.create(null), names = new Set<string>(); let total = 0;
|
||||
for (const [name,file] of entries) {
|
||||
pluginAssert(pluginPath(name) && (name.startsWith("client/") || name.startsWith("server/")) && !names.has(name.toLowerCase())); names.add(name.toLowerCase());
|
||||
pluginAssert(pluginRecord(file) && (file.encoding === "utf8" || file.encoding === "base64") && typeof file.data === "string" && file.data.length <= PLUGIN_LIMIT_BYTES);
|
||||
if (file.encoding === "base64") pluginAssert(file.data.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(file.data));
|
||||
const content: PluginFile = {encoding:file.encoding,data:file.data}; const size = pluginFileSize(content);
|
||||
pluginAssert(size <= PLUGIN_FILE_LIMIT_BYTES && (total += size) <= PLUGIN_CONTENT_LIMIT_BYTES,"PLUGIN_TOO_LARGE"); files[name] = content;
|
||||
}
|
||||
for (const name of names) for (let i=name.indexOf("/");i>=0;i=name.indexOf("/",i+1)) pluginAssert(!names.has(name.slice(0,i)));
|
||||
pluginAssert(files[manifest.client.entry]?.encoding === "utf8"); if (manifest.server) pluginAssert(files[manifest.server.entry]?.encoding === "utf8");
|
||||
const result = {manifest,files}; pluginAssert(new TextEncoder().encode(JSON.stringify(result)).length <= PLUGIN_LIMIT_BYTES,"PLUGIN_TOO_LARGE"); return result;
|
||||
}
|
||||
export function parsePluginJson(v: unknown, maxBytes = 64 * 1024): JsonValue {
|
||||
let count = 0;
|
||||
function visit(item: unknown, depth: number): void {
|
||||
pluginAssert(depth <= 64 && ++count <= 100000);
|
||||
if (item === null || typeof item === "boolean" || typeof item === "string") return;
|
||||
if (typeof item === "number") { pluginAssert(Number.isFinite(item)); return; }
|
||||
pluginAssert(Array.isArray(item) || pluginRecord(item));
|
||||
if (Array.isArray(item)) item.forEach(child=>visit(child,depth+1));
|
||||
else for (const [key,child] of Object.entries(item)) { pluginAssert(!["__proto__","prototype","constructor"].includes(key)); visit(child,depth+1); }
|
||||
}
|
||||
visit(v,0); const json=JSON.stringify(v); pluginAssert(new TextEncoder().encode(json).length <= maxBytes,"PLUGIN_TOO_LARGE"); return JSON.parse(json) as JsonValue;
|
||||
}
|
||||
export function readInstalledPlugin(v: unknown): InstalledPlugin {
|
||||
pluginAssert(pluginRecord(v) && pluginRecord(v.settings) && typeof v.revision === "string" && /^[a-f0-9]{64}$/.test(v.revision) && typeof v.installedAt === "number" && Number.isFinite(v.installedAt));
|
||||
const manifest=parsePluginManifest(v.manifest),s=v.settings;
|
||||
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
|
||||
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
|
||||
if(v.runtime!==undefined){pluginAssert(pluginRecord(v.runtime) && ["disabled","client","stopped","starting","running","failed"].includes(String(v.runtime.state)) && (v.runtime.error===undefined||typeof v.runtime.error==="string"));result.runtime={state:v.runtime.state as PluginRuntimeStatus["state"],...(v.runtime.error?{error:v.runtime.error as string}:{})};}
|
||||
return result;
|
||||
}
|
||||
export 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) };
|
||||
runtime(v:unknown):{runtime:PluginRuntimeSettings}{
|
||||
pluginAssert(pluginRecord(v)&&pluginRecord(v.runtime));const r=v.runtime;
|
||||
pluginAssert(typeof r.publicOrigin==='string'&&r.publicOrigin.length<=300&&typeof r.available==='boolean'&&typeof r.port==='number'&&Number.isInteger(r.port)&&r.port>=0&&r.port<=65535&&typeof r.revision==='string'&&/^[a-f0-9]{64}$/.test(r.revision));
|
||||
return {runtime:{publicOrigin:r.publicOrigin,port:r.port,available:r.available,revision:r.revision}};
|
||||
},
|
||||
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 };
|
||||
installed(v: unknown): {plugins:InstalledPlugin[]} {pluginAssert(pluginRecord(v)&&Array.isArray(v.plugins)&&v.plugins.length<=50);return {plugins:v.plugins.map(readInstalledPlugin)};},
|
||||
saved(v: unknown): {plugin:InstalledPlugin} {pluginAssert(pluginRecord(v));return {plugin:readInstalledPlugin(v.plugin)};},
|
||||
catalog(v: unknown): PluginCatalog {
|
||||
pluginAssert(pluginRecord(v)&&v.repository===PLUGIN_STORE_REPOSITORY&&Array.isArray(v.entries)&&v.entries.length<=50);
|
||||
const entries=v.entries.map(e=>{pluginAssert(pluginRecord(e)&&pluginId(e.id)&&typeof e.repository==="string"&&/^https:\/\/github\.com\/[a-zA-Z0-9-]+\/[a-zA-Z0-9_.-]+$/.test(e.repository)&&typeof e.metadataPath==="string"&&typeof e.revision==="string"&&(e.error===null||typeof e.error==="string"));return {id:e.id,repository:e.repository,metadataPath:e.metadataPath,revision:e.revision,error:e.error,manifest:e.manifest===null?null:parsePluginManifest(e.manifest)};});return {repository:v.repository,entries};
|
||||
},
|
||||
};
|
||||
@@ -12,7 +12,7 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
|
||||
|
||||
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
|
||||
export type ServerMessage =
|
||||
| Message<"connected", { tsClientId: number; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
|
||||
| Message<"memberEnter", ChannelMember>
|
||||
| Message<"memberLeave", { id: number }>
|
||||
@@ -135,7 +135,7 @@ export function parseScreenShareStream(value: unknown): ScreenShareStreamDescrip
|
||||
}
|
||||
|
||||
const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> = {
|
||||
connected: m => clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
|
||||
connected: m => optional(m.pluginSession, v => text(v) && /^[A-Za-z0-9_-]{43}$/.test(v)) && clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
|
||||
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
|
||||
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
|
||||
serverInfo: m => text(m.name) && m.name.length <= 256
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<dialog ref="dialog" class="ws-instance-authorization" @cancel.prevent="cancel" @close="authorizationRequested = false">
|
||||
<form @submit.prevent="save">
|
||||
<div class="ws-authorization-mark" aria-hidden="true">◈</div>
|
||||
<h2>{{ copy.title }}</h2>
|
||||
<p>{{ copy.description }}</p>
|
||||
<p>{{ copy.alternative }}</p>
|
||||
<label><input v-model="checked" type="checkbox" /><span>{{ copy.choice }}</span></label>
|
||||
<footer>
|
||||
<button type="button" @click="decline">{{ copy.decline }}</button>
|
||||
<button class="ws-authorization-primary" type="submit" :disabled="firstVisit && !checked">{{ firstVisit ? copy.accept : copy.save }}</button>
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
const props = defineProps<{ language: SiteLanguage }>();
|
||||
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
|
||||
const copy = computed(() => instanceAuthorizationCopy[props.language]);
|
||||
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
|
||||
watch([dialog, authorizationRequested, authorizationDecision], () => {
|
||||
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
|
||||
firstVisit.value = authorizationDecision.value === null;
|
||||
checked.value = authorizationDecision.value === true;
|
||||
dialog.value.showModal();
|
||||
}, { flush: 'post' });
|
||||
function finish() { authorizationRequested.value = false; dialog.value?.close(); }
|
||||
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
|
||||
function decline() { setInstanceAuthorization(false); finish(); }
|
||||
function cancel() { if (firstVisit.value) decline(); else finish(); }
|
||||
onBeforeUnmount(() => dialog.value?.close());
|
||||
</script>
|
||||
<style>
|
||||
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:14px/1.75 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto}
|
||||
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
|
||||
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
|
||||
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
|
||||
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
|
||||
</style>
|
||||
@@ -1,111 +1,163 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<button v-if="connected" class="ws-plugin-launcher" type="button" @click="show">◈ {{ tr('title') }}</button>
|
||||
<dialog ref="dialog" class="ws-plugin-dialog" :data-plugin-theme="theme" @close="closed" @cancel="closed">
|
||||
<header><strong>{{ current?.manifest.name ?? tr('title') }}</strong><button type="button" @click="dialog?.close()">{{ tr('close') }}</button></header>
|
||||
<p v-if="error" role="alert" class="ws-plugin-error">{{ error }}</p>
|
||||
<template v-if="!current">
|
||||
<div class="ws-plugin-toolbar"><button type="button" :disabled="busy" @click="refresh">{{ busy ? tr('loading') : tr('refresh') }}</button></div>
|
||||
<p>{{ tr('enableNote') }}</p><p v-if="!busy && !available.length">{{ tr('empty') }}</p>
|
||||
<section v-for="entry in available" :key="entry.manifest.id" class="ws-plugin-entry">
|
||||
<div><strong>{{ entry.manifest.name }}</strong><small>{{ entry.scope === 'server' ? tr('server') : tr('instance') }} · {{ entry.manifest.version }}</small><p>{{ entry.manifest.description }}</p></div>
|
||||
<button type="button" :disabled="busy" @click="launch(entry.manifest.id)">{{ tr('open') }}</button>
|
||||
</section>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="ws-plugin-toolbar"><button type="button" @click="stop">← {{ tr('back') }}</button><small>{{ tr('permission') }}: {{ current.manifest.permissions.join(', ') }}</small></div>
|
||||
<iframe ref="frame" :key="channel" :title="current.manifest.name" :srcdoc="documentSource" sandbox="allow-scripts" allow="fullscreen" referrerpolicy="no-referrer" @load="sendContext"></iframe>
|
||||
</template>
|
||||
</dialog>
|
||||
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
|
||||
<button ref="launcher" class="ws-plugin-launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
|
||||
<span>{{ tr('title') }}</span><i v-if="current" />
|
||||
</button>
|
||||
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
|
||||
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
|
||||
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
|
||||
<div class="ws-plugin-window-title"><strong>{{ current && appView ? current.manifest.name : tr('title') }}</strong><small>WebSpeak</small></div>
|
||||
<div class="ws-plugin-window-controls" @pointerdown.stop @dblclick.stop>
|
||||
<button type="button" :title="ui.minimize" :aria-label="ui.minimize" @click="minimize"><svg viewBox="0 0 24 24"><path d="M5 17h14" /></svg></button>
|
||||
<button type="button" :title="maximized ? ui.restore : ui.maximize" :aria-label="maximized ? ui.restore : ui.maximize" @click="toggleMaximize"><svg viewBox="0 0 24 24"><path :d="maximized ? 'M8 4h12v12M4 8h12v12H4z' : 'M5 5h14v14H5z'" /></svg></button>
|
||||
<button class="ws-plugin-close" type="button" :title="tr('close')" :aria-label="tr('close')" @click="close"><svg viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" /></svg></button>
|
||||
</div>
|
||||
</header>
|
||||
<nav class="ws-plugin-navigation" :aria-label="tr('title')">
|
||||
<button type="button" :class="{ active: !appView }" @click="appView = false">{{ ui.workspace }}</button>
|
||||
<button v-if="current" type="button" :class="{ active: appView }" @click="appView = true">{{ current.manifest.name }}</button>
|
||||
<span v-if="current && appView" class="ws-plugin-version">v{{ current.manifest.version }}</span>
|
||||
</nav>
|
||||
<p v-if="error" role="alert" class="ws-plugin-error">{{ error }}</p>
|
||||
<div v-show="!appView" class="ws-plugin-library">
|
||||
<div class="ws-plugin-library-heading"><div><h2>{{ tr('title') }}</h2><span>{{ available.length }} {{ ui.count }}</span></div><button type="button" :disabled="busy" @click="refresh">{{ busy ? tr('loading') : tr('refresh') }}</button></div>
|
||||
<input v-model="search" class="ws-plugin-search" type="search" :placeholder="ui.search" :aria-label="ui.search" />
|
||||
<p v-if="!busy && !filtered.length" class="ws-plugin-empty">{{ available.length ? ui.noResults : tr('empty') }}</p>
|
||||
<div class="ws-plugin-grid">
|
||||
<article v-for="entry in filtered" :key="entry.manifest.id" class="ws-plugin-entry">
|
||||
<div class="ws-plugin-app-mark" aria-hidden="true">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</div>
|
||||
<div class="ws-plugin-entry-copy"><h3>{{ entry.manifest.name }}</h3><small>v{{ entry.manifest.version }} · {{ entry.scope === 'server' ? tr('server') : tr('instance') }}</small><p>{{ entry.manifest.description }}</p></div>
|
||||
<p v-if="entry.runtime.state === 'failed'" class="ws-plugin-entry-error">{{ entry.runtime.error }}</p>
|
||||
<button type="button" :disabled="busy || entry.runtime.state === 'failed'" @click="launch(entry.manifest.id)">{{ tr('open') }} <span aria-hidden="true">↗</span></button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="appView && current" class="ws-plugin-browser">
|
||||
<iframe v-if="current" ref="frame" :key="current.id" :title="current.manifest.name" :src="current.url" :allow="browserFeatures" referrerpolicy="no-referrer"></iframe>
|
||||
</div>
|
||||
<div v-if="dragging" class="ws-plugin-drag-shield" />
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
|
||||
import { parsePluginPackage, pluginRecord, parsePluginJson, type PluginManifest, type PluginScope, type PluginRoomSnapshot } from '../../../src/shared/plugins.js';
|
||||
import { pluginFrameDocument } from '../services/plugin-frame.js';
|
||||
import type { PluginTransport } from '../services/plugin-transport.js';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
|
||||
import { createPluginAppClient, type AvailablePluginApp, type PluginAppClient } from '../services/plugin-app-client.js';
|
||||
import { type PluginAppLaunch, pluginRecord } from '../../../src/shared/plugins.js';
|
||||
import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
|
||||
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
const props = defineProps<{ transport: PluginTransport; connected: boolean; language: SiteLanguage }>();
|
||||
import { thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage }>();
|
||||
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
|
||||
const dialog = ref<HTMLDialogElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
|
||||
const available = shallowRef<{ manifest: PluginManifest; scope: PluginScope }[]>([]);
|
||||
const current = shallowRef<ReturnType<typeof parsePluginPackage> | null>(null);
|
||||
const documentSource = ref(''), channel = ref(''), theme = ref<'light'|'dark'>('light');
|
||||
const busy = ref(false), error = ref(''); let epoch = 0, openingId: string | undefined, context: Record<string,unknown> = {}, observer: MutationObserver | undefined;
|
||||
const inFlight = new Set<number>();
|
||||
const pluginId = computed(() => current.value?.manifest.id);
|
||||
const ui = computed(() => pluginWindowTranslations[props.language]);
|
||||
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
|
||||
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
|
||||
const busy = ref(false), error = ref(''), theme = ref<'light' | 'dark'>('light');
|
||||
const visible = ref(false), maximized = ref(false), appView = ref(false), dragging = ref(false), search = ref('');
|
||||
const position = ref<Record<string, string>>({});
|
||||
const launcherPosition = ref<Record<string, string>>({});
|
||||
const filtered = computed(() => available.value.filter(entry => `${entry.manifest.name} ${entry.manifest.description}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())));
|
||||
let epoch = 0, pending: AbortController | undefined, opening: { client: PluginAppClient; key: string } | undefined, observer: MutationObserver | undefined;
|
||||
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; kind: 'window' | 'launcher'; moved: boolean } | undefined;
|
||||
let suppressLauncherClick = false, resizeObserver: ResizeObserver | undefined;
|
||||
const browserFeatures = computed(() => {
|
||||
const policy = (document as Document & { featurePolicy?: { features(): string[] } }).featurePolicy;
|
||||
const features = policy?.features() ?? ['fullscreen', 'autoplay', 'camera', 'microphone', 'display-capture', 'clipboard-read', 'clipboard-write', 'geolocation', 'screen-wake-lock'];
|
||||
return features.filter(feature => /^[a-z0-9-]+$/.test(feature)).map(feature => feature + ' *').join('; ');
|
||||
});
|
||||
function detectTheme() {
|
||||
const root = document.querySelector('.ws-skin-root');
|
||||
const color = root ? getComputedStyle(root).color.match(/[\d.]+/g)?.map(Number) : null;
|
||||
theme.value = color && color.length >= 3 ? (color[0]*.2126+color[1]*.7152+color[2]*.0722 > 140 ? 'dark':'light') : matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
|
||||
const style = getComputedStyle(root ?? document.documentElement);
|
||||
if (style.colorScheme === 'dark' || style.colorScheme === 'light') { theme.value = style.colorScheme; return; }
|
||||
const color = root ? style.color.match(/[\d.]+/g)?.map(Number) : null;
|
||||
theme.value = color && color.length >= 3 ? (color[0] * .2126 + color[1] * .7152 + color[2] * .0722 > 140 ? 'dark' : 'light') : matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
function send(value: object) { frame.value?.contentWindow?.postMessage({ channel: channel.value, ...value }, '*'); }
|
||||
function sendContext() { send({ type: 'context', context: { ...context, language: props.language, theme: theme.value } }); }
|
||||
function client() { return createPluginAppClient(props.gatewayUrl, props.sessionToken); }
|
||||
async function refresh() {
|
||||
const owner = ++epoch; busy.value = true; error.value = '';
|
||||
try {
|
||||
const result = await props.transport.request('list');
|
||||
if (owner !== epoch) return;
|
||||
if (!Array.isArray(result) || result.length > 50) throw new Error('PLUGIN_INVALID_RESPONSE');
|
||||
available.value = result.map(v => { if (!pluginRecord(v)) throw new Error('PLUGIN_INVALID_RESPONSE');
|
||||
const manifest = v.manifest; if (!pluginRecord(manifest) || typeof manifest.id !== 'string' || typeof manifest.name !== 'string' || (v.scope !== 'server' && v.scope !== 'instance')) throw new Error('PLUGIN_INVALID_RESPONSE');
|
||||
return { manifest: manifest as unknown as PluginManifest, scope: v.scope }; });
|
||||
} catch (e) { if (owner === epoch) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
finally { if (owner === epoch) busy.value = false; }
|
||||
if (!thirdPartyAllowed.value) return;
|
||||
const owner = ++epoch; pending?.abort(); const controller = new AbortController(); pending = controller; busy.value = true; error.value = '';
|
||||
try { const entries = await client().list(controller.signal); if (owner === epoch) available.value = entries; }
|
||||
catch (e) { if (owner === epoch && !controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
|
||||
}
|
||||
function show() { detectTheme(); dialog.value?.showModal(); void refresh(); }
|
||||
function toggle() {
|
||||
if (suppressLauncherClick) { suppressLauncherClick = false; return; }
|
||||
if (visible.value) { minimize(); return; }
|
||||
detectTheme(); visible.value = true;
|
||||
if (!current.value) { appView.value = false; void refresh(); }
|
||||
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
|
||||
}
|
||||
function minimize() { endDrag(); visible.value = false; launcher.value?.focus(); }
|
||||
function close() { stop(); error.value = ''; available.value = []; search.value = ''; minimize(); }
|
||||
function stop() {
|
||||
const id = pluginId.value ?? openingId; ++epoch; openingId = undefined; inFlight.clear(); current.value = null; documentSource.value = ''; context = {}; channel.value = ''; busy.value = false;
|
||||
if (id) void props.transport.request('close', { pluginId: id }).catch(() => undefined);
|
||||
++epoch; pending?.abort(); pending = undefined; const old = opening; opening = undefined; current.value = null; appView.value = false; busy.value = false;
|
||||
if (old) void old.client.cancelOpen(old.key).catch(() => undefined);
|
||||
}
|
||||
function closed() { stop(); error.value = ''; available.value = []; }
|
||||
async function launch(id: string) {
|
||||
const owner = ++epoch; openingId = id; busy.value = true; error.value = '';
|
||||
if (!thirdPartyAllowed.value) return;
|
||||
if (current.value?.manifest.id === id) { appView.value = true; return; }
|
||||
stop(); const owner = ++epoch, controller = new AbortController(), service = client(), key = crypto.randomUUID(); pending = controller; opening = { client: service, key }; busy.value = true; error.value = '';
|
||||
try {
|
||||
const result = await props.transport.request('open', { pluginId: id });
|
||||
// stop() queues the close after this open on the same ordered socket.
|
||||
// A late response must never close a newer opening of the same plugin.
|
||||
const app = await service.open(id, { openId: key, theme: theme.value, language: props.language }, controller.signal);
|
||||
if (owner !== epoch) return;
|
||||
if (!pluginRecord(result) || !pluginRecord(result.snapshot)) throw new Error('PLUGIN_INVALID_RESPONSE');
|
||||
const pack = parsePluginPackage(result.package);
|
||||
if (pack.manifest.id !== id) throw new Error('PLUGIN_INVALID_RESPONSE');
|
||||
current.value = pack; context = { config: result.config, self: result.self, scope: result.scope, snapshot: result.snapshot };
|
||||
channel.value = crypto.randomUUID(); documentSource.value = pluginFrameDocument(pack, channel.value);
|
||||
} catch (e) { if (owner === epoch) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
finally { if (owner === epoch) { openingId = undefined; busy.value = false; } }
|
||||
if (new URL(app.url).origin === location.origin) throw new Error('PLUGIN_SEPARATE_ORIGIN_REQUIRED');
|
||||
current.value = app; appView.value = true;
|
||||
} catch (e) {
|
||||
if (owner === epoch) { const old = opening; opening = undefined; if (old) void old.client.cancelOpen(old.key).catch(() => undefined); if (!controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
|
||||
} finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
|
||||
}
|
||||
async function receive(event: MessageEvent) {
|
||||
if (!frame.value || event.source !== frame.value.contentWindow || !pluginRecord(event.data) || event.data.channel !== channel.value || !current.value) return;
|
||||
const value = event.data;
|
||||
if (value.type === 'ready') { sendContext(); return; }
|
||||
if (value.type !== 'request' || !Number.isSafeInteger(value.id) || inFlight.has(value.id as number) || inFlight.size >= 8) return;
|
||||
const id = value.id as number, owner = epoch, plugin = pluginId.value!; inFlight.add(id);
|
||||
try {
|
||||
let result: unknown;
|
||||
if (value.method === 'room.snapshot') result = await props.transport.request('snapshot', { pluginId: plugin });
|
||||
else if (value.method === 'room.update' && pluginRecord(value.args) && Number.isSafeInteger(value.args.revision)) {
|
||||
result = await props.transport.request('update', { pluginId: plugin, revision: value.args.revision as number, state: parsePluginJson(value.args.state) });
|
||||
} else throw new Error('PLUGIN_PERMISSION_DENIED');
|
||||
if (owner === epoch) send({ type: 'reply', id, result });
|
||||
} catch (e) { if (owner === epoch) send({ type: 'reply', id, error: e instanceof Error ? e.message : 'PLUGIN_FAILED' }); }
|
||||
finally { if (owner === epoch) inFlight.delete(id); }
|
||||
function message(event: MessageEvent) {
|
||||
if (!current.value || event.source !== frame.value?.contentWindow || event.origin !== new URL(current.value.url).origin || !pluginRecord(event.data)) return;
|
||||
if (event.data.type === 'webspeak-app-closed' && event.data.id === current.value.id) { stop(); error.value = tr('context'); }
|
||||
}
|
||||
const unsubscribe = props.transport.subscribe(message => {
|
||||
if (message.type === 'pluginReset') { stop(); available.value = []; dialog.value?.close(); return; }
|
||||
if (message.type !== 'pluginEvent' || message.pluginId !== pluginId.value) return;
|
||||
if (!message.snapshot) { stop(); error.value = tr('context'); return; }
|
||||
context.snapshot = message.snapshot as PluginRoomSnapshot; send({ type: 'snapshot', snapshot: message.snapshot });
|
||||
function appearance() { if (current.value && opening) void opening.client.appearance(current.value.id, theme.value, props.language).catch(() => undefined); }
|
||||
function fitWindow() {
|
||||
if (launcher.value && launcherPosition.value.left) {
|
||||
const box = launcher.value.getBoundingClientRect();
|
||||
launcherPosition.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, right: 'auto', bottom: 'auto' };
|
||||
}
|
||||
if (!visible.value || maximized.value || !windowElement.value) return;
|
||||
const box = windowElement.value.getBoundingClientRect();
|
||||
position.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, transform: 'none' };
|
||||
}
|
||||
function toggleMaximize() { endDrag(); maximized.value = !maximized.value; if (!maximized.value) void nextTick(fitWindow); }
|
||||
function startDrag(event: PointerEvent) {
|
||||
if (event.button !== 0 || maximized.value || (event.target as HTMLElement).closest('button')) return;
|
||||
const box = windowElement.value?.getBoundingClientRect(); if (!box) return;
|
||||
event.preventDefault(); const handle = event.currentTarget as HTMLElement;
|
||||
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, kind: 'window', moved: false }; dragging.value = true;
|
||||
handle.setPointerCapture(event.pointerId);
|
||||
}
|
||||
function startLauncherDrag(event: PointerEvent) {
|
||||
if (event.button !== 0 || !launcher.value) return;
|
||||
const box = launcher.value.getBoundingClientRect(); suppressLauncherClick = false;
|
||||
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle: launcher.value, kind: 'launcher', moved: false };
|
||||
launcher.value.setPointerCapture(event.pointerId);
|
||||
}
|
||||
function moveDrag(event: PointerEvent) {
|
||||
if (!drag || drag.id !== event.pointerId) return;
|
||||
const target = drag.kind === 'launcher' ? launcher.value : windowElement.value; if (!target) return;
|
||||
if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5 && !drag.moved) return;
|
||||
drag.moved = true; const box = target.getBoundingClientRect();
|
||||
const next = { left: `${Math.max(8, Math.min(drag.left + event.clientX - drag.x, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(drag.top + event.clientY - drag.y, innerHeight - box.height - 8))}px`, transform: 'none' };
|
||||
if (drag.kind === 'launcher') launcherPosition.value = { ...next, right: 'auto', bottom: 'auto' }; else position.value = next;
|
||||
}
|
||||
function endDrag() {
|
||||
const old = drag; drag = undefined; dragging.value = false;
|
||||
if (old?.kind === 'launcher' && old.moved) suppressLauncherClick = true;
|
||||
if (old?.handle.hasPointerCapture(old.id)) old.handle.releasePointerCapture(old.id);
|
||||
}
|
||||
watch(windowElement, element => { resizeObserver?.disconnect(); if (element) { resizeObserver = new ResizeObserver(fitWindow); resizeObserver.observe(element); } });
|
||||
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, close);
|
||||
watch(thirdPartyAllowed, allowed => { if (!allowed) close(); }, { flush: 'sync' });
|
||||
watch(() => props.language, appearance); watch(theme, appearance);
|
||||
onMounted(() => {
|
||||
detectTheme(); window.addEventListener('message', message); window.addEventListener('resize', fitWindow); window.addEventListener('pointermove', moveDrag); window.addEventListener('pointerup', endDrag); window.addEventListener('pointercancel', endDrag); window.addEventListener('blur', endDrag);
|
||||
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
|
||||
});
|
||||
watch(() => props.language, sendContext);
|
||||
watch(theme, sendContext);
|
||||
watch(() => props.connected, connected => { if (!connected) { closed(); dialog.value?.close(); } });
|
||||
onMounted(() => { window.addEventListener('message', receive); observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter:['data-ws-skin','data-theme'] }); });
|
||||
onBeforeUnmount(() => { unsubscribe(); stop(); observer?.disconnect(); window.removeEventListener('message', receive); dialog.value?.close(); });
|
||||
onBeforeUnmount(() => { stop(); endDrag(); observer?.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('message', message); window.removeEventListener('resize', fitWindow); window.removeEventListener('pointermove', moveDrag); window.removeEventListener('pointerup', endDrag); window.removeEventListener('pointercancel', endDrag); window.removeEventListener('blur', endDrag); });
|
||||
</script>
|
||||
<style>
|
||||
.ws-plugin-launcher{all:initial;position:fixed;right:16px;top:88px;z-index:10000;font:600 14px system-ui;cursor:pointer;background:#184b48;color:white;border:1px solid #4d827e;border-radius:24px;padding:10px 16px;box-shadow:0 4px 20px #0003}
|
||||
.ws-plugin-dialog{box-sizing:border-box;width:min(960px,calc(100vw - 24px));max-height:calc(100dvh - 32px);padding:20px;border:1px solid #b6c9c7;border-radius:16px;background:#fff;color:#182e2d;font:15px/1.5 system-ui;overflow:auto}
|
||||
.ws-plugin-dialog[data-plugin-theme="dark"]{background:#20242b;color:#ecf2f1;border-color:#4a525d}.ws-plugin-dialog::backdrop{background:#0009}.ws-plugin-dialog header,.ws-plugin-toolbar,.ws-plugin-entry{display:flex;align-items:center;gap:12px;justify-content:space-between}.ws-plugin-dialog header strong{font-size:20px}.ws-plugin-dialog button{font:inherit;cursor:pointer;border:1px solid #779c98;border-radius:8px;padding:8px 12px;background:#e5f3f0;color:#153f3b}.ws-plugin-dialog button:disabled{opacity:.5;cursor:wait}.ws-plugin-dialog iframe{display:block;width:100%;height:min(620px,68dvh);border:1px solid #779c98;border-radius:8px;background:transparent}.ws-plugin-toolbar{margin:14px 0;flex-wrap:wrap}.ws-plugin-entry{border-top:1px solid #779c9866;padding:16px 0}.ws-plugin-entry small{display:block;opacity:.7}.ws-plugin-entry p{margin:6px 0}.ws-plugin-error{color:#c73131;overflow-wrap:anywhere}
|
||||
@media(max-width:600px){.ws-plugin-launcher{top:72px;right:8px;padding:8px 12px}.ws-plugin-dialog{padding:14px}.ws-plugin-entry{align-items:start}.ws-plugin-dialog iframe{height:65dvh}}
|
||||
</style>
|
||||
<style src="../styles/plugin-overlay.css"></style>
|
||||
@@ -20,6 +20,7 @@ import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui
|
||||
import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js";
|
||||
import { createSkinPluginAssetUrlCache } from "../services/skin-plugin-asset-urls.js";
|
||||
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
|
||||
import { canUseSkin, openInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
|
||||
type Scalar = string | number | boolean;
|
||||
@@ -108,14 +109,14 @@ export default defineComponent({
|
||||
const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page));
|
||||
const pendingApproval = computed(() => {
|
||||
refresh.value;
|
||||
return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
return denied.value || !canUseSkin(props.skinId) ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
});
|
||||
const accessComponents = computed(() => pendingApproval.value.length
|
||||
? pendingApproval.value
|
||||
: matchingComponents.value.filter((component) => component.permissions.length > 0));
|
||||
const activeComponents = computed(() => {
|
||||
refresh.value;
|
||||
return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component));
|
||||
return canUseSkin(props.skinId) ? matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) : [];
|
||||
});
|
||||
const surfaceCandidate = computed(() => activeComponents.value.find((component) => component.mode === "surface") ?? null);
|
||||
const activeSurface = computed(() => surfaceSuppressed.value ? null : surfaceCandidate.value);
|
||||
@@ -220,7 +221,7 @@ export default defineComponent({
|
||||
|
||||
function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record<string, Scalar>): void {
|
||||
const definition = component.actions[actionId];
|
||||
if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
if (!definition || !canUseSkin(props.skinId) || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
const args = resolveActionArgs(definition, context, state);
|
||||
if (definition.type === "ui.setState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) {
|
||||
@@ -244,7 +245,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function dispatchRuntimeCallback(component: SkinPluginComponent, handlerId: string, eventName: string, event: Event, state: Record<string, Scalar>): void {
|
||||
if (!component.runtimeCallbacks) return;
|
||||
if (!canUseSkin(props.skinId) || !component.runtimeCallbacks) return;
|
||||
const callbackEvent: Record<string, unknown> = { componentId: component.id, handlerId, eventName };
|
||||
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) callbackEvent.key = event.key;
|
||||
const mayReadUserInput = props.extensionPermissions.includes("ui.input.read");
|
||||
@@ -419,8 +420,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function openAccessManager(): void {
|
||||
denied.value = false;
|
||||
manageOpen.value = true;
|
||||
openInstanceAuthorization();
|
||||
}
|
||||
|
||||
function closeOrDisable(): void {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-r
|
||||
import SkinPluginOutlet from "./SkinPluginOutlet.js";
|
||||
import { approveSkinRuntimePlugin, getSkinRuntimePluginApproval, revokeSkinRuntimePluginApprovals } from "../services/skin-runtime-plugin-approval.js";
|
||||
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
|
||||
import { canUseSkin, openInstanceAuthorization } from '../services/instance-authorization.js';
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
import { createSkinRuntimePluginSession } from "../services/skin-runtime-plugin-session.js";
|
||||
import { createSkinRuntimePluginWasmSandbox } from "../services/skin-runtime-plugin-wasm.js";
|
||||
@@ -63,6 +64,7 @@ function createRun(
|
||||
skinVersion,
|
||||
plugin,
|
||||
approval,
|
||||
signal: abortController.signal,
|
||||
files,
|
||||
uiInput: input,
|
||||
context,
|
||||
@@ -133,6 +135,7 @@ export default defineComponent({
|
||||
|
||||
const pagePlugins = computed(() => props.plugins?.plugins.filter((plugin) => plugin.page === props.page) ?? []);
|
||||
const approved = (plugin: SkinRuntimePlugin): SkinRuntimePluginApproval | null => {
|
||||
if (!canUseSkin(props.skinId)) return null;
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) return null;
|
||||
const memoryGrant = inMemoryApprovals.get(plugin.id);
|
||||
@@ -243,6 +246,7 @@ export default defineComponent({
|
||||
await handler(action.args);
|
||||
},
|
||||
onOutput: () => {
|
||||
if (!canUseSkin(props.skinId) || disposed || sessions.get(plugin.id) !== session) return;
|
||||
installStyle(plugin);
|
||||
outputs.value = { ...outputs.value, [plugin.id]: session.output };
|
||||
digestErrors.value = { ...digestErrors.value, [plugin.id]: "" };
|
||||
@@ -257,6 +261,7 @@ export default defineComponent({
|
||||
|
||||
function reconcile(): void {
|
||||
if (disposed) return;
|
||||
if (!canUseSkin(props.skinId)) { stopAll('instance-authorization-revoked'); return; }
|
||||
const currentIds = new Set(pagePlugins.value.map((plugin) => plugin.id));
|
||||
for (const pluginId of [...sessions.keys()]) if (!currentIds.has(pluginId)) stopPlugin(pluginId, "page-changed");
|
||||
for (const plugin of pagePlugins.value) {
|
||||
@@ -266,6 +271,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function approvePending(): void {
|
||||
if (!canUseSkin(props.skinId)) return;
|
||||
for (const plugin of pending.value) {
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) continue;
|
||||
@@ -294,7 +300,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
function openManager(): void {
|
||||
managerOpen.value = true;
|
||||
openInstanceAuthorization();
|
||||
}
|
||||
|
||||
function dispatch(pluginId: string, value: unknown): void {
|
||||
@@ -342,6 +348,10 @@ export default defineComponent({
|
||||
}, { immediate: true });
|
||||
|
||||
watch(() => [props.page, digests.value, revision.value], reconcile, { deep: true });
|
||||
watch(() => canUseSkin(props.skinId), allowed => {
|
||||
if (!allowed) { stopAll('instance-authorization-revoked'); managerOpen.value = false; }
|
||||
else approvePending();
|
||||
}, { flush: 'sync' });
|
||||
watch(editorMode.isEnabled, (enabled) => { if (!enabled) managerOpen.value = false; });
|
||||
watch(() => props.context, () => {
|
||||
if (disposed) return;
|
||||
|
||||
@@ -35,6 +35,9 @@
|
||||
<span>{{ option.label }}</span>
|
||||
<Icon v-if="modelValue === option.value" name="check" :size="14" />
|
||||
</button>
|
||||
<button type="button" class="skin-option skin-authorization" role="option" :aria-selected="false" @click="authorization">
|
||||
<Icon name="shield" :size="16" /><span>{{ authorizationCopy.menu }}</span><small>{{ thirdPartyAllowed ? authorizationCopy.enabled : authorizationCopy.disabled }}</small>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -42,6 +45,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
import { authorizationLanguage, canUseSkin, openInstanceAuthorization, thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
|
||||
|
||||
export interface SkinOption {
|
||||
value: string;
|
||||
@@ -60,7 +65,9 @@ const emit = defineEmits<{
|
||||
change: [value: string];
|
||||
}>();
|
||||
|
||||
const options = computed(() => props.options);
|
||||
const options = computed(() => props.options.filter(option => canUseSkin(option.value)));
|
||||
const authorizationCopy = computed(() => instanceAuthorizationCopy[authorizationLanguage.value]);
|
||||
function authorization() { close(); openInstanceAuthorization(); }
|
||||
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0] ?? {
|
||||
value: props.modelValue,
|
||||
label: props.menuLabel,
|
||||
@@ -92,6 +99,8 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
|
||||
flex: 0 0 auto;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.skin-authorization{margin-top:6px;border-top:1px solid #8bdad8!important}
|
||||
.skin-authorization small{margin-left:auto;font-size:10px;opacity:.75}
|
||||
|
||||
.skin-trigger {
|
||||
display: inline-flex;
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
<template>
|
||||
<section class="page-content plugin-admin">
|
||||
<header class="plugin-hero">
|
||||
<div><span class="plugin-eyebrow"><Icon name="grid" :size="14" /> EXTENSIONS</span><h2>{{ tr('store') }}</h2><p>{{ tr('lead') }}</p><div class="plugin-metrics"><span><b>{{ model.catalog.value?.entries.length ?? '—' }}</b>{{ text('available') }}</span><i></i><span><b>{{ model.installed.value.length }}</b>{{ tr('installed') }}</span><i></i><span><b>{{ enabledCount }}</b>{{ text('active') }}</span></div></div>
|
||||
<div><span class="plugin-eyebrow"><Icon name="grid" :size="14" /> APPS</span><h2>{{ tr('store') }}</h2><p>{{ tr('lead') }}</p><div class="plugin-metrics"><span><b>{{ model.catalog.value?.entries.length ?? '—' }}</b>{{ text('available') }}</span><i></i><span><b>{{ model.installed.value.length }}</b>{{ tr('installed') }}</span><i></i><span><b>{{ enabledCount }}</b>{{ text('active') }}</span></div></div>
|
||||
<div class="plugin-hero-art" aria-hidden="true"><i></i><i></i><i></i><i></i><b>+</b></div>
|
||||
</header>
|
||||
<details class="plugin-runtime-settings"><summary><Icon name="server" :size="16" />{{ tr('runtime') }}<span class="plugin-status" :class="{active:model.runtime.value?.available}"><i></i>{{ tr(model.runtime.value?.available?'running':'stopped') }} · {{ model.runtime.value?.port ?? '—' }}</span></summary><p>{{ tr('originHelp') }}</p><form @submit.prevent="model.saveRuntime"><label>{{ tr('origin') }}<input v-model="model.origin.value" type="url" placeholder="https://apps.example.com" :disabled="model.busy.value" /></label><button class="plugin-button primary" type="submit" :disabled="model.busy.value || !model.runtime.value">{{ tr('save') }}</button></form></details>
|
||||
<div class="plugin-toolbar">
|
||||
<nav class="plugin-tabs" :aria-label="tr('store')"><button type="button" :aria-current="tab==='store'?'page':undefined" @click="tab='store'"><Icon name="compass" :size="16" />{{ text('discover') }}</button><button type="button" :aria-current="tab==='installed'?'page':undefined" @click="tab='installed'"><Icon name="grid" :size="16" />{{ tr('installed') }}<span>{{ model.installed.value.length }}</span></button></nav>
|
||||
<div class="plugin-tools"><label class="plugin-search"><Icon name="search" :size="16" /><input v-model="search" type="search" :aria-label="text('search')" :placeholder="text('search')" /></label><button class="plugin-refresh" type="button" :disabled="model.busy.value" :title="tr('refresh')" :aria-label="tr('refresh')" @click="model.load"><Icon name="refresh" :size="17" /></button></div>
|
||||
</div>
|
||||
<p v-if="model.error.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('error') }}: {{ model.error.value }}</p>
|
||||
<p v-if="tab==='store' && model.catalogError.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('catalogError') }} · {{ model.catalogError.value }}</p>
|
||||
<p v-if="notice" class="plugin-feedback" role="status"><Icon name="check" :size="17" />{{ notice }}</p>
|
||||
<div class="plugin-section-heading"><div><h3>{{ tab==='store'?text('discover'):tr('installed') }}</h3><span v-if="tab==='store'" class="plugin-source"><i></i>{{ text('source') }}</span></div><a v-if="tab==='store'" :href="PLUGIN_STORE_REPOSITORY" target="_blank" rel="noopener noreferrer"><Icon name="github" :size="16" />GitHub ↗</a><button v-else class="plugin-button" type="button" :disabled="model.busy.value" @click="fileInput?.click()"><Icon name="share" :size="15" />{{ tr('upload') }}</button></div>
|
||||
<input ref="fileInput" class="plugin-file-input" type="file" accept=".wplugin,application/json" @change="upload" />
|
||||
@@ -16,21 +18,21 @@
|
||||
<div v-if="tab==='store'" class="plugin-store-grid">
|
||||
<article v-for="entry in catalogEntries" :key="entry.id" class="plugin-market-card">
|
||||
<div class="plugin-card-visual"><div class="plugin-card-symbol"><Icon name="grid" :size="38" /></div><span>API {{ entry.manifest?.apiVersion ?? '—' }}</span><i aria-hidden="true"></i></div>
|
||||
<div class="plugin-card-body"><div class="plugin-card-title"><h4>{{ entry.manifest?.name ?? entry.id }}</h4><small>v{{ entry.manifest?.version ?? '—' }}</small></div><p class="plugin-author">{{ entry.manifest?.author }} · {{ entry.manifest?.license }}</p><p class="plugin-description">{{ entry.manifest?.description }}</p><div class="plugin-tags"><span v-for="scope in entry.manifest?.scopes" :key="scope"><Icon name="server" :size="12" />{{ tr(scope) }}</span></div><div class="plugin-permissions"><span v-for="permission in entry.manifest?.permissions" :key="permission"><Icon name="check" :size="12" />{{ text(permission==='room.read'?'read':'write') }}</span></div><p v-if="entry.error" class="is-error">{{ entry.error }}</p></div>
|
||||
<div class="plugin-card-body"><div class="plugin-card-title"><h4>{{ entry.manifest?.name ?? entry.id }}</h4><small>v{{ entry.manifest?.version ?? '—' }}</small></div><p class="plugin-author">{{ entry.manifest?.author }} · {{ entry.manifest?.license }}</p><p class="plugin-description">{{ entry.manifest?.description }}</p><div class="plugin-tags"><span v-for="scope in entry.manifest?.scopes" :key="scope"><Icon name="server" :size="12" />{{ tr(scope) }}</span></div><div class="plugin-permissions"><span>{{ tr('client') }}</span><span v-if="entry.manifest?.server">{{ tr('backend') }}</span></div><p v-if="entry.error" class="is-error">{{ entry.error }}</p></div>
|
||||
<footer><a :href="entry.repository" target="_blank" rel="noopener noreferrer" :aria-label="`${entry.manifest?.name ?? entry.id} · GitHub`"><Icon name="github" :size="16" />GitHub ↗</a><button class="plugin-button primary" type="button" :disabled="model.busy.value || !entry.manifest || !!entry.error" @click="install(entry)"><Icon name="download" :size="15" />{{ installLabel(entry) }}</button></footer>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else class="plugin-installed-list">
|
||||
<article v-for="plugin in installedEntries" :key="plugin.manifest.id" class="plugin-installed-card">
|
||||
<header><div class="plugin-installed-icon"><Icon name="grid" :size="23" /></div><div class="plugin-installed-name"><h4>{{ plugin.manifest.name }}</h4><p>v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}</p></div><span class="plugin-status" :class="{active:plugin.settings.enabled}"><i></i>{{ text(plugin.settings.enabled?'active':'inactive') }}</span></header>
|
||||
<p class="plugin-description">{{ plugin.manifest.description }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span></div>
|
||||
<header><div class="plugin-installed-icon"><Icon name="grid" :size="23" /></div><div class="plugin-installed-name"><h4>{{ plugin.manifest.name }}</h4><p>v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}</p></div><span class="plugin-status" :class="{active:plugin.settings.enabled}"><i></i>{{ tr(plugin.runtime?.state ?? 'disabled') }}</span></header>
|
||||
<p class="plugin-description">{{ plugin.manifest.description }}</p><p v-if="plugin.runtime?.error" class="is-error" role="alert">{{ plugin.runtime.error }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span></div>
|
||||
<details :open="expanded===plugin.manifest.id" @toggle="onToggle($event,plugin.manifest.id)"><summary><Icon name="settings" :size="16" />{{ text('configure') }}<Icon class="plugin-chevron" name="chevron-down" :size="15" /></summary><fieldset :disabled="model.busy.value">
|
||||
<div class="plugin-enable-row"><div><strong>{{ tr('enabled') }}</strong><p>{{ text('review') }}</p></div><label class="plugin-switch"><input v-model="model.drafts[plugin.manifest.id].enabled" type="checkbox" :aria-label="tr('enabled')" /><span></span></label></div>
|
||||
<div class="plugin-permissions"><span v-for="permission in plugin.manifest.permissions" :key="permission"><Icon name="shield" :size="13" />{{ text(permission==='room.read'?'read':'write') }}</span></div>
|
||||
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].trusted" type="checkbox" />{{ tr('trust') }}</label><p class="plugin-trust-note">{{ tr('enableNote') }}</p>
|
||||
<label>{{ tr('scope') }}<select v-model="model.drafts[plugin.manifest.id].scope"><option v-for="scope in plugin.manifest.scopes" :key="scope" :value="scope">{{ tr(scope) }}</option></select></label>
|
||||
<label v-if="model.drafts[plugin.manifest.id].scope==='server'">{{ tr('targets') }}<textarea v-model="model.drafts[plugin.manifest.id].targets" rows="3" maxlength="15000" placeholder="voice.example.com:9987"></textarea></label>
|
||||
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="8192" spellcheck="false"></textarea></label></details>
|
||||
<div class="plugin-settings-actions"><button class="plugin-button danger" type="button" @click="remove(plugin)"><Icon name="trash" :size="14" />{{ tr('remove') }}</button><button class="plugin-button primary" type="button" @click="save(plugin)"><Icon name="check" :size="15" />{{ tr('save') }}</button></div>
|
||||
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="65536" spellcheck="false"></textarea></label><template v-if="plugin.manifest.server"><label>{{ tr('privateConfig') }}<small>{{ tr(plugin.settings.hasServerConfig?'secretSaved':'secretEmpty') }}</small><select v-model="model.drafts[plugin.manifest.id].serverConfigAction"><option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option></select><textarea v-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace'" v-model="model.drafts[plugin.manifest.id].serverConfig" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" autocapitalize="off" autocorrect="off"></textarea></label></template></details>
|
||||
<div class="plugin-settings-actions"><button v-if="plugin.manifest.server" class="plugin-button" type="button" :disabled="!plugin.settings.enabled" @click="model.restart(plugin)">{{ tr('restart') }}</button><button class="plugin-button danger" type="button" @click="remove(plugin)"><Icon name="trash" :size="14" />{{ tr('remove') }}</button><button class="plugin-button primary" type="button" @click="save(plugin)"><Icon name="check" :size="15" />{{ tr('save') }}</button></div>
|
||||
</fieldset></details>
|
||||
</article>
|
||||
</div>
|
||||
@@ -80,4 +82,5 @@ section.page-content.plugin-admin{display:grid;grid-template-columns:minmax(0,1f
|
||||
.plugin-installed-card fieldset>label,.plugin-advanced label{display:grid;gap:8px;color:var(--admin-muted);font-size:11px}.plugin-installed-card textarea,.plugin-installed-card select{width:100%;min-width:0;max-width:100%;border:1px solid var(--admin-border);padding:10px 12px;border-radius:8px;background:var(--admin-field);color:var(--admin-text);font-size:12px}.plugin-installed-card textarea{resize:vertical;line-height:1.7}.plugin-advanced{border:1px solid var(--admin-border);border-radius:9px;padding:0 12px}.plugin-advanced summary{display:flex;align-items:center;justify-content:space-between;font-size:11px;color:var(--admin-muted);padding:12px 0;cursor:pointer}.plugin-advanced label{padding-bottom:12px}.plugin-advanced textarea{font-family:ui-monospace,monospace}.plugin-settings-actions{display:flex;justify-content:space-between;gap:12px;padding-top:4px}.plugin-scope-help{margin-top:8px;border-top:1px solid var(--admin-border);padding-top:20px;color:var(--admin-muted);font-size:11px}.plugin-scope-help summary{display:flex;gap:8px;align-items:center;cursor:pointer;width:fit-content}.plugin-scope-help p{line-height:1.8;margin-top:12px;max-width:850px}.plugin-empty{display:grid;justify-items:center;gap:16px;padding:60px 20px;color:var(--admin-muted);text-align:center;border:1px dashed var(--admin-border);border-radius:16px}.plugin-empty h4{font-size:14px}.plugin-admin :is(button,a,input,textarea,select,summary):focus-visible{outline:3px solid color-mix(in srgb,var(--admin-accent) 35%,transparent);outline-offset:3px}
|
||||
@media(max-width:1100px){.plugin-hero-art{width:100px;flex-basis:100px;margin-right:0}.plugin-hero{padding:26px}.plugin-tools{flex:1;justify-content:end}.plugin-search{flex:1;max-width:320px}.plugin-search input{width:100%}}
|
||||
@media(max-width:600px){.plugin-admin{gap:18px}.plugin-hero{padding:24px 20px;border-radius:16px}.plugin-hero h2{font-size:25px}.plugin-hero p{font-size:12px}.plugin-hero-art{position:absolute;width:110px;right:-28px;top:-35px;opacity:.12}.plugin-metrics{gap:12px}.plugin-metrics>span{gap:6px;font-size:10px}.plugin-metrics b{font-size:18px}.plugin-tabs,.plugin-tools{width:100%}.plugin-tabs button{flex:1;justify-content:center;padding:8px 10px}.plugin-search{max-width:none}.plugin-section-heading>div{gap:8px}.plugin-section-heading h3{font-size:14px}.plugin-source{font-size:9px}.plugin-card-body{padding:18px}.plugin-market-card{max-width:none}.plugin-installed-card>header{padding:18px 16px 12px;flex-wrap:wrap;gap:10px}.plugin-installed-icon{width:40px;height:40px}.plugin-installed-name h4{font-size:13px}.plugin-status{font-size:9px}.plugin-installed-card>.plugin-description,.plugin-installed-meta{padding-left:16px;padding-right:16px}.plugin-installed-card>details>summary{padding:14px 16px}.plugin-installed-card fieldset{padding:4px 16px 16px}.plugin-enable-row{padding:12px}}
|
||||
.plugin-runtime-settings{border:1px solid var(--admin-border);border-radius:14px;background:var(--admin-surface);padding:18px}.plugin-runtime-settings>summary{display:flex;align-items:center;gap:12px;cursor:pointer;font-weight:650}.plugin-runtime-settings>p{margin:16px 0;color:var(--admin-muted);font-size:12px;line-height:1.7}.plugin-runtime-settings form{display:flex;align-items:end;gap:14px;flex-wrap:wrap}.plugin-runtime-settings label{display:grid;flex:1;gap:8px;font-size:12px;min-width:min(100%,260px)}.plugin-runtime-settings input{width:100%;box-sizing:border-box;border:1px solid var(--admin-border);border-radius:9px;padding:10px;background:var(--admin-raised);color:var(--admin-text)}.plugin-trust{display:flex!important;align-items:start!important;gap:10px!important;font-weight:650}.plugin-trust input{width:auto!important;margin-top:3px;flex:none}.plugin-trust-note{font-size:12px;color:var(--admin-muted);line-height:1.7}.plugin-advanced label>small{color:var(--admin-muted);font-weight:400}.plugin-settings-actions{flex-wrap:wrap}
|
||||
</style>
|
||||
@@ -1,54 +1,47 @@
|
||||
import { reactive, ref, shallowRef } from "vue";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
|
||||
import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry } from "../../../src/shared/plugins.js";
|
||||
import { reactive, ref, shallowRef } from 'vue';
|
||||
import { createAdminRequests } from '../services/admin-requests.js';
|
||||
import { isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js';
|
||||
import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js';
|
||||
|
||||
export function useAdminPlugins(api: AdminApi) {
|
||||
const installed = shallowRef<InstalledPlugin[]>([]), catalog = shallowRef<PluginCatalog | null>(null);
|
||||
const busy = ref(false), error = ref(''), requests = createAdminRequests();
|
||||
const drafts = reactive<Record<string, { enabled: boolean; scope: 'server'|'instance'; targets: string; config: string }>>({});
|
||||
function apply(records: InstalledPlugin[]) {
|
||||
installed.value = records;
|
||||
for (const record of records) if (!drafts[record.manifest.id]) drafts[record.manifest.id] = {
|
||||
enabled: record.settings.enabled, scope: record.settings.scope, targets: record.settings.targets.join('\n'), config: JSON.stringify(record.settings.config, null, 2),
|
||||
};
|
||||
for (const id of Object.keys(drafts)) if (!records.some(r => r.manifest.id === id)) delete drafts[id];
|
||||
const installed=shallowRef<InstalledPlugin[]>([]),catalog=shallowRef<PluginCatalog|null>(null),runtime=shallowRef<PluginRuntimeSettings|null>(null);
|
||||
const origin=ref(''),busy=ref(false),error=ref(''),catalogError=ref(''),requests=createAdminRequests();
|
||||
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string}>>({});
|
||||
function apply(records:InstalledPlugin[]){
|
||||
installed.value=records;
|
||||
for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''};
|
||||
for(const id of Object.keys(drafts))if(!records.some(r=>r.manifest.id===id))delete drafts[id];
|
||||
}
|
||||
async function work(run: (signal: AbortSignal, current: () => boolean) => Promise<void>) {
|
||||
if (busy.value) return;
|
||||
const request = requests.begin('plugins'); busy.value = true; error.value = '';
|
||||
const timer = setTimeout(() => { if (request.isCurrent()) { error.value='PLUGIN_TIMEOUT'; requests.cancel('plugins'); busy.value=false; } }, 90_000);
|
||||
try { await run(request.signal, request.isCurrent); }
|
||||
catch (e) { if (request.isCurrent() && !isAdminRequestCancelled(e)) error.value = e instanceof Error ? e.message : 'PLUGIN_FAILED'; }
|
||||
finally { clearTimeout(timer); if (request.isCurrent()) busy.value = false; request.finish(); }
|
||||
async function work(run:(signal:AbortSignal,current:()=>boolean)=>Promise<void>){
|
||||
if(busy.value)return;const request=requests.begin('plugins');busy.value=true;error.value='';
|
||||
const timer=setTimeout(()=>{if(request.isCurrent()){error.value='PLUGIN_TIMEOUT';requests.cancel('plugins');busy.value=false;}},90_000);
|
||||
try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof Error?e.message:'PLUGIN_FAILED';}
|
||||
finally{clearTimeout(timer);if(request.isCurrent())busy.value=false;request.finish();}
|
||||
}
|
||||
function load() { return work(async (signal, current) => {
|
||||
const result = await api.plugins(signal); if (current()) apply(result.plugins);
|
||||
// Installed packages remain manageable even when GitHub is unavailable.
|
||||
const store = await api.pluginStore(signal); if (current()) catalog.value = store;
|
||||
}); }
|
||||
async function install(entry: PluginStoreEntry) {
|
||||
return work(async (signal, current) => {
|
||||
const result = await api.installPlugin({ id: entry.id, revision: entry.revision, installedRevision: installed.value.find(p => p.manifest.id === entry.id)?.revision ?? null }, signal);
|
||||
if (current()) { delete drafts[entry.id]; apply([...installed.value.filter(p => p.manifest.id !== entry.id), result.plugin]); }
|
||||
});
|
||||
}
|
||||
function save(record: InstalledPlugin) {
|
||||
return work(async (signal, current) => {
|
||||
const draft = drafts[record.manifest.id], captured = JSON.stringify(draft);
|
||||
const settings = { enabled: draft.enabled, scope: draft.scope, targets: draft.targets.split(/\r?\n/).map(t => t.trim()).filter(Boolean), config: JSON.parse(draft.config) };
|
||||
const result = await api.configurePlugin(record.manifest.id, record.revision, settings, signal);
|
||||
if (current()) { if (JSON.stringify(drafts[record.manifest.id]) === captured) delete drafts[record.manifest.id]; apply(installed.value.map(p => p.manifest.id === record.manifest.id ? result.plugin : p)); }
|
||||
});
|
||||
}
|
||||
function remove(record: InstalledPlugin) { return work(async (signal, current) => { await api.removePlugin(record.manifest.id, record.revision, signal); if (current()) apply(installed.value.filter(p => p.manifest.id !== record.manifest.id)); }); }
|
||||
function upload(file: File) { return work(async (signal, current) => {
|
||||
if (file.size > PLUGIN_LIMIT_BYTES) throw new Error('PLUGIN_TOO_LARGE');
|
||||
const pack = parsePluginPackage(JSON.parse(await file.text())); if (!current()) return;
|
||||
const result = await api.uploadPlugin(pack, installed.value.find(p => p.manifest.id === pack.manifest.id)?.revision ?? null, signal);
|
||||
if (current()) { delete drafts[pack.manifest.id]; apply([...installed.value.filter(p => p.manifest.id !== pack.manifest.id), result.plugin]); }
|
||||
}); }
|
||||
function cancelRequests() { requests.reset(); busy.value = false; }
|
||||
function reset() { cancelRequests(); installed.value = []; catalog.value = null; error.value = ''; for (const id of Object.keys(drafts)) delete drafts[id]; }
|
||||
return { installed, catalog, busy, error, drafts, load, install, save, remove, upload, cancelRequests, reset };
|
||||
function load(){return work(async(signal,current)=>{
|
||||
const records=await api.plugins(signal);if(current())apply(records.plugins);
|
||||
const settings=await api.pluginRuntime(signal);if(current()){runtime.value=settings.runtime;origin.value=settings.runtime.publicOrigin;}
|
||||
try{const store=await api.pluginStore(signal);if(current()){catalog.value=store;catalogError.value='';}}catch(e){if(current()&&!isAdminRequestCancelled(e)){catalog.value=null;catalogError.value=e instanceof Error?e.message:'PLUGIN_STORE_UNAVAILABLE';}}
|
||||
});}
|
||||
function install(entry:PluginStoreEntry){return work(async(signal,current)=>{
|
||||
const result=await api.installPlugin({id:entry.id,revision:entry.revision,installedRevision:installed.value.find(p=>p.manifest.id===entry.id)?.revision??null},signal);
|
||||
if(current()){delete drafts[entry.id];apply([...installed.value.filter(p=>p.manifest.id!==entry.id),result.plugin]);}
|
||||
});}
|
||||
function save(record:InstalledPlugin){return work(async(signal,current)=>{
|
||||
const draft=drafts[record.manifest.id],captured=JSON.stringify(draft);
|
||||
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})};
|
||||
const result=await api.configurePlugin(record.manifest.id,record.revision,settings,signal);
|
||||
if(current()){if(JSON.stringify(drafts[record.manifest.id])===captured)delete drafts[record.manifest.id];apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));}
|
||||
});}
|
||||
function restart(record:InstalledPlugin){return work(async(signal,current)=>{const result=await api.restartPlugin(record.manifest.id,record.revision,signal);if(current())apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));});}
|
||||
function saveRuntime(){return work(async(signal,current)=>{if(!runtime.value)return;const captured=origin.value,result=await api.configurePluginRuntime(captured,runtime.value.revision,signal);if(current()){runtime.value=result.runtime;if(origin.value===captured)origin.value=result.runtime.publicOrigin;}});}
|
||||
function remove(record:InstalledPlugin){return work(async(signal,current)=>{await api.removePlugin(record.manifest.id,record.revision,signal);if(current())apply(installed.value.filter(p=>p.manifest.id!==record.manifest.id));});}
|
||||
function upload(file:File){return work(async(signal,current)=>{
|
||||
if(file.size>PLUGIN_LIMIT_BYTES)throw new Error('PLUGIN_TOO_LARGE');const pack=parsePluginPackage(JSON.parse(await file.text()));if(!current())return;
|
||||
const result=await api.uploadPlugin(pack,installed.value.find(p=>p.manifest.id===pack.manifest.id)?.revision??null,signal);
|
||||
if(current()){delete drafts[pack.manifest.id];apply([...installed.value.filter(p=>p.manifest.id!==pack.manifest.id),result.plugin]);}
|
||||
});}
|
||||
function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';}}
|
||||
function reset(){cancelRequests();installed.value=[];catalog.value=null;runtime.value=null;origin.value='';error.value='';catalogError.value='';for(const id of Object.keys(drafts))delete drafts[id];}
|
||||
return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { onScopeDispose, ref, shallowRef, type Ref } from "vue";
|
||||
import { computed, onScopeDispose, ref, shallowRef, watch, type Ref } from "vue";
|
||||
import { canUseSkin, thirdPartyAllowed } from '../services/instance-authorization.js';
|
||||
import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
import { BUILTIN_SKIN_CATALOG, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
|
||||
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
|
||||
@@ -19,7 +20,8 @@ const fallbackId = () => isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUI
|
||||
/** One page owns initialization, choices and their late responses, including persistence. */
|
||||
export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
const activeSkin = options.activeSkin ?? shallowRef<InstalledSkin | null>(null);
|
||||
const stored = getStoredSkinId();
|
||||
const candidate = getStoredSkinId();
|
||||
const stored = candidate && canUseSkin(candidate) ? candidate : null;
|
||||
const activeSkinId = ref(stored ?? fallbackId());
|
||||
const skinReady = ref(Boolean(stored && builtin(stored)));
|
||||
const skinLoadError = shallowRef<{ skinId: string } | null>(null);
|
||||
@@ -37,6 +39,7 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
|
||||
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false, clearLoadError = true) {
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) id = fallbackId();
|
||||
const entry = catalogSkins.value.find(skin => skin.id === id);
|
||||
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal }));
|
||||
if (!owns(operation)) return;
|
||||
@@ -119,5 +122,19 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
await select(fallbackId());
|
||||
}
|
||||
|
||||
return { activeSkin, activeSkinId, skinReady, skinLoadError, installedSkins, catalogSkins, initialize, select, cancel, reset, switchToBuiltIn, switchToBuiltInAfterLoadError };
|
||||
watch(thirdPartyAllowed, allowed => {
|
||||
if (disposed) return;
|
||||
if (allowed) { void initialize(); return; }
|
||||
cancel();
|
||||
activeSkin.value = null;
|
||||
skinLoadError.value = null;
|
||||
clearCustomSkinStyle();
|
||||
activeSkinId.value = fallbackId();
|
||||
skinReady.value = true;
|
||||
void select(fallbackId());
|
||||
}, { flush: 'sync' });
|
||||
return { activeSkin, activeSkinId, skinReady, skinLoadError,
|
||||
installedSkins: computed(() => installedSkins.value.filter(skin => canUseSkin(skin.id))),
|
||||
catalogSkins: computed(() => catalogSkins.value.filter(skin => canUseSkin(skin.id))),
|
||||
initialize, select, cancel, reset, switchToBuiltIn, switchToBuiltInAfterLoadError };
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accom
|
||||
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
import { createVoiceConnection } from "../voice/connection.js";
|
||||
import { createVoiceCommands } from "../voice/commands.js";
|
||||
import { createPluginTransport } from "../services/plugin-transport.js";
|
||||
import { createVoiceSessionState } from "../voice/session-state.js";
|
||||
import { applySavedMemberVolumes } from "../voice/member-volume-preferences.js";
|
||||
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
|
||||
@@ -201,7 +200,7 @@ export function useVoiceWebSocket() {
|
||||
const ws = shallowRef<WebSocket | null>(null);
|
||||
const serverInfo = shallowRef<VoiceServerInfo | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
|
||||
const plugins = createPluginTransport(() => ws.value, () => state.connected);
|
||||
const pluginSession = ref("");
|
||||
const sessionState = createVoiceSessionState({
|
||||
selfId: () => state.tsClientId,
|
||||
onMemberRemoved(id) {
|
||||
@@ -1025,7 +1024,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** All ways a session ends release the same owned media and pending work. */
|
||||
function releaseSessionResources(sendScreenStop = false): void {
|
||||
plugins.reset();
|
||||
pluginSession.value = "";
|
||||
chatGeneration++;
|
||||
inputDeviceGeneration++;
|
||||
outputDeviceGeneration++;
|
||||
@@ -1046,7 +1045,6 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function handleMessage(raw: unknown): void {
|
||||
if (plugins.receive(raw)) return;
|
||||
const msg = parseServerMessage(raw);
|
||||
if (!msg || screenShare.handleMessage(msg) || sessionState.receive(msg)) return;
|
||||
switch (msg.type) {
|
||||
@@ -1069,6 +1067,7 @@ export function useVoiceWebSocket() {
|
||||
state.errorCode = "";
|
||||
state.channelSwitchedChannelId = "";
|
||||
state.tsClientId = Number(msg.tsClientId) || 0;
|
||||
pluginSession.value = msg.pluginSession ?? "";
|
||||
// The mute preference is local to the browser, while TeamSpeak shows
|
||||
// the gateway's own client_input_muted flag to other clients. Send it
|
||||
// as soon as the session is ready so a muted reconnect is visible to
|
||||
@@ -1420,7 +1419,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
return {
|
||||
plugins,
|
||||
pluginSession,
|
||||
...screenShare.api,
|
||||
ws,
|
||||
state,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { computed, reactive, ref, type Ref } from "vue";
|
||||
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { APP_VERSION } from "../services/app-version.js";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
|
||||
interface RelayOption {
|
||||
@@ -28,7 +29,7 @@ export function useWebClientPublicConfig({
|
||||
const initialized = ref(false);
|
||||
const mobileMode = ref(false);
|
||||
const siteName = ref("WebSpeak");
|
||||
const appVersion = ref("0.2.7");
|
||||
const appVersion = ref(APP_VERSION);
|
||||
const visitorNumber = ref<number | null>(null);
|
||||
const visitorTotal = ref<number | null>(null);
|
||||
const accelerationRelays = ref<RelayOption[]>([]);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
const en = {
|
||||
menu: 'Authorization', title: 'Skins & plugins',
|
||||
description: 'To provide customization and plugin features, third-party skins and plugins supplied by this WebSpeak instance may access information displayed in your channels, such as member names, channel details and chat messages. Connection credentials are excluded. Each WebSpeak instance is maintained by its own service provider.',
|
||||
choice: 'I allow this instance’s third-party skins and plugins to use this information.',
|
||||
alternative: 'If you decline, you can still use the three official skins: Day, Night and ILLUSIA. Other skins (including KAAK) and plugins will be hidden. You can change this choice in the skin menu at any time.',
|
||||
accept: 'Agree and continue', decline: 'Use official skins only', save: 'Save', enabled: 'On', disabled: 'Off',
|
||||
};
|
||||
export const instanceAuthorizationCopy: Record<SiteLanguage, typeof en> = {
|
||||
en,
|
||||
zh: { menu: '授权', title: '皮肤与插件授权', description: '为了正常提供美化与插件功能,当前 WebSpeak 实例提供的第三方皮肤及插件可能需要读取频道中显示的信息,例如成员昵称、频道信息和聊天内容,不包括连接凭据。每个 WebSpeak 实例由各自的服务提供者维护。', choice: '我同意当前实例提供的第三方皮肤与插件使用上述信息。', alternative: '若不同意,仍可使用日间、夜间、ILLUSIA 三款官方皮肤;其他皮肤(包括 KAAK)及插件将被隐藏。你可以随时在皮肤菜单的“授权”中更改选择。', accept: '同意并继续', decline: '仅使用官方皮肤', save: '保存', enabled: '已开启', disabled: '已关闭' },
|
||||
de: { menu: 'Berechtigung', title: 'Designs & Plugins', description: 'Designs und Plugins von Drittanbietern dieser WebSpeak-Instanz können für ihre Funktionen auf angezeigte Kanalinformationen zugreifen, etwa Mitgliedsnamen, Kanaldetails und Chatnachrichten. Verbindungszugangsdaten sind ausgeschlossen. Jede Instanz wird von ihrem eigenen Dienstanbieter betrieben.', choice: 'Ich erlaube den Designs und Plugins dieser Instanz die Nutzung dieser Informationen.', alternative: 'Ohne Zustimmung bleiben die drei offiziellen Designs Tag, Nacht und ILLUSIA verfügbar. Andere Designs (einschließlich KAAK) und Plugins werden ausgeblendet. Die Auswahl lässt sich jederzeit im Designmenü ändern.', accept: 'Zustimmen und fortfahren', decline: 'Nur offizielle Designs', save: 'Speichern', enabled: 'An', disabled: 'Aus' },
|
||||
ru: { menu: 'Разрешение', title: 'Темы и плагины', description: 'Сторонние темы и плагины этого экземпляра WebSpeak могут использовать сведения, отображаемые в каналах: имена участников, данные каналов и сообщения чата. Учётные данные подключения исключены. Каждый экземпляр обслуживает собственный поставщик услуг.', choice: 'Я разрешаю сторонним темам и плагинам этого экземпляра использовать эти сведения.', alternative: 'Без согласия доступны три официальные темы: дневная, ночная и ILLUSIA. Другие темы (включая KAAK) и плагины будут скрыты. Выбор можно изменить в меню тем.', accept: 'Разрешить и продолжить', decline: 'Только официальные темы', save: 'Сохранить', enabled: 'Включено', disabled: 'Выключено' },
|
||||
ja: { menu: '許可', title: 'スキンとプラグイン', description: 'この WebSpeak インスタンスが提供するサードパーティ製スキンとプラグインは、機能の提供のためにメンバー名、チャンネル情報、チャットなどの表示情報を利用する場合があります。接続用の認証情報は含まれません。各インスタンスはそれぞれのサービス提供者が管理しています。', choice: 'このインスタンスのスキンとプラグインによる上記情報の利用に同意します。', alternative: '同意しない場合も、公式の昼・夜・ILLUSIA の3つのスキンを使用できます。その他のスキン(KAAK を含む)とプラグインは非表示になります。スキンメニューからいつでも変更できます。', accept: '同意して続ける', decline: '公式スキンのみ使用', save: '保存', enabled: '有効', disabled: '無効' },
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
const en={available:'Available plugins',discover:'Discover',search:'Search plugins or authors',active:'Enabled',inactive:'Disabled',configure:'Configure plugin',advanced:'Advanced configuration',add:'Install plugin',update:'Update',reinstall:'Reinstall',empty:'No matching plugins',read:'Read shared room',write:'Update shared room',review:'Review permissions before enabling',installedNotice:'Installed. Review settings and enable the plugin.',source:'Distributed through GitHub',scopeHelp:'About plugin scopes'};
|
||||
const en={available:'Available plugins',discover:'Discover',search:'Search plugins or authors',active:'Enabled',inactive:'Disabled',configure:'Configure plugin',advanced:'Advanced configuration',add:'Install plugin',update:'Update',reinstall:'Reinstall',empty:'No matching plugins',review:'Review the source and dependencies before enabling',installedNotice:'Installed. Review settings and enable the plugin.',source:'Distributed through GitHub',scopeHelp:'About plugin scopes'};
|
||||
export type PluginStoreTextKey=keyof typeof en;
|
||||
export const pluginStoreTranslations:Record<SiteLanguage,Record<PluginStoreTextKey,string>>={
|
||||
en,
|
||||
zh:{available:'可用插件',discover:'发现插件',search:'搜索插件名称或作者',active:'已启用',inactive:'未启用',configure:'配置插件',advanced:'高级配置',add:'安装插件',update:'更新插件',reinstall:'重新安装',empty:'没有找到匹配的插件',read:'读取共享房间',write:'更新共享房间',review:'启用前请检查插件权限',installedNotice:'安装成功,请检查设置后启用插件。',source:'通过 GitHub 分发',scopeHelp:'了解插件作用域'},
|
||||
de:{available:'Verfügbare Plugins',discover:'Entdecken',search:'Plugins oder Autoren suchen',active:'Aktiviert',inactive:'Deaktiviert',configure:'Plugin konfigurieren',advanced:'Erweiterte Konfiguration',add:'Plugin installieren',update:'Aktualisieren',reinstall:'Neu installieren',empty:'Keine passenden Plugins',read:'Gemeinsamen Raum lesen',write:'Gemeinsamen Raum ändern',review:'Berechtigungen vor dem Aktivieren prüfen',installedNotice:'Installiert. Einstellungen prüfen und Plugin aktivieren.',source:'Verteilung über GitHub',scopeHelp:'Geltungsbereiche verstehen'},
|
||||
ru:{available:'Доступные плагины',discover:'Обзор',search:'Поиск плагинов или авторов',active:'Включён',inactive:'Выключен',configure:'Настроить плагин',advanced:'Дополнительные настройки',add:'Установить плагин',update:'Обновить',reinstall:'Переустановить',empty:'Подходящих плагинов нет',read:'Чтение общей комнаты',write:'Изменение общей комнаты',review:'Проверьте разрешения перед включением',installedNotice:'Установлено. Проверьте настройки и включите плагин.',source:'Распространение через GitHub',scopeHelp:'Области действия плагинов'},
|
||||
ja:{available:'利用可能',discover:'見つける',search:'プラグイン名・作者を検索',active:'有効',inactive:'無効',configure:'プラグイン設定',advanced:'詳細設定',add:'インストール',update:'更新',reinstall:'再インストール',empty:'一致するプラグインがありません',read:'共有ルームの読み取り',write:'共有ルームの更新',review:'有効化する前に権限を確認してください',installedNotice:'インストールしました。設定を確認して有効にしてください。',source:'GitHub で配布',scopeHelp:'スコープについて'},
|
||||
zh:{available:'可用插件',discover:'发现插件',search:'搜索插件名称或作者',active:'已启用',inactive:'未启用',configure:'配置插件',advanced:'高级配置',add:'安装插件',update:'更新插件',reinstall:'重新安装',empty:'没有找到匹配的插件',review:'启用前请审核源码和依赖',installedNotice:'安装成功,请检查设置后启用插件。',source:'通过 GitHub 分发',scopeHelp:'了解插件作用域'},
|
||||
de:{available:'Verfügbare Plugins',discover:'Entdecken',search:'Plugins oder Autoren suchen',active:'Aktiviert',inactive:'Deaktiviert',configure:'Plugin konfigurieren',advanced:'Erweiterte Konfiguration',add:'Plugin installieren',update:'Aktualisieren',reinstall:'Neu installieren',empty:'Keine passenden Plugins',review:'Quellcode und Abhängigkeiten vor der Aktivierung prüfen',installedNotice:'Installiert. Einstellungen prüfen und Plugin aktivieren.',source:'Verteilung über GitHub',scopeHelp:'Geltungsbereiche verstehen'},
|
||||
ru:{available:'Доступные плагины',discover:'Обзор',search:'Поиск плагинов или авторов',active:'Включён',inactive:'Выключен',configure:'Настроить плагин',advanced:'Дополнительные настройки',add:'Установить плагин',update:'Обновить',reinstall:'Переустановить',empty:'Подходящих плагинов нет',review:'Проверьте код и зависимости перед включением',installedNotice:'Установлено. Проверьте настройки и включите плагин.',source:'Распространение через GitHub',scopeHelp:'Области действия плагинов'},
|
||||
ja:{available:'利用可能',discover:'見つける',search:'プラグイン名・作者を検索',active:'有効',inactive:'無効',configure:'プラグイン設定',advanced:'詳細設定',add:'インストール',update:'更新',reinstall:'再インストール',empty:'一致するプラグインがありません',review:'有効化する前にコードと依存関係を確認してください',installedNotice:'インストールしました。設定を確認して有効にしてください。',source:'GitHub で配布',scopeHelp:'スコープについて'},
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
|
||||
const en = { minimize: 'Minimize', maximize: 'Maximize', restore: 'Restore', search: 'Find a plugin…', resume: 'Return to app', workspace: 'Application library', count: 'available', move: 'Drag to move', noResults: 'No matching plugins' };
|
||||
export const pluginWindowTranslations: Record<SiteLanguage, typeof en> = {
|
||||
en,
|
||||
zh: { minimize: '最小化', maximize: '最大化', restore: '还原', search: '搜索插件…', resume: '返回应用', workspace: '应用库', count: '个可用', move: '拖动窗口', noResults: '没有匹配的插件' },
|
||||
de: { minimize: 'Minimieren', maximize: 'Maximieren', restore: 'Wiederherstellen', search: 'Plugin suchen…', resume: 'Zur Anwendung', workspace: 'Anwendungen', count: 'verfügbar', move: 'Zum Verschieben ziehen', noResults: 'Keine passenden Plugins' },
|
||||
ru: { minimize: 'Свернуть', maximize: 'Развернуть', restore: 'Восстановить', search: 'Найти плагин…', resume: 'Вернуться к приложению', workspace: 'Библиотека приложений', count: 'доступно', move: 'Перетащите окно', noResults: 'Плагины не найдены' },
|
||||
ja: { minimize: '最小化', maximize: '最大化', restore: '元に戻す', search: 'プラグインを検索…', resume: 'アプリに戻る', workspace: 'アプリライブラリ', count: '件利用可能', move: 'ドラッグして移動', noResults: '一致するプラグインはありません' },
|
||||
};
|
||||
+239
-11
@@ -1,17 +1,245 @@
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
const en = {
|
||||
title: "Plugins", store: "Plugin store", installed: "Installed plugins", refresh: "Refresh", install: "Install / update", upload: "Import .wplugin", remove: "Remove", save: "Save settings",
|
||||
server: "Server plugin", instance: "WebSpeak instance plugin", targets: "TS server targets (one host:port per line)", config: "Public configuration (JSON; never enter secrets)", enabled: "Enable plugin",
|
||||
lead: "Install from GitHub, review permissions, then enable. Updates are disabled until reviewed again.", empty: "No plugins available", open: "Open", close: "Close", back: "Back to plugins", permission: "Permissions", scope: "Scope", source: "Distribution repository",
|
||||
loading: "Loading…", error: "Plugin operation failed", removed: "Remove this plugin? Its active rooms will close.", context: "The connection, channel or plugin changed. Open the plugin again.",
|
||||
note: "Server plugins share a room within each channel of the configured TS server. Instance plugins share a room across all connected users on this WebSpeak gateway.",
|
||||
enableNote: "Opening a plugin runs third-party browser code in an isolated panel. Public configuration and room state are visible to participants.",
|
||||
"panelNote":"Applications reviewed and enabled by this instance’s administrator. Browser permission prompts still apply.",
|
||||
"catalogError":"The application catalog is unavailable or requires API v2. Local import remains available.",
|
||||
"title": "Plugins",
|
||||
"store": "Plugin store",
|
||||
"installed": "Installed plugins",
|
||||
"refresh": "Refresh",
|
||||
"install": "Install / update",
|
||||
"upload": "Import .wplugin",
|
||||
"remove": "Remove",
|
||||
"save": "Save settings",
|
||||
"server": "TS server scope",
|
||||
"instance": "WebSpeak instance scope",
|
||||
"targets": "Allowed TS targets (one host:port per line)",
|
||||
"config": "Public configuration (JSON; visible to users)",
|
||||
"enabled": "Enable plugin",
|
||||
"lead": "Reviewed applications with standard browser capabilities and optional Node services. Updates require renewed trust.",
|
||||
"empty": "No plugins available",
|
||||
"open": "Open",
|
||||
"close": "Close",
|
||||
"back": "Back to plugins",
|
||||
"scope": "Scope",
|
||||
"source": "Distribution repository",
|
||||
"loading": "Loading…",
|
||||
"error": "Plugin operation failed",
|
||||
"removed": "Remove this application? Open sessions will close; its backend data is retained.",
|
||||
"context": "The connection or application changed. Open it again.",
|
||||
"note": "Scope controls admission and supplies a context key. Authors implement their own collaboration and routes. Server scope follows the actual TS target and channel; instance scope spans this gateway.",
|
||||
"enableNote": "These are trusted applications on a separate origin. Node backends run with the WebSpeak service account’s OS privileges. Review the source and dependencies before enabling.",
|
||||
"runtime": "Application runtime",
|
||||
"origin": "Public runtime origin",
|
||||
"originHelp": "Use a separate HTTPS origin, such as https://apps.example.com, proxying to the runtime port. Blank enables local automatic addressing only.",
|
||||
"trust": "I have reviewed and trust this application and its dependencies",
|
||||
"privateConfig": "Private backend configuration (JSON; encrypted at rest)",
|
||||
"keep": "Keep existing secret configuration",
|
||||
"replace": "Replace secret configuration",
|
||||
"erase": "Remove secret configuration",
|
||||
"secretSaved": "Private configuration is stored",
|
||||
"secretEmpty": "No private configuration stored",
|
||||
"restart": "Restart backend",
|
||||
"client": "Browser application",
|
||||
"backend": "Node backend",
|
||||
"disabled": "Disabled",
|
||||
"stopped": "Stopped",
|
||||
"starting": "Starting",
|
||||
"running": "Running",
|
||||
"failed": "Failed"
|
||||
};
|
||||
export type PluginTextKey = keyof typeof en;
|
||||
export const pluginTranslations: Record<SiteLanguage, Record<PluginTextKey,string>> = {
|
||||
en,
|
||||
zh: { title:"插件功能",store:"插件商店",installed:"已安装插件",refresh:"刷新",install:"安装 / 更新",upload:"导入 .wplugin",remove:"移除",save:"保存设置",server:"服务器插件",instance:"WebSpeak 实例插件",targets:"TS 服务器地址(每行一个 host:port)",config:"公开配置(JSON;请勿填入任何密钥)",enabled:"启用插件",lead:"从 GitHub 安装,审查权限后启用。更新后须重新审查并启用。",empty:"暂无可用插件",open:"打开",close:"关闭",back:"返回插件列表",permission:"权限",scope:"作用域",source:"分发仓库",loading:"加载中…",error:"插件操作失败",removed:"移除此插件?正在使用的插件房间将关闭。",context:"连接、频道或插件发生变化,请重新打开插件。",note:"服务器插件在指定 TS 服务器的每个频道内共享房间;实例插件在当前 WebSpeak 网关的所有已连接用户间共享房间。",enableNote:"打开插件会在隔离面板中执行第三方浏览器代码。公开配置和房间状态对参与者可见。" },
|
||||
de: {title:"Plugins",store:"Plugin-Store",installed:"Installierte Plugins",refresh:"Aktualisieren",install:"Installieren / aktualisieren",upload:".wplugin importieren",remove:"Entfernen",save:"Einstellungen speichern",server:"Server-Plugin",instance:"WebSpeak-Instanz-Plugin",targets:"TS-Server (host:port, eine Adresse pro Zeile)",config:"Öffentliche Konfiguration (JSON; keine Geheimnisse)",enabled:"Plugin aktivieren",lead:"Von GitHub installieren, Berechtigungen prüfen und aktivieren. Updates erfordern erneute Aktivierung.",empty:"Keine Plugins verfügbar",open:"Öffnen",close:"Schließen",back:"Zur Plugin-Liste",permission:"Berechtigungen",scope:"Geltungsbereich",source:"Verteilungsrepository",loading:"Wird geladen…",error:"Plugin-Vorgang fehlgeschlagen",removed:"Plugin entfernen? Aktive Räume werden geschlossen.",context:"Verbindung, Kanal oder Plugin geändert. Plugin erneut öffnen.",note:"Server-Plugins teilen Räume pro Kanal des konfigurierten TS-Servers. Instanz-Plugins teilen einen Raum mit allen verbundenen Nutzern dieses Gateways.",enableNote:"Plugins führen fremden Browsercode in einem isolierten Bereich aus. Öffentliche Konfiguration und Raumzustand sind für Teilnehmer sichtbar."},
|
||||
ru: {title:"Плагины",store:"Магазин плагинов",installed:"Установленные плагины",refresh:"Обновить",install:"Установить / обновить",upload:"Импорт .wplugin",remove:"Удалить",save:"Сохранить настройки",server:"Плагин сервера",instance:"Плагин экземпляра WebSpeak",targets:"Адреса TS (host:port, по одному в строке)",config:"Публичные настройки (JSON; без секретов)",enabled:"Включить плагин",lead:"Установите из GitHub, проверьте разрешения и включите. После обновления требуется повторное включение.",empty:"Нет доступных плагинов",open:"Открыть",close:"Закрыть",back:"К списку плагинов",permission:"Разрешения",scope:"Область действия",source:"Репозиторий распространения",loading:"Загрузка…",error:"Ошибка операции плагина",removed:"Удалить плагин? Активные комнаты закроются.",context:"Соединение, канал или плагин изменились. Откройте плагин снова.",note:"Плагины сервера создают общую комнату в каждом канале указанного TS-сервера. Плагины экземпляра объединяют всех подключённых пользователей шлюза.",enableNote:"Плагин выполняет сторонний код в изолированной панели. Публичные настройки и состояние комнаты видны участникам."},
|
||||
ja: {title:"プラグイン",store:"プラグインストア",installed:"インストール済み",refresh:"更新",install:"インストール / 更新",upload:".wplugin を読み込む",remove:"削除",save:"設定を保存",server:"サーバープラグイン",instance:"WebSpeak インスタンスプラグイン",targets:"TS サーバー(1行に host:port を1つ)",config:"公開設定(JSON、秘密情報を入力しないでください)",enabled:"有効にする",lead:"GitHub からインストールし、権限を確認して有効にします。更新後は再度有効化してください。",empty:"利用できるプラグインがありません",open:"開く",close:"閉じる",back:"一覧に戻る",permission:"権限",scope:"スコープ",source:"配布リポジトリ",loading:"読み込み中…",error:"プラグイン操作に失敗しました",removed:"削除しますか?使用中のルームは閉じられます。",context:"接続、チャンネルまたはプラグインが変更されました。開き直してください。",note:"サーバープラグインは指定 TS サーバーのチャンネルごとに共有します。インスタンスプラグインは同じゲートウェイの接続ユーザー全員で共有します。",enableNote:"隔離パネルでサードパーティーコードを実行します。公開設定とルーム状態は参加者に見えます。"},
|
||||
en,
|
||||
zh:{
|
||||
"panelNote":"这里只显示实例管理员已审核并启用的应用,使用时仍需遵守浏览器的权限提示。",
|
||||
"catalogError":"应用目录暂不可用或需要升级为 API v2,仍可导入本地应用包。",
|
||||
"title": "插件功能",
|
||||
"store": "插件商店",
|
||||
"installed": "已安装插件",
|
||||
"refresh": "刷新",
|
||||
"install": "安装 / 更新",
|
||||
"upload": "导入 .wplugin",
|
||||
"remove": "移除",
|
||||
"save": "保存设置",
|
||||
"server": "TS 服务器范围",
|
||||
"instance": "WebSpeak 实例范围",
|
||||
"targets": "允许的 TS 地址(每行一个 host:port)",
|
||||
"config": "公开配置(JSON;用户可见)",
|
||||
"enabled": "启用插件",
|
||||
"lead": "经审核的应用,可使用标准浏览器能力和可选的 Node 服务。更新后需要重新信任。",
|
||||
"empty": "暂无可用插件",
|
||||
"open": "打开",
|
||||
"close": "关闭",
|
||||
"back": "返回插件列表",
|
||||
"scope": "作用域",
|
||||
"source": "分发仓库",
|
||||
"loading": "加载中…",
|
||||
"error": "插件操作失败",
|
||||
"removed": "移除此应用?已打开的会话将关闭,后端数据会保留。",
|
||||
"context": "连接或应用已变化,请重新打开。",
|
||||
"note": "作用域负责准入并提供上下文标识,协作逻辑和路由由作者编写。服务器范围跟随实际 TS 目标和频道;实例范围覆盖当前网关。",
|
||||
"enableNote": "插件是运行于独立源的受信任应用。Node 后端拥有 WebSpeak 服务账户的操作系统权限。启用前请审核源码和依赖。",
|
||||
"runtime": "应用运行时",
|
||||
"origin": "运行时公开源地址",
|
||||
"originHelp": "配置独立的 HTTPS 源,如 https://apps.example.com,并反向代理到运行时端口。留空仅支持本地自动地址。",
|
||||
"trust": "我已审核并信任此应用及其依赖",
|
||||
"privateConfig": "后端私密配置(JSON;加密存储)",
|
||||
"keep": "保留现有私密配置",
|
||||
"replace": "替换私密配置",
|
||||
"erase": "删除私密配置",
|
||||
"secretSaved": "已保存私密配置",
|
||||
"secretEmpty": "尚无私密配置",
|
||||
"restart": "重启后端",
|
||||
"client": "浏览器应用",
|
||||
"backend": "Node 后端",
|
||||
"disabled": "未启用",
|
||||
"stopped": "已停止",
|
||||
"starting": "启动中",
|
||||
"running": "运行中",
|
||||
"failed": "失败"
|
||||
},
|
||||
de:{
|
||||
"panelNote":"Von der Instanzadministration geprüfte und aktivierte Anwendungen. Browser-Berechtigungsabfragen gelten weiterhin.",
|
||||
"catalogError":"Der Katalog ist nicht verfügbar oder benötigt API v2. Lokaler Import bleibt möglich.",
|
||||
"title": "Plugins",
|
||||
"store": "Plugin-Store",
|
||||
"installed": "Installierte Plugins",
|
||||
"refresh": "Aktualisieren",
|
||||
"install": "Installieren / aktualisieren",
|
||||
"upload": ".wplugin importieren",
|
||||
"remove": "Entfernen",
|
||||
"save": "Einstellungen speichern",
|
||||
"server": "TS-Server-Bereich",
|
||||
"instance": "WebSpeak-Instanz-Bereich",
|
||||
"targets": "Erlaubte TS-Ziele (host:port pro Zeile)",
|
||||
"config": "Öffentliche Konfiguration (JSON; für Nutzer sichtbar)",
|
||||
"enabled": "Plugin aktivieren",
|
||||
"lead": "Geprüfte Anwendungen mit Browserfunktionen und optionalen Node-Diensten. Updates erfordern erneutes Vertrauen.",
|
||||
"empty": "Keine Plugins verfügbar",
|
||||
"open": "Öffnen",
|
||||
"close": "Schließen",
|
||||
"back": "Zur Plugin-Liste",
|
||||
"scope": "Bereich",
|
||||
"source": "Verteilungsrepository",
|
||||
"loading": "Wird geladen…",
|
||||
"error": "Plugin-Vorgang fehlgeschlagen",
|
||||
"removed": "Anwendung entfernen? Sitzungen werden geschlossen; Backend-Daten bleiben erhalten.",
|
||||
"context": "Verbindung oder Anwendung geändert. Erneut öffnen.",
|
||||
"note": "Der Bereich steuert den Zugang und liefert einen Kontextschlüssel. Zusammenarbeit und Routen implementiert der Autor. Server-Bereiche folgen TS-Ziel und Kanal; Instanz-Bereiche gelten für dieses Gateway.",
|
||||
"enableNote": "Vertrauenswürdige Anwendungen auf einer separaten Origin. Node-Backends haben die Betriebssystemrechte des WebSpeak-Dienstkontos. Quellcode und Abhängigkeiten vor der Aktivierung prüfen.",
|
||||
"runtime": "Anwendungslaufzeit",
|
||||
"origin": "Öffentliche Runtime-Origin",
|
||||
"originHelp": "Separate HTTPS-Origin, z. B. https://apps.example.com, auf den Runtime-Port weiterleiten. Leer nur für lokale automatische Adressen.",
|
||||
"trust": "Ich habe diese Anwendung und ihre Abhängigkeiten geprüft und vertraue ihnen",
|
||||
"privateConfig": "Private Backend-Konfiguration (JSON; verschlüsselt gespeichert)",
|
||||
"keep": "Vorhandene private Konfiguration behalten",
|
||||
"replace": "Private Konfiguration ersetzen",
|
||||
"erase": "Private Konfiguration löschen",
|
||||
"secretSaved": "Private Konfiguration gespeichert",
|
||||
"secretEmpty": "Keine private Konfiguration gespeichert",
|
||||
"restart": "Backend neu starten",
|
||||
"client": "Browseranwendung",
|
||||
"backend": "Node-Backend",
|
||||
"disabled": "Deaktiviert",
|
||||
"stopped": "Gestoppt",
|
||||
"starting": "Startet",
|
||||
"running": "Läuft",
|
||||
"failed": "Fehlgeschlagen"
|
||||
},
|
||||
ru:{
|
||||
"panelNote":"Приложения проверены и включены администратором экземпляра. Разрешения браузера по-прежнему применяются.",
|
||||
"catalogError":"Каталог недоступен или требует API v2. Локальный импорт по-прежнему доступен.",
|
||||
"title": "Плагины",
|
||||
"store": "Магазин плагинов",
|
||||
"installed": "Установленные плагины",
|
||||
"refresh": "Обновить",
|
||||
"install": "Установить / обновить",
|
||||
"upload": "Импорт .wplugin",
|
||||
"remove": "Удалить",
|
||||
"save": "Сохранить настройки",
|
||||
"server": "Область TS-сервера",
|
||||
"instance": "Область экземпляра WebSpeak",
|
||||
"targets": "Разрешённые адреса TS (host:port, по одному в строке)",
|
||||
"config": "Публичные настройки (JSON; видны пользователям)",
|
||||
"enabled": "Включить плагин",
|
||||
"lead": "Проверенные приложения с возможностями браузера и необязательными сервисами Node. Обновления требуют повторного доверия.",
|
||||
"empty": "Нет доступных плагинов",
|
||||
"open": "Открыть",
|
||||
"close": "Закрыть",
|
||||
"back": "К списку плагинов",
|
||||
"scope": "Область действия",
|
||||
"source": "Репозиторий распространения",
|
||||
"loading": "Загрузка…",
|
||||
"error": "Ошибка операции плагина",
|
||||
"removed": "Удалить приложение? Сеансы закроются; данные сервиса сохранятся.",
|
||||
"context": "Соединение или приложение изменились. Откройте снова.",
|
||||
"note": "Область определяет доступ и ключ контекста. Автор реализует совместную работу и маршруты. Область сервера следует фактическому адресу TS и каналу, экземпляра — всему шлюзу.",
|
||||
"enableNote": "Это доверенные приложения на отдельном источнике. Сервисы Node обладают правами учётной записи WebSpeak в ОС. До включения проверьте код и зависимости.",
|
||||
"runtime": "Среда приложений",
|
||||
"origin": "Публичный источник среды",
|
||||
"originHelp": "Отдельный HTTPS-источник, например https://apps.example.com, с проксированием на порт среды. Пустое поле — только для локальных адресов.",
|
||||
"trust": "Я проверил приложение и зависимости и доверяю им",
|
||||
"privateConfig": "Приватные настройки сервиса (JSON; хранятся зашифрованными)",
|
||||
"keep": "Сохранить текущие приватные настройки",
|
||||
"replace": "Заменить приватные настройки",
|
||||
"erase": "Удалить приватные настройки",
|
||||
"secretSaved": "Приватные настройки сохранены",
|
||||
"secretEmpty": "Приватных настроек нет",
|
||||
"restart": "Перезапустить сервис",
|
||||
"client": "Браузерное приложение",
|
||||
"backend": "Сервис Node",
|
||||
"disabled": "Выключен",
|
||||
"stopped": "Остановлен",
|
||||
"starting": "Запускается",
|
||||
"running": "Работает",
|
||||
"failed": "Ошибка"
|
||||
},
|
||||
ja:{
|
||||
"panelNote":"インスタンス管理者が審査して有効にしたアプリです。ブラウザーの権限確認は引き続き必要です。",
|
||||
"catalogError":"カタログが利用できないか API v2 が必要です。ローカル読み込みは利用できます。",
|
||||
"title": "プラグイン",
|
||||
"store": "プラグインストア",
|
||||
"installed": "インストール済み",
|
||||
"refresh": "更新",
|
||||
"install": "インストール / 更新",
|
||||
"upload": ".wplugin を読み込む",
|
||||
"remove": "削除",
|
||||
"save": "設定を保存",
|
||||
"server": "TS サーバー範囲",
|
||||
"instance": "WebSpeak インスタンス範囲",
|
||||
"targets": "許可する TS アドレス(1行に host:port)",
|
||||
"config": "公開設定(JSON、ユーザーに公開)",
|
||||
"enabled": "有効にする",
|
||||
"lead": "標準ブラウザー機能と任意の Node サービスを使う審査済みアプリです。更新後は再度信頼を確認します。",
|
||||
"empty": "利用できるプラグインがありません",
|
||||
"open": "開く",
|
||||
"close": "閉じる",
|
||||
"back": "一覧に戻る",
|
||||
"scope": "範囲",
|
||||
"source": "配布リポジトリ",
|
||||
"loading": "読み込み中…",
|
||||
"error": "プラグイン操作に失敗しました",
|
||||
"removed": "削除しますか?セッションは閉じますが、バックエンドのデータは保持します。",
|
||||
"context": "接続またはアプリが変わりました。開き直してください。",
|
||||
"note": "範囲はアクセスとコンテキストキーを提供します。共同作業やルートは作者が実装します。サーバー範囲は実際の TS 接続先とチャンネル、インスタンス範囲は現在のゲートウェイに適用します。",
|
||||
"enableNote": "別オリジンで動く信頼済みアプリです。Node バックエンドは WebSpeak サービスアカウントの OS 権限で動作します。有効化前にコードと依存関係を確認してください。",
|
||||
"runtime": "アプリ実行環境",
|
||||
"origin": "公開ランタイムオリジン",
|
||||
"originHelp": "https://apps.example.com のような別 HTTPS オリジンを実行ポートへ転送します。空欄はローカル自動アドレス専用です。",
|
||||
"trust": "アプリと依存関係を審査し、信頼します",
|
||||
"privateConfig": "バックエンドの秘密設定(JSON、暗号化して保存)",
|
||||
"keep": "現在の秘密設定を保持",
|
||||
"replace": "秘密設定を置換",
|
||||
"erase": "秘密設定を削除",
|
||||
"secretSaved": "秘密設定を保存済み",
|
||||
"secretEmpty": "秘密設定なし",
|
||||
"restart": "バックエンドを再起動",
|
||||
"client": "ブラウザーアプリ",
|
||||
"backend": "Node バックエンド",
|
||||
"disabled": "無効",
|
||||
"stopped": "停止",
|
||||
"starting": "起動中",
|
||||
"running": "動作中",
|
||||
"failed": "失敗"
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
|
||||
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
|
||||
import { pluginResponses, type PluginPackage, type PluginSettings } from "../../../src/shared/plugins.js";
|
||||
import { pluginResponses, type PluginPackage, type PluginSettingsInput } from "../../../src/shared/plugins.js";
|
||||
|
||||
export class AdminApiError extends Error {
|
||||
constructor(readonly code: string, readonly status = 0, message = code) {
|
||||
@@ -103,9 +103,12 @@ export function createAdminApi(options: AdminApiOptions) {
|
||||
invalidate() { generation++; for (const controller of pending) controller.abort(); },
|
||||
plugins: (signal?: AbortSignal) => request("/plugins", pluginResponses.installed, "GET", undefined, true, signal),
|
||||
pluginStore: (signal?: AbortSignal) => request("/plugins/store", pluginResponses.catalog, "GET", undefined, true, signal),
|
||||
pluginRuntime: (signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "GET", undefined, true, signal),
|
||||
configurePluginRuntime: (publicOrigin: string, revision: string, signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "PUT", { publicOrigin, revision }, true, signal),
|
||||
restartPlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/restart`, pluginResponses.saved, "POST", { revision }, true, signal),
|
||||
installPlugin: (body: { id: string; revision: string; installedRevision: string | null }, signal?: AbortSignal) => request("/plugins/store/install", pluginResponses.saved, "POST", body, true, signal),
|
||||
uploadPlugin: (pack: PluginPackage, installedRevision: string | null, signal?: AbortSignal) => request("/plugins/upload", pluginResponses.saved, "POST", { package: pack, installedRevision }, true, signal),
|
||||
configurePlugin: (id: string, revision: string, settings: PluginSettings, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
|
||||
configurePlugin: (id: string, revision: string, settings: PluginSettingsInput, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
|
||||
removePlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}`, adminResponses.ok, "DELETE", { revision }, true, signal),
|
||||
session: (signal?: AbortSignal) => request("/session", adminResponses.session, "GET", undefined, true, signal),
|
||||
login: (username: string, password: string, signal?: AbortSignal) => request("/login", adminResponses.login, "POST", { username, password }, false, signal),
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import appPackage from "../../../package.json";
|
||||
|
||||
// Available before the public config request completes, including on the demo page.
|
||||
export const APP_VERSION = appPackage.version;
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createInstanceAuthorization, INSTANCE_AUTHORIZATION_KEY, canUseSkin, setInstanceAuthorization } from './instance-authorization.js';
|
||||
|
||||
function storage() {
|
||||
const values = new Map<string, string>();
|
||||
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
|
||||
}
|
||||
test('new instances require an explicit decision; legacy package approvals do not imply consent', () => {
|
||||
const data = storage(); data.values.set('webspeak:skin-plugin-approvals', '{"grants":{"old":true}}');
|
||||
const state = createInstanceAuthorization(data);
|
||||
assert.equal(state.decision.value, null); assert.equal(state.allowed.value, false);
|
||||
state.set(false); assert.equal(createInstanceAuthorization(data).decision.value, false);
|
||||
state.set(true); assert.equal(createInstanceAuthorization(data).allowed.value, true);
|
||||
assert.deepEqual([...data.values.keys()].sort(), [INSTANCE_AUTHORIZATION_KEY, 'webspeak:skin-plugin-approvals'].sort());
|
||||
});
|
||||
test('separate instance storage stays independent; revocation and clearing propagate on reload', () => {
|
||||
const first = storage(), second = storage(), tab = createInstanceAuthorization(first), otherTab = createInstanceAuthorization(first);
|
||||
tab.set(true); otherTab.reload(); assert.equal(otherTab.allowed.value, true);
|
||||
assert.equal(createInstanceAuthorization(second).decision.value, null);
|
||||
tab.set(false); otherTab.reload(); assert.equal(otherTab.allowed.value, false);
|
||||
first.values.clear(); otherTab.reload(); assert.equal(otherTab.decision.value, null);
|
||||
});
|
||||
test('malformed or inaccessible storage never grants access; explicit choices survive in memory', () => {
|
||||
const data = storage();
|
||||
for (const value of ['true', '{}', '{"schemaVersion":1,"allowed":"true"}', '{"schemaVersion":2,"allowed":true}', 'broken']) {
|
||||
data.setItem(INSTANCE_AUTHORIZATION_KEY, value); assert.equal(createInstanceAuthorization(data).allowed.value, false);
|
||||
}
|
||||
const unavailable = createInstanceAuthorization({ getItem() { throw Error(); }, setItem() { throw Error(); } });
|
||||
assert.equal(unavailable.allowed.value, false); unavailable.set(true); assert.equal(unavailable.allowed.value, true);
|
||||
unavailable.set(false); assert.equal(unavailable.allowed.value, false);
|
||||
});
|
||||
test('only the three official IDs bypass consent, including when KAAK is shipped as built-in', () => {
|
||||
setInstanceAuthorization(false);
|
||||
for (const id of ['builtin.light', 'builtin.dark', 'community.illusia-voice']) assert.equal(canUseSkin(id), true);
|
||||
for (const id of ['community.kaak-voice', 'community.discord-voice', 'builtin.other']) assert.equal(canUseSkin(id), false);
|
||||
setInstanceAuthorization(true); assert.equal(canUseSkin('community.kaak-voice'), true);
|
||||
setInstanceAuthorization(false);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { computed, readonly, ref } from 'vue';
|
||||
import type { SiteLanguage } from '../../../src/site-copy.js';
|
||||
|
||||
export const INSTANCE_AUTHORIZATION_KEY = 'webspeak:instance-authorization:v1';
|
||||
export const OFFICIAL_SKIN_IDS = new Set(['builtin.light', 'builtin.dark', 'community.illusia-voice']);
|
||||
type AuthorizationStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
|
||||
/** A decision belongs to this browser origin, never to a skin package or a TS account. */
|
||||
export function createInstanceAuthorization(storage: AuthorizationStorage) {
|
||||
function read(): boolean | null {
|
||||
try {
|
||||
const value = JSON.parse(storage.getItem(INSTANCE_AUTHORIZATION_KEY) ?? 'null');
|
||||
return value?.schemaVersion === 1 && typeof value.allowed === 'boolean' ? value.allowed : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
const decision = ref<boolean | null>(read());
|
||||
return {
|
||||
decision: readonly(decision),
|
||||
allowed: computed(() => decision.value === true),
|
||||
set(allowed: boolean) {
|
||||
// Notify consumers synchronously so revocation also retires in-flight loads.
|
||||
decision.value = allowed;
|
||||
try { storage.setItem(INSTANCE_AUTHORIZATION_KEY, JSON.stringify({ schemaVersion: 1, allowed })); } catch { /* Keep this page's explicit decision when storage is unavailable. */ }
|
||||
},
|
||||
reload() { decision.value = read(); },
|
||||
};
|
||||
}
|
||||
|
||||
const store = createInstanceAuthorization({
|
||||
getItem: key => typeof window === 'undefined' ? null : window.localStorage.getItem(key),
|
||||
setItem: (key, value) => { if (typeof window !== 'undefined') window.localStorage.setItem(key, value); },
|
||||
});
|
||||
export const authorizationDecision = store.decision;
|
||||
export const thirdPartyAllowed = store.allowed;
|
||||
export const authorizationRequested = ref(false);
|
||||
export const authorizationLanguage = ref<SiteLanguage>('zh');
|
||||
export const setInstanceAuthorization = store.set;
|
||||
export const canUseSkin = (id: string) => OFFICIAL_SKIN_IDS.has(id) || thirdPartyAllowed.value;
|
||||
export function openInstanceAuthorization() { authorizationRequested.value = true; }
|
||||
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') window.addEventListener('storage', event => {
|
||||
if (event.key === INSTANCE_AUTHORIZATION_KEY || event.key === null) store.reload();
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPluginAppClient } from './plugin-app-client.js';
|
||||
const token='a'.repeat(43),id='b'.repeat(43);
|
||||
const manifest={apiVersion:2,id:'test.app',name:'Test',version:'1.0.0',author:'Test',license:'MIT',description:'App',scopes:['instance'],client:{entry:'client/index.html'}};
|
||||
test('plugin control uses the connected gateway origin and never sends its voice query or cookies',async()=>{
|
||||
const seen:Array<{url:string;init:RequestInit|undefined}>=[];
|
||||
const client=createPluginAppClient('wss://relay.example/voice?credential=private',token,async(url,init)=>{seen.push({url:String(url),init});return Response.json({plugins:[{manifest,scope:'instance',runtime:{state:'client'}}]});});
|
||||
assert.equal((await client.list())[0].manifest.id,'test.app');assert.equal(seen[0].url,'https://relay.example/api/plugins');assert.equal(seen[0].init?.credentials,'omit');assert.equal(new Headers(seen[0].init?.headers).get('authorization'),'Bearer '+token);
|
||||
assert.throws(()=>createPluginAppClient('https://x','invalid'));assert.throws(()=>createPluginAppClient('https://user:secret@example.com',token));
|
||||
});
|
||||
test('launch validation rejects mismatched IDs, unsafe URLs and invalid runtime responses',async()=>{
|
||||
for(const value of [{id,url:`https://apps.example/apps/${id}/client/index.html`,manifest:{...manifest,id:'another.app'}},{id,url:`https://user:secret@apps.example/apps/${id}/client/index.html`,manifest},{id,url:'javascript:alert(1)',manifest},{id,url:`https://apps.example/apps/${id}/client/index.html?ticket=x`,manifest}]){
|
||||
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json(value));await assert.rejects(client.open('test.app',{openId:'operation-123',theme:'light',language:'en'}));
|
||||
}
|
||||
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json({plugins:[{manifest,scope:'anything',runtime:{state:'unknown'}}]}));await assert.rejects(client.list());
|
||||
});
|
||||
test('control requests time out through response body parsing and support caller cancellation',async()=>{
|
||||
const slow:typeof fetch=async(_url,init)=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))));
|
||||
const client=createPluginAppClient('http://localhost:3040',token,slow,15);await assert.rejects(client.list(),/PLUGIN_TIMEOUT/);
|
||||
const controller=new AbortController(),request=client.list(controller.signal);controller.abort();await assert.rejects(request,/PLUGIN_REQUEST_CANCELLED/);
|
||||
const body:typeof fetch=async(_url,init)=>({ok:true,json:()=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))))}) as Response;
|
||||
await assert.rejects(createPluginAppClient('http://localhost:3040',token,body,15).list(),/PLUGIN_TIMEOUT/);
|
||||
});
|
||||
test('pending open cancellation remains a separate operation and status errors are bounded codes',async()=>{
|
||||
const requests:string[]=[];const client=createPluginAppClient('http://localhost:3040',token,async(url,init)=>{requests.push(`${init?.method} ${url}`);return Response.json({ok:true});});
|
||||
await client.cancelOpen('operation-123');assert.match(requests[0],/^DELETE .*\/opening\/operation-123$/);
|
||||
await assert.rejects(createPluginAppClient('http://localhost:3040',token,async()=>Response.json({code:'<secret error body>'},{status:500})).list(),/PLUGIN_RUNTIME_FAILED/);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { parsePluginManifest, pluginAssert, pluginRecord, type PluginManifest, type PluginAppLaunch, type PluginScope, type PluginRuntimeStatus } from '../../../src/shared/plugins.js';
|
||||
|
||||
export interface AvailablePluginApp { manifest: PluginManifest; scope: PluginScope; runtime: PluginRuntimeStatus }
|
||||
export function createPluginAppClient(gatewayUrl:string,token:string,fetcher:typeof fetch=fetch,timeoutMs=15000){
|
||||
pluginAssert(/^[A-Za-z0-9_-]{43}$/.test(token),'PLUGIN_NOT_CONNECTED');
|
||||
const gateway=new URL(gatewayUrl);pluginAssert(['ws:','wss:','http:','https:'].includes(gateway.protocol)&&!gateway.username&&!gateway.password);
|
||||
gateway.protocol=gateway.protocol==='wss:'||gateway.protocol==='https:'?'https:':'http:';
|
||||
const base=gateway.origin+'/api/plugins';
|
||||
async function request(route:string,method='GET',body?:unknown,signal?:AbortSignal):Promise<unknown>{
|
||||
const controller=new AbortController();let timedOut=false;
|
||||
const abort=()=>controller.abort();if(signal?.aborted)abort();else signal?.addEventListener('abort',abort,{once:true});
|
||||
const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeoutMs);
|
||||
try{
|
||||
const response=await fetcher(base+route,{method,headers:{authorization:'Bearer '+token,...(body===undefined?{}:{'content-type':'application/json'})},credentials:'omit',redirect:'error',signal:controller.signal,...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
const value:unknown=await response.json();
|
||||
if(!response.ok)throw new Error(pluginRecord(value)&&typeof value.code==='string'&&/^[A-Z0-9_]{1,80}$/.test(value.code)?value.code:'PLUGIN_RUNTIME_FAILED');
|
||||
return value;
|
||||
}catch(error){if(timedOut)throw new Error('PLUGIN_TIMEOUT');if(signal?.aborted)throw new Error('PLUGIN_REQUEST_CANCELLED');throw error;}
|
||||
finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);}
|
||||
}
|
||||
return {
|
||||
async list(signal?:AbortSignal):Promise<AvailablePluginApp[]>{
|
||||
const value=await request('','GET',undefined,signal);pluginAssert(pluginRecord(value)&&Array.isArray(value.plugins)&&value.plugins.length<=50,'PLUGIN_INVALID_RESPONSE');
|
||||
return value.plugins.map(entry=>{
|
||||
pluginAssert(pluginRecord(entry)&&(entry.scope==='server'||entry.scope==='instance')&&pluginRecord(entry.runtime)&&['disabled','client','stopped','starting','running','failed'].includes(String(entry.runtime.state)),'PLUGIN_INVALID_RESPONSE');
|
||||
return {manifest:parsePluginManifest(entry.manifest),scope:entry.scope,runtime:{state:entry.runtime.state as PluginRuntimeStatus['state'],...(typeof entry.runtime.error==='string'?{error:entry.runtime.error}:{})}};
|
||||
});
|
||||
},
|
||||
async open(id:string,options:{openId:string;theme:'light'|'dark';language:string},signal?:AbortSignal):Promise<PluginAppLaunch>{
|
||||
const value=await request('/'+encodeURIComponent(id)+'/open','POST',options,signal);
|
||||
pluginAssert(pluginRecord(value)&&typeof value.id==='string'&&/^[A-Za-z0-9_-]{43}$/.test(value.id)&&typeof value.url==='string','PLUGIN_INVALID_RESPONSE');
|
||||
const manifest=parsePluginManifest(value.manifest),url=new URL(value.url);
|
||||
pluginAssert(manifest.id===id&&['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&url.pathname==='/apps/'+value.id+'/'+manifest.client.entry&&!url.hash&&!url.search,'PLUGIN_INVALID_RESPONSE');
|
||||
return {id:value.id,url:url.href,manifest};
|
||||
},
|
||||
cancelOpen:(openId:string)=>request('/opening/'+encodeURIComponent(openId),'DELETE'),
|
||||
appearance:(id:string,theme:'light'|'dark',language:string)=>request('/apps/'+encodeURIComponent(id),'PATCH',{theme,language}),
|
||||
};
|
||||
}
|
||||
export type PluginAppClient=ReturnType<typeof createPluginAppClient>;
|
||||
@@ -1,32 +0,0 @@
|
||||
import { type PluginPackage } from "../../../src/shared/plugins.js";
|
||||
|
||||
/** The SDK never receives a voice socket, TS identity, cookie, or admin API. */
|
||||
export function pluginFrameDocument(pack: PluginPackage, channel: string): string {
|
||||
const escape = (source: string, tag: string) => source.replace(new RegExp(`</${tag}`, "gi"), `<\\/${tag}`);
|
||||
const bootstrap = `(() => {
|
||||
const channel = ${JSON.stringify(channel)};
|
||||
const pending = new Map(), listeners = new Set(); let sequence = 0, context;
|
||||
const send = value => parent.postMessage({channel,...value}, '*');
|
||||
const ready = new Promise(resolve => window.addEventListener('message', function receive(event) {
|
||||
if(event.source !== parent || event.data?.channel !== channel) return;
|
||||
const m = event.data;
|
||||
if(m.type === 'context') { context=m.context; document.documentElement.dataset.theme=context.theme;
|
||||
document.getElementById('plugin-light').media=context.theme==='dark'?'not all':'all';
|
||||
document.getElementById('plugin-dark').media=context.theme==='dark'?'all':'not all'; resolve(context); }
|
||||
if(m.type === 'snapshot') for(const fn of listeners) { try {fn(m.snapshot);} catch {} }
|
||||
if(m.type === 'reply') { const task=pending.get(m.id); if(task) {pending.delete(m.id); clearTimeout(task.timer); m.error?task.reject(new Error(m.error)):task.resolve(m.result);} }
|
||||
}));
|
||||
const request = (method,args) => new Promise((resolve,reject) => {
|
||||
if(pending.size>=16) return reject(new Error('PLUGIN_RATE_LIMITED'));
|
||||
const id=++sequence, timer=setTimeout(()=>{pending.delete(id);reject(new Error('PLUGIN_TIMEOUT'));},12000);
|
||||
pending.set(id,{resolve,reject,timer}); send({type:'request',id,method,args});
|
||||
});
|
||||
window.webspeak = Object.freeze({apiVersion:1,ready,
|
||||
room:Object.freeze({snapshot:()=>request('room.snapshot'),update:(revision,state)=>request('room.update',{revision,state}),
|
||||
subscribe(fn){listeners.add(fn); return ()=>listeners.delete(fn);}})});
|
||||
send({type:'ready'});
|
||||
})();`;
|
||||
// Opaque origin + no same-origin, popups, forms, navigation, fetch, or nested frames.
|
||||
const csp = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src https: data:; media-src https: http: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="${csp}"><script>${escape(bootstrap,"script")}</script><style>html,body{margin:0;min-height:100%;font:15px system-ui}*{box-sizing:border-box}body{padding:20px}html[data-theme="dark"]{color-scheme:dark}</style><style id="plugin-light">${escape(pack.styles.light,"style")}</style><style id="plugin-dark" media="not all">${escape(pack.styles.dark,"style")}</style></head><body>${pack.html}<script>${escape(pack.script,"script")}</script></body></html>`;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPluginTransport } from './plugin-transport.js';
|
||||
|
||||
test('plugin requests correlate replies, reset pending work and release subscribers independently',async () => {
|
||||
const sent:any[]=[];const socket={readyState:1,send:(v:string)=>sent.push(JSON.parse(v))} as unknown as WebSocket;
|
||||
const transport=createPluginTransport(()=>socket,()=>true);
|
||||
const result=transport.request('list');assert.equal(sent[0].type,'pluginRequest');
|
||||
transport.receive({type:'pluginReply',requestId:sent[0].requestId,ok:true,result:[{id:'a'}]});
|
||||
assert.deepEqual(await result,[{id:'a'}]);
|
||||
const events:any[]=[];const off=transport.subscribe(m=>events.push(m));
|
||||
transport.receive({type:'pluginEvent',pluginId:'a',snapshot:null});assert.equal(events.length,1);
|
||||
const pending=transport.request('open',{pluginId:'a'});transport.reset();await assert.rejects(pending,/PLUGIN_NOT_CONNECTED/);
|
||||
transport.receive({type:'pluginReply',requestId:sent[1].requestId,ok:true,result:{old:true}});assert.equal(events.at(-1).type,'pluginReset');
|
||||
off();transport.reset();assert.equal(events.length,2);
|
||||
});
|
||||
test('server errors, disconnected sockets and request quotas do not leak promises',async () => {
|
||||
const sent:any[]=[];let connected=false;const socket={readyState:1,send:(v:string)=>sent.push(JSON.parse(v))} as unknown as WebSocket;
|
||||
const transport=createPluginTransport(()=>socket,()=>connected);
|
||||
await assert.rejects(transport.request('list'),/PLUGIN_NOT_CONNECTED/);connected=true;
|
||||
const failed=transport.request('snapshot',{pluginId:'a'});
|
||||
transport.receive({type:'pluginReply',requestId:sent[0].requestId,ok:false,code:'PLUGIN_NOT_OPEN'});await assert.rejects(failed,/PLUGIN_NOT_OPEN/);
|
||||
const pending=Array.from({length:16},()=>transport.request('list').catch(e=>e.message));
|
||||
await assert.rejects(transport.request('list'),/PLUGIN_RATE_LIMITED/);transport.reset();
|
||||
assert.ok((await Promise.all(pending)).every(v=>v==='PLUGIN_NOT_CONNECTED'));
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
import { pluginRecord, type PluginRequest, type PluginMessage } from "../../../src/shared/plugins.js";
|
||||
|
||||
/** Owns requests and event subscribers for one voice connection. */
|
||||
export function createPluginTransport(socket: () => WebSocket | null, connected: () => boolean) {
|
||||
let sequence = 0;
|
||||
const pending = new Map<string, { finish(value?: unknown, error?: Error): void }>();
|
||||
const listeners = new Set<(message: PluginMessage | { type: "pluginReset" }) => void>();
|
||||
function emit(message: PluginMessage | { type: "pluginReset" }): void { for (const listener of [...listeners]) { try { listener(message); } catch { /* isolate presentation */ } } }
|
||||
return {
|
||||
request(action: PluginRequest["action"], fields: { pluginId?: string; revision?: number; state?: unknown } = {}): Promise<unknown> {
|
||||
const ws = socket();
|
||||
if (!connected() || ws?.readyState !== 1) return Promise.reject(new Error("PLUGIN_NOT_CONNECTED"));
|
||||
if (pending.size >= 16) return Promise.reject(new Error("PLUGIN_RATE_LIMITED"));
|
||||
const requestId = `plugin-${Date.now().toString(36)}-${++sequence}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => finish(undefined, new Error("PLUGIN_TIMEOUT")), 15_000);
|
||||
const finish = (value?: unknown, error?: Error) => { if (!pending.delete(requestId)) return; clearTimeout(timer); error ? reject(error) : resolve(value); };
|
||||
pending.set(requestId, { finish });
|
||||
try { ws.send(JSON.stringify({ type: "pluginRequest", requestId, action, ...fields })); }
|
||||
catch { finish(undefined, new Error("PLUGIN_NOT_CONNECTED")); }
|
||||
});
|
||||
},
|
||||
receive(value: unknown): boolean {
|
||||
if (!pluginRecord(value)) return false;
|
||||
if (value.type === "pluginReply") {
|
||||
if (typeof value.requestId === "string" && typeof value.ok === "boolean") pending.get(value.requestId)?.finish(value.result,
|
||||
value.ok ? undefined : new Error(typeof value.code === "string" ? value.code.slice(0, 80) : "PLUGIN_FAILED"));
|
||||
return true;
|
||||
}
|
||||
if (value.type === "pluginEvent" && typeof value.pluginId === "string" && (value.snapshot === null || pluginRecord(value.snapshot))) {
|
||||
emit(value as unknown as PluginMessage); return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
subscribe(listener: (message: PluginMessage | { type: "pluginReset" }) => void): () => void { listeners.add(listener); return () => listeners.delete(listener); },
|
||||
reset(): void { for (const item of [...pending.values()]) item.finish(undefined, new Error("PLUGIN_NOT_CONNECTED")); emit({ type: "pluginReset" }); },
|
||||
};
|
||||
}
|
||||
export type PluginTransport = ReturnType<typeof createPluginTransport>;
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import test, { beforeEach } from "node:test";
|
||||
import { setInstanceAuthorization } from './instance-authorization.js';
|
||||
import { createRenderer, createSSRApp, defineComponent, h, nextTick, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
SkinExtensionUiOutputError,
|
||||
} from "../../../src/shared/skin-extension-ui.js";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
beforeEach(() => setInstanceAuthorization(true));
|
||||
|
||||
function outputDocument(componentId = "runtime-ui", root?: Record<string, unknown>, permissions: string[] = [], actions: Record<string, unknown> = {}, state?: Record<string, unknown>): string {
|
||||
return JSON.stringify({
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
/** Temporary development policy. Re-enable consent before public skin distribution. */
|
||||
/** Per-package dialogs are replaced by the explicit, revocable instance authorization.
|
||||
* Hosts must check canUseSkin before issuing/using internal manifest-bound grants. */
|
||||
export const PROMPT_FOR_SKIN_PERMISSIONS = false;
|
||||
@@ -51,7 +51,7 @@ export function getSkinRuntimePluginApproval(
|
||||
return grant && isSkinRuntimePluginApproved(grant, skinId, skinVersion, plugin, digest) ? grant : null;
|
||||
}
|
||||
|
||||
/** Called only by the host consent UI after a user explicitly approves this exact package. */
|
||||
/** Internal digest-bound record. The host must first allow this skin through instance authorization. */
|
||||
export function approveSkinRuntimePlugin(
|
||||
skinId: string,
|
||||
skinVersion: string,
|
||||
|
||||
@@ -35,6 +35,19 @@ async function approvedFiles(source = createSkinExtensionWasmPrefixByteImmediate
|
||||
return { files, digest, approval: createSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest) };
|
||||
}
|
||||
|
||||
test('revocation while package bytes are being verified prevents worker startup', async () => {
|
||||
const { files, approval } = await approvedFiles();
|
||||
const controller = new AbortController(), original = files[plugin.entry];
|
||||
class RevokedBlob extends Blob {
|
||||
override async arrayBuffer(): Promise<ArrayBuffer> { controller.abort(); return super.arrayBuffer(); }
|
||||
}
|
||||
await assert.rejects(createSkinRuntimePluginWasmSandbox({
|
||||
skinId: 'community.sample', skinVersion: '2.0.0', plugin, approval,
|
||||
files: { [plugin.entry]: new RevokedBlob([original]) }, signal: controller.signal,
|
||||
readSessionStatus: async () => ({ connected: true, channelName: 'Test', memberCount: 1 }),
|
||||
}), { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test("Wasm plugin startup rechecks the exact digest approval before creating a Worker", async () => {
|
||||
const { files, approval } = await approvedFiles();
|
||||
const staleApproval = { ...approval, digest: "0".repeat(64) };
|
||||
|
||||
@@ -26,6 +26,7 @@ export class SkinRuntimePluginWasmError extends Error {
|
||||
}
|
||||
|
||||
export interface SkinRuntimePluginWasmOptions {
|
||||
signal?: AbortSignal;
|
||||
skinId: string;
|
||||
skinVersion: string;
|
||||
plugin: SkinRuntimePlugin;
|
||||
@@ -43,6 +44,7 @@ const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSI
|
||||
export async function createSkinRuntimePluginWasmSandbox(
|
||||
options: SkinRuntimePluginWasmOptions,
|
||||
): Promise<SkinExtensionWasmSandboxHandle> {
|
||||
options.signal?.throwIfAborted();
|
||||
const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [options.plugin] }).plugins[0];
|
||||
if (plugin.runtime !== "wasm") throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "Only a Wasm plugin entry can use the bounded Wasm runner.");
|
||||
|
||||
@@ -52,6 +54,7 @@ export async function createSkinRuntimePluginWasmSandbox(
|
||||
}
|
||||
|
||||
const digest = await computeSkinRuntimePluginDigest(plugin, options.files);
|
||||
options.signal?.throwIfAborted();
|
||||
let approval: SkinRuntimePluginApproval;
|
||||
try { approval = parseSkinRuntimePluginApproval(options.approval); }
|
||||
catch { throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_APPROVAL_INVALID", "The Wasm plugin does not have a valid local approval."); }
|
||||
@@ -62,6 +65,7 @@ export async function createSkinRuntimePluginWasmSandbox(
|
||||
const entry = options.files[plugin.entry];
|
||||
if (!(entry instanceof Blob)) throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "The approved Wasm entry is unavailable.");
|
||||
const wasmBytes = new Uint8Array(await entry.arrayBuffer());
|
||||
options.signal?.throwIfAborted();
|
||||
const baseInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
|
||||
const uiInput = parseSkinExtensionUiInput({
|
||||
...baseInput,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
|
||||
import { APP_VERSION } from "./app-version.js";
|
||||
import type { InstalledSkin } from "./skin-pack.js";
|
||||
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
|
||||
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
|
||||
import { setSkinLayoutPackage } from "./skin-layout-runtime.js";
|
||||
import { canUseSkin } from './instance-authorization.js';
|
||||
|
||||
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
|
||||
export const BUILTIN_LIGHT_SKIN = "builtin.light";
|
||||
@@ -34,7 +36,7 @@ export async function activateStoredSkin(): Promise<InstalledSkin | null> {
|
||||
return activateSkin(selectedId);
|
||||
}
|
||||
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.7", options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
|
||||
export async function activateSkin(id: string, expectedVersion?: string, appVersion = APP_VERSION, options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
|
||||
// An already retired page must not cancel a newer page's activation.
|
||||
options.signal?.throwIfAborted();
|
||||
pendingActivation?.cancel();
|
||||
@@ -51,6 +53,7 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
|
||||
async function prepareAndActivate(id: string, expectedVersion: string | undefined, appVersion: string,
|
||||
operation: ReturnType<typeof createSkinOperation>): Promise<InstalledSkin | null> {
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) return fallBackToBuiltin();
|
||||
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
|
||||
removeCustomSkinStyle();
|
||||
setSkinLayoutPackage(id, null);
|
||||
@@ -92,6 +95,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
|
||||
candidateUrls = compiled.objectUrls;
|
||||
operation.check();
|
||||
if (!canUseSkin(id)) { candidateUrls.forEach(url => URL.revokeObjectURL(url)); return fallBackToBuiltin(); }
|
||||
// A community skin is a complete appearance choice, not an overlay on the
|
||||
// previously selected day/night skin. Keep the document theme (used by the
|
||||
// independent admin appearance) but give unstyled public parts a light,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
.ws-plugin-overlay{--po-bg:#f5f7fc;--po-surface:#fff;--po-raised:#edf1f9;--po-line:#dae1ef;--po-text:#233049;--po-muted:#65728b;--po-accent:#5265df;--po-tint:#e9edff;position:fixed;inset:0;z-index:10000;pointer-events:none;color:var(--po-text);font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;color-scheme:light;text-align:left}
|
||||
.ws-plugin-overlay[data-plugin-theme="dark"]{--po-bg:#171c27;--po-surface:#202736;--po-raised:#2a3345;--po-line:#364158;--po-text:#edf2ff;--po-muted:#a5b1ca;--po-accent:#a4b0ff;--po-tint:#333e64;color-scheme:dark}
|
||||
.ws-plugin-overlay *{box-sizing:border-box}
|
||||
.ws-plugin-overlay button{appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:8px;margin:0;min-width:0;width:auto;height:auto;font:inherit;letter-spacing:normal;text-transform:none;border:1px solid var(--po-line);border-radius:9px;padding:8px 14px;background:var(--po-surface);color:var(--po-text);box-shadow:none;cursor:pointer;white-space:normal}
|
||||
.ws-plugin-overlay button:hover{background:var(--po-raised);border-color:var(--po-accent)}
|
||||
.ws-plugin-overlay button:disabled{opacity:.5;cursor:wait}
|
||||
.ws-plugin-overlay button:focus-visible,.ws-plugin-search:focus-visible{outline:2px solid var(--po-accent);outline-offset:3px}
|
||||
.ws-plugin-overlay svg{display:block;width:19px;height:19px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
|
||||
.ws-plugin-overlay .ws-plugin-launcher{position:absolute;pointer-events:auto;right:max(20px,env(safe-area-inset-right));bottom:calc(22px + env(safe-area-inset-bottom));padding:13px 18px;border:1px solid #ffffff35;border-radius:18px;background:#303f78;color:#fff;box-shadow:0 8px 30px #101a4240;font-weight:650;transition:background .15s,box-shadow .15s}
|
||||
.ws-plugin-overlay .ws-plugin-launcher:hover{background:#405496;box-shadow:0 10px 35px #101a4260}
|
||||
.ws-plugin-launcher i{width:7px;height:7px;border-radius:50%;background:#9ee7b5}
|
||||
.ws-plugin-window{position:absolute;pointer-events:auto;left:50%;top:10dvh;transform:translateX(-50%);display:flex;flex-direction:column;width:min(1080px,calc(100vw - 32px));height:min(760px,80dvh);min-width:320px;min-height:240px;max-width:calc(100vw - 16px);max-height:calc(100dvh - 16px);overflow:hidden;resize:both;border:1px solid var(--po-line);border-radius:17px;background:var(--po-bg);box-shadow:0 30px 100px #080e3540,0 4px 20px #080e3520;isolation:isolate}
|
||||
.ws-plugin-window:focus{outline:none}
|
||||
.ws-plugin-window.is-maximized{inset:8px!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 16px)!important;transform:none!important;resize:none}
|
||||
.ws-plugin-titlebar{display:flex;align-items:center;gap:12px;flex:none;min-height:62px;margin:0;padding:8px 10px 8px 20px;border-bottom:1px solid var(--po-line);background:var(--po-surface);cursor:grab;touch-action:none;user-select:none}
|
||||
.is-dragging .ws-plugin-titlebar{cursor:grabbing}
|
||||
.ws-plugin-mark{display:grid;place-items:center;width:32px;height:32px;flex:none;border-radius:10px;background:var(--po-tint);color:var(--po-accent);font-size:23px}
|
||||
.ws-plugin-window-title{display:flex;align-items:baseline;gap:12px;min-width:0;flex:1}
|
||||
.ws-plugin-window-title strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:650}
|
||||
.ws-plugin-window-title small{color:var(--po-muted);font-size:11px;flex:none}
|
||||
.ws-plugin-window-controls{display:flex;gap:3px;flex:none}
|
||||
.ws-plugin-overlay .ws-plugin-window-controls button{padding:9px;border:0;border-radius:8px;background:transparent;color:var(--po-muted)}
|
||||
.ws-plugin-overlay .ws-plugin-window-controls button:hover{background:var(--po-raised);color:var(--po-text)}
|
||||
.ws-plugin-overlay .ws-plugin-window-controls .ws-plugin-close:hover{background:#d44354;color:white}
|
||||
.ws-plugin-navigation{display:flex;align-items:center;gap:6px;min-height:52px;flex:none;padding:8px 16px;border-bottom:1px solid var(--po-line);overflow-x:auto}
|
||||
.ws-plugin-overlay .ws-plugin-navigation button{flex:none;padding:7px 12px;border:0;background:transparent;color:var(--po-muted);font-size:12px}
|
||||
.ws-plugin-overlay .ws-plugin-navigation button.active{background:var(--po-tint);color:var(--po-accent);font-weight:650}
|
||||
.ws-plugin-version{margin-left:auto;white-space:nowrap;color:var(--po-muted);font-size:11px}
|
||||
.ws-plugin-library{flex:1;min-height:0;padding:26px;overflow:auto;overscroll-behavior:contain}
|
||||
.ws-plugin-library-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:20px}
|
||||
.ws-plugin-library-heading h2{margin:0 0 3px;color:var(--po-text);font-size:24px;font-weight:700;line-height:1.3}
|
||||
.ws-plugin-library-heading span{font-size:12px;color:var(--po-muted)}
|
||||
.ws-plugin-overlay .ws-plugin-search{display:block;width:100%;height:42px;margin:0 0 22px;padding:10px 14px;background:var(--po-surface);color:var(--po-text);font:inherit;border:1px solid var(--po-line);border-radius:10px;box-shadow:none}
|
||||
.ws-plugin-search::placeholder{color:var(--po-muted)}
|
||||
.ws-plugin-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,270px),1fr));align-items:start;gap:16px}
|
||||
.ws-plugin-entry{display:grid;grid-template-columns:44px minmax(0,1fr);gap:14px;padding:20px;background:var(--po-surface);border:1px solid var(--po-line);border-radius:13px}
|
||||
.ws-plugin-app-mark{display:grid;place-items:center;width:44px;height:44px;border-radius:13px;background:var(--po-tint);color:var(--po-accent);font-size:22px;font-weight:700}
|
||||
.ws-plugin-entry h3{margin:0 0 4px;font-size:15px;font-weight:650;overflow-wrap:anywhere;color:var(--po-text)}
|
||||
.ws-plugin-entry small{display:block;color:var(--po-muted);font-size:11px}
|
||||
.ws-plugin-entry p{margin:12px 0 0;color:var(--po-muted);font-size:13px;overflow-wrap:anywhere}
|
||||
.ws-plugin-overlay .ws-plugin-entry button{grid-column:1/-1;justify-content:space-between;width:100%;background:var(--po-tint);border-color:transparent;color:var(--po-accent);font-weight:600}
|
||||
.ws-plugin-entry-error{grid-column:1/-1;color:#d1495b!important}
|
||||
.ws-plugin-empty{text-align:center;color:var(--po-muted);padding:50px 12px}
|
||||
.ws-plugin-error{flex:none;margin:0;padding:12px 20px;background:#dc50541a;color:#d1495b;overflow-wrap:anywhere;max-height:100px;overflow:auto}
|
||||
.ws-plugin-browser{flex:1;min-height:0;display:flex;background:var(--po-surface)}
|
||||
.ws-plugin-browser iframe{display:block;flex:1;width:100%;height:100%;min-height:0;border:0;border-radius:0;background:var(--po-surface)}
|
||||
.ws-plugin-drag-shield{position:absolute;inset:62px 0 0;z-index:1;cursor:grabbing}
|
||||
@media(max-width:600px){.ws-plugin-window{left:8px!important;top:8px!important;transform:none!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 92px);min-width:0;resize:none;border-radius:13px}.ws-plugin-titlebar{padding-left:12px;gap:8px}.ws-plugin-window-title small{display:none}.ws-plugin-library{padding:18px}.ws-plugin-overlay .ws-plugin-launcher{bottom:calc(16px + env(safe-area-inset-bottom));right:12px;padding:12px 14px}.ws-plugin-library-heading h2{font-size:21px}.ws-plugin-entry{padding:16px}.ws-plugin-navigation{padding-inline:10px}}
|
||||
@media(prefers-reduced-motion:reduce){.ws-plugin-overlay .ws-plugin-launcher{transition:none}}
|
||||
.ws-plugin-launcher{touch-action:none;user-select:none}
|
||||
@@ -58,11 +58,13 @@
|
||||
<div v-if="poke" class="demo-poke" data-ws-part="demo.poke-notification" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" data-ws-part="demo.poke.dismiss" @click="poke = false"><Icon name="close" :size="14" /></button></div>
|
||||
</div>
|
||||
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
|
||||
<InstanceAuthorization :language="language" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
|
||||
import "../styles/skin-plugin.css";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
|
||||
@@ -870,7 +870,7 @@
|
||||
<div class="ws-skin-mount-slot" data-ws-skin-mount="voice.workspace.overlay"></div>
|
||||
</div>
|
||||
|
||||
<PluginPanel :transport="plugins" :connected="voiceState.connected" :language="language" />
|
||||
<PluginPanel :session-token="pluginSession" :gateway-url="pluginVoiceSocket?.url ?? ''" :connected="voiceState.connected" :language="language" />
|
||||
<IdentityImportDialog
|
||||
v-if="identityImportOpen"
|
||||
v-model="identityImportText"
|
||||
@@ -958,6 +958,7 @@
|
||||
>
|
||||
</div>
|
||||
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
|
||||
<InstanceAuthorization :language="language" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
@@ -1003,6 +1004,7 @@ import { useWebClientChannels, type TreeChannel } from "../composables/useWebCli
|
||||
import { useWebClientConnection } from "../composables/useWebClientConnection.js";
|
||||
import { useWebClientMembers } from "../composables/useWebClientMembers.js";
|
||||
import PluginPanel from "../components/PluginPanel.vue";
|
||||
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
|
||||
import { useVoiceWebSocket, type ChannelMember, type ChatMessage } from "../composables/useVoiceWebSocket.js";
|
||||
import { useWebClientScreenShare } from "../composables/useWebClientScreenShare.js";
|
||||
import { useWebClientPerformance } from "../composables/useWebClientPerformance.js";
|
||||
@@ -1104,7 +1106,8 @@ const {
|
||||
leaveScreenShare,
|
||||
checkSupport,
|
||||
clearError,
|
||||
plugins,
|
||||
pluginSession,
|
||||
ws: pluginVoiceSocket,
|
||||
measureVoiceAudioStatus,
|
||||
} = useVoiceWebSocket();
|
||||
const performance = useWebClientPerformance(computed(() => voiceState.connected), measureVoiceAudioStatus);
|
||||
|
||||
@@ -337,7 +337,7 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
startScreenShareStatsPolling();
|
||||
traceScreenShare("peer-created", { streamId, peerId, role });
|
||||
if (role === "owner") {
|
||||
// Match TeamSpeak's screen-share offer shape: video is MID 0, optional
|
||||
// Match TeamSpeak's screen-share offer shape: video is MID 0,
|
||||
// audio follows it, and a publisher only sends media.
|
||||
const localTracks = [...(screenShareLocalStream?.getTracks() ?? [])];
|
||||
localTracks.sort((left, right) => left.kind === right.kind ? 0 : left.kind === "video" ? -1 : 1);
|
||||
@@ -347,6 +347,13 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
if (transceiver) transceiver.direction = "sendonly";
|
||||
if (track.kind === "video") void configureScreenShareVideoSender(sender, track);
|
||||
}
|
||||
// The native receiver does not answer video-only offers. Window/monitor
|
||||
// capture (or audio disabled by the user) often returns no audio track.
|
||||
// Negotiate the required audio section without capturing a microphone,
|
||||
// fabricating a track or claiming that shared audio is available.
|
||||
if (peerId.startsWith("ts-viewer-") && !localTracks.some(track => track.kind === "audio")) {
|
||||
peer.addTransceiver("audio", { direction: "sendonly" });
|
||||
}
|
||||
} else {
|
||||
peer.addTransceiver("video", { direction: "recvonly" });
|
||||
const stream = screenShareStreams.find((candidate) => candidate.streamId === streamId);
|
||||
@@ -537,12 +544,19 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
await peer.setLocalDescription(offer);
|
||||
if (!isCurrentPeer(peerId, peer)) return;
|
||||
armScreenSharePeerTimer(peerId);
|
||||
traceScreenShare("native-viewer-offer-ready", { streamId, peerId });
|
||||
const sdp = peer.localDescription?.sdp ?? offer.sdp ?? "";
|
||||
traceScreenShare("native-viewer-offer-ready", {
|
||||
streamId, peerId,
|
||||
hasAudioSection: /^m=audio\s/m.test(sdp),
|
||||
hasVideoSection: /^m=video\s/m.test(sdp),
|
||||
capturedAudio: (screenShareLocalStream?.getAudioTracks().length ?? 0) > 0,
|
||||
displaySurface: screenShareLocalStream?.getVideoTracks()[0]?.getSettings().displaySurface ?? null,
|
||||
});
|
||||
sendScreenShareMessage({
|
||||
type: "screenShareSignal",
|
||||
streamId,
|
||||
targetPeerId: peerId,
|
||||
signal: { kind: "offer", sdp: peer.localDescription?.sdp ?? offer.sdp ?? "" },
|
||||
signal: { kind: "offer", sdp },
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
traceScreenShare("native-viewer-offer-failed", { streamId, peerId, errorName: error instanceof Error ? error.name : "unknown" });
|
||||
|
||||
@@ -1,72 +1,146 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { once, EventEmitter } from 'node:events';
|
||||
import { createServer } from 'node:http';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { once } from 'node:events';
|
||||
import { mkdtemp, rm, readFile, readdir } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import express from 'express';
|
||||
import { WebSocket } from 'ws';
|
||||
import pino from 'pino';
|
||||
import { PluginRegistry } from '../../src/plugins/registry.js';
|
||||
import { PluginStore } from '../../src/plugins/store.js';
|
||||
import { parsePluginPackage, PLUGIN_STORE_INDEX } from '../../src/shared/plugins.js';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createAdminRouter } from '../../src/admin/admin-router.js';
|
||||
import { AdminSessionStore } from '../../src/admin/admin-session.js';
|
||||
import type { AdminService } from '../../src/admin/admin-service.js';
|
||||
import { createAdminApi } from '../src/services/admin-api.js';
|
||||
import { JoinTicketStore } from '../../src/server/join-ticket.js';
|
||||
import { VoiceBridge } from '../../src/server/voice-bridge.js';
|
||||
import type { TSClient } from '../../src/server/ts-client.js';
|
||||
import { PluginRuntime } from '../../src/plugins/runtime.js';
|
||||
import { createPluginRuntimeRouter } from '../../src/plugins/runtime-router.js';
|
||||
import { parsePluginPackage, type PluginPackage, type PluginParticipant } from '../../src/shared/plugins.js';
|
||||
import { createLogger } from '../../src/logger.js';
|
||||
|
||||
test('actual administrator routes support store install, CAS configuration, import and removal with authentication/CSRF',async t=>{
|
||||
const directory=await mkdtemp(path.join(tmpdir(),'webspeak-plugin-http-'));
|
||||
t.after(async()=>{assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});
|
||||
const registry=new PluginRegistry(directory);await registry.initialize();
|
||||
const pack=parsePluginPackage(JSON.parse(await readFile(new URL('../../docs/examples/watch-together.wplugin',import.meta.url),'utf8')));
|
||||
const bytes=JSON.stringify(pack),sha=createHash('sha256').update(bytes).digest('hex');
|
||||
const store=new PluginStore(async url=>String(url)===PLUGIN_STORE_INDEX?Response.json({schemaVersion:1,plugins:[{id:pack.manifest.id,repository:'https://github.com/Huddle-Up-Forge/webspeak-plugin'}]}):String(url).endsWith('/plugin.json')?Response.json({manifest:pack.manifest,package:{ref:'main',path:'watch-together.wplugin',sha256:sha}}):new Response(bytes));
|
||||
const audits:string[]=[];
|
||||
const service={isInitialized:()=>true,isPasswordChangeRequired:()=>false,verifyPassword:async()=>true,database:{addAudit:(name:string)=>audits.push(name)}} as unknown as AdminService;
|
||||
const app=express();app.use(express.json({limit:'600kb'}));
|
||||
app.use('/api/admin',createAdminRouter({service,sessions:new AdminSessionStore(),logger:pino({enabled:false}),getActiveSessions:()=>0,getPeakSessions:()=>0,startedAt:Date.now(),pluginRegistry:registry,pluginStore:store}));
|
||||
const server=app.listen(0,'127.0.0.1');await once(server,'listening');t.after(()=>new Promise<void>(r=>{server.closeAllConnections();server.close(()=>r());}));
|
||||
const address=server.address();assert.ok(address&&typeof address!=='string');const origin=`http://127.0.0.1:${address.port}`;
|
||||
let cookie='',csrf='';const api=createAdminApi({csrfToken:()=>csrf,fetch:async(url,init)=>{const headers=new Headers(init?.headers);headers.set('origin',origin);if(cookie)headers.set('cookie',cookie);const response=await fetch(origin+url,{...init,headers});const c=response.headers.get('set-cookie');if(c)cookie=c.split(';')[0];return response;}});
|
||||
await assert.rejects(api.plugins(),(e:any)=>e.status===401);csrf=(await api.login('admin','test-password')).csrfToken;
|
||||
for(const [method,url,body] of [['POST','/plugins/upload',{package:pack,installedRevision:null}],['PUT','/plugins/a/settings',{}],['DELETE','/plugins/a',{}],['POST','/plugins/store/install',{}]] as const){
|
||||
const denied=await fetch(origin+'/api/admin'+url,{method,headers:{origin,cookie,'content-type':'application/json'},body:JSON.stringify(body)});assert.equal(denied.status,403);
|
||||
}
|
||||
const entry=(await api.pluginStore()).entries[0];const outcomes=await Promise.allSettled([api.installPlugin({id:entry.id,revision:entry.revision,installedRevision:null}),api.installPlugin({id:entry.id,revision:entry.revision,installedRevision:null})]);
|
||||
assert.equal(outcomes.filter(r=>r.status==='fulfilled').length,1);assert.equal(outcomes.filter(r=>r.status==='rejected').length,1);
|
||||
let installed=(await api.plugins()).plugins[0];assert.equal(installed.settings.enabled,false);
|
||||
const configured=await api.configurePlugin(installed.manifest.id,installed.revision,{enabled:true,scope:'instance',targets:[],config:{example:1}});assert.equal(configured.plugin.settings.enabled,true);
|
||||
await assert.rejects(api.configurePlugin(installed.manifest.id,installed.revision,installed.settings),(e:any)=>e.code==='PLUGIN_CHANGED');
|
||||
const imported=await api.uploadPlugin(pack,configured.plugin.revision);assert.equal(imported.plugin.settings.enabled,false);
|
||||
await api.removePlugin(pack.manifest.id,imported.plugin.revision);assert.equal((await api.plugins()).plugins.length,0);
|
||||
assert.ok(audits.includes('ADMIN_PLUGIN_INSTALLED')&&audits.includes('ADMIN_PLUGIN_CONFIGURED')&&audits.includes('ADMIN_PLUGIN_REMOVED'));
|
||||
});
|
||||
|
||||
class TeamSpeakStub extends EventEmitter {
|
||||
async connect(){this.emit('directorySnapshot',{channels:[],clients:[]});}
|
||||
async disconnect(){} getClientId(){return 1;} getChannelId(){return 1n;} isConnected(){return true;}
|
||||
async getServerInfo(){return {name:'Plugin wire test',iconId:null};}async getServerPresentation(){return {bannerUrl:null,welcomeMessage:''};}async getServerIcon(){return null;}
|
||||
async getClientAvatar(){return null;}async sendProtocolCommand(){}async setAccompanimentActive(){}
|
||||
const require=createRequire(import.meta.url);
|
||||
const serverSource=`import {WebSocketServer} from 'ws';import {writeFile,readFile} from 'node:fs/promises';import path from 'node:path';export default async({dataDir,config,events})=>{let joins=0;events.on('participantJoined',()=>joins++);const wss=new WebSocketServer({noServer:true});wss.on('connection',(socket,request)=>socket.on('message',data=>socket.send(JSON.stringify({echo:data.toString(),route:request.url,user:request.webspeak.self.nickname,scope:request.webspeak.scope.key}))));return {handle:async(request,response)=>{let count=Number(await readFile(path.join(dataDir,'value.txt'),'utf8').catch(()=>0));if(request.method==='POST'){count++;await writeFile(path.join(dataDir,'value.txt'),String(count));}response.setHeader('content-type','application/json');response.end(JSON.stringify({route:request.url,user:request.webspeak.self.nickname,scope:request.webspeak.scope.key,cookie:request.headers.cookie??null,authorization:request.headers.authorization??null,configured:config?.secret==='private',count,joins}));},upgrade:(request,socket,head)=>wss.handleUpgrade(request,socket,head,ws=>wss.emit('connection',ws,request)),stop:()=>{for(const client of wss.clients)client.terminate();wss.close();}};};`;
|
||||
async function application(server=false):Promise<PluginPackage>{
|
||||
const pack:any={manifest:{apiVersion:2,id:'test.runtime-app',name:'Runtime application',version:'1.0.0',author:'Test',license:'MIT',description:'HTTP and WebSocket runtime fixture',scopes:['server','instance'],client:{entry:'client/index.html'},...(server?{server:{entry:'server/main.mjs'}}:{})},files:{'client/index.html':{encoding:'utf8',data:'<!doctype html><html><head><title>App</title><script type="module" src="./main.js"></script></head><body>Application</body></html>'},'client/main.js':{encoding:'utf8',data:'const context=await webspeak.ready;document.body.textContent=context.self.nickname;'},'client/theme.css':{encoding:'utf8',data:'body{color:#123}'}}};
|
||||
if(server){pack.files['server/main.mjs']={encoding:'utf8',data:serverSource};const base=path.dirname(require.resolve('ws/package.json'));
|
||||
async function collect(dir:string,relative=''){for(const entry of await readdir(dir,{withFileTypes:true})){if(entry.isSymbolicLink())throw new Error('Unexpected test dependency link');const name=relative?relative+'/'+entry.name:entry.name;if(entry.isDirectory())await collect(path.join(dir,entry.name),name);else pack.files['server/node_modules/ws/'+name]={encoding:'utf8',data:await readFile(path.join(dir,entry.name),'utf8')};}}
|
||||
await collect(base);
|
||||
}
|
||||
return parsePluginPackage(pack);
|
||||
}
|
||||
test('two real voice WebSockets exchange generic plugin state and leaving removes a participant', {timeout:10000},async t=>{
|
||||
const directory=await mkdtemp(path.join(tmpdir(),'webspeak-plugin-ws-'));
|
||||
const registry=new PluginRegistry(directory);await registry.initialize();const pack=parsePluginPackage(JSON.parse(await readFile(new URL('../../docs/examples/watch-together.wplugin',import.meta.url),'utf8')));
|
||||
const installed=await registry.install(pack,null);await registry.configure(pack.manifest.id,{enabled:true,scope:'server',targets:['voice.example:9987'],config:{}},installed.revision);
|
||||
const tickets=new JoinTicketStore(),bridge=new VoiceBridge({joinTickets:tickets,pluginRegistry:registry},pino({enabled:false}),undefined,{createTeamSpeakClient:()=>new TeamSpeakStub() as unknown as TSClient,createEncoder:()=>({encode:()=>Buffer.alloc(0),dispose(){}})});
|
||||
const server=createServer();bridge.attach(server);server.listen(0,'127.0.0.1');await once(server,'listening');const address=server.address();assert.ok(address&&typeof address!=='string');const sockets:WebSocket[]=[];
|
||||
t.after(async()=>{for(const ws of sockets)ws.terminate();await bridge.shutdown();await new Promise<void>(r=>server.close(()=>r()));assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});
|
||||
async function client(nickname:string){const ticket=tickets.create({target:{host:'voice.example',port:9987},nickname,serverPassword:''});const ws=new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);sockets.push(ws);
|
||||
await new Promise<void>(resolve=>ws.on('message',data=>{if(JSON.parse(data.toString()).type==='connected')resolve();}));return ws;}
|
||||
const a=await client('Alice'),b=await client('Bob');let seq=0;
|
||||
function send(ws:WebSocket,action:string,fields={}){const requestId=`r-${++seq}`;return new Promise<any>(resolve=>{const listener=(data:Buffer)=>{const m=JSON.parse(data.toString());if(m.type==='pluginReply'&&m.requestId===requestId){ws.off('message',listener);resolve(m);}};ws.on('message',listener);ws.send(JSON.stringify({type:'pluginRequest',requestId,action,pluginId:pack.manifest.id,...fields}));});}
|
||||
assert.equal((await send(a,'list')).result.length,1);const first=await send(a,'open'),second=await send(b,'open');assert.equal(first.result.snapshot.roomId,second.result.snapshot.roomId);
|
||||
const state={url:'https://video.example/test.mp4',playing:true,position:42,updatedAt:Date.now()};assert.equal((await send(a,'update',{revision:0,state})).ok,true);
|
||||
assert.deepEqual((await send(b,'snapshot')).result.state,state);assert.equal((await send(b,'snapshot')).result.participants.length,2);
|
||||
await send(a,'close');assert.equal((await send(b,'snapshot')).result.participants.length,1);
|
||||
async function environment(t:test.TestContext){
|
||||
const cleanup:Array<()=>Promise<unknown>|void>=[];
|
||||
const directory=await mkdtemp(path.join(tmpdir(),'webspeak-runtime-http-')),registry=new PluginRegistry(directory,Buffer.alloc(32,3));await registry.initialize();
|
||||
const participants=new Map<string,PluginParticipant>([['a'.repeat(43),{id:'alice',nickname:'测试参与者甲',uid:'public-a',target:'one.example:9987',channelId:'1',members:[]}],['b'.repeat(43),{id:'bob',nickname:'Bob',target:'two.example:9987',channelId:'2',members:[]}]]);
|
||||
const runtime=new PluginRuntime({registry,participant:token=>participants.get(token)??null,logger:createLogger(),port:0,host:'127.0.0.1'});await runtime.start();
|
||||
const app=express();app.use(express.json());app.use('/api/plugins',createPluginRuntimeRouter(runtime));const server=app.listen(0,'127.0.0.1');await once(server,'listening');const address=server.address();assert.ok(address&&typeof address!=='string');const base=`http://127.0.0.1:${address.port}`;
|
||||
t.after(async()=>{for(const dispose of cleanup)await dispose();await runtime.close();server.closeAllConnections();await new Promise<void>(resolve=>server.close(()=>resolve()));assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});
|
||||
const call=(route:string,method='GET',body?:unknown,token='a'.repeat(43))=>fetch(base+'/api/plugins'+route,{method,headers:{authorization:'Bearer '+token,origin:base,...(body===undefined?{}:{'content-type':'application/json'})},...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
async function install(backend=false,scope:'server'|'instance'='instance'){
|
||||
const pack=await application(backend),first=await registry.install(pack,null);
|
||||
const enabled=await registry.configure(pack.manifest.id,{enabled:true,trusted:true,scope,targets:scope==='server'?['one.example:9987']:[],config:{public:'setting'},serverConfigAction:'replace',serverConfig:{secret:'private'}},first.revision);await runtime.synchronize(pack.manifest.id);return enabled;
|
||||
}
|
||||
const launch=async(id='test.runtime-app',token='a'.repeat(43))=>{const response=await call('/'+id+'/open','POST',{theme:'dark',language:'zh'},token);assert.equal(response.status,201,await response.clone().text());return response.json() as Promise<{id:string;url:string}>;};
|
||||
return {directory,registry,runtime,participants,base,call,install,launch,cleanup};
|
||||
}
|
||||
|
||||
test('application control authenticates users and serves real modules on a separate origin without server source',async t=>{
|
||||
const env=await environment(t);assert.equal((await env.call('/','GET',undefined,'wrong')).status,401);await env.install();
|
||||
const directory=await(await env.call('/')).json();assert.equal(directory.plugins[0].manifest.apiVersion,2);assert.equal(directory.plugins[0].manifest.permissions,undefined);
|
||||
const launch=await env.launch(),url=new URL(launch.url);assert.notEqual(url.origin,env.base);
|
||||
const html=await(await fetch(url)).text();assert.match(html,/_runtime\/sdk.js/);assert.match(html,/type="module"/);assert.match(html,/Application/);
|
||||
assert.match(await(await fetch(new URL('./main.js',url))).text(),/webspeak.ready/);
|
||||
const root=url.origin+'/apps/'+launch.id;const context=await(await fetch(root+'/_runtime/context')).json();assert.equal(context.self.nickname,'测试参与者甲');assert.equal(context.apiVersion,2);assert.equal(context.theme,'dark');assert.equal(context.config.public,'setting');assert.equal(JSON.stringify(context).includes('private'),false);
|
||||
assert.equal((await fetch(root+'/server/main.mjs')).status,403);assert.equal((await fetch(root+'/client/missing.js')).status,404);
|
||||
assert.equal((await env.call('/apps/'+launch.id,'DELETE',undefined,'b'.repeat(43))).status,403);
|
||||
assert.equal((await env.call('/apps/'+launch.id,'DELETE')).status,200);assert.equal((await fetch(launch.url)).status,403);
|
||||
});
|
||||
|
||||
test('arbitrary backend HTTP and bidirectional WebSocket routes receive authenticated context and no host credentials',async t=>{
|
||||
const env=await environment(t);await env.install(true);const launch=await env.launch(),origin=new URL(launch.url).origin,base=origin+'/apps/'+launch.id+'/server';
|
||||
const response=await fetch(base+'/custom/route?x=1',{method:'POST',headers:{cookie:'webspeak_admin_session=never-forward',authorization:'Bearer never-forward','x-webspeak-context':'spoofed'}});
|
||||
assert.equal(response.status,200);const value=await response.json();assert.equal(value.route,'/custom/route?x=1');assert.equal(value.user,'测试参与者甲');assert.equal(value.cookie,null);assert.equal(value.authorization,null);assert.equal(value.configured,true);assert.equal(value.count,1);assert.equal(value.joins,1);
|
||||
const socket=new WebSocket(base.replace(/^http/,'ws')+'/custom/socket');await once(socket,'open');const reply=once(socket,'message');socket.send('author-defined-message');const [bytes]=await reply;const message=JSON.parse(String(bytes));assert.equal(message.echo,'author-defined-message');assert.equal(message.route,'/custom/socket');assert.equal(message.user,'测试参与者甲');
|
||||
const close=once(socket,'close');await env.call('/apps/'+launch.id,'DELETE');await close;
|
||||
});
|
||||
|
||||
test('server scope is enforced from the actual participant and channel changes invalidate apps',async t=>{
|
||||
const env=await environment(t);await env.install(false,'server');assert.equal((await(await env.call('/','GET',undefined,'b'.repeat(43))).json()).plugins.length,0);
|
||||
assert.equal((await env.call('/test.runtime-app/open','POST',{target:'one.example:9987'},'b'.repeat(43))).status,403);
|
||||
const launch=await env.launch();env.participants.get('a'.repeat(43))!.channelId='3';assert.equal((await fetch(launch.url)).status,403);
|
||||
});
|
||||
|
||||
test('instance apps retain scope across channel changes and runtime context events carry updates',async t=>{
|
||||
const env=await environment(t);await env.install();const launch=await env.launch(),base=new URL(launch.url).origin+'/apps/'+launch.id;
|
||||
const controller=new AbortController(),events=await fetch(base+'/_runtime/events',{signal:controller.signal});assert.equal(events.status,200);const reader=events.body!.getReader();const first=new TextDecoder().decode((await reader.read()).value);assert.match(first,/event: context/);assert.match(first,/测试参与者甲/);
|
||||
env.participants.get('a'.repeat(43))!.channelId='3';const updated=await(await fetch(base+'/_runtime/context')).json();assert.equal(updated.connection.channelId,'3');assert.equal(updated.scope.key,'instance');
|
||||
controller.abort();await reader.cancel().catch(()=>undefined);
|
||||
await env.call('/apps/'+launch.id,'PATCH',{theme:'light',language:'en'});const appearance=await(await fetch(base+'/_runtime/context')).json();assert.equal(appearance.theme,'light');assert.equal(appearance.language,'en');
|
||||
});
|
||||
|
||||
test('disable, update and disconnect revoke existing app authorities and preserve backend data',async t=>{
|
||||
const env=await environment(t),installed=await env.install(true),launch=await env.launch(),origin=new URL(launch.url).origin;
|
||||
await fetch(origin+'/apps/'+launch.id+'/server/save',{method:'POST'});
|
||||
const disabled=await env.registry.configure(installed.manifest.id,{...installed.settings,enabled:false},installed.revision);assert.equal((await fetch(launch.url)).status,403);await env.runtime.synchronize(installed.manifest.id);assert.equal(env.runtime.status(installed.manifest.id).state,'disabled');
|
||||
const enabled=await env.registry.configure(installed.manifest.id,{...disabled.settings,enabled:true},disabled.revision);await env.runtime.synchronize(enabled.manifest.id);const replacement=await env.launch();const count=await(await fetch(new URL(replacement.url).origin+'/apps/'+replacement.id+'/server/read')).json();assert.equal(count.count,1);
|
||||
env.participants.delete('a'.repeat(43));assert.equal((await fetch(replacement.url)).status,403);
|
||||
const update=await env.registry.install({...await application(true),manifest:{...(await application(true)).manifest,version:'1.1.0'}},enabled.revision);assert.equal(update.settings.enabled,false);assert.equal(update.settings.trusted,false);
|
||||
});
|
||||
|
||||
test('public runtime origin changes use revision checks and cannot collapse into the host origin',async t=>{
|
||||
const env=await environment(t);await env.install();const settings=env.runtime.settings();await env.runtime.configureOrigin('https://plugins.example.com',settings.revision);
|
||||
await assert.rejects(env.runtime.configureOrigin('',settings.revision),/PLUGIN_CHANGED/);
|
||||
const launch=await env.launch();assert.equal(new URL(launch.url).origin,'https://plugins.example.com');
|
||||
await env.runtime.configureOrigin(env.base,env.runtime.settings().revision);assert.equal((await env.call('/test.runtime-app/open','POST',{})).status,403);
|
||||
await assert.rejects(env.runtime.configureOrigin('https://user:password@example.com',env.runtime.settings().revision));
|
||||
});
|
||||
|
||||
test('public origins require HTTPS while loopback development permits HTTP',async t=>{const env=await environment(t);await assert.rejects(env.runtime.configureOrigin('http://apps.example.com',env.runtime.settings().revision),/PLUGIN_HTTPS_REQUIRED/);assert.equal((await env.runtime.configureOrigin('http://localhost:3042',env.runtime.settings().revision)).publicOrigin,'http://localhost:3042');});
|
||||
|
||||
test('open operations are idempotent, bound to one app and cancellable before and during startup',async t=>{
|
||||
const env=await environment(t);await env.install();
|
||||
const options={openId:'idempotent-operation',theme:'light',language:'en'};
|
||||
const first=await env.runtime.open('a'.repeat(43),'test.runtime-app',options,env.base),second=await env.runtime.open('a'.repeat(43),'test.runtime-app',options,env.base);assert.equal(second.id,first.id);
|
||||
const pack=await application(),other=await env.registry.install({...pack,manifest:{...pack.manifest,id:'test.other-app'}},null);await env.registry.configure(other.manifest.id,{...other.settings,scope:'instance',enabled:true,trusted:true},other.revision);
|
||||
await assert.rejects(env.runtime.open('a'.repeat(43),'test.other-app',options,env.base),/PLUGIN_OPEN_CONFLICT/);
|
||||
env.runtime.cancelOpen('a'.repeat(43),'cancelled-operation');await assert.rejects(env.runtime.open('a'.repeat(43),'test.runtime-app',{openId:'cancelled-operation'},env.base),/PLUGIN_CANCELLED/);
|
||||
const original=env.runtime.synchronize.bind(env.runtime);let release!:()=>void,entered!:()=>void;const waiting=new Promise<void>(resolve=>entered=resolve),barrier=new Promise<void>(resolve=>release=resolve);
|
||||
env.runtime.synchronize=async id=>{entered();await barrier;return original(id);};
|
||||
const pending=env.runtime.open('a'.repeat(43),'test.runtime-app',{openId:'pending-operation'},env.base);await waiting;env.runtime.cancelOpen('a'.repeat(43),'pending-operation');release();await assert.rejects(pending,/PLUGIN_CANCELLED/);env.runtime.synchronize=original;
|
||||
env.runtime.cancelOpen('a'.repeat(43),options.openId);assert.equal((await fetch(first.url)).status,403);
|
||||
});
|
||||
import { WebSpeakDatabase } from '../../src/persistence/database.js';
|
||||
import { AdminService } from '../../src/admin/admin-service.js';
|
||||
import { AdminSessionStore } from '../../src/admin/admin-session.js';
|
||||
import { createAdminRouter } from '../../src/admin/admin-router.js';
|
||||
import { createAdminApi } from '../src/services/admin-api.js';
|
||||
import { PluginStore } from '../../src/plugins/store.js';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
test('v2 admin HTTP requires authentication, origin, CSRF and renewed trust; secrets remain private',async t=>{
|
||||
const env=await environment(t),database=new WebSpeakDatabase(path.join(env.directory,'admin.db')),logger=createLogger();
|
||||
env.cleanup.push(()=>database.close());
|
||||
const service=new AdminService(database,Buffer.alloc(32,7),logger,path.join(env.directory,'absent.json'),undefined,'test');await service.initialize();await service.changePassword('runtime-test-password');
|
||||
const pack=await application(true),bytes=JSON.stringify(pack),digest=createHash('sha256').update(bytes).digest('hex');
|
||||
let packageBytes=bytes;
|
||||
const store=new PluginStore(async(url)=>{
|
||||
const address=String(url);if(address.endsWith('/index.json'))return Response.json({schemaVersion:2,plugins:[{id:pack.manifest.id,repository:'https://github.com/example/app'}]});
|
||||
if(address.endsWith('/plugin.json'))return Response.json({manifest:pack.manifest,package:{ref:'fixed-commit',path:'packages/app.wplugin',sha256:digest}});
|
||||
return new Response(packageBytes);
|
||||
});
|
||||
const app=express();app.use((req,res,next)=>req.path.startsWith('/api/admin/plugins')?next():express.json()(req,res,next));
|
||||
app.use('/api/admin',createAdminRouter({service,sessions:new AdminSessionStore(),logger,getActiveSessions:()=>0,getPeakSessions:()=>0,startedAt:Date.now(),version:'test',pluginRegistry:env.registry,pluginRuntime:env.runtime,pluginStore:store}));
|
||||
const server=app.listen(0,'127.0.0.1');await once(server,'listening');const address=server.address();assert.ok(address&&typeof address!=='string');const origin=`http://127.0.0.1:${address.port}`;
|
||||
env.cleanup.unshift(async()=>{server.closeAllConnections();await new Promise<void>(resolve=>server.close(()=>resolve()));});
|
||||
let cookie='',csrf='';const api=createAdminApi({csrfToken:()=>csrf,fetch:async(url,init)=>{const headers=new Headers(init?.headers);headers.set('origin',origin);if(cookie)headers.set('cookie',cookie);const response=await fetch(origin+url,{...init,headers});const setCookie=response.headers.get('set-cookie');if(setCookie)cookie=setCookie.split(';')[0];return response;}});
|
||||
assert.equal((await fetch(origin+'/api/admin/plugins')).status,401);
|
||||
assert.equal((await fetch(origin+'/api/admin/plugins/upload',{method:'POST',headers:{'content-type':'application/json'},body:'invalid-json'})).status,401,'bundle parsing must follow authentication');
|
||||
csrf=(await api.login('admin','runtime-test-password')).csrfToken;
|
||||
const write=(headers:Record<string,string>)=>fetch(origin+'/api/admin/plugins/upload',{method:'POST',headers:{cookie,'content-type':'application/json',...headers},body:JSON.stringify({package:pack,installedRevision:null})});
|
||||
assert.equal((await write({origin})).status,403);assert.equal((await write({origin:'https://other.example','x-csrf-token':csrf})).status,403);
|
||||
const catalog=await api.pluginStore();assert.equal(catalog.entries[0].manifest?.apiVersion,2);
|
||||
packageBytes='tampered';await assert.rejects(api.installPlugin({id:pack.manifest.id,revision:catalog.entries[0].revision,installedRevision:null}),/PLUGIN_CHECKSUM/);packageBytes=bytes;
|
||||
const installed=(await api.installPlugin({id:pack.manifest.id,revision:catalog.entries[0].revision,installedRevision:null})).plugin;assert.equal(installed.settings.trusted,false);
|
||||
await assert.rejects(api.configurePlugin(pack.manifest.id,installed.revision,{...installed.settings,enabled:true}),/PLUGIN_TRUST_REQUIRED/);
|
||||
const enabled=(await api.configurePlugin(pack.manifest.id,installed.revision,{...installed.settings,enabled:true,trusted:true,scope:'instance',serverConfigAction:'replace',serverConfig:{secret:'private-test-value'}})).plugin;
|
||||
assert.equal(enabled.runtime?.state,'running');assert.equal((await api.restartPlugin(pack.manifest.id,enabled.revision)).plugin.runtime?.state,'running');
|
||||
const list=await api.plugins();assert.equal(list.plugins[0].settings.hasServerConfig,true);assert.equal(JSON.stringify(list).includes('private-test-value'),false);
|
||||
const settings=(await api.pluginRuntime()).runtime,saved=(await api.configurePluginRuntime('https://apps.example.com',settings.revision)).runtime;assert.equal(saved.publicOrigin,'https://apps.example.com');await assert.rejects(api.configurePluginRuntime('',settings.revision),/PLUGIN_CHANGED/);
|
||||
const updated=(await api.uploadPlugin({...pack,manifest:{...pack.manifest,version:'1.1.0'}},enabled.revision)).plugin;assert.equal(updated.settings.enabled,false);assert.equal(updated.settings.trusted,false);assert.equal(updated.settings.hasServerConfig,true);
|
||||
await assert.rejects(api.removePlugin(pack.manifest.id,enabled.revision),/PLUGIN_CHANGED/);await api.removePlugin(pack.manifest.id,updated.revision);assert.equal((await api.plugins()).plugins.length,0);
|
||||
});
|
||||
@@ -30,6 +30,7 @@ class Peer {
|
||||
parameters: RTCRtpSendParameters | null = null;
|
||||
codecPreferences: RTCRtpCodecCapability[] = [];
|
||||
private readonly transceivers: Array<{
|
||||
direction?: RTCRtpTransceiverDirection;
|
||||
sender: { track: { kind: string } | null };
|
||||
receiver: { track: { kind: string } | null };
|
||||
setCodecPreferences: (codecs: RTCRtpCodecCapability[]) => void;
|
||||
@@ -41,8 +42,9 @@ class Peer {
|
||||
setLocalDescription(description: unknown) { this.localDescription = description; return Promise.resolve(); }
|
||||
setRemoteDescription() { return Promise.resolve(); }
|
||||
addIceCandidate() { return Promise.resolve(); }
|
||||
addTransceiver(kind: string) {
|
||||
addTransceiver(kind: string, options?: RTCRtpTransceiverInit) {
|
||||
const transceiver = {
|
||||
direction: options?.direction ?? 'sendrecv',
|
||||
sender: { track: null },
|
||||
receiver: { track: { kind } },
|
||||
setCodecPreferences: (codecs: RTCRtpCodecCapability[]) => { this.codecPreferences = codecs; },
|
||||
@@ -65,7 +67,7 @@ class Peer {
|
||||
}
|
||||
|
||||
let controller: ReturnType<typeof createScreenShareController>;
|
||||
let sent: Array<{ type: string; requestId?: string }>;
|
||||
let sent: Array<{ type: string; requestId?: string; audio?: boolean }>;
|
||||
const globals = new Map<string, PropertyDescriptor | undefined>();
|
||||
function replaceGlobal(name: string, value: unknown) {
|
||||
globals.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
@@ -210,6 +212,44 @@ test("native TeamSpeak viewers prefer VP8 for decoder compatibility", async () =
|
||||
]);
|
||||
});
|
||||
|
||||
for (const surface of ['window', 'monitor', 'browser']) {
|
||||
test(`native viewing of ${surface} capture without audio still negotiates an audio section`, async () => {
|
||||
const capture = stream();
|
||||
Object.assign(capture.track, { getSettings: () => ({ displaySurface: surface }) });
|
||||
Object.assign(navigator.mediaDevices, { getDisplayMedia: async () => capture });
|
||||
await controller.api.startScreenShare(false); confirmStart('local');
|
||||
assert.equal(sent.find(message => message.type === 'screenShareStart')?.audio, false);
|
||||
controller.handleMessage({ type: 'screenShareNativeViewerJoined', streamId: 'local', viewerPeerId: 'ts-viewer-7' });
|
||||
await nextTurn();
|
||||
const transceivers = Peer.instances[0].getTransceivers();
|
||||
assert.equal(transceivers.length, 2);
|
||||
assert.equal(transceivers[0].sender.track?.kind, 'video');
|
||||
assert.equal(transceivers[1].receiver.track?.kind, 'audio');
|
||||
assert.equal(transceivers[1].direction, 'sendonly');
|
||||
assert.equal(transceivers[1].sender.track, null, 'negotiating audio must not start a microphone or synthesize captured audio');
|
||||
assert.equal(capture.getTracks().length, 1);
|
||||
});
|
||||
}
|
||||
|
||||
test('native viewing retains actual captured audio without adding a duplicate audio section', async () => {
|
||||
const capture = stream(), audio = new Track(); audio.kind = 'audio';
|
||||
Object.assign(navigator.mediaDevices, { getDisplayMedia: async () => ({ ...capture, getTracks: () => [audio, capture.track], getAudioTracks: () => [audio] }) });
|
||||
await controller.api.startScreenShare(); confirmStart('local');
|
||||
controller.handleMessage({ type: 'screenShareNativeViewerJoined', streamId: 'local', viewerPeerId: 'ts-viewer-7' });
|
||||
await nextTurn();
|
||||
const transceivers = Peer.instances[0].getTransceivers();
|
||||
assert.deepEqual(transceivers.map(item => item.sender.track?.kind), ['video', 'audio']);
|
||||
assert.equal(sent.find(message => message.type === 'screenShareStart')?.audio, true);
|
||||
});
|
||||
|
||||
test('browser viewers do not get a synthetic audio section for video-only sharing', async () => {
|
||||
await controller.api.startScreenShare(false); confirmStart('local');
|
||||
controller.handleMessage({ type: 'screenShareSignal', streamId: 'local', fromPeerId: 'web-viewer', signal: { kind: 'offer', sdp: 'browser offer' } });
|
||||
await nextTurn();
|
||||
assert.equal(Peer.instances[0].getTransceivers().length, 1);
|
||||
assert.equal(Peer.instances[0].getTransceivers()[0].sender.track?.kind, 'video');
|
||||
});
|
||||
|
||||
test("viewer visibility follows the selected stream so the player and card cannot disagree", async () => {
|
||||
assert.equal(controller.api.screenShareViewing.value, false);
|
||||
assert.equal(controller.api.screenShareViewingStreamId.value, "");
|
||||
|
||||
@@ -2,10 +2,12 @@ import assert from "node:assert/strict";
|
||||
import { before, after, beforeEach, afterEach, test } from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createServer } from "vite";
|
||||
import { effectScope, ref } from "vue";
|
||||
|
||||
let vite, runtime, catalog, handler, installed, writes, storage, elements, root, usePublicSkin, scope;
|
||||
let vite, runtime, catalog, authorization, handler, installed, writes, storage, elements, root, usePublicSkin, useWebClientPublicConfig, scope;
|
||||
const { version: appVersion } = JSON.parse(await readFile(new URL("../../package.json", import.meta.url), "utf8"));
|
||||
const globals = new Map();
|
||||
function global(name, value) {
|
||||
if (!globals.has(name)) globals.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
@@ -41,7 +43,9 @@ before(async () => {
|
||||
optimizeDeps: { noDiscovery: true, include: [] }, appType: "custom" });
|
||||
runtime = await vite.ssrLoadModule("/src/services/skin-runtime.ts");
|
||||
catalog = await vite.ssrLoadModule("/src/services/skin-catalog.ts");
|
||||
authorization = await vite.ssrLoadModule('/src/services/instance-authorization.ts');
|
||||
({ usePublicSkin } = await vite.ssrLoadModule("/src/composables/usePublicSkin.ts"));
|
||||
({ useWebClientPublicConfig } = await vite.ssrLoadModule("/src/composables/useWebClientPublicConfig.ts"));
|
||||
});
|
||||
beforeEach(async () => {
|
||||
installed = new Map(); writes = []; storage = new Map(); elements = new Map(); root = new Element();
|
||||
@@ -56,6 +60,8 @@ beforeEach(async () => {
|
||||
preferences: async () => ({ schemaVersion: 1 }), persist: async value => writes.push(value) });
|
||||
handler = async () => json({ skins: [] });
|
||||
global("fetch", (...args) => handler(...args));
|
||||
// Existing lifecycle cases exercise explicitly authorized custom skins.
|
||||
authorization.setInstanceAuthorization(true);
|
||||
// A failed directory load keeps locally installed packages available.
|
||||
handler = async () => { throw new Error("offline"); };
|
||||
await catalog.listPublicSkins();
|
||||
@@ -69,6 +75,35 @@ after(async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('without instance consent, cached third-party packages are never read or installed', async () => {
|
||||
authorization.setInstanceAuthorization(false);
|
||||
let reads = 0;
|
||||
globalThis.skinStorage.get = async () => { reads++; return skin('community.kaak-voice'); };
|
||||
storage.set('webspeak:skin-choice', 'community.kaak-voice');
|
||||
storage.set('webspeak:active-skin', 'community.kaak-voice');
|
||||
const view = page(); await view.initialize(); await view.select('community.kaak-voice');
|
||||
assert.equal(reads, 0);
|
||||
assert.equal(view.activeSkinId.value, 'builtin.light');
|
||||
assert.equal(view.activeSkin.value, null);
|
||||
assert.deepEqual(view.catalogSkins.value.map(skin => skin.id), ['builtin.light', 'builtin.dark', 'community.illusia-voice']);
|
||||
assert.equal(view.skinLoadError.value, null, 'declining is not a skin loading error');
|
||||
});
|
||||
|
||||
test('revoking consent cancels an in-flight custom load and removes an already active skin', async () => {
|
||||
installed.set('sample.a', skin('sample.a'));
|
||||
const view = page({ timeoutMs: 3000 }); await view.select('sample.a');
|
||||
assert.equal(elements.has('webspeak-active-custom-skin'), true);
|
||||
const read = deferred(); globalThis.skinStorage.get = () => read.promise;
|
||||
const loading = view.select('sample.b');
|
||||
authorization.setInstanceAuthorization(false);
|
||||
await loading; await nextTurn();
|
||||
read.resolve(skin('sample.b')); await nextTurn();
|
||||
assert.equal(view.activeSkin.value, null);
|
||||
assert.equal(view.activeSkinId.value, 'builtin.light');
|
||||
assert.equal(elements.has('webspeak-active-custom-skin'), false);
|
||||
assert.equal(elements.has('webspeak-active-custom-skin-base'), false);
|
||||
});
|
||||
|
||||
test("a late custom activation cannot replace a newer built-in choice", async () => {
|
||||
const read = deferred(); globalThis.skinStorage.get = () => read.promise;
|
||||
const old = runtime.activateSkin("sample.a").catch(error => error);
|
||||
@@ -201,6 +236,52 @@ test("normal initialization uses the instance default and cached custom content"
|
||||
assert.equal(storage.has("webspeak:skin-choice"), false);
|
||||
assert.equal(root.dataset.wsSkin, item.id);
|
||||
});
|
||||
test("first entry activates a compatible remembered skin before public config arrives", async () => {
|
||||
const item = { ...skin("sample.current"), minAppVersion: appVersion, author: "test", license: "MIT" };
|
||||
installed.set(item.id, item);
|
||||
storage.set("webspeak:skin-choice", item.id);
|
||||
const response = deferred();
|
||||
global("location", { search: "" });
|
||||
handler = async url => url === "/api/public-config" ? response.promise
|
||||
: json({ skins: [item], defaultSkinId: "builtin.light" });
|
||||
const config = useWebClientPublicConfig({ serverHost: ref(""), serverPort: ref("9987"),
|
||||
accelerationRelayId: ref(""), language: ref("en"), t: key => key });
|
||||
const loading = config.loadPublicConfig();
|
||||
const view = page({ timeoutMs: 1_000, appVersion: () => config.appVersion.value });
|
||||
try {
|
||||
await view.initialize();
|
||||
assert.equal(config.serverConfigLoading.value, true, "the config response is still pending");
|
||||
assert.equal(view.activeSkinId.value, item.id);
|
||||
assert.equal(view.skinLoadError.value, null);
|
||||
assert.equal(root.dataset.wsSkin, item.id);
|
||||
await view.select("builtin.dark");
|
||||
await view.select(item.id);
|
||||
assert.equal(view.activeSkinId.value, item.id, "initial entry and manual selection use the same version");
|
||||
} finally {
|
||||
response.resolve(json({ version: appVersion }));
|
||||
await loading;
|
||||
}
|
||||
});
|
||||
test("demo initialization uses the running build version without a public config provider", async () => {
|
||||
const item = { ...skin("sample.current"), minAppVersion: appVersion, author: "test", license: "MIT" };
|
||||
installed.set(item.id, item);
|
||||
handler = async () => json({ skins: [item], defaultSkinId: item.id });
|
||||
const view = page({ timeoutMs: 1_000 });
|
||||
await view.initialize();
|
||||
assert.equal(view.activeSkinId.value, item.id);
|
||||
assert.equal(view.skinLoadError.value, null);
|
||||
});
|
||||
test("using the running build version still rejects a skin requiring a newer runtime", async () => {
|
||||
const item = { ...skin("sample.future"), minAppVersion: "999.0.0", author: "test", license: "MIT" };
|
||||
installed.set(item.id, item);
|
||||
storage.set("webspeak:skin-choice", item.id);
|
||||
handler = async () => json({ skins: [item], defaultSkinId: item.id });
|
||||
const view = page({ timeoutMs: 1_000 });
|
||||
await view.initialize();
|
||||
assert.equal(view.activeSkinId.value, "builtin.light");
|
||||
assert.equal(view.skinLoadError.value.skinId, item.id);
|
||||
assert.equal(storage.get("webspeak:skin-choice"), item.id);
|
||||
});
|
||||
test("reset prevents outstanding choices from restoring cleared state", async () => {
|
||||
const read = deferred(); globalThis.skinStorage.get = () => read.promise;
|
||||
const view = page(), old = view.select("sample.a");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { after, before, test } from "node:test";
|
||||
import { after, before, beforeEach, test } from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as Vue from "vue";
|
||||
import { createRenderer, nextTick, ssrContextKey, createSSRApp } from "vue";
|
||||
@@ -15,6 +15,7 @@ let SkinPluginEditor;
|
||||
let SkinPluginOutlet;
|
||||
let authoring;
|
||||
let approvals;
|
||||
let authorization;
|
||||
let focusedNode;
|
||||
let supportsPopoverApi = true;
|
||||
const localStorageDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
|
||||
@@ -148,6 +149,7 @@ before(async () => {
|
||||
({ default: SkinPluginEditor } = await vite.ssrLoadModule("/src/components/SkinPluginEditor.vue"));
|
||||
({ default: SkinPluginOutlet } = await vite.ssrLoadModule("/src/components/SkinPluginOutlet.ts"));
|
||||
approvals = await vite.ssrLoadModule("/src/services/skin-plugin-approval.ts");
|
||||
authorization = await vite.ssrLoadModule('/src/services/instance-authorization.ts');
|
||||
const require = createRequire(import.meta.url);
|
||||
const { parse, compileScript, compileTemplate } = require("../node_modules/@vue/compiler-sfc");
|
||||
const filename = fileURLToPath(new URL("../src/components/SkinPluginEditor.vue", import.meta.url));
|
||||
@@ -170,6 +172,25 @@ after(async () => {
|
||||
if (localStorageDescriptor) Object.defineProperty(globalThis, "localStorage", localStorageDescriptor);
|
||||
else Reflect.deleteProperty(globalThis, "localStorage");
|
||||
});
|
||||
beforeEach(() => authorization.setInstanceAuthorization(true));
|
||||
|
||||
test('instance refusal overrides cached component grants and revocation removes mounted UI', async () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: new MemoryStorage() });
|
||||
const skinId = 'community.consent-regression', skinVersion = '1.0.0';
|
||||
const component = { id: 'private-panel', name: 'Panel', page: 'voice', accessibleName: 'Panel', permissions: ['session.status.read'], actions: {}, root: { tag: 'div', children: [{ text: 'Third-party channel content' }] } };
|
||||
approvals.approveSkinPluginComponents(skinId, skinVersion, [component]);
|
||||
authorization.setInstanceAuthorization(false);
|
||||
const root = hostNode('root');
|
||||
const app = renderer.createApp({ render: () => Vue.h(SkinPluginOutlet, { skinId, skinVersion, page: 'voice', document: { schemaVersion: 3, components: [component] }, assets: {}, data: {}, actions: {} }) });
|
||||
app.mount(root);
|
||||
try {
|
||||
await nextTick(); assert.doesNotMatch(nodeText(root), /Third-party channel content/);
|
||||
authorization.setInstanceAuthorization(true);
|
||||
await nextTick(); await nextTick(); assert.match(nodeText(root), /Third-party channel content/);
|
||||
authorization.setInstanceAuthorization(false);
|
||||
await nextTick(); assert.doesNotMatch(nodeText(root), /Third-party channel content/);
|
||||
} finally { app.unmount(); }
|
||||
});
|
||||
|
||||
test("component editor creates, changes, and deletes a skin component tree through its UI", async () => {
|
||||
focusedNode = null;
|
||||
@@ -939,7 +960,7 @@ test("deleting the last surface component immediately restores the host page", a
|
||||
}
|
||||
});
|
||||
|
||||
test("surface permissions auto-approve in development without showing prompts or recovery controls", async () => {
|
||||
test("authorized instance grants declared surface permissions without per-skin prompts or recovery controls", async () => {
|
||||
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
|
||||
const skinId = "community.access-lifecycle";
|
||||
const skinVersion = "1.0.0";
|
||||
@@ -993,7 +1014,7 @@ test("surface permissions auto-approve in development without showing prompts or
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const activeSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice");
|
||||
assert.ok(activeSurface, "the validated surface receives its declared access in development");
|
||||
assert.ok(activeSurface, "the validated surface receives access after the instance decision");
|
||||
assert.match(nodeText(activeSurface), /Protected custom page/);
|
||||
assert.equal(visit(root, node => node.props["data-native-host"] === "true"), null);
|
||||
assert.equal(visit(teleportRoot, node => node.props["data-ws-plugin-consent"] === "true"), null,
|
||||
|
||||
Reference in new issue
Block a user