@openchamber/web 1.24.0 → 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-C9kV-n7r.js → CodeMirrorCommentWidgets-DvUH815P.js} +1 -1
- package/dist/assets/DiffView-DkC3xlRJ.js +4 -0
- package/dist/assets/{FilesView-vjJx7VaM.js → FilesView-D0bM9FVB.js} +6 -6
- package/dist/assets/GitView-Bxuv3dfP.js +6 -0
- package/dist/assets/GuestAttachDialog-B0u3Q5uO.js +1 -0
- package/dist/assets/{JsonTreeView-D_4G5X6-.js → JsonTreeView-BBVPFM5K.js} +1 -1
- package/dist/assets/{LinearIssuesView-1uKhePfH.js → LinearIssuesView-UI1FcSC8.js} +1 -1
- package/dist/assets/{MarkdownImageGallery-Ix7N_2wp.js → MarkdownImageGallery-CUJxH8Le.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Deel_y5S.js → MarkdownRendererImpl-D5BZOg8X.js} +1 -1
- package/dist/assets/{OnboardingScreen-ToIakxb_.js → OnboardingScreen-5Gou9cGD.js} +1 -1
- package/dist/assets/{PatchDiff-BjMgezr1.js → PatchDiff-C4rE5k6z.js} +1 -1
- package/dist/assets/{PierreDiffViewer-53Ghfnlr.js → PierreDiffViewer-ByRVu6ss.js} +1 -1
- package/dist/assets/{PlanView-BGAzxDwD.js → PlanView-u2yi5XGJ.js} +4 -4
- package/dist/assets/PluginPane-QxjsKYeO.js +3 -0
- package/dist/assets/SettingsView-Fo5ZqMaT.js +29 -0
- package/dist/assets/SettingsWindow-HVDVANjJ.js +1 -0
- package/dist/assets/{SubmoduleDiffSummary--YFqK6Ih.js → SubmoduleDiffSummary-D3hzkybB.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DRWBvdaJ.js → ToolOutputDialog-3J6IRayW.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-BxZJCU28.js → ToolPartDiffPreview-DarxPjSd.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DCXjBGRf.js → VirtualizedFileDiff-CZgXWHjU.js} +4 -4
- package/dist/assets/{WalkthroughView-CfIPvWWa.js → WalkthroughView-wSpED5L4.js} +2 -2
- package/dist/assets/{appThemeRegistry-DDROzcUO.js → appThemeRegistry-Cf8KitzT.js} +1 -1
- package/dist/assets/commitAndPush-DZnzlhvc.js +1 -0
- package/dist/assets/{computeVirtualFileMetrics-DHgQIkUq.js → computeVirtualFileMetrics-VYnT_A2h.js} +1 -1
- package/dist/assets/{de-CX_f-T5U.js → de-BM_8EDD3.js} +4 -4
- package/dist/assets/{es-BERmWNn_.js → es-CxZjlqpo.js} +3 -3
- package/dist/assets/{fr-BjYYE_-z.js → fr-VCixCnMW.js} +4 -4
- package/dist/assets/{index-WjufPkIV.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-D9faP70y.js → isDiffPlainText-ImDG3Uhg.js} +1 -1
- package/dist/assets/{isFilePlainText-6qOcz5Ky.js → isFilePlainText-D_YDVYDb.js} +1 -1
- package/dist/assets/{ja-DxqeAk9N.js → ja-CZ5k_GyD.js} +4 -4
- package/dist/assets/{ko-Dty1aUod.js → ko-7YM3A1Xh.js} +4 -4
- package/dist/assets/{main-Bjcre_GE.js → main-CycplCph.js} +2 -2
- package/dist/assets/main-DFYTCx5o.js +896 -0
- package/dist/assets/markdownCore-DHvqMxPn.js +5 -0
- package/dist/assets/{miniChat-Dz_bPgMc.js → miniChat-DIQKfY2V.js} +2 -2
- package/dist/assets/{mobile-BbZPBJrK.js → mobile-BMwz5q-m.js} +2 -2
- package/dist/assets/{patchFileDiff-BvU6KOQC.js → patchFileDiff-DDQ6Rq5e.js} +3 -3
- package/dist/assets/{pl-CX-_ROkr.js → pl-BcgDO_w5.js} +4 -4
- package/dist/assets/{pt-BR-DhRR1arx.js → pt-BR-CU2u_1q5.js} +3 -3
- 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-DW3xqMQ8.js → scheduledTasksApi-D8pq6gQz.js} +1 -1
- package/dist/assets/{shikiHighlight-DsxD9QEa.js → shikiHighlight-1imXsir9.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-Da7ed8qM.js → textMateThemeFromAppTheme-Dgqc63LZ.js} +1 -1
- package/dist/assets/tr-DuYhOzNe.js +7 -0
- package/dist/assets/{uk-CD21CXFV.js → uk-Cuk7-uvq.js} +3 -3
- package/dist/assets/{useAppFontEffects-hfv2s6mZ.js → useAppFontEffects-BItUWdo4.js} +147 -147
- package/dist/assets/{useInlineCommentController-BmtfVbo8.js → useInlineCommentController-CkbKsm7m.js} +2 -2
- package/dist/assets/useRootScrollLock-vmzxZjWA.js +2 -0
- package/dist/assets/{vendor-codemirror-language-data-BPMJpOpT.js → vendor-codemirror-language-data-BDyxuqK4.js} +2 -2
- 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/{web-components-U-hWbgJo.js → web-components-D7FinaeH.js} +1 -1
- package/dist/assets/{zh-CN-BWvlPHY-.js → zh-CN-CUWoiRHd.js} +3 -3
- package/dist/assets/{zh-TW-CRp5dJU2.js → zh-TW-CQ8EBSBN.js} +3 -3
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +4 -3
- package/server/index.js +26 -7
- 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/git/DOCUMENTATION.md +17 -4
- package/server/lib/git/routes.js +1 -1
- 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 +232 -62
- package/server/lib/git/service.test.js +273 -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 +5 -3
- package/server/lib/guests/background.test.js +83 -0
- package/server/lib/guests/catalog.js +20 -9
- package/server/lib/guests/catalog.test.js +5 -5
- package/server/lib/guests/routes.js +2 -2
- 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/opencode/feature-routes-runtime.js +5 -0
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-registry.json +8 -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/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/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 +13 -9
- package/server/lib/ui-auth/ui-auth.test.js +56 -0
- package/dist/assets/DiffView-B7YkbY-u.js +0 -4
- package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +0 -1
- package/dist/assets/GitView-BLhlMYEY.js +0 -6
- package/dist/assets/GuestAttachDialog-B-fwE8r3.js +0 -3
- package/dist/assets/SettingsView-n2X-jfBB.js +0 -29
- package/dist/assets/SettingsWindow-Bi8LE9XI.js +0 -1
- package/dist/assets/index-DpzTz2UH.css +0 -1
- package/dist/assets/index-Dy8xgawx.js +0 -40
- package/dist/assets/main-BOYSXfYn.js +0 -896
- package/dist/assets/markdownCore-DPrwM1rU.js +0 -5
- package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +0 -2
- package/dist/assets/renderMobileApp-BK1kFlcJ.js +0 -25
- package/dist/assets/runtimeEndpointReset-BULHvOwb.js +0 -25
- package/dist/assets/tr-cIQtYBpg.js +0 -7
- package/dist/assets/useRootScrollLock-Cwc4kSl2.js +0 -1
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Routing configuration on disk.
|
|
3
|
+
*
|
|
4
|
+
* `routing.json` holds only deviations from the built-in defaults: a patched or
|
|
5
|
+
* disabled built-in category, a user category, the fallback model, thresholds.
|
|
6
|
+
* `routing-auth.json` holds the Jev API key alone, mode 0600, so the config
|
|
7
|
+
* file can be read, shown and exported without carrying a secret.
|
|
8
|
+
*
|
|
9
|
+
* Reads never throw on a missing file (a fresh install is the defaults); a
|
|
10
|
+
* malformed file is an error, not an empty config, so a bad write cannot
|
|
11
|
+
* silently reset the user's categories.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs/promises';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { z } from 'zod';
|
|
16
|
+
import {
|
|
17
|
+
BUILTIN_CATEGORIES,
|
|
18
|
+
DEFAULT_MIN_CONFIDENCE,
|
|
19
|
+
DEFAULT_SAFETY_THRESHOLD,
|
|
20
|
+
THINKING_LEVELS,
|
|
21
|
+
isAutoModel,
|
|
22
|
+
} from './defaults.js';
|
|
23
|
+
|
|
24
|
+
const FILE_VERSION = 1;
|
|
25
|
+
const CATEGORY_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
26
|
+
|
|
27
|
+
// The Auto sentinel is what routing resolves *from*; as a fallback or category
|
|
28
|
+
// model it would send itself to OpenCode.
|
|
29
|
+
const modelSchema = z.object({
|
|
30
|
+
providerID: z.string().trim().min(1).max(200),
|
|
31
|
+
modelID: z.string().trim().min(1).max(200),
|
|
32
|
+
}).strict().refine((model) => !isAutoModel(model), { message: 'The Auto model cannot be a routing target' });
|
|
33
|
+
|
|
34
|
+
const variantSchema = z.string().trim().min(1).max(80).nullable();
|
|
35
|
+
const agentSchema = z.string().trim().min(1).max(80).nullable();
|
|
36
|
+
|
|
37
|
+
/** A built-in category on disk carries only what the user changed. */
|
|
38
|
+
const builtinOverrideSchema = z.object({
|
|
39
|
+
builtin: z.literal(true),
|
|
40
|
+
disabled: z.boolean().optional(),
|
|
41
|
+
deleted: z.boolean().optional(),
|
|
42
|
+
name: z.string().trim().min(1).max(60).optional(),
|
|
43
|
+
description: z.string().trim().min(1).max(2000).optional(),
|
|
44
|
+
model: modelSchema.nullable().optional(),
|
|
45
|
+
variant: variantSchema.optional(),
|
|
46
|
+
agent: agentSchema.optional(),
|
|
47
|
+
}).strict();
|
|
48
|
+
|
|
49
|
+
const userCategorySchema = z.object({
|
|
50
|
+
builtin: z.literal(false),
|
|
51
|
+
disabled: z.boolean().optional(),
|
|
52
|
+
name: z.string().trim().min(1).max(60),
|
|
53
|
+
description: z.string().trim().min(1).max(2000),
|
|
54
|
+
model: modelSchema.nullable().optional(),
|
|
55
|
+
variant: variantSchema.optional(),
|
|
56
|
+
agent: agentSchema.optional(),
|
|
57
|
+
}).strict();
|
|
58
|
+
|
|
59
|
+
const fileSchema = z.object({
|
|
60
|
+
version: z.literal(FILE_VERSION),
|
|
61
|
+
enabled: z.boolean().optional(),
|
|
62
|
+
fallback: z.object({ model: modelSchema, variant: variantSchema.optional() }).strict().nullable().optional(),
|
|
63
|
+
minConfidence: z.number().min(0).max(1).optional(),
|
|
64
|
+
safetyNet: z.object({ enabled: z.boolean(), threshold: z.number().min(0).max(1) }).strict().optional(),
|
|
65
|
+
categories: z.record(z.string().regex(CATEGORY_ID), z.discriminatedUnion('builtin', [builtinOverrideSchema, userCategorySchema])).optional(),
|
|
66
|
+
}).strict();
|
|
67
|
+
|
|
68
|
+
/** The effective category the runtime and the UI work with. */
|
|
69
|
+
const effectiveCategorySchema = z.object({
|
|
70
|
+
id: z.string().regex(CATEGORY_ID),
|
|
71
|
+
builtin: z.boolean(),
|
|
72
|
+
enabled: z.boolean(),
|
|
73
|
+
name: z.string().trim().min(1).max(60),
|
|
74
|
+
description: z.string().trim().min(1).max(2000),
|
|
75
|
+
model: modelSchema.nullable(),
|
|
76
|
+
variant: variantSchema,
|
|
77
|
+
agent: agentSchema,
|
|
78
|
+
}).strict();
|
|
79
|
+
|
|
80
|
+
const effectiveConfigSchema = z.object({
|
|
81
|
+
enabled: z.boolean(),
|
|
82
|
+
fallback: z.object({ model: modelSchema, variant: variantSchema }).strict().nullable(),
|
|
83
|
+
minConfidence: z.number().min(0).max(1),
|
|
84
|
+
safetyNet: z.object({ enabled: z.boolean(), threshold: z.number().min(0).max(1) }).strict(),
|
|
85
|
+
categories: z.array(effectiveCategorySchema).max(32),
|
|
86
|
+
}).strict();
|
|
87
|
+
|
|
88
|
+
const authSchema = z.object({ token: z.string().min(1).max(4000) }).strict();
|
|
89
|
+
|
|
90
|
+
const routingConfigPath = (dataDir) => path.join(dataDir, 'routing.json');
|
|
91
|
+
const routingAuthPath = (dataDir) => path.join(dataDir, 'routing-auth.json');
|
|
92
|
+
|
|
93
|
+
const readJsonFile = async (file, schema) => {
|
|
94
|
+
let raw;
|
|
95
|
+
try {
|
|
96
|
+
raw = await fs.readFile(file, 'utf8');
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error?.code === 'ENOENT') return null;
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
const text = raw.replace(/^/, '').trim();
|
|
102
|
+
if (text === '') return null;
|
|
103
|
+
const parsed = schema.safeParse(JSON.parse(text));
|
|
104
|
+
if (!parsed.success) throw new Error(`Invalid ${path.basename(file)}: ${parsed.error.issues[0]?.message ?? 'schema mismatch'}`);
|
|
105
|
+
return parsed.data;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const writeJsonFile = async (file, value, mode) => {
|
|
109
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
110
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
111
|
+
await fs.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode });
|
|
112
|
+
await fs.rename(tmp, file);
|
|
113
|
+
if (mode) await fs.chmod(file, mode);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const emptyFile = () => ({ version: FILE_VERSION });
|
|
117
|
+
|
|
118
|
+
/** Built-ins plus the stored deviations, in built-in order followed by user categories. */
|
|
119
|
+
export const resolveEffectiveConfig = (stored) => {
|
|
120
|
+
const file = stored ?? emptyFile();
|
|
121
|
+
const overrides = file.categories ?? {};
|
|
122
|
+
const categories = [];
|
|
123
|
+
for (const builtin of BUILTIN_CATEGORIES) {
|
|
124
|
+
const override = overrides[builtin.id];
|
|
125
|
+
if (override && override.builtin !== true) continue; // a user id colliding with a built-in is ignored
|
|
126
|
+
if (override?.deleted) continue;
|
|
127
|
+
categories.push({
|
|
128
|
+
id: builtin.id,
|
|
129
|
+
builtin: true,
|
|
130
|
+
enabled: !(override?.disabled === true),
|
|
131
|
+
name: override?.name ?? builtin.name,
|
|
132
|
+
description: override?.description ?? builtin.description,
|
|
133
|
+
model: override?.model ?? null,
|
|
134
|
+
variant: override?.variant ?? null,
|
|
135
|
+
agent: override?.agent ?? null,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
for (const [id, entry] of Object.entries(overrides)) {
|
|
139
|
+
if (entry.builtin !== false) continue;
|
|
140
|
+
categories.push({
|
|
141
|
+
id,
|
|
142
|
+
builtin: false,
|
|
143
|
+
enabled: !(entry.disabled === true),
|
|
144
|
+
name: entry.name,
|
|
145
|
+
description: entry.description,
|
|
146
|
+
model: entry.model ?? null,
|
|
147
|
+
variant: entry.variant ?? null,
|
|
148
|
+
agent: entry.agent ?? null,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
enabled: file.enabled ?? false,
|
|
153
|
+
fallback: file.fallback ? { model: file.fallback.model, variant: file.fallback.variant ?? null } : null,
|
|
154
|
+
minConfidence: file.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
|
|
155
|
+
safetyNet: file.safetyNet ?? { enabled: false, threshold: DEFAULT_SAFETY_THRESHOLD },
|
|
156
|
+
categories,
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/** The stored shape for an effective config: built-ins keep only their deviations. */
|
|
161
|
+
export const toStoredConfig = (config) => {
|
|
162
|
+
const categories = {};
|
|
163
|
+
const builtinIds = new Set(BUILTIN_CATEGORIES.map((c) => c.id));
|
|
164
|
+
const present = new Set();
|
|
165
|
+
for (const category of config.categories) {
|
|
166
|
+
present.add(category.id);
|
|
167
|
+
if (category.builtin) {
|
|
168
|
+
const builtin = BUILTIN_CATEGORIES.find((c) => c.id === category.id);
|
|
169
|
+
if (!builtin) continue;
|
|
170
|
+
const override = { builtin: true };
|
|
171
|
+
if (!category.enabled) override.disabled = true;
|
|
172
|
+
if (category.name !== builtin.name) override.name = category.name;
|
|
173
|
+
if (category.description !== builtin.description) override.description = category.description;
|
|
174
|
+
if (category.model) override.model = category.model;
|
|
175
|
+
if (category.variant) override.variant = category.variant;
|
|
176
|
+
if (category.agent) override.agent = category.agent;
|
|
177
|
+
if (Object.keys(override).length > 1) categories[category.id] = override;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (builtinIds.has(category.id)) continue;
|
|
181
|
+
const entry = { builtin: false, name: category.name, description: category.description };
|
|
182
|
+
if (!category.enabled) entry.disabled = true;
|
|
183
|
+
if (category.model) entry.model = category.model;
|
|
184
|
+
if (category.variant) entry.variant = category.variant;
|
|
185
|
+
if (category.agent) entry.agent = category.agent;
|
|
186
|
+
categories[category.id] = entry;
|
|
187
|
+
}
|
|
188
|
+
for (const builtin of BUILTIN_CATEGORIES) {
|
|
189
|
+
if (!present.has(builtin.id)) categories[builtin.id] = { builtin: true, deleted: true };
|
|
190
|
+
}
|
|
191
|
+
const stored = { version: FILE_VERSION, enabled: config.enabled, minConfidence: config.minConfidence, safetyNet: config.safetyNet };
|
|
192
|
+
if (config.fallback) {
|
|
193
|
+
stored.fallback = { model: config.fallback.model };
|
|
194
|
+
if (config.fallback.variant) stored.fallback.variant = config.fallback.variant;
|
|
195
|
+
}
|
|
196
|
+
if (Object.keys(categories).length > 0) stored.categories = categories;
|
|
197
|
+
return stored;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** Parses an untrusted effective config (a PUT body) into the trusted shape, or throws. */
|
|
201
|
+
export const parseEffectiveConfig = (input) => {
|
|
202
|
+
const parsed = effectiveConfigSchema.safeParse(input);
|
|
203
|
+
if (!parsed.success) {
|
|
204
|
+
const issue = parsed.error.issues[0];
|
|
205
|
+
throw Object.assign(new Error(`Invalid routing config at ${issue?.path.join('.') || 'root'}: ${issue?.message ?? 'schema mismatch'}`), { status: 400 });
|
|
206
|
+
}
|
|
207
|
+
const config = parsed.data;
|
|
208
|
+
const ids = new Set();
|
|
209
|
+
for (const category of config.categories) {
|
|
210
|
+
if (ids.has(category.id)) throw Object.assign(new Error(`Duplicate category id ${category.id}`), { status: 400 });
|
|
211
|
+
ids.add(category.id);
|
|
212
|
+
if (category.variant && !THINKING_LEVELS.includes(category.variant) && !/^[\w.-]+$/.test(category.variant)) {
|
|
213
|
+
throw Object.assign(new Error(`Invalid variant for ${category.id}`), { status: 400 });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return config;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
export const createRoutingStore = ({ dataDir }) => {
|
|
220
|
+
const configFile = routingConfigPath(dataDir);
|
|
221
|
+
const authFile = routingAuthPath(dataDir);
|
|
222
|
+
let writeChain = Promise.resolve();
|
|
223
|
+
const serialize = (run) => {
|
|
224
|
+
const next = writeChain.catch(() => undefined).then(run);
|
|
225
|
+
writeChain = next;
|
|
226
|
+
return next;
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
return {
|
|
230
|
+
/** Effective config; a missing file is the defaults, a broken file throws. */
|
|
231
|
+
readConfig: async () => resolveEffectiveConfig(await readJsonFile(configFile, fileSchema)),
|
|
232
|
+
writeConfig: (config) => serialize(async () => {
|
|
233
|
+
await writeJsonFile(configFile, toStoredConfig(config));
|
|
234
|
+
return config;
|
|
235
|
+
}),
|
|
236
|
+
readToken: async () => {
|
|
237
|
+
try {
|
|
238
|
+
return (await readJsonFile(authFile, authSchema))?.token ?? null;
|
|
239
|
+
} catch (error) {
|
|
240
|
+
console.warn('[routing] routing-auth.json is unreadable:', error?.message ?? error);
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
writeToken: (token) => serialize(() => writeJsonFile(authFile, { token }, 0o600)),
|
|
245
|
+
clearToken: () => serialize(async () => {
|
|
246
|
+
await fs.rm(authFile, { force: true });
|
|
247
|
+
}),
|
|
248
|
+
};
|
|
249
|
+
};
|
|
@@ -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
|
});
|
|
@@ -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;
|
|
@@ -516,7 +517,7 @@ export const createUiAuth = ({
|
|
|
516
517
|
const secure = isSecureRequest(req);
|
|
517
518
|
const maxAgeSeconds = Math.floor(ttlMs / 1000);
|
|
518
519
|
const header = buildCookie({
|
|
519
|
-
name: cookieName,
|
|
520
|
+
name: sessionCookieNameForRequest(req, cookieName),
|
|
520
521
|
value: encodeURIComponent(token),
|
|
521
522
|
maxAge: maxAgeSeconds,
|
|
522
523
|
secure,
|
|
@@ -526,8 +527,9 @@ export const createUiAuth = ({
|
|
|
526
527
|
|
|
527
528
|
const ensureSessionToken = async (req, res) => {
|
|
528
529
|
const cookies = parseCookies(req.headers.cookie);
|
|
529
|
-
|
|
530
|
-
|
|
530
|
+
const name = sessionCookieNameForRequest(req, cookieName);
|
|
531
|
+
if (cookies[name]) {
|
|
532
|
+
return cookies[name];
|
|
531
533
|
}
|
|
532
534
|
const token = crypto.randomBytes(32).toString('base64url');
|
|
533
535
|
setSessionCookie(req, res, token, sessionTtlMs);
|
|
@@ -560,8 +562,9 @@ export const createUiAuth = ({
|
|
|
560
562
|
|
|
561
563
|
const resolveAuthContext = async (req, res, { allowClientAuth = true, allowUrlToken = true } = {}) => {
|
|
562
564
|
const cookies = parseCookies(req.headers.cookie);
|
|
563
|
-
|
|
564
|
-
|
|
565
|
+
const name = sessionCookieNameForRequest(req, cookieName);
|
|
566
|
+
if (cookies[name]) {
|
|
567
|
+
return { type: 'session', token: cookies[name] };
|
|
565
568
|
}
|
|
566
569
|
if (allowClientAuth) {
|
|
567
570
|
const clientAuth = await authenticateClientRequest(req, { allowUrlToken });
|
|
@@ -672,8 +675,9 @@ export const createUiAuth = ({
|
|
|
672
675
|
|
|
673
676
|
const getTokenFromRequest = (req) => {
|
|
674
677
|
const cookies = parseCookies(req.headers.cookie);
|
|
675
|
-
|
|
676
|
-
|
|
678
|
+
const name = sessionCookieNameForRequest(req, cookieName);
|
|
679
|
+
if (cookies[name]) {
|
|
680
|
+
return cookies[name];
|
|
677
681
|
}
|
|
678
682
|
return null;
|
|
679
683
|
};
|
|
@@ -682,7 +686,7 @@ export const createUiAuth = ({
|
|
|
682
686
|
const secure = isSecureRequest(req);
|
|
683
687
|
const maxAgeSeconds = Math.floor(ttlMs / 1000);
|
|
684
688
|
const header = buildCookie({
|
|
685
|
-
name: cookieName,
|
|
689
|
+
name: sessionCookieNameForRequest(req, cookieName),
|
|
686
690
|
value: encodeURIComponent(token),
|
|
687
691
|
maxAge: maxAgeSeconds,
|
|
688
692
|
secure,
|
|
@@ -693,7 +697,7 @@ export const createUiAuth = ({
|
|
|
693
697
|
const clearSessionCookie = (req, res) => {
|
|
694
698
|
const secure = isSecureRequest(req);
|
|
695
699
|
const header = buildCookie({
|
|
696
|
-
name: cookieName,
|
|
700
|
+
name: sessionCookieNameForRequest(req, cookieName),
|
|
697
701
|
value: '',
|
|
698
702
|
maxAge: 0,
|
|
699
703
|
secure,
|
|
@@ -357,3 +357,59 @@ describe('ui auth client credential seam', () => {
|
|
|
357
357
|
expect(expiresAt).toBeLessThanOrEqual(Date.now() + 124_000);
|
|
358
358
|
});
|
|
359
359
|
});
|
|
360
|
+
|
|
361
|
+
// issue #2377: browsers key cookie jars on host only, so two instances on one
|
|
362
|
+
// LAN IP (different ports) collided on `oc_ui_session`. Cookies are now scoped
|
|
363
|
+
// by the request port so each instance owns its own slot.
|
|
364
|
+
describe('ui auth port-scoped session cookies (issue #2377)', () => {
|
|
365
|
+
const loginHost = async (auth, host) => {
|
|
366
|
+
const req = { method: 'POST', headers: { host }, body: { password: 'secret' } };
|
|
367
|
+
const res = createResponse();
|
|
368
|
+
await auth.handleSessionCreate(req, res);
|
|
369
|
+
return String(res.getHeader('set-cookie') || '').split(';', 1)[0];
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
it('names the issued cookie with the request port', async () => {
|
|
373
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
374
|
+
const auth = createUiAuth({ password: 'secret' });
|
|
375
|
+
|
|
376
|
+
const issued = await loginHost(auth, '192.168.0.1:3000');
|
|
377
|
+
expect(issued).toMatch(/^oc_ui_session_3000=/);
|
|
378
|
+
expect(issued.length).toBeGreaterThan('oc_ui_session_3000='.length);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
it('keeps the bare cookie name when the host has no explicit port', async () => {
|
|
382
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
383
|
+
const auth = createUiAuth({ password: 'secret' });
|
|
384
|
+
|
|
385
|
+
expect(await loginHost(auth, '192.168.0.1')).toMatch(/^oc_ui_session=/);
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
it('reads the slot for the request port and ignores another port cookie', async () => {
|
|
389
|
+
const createUiAuth = await loadCreateUiAuth();
|
|
390
|
+
const auth = createUiAuth({ password: 'secret' });
|
|
391
|
+
|
|
392
|
+
// Valid token issued against :3000.
|
|
393
|
+
const portCookie = await loginHost(auth, '192.168.0.1:3000');
|
|
394
|
+
const validToken = portCookie.slice('oc_ui_session_3000='.length);
|
|
395
|
+
|
|
396
|
+
// A request that lands on :3001 must read the :3001 slot, NOT the :3000 one,
|
|
397
|
+
// even though the browser ships both cookies to either port.
|
|
398
|
+
const wrongSlot = {
|
|
399
|
+
method: 'GET',
|
|
400
|
+
headers: { host: '192.168.0.1:3001', cookie: `oc_ui_session_3000=${validToken}; oc_ui_session_3001=stale` },
|
|
401
|
+
};
|
|
402
|
+
const wrongRes = createResponse();
|
|
403
|
+
await auth.handleSessionStatus(wrongSlot, wrongRes);
|
|
404
|
+
expect(wrongRes.body.authenticated).toBe(false);
|
|
405
|
+
|
|
406
|
+
// The same token read on its own port authenticates.
|
|
407
|
+
const rightSlot = {
|
|
408
|
+
method: 'GET',
|
|
409
|
+
headers: { host: '192.168.0.1:3000', cookie: `oc_ui_session_3000=${validToken}` },
|
|
410
|
+
};
|
|
411
|
+
const rightRes = createResponse();
|
|
412
|
+
await auth.handleSessionStatus(rightSlot, rightRes);
|
|
413
|
+
expect(rightRes.body.authenticated).toBe(true);
|
|
414
|
+
});
|
|
415
|
+
});
|