@jskit-ai/auth-provider-local-db-core 0.1.156 → 0.1.158

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