@vue-skuilder/express 0.2.24 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.env.development +4 -0
  2. package/assets/courseValidateDocUpdate.js +159 -1
  3. package/dist/assets/courseValidateDocUpdate.js +159 -1
  4. package/dist/couchdb/identityAssertion.d.ts +49 -0
  5. package/dist/couchdb/identityAssertion.d.ts.map +1 -0
  6. package/dist/couchdb/identityAssertion.js +90 -0
  7. package/dist/couchdb/identityAssertion.js.map +1 -0
  8. package/dist/couchdb/sessionCookie.d.ts +28 -0
  9. package/dist/couchdb/sessionCookie.d.ts.map +1 -0
  10. package/dist/couchdb/sessionCookie.js +101 -0
  11. package/dist/couchdb/sessionCookie.js.map +1 -0
  12. package/dist/couchdb/userDesignDocs.d.ts +3 -1
  13. package/dist/couchdb/userDesignDocs.d.ts.map +1 -1
  14. package/dist/couchdb/userDesignDocs.js +7 -5
  15. package/dist/couchdb/userDesignDocs.js.map +1 -1
  16. package/dist/couchdb/userLookup.d.ts +6 -0
  17. package/dist/couchdb/userLookup.d.ts.map +1 -1
  18. package/dist/couchdb/userLookup.js +29 -2
  19. package/dist/couchdb/userLookup.js.map +1 -1
  20. package/dist/routes/auth.d.ts.map +1 -1
  21. package/dist/routes/auth.js +124 -14
  22. package/dist/routes/auth.js.map +1 -1
  23. package/dist/utils/email.d.ts +11 -0
  24. package/dist/utils/email.d.ts.map +1 -0
  25. package/dist/utils/email.js +13 -0
  26. package/dist/utils/email.js.map +1 -0
  27. package/eslint.config.js +1 -1
  28. package/package.json +5 -4
  29. package/scripts/test-course-validator.ts +398 -0
  30. package/src/couchdb/identityAssertion.ts +163 -0
  31. package/src/couchdb/sessionCookie.ts +135 -0
  32. package/src/couchdb/userDesignDocs.ts +7 -5
  33. package/src/couchdb/userLookup.ts +29 -2
  34. package/src/routes/auth.ts +130 -14
  35. package/src/utils/email.ts +12 -0
@@ -0,0 +1,398 @@
1
+ /**
2
+ * Test matrix for assets/courseValidateDocUpdate.js against a REAL CouchDB.
3
+ *
4
+ * The validate_doc_update function runs inside CouchDB's SpiderMonkey (ES5),
5
+ * so unit-testing it in Node proves little. This script creates a scratch
6
+ * course DB on the local dev couch, installs the validator, seeds a CARD doc
7
+ * as admin, then exercises the dynamic-card-ELO rules as a non-admin user.
8
+ *
9
+ * Prereqs: a couch with admin `admin`/`password` (local: `yarn couchdb:start`
10
+ * at repo root). The non-admin user `test`/`test` is created if missing.
11
+ * Runs in CI (ci-pkg-express.yml) against the workflow's couch.
12
+ *
13
+ * Usage (from packages/express):
14
+ * npx tsx scripts/test-course-validator.ts
15
+ *
16
+ * Env overrides: COUCH_URL, COUCH_ADMIN, COUCH_ADMIN_PW, COUCH_USER, COUCH_USER_PW
17
+ */
18
+ import { readFileSync } from 'fs';
19
+ import { dirname, join } from 'path';
20
+ import { fileURLToPath } from 'url';
21
+
22
+ const __dirname = dirname(fileURLToPath(import.meta.url));
23
+
24
+ const COUCH_URL = process.env.COUCH_URL ?? 'http://localhost:5984';
25
+ const ADMIN = { name: process.env.COUCH_ADMIN ?? 'admin', pw: process.env.COUCH_ADMIN_PW ?? 'password' };
26
+ const USER = { name: process.env.COUCH_USER ?? 'test', pw: process.env.COUCH_USER_PW ?? 'test' };
27
+ const DB = 'coursedb-validator-test';
28
+
29
+ const validatorSource = readFileSync(join(__dirname, '..', 'assets', 'courseValidateDocUpdate.js'), 'utf-8');
30
+
31
+ type Cred = { name: string; pw: string };
32
+ type Doc = Record<string, unknown> & { _id: string; _rev?: string };
33
+
34
+ async function req(cred: Cred, method: string, path: string, body?: unknown) {
35
+ const res = await fetch(`${COUCH_URL}/${path}`, {
36
+ method,
37
+ headers: {
38
+ Authorization: 'Basic ' + Buffer.from(`${cred.name}:${cred.pw}`).toString('base64'),
39
+ 'Content-Type': 'application/json',
40
+ },
41
+ body: body === undefined ? undefined : JSON.stringify(body),
42
+ });
43
+ let json: any = null;
44
+ try {
45
+ json = await res.json();
46
+ } catch {
47
+ /* no body */
48
+ }
49
+ return { status: res.status, json };
50
+ }
51
+
52
+ async function getDoc(cred: Cred, id: string): Promise<Doc> {
53
+ const r = await req(cred, 'GET', `${DB}/${encodeURIComponent(id)}`);
54
+ if (r.status !== 200) throw new Error(`GET ${id} -> ${r.status} ${JSON.stringify(r.json)}`);
55
+ return r.json as Doc;
56
+ }
57
+
58
+ async function put(cred: Cred, doc: Doc) {
59
+ return req(cred, 'PUT', `${DB}/${encodeURIComponent(doc._id)}`, doc);
60
+ }
61
+
62
+ // ---- fixtures ---------------------------------------------------------------
63
+
64
+ const CARD_ID = 'c-test-card-1';
65
+ const TAG_A = 'gpc:exercise:a-AE';
66
+ const TAG_B = 'ui:missing-letters';
67
+
68
+ function freshCard(): Doc {
69
+ return {
70
+ _id: CARD_ID,
71
+ course: 'ExampleCourse',
72
+ docType: 'CARD',
73
+ id_displayable_data: ['dd-test-card-1'],
74
+ id_view: 'ExampleCourse.question.MissingLetters.MissingLettersView',
75
+ elo: {
76
+ global: { score: 1405, count: 3 },
77
+ tags: {
78
+ [TAG_A]: { score: 1404, count: 3 },
79
+ [TAG_B]: { score: 1408, count: 0 },
80
+ },
81
+ misc: {},
82
+ },
83
+ seedElo: {
84
+ global: { score: 1405, count: 0 },
85
+ tags: {
86
+ [TAG_A]: { score: 1404, count: 0 },
87
+ [TAG_B]: { score: 1408, count: 0 },
88
+ },
89
+ misc: {},
90
+ },
91
+ author: 'content-pipeline-v1',
92
+ sourceRef: 'gen:content-pipeline-v1',
93
+ };
94
+ }
95
+
96
+ const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x));
97
+
98
+ // ---- harness ----------------------------------------------------------------
99
+
100
+ type Expect = { status: number; reasonIncludes?: string };
101
+ const results: { name: string; pass: boolean; detail: string }[] = [];
102
+
103
+ async function check(name: string, run: () => Promise<{ status: number; json: any }>, expect: Expect) {
104
+ const r = await run();
105
+ const reason: string = r.json?.reason ?? '';
106
+ let pass = r.status === expect.status;
107
+ if (pass && expect.reasonIncludes) pass = reason.includes(expect.reasonIncludes);
108
+ results.push({
109
+ name,
110
+ pass,
111
+ detail: `${r.status}${reason ? ' ' + reason : ''}${pass ? '' : ` (expected ${expect.status}${expect.reasonIncludes ? ' ~ "' + expect.reasonIncludes + '"' : ''})`}`,
112
+ });
113
+ }
114
+
115
+ /** Reset the card as admin so each case starts from a known state. */
116
+ async function resetCard(): Promise<Doc> {
117
+ const existing = await req(ADMIN, 'GET', `${DB}/${encodeURIComponent(CARD_ID)}`);
118
+ const doc = freshCard();
119
+ if (existing.status === 200) doc._rev = (existing.json as Doc)._rev;
120
+ const r = await put(ADMIN, doc);
121
+ if (r.status !== 201) throw new Error(`admin reset failed: ${r.status} ${JSON.stringify(r.json)}`);
122
+ return getDoc(USER, CARD_ID);
123
+ }
124
+
125
+ /** A realistic one-step elo update touching global + TAG_A (TAG_B untouched). */
126
+ function stepped(doc: Doc, dScore = -12): Doc {
127
+ const d = clone(doc);
128
+ const elo: any = d.elo;
129
+ elo.global = { score: elo.global.score + dScore, count: elo.global.count + 1 };
130
+ elo.tags[TAG_A] = { score: elo.tags[TAG_A].score + dScore, count: elo.tags[TAG_A].count + 1 };
131
+ return d;
132
+ }
133
+
134
+ async function main() {
135
+ // Ensure the non-admin user exists (CI couch starts with only the admin).
136
+ // A fresh CouchDB 2.x has no `_users` database until cluster setup runs,
137
+ // so create it first (201 new, 412 exists). Then the user (409 = exists).
138
+ const mkUsersDb = await req(ADMIN, 'PUT', '_users');
139
+ if (mkUsersDb.status !== 201 && mkUsersDb.status !== 412) {
140
+ throw new Error(`could not ensure _users db: ${mkUsersDb.status} ${JSON.stringify(mkUsersDb.json)}`);
141
+ }
142
+ const userDocId = `_users/org.couchdb.user:${USER.name}`;
143
+ const mk = await req(ADMIN, 'PUT', userDocId, {
144
+ name: USER.name,
145
+ password: USER.pw,
146
+ roles: [],
147
+ type: 'user',
148
+ });
149
+ if (mk.status !== 201 && mk.status !== 409) {
150
+ throw new Error(`could not create non-admin user ${USER.name}: ${mk.status} ${JSON.stringify(mk.json)}`);
151
+ }
152
+
153
+ // sanity: non-admin user must authenticate and not be admin
154
+ const sess = await req(USER, 'GET', '_session');
155
+ if (sess.status !== 200 || sess.json?.userCtx?.name !== USER.name) {
156
+ throw new Error(`non-admin user ${USER.name} cannot authenticate: ${sess.status} ${JSON.stringify(sess.json)}`);
157
+ }
158
+ if ((sess.json.userCtx.roles as string[]).includes('_admin')) throw new Error(`${USER.name} is an admin; test is meaningless`);
159
+
160
+ // scratch DB
161
+ await req(ADMIN, 'DELETE', DB);
162
+ const create = await req(ADMIN, 'PUT', DB);
163
+ if (create.status !== 201) throw new Error(`create ${DB}: ${create.status} ${JSON.stringify(create.json)}`);
164
+ // members: [] => any authenticated user can read/write (matches LP prod _security)
165
+ await req(ADMIN, 'PUT', `${DB}/_security`, {
166
+ admins: { names: [], roles: ['_admin'] },
167
+ members: { names: [], roles: [] },
168
+ });
169
+ const dd = await put(ADMIN, { _id: '_design/_auth', validate_doc_update: validatorSource });
170
+ if (dd.status !== 201) throw new Error(`install validator: ${dd.status} ${JSON.stringify(dd.json)}`);
171
+
172
+ try {
173
+ // 1. elo-only write within bounds -> 201
174
+ let doc = await resetCard();
175
+ await check('1. elo-only bounded step (global + one tag, other tag untouched)', () => put(USER, stepped(doc)), { status: 201 });
176
+
177
+ // 1b. max-magnitude step (exactly 64) -> 201
178
+ doc = await resetCard();
179
+ await check('1b. score delta exactly 64', () => put(USER, stepped(doc, 64)), { status: 201 });
180
+
181
+ // 1c. key order shuffled on the round trip -> 201
182
+ doc = await resetCard();
183
+ {
184
+ const s = stepped(doc);
185
+ const shuffled: Doc = { _id: s._id } as Doc;
186
+ for (const k of Object.keys(s).reverse()) shuffled[k] = s[k];
187
+ await check('1c. elo-only step with reversed key order', () => put(USER, shuffled), { status: 201 });
188
+ }
189
+
190
+ // 2. elo + another field changed -> forbidden (elo-only message, not the author rule)
191
+ doc = await resetCard();
192
+ {
193
+ const s = stepped(doc);
194
+ s.sourceRef = 'tampered';
195
+ await check('2a. elo step + sourceRef changed', () => put(USER, s), {
196
+ status: 403,
197
+ reasonIncludes: 'only the elo field may change (field "sourceRef"',
198
+ });
199
+ }
200
+ doc = await resetCard();
201
+ {
202
+ const s = stepped(doc);
203
+ (s.seedElo as any).global.score = 1;
204
+ await check('2b. elo step + seedElo changed', () => put(USER, s), {
205
+ status: 403,
206
+ reasonIncludes: 'only the elo field may change (field "seedElo"',
207
+ });
208
+ }
209
+ doc = await resetCard();
210
+ {
211
+ const s = stepped(doc);
212
+ s.author = USER.name; // try to claim authorship
213
+ await check('2c. elo step + author changed to self', () => put(USER, s), {
214
+ status: 403,
215
+ reasonIncludes: 'only the elo field may change (field "author"',
216
+ });
217
+ }
218
+ doc = await resetCard();
219
+ {
220
+ const s = stepped(doc);
221
+ s.extraField = 1;
222
+ await check('2d. elo step + new field added', () => put(USER, s), {
223
+ status: 403,
224
+ reasonIncludes: 'only the elo field may change (field "extraField"',
225
+ });
226
+ }
227
+ doc = await resetCard();
228
+ {
229
+ const s = clone(doc);
230
+ s.sourceRef = 'tampered'; // no elo change at all
231
+ await check('2e. non-elo field changed, elo untouched', () => put(USER, s), {
232
+ status: 403,
233
+ reasonIncludes: 'only the elo field may change',
234
+ });
235
+ }
236
+
237
+ // 3. score delta 65 -> forbidden
238
+ doc = await resetCard();
239
+ await check('3. global score delta 65', () => put(USER, stepped(doc, 65)), {
240
+ status: 403,
241
+ reasonIncludes: 'elo.global: score may move at most 64',
242
+ });
243
+ doc = await resetCard();
244
+ {
245
+ const s = stepped(doc);
246
+ (s.elo as any).tags[TAG_A].score += 100;
247
+ await check('3b. tag score delta > 64', () => put(USER, s), {
248
+ status: 403,
249
+ reasonIncludes: `elo.tags["${TAG_A}"]: score may move at most 64`,
250
+ });
251
+ }
252
+
253
+ // 4. count +2 -> forbidden
254
+ doc = await resetCard();
255
+ {
256
+ const s = stepped(doc);
257
+ (s.elo as any).global.count += 1;
258
+ await check('4. global count +2', () => put(USER, s), {
259
+ status: 403,
260
+ reasonIncludes: 'elo.global: count must increment by exactly 1',
261
+ });
262
+ }
263
+
264
+ // 5. count unchanged, score moved (stale retry after lost MVCC race) -> forbidden
265
+ doc = await resetCard();
266
+ {
267
+ const s = stepped(doc);
268
+ (s.elo as any).global.count -= 1;
269
+ await check('5. global score moved, count unchanged (stale retry)', () => put(USER, s), {
270
+ status: 403,
271
+ reasonIncludes: 'elo.global: count must increment by exactly 1',
272
+ });
273
+ }
274
+
275
+ // 6. new tag entry with count 1 -> 201; count 3 -> forbidden; far from global -> forbidden
276
+ doc = await resetCard();
277
+ {
278
+ const s = stepped(doc);
279
+ (s.elo as any).tags['gpc:exercise:t-T'] = { score: (doc.elo as any).global.score + 20, count: 1 };
280
+ await check('6a. new tag entry count 1, near global', () => put(USER, s), { status: 201 });
281
+ }
282
+ doc = await resetCard();
283
+ {
284
+ const s = stepped(doc);
285
+ (s.elo as any).tags['gpc:exercise:t-T'] = { score: (doc.elo as any).global.score + 20, count: 3 };
286
+ await check('6b. new tag entry count 3', () => put(USER, s), {
287
+ status: 403,
288
+ reasonIncludes: 'a new tag rank must have count 1',
289
+ });
290
+ }
291
+ doc = await resetCard();
292
+ {
293
+ const s = stepped(doc);
294
+ (s.elo as any).tags['gpc:exercise:t-T'] = { score: 1000, count: 1 };
295
+ await check('6c. new tag entry count 1 but 405 from global', () => put(USER, s), {
296
+ status: 403,
297
+ reasonIncludes: 'must start within 64 of the card global score',
298
+ });
299
+ }
300
+
301
+ // 7. removing a tag entry -> forbidden
302
+ doc = await resetCard();
303
+ {
304
+ const s = stepped(doc);
305
+ delete (s.elo as any).tags[TAG_B];
306
+ await check('7. tag entry removed', () => put(USER, s), {
307
+ status: 403,
308
+ reasonIncludes: `elo.tags["${TAG_B}"] may not be removed`,
309
+ });
310
+ }
311
+
312
+ // 7b. misc changed -> forbidden
313
+ doc = await resetCard();
314
+ {
315
+ const s = stepped(doc);
316
+ (s.elo as any).misc = { x: { score: 1, count: 1 } };
317
+ await check('7b. elo.misc changed', () => put(USER, s), { status: 403, reasonIncludes: 'elo.misc may not change' });
318
+ }
319
+
320
+ // 7c. extra field on an existing tag rank -> forbidden
321
+ doc = await resetCard();
322
+ {
323
+ const s = stepped(doc);
324
+ (s.elo as any).tags[TAG_A].recent = [];
325
+ await check('7c. extra field added to a tag rank', () => put(USER, s), {
326
+ status: 403,
327
+ reasonIncludes: 'only score and count may change (field "recent")',
328
+ });
329
+ }
330
+
331
+ // 7d. malformed elo (number) -> forbidden
332
+ doc = await resetCard();
333
+ {
334
+ const s = clone(doc);
335
+ s.elo = 1400;
336
+ await check('7d. elo replaced by a number', () => put(USER, s), {
337
+ status: 403,
338
+ reasonIncludes: 'must have the CourseElo shape',
339
+ });
340
+ }
341
+
342
+ // 8. non-CARD doc elo-only write -> forbidden (author rule)
343
+ {
344
+ const tag: Doc = {
345
+ _id: 'TAG-gpc:exercise:a-AE',
346
+ course: 'x',
347
+ docType: 'TAG',
348
+ name: TAG_A,
349
+ taggedCards: [CARD_ID],
350
+ author: 'content-pipeline-v1',
351
+ elo: { global: { score: 1000, count: 0 }, tags: {}, misc: {} },
352
+ };
353
+ const r = await put(ADMIN, tag);
354
+ if (r.status !== 201) throw new Error('seed TAG failed');
355
+ const t = await getDoc(USER, tag._id);
356
+ (t.elo as any).global = { score: 1010, count: 1 };
357
+ await check('8. non-CARD (TAG) doc, elo-only bounded step', () => put(USER, t), {
358
+ status: 403,
359
+ reasonIncludes: 'You can only modify your own documents',
360
+ });
361
+ }
362
+
363
+ // 8b. non-admin creating a card with someone else's author -> forbidden (unchanged rule)
364
+ await check(
365
+ '8b. non-admin creates doc with foreign author',
366
+ () => put(USER, { ...freshCard(), _id: 'c-new-card' }),
367
+ { status: 403, reasonIncludes: 'Document author must match your username' }
368
+ );
369
+
370
+ // 9. admin writes anything -> 201
371
+ doc = await resetCard();
372
+ {
373
+ const s = clone(doc);
374
+ s.sourceRef = 'admin-edit';
375
+ (s.elo as any).global = { score: 5, count: 99 };
376
+ delete (s.elo as any).tags[TAG_B];
377
+ await check('9. admin: arbitrary edit incl. wild elo', () => put(ADMIN, s), { status: 201 });
378
+ }
379
+ } finally {
380
+ const del = await req(ADMIN, 'DELETE', DB);
381
+ console.log(`\ncleanup: DELETE ${DB} -> ${del.status}`);
382
+ }
383
+
384
+ // ---- report
385
+ const width = Math.max(...results.map((r) => r.name.length));
386
+ let failed = 0;
387
+ for (const r of results) {
388
+ if (!r.pass) failed++;
389
+ console.log(`${r.pass ? 'PASS' : 'FAIL'} ${r.name.padEnd(width)} ${r.detail}`);
390
+ }
391
+ console.log(`\n${results.length - failed}/${results.length} passed`);
392
+ process.exit(failed ? 1 : 0);
393
+ }
394
+
395
+ main().catch((e) => {
396
+ console.error(e);
397
+ process.exit(2);
398
+ });
@@ -0,0 +1,163 @@
1
+ import type { CouchDbUserDoc } from '@vue-skuilder/db';
2
+ import { getCouchDB } from './index.js';
3
+ import {
4
+ findUserByUsername,
5
+ findUsernamesByEmail,
6
+ findVerifiedUserByEmail,
7
+ updateUserDoc,
8
+ } from './userLookup.js';
9
+ import { generateSecureToken } from '../utils/tokens.js';
10
+ import { normalizeEmail } from '../utils/email.js';
11
+ import { isNanoError } from '../utils/types.js';
12
+ import logger from '../logger.js';
13
+
14
+ /**
15
+ * Identity assertion: "a trusted caller vouches that this person controls this
16
+ * email" → the account that email belongs to, created if need be.
17
+ *
18
+ * The provider-agnostic core of third-party sign-in (Google, Apple, SSO, magic
19
+ * links). Provider token verification lives with the caller; this module owns
20
+ * the `_users` rules, which must stay in one place alongside /verify,
21
+ * /resolve-login and reset:
22
+ *
23
+ * Resolution order (mirrors /resolve-login's candidates):
24
+ * 1. the account that has *verified* this email;
25
+ * 2. the account whose username IS the email (unless its recovery address
26
+ * has since been changed to something else — then the name is just an
27
+ * opaque id and the address is no longer the owner's);
28
+ * 3. accounts with this email saved but unverified (first by name, so the
29
+ * pick is deterministic);
30
+ * 4. none: create a verified account named after the email.
31
+ *
32
+ * Rules:
33
+ * - Accounts with any role are never resolved. App users carry `roles: []`;
34
+ * a role means a privileged account, which must stay password-only, or it
35
+ * is only as secure as the third-party account sharing its address.
36
+ * - Linking an existing account (1–3) requires `authoritative: true`: the
37
+ * asserter must be authoritative for the address, not merely have checked
38
+ * it once. Otherwise a lapsed-then-reregistered address would open someone
39
+ * else's account. Creating a *new* account needs no such guarantee.
40
+ * - Linking an unverified account (2–3) marks it verified and rotates its
41
+ * password to a random one. The rotation regenerates the salt CouchDB signs
42
+ * session cookies with, killing any squatter's sessions; the legitimate
43
+ * owner can get a password back through reset.
44
+ * - Linking a verified account (1) mutates nothing.
45
+ */
46
+
47
+ export interface IdentityAssertion {
48
+ email: string;
49
+ /** Free-form provider tag, for logs and the `_users` doc. */
50
+ provider: string;
51
+ /** Whether the asserter is authoritative for this address right now. */
52
+ authoritative: boolean;
53
+ }
54
+
55
+ export type IdentityResolution =
56
+ | { ok: true; username: string; outcome: 'existing' | 'linked' | 'created' }
57
+ | {
58
+ ok: false;
59
+ code: 'privileged_account' | 'link_requires_authoritative' | 'username_conflict';
60
+ };
61
+
62
+ type UserDoc = CouchDbUserDoc & {
63
+ roles?: string[];
64
+ linkedProviders?: string[];
65
+ /** Plaintext on write only; CouchDB hashes it (new salt) on save. */
66
+ password?: string;
67
+ };
68
+
69
+ function isPrivileged(doc: UserDoc): boolean {
70
+ return Array.isArray(doc.roles) && doc.roles.length > 0;
71
+ }
72
+
73
+ function withProvider(doc: UserDoc, provider: string): string[] {
74
+ const existing = Array.isArray(doc.linkedProviders) ? doc.linkedProviders : [];
75
+ return existing.includes(provider) ? existing : [...existing, provider];
76
+ }
77
+
78
+ export async function resolveAssertedIdentity(
79
+ assertion: IdentityAssertion
80
+ ): Promise<IdentityResolution> {
81
+ const email = normalizeEmail(assertion.email);
82
+ const { provider, authoritative } = assertion;
83
+
84
+ // 1. Verified owner of the address.
85
+ const verified = (await findVerifiedUserByEmail(email)) as UserDoc | null;
86
+ if (verified) {
87
+ if (isPrivileged(verified)) return refuse('privileged_account', verified.name, provider);
88
+ if (!authoritative) return refuse('link_requires_authoritative', verified.name, provider);
89
+ return { ok: true, username: verified.name, outcome: 'existing' };
90
+ }
91
+
92
+ // 2 + 3. Unverified claims on the address.
93
+ const byName = (await findUserByUsername(email)) as UserDoc | null;
94
+ const nameCandidate = byName && (!byName.email || byName.email === email) ? byName : null;
95
+
96
+ let target: UserDoc | null = nameCandidate;
97
+ if (!target) {
98
+ const names = (await findUsernamesByEmail(email, 10)).sort();
99
+ if (names.length > 1) {
100
+ logger.warn(
101
+ `[identity] ${names.length} unverified accounts claim ${email}; linking ${names[0]}`
102
+ );
103
+ }
104
+ if (names.length > 0) target = (await findUserByUsername(names[0])) as UserDoc | null;
105
+ }
106
+
107
+ if (target) {
108
+ if (isPrivileged(target)) return refuse('privileged_account', target.name, provider);
109
+ if (!authoritative) return refuse('link_requires_authoritative', target.name, provider);
110
+
111
+ // Already verified for this address: step 1 should have found it, but the
112
+ // by_verified_email lookup fails open while its view is missing. Never
113
+ // rotate a verified owner's password.
114
+ if (target.status === 'verified' && target.email === email) {
115
+ return { ok: true, username: target.name, outcome: 'existing' };
116
+ }
117
+
118
+ target.email = email;
119
+ target.status = 'verified';
120
+ target.verificationToken = null;
121
+ target.verificationTokenExpiresAt = null;
122
+ target.password = generateSecureToken();
123
+ target.linkedProviders = withProvider(target, provider);
124
+ await updateUserDoc(target);
125
+ logger.info(`[identity] linked ${target.name} via ${provider} (verified, password rotated)`);
126
+ return { ok: true, username: target.name, outcome: 'linked' };
127
+ }
128
+
129
+ // 4. New account. The name is taken only if an account named after this
130
+ // address moved its recovery email elsewhere (skipped in step 2).
131
+ if (byName) return refuse('username_conflict', byName.name, provider);
132
+
133
+ const newDoc = {
134
+ _id: `org.couchdb.user:${email}`,
135
+ name: email,
136
+ type: 'user',
137
+ roles: [] as string[],
138
+ password: generateSecureToken(),
139
+ email,
140
+ status: 'verified',
141
+ linkedProviders: [provider],
142
+ };
143
+ try {
144
+ await getCouchDB().use('_users').insert(newDoc);
145
+ } catch (error: unknown) {
146
+ if (isNanoError(error) && error.statusCode === 409) {
147
+ // Raced a concurrent signup for the same address.
148
+ return refuse('username_conflict', email, provider);
149
+ }
150
+ throw error;
151
+ }
152
+ logger.info(`[identity] created ${email} via ${provider}`);
153
+ return { ok: true, username: email, outcome: 'created' };
154
+ }
155
+
156
+ function refuse(
157
+ code: 'privileged_account' | 'link_requires_authoritative' | 'username_conflict',
158
+ username: string,
159
+ provider: string
160
+ ): IdentityResolution {
161
+ logger.warn(`[identity] refused ${provider} assertion for ${username}: ${code}`);
162
+ return { ok: false, code };
163
+ }
@@ -0,0 +1,135 @@
1
+ import crypto from 'crypto';
2
+ import { getCouchDB } from './index.js';
3
+ import { findUserByUsername } from './userLookup.js';
4
+ import { isNanoError } from '../utils/types.js';
5
+
6
+ /**
7
+ * Server-side minting of CouchDB `AuthSession` cookies.
8
+ *
9
+ * Lets express establish a session for a user whose identity was proven some
10
+ * other way (see identityAssertion.ts) — there is no password to hand to
11
+ * `_session`. The cookie is byte-for-byte what CouchDB itself issues:
12
+ *
13
+ * base64url( "<name>:<TIMESTAMP_HEX>:" ++ HMAC(alg, secret ++ salt, "<name>:<TIMESTAMP_HEX>") )
14
+ *
15
+ * - alg: the FIRST entry of `[chttpd_auth] hash_algorithms` (3.3+, default
16
+ * "sha256, sha"); CouchDB 2.x has no such key and always uses SHA1.
17
+ * - secret: `[chttpd_auth] secret`, falling back to the legacy
18
+ * `[couch_httpd_auth]` section, as CouchDB itself does.
19
+ * - salt: the user's `_users` doc `salt`. Changing a user's password
20
+ * regenerates it, which invalidates every outstanding cookie for them.
21
+ *
22
+ * Config is read from the server's `_node/_local/_config` on every mint (admin
23
+ * creds), so the secret never lives in env files and a rotation takes effect
24
+ * immediately.
25
+ *
26
+ * Tied to CouchDB's cookie format: test/identityAssertion.test.ts compares minted
27
+ * cookies byte for byte with CouchDB-issued ones; run it against the production
28
+ * CouchDB version after any upgrade.
29
+ */
30
+
31
+ /** CouchDB's defaults for the keys we read. */
32
+ const DEFAULT_TIMEOUT_SECONDS = 600;
33
+
34
+ export interface MintedSessionCookie {
35
+ name: 'AuthSession';
36
+ value: string;
37
+ /** Seconds, when CouchDB issues persistent cookies; null = session cookie. */
38
+ maxAge: number | null;
39
+ }
40
+
41
+ async function readConfig(section: string, key: string): Promise<string | null> {
42
+ try {
43
+ const value = await getCouchDB().request({
44
+ path: `_node/_local/_config/${section}/${key}`,
45
+ });
46
+ return typeof value === 'string' ? value : null;
47
+ } catch (error: unknown) {
48
+ if (isNanoError(error) && error.statusCode === 404) return null;
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ /** chttpd_auth first, then the legacy couch_httpd_auth section. */
54
+ async function readAuthConfig(key: string): Promise<string | null> {
55
+ return (await readConfig('chttpd_auth', key)) ?? (await readConfig('couch_httpd_auth', key));
56
+ }
57
+
58
+ /** Map a CouchDB (Erlang) hash name to a Node crypto one. */
59
+ function nodeHashName(couchName: string): string {
60
+ const name = couchName.trim().toLowerCase();
61
+ if (name === 'sha') return 'sha1';
62
+ if (['sha224', 'sha256', 'sha384', 'sha512'].includes(name)) return name;
63
+ throw new Error(`Unsupported CouchDB cookie hash algorithm: ${couchName}`);
64
+ }
65
+
66
+ export interface CookieParams {
67
+ username: string;
68
+ secret: string;
69
+ salt: string;
70
+ /** Node crypto hash name, e.g. 'sha256'. */
71
+ hash: string;
72
+ /** Seconds since the epoch. */
73
+ timestamp: number;
74
+ }
75
+
76
+ /** Pure cookie-value computation (exported for tests). */
77
+ export function computeAuthSessionValue(p: CookieParams): string {
78
+ const sessionData = `${p.username}:${p.timestamp.toString(16).toUpperCase()}`;
79
+ const mac = crypto
80
+ .createHmac(p.hash, p.secret + p.salt) // string keys are UTF-8
81
+ .update(sessionData, 'utf8')
82
+ .digest();
83
+ // Spread to bytes: Buffer.concat trips this package's Buffer/Uint8Array typings.
84
+ return Buffer.from([...Buffer.from(sessionData + ':', 'utf8'), ...mac]).toString('base64url');
85
+ }
86
+
87
+ export interface CookieConfig {
88
+ secret: string;
89
+ /** Node crypto hash name used to sign new cookies. */
90
+ hash: string;
91
+ timeout: number;
92
+ persistent: boolean;
93
+ }
94
+
95
+ /** The server's cookie-signing config, resolved the way CouchDB resolves it. */
96
+ export async function readCookieConfig(): Promise<CookieConfig> {
97
+ const secret = await readAuthConfig('secret');
98
+ if (!secret) {
99
+ throw new Error('Cannot mint session: CouchDB auth secret is not configured');
100
+ }
101
+
102
+ const algorithms = await readConfig('chttpd_auth', 'hash_algorithms');
103
+ const hash = algorithms ? nodeHashName(algorithms.split(',')[0]) : 'sha1';
104
+
105
+ const timeoutRaw = await readAuthConfig('timeout');
106
+ const timeout = timeoutRaw ? parseInt(timeoutRaw, 10) : DEFAULT_TIMEOUT_SECONDS;
107
+
108
+ // Default true since CouchDB 3.0.
109
+ const persistentRaw = await readAuthConfig('allow_persistent_cookies');
110
+ const persistent = persistentRaw === null ? true : persistentRaw === 'true';
111
+
112
+ return { secret, hash, timeout, persistent };
113
+ }
114
+
115
+ export async function mintAuthSessionCookie(username: string): Promise<MintedSessionCookie> {
116
+ const userDoc = await findUserByUsername(username);
117
+ const salt = (userDoc as { salt?: unknown } | null)?.salt;
118
+ if (!userDoc || typeof salt !== 'string' || !salt) {
119
+ throw new Error(`Cannot mint session for ${username}: no user or no salt`);
120
+ }
121
+
122
+ const { secret, hash, timeout, persistent } = await readCookieConfig();
123
+
124
+ return {
125
+ name: 'AuthSession',
126
+ value: computeAuthSessionValue({
127
+ username,
128
+ secret,
129
+ salt,
130
+ hash,
131
+ timestamp: Math.floor(Date.now() / 1000),
132
+ }),
133
+ maxAge: persistent ? timeout : null,
134
+ };
135
+ }