@dsh-teamwork/dsh-teamwork 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +5 -2
  2. package/README.zh-CN.md +1 -1
  3. package/docs/development.md +72 -2
  4. package/docs/en/guide.md +43 -2
  5. package/docs/zh-CN/guide.md +18 -2
  6. package/lib/audit-archive.js +174 -0
  7. package/lib/audit-archive.js.map +1 -0
  8. package/lib/audit-cli.js +91 -0
  9. package/lib/audit-cli.js.map +1 -0
  10. package/lib/bridge.js +32 -10
  11. package/lib/bridge.js.map +1 -1
  12. package/lib/client.js +37 -15
  13. package/lib/client.js.map +1 -1
  14. package/lib/config-sync.js +1 -1
  15. package/lib/config-sync.js.map +1 -1
  16. package/lib/index.js +333 -94
  17. package/lib/index.js.map +1 -1
  18. package/lib/locale.js +18 -0
  19. package/lib/locale.js.map +1 -0
  20. package/lib/login-callback.js +1 -1
  21. package/lib/login-callback.js.map +1 -1
  22. package/lib/messages.js +119 -0
  23. package/lib/messages.js.map +1 -0
  24. package/lib/panel.js +27 -20
  25. package/lib/panel.js.map +1 -1
  26. package/lib/phone-security.js +120 -2
  27. package/lib/phone-security.js.map +1 -1
  28. package/lib/pin-lock.js +89 -0
  29. package/lib/pin-lock.js.map +1 -0
  30. package/lib/platform-models.js +10 -7
  31. package/lib/platform-models.js.map +1 -1
  32. package/lib/plugin-status.js +4 -4
  33. package/lib/plugin-status.js.map +1 -1
  34. package/lib/preset-session.js +2 -1
  35. package/lib/preset-session.js.map +1 -1
  36. package/lib/relay.js +14 -9
  37. package/lib/relay.js.map +1 -1
  38. package/lib/shared-mode.js +151 -0
  39. package/lib/shared-mode.js.map +1 -0
  40. package/lib/shared-owner.js +122 -0
  41. package/lib/shared-owner.js.map +1 -0
  42. package/lib/shared-roster.js +112 -0
  43. package/lib/shared-roster.js.map +1 -0
  44. package/lib/task-session.js +21 -19
  45. package/lib/task-session.js.map +1 -1
  46. package/lib/types/audit-archive.d.ts +78 -0
  47. package/lib/types/audit-archive.d.ts.map +1 -0
  48. package/lib/types/audit-cli.d.ts +14 -0
  49. package/lib/types/audit-cli.d.ts.map +1 -0
  50. package/lib/types/bridge.d.ts +7 -3
  51. package/lib/types/bridge.d.ts.map +1 -1
  52. package/lib/types/client.d.ts +21 -4
  53. package/lib/types/client.d.ts.map +1 -1
  54. package/lib/types/index.d.ts.map +1 -1
  55. package/lib/types/locale.d.ts +13 -0
  56. package/lib/types/locale.d.ts.map +1 -0
  57. package/lib/types/messages.d.ts +67 -0
  58. package/lib/types/messages.d.ts.map +1 -0
  59. package/lib/types/panel.d.ts +64 -8
  60. package/lib/types/panel.d.ts.map +1 -1
  61. package/lib/types/phone-security.d.ts +37 -0
  62. package/lib/types/phone-security.d.ts.map +1 -1
  63. package/lib/types/pin-lock.d.ts +36 -0
  64. package/lib/types/pin-lock.d.ts.map +1 -0
  65. package/lib/types/platform-models.d.ts.map +1 -1
  66. package/lib/types/preset-session.d.ts.map +1 -1
  67. package/lib/types/relay.d.ts +15 -1
  68. package/lib/types/relay.d.ts.map +1 -1
  69. package/lib/types/shared-mode.d.ts +50 -0
  70. package/lib/types/shared-mode.d.ts.map +1 -0
  71. package/lib/types/shared-owner.d.ts +42 -0
  72. package/lib/types/shared-owner.d.ts.map +1 -0
  73. package/lib/types/shared-roster.d.ts +49 -0
  74. package/lib/types/shared-roster.d.ts.map +1 -0
  75. package/lib/types/task-session.d.ts +2 -2
  76. package/lib/types/task-session.d.ts.map +1 -1
  77. package/lib/web/client.js +1086 -355
  78. package/package.json +8 -1
package/README.md CHANGED
@@ -17,8 +17,11 @@ The team assistant helps with sharing, usage and administration in conversation.
17
17
 
18
18
  ![Teamwork panel in a real DSH host, with demonstration team resources](https://raw.githubusercontent.com/dsh-teamwork/dsh-teamwork/main/assets/readme/teamwork-panel.png)
19
19
 
20
- The plugin panel currently uses Simplified Chinese. The web console supports
21
- English and Simplified Chinese. Screenshots use a local demonstration team.
20
+ The plugin panel and the web console speak English and Simplified Chinese:
21
+ the panel follows the language of your Teamwork account (**Account** in the
22
+ panel). Terminal `/teamwork` output is always English; model replies follow the
23
+ conversation. Screenshots use a local
24
+ demonstration team.
22
25
 
23
26
  ## What you can do
24
27
 
package/README.zh-CN.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  ![真实 DSH 宿主中的 Teamwork 面板,使用本地演示团队](https://raw.githubusercontent.com/dsh-teamwork/dsh-teamwork/main/assets/readme/teamwork-panel.png)
17
17
 
18
- 插件面板目前使用简体中文;网页控制台支持英文和简体中文。截图均来自本地演示团队。
18
+ 插件面板和网页控制台都支持英文和简体中文;面板跟随你的 Teamwork 账号语言(面板中的“我的账号”)。终端 `/teamwork` 命令的输出统一为英文;模型的回复跟随对话语言。截图均来自本地演示团队。
19
19
 
20
20
  ## 可以做什么
21
21
 
@@ -24,6 +24,14 @@ versions are pinned to rc.3 and Zod to 4.6.6 to avoid recursive type expansion
24
24
  across mismatched versions. Never add `@deepseek-ai/dsh-*` to runtime dependencies:
25
25
  hoisted installations can shadow the upgraded host even when the plugin is disabled.
26
26
 
27
+ For a live host, `pnpm dev` links this checkout into a `web` profile under the
28
+ gitignored `.dsh-home/` (as `DSH_HOME`, so `~/.dsh` is untouched), watch-builds `lib/`
29
+ with `dsh-hmr` reloading it, and boots `dsh web`; arguments after `pnpm dev` reach
30
+ `dsh web`. Put local overrides such as `apiEndpoint` in the gitignored
31
+ `cordis.local.patch.yml`, which outranks the generated `.dsh-home/cordis.patch.yml`.
32
+ `DSH_CLI` selects a specific host. `pnpm dev:reset` deletes the dev home, including
33
+ its sign-in cache. On exit the browser bundle is rebuilt without source maps.
34
+
27
35
  The real-host suites install the packed plugin in temporary profiles and use
28
36
  an isolated local fixture registry and package store:
29
37
 
@@ -66,8 +74,13 @@ retain the previous snapshot. Sync never installs plugins or uploads conversatio
66
74
  Team models use `teamwork-platform` with the configuration ID as wire model.
67
75
  `src/platform-models.ts` adapts text, tool calls and streamed output to the chosen
68
76
  service's `/api/llm/chat/completions`. There is no provider-direct fallback or
69
- local provider-key lookup. Model capability values come from team configuration;
70
- missing context/output limits use 32K/4096, with output bounded by context.
77
+ local provider-key lookup. Model capability values come from team configuration.
78
+ A model, or a preset's model, without `contextWindow` is not guessed: the adapter
79
+ does not offer it; selection, readiness, `agent/request` and sync report
80
+ `modelLimitProblem` (`say('model.noContextWindow')`), and the panel words
81
+ `contextWindowMissing` itself. (A guessed 32K window left DSH's compaction,
82
+ which reserves 64K headroom by default, no budget: `MODEL_SWITCH_COMPACTION_FAILED`.)
83
+ A missing output limit uses 4096, bounded by the context window.
71
84
  Multimodal input and other provider protocols are not implemented by this adapter.
72
85
 
73
86
  Presets use native `agentPresets` registration, mounting, selection and revisions.
@@ -121,6 +134,63 @@ still clears the token until the file changes. In this mode the relay is never
121
134
  opened, and sign-in, sign-out and server changes are refused: the server reaches
122
135
  a cloud computer itself, and the token belongs to the host, not a member.
123
136
 
137
+ ## Shared mode
138
+
139
+ `src/shared-mode.ts` makes a DSH its team's shared DSH (the server's
140
+ `docs/tech/shared-dsh.md`, part of the community edition). `/teamwork share enable <key>` trades a team
141
+ host key for a one-hour host token (platform ADR 0047): the server's nonce is
142
+ signed with this DSH's identity key from `<cache>.phone-keys.json`, and the first
143
+ exchange binds the key to that identity, so a copied key is refused elsewhere.
144
+ The key is saved to `<cache>.shared.json` (mode 0600) only once accepted, the
145
+ token reaches `TeamworkClient.useToken` like a host-provided one, and it is
146
+ renewed ten minutes before it ends, or a minute after a failure that may pass;
147
+ a key the server no longer accepts drops the token. Enabling signs a personal
148
+ account out first, and while shared, sign-in and sign-out are refused and the
149
+ relay connects with the host token. A host-provided token (`tokenFile`)
150
+ excludes shared mode.
151
+
152
+ `src/shared-roster.ts` is the DSH's own roster (`<cache>.shared-roster.json`,
153
+ mode 0600): invites (a single-use secret per listed member, kept as a hash, a
154
+ day long), each member's paired devices, and each session's starter. A member's
155
+ handset joins through the relay, pins this DSH's key from the invite, and hands
156
+ the secret over inside the channel; `PhoneSecurity` admits it through the
157
+ roster instead of a safety code. The relay's `members` list prunes the roster.
158
+ `src/shared-owner.ts` is what the bridge asks before any call or stream and
159
+ after `session/create` and `session/list`: a member reaches only sessions they
160
+ started, sees only their events, and answers only questions they were shown.
161
+
162
+ `src/pin-lock.ts` is the PIN lock, on a shared DSH and on a personal computer
163
+ alike (`<cache>.pins.json`, mode 0600): one four-digit PIN per member (`owner`
164
+ on a personal computer), kept as scrypt, and a failure count that survives a
165
+ restart. Once a channel is authorized, `PhoneSecurity` tells the phone
166
+ `pinRequired` (with `set` when the member has none yet), answers `unlock` and
167
+ `setPin` with `unlocked`, `pinWrong`, `pinLocked` or `pinInvalid`, and refuses
168
+ every call (`teamwork/locked`) and stream until unlocked, and again after
169
+ fifteen minutes with nothing sent. Five wrong PINs lock the member on every
170
+ device until `/teamwork share unlock <email>` or `/teamwork pin reset` clears
171
+ it. Signing out, entering or leaving shared mode clears every PIN.
172
+
173
+ `src/audit-archive.ts` is a shared DSH's audit archive (the server's ADR 0045):
174
+ every frame between a member's device and this DSH, both ways, becomes a record
175
+ (member, device, direction, time; a string over 64 KiB kept as its length and
176
+ SHA-256). Records collect for a minute or 1 MiB, are HPKE-sealed (`@hpke/core`,
177
+ exact version) to the admin's audit public key under a header the AEAD binds
178
+ (host, sequence, the previous segment's SHA-256, the key's fingerprint), signed
179
+ with the identity key the host key is bound to, written to
180
+ `<cache>.audit.json.queue/`, and uploaded in order to
181
+ `POST /relay/shared/archive`; a segment leaves the queue only once the server
182
+ holds it. `<cache>.audit.json` keeps the key and the chain's position. No
183
+ member is admitted until `/teamwork share audit-key` sets a key; leaving
184
+ shared mode flushes and forgets it. `src/audit-cli.ts` is the
185
+ `dsh-teamwork-audit` bin the admin runs on their own machine: `keygen` writes
186
+ a key pair (mode 0600, never overwriting), `read` opens an exported archive
187
+ and reports a gap, an alteration or another key.
188
+
189
+ The panel's **Shared DSH** page (`Shared` in `src/web/TeamworkPanel.tsx`, the
190
+ `share-*` routes in `src/panel.ts`) runs the same functions as
191
+ `/teamwork share`; in shared mode `PanelState.shared` is set, no profile is
192
+ read, and the header offers that page in place of Phone and Account.
193
+
124
194
  ## Phone transport
125
195
 
126
196
  The hosted relay is optional and discovered through `GET /api/relay`. The host
package/docs/en/guide.md CHANGED
@@ -46,11 +46,44 @@ phone pairing to that team. A person may belong to several teams.
46
46
 
47
47
  Create or join teams in the web console. New teams receive a built-in assistant;
48
48
  existing teams are unchanged. Team renaming does not automatically rename the
49
- assistant. Use its preset with a working model and ask it to inspect real state.
49
+ assistant. It leads the panel's presets: **Ask the assistant** starts a session
50
+ with it. Give it a working model and ask it to inspect real state. While an
51
+ administrator browses a team, the panel's header shows how many submissions wait
52
+ for review and opens them in the console.
53
+
54
+ ### A team's shared DSH
55
+
56
+ On the hosted service a team admin can make one DSH the team's own: create a
57
+ key under **Shared DSHs** in the team's console, then run
58
+ `/teamwork share enable <key>` in that DSH. It then signs in as the team, not as
59
+ a person: personal sign-in is refused while it is shared, it syncs that one
60
+ team, and its team-model calls are billed to the team. The first machine that
61
+ uses a key keeps it; the same key on another machine is refused, and an admin
62
+ who rotates or deletes the key cuts it off. `/teamwork share disable` deletes
63
+ the key. A team admin chooses in the console who may reach it; for each of
64
+ them, run `/teamwork share invite <email>` here and hand the link over in
65
+ person or through a channel the team trusts, never through the Teamwork server.
66
+ Each member's sessions are theirs alone: others cannot list, follow or answer
67
+ them. Phone and web clients that open the link arrive in a later release.
68
+
69
+ A shared DSH admits nobody until its admin sets the team's audit key. On their
70
+ own computer the admin runs `dsh-teamwork-audit keygen` (installed with this
71
+ package), which writes `audit-key.json` and prints
72
+ `/teamwork share audit-key <public key>` to run here. From then on this DSH
73
+ seals every exchange with a member's device to that key and uploads it; the
74
+ server keeps it and cannot read it. The admin downloads it from the console and
75
+ opens it with `dsh-teamwork-audit read <file> --key audit-key.json`. A lost key
76
+ cannot be recovered.
77
+
78
+ Everything above can also be done in the Teamwork panel: **Use this DSH as a
79
+ team's shared DSH** on its sign-in screen or account page turns shared mode on,
80
+ and its **Shared DSH** page then sets the audit key, lists the members who may
81
+ reach it with their devices, makes an invite (a link and a QR code), unlocks a
82
+ member locked out by wrong PINs, and turns shared mode off.
50
83
 
51
84
  ## Choose a model or preset
52
85
 
53
- Use **New session** for a team preset. **Use in current session** works only
86
+ Use **New session** for a team preset. **Use in this blank session** works only
54
87
  before the conversation begins. Started sessions keep their preset generation;
55
88
  use a new session to adopt an update. A restart cannot promise to reconstruct a
56
89
  deleted old preset: a version mismatch blocks team inference and gives recovery
@@ -94,6 +127,14 @@ Run these in DSH's command input, not your shell. IDs come from `/teamwork list`
94
127
  | --- | --- |
95
128
  | `/teamwork login` | Open browser authorization. |
96
129
  | `/teamwork authorize <code>` | Redeem a fallback authorization code. |
130
+ | `/teamwork share enable <key>` | Make this DSH its team's shared DSH with a team host key (hosted service). |
131
+ | `/teamwork share disable` | End shared mode and delete its key. |
132
+ | `/teamwork share status` | Show the shared DSH's name, team and host token. |
133
+ | `/teamwork share invite <email>` | A single-use link, valid a day, that pairs one listed member's device with this shared DSH. |
134
+ | `/teamwork share members` | The members who may reach this shared DSH, and their devices. |
135
+ | `/teamwork share unlock <email>` | Clear a member's PIN and lock on this shared DSH; they set a new PIN next time. |
136
+ | `/teamwork share audit-key <key>` | Seal this shared DSH's archive to the key `dsh-teamwork-audit keygen` printed; members are admitted only once it is set. |
137
+ | `/teamwork pin reset` | Clear your own phone PIN and lock on this computer; set a new one from your phone. |
97
138
  | `/teamwork status` | Show authentication, sync status and recent errors. |
98
139
  | `/teamwork sync` | Refresh the team's resources. |
99
140
  | `/teamwork list` | List configuration IDs. |
@@ -21,11 +21,19 @@
21
21
 
22
22
  授权完成后立即同步,默认每 60 秒刷新。用团队下拉框浏览一个或所有团队;改变浏览范围不改变已有会话的目标团队,也不能把手机授权限制到这个团队。一个账号可以加入多个团队。
23
23
 
24
- 在网页控制台创建或加入团队。新团队会获得内置助理,已有团队不自动补建;重命名团队不会自动重命名助理。为助理预设选择可用模型后,要求它读取真实状态再操作。
24
+ 在网页控制台创建或加入团队。新团队会获得内置助理,已有团队不自动补建;重命名团队不会自动重命名助理。助理排在面板预设的最前面,点击“问问助理”即可用它新建会话。为助理选择可用模型后,要求它读取真实状态再操作。管理员浏览某个团队时,面板顶部会显示待审核的提交数量,点击即可在控制台打开。
25
+
26
+ ### 团队共享 DSH
27
+
28
+ 在托管服务上,团队管理员可以把一台 DSH 设为团队自己的:在团队控制台的**共享 DSH**里创建 key,再在那台 DSH 中运行 `/teamwork share enable <key>`。之后它以团队身份登录而不是个人:共享期间拒绝个人登录,只同步这一个团队,团队模型的调用计入团队。第一台使用 key 的机器会绑定它,同一个 key 换到其他机器上会被拒绝;管理员更换或删除 key 后它立即失效。`/teamwork share disable` 会删除 key。团队管理员在控制台决定谁可以访问它;对其中每个人,在这里运行 `/teamwork share invite <email>`,并当面或通过团队信任的渠道交给对方,不要经过 Teamwork 服务器。每个成员的会话只属于自己,其他人无法查看、跟随或回答。打开邀请链接的手机和网页客户端将在后续版本提供。
29
+
30
+ 共享 DSH 在管理员设置团队审计密钥之前不会接纳任何人。管理员在自己的电脑上运行 `dsh-teamwork-audit keygen`(随本插件包安装),它会写出 `audit-key.json` 并打印要在这里运行的 `/teamwork share audit-key <public key>`。此后这台 DSH 会把与成员设备之间的每次交互加密到这把密钥并上传,服务器保存它却无法读取。管理员在控制台下载归档,用 `dsh-teamwork-audit read <file> --key audit-key.json` 打开。丢失的密钥无法找回。
31
+
32
+ 以上操作也都可以在 Teamwork 面板中完成:在登录页或账号页选择**把这台 DSH 设为团队的共享 DSH** 即可开启共享模式;开启后的**共享 DSH** 页可以设置审计密钥、查看可访问的成员及其设备、生成邀请(链接和二维码)、为输错 PIN 被锁定的成员解锁,以及关闭共享模式。
25
33
 
26
34
  ## 选择模型或预设
27
35
 
28
- 使用“新建会话”应用团队预设。“用于当前会话”仅适用于尚未开始对话的会话。已开始的会话保留原预设代次,使用新会话采用更新。跨重启不保证重建已删除的旧预设;发现版本不一致时会阻止团队推理并给出恢复指引。
36
+ 使用“新建会话”应用团队预设。“用于当前空白会话”仅适用于尚未开始对话的会话。已开始的会话保留原预设代次,使用新会话采用更新。跨重启不保证重建已删除的旧预设;发现版本不一致时会阻止团队推理并给出恢复指引。
29
37
 
30
38
  必需工具和固定版本的插件依赖必须就绪,可选工具缺失只提示。工具已注册仍须满足 DSH 授权与运行条件。团队模型经过团队服务;继承本地模型的预设继续使用所继承的模型。
31
39
 
@@ -51,6 +59,14 @@
51
59
  | --- | --- |
52
60
  | `/teamwork login` | 打开浏览器授权。 |
53
61
  | `/teamwork authorize <code>` | 兑换备用授权码。 |
62
+ | `/teamwork share enable <key>` | 用团队授权 key 把这台 DSH 设为团队的共享 DSH(托管服务)。 |
63
+ | `/teamwork share disable` | 关闭共享模式并删除 key。 |
64
+ | `/teamwork share status` | 查看共享 DSH 的名称、团队和 token 状态。 |
65
+ | `/teamwork share invite <email>` | 生成一次性邀请链接(一天内有效),让名单中的一位成员把设备配对到这台共享 DSH。 |
66
+ | `/teamwork share members` | 查看可访问这台共享 DSH 的成员及其设备。 |
67
+ | `/teamwork share unlock <email>` | 清除某个成员在这台共享 DSH 上的 PIN 和锁定,对方下次连接时重新设置。 |
68
+ | `/teamwork share audit-key <key>` | 把这台共享 DSH 的归档加密到 `dsh-teamwork-audit keygen` 打印的密钥;设置之后才会接纳成员。 |
69
+ | `/teamwork pin reset` | 清除你自己手机在这台计算机上的 PIN 和锁定,再从手机设置新的。 |
54
70
  | `/teamwork status` | 查看登录、同步和最近错误。 |
55
71
  | `/teamwork sync` | 刷新团队资源。 |
56
72
  | `/teamwork list` | 列出配置 ID。 |
@@ -0,0 +1,174 @@
1
+ /**
2
+ * A shared DSH's audit archive (the server's `docs/tech/shared-dsh.md`, "The audit archive", and its ADR 0045): every
3
+ * frame between a member's device and this DSH, recorded with the member, the device and the time, sealed to a key
4
+ * only the team's admin holds, and uploaded to the server, which keeps it and cannot open it.
5
+ *
6
+ * Records collect for a minute, or until they reach 1 MiB, and become one segment: the records as JSON, HPKE-sealed
7
+ * (RFC 9180: DHKEM X25519, HKDF-SHA256, AES-256-GCM) to the audit public key, under a clear header the AEAD binds
8
+ * (host, sequence, the previous segment's SHA-256, the key's fingerprint), signed by this DSH's identity key. A
9
+ * segment is written to a queue on disk before it is uploaded, in order, so a lost connection loses nothing; the chain
10
+ * makes a dropped or altered segment show when the admin reads it (`dsh-teamwork-audit read`, src/audit-cli.ts).
11
+ * A string over 64 KiB in a frame (a file's bytes) is recorded by its length and SHA-256 only.
12
+ */
13
+ import { createHash, randomBytes } from 'node:crypto';
14
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
15
+ import { dirname, join } from 'node:path';
16
+ import { Aes256Gcm, CipherSuite, DhkemX25519HkdfSha256, HkdfSha256 } from '@hpke/core';
17
+ import { z } from 'zod';
18
+ export const suite = new CipherSuite({ kem: new DhkemX25519HkdfSha256(), kdf: new HkdfSha256(), aead: new Aes256Gcm() });
19
+ export const SEGMENT_BYTES = 1 << 20;
20
+ export const SEGMENT_MS = 60 * 1000;
21
+ const LARGE_STRING = 64 * 1024;
22
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
23
+ /** A string's UTF-8 bytes as the ArrayBuffer HPKE takes. */
24
+ export const bytesOf = (text) => { const bytes = new TextEncoder().encode(text); return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength); };
25
+ const b64 = (bytes) => Buffer.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)).toString('base64');
26
+ /** The clear header the AEAD binds: whoever opens a segment knows these were not moved between segments. */
27
+ export const segmentHeader = (s) => `dsh-teamwork audit segment\n${s.host}\n${s.seq}\n${s.prev}\n${s.key}`;
28
+ /** What this DSH signs, and the server checks before it keeps a segment (its `server/relay/archive.go`). */
29
+ export const segmentSigned = (s) => `${segmentHeader(s)}\n${sha256(`${s.enc}.${s.ct}`)}`;
30
+ export const keyFingerprint = (publicKey) => sha256(Buffer.from(publicKey, 'base64'));
31
+ /** A frame as the archive keeps it: large strings by their length and digest. */
32
+ export function recordable(value) {
33
+ if (typeof value === 'string')
34
+ return value.length > LARGE_STRING ? { omitted: value.length, sha256: sha256(value) } : value;
35
+ if (Array.isArray(value))
36
+ return value.map(recordable);
37
+ if (value && typeof value === 'object')
38
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, recordable(v)]));
39
+ return value;
40
+ }
41
+ /** The audit key, and where this host's chain stands: a different host starts its own chain. */
42
+ const stateSchema = z.object({ publicKey: z.string().optional(), host: z.string().optional(), seq: z.number().int().min(0), prev: z.string() });
43
+ export const auditArchivePath = (cachePath) => cachePath.replace(/(\.json)?$/, '.audit.json');
44
+ export class AuditArchive {
45
+ options;
46
+ state;
47
+ records = [];
48
+ bytes = 0;
49
+ timer;
50
+ sealing = Promise.resolve();
51
+ draining;
52
+ publicKey;
53
+ constructor(options) {
54
+ this.options = options;
55
+ }
56
+ get queue() { return `${this.options.path}.queue`; }
57
+ load() {
58
+ return (this.state ??= readFile(this.options.path, 'utf8').then((text) => stateSchema.parse(JSON.parse(text)), (error) => { if (error.code === 'ENOENT')
59
+ return { seq: 0, prev: '' }; throw error; }).then((state) => { this.publicKey = state.publicKey; return state; }));
60
+ }
61
+ async save(state) {
62
+ await mkdir(dirname(this.options.path), { recursive: true, mode: 0o700 });
63
+ const temporary = `${this.options.path}.${randomBytes(8).toString('hex')}.tmp`;
64
+ try {
65
+ await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
66
+ await rename(temporary, this.options.path);
67
+ }
68
+ finally {
69
+ await rm(temporary, { force: true });
70
+ }
71
+ }
72
+ /** Whether an audit key is set: a shared DSH admits no member until it is. */
73
+ async ready() { return !!(await this.load()).publicKey; }
74
+ /** The audit key's fingerprint, or undefined before one is set. */
75
+ async fingerprint() { const { publicKey } = await this.load(); return publicKey ? keyFingerprint(publicKey) : undefined; }
76
+ /** The admin's audit public key (raw X25519, base64, from `dsh-teamwork-audit keygen`). New segments are sealed to it. */
77
+ async setKey(publicKey) {
78
+ const raw = Buffer.from(publicKey.trim(), 'base64');
79
+ if (raw.length !== 32)
80
+ throw new Error('That is not an audit public key. Run dsh-teamwork-audit keygen on your own machine and paste the key it prints.');
81
+ await suite.kem.deserializePublicKey(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength));
82
+ await this.flush();
83
+ this.sealing = this.sealing.then(async () => {
84
+ const state = await this.load();
85
+ state.publicKey = raw.toString('base64');
86
+ this.publicKey = state.publicKey;
87
+ await this.save(state);
88
+ });
89
+ await this.sealing;
90
+ return keyFingerprint(raw.toString('base64'));
91
+ }
92
+ /** Records one frame of a member's; nothing is recorded before an audit key is set. */
93
+ record(entry) {
94
+ if (!this.publicKey)
95
+ return;
96
+ const record = { at: new Date(this.options.now?.() ?? Date.now()).toISOString(), ...entry, frame: recordable(entry.frame) };
97
+ this.records.push(record);
98
+ this.bytes += JSON.stringify(record).length;
99
+ if (this.bytes >= SEGMENT_BYTES)
100
+ void this.flush();
101
+ else if (!this.timer) {
102
+ this.timer = setTimeout(() => void this.flush(), SEGMENT_MS);
103
+ this.timer.unref?.();
104
+ }
105
+ }
106
+ /** Seals what has collected into the next segment, queues it on disk, and uploads the queue. */
107
+ flush() {
108
+ if (this.timer)
109
+ clearTimeout(this.timer);
110
+ this.timer = undefined;
111
+ const records = this.records.splice(0);
112
+ this.bytes = 0;
113
+ if (records.length)
114
+ this.sealing = this.sealing.then(() => this.seal(records)).catch((error) => this.options.log?.(`audit archive: ${error.message}`));
115
+ return this.sealing.then(() => this.drain());
116
+ }
117
+ async seal(records) {
118
+ const state = await this.load(), host = this.options.hostId();
119
+ if (!state.publicKey || !host)
120
+ return;
121
+ if (state.host !== host)
122
+ Object.assign(state, { host, seq: 0, prev: '' });
123
+ const header = { host, seq: state.seq + 1, prev: state.prev, key: keyFingerprint(state.publicKey) };
124
+ const sender = await suite.createSenderContext({ recipientPublicKey: await suite.kem.deserializePublicKey(new Uint8Array(Buffer.from(state.publicKey, 'base64')).buffer) });
125
+ const ct = await sender.seal(bytesOf(JSON.stringify(records)), bytesOf(segmentHeader(header)));
126
+ const unsigned = { ...header, enc: b64(sender.enc), ct: b64(ct) };
127
+ const identity = await this.options.identity();
128
+ const segment = { v: 1, ...unsigned, sig: b64(await identity.privateKey.sign(new TextEncoder().encode(segmentSigned(unsigned)))) };
129
+ const body = JSON.stringify(segment);
130
+ await mkdir(this.queue, { recursive: true, mode: 0o700 });
131
+ await writeFile(join(this.queue, `${String(segment.seq).padStart(12, '0')}.json`), body, { mode: 0o600 });
132
+ await this.save({ ...state, seq: segment.seq, prev: sha256(body) });
133
+ state.seq = segment.seq;
134
+ state.prev = sha256(body);
135
+ }
136
+ /** Uploads queued segments in order; one the server refuses as out of order stops the queue and is said. */
137
+ drain() {
138
+ return (this.draining ??= (async () => {
139
+ try {
140
+ const files = (await readdir(this.queue).catch(() => [])).filter((f) => f.endsWith('.json')).sort();
141
+ for (const file of files) {
142
+ const body = await readFile(join(this.queue, file), 'utf8');
143
+ const { status } = await this.options.upload(body);
144
+ if (status === 200 || status === 201) {
145
+ await rm(join(this.queue, file), { force: true });
146
+ continue;
147
+ }
148
+ this.options.log?.(`audit archive: the server refused segment ${file} (${status}); it stays queued.`);
149
+ break;
150
+ }
151
+ }
152
+ catch (error) {
153
+ this.options.log?.(`audit archive: could not upload (${error.message}); retrying with the next segment.`);
154
+ }
155
+ finally {
156
+ this.draining = undefined;
157
+ }
158
+ })());
159
+ }
160
+ stop() { if (this.timer)
161
+ clearTimeout(this.timer); this.timer = undefined; }
162
+ /**
163
+ * Shared mode ended: what collected is sealed and sent if it can be, then the key goes, so nothing more is recorded.
164
+ * The chain's place stays: the same shared host enabled again continues its chain rather than restarting it.
165
+ */
166
+ async clear() {
167
+ await this.flush();
168
+ this.stop();
169
+ this.publicKey = undefined;
170
+ this.sealing = this.sealing.then(async () => { const state = await this.load(); delete state.publicKey; await this.save(state); });
171
+ await this.sealing;
172
+ }
173
+ }
174
+ //# sourceMappingURL=audit-archive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-archive.js","sourceRoot":"","sources":["../src/audit-archive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACvF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,qBAAqB,EAAE,EAAE,GAAG,EAAE,IAAI,UAAU,EAAE,EAAE,IAAI,EAAE,IAAI,SAAS,EAAE,EAAE,CAAC,CAAC;AACzH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,CAAC;AACrC,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,GAAG,IAAI,CAAC;AACpC,MAAM,YAAY,GAAG,EAAE,GAAG,IAAI,CAAC;AAK/B,MAAM,MAAM,GAAG,CAAC,IAAyB,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9F,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE,GAAG,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,MAAM,CAAC,KAA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IAE5E;;;OAGG;IACH,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACnB,IAAI,CAAC,IAAI,EAAE,CAAC;QAAC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QACxC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,GAAG,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,KAAK,CAAC,SAAS,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACnI,MAAM,IAAI,CAAC,OAAO,CAAC;IACrB,CAAC;CACF"}
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `dsh-teamwork-audit`, run by a team's admin on their own machine (the server's `docs/tech/shared-dsh.md`, "The audit
4
+ * archive"):
5
+ *
6
+ * dsh-teamwork-audit keygen [file] writes a new audit key pair to file (default audit-key.json, mode 0600)
7
+ * and prints the public key to give the shared DSH
8
+ * dsh-teamwork-audit read <archive> [--key file] opens an archive the team console exported (one segment per line),
9
+ * checks the chain, and prints each record as one JSON line; anything
10
+ * missing, altered or sealed to another key is said on stderr, and the
11
+ * exit code is then 1
12
+ *
13
+ * The private key never leaves the file keygen wrote. A lost key cannot be recovered: its segments stay unreadable.
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import { realpathSync } from 'node:fs';
17
+ import { readFile, writeFile } from 'node:fs/promises';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { bytesOf, keyFingerprint, segmentHeader, suite } from './audit-archive.js';
20
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
21
+ const buffer = (base64) => new Uint8Array(Buffer.from(base64, 'base64')).buffer;
22
+ export async function keygen(file) {
23
+ const pair = await suite.kem.generateKeyPair();
24
+ const publicKey = Buffer.from(await suite.kem.serializePublicKey(pair.publicKey)).toString('base64');
25
+ const privateKey = Buffer.from(await suite.kem.serializePrivateKey(pair.privateKey)).toString('base64');
26
+ await writeFile(file, JSON.stringify({ type: 'dsh-teamwork-audit-key', publicKey, privateKey }), { mode: 0o600, flag: 'wx' });
27
+ return { publicKey, fingerprint: keyFingerprint(publicKey) };
28
+ }
29
+ /** Every record in an exported archive, and every problem with it; the archive's lines are segments in order. */
30
+ export async function read(archive, key) {
31
+ const fingerprint = keyFingerprint(key.publicKey);
32
+ const recipientKey = await suite.kem.deserializePrivateKey(buffer(key.privateKey));
33
+ const records = [], problems = [];
34
+ let expected;
35
+ for (const line of archive.split('\n').filter((l) => l.trim())) {
36
+ let segment;
37
+ try {
38
+ segment = JSON.parse(line);
39
+ }
40
+ catch {
41
+ problems.push('A line is not a segment.');
42
+ continue;
43
+ }
44
+ if (!expected && segment.seq !== 1)
45
+ problems.push(`The archive starts at segment ${segment.seq}: earlier ones are missing.`);
46
+ if (expected && (segment.seq !== expected.seq || segment.prev !== expected.prev))
47
+ problems.push(`Segment ${segment.seq} does not follow segment ${expected.seq - 1}: one is missing or was altered.`);
48
+ expected = { seq: segment.seq + 1, prev: sha256(line) };
49
+ if (segment.key !== fingerprint) {
50
+ problems.push(`Segment ${segment.seq} is sealed to another key (${segment.key}).`);
51
+ continue;
52
+ }
53
+ try {
54
+ const recipient = await suite.createRecipientContext({ recipientKey, enc: buffer(segment.enc) });
55
+ const plain = await recipient.open(buffer(segment.ct), bytesOf(segmentHeader(segment)));
56
+ records.push(...JSON.parse(new TextDecoder().decode(plain)));
57
+ }
58
+ catch {
59
+ problems.push(`Segment ${segment.seq} does not open: it was altered, or its header was.`);
60
+ }
61
+ }
62
+ return { records, problems };
63
+ }
64
+ async function main(args) {
65
+ const [command, file] = args;
66
+ if (command === 'keygen') {
67
+ const target = file ?? 'audit-key.json';
68
+ const { publicKey, fingerprint } = await keygen(target);
69
+ console.log(`Wrote ${target}. Keep it safe: a lost key cannot be recovered, and whoever holds it reads every session.`);
70
+ console.log(`In the shared DSH, run:\n/teamwork share audit-key ${publicKey}`);
71
+ console.log(`Fingerprint: ${fingerprint}`);
72
+ return 0;
73
+ }
74
+ if (command === 'read' && file) {
75
+ const at = args.indexOf('--key');
76
+ const key = JSON.parse(await readFile(at > 0 ? args[at + 1] : 'audit-key.json', 'utf8'));
77
+ const { records, problems } = await read(await readFile(file, 'utf8'), key);
78
+ for (const record of records)
79
+ console.log(JSON.stringify(record));
80
+ for (const problem of problems)
81
+ console.error(problem);
82
+ return problems.length ? 1 : 0;
83
+ }
84
+ console.error('usage: dsh-teamwork-audit keygen [file] | dsh-teamwork-audit read <archive.ndjson> [--key audit-key.json]');
85
+ return 2;
86
+ }
87
+ // Run as a command (through npm's bin link too), not when imported by tests.
88
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
89
+ main(process.argv.slice(2)).then((code) => process.exit(code), (error) => { console.error(error.message); process.exit(1); });
90
+ }
91
+ //# sourceMappingURL=audit-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-cli.js","sourceRoot":"","sources":["../src/audit-cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,KAAK,EAAgB,MAAM,oBAAoB,CAAC;AAEjG,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACjF,MAAM,MAAM,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,IAAI,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,EAAE,GAAG,MAAM,IAAI,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC;QAC5E,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;QAClE,KAAK,MAAM,OAAO,IAAI,QAAQ;YAAE,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACvD,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,2GAA2G,CAAC,CAAC;IAC3H,OAAO,CAAC,CAAC;AACX,CAAC;AAED,6EAA6E;AAC7E,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACxF,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAE,KAAe,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3I,CAAC"}
package/lib/bridge.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * The phone's side of this DSH (dsh-teamwork-premium ADR 0009,
3
- * `premium/docs/tech/mobile-relay.md`, "The allow-list"). The relay hands this
2
+ * The phone's side of this DSH (the server's
3
+ * `docs/tech/relay.md`, "The allow-list"). The relay hands this
4
4
  * plugin a confirmed pairing's `call` and `mux` frames; the bridge checks each
5
5
  * against the allow-list and replays it against DSH's own Remote API on
6
6
  * loopback, as an answering identity of that pairing's own, then sends the
@@ -61,7 +61,7 @@ export class Bridge {
61
61
  link(pairingId) {
62
62
  let link = this.links.get(pairingId);
63
63
  if (!link)
64
- this.links.set(pairingId, link = { queued: [], streams: new Set() });
64
+ this.links.set(pairingId, link = { queued: [], streams: new Map(), inbound: Promise.resolve(), outbound: Promise.resolve() });
65
65
  return link;
66
66
  }
67
67
  drop(pairingId) {
@@ -70,6 +70,7 @@ export class Bridge {
70
70
  return;
71
71
  this.links.delete(pairingId);
72
72
  this.uploads.drop(pairingId);
73
+ this.options.owners?.()?.drop(pairingId);
73
74
  link.mux?.close(1000, 'phone left');
74
75
  }
75
76
  async call(frame) {
@@ -94,6 +95,9 @@ export class Bridge {
94
95
  };
95
96
  if (!ALLOWED_CALLS.has(frame.method))
96
97
  return answer(403, { error: 'method_not_allowed' });
98
+ const owners = this.options.owners?.();
99
+ if (owners && !(await owners.admitCall(frame.pairingId, frame.method, frame.body)))
100
+ return answer(200, { result: { ok: false, error: { code: 'teamwork/not_found' } } });
97
101
  const origin = this.origin();
98
102
  if (!origin)
99
103
  return answer(503, { error: 'no_web_server' });
@@ -205,13 +209,14 @@ export class Bridge {
205
209
  for (const id of uploaded)
206
210
  this.uploads.cancel(frame.pairingId, promptSession, id);
207
211
  }
208
- answer(response.status, text ? parseJson(text) : null);
212
+ const body = text ? parseJson(text) : null;
213
+ answer(response.status, owners && response.ok ? await owners.afterCall(frame.pairingId, frame.method, body) : body);
209
214
  }
210
215
  catch (error) {
211
216
  if (error instanceof PhoneSessionError)
212
217
  return answer(200, { result: { ok: false, error: { code: `teamwork/${error.code}` } } });
213
218
  link.cookie = undefined;
214
- this.options.log?.('手机的请求无法到达 DSH', error);
219
+ this.options.log?.('A phone request could not reach DSH', error);
215
220
  answer(502, { error: 'dsh_unreachable' });
216
221
  }
217
222
  }
@@ -219,14 +224,22 @@ export class Bridge {
219
224
  const parsed = clientMuxSchema.safeParse(body);
220
225
  if (!parsed.success)
221
226
  return;
222
- const message = parsed.data;
223
227
  const link = this.link(pairingId);
228
+ // Without a filter nothing waits, so frames go on at once and in order.
229
+ if (!this.options.owners?.())
230
+ return void this.muxNow(pairingId, link, parsed.data);
231
+ link.inbound = link.inbound.then(() => this.muxNow(pairingId, link, parsed.data)).catch((error) => this.options.log?.('A phone stream frame failed', error));
232
+ }
233
+ async muxNow(pairingId, link, message) {
224
234
  if (message.type === 'open') {
225
235
  if (!ALLOWED_STREAMS.has(message.endpoint))
226
236
  return this.fail(pairingId, message.streamId, 'stream_not_allowed');
227
237
  if (link.streams.has(message.streamId))
228
238
  return this.fail(pairingId, message.streamId, 'stream_exists');
229
- link.streams.add(message.streamId);
239
+ const owners = this.options.owners?.();
240
+ if (owners && !(await owners.admitOpen(pairingId, message.endpoint, message.payload)))
241
+ return this.fail(pairingId, message.streamId, 'not_found');
242
+ link.streams.set(message.streamId, message.endpoint);
230
243
  }
231
244
  else if (!link.streams.has(message.streamId)) {
232
245
  // Not a stream this pairing opened: it reaches nothing.
@@ -254,7 +267,7 @@ export class Bridge {
254
267
  }
255
268
  catch (error) {
256
269
  link.cookie = undefined;
257
- this.options.log?.('无法为手机登录 DSH', error);
270
+ this.options.log?.('Could not sign DSH in for the phone', error);
258
271
  return this.closeStreams(pairingId, link, 'dsh_unreachable');
259
272
  }
260
273
  if (this.links.get(pairingId) !== link || link.mux)
@@ -270,9 +283,18 @@ export class Bridge {
270
283
  const message = serverMuxSchema.safeParse(parseJson(String(event.data)));
271
284
  if (!message.success)
272
285
  return;
286
+ const endpoint = link.streams.get(message.data.streamId);
273
287
  if (message.data.type === 'end' || message.data.type === 'error')
274
288
  link.streams.delete(message.data.streamId);
275
- this.options.send({ t: 'mux', pairingId, body: message.data });
289
+ const owners = this.options.owners?.();
290
+ if (!owners || endpoint !== '$events' || message.data.type !== 'item')
291
+ return void this.options.send({ t: 'mux', pairingId, body: message.data });
292
+ const data = message.data;
293
+ link.outbound = link.outbound.then(async () => {
294
+ const value = await owners.eventFor(pairingId, data.value);
295
+ if (value !== undefined)
296
+ this.options.send({ t: 'mux', pairingId, body: data });
297
+ }).catch((error) => this.options.log?.('A phone event could not be filtered', error));
276
298
  });
277
299
  mux.addEventListener('close', () => {
278
300
  if (link.mux !== mux)
@@ -285,7 +307,7 @@ export class Bridge {
285
307
  /** Every open stream of a pairing ends, as DSH itself would end it. */
286
308
  closeStreams(pairingId, link, code) {
287
309
  link.queued = [];
288
- for (const streamId of link.streams)
310
+ for (const streamId of link.streams.keys())
289
311
  this.fail(pairingId, streamId, code);
290
312
  link.streams.clear();
291
313
  }