@pi-chamber/web 0.9.6 → 0.9.8-rc.1

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 (95) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramView-0Iq1ak1I.js → DiagramView-BMBrrFLy.js} +1 -1
  3. package/dist/assets/{DiffView-DD1AFRi3.js → DiffView-yVBxHkBI.js} +1 -1
  4. package/dist/assets/{FileSaveConflictDialog-CoKwDovb.js → FileSaveConflictDialog-D0siEm8l.js} +1 -1
  5. package/dist/assets/FilesView-CkcKBKkT.js +6 -0
  6. package/dist/assets/{GitView-LFEpCasf.js → GitView-CfuhQOfc.js} +3 -3
  7. package/dist/assets/{JsonTreeView-Cwjgvh4g.js → JsonTreeView-6kRdE1BO.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-_7kV1yNw.js → MarkdownRendererImpl-CRWbN_Jc.js} +2 -2
  9. package/dist/assets/{PatchDiff-DG43C1HW.js → PatchDiff-B0ssv8Aw.js} +1 -1
  10. package/dist/assets/{SessionSwitcherContent-DCFXPY3d.js → SessionSwitcherContent-NmfI4B0Z.js} +1 -1
  11. package/dist/assets/{SessionSwitcherDropdown-QY7FKuEQ.js → SessionSwitcherDropdown-DmE2hYTN.js} +2 -2
  12. package/dist/assets/SessionUnreadDot-LDTswryg.js +1 -0
  13. package/dist/assets/SettingsView-D0iw6y_H.js +2 -0
  14. package/dist/assets/SettingsWindow-BT2TzUBK.js +1 -0
  15. package/dist/assets/{ToolOutputDialog-IlCrS6BR.js → ToolOutputDialog-Bnl51bva.js} +4 -4
  16. package/dist/assets/{ToolPartDiffPreview-D68JV0rR.js → ToolPartDiffPreview-DgPtLS_h.js} +1 -1
  17. package/dist/assets/{VirtualizedFileDiff-Bl-rAYeh.js → VirtualizedFileDiff-D3zBpYIS.js} +4 -4
  18. package/dist/assets/collapsible-_urywMu5.js +1 -0
  19. package/dist/assets/{computeVirtualFileMetrics-FSOm2VrW.js → computeVirtualFileMetrics-y2AJzpKw.js} +2 -2
  20. package/dist/assets/{contextFileOpenGuard-Bxb6AIPa.js → contextFileOpenGuard-DYUFkrPT.js} +1 -1
  21. package/dist/assets/{gitStatusPredicates-DxolDpMd.js → gitStatusPredicates-CbFfOlbV.js} +1 -1
  22. package/dist/assets/index-BXgR2dKM.css +1 -0
  23. package/dist/assets/index-CrqlVJXp.js +8 -0
  24. package/dist/assets/{index-Dh58uD3I.js → index-DwJJarzh.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-D3_04XCh.js → isDiffPlainText-kXPOivsq.js} +1 -1
  26. package/dist/assets/{isFilePlainText-CHouYQhH.js → isFilePlainText-BBIPqnLo.js} +1 -1
  27. package/dist/assets/{main-HzTrVvbB.js → main-BshSYpnV.js} +7 -7
  28. package/dist/assets/{main-CH3EqGJI.js → main-RrPyfmCA.js} +2 -2
  29. package/dist/assets/{markdownCore-DJU4KvHP.js → markdownCore-BxXmpZtB.js} +1 -1
  30. package/dist/assets/{miniChat-Ca3TpaaA.js → miniChat-DRNgmC-q.js} +2 -2
  31. package/dist/assets/{mobile-lj4gpGsO.js → mobile-CdmgVKW4.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-B80Jqq8b.js +2 -0
  33. package/dist/assets/renderMobileApp-CLcBvRiy.js +11 -0
  34. package/dist/assets/runtimeEndpointReset-DHHCemOu.js +53 -0
  35. package/dist/assets/{runtimeSurface-CE_VNjdH.js → runtimeSurface-C9kx2zfD.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-BvFAP9zG.js → useAppFontEffects-Dp6vM-Zr.js} +104 -104
  37. package/dist/assets/{useFilesViewSearch-BD79p3A2.js → useFilesViewSearch-Bc8PTYrg.js} +2 -2
  38. package/dist/assets/{usePushVisibilityBeacon-CWg0j-Wg.js → usePushVisibilityBeacon-DMcKyNtE.js} +1 -1
  39. package/dist/assets/{useSwitcherItems-CazJ6Yox.js → useSwitcherItems-DEvsORZ_.js} +1 -1
  40. package/dist/assets/{vendor-base-ui-CdaWtC7e.js → vendor-base-ui-C60wdVnS.js} +1 -1
  41. package/dist/assets/{vendor-codemirror-language-data-CP3j3-xu.js → vendor-codemirror-language-data-DLimsiRH.js} +2 -2
  42. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-Bkw82kL9.js} +1 -1
  43. package/dist/assets/{vendor-floating-ui-react-dom-BZOGXAGe.js → vendor-floating-ui-react-dom-KLmnYDaG.js} +1 -1
  44. package/dist/assets/{web-components-DWuadqra.js → web-components-05Oa3k7a.js} +3 -3
  45. package/dist/index.html +4 -4
  46. package/dist/mini-chat.html +3 -3
  47. package/dist/mobile.html +3 -3
  48. package/package.json +1 -1
  49. package/server/index.js +17 -3
  50. package/server/lib/client-auth/DOCUMENTATION.md +184 -0
  51. package/server/lib/client-auth/live-revocation.test.js +567 -0
  52. package/server/lib/client-auth/principal-tracker.js +383 -0
  53. package/server/lib/client-auth/principal-tracker.test.js +321 -0
  54. package/server/lib/client-auth/remote-clients.js +31 -0
  55. package/server/lib/client-auth/remote-clients.test.js +44 -0
  56. package/server/lib/pi/event-stream.js +269 -0
  57. package/server/lib/pi/event-stream.test.js +776 -0
  58. package/server/lib/pi/routes.js +88 -31
  59. package/server/lib/pi/routes.test.js +92 -20
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -4
  61. package/server/lib/pi/session-daemon/ipc-client.js +19 -15
  62. package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
  63. package/server/lib/pi/session-daemon/prompt-preflight.test.js +5 -1
  64. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +15 -5
  65. package/server/lib/pi/session-daemon/send-operation-registry.js +26 -23
  66. package/server/lib/pi/session-daemon/send-operation-registry.test.js +26 -20
  67. package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
  68. package/server/lib/pi/session-daemon/session-daemon.js +79 -18
  69. package/server/lib/pi/session-daemon/session-daemon.test.js +10 -4
  70. package/server/lib/pi/session-daemon/session-replay.test.js +8 -3
  71. package/server/lib/pi/session-daemon/supervisor.js +30 -5
  72. package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
  73. package/server/lib/pi/ui-settings-store.js +7 -1
  74. package/server/lib/pi/ui-settings-store.test.js +19 -1
  75. package/server/lib/server/core-routes.js +11 -1
  76. package/server/lib/stt/DOCUMENTATION.md +2 -0
  77. package/server/lib/stt/runtime.js +39 -2
  78. package/server/lib/stt/runtime.test.js +53 -0
  79. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  80. package/server/lib/terminal/runtime.js +48 -2
  81. package/server/lib/terminal/runtime.test.js +35 -0
  82. package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
  83. package/server/lib/ui-auth/ui-auth.js +98 -0
  84. package/server/lib/ui-auth/ui-auth.test.js +249 -0
  85. package/server/lib/workspace/host.js +3 -1
  86. package/dist/assets/FilesView-B_BF39ef.js +0 -6
  87. package/dist/assets/SessionUnreadDot-DGT31A3z.js +0 -1
  88. package/dist/assets/SettingsView-eG-wN-yY.js +0 -2
  89. package/dist/assets/SettingsWindow-Dvnp8YrA.js +0 -1
  90. package/dist/assets/collapsible-BjniCdZ5.js +0 -1
  91. package/dist/assets/index-BpmGBboM.css +0 -1
  92. package/dist/assets/index-DZnzXhTs.js +0 -8
  93. package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +0 -2
  94. package/dist/assets/renderMobileApp-CcWQ1sCf.js +0 -11
  95. package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +0 -53
@@ -0,0 +1,321 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import {
3
+ MAX_LIVE_CONNECTIONS_GLOBAL,
4
+ MAX_LIVE_CONNECTIONS_PER_PRINCIPAL,
5
+ MAX_REMEMBERED_REVOKED_CLIENTS,
6
+ createPrincipalTracker,
7
+ createRevocationCoordinator,
8
+ } from './principal-tracker.js';
9
+
10
+ describe('principal tracker', () => {
11
+ it('closes only the revoked principal connections and reports the count', () => {
12
+ const tracker = createPrincipalTracker();
13
+ const closedA = [];
14
+ const closedB = [];
15
+ tracker.track({ principal: 'client:a', close: (reason) => closedA.push(reason) });
16
+ tracker.track({ principal: 'client:a', close: (reason) => closedA.push(reason) });
17
+ tracker.track({ principal: 'client:b', close: (reason) => closedB.push(reason) });
18
+
19
+ expect(tracker.size).toBe(3);
20
+ expect(tracker.countPrincipal('client:a')).toBe(2);
21
+ expect(tracker.closePrincipal('client:a', 'credential-revoked')).toBe(2);
22
+
23
+ expect(closedA).toEqual(['credential-revoked', 'credential-revoked']);
24
+ expect(closedB).toEqual([]);
25
+ expect(tracker.size).toBe(1);
26
+ expect(tracker.closePrincipal('client:a', 'credential-revoked')).toBe(0);
27
+ expect(tracker.closePrincipal('client:missing')).toBe(0);
28
+ });
29
+
30
+ it('detaches entries when connections end naturally and keeps revoke idempotent', () => {
31
+ const tracker = createPrincipalTracker();
32
+ const closed = [];
33
+ const entry = tracker.track({ principal: 'client:a', close: (reason) => closed.push(reason) });
34
+
35
+ entry.end();
36
+ expect(tracker.countPrincipal('client:a')).toBe(0);
37
+ expect(entry.revoke('late')).toBe(false);
38
+ expect(closed).toEqual([]);
39
+
40
+ const revoked = tracker.track({ principal: 'client:b', close: () => {} });
41
+ expect(revoked.revoke('credential-revoked')).toBe(true);
42
+ expect(revoked.revoke('credential-revoked')).toBe(false);
43
+ expect(revoked.end()).toBeUndefined();
44
+ expect(tracker.size).toBe(0);
45
+ });
46
+
47
+ it('isolates a failing close so other principals still close', () => {
48
+ const errors = [];
49
+ const tracker = createPrincipalTracker({ onCloseError: ({ error }) => errors.push(error) });
50
+ const closed = [];
51
+ tracker.track({ principal: 'client:bad', close: () => { throw new Error('destroy failed'); } });
52
+ tracker.track({ principal: 'client:good', close: (reason) => closed.push(reason) });
53
+
54
+ expect(tracker.closeAll('shutdown')).toBe(2);
55
+ expect(closed).toEqual(['shutdown']);
56
+ expect(errors).toHaveLength(1);
57
+ expect(errors[0]).toBeInstanceOf(Error);
58
+ expect(tracker.size).toBe(0);
59
+ });
60
+
61
+ it('closeAll reports every tracked principal and empties the index', () => {
62
+ const tracker = createPrincipalTracker();
63
+ tracker.track({ principal: 'client:a', close: () => {} });
64
+ tracker.track({ principal: 'client:b', close: () => {} });
65
+ tracker.track({ principal: 'session-jwt-1', close: () => {} });
66
+ expect([...tracker.principals()].sort()).toEqual(['client:a', 'client:b', 'session-jwt-1']);
67
+ expect(tracker.closeAll('signout-everywhere')).toBe(3);
68
+ expect(tracker.size).toBe(0);
69
+ });
70
+
71
+ it('rejects tracking without a principal or close callback', () => {
72
+ const tracker = createPrincipalTracker();
73
+ expect(() => tracker.track({ principal: '', close: () => {} })).toThrow();
74
+ expect(() => tracker.track({ principal: 'client:a' })).toThrow();
75
+ });
76
+ });
77
+
78
+ describe('revocation coordinator', () => {
79
+ it('closes the revoked principal connections immediately on the in-process path', () => {
80
+ const closed = [];
81
+ const coordinator = createRevocationCoordinator({ listRevokedClientIds: async () => [] });
82
+ coordinator.trackLiveConnection({ principal: 'client:dev-1', close: (reason) => closed.push(reason) });
83
+ coordinator.trackLiveConnection({ principal: 'client:dev-2', close: () => closed.push('other') });
84
+
85
+ expect(coordinator.clientRevoked('dev-1')).toBe(1);
86
+ expect(coordinator.clientRevoked('unknown-device')).toBe(0);
87
+ expect(closed).toEqual(['credential-revoked']);
88
+ expect(coordinator.liveConnectionCount).toBe(1);
89
+ });
90
+
91
+ it('converges with cross-process revocations through the bounded poll', async () => {
92
+ let revokedIds = [];
93
+ const polls = { count: 0 };
94
+ const coordinator = createRevocationCoordinator({
95
+ listRevokedClientIds: async () => {
96
+ polls.count += 1;
97
+ return revokedIds;
98
+ },
99
+ pollIntervalMs: 5,
100
+ setIntervalFn: (fn, ms) => setInterval(fn, ms),
101
+ clearIntervalFn: (handle) => clearInterval(handle),
102
+ });
103
+ const closed = [];
104
+ coordinator.trackLiveConnection({ principal: 'client:dev-1', close: (reason) => closed.push(reason) });
105
+ coordinator.start();
106
+
107
+ // Simulate a revocation committed by another process sharing the store.
108
+ revokedIds = ['dev-1'];
109
+ await new Promise((resolve) => setTimeout(resolve, 40));
110
+
111
+ expect(polls.count).toBeGreaterThan(0);
112
+ expect(closed).toEqual(['credential-revoked']);
113
+ await coordinator.dispose();
114
+ });
115
+
116
+ it('keeps previous state when a poll fails and recovers on the next tick', async () => {
117
+ let shouldFail = false;
118
+ let revokedIds = [];
119
+ const coordinator = createRevocationCoordinator({
120
+ listRevokedClientIds: async () => {
121
+ if (shouldFail) throw new Error('store read failed');
122
+ return revokedIds;
123
+ },
124
+ pollIntervalMs: 5,
125
+ setIntervalFn: (fn, ms) => setInterval(fn, ms),
126
+ clearIntervalFn: (handle) => clearInterval(handle),
127
+ });
128
+ const closed = [];
129
+ coordinator.trackLiveConnection({ principal: 'client:dev-1', close: (reason) => closed.push(reason) });
130
+ coordinator.start();
131
+
132
+ shouldFail = true;
133
+ await new Promise((resolve) => setTimeout(resolve, 25));
134
+ expect(closed).toEqual([]);
135
+
136
+ shouldFail = false;
137
+ revokedIds = ['dev-1'];
138
+ await new Promise((resolve) => setTimeout(resolve, 25));
139
+ expect(closed).toEqual(['credential-revoked']);
140
+ await coordinator.dispose();
141
+ });
142
+
143
+ it('dispose stops polling and closes remaining connections synchronously', async () => {
144
+ let polls = 0;
145
+ const coordinator = createRevocationCoordinator({
146
+ listRevokedClientIds: async () => {
147
+ polls += 1;
148
+ return [];
149
+ },
150
+ pollIntervalMs: 5,
151
+ setIntervalFn: (fn, ms) => setInterval(fn, ms),
152
+ clearIntervalFn: (handle) => clearInterval(handle),
153
+ });
154
+ coordinator.trackLiveConnection({ principal: 'client:dev-1', close: () => {} });
155
+ coordinator.start();
156
+ await new Promise((resolve) => setTimeout(resolve, 20));
157
+ expect(coordinator.dispose({ closeConnections: true })).toBe(1);
158
+ expect(coordinator.liveConnectionCount).toBe(0);
159
+
160
+ const pollsAfterDispose = polls;
161
+ await new Promise((resolve) => setTimeout(resolve, 20));
162
+ expect(polls).toBe(pollsAfterDispose);
163
+ });
164
+
165
+ it('dispose without closeConnections leaves tracked connections in place', () => {
166
+ const coordinator = createRevocationCoordinator({ listRevokedClientIds: async () => [] });
167
+ coordinator.trackLiveConnection({ principal: 'client:dev-1', close: () => {} });
168
+ coordinator.dispose({ closeConnections: false });
169
+ expect(coordinator.liveConnectionCount).toBe(1);
170
+ });
171
+
172
+ it('requires a listRevokedClientIds implementation', () => {
173
+ expect(() => createRevocationCoordinator({})).toThrow();
174
+ });
175
+ });
176
+
177
+ describe('principal tracker resource bounds', () => {
178
+ it('reject-closes a new connection beyond the per-principal bound without evicting unrelated entries', () => {
179
+ const tracker = createPrincipalTracker({ maxPerPrincipal: 2, maxTotal: 10 });
180
+ const closedA = [];
181
+ const closedB = [];
182
+ tracker.track({ principal: 'client:a', close: () => {} });
183
+ tracker.track({ principal: 'client:a', close: () => {} });
184
+ tracker.track({ principal: 'client:b', close: (reason) => closedB.push(reason) });
185
+
186
+ const rejected = tracker.track({ principal: 'client:a', close: (reason) => closedA.push(reason) });
187
+ expect(rejected.active).toBe(false);
188
+ expect(closedA).toEqual(['over-limit']);
189
+ expect(rejected.revoke('late')).toBe(false);
190
+ rejected.end();
191
+ // Unrelated entries are untouched: A keeps 2, B keeps 1.
192
+ expect(tracker.countPrincipal('client:a')).toBe(2);
193
+ expect(tracker.countPrincipal('client:b')).toBe(1);
194
+ expect(tracker.size).toBe(3);
195
+ expect(closedB).toEqual([]);
196
+ });
197
+
198
+ it('reject-closes a new connection beyond the global bound without evicting unrelated entries', () => {
199
+ const tracker = createPrincipalTracker({ maxPerPrincipal: 10, maxTotal: 2 });
200
+ tracker.track({ principal: 'client:a', close: () => {} });
201
+ tracker.track({ principal: 'client:b', close: () => {} });
202
+ const closed = [];
203
+ const rejected = tracker.track({ principal: 'client:c', close: (reason) => closed.push(reason) });
204
+ expect(rejected.active).toBe(false);
205
+ expect(closed).toEqual(['over-limit']);
206
+ expect(tracker.size).toBe(2);
207
+ expect(tracker.countPrincipal('client:a')).toBe(1);
208
+ expect(tracker.countPrincipal('client:b')).toBe(1);
209
+ });
210
+
211
+ it('exposes the configured bounds and defaults', () => {
212
+ const tracker = createPrincipalTracker();
213
+ expect(tracker.maxPerPrincipal).toBe(MAX_LIVE_CONNECTIONS_PER_PRINCIPAL);
214
+ expect(tracker.maxTotal).toBe(MAX_LIVE_CONNECTIONS_GLOBAL);
215
+ const coordinator = createRevocationCoordinator({ listRevokedClientIds: async () => [] });
216
+ expect(coordinator.maxRevoked).toBe(MAX_REMEMBERED_REVOKED_CLIENTS);
217
+ coordinator.dispose({ closeConnections: false });
218
+ });
219
+
220
+ it('disposed tracker reject-closes new registrations', () => {
221
+ const tracker = createPrincipalTracker();
222
+ tracker.track({ principal: 'client:a', close: () => {} });
223
+ expect(tracker.dispose('shutdown')).toBe(1);
224
+ expect(tracker.disposed).toBe(true);
225
+ const closed = [];
226
+ const rejected = tracker.track({ principal: 'client:b', close: (reason) => closed.push(reason) });
227
+ expect(rejected.active).toBe(false);
228
+ expect(closed).toEqual(['shutdown']);
229
+ expect(tracker.size).toBe(0);
230
+ });
231
+ });
232
+
233
+ describe('revocation coordinator verify-registration barrier', () => {
234
+ it('rejects a late client registration that races revocation (no poll involved)', () => {
235
+ const coordinator = createRevocationCoordinator({ listRevokedClientIds: async () => [] });
236
+ // Verification passed, then the revoke commits+closes before track.
237
+ expect(coordinator.clientRevoked('dev-1')).toBe(0);
238
+ expect(coordinator.isClientRevoked('dev-1')).toBe(true);
239
+ const closed = [];
240
+ const late = coordinator.trackLiveConnection({
241
+ principal: 'client:dev-1',
242
+ close: (reason) => closed.push(reason),
243
+ });
244
+ expect(late.active).toBe(false);
245
+ expect(closed).toEqual(['credential-revoked']);
246
+ expect(coordinator.liveConnectionCount).toBe(0);
247
+ expect(late.revoke('late')).toBe(false);
248
+ coordinator.dispose({ closeConnections: false });
249
+ });
250
+
251
+ it('rejects a stale-generation registration after global invalidation without trusting the principal', () => {
252
+ const coordinator = createRevocationCoordinator({ listRevokedClientIds: async () => [] });
253
+ const generation = coordinator.getGeneration();
254
+ // A global sign-out commits between verify and track.
255
+ expect(coordinator.revokeAllLive('signout-everywhere')).toBe(0);
256
+ const closed = [];
257
+ const late = coordinator.trackLiveConnection({
258
+ principal: 'session-jwt-old',
259
+ close: (reason) => closed.push(reason),
260
+ generation,
261
+ });
262
+ expect(late.active).toBe(false);
263
+ expect(closed).toEqual(['global-invalidation']);
264
+ // A registration verified AFTER the invalidation carries the new
265
+ // generation and is tracked normally.
266
+ const fresh = coordinator.trackLiveConnection({
267
+ principal: 'session-jwt-new',
268
+ close: () => {},
269
+ generation: coordinator.getGeneration(),
270
+ });
271
+ expect(fresh.active).toBe(true);
272
+ expect(coordinator.liveConnectionCount).toBe(1);
273
+ coordinator.dispose();
274
+ });
275
+
276
+ it('reject-closes beyond coordinator bounds without evicting unrelated principals', () => {
277
+ const coordinator = createRevocationCoordinator({
278
+ listRevokedClientIds: async () => [],
279
+ maxPerPrincipal: 1,
280
+ maxTotal: 10,
281
+ });
282
+ coordinator.trackLiveConnection({ principal: 'client:a', close: () => {} });
283
+ const closed = [];
284
+ const rejected = coordinator.trackLiveConnection({
285
+ principal: 'client:a',
286
+ close: (reason) => closed.push(reason),
287
+ });
288
+ expect(rejected.active).toBe(false);
289
+ expect(closed).toEqual(['over-limit']);
290
+ expect(coordinator.countPrincipal('client:a')).toBe(1);
291
+ coordinator.dispose();
292
+ });
293
+
294
+ it('disposed coordinator reject-closes new registrations', () => {
295
+ const coordinator = createRevocationCoordinator({ listRevokedClientIds: async () => [] });
296
+ coordinator.dispose({ closeConnections: false });
297
+ const closed = [];
298
+ const rejected = coordinator.trackLiveConnection({
299
+ principal: 'client:a',
300
+ close: (reason) => closed.push(reason),
301
+ });
302
+ expect(rejected.active).toBe(false);
303
+ expect(closed).toEqual(['shutdown']);
304
+ });
305
+
306
+ it('bounds remembered revoked IDs with FIFO eviction', () => {
307
+ const coordinator = createRevocationCoordinator({
308
+ listRevokedClientIds: async () => [],
309
+ maxRevoked: 2,
310
+ });
311
+ coordinator.clientRevoked('a');
312
+ coordinator.clientRevoked('b');
313
+ expect(coordinator.getRevokedCount()).toBe(2);
314
+ coordinator.clientRevoked('c');
315
+ expect(coordinator.getRevokedCount()).toBe(2);
316
+ expect(coordinator.isClientRevoked('a')).toBe(false);
317
+ expect(coordinator.isClientRevoked('b')).toBe(true);
318
+ expect(coordinator.isClientRevoked('c')).toBe(true);
319
+ coordinator.dispose({ closeConnections: false });
320
+ });
321
+ });
@@ -245,6 +245,35 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
245
245
  });
246
246
  };
247
247
 
248
+ // Establishment-time principal validation for credentials that cannot be
249
+ // re-checked from their bearer form — the encrypted URL token embeds the
250
+ // principal, so revocation must be re-checked against the store whenever
251
+ // such a token is used to establish a connection. This closes the
252
+ // mint/open race: a URL token minted moments before revocation is denied
253
+ // at open time even though its 60-second TTL has not elapsed.
254
+ const isClientValid = async (id) => {
255
+ if (typeof id !== 'string' || id.trim().length === 0) return false;
256
+ return withStoreMutation(async () => {
257
+ const store = await readStore();
258
+ const client = store.clients.find((entry) => entry.id === id);
259
+ if (!client || client.revokedAt) return false;
260
+ const expires = Date.parse(client.expiresAt || '');
261
+ return !Number.isFinite(expires) || expires > Date.now();
262
+ });
263
+ };
264
+
265
+ // Cross-process revocation propagation surface: the credential store is a
266
+ // file shared with other processes (pairing CLI), so a second process
267
+ // cannot emit revocations here. The live-revocation coordinator polls this
268
+ // bounded list and closes affected connections; a failed read must be
269
+ // retried by the caller, not treated as an authoritative empty result.
270
+ const listRevokedClientIds = async () => {
271
+ return withStoreMutation(async () => {
272
+ const store = await readStore();
273
+ return store.clients.filter((entry) => entry.revokedAt).map((entry) => entry.id);
274
+ });
275
+ };
276
+
248
277
  const authenticateBearerToken = async (token, req) => {
249
278
  if (typeof token !== 'string' || !token.startsWith(TOKEN_PREFIX)) {
250
279
  return null;
@@ -287,5 +316,7 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
287
316
  hasActiveRelayClients,
288
317
  purgeRevokedClients,
289
318
  revokeClient,
319
+ isClientValid,
320
+ listRevokedClientIds,
290
321
  };
291
322
  };
@@ -155,4 +155,48 @@ describe('remote client auth runtime', () => {
155
155
  await fs.rm(dir, { recursive: true, force: true });
156
156
  }
157
157
  });
158
+
159
+ it('validates client principals for URL-token establishment after revocation or expiry', async () => {
160
+ const { dir, runtime } = await createRuntime();
161
+ try {
162
+ const created = await runtime.createClient({ label: 'Phone' });
163
+ expect(await runtime.isClientValid(created.client.id)).toBe(true);
164
+
165
+ // Revoked principals are denied even though a URL token minted before
166
+ // revocation still decrypts (the mint/open race).
167
+ await runtime.revokeClient(created.client.id);
168
+ expect(await runtime.isClientValid(created.client.id)).toBe(false);
169
+
170
+ // Expired principals are establishment-denied as well.
171
+ const expired = await runtime.createClient({ label: 'Old', expiresAt: '2000-01-01T00:00:00.000Z' });
172
+ expect(await runtime.isClientValid(expired.client.id)).toBe(false);
173
+
174
+ expect(await runtime.isClientValid('missing-id')).toBe(false);
175
+ expect(await runtime.isClientValid('')).toBe(false);
176
+ expect(await runtime.isClientValid(undefined)).toBe(false);
177
+ } finally {
178
+ await fs.rm(dir, { recursive: true, force: true });
179
+ }
180
+ });
181
+
182
+ it('lists revoked client ids for cross-process revocation propagation', async () => {
183
+ const { dir, runtime } = await createRuntime();
184
+ try {
185
+ const first = await runtime.createClient({ label: 'Phone' });
186
+ const second = await runtime.createClient({ label: 'Tablet' });
187
+ expect(await runtime.listRevokedClientIds()).toEqual([]);
188
+
189
+ await runtime.revokeClient(first.client.id);
190
+ expect(await runtime.listRevokedClientIds()).toEqual([first.client.id]);
191
+
192
+ await runtime.revokeClient(second.client.id);
193
+ expect((await runtime.listRevokedClientIds()).sort()).toEqual([first.client.id, second.client.id].sort());
194
+
195
+ // Purge removes the entries; the list stays bounded by the store.
196
+ await runtime.purgeRevokedClients();
197
+ expect(await runtime.listRevokedClientIds()).toEqual([]);
198
+ } finally {
199
+ await fs.rm(dir, { recursive: true, force: true });
200
+ }
201
+ });
158
202
  });
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Pi event stream connection lifecycle.
3
+ *
4
+ * Owns everything one `/api/pi/events` SSE connection needs to run safely, so
5
+ * the route stays a thin adapter:
6
+ *
7
+ * - Cleanup is installed before `subscribe` is awaited, so a client that
8
+ * disconnects while the subscription is still opening cannot leak the daemon
9
+ * subscription; when the late subscription resolves it is closed exactly
10
+ * once.
11
+ * - Every teardown path (client disconnect, subscription error, server
12
+ * shutdown) funnels through one idempotent cleanup, so close/end/heartbeat
13
+ * teardown runs at most once per connection regardless of how many close
14
+ * events race.
15
+ * - An `AbortSignal` is handed through the supervisor to the IPC client, so
16
+ * shutdown can cancel a subscription while its daemon socket is opening.
17
+ * - Named heartbeat events are never written to a dead response, and no late
18
+ * frame is written after cleanup.
19
+ * - The response socket buffer is byte-bounded and enforced BEFORE each
20
+ * write, so no frame ever overshoots the bound by one huge write. A frame
21
+ * that would not fit is never written: the stream ends and the client
22
+ * reconnects from its last accepted sequence, where the daemon replays the
23
+ * missed suffix or issues an authoritative snapshot. Nothing is silently
24
+ * removed from an otherwise contiguous stream, but frames that were never
25
+ * flushed to the socket are NOT promised as delivered — the reconnect
26
+ * replay is the delivery guarantee.
27
+ * - A stalled reader is always released with a bounded deadline. When a
28
+ * write returns false, a drain deadline ends the connection even if the
29
+ * client goes quiet before crossing the byte bound. After `res.end()`, a
30
+ * terminate deadline destroys the response: `end()` alone only queues the
31
+ * FIN behind unflushed data, so a client that never reads would hold the
32
+ * socket (and server shutdown) open forever.
33
+ * - The response `'error'` guard stays attached for the response's lifetime
34
+ * and is idempotent: cleanup can complete while data is still in flight,
35
+ * and a late `'error'` with no listener would crash the process.
36
+ * - A healthy client's connection is independent of a slow one.
37
+ */
38
+
39
+ export const DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
40
+ const DEFAULT_EVENT_STREAM_DRAIN_TIMEOUT_MS = 5_000;
41
+ const DEFAULT_EVENT_STREAM_TERMINATE_TIMEOUT_MS = 5_000;
42
+
43
+ /**
44
+ * Tracks live event stream connections so the server can end all of them
45
+ * (active or still opening) during shutdown.
46
+ */
47
+ export const createPiEventStreamRegistry = () => {
48
+ const connections = new Set();
49
+ return {
50
+ get size() {
51
+ return connections.size;
52
+ },
53
+ add: (connection) => {
54
+ connections.add(connection);
55
+ },
56
+ delete: (connection) => {
57
+ connections.delete(connection);
58
+ },
59
+ /** Idempotent per connection: closing twice closes the subscription once. */
60
+ closeAll: () => {
61
+ for (const connection of [...connections]) connection.close();
62
+ },
63
+ };
64
+ };
65
+
66
+ /**
67
+ * Run one SSE event stream connection to completion.
68
+ *
69
+ * The route must have already validated the query, checked the runtime, and
70
+ * flushed the SSE headers. `subscribe` receives `{ onEvent, onError, signal }`
71
+ * and resolves to a close function (or undefined).
72
+ */
73
+ export const openPiEventStream = ({
74
+ req,
75
+ res,
76
+ subscribe,
77
+ projectFrame,
78
+ heartbeatMs = 15_000,
79
+ maxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
80
+ drainTimeoutMs = DEFAULT_EVENT_STREAM_DRAIN_TIMEOUT_MS,
81
+ terminateTimeoutMs = DEFAULT_EVENT_STREAM_TERMINATE_TIMEOUT_MS,
82
+ registry,
83
+ respondWithError,
84
+ }) => {
85
+ let closed = false;
86
+ let heartbeat;
87
+ let drainTimer;
88
+ let terminateTimer;
89
+ let subscriptionClose;
90
+ let subscriptionClosed = false;
91
+ const abort = new AbortController();
92
+ const connection = { close: () => endConnection() };
93
+
94
+ const closeSubscriptionOnce = (close) => {
95
+ if (subscriptionClosed || typeof close !== 'function') return;
96
+ subscriptionClosed = true;
97
+ try {
98
+ close();
99
+ } catch {
100
+ // A subscriber that throws on close must not break teardown.
101
+ }
102
+ };
103
+
104
+ const isDead = () => closed || res.destroyed === true || res.writableEnded === true;
105
+
106
+ const clearHeartbeat = () => {
107
+ if (heartbeat !== undefined) {
108
+ clearInterval(heartbeat);
109
+ heartbeat = undefined;
110
+ }
111
+ };
112
+
113
+ const clearDrainTimer = () => {
114
+ if (drainTimer !== undefined) {
115
+ clearTimeout(drainTimer);
116
+ drainTimer = undefined;
117
+ }
118
+ };
119
+
120
+ const clearTerminateTimer = () => {
121
+ if (terminateTimer !== undefined) {
122
+ clearTimeout(terminateTimer);
123
+ terminateTimer = undefined;
124
+ }
125
+ };
126
+
127
+ function cleanup() {
128
+ if (closed) return;
129
+ closed = true;
130
+ clearHeartbeat();
131
+ clearDrainTimer();
132
+ clearTerminateTimer();
133
+ abort.abort();
134
+ closeSubscriptionOnce(subscriptionClose);
135
+ req.off('close', onGone);
136
+ res.off('close', onResClose);
137
+ res.off('drain', onDrain);
138
+ // The 'error' guard intentionally stays attached: teardown can complete
139
+ // while data is still in flight, and an unhandled late 'error' would
140
+ // crash the process. It is idempotent (cleanup re-enters as a no-op) and
141
+ // dies with the response object.
142
+ registry?.delete(connection);
143
+ }
144
+
145
+ const onGone = () => cleanup();
146
+ const onDrain = () => clearDrainTimer();
147
+
148
+ const onResClose = () => {
149
+ // The response fully finished (end flushed or destroyed): no further
150
+ // error can occur, so the guard can be detached now. The terminate
151
+ // deadline is cleared even when cleanup already ran (its early return
152
+ // would otherwise leave the timer pending behind a finished response).
153
+ res.off('error', onGone);
154
+ clearTerminateTimer();
155
+ cleanup();
156
+ };
157
+
158
+ /**
159
+ * End the stream after teardown so the client reconnects (shutdown, error,
160
+ * backpressure). The response socket may still hold unflushed data for a
161
+ * stalled reader — `res.end()` alone queues the FIN behind it and the
162
+ * socket stays open forever — so a bounded terminate deadline destroys the
163
+ * socket if it does not finish in time.
164
+ */
165
+ const endConnection = () => {
166
+ cleanup();
167
+ if (!res.writableEnded && !res.destroyed) res.end();
168
+ if (!res.destroyed) {
169
+ // `res.end()` alone only queues the FIN behind unflushed data: a
170
+ // stalled reader never receives it, so the socket (and server
171
+ // shutdown) stays open forever. Bound the wait and destroy. The timer
172
+ // is cleared only by the response's 'close' event — 'finish' fires as
173
+ // soon as the data is handed to the socket, which proves nothing about
174
+ // the socket actually releasing.
175
+ terminateTimer = setTimeout(() => {
176
+ terminateTimer = undefined;
177
+ if (!res.destroyed) res.destroy();
178
+ }, terminateTimeoutMs);
179
+ }
180
+ };
181
+
182
+ /** Bound the wait for 'drain' after a full socket buffer, even for a client that then goes quiet. */
183
+ const armDrainDeadline = () => {
184
+ if (drainTimer !== undefined) return;
185
+ res.once('drain', onDrain);
186
+ drainTimer = setTimeout(() => {
187
+ drainTimer = undefined;
188
+ res.off('drain', onDrain);
189
+ // A socket that never drains must not hold the connection (and server
190
+ // shutdown) open indefinitely: end it so the client reconnects from its
191
+ // last accepted sequence and the daemon replays or snapshots.
192
+ endConnection();
193
+ }, drainTimeoutMs);
194
+ };
195
+
196
+ const write = (chunk) => {
197
+ if (isDead()) return false;
198
+ const size = Buffer.byteLength(chunk);
199
+ // Enforce the byte bound BEFORE writing: a frame that would not fit is
200
+ // never written, so the socket buffer never overshoots the bound by one
201
+ // huge frame. Everything after this point is skipped because cleanup ends
202
+ // the stream, so the client never observes a silently missing frame
203
+ // inside an otherwise contiguous stream — it reconnects from its last
204
+ // accepted sequence and the daemon replays or snapshots.
205
+ if (res.writableLength + size > maxBufferedBytes) {
206
+ endConnection();
207
+ return false;
208
+ }
209
+ const drained = res.write(chunk);
210
+ if (!drained) armDrainDeadline();
211
+ return drained;
212
+ };
213
+
214
+ const send = (frame) => {
215
+ if (isDead()) return;
216
+ const event = projectFrame(frame);
217
+ if (event) write(`data: ${JSON.stringify(event)}\n\n`);
218
+ };
219
+
220
+ // Install cleanup before awaiting subscribe so a disconnect during the
221
+ // opening window cannot leak the daemon subscription.
222
+ req.once('close', onGone);
223
+ res.once('close', onResClose);
224
+ res.on('error', onGone);
225
+ registry?.add(connection);
226
+
227
+ void (async () => {
228
+ let attach;
229
+ try {
230
+ attach = await subscribe({
231
+ onEvent: send,
232
+ onError: endConnection,
233
+ signal: abort.signal,
234
+ });
235
+ } catch (error) {
236
+ cleanup();
237
+ if (typeof respondWithError === 'function') respondWithError(error);
238
+ else if (!res.writableEnded && !res.destroyed) res.end();
239
+ return;
240
+ }
241
+ // The client disconnected, the subscription errored, or the server shut
242
+ // down while the subscription was opening: close the late subscription
243
+ // exactly once and never attach a heartbeat to a dead response.
244
+ if (closed) {
245
+ closeSubscriptionOnce(attach);
246
+ return;
247
+ }
248
+ subscriptionClose = attach;
249
+
250
+ const sendHeartbeat = () => {
251
+ if (isDead()) return;
252
+ // Named heartbeat events are visible to native EventSource clients.
253
+ // Comment-only SSE heartbeats keep proxies open but are hidden from the
254
+ // EventSource API, so WKWebView cannot use them to detect a silent link.
255
+ write('event: heartbeat\ndata: {}\n\n');
256
+ };
257
+ // Send one immediately so an empty replay still proves the connection is
258
+ // healthy before the client resets its reconnect backoff.
259
+ sendHeartbeat();
260
+ heartbeat = setInterval(sendHeartbeat, heartbeatMs);
261
+ })();
262
+
263
+ return {
264
+ get closed() {
265
+ return closed;
266
+ },
267
+ abortSignal: abort.signal,
268
+ };
269
+ };