@jskit-ai/auth-provider-local-db-core 0.1.157 → 0.1.159

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.
@@ -1,33 +1,33 @@
1
+ import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
1
2
  import { isDuplicateEntryError } from "@jskit-ai/database-runtime/shared/duplicateEntry";
3
+ import { ConflictError } from "@jskit-ai/kernel/server/runtime/errors";
4
+ import { passedOn } from "@jskit-ai/resource-runtime/server";
5
+ import { nowIso, toDate } from "./dateTimes.js";
6
+ import { IDENTITIES_TABLE } from "./identityStore.js";
2
7
 
3
8
  const TABLES = Object.freeze({
4
9
  users: "auth_local_users",
5
10
  sessions: "auth_local_sessions",
6
11
  recovery: "auth_local_recovery",
7
- identities: "auth_local_identities",
12
+ identities: IDENTITIES_TABLE,
8
13
  oauthAttempts: "auth_local_oauth_attempts",
9
14
  signInFailures: "auth_local_sign_in_failures",
10
15
  registrations: "auth_local_registrations"
11
16
  });
12
17
 
13
- function nowIso() {
14
- return new Date().toISOString();
15
- }
18
+ // The tables local sign-in keeps outside table resources, for an app test's expectEveryTableOwned infrastructureTables.
19
+ const INFRASTRUCTURE_TABLES = Object.freeze([IDENTITIES_TABLE]);
16
20
 
17
- function toDate(value) {
18
- const date = value instanceof Date ? value : new Date(value);
19
- if (Number.isNaN(date.getTime())) {
20
- throw new TypeError("Invalid local auth DB timestamp.");
21
- }
22
- return date;
23
- }
21
+ // One page of one record: a lookup by a unique field.
22
+ const FIRST = Object.freeze({ size: 1 });
24
23
 
24
+ // The ISO text written for a required timestamp: the value, or the fallback (now) when it has none.
25
25
  function requiredDateTime(value, fallback = nowIso()) {
26
- return toDate(value || fallback);
26
+ return toDate(value || fallback).toISOString();
27
27
  }
28
28
 
29
29
  function optionalDateTime(value) {
30
- return value ? toDate(value) : null;
30
+ return value ? toDate(value).toISOString() : null;
31
31
  }
32
32
 
33
33
  function readDateTime(value, fallback = "") {
@@ -37,431 +37,583 @@ function readDateTime(value, fallback = "") {
37
37
  return toDate(value).toISOString();
38
38
  }
39
39
 
40
- function readPassword(row) {
41
- return {
42
- algorithm: String(row.password_algorithm || ""),
43
- version: String(row.password_version || ""),
44
- salt: String(row.password_salt || ""),
45
- hash: String(row.password_hash || "")
46
- };
40
+ function text(value) {
41
+ return String(value || "");
47
42
  }
48
43
 
49
- function writePassword(password = {}) {
44
+ // A session's conditional update compares only whose session it is and where it stands.
45
+ const SESSION_CONDITIONS = Object.freeze(["userId", "purpose", "revokedAt"]);
46
+
47
+ function requireSessionConditions(onlyIf) {
48
+ if (!onlyIf || typeof onlyIf !== "object" || Array.isArray(onlyIf) || Object.keys(onlyIf).length < 1 ||
49
+ Object.keys(onlyIf).some((key) => !SESSION_CONDITIONS.includes(key))) {
50
+ throw new TypeError(`auth.local.sessions.update() takes onlyIf with ${SESSION_CONDITIONS.join(", ")} only.`);
51
+ }
52
+ }
53
+
54
+ // A user's recovery tokens are of a kind by the start of their ids: a password reset's are `rec_`, an app's own
55
+ // kinds (such as a sign-in link) have prefixes of their own.
56
+ function requireIdPrefix(idPrefix) {
57
+ if (typeof idPrefix !== "string" || !idPrefix) {
58
+ throw new TypeError("auth.local.recovery.consumeForUser() takes the idPrefix of the tokens it consumes, such as \"rec_\".");
59
+ }
60
+ }
61
+
62
+ function readPassword(record) {
50
63
  return {
51
- password_algorithm: String(password.algorithm || ""),
52
- password_version: String(password.version || ""),
53
- password_salt: String(password.salt || ""),
54
- password_hash: String(password.hash || "")
64
+ algorithm: text(record.passwordAlgorithm),
65
+ version: text(record.passwordVersion),
66
+ salt: text(record.passwordSalt),
67
+ hash: text(record.passwordHash)
55
68
  };
56
69
  }
57
70
 
58
- function mapUser(row) {
59
- if (!row) {
60
- return null;
61
- }
71
+ function writePassword(password = {}) {
62
72
  return {
63
- id: String(row.id || ""),
64
- email: String(row.email || ""),
65
- displayName: String(row.display_name || ""),
66
- password: readPassword(row),
67
- createdAt: readDateTime(row.created_at),
68
- updatedAt: readDateTime(row.updated_at),
69
- disabled: row.disabled === true || row.disabled === 1 || row.disabled === "1"
73
+ passwordAlgorithm: text(password.algorithm),
74
+ passwordVersion: text(password.version),
75
+ passwordSalt: text(password.salt),
76
+ passwordHash: text(password.hash)
70
77
  };
71
78
  }
72
79
 
73
- function mapSession(row) {
74
- if (!row) {
80
+ function mapUser(record) {
81
+ if (!record) {
75
82
  return null;
76
83
  }
77
84
  return {
78
- id: String(row.id || ""),
79
- userId: String(row.user_id || ""),
80
- tokenHash: String(row.token_hash || ""),
81
- purpose: String(row.purpose || "normal"),
82
- createdAt: readDateTime(row.created_at),
83
- expiresAt: readDateTime(row.expires_at),
84
- revokedAt: readDateTime(row.revoked_at)
85
+ id: text(record.id),
86
+ email: text(record.email),
87
+ displayName: text(record.displayName),
88
+ password: readPassword(record),
89
+ createdAt: readDateTime(record.createdAt),
90
+ updatedAt: readDateTime(record.updatedAt),
91
+ emailVerifiedAt: readDateTime(record.emailVerifiedAt),
92
+ disabled: record.disabled === true || record.disabled === 1 || record.disabled === "1"
85
93
  };
86
94
  }
87
95
 
88
- function mapRecovery(row) {
89
- if (!row) {
96
+ function mapSession(record) {
97
+ if (!record) {
90
98
  return null;
91
99
  }
92
100
  return {
93
- id: String(row.id || ""),
94
- userId: String(row.user_id || ""),
95
- tokenHash: String(row.token_hash || ""),
96
- createdAt: readDateTime(row.created_at),
97
- expiresAt: readDateTime(row.expires_at),
98
- usedAt: readDateTime(row.used_at)
101
+ id: text(record.id),
102
+ userId: text(record.userId),
103
+ tokenHash: text(record.tokenHash),
104
+ purpose: String(record.purpose || "normal"),
105
+ createdAt: readDateTime(record.createdAt),
106
+ expiresAt: readDateTime(record.expiresAt),
107
+ revokedAt: readDateTime(record.revokedAt)
99
108
  };
100
109
  }
101
110
 
102
- function mapIdentity(row) {
103
- if (!row) {
111
+ function mapRecovery(record) {
112
+ if (!record) {
104
113
  return null;
105
114
  }
106
115
  return {
107
- userId: String(row.user_id || ""),
108
- provider: String(row.provider || ""),
109
- providerSubject: String(row.provider_subject || ""),
110
- email: String(row.email || ""),
111
- createdAt: readDateTime(row.created_at)
116
+ id: text(record.id),
117
+ userId: text(record.userId),
118
+ tokenHash: text(record.tokenHash),
119
+ createdAt: readDateTime(record.createdAt),
120
+ expiresAt: readDateTime(record.expiresAt),
121
+ usedAt: readDateTime(record.usedAt)
112
122
  };
113
123
  }
114
124
 
115
- function mapOAuthAttempt(row) {
116
- if (!row) {
125
+ function mapOAuthAttempt(record) {
126
+ if (!record) {
117
127
  return null;
118
128
  }
119
129
  return {
120
- browserKeyHash: String(row.browser_key_hash || ""),
121
- provider: String(row.provider || ""),
122
- intent: String(row.intent || ""),
123
- userId: String(row.user_id || ""),
124
- state: String(row.state || ""),
125
- nonce: String(row.nonce || ""),
126
- codeVerifier: String(row.code_verifier || ""),
127
- returnTo: String(row.return_to || ""),
128
- createdAt: readDateTime(row.created_at),
129
- expiresAt: readDateTime(row.expires_at)
130
+ browserKeyHash: text(record.id),
131
+ provider: text(record.provider),
132
+ intent: text(record.intent),
133
+ userId: text(record.userId),
134
+ state: text(record.state),
135
+ nonce: text(record.nonce),
136
+ codeVerifier: text(record.codeVerifier),
137
+ returnTo: text(record.returnTo),
138
+ createdAt: readDateTime(record.createdAt),
139
+ expiresAt: readDateTime(record.expiresAt)
130
140
  };
131
141
  }
132
142
 
133
- function mapSignInFailures(row) {
134
- if (!row) {
143
+ function mapSignInFailures(record) {
144
+ if (!record) {
135
145
  return null;
136
146
  }
137
147
  return {
138
- email: String(row.email || ""),
139
- failures: Number(row.failures || 0),
140
- lastFailedAt: readDateTime(row.last_failed_at),
141
- lockedUntil: readDateTime(row.locked_until)
148
+ email: text(record.id),
149
+ failures: Number(record.failures || 0),
150
+ lastFailedAt: readDateTime(record.lastFailedAt),
151
+ lockedUntil: readDateTime(record.lockedUntil)
142
152
  };
143
153
  }
144
154
 
145
- function mapRegistration(row) {
146
- if (!row) {
155
+ function mapRegistration(record) {
156
+ if (!record) {
147
157
  return null;
148
158
  }
149
- const invitationToken = String(row.invitation_token || "");
159
+ const invitationToken = text(record.invitationToken);
150
160
  return {
151
- email: String(row.email || ""),
152
- displayName: String(row.display_name || ""),
153
- password: readPassword(row),
154
- invitation: invitationToken ? { token: invitationToken, source: String(row.invitation_source || "") } : null,
155
- tokenHash: String(row.token_hash || ""),
156
- createdAt: readDateTime(row.created_at),
157
- expiresAt: readDateTime(row.expires_at)
161
+ email: text(record.id),
162
+ displayName: text(record.displayName),
163
+ password: readPassword(record),
164
+ invitation: invitationToken ? { token: invitationToken, source: text(record.invitationSource) } : null,
165
+ tokenHash: text(record.tokenHash),
166
+ createdAt: readDateTime(record.createdAt),
167
+ expiresAt: readDateTime(record.expiresAt)
158
168
  };
159
169
  }
160
170
 
161
- function registrationRow(record = {}) {
171
+ function registrationRecord(input = {}) {
162
172
  return {
163
- email: String(record.email || ""),
164
- display_name: String(record.displayName || ""),
165
- ...writePassword(record.password),
166
- invitation_token: record.invitation?.token ? String(record.invitation.token) : null,
167
- invitation_source: record.invitation?.token ? String(record.invitation.source || "") : null,
168
- token_hash: String(record.tokenHash || ""),
169
- created_at: requiredDateTime(record.createdAt),
170
- expires_at: requiredDateTime(record.expiresAt)
173
+ displayName: text(input.displayName),
174
+ ...writePassword(input.password),
175
+ invitationToken: input.invitation?.token ? String(input.invitation.token) : null,
176
+ invitationSource: input.invitation?.token ? text(input.invitation.source) : null,
177
+ tokenHash: text(input.tokenHash),
178
+ createdAt: requiredDateTime(input.createdAt),
179
+ expiresAt: requiredDateTime(input.expiresAt)
171
180
  };
172
181
  }
173
182
 
174
- function userInsert(input = {}) {
183
+ function userRecord(input = {}) {
175
184
  const createdAt = requiredDateTime(input.createdAt);
176
185
  return {
177
- id: String(input.id || ""),
178
- email: String(input.email || ""),
179
- display_name: String(input.displayName || ""),
186
+ id: text(input.id),
187
+ email: text(input.email),
188
+ displayName: text(input.displayName),
180
189
  ...writePassword(input.password),
181
190
  disabled: input.disabled === true,
182
- created_at: createdAt,
183
- updated_at: requiredDateTime(input.updatedAt, createdAt)
191
+ createdAt,
192
+ updatedAt: requiredDateTime(input.updatedAt, createdAt)
184
193
  };
185
194
  }
186
195
 
187
- function sessionInsert(input = {}) {
196
+ function sessionRecord(input = {}) {
188
197
  const createdAt = requiredDateTime(input.createdAt);
189
198
  return {
190
- id: String(input.id || ""),
191
- user_id: String(input.userId || ""),
192
- token_hash: String(input.tokenHash || ""),
199
+ id: text(input.id),
200
+ userId: text(input.userId),
201
+ tokenHash: text(input.tokenHash),
193
202
  purpose: String(input.purpose || "normal"),
194
- expires_at: requiredDateTime(input.expiresAt),
195
- revoked_at: optionalDateTime(input.revokedAt),
196
- created_at: createdAt,
197
- updated_at: requiredDateTime(input.updatedAt, createdAt)
203
+ expiresAt: requiredDateTime(input.expiresAt),
204
+ revokedAt: optionalDateTime(input.revokedAt),
205
+ createdAt,
206
+ updatedAt: requiredDateTime(input.updatedAt, createdAt)
198
207
  };
199
208
  }
200
209
 
201
- function recoveryInsert(input = {}) {
210
+ function recoveryRecord(input = {}) {
202
211
  const createdAt = requiredDateTime(input.createdAt);
203
212
  return {
204
- id: String(input.id || ""),
205
- user_id: String(input.userId || ""),
206
- token_hash: String(input.tokenHash || ""),
207
- expires_at: requiredDateTime(input.expiresAt),
208
- used_at: optionalDateTime(input.usedAt),
209
- created_at: createdAt,
210
- updated_at: requiredDateTime(input.updatedAt, createdAt)
213
+ id: text(input.id),
214
+ userId: text(input.userId),
215
+ tokenHash: text(input.tokenHash),
216
+ expiresAt: requiredDateTime(input.expiresAt),
217
+ usedAt: optionalDateTime(input.usedAt),
218
+ createdAt,
219
+ updatedAt: requiredDateTime(input.updatedAt, createdAt)
220
+ };
221
+ }
222
+
223
+ function oauthAttemptRecord(input = {}) {
224
+ return {
225
+ id: text(input.browserKeyHash),
226
+ provider: text(input.provider),
227
+ intent: text(input.intent),
228
+ userId: input.userId ? String(input.userId) : null,
229
+ state: text(input.state),
230
+ nonce: text(input.nonce),
231
+ codeVerifier: text(input.codeVerifier),
232
+ returnTo: text(input.returnTo),
233
+ expiresAt: requiredDateTime(input.expiresAt),
234
+ createdAt: requiredDateTime(input.createdAt)
211
235
  };
212
236
  }
213
237
 
214
238
  /**
215
- * The `auth.local.backend` that keeps local auth's records in the database.
216
- * @param {object} dependencies
217
- * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} dependencies.knex
218
- * @param {import("@jskit-ai/database-runtime/server/types").RuntimeTransactionManager} dependencies.transactionManager
239
+ * The record a unique field's value finds, or null; an empty value finds none.
240
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
241
+ * @param {string} field
242
+ * @param {unknown} value
243
+ * @param {object} options
219
244
  */
220
- function createLocalDbBackend({ knex, transactionManager }) {
221
- function table(client, tableName) {
222
- return client(tableName);
245
+ async function findOne(handle, field, value, options) {
246
+ const wanted = text(value);
247
+ if (!wanted) {
248
+ return null;
223
249
  }
250
+ const { records } = await handle.query({ filters: { [field]: wanted }, page: FIRST }, options);
251
+ return records[0] || null;
252
+ }
224
253
 
225
- function createTx(client) {
226
- return Object.freeze({
227
- users: Object.freeze({
228
- async create(input) {
229
- const row = userInsert(input);
230
- try {
231
- await table(client, TABLES.users).insert(row);
232
- } catch (error) {
233
- if (isDuplicateEntryError(error, { client: knex })) {
234
- throw new Error("Local auth user already exists.");
235
- }
236
- throw error;
237
- }
238
- return mapUser(row);
239
- },
240
- async findById(userId) {
241
- return mapUser(await table(client, TABLES.users).where({ id: String(userId || "") }).first());
242
- },
243
- async findByEmail(email) {
244
- return mapUser(await table(client, TABLES.users).where({ email: String(email || "") }).first());
245
- },
246
- async hasAny() {
247
- return Boolean(await table(client, TABLES.users).first("id"));
248
- },
249
- async updatePassword(userId, passwordRecord) {
250
- const updatedAt = requiredDateTime();
251
- await table(client, TABLES.users)
252
- .where({ id: String(userId || "") })
253
- .update({
254
- ...writePassword(passwordRecord),
255
- updated_at: updatedAt
256
- });
257
- return mapUser(await table(client, TABLES.users).where({ id: String(userId || "") }).first());
258
- },
259
- async updateProfile(userId, updates = {}) {
260
- const patch = {
261
- updated_at: requiredDateTime()
262
- };
263
- if (typeof updates.displayName === "string") {
264
- patch.display_name = updates.displayName;
265
- }
266
- await table(client, TABLES.users).where({ id: String(userId || "") }).update(patch);
267
- return mapUser(await table(client, TABLES.users).where({ id: String(userId || "") }).first());
268
- }
269
- }),
270
- sessions: Object.freeze({
271
- async create(input) {
272
- const row = sessionInsert(input);
273
- await table(client, TABLES.sessions).insert(row);
274
- return mapSession(row);
275
- },
276
- async findById(sessionId) {
277
- return mapSession(await table(client, TABLES.sessions).where({ id: String(sessionId || "") }).first());
278
- },
279
- async findByTokenHash(tokenHash) {
280
- return mapSession(await table(client, TABLES.sessions).where({ token_hash: String(tokenHash || "") }).first());
281
- },
282
- async revoke(sessionId) {
283
- const existing = await table(client, TABLES.sessions).where({ id: String(sessionId || "") }).first();
284
- if (!existing || existing.revoked_at) {
285
- return mapSession(existing);
286
- }
287
- const updatedAt = requiredDateTime();
288
- await table(client, TABLES.sessions)
289
- .where({ id: String(sessionId || "") })
290
- .update({
291
- revoked_at: updatedAt,
292
- updated_at: updatedAt
293
- });
294
- return mapSession(await table(client, TABLES.sessions).where({ id: String(sessionId || "") }).first());
295
- },
296
- async revokeForUser(userId, options = {}) {
297
- const query = table(client, TABLES.sessions)
298
- .where({ user_id: String(userId || "") })
299
- .whereNull("revoked_at");
300
- const exceptSessionId = String(options.exceptSessionId || "");
301
- if (exceptSessionId) {
302
- query.whereNot("id", exceptSessionId);
303
- }
304
- const updatedAt = requiredDateTime();
305
- const count = await query.update({
306
- revoked_at: updatedAt,
307
- updated_at: updatedAt
308
- });
309
- return Number(count || 0);
310
- }
311
- }),
312
- recovery: Object.freeze({
313
- async create(input) {
314
- const row = recoveryInsert(input);
315
- await table(client, TABLES.recovery).insert(row);
316
- return mapRecovery(row);
317
- },
318
- async findByTokenHash(tokenHash) {
319
- return mapRecovery(await table(client, TABLES.recovery).where({ token_hash: String(tokenHash || "") }).first());
320
- },
321
- async consume(tokenId) {
322
- const existing = await table(client, TABLES.recovery).where({ id: String(tokenId || "") }).first();
323
- if (!existing || existing.used_at) {
324
- return mapRecovery(existing);
325
- }
326
- const updatedAt = requiredDateTime();
327
- await table(client, TABLES.recovery)
328
- .where({ id: String(tokenId || "") })
329
- .update({
330
- used_at: updatedAt,
331
- updated_at: updatedAt
332
- });
333
- return mapRecovery(await table(client, TABLES.recovery).where({ id: String(tokenId || "") }).first());
334
- },
335
- async consumeForUser(userId) {
336
- const updatedAt = requiredDateTime();
337
- const count = await table(client, TABLES.recovery)
338
- .where({ user_id: String(userId || "") })
339
- .whereNull("used_at")
340
- .update({
341
- used_at: updatedAt,
342
- updated_at: updatedAt
343
- });
344
- return Number(count || 0);
345
- }
346
- }),
347
- identities: Object.freeze({
348
- async create(input) {
349
- const row = {
350
- user_id: String(input.userId || ""),
351
- provider: String(input.provider || ""),
352
- provider_subject: String(input.providerSubject || ""),
353
- email: String(input.email || ""),
354
- created_at: requiredDateTime(input.createdAt)
355
- };
356
- await table(client, TABLES.identities).insert(row);
357
- return mapIdentity(row);
358
- },
359
- async findByProviderSubject(provider, providerSubject) {
360
- return mapIdentity(await table(client, TABLES.identities)
361
- .where({ provider: String(provider || ""), provider_subject: String(providerSubject || "") })
362
- .first());
363
- },
364
- async listForUser(userId) {
365
- const rows = await table(client, TABLES.identities).where({ user_id: String(userId || "") });
366
- return rows.map(mapIdentity);
367
- },
368
- async deleteForUser(userId, provider) {
369
- const count = await table(client, TABLES.identities)
370
- .where({ user_id: String(userId || ""), provider: String(provider || "") })
371
- .delete();
372
- return Number(count || 0);
373
- }
374
- }),
375
- oauthAttempts: Object.freeze({
376
- async create(input) {
377
- const row = {
378
- browser_key_hash: String(input.browserKeyHash || ""),
379
- provider: String(input.provider || ""),
380
- intent: String(input.intent || ""),
381
- user_id: input.userId ? String(input.userId) : null,
382
- state: String(input.state || ""),
383
- nonce: String(input.nonce || ""),
384
- code_verifier: String(input.codeVerifier || ""),
385
- return_to: String(input.returnTo || ""),
386
- expires_at: requiredDateTime(input.expiresAt),
387
- created_at: requiredDateTime(input.createdAt)
388
- };
389
- await table(client, TABLES.oauthAttempts).insert(row);
390
- return mapOAuthAttempt(row);
391
- },
392
- // Only the request whose delete removes the row gets the attempt, so
393
- // concurrent callbacks on several servers cannot both use it.
394
- async take(browserKeyHash) {
395
- const where = { browser_key_hash: String(browserKeyHash || "") };
396
- const row = await table(client, TABLES.oauthAttempts).where(where).first();
397
- if (!row) {
398
- return null;
399
- }
400
- const count = await table(client, TABLES.oauthAttempts).where(where).delete();
401
- return Number(count || 0) === 1 ? mapOAuthAttempt(row) : null;
402
- },
403
- async deleteExpired(now) {
404
- const count = await table(client, TABLES.oauthAttempts)
405
- .where("expires_at", "<=", requiredDateTime(now))
406
- .delete();
407
- return Number(count || 0);
408
- }
409
- }),
410
- signInFailures: Object.freeze({
411
- async find(email) {
412
- return mapSignInFailures(await table(client, TABLES.signInFailures).where({ email: String(email || "") }).first());
413
- },
414
- async save(record) {
415
- const row = {
416
- email: String(record.email || ""),
417
- failures: Number(record.failures || 0),
418
- last_failed_at: requiredDateTime(record.lastFailedAt),
419
- locked_until: optionalDateTime(record.lockedUntil)
420
- };
421
- await table(client, TABLES.signInFailures).insert(row).onConflict("email").merge();
422
- return mapSignInFailures(row);
423
- },
424
- async clear(email) {
425
- const count = await table(client, TABLES.signInFailures).where({ email: String(email || "") }).delete();
426
- return Number(count || 0);
427
- },
428
- async deleteBefore(lastFailedAt) {
429
- const count = await table(client, TABLES.signInFailures)
430
- .where("last_failed_at", "<", requiredDateTime(lastFailedAt))
431
- .delete();
432
- return Number(count || 0);
433
- }
434
- }),
435
- registrations: Object.freeze({
436
- async save(record) {
437
- const row = registrationRow(record);
438
- await table(client, TABLES.registrations).insert(row).onConflict("email").merge();
439
- return mapRegistration(row);
440
- },
441
- async findByEmail(email) {
442
- return mapRegistration(await table(client, TABLES.registrations).where({ email: String(email || "") }).first());
443
- },
444
- async findByTokenHash(tokenHash) {
445
- return mapRegistration(await table(client, TABLES.registrations)
446
- .where({ token_hash: String(tokenHash || "") })
447
- .first());
448
- },
449
- async delete(email) {
450
- const count = await table(client, TABLES.registrations).where({ email: String(email || "") }).delete();
451
- return Number(count || 0);
452
- },
453
- async deleteExpired(now) {
454
- const count = await table(client, TABLES.registrations)
455
- .where("expires_at", "<=", requiredDateTime(now))
456
- .delete();
457
- return Number(count || 0);
458
- }
459
- })
460
- });
254
+ /**
255
+ * The record with this id, or null; an empty id finds none.
256
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
257
+ * @param {unknown} id
258
+ * @param {object} options
259
+ */
260
+ async function findById(handle, id, options) {
261
+ const wanted = text(id);
262
+ return wanted ? handle.get(wanted, {}, { ...options, missing: "skip" }) : null;
263
+ }
264
+
265
+ /**
266
+ * Deletes the record with this id and answers 1, or 0 when it is missing: one DELETE, so of two concurrent deletes
267
+ * only one answers 1.
268
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
269
+ * @param {unknown} id
270
+ * @param {object} options
271
+ */
272
+ async function deleteById(handle, id, options) {
273
+ const wanted = text(id);
274
+ return wanted && (await handle.delete(wanted, { ...options, missing: "skip" })) !== null ? 1 : 0;
275
+ }
276
+
277
+ /**
278
+ * Writes an email's sign-in failure record: patches it when it exists, creates it otherwise. An upsert keyed on the
279
+ * email would keep the later of two first failures counted at once, so they would count once; this create instead
280
+ * fails the later one with a duplicate entry, and the backend runs that sign-in again on the row the first one made.
281
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} failures
282
+ * @param {string} email
283
+ * @param {Record<string, unknown>} attributes
284
+ * @param {object} options
285
+ */
286
+ async function replaceFailures(failures, email, attributes, options) {
287
+ if (await failures.get(email, {}, { ...options, missing: "skip" })) {
288
+ await failures.patch(email, attributes, { ...options, returning: "none" });
289
+ } else {
290
+ await failures.create({ id: email, ...attributes }, { ...options, returning: "none" });
461
291
  }
292
+ }
293
+
294
+ /**
295
+ * Patches an existing record and answers it after the change; null when it is missing, which fails no transaction.
296
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
297
+ * @param {unknown} id
298
+ * @param {Record<string, unknown>} changes
299
+ * @param {object} options
300
+ */
301
+ async function patchExisting(handle, id, changes, options) {
302
+ const wanted = text(id);
303
+ return wanted ? handle.patch(wanted, changes, { ...options, missing: "skip" }) : null;
304
+ }
305
+
306
+ /**
307
+ * Local auth's accounts.
308
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} users
309
+ * @param {object} options
310
+ */
311
+ function userRecords(users, options) {
312
+ return Object.freeze({
313
+ async create(input) {
314
+ const record = userRecord(input);
315
+ try {
316
+ await users.create(record, { ...options, returning: "none" });
317
+ } catch (error) {
318
+ if (isDuplicateEntryError(error)) {
319
+ throw new ConflictError("An account with this id or email already exists.", { code: "auth.local.accounts.exists", cause: error });
320
+ }
321
+ throw error;
322
+ }
323
+ return mapUser(record);
324
+ },
325
+ async findById(userId) {
326
+ return mapUser(await findById(users, userId, options));
327
+ },
328
+ async findByEmail(email) {
329
+ return mapUser(await findOne(users, "email", email, options));
330
+ },
331
+ async hasAny() {
332
+ return (await users.query({ page: FIRST }, options)).records.length > 0;
333
+ },
334
+ async updatePassword(userId, passwordRecord) {
335
+ return mapUser(await patchExisting(users, userId, { ...writePassword(passwordRecord), updatedAt: requiredDateTime() }, options));
336
+ },
337
+ async updateProfile(userId, updates = {}) {
338
+ const changes = { updatedAt: requiredDateTime() };
339
+ if (typeof updates.displayName === "string") {
340
+ changes.displayName = updates.displayName;
341
+ }
342
+ return mapUser(await patchExisting(users, userId, changes, options));
343
+ },
344
+ // Using an emailed link proves the account owns its email address; the first proof is kept.
345
+ async markEmailVerified(userId) {
346
+ const id = text(userId);
347
+ if (!id) {
348
+ return null;
349
+ }
350
+ await users.patch(id, { emailVerifiedAt: requiredDateTime() }, { ...options, onlyIf: { emailVerifiedAt: null }, missing: "skip", returning: "none" });
351
+ return mapUser(await users.get(id, {}, { ...options, missing: "skip" }));
352
+ }
353
+ });
354
+ }
355
+
356
+ /**
357
+ * Local auth's sessions.
358
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} sessions
359
+ * @param {object} options
360
+ */
361
+ function sessionRecords(sessions, options) {
362
+ return Object.freeze({
363
+ async create(input) {
364
+ const record = sessionRecord(input);
365
+ await sessions.create(record, { ...options, returning: "none" });
366
+ return mapSession(record);
367
+ },
368
+ async findById(sessionId) {
369
+ return mapSession(await findById(sessions, sessionId, options));
370
+ },
371
+ async findByTokenHash(tokenHash) {
372
+ return mapSession(await findOne(sessions, "tokenHash", tokenHash, options));
373
+ },
374
+ // Only a session's purpose and expiry change, as when a magic-link session becomes a normal one.
375
+ // updateOptions.onlyIf changes it only while it still has those values (userId, purpose, revokedAt: null), in
376
+ // the UPDATE itself: a session that is missing or no longer matches answers null, with nothing written.
377
+ async update(sessionId, { purpose, expiresAt, ...rest } = {}, { onlyIf } = {}) {
378
+ if (Object.keys(rest).length > 0) {
379
+ throw new TypeError("auth.local.sessions.update() changes a session's purpose and expiresAt only.");
380
+ }
381
+ const changes = { updatedAt: requiredDateTime() };
382
+ if (purpose !== undefined) {
383
+ changes.purpose = String(purpose || "normal");
384
+ }
385
+ if (expiresAt !== undefined) {
386
+ changes.expiresAt = requiredDateTime(expiresAt);
387
+ }
388
+ if (onlyIf === undefined) {
389
+ return mapSession(await patchExisting(sessions, sessionId, changes, options));
390
+ }
391
+ requireSessionConditions(onlyIf);
392
+ return mapSession(await patchExisting(sessions, sessionId, changes, { ...options, onlyIf }));
393
+ },
394
+ async revoke(sessionId) {
395
+ const existing = await findById(sessions, sessionId, options);
396
+ if (!existing || existing.revokedAt) {
397
+ return mapSession(existing);
398
+ }
399
+ const revokedAt = requiredDateTime();
400
+ return mapSession(await sessions.patch(existing.id, { revokedAt, updatedAt: revokedAt }, { ...options, missing: "skip" }));
401
+ },
402
+ // revokeOptions.exceptSessionId keeps that session.
403
+ async revokeForUser(userId, revokeOptions = {}) {
404
+ const owner = text(userId);
405
+ if (!owner) {
406
+ return 0;
407
+ }
408
+ const exceptSessionId = text(revokeOptions.exceptSessionId);
409
+ const revokedAt = requiredDateTime();
410
+ return sessions.patchWhere(
411
+ exceptSessionId ? { userId: owner, exceptId: exceptSessionId } : { userId: owner },
412
+ { revokedAt, updatedAt: revokedAt },
413
+ { ...options, onlyIf: { revokedAt: null }, returning: "count" }
414
+ );
415
+ },
416
+ async deleteExpired(now) {
417
+ return sessions.deleteWhere({ expiresAtOrBefore: requiredDateTime(now) }, { ...options, returning: "count" });
418
+ }
419
+ });
420
+ }
421
+
422
+ /**
423
+ * Local auth's password recovery tokens.
424
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} recovery
425
+ * @param {object} options
426
+ */
427
+ function recoveryRecords(recovery, options) {
428
+ return Object.freeze({
429
+ async create(input) {
430
+ const record = recoveryRecord(input);
431
+ await recovery.create(record, { ...options, returning: "none" });
432
+ return mapRecovery(record);
433
+ },
434
+ async findByTokenHash(tokenHash) {
435
+ return mapRecovery(await findOne(recovery, "tokenHash", tokenHash, options));
436
+ },
437
+ // The consumed token, or null when it is missing or already used: of two consumers at once, the one whose
438
+ // conditional write lands first wins.
439
+ async consume(tokenId) {
440
+ const id = text(tokenId);
441
+ if (!id) {
442
+ return null;
443
+ }
444
+ const usedAt = requiredDateTime();
445
+ return mapRecovery(await recovery.patch(id, { usedAt, updatedAt: usedAt }, {
446
+ ...options,
447
+ onlyIf: { usedAt: null },
448
+ missing: "skip"
449
+ }));
450
+ },
451
+ // The user's unused tokens of one kind (consumeOptions.idPrefix), never their others: a new sign-in link leaves
452
+ // an open password reset usable, and the other way round.
453
+ async consumeForUser(userId, { idPrefix } = {}) {
454
+ requireIdPrefix(idPrefix);
455
+ const owner = text(userId);
456
+ if (!owner) {
457
+ return 0;
458
+ }
459
+ const usedAt = requiredDateTime();
460
+ return recovery.patchWhere({ userId: owner, idPrefix }, { usedAt, updatedAt: usedAt }, {
461
+ ...options,
462
+ onlyIf: { usedAt: null },
463
+ returning: "count"
464
+ });
465
+ }
466
+ });
467
+ }
468
+
469
+ /**
470
+ * Local auth's pending provider sign-ins and links.
471
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} attempts
472
+ * @param {object} options
473
+ */
474
+ function oauthAttemptRecords(attempts, options) {
475
+ return Object.freeze({
476
+ async create(input) {
477
+ const record = oauthAttemptRecord(input);
478
+ await attempts.create(record, { ...options, returning: "none" });
479
+ return mapOAuthAttempt(record);
480
+ },
481
+ // Only the request that locks the row and deletes it gets the attempt, so concurrent callbacks on several servers
482
+ // cannot both use it: the others wait for the lock and then find no row. It runs in the backend's transaction.
483
+ async take(browserKeyHash) {
484
+ const id = text(browserKeyHash);
485
+ const [record] = id ? await attempts.lockMany([id], { ...options, missing: "skip" }) : [];
486
+ if (!record) {
487
+ return null;
488
+ }
489
+ await attempts.delete(record.id, options);
490
+ return mapOAuthAttempt(record);
491
+ },
492
+ async deleteExpired(now) {
493
+ return attempts.deleteWhere({ expiresAtOrBefore: requiredDateTime(now) }, { ...options, returning: "count" });
494
+ }
495
+ });
496
+ }
497
+
498
+ /**
499
+ * Local auth's failed sign-ins per account email.
500
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} failures
501
+ * @param {object} options
502
+ */
503
+ function signInFailureRecords(failures, options) {
504
+ return Object.freeze({
505
+ // Locks the email's record until the transaction ends, so concurrent failed sign-ins count one after another.
506
+ async find(email) {
507
+ const id = text(email);
508
+ return id ? mapSignInFailures(await failures.lock(id, { ...options, missing: "skip" })) : null;
509
+ },
510
+ async save(input) {
511
+ const email = text(input.email);
512
+ const record = {
513
+ failures: Number(input.failures || 0),
514
+ lastFailedAt: requiredDateTime(input.lastFailedAt),
515
+ lockedUntil: optionalDateTime(input.lockedUntil)
516
+ };
517
+ await replaceFailures(failures, email, record, options);
518
+ return mapSignInFailures({ id: email, ...record });
519
+ },
520
+ async clear(email) {
521
+ return deleteById(failures, email, options);
522
+ },
523
+ async deleteBefore(lastFailedAt) {
524
+ return failures.deleteWhere({ lastFailedBefore: requiredDateTime(lastFailedAt) }, { ...options, returning: "count" });
525
+ }
526
+ });
527
+ }
528
+
529
+ /**
530
+ * Local auth's registrations waiting for their email to be confirmed.
531
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} registrations
532
+ * @param {object} options
533
+ */
534
+ function registrationRecords(registrations, options) {
535
+ return Object.freeze({
536
+ async save(input) {
537
+ const email = text(input.email);
538
+ const record = registrationRecord(input);
539
+ // One statement creates the registration or replaces its fields, so two first registrations at once both land
540
+ // and the later one stays: the registrations table has no owners, so the email, its id, keys the upsert.
541
+ await registrations.createMany([{ id: email, ...record }], { ...options, onConflict: { keys: ["id"], action: "merge" } });
542
+ return mapRegistration({ id: email, ...record });
543
+ },
544
+ async findByEmail(email) {
545
+ return mapRegistration(await findById(registrations, email, options));
546
+ },
547
+ async findByTokenHash(tokenHash) {
548
+ return mapRegistration(await findOne(registrations, "tokenHash", tokenHash, options));
549
+ },
550
+ async delete(email) {
551
+ return deleteById(registrations, email, options);
552
+ },
553
+ async deleteExpired(now) {
554
+ return registrations.deleteWhere({ expiresAtOrBefore: requiredDateTime(now) }, { ...options, returning: "count" });
555
+ }
556
+ });
557
+ }
558
+
559
+ /**
560
+ * @typedef {object} LocalAuthHandles The handles of the tables the database backend feature owns, by resource name.
561
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthUsers
562
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthSessions
563
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthRecovery
564
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthOAuthAttempts
565
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthSignInFailures
566
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthRegistrations
567
+ */
568
+
569
+ /**
570
+ * Local auth's records, every call in the given options' transaction.
571
+ * @param {LocalAuthHandles} resources
572
+ * @param {import("./identityStore.js").IdentityStore} identities
573
+ * @param {object} options
574
+ */
575
+ function createRecords(resources, identities, options) {
576
+ return Object.freeze({
577
+ users: userRecords(resources.localAuthUsers, options),
578
+ sessions: sessionRecords(resources.localAuthSessions, options),
579
+ recovery: recoveryRecords(resources.localAuthRecovery, options),
580
+ identities: Object.freeze({
581
+ create: (input) => identities.create(input, options),
582
+ findByProviderSubject: (provider, providerSubject) => identities.findByProviderSubject(provider, providerSubject, options),
583
+ listForUser: (userId) => identities.listForUser(userId, options),
584
+ deleteForUser: (userId, provider) => identities.deleteForUser(userId, provider, options)
585
+ }),
586
+ oauthAttempts: oauthAttemptRecords(resources.localAuthOAuthAttempts, options),
587
+ signInFailures: signInFailureRecords(resources.localAuthSignInFailures, options),
588
+ registrations: registrationRecords(resources.localAuthRegistrations, options)
589
+ });
590
+ }
462
591
 
592
+ /**
593
+ * The `auth.local.backend` that keeps local auth's records in the database: each withTransaction opens one
594
+ * transaction on the records' handles, runs it again whole on a deadlock, and hands the callback the records in it.
595
+ * A failed callback rejects with the callback's own error (an AppError stays one); a failed commit rejects with
596
+ * json-rest-api's RestApiWriteError. Every call runs in the feature's system context.
597
+ * @param {object} dependencies
598
+ * @param {LocalAuthHandles} dependencies.resources
599
+ * @param {import("./identityStore.js").IdentityStore} dependencies.identities
600
+ * @param {object} dependencies.context The feature's system context.
601
+ */
602
+ function createLocalDbBackend({ resources, identities, context }) {
603
+ const run = (callback) => resources.localAuthUsers.withTransaction({ context }, (txOptions) => callback(createRecords(resources, identities, txOptions)));
604
+
605
+ // Two first failed sign-ins of one email at once both find no failure record and both create it, and the loser
606
+ // fails with a duplicate entry. Its transaction rolled back whole, so the sign-in runs once more and then counts
607
+ // its failure on the winner's row.
463
608
  async function withTransaction(callback) {
464
- return transactionManager.inTransaction(async (trx) => callback(createTx(trx)));
609
+ try {
610
+ return await run(callback);
611
+ } catch (error) {
612
+ if (error?.transactionOutcome !== "rolledBack" || !isDuplicateEntryError(error)) {
613
+ throw error;
614
+ }
615
+ return run(callback);
616
+ }
465
617
  }
466
618
 
467
619
  return Object.freeze({
@@ -470,4 +622,52 @@ function createLocalDbBackend({ knex, transactionManager }) {
470
622
  });
471
623
  }
472
624
 
473
- export { TABLES as LOCAL_AUTH_DB_TABLES, createLocalDbBackend };
625
+ /**
626
+ * The owner APIs of local auth's accounts, sessions and recovery tokens, for
627
+ * application code that works with them beside local auth: the
628
+ * `auth.local.accounts`, `auth.local.sessions` and `auth.local.recovery`
629
+ * capabilities. Each call takes the call's options last and runs in their
630
+ * transaction (one a handle's withTransaction opened), or on its own, always
631
+ * in the feature's system context: local sign-in writes its own records.
632
+ * @param {object} dependencies
633
+ * @param {LocalAuthHandles} dependencies.resources
634
+ * @param {import("./identityStore.js").IdentityStore} dependencies.identities
635
+ * @param {object} dependencies.context The feature's system context.
636
+ */
637
+ function createLocalDbOwners({ resources, identities, context }) {
638
+ const records = (options) => createRecords(resources, identities, { ...passedOn(options), context });
639
+
640
+ // An email is kept and found as local sign-in keeps it: trimmed and in lower case.
641
+ const accounts = Object.freeze({
642
+ create: (input, options = {}) => records(options).users.create({ ...input, email: normalizeEmail(input?.email) }),
643
+ findById: (userId, options = {}) => records(options).users.findById(userId),
644
+ findByEmail: (email, options = {}) => records(options).users.findByEmail(normalizeEmail(email)),
645
+ updatePassword: (userId, passwordRecord, options = {}) => records(options).users.updatePassword(userId, passwordRecord),
646
+ updateProfile: (userId, updates, options = {}) => records(options).users.updateProfile(userId, updates),
647
+ markEmailVerified: (userId, options = {}) => records(options).users.markEmailVerified(userId)
648
+ });
649
+ const sessions = Object.freeze({
650
+ create: (input, options = {}) => records(options).sessions.create(input),
651
+ // options.onlyIf (userId, purpose, revokedAt) changes the session only while it still matches, or answers null.
652
+ update: (sessionId, changes, { onlyIf, ...options } = {}) => records(options).sessions.update(sessionId, changes, { onlyIf }),
653
+ revoke: (sessionId, options = {}) => records(options).sessions.revoke(sessionId),
654
+ // options.exceptSessionId keeps that session.
655
+ revokeForUser: (userId, { exceptSessionId, ...options } = {}) => records(options).sessions.revokeForUser(userId, { exceptSessionId }),
656
+ deleteExpired: (now, options = {}) => records(options).sessions.deleteExpired(now)
657
+ });
658
+ const recovery = Object.freeze({
659
+ create: (input, options = {}) => records(options).recovery.create(input),
660
+ findByTokenHash: (tokenHash, options = {}) => records(options).recovery.findByTokenHash(tokenHash),
661
+ consume: (tokenId, options = {}) => records(options).recovery.consume(tokenId),
662
+ // options.idPrefix names the kind of token consumed, such as "rec_" for a password reset's.
663
+ consumeForUser: (userId, { idPrefix, ...options } = {}) => records(options).recovery.consumeForUser(userId, { idPrefix })
664
+ });
665
+
666
+ return Object.freeze({
667
+ accounts,
668
+ sessions,
669
+ recovery
670
+ });
671
+ }
672
+
673
+ export { TABLES as LOCAL_AUTH_DB_TABLES, INFRASTRUCTURE_TABLES as LOCAL_AUTH_INFRASTRUCTURE_TABLES, createLocalDbBackend, createLocalDbOwners };