@pi-chamber/web 0.9.5 → 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 (104) hide show
  1. package/dist/assets/DiagramView-BvrCkm_z.js +1 -0
  2. package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
  3. package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
  4. package/dist/assets/FilesView-CNHu4RnC.js +6 -0
  5. package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
  6. package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
  8. package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-BdSDgvhC.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-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
  15. package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
  17. package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-BvPOjeOy.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-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
  25. package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
  26. package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
  27. package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
  28. package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
  29. package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
  30. package/dist/assets/{mobile-D0HVxiyJ.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-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
  36. package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
  37. package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
  38. package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
  39. package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
  40. package/dist/assets/{web-components-B5sMa_kC.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/fs/DOCUMENTATION.md +15 -3
  53. package/server/lib/fs/routes.js +369 -51
  54. package/server/lib/fs/routes.test.js +565 -3
  55. package/server/lib/fs/search.js +74 -29
  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 +132 -28
  59. package/server/lib/pi/routes.test.js +213 -4
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -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-operations.test.js +9 -3
  64. package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
  65. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
  66. package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
  67. package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
  68. package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
  69. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
  70. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
  71. package/server/lib/pi/session-daemon/session-daemon.js +339 -37
  72. package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
  73. package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
  74. package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
  75. package/server/lib/pi/session-daemon/supervisor.js +30 -5
  76. package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
  77. package/server/lib/pi/ui-settings-store.js +1 -1
  78. package/server/lib/pi/ui-settings-store.test.js +3 -1
  79. package/server/lib/server/core-routes.js +11 -1
  80. package/server/lib/server/cors.js +6 -0
  81. package/server/lib/server/cors.test.js +3 -0
  82. package/server/lib/stt/DOCUMENTATION.md +2 -0
  83. package/server/lib/stt/runtime.js +39 -2
  84. package/server/lib/stt/runtime.test.js +53 -0
  85. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  86. package/server/lib/terminal/runtime.js +48 -2
  87. package/server/lib/terminal/runtime.test.js +35 -0
  88. package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
  89. package/server/lib/ui-auth/ui-auth.js +98 -0
  90. package/server/lib/ui-auth/ui-auth.test.js +249 -0
  91. package/server/lib/workspace/host.js +9 -3
  92. package/server/lib/workspace/host.test.js +15 -0
  93. package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
  94. package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
  95. package/dist/assets/FilesView-CJytSUAX.js +0 -6
  96. package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
  97. package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
  98. package/dist/assets/index-DIF8b4bh.css +0 -1
  99. package/dist/assets/index-jrfQYSvP.js +0 -8
  100. package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
  101. package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
  102. package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
  103. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
  104. package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
@@ -0,0 +1,567 @@
1
+ import { afterAll, describe, expect, it } from 'bun:test';
2
+ import fs from 'node:fs';
3
+ import http from 'node:http';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import express from 'express';
8
+ import { WebSocket } from 'ws';
9
+
10
+ // The data dir must exist before ui-auth.js resolves its JWT secret path.
11
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-live-revocation-'));
12
+ process.env.PICHAMBER_DATA_DIR = dataDir;
13
+
14
+ afterAll(() => {
15
+ fs.rmSync(dataDir, { recursive: true, force: true });
16
+ });
17
+
18
+ const loadModules = async () => ({
19
+ createUiAuth: (await import('../ui-auth/ui-auth.js')).createUiAuth,
20
+ createRemoteClientAuthRuntime: (await import('./remote-clients.js')).createRemoteClientAuthRuntime,
21
+ createRevocationCoordinator: (await import('./principal-tracker.js')).createRevocationCoordinator,
22
+ createRequestSecurityRuntime: (await import('../security/request-security.js')).createRequestSecurityRuntime,
23
+ createTerminalRuntime: (await import('../terminal/runtime.js')).createTerminalRuntime,
24
+ createSttRuntime: (await import('../stt/runtime.js')).createSttRuntime,
25
+ createTunnelHost: (await import('../relay/tunnel-host.js')).createTunnelHost,
26
+ tunnelCodec: await import('../relay/tunnel-codec.js'),
27
+ });
28
+
29
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30
+ const withTimeout = (promise, label, ms = 3000) => Promise.race([
31
+ promise,
32
+ wait(ms).then(() => { throw new Error(`timed out waiting for ${label}`); }),
33
+ ]);
34
+
35
+ const openWebSocket = async (url, headers = {}) => {
36
+ const socket = new WebSocket(url, { headers });
37
+ // A server-side destroy can surface as multiple 'error' events (hangup
38
+ // emits error+close; a second error can fire after the handshake settles).
39
+ // Keep a persistent swallow handler from creation so no late error crashes
40
+ // the run; the once handlers below still observe the handshake outcome.
41
+ socket.on('error', () => {});
42
+ const outcome = withTimeout(new Promise((resolve, reject) => {
43
+ socket.once('open', () => resolve('open'));
44
+ socket.once('close', () => resolve('closed'));
45
+ socket.once('error', (error) => reject(error));
46
+ }), 'websocket handshake');
47
+ try {
48
+ const result = await outcome;
49
+ return { socket, result };
50
+ } catch (error) {
51
+ return { socket, result: 'error', error };
52
+ }
53
+ };
54
+
55
+ const waitForSocketClose = (socket, ms = 3000) => withTimeout(new Promise((resolve) => {
56
+ if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return resolve('closed');
57
+ socket.once('close', () => resolve('closed'));
58
+ }), 'websocket close', ms);
59
+
60
+ const waitForSseEnd = async (response, ms = 3000) => {
61
+ const reader = response.body.getReader();
62
+ return withTimeout((async () => {
63
+ try {
64
+ for (;;) {
65
+ const { done } = await reader.read();
66
+ if (done) return 'ended';
67
+ }
68
+ } catch {
69
+ return 'destroyed';
70
+ }
71
+ })(), 'sse end', ms);
72
+ };
73
+
74
+ describe('live credential revocation across transports', () => {
75
+ it('closes the revoked principal SSE and terminal/dictation connections, denies re-entry, and converges cross-process', async () => {
76
+ const {
77
+ createUiAuth,
78
+ createRemoteClientAuthRuntime,
79
+ createRevocationCoordinator,
80
+ createRequestSecurityRuntime,
81
+ createTerminalRuntime,
82
+ createSttRuntime,
83
+ } = await loadModules();
84
+
85
+ const storePath = path.join(dataDir, 'remote-clients.json');
86
+ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto, storePath });
87
+ // Bounded poll: in-process revocations close immediately through the
88
+ // revoke route; this interval also bounds cross-process convergence.
89
+ const liveRevocation = createRevocationCoordinator({
90
+ listRevokedClientIds: () => remoteClientAuthRuntime.listRevokedClientIds(),
91
+ pollIntervalMs: 25,
92
+ });
93
+ liveRevocation.start();
94
+
95
+ const uiAuthController = createUiAuth({
96
+ password: 'secret',
97
+ readSettingsFromDiskMigrated: async () => ({}),
98
+ clientAuthController: remoteClientAuthRuntime,
99
+ liveRevocation,
100
+ });
101
+ const security = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
102
+
103
+ const app = express();
104
+ app.use(express.json({ limit: '1mb' }));
105
+
106
+ // SSE at the auth-owning boundary: requireAuth resolves the principal and
107
+ // registers the live connection; the route only streams frames.
108
+ const sseClients = new Set();
109
+ app.get('/api/pi/events', (req, res) => {
110
+ void uiAuthController.requireAuth(req, res, () => {
111
+ res.status(200).set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
112
+ res.flushHeaders?.();
113
+ res.write('data: {"hello":true}\n\n');
114
+ const heartbeat = setInterval(() => {
115
+ if (res.destroyed || res.writableEnded) return;
116
+ res.write('event: heartbeat\ndata: {}\n\n');
117
+ }, 50);
118
+ sseClients.add(res);
119
+ res.once('close', () => {
120
+ clearInterval(heartbeat);
121
+ sseClients.delete(res);
122
+ });
123
+ });
124
+ });
125
+
126
+ // Mirror of the auth-owning core revoke route: store write, then immediate
127
+ // in-process close through the coordinator.
128
+ app.delete('/api/client-auth/clients/:id', (req, res) => {
129
+ void uiAuthController.requireAuth(req, res, async () => {
130
+ const result = await remoteClientAuthRuntime.revokeClient(req.params?.id);
131
+ if (!result.revoked) {
132
+ return res.status(404).json({ revoked: false, error: 'Client not found' });
133
+ }
134
+ const closedConnections = liveRevocation.clientRevoked(result.client.id);
135
+ res.json({ ...result, closedConnections });
136
+ });
137
+ });
138
+
139
+ app.post('/auth/url-token', (req, res) => {
140
+ void uiAuthController.handleUrlAuthToken(req, res);
141
+ });
142
+
143
+ const realServer = http.createServer(app);
144
+
145
+ const fakePtyProvider = async () => ({
146
+ backend: 'fake-pty',
147
+ spawn: () => {
148
+ const data = new Set();
149
+ const exits = new Set();
150
+ return {
151
+ pid: 42_000,
152
+ write() {},
153
+ resize() {},
154
+ kill() {},
155
+ onData(handler) { data.add(handler); return { dispose: () => data.delete(handler) }; },
156
+ onExit(handler) { exits.add(handler); return { dispose: () => exits.delete(handler) }; },
157
+ };
158
+ },
159
+ });
160
+ // The terminal/dictation upgrade handlers attach to the real HTTP server.
161
+ const terminalRuntime = createTerminalRuntime({
162
+ app, server: realServer, express, fs, path,
163
+ uiAuthController,
164
+ liveRevocation,
165
+ buildAugmentedPath: () => process.env.PATH || '',
166
+ searchPathFor: () => '/bin/sh',
167
+ isExecutable: () => true,
168
+ isRequestOriginAllowed: security.isRequestOriginAllowed,
169
+ rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
170
+ TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS: 1000,
171
+ loadPtyProvider: fakePtyProvider,
172
+ terminalTerminationGraceMs: 10,
173
+ });
174
+ const sttRuntime = createSttRuntime({
175
+ app, server: realServer, express,
176
+ uiAuthController,
177
+ liveRevocation,
178
+ isRequestOriginAllowed: security.isRequestOriginAllowed,
179
+ rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
180
+ modelsDir: path.join(dataDir, 'speech-models'),
181
+ configFile: path.join(dataDir, 'stt', 'config.json'),
182
+ });
183
+
184
+ await new Promise((resolve) => realServer.listen(0, '127.0.0.1', resolve));
185
+ const port = realServer.address().port;
186
+ const base = `http://127.0.0.1:${port}`;
187
+ const origin = base;
188
+
189
+ try {
190
+ const deviceA = await remoteClientAuthRuntime.createClient({ label: 'Phone A' });
191
+ const deviceB = await remoteClientAuthRuntime.createClient({ label: 'Tablet B' });
192
+
193
+ // Mint A's URL tokens BEFORE revocation: they must fail at establishment
194
+ // afterwards (mint/open race), even though their 60s TTL has not elapsed.
195
+ const mintToken = async (bearer) => {
196
+ const response = await fetch(`${base}/auth/url-token`, {
197
+ method: 'POST',
198
+ headers: { authorization: `Bearer ${bearer}`, accept: 'application/json' },
199
+ });
200
+ expect(response.status).toBe(200);
201
+ return (await response.json()).token;
202
+ };
203
+ const urlTokenA = await mintToken(deviceA.token);
204
+
205
+ // Device A: direct SSE, relay-classified SSE (header only — NOT a true
206
+ // relay tunnel; it exercises transport classification/usesRelay healing
207
+ // through the same server-side auth gate), terminal WS, dictation WS.
208
+ // True tunnel dispatch (loopback fetch with overwritten origin) is
209
+ // covered by the disposable tunnel-host integration below.
210
+ const sseDirect = await fetch(`${base}/api/pi/events`, { headers: { authorization: `Bearer ${deviceA.token}` } });
211
+ expect(sseDirect.status).toBe(200);
212
+ const sseRelayClassified = await fetch(`${base}/api/pi/events`, {
213
+ headers: { authorization: `Bearer ${deviceA.token}`, 'x-pichamber-relay-connection': 'tunnel-conn-1' },
214
+ });
215
+ expect(sseRelayClassified.status).toBe(200);
216
+ const sseOther = await fetch(`${base}/api/pi/events`, { headers: { authorization: `Bearer ${deviceB.token}` } });
217
+ expect(sseOther.status).toBe(200);
218
+ // Relay traffic must not be misclassified: the store heals usesRelay.
219
+ const listedA = (await remoteClientAuthRuntime.listClients()).find((client) => client.id === deviceA.client.id);
220
+ expect(listedA.usesRelay).toBe(true);
221
+
222
+ const wsHeaders = { origin };
223
+ const terminalSocket = await openWebSocket(`${base}/api/terminal/ws?oc_url_token=${encodeURIComponent(urlTokenA)}`, wsHeaders);
224
+ expect(terminalSocket.result).toBe('open');
225
+ const sttSocket = await openWebSocket(`${base}/api/stt/ws?oc_url_token=${encodeURIComponent(urlTokenA)}`, wsHeaders);
226
+ expect(sttSocket.result).toBe('open');
227
+
228
+ // Four live connections for A, none for B.
229
+ expect(liveRevocation.countPrincipal(`client:${deviceA.client.id}`)).toBe(4);
230
+ expect(liveRevocation.countPrincipal(`client:${deviceB.client.id}`)).toBe(1);
231
+
232
+ // Revoke A through the route: the response reports the closed sockets.
233
+ const revokeResponse = await fetch(`${base}/api/client-auth/clients/${deviceA.client.id}`, {
234
+ method: 'DELETE',
235
+ headers: { authorization: `Bearer ${deviceA.token}` },
236
+ });
237
+ expect(revokeResponse.status).toBe(200);
238
+ const revokeBody = await revokeResponse.json();
239
+ expect(revokeBody.revoked).toBe(true);
240
+ expect(revokeBody.closedConnections).toBe(4);
241
+
242
+ // Every A connection ends bounded (destroy surfaces as either a clean
243
+ // end or a connection reset, depending on flush timing); B survives.
244
+ expect(['ended', 'destroyed']).toContain(await waitForSseEnd(sseDirect));
245
+ expect(['ended', 'destroyed']).toContain(await waitForSseEnd(sseRelayClassified));
246
+ expect(await waitForSocketClose(terminalSocket.socket)).toBe('closed');
247
+ expect(await waitForSocketClose(sttSocket.socket)).toBe('closed');
248
+ await wait(60);
249
+ // B's live connection is untouched by A's revocation.
250
+ expect(liveRevocation.countPrincipal(`client:${deviceB.client.id}`)).toBe(1);
251
+ expect((await fetch(`${base}/api/pi/events`, { headers: { authorization: `Bearer ${deviceB.token}` } })).status).toBe(200);
252
+
253
+ // Revoked credentials cannot re-establish anything.
254
+ const reconnect = await fetch(`${base}/api/pi/events`, { headers: { authorization: `Bearer ${deviceA.token}` } });
255
+ expect(reconnect.status).toBe(401);
256
+ const racedTerminal = await openWebSocket(`${base}/api/terminal/ws?oc_url_token=${encodeURIComponent(urlTokenA)}`, wsHeaders);
257
+ expect(racedTerminal.result).toBe('error');
258
+ // Client libraries phrase the 401 handshake rejection differently; the
259
+ // upgrade never opens either way.
260
+ expect(/401|Connection ended|Unexpected server response/.test(String(racedTerminal.error?.message))).toBe(true);
261
+ const racedStt = await openWebSocket(`${base}/api/stt/ws?oc_url_token=${encodeURIComponent(urlTokenA)}`, wsHeaders);
262
+ expect(racedStt.result).toBe('error');
263
+
264
+ // Cross-process propagation: a second process shares the credential
265
+ // store (no emitter exists between processes). Its revocation of B is
266
+ // picked up by the bounded poll when storage reads succeed (healthy
267
+ // storage). While polls fail, established cross-process connections are
268
+ // retained (degraded); new establishment stays authoritatively gated.
269
+ const secondProcessRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto, storePath });
270
+ await secondProcessRuntime.revokeClient(deviceB.client.id);
271
+ // B's stream only ends once the poll observes the cross-process write.
272
+ expect(['ended', 'destroyed']).toContain(await waitForSseEnd(sseOther));
273
+ } finally {
274
+ liveRevocation.dispose();
275
+ await Promise.allSettled([terminalRuntime.shutdown(), sttRuntime.shutdown()]);
276
+ realServer.closeAllConnections?.();
277
+ await new Promise((resolve) => realServer.close(resolve));
278
+ }
279
+ }, 20_000);
280
+
281
+ it('rejects WebSocket upgrades with an untrusted origin through the real gate', async () => {
282
+ const {
283
+ createUiAuth,
284
+ createRemoteClientAuthRuntime,
285
+ createRevocationCoordinator,
286
+ createRequestSecurityRuntime,
287
+ createTerminalRuntime,
288
+ } = await loadModules();
289
+ const storePath = path.join(dataDir, `remote-clients-origin-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
290
+ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto, storePath });
291
+ const liveRevocation = createRevocationCoordinator({
292
+ listRevokedClientIds: () => remoteClientAuthRuntime.listRevokedClientIds(),
293
+ pollIntervalMs: 60_000,
294
+ });
295
+ const uiAuthController = createUiAuth({
296
+ password: 'secret',
297
+ readSettingsFromDiskMigrated: async () => ({}),
298
+ clientAuthController: remoteClientAuthRuntime,
299
+ liveRevocation,
300
+ });
301
+ const security = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
302
+ const app = express();
303
+ app.post('/auth/url-token', (req, res) => {
304
+ void uiAuthController.handleUrlAuthToken(req, res);
305
+ });
306
+ const realServer = http.createServer(app);
307
+ const terminalRuntime = createTerminalRuntime({
308
+ app,
309
+ server: realServer,
310
+ express,
311
+ fs,
312
+ path,
313
+ uiAuthController,
314
+ liveRevocation,
315
+ buildAugmentedPath: () => process.env.PATH || '',
316
+ searchPathFor: () => '/bin/sh',
317
+ isExecutable: () => true,
318
+ isRequestOriginAllowed: security.isRequestOriginAllowed,
319
+ rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
320
+ TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS: 1000,
321
+ loadPtyProvider: async () => ({
322
+ backend: 'fake-pty',
323
+ spawn: () => ({
324
+ pid: 42_001,
325
+ write() {},
326
+ resize() {},
327
+ kill() {},
328
+ onData() { return { dispose: () => {} }; },
329
+ onExit() { return { dispose: () => {} }; },
330
+ }),
331
+ }),
332
+ terminalTerminationGraceMs: 10,
333
+ });
334
+ await new Promise((resolve) => realServer.listen(0, '127.0.0.1', resolve));
335
+ const port = realServer.address().port;
336
+ const base = `http://127.0.0.1:${port}`;
337
+ try {
338
+ const device = await remoteClientAuthRuntime.createClient({ label: 'Origin probe' });
339
+ const mint = await fetch(`${base}/auth/url-token`, {
340
+ method: 'POST',
341
+ headers: { authorization: `Bearer ${device.token}` },
342
+ });
343
+ expect(mint.status).toBe(200);
344
+ const urlToken = (await mint.json()).token;
345
+ // Real gate: loopback origin derived from Host is trusted.
346
+ const trusted = await openWebSocket(`${base}/api/terminal/ws?oc_url_token=${encodeURIComponent(urlToken)}`, { origin: base });
347
+ expect(trusted.result).toBe('open');
348
+ trusted.socket.on('error', () => {});
349
+ trusted.socket.close();
350
+ await waitForSocketClose(trusted.socket);
351
+ // Real gate: an unrelated origin is rejected without opening.
352
+ const untrusted = await openWebSocket(`${base}/api/terminal/ws?oc_url_token=${encodeURIComponent(urlToken)}`, { origin: 'https://evil.example' });
353
+ expect(untrusted.result).toBe('error');
354
+ expect(/403|Failed|Unexpected|Connection ended/.test(String(untrusted.error?.message ?? ''))).toBe(true);
355
+ } finally {
356
+ liveRevocation.dispose();
357
+ await terminalRuntime.shutdown().catch(() => {});
358
+ realServer.closeAllConnections?.();
359
+ await new Promise((resolve) => realServer.close(resolve));
360
+ await fs.promises.rm(storePath, { force: true }).catch(() => {});
361
+ }
362
+ }, 20_000);
363
+
364
+ it('rejects a WebSocket racing revocation during the origin gate without calling handleUpgrade', async () => {
365
+ const {
366
+ createUiAuth,
367
+ createRemoteClientAuthRuntime,
368
+ createRevocationCoordinator,
369
+ createRequestSecurityRuntime,
370
+ createTerminalRuntime,
371
+ } = await loadModules();
372
+ const storePath = path.join(dataDir, `remote-clients-race-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
373
+ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto, storePath });
374
+ const liveRevocation = createRevocationCoordinator({
375
+ listRevokedClientIds: () => remoteClientAuthRuntime.listRevokedClientIds(),
376
+ pollIntervalMs: 60_000,
377
+ });
378
+ const uiAuthController = createUiAuth({
379
+ password: 'secret',
380
+ readSettingsFromDiskMigrated: async () => ({}),
381
+ clientAuthController: remoteClientAuthRuntime,
382
+ liveRevocation,
383
+ });
384
+ const security = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
385
+ const app = express();
386
+ app.post('/auth/url-token', (req, res) => {
387
+ void uiAuthController.handleUrlAuthToken(req, res);
388
+ });
389
+ const realServer = http.createServer(app);
390
+ // Deterministic verify-registration race: the origin gate awaits, and the
391
+ // revocation commits inside that window — after ensureSessionToken
392
+ // already resolved the principal, before trackLiveConnection runs.
393
+ const racingOriginGate = async (req) => {
394
+ const allowed = await security.isRequestOriginAllowed(req);
395
+ if (allowed && req.__revokeTarget) {
396
+ await remoteClientAuthRuntime.revokeClient(req.__revokeTarget);
397
+ liveRevocation.clientRevoked(req.__revokeTarget);
398
+ }
399
+ return allowed;
400
+ };
401
+ // Tag the racing request by wrapping ensureSessionToken:stash the client
402
+ // id on the req object the origin gate can read. The URL token embeds
403
+ // `client:<id>`; decoding is unnecessary — the test knows the id.
404
+ const deviceForRace = await remoteClientAuthRuntime.createClient({ label: 'Racer' });
405
+ const terminalRuntime = createTerminalRuntime({
406
+ app,
407
+ server: realServer,
408
+ express,
409
+ fs,
410
+ path,
411
+ uiAuthController: {
412
+ ...uiAuthController,
413
+ enabled: true,
414
+ ensureSessionToken: async (req) => {
415
+ const principal = await uiAuthController.ensureSessionToken(req, null);
416
+ if (principal === `client:${deviceForRace.client.id}`) req.__revokeTarget = deviceForRace.client.id;
417
+ return principal;
418
+ },
419
+ },
420
+ liveRevocation,
421
+ buildAugmentedPath: () => process.env.PATH || '',
422
+ searchPathFor: () => '/bin/sh',
423
+ isExecutable: () => true,
424
+ isRequestOriginAllowed: racingOriginGate,
425
+ rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
426
+ TERMINAL_INPUT_WS_HEARTBEAT_INTERVAL_MS: 1000,
427
+ loadPtyProvider: async () => ({
428
+ backend: 'fake-pty',
429
+ spawn: () => ({
430
+ pid: 42_002,
431
+ write() {},
432
+ resize() {},
433
+ kill() {},
434
+ onData() { return { dispose: () => {} }; },
435
+ onExit() { return { dispose: () => {} }; },
436
+ }),
437
+ }),
438
+ terminalTerminationGraceMs: 10,
439
+ });
440
+ await new Promise((resolve) => realServer.listen(0, '127.0.0.1', resolve));
441
+ const port = realServer.address().port;
442
+ const base = `http://127.0.0.1:${port}`;
443
+ try {
444
+ const mint = await fetch(`${base}/auth/url-token`, {
445
+ method: 'POST',
446
+ headers: { authorization: `Bearer ${deviceForRace.token}` },
447
+ });
448
+ expect(mint.status).toBe(200);
449
+ const urlToken = (await mint.json()).token;
450
+ // The principal verified, then the revoke committed during the origin
451
+ // await; the coordinator's revoked memory must reject the late
452
+ // registration so handleUpgrade never runs and the socket never opens.
453
+ const raced = await openWebSocket(`${base}/api/terminal/ws?oc_url_token=${encodeURIComponent(urlToken)}`, { origin: base });
454
+ expect(raced.result).toBe('error');
455
+ expect(coordinatorHasNoLiveConnection(liveRevocation, deviceForRace.client.id)).toBe(true);
456
+ } finally {
457
+ liveRevocation.dispose();
458
+ await terminalRuntime.shutdown().catch(() => {});
459
+ realServer.closeAllConnections?.();
460
+ await new Promise((resolve) => realServer.close(resolve));
461
+ await fs.promises.rm(storePath, { force: true }).catch(() => {});
462
+ }
463
+ }, 20_000);
464
+
465
+ it('dispatches authenticated HTTP through the true tunnel host with loopback origin (disposable)', async () => {
466
+ const {
467
+ createUiAuth,
468
+ createRemoteClientAuthRuntime,
469
+ createRevocationCoordinator,
470
+ createTunnelHost,
471
+ tunnelCodec,
472
+ } = await loadModules();
473
+ const { TunnelFrameType, encodeTunnelFrame, decodeTunnelFrame, encodeJsonPayload } = tunnelCodec;
474
+ const storePath = path.join(dataDir, `remote-clients-tunnel-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
475
+ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto, storePath });
476
+ const liveRevocation = createRevocationCoordinator({
477
+ listRevokedClientIds: () => remoteClientAuthRuntime.listRevokedClientIds(),
478
+ pollIntervalMs: 60_000,
479
+ });
480
+ const uiAuthController = createUiAuth({
481
+ password: 'secret',
482
+ readSettingsFromDiskMigrated: async () => ({}),
483
+ clientAuthController: remoteClientAuthRuntime,
484
+ liveRevocation,
485
+ });
486
+ const app = express();
487
+ // Echo route behind the real auth gate: proves the tunneled bearer was
488
+ // authenticated and shows which origin/relay headers the host presented.
489
+ app.get('/api/echo-tunnel', (req, res) => {
490
+ void uiAuthController.requireAuth(req, res, () => {
491
+ res.json({
492
+ origin: req.headers.origin ?? null,
493
+ relay: req.headers['x-pichamber-relay-connection'] ?? null,
494
+ });
495
+ });
496
+ });
497
+ const realServer = http.createServer(app);
498
+ await new Promise((resolve) => realServer.listen(0, '127.0.0.1', resolve));
499
+ const port = realServer.address().port;
500
+ const loopbackOrigin = `http://127.0.0.1:${port}`;
501
+ const outbound = [];
502
+ const host = createTunnelHost({
503
+ connectionId: 'tunnel-conn-true',
504
+ getLocalPort: () => port,
505
+ sendFrame: (frame) => { outbound.push(frame); },
506
+ getBufferedAmount: () => 0,
507
+ });
508
+ const waitForFrames = async (predicate, ms = 3000) => {
509
+ const start = Date.now();
510
+ for (;;) {
511
+ if (predicate()) return;
512
+ if (Date.now() - start > ms) throw new Error('timed out waiting for tunnel frames');
513
+ await wait(10);
514
+ }
515
+ };
516
+ try {
517
+ const device = await remoteClientAuthRuntime.createClient({ label: 'Tunnel device' });
518
+ const decodeOutbound = () => outbound.map((frame) => decodeTunnelFrame(frame));
519
+ // Authenticated request through the true host: client-supplied origin
520
+ // must be overwritten with the loopback origin being dialed.
521
+ outbound.length = 0;
522
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
523
+ method: 'GET',
524
+ path: '/api/echo-tunnel',
525
+ query: '',
526
+ headers: { authorization: `Bearer ${device.token}`, origin: 'https://evil.example' },
527
+ })));
528
+ await waitForFrames(() => decodeOutbound().some((f) => f.frameType === TunnelFrameType.StreamEnd));
529
+ const frames = decodeOutbound();
530
+ const response = frames.find((f) => f.frameType === TunnelFrameType.HttpResponse);
531
+ expect(response).toBeTruthy();
532
+ const responsePayload = JSON.parse(Buffer.from(response.payload).toString('utf8'));
533
+ expect(responsePayload.status).toBe(200);
534
+ const bodyFrame = frames.find((f) => f.frameType === TunnelFrameType.HttpBody);
535
+ expect(bodyFrame).toBeTruthy();
536
+ const body = JSON.parse(Buffer.from(bodyFrame.payload).toString('utf8'));
537
+ expect(body.origin).toBe(loopbackOrigin);
538
+ expect(body.relay).toBe('tunnel-conn-true');
539
+ // Unauthenticated request through the same host is denied by the same
540
+ // server-side gate (no credentials injected by the host).
541
+ outbound.length = 0;
542
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, 3, encodeJsonPayload({
543
+ method: 'GET',
544
+ path: '/api/echo-tunnel',
545
+ query: '',
546
+ headers: { origin: 'https://evil.example' },
547
+ })));
548
+ await waitForFrames(() => decodeOutbound().some((f) => f.frameType === TunnelFrameType.StreamEnd));
549
+ const denied = decodeOutbound().find((f) => f.frameType === TunnelFrameType.HttpResponse);
550
+ expect(JSON.parse(Buffer.from(denied.payload).toString('utf8')).status).toBe(401);
551
+ } finally {
552
+ host.close();
553
+ liveRevocation.dispose();
554
+ uiAuthController.dispose?.();
555
+ realServer.closeAllConnections?.();
556
+ await new Promise((resolve) => realServer.close(resolve));
557
+ await fs.promises.rm(storePath, { force: true }).catch(() => {});
558
+ }
559
+ // Gap label: this proves true-tunnel HTTP auth + origin overwrite. It
560
+ // does not prove tunneled WebSocket upgrades or long-lived SSE streaming
561
+ // through the tunnel — those paths reuse the same server-side
562
+ // ensureSessionToken/origin gates but have no disposable integration here.
563
+ }, 20_000);
564
+ });
565
+
566
+ const coordinatorHasNoLiveConnection = (coordinator, clientId) =>
567
+ coordinator.countPrincipal(`client:${clientId}`) === 0;