@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.
- package/dist/assets/DiagramView-BvrCkm_z.js +1 -0
- package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
- package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
- package/dist/assets/FilesView-CNHu4RnC.js +6 -0
- package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
- package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
- package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-CDRZswx-.js} +1 -1
- package/dist/assets/SettingsView-hyAGp836.js +2 -0
- package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
- package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
- package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-D_31YElh.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-BZpvAhrX.js +8 -0
- package/dist/assets/{index-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
- package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
- package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
- package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
- package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
- package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
- package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
- package/dist/assets/{mobile-D0HVxiyJ.js → mobile-BmSlVuhn.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
- package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
- package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
- package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
- package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
- package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
- package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
- package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
- package/dist/assets/{web-components-B5sMa_kC.js → web-components-CYngz9Ml.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +17 -3
- package/server/lib/client-auth/DOCUMENTATION.md +184 -0
- package/server/lib/client-auth/live-revocation.test.js +567 -0
- package/server/lib/client-auth/principal-tracker.js +383 -0
- package/server/lib/client-auth/principal-tracker.test.js +321 -0
- package/server/lib/client-auth/remote-clients.js +31 -0
- package/server/lib/client-auth/remote-clients.test.js +44 -0
- package/server/lib/fs/DOCUMENTATION.md +15 -3
- package/server/lib/fs/routes.js +369 -51
- package/server/lib/fs/routes.test.js +565 -3
- package/server/lib/fs/search.js +74 -29
- package/server/lib/pi/event-stream.js +269 -0
- package/server/lib/pi/event-stream.test.js +776 -0
- package/server/lib/pi/routes.js +132 -28
- package/server/lib/pi/routes.test.js +213 -4
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -4
- package/server/lib/pi/session-daemon/ipc-client.js +19 -15
- package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
- package/server/lib/pi/session-daemon/prompt-operations.test.js +9 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
- package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
- package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
- package/server/lib/pi/session-daemon/session-daemon.js +339 -37
- package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
- package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
- package/server/lib/pi/session-daemon/supervisor.js +30 -5
- package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
- package/server/lib/pi/ui-settings-store.js +1 -1
- package/server/lib/pi/ui-settings-store.test.js +3 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -0
- package/server/lib/stt/DOCUMENTATION.md +2 -0
- package/server/lib/stt/runtime.js +39 -2
- package/server/lib/stt/runtime.test.js +53 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +48 -2
- package/server/lib/terminal/runtime.test.js +35 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
- package/server/lib/ui-auth/ui-auth.js +98 -0
- package/server/lib/ui-auth/ui-auth.test.js +249 -0
- package/server/lib/workspace/host.js +9 -3
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
- package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
- package/dist/assets/FilesView-CJytSUAX.js +0 -6
- package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
- package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
- package/dist/assets/index-DIF8b4bh.css +0 -1
- package/dist/assets/index-jrfQYSvP.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
- package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
- package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
- package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
- package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
|
@@ -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
|
|
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);
|
|
@@ -2,6 +2,8 @@ import { afterAll, describe, expect, it } from 'bun:test';
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import { createPrincipalTracker } from '../client-auth/principal-tracker.js';
|
|
5
7
|
|
|
6
8
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-ui-auth-test-'));
|
|
7
9
|
process.env.PICHAMBER_DATA_DIR = dataDir;
|
|
@@ -300,3 +302,250 @@ describe('ui auth client credential seam', () => {
|
|
|
300
302
|
expect(expiresAt).toBeLessThanOrEqual(Date.now() + 124_000);
|
|
301
303
|
});
|
|
302
304
|
});
|
|
305
|
+
|
|
306
|
+
describe('ui auth live revocation', () => {
|
|
307
|
+
const createRealClientAuth = async () => {
|
|
308
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-ui-auth-revoke-'));
|
|
309
|
+
const remoteClientAuthRuntime = (await import('../client-auth/remote-clients.js')).createRemoteClientAuthRuntime({
|
|
310
|
+
fsPromises: fs.promises,
|
|
311
|
+
path,
|
|
312
|
+
crypto,
|
|
313
|
+
storePath: path.join(dir, 'remote-clients.json'),
|
|
314
|
+
});
|
|
315
|
+
return { dir, remoteClientAuthRuntime };
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
const createEventStreamResponse = () => {
|
|
319
|
+
const res = createResponse();
|
|
320
|
+
res.destroyed = false;
|
|
321
|
+
res.writableEnded = false;
|
|
322
|
+
res.destroyCalls = 0;
|
|
323
|
+
res.destroy = () => {
|
|
324
|
+
res.destroyCalls += 1;
|
|
325
|
+
res.destroyed = true;
|
|
326
|
+
};
|
|
327
|
+
return res;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const eventStreamReq = (headers = {}) => ({
|
|
331
|
+
method: 'GET',
|
|
332
|
+
path: '/api/pi/events',
|
|
333
|
+
url: '/api/pi/events',
|
|
334
|
+
headers,
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it('denies an already-minted URL token at establishment after revocation (mint/open race)', async () => {
|
|
338
|
+
const { dir, remoteClientAuthRuntime } = await createRealClientAuth();
|
|
339
|
+
try {
|
|
340
|
+
const created = await remoteClientAuthRuntime.createClient({ label: 'Phone' });
|
|
341
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
342
|
+
const auth = createUiAuth({
|
|
343
|
+
password: 'secret',
|
|
344
|
+
clientAuthController: remoteClientAuthRuntime,
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
const mintRes = createResponse();
|
|
348
|
+
await auth.handleUrlAuthToken({
|
|
349
|
+
method: 'POST',
|
|
350
|
+
path: '/auth/url-token',
|
|
351
|
+
headers: { authorization: `Bearer ${created.token}`, accept: 'application/json' },
|
|
352
|
+
}, mintRes);
|
|
353
|
+
const urlToken = mintRes.body.token;
|
|
354
|
+
expect(urlToken.startsWith('oc_url_')).toBe(true);
|
|
355
|
+
|
|
356
|
+
// Establishment still works before revocation.
|
|
357
|
+
const wsPath = '/api/terminal/ws';
|
|
358
|
+
const beforeRevoke = {
|
|
359
|
+
method: 'GET',
|
|
360
|
+
path: wsPath,
|
|
361
|
+
url: `${wsPath}?oc_url_token=${encodeURIComponent(urlToken)}`,
|
|
362
|
+
headers: { connection: 'Upgrade', upgrade: 'websocket' },
|
|
363
|
+
};
|
|
364
|
+
expect(await auth.ensureSessionToken(beforeRevoke, createResponse())).toBe(`client:${created.client.id}`);
|
|
365
|
+
|
|
366
|
+
// Revoke, then try to open with the token minted moments earlier.
|
|
367
|
+
await remoteClientAuthRuntime.revokeClient(created.client.id);
|
|
368
|
+
for (const path of ['/api/terminal/ws', '/api/stt/ws']) {
|
|
369
|
+
const openReq = {
|
|
370
|
+
method: 'GET',
|
|
371
|
+
path,
|
|
372
|
+
url: `${path}?oc_url_token=${encodeURIComponent(urlToken)}`,
|
|
373
|
+
headers: { connection: 'Upgrade', upgrade: 'websocket' },
|
|
374
|
+
};
|
|
375
|
+
expect(await auth.ensureSessionToken(openReq, createResponse())).toBe(null);
|
|
376
|
+
}
|
|
377
|
+
const sseReq = {
|
|
378
|
+
method: 'GET',
|
|
379
|
+
path: '/api/pi/events',
|
|
380
|
+
url: `/api/pi/events?oc_url_token=${encodeURIComponent(urlToken)}`,
|
|
381
|
+
headers: {},
|
|
382
|
+
};
|
|
383
|
+
const sseRes = createResponse();
|
|
384
|
+
let opened = false;
|
|
385
|
+
await auth.requireAuth(sseReq, sseRes, () => { opened = true; });
|
|
386
|
+
expect(opened).toBe(false);
|
|
387
|
+
expect(sseRes.statusCode).toBe(401);
|
|
388
|
+
auth.dispose();
|
|
389
|
+
} finally {
|
|
390
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
it('tracks authenticated SSE connections under the verified principal and closes them on revocation', async () => {
|
|
395
|
+
const { dir, remoteClientAuthRuntime } = await createRealClientAuth();
|
|
396
|
+
try {
|
|
397
|
+
const revokedDevice = await remoteClientAuthRuntime.createClient({ label: 'Phone' });
|
|
398
|
+
const otherDevice = await remoteClientAuthRuntime.createClient({ label: 'Tablet' });
|
|
399
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
400
|
+
const tracker = createPrincipalTracker();
|
|
401
|
+
const liveRevocation = {
|
|
402
|
+
trackLiveConnection: ({ principal, close }) => tracker.track({ principal, close }),
|
|
403
|
+
clientRevoked: (clientId) => tracker.closePrincipal(`client:${clientId}`, 'credential-revoked'),
|
|
404
|
+
revokeAllLive: (reason) => tracker.closeAll(reason),
|
|
405
|
+
};
|
|
406
|
+
const auth = createUiAuth({
|
|
407
|
+
password: 'secret',
|
|
408
|
+
clientAuthController: remoteClientAuthRuntime,
|
|
409
|
+
liveRevocation,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
const revokedRes = createEventStreamResponse();
|
|
413
|
+
const otherRes = createEventStreamResponse();
|
|
414
|
+
await auth.requireAuth(eventStreamReq({ authorization: `Bearer ${revokedDevice.token}` }), revokedRes, () => {});
|
|
415
|
+
await auth.requireAuth(eventStreamReq({ authorization: `Bearer ${otherDevice.token}` }), otherRes, () => {});
|
|
416
|
+
|
|
417
|
+
// Both streams are tracked under their store-derived principal — never
|
|
418
|
+
// under a client-supplied ID.
|
|
419
|
+
expect(tracker.countPrincipal(`client:${revokedDevice.client.id}`)).toBe(1);
|
|
420
|
+
expect(tracker.countPrincipal(`client:${otherDevice.client.id}`)).toBe(1);
|
|
421
|
+
expect(revokedRes.destroyCalls).toBe(0);
|
|
422
|
+
|
|
423
|
+
// The auth-owning revoke route: store write, then immediate close.
|
|
424
|
+
await remoteClientAuthRuntime.revokeClient(revokedDevice.client.id);
|
|
425
|
+
expect(liveRevocation.clientRevoked(revokedDevice.client.id)).toBe(1);
|
|
426
|
+
|
|
427
|
+
expect(revokedRes.destroyCalls).toBe(1);
|
|
428
|
+
// The other device keeps its live connection.
|
|
429
|
+
expect(otherRes.destroyCalls).toBe(0);
|
|
430
|
+
expect(tracker.countPrincipal(`client:${otherDevice.client.id}`)).toBe(1);
|
|
431
|
+
|
|
432
|
+
// A revoked device cannot reconnect.
|
|
433
|
+
const reconnectRes = createResponse();
|
|
434
|
+
let reconnected = false;
|
|
435
|
+
await auth.requireAuth(eventStreamReq({ authorization: `Bearer ${revokedDevice.token}` }), reconnectRes, () => { reconnected = true; });
|
|
436
|
+
expect(reconnected).toBe(false);
|
|
437
|
+
expect(reconnectRes.statusCode).toBe(401);
|
|
438
|
+
|
|
439
|
+
auth.dispose();
|
|
440
|
+
} finally {
|
|
441
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
it('closes tracked live connections when global sign-out is requested', async () => {
|
|
446
|
+
const { dir, remoteClientAuthRuntime } = await createRealClientAuth();
|
|
447
|
+
try {
|
|
448
|
+
const created = await remoteClientAuthRuntime.createClient({ label: 'Phone' });
|
|
449
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
450
|
+
const tracker = createPrincipalTracker();
|
|
451
|
+
const closed = [];
|
|
452
|
+
const liveRevocation = {
|
|
453
|
+
trackLiveConnection: ({ principal, close }) => tracker.track({
|
|
454
|
+
principal,
|
|
455
|
+
close: (reason) => {
|
|
456
|
+
closed.push({ principal, reason });
|
|
457
|
+
// Forward to the transport close the auth boundary registered.
|
|
458
|
+
close(reason);
|
|
459
|
+
},
|
|
460
|
+
}),
|
|
461
|
+
revokeAllLive: (reason) => tracker.closeAll(reason),
|
|
462
|
+
};
|
|
463
|
+
const auth = createUiAuth({
|
|
464
|
+
password: 'secret',
|
|
465
|
+
clientAuthController: remoteClientAuthRuntime,
|
|
466
|
+
liveRevocation,
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
const loginRes = createResponse();
|
|
470
|
+
await auth.handleSessionCreate({ method: 'POST', headers: {}, body: { password: 'secret' } }, loginRes);
|
|
471
|
+
const sessionCookie = String(loginRes.getHeader('set-cookie') || '').split(';', 1)[0];
|
|
472
|
+
|
|
473
|
+
const sseRes = createEventStreamResponse();
|
|
474
|
+
await auth.requireAuth(eventStreamReq({ cookie: sessionCookie }), sseRes, () => {});
|
|
475
|
+
|
|
476
|
+
const resetRes = createResponse();
|
|
477
|
+
await auth.requireSessionAuth({ method: 'POST', path: '/auth/reset', headers: { cookie: sessionCookie } }, resetRes, async () => {
|
|
478
|
+
await auth.handleResetAuth({ method: 'POST', path: '/auth/reset', headers: { cookie: sessionCookie } }, resetRes);
|
|
479
|
+
});
|
|
480
|
+
expect(resetRes.body.signedOutEverywhere).toBe(true);
|
|
481
|
+
expect(closed).toEqual([{ principal: expect.any(String), reason: 'signout-everywhere' }]);
|
|
482
|
+
expect(sseRes.destroyCalls).toBe(1);
|
|
483
|
+
|
|
484
|
+
// The rotated signing secret denies the old session immediately.
|
|
485
|
+
const afterRes = createResponse();
|
|
486
|
+
let afterCalled = false;
|
|
487
|
+
await auth.requireAuth(eventStreamReq({ cookie: sessionCookie }), afterRes, () => { afterCalled = true; });
|
|
488
|
+
expect(afterCalled).toBe(false);
|
|
489
|
+
expect(afterRes.statusCode).toBe(401);
|
|
490
|
+
auth.dispose();
|
|
491
|
+
} finally {
|
|
492
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
it('passes the pre-verify generation to the tracker so a racing global invalidation is rejected', async () => {
|
|
497
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
498
|
+
const seen = [];
|
|
499
|
+
let generation = 7;
|
|
500
|
+
const liveRevocation = {
|
|
501
|
+
getGeneration: () => generation,
|
|
502
|
+
trackLiveConnection: ({ principal, close, generation: atTrack }) => {
|
|
503
|
+
seen.push({ principal, generation: atTrack });
|
|
504
|
+
return { end: () => {}, revoke: () => false, active: true };
|
|
505
|
+
},
|
|
506
|
+
};
|
|
507
|
+
const auth = createUiAuth({
|
|
508
|
+
password: 'secret',
|
|
509
|
+
clientAuthController: { authenticateBearerToken: async () => null },
|
|
510
|
+
liveRevocation,
|
|
511
|
+
});
|
|
512
|
+
const loginRes = createResponse();
|
|
513
|
+
await auth.handleSessionCreate({ method: 'POST', headers: {}, body: { password: 'secret' } }, loginRes);
|
|
514
|
+
const sessionCookie = String(loginRes.getHeader('set-cookie') || '').split(';', 1)[0];
|
|
515
|
+
// Generation is captured before verification; a rotation racing the
|
|
516
|
+
// await would bump the coordinator, so the captured value must match
|
|
517
|
+
// the pre-verify snapshot, not a post-verify reread.
|
|
518
|
+
generation = 7;
|
|
519
|
+
await auth.requireAuth(eventStreamReq({ cookie: sessionCookie }), createResponse(), () => {});
|
|
520
|
+
expect(seen).toHaveLength(1);
|
|
521
|
+
expect(seen[0].generation).toBe(7);
|
|
522
|
+
auth.dispose();
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
it('refuses global sign-out while PICHAMBER_JWT_SECRET is set without closing live connections', async () => {
|
|
526
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
527
|
+
const previous = process.env.PICHAMBER_JWT_SECRET;
|
|
528
|
+
process.env.PICHAMBER_JWT_SECRET = 'env-secret-for-test';
|
|
529
|
+
try {
|
|
530
|
+
let revokeCalls = 0;
|
|
531
|
+
const liveRevocation = {
|
|
532
|
+
trackLiveConnection: () => ({ end: () => {}, revoke: () => false, active: true }),
|
|
533
|
+
revokeAllLive: () => { revokeCalls += 1; return 0; },
|
|
534
|
+
};
|
|
535
|
+
const auth = createUiAuth({
|
|
536
|
+
password: 'secret',
|
|
537
|
+
clientAuthController: { authenticateBearerToken: async () => null },
|
|
538
|
+
liveRevocation,
|
|
539
|
+
});
|
|
540
|
+
const res = createResponse();
|
|
541
|
+
await auth.handleResetAuth({ method: 'POST', headers: {} }, res);
|
|
542
|
+
expect(res.statusCode).toBe(400);
|
|
543
|
+
expect(String(res.body?.error || '')).toMatch(/PICHAMBER_JWT_SECRET/);
|
|
544
|
+
expect(revokeCalls).toBe(0);
|
|
545
|
+
auth.dispose();
|
|
546
|
+
} finally {
|
|
547
|
+
if (previous === undefined) delete process.env.PICHAMBER_JWT_SECRET;
|
|
548
|
+
else process.env.PICHAMBER_JWT_SECRET = previous;
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
});
|
|
@@ -13,7 +13,11 @@ import { createTerminalRuntime } from '../terminal/runtime.js';
|
|
|
13
13
|
import { createSttRuntime } from '../stt/runtime.js';
|
|
14
14
|
import { getExecutableSearchDirectories } from '../tunnels/executable-search.js';
|
|
15
15
|
|
|
16
|
-
const normalizeDirectoryPath = (value) =>
|
|
16
|
+
export const normalizeDirectoryPath = (value) => {
|
|
17
|
+
if (typeof value !== 'string') return '';
|
|
18
|
+
const requested = value.trim();
|
|
19
|
+
return path.resolve(requested === '~' ? os.homedir() : requested);
|
|
20
|
+
};
|
|
17
21
|
|
|
18
22
|
const buildAugmentedPath = () => mergePathValues(process.env.PATH || '', process.env.Path || '', path.delimiter);
|
|
19
23
|
|
|
@@ -40,7 +44,7 @@ const resolveProjectDirectory = async (req) => {
|
|
|
40
44
|
const requested = typeof query === 'string' && query.trim() ? query.trim() : (typeof header === 'string' ? header.trim() : '');
|
|
41
45
|
if (!requested) return { directory: process.cwd(), error: null };
|
|
42
46
|
try {
|
|
43
|
-
const resolved =
|
|
47
|
+
const resolved = normalizeDirectoryPath(requested);
|
|
44
48
|
const stats = await fs.promises.stat(resolved);
|
|
45
49
|
if (!stats.isDirectory()) return { directory: null, error: 'Specified path is not a directory' };
|
|
46
50
|
return { directory: await fs.promises.realpath(resolved), error: null };
|
|
@@ -49,7 +53,7 @@ const resolveProjectDirectory = async (req) => {
|
|
|
49
53
|
}
|
|
50
54
|
};
|
|
51
55
|
|
|
52
|
-
export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthController, dataDir }) => {
|
|
56
|
+
export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthController, dataDir, liveRevocation = null }) => {
|
|
53
57
|
const security = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
|
|
54
58
|
registerGitRoutes(app);
|
|
55
59
|
registerFsRoutes(app, {
|
|
@@ -71,6 +75,7 @@ export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthCont
|
|
|
71
75
|
fs,
|
|
72
76
|
path,
|
|
73
77
|
uiAuthController,
|
|
78
|
+
liveRevocation,
|
|
74
79
|
buildAugmentedPath,
|
|
75
80
|
searchPathFor,
|
|
76
81
|
isExecutable,
|
|
@@ -82,6 +87,7 @@ export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthCont
|
|
|
82
87
|
server,
|
|
83
88
|
express,
|
|
84
89
|
uiAuthController,
|
|
90
|
+
liveRevocation,
|
|
85
91
|
isRequestOriginAllowed: security.isRequestOriginAllowed,
|
|
86
92
|
rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
|
|
87
93
|
modelsDir: path.join(dataDir, 'speech-models'),
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import { normalizeDirectoryPath } from './host.js';
|
|
6
|
+
|
|
7
|
+
describe('workspace directory normalization', () => {
|
|
8
|
+
it('expands the global-session home sentinel', () => {
|
|
9
|
+
expect(normalizeDirectoryPath('~')).toBe(path.resolve(os.homedir()));
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('keeps ordinary path resolution behavior', () => {
|
|
13
|
+
expect(normalizeDirectoryPath('./workspace')).toBe(path.resolve('./workspace'));
|
|
14
|
+
});
|
|
15
|
+
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{m as x}from"./index-jrfQYSvP.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{R as r,j as t}from"./vendor-react-B5Z1Mdn3.js";import{u as a}from"./index-jrfQYSvP.js";import{a9 as v,I as m}from"./useAppFontEffects-BP07Vl6M.js";import{D as j}from"./DiagramEditor-BPDkGHsj.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-CdaWtC7e.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-vilE4xyj.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-BJrrV83E.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-CNlncqrr.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";import"./vendor-react-drawio-BYDptOsj.js";function Kt(){const{files:o}=v(),[e,d]=r.useState(null),[s,p]=r.useState(""),[x,n]=r.useState(!0),l=r.useRef(null),c=a(i=>i.pendingDiagramFile),u=r.useCallback(async i=>{n(!0),d(i);try{const f=await o?.readFile?.(i);f&&p(f.content)}catch{p("")}finally{n(!1)}},[o]);r.useEffect(()=>{if(!c)return;const i=a.getState().consumePendingDiagramFile();i&&u(i)},[u,c]);const g=r.useCallback(async()=>{const i=l.current?.getXml();e&&o?.writeFile&&i&&i!==s&&(await o.writeFile(e,i),p(i))},[e,o,s]),h=e?e.split("/").pop()||e:"";return e?x?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx(m,{name:"loader-4",className:"size-4 animate-spin"})}):t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[t.jsx(m,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:h}),t.jsx("button",{type:"button",onClick:()=>{g()},className:"size-6 flex items-center justify-center rounded-md text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Save diagram",children:t.jsx(m,{name:"save-3",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>a.getState().setActiveMainTab("chat"),className:"size-6 flex items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Close diagram view",children:t.jsx(m,{name:"close",className:"size-4"})})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(j,{ref:l,xml:s,className:"h-full"})})]}):t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("div",{className:"typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}export{Kt as DiagramView};
|