@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
package/server/index.js CHANGED
@@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url';
9
9
 
10
10
  import { createClientPairingRuntime } from './lib/client-auth/pairing.js';
11
11
  import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.js';
12
+ import { createRevocationCoordinator } from './lib/client-auth/principal-tracker.js';
12
13
  import { resolvePiChamberDataDir } from './lib/pichamber-data-dir.js';
13
14
  import { createTunnelService } from './lib/server/tunnel-service.js';
14
15
  import { registerPiRuntimeRoutes } from './lib/pi/routes.js';
@@ -123,9 +124,17 @@ export async function startWebUiServer(options = {}) {
123
124
  const serverStartedAt = new Date().toISOString();
124
125
  const dataPath = (name) => path.join(PICHAMBER_DATA_DIR, name);
125
126
  const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto: await import('node:crypto'), storePath: dataPath('remote-clients.json') });
127
+ // Live credential revocation (#9): tracks authenticated SSE/terminal/dictation
128
+ // connections and closes a revoked principal's connections. The revoke route
129
+ // closes in-process immediately; the bounded poll converges with revocations
130
+ // committed by other processes sharing this data directory.
131
+ const liveRevocation = createRevocationCoordinator({
132
+ listRevokedClientIds: () => remoteClientAuthRuntime.listRevokedClientIds(),
133
+ });
134
+ liveRevocation.start();
126
135
  const clientPairingRuntime = createClientPairingRuntime({ fsPromises: fs.promises, path, crypto: await import('node:crypto'), storePath: dataPath('client-pairing-sessions.json'), remoteClientAuthRuntime });
127
136
  const tunnelAuthController = createTunnelAuth();
128
- const uiAuthController = createUiAuth({ password: uiPassword, readSettingsFromDiskMigrated: async () => ({}) , clientAuthController: remoteClientAuthRuntime });
137
+ const uiAuthController = createUiAuth({ password: uiPassword, readSettingsFromDiskMigrated: async () => ({}), clientAuthController: remoteClientAuthRuntime, liveRevocation });
129
138
  // One daemon per server profile. The supervisor is created after HTTP
130
139
  // listen so the profile key uses the bound port; routes observe it through
131
140
  // the getter and report unavailable until it exists.
@@ -184,6 +193,7 @@ export async function startWebUiServer(options = {}) {
184
193
  uiAuthController,
185
194
  remoteClientAuthRuntime,
186
195
  clientPairingRuntime,
196
+ liveRevocation,
187
197
  readSettingsFromDiskMigrated: async () => ({}),
188
198
  normalizeTunnelSessionTtlMs: () => 8 * 60 * 60 * 1000,
189
199
  getPairingTransports: () => pairingTransports.getPairingTransports(),
@@ -191,7 +201,7 @@ export async function startWebUiServer(options = {}) {
191
201
  getServerId: async () => null,
192
202
  getServerLabel: () => os.hostname() || 'PiChamber',
193
203
  });
194
- registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => piSessionDaemonRuntime });
204
+ const piRuntimeRoutes = registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => piSessionDaemonRuntime });
195
205
  // Cloudflare Tunnel external access (manual token + quick modes).
196
206
  const requireTunnelAuth = (req, res, next) => uiAuthController.requireAuth(req, res, next);
197
207
  app.get('/api/pichamber/tunnel/status', requireTunnelAuth, async (_req, res) => {
@@ -215,7 +225,7 @@ export async function startWebUiServer(options = {}) {
215
225
  app.get('/api/pichamber/tunnel/doctor', requireTunnelAuth, async (req, res) => {
216
226
  try { const status = await tunnelService.getStatus(); const checkResult = await tunnelService.check(); res.json({ ok: true, status, check: checkResult, query: req.query }); } catch (error) { res.status(500).json({ ok: false, error: error?.message || 'Doctor failed' }); }
217
227
  });
218
- const workspaceRuntime = registerWorkspaceIntegrations({ app, server, express, uiAuthController, dataDir: PICHAMBER_DATA_DIR });
228
+ const workspaceRuntime = registerWorkspaceIntegrations({ app, server, express, uiAuthController, dataDir: PICHAMBER_DATA_DIR, liveRevocation });
219
229
  registerStaticRoutes(app, { apiOnly });
220
230
 
221
231
  await listen(server, port, host);
@@ -253,6 +263,10 @@ export async function startWebUiServer(options = {}) {
253
263
  if (stopped) return;
254
264
  stopped = true;
255
265
  if (activeController === controller) activeController = null;
266
+ // Stop revocation polling and end active or opening SSE streams before
267
+ // asking the HTTP server to wait on its sockets.
268
+ liveRevocation.dispose();
269
+ piRuntimeRoutes.closeEventStreams();
256
270
  await Promise.allSettled([
257
271
  workspaceRuntime.shutdown(),
258
272
  piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
@@ -0,0 +1,184 @@
1
+ # Client Auth Module Documentation
2
+
3
+ ## Purpose
4
+
5
+ This module owns the trusted-device credential store and the live lifetime of
6
+ credentials that the UI auth gate accepts: client bearer tokens
7
+ (`oc_client_…`) and the principals they resolve to. Password, passkey, and
8
+ Pairing v2 are issuance methods (see `../ui-auth/DOCUMENTATION.md`); this
9
+ module owns storage, authentication, revocation, and — since live credential
10
+ revocation (#9) — the closing of established connections when a credential is
11
+ revoked or globally invalidated.
12
+
13
+ ## Files
14
+
15
+ - `remote-clients.js`: trusted-device client token storage (hashed tokens,
16
+ atomic writes, cross-process file lock), bearer authentication, last-used
17
+ tracking, relay-demand signals, revocation, and principal validation.
18
+ - `pairing.js`: short-lived Pairing v2 sessions and one-time secret redemption
19
+ into trusted-device client tokens.
20
+ - `principal-tracker.js`: live connection tracking by principal plus the
21
+ revocation coordinator that closes tracked connections on revocation.
22
+
23
+ ## Principal model
24
+
25
+ A principal is derived from verified credentials at the auth-owning boundary
26
+ (`uiAuthController.requireAuth` / `ensureSessionToken`), never from anything a
27
+ client supplies:
28
+
29
+ - `client:<id>` — a remote-client bearer token resolved through the hashed
30
+ token store.
31
+ - The raw UI session JWT — a browser session authenticated by its cookie.
32
+ - Opaque session tokens in passwordless mode (no credential store; no
33
+ revocation concept).
34
+
35
+ ## Live credential revocation (#9)
36
+
37
+ Revoking a credential must do more than mark the store record. Four
38
+
39
+ deterministic barriers cover mint, auth, track, and upgrade:
40
+
41
+ 1. **Deny new establishment (mint/auth).** Bearer authentication fails on the
42
+ revoked record (`authenticateBearerToken`), so mints and API calls fail at
43
+ once.
44
+ 2. **Deny already-minted URL tokens (mint/open race).** The encrypted
45
+ `oc_url_token` embeds the principal, so establishment re-validates it
46
+ against the store (`isClientValid`) and the current signing secret
47
+ (`verifySessionToken`). A URL token minted moments before revocation or
48
+ global sign-out is refused at open time even though its 60-second TTL has
49
+ not elapsed.
50
+ 3. **Close established connections.** The coordinator closes the tracked
51
+ connections of the revoked principal. Applies to SSE event streams
52
+ (`/api/pi/events`) and the terminal (`/api/terminal/ws`) and dictation
53
+ (`/api/stt/ws`) WebSocket upgrades over direct connections. Relayed traffic
54
+ reaches the same server-side gates (the tunnel host dials loopback and
55
+ presents the loopback origin); the `x-pichamber-relay-connection` header is
56
+ transport classification only. A header-marked direct request is NOT a true
57
+ tunnel — see Verification below.
58
+ 4. **Reject late registration (verify-registration race, track/upgrade).**
59
+ Bearer/URL validation awaits the store and the WebSocket path additionally
60
+ awaits the origin gate, so a revocation can commit+close between
61
+ verification and registration. The coordinator remembers every in-process
62
+ revocation (`revokedClientIds`, bounded FIFO, default 2000) and a monotonic
63
+ global generation (bumped by every `revokeAllLive()`). `trackLiveConnection`
64
+ checks both synchronously — revoked-ID match reject-closes with
65
+ `close('credential-revoked')`, stale-generation match reject-closes with
66
+ `close('global-invalidation')` — without trusting the caller's principal.
67
+ The synchronous check+insert is atomic, so no in-process revoke slips
68
+ between them. Auth boundaries capture `getGeneration()` BEFORE their first
69
+ await (SSE in `requireAuth`, WebSocket in the upgrade handler before
70
+ `ensureSessionToken`/origin) and pass it at track time; WebSocket upgrades
71
+ with an inactive entry (`active === false`) must skip `handleUpgrade` (the
72
+ socket is already destroyed).
73
+
74
+ ### URL-token expiry vs connection lifetime
75
+
76
+ The 60-second URL token TTL gates **establishment only**. It is never a
77
+ connection lifetime grant: an established SSE stream or WebSocket is governed
78
+ by live revocation tracking, not by token expiry, and connections are not
79
+ closed when their mint token ages out.
80
+
81
+ ### Latency guarantee (healthy storage only)
82
+
83
+ - **In-process revocation** (the `DELETE /api/client-auth/clients/:id` route
84
+ and global sign-out `/auth/reset`): the store write commits, then
85
+ `clientRevoked()` / `revokeAllLive()` closes the tracked connections
86
+ synchronously inside the revoking request. No timers are involved; the
87
+ response reports `closedConnections`.
88
+ - **Cross-process propagation**: the credential store is a file shared by
89
+ processes using the data directory (one server plus the
90
+ `pichamber connect-url` pairing CLI, which shares only
91
+ `remote-clients.json`). No cross-process revocation emitter exists, and none
92
+ is claimed. Propagation is a **bounded poll** of `listRevokedClientIds()`
93
+ (default every 15 seconds, timer unref'd); a revocation committed by another
94
+ process therefore closes this process's tracked connections within one poll
95
+ interval **after the next successful poll**. A failed poll tick provides no
96
+ guarantee — it is transient (current state kept, next tick retries, never an
97
+ authoritative empty result), but while polls fail, already-established
98
+ cross-process connections are retained (degraded retention). New
99
+ bearer/URL-token establishment stays authoritatively gated by direct
100
+ store/secret reads and is unaffected by poll health.
101
+
102
+ ### Topology
103
+
104
+ One server process per data directory. The pairing CLI never rotates the JWT
105
+ secret, so browser-session rotation (`/auth/reset`) is in-process only and has
106
+ no cross-process poll. Multi-server sharing of one data directory is not
107
+ supported.
108
+
109
+ ### Scope boundary
110
+
111
+ Cloudflare-tunnel sessions are a separate credential system owned by
112
+ `../server/tunnel-auth.js`; their established-connection semantics are not
113
+ managed by this tracker. Revoking a remote client never touches other
114
+ clients' connections or Pi daemon work: closing one SSE connection tears down
115
+ only that client's daemon subscription through the normal disconnect path.
116
+
117
+ ### Global invalidation (sign-out everywhere)
118
+
119
+ `/auth/reset` rotates the JWT secret — invalidating every outstanding UI
120
+ session JWT and URL token from then on — and calls `revokeAllLive()` so all
121
+ tracked established connections (client and session principals, SSE and
122
+ WebSocket) end immediately. New cookies and URL tokens are issued from the
123
+ reread in-memory secret, so they bind to the new generation. While
124
+ `PICHAMBER_JWT_SECRET` is set, rotation is impossible and `/auth/reset`
125
+ returns 400 without side effects (no live close, no passkey clear) — closing
126
+ live connections while leaving the secret valid would imply a sign-out that
127
+ never happened.
128
+
129
+ ### Resource bounds
130
+
131
+ - `MAX_LIVE_CONNECTIONS_PER_PRINCIPAL = 50`, `MAX_LIVE_CONNECTIONS_GLOBAL =
132
+ 1000`: a new registration beyond either bound is reject-closed synchronously
133
+ with `close('over-limit')` without evicting unrelated entries. Memory is
134
+ O(global) entries (each a small id/principal/closure triple).
135
+ - `MAX_REMEMBERED_REVOKED_CLIENTS = 2000`: revoked-ID memory for the
136
+ verify-registration barrier is a bounded FIFO; beyond it the oldest ID is
137
+ evicted and falls back to establishment-time store checks plus the next
138
+ poll.
139
+ - After `dispose()` (shutdown) every new registration is reject-closed with
140
+ `close('shutdown')`.
141
+
142
+ ## Tracking lifecycle and cleanup
143
+
144
+ - Connections are tracked only after all auth/origin gates pass, and before
145
+ the transport is handed to the route (SSE) or the WebSocket upgrade
146
+ (`handleUpgrade`), so the pending window is covered: a revocation racing a
147
+ still-opening connection destroys it. The generation is captured before the
148
+ first auth/origin await; track rejects stale generations and revoked IDs
149
+ synchronously, and WebSocket upgrades skip `handleUpgrade` for inactive
150
+ entries.
151
+ - Entries are removed when the transport ends by itself (`res.once('close')`
152
+ for SSE, `socket.once('close')` for upgrades — this also covers failed
153
+ upgrades), so the index never accumulates dead entries.
154
+ - `close` callbacks are synchronous destroys wrapped idempotently; a failing
155
+ close is isolated (reported via `onCloseError`) and cannot strand other
156
+ connections. Reject-close paths (`over-limit`, `credential-revoked`,
157
+ `global-invalidation`, `shutdown`) use the same isolation.
158
+ - Shutdown: `dispose()` stops the poll timer and closes remaining tracked
159
+ connections synchronously (bounded cleanup); later registrations are
160
+ reject-closed. The terminal/STT runtimes' own shutdown terminates their
161
+ sockets through their normal paths.
162
+ - Revoke/self-revoke authorization (which caller may revoke which ID) is
163
+ enforced at the core route; the tracker keys off the store-derived
164
+ principal only and never trusts a caller-supplied ID.
165
+
166
+ ## Verification
167
+
168
+ ```sh
169
+ bun test packages/web/server/lib/client-auth/principal-tracker.test.js
170
+ bun test packages/web/server/lib/ui-auth/ui-auth.test.js
171
+ bun test packages/web/server/lib/client-auth/live-revocation.test.js
172
+ ```
173
+
174
+ `live-revocation.test.js` exercises the real auth and origin gates (no
175
+ stubbed upgrades) with synthetic credentials over direct and
176
+ relay-classified SSE (header only — NOT a true tunnel), terminal and
177
+ dictation WebSocket upgrades with trusted/untrusted origins, another-device
178
+ isolation, the verify-registration race during the origin gate, the
179
+ cross-process second-runtime revocation, and shutdown cleanup. A disposable
180
+ true-tunnel integration dispatches authenticated HTTP through
181
+ `createTunnelHost` to loopback, proving bearer auth and loopback-origin
182
+ overwrite with the real gate. Gap: tunneled WebSocket upgrades and long-lived
183
+ SSE streaming through the tunnel reuse the same server-side gates but have no
184
+ disposable integration here.