@jskit-ai/auth-provider-local-db-core 0.1.181 → 0.1.183

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 CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Used one-time passes in the database: the table `auth_local_used_passes` (the hash of each pass's id, until it expires), created by the new migration `auth_local_db_used_passes`, behind the backend contract's `passes` collection, so a pass one server accepted is refused by every server on the database. Two first uses at once both find no row, and the later one's duplicate entry runs its transaction again, which finds it. `LOCAL_AUTH_DB_TABLES.passes` names the table, which the package owns.
5
6
  - The package manifest no longer requires `runtime.actions`: its feature declares no actions, so since the kernel's 9646ecf21 it does not require the action catalogue, and the catalog's manifest check reported the requirement as one no server provider has.
6
7
  - 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.
7
8
  - `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.
@@ -0,0 +1,20 @@
1
+ const USED_PASSES_TABLE = "auth_local_used_passes";
2
+
3
+ exports.up = async function up(knex) {
4
+ // A one-time sign-in pass that signed someone in, or was refused after its
5
+ // first use was recorded: the hash of the pass's id, kept until the pass
6
+ // could no longer be used anyway, so every server sharing the database
7
+ // refuses it again.
8
+ if (!(await knex.schema.hasTable(USED_PASSES_TABLE))) {
9
+ await knex.schema.createTable(USED_PASSES_TABLE, (table) => {
10
+ table.string("id", 64).primary();
11
+ table.timestamp("expires_at").notNullable();
12
+ table.timestamp("created_at").notNullable();
13
+ table.index(["expires_at"], "idx_auth_local_used_passes_expires");
14
+ });
15
+ }
16
+ };
17
+
18
+ exports.down = async function down(knex) {
19
+ await knex.schema.dropTableIfExists(USED_PASSES_TABLE);
20
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-db-core",
3
- "version": "0.1.181",
3
+ "version": "0.1.183",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -11,11 +11,11 @@
11
11
  "./server/types": "./src/server/types.js"
12
12
  },
13
13
  "dependencies": {
14
- "@jskit-ai/auth-provider-local-core": "0.2.32",
14
+ "@jskit-ai/auth-provider-local-core": "0.2.34",
15
15
  "@jskit-ai/resource-core": "0.1.217"
16
16
  },
17
17
  "peerDependencies": {
18
- "@jskit-ai/auth-core": "0.2.27",
18
+ "@jskit-ai/auth-core": "0.2.29",
19
19
  "@jskit-ai/database-runtime": "0.1.275",
20
20
  "@jskit-ai/kernel": "0.2.26",
21
21
  "@jskit-ai/resource-runtime": "0.2.33"
@@ -75,6 +75,9 @@
75
75
  },
76
76
  {
77
77
  "tableName": "auth_local_second_factors"
78
+ },
79
+ {
80
+ "tableName": "auth_local_used_passes"
78
81
  }
79
82
  ]
80
83
  }
@@ -4,6 +4,7 @@ import { ConflictError } from "@jskit-ai/kernel/server/runtime/errors";
4
4
  import { passedOn } from "@jskit-ai/resource-runtime/server";
5
5
  import { IDENTITIES_TABLE } from "./identityStore.js";
6
6
  import { secondFactorRecords } from "./secondFactorRecords.js";
7
+ import { usedPassRecords } from "./usedPassRecords.js";
7
8
  import {
8
9
  deleteById,
9
10
  findById,
@@ -24,7 +25,8 @@ const TABLES = Object.freeze({
24
25
  oauthAttempts: "auth_local_oauth_attempts",
25
26
  signInFailures: "auth_local_sign_in_failures",
26
27
  registrations: "auth_local_registrations",
27
- secondFactors: "auth_local_second_factors"
28
+ secondFactors: "auth_local_second_factors",
29
+ passes: "auth_local_used_passes"
28
30
  });
29
31
 
30
32
  // The tables local sign-in keeps outside table resources, for an app test's expectEveryTableOwned infrastructureTables.
@@ -504,6 +506,7 @@ function registrationRecords(registrations, options) {
504
506
  * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthSignInFailures
505
507
  * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthRegistrations
506
508
  * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthSecondFactors
509
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} localAuthUsedPasses
507
510
  */
508
511
 
509
512
  /**
@@ -526,7 +529,8 @@ function createRecords(resources, identities, options) {
526
529
  oauthAttempts: oauthAttemptRecords(resources.localAuthOAuthAttempts, options),
527
530
  signInFailures: signInFailureRecords(resources.localAuthSignInFailures, options),
528
531
  registrations: registrationRecords(resources.localAuthRegistrations, options),
529
- secondFactors: secondFactorRecords(resources.localAuthSecondFactors, options)
532
+ secondFactors: secondFactorRecords(resources.localAuthSecondFactors, options),
533
+ passes: usedPassRecords(resources.localAuthUsedPasses, options)
530
534
  });
531
535
  }
532
536
 
@@ -168,6 +168,20 @@ const localAuthSecondFactorResource = defineTableResource({
168
168
  }
169
169
  });
170
170
 
171
+ // auth_local_used_passes: a one-time sign-in pass already used, keyed by the hash of its id, until it expires.
172
+ const localAuthUsedPassResource = defineTableResource({
173
+ name: "localAuthUsedPasses",
174
+ tableName: "auth_local_used_passes",
175
+ ownership: "public",
176
+ schema: {
177
+ expiresAt: dateTime,
178
+ createdAt: dateTime
179
+ },
180
+ searchSchema: {
181
+ expiresAtOrBefore
182
+ }
183
+ });
184
+
171
185
  const LOCAL_AUTH_RESOURCES = Object.freeze([
172
186
  localAuthUserResource,
173
187
  localAuthSessionResource,
@@ -175,7 +189,8 @@ const LOCAL_AUTH_RESOURCES = Object.freeze([
175
189
  localAuthOAuthAttemptResource,
176
190
  localAuthSignInFailureResource,
177
191
  localAuthRegistrationResource,
178
- localAuthSecondFactorResource
192
+ localAuthSecondFactorResource,
193
+ localAuthUsedPassResource
179
194
  ]);
180
195
 
181
196
  export {
@@ -186,5 +201,6 @@ export {
186
201
  localAuthSecondFactorResource,
187
202
  localAuthSessionResource,
188
203
  localAuthSignInFailureResource,
204
+ localAuthUsedPassResource,
189
205
  localAuthUserResource
190
206
  };
@@ -0,0 +1,29 @@
1
+ import { findById, requiredDateTime, text } from "./tableRecords.js";
2
+
3
+ /**
4
+ * Local auth's used one-time passes, by the hash of each pass's id. Two first uses of one pass at once, on one server
5
+ * or two, both find no row and both create it: the later fails with a duplicate entry, its transaction rolls back, and
6
+ * the backend runs it again, which finds the row and answers false.
7
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} usedPasses
8
+ * @param {object} options
9
+ */
10
+ function usedPassRecords(usedPasses, options) {
11
+ return Object.freeze({
12
+ async use(input) {
13
+ const id = text(input.id);
14
+ if (await findById(usedPasses, id, options)) {
15
+ return false;
16
+ }
17
+ await usedPasses.create(
18
+ { id, expiresAt: requiredDateTime(input.expiresAt), createdAt: requiredDateTime() },
19
+ { ...options, returning: "none" }
20
+ );
21
+ return true;
22
+ },
23
+ async deleteExpired(now) {
24
+ return usedPasses.deleteWhere({ expiresAtOrBefore: requiredDateTime(now) }, { ...options, returning: "count" });
25
+ }
26
+ });
27
+ }
28
+
29
+ export { usedPassRecords };
@@ -44,7 +44,8 @@ test("accounts: create answers the account it wrote, reads find it by id and ema
44
44
  oauthAttempts: "auth_local_oauth_attempts",
45
45
  signInFailures: "auth_local_sign_in_failures",
46
46
  registrations: "auth_local_registrations",
47
- secondFactors: "auth_local_second_factors"
47
+ secondFactors: "auth_local_second_factors",
48
+ passes: "auth_local_used_passes"
48
49
  });
49
50
  assert.equal(await backend.withTransaction((tx) => tx.users.hasAny()), false);
50
51
 
@@ -0,0 +1,54 @@
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 { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
6
+ import { createPassIssuer, passIdentityByEmail, passwordlessAccount } from "../../auth-provider-local-core/test-support/passSignInScenario.js";
7
+ import { openLocalAuthDatabase } from "./support/mysqlLocalAuth.js";
8
+
9
+ const usePass = (tx) => tx.passes.use({ id: "hash-of-one-pass", expiresAt: "2026-11-13T10:01:30.000Z" });
10
+
11
+ test("two first uses of one pass at once, as two servers make them, record it once and only one is first", async (context) => {
12
+ requireTestDatabase(process.env);
13
+ const { backend, knex } = await openLocalAuthDatabase(context, "da_local_pass_race");
14
+ const snapshotTaken = Promise.withResolvers();
15
+ const otherCommitted = Promise.withResolvers();
16
+ let attempts = 0;
17
+ // A reads first, so its snapshot is older than B's row; then B records the pass and commits; then A looks for the
18
+ // pass, does not see B's row, and records it too. A's insert meets B's row, its transaction rolls back, and it runs
19
+ // again, seeing the row: A is not first.
20
+ const useA = backend.withTransaction(async (tx) => {
21
+ attempts += 1;
22
+ if (attempts === 1) {
23
+ await tx.users.findById("usr_nobody");
24
+ snapshotTaken.resolve();
25
+ await otherCommitted.promise;
26
+ }
27
+ return usePass(tx);
28
+ });
29
+ await snapshotTaken.promise;
30
+ assert.equal(await backend.withTransaction(usePass), true);
31
+ otherCommitted.resolve();
32
+
33
+ assert.equal(await useA, false);
34
+ assert.equal(attempts, 2);
35
+ assert.equal((await knex("auth_local_used_passes").where({ id: "hash-of-one-pass" })).length, 1);
36
+ });
37
+
38
+ test("of one pass posted to two servers at the same moment, one signs in and the other is refused as replayed", async (context) => {
39
+ requireTestDatabase(process.env);
40
+ const { backend } = await openLocalAuthDatabase(context, "da_local_pass_twice");
41
+ const issuer = createPassIssuer();
42
+ await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
43
+ // Each service has its own connections from the pool, as two servers do.
44
+ const servers = [0, 1].map(() =>
45
+ createLocalAuthService({ ...localServiceOptions({ env: issuer.env }), backend, passIdentity: passIdentityByEmail(backend) }));
46
+
47
+ for (let round = 0; round < 10; round += 1) {
48
+ const pass = issuer.pass("ada@example.com");
49
+ const outcomes = await Promise.allSettled(servers.map((server) => server.signInWithPass({ pass })));
50
+ assert.equal(outcomes.filter(({ status }) => status === "fulfilled").length, 1);
51
+ const [refusal] = outcomes.filter(({ status }) => status === "rejected");
52
+ assert.equal(refusal.reason.code, "auth.pass.replayed");
53
+ }
54
+ });
@@ -0,0 +1,86 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFile } from "node:child_process";
3
+ import fs from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { promisify } from "node:util";
9
+ import { createLocalAuthService } from "../../auth-provider-local-core/src/server/lib/index.js";
10
+ import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
11
+ import {
12
+ createPassIssuer,
13
+ exercisePassSignIn,
14
+ passIdentityByEmail,
15
+ passwordlessAccount
16
+ } from "../../auth-provider-local-core/test-support/passSignInScenario.js";
17
+ import { LOCAL_AUTH_DB_TABLES } from "../src/server/lib/index.js";
18
+ import { openSqliteLocalAuth } from "./support/localAuthRuntime.js";
19
+
20
+ const SERVER_SCRIPT = fileURLToPath(new URL("./support/passSignInServer.js", import.meta.url));
21
+ const runFile = promisify(execFile);
22
+
23
+ function startService(backend, issuer) {
24
+ return createLocalAuthService({ ...localServiceOptions({ env: issuer.env }), backend, passIdentity: passIdentityByEmail(backend) });
25
+ }
26
+
27
+ test("a one-time pass signs its person in once, and every other pass is refused with its reason (database backend)", async (t) => {
28
+ const issuer = createPassIssuer();
29
+ const { backend, knex } = await openSqliteLocalAuth(t);
30
+ await exercisePassSignIn(startService(backend, issuer), { backend, issuer });
31
+
32
+ // The six passes used (two that signed in, three unmapped and the late one), by the hashes of their ids.
33
+ const used = await knex(LOCAL_AUTH_DB_TABLES.passes).select("id");
34
+ assert.equal(used.length, 6);
35
+ assert.ok(used.every(({ id }) => /^[\w-]{43}$/u.test(id)));
36
+ });
37
+
38
+ test("used passes are deleted once they could no longer be used, so the table holds only the last minutes' passes", async (t) => {
39
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-13T10:00:00.000Z") });
40
+ const issuer = createPassIssuer();
41
+ const { backend, knex } = await openSqliteLocalAuth(t);
42
+ await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
43
+ const service = startService(backend, issuer);
44
+ await service.signInWithPass({ pass: issuer.pass("ada@example.com") });
45
+ await service.signInWithPass({ pass: issuer.pass("ada@example.com") });
46
+ assert.equal((await knex(LOCAL_AUTH_DB_TABLES.passes).count({ count: "*" }))[0].count, 2);
47
+
48
+ t.mock.timers.tick(90_000);
49
+ await service.signInWithPass({ pass: issuer.pass("ada@example.com") });
50
+ assert.equal((await knex(LOCAL_AUTH_DB_TABLES.passes).count({ count: "*" }))[0].count, 1);
51
+ });
52
+
53
+ /**
54
+ * Signs in with the pass on a server in a process of its own, over the database file.
55
+ * @param {string} filename
56
+ * @param {string} pass
57
+ * @param {Record<string, string>} env
58
+ */
59
+ async function signInOnAnotherServer(filename, pass, env) {
60
+ const { stdout } = await runFile(process.execPath, [SERVER_SCRIPT, filename, pass], {
61
+ env: { ...process.env, ...env },
62
+ timeout: 30_000
63
+ });
64
+ return JSON.parse(stdout);
65
+ }
66
+
67
+ test("a pass one server accepted is refused by another server on the same database, as replayed", async (t) => {
68
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-pass-db-"));
69
+ t.after(() => fs.rm(directory, { recursive: true, force: true }));
70
+ const filename = path.join(directory, "app.sqlite");
71
+ const { backend, knex } = await openSqliteLocalAuth(t, { filename });
72
+ await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
73
+ const issuer = createPassIssuer();
74
+ const pass = issuer.pass("ada@example.com", { id: "pass-for-two-servers" });
75
+
76
+ assert.deepEqual(await signInOnAnotherServer(filename, pass, issuer.env), { ok: true, userId: "usr_ada" });
77
+ assert.deepEqual(await signInOnAnotherServer(filename, pass, issuer.env), { ok: false, status: 401, code: "auth.pass.replayed" });
78
+ // This process is a third server on the database, and refuses it too.
79
+ await assert.rejects(startService(backend, issuer).signInWithPass({ pass }), { status: 401, code: "auth.pass.replayed" });
80
+ // The issuer's next pass signs in on the second server.
81
+ assert.deepEqual(await signInOnAnotherServer(filename, issuer.pass("ada@example.com"), issuer.env), { ok: true, userId: "usr_ada" });
82
+
83
+ const used = await knex(LOCAL_AUTH_DB_TABLES.passes).select("id");
84
+ assert.equal(used.length, 2);
85
+ assert.ok(used.every(({ id }) => id !== "pass-for-two-servers"));
86
+ });
@@ -417,7 +417,8 @@ test("package metadata declares portable local auth DB migrations without instal
417
417
  LOCAL_AUTH_DB_TABLES.oauthAttempts,
418
418
  LOCAL_AUTH_DB_TABLES.signInFailures,
419
419
  LOCAL_AUTH_DB_TABLES.registrations,
420
- LOCAL_AUTH_DB_TABLES.secondFactors
420
+ LOCAL_AUTH_DB_TABLES.secondFactors,
421
+ LOCAL_AUTH_DB_TABLES.passes
421
422
  ]
422
423
  );
423
424
  });
@@ -6,15 +6,17 @@ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResourc
6
6
  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
+ import usedPassesMigration from "../../migrations/auth_local_db_used_passes.cjs";
9
10
  import emailVerifiedMigration from "../../migrations/auth_local_db_users_email_verified.cjs";
10
11
  import secondFactorsMigration from "../../migrations/auth_local_db_users_second_factors.cjs";
11
12
  import { AuthLocalDatabaseBackendProvider } from "../../src/server/providers/AuthLocalDatabaseBackendProvider.js";
12
13
 
13
- // Every local auth migration, in order.
14
+ // Every local auth migration, in the order Knex runs their files.
14
15
  const LOCAL_AUTH_MIGRATIONS = Object.freeze([
15
16
  initialMigration,
16
17
  oauthMigration,
17
18
  protectionMigration,
19
+ usedPassesMigration,
18
20
  emailVerifiedMigration,
19
21
  secondFactorsMigration
20
22
  ]);
@@ -87,15 +89,16 @@ async function startLocalAuthRecords(knex) {
87
89
  }
88
90
 
89
91
  /**
90
- * A migrated in-memory SQLite database of the test's own, which enforces its foreign keys and is closed after the
91
- * test.
92
+ * A migrated SQLite database of the test's own, in memory unless `filename` names a file, which enforces its foreign
93
+ * keys and is closed after the test.
92
94
  * @param {import("node:test").TestContext} context
93
- * @param {{ acquireConnectionTimeout?: number }} [options] how long a query waits for the pool's one connection
95
+ * @param {{ acquireConnectionTimeout?: number, filename?: string }} [options] how long a query waits for the pool's one
96
+ * connection, and the database file
94
97
  */
95
- async function openMigratedSqlite(context, { acquireConnectionTimeout = 60_000 } = {}) {
98
+ async function openMigratedSqlite(context, { acquireConnectionTimeout = 60_000, filename = ":memory:" } = {}) {
96
99
  const knex = createKnex({
97
100
  client: "better-sqlite3",
98
- connection: { filename: ":memory:" },
101
+ connection: { filename },
99
102
  useNullAsDefault: true,
100
103
  acquireConnectionTimeout
101
104
  });
@@ -0,0 +1,41 @@
1
+ // One server of the two-server replay test, in a process of its own: local auth on the database backend, over the
2
+ // SQLite file the test migrated (argv[2]), trusting the issuer the AUTH_PASS_* env names. It signs in once with the
3
+ // pass in argv[3] and prints the outcome as JSON.
4
+ import createKnex from "knex";
5
+ import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
6
+ import { createLocalAuthService } from "../../../auth-provider-local-core/src/server/lib/index.js";
7
+ import { localServiceOptions } from "../../../auth-provider-local-core/test-support/localService.js";
8
+ import { passIdentityByEmail } from "../../../auth-provider-local-core/test-support/passSignInScenario.js";
9
+ import { AuthLocalDatabaseBackendProvider } from "../../src/server/providers/AuthLocalDatabaseBackendProvider.js";
10
+ import { localAuthRuntimeInputs } from "./localAuthRuntime.js";
11
+
12
+ const [filename, pass] = process.argv.slice(2);
13
+ const knex = createKnex({ client: "better-sqlite3", connection: { filename }, useNullAsDefault: true });
14
+ try {
15
+ const { inputs } = await localAuthRuntimeInputs(knex);
16
+ let backend = null;
17
+ const probe = defineProvider({
18
+ id: "test.auth.pass-server",
19
+ requires: { started: "auth.local.backend" },
20
+ setup({ started }) {
21
+ backend = started;
22
+ return {};
23
+ }
24
+ });
25
+ await createCapabilityRuntime({ inputs, providers: [AuthLocalDatabaseBackendProvider, probe] }).start();
26
+ const { AUTH_PASS_PUBLIC_KEY, AUTH_PASS_AUDIENCE, AUTH_PASS_RESOURCE } = process.env;
27
+ const service = createLocalAuthService({
28
+ ...localServiceOptions({ env: { AUTH_PASS_PUBLIC_KEY, AUTH_PASS_AUDIENCE, AUTH_PASS_RESOURCE } }),
29
+ backend,
30
+ passIdentity: passIdentityByEmail(backend)
31
+ });
32
+ let outcome;
33
+ try {
34
+ outcome = { ok: true, userId: (await service.signInWithPass({ pass })).actor.id };
35
+ } catch (error) {
36
+ outcome = { ok: false, status: error.status, code: error.code };
37
+ }
38
+ process.stdout.write(JSON.stringify(outcome));
39
+ } finally {
40
+ await knex.destroy();
41
+ }