@jskit-ai/auth-provider-local-db-core 0.1.173 → 0.1.175
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -0
- package/migrations/auth_local_db_users_second_factors.cjs +43 -0
- package/package.json +10 -7
- package/src/server/lib/dbBackend.js +38 -97
- package/src/server/lib/localAuthResources.js +32 -2
- package/src/server/lib/secondFactorRecords.js +72 -0
- package/src/server/lib/tableRecords.js +97 -0
- package/test/localAuthRecords.mysql.test.js +5 -3
- package/test/providerRuntime.test.js +2 -1
- package/test/secondFactor.mysql.test.js +4 -0
- package/test/secondFactor.postgres.test.js +4 -0
- package/test/secondFactor.test.js +4 -0
- package/test/support/localAuthRuntime.js +8 -1
- package/test/support/secondFactorCases.js +102 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Second factors in the database: the table `auth_local_second_factors` (one row per account, deleted with it) and the sessions' `second_factor_at` column, created by the new migration `auth_local_db_users_second_factors`, behind the backend contract's `secondFactors` collection and `sessions.markSecondFactorProved` / `sessions.clearSecondFactorForUser`. `LOCAL_AUTH_DB_TABLES.secondFactors` names the table, which the package owns.
|
|
5
6
|
- `auth.local.recovery.consumeForUser(userId, { ...options, idPrefix })` consumes only the user's open tokens whose id starts with `idPrefix`, such as `"rec_"` for a password reset's, and requires it (a `TypeError` without one). It consumed every open token of the user, so an app's new sign-in link (its own `magic_…` tokens) cancelled an outstanding password reset, and a reset its links. The prefix is compared exactly, never as a LIKE pattern, through the recovery table's new server-only `idPrefix` filter. The backend's `recovery.consumeForUser(userId, { idPrefix })` takes it too.
|
|
6
7
|
- `auth.local.sessions.update(sessionId, changes, { ...options, onlyIf })` changes the session only while it still has the `onlyIf` values (`userId`, `purpose`, `revokedAt`; others are refused), compared in the one UPDATE, and answers null, writing nothing, when it is missing or no longer matches. An app promotes a sign-in link's session with `onlyIf: { userId, purpose: "recovery", revokedAt: null }` instead of updating it unconditionally and checking afterwards. Its tests run on SQLite, MariaDB/MySQL and PostgreSQL (`tokenKinds*.test.js`; the PostgreSQL one in CI's PostgreSQL job).
|
|
7
8
|
- Its table resources declare the foreign keys their migrations create (`foreignKeys`), so json-rest-api 3.1.0 can skip the visibility query a system-context read makes for a record such a key guarantees exists. `jskit test --databases` checks each against an app's test database: auth_local_sessions.user_id and auth_local_recovery.user_id to auth_local_users. `localAuthRecords.mysql.test.js` proves the declarations match the migrations on MariaDB.
|
|
@@ -16,4 +17,5 @@
|
|
|
16
17
|
|
|
17
18
|
### Upgrading
|
|
18
19
|
|
|
20
|
+
- Run `npm run db:migrate` before the new version serves requests: every session read selects `second_factor_at`, so until the migration `auth_local_db_users_second_factors` has run every signed-in request fails with an unknown column.
|
|
19
21
|
- Run `npm run db:migrate` before the new version serves requests: its account reads select `email_verified_at`, so until the migration has run every sign-in and account read fails with an unknown column. An application that added `email_verified_at` itself keeps its column (the migration leaves an existing one alone) and replaces its own writes with `markEmailVerified`.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const USERS_TABLE = "auth_local_users";
|
|
2
|
+
const SESSIONS_TABLE = "auth_local_sessions";
|
|
3
|
+
const SECOND_FACTORS_TABLE = "auth_local_second_factors";
|
|
4
|
+
const SESSION_SECOND_FACTOR_COLUMN = "second_factor_at";
|
|
5
|
+
|
|
6
|
+
exports.up = async function up(knex) {
|
|
7
|
+
// An account's second factor: its authenticator secret, sealed with the
|
|
8
|
+
// application's key; when its first code confirmed it (null while it is
|
|
9
|
+
// being set up); the 30-second step of the last code accepted; the keyed
|
|
10
|
+
// hashes of its unused recovery codes, comma-separated; and its wrong codes,
|
|
11
|
+
// counted as failed sign-ins are. Deleting the account deletes it.
|
|
12
|
+
if (!(await knex.schema.hasTable(SECOND_FACTORS_TABLE))) {
|
|
13
|
+
await knex.schema.createTable(SECOND_FACTORS_TABLE, (table) => {
|
|
14
|
+
table.string("user_id", 80).primary();
|
|
15
|
+
table.string("secret_sealed", 255).notNullable();
|
|
16
|
+
table.timestamp("confirmed_at").nullable();
|
|
17
|
+
table.integer("last_used_step").unsigned().notNullable();
|
|
18
|
+
table.string("recovery_code_hashes", 1024).notNullable();
|
|
19
|
+
table.integer("failures").unsigned().notNullable();
|
|
20
|
+
table.timestamp("last_failed_at").nullable();
|
|
21
|
+
table.timestamp("locked_until").nullable();
|
|
22
|
+
table.timestamp("created_at").notNullable();
|
|
23
|
+
table.timestamp("updated_at").notNullable();
|
|
24
|
+
table.foreign(["user_id"], "fk_auth_local_second_factors_user").references(["id"]).inTable(USERS_TABLE).onUpdate("RESTRICT").onDelete("CASCADE");
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// When a session last proved its account's second factor; null when it has not.
|
|
29
|
+
if (!(await knex.schema.hasColumn(SESSIONS_TABLE, SESSION_SECOND_FACTOR_COLUMN))) {
|
|
30
|
+
await knex.schema.alterTable(SESSIONS_TABLE, (table) => {
|
|
31
|
+
table.timestamp(SESSION_SECOND_FACTOR_COLUMN).nullable();
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
exports.down = async function down(knex) {
|
|
37
|
+
if (await knex.schema.hasColumn(SESSIONS_TABLE, SESSION_SECOND_FACTOR_COLUMN)) {
|
|
38
|
+
await knex.schema.alterTable(SESSIONS_TABLE, (table) => {
|
|
39
|
+
table.dropColumn(SESSION_SECOND_FACTOR_COLUMN);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
await knex.schema.dropTableIfExists(SECOND_FACTORS_TABLE);
|
|
43
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-db-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.175",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -11,14 +11,14 @@
|
|
|
11
11
|
"./server/types": "./src/server/types.js"
|
|
12
12
|
},
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"@jskit-ai/auth-provider-local-core": "0.2.
|
|
15
|
-
"@jskit-ai/resource-core": "0.1.
|
|
14
|
+
"@jskit-ai/auth-provider-local-core": "0.2.26",
|
|
15
|
+
"@jskit-ai/resource-core": "0.1.213"
|
|
16
16
|
},
|
|
17
17
|
"peerDependencies": {
|
|
18
|
-
"@jskit-ai/auth-core": "0.2.
|
|
19
|
-
"@jskit-ai/database-runtime": "0.1.
|
|
20
|
-
"@jskit-ai/kernel": "0.2.
|
|
21
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
18
|
+
"@jskit-ai/auth-core": "0.2.22",
|
|
19
|
+
"@jskit-ai/database-runtime": "0.1.271",
|
|
20
|
+
"@jskit-ai/kernel": "0.2.22",
|
|
21
|
+
"@jskit-ai/resource-runtime": "0.2.29"
|
|
22
22
|
},
|
|
23
23
|
"description": "Database-backed local auth storage backend for JSKIT local auth.",
|
|
24
24
|
"jskit": {
|
|
@@ -73,6 +73,9 @@
|
|
|
73
73
|
},
|
|
74
74
|
{
|
|
75
75
|
"tableName": "auth_local_registrations"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"tableName": "auth_local_second_factors"
|
|
76
79
|
}
|
|
77
80
|
]
|
|
78
81
|
}
|
|
@@ -2,8 +2,19 @@ import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
|
|
|
2
2
|
import { isDuplicateEntryError } from "@jskit-ai/database-runtime/shared/duplicateEntry";
|
|
3
3
|
import { ConflictError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
4
4
|
import { passedOn } from "@jskit-ai/resource-runtime/server";
|
|
5
|
-
import { nowIso, toDate } from "./dateTimes.js";
|
|
6
5
|
import { IDENTITIES_TABLE } from "./identityStore.js";
|
|
6
|
+
import { secondFactorRecords } from "./secondFactorRecords.js";
|
|
7
|
+
import {
|
|
8
|
+
deleteById,
|
|
9
|
+
findById,
|
|
10
|
+
findOne,
|
|
11
|
+
optionalDateTime,
|
|
12
|
+
patchExisting,
|
|
13
|
+
readDateTime,
|
|
14
|
+
replaceById,
|
|
15
|
+
requiredDateTime,
|
|
16
|
+
text
|
|
17
|
+
} from "./tableRecords.js";
|
|
7
18
|
|
|
8
19
|
const TABLES = Object.freeze({
|
|
9
20
|
users: "auth_local_users",
|
|
@@ -12,35 +23,13 @@ const TABLES = Object.freeze({
|
|
|
12
23
|
identities: IDENTITIES_TABLE,
|
|
13
24
|
oauthAttempts: "auth_local_oauth_attempts",
|
|
14
25
|
signInFailures: "auth_local_sign_in_failures",
|
|
15
|
-
registrations: "auth_local_registrations"
|
|
26
|
+
registrations: "auth_local_registrations",
|
|
27
|
+
secondFactors: "auth_local_second_factors"
|
|
16
28
|
});
|
|
17
29
|
|
|
18
30
|
// The tables local sign-in keeps outside table resources, for an app test's expectEveryTableOwned infrastructureTables.
|
|
19
31
|
const INFRASTRUCTURE_TABLES = Object.freeze([IDENTITIES_TABLE]);
|
|
20
32
|
|
|
21
|
-
// One page of one record: a lookup by a unique field.
|
|
22
|
-
const FIRST = Object.freeze({ size: 1 });
|
|
23
|
-
|
|
24
|
-
// The ISO text written for a required timestamp: the value, or the fallback (now) when it has none.
|
|
25
|
-
function requiredDateTime(value, fallback = nowIso()) {
|
|
26
|
-
return toDate(value || fallback).toISOString();
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function optionalDateTime(value) {
|
|
30
|
-
return value ? toDate(value).toISOString() : null;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function readDateTime(value, fallback = "") {
|
|
34
|
-
if (!value) {
|
|
35
|
-
return fallback;
|
|
36
|
-
}
|
|
37
|
-
return toDate(value).toISOString();
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function text(value) {
|
|
41
|
-
return String(value || "");
|
|
42
|
-
}
|
|
43
|
-
|
|
44
33
|
// A session's conditional update compares only whose session it is and where it stands.
|
|
45
34
|
const SESSION_CONDITIONS = Object.freeze(["userId", "purpose", "revokedAt"]);
|
|
46
35
|
|
|
@@ -104,7 +93,8 @@ function mapSession(record) {
|
|
|
104
93
|
purpose: String(record.purpose || "normal"),
|
|
105
94
|
createdAt: readDateTime(record.createdAt),
|
|
106
95
|
expiresAt: readDateTime(record.expiresAt),
|
|
107
|
-
revokedAt: readDateTime(record.revokedAt)
|
|
96
|
+
revokedAt: readDateTime(record.revokedAt),
|
|
97
|
+
secondFactorAt: readDateTime(record.secondFactorAt)
|
|
108
98
|
};
|
|
109
99
|
}
|
|
110
100
|
|
|
@@ -202,6 +192,7 @@ function sessionRecord(input = {}) {
|
|
|
202
192
|
purpose: String(input.purpose || "normal"),
|
|
203
193
|
expiresAt: requiredDateTime(input.expiresAt),
|
|
204
194
|
revokedAt: optionalDateTime(input.revokedAt),
|
|
195
|
+
secondFactorAt: optionalDateTime(input.secondFactorAt),
|
|
205
196
|
createdAt,
|
|
206
197
|
updatedAt: requiredDateTime(input.updatedAt, createdAt)
|
|
207
198
|
};
|
|
@@ -235,74 +226,6 @@ function oauthAttemptRecord(input = {}) {
|
|
|
235
226
|
};
|
|
236
227
|
}
|
|
237
228
|
|
|
238
|
-
/**
|
|
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
|
|
244
|
-
*/
|
|
245
|
-
async function findOne(handle, field, value, options) {
|
|
246
|
-
const wanted = text(value);
|
|
247
|
-
if (!wanted) {
|
|
248
|
-
return null;
|
|
249
|
-
}
|
|
250
|
-
const { records } = await handle.query({ filters: { [field]: wanted }, page: FIRST }, options);
|
|
251
|
-
return records[0] || null;
|
|
252
|
-
}
|
|
253
|
-
|
|
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" });
|
|
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
229
|
/**
|
|
307
230
|
* Local auth's accounts.
|
|
308
231
|
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} users
|
|
@@ -329,7 +252,7 @@ function userRecords(users, options) {
|
|
|
329
252
|
return mapUser(await findOne(users, "email", email, options));
|
|
330
253
|
},
|
|
331
254
|
async hasAny() {
|
|
332
|
-
return (await users.query({ page:
|
|
255
|
+
return (await users.query({ page: { size: 1 } }, options)).records.length > 0;
|
|
333
256
|
},
|
|
334
257
|
async updatePassword(userId, passwordRecord) {
|
|
335
258
|
return mapUser(await patchExisting(users, userId, { ...writePassword(passwordRecord), updatedAt: requiredDateTime() }, options));
|
|
@@ -415,6 +338,22 @@ function sessionRecords(sessions, options) {
|
|
|
415
338
|
},
|
|
416
339
|
async deleteExpired(now) {
|
|
417
340
|
return sessions.deleteWhere({ expiresAtOrBefore: requiredDateTime(now) }, { ...options, returning: "count" });
|
|
341
|
+
},
|
|
342
|
+
async markSecondFactorProved(sessionId, secondFactorAt) {
|
|
343
|
+
const at = requiredDateTime(secondFactorAt);
|
|
344
|
+
return mapSession(await patchExisting(sessions, sessionId, { secondFactorAt: at, updatedAt: at }, options));
|
|
345
|
+
},
|
|
346
|
+
// Forgets every proof of the user's sessions, as when their second factor is removed; answers how many it changed.
|
|
347
|
+
async clearSecondFactorForUser(userId) {
|
|
348
|
+
const owner = text(userId);
|
|
349
|
+
if (!owner) {
|
|
350
|
+
return 0;
|
|
351
|
+
}
|
|
352
|
+
return sessions.patchWhere(
|
|
353
|
+
{ userId: owner, secondFactorProved: true },
|
|
354
|
+
{ secondFactorAt: null, updatedAt: requiredDateTime() },
|
|
355
|
+
{ ...options, returning: "count" }
|
|
356
|
+
);
|
|
418
357
|
}
|
|
419
358
|
});
|
|
420
359
|
}
|
|
@@ -514,7 +453,7 @@ function signInFailureRecords(failures, options) {
|
|
|
514
453
|
lastFailedAt: requiredDateTime(input.lastFailedAt),
|
|
515
454
|
lockedUntil: optionalDateTime(input.lockedUntil)
|
|
516
455
|
};
|
|
517
|
-
await
|
|
456
|
+
await replaceById(failures, email, record, options);
|
|
518
457
|
return mapSignInFailures({ id: email, ...record });
|
|
519
458
|
},
|
|
520
459
|
async clear(email) {
|
|
@@ -564,6 +503,7 @@ function registrationRecords(registrations, options) {
|
|
|
564
503
|
* @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthOAuthAttempts
|
|
565
504
|
* @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthSignInFailures
|
|
566
505
|
* @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthRegistrations
|
|
506
|
+
* @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthSecondFactors
|
|
567
507
|
*/
|
|
568
508
|
|
|
569
509
|
/**
|
|
@@ -585,7 +525,8 @@ function createRecords(resources, identities, options) {
|
|
|
585
525
|
}),
|
|
586
526
|
oauthAttempts: oauthAttemptRecords(resources.localAuthOAuthAttempts, options),
|
|
587
527
|
signInFailures: signInFailureRecords(resources.localAuthSignInFailures, options),
|
|
588
|
-
registrations: registrationRecords(resources.localAuthRegistrations, options)
|
|
528
|
+
registrations: registrationRecords(resources.localAuthRegistrations, options),
|
|
529
|
+
secondFactors: secondFactorRecords(resources.localAuthSecondFactors, options)
|
|
589
530
|
});
|
|
590
531
|
}
|
|
591
532
|
|
|
@@ -24,6 +24,11 @@ function idStartsWith(query, prefix, { column }) {
|
|
|
24
24
|
query.whereRaw("substr(??, 1, ?) = ?", [column("id"), prefix.length, prefix]);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
// Sessions that proved their account's second factor.
|
|
28
|
+
function hasSecondFactorAt(query, _proved, { column }) {
|
|
29
|
+
query.whereNotNull(column("secondFactorAt"));
|
|
30
|
+
}
|
|
31
|
+
|
|
27
32
|
// auth_local_users: one row per local account, keyed by its text id.
|
|
28
33
|
const localAuthUserResource = defineTableResource({
|
|
29
34
|
name: "localAuthUsers",
|
|
@@ -52,13 +57,15 @@ const localAuthSessionResource = defineTableResource({
|
|
|
52
57
|
purpose: text,
|
|
53
58
|
expiresAt: dateTime,
|
|
54
59
|
revokedAt: optionalDateTime,
|
|
60
|
+
secondFactorAt: optionalDateTime,
|
|
55
61
|
createdAt: dateTime,
|
|
56
62
|
updatedAt: dateTime
|
|
57
63
|
},
|
|
58
64
|
searchSchema: {
|
|
59
65
|
// Every session of a user but one.
|
|
60
66
|
exceptId: { type: "string", actualField: "id", filterOperator: "!=" },
|
|
61
|
-
expiresAtOrBefore
|
|
67
|
+
expiresAtOrBefore,
|
|
68
|
+
secondFactorProved: { type: "boolean", applyFilter: hasSecondFactorAt }
|
|
62
69
|
}
|
|
63
70
|
});
|
|
64
71
|
|
|
@@ -140,13 +147,35 @@ const localAuthRegistrationResource = defineTableResource({
|
|
|
140
147
|
}
|
|
141
148
|
});
|
|
142
149
|
|
|
150
|
+
// auth_local_second_factors: an account's authenticator, keyed by the account's id; its secret is sealed with the
|
|
151
|
+
// application's key and its recovery codes are kept as keyed hashes, comma-separated.
|
|
152
|
+
const localAuthSecondFactorResource = defineTableResource({
|
|
153
|
+
name: "localAuthSecondFactors",
|
|
154
|
+
tableName: "auth_local_second_factors",
|
|
155
|
+
idProperty: "user_id",
|
|
156
|
+
ownership: "public",
|
|
157
|
+
foreignKeys: [{ columns: ["id"], referencedTableName: "auth_local_users" }],
|
|
158
|
+
schema: {
|
|
159
|
+
secretSealed: text,
|
|
160
|
+
confirmedAt: optionalDateTime,
|
|
161
|
+
lastUsedStep: { type: "integer" },
|
|
162
|
+
recoveryCodeHashes: text,
|
|
163
|
+
failures: { type: "integer" },
|
|
164
|
+
lastFailedAt: optionalDateTime,
|
|
165
|
+
lockedUntil: optionalDateTime,
|
|
166
|
+
createdAt: dateTime,
|
|
167
|
+
updatedAt: dateTime
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
143
171
|
const LOCAL_AUTH_RESOURCES = Object.freeze([
|
|
144
172
|
localAuthUserResource,
|
|
145
173
|
localAuthSessionResource,
|
|
146
174
|
localAuthRecoveryResource,
|
|
147
175
|
localAuthOAuthAttemptResource,
|
|
148
176
|
localAuthSignInFailureResource,
|
|
149
|
-
localAuthRegistrationResource
|
|
177
|
+
localAuthRegistrationResource,
|
|
178
|
+
localAuthSecondFactorResource
|
|
150
179
|
]);
|
|
151
180
|
|
|
152
181
|
export {
|
|
@@ -154,6 +183,7 @@ export {
|
|
|
154
183
|
localAuthOAuthAttemptResource,
|
|
155
184
|
localAuthRecoveryResource,
|
|
156
185
|
localAuthRegistrationResource,
|
|
186
|
+
localAuthSecondFactorResource,
|
|
157
187
|
localAuthSessionResource,
|
|
158
188
|
localAuthSignInFailureResource,
|
|
159
189
|
localAuthUserResource
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { deleteById, optionalDateTime, readDateTime, replaceById, requiredDateTime, text } from "./tableRecords.js";
|
|
2
|
+
|
|
3
|
+
// The ids one read binds: far under PostgreSQL's 65,535 parameters, and one page of the runtime's every-row reads.
|
|
4
|
+
const IDS_PER_READ = 1000;
|
|
5
|
+
|
|
6
|
+
function mapSecondFactor(record) {
|
|
7
|
+
if (!record) {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
return {
|
|
11
|
+
userId: text(record.id),
|
|
12
|
+
secretSealed: text(record.secretSealed),
|
|
13
|
+
confirmedAt: readDateTime(record.confirmedAt),
|
|
14
|
+
lastUsedStep: Number(record.lastUsedStep || 0),
|
|
15
|
+
recoveryCodes: record.recoveryCodeHashes ? String(record.recoveryCodeHashes).split(",") : [],
|
|
16
|
+
failures: Number(record.failures || 0),
|
|
17
|
+
lastFailedAt: readDateTime(record.lastFailedAt),
|
|
18
|
+
lockedUntil: readDateTime(record.lockedUntil),
|
|
19
|
+
createdAt: readDateTime(record.createdAt),
|
|
20
|
+
updatedAt: readDateTime(record.updatedAt)
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function secondFactorRecord(input = {}) {
|
|
25
|
+
const createdAt = requiredDateTime(input.createdAt);
|
|
26
|
+
return {
|
|
27
|
+
secretSealed: text(input.secretSealed),
|
|
28
|
+
confirmedAt: optionalDateTime(input.confirmedAt),
|
|
29
|
+
lastUsedStep: Number(input.lastUsedStep || 0),
|
|
30
|
+
recoveryCodeHashes: (input.recoveryCodes || []).join(","),
|
|
31
|
+
failures: Number(input.failures || 0),
|
|
32
|
+
lastFailedAt: optionalDateTime(input.lastFailedAt),
|
|
33
|
+
lockedUntil: optionalDateTime(input.lockedUntil),
|
|
34
|
+
createdAt,
|
|
35
|
+
updatedAt: requiredDateTime(input.updatedAt, createdAt)
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Local auth's second factors, one per account.
|
|
41
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} secondFactors
|
|
42
|
+
* @param {object} options
|
|
43
|
+
*/
|
|
44
|
+
function secondFactorRecords(secondFactors, options) {
|
|
45
|
+
return Object.freeze({
|
|
46
|
+
// Locks the account's record until the transaction ends, so concurrent codes are checked one after another.
|
|
47
|
+
async find(userId) {
|
|
48
|
+
const id = text(userId);
|
|
49
|
+
return id ? mapSecondFactor(await secondFactors.lock(id, { ...options, missing: "skip" })) : null;
|
|
50
|
+
},
|
|
51
|
+
// The accounts' records, however many: one read per 1,000 distinct ids.
|
|
52
|
+
async findMany(userIds) {
|
|
53
|
+
const ids = [...new Set(userIds.map(text).filter(Boolean))];
|
|
54
|
+
const records = [];
|
|
55
|
+
for (let start = 0; start < ids.length; start += IDS_PER_READ) {
|
|
56
|
+
records.push(...await secondFactors.queryAll({ filters: { id: ids.slice(start, start + IDS_PER_READ) } }, options));
|
|
57
|
+
}
|
|
58
|
+
return records.map(mapSecondFactor);
|
|
59
|
+
},
|
|
60
|
+
async save(input) {
|
|
61
|
+
const userId = text(input.userId);
|
|
62
|
+
const record = secondFactorRecord(input);
|
|
63
|
+
await replaceById(secondFactors, userId, record, options);
|
|
64
|
+
return mapSecondFactor({ id: userId, ...record });
|
|
65
|
+
},
|
|
66
|
+
async delete(userId) {
|
|
67
|
+
return deleteById(secondFactors, userId, options);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export { secondFactorRecords };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// What local sign-in's table records share: their values as stored and read back, and one-record reads and writes on a
|
|
2
|
+
// table resource handle.
|
|
3
|
+
|
|
4
|
+
import { nowIso, toDate } from "./dateTimes.js";
|
|
5
|
+
|
|
6
|
+
// One page of one record: a lookup by a unique field.
|
|
7
|
+
const FIRST = Object.freeze({ size: 1 });
|
|
8
|
+
|
|
9
|
+
// The ISO text written for a required timestamp: the value, or the fallback (now) when it has none.
|
|
10
|
+
function requiredDateTime(value, fallback = nowIso()) {
|
|
11
|
+
return toDate(value || fallback).toISOString();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function optionalDateTime(value) {
|
|
15
|
+
return value ? toDate(value).toISOString() : null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function readDateTime(value, fallback = "") {
|
|
19
|
+
if (!value) {
|
|
20
|
+
return fallback;
|
|
21
|
+
}
|
|
22
|
+
return toDate(value).toISOString();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function text(value) {
|
|
26
|
+
return String(value || "");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The record a unique field's value finds, or null; an empty value finds none.
|
|
31
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
|
|
32
|
+
* @param {string} field
|
|
33
|
+
* @param {unknown} value
|
|
34
|
+
* @param {object} options
|
|
35
|
+
*/
|
|
36
|
+
async function findOne(handle, field, value, options) {
|
|
37
|
+
const wanted = text(value);
|
|
38
|
+
if (!wanted) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const { records } = await handle.query({ filters: { [field]: wanted }, page: FIRST }, options);
|
|
42
|
+
return records[0] || null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The record with this id, or null; an empty id finds none.
|
|
47
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
|
|
48
|
+
* @param {unknown} id
|
|
49
|
+
* @param {object} options
|
|
50
|
+
*/
|
|
51
|
+
async function findById(handle, id, options) {
|
|
52
|
+
const wanted = text(id);
|
|
53
|
+
return wanted ? handle.get(wanted, {}, { ...options, missing: "skip" }) : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Deletes the record with this id and answers 1, or 0 when it is missing: one DELETE, so of two concurrent deletes
|
|
58
|
+
* only one answers 1.
|
|
59
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
|
|
60
|
+
* @param {unknown} id
|
|
61
|
+
* @param {object} options
|
|
62
|
+
*/
|
|
63
|
+
async function deleteById(handle, id, options) {
|
|
64
|
+
const wanted = text(id);
|
|
65
|
+
return wanted && (await handle.delete(wanted, { ...options, missing: "skip" })) !== null ? 1 : 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Writes the record with this id: patches it when it exists, creates it otherwise. An upsert would keep the later of
|
|
70
|
+
* two first writes at once, so two first failed sign-ins of an email would count once; this create instead fails the
|
|
71
|
+
* later one with a duplicate entry, and the backend runs that call again on the row the first one made.
|
|
72
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
|
|
73
|
+
* @param {string} id
|
|
74
|
+
* @param {Record<string, unknown>} attributes
|
|
75
|
+
* @param {object} options
|
|
76
|
+
*/
|
|
77
|
+
async function replaceById(handle, id, attributes, options) {
|
|
78
|
+
if (await handle.get(id, {}, { ...options, missing: "skip" })) {
|
|
79
|
+
await handle.patch(id, attributes, { ...options, returning: "none" });
|
|
80
|
+
} else {
|
|
81
|
+
await handle.create({ id, ...attributes }, { ...options, returning: "none" });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Patches an existing record and answers it after the change; null when it is missing, which fails no transaction.
|
|
87
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} handle
|
|
88
|
+
* @param {unknown} id
|
|
89
|
+
* @param {Record<string, unknown>} changes
|
|
90
|
+
* @param {object} options
|
|
91
|
+
*/
|
|
92
|
+
async function patchExisting(handle, id, changes, options) {
|
|
93
|
+
const wanted = text(id);
|
|
94
|
+
return wanted ? handle.patch(wanted, changes, { ...options, missing: "skip" }) : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { deleteById, findById, findOne, optionalDateTime, patchExisting, readDateTime, replaceById, requiredDateTime, text };
|
|
@@ -18,7 +18,7 @@ const NO_PASSWORD = Object.freeze({ algorithm: "", version: "", salt: "", hash:
|
|
|
18
18
|
const CREATED = "2026-11-01T08:00:00.000Z";
|
|
19
19
|
const ISO_SECONDS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.000Z$/u;
|
|
20
20
|
const ACCOUNT_KEYS = ["id", "email", "displayName", "password", "createdAt", "updatedAt", "emailVerifiedAt", "disabled"];
|
|
21
|
-
const SESSION_KEYS = ["id", "userId", "tokenHash", "purpose", "createdAt", "expiresAt", "revokedAt"];
|
|
21
|
+
const SESSION_KEYS = ["id", "userId", "tokenHash", "purpose", "createdAt", "expiresAt", "revokedAt", "secondFactorAt"];
|
|
22
22
|
const RECOVERY_KEYS = ["id", "userId", "tokenHash", "createdAt", "expiresAt", "usedAt"];
|
|
23
23
|
|
|
24
24
|
/** The current second, as the second-precision timestamps keep it. */
|
|
@@ -43,7 +43,8 @@ test("accounts: create answers the account it wrote, reads find it by id and ema
|
|
|
43
43
|
identities: "auth_local_identities",
|
|
44
44
|
oauthAttempts: "auth_local_oauth_attempts",
|
|
45
45
|
signInFailures: "auth_local_sign_in_failures",
|
|
46
|
-
registrations: "auth_local_registrations"
|
|
46
|
+
registrations: "auth_local_registrations",
|
|
47
|
+
secondFactors: "auth_local_second_factors"
|
|
47
48
|
});
|
|
48
49
|
assert.equal(await backend.withTransaction((tx) => tx.users.hasAny()), false);
|
|
49
50
|
|
|
@@ -151,7 +152,8 @@ test("sessions: create, reads, revoke once, revoke a user's live sessions but on
|
|
|
151
152
|
purpose: "normal",
|
|
152
153
|
createdAt: CREATED,
|
|
153
154
|
expiresAt: "2026-12-01T00:00:00.000Z",
|
|
154
|
-
revokedAt: ""
|
|
155
|
+
revokedAt: "",
|
|
156
|
+
secondFactorAt: ""
|
|
155
157
|
}, "a session without a purpose is a normal one");
|
|
156
158
|
const preview = await backend.withTransaction((tx) => tx.sessions.create(session("ses_two", "usr_ada", "2026-12-01T00:00:00.000Z", { purpose: "dev-auth" })));
|
|
157
159
|
assert.equal(preview.purpose, "dev-auth");
|
|
@@ -367,7 +367,8 @@ test("package metadata declares portable local auth DB migrations without instal
|
|
|
367
367
|
LOCAL_AUTH_DB_TABLES.identities,
|
|
368
368
|
LOCAL_AUTH_DB_TABLES.oauthAttempts,
|
|
369
369
|
LOCAL_AUTH_DB_TABLES.signInFailures,
|
|
370
|
-
LOCAL_AUTH_DB_TABLES.registrations
|
|
370
|
+
LOCAL_AUTH_DB_TABLES.registrations,
|
|
371
|
+
LOCAL_AUTH_DB_TABLES.secondFactors
|
|
371
372
|
]
|
|
372
373
|
);
|
|
373
374
|
});
|
|
@@ -7,10 +7,17 @@ import initialMigration from "../../migrations/auth_local_db_initial.cjs";
|
|
|
7
7
|
import oauthMigration from "../../migrations/auth_local_db_oauth.cjs";
|
|
8
8
|
import protectionMigration from "../../migrations/auth_local_db_protection.cjs";
|
|
9
9
|
import emailVerifiedMigration from "../../migrations/auth_local_db_users_email_verified.cjs";
|
|
10
|
+
import secondFactorsMigration from "../../migrations/auth_local_db_users_second_factors.cjs";
|
|
10
11
|
import { AuthLocalDatabaseBackendProvider } from "../../src/server/providers/AuthLocalDatabaseBackendProvider.js";
|
|
11
12
|
|
|
12
13
|
// Every local auth migration, in order.
|
|
13
|
-
const LOCAL_AUTH_MIGRATIONS = Object.freeze([
|
|
14
|
+
const LOCAL_AUTH_MIGRATIONS = Object.freeze([
|
|
15
|
+
initialMigration,
|
|
16
|
+
oauthMigration,
|
|
17
|
+
protectionMigration,
|
|
18
|
+
emailVerifiedMigration,
|
|
19
|
+
secondFactorsMigration
|
|
20
|
+
]);
|
|
14
21
|
|
|
15
22
|
/**
|
|
16
23
|
* The capabilities an application gives local auth's database backend, on the test's Knex: the database, an action
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
4
|
+
import { createLocalAuthService } from "../../../auth-provider-local-core/src/server/lib/index.js";
|
|
5
|
+
import {
|
|
6
|
+
SCENARIO_START,
|
|
7
|
+
exerciseSecondFactor,
|
|
8
|
+
secondFactorServiceOptions
|
|
9
|
+
} from "../../../auth-provider-local-core/test-support/secondFactorScenario.js";
|
|
10
|
+
import secondFactorsMigration from "../../migrations/auth_local_db_users_second_factors.cjs";
|
|
11
|
+
import { LOCAL_AUTH_DB_TABLES } from "../../src/server/lib/index.js";
|
|
12
|
+
|
|
13
|
+
// Second factors in the database, on SQLite, MariaDB/MySQL and PostgreSQL alike: the whole scenario through local
|
|
14
|
+
// auth's service, and the migration, which runs again, down and up, and whose rows go with their account.
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Registers the tests on the records `open(context, suffix)` answers: its Knex and startLocalAuthRecords()'s records.
|
|
18
|
+
* @param {(context: import("node:test").TestContext, suffix: string) => Promise<any>} open
|
|
19
|
+
* @param {{ database?: boolean, skip?: string | false }} [options] `database`: the records need TEST_DB_NAME.
|
|
20
|
+
*/
|
|
21
|
+
function secondFactorCases(open, { database = false, skip = false } = {}) {
|
|
22
|
+
test("an authenticator sets up, proves sessions, refuses wrong, used and expired codes, waits, and resets (database backend)", { skip }, async (t) => {
|
|
23
|
+
if (database) requireTestDatabase(process.env);
|
|
24
|
+
const { knex, backend } = await open(t, "da_local_2fa");
|
|
25
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
26
|
+
const { events, options } = secondFactorServiceOptions();
|
|
27
|
+
await exerciseSecondFactor(t, {
|
|
28
|
+
service: createLocalAuthService({ ...options, backend }),
|
|
29
|
+
events,
|
|
30
|
+
async storedText() {
|
|
31
|
+
return JSON.stringify([
|
|
32
|
+
await knex(LOCAL_AUTH_DB_TABLES.secondFactors).select(),
|
|
33
|
+
await knex(LOCAL_AUTH_DB_TABLES.sessions).select()
|
|
34
|
+
]);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Ada's started setup is the one factor left, with the secret sealed for her account.
|
|
39
|
+
const [factor] = await knex(LOCAL_AUTH_DB_TABLES.secondFactors).select();
|
|
40
|
+
assert.equal(factor.confirmed_at, null);
|
|
41
|
+
assert.match(factor.secret_sealed, /^v1\./u);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("the second factor migration runs again, goes down and up, and deleting an account deletes its factor", { skip }, async (t) => {
|
|
45
|
+
if (database) requireTestDatabase(process.env);
|
|
46
|
+
const { knex, backend } = await open(t, "da_local_2fa_migration");
|
|
47
|
+
await secondFactorsMigration.up(knex);
|
|
48
|
+
const at = "2026-11-13T10:00:00.000Z";
|
|
49
|
+
await backend.withTransaction(async (tx) => {
|
|
50
|
+
await tx.users.create({ id: "usr_ada", email: "ada@example.com", displayName: "Ada", password: {}, createdAt: at });
|
|
51
|
+
await tx.sessions.create({ id: "ses_ada", userId: "usr_ada", tokenHash: "hash-ada", expiresAt: "2026-12-01T00:00:00.000Z", createdAt: at });
|
|
52
|
+
await tx.secondFactors.save({
|
|
53
|
+
userId: "usr_ada",
|
|
54
|
+
secretSealed: "v1.nonce.body.tag",
|
|
55
|
+
confirmedAt: at,
|
|
56
|
+
lastUsedStep: 58767600,
|
|
57
|
+
recoveryCodes: ["hash-one", "hash-two"],
|
|
58
|
+
failures: 0,
|
|
59
|
+
lastFailedAt: "",
|
|
60
|
+
lockedUntil: "",
|
|
61
|
+
createdAt: at,
|
|
62
|
+
updatedAt: at
|
|
63
|
+
});
|
|
64
|
+
assert.equal((await tx.sessions.markSecondFactorProved("ses_ada", at)).secondFactorAt, at);
|
|
65
|
+
});
|
|
66
|
+
assert.deepEqual(await backend.withTransaction((tx) => tx.secondFactors.findMany(["usr_ada", "usr_missing", "usr_ada"])), [{
|
|
67
|
+
userId: "usr_ada",
|
|
68
|
+
secretSealed: "v1.nonce.body.tag",
|
|
69
|
+
confirmedAt: at,
|
|
70
|
+
lastUsedStep: 58767600,
|
|
71
|
+
recoveryCodes: ["hash-one", "hash-two"],
|
|
72
|
+
failures: 0,
|
|
73
|
+
lastFailedAt: "",
|
|
74
|
+
lockedUntil: "",
|
|
75
|
+
createdAt: at,
|
|
76
|
+
updatedAt: at
|
|
77
|
+
}]);
|
|
78
|
+
assert.equal(await backend.withTransaction((tx) => tx.sessions.clearSecondFactorForUser("usr_ada")), 1);
|
|
79
|
+
assert.equal(await backend.withTransaction((tx) => tx.sessions.clearSecondFactorForUser("usr_ada")), 0, "a session without a proof is left alone");
|
|
80
|
+
assert.equal((await backend.withTransaction((tx) => tx.sessions.findById("ses_ada"))).secondFactorAt, "");
|
|
81
|
+
|
|
82
|
+
await backend.withTransaction(async (tx) => {
|
|
83
|
+
await tx.users.create({ id: "usr_bob", email: "bob@example.com", displayName: "Bob", password: {}, createdAt: at });
|
|
84
|
+
await tx.sessions.create({ id: "ses_bob", userId: "usr_bob", tokenHash: "hash-bob", expiresAt: "2026-12-01T00:00:00.000Z", createdAt: at });
|
|
85
|
+
});
|
|
86
|
+
await knex(LOCAL_AUTH_DB_TABLES.users).where({ id: "usr_ada" }).delete();
|
|
87
|
+
assert.deepEqual(await knex(LOCAL_AUTH_DB_TABLES.secondFactors).select("user_id"), []);
|
|
88
|
+
|
|
89
|
+
// Down removes the table and the sessions' column, keeping Bob's session; up brings both back.
|
|
90
|
+
const schema = async () => [
|
|
91
|
+
await knex.schema.hasTable(LOCAL_AUTH_DB_TABLES.secondFactors),
|
|
92
|
+
await knex.schema.hasColumn(LOCAL_AUTH_DB_TABLES.sessions, "second_factor_at")
|
|
93
|
+
];
|
|
94
|
+
await secondFactorsMigration.down(knex);
|
|
95
|
+
assert.deepEqual(await schema(), [false, false]);
|
|
96
|
+
assert.deepEqual(await knex(LOCAL_AUTH_DB_TABLES.sessions).pluck("id"), ["ses_bob"]);
|
|
97
|
+
await secondFactorsMigration.up(knex);
|
|
98
|
+
assert.deepEqual(await schema(), [true, true]);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export { secondFactorCases };
|