@pi-chamber/web 0.9.6 → 0.9.7

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 (85) hide show
  1. package/dist/assets/{DiagramView-0Iq1ak1I.js → DiagramView-BvrCkm_z.js} +1 -1
  2. package/dist/assets/{DiffView-DD1AFRi3.js → DiffView-DMvRLRN1.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-CoKwDovb.js → FileSaveConflictDialog-DGa9u43J.js} +1 -1
  4. package/dist/assets/{FilesView-B_BF39ef.js → FilesView-CNHu4RnC.js} +4 -4
  5. package/dist/assets/{GitView-LFEpCasf.js → GitView-Cbepz-bR.js} +3 -3
  6. package/dist/assets/{JsonTreeView-Cwjgvh4g.js → JsonTreeView-C2X5oXQm.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-_7kV1yNw.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
  8. package/dist/assets/{PatchDiff-DG43C1HW.js → PatchDiff-i_9BIlgo.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-DCFXPY3d.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-QY7FKuEQ.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-DGT31A3z.js → SessionUnreadDot-CDRZswx-.js} +1 -1
  12. package/dist/assets/SettingsView-hyAGp836.js +2 -0
  13. package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
  14. package/dist/assets/{ToolOutputDialog-IlCrS6BR.js → ToolOutputDialog-CJ87b80H.js} +5 -5
  15. package/dist/assets/{ToolPartDiffPreview-D68JV0rR.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-Bl-rAYeh.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
  17. package/dist/assets/{collapsible-BjniCdZ5.js → collapsible-DesjbW8a.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-FSOm2VrW.js → computeVirtualFileMetrics-CsAu9rOt.js} +1 -1
  19. package/dist/assets/{contextFileOpenGuard-Bxb6AIPa.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-DxolDpMd.js → gitStatusPredicates-D_31YElh.js} +1 -1
  21. package/dist/assets/index-BXgR2dKM.css +1 -0
  22. package/dist/assets/index-BZpvAhrX.js +8 -0
  23. package/dist/assets/{index-Dh58uD3I.js → index-CXLVW_GG.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-D3_04XCh.js → isDiffPlainText-BX609Lau.js} +1 -1
  25. package/dist/assets/{isFilePlainText-CHouYQhH.js → isFilePlainText-FgBWqu9b.js} +1 -1
  26. package/dist/assets/{main-CH3EqGJI.js → main-C_pL2r_k.js} +2 -2
  27. package/dist/assets/{main-HzTrVvbB.js → main-tv2uysSs.js} +7 -7
  28. package/dist/assets/{markdownCore-DJU4KvHP.js → markdownCore-D3Ibaffd.js} +1 -1
  29. package/dist/assets/{miniChat-Ca3TpaaA.js → miniChat-B0xQlBzZ.js} +2 -2
  30. package/dist/assets/{mobile-lj4gpGsO.js → mobile-BmSlVuhn.js} +2 -2
  31. package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
  32. package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
  33. package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
  34. package/dist/assets/{runtimeSurface-CE_VNjdH.js → runtimeSurface-egSD9pqj.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-BvFAP9zG.js → useAppFontEffects-C9QQrBIx.js} +104 -104
  36. package/dist/assets/{useFilesViewSearch-BD79p3A2.js → useFilesViewSearch-BTZutbn-.js} +2 -2
  37. package/dist/assets/{usePushVisibilityBeacon-CWg0j-Wg.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
  38. package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
  39. package/dist/assets/{vendor-codemirror-language-data-CP3j3-xu.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
  40. package/dist/assets/{web-components-DWuadqra.js → web-components-CYngz9Ml.js} +1 -1
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/index.js +17 -3
  46. package/server/lib/client-auth/DOCUMENTATION.md +184 -0
  47. package/server/lib/client-auth/live-revocation.test.js +567 -0
  48. package/server/lib/client-auth/principal-tracker.js +383 -0
  49. package/server/lib/client-auth/principal-tracker.test.js +321 -0
  50. package/server/lib/client-auth/remote-clients.js +31 -0
  51. package/server/lib/client-auth/remote-clients.test.js +44 -0
  52. package/server/lib/pi/event-stream.js +269 -0
  53. package/server/lib/pi/event-stream.test.js +776 -0
  54. package/server/lib/pi/routes.js +76 -25
  55. package/server/lib/pi/routes.test.js +48 -4
  56. package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -4
  57. package/server/lib/pi/session-daemon/ipc-client.js +19 -15
  58. package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
  59. package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
  60. package/server/lib/pi/session-daemon/session-daemon.js +55 -6
  61. package/server/lib/pi/session-daemon/session-daemon.test.js +10 -4
  62. package/server/lib/pi/session-daemon/session-replay.test.js +8 -3
  63. package/server/lib/pi/session-daemon/supervisor.js +30 -5
  64. package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
  65. package/server/lib/pi/ui-settings-store.js +1 -1
  66. package/server/lib/pi/ui-settings-store.test.js +3 -1
  67. package/server/lib/server/core-routes.js +11 -1
  68. package/server/lib/stt/DOCUMENTATION.md +2 -0
  69. package/server/lib/stt/runtime.js +39 -2
  70. package/server/lib/stt/runtime.test.js +53 -0
  71. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  72. package/server/lib/terminal/runtime.js +48 -2
  73. package/server/lib/terminal/runtime.test.js +35 -0
  74. package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
  75. package/server/lib/ui-auth/ui-auth.js +98 -0
  76. package/server/lib/ui-auth/ui-auth.test.js +249 -0
  77. package/server/lib/workspace/host.js +3 -1
  78. package/dist/assets/SettingsView-eG-wN-yY.js +0 -2
  79. package/dist/assets/SettingsWindow-Dvnp8YrA.js +0 -1
  80. package/dist/assets/index-BpmGBboM.css +0 -1
  81. package/dist/assets/index-DZnzXhTs.js +0 -8
  82. package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +0 -2
  83. package/dist/assets/renderMobileApp-CcWQ1sCf.js +0 -11
  84. package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +0 -53
  85. package/dist/assets/useSwitcherItems-CazJ6Yox.js +0 -1
@@ -54,7 +54,7 @@ const LOCAL_FIELDS = new Set([
54
54
  'securityScopedBookmarks', 'pinnedDirectories', 'defaultGitIdentityId', 'openInAppId',
55
55
  'terminalShell', 'terminalLoginShells', 'desktopLanAccessEnabled',
56
56
  'desktopKeepAwakeEnabled', 'desktopProcessPerformanceRecordingEnabled',
57
- 'desktopMinimizeToTrayEnabled', 'desktopMacMenuBarEnabled',
57
+ 'desktopMinimizeToTrayEnabled', 'desktopCloseToTrayEnabled', 'desktopMacMenuBarEnabled',
58
58
  'desktopWindowState', 'desktopLocalPort', 'desktopInstallId', 'desktopHosts',
59
59
  'desktopDefaultHostId', 'desktopInitialHostChoiceCompleted',
60
60
  'pwaAppName', 'pwaOrientation', 'mobileKeyboardMode',
@@ -68,11 +68,12 @@ describe('Pi UI settings store', () => {
68
68
  const { file, runtimeFile, store } = await makeStore();
69
69
  await Promise.all([
70
70
  store.write({ themeId: 'dark' }),
71
- store.write({ projects: [{ id: 'one', path: '/one' }] }),
71
+ store.write({ projects: [{ id: 'one', path: '/one' }], desktopCloseToTrayEnabled: false }),
72
72
  ]);
73
73
  await expect(store.read()).resolves.toEqual({
74
74
  themeId: 'dark',
75
75
  projects: [{ id: 'one', path: '/one' }],
76
+ desktopCloseToTrayEnabled: false,
76
77
  });
77
78
  await expect(readJson(file)).resolves.toEqual({
78
79
  __pichamberSettingsScope: 'portable-v1',
@@ -80,6 +81,7 @@ describe('Pi UI settings store', () => {
80
81
  });
81
82
  await expect(readJson(runtimeFile)).resolves.toEqual({
82
83
  projects: [{ id: 'one', path: '/one' }],
84
+ desktopCloseToTrayEnabled: false,
83
85
  });
84
86
  });
85
87
 
@@ -391,6 +391,11 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
391
391
  remoteClientAuthRuntime,
392
392
  clientPairingRuntime,
393
393
  readSettingsFromDiskMigrated,
394
+ // Live-revocation coordinator: closes the revoked principal's tracked
395
+ // live connections (SSE, terminal/dictation WebSocket) in this process
396
+ // immediately after the store write commits. Cross-process convergence
397
+ // is the coordinator's bounded poll, not this emitter.
398
+ liveRevocation = null,
394
399
  normalizeTunnelSessionTtlMs,
395
400
  // Returns the relay pairing candidate ({ type:'relay', relayUrl, serverId,
396
401
  // hostEncPubJwk, priority }) when the host relay is enabled, else null.
@@ -821,8 +826,13 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
821
826
  if (!result.revoked) {
822
827
  return res.status(404).json({ revoked: false, error: 'Client not found' });
823
828
  }
829
+ // Close the revoked principal's live connections now that the store
830
+ // marks them revoked; new bearer/URL-token establishment is denied by
831
+ // the credential checks. The revoked device's own request may be the
832
+ // one being closed — the count reports what was torn down.
833
+ const closedConnections = liveRevocation?.clientRevoked?.(result.client.id) ?? 0;
824
834
  void reconcileRelay();
825
- res.json(result);
835
+ res.json({ ...result, closedConnections });
826
836
  });
827
837
  });
828
838
 
@@ -21,6 +21,8 @@ This module owns final-only composer dictation for web, Electron, hosted mobile,
21
21
 
22
22
  All routes use the existing `/api` authentication middleware. The WebSocket path is in both the URL-token and private-relay allowlists. Shared UI opens it through `openRuntimeWebSocket` with the token returned by that connection's URL-auth mint. A failed older connection cannot clear a newer shared token.
23
23
 
24
+ This runtime owns the WebSocket's auth and connection lifetime: the upgrade re-validates the principal (credential store or signing secret) at establishment, so a URL token minted before a revocation or global sign-out is denied at open; the coordinator generation is captured before the auth/origin awaits and passed at track time, so a revocation racing verification reject-closes without trusting the principal and `handleUpgrade` is skipped for inactive entries. After the upgrade the connection is registered with the live-revocation coordinator under the authenticated principal, so a later revocation closes the socket within the documented latency guarantee. The 60-second URL token TTL gates establishment only — it never schedules a connection's death. Resource bounds (50 per principal / 1000 global) reject-close with `close('over-limit')` without evicting unrelated sockets. See `../client-auth/DOCUMENTATION.md`.
25
+
24
26
  Remote URL and API-key values live in `<PiChamber data>/stt/config.json` with owner-only permissions where the platform supports them. Status responses redact API keys. WebSocket start frames carry only a stored provider configuration ID. They never accept a URL or credential.
25
27
 
26
28
  Local models live under `<PiChamber data>/speech-models`. Downloads verify a pinned archive size and SHA-256 checksum, extract into a staging directory, hash required installed files into a manifest, and rename only after verification. Missing, changed-size, or checksum-invalid models are removed before retry. The main server process never imports `sherpa-onnx-node`; only `worker-process.js` does.
@@ -6,7 +6,7 @@ import { SttStreamManager } from './stream-manager.js';
6
6
 
7
7
  const HEARTBEAT_MS = 30_000;
8
8
 
9
- export function createSttRuntime({ app, server, express, uiAuthController, isRequestOriginAllowed, rejectWebSocketUpgrade, modelsDir, configFile }) {
9
+ export function createSttRuntime({ app, server, express, uiAuthController, isRequestOriginAllowed, rejectWebSocketUpgrade, modelsDir, configFile, liveRevocation = null }) {
10
10
  const service = createSttService({ modelsDir, configFile });
11
11
  const manager = new SttStreamManager({ createTranscriber: (providerConfigId) => service.createTranscriber(providerConfigId) });
12
12
 
@@ -82,15 +82,52 @@ export function createSttRuntime({ app, server, express, uiAuthController, isReq
82
82
  socket.on('error', () => {});
83
83
  });
84
84
 
85
+ const trackUpgradePrincipal = (socket, principal, generation) => {
86
+ if (!principal || typeof liveRevocation?.trackLiveConnection !== 'function') return null;
87
+ let tracked;
88
+ try {
89
+ tracked = liveRevocation.trackLiveConnection({
90
+ principal,
91
+ close: () => {
92
+ if (!socket.destroyed) socket.destroy();
93
+ },
94
+ generation,
95
+ });
96
+ } catch {
97
+ try { if (!socket.destroyed) socket.destroy(); } catch {}
98
+ // A throwing tracker already destroyed the socket above; return an
99
+ // inactive entry so the caller skips handleUpgrade like any other
100
+ // rejected registration instead of upgrading a destroyed socket.
101
+ return { active: false, end: () => {}, revoke: () => false };
102
+ }
103
+ // Covers the pending window, a failed upgrade, and the natural close.
104
+ // Rejected registrations already destroyed the socket; the inactive entry
105
+ // signals the caller to skip handleUpgrade.
106
+ socket.once('close', () => tracked.end());
107
+ return tracked;
108
+ };
109
+
85
110
  const upgradeHandler = (req, socket, head) => {
86
111
  if (parseRequestPathname(req.url) !== STT_WS_PATH) return;
87
112
  void (async () => {
88
113
  try {
114
+ let principal = null;
115
+ let generation;
116
+ try {
117
+ if (typeof liveRevocation?.getGeneration === 'function') generation = liveRevocation.getGeneration();
118
+ } catch {
119
+ generation = undefined;
120
+ }
89
121
  if (uiAuthController?.enabled) {
90
- if (!await uiAuthController.ensureSessionToken(req, null)) { rejectWebSocketUpgrade(socket, 401, 'UI authentication required'); return; }
122
+ principal = await uiAuthController.ensureSessionToken(req, null);
123
+ if (!principal) { rejectWebSocketUpgrade(socket, 401, 'UI authentication required'); return; }
91
124
  if (!await isRequestOriginAllowed(req)) { rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); return; }
92
125
  }
93
126
  if (!wsServer) { rejectWebSocketUpgrade(socket, 503, 'STT WebSocket unavailable'); return; }
127
+ // Deterministic verify-registration barrier, as in the terminal
128
+ // runtime: generation captured before the auth/origin awaits.
129
+ const tracked = trackUpgradePrincipal(socket, principal, generation);
130
+ if (principal && tracked && tracked.active === false) return;
94
131
  wsServer.handleUpgrade(req, socket, head, (ws) => wsServer.emit('connection', ws, req));
95
132
  } catch { rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }
96
133
  })();
@@ -0,0 +1,53 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { describe, expect, test } from 'bun:test';
3
+ import { WebSocketServer } from 'ws';
4
+
5
+ import { createSttRuntime } from './runtime.js';
6
+
7
+ describe('STT runtime upgrade', () => {
8
+ test('skips handleUpgrade when principal tracking throws', async () => {
9
+ const originalHandleUpgrade = WebSocketServer.prototype.handleUpgrade;
10
+ let handleUpgradeCalls = 0;
11
+ WebSocketServer.prototype.handleUpgrade = function () {
12
+ handleUpgradeCalls += 1;
13
+ return undefined;
14
+ };
15
+ const app = {
16
+ get() {},
17
+ put() {},
18
+ post() {},
19
+ delete() {},
20
+ };
21
+ const express = { json: () => (_req, _res, next) => next?.() };
22
+ const server = new EventEmitter();
23
+ const runtime = createSttRuntime({
24
+ app,
25
+ server,
26
+ express,
27
+ uiAuthController: {
28
+ enabled: true,
29
+ ensureSessionToken: async () => 'client:thrower',
30
+ },
31
+ isRequestOriginAllowed: async () => true,
32
+ rejectWebSocketUpgrade: () => {},
33
+ modelsDir: '/tmp/stt-test-models',
34
+ configFile: '/tmp/stt-test-config.json',
35
+ liveRevocation: {
36
+ getGeneration: () => 0,
37
+ trackLiveConnection: () => { throw new Error('tracker boom'); },
38
+ },
39
+ });
40
+ try {
41
+ const socket = new EventEmitter();
42
+ socket.destroyed = false;
43
+ socket.destroy = function () { this.destroyed = true; };
44
+ server.emit('upgrade', { url: '/api/stt/ws', headers: {} }, socket, Buffer.alloc(0));
45
+ await new Promise((resolve) => setTimeout(resolve, 10));
46
+ expect(socket.destroyed).toBe(true);
47
+ expect(handleUpgradeCalls).toBe(0);
48
+ } finally {
49
+ WebSocketServer.prototype.handleUpgrade = originalHandleUpgrade;
50
+ await runtime.shutdown();
51
+ }
52
+ });
53
+ });
@@ -38,6 +38,8 @@ HTTP remains the authenticated command plane for create, resize, appearance upda
38
38
 
39
39
  The WebSocket path must remain in both `isUrlAuthWebSocketPath` and relay `ALLOWED_WS_PATHS`. The client must use `getRuntimeUrlResolver().websocket()` and `openRuntimeWebSocket`; direct local URLs or raw browser WebSockets break relay and URL-token authentication.
40
40
 
41
+ This runtime owns the WebSocket's auth and connection lifetime: the upgrade re-validates the principal (credential store or signing secret) at establishment, so an already-minted URL token minted before a revocation or global sign-out is denied at open; the coordinator generation is captured before the auth/origin awaits and passed at track time, so a revocation racing verification reject-closes without trusting the principal and `handleUpgrade` is skipped for inactive entries. After the upgrade the connection is registered with the live-revocation coordinator under the authenticated principal, so a later revocation closes the socket within the documented latency guarantee. The 60-second URL token TTL gates establishment only — it never schedules a connection's death. Resource bounds (50 per principal / 1000 global) reject-close with `close('over-limit')` without evicting unrelated sockets. See `../client-auth/DOCUMENTATION.md`.
42
+
41
43
  ## Verification
42
44
 
43
45
  Run:
@@ -29,7 +29,11 @@ const trimHistory = (history) => {
29
29
  export function createTerminalRuntime({
30
30
  app, server, fs, path, uiAuthController, buildAugmentedPath, searchPathFor, isExecutable,
31
31
  isRequestOriginAllowed, rejectWebSocketUpgrade, TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS,
32
- loadPtyProvider, terminalTerminationGraceMs = TERMINATION_GRACE_MS,
32
+ // Live-revocation owner for this transport: upgrades are tracked under the
33
+ // authenticated principal so a later revocation or global invalidation
34
+ // closes the socket. Lifetime is not tied to the 60-second URL token TTL
35
+ // used to establish the connection.
36
+ liveRevocation = null, loadPtyProvider, terminalTerminationGraceMs = TERMINATION_GRACE_MS,
33
37
  }) {
34
38
  const sessions = new Map();
35
39
  const pendingSessionCreates = new Map();
@@ -274,15 +278,57 @@ export function createTerminalRuntime({
274
278
  socket.on('close', cleanup); socket.on('error', () => {});
275
279
  });
276
280
 
281
+ const trackUpgradePrincipal = (socket, principal, generation) => {
282
+ if (!principal || typeof liveRevocation?.trackLiveConnection !== 'function') return null;
283
+ let tracked;
284
+ try {
285
+ tracked = liveRevocation.trackLiveConnection({
286
+ principal,
287
+ close: () => {
288
+ if (!socket.destroyed) socket.destroy();
289
+ },
290
+ generation,
291
+ });
292
+ } catch {
293
+ try { if (!socket.destroyed) socket.destroy(); } catch {}
294
+ // A throwing tracker already destroyed the socket above; return an
295
+ // inactive entry so the caller skips handleUpgrade like any other
296
+ // rejected registration instead of upgrading a destroyed socket.
297
+ return { active: false, end: () => {}, revoke: () => false };
298
+ }
299
+ // Covers the pending window (gates passed, upgrade not yet handled), a
300
+ // failed upgrade, and the natural close after the WebSocket is live.
301
+ // Rejected registrations (revoked/stale-generation/over-limit/disposed)
302
+ // already destroyed the socket via close(); the inactive entry keeps the
303
+ // close handler safe and signals the caller to skip handleUpgrade.
304
+ socket.once('close', () => tracked.end());
305
+ return tracked;
306
+ };
307
+
277
308
  const upgradeHandler = (req, socket, head) => {
278
309
  if (parseRequestPathname(req.url) !== TERMINAL_WS_PATH) return;
279
310
  void (async () => {
280
311
  try {
312
+ let principal = null;
313
+ let generation;
314
+ try {
315
+ if (typeof liveRevocation?.getGeneration === 'function') generation = liveRevocation.getGeneration();
316
+ } catch {
317
+ generation = undefined;
318
+ }
281
319
  if (uiAuthController?.enabled) {
282
- if (!await uiAuthController.ensureSessionToken(req, null)) { rejectWebSocketUpgrade(socket, 401, 'UI authentication required'); return; }
320
+ principal = await uiAuthController.ensureSessionToken(req, null);
321
+ if (!principal) { rejectWebSocketUpgrade(socket, 401, 'UI authentication required'); return; }
283
322
  if (!await isRequestOriginAllowed(req)) { rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); return; }
284
323
  }
285
324
  if (!wsServer) { rejectWebSocketUpgrade(socket, 500, 'Terminal WebSocket unavailable'); return; }
325
+ // Deterministic verify-registration barrier: generation was captured
326
+ // before the auth/origin awaits, so a revocation or global
327
+ // invalidation racing verification reject-closes here without trusting
328
+ // the principal. An inactive entry means the socket is already
329
+ // destroyed — never call handleUpgrade for it.
330
+ const tracked = trackUpgradePrincipal(socket, principal, generation);
331
+ if (principal && tracked && tracked.active === false) return;
286
332
  wsServer.handleUpgrade(req, socket, head, (ws) => wsServer.emit('connection', ws, req));
287
333
  } catch { rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }
288
334
  })();
@@ -563,4 +563,39 @@ describe('terminal runtime', () => {
563
563
  await new Promise((resolve) => server.close(resolve));
564
564
  }
565
565
  }, 15_000);
566
+
567
+ it('skips handleUpgrade when principal tracking throws', async () => {
568
+ const { WebSocketServer } = await import('ws');
569
+ const originalHandleUpgrade = WebSocketServer.prototype.handleUpgrade;
570
+ let handleUpgradeCalls = 0;
571
+ WebSocketServer.prototype.handleUpgrade = function () {
572
+ handleUpgradeCalls += 1;
573
+ return undefined;
574
+ };
575
+ const server = new EventEmitter();
576
+ const runtime = createRuntime(server, {
577
+ uiAuthController: {
578
+ enabled: true,
579
+ ensureSessionToken: async () => 'client:thrower',
580
+ },
581
+ isRequestOriginAllowed: async () => true,
582
+ rejectWebSocketUpgrade: () => {},
583
+ liveRevocation: {
584
+ getGeneration: () => 0,
585
+ trackLiveConnection: () => { throw new Error('tracker boom'); },
586
+ },
587
+ });
588
+ try {
589
+ const socket = new EventEmitter();
590
+ socket.destroyed = false;
591
+ socket.destroy = function () { this.destroyed = true; };
592
+ server.emit('upgrade', { url: '/api/terminal/ws', headers: {} }, socket, Buffer.alloc(0));
593
+ await new Promise((resolve) => setTimeout(resolve, 10));
594
+ expect(socket.destroyed).toBe(true);
595
+ expect(handleUpgradeCalls).toBe(0);
596
+ } finally {
597
+ WebSocketServer.prototype.handleUpgrade = originalHandleUpgrade;
598
+ await runtime.shutdown();
599
+ }
600
+ });
566
601
  });
@@ -9,18 +9,27 @@ Pairing v2 is implemented by `packages/web/server/lib/client-auth/pairing.js`. I
9
9
 
10
10
  Browser WebSocket clients mint a 60-second `oc_url_token` through the authenticated `/auth/url-token` route because the WebSocket constructor cannot attach an Authorization header. The token is encrypted with a key derived from the server's persisted JWT secret, so an ordinary server restart does not invalidate a token that the browser may still use. Global sign-out rotates that secret and invalidates outstanding tokens. The token is accepted only for the explicit WebSocket allowlist, currently `/api/terminal/ws` and `/api/stt/ws`; ordinary API routes and unknown upgrade paths reject it. The token resolves to the UI session or remote-client identity that minted it.
11
11
 
12
+ The 60-second URL token TTL gates **establishment only**. Every establishment (WebSocket upgrade, SSE event-stream request) re-validates the embedded principal — client principals against the credential store, UI session principals against the current signing secret — so a token minted before a revocation or global sign-out is denied at open time (the mint/open race). An established connection's lifetime is governed by live revocation tracking, never by token expiry; see `../client-auth/DOCUMENTATION.md` for the latency guarantee (immediate in-process closure, bounded poll after the next successful read on healthy storage) and resource bounds (50 per principal / 1000 global / 2000 revoked IDs).
13
+
14
+ Verify-registration barrier: `requireAuth` captures the coordinator generation (`liveRevocation.getGeneration()`) BEFORE its first auth await and passes it to `trackLiveConnection`, so a global invalidation racing verification is rejected without trusting the principal. WebSocket upgrades capture the same generation before `ensureSessionToken`/origin and skip `handleUpgrade` for inactive entries. Per-principal revokes are covered by the coordinator's revoked-ID memory even without the generation.
15
+
16
+ Signing-secret topology: the JWT secret is read once at startup (env override or persisted file) and cached in memory; `rotateJwtSecret` rewrites the file and rereads into memory synchronously, so new cookies and URL tokens bind to the new generation. Rotation is single-server only — the pairing CLI never rotates the secret and multi-server sharing is unsupported. While `PICHAMBER_JWT_SECRET` is set, `/auth/reset` returns 400 without side effects; global sign-out is unavailable.
17
+
12
18
  ## Entrypoints and structure
13
- - `packages/web/server/lib/ui-auth/ui-auth.js`: UI auth controller runtime, cookie/session issuance, rate limiting, and auth route handlers.
19
+ - `packages/web/server/lib/ui-auth/ui-auth.js`: UI auth controller runtime, cookie/session issuance, rate limiting, auth route handlers, and the auth-owning boundary where authenticated SSE event streams are registered for live revocation.
14
20
  - `packages/web/server/lib/ui-auth/ui-passkeys.js`: passkey store and WebAuthn registration/authentication verification helpers.
15
21
  - `packages/web/server/lib/client-auth/remote-clients.js`: trusted-device client token storage, bearer authentication, last-used tracking, and revocation.
16
22
  - `packages/web/server/lib/client-auth/pairing.js`: short-lived Pairing v2 sessions and one-time secret redemption into trusted-device client tokens.
17
23
 
18
24
  ## Public exports (ui-auth.js)
19
- - `createUiAuth({ password, cookieName, sessionTtlMs, readSettingsFromDiskMigrated })`: creates UI auth controller with methods:
25
+ - `createUiAuth({ password, cookieName, sessionTtlMs, readSettingsFromDiskMigrated, clientAuthController, requireClientAuth, liveRevocation })`: creates UI auth controller with methods:
20
26
  - `enabled`
21
- - `requireAuth(req, res, next)`
27
+ - `requireAuth(req, res, next)` — also registers authenticated `/api/pi/events` GET requests under their verified principal with `liveRevocation`
28
+ - `requireSessionAuth(req, res, next)`
29
+ - `resolveAuthContext(req, res, { allowClientAuth, allowUrlToken })`
22
30
  - `handleSessionStatus(req, res)`
23
31
  - `handleSessionCreate(req, res)`
32
+ - `handleUrlAuthToken(req, res)` — mints 60-second establishment tokens
24
33
  - `handlePasskeyStatus(req, res)`
25
34
  - `handlePasskeyRegistrationOptions(req, res)`
26
35
  - `handlePasskeyRegistrationVerify(req, res)`
@@ -28,7 +37,7 @@ Browser WebSocket clients mint a 60-second `oc_url_token` through the authentica
28
37
  - `handlePasskeyAuthenticationVerify(req, res)`
29
38
  - `handlePasskeyList(req, res)`
30
39
  - `handlePasskeyRevoke(req, res)`
31
- - `handleResetAuth(req, res)`
40
+ - `handleResetAuth(req, res)` — global sign-out: rotates the signing secret AND closes all tracked live connections; 400 without side effects while `PICHAMBER_JWT_SECRET` is set
32
41
  - `ensureSessionToken(req, res)`
33
42
  - `dispose()`
34
43
 
@@ -294,6 +294,11 @@ const isWebSocketUpgrade = (req) => {
294
294
 
295
295
  const isUrlAuthReadableHttpPath = (pathname) => pathname === '/api/pi/events';
296
296
 
297
+ const isEventStreamRequest = (req) => {
298
+ const method = typeof req?.method === 'string' ? req.method.toUpperCase() : 'GET';
299
+ return method === 'GET' && isUrlAuthReadableHttpPath(getRequestPathname(req));
300
+ };
301
+
297
302
  const URL_AUTH_WEBSOCKET_PATHS = new Set([
298
303
  '/api/terminal/ws',
299
304
  '/api/stt/ws',
@@ -404,9 +409,13 @@ export const createUiAuth = ({
404
409
  readSettingsFromDiskMigrated,
405
410
  clientAuthController = null,
406
411
  requireClientAuth = false,
412
+ liveRevocation = null,
407
413
  } = {}) => {
408
414
  const normalizedPassword = normalizePassword(password);
409
415
  let jwtSecret = getOrCreateJwtSecret();
416
+ // Set by the password branch; lets the shared URL-token establishment path
417
+ // re-validate UI-session principals against the current signing secret.
418
+ let verifySessionToken = null;
410
419
 
411
420
  const getUrlAuthEncryptionKey = () => crypto.createHash('sha256').update(jwtSecret).digest();
412
421
 
@@ -420,6 +429,24 @@ export const createUiAuth = ({
420
429
  return { token: `${URL_AUTH_TOKEN_PREFIX}${encryptedToken}`, expiresAt };
421
430
  };
422
431
 
432
+ const isPrincipalValidForEstablishment = async (sessionToken) => {
433
+ if (typeof sessionToken !== 'string' || sessionToken.length === 0) return false;
434
+ if (sessionToken.startsWith('client:')) {
435
+ if (typeof clientAuthController?.isClientValid !== 'function') return true;
436
+ try {
437
+ return await clientAuthController.isClientValid(sessionToken.slice('client:'.length)) === true;
438
+ } catch {
439
+ return false;
440
+ }
441
+ }
442
+ if (typeof verifySessionToken !== 'function') return true;
443
+ try {
444
+ return await verifySessionToken(sessionToken) === true;
445
+ } catch {
446
+ return false;
447
+ }
448
+ };
449
+
423
450
  const authenticateUrlAuthToken = async (req) => {
424
451
  if (!canUseUrlAuthTokenForRequest(req)) return null;
425
452
  const token = getUrlAuthTokenFromRequest(req);
@@ -430,6 +457,12 @@ export const createUiAuth = ({
430
457
  contentEncryptionAlgorithms: ['A256GCM'],
431
458
  });
432
459
  if (payload.type !== 'url-auth' || typeof payload.sessionToken !== 'string' || !payload.sessionToken) return null;
460
+ // The 60-second token TTL gates establishment only; it is not a
461
+ // connection lifetime grant. Re-validate the embedded principal against
462
+ // the credential store (revocation) and the current signing secret
463
+ // (global invalidation) so a token minted before either event is denied
464
+ // at open time — the mint/open race.
465
+ if (!await isPrincipalValidForEstablishment(payload.sessionToken)) return null;
433
466
  return { ok: true, sessionToken: payload.sessionToken };
434
467
  } catch {
435
468
  return null;
@@ -475,6 +508,45 @@ export const createUiAuth = ({
475
508
  client: clientAuth?.client || null,
476
509
  });
477
510
 
511
+ // Live revocation at the auth-owning boundary: a successfully authenticated
512
+ // SSE event-stream request is tracked under the principal derived from its
513
+ // verified credential (never a client-supplied ID), so a later revocation
514
+ // or global invalidation can close it. Lifetime is governed by the tracker,
515
+ // not by the 60-second URL token TTL used to establish the connection.
516
+ // `generation` must be the coordinator generation captured BEFORE the
517
+ // caller's first auth await; a stale value reject-closes the late
518
+ // registration (verify-registration race) without trusting the principal.
519
+ const trackEventStreamPrincipal = (req, res, principal, generation) => {
520
+ if (!liveRevocation || typeof liveRevocation.trackLiveConnection !== 'function') return;
521
+ if (!isEventStreamRequest(req)) return;
522
+ if (typeof principal !== 'string' || principal.length === 0) return;
523
+ let entry;
524
+ try {
525
+ entry = liveRevocation.trackLiveConnection({
526
+ principal,
527
+ close: () => {
528
+ if (res.destroyed || res.writableEnded) return;
529
+ res.destroy();
530
+ },
531
+ generation,
532
+ });
533
+ } catch {
534
+ return;
535
+ }
536
+ // Rejected registrations (revoked/stale-generation/over-limit/disposed)
537
+ // already destroyed the response via close(); attaching end() is still
538
+ // safe (inactive entries are no-ops) and covers the natural-close path.
539
+ res.once?.('close', () => entry.end());
540
+ };
541
+
542
+ const captureLiveGeneration = () => {
543
+ try {
544
+ if (typeof liveRevocation?.getGeneration === 'function') return liveRevocation.getGeneration();
545
+ } catch {
546
+ }
547
+ return undefined;
548
+ };
549
+
478
550
  if (!normalizedPassword) {
479
551
  const setSessionCookie = (req, res, token, ttlMs = sessionTtlMs) => {
480
552
  const secure = isSecureRequest(req);
@@ -505,8 +577,10 @@ export const createUiAuth = ({
505
577
  if (req.method === 'OPTIONS') {
506
578
  return next();
507
579
  }
580
+ const generation = captureLiveGeneration();
508
581
  const clientAuth = await authenticateClientRequest(req);
509
582
  if (clientAuth) {
583
+ trackEventStreamPrincipal(req, res, clientSessionToken(clientAuth), generation);
510
584
  return next();
511
585
  }
512
586
  return res.status(401).json({ error: 'Client authentication required', locked: true, clientAuthRequired: true });
@@ -689,6 +763,7 @@ export const createUiAuth = ({
689
763
  return false;
690
764
  }
691
765
  };
766
+ verifySessionToken = isSessionValid;
692
767
 
693
768
  const issueSession = async (req, res, { trustDevice = false } = {}) => {
694
769
  const ttlMs = resolveSessionTtlMs(trustDevice);
@@ -717,12 +792,19 @@ export const createUiAuth = ({
717
792
  if (req.method === 'OPTIONS') {
718
793
  return next();
719
794
  }
795
+ // Deterministic verify-registration barrier: capture the live generation
796
+ // before the first await so a global invalidation racing verification is
797
+ // rejected at track time. Per-principal revokes are covered by the
798
+ // coordinator's revoked-ID memory even without the generation.
799
+ const generation = captureLiveGeneration();
720
800
  const token = getTokenFromRequest(req);
721
801
  if (await isSessionValid(token)) {
802
+ trackEventStreamPrincipal(req, res, token, generation);
722
803
  return next();
723
804
  }
724
805
  const clientAuth = await authenticateClientRequest(req);
725
806
  if (clientAuth) {
807
+ trackEventStreamPrincipal(req, res, clientSessionToken(clientAuth), generation);
726
808
  return next();
727
809
  }
728
810
  clearSessionCookie(req, res);
@@ -939,6 +1021,22 @@ export const createUiAuth = ({
939
1021
 
940
1022
  const handleResetAuth = (req, res) => {
941
1023
  try {
1024
+ // Env-secret topology cannot rotate: the signing key is the process
1025
+ // environment, not the persisted file, so global invalidation is
1026
+ // unavailable. Fail honestly without side effects — closing live
1027
+ // connections while leaving the secret (and every outstanding JWT/URL
1028
+ // token) valid would imply a sign-out that never happened.
1029
+ if (process.env.PICHAMBER_JWT_SECRET) {
1030
+ return res.status(400).json({ error: 'Global sign-out is unavailable while PICHAMBER_JWT_SECRET is set' });
1031
+ }
1032
+ // Global invalidation ends established live connections (SSE, terminal,
1033
+ // dictation) immediately; the rotated signing secret denies every
1034
+ // outstanding session JWT and URL token from here on. New cookies and
1035
+ // URL tokens are issued from the reread in-memory secret, so they are
1036
+ // bound to the new generation. Single-server topology: rotation is
1037
+ // in-process only (the pairing CLI never rotates the JWT secret), so
1038
+ // no cross-process poll is involved.
1039
+ liveRevocation?.revokeAllLive?.('signout-everywhere');
942
1040
  const passkeyResult = passkeyController.clearAllPasskeys();
943
1041
  rotateJwtSecret();
944
1042
  clearSessionCookie(req, res);