@cossackframework/cms 0.9.2 → 0.9.4

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 (120) hide show
  1. package/agent-docs.json +8 -8
  2. package/app/cossack-recipe.json +12 -8
  3. package/app/src/auth-events.ts +33 -0
  4. package/app/src/auth-input.ts +3 -0
  5. package/app/src/auth-options.ts +39 -7
  6. package/app/src/auth.ts +1309 -641
  7. package/app/src/avatars.ts +13 -0
  8. package/app/src/brand.ts +24 -2
  9. package/app/src/cms/actor.ts +13 -0
  10. package/app/src/cms/collab/room.ts +1 -1
  11. package/app/src/cms/content-api.ts +2 -1
  12. package/app/src/cms/content.ts +3 -2
  13. package/app/src/cms/dev-mail.ts +77 -0
  14. package/app/src/cms/index.ts +37 -10
  15. package/app/src/cms/maintenance.ts +1 -6
  16. package/app/src/cms/manage.ts +17 -14
  17. package/app/src/cms/middleware.ts +58 -18
  18. package/app/src/cms/network-accounts.ts +110 -0
  19. package/app/src/cms/notes-announce.ts +1 -1
  20. package/app/src/cms/people.ts +177 -0
  21. package/app/src/cms/recovery.ts +9 -14
  22. package/app/src/cms/request-calls.ts +56 -0
  23. package/app/src/cms/settings-form.ts +23 -6
  24. package/app/src/cms/settings-network.ts +8 -4
  25. package/app/src/cms/settings-search.ts +1 -0
  26. package/app/src/cms/site-editing.ts +3 -2
  27. package/app/src/cms/site-registration.ts +64 -0
  28. package/app/src/cms/site.ts +30 -19
  29. package/app/src/cms/sites.ts +182 -0
  30. package/app/src/dashboard/access.ts +3 -2
  31. package/app/src/dashboard/modules/users.ts +1 -0
  32. package/app/src/lib/permissions.ts +24 -0
  33. package/app/src/lib/uuid.ts +6 -0
  34. package/app/src/mail.ts +15 -0
  35. package/app/src/middlewares/auth.ts +6 -2
  36. package/app/src/middlewares/tenant.ts +108 -0
  37. package/app/src/pages/(site)/[...path]/index.ts +1 -1
  38. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
  39. package/app/src/pages/api/cms/dev/mail.ts +19 -0
  40. package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
  41. package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
  42. package/app/src/pages/auth/login/index.ts +1 -1
  43. package/app/src/pages/auth/magic/index.ts +1 -1
  44. package/app/src/pages/auth/recovery.ts +20 -0
  45. package/app/src/pages/auth/register-site/index.ts +146 -0
  46. package/app/src/pages/auth/setup/index.ts +8 -3
  47. package/app/src/pages/auth/tenant/callback.ts +23 -0
  48. package/app/src/pages/auth/tenant/redirect.ts +91 -0
  49. package/app/src/pages/auth/verify/index.ts +3 -7
  50. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
  51. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
  52. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
  53. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
  54. package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
  55. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
  56. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
  57. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
  58. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
  59. package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
  60. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
  61. package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
  62. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
  63. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
  64. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
  65. package/app/src/pages/dashboard/index.ts +3 -2
  66. package/app/src/pages/dashboard/roles/index.ts +2 -2
  67. package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
  68. package/app/src/services/api-tokens.ts +86 -0
  69. package/app/src/services/rbac.ts +26 -15
  70. package/app/src/services/roles.ts +125 -35
  71. package/app/src/services/security.ts +384 -0
  72. package/app/src/services/tenants.ts +447 -0
  73. package/app/src/services/users.ts +241 -97
  74. package/app/src/tenants.ts +219 -0
  75. package/package.json +48 -12
  76. package/src/block-references.ts +3 -3
  77. package/src/collections.ts +3 -1
  78. package/src/forms.ts +4 -2
  79. package/src/hooks.ts +19 -1
  80. package/src/index.ts +4 -4
  81. package/src/isolate-core.ts +1 -1
  82. package/src/isolation.ts +1 -0
  83. package/src/manifest.ts +43 -2
  84. package/src/permissions.ts +13 -7
  85. package/src/resource.ts +85 -2
  86. package/src/server/attempts.ts +64 -0
  87. package/src/server/automations.ts +2 -2
  88. package/src/server/batch.ts +106 -0
  89. package/src/server/budget.ts +17 -0
  90. package/src/server/field-values.ts +207 -0
  91. package/src/server/forms.ts +3 -3
  92. package/src/server/host-schema.ts +55 -7
  93. package/src/server/host.ts +213 -85
  94. package/src/server/index.ts +9 -14
  95. package/src/server/isolation.ts +10 -0
  96. package/src/server/network.ts +129 -44
  97. package/src/server/outbox.ts +2 -2
  98. package/src/server/people.ts +191 -0
  99. package/src/server/reconcile.ts +5 -5
  100. package/src/server/repository.ts +243 -84
  101. package/src/server/shared-read.ts +34 -0
  102. package/src/server/site-export.ts +23 -13
  103. package/src/server/site-import.ts +12 -33
  104. package/src/server/site-settings.ts +9 -3
  105. package/src/server/sites.ts +117 -187
  106. package/src/server/stores.ts +3 -300
  107. package/src/server/taxonomies.ts +64 -13
  108. package/src/server/users.ts +151 -498
  109. package/src/settings-controls.ts +8 -4
  110. package/src/settings.ts +26 -3
  111. package/src/storage/cloudflare.ts +2 -0
  112. package/src/storage/index.ts +6 -0
  113. package/src/theme.ts +2 -2
  114. package/src/version.ts +1 -1
  115. package/app/src/cms/handoff.ts +0 -202
  116. package/src/server/accounts.ts +0 -418
  117. package/src/server/api-tokens.ts +0 -91
  118. package/src/server/auth.ts +0 -89
  119. package/src/server/handoffs.ts +0 -107
  120. package/src/server/security.ts +0 -391
@@ -1,107 +0,0 @@
1
- /**
2
- * Sign-in handoffs on the network database. Accounts sign in only on the network host; a site
3
- * gets its own session from a one-use code bound to the site and the network session, valid for
4
- * a minute. The network remembers which sites each session reached, to end their child
5
- * sessions with it.
6
- */
7
- import type { RomeDB } from '@cossackframework/romedb';
8
- import type { EndedSessions } from './stores';
9
-
10
- const CODE = /^[a-f0-9]{64}$/;
11
- const WRITE = { kind: 'cms.handoffs', retryConflicts: 5 } as const;
12
-
13
- const sha256 = async (text: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]
14
- .map(byte => byte.toString(16).padStart(2, '0')).join('');
15
-
16
- export interface Handoff {
17
- /** The network session's public reference: the child session's parent. */
18
- readonly session: string;
19
- readonly user: string;
20
- /** The account's network role now, which the child session copies. */
21
- readonly networkRole: string | null;
22
- /** When the network session expires; the child session ends no later. */
23
- readonly expiresAt: number;
24
- /** Whether the network session's sign-in used a second factor; the child session copies it. */
25
- readonly secondFactor: boolean;
26
- }
27
-
28
- export class CmsHandoffs {
29
- readonly #db: RomeDB;
30
- readonly #now: () => number;
31
-
32
- constructor(db: RomeDB, options: { now?: () => number } = {}) {
33
- this.#db = db;
34
- this.#now = options.now ?? Date.now;
35
- }
36
-
37
- /** A code for the network session to sign in on the site. Only its SHA-256 is stored. */
38
- async issue(input: { session: string; user: string; site: string; ttlMs?: number }): Promise<string> {
39
- const code = [...crypto.getRandomValues(new Uint8Array(32))].map(byte => byte.toString(16).padStart(2, '0')).join('');
40
- const now = this.#now();
41
- await this.#db.write([{ rql: 'INSERT INTO cms_handoffs (id, session_id, user_id, site_id, created_at, expires_at) VALUES ($id, $session, $user, $site, $now, $expires)',
42
- params: { $id: await sha256(code), $session: input.session, $user: input.user, $site: input.site, $now: now, $expires: now + (input.ttlMs ?? 60_000) } }], WRITE);
43
- return code;
44
- }
45
-
46
- /**
47
- * The handoff a code names for this site, used at most once. Null when the code is unknown,
48
- * expired, for another site or used, or when its network session or active account is gone.
49
- */
50
- async consume(code: string, site: string): Promise<Handoff | null> {
51
- if (typeof code !== 'string' || !CODE.test(code)) return null;
52
- const id = await sha256(code);
53
- const now = this.#now();
54
- const found = await this.#db.read([{
55
- rql: `SELECT h.session_id, h.user_id, a.network_role, s.expires_at, s.second_factor FROM cms_handoffs h JOIN cms_accounts a ON a.id = h.user_id
56
- JOIN cms_auth_sessions s ON s.public_id = h.session_id AND s.user_id = h.user_id
57
- WHERE h.id = $id AND h.site_id = $site AND h.expires_at > $now AND s.expires_at > $now AND a.status = 'active'`,
58
- params: { $id: id, $site: site, $now: now },
59
- }]);
60
- const row = found.results[0]!.rows[0];
61
- if (!row) {
62
- await this.#db.write([{ rql: 'DELETE FROM cms_handoffs WHERE id = $id', params: { $id: id } }], WRITE);
63
- return null;
64
- }
65
- const handoff = { session: row[0] as string, user: row[1] as string, networkRole: row[2] as string | null, expiresAt: Number(row[3]), secondFactor: row[4] !== null && Number(row[4]) === 1 };
66
- // Only the request whose delete removed the code may use it. The site is recorded for the
67
- // network session only while that session lives, so a sign-out finds every site it reached.
68
- const taken = await this.#db.write([
69
- { rql: 'DELETE FROM cms_handoffs WHERE id = $id', params: { $id: id } },
70
- {
71
- rql: `INSERT INTO cms_session_sites (session_id, site_id, user_id, created_at) SELECT $session, $site, $user, $now
72
- WHERE EXISTS (SELECT 1 FROM cms_auth_sessions WHERE public_id = $session AND user_id = $user AND expires_at > $now) ON CONFLICT (session_id, site_id) DO NOTHING`,
73
- params: { $session: handoff.session, $site: site, $user: handoff.user, $now: now },
74
- },
75
- ], WRITE);
76
- if (taken.results[0]!.affected !== 1n) return null;
77
- // Signed out since the read: no child session. A sign-out after this check lists the site.
78
- const alive = await this.#db.read([{ rql: 'SELECT 1 FROM cms_auth_sessions WHERE public_id = $session AND user_id = $user AND expires_at > $now', params: { $session: handoff.session, $user: handoff.user, $now: now } }]);
79
- if (!alive.results[0]!.rows.length) return null;
80
- return Object.freeze(handoff);
81
- }
82
-
83
- /** The sites these network sessions reached; `forget` drops the record once their child sessions ended. */
84
- async reached(ended: EndedSessions): Promise<string[]> {
85
- const result = await this.#db.read(['session' in ended
86
- ? { rql: 'SELECT DISTINCT site_id FROM cms_session_sites WHERE session_id = $session', params: { $session: ended.session } }
87
- : { rql: `SELECT DISTINCT site_id FROM cms_session_sites WHERE user_id = $user${ended.except ? ' AND session_id != $except' : ''}`, params: { $user: ended.user, ...(ended.except ? { $except: ended.except } : {}) } }]);
88
- return result.results[0]!.rows.map(row => row[0] as string);
89
- }
90
-
91
- async forget(ended: EndedSessions): Promise<void> {
92
- await this.#db.write(['session' in ended
93
- ? { rql: 'DELETE FROM cms_session_sites WHERE session_id = $session', params: { $session: ended.session } }
94
- : { rql: `DELETE FROM cms_session_sites WHERE user_id = $user${ended.except ? ' AND session_id != $except' : ''}`, params: { $user: ended.user, ...(ended.except ? { $except: ended.except } : {}) } }], WRITE);
95
- }
96
-
97
- async purgeExpired(): Promise<void> {
98
- const now = this.#now();
99
- const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_handoffs WHERE expires_at <= $now LIMIT 1', params: { $now: now } }]);
100
- if (!expired.results[0]!.rows.length) return;
101
- await this.#db.write([
102
- { rql: 'DELETE FROM cms_handoffs WHERE id IN (SELECT id FROM cms_handoffs WHERE expires_at <= $now LIMIT 500)', params: { $now: now } },
103
- // Records of network sessions that ended without telling the sites, after their expiry.
104
- { rql: 'DELETE FROM cms_session_sites WHERE session_id IN (SELECT ss.session_id FROM cms_session_sites ss WHERE NOT EXISTS (SELECT 1 FROM cms_auth_sessions s WHERE s.public_id = ss.session_id) LIMIT 500)' },
105
- ], WRITE);
106
- }
107
- }
@@ -1,391 +0,0 @@
1
- /**
2
- * Second factors of CMS users: an authenticator app's secret, recovery codes, passkeys, and
3
- * the short-lived challenges of pending sign-ins and passkey ceremonies.
4
- */
5
- import { generateRecoveryCodes, generateTotpSecret, hashRecoveryCode, verifyTotp } from '@cossackframework/auth';
6
- import type { RomeDB, Value } from '@cossackframework/romedb';
7
- import { CmsError } from '../errors';
8
- import { randomToken, sha256Hex } from './tokens';
9
-
10
- export interface PasskeyInfo {
11
- readonly id: string;
12
- readonly name: string;
13
- readonly deviceType: string | null;
14
- readonly backedUp: boolean;
15
- readonly createdAt: number;
16
- readonly lastUsedAt: number | null;
17
- }
18
-
19
- export interface StoredPasskeyRow extends PasskeyInfo {
20
- readonly userId: string;
21
- readonly publicKey: string;
22
- readonly counter: number;
23
- readonly transports: readonly string[] | null;
24
- }
25
-
26
- export interface SecurityStatus {
27
- /** An authenticator app is set up and confirmed. */
28
- readonly totp: boolean;
29
- /** Unused recovery codes. */
30
- readonly recoveryCodes: number;
31
- readonly passkeys: readonly PasskeyInfo[];
32
- }
33
-
34
- export type ChallengeKind = 'signin' | 'passkey-register' | 'passkey-signin';
35
-
36
- const WRITE = { kind: 'cms.security', retryConflicts: 5 } as const;
37
- /** Attempt counters: one row takes every attempt of a burst, so they retry longer. */
38
- const COUNT = { kind: 'cms.security', retryConflicts: 20 } as const;
39
- const PASSKEY_COLUMNS = 'id, user_id, name, public_key, counter, transports, device_type, backed_up, created_at, last_used_at';
40
- /** Wrong codes a pending sign-in allows. */
41
- export const SIGN_IN_ATTEMPTS = 5;
42
- /**
43
- * Second-factor codes counted per account for a window, across every pending sign-in: a right
44
- * password does not give them back, so knowing the password does not buy more guesses.
45
- */
46
- export const SECOND_FACTOR_LOCK = Object.freeze({ windowMs: 15 * 60_000, perAccount: 10 });
47
- /**
48
- * Password sign-ins are counted per email and per client address for a window, a right password
49
- * giving its attempt back; past the limit the sign-in is refused until the window ends, whether
50
- * or not the account exists.
51
- */
52
- export const SIGN_IN_LOCK = Object.freeze({ windowMs: 15 * 60_000, perEmail: 5, perAddress: 20 });
53
- /** Password reset requests per email and per address in an hour; beyond them nothing is sent. */
54
- export const RESET_REQUESTS = Object.freeze({ windowMs: 60 * 60_000, perEmail: 3, perAddress: 10 });
55
-
56
- export class CmsSecurity {
57
- readonly #db: RomeDB;
58
- readonly #now: () => number;
59
-
60
- constructor(db: RomeDB, options: { now?: () => number } = {}) {
61
- this.#db = db;
62
- this.#now = options.now ?? Date.now;
63
- }
64
-
65
- /**
66
- * Start a password sign-in: one attempt is counted for the email and for the address before
67
- * the password is checked, in conditional writes, so attempts sent at once are held to the
68
- * limits as well as one after another. Refused while either is at its limit for the window.
69
- * A right password gives the attempt back (`signInSucceeded`); a wrong one leaves it counted.
70
- */
71
- async signInBegin(email: string, address: string): Promise<{ ok: true } | { ok: false; retryAfterMs: number }> {
72
- const [emailId, addressId] = [await emailKey(email), addressKey(address)];
73
- const byEmail = await this.#count(emailId, SIGN_IN_LOCK.windowMs, SIGN_IN_LOCK.perEmail);
74
- const byAddress = byEmail && await this.#count(addressId, SIGN_IN_LOCK.windowMs, SIGN_IN_LOCK.perAddress);
75
- if (byEmail && byAddress) return { ok: true };
76
- // The email's attempt does not stand when the address refused it.
77
- if (byEmail) await this.#giveBack(emailId);
78
- const result = await this.#db.read([{ rql: 'SELECT until FROM cms_attempts WHERE key = $key', params: { $key: byEmail ? addressId : emailId } }]);
79
- const until = Number((result.results[0]!.rows[0]?.[0] as bigint | undefined) ?? 0n);
80
- return { ok: false, retryAfterMs: Math.max(1, until - this.#now()) };
81
- }
82
-
83
- /** A right password: the email's failures are forgotten, and the address gets this attempt back. */
84
- async signInSucceeded(email: string, address: string): Promise<void> {
85
- await this.#bestEffort('DELETE FROM cms_attempts WHERE key = $key', await emailKey(email));
86
- await this.#giveBack(addressKey(address));
87
- }
88
-
89
- async #giveBack(key: string): Promise<void> {
90
- await this.#bestEffort('UPDATE cms_attempts SET count = count - 1 WHERE key = $key AND count > 0', key);
91
- }
92
-
93
- /**
94
- * A write that gives attempts back. Under a burst on the same key it can keep conflicting past
95
- * the retries: the attempt then stays counted (the limit errs shut), and the request goes on.
96
- */
97
- async #bestEffort(rql: string, key: string): Promise<void> {
98
- try { await this.#db.write([{ rql, params: { $key: key } }], COUNT); }
99
- catch (error) {
100
- if ((error as { code?: string }).code !== 'RDB_WRITE_CONFLICT') throw error;
101
- console.warn('[cms] a sign-in attempt could not be given back: the key is busy');
102
- }
103
- }
104
-
105
- /**
106
- * Count an attempt of `kind` (such as `reset`) for a key within a window; false past `max`.
107
- * A refused attempt keeps the gate shut until the window ends.
108
- */
109
- async attempt(kind: string, key: string, max: number, windowMs: number): Promise<boolean> {
110
- return this.#count(attemptKey(kind, key), windowMs, max);
111
- }
112
-
113
- /** Give back an attempt `attempt()` counted, for one that did not go ahead after all. */
114
- async release(kind: string, key: string): Promise<void> {
115
- await this.#giveBack(attemptKey(kind, key));
116
- }
117
-
118
- /**
119
- * One more attempt for the key, unless it already has `max` in its window: true when this
120
- * one was counted. The database does the counting in one write (an ended window starts
121
- * again, then a conditional increment), so concurrent attempts are each counted once and
122
- * no more than `max` are let through.
123
- */
124
- async #count(key: string, windowMs: number, max: number): Promise<boolean> {
125
- const now = this.#now();
126
- try {
127
- const result = await this.#db.write([
128
- { rql: 'DELETE FROM cms_attempts WHERE key = $key AND until <= $now', params: { $key: key, $now: now } },
129
- { rql: 'INSERT INTO cms_attempts (key, count, until) VALUES ($key, 0, $until) ON CONFLICT (key) DO NOTHING', params: { $key: key, $until: now + windowMs } },
130
- { rql: 'UPDATE cms_attempts SET count = count + 1 WHERE key = $key AND count < $max', params: { $key: key, $max: max } },
131
- ], COUNT);
132
- return result.results[2]!.affected === 1n;
133
- } catch (error) {
134
- // A key under a burst of attempts can keep conflicting past the retries: refuse this
135
- // attempt, as the limit would, rather than fail the request.
136
- if ((error as { code?: string }).code === 'RDB_WRITE_CONFLICT') return false;
137
- throw error;
138
- }
139
- }
140
-
141
- async status(userId: string): Promise<SecurityStatus> {
142
- const result = await this.#db.read([
143
- { rql: 'SELECT totp_confirmed_at, recovery FROM cms_user_security WHERE user_id = $user', params: { $user: userId } },
144
- { rql: `SELECT ${PASSKEY_COLUMNS} FROM cms_passkeys WHERE user_id = $user ORDER BY created_at LIMIT 50`, params: { $user: userId } },
145
- ]);
146
- const row = result.results[0]!.rows[0];
147
- const recovery = row?.[1] ? (JSON.parse(row[1] as string) as string[]) : [];
148
- return { totp: Boolean(row?.[0]), recoveryCodes: row?.[0] ? recovery.length : 0, passkeys: result.results[1]!.rows.map(passkeyOf).map(({ userId: _u, publicKey: _p, counter: _c, transports: _t, ...info }) => info) };
149
- }
150
-
151
- /** Whether the user has an authenticator app or a passkey. */
152
- async hasSecondFactor(userId: string): Promise<boolean> {
153
- const status = await this.status(userId);
154
- return status.totp || status.passkeys.length > 0;
155
- }
156
-
157
- /** Whether a code from the authenticator app is required at sign-in (passkeys sign in on their own). */
158
- async requiresCode(userId: string): Promise<boolean> {
159
- return (await this.status(userId)).totp;
160
- }
161
-
162
- /**
163
- * A new, unconfirmed authenticator secret. It takes effect once confirmed with a code. A
164
- * confirmed authenticator stays as it is: replacing it means turning it off first, which
165
- * asks for one of its codes, so starting a setup never removes the factor in use.
166
- */
167
- async startTotp(userId: string): Promise<string> {
168
- const secret = generateTotpSecret();
169
- const now = this.#now();
170
- const result = await this.#db.write([
171
- { rql: 'INSERT INTO cms_user_security (user_id, totp_secret, totp_confirmed_at, totp_last_step, recovery, updated_at) VALUES ($user, $secret, NULL, NULL, NULL, $now) ON CONFLICT (user_id) DO NOTHING',
172
- params: { $user: userId, $secret: secret, $now: now } },
173
- { rql: 'UPDATE cms_user_security SET totp_secret = $secret, totp_last_step = NULL, updated_at = $now WHERE user_id = $user AND totp_confirmed_at IS NULL',
174
- params: { $user: userId, $secret: secret, $now: now } },
175
- ], WRITE);
176
- if (result.results[1]!.affected !== 1n) throw new CmsError('CMS_VALIDATION', 'An authenticator app is already on. Turn it off with one of its codes before setting up another.');
177
- return secret;
178
- }
179
-
180
- /** The pending or confirmed secret, for showing the QR code again while setting up. */
181
- async pendingSecret(userId: string): Promise<string | null> {
182
- const result = await this.#db.read([{ rql: 'SELECT totp_secret, totp_confirmed_at FROM cms_user_security WHERE user_id = $user', params: { $user: userId } }]);
183
- const row = result.results[0]!.rows[0];
184
- return row && row[0] && !row[1] ? row[0] as string : null;
185
- }
186
-
187
- /** Confirm the authenticator with a current code. Returns new recovery codes, shown once. */
188
- async confirmTotp(userId: string, code: string): Promise<string[]> {
189
- const secret = await this.pendingSecret(userId);
190
- if (!secret) throw new CmsError('CMS_VALIDATION', 'Start the authenticator setup again.');
191
- const step = await verifyTotp(secret, code, { now: this.#now() });
192
- if (step === null) throw new CmsError('CMS_VALIDATION', 'That code is not right. Check the time on your device and try again.', { fields: { code: 'is not right.' } });
193
- const codes = generateRecoveryCodes();
194
- const hashes = await Promise.all(codes.map(hashRecoveryCode));
195
- await this.#db.write([{
196
- rql: 'UPDATE cms_user_security SET totp_confirmed_at = $now, totp_last_step = $step, recovery = $recovery, updated_at = $now WHERE user_id = $user AND totp_secret = $secret',
197
- params: { $now: this.#now(), $step: step, $recovery: JSON.stringify(hashes), $user: userId, $secret: secret },
198
- }], WRITE);
199
- return codes;
200
- }
201
-
202
- /** New recovery codes, replacing the old ones. Needs a confirmed authenticator. */
203
- async regenerateRecoveryCodes(userId: string): Promise<string[]> {
204
- if (!(await this.status(userId)).totp) throw new CmsError('CMS_VALIDATION', 'Set up an authenticator app first.');
205
- const codes = generateRecoveryCodes();
206
- await this.#db.write([{ rql: 'UPDATE cms_user_security SET recovery = $recovery, updated_at = $now WHERE user_id = $user',
207
- params: { $recovery: JSON.stringify(await Promise.all(codes.map(hashRecoveryCode))), $now: this.#now(), $user: userId } }], WRITE);
208
- return codes;
209
- }
210
-
211
- async disableTotp(userId: string): Promise<void> {
212
- await this.#db.write([{ rql: 'DELETE FROM cms_user_security WHERE user_id = $user', params: { $user: userId } }], WRITE);
213
- }
214
-
215
- /**
216
- * Check a second-factor code: the authenticator's current code (each step once) or an
217
- * unused recovery code, which is used up.
218
- */
219
- async verifyCode(userId: string, code: string): Promise<'totp' | 'recovery' | null> {
220
- const result = await this.#db.read([{ rql: 'SELECT totp_secret, totp_confirmed_at, totp_last_step, recovery FROM cms_user_security WHERE user_id = $user', params: { $user: userId } }]);
221
- const row = result.results[0]!.rows[0];
222
- if (!row || !row[1]) return null;
223
- const last = row[2] === null ? null : Number(row[2] as bigint);
224
- const step = await verifyTotp(row[0] as string, code, { now: this.#now(), afterStep: last });
225
- if (step !== null) {
226
- // The step is recorded only if no other sign-in used it first.
227
- const update = await this.#db.write([{
228
- rql: 'UPDATE cms_user_security SET totp_last_step = $step WHERE user_id = $user AND (totp_last_step IS NULL OR totp_last_step < $step)',
229
- params: { $step: step, $user: userId },
230
- }], WRITE);
231
- return update.results[0]!.affected === 1n ? 'totp' : null;
232
- }
233
- const hashes = row[3] ? JSON.parse(row[3] as string) as string[] : [];
234
- const hash = await hashRecoveryCode(code);
235
- if (!hashes.includes(hash)) return null;
236
- const update = await this.#db.write([{ rql: 'UPDATE cms_user_security SET recovery = $next, updated_at = $now WHERE user_id = $user AND recovery = $current',
237
- params: { $next: JSON.stringify(hashes.filter(entry => entry !== hash)), $now: this.#now(), $user: userId, $current: row[3] as string } }], WRITE);
238
- return update.results[0]!.affected === 1n ? 'recovery' : null;
239
- }
240
-
241
- async passkeys(userId: string): Promise<StoredPasskeyRow[]> {
242
- const result = await this.#db.read([{ rql: `SELECT ${PASSKEY_COLUMNS} FROM cms_passkeys WHERE user_id = $user ORDER BY created_at LIMIT 50`, params: { $user: userId } }]);
243
- return result.results[0]!.rows.map(passkeyOf);
244
- }
245
-
246
- async passkey(id: string): Promise<StoredPasskeyRow | null> {
247
- if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,1024}$/.test(id)) return null;
248
- const result = await this.#db.read([{ rql: `SELECT ${PASSKEY_COLUMNS} FROM cms_passkeys WHERE id = $id`, params: { $id: id } }]);
249
- const row = result.results[0]!.rows[0];
250
- return row ? passkeyOf(row) : null;
251
- }
252
-
253
- async addPasskey(userId: string, passkey: { id: string; publicKey: string; counter: number; transports?: readonly string[]; deviceType?: string; backedUp?: boolean }, name: string): Promise<void> {
254
- const label = name.trim().slice(0, 80) || 'Passkey';
255
- if ((await this.passkeys(userId)).length >= 20) throw new CmsError('CMS_LIMIT', 'A user can have at most 20 passkeys.');
256
- try {
257
- await this.#db.write([{
258
- rql: `INSERT INTO cms_passkeys (id, user_id, name, public_key, counter, transports, device_type, backed_up, created_at) VALUES ($id, $user, $name, $key, $counter, $transports, $device, $backed, $now)`,
259
- params: { $id: passkey.id, $user: userId, $name: label, $key: passkey.publicKey, $counter: passkey.counter, $transports: passkey.transports ? JSON.stringify(passkey.transports) : null,
260
- $device: passkey.deviceType ?? null, $backed: passkey.backedUp ? 1 : 0, $now: this.#now() },
261
- }], WRITE);
262
- } catch (error) {
263
- if ((error as { code?: string }).code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'This passkey is already registered.', { cause: error });
264
- throw error;
265
- }
266
- }
267
-
268
- async renamePasskey(userId: string, id: string, name: string): Promise<void> {
269
- await this.#db.write([{ rql: 'UPDATE cms_passkeys SET name = $name WHERE id = $id AND user_id = $user', params: { $name: name.trim().slice(0, 80) || 'Passkey', $id: id, $user: userId } }], WRITE);
270
- }
271
-
272
- async removePasskey(userId: string, id: string): Promise<void> {
273
- await this.#db.write([{ rql: 'DELETE FROM cms_passkeys WHERE id = $id AND user_id = $user', params: { $id: id, $user: userId } }], WRITE);
274
- }
275
-
276
- /** Record a passkey sign-in; the counter only moves forward. */
277
- async usePasskey(id: string, counter: number): Promise<void> {
278
- await this.#db.write([{ rql: 'UPDATE cms_passkeys SET counter = $counter, last_used_at = $now WHERE id = $id', params: { $counter: counter, $now: this.#now(), $id: id } }], WRITE);
279
- }
280
-
281
- /** Remove every second factor, for a user who lost their device. */
282
- async reset(userId: string): Promise<void> {
283
- await this.#db.write([
284
- { rql: 'DELETE FROM cms_user_security WHERE user_id = $user', params: { $user: userId } },
285
- { rql: 'DELETE FROM cms_passkeys WHERE user_id = $user', params: { $user: userId } },
286
- ], WRITE);
287
- }
288
-
289
- /** A challenge kept for `ttlMs`; its random ID goes into a cookie or form. */
290
- async createChallenge(kind: ChallengeKind, userId: string | null, challenge: string, ttlMs = 5 * 60_000): Promise<string> {
291
- const id = randomToken(24);
292
- await this.#db.write([{ rql: 'INSERT INTO cms_auth_challenges (id, kind, user_id, challenge, attempts, expires_at) VALUES ($id, $kind, $user, $challenge, 0, $expires)',
293
- params: { $id: id, $kind: kind, $user: userId, $challenge: challenge, $expires: this.#now() + ttlMs } }], WRITE);
294
- return id;
295
- }
296
-
297
- /** A live challenge of the kind, without using it up. */
298
- async challenge(id: string, kind: ChallengeKind): Promise<{ userId: string | null; challenge: string; attempts: number } | null> {
299
- if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{20,64}$/.test(id)) return null;
300
- const result = await this.#db.read([{ rql: 'SELECT user_id, challenge, attempts, expires_at FROM cms_auth_challenges WHERE id = $id AND kind = $kind', params: { $id: id, $kind: kind } }]);
301
- const row = result.results[0]!.rows[0];
302
- if (!row || Number(row[3] as bigint) <= this.#now()) return null;
303
- return { userId: row[0] as string | null, challenge: row[1] as string, attempts: Number(row[2] as bigint) };
304
- }
305
-
306
- /** Use up a challenge: true only for the first caller while it is live. */
307
- async takeChallenge(id: string, kind: ChallengeKind): Promise<boolean> {
308
- const result = await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id = $id AND kind = $kind AND expires_at > $now', params: { $id: id, $kind: kind, $now: this.#now() } }], WRITE);
309
- return result.results[0]!.affected === 1n;
310
- }
311
-
312
- /**
313
- * Spend one try of a pending sign-in before its code is checked: counted on the challenge
314
- * (in a conditional write, so codes sent at once each take a try and no more than
315
- * `SIGN_IN_ATTEMPTS` are checked) and on the account (`SECOND_FACTOR_LOCK`). `expired` when
316
- * the challenge has no tries left or ended, `locked` when the account has used its codes.
317
- */
318
- async secondFactorAttempt(id: string, userId: string): Promise<{ left: number } | 'expired' | 'locked'> {
319
- const now = this.#now();
320
- const counted = await this.#db.write([{ rql: 'UPDATE cms_auth_challenges SET attempts = attempts + 1 WHERE id = $id AND kind = $kind AND user_id = $user AND attempts < $max AND expires_at > $now',
321
- params: { $id: id, $kind: 'signin', $user: userId, $max: SIGN_IN_ATTEMPTS, $now: now } }], WRITE);
322
- if (counted.results[0]!.affected !== 1n) return 'expired';
323
- if (!(await this.#count(secondFactorKey(userId), SECOND_FACTOR_LOCK.windowMs, SECOND_FACTOR_LOCK.perAccount))) {
324
- await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id = $id', params: { $id: id } }], WRITE);
325
- return 'locked';
326
- }
327
- const live = await this.#db.read([{ rql: 'SELECT attempts FROM cms_auth_challenges WHERE id = $id', params: { $id: id } }]);
328
- const row = live.results[0]!.rows[0];
329
- return { left: row ? SIGN_IN_ATTEMPTS - Number(row[0] as bigint) : 0 };
330
- }
331
-
332
- /**
333
- * Spend one of the account's code tries outside a sign-in (turning the authenticator off,
334
- * new recovery codes): the same per-account count as `secondFactorAttempt`, so codes cannot
335
- * be guessed faster on the security page than at sign-in. False when the account is locked.
336
- */
337
- async codeAttempt(userId: string): Promise<boolean> {
338
- return this.#count(secondFactorKey(userId), SECOND_FACTOR_LOCK.windowMs, SECOND_FACTOR_LOCK.perAccount);
339
- }
340
-
341
- /** A wrong code: the challenge ends once it has no tries left. */
342
- async failChallenge(id: string): Promise<void> {
343
- await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id = $id AND attempts >= $max', params: { $id: id, $max: SIGN_IN_ATTEMPTS } }], WRITE);
344
- }
345
-
346
- /** A right code: the account's second-factor count starts again. */
347
- async secondFactorSucceeded(userId: string): Promise<void> {
348
- await this.#db.write([{ rql: 'DELETE FROM cms_attempts WHERE key = $key', params: { $key: secondFactorKey(userId) } }], WRITE);
349
- }
350
-
351
- async purgeExpired(): Promise<void> {
352
- const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_auth_challenges WHERE expires_at <= $now LIMIT 1', params: { $now: this.#now() } }]);
353
- if (!expired.results[0]!.rows.length) return;
354
- await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id IN (SELECT id FROM cms_auth_challenges WHERE expires_at <= $now LIMIT 500)', params: { $now: this.#now() } }], WRITE);
355
- }
356
-
357
- /** Remove attempt counts whose window ended (500 at a time), which nothing else would. */
358
- async purgeAttempts(): Promise<void> {
359
- const now = this.#now();
360
- const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_attempts WHERE until <= $now LIMIT 1', params: { $now: now } }]);
361
- if (!expired.results[0]!.rows.length) return;
362
- await this.#db.write([{ rql: 'DELETE FROM cms_attempts WHERE key IN (SELECT key FROM cms_attempts WHERE until <= $now LIMIT 500)', params: { $now: now } }], WRITE);
363
- }
364
- }
365
-
366
- function passkeyOf(row: readonly Value[]): StoredPasskeyRow {
367
- return Object.freeze({
368
- id: row[0] as string, userId: row[1] as string, name: row[2] as string, publicKey: row[3] as string, counter: Number(row[4] as bigint),
369
- transports: row[5] ? JSON.parse(row[5] as string) as string[] : null, deviceType: row[6] as string | null, backedUp: Number(row[7] as bigint) === 1,
370
- createdAt: Number(row[8] as bigint), lastUsedAt: row[9] === null ? null : Number(row[9] as bigint),
371
- });
372
- }
373
-
374
- /** The sign-in counter of an email: hashed, lower-cased. */
375
- async function emailKey(email: string): Promise<string> {
376
- return `signin:e:${await sha256Hex(email.trim().toLowerCase())}`;
377
- }
378
-
379
- /** The second-factor counter of an account. */
380
- function secondFactorKey(userId: string): string {
381
- return `signin:2fa:${userId.replace(/[^\x21-\x7e]/g, '-').slice(0, 100)}`;
382
- }
383
-
384
- /** The sign-in counter of a client address. */
385
- function addressKey(address: string): string {
386
- return `signin:a:${(address || 'unknown').replace(/[^\x21-\x7e]/g, '-').slice(0, 100)}`;
387
- }
388
-
389
- function attemptKey(kind: string, key: string): string {
390
- return `attempt:${kind}:${key.replace(/[^\x21-\x7e]/g, '-').slice(0, 120)}`;
391
- }