@openchamber/web 1.23.2 → 1.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.test.js +7 -6
- package/bin/lib/cli-http.js +5 -1
- package/dist/assets/{CodeMirrorCommentWidgets-DdNGwbBw.js → CodeMirrorCommentWidgets-DvUH815P.js} +1 -1
- package/dist/assets/DiffView-DkC3xlRJ.js +4 -0
- package/dist/assets/FilesView-D0bM9FVB.js +13 -0
- package/dist/assets/GitView-Bxuv3dfP.js +6 -0
- package/dist/assets/GuestAttachDialog-B0u3Q5uO.js +1 -0
- package/dist/assets/{JsonTreeView-Chzx5Y6N.js → JsonTreeView-BBVPFM5K.js} +1 -1
- package/dist/assets/LinearIssuesView-UI1FcSC8.js +1 -0
- package/dist/assets/{MarkdownImageGallery-CugnrZ6f.js → MarkdownImageGallery-CUJxH8Le.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-D5BZOg8X.js +12 -0
- package/dist/assets/{OnboardingScreen-hH9xcTjA.js → OnboardingScreen-5Gou9cGD.js} +1 -1
- package/dist/assets/{PatchDiff-DRgNYc9l.js → PatchDiff-C4rE5k6z.js} +1 -1
- package/dist/assets/{PierreDiffViewer-ZT2CKuzJ.js → PierreDiffViewer-ByRVu6ss.js} +5 -5
- package/dist/assets/PlanView-u2yi5XGJ.js +5 -0
- package/dist/assets/PluginPane-QxjsKYeO.js +3 -0
- package/dist/assets/SettingsView-Fo5ZqMaT.js +29 -0
- package/dist/assets/{SettingsWindow-DisOghhD.js → SettingsWindow-HVDVANjJ.js} +1 -1
- package/dist/assets/SubmoduleDiffSummary-D3hzkybB.js +1 -0
- package/dist/assets/ToolOutputDialog-3J6IRayW.js +15 -0
- package/dist/assets/{ToolPartDiffPreview-oWxWCu-4.js → ToolPartDiffPreview-DarxPjSd.js} +2 -2
- package/dist/assets/{VirtualizedFileDiff-CiyrAq_I.js → VirtualizedFileDiff-CZgXWHjU.js} +4 -4
- package/dist/assets/{WalkthroughView-CKTevaea.js → WalkthroughView-wSpED5L4.js} +2 -2
- package/dist/assets/appThemeRegistry-Cf8KitzT.js +1 -0
- package/dist/assets/commitAndPush-DZnzlhvc.js +1 -0
- package/dist/assets/{computeVirtualFileMetrics-SUWoTyPe.js → computeVirtualFileMetrics-VYnT_A2h.js} +1 -1
- package/dist/assets/de-BM_8EDD3.js +10 -0
- package/dist/assets/es-CxZjlqpo.js +16 -0
- package/dist/assets/fr-VCixCnMW.js +14 -0
- package/dist/assets/{index-C4jJ3Ur5.js → index-3U4CtS9b.js} +1 -1
- package/dist/assets/index-B9Hvzjwl.css +1 -0
- package/dist/assets/index-DLHQogv8.js +40 -0
- package/dist/assets/{isDiffPlainText-DfG0cZxr.js → isDiffPlainText-ImDG3Uhg.js} +1 -1
- package/dist/assets/{isFilePlainText-CyNivOCU.js → isFilePlainText-D_YDVYDb.js} +1 -1
- package/dist/assets/ja-CZ5k_GyD.js +16 -0
- package/dist/assets/ko-7YM3A1Xh.js +16 -0
- package/dist/assets/{main-B8cGozKr.js → main-CycplCph.js} +2 -2
- package/dist/assets/main-DFYTCx5o.js +896 -0
- package/dist/assets/{markdown-shiki.worker-D5fBU-lw.js → markdown-shiki.worker-CahLvHIq.js} +5 -5
- package/dist/assets/markdownCore-DHvqMxPn.js +5 -0
- package/dist/assets/{miniChat-Cay99IxR.js → miniChat-DIQKfY2V.js} +2 -2
- package/dist/assets/{mobile-Zfhix7nz.js → mobile-BMwz5q-m.js} +2 -2
- package/dist/assets/{patchFileDiff-CJ5AN9Ql.js → patchFileDiff-DDQ6Rq5e.js} +3 -3
- package/dist/assets/pl-BcgDO_w5.js +16 -0
- package/dist/assets/{pt-BR-CLosVawq.js → pt-BR-CU2u_1q5.js} +4 -4
- package/dist/assets/renderElectronMiniChatApp-3_d6g6CU.js +2 -0
- package/dist/assets/renderMobileApp-D0Y8DtkA.js +25 -0
- package/dist/assets/runtimeEndpointReset-DhC3REb2.js +25 -0
- package/dist/assets/{scheduledTasksApi-CGFV4Pap.js → scheduledTasksApi-D8pq6gQz.js} +1 -1
- package/dist/assets/shikiHighlight-1imXsir9.js +1 -0
- package/dist/assets/textMateThemeFromAppTheme-Dgqc63LZ.js +1 -0
- package/dist/assets/tr-DuYhOzNe.js +7 -0
- package/dist/assets/uk-Cuk7-uvq.js +16 -0
- package/dist/assets/useAppFontEffects-BItUWdo4.js +7333 -0
- package/dist/assets/useInlineCommentController-CkbKsm7m.js +2 -0
- package/dist/assets/useRootScrollLock-vmzxZjWA.js +2 -0
- package/dist/assets/{vendor-base-ui-BY_5qla_.js → vendor-base-ui-CsXYnR5c.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-ES33GhKK.js → vendor-codemirror-language-data-BDyxuqK4.js} +2 -2
- package/dist/assets/vendor-framer-motion-Bq3iTZ6r.js +1 -0
- package/dist/assets/{vendor-motion-dom-D_o3BTI3.js → vendor-motion-dom-DcCgeG69.js} +1 -1
- package/dist/assets/vendor-strip-json-comments-5dJlOkP1.js +4 -0
- package/dist/assets/{vendor-tanstack-react-virtual-g05Cx3z9.js → vendor-tanstack-react-virtual-ClYN8CzB.js} +1 -1
- package/dist/assets/{vendor-tanstack-virtual-core-Dubg10g5.js → vendor-tanstack-virtual-core-BewVQryB.js} +1 -1
- package/dist/assets/{vendor-zod-B6551dwG.js → vendor-zod-fZppILAM.js} +4 -4
- package/dist/assets/{web-components-CJZwV5BE.js → web-components-D7FinaeH.js} +2 -2
- package/dist/assets/zh-CN-CUWoiRHd.js +16 -0
- package/dist/assets/zh-TW-CQ8EBSBN.js +16 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +9 -6
- package/server/built-in-extensions/registry.json +4 -0
- package/server/index.d.ts +2 -0
- package/server/index.js +41 -10
- package/server/lib/changelog/update-notes.js +2 -1
- package/server/lib/changelog/update-notes.test.js +19 -0
- package/server/lib/event-stream/DOCUMENTATION.md +23 -0
- package/server/lib/event-stream/delta-coalescer.js +0 -0
- package/server/lib/event-stream/delta-coalescer.test.js +292 -0
- package/server/lib/event-stream/global-hub.js +53 -23
- package/server/lib/event-stream/global-hub.test.js +160 -0
- package/server/lib/event-stream/global-ws-bridge.js +1 -0
- package/server/lib/event-stream/index.js +4 -0
- package/server/lib/fs/DOCUMENTATION.md +8 -0
- package/server/lib/fs/git-process.test.js +77 -0
- package/server/lib/fs/routes.js +2 -1
- package/server/lib/fs/search.js +2 -1
- package/server/lib/git/DOCUMENTATION.md +19 -4
- package/server/lib/git/routes.js +16 -3
- package/server/lib/git/serial-refresh.js +93 -0
- package/server/lib/git/serial-refresh.test.js +112 -0
- package/server/lib/git/service.js +336 -62
- package/server/lib/git/service.test.js +400 -0
- package/server/lib/github/pr-status.js +5 -5
- package/server/lib/github/pr-status.test.js +1 -1
- package/server/lib/github/routes.js +4 -4
- package/server/lib/guests/DOCUMENTATION.md +68 -0
- package/server/lib/guests/auth-store.js +184 -0
- package/server/lib/guests/auth-store.test.js +112 -0
- package/server/lib/guests/background.test.js +83 -0
- package/server/lib/guests/builtins.js +34 -0
- package/server/lib/guests/builtins.test.js +174 -0
- package/server/lib/guests/catalog.js +477 -0
- package/server/lib/guests/catalog.test.js +390 -0
- package/server/lib/guests/clone.js +297 -0
- package/server/lib/guests/extract-zip.js +136 -0
- package/server/lib/guests/extract-zip.test.js +109 -0
- package/server/lib/guests/files.js +308 -0
- package/server/lib/guests/files.test.js +262 -0
- package/server/lib/guests/grant-scope.js +81 -0
- package/server/lib/guests/grant-scope.test.js +75 -0
- package/server/lib/guests/host-session.js +73 -0
- package/server/lib/guests/host-session.test.js +30 -0
- package/server/lib/guests/html-styles.js +6 -0
- package/server/lib/guests/html-styles.test.js +45 -0
- package/server/lib/guests/html-tokens.js +73 -0
- package/server/lib/guests/html-tokens.test.js +53 -0
- package/server/lib/guests/install.js +406 -0
- package/server/lib/guests/install.test.js +338 -0
- package/server/lib/guests/oauth.js +501 -0
- package/server/lib/guests/oauth.test.js +481 -0
- package/server/lib/guests/persist.js +336 -0
- package/server/lib/guests/persist.test.js +288 -0
- package/server/lib/guests/request.js +112 -0
- package/server/lib/guests/request.test.js +206 -0
- package/server/lib/guests/routes.js +838 -0
- package/server/lib/guests/service.js +538 -0
- package/server/lib/guests/service.test.js +277 -0
- package/server/lib/guests/sockets.js +129 -0
- package/server/lib/guests/sockets.test.js +110 -0
- package/server/lib/guests/ssh-install.test.js +188 -0
- package/server/lib/guests/storage.js +68 -0
- package/server/lib/guests/storage.test.js +59 -0
- package/server/lib/guests/updates.js +294 -0
- package/server/lib/guests/updates.test.js +334 -0
- package/server/lib/guests/upload.js +50 -0
- package/server/lib/guests/upload.test.js +131 -0
- package/server/lib/linear/DOCUMENTATION.md +1 -1
- package/server/lib/message-queue/DOCUMENTATION.md +6 -0
- package/server/lib/message-queue/runtime.js +5 -0
- package/server/lib/message-queue/runtime.test.js +32 -1
- package/server/lib/openchamber-control/DOCUMENTATION.md +6 -0
- package/server/lib/openchamber-sessions/routes.js +44 -11
- package/server/lib/openchamber-sessions/routes.test.js +47 -0
- package/server/lib/opencode/DOCUMENTATION.md +40 -0
- package/server/lib/opencode/core-routes.js +39 -1
- package/server/lib/opencode/feature-routes-runtime.js +15 -0
- package/server/lib/opencode/lifecycle-process.test.js +84 -0
- package/server/lib/opencode/lifecycle.js +54 -67
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-normalization-runtime.js +2 -0
- package/server/lib/opencode/settings-normalization-runtime.test.js +13 -0
- package/server/lib/opencode/settings-registry.json +12 -0
- package/server/lib/opencode/shutdown-runtime.js +3 -0
- package/server/lib/opencode/shutdown-runtime.test.js +24 -0
- package/server/lib/opencode/theme-archive.js +53 -0
- package/server/lib/opencode/theme-catalog.js +171 -0
- package/server/lib/opencode/theme-catalog.test.js +125 -0
- package/server/lib/opencode/theme-import.test.js +144 -0
- package/server/lib/opencode/theme-runtime.js +100 -28
- package/server/lib/opencode/theme-runtime.test.js +15 -0
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +8 -0
- package/server/lib/permission-auto-accept/runtime.js +13 -0
- package/server/lib/permission-auto-accept/runtime.test.js +37 -1
- package/server/lib/quota/DOCUMENTATION.md +0 -1
- package/server/lib/quota/providers/index.js +0 -7
- package/server/lib/routing/DOCUMENTATION.md +81 -0
- package/server/lib/routing/defaults.js +98 -0
- package/server/lib/routing/feature-flag.js +11 -0
- package/server/lib/routing/history.js +34 -0
- package/server/lib/routing/jev.js +98 -0
- package/server/lib/routing/routes.http.test.js +100 -0
- package/server/lib/routing/routes.js +81 -0
- package/server/lib/routing/runtime.js +217 -0
- package/server/lib/routing/runtime.test.js +188 -0
- package/server/lib/routing/store.js +249 -0
- package/server/lib/routing/store.test.js +96 -0
- package/server/lib/security/request-security.js +9 -5
- package/server/lib/security/request-security.test.js +37 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +17 -2
- package/server/lib/terminal/runtime.test.js +45 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +8 -0
- package/server/lib/ui-auth/session-cookie.js +51 -0
- package/server/lib/ui-auth/session-cookie.test.js +46 -0
- package/server/lib/ui-auth/ui-auth.js +56 -17
- package/server/lib/ui-auth/ui-auth.test.js +96 -0
- package/dist/assets/DiffView-GYriC0Wk.js +0 -4
- package/dist/assets/DirtyBranchSwitchDialog-Bv0C99hc.js +0 -1
- package/dist/assets/FilesView-2Lin13wx.js +0 -13
- package/dist/assets/GitView-9wKba3UO.js +0 -6
- package/dist/assets/LinearIssuesView-DXS9QJiR.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CaMyct2Q.js +0 -12
- package/dist/assets/PlanView-DiTBm2BD.js +0 -5
- package/dist/assets/SettingsView-CN8VeM99.js +0 -28
- package/dist/assets/ToolOutputDialog-BqiKydxR.js +0 -15
- package/dist/assets/appThemeRegistry-BK0dHKa6.js +0 -1
- package/dist/assets/de-DQWC94VK.js +0 -10
- package/dist/assets/es-DixFUD3m.js +0 -16
- package/dist/assets/fr-D6u8tvfA.js +0 -14
- package/dist/assets/index-BvpFzhLs.js +0 -40
- package/dist/assets/index-n5p3SnES.css +0 -1
- package/dist/assets/ja-4u4pCorB.js +0 -16
- package/dist/assets/ko-C27-LW_b.js +0 -16
- package/dist/assets/main-tEA-fFPg.js +0 -930
- package/dist/assets/markdownCore-kyGrWGsn.js +0 -5
- package/dist/assets/pl-FtCjsNdW.js +0 -16
- package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-CuHOGlF4.js +0 -2
- package/dist/assets/renderMobileApp-C4X_KUH8.js +0 -25
- package/dist/assets/runtimeEndpointReset-CMg-KUx3.js +0 -41
- package/dist/assets/shikiHighlight-DdKWYWrV.js +0 -1
- package/dist/assets/tr-D2j6wUez.js +0 -7
- package/dist/assets/uk-C6IzmwM_.js +0 -16
- package/dist/assets/useAppFontEffects-DgCHy6Mr.js +0 -7282
- package/dist/assets/useGitComparison-BIaI0WZI.js +0 -1
- package/dist/assets/useInlineCommentController-2wcCtpM3.js +0 -2
- package/dist/assets/useRootScrollLock-CbWA03xR.js +0 -1
- package/dist/assets/vendor-framer-motion-livSKyyV.js +0 -1
- package/dist/assets/zh-CN-Wl6tIDz1.js +0 -16
- package/dist/assets/zh-TW-hgphoWSN.js +0 -16
- package/server/lib/quota/providers/crof.js +0 -96
- package/server/lib/quota/providers/crof.test.js +0 -98
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createRoutingStore, parseEffectiveConfig, resolveEffectiveConfig, toStoredConfig } from './store.js';
|
|
6
|
+
import { BUILTIN_CATEGORIES } from './defaults.js';
|
|
7
|
+
|
|
8
|
+
const tempDir = () => fs.mkdtemp(path.join(os.tmpdir(), 'routing-store-'));
|
|
9
|
+
|
|
10
|
+
const sampleConfig = (patch = {}) => ({
|
|
11
|
+
enabled: true,
|
|
12
|
+
fallback: { model: { providerID: 'anthropic', modelID: 'claude-sonnet-5' }, variant: 'medium' },
|
|
13
|
+
minConfidence: 0.6,
|
|
14
|
+
safetyNet: { enabled: true, threshold: 0.6 },
|
|
15
|
+
categories: resolveEffectiveConfig(null).categories,
|
|
16
|
+
...patch,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe('routing store', () => {
|
|
20
|
+
it('resolves the defaults when nothing is stored', async () => {
|
|
21
|
+
const store = createRoutingStore({ dataDir: await tempDir() });
|
|
22
|
+
const config = await store.readConfig();
|
|
23
|
+
expect(config.enabled).toBe(false);
|
|
24
|
+
expect(config.fallback).toBeNull();
|
|
25
|
+
expect(config.categories.map((c) => c.id)).toEqual(BUILTIN_CATEGORIES.map((c) => c.id));
|
|
26
|
+
expect(config.categories.every((c) => c.builtin && c.enabled && c.model === null)).toBe(true);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('stores only deviations from the built-ins and round-trips them', async () => {
|
|
30
|
+
const dir = await tempDir();
|
|
31
|
+
const store = createRoutingStore({ dataDir: dir });
|
|
32
|
+
const config = sampleConfig();
|
|
33
|
+
config.categories[0] = { ...config.categories[0], enabled: false };
|
|
34
|
+
config.categories[3] = { ...config.categories[3], model: { providerID: 'openai', modelID: 'gpt-6-astra' }, variant: 'high', agent: 'plan' };
|
|
35
|
+
config.categories.push({ id: 'my-refactors', builtin: false, enabled: true, name: 'My refactors', description: 'Refactors across modules.', model: null, variant: null, agent: null });
|
|
36
|
+
await store.writeConfig(config);
|
|
37
|
+
|
|
38
|
+
const stored = JSON.parse(await fs.readFile(path.join(dir, 'routing.json'), 'utf8'));
|
|
39
|
+
expect(stored.categories).toEqual({
|
|
40
|
+
trivial: { builtin: true, disabled: true },
|
|
41
|
+
hard: { builtin: true, model: { providerID: 'openai', modelID: 'gpt-6-astra' }, variant: 'high', agent: 'plan' },
|
|
42
|
+
'my-refactors': { builtin: false, name: 'My refactors', description: 'Refactors across modules.' },
|
|
43
|
+
});
|
|
44
|
+
expect(await store.readConfig()).toEqual(config);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('records a removed built-in as deleted and keeps the others', async () => {
|
|
48
|
+
const config = sampleConfig();
|
|
49
|
+
config.categories = config.categories.filter((c) => c.id !== 'research');
|
|
50
|
+
const stored = toStoredConfig(config);
|
|
51
|
+
expect(stored.categories.research).toEqual({ builtin: true, deleted: true });
|
|
52
|
+
const resolved = resolveEffectiveConfig(stored);
|
|
53
|
+
expect(resolved.categories.map((c) => c.id)).toEqual(['trivial', 'implement', 'hard']);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('applies later built-in text to an untouched category but keeps an edited one', () => {
|
|
57
|
+
const edited = resolveEffectiveConfig({ version: 1, categories: { hard: { builtin: true, description: 'My own hard.' } } });
|
|
58
|
+
expect(edited.categories.find((c) => c.id === 'hard').description).toBe('My own hard.');
|
|
59
|
+
expect(edited.categories.find((c) => c.id === 'trivial').description).toBe(BUILTIN_CATEGORIES[0].description);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('rejects a malformed file instead of treating it as empty', async () => {
|
|
63
|
+
const dir = await tempDir();
|
|
64
|
+
await fs.writeFile(path.join(dir, 'routing.json'), '{"version":1,"categories":{"x":{"builtin":false}}}');
|
|
65
|
+
const store = createRoutingStore({ dataDir: dir });
|
|
66
|
+
await expect(store.readConfig()).rejects.toThrow(/Invalid routing.json/);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('rejects an invalid PUT body with a 400 status', () => {
|
|
70
|
+
expect(() => parseEffectiveConfig({ enabled: true })).toThrow(expect.objectContaining({ status: 400 }));
|
|
71
|
+
const duplicate = sampleConfig();
|
|
72
|
+
duplicate.categories = [...duplicate.categories, { ...duplicate.categories[0], builtin: false }];
|
|
73
|
+
expect(() => parseEffectiveConfig(duplicate)).toThrow(/Duplicate category id/);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('refuses the Auto sentinel as a fallback or category model', () => {
|
|
77
|
+
const asFallback = sampleConfig({ fallback: { model: { providerID: 'openchamber', modelID: 'auto' }, variant: null } });
|
|
78
|
+
expect(() => parseEffectiveConfig(asFallback)).toThrow(/Auto model cannot be a routing target/);
|
|
79
|
+
const asCategory = sampleConfig();
|
|
80
|
+
asCategory.categories = asCategory.categories.map((c, i) => (i === 0 ? { ...c, model: { providerID: 'openchamber', modelID: 'auto' } } : c));
|
|
81
|
+
expect(() => parseEffectiveConfig(asCategory)).toThrow(/Auto model cannot be a routing target/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('keeps the token in its own 0600 file and clears it', async () => {
|
|
85
|
+
const dir = await tempDir();
|
|
86
|
+
const store = createRoutingStore({ dataDir: dir });
|
|
87
|
+
expect(await store.readToken()).toBeNull();
|
|
88
|
+
await store.writeToken('ts-secret');
|
|
89
|
+
expect(await store.readToken()).toBe('ts-secret');
|
|
90
|
+
const stat = await fs.stat(path.join(dir, 'routing-auth.json'));
|
|
91
|
+
if (process.platform !== 'win32') expect(stat.mode & 0o777).toBe(0o600);
|
|
92
|
+
expect(JSON.stringify(JSON.parse(await fs.readFile(path.join(dir, 'routing.json'), 'utf8').catch(() => '{}')))).not.toContain('ts-secret');
|
|
93
|
+
await store.clearToken();
|
|
94
|
+
expect(await store.readToken()).toBeNull();
|
|
95
|
+
});
|
|
96
|
+
});
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { sessionCookieNameForRequest } from '../ui-auth/session-cookie.js';
|
|
2
|
+
|
|
1
3
|
export const createRequestSecurityRuntime = (deps) => {
|
|
2
4
|
const { readSettingsFromDiskMigrated } = deps;
|
|
3
5
|
// Origins of packaged (non-browser) clients whose WebView origin never
|
|
@@ -17,12 +19,14 @@ export const createRequestSecurityRuntime = (deps) => {
|
|
|
17
19
|
if (!cookieHeader || typeof cookieHeader !== 'string') {
|
|
18
20
|
return null;
|
|
19
21
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
// Match the exact slot for the host:port this request arrived on. A browser
|
|
23
|
+
// shares cookies across ports on LAN and loopback hosts. This extracts
|
|
24
|
+
// notification/session identity, not a CSRF token, using the same name
|
|
25
|
+
// as ui-auth's session issuance and validation.
|
|
26
|
+
const expected = sessionCookieNameForRequest(req);
|
|
27
|
+
for (const segment of cookieHeader.split(';')) {
|
|
22
28
|
const [rawName, ...rest] = segment.split('=');
|
|
23
|
-
|
|
24
|
-
if (!name) continue;
|
|
25
|
-
if (name !== 'oc_ui_session') continue;
|
|
29
|
+
if (rawName?.trim() !== expected) continue;
|
|
26
30
|
const value = rest.join('=').trim();
|
|
27
31
|
try {
|
|
28
32
|
return decodeURIComponent(value || '');
|
|
@@ -80,4 +80,41 @@ describe('request security runtime', () => {
|
|
|
80
80
|
headers: { ...request.headers, origin: 'https://evil.example.com' },
|
|
81
81
|
})).toBe(false);
|
|
82
82
|
});
|
|
83
|
+
|
|
84
|
+
test('reads the slot for the request port when a browser shares jars across LAN ports', () => {
|
|
85
|
+
const runtime = createRuntime();
|
|
86
|
+
// Two instances on one LAN IP: the browser sends BOTH session cookies to
|
|
87
|
+
// either port (browsers key cookie jars on host, not port — issue #2377).
|
|
88
|
+
const req = {
|
|
89
|
+
headers: {
|
|
90
|
+
host: '192.168.0.1:3001',
|
|
91
|
+
cookie: 'oc_ui_session_3000=token-a; oc_ui_session_3001=token-b',
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
expect(runtime.getUiSessionTokenFromRequest(req)).toBe('token-b');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('never reads another port cookie when this port has none of its own', () => {
|
|
98
|
+
const runtime = createRuntime();
|
|
99
|
+
// Reaching :3001 with only the :3000 cookie in the jar must NOT borrow the
|
|
100
|
+
// other instance's session — it stays unauthenticated for this port.
|
|
101
|
+
const req = {
|
|
102
|
+
headers: { host: '192.168.0.1:3001', cookie: 'oc_ui_session_3000=token-a' },
|
|
103
|
+
};
|
|
104
|
+
expect(runtime.getUiSessionTokenFromRequest(req)).toBeNull();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('reads the bare cookie for a host without an explicit port', () => {
|
|
108
|
+
const runtime = createRuntime();
|
|
109
|
+
const req = {
|
|
110
|
+
headers: { host: '192.168.0.1', cookie: 'oc_ui_session=token-bare' },
|
|
111
|
+
};
|
|
112
|
+
expect(runtime.getUiSessionTokenFromRequest(req)).toBe('token-bare');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('returns null when no session cookie is present', () => {
|
|
116
|
+
const runtime = createRuntime();
|
|
117
|
+
const req = { headers: { host: '192.168.0.1:3000', cookie: 'theme=dark; oc_url_token=x' } };
|
|
118
|
+
expect(runtime.getUiSessionTokenFromRequest(req)).toBeNull();
|
|
119
|
+
});
|
|
83
120
|
});
|
|
@@ -37,8 +37,10 @@ HTTP remains the authenticated command plane for create, resize, appearance upda
|
|
|
37
37
|
- Deduplicated create responses may describe another client's execution. Cancellation cleanup closes only the terminal ID allocated for the cancelled request; it never closes an adopted peer execution.
|
|
38
38
|
- Create and restart validate the working directory with a real `stat` and answer HTTP 400 `Invalid working directory` when it is not a directory. When the path does not exist at all (`ENOENT`/`ENOTDIR`, a worktree deleted outside OpenChamber) the body also carries `code: "TERMINAL_CWD_MISSING"`. The client shows the failure without moving the session. The runtime never substitutes a parent directory on its own.
|
|
39
39
|
- Restarts are serialized per terminal. Each restart spawns and wires the replacement before terminating the old process, retaining the terminal ID. Command-mode sessions reject restart with HTTP 400 instead of silently turning into interactive shells with stale action metadata.
|
|
40
|
+
- A restart rechecks session ownership before and after PTY creation. Close, force-kill, idle removal, or shutdown can invalidate it while spawn is pending. A late replacement is terminated instead of being attached to a retired session.
|
|
40
41
|
- A delete that arrives while create is still pending leaves a cancellation tombstone. When the PTY arrives, the runtime terminates it immediately, never inserts the session into the live map, and returns a create error while the delete still succeeds.
|
|
41
42
|
- Close uses SIGTERM with bounded SIGKILL escalation. Force-kill, idle cleanup, and runtime shutdown terminate process groups immediately where supported. Removal explicitly sends a fatal scoped closure and evicts client projections even when a PTY backend fails to emit `onExit`; attached terminals are not considered idle.
|
|
43
|
+
- Shutdown is single-flight, rejects new creates, cancels pending creates, and waits for pending creates and restarts before clearing live sessions. A PTY that arrives during shutdown follows the same cancellation cleanup as a pending create that was explicitly closed.
|
|
42
44
|
|
|
43
45
|
## Security And Relay
|
|
44
46
|
|
|
@@ -100,6 +100,7 @@ export function createTerminalRuntime({
|
|
|
100
100
|
const pendingTerminations = new Set();
|
|
101
101
|
const runtime = typeof globalThis.Bun === 'undefined' ? 'node' : 'bun';
|
|
102
102
|
let ptyProviderPromise = null;
|
|
103
|
+
let shutdownPromise = null;
|
|
103
104
|
let wsServer = new WebSocketServer({ noServer: true, maxPayload: TERMINAL_WS_MAX_PAYLOAD_BYTES });
|
|
104
105
|
const shellResolver = createTerminalShellResolver({ fs, path, searchPathFor, isExecutable, buildAugmentedPath });
|
|
105
106
|
|
|
@@ -282,6 +283,7 @@ export function createTerminalRuntime({
|
|
|
282
283
|
};
|
|
283
284
|
|
|
284
285
|
const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false, mode, command, purpose }) => {
|
|
286
|
+
if (shutdownPromise) throw new Error('Terminal runtime is shutting down');
|
|
285
287
|
if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
|
|
286
288
|
if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
|
|
287
289
|
const normalizedShell = normalizeTerminalShell(shell);
|
|
@@ -507,10 +509,15 @@ export function createTerminalRuntime({
|
|
|
507
509
|
const previousRestart = pendingSessionRestarts.get(session.id) ?? Promise.resolve();
|
|
508
510
|
const restart = previousRestart.catch(() => {}).then(async () => {
|
|
509
511
|
await validateCwd(cwd);
|
|
512
|
+
if (shutdownPromise || sessions.get(session.id) !== session) throw new Error('Terminal session was closed during restart');
|
|
510
513
|
if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
|
|
511
514
|
if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
|
|
512
515
|
const oldProcess = session.process;
|
|
513
516
|
const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell });
|
|
517
|
+
if (shutdownPromise || sessions.get(session.id) !== session) {
|
|
518
|
+
await terminateProcess(spawned.process, true);
|
|
519
|
+
throw new Error('Terminal session was closed during restart');
|
|
520
|
+
}
|
|
514
521
|
session.process = spawned.process; session.backend = spawned.backend; session.shell = spawned.shell; session.loginShell = spawned.loginShell; session.cwd = cwd; session.cols = cols; session.rows = rows;
|
|
515
522
|
session.history = ''; session.pendingHistoryControlSequence = ''; session.pendingThemeControlSequence = ''; session.themeModeEnabled = false; session.status = 'running'; session.exitCode = null; session.signal = null; session.eventQueue.length = 0;
|
|
516
523
|
session.themeMode = themeMode === 'light' ? 'light' : 'dark'; session.terminalBackground = terminalBackground; session.terminalForeground = terminalForeground;
|
|
@@ -560,9 +567,13 @@ export function createTerminalRuntime({
|
|
|
560
567
|
}
|
|
561
568
|
}, 5 * 60 * 1000);
|
|
562
569
|
|
|
563
|
-
const
|
|
570
|
+
const stop = async () => {
|
|
564
571
|
server.off('upgrade', upgradeHandler); clearInterval(idleSweep);
|
|
565
|
-
|
|
572
|
+
for (const pending of pendingSessionCreates.values()) pending.cancelled = true;
|
|
573
|
+
await Promise.allSettled([
|
|
574
|
+
...[...pendingSessionCreates.values()].map((pending) => pending.promise),
|
|
575
|
+
...pendingSessionRestarts.values(),
|
|
576
|
+
]);
|
|
566
577
|
for (const session of sessions.values()) void terminateProcess(session.process, true);
|
|
567
578
|
sessions.clear();
|
|
568
579
|
await Promise.allSettled([...pendingTerminations]);
|
|
@@ -574,5 +585,9 @@ export function createTerminalRuntime({
|
|
|
574
585
|
]);
|
|
575
586
|
wsServer = null;
|
|
576
587
|
};
|
|
588
|
+
const shutdown = () => {
|
|
589
|
+
if (!shutdownPromise) shutdownPromise = stop();
|
|
590
|
+
return shutdownPromise;
|
|
591
|
+
};
|
|
577
592
|
return { shutdown };
|
|
578
593
|
}
|
|
@@ -210,6 +210,51 @@ describe('terminal runtime', () => {
|
|
|
210
210
|
} finally { await harness.runtime.shutdown(); }
|
|
211
211
|
});
|
|
212
212
|
|
|
213
|
+
it('reaps a pending create during shutdown and rejects later creates', async () => {
|
|
214
|
+
const gate = deferred();
|
|
215
|
+
const harness = createHarness({ spawnDeferred: gate });
|
|
216
|
+
const create = harness.routes.post.get('/api/terminal/create');
|
|
217
|
+
const response = createResponse();
|
|
218
|
+
const creation = create({ body: { sessionId: 'pending', cwd: '/repo' } }, response);
|
|
219
|
+
const closing = harness.runtime.shutdown();
|
|
220
|
+
gate.resolve();
|
|
221
|
+
await Promise.all([creation, closing]);
|
|
222
|
+
expect(harness.processes).toHaveLength(1);
|
|
223
|
+
expect(harness.processes[0].killed).toBe(true);
|
|
224
|
+
expect(response.statusCode).toBe(400);
|
|
225
|
+
const later = createResponse();
|
|
226
|
+
await create({ body: { sessionId: 'later', cwd: '/repo' } }, later);
|
|
227
|
+
expect(later.statusCode).toBe(400);
|
|
228
|
+
expect(harness.processes).toHaveLength(1);
|
|
229
|
+
await harness.runtime.shutdown();
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
for (const removal of ['close', 'force-kill']) {
|
|
233
|
+
it(`reaps a replacement PTY when ${removal} wins a pending restart`, async () => {
|
|
234
|
+
const gate = { promise: Promise.resolve() };
|
|
235
|
+
const harness = createHarness({ spawnDeferred: gate });
|
|
236
|
+
try {
|
|
237
|
+
await harness.routes.post.get('/api/terminal/create')({ body: { sessionId: 'terminal', cwd: '/repo' } }, createResponse());
|
|
238
|
+
const replacement = deferred();
|
|
239
|
+
gate.promise = replacement.promise;
|
|
240
|
+
const response = createResponse();
|
|
241
|
+
const restarting = harness.routes.post.get('/api/terminal/:sessionId/restart')({ params: { sessionId: 'terminal' }, body: {} }, response);
|
|
242
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
243
|
+
const removed = createResponse();
|
|
244
|
+
if (removal === 'close') {
|
|
245
|
+
await harness.routes.delete.get('/api/terminal/:sessionId')({ params: { sessionId: 'terminal' } }, removed);
|
|
246
|
+
} else {
|
|
247
|
+
harness.routes.post.get('/api/terminal/force-kill')({ body: { sessionId: 'terminal' } }, removed);
|
|
248
|
+
}
|
|
249
|
+
replacement.resolve();
|
|
250
|
+
await restarting;
|
|
251
|
+
expect(harness.processes).toHaveLength(2);
|
|
252
|
+
expect(harness.processes.every((child) => child.killed)).toBe(true);
|
|
253
|
+
expect(response.statusCode).toBe(400);
|
|
254
|
+
} finally { await harness.runtime.shutdown(); }
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
213
258
|
it('retains completed output when the replacement command fails to start', async () => {
|
|
214
259
|
let available = true;
|
|
215
260
|
const harness = createHarness({ fs: { promises: { stat: async () => ({ isDirectory: () => available }) } } });
|
|
@@ -10,9 +10,17 @@ Pairing v2 is implemented by `packages/web/server/lib/client-auth/pairing.js`. I
|
|
|
10
10
|
## Entrypoints and structure
|
|
11
11
|
- `packages/web/server/lib/ui-auth/ui-auth.js`: UI auth controller runtime, cookie/session issuance, rate limiting, and auth route handlers.
|
|
12
12
|
- `packages/web/server/lib/ui-auth/ui-passkeys.js`: passkey store and WebAuthn registration/authentication verification helpers.
|
|
13
|
+
- `packages/web/server/lib/ui-auth/session-cookie.js`: resolves the session cookie name from a request's `Host` port; shared by session issuance and validation in `ui-auth.js` and notification/session identity extraction in `packages/web/server/lib/security/request-security.js`.
|
|
13
14
|
- `packages/web/server/lib/client-auth/remote-clients.js`: trusted-device client token storage, bearer authentication, last-used tracking, and revocation.
|
|
14
15
|
- `packages/web/server/lib/client-auth/pairing.js`: short-lived Pairing v2 sessions and one-time secret redemption into trusted-device client tokens.
|
|
15
16
|
|
|
17
|
+
## Session cookie scoping
|
|
18
|
+
Browsers key a cookie jar on the host only, never the port (RFC 6265). Two OpenChamber instances reached through the same hostname on different ports therefore shared a single `oc_ui_session` cookie. Logging into the second overwrote the first instance's session cookie (issue #2377). This affects LAN and loopback hosts alike.
|
|
19
|
+
|
|
20
|
+
`sessionCookieNameForRequest(req, base)` folds the request `Host` port into the cookie name: `oc_ui_session_<port>` when the host carries an explicit port (including a port from `x-forwarded-host`), or the bare `oc_ui_session` when it does not. `localhost:3000` and `localhost:3001` use separate names, just like two ports on one LAN address. Password and browser passkey login both call `issueSession` and receive this cookie. Session validation, clearing, and notification identity extraction use the same resolver; identity extraction does not provide a CSRF token. Bearer-token validation is unchanged.
|
|
21
|
+
|
|
22
|
+
Compatibility: upgrading renames the cookie for any explicit-port host, so already-signed-in browser sessions must log in once again. No on-disk format changes.
|
|
23
|
+
|
|
16
24
|
## Public exports (ui-auth.js)
|
|
17
25
|
- `createUiAuth({ password, cookieName, sessionTtlMs, readSettingsFromDiskMigrated })`: creates UI auth controller with methods:
|
|
18
26
|
- `enabled`
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session cookie naming that is stable per host:port.
|
|
3
|
+
*
|
|
4
|
+
* Browsers do not isolate cookies by port (RFC 6265). Instances on the same
|
|
5
|
+
* hostname overwrite one another's session cookies without distinct names.
|
|
6
|
+
* This applies to LAN addresses and same-host loopback instances alike.
|
|
7
|
+
*
|
|
8
|
+
* We fold the request port into the cookie name so each port owns its own
|
|
9
|
+
* cookie. Password/passkey session issuance and validation (`ui-auth.js`) and
|
|
10
|
+
* notification identity extraction (`request-security.js`) share this resolver.
|
|
11
|
+
* A host with no explicit port keeps the bare `oc_ui_session` name.
|
|
12
|
+
*/
|
|
13
|
+
export const SESSION_COOKIE_BASE = 'oc_ui_session';
|
|
14
|
+
|
|
15
|
+
const forwardedHost = (headers) => {
|
|
16
|
+
const forwarded = headers?.['x-forwarded-host'];
|
|
17
|
+
if (typeof forwarded === 'string' && forwarded.trim().length > 0) {
|
|
18
|
+
return forwarded.split(',')[0].trim();
|
|
19
|
+
}
|
|
20
|
+
const host = headers?.host;
|
|
21
|
+
return typeof host === 'string' ? host.trim() : '';
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Extract the trailing port from a Host authority, or null when there is none.
|
|
26
|
+
* Handles bracketed IPv6 (`[::1]:3000`, `[::1]`) and plain host names.
|
|
27
|
+
*/
|
|
28
|
+
const hostPort = (host) => {
|
|
29
|
+
if (host.startsWith('[')) {
|
|
30
|
+
const end = host.indexOf(']');
|
|
31
|
+
if (end === -1) return null;
|
|
32
|
+
const rest = host.slice(end + 1);
|
|
33
|
+
if (!rest.startsWith(':')) return null;
|
|
34
|
+
return /^\d+$/.test(rest.slice(1)) ? rest.slice(1) : null;
|
|
35
|
+
}
|
|
36
|
+
const matches = host.match(/:(\d+)$/);
|
|
37
|
+
return matches ? matches[1] : null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolve the session cookie name for a request. Returns the bare base name
|
|
42
|
+
* when the host carries no explicit port, otherwise `<base>_<port>`.
|
|
43
|
+
*/
|
|
44
|
+
export const sessionCookieNameForRequest = (req, base = SESSION_COOKIE_BASE) => {
|
|
45
|
+
const host = forwardedHost(req?.headers || {});
|
|
46
|
+
const port = host ? hostPort(host) : null;
|
|
47
|
+
if (!port) return base;
|
|
48
|
+
const portNumber = Number.parseInt(port, 10);
|
|
49
|
+
if (!Number.isFinite(portNumber) || portNumber <= 0) return base;
|
|
50
|
+
return `${base}_${port}`;
|
|
51
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
SESSION_COOKIE_BASE,
|
|
4
|
+
sessionCookieNameForRequest,
|
|
5
|
+
} from './session-cookie.js';
|
|
6
|
+
|
|
7
|
+
const req = (host, forwarded) => ({
|
|
8
|
+
headers: {
|
|
9
|
+
...(host ? { host } : {}),
|
|
10
|
+
...(forwarded ? { 'x-forwarded-host': forwarded } : {}),
|
|
11
|
+
},
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
describe('sessionCookieNameForRequest', () => {
|
|
15
|
+
test('keeps the bare base name when the host has no explicit port', () => {
|
|
16
|
+
expect(sessionCookieNameForRequest(req('192.168.0.1'))).toBe(SESSION_COOKIE_BASE);
|
|
17
|
+
expect(sessionCookieNameForRequest(req('example.com'))).toBe(SESSION_COOKIE_BASE);
|
|
18
|
+
expect(sessionCookieNameForRequest(req(''))).toBe(SESSION_COOKIE_BASE);
|
|
19
|
+
expect(sessionCookieNameForRequest(undefined)).toBe(SESSION_COOKIE_BASE);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('folds the port into the name so LAN instances on one IP are isolated', () => {
|
|
23
|
+
expect(sessionCookieNameForRequest(req('192.168.0.1:3000'))).toBe('oc_ui_session_3000');
|
|
24
|
+
expect(sessionCookieNameForRequest(req('192.168.0.1:3001'))).toBe('oc_ui_session_3001');
|
|
25
|
+
expect(sessionCookieNameForRequest(req('192.168.0.1:8080'))).toBe('oc_ui_session_8080');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('handles IPv6 authorities', () => {
|
|
29
|
+
expect(sessionCookieNameForRequest(req('[::1]:3000'))).toBe('oc_ui_session_3000');
|
|
30
|
+
expect(sessionCookieNameForRequest(req('[::1]'))).toBe(SESSION_COOKIE_BASE);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('prefers the forwarded host port over the direct host', () => {
|
|
34
|
+
expect(sessionCookieNameForRequest(req('127.0.0.1:3902', '203.0.113.9:8443')))
|
|
35
|
+
.toBe('oc_ui_session_8443');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('ignores malformed or non-numeric ports', () => {
|
|
39
|
+
expect(sessionCookieNameForRequest(req('192.168.0.1:notaport'))).toBe(SESSION_COOKIE_BASE);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('honours a custom base name', () => {
|
|
43
|
+
expect(sessionCookieNameForRequest(req('127.0.0.1:3000'), 'my_app')).toBe('my_app_3000');
|
|
44
|
+
expect(sessionCookieNameForRequest(req('127.0.0.1'), 'my_app')).toBe('my_app');
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -4,6 +4,7 @@ import fs from 'fs';
|
|
|
4
4
|
import path from 'path';
|
|
5
5
|
import os from 'os';
|
|
6
6
|
import { createUiPasskeys } from './ui-passkeys.js';
|
|
7
|
+
import { sessionCookieNameForRequest } from './session-cookie.js';
|
|
7
8
|
|
|
8
9
|
const SESSION_COOKIE_NAME = 'oc_ui_session';
|
|
9
10
|
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
|
|
@@ -291,6 +292,25 @@ const isWebSocketUpgrade = (req) => {
|
|
|
291
292
|
return String(upgradeValue || '').toLowerCase() === 'websocket';
|
|
292
293
|
};
|
|
293
294
|
|
|
295
|
+
const GUEST_URL_AUTH_SCOPE = /^guest:([a-z][a-z0-9-]*)$/;
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* A URL token scope narrows where the token is accepted. `guest:<id>` is
|
|
299
|
+
* minted for a guest iframe and only opens that guest's own package files:
|
|
300
|
+
* the iframe URL is readable by the guest's script, so the token must be
|
|
301
|
+
* worthless anywhere else.
|
|
302
|
+
* @returns {{ kind: 'guest', id: string } | null | undefined} `undefined` when the value is not a scope
|
|
303
|
+
*/
|
|
304
|
+
const parseUrlAuthScope = (value) => {
|
|
305
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
306
|
+
if (raw === undefined || raw === null || raw === '') return null;
|
|
307
|
+
if (typeof raw !== 'string') return undefined;
|
|
308
|
+
const match = raw.trim().match(GUEST_URL_AUTH_SCOPE);
|
|
309
|
+
return match ? { kind: 'guest', id: match[1] } : undefined;
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
const isGuestScopedPath = (pathname, guestId) => pathname.startsWith(`/api/guests/${guestId}/`);
|
|
313
|
+
|
|
294
314
|
const isUrlAuthReadableHttpPath = (pathname) => {
|
|
295
315
|
return pathname === '/api/event'
|
|
296
316
|
|| pathname === '/api/global/event'
|
|
@@ -301,7 +321,9 @@ const isUrlAuthReadableHttpPath = (pathname) => {
|
|
|
301
321
|
|| pathname === '/api/fs/serve'
|
|
302
322
|
|| pathname.startsWith('/api/fs/serve/')
|
|
303
323
|
|| pathname.startsWith('/api/preview/proxy/')
|
|
304
|
-
|| /^\/api\/projects\/[^/]+\/icon$/.test(pathname)
|
|
324
|
+
|| /^\/api\/projects\/[^/]+\/icon$/.test(pathname)
|
|
325
|
+
|| pathname === '/api/guests'
|
|
326
|
+
|| /^\/api\/guests\/[a-z][a-z0-9-]*\//.test(pathname);
|
|
305
327
|
};
|
|
306
328
|
|
|
307
329
|
const isUrlAuthWebSocketPath = (pathname) => {
|
|
@@ -314,9 +336,12 @@ const isUrlAuthWebSocketPath = (pathname) => {
|
|
|
314
336
|
|| pathname.startsWith('/api/preview/proxy/');
|
|
315
337
|
};
|
|
316
338
|
|
|
317
|
-
const canUseUrlAuthTokenForRequest = (req) => {
|
|
339
|
+
const canUseUrlAuthTokenForRequest = (req, scope = null) => {
|
|
318
340
|
const method = typeof req?.method === 'string' ? req.method.toUpperCase() : 'GET';
|
|
319
341
|
const pathname = getRequestPathname(req);
|
|
342
|
+
if (scope?.kind === 'guest') {
|
|
343
|
+
return !isWebSocketUpgrade(req) && method === 'GET' && isGuestScopedPath(pathname, scope.id);
|
|
344
|
+
}
|
|
320
345
|
if (isWebSocketUpgrade(req)) {
|
|
321
346
|
return isUrlAuthWebSocketPath(pathname);
|
|
322
347
|
}
|
|
@@ -425,16 +450,15 @@ export const createUiAuth = ({
|
|
|
425
450
|
}
|
|
426
451
|
};
|
|
427
452
|
|
|
428
|
-
const issueUrlAuthTokenForSession = (sessionToken) => {
|
|
453
|
+
const issueUrlAuthTokenForSession = (sessionToken, scope = null) => {
|
|
429
454
|
sweepUrlAuthTokens();
|
|
430
455
|
const token = `${URL_AUTH_TOKEN_PREFIX}${crypto.randomBytes(24).toString('base64url')}`;
|
|
431
456
|
const expiresAt = Date.now() + URL_AUTH_TOKEN_TTL_MS;
|
|
432
|
-
urlAuthTokens.set(token, { sessionToken, expiresAt });
|
|
457
|
+
urlAuthTokens.set(token, { sessionToken, expiresAt, scope });
|
|
433
458
|
return { token, expiresAt };
|
|
434
459
|
};
|
|
435
460
|
|
|
436
461
|
const authenticateUrlAuthToken = (req) => {
|
|
437
|
-
if (!canUseUrlAuthTokenForRequest(req)) return null;
|
|
438
462
|
const token = getUrlAuthTokenFromRequest(req);
|
|
439
463
|
if (!token || !token.startsWith(URL_AUTH_TOKEN_PREFIX)) return null;
|
|
440
464
|
const entry = urlAuthTokens.get(token);
|
|
@@ -442,9 +466,13 @@ export const createUiAuth = ({
|
|
|
442
466
|
urlAuthTokens.delete(token);
|
|
443
467
|
return null;
|
|
444
468
|
}
|
|
469
|
+
if (!canUseUrlAuthTokenForRequest(req, entry.scope)) return null;
|
|
445
470
|
return { ok: true, sessionToken: entry.sessionToken || 'url:authenticated' };
|
|
446
471
|
};
|
|
447
472
|
|
|
473
|
+
/** Scope requested on `POST /auth/url-token`: `?scope=guest:<id>` or `{ scope }` in the body. */
|
|
474
|
+
const readRequestedUrlAuthScope = (req) => parseUrlAuthScope(req?.body?.scope ?? req?.query?.scope);
|
|
475
|
+
|
|
448
476
|
const authenticateClientRequest = async (req, { allowUrlToken = true } = {}) => {
|
|
449
477
|
if (allowUrlToken) {
|
|
450
478
|
const urlAuth = authenticateUrlAuthToken(req);
|
|
@@ -489,7 +517,7 @@ export const createUiAuth = ({
|
|
|
489
517
|
const secure = isSecureRequest(req);
|
|
490
518
|
const maxAgeSeconds = Math.floor(ttlMs / 1000);
|
|
491
519
|
const header = buildCookie({
|
|
492
|
-
name: cookieName,
|
|
520
|
+
name: sessionCookieNameForRequest(req, cookieName),
|
|
493
521
|
value: encodeURIComponent(token),
|
|
494
522
|
maxAge: maxAgeSeconds,
|
|
495
523
|
secure,
|
|
@@ -499,8 +527,9 @@ export const createUiAuth = ({
|
|
|
499
527
|
|
|
500
528
|
const ensureSessionToken = async (req, res) => {
|
|
501
529
|
const cookies = parseCookies(req.headers.cookie);
|
|
502
|
-
|
|
503
|
-
|
|
530
|
+
const name = sessionCookieNameForRequest(req, cookieName);
|
|
531
|
+
if (cookies[name]) {
|
|
532
|
+
return cookies[name];
|
|
504
533
|
}
|
|
505
534
|
const token = crypto.randomBytes(32).toString('base64url');
|
|
506
535
|
setSessionCookie(req, res, token, sessionTtlMs);
|
|
@@ -533,8 +562,9 @@ export const createUiAuth = ({
|
|
|
533
562
|
|
|
534
563
|
const resolveAuthContext = async (req, res, { allowClientAuth = true, allowUrlToken = true } = {}) => {
|
|
535
564
|
const cookies = parseCookies(req.headers.cookie);
|
|
536
|
-
|
|
537
|
-
|
|
565
|
+
const name = sessionCookieNameForRequest(req, cookieName);
|
|
566
|
+
if (cookies[name]) {
|
|
567
|
+
return { type: 'session', token: cookies[name] };
|
|
538
568
|
}
|
|
539
569
|
if (allowClientAuth) {
|
|
540
570
|
const clientAuth = await authenticateClientRequest(req, { allowUrlToken });
|
|
@@ -566,17 +596,21 @@ export const createUiAuth = ({
|
|
|
566
596
|
res.status(400).json({ error: 'UI password not configured' });
|
|
567
597
|
},
|
|
568
598
|
handleUrlAuthToken: async (req, res) => {
|
|
599
|
+
const scope = readRequestedUrlAuthScope(req);
|
|
600
|
+
if (scope === undefined) {
|
|
601
|
+
return res.status(400).json({ error: 'Unknown URL token scope' });
|
|
602
|
+
}
|
|
569
603
|
const clientAuth = await authenticateClientRequest(req, { allowUrlToken: false });
|
|
570
604
|
if (clientAuth) {
|
|
571
605
|
res.setHeader('Cache-Control', 'no-store');
|
|
572
|
-
return res.json(issueUrlAuthTokenForSession(clientSessionToken(clientAuth)));
|
|
606
|
+
return res.json(issueUrlAuthTokenForSession(clientSessionToken(clientAuth), scope));
|
|
573
607
|
}
|
|
574
608
|
if (requireClientAuth) {
|
|
575
609
|
return res.status(401).json({ error: 'Client authentication required', locked: true, clientAuthRequired: true });
|
|
576
610
|
}
|
|
577
611
|
const sessionToken = await ensureSessionToken(req, res);
|
|
578
612
|
res.setHeader('Cache-Control', 'no-store');
|
|
579
|
-
return res.json(issueUrlAuthTokenForSession(sessionToken));
|
|
613
|
+
return res.json(issueUrlAuthTokenForSession(sessionToken, scope));
|
|
580
614
|
},
|
|
581
615
|
handlePasskeyStatus: (_req, res) => {
|
|
582
616
|
res.json({ enabled: false, hasPasskeys: false, passkeyCount: 0, rpID: null });
|
|
@@ -641,8 +675,9 @@ export const createUiAuth = ({
|
|
|
641
675
|
|
|
642
676
|
const getTokenFromRequest = (req) => {
|
|
643
677
|
const cookies = parseCookies(req.headers.cookie);
|
|
644
|
-
|
|
645
|
-
|
|
678
|
+
const name = sessionCookieNameForRequest(req, cookieName);
|
|
679
|
+
if (cookies[name]) {
|
|
680
|
+
return cookies[name];
|
|
646
681
|
}
|
|
647
682
|
return null;
|
|
648
683
|
};
|
|
@@ -651,7 +686,7 @@ export const createUiAuth = ({
|
|
|
651
686
|
const secure = isSecureRequest(req);
|
|
652
687
|
const maxAgeSeconds = Math.floor(ttlMs / 1000);
|
|
653
688
|
const header = buildCookie({
|
|
654
|
-
name: cookieName,
|
|
689
|
+
name: sessionCookieNameForRequest(req, cookieName),
|
|
655
690
|
value: encodeURIComponent(token),
|
|
656
691
|
maxAge: maxAgeSeconds,
|
|
657
692
|
secure,
|
|
@@ -662,7 +697,7 @@ export const createUiAuth = ({
|
|
|
662
697
|
const clearSessionCookie = (req, res) => {
|
|
663
698
|
const secure = isSecureRequest(req);
|
|
664
699
|
const header = buildCookie({
|
|
665
|
-
name: cookieName,
|
|
700
|
+
name: sessionCookieNameForRequest(req, cookieName),
|
|
666
701
|
value: '',
|
|
667
702
|
maxAge: 0,
|
|
668
703
|
secure,
|
|
@@ -799,13 +834,17 @@ export const createUiAuth = ({
|
|
|
799
834
|
};
|
|
800
835
|
|
|
801
836
|
const handleUrlAuthToken = async (req, res) => {
|
|
837
|
+
const scope = readRequestedUrlAuthScope(req);
|
|
838
|
+
if (scope === undefined) {
|
|
839
|
+
return res.status(400).json({ error: 'Unknown URL token scope' });
|
|
840
|
+
}
|
|
802
841
|
const sessionToken = await resolveAuthenticatedSessionToken(req, { allowUrlToken: false });
|
|
803
842
|
if (!sessionToken) {
|
|
804
843
|
clearSessionCookie(req, res);
|
|
805
844
|
return respondUnauthorized(req, res);
|
|
806
845
|
}
|
|
807
846
|
res.setHeader('Cache-Control', 'no-store');
|
|
808
|
-
return res.json(issueUrlAuthTokenForSession(sessionToken));
|
|
847
|
+
return res.json(issueUrlAuthTokenForSession(sessionToken, scope));
|
|
809
848
|
};
|
|
810
849
|
|
|
811
850
|
const handleSessionCreate = async (req, res) => {
|