@jskit-ai/auth-provider-local-db-core 0.1.151 → 0.1.153

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.
@@ -0,0 +1,42 @@
1
+ const SIGN_IN_FAILURES_TABLE = "auth_local_sign_in_failures";
2
+ const REGISTRATIONS_TABLE = "auth_local_registrations";
3
+
4
+ exports.up = async function up(knex) {
5
+ // An account email's recent failed sign-ins, kept whether or not the account
6
+ // exists; a successful sign-in or a password reset deletes it, and it is
7
+ // forgotten a day after its last failure.
8
+ if (!(await knex.schema.hasTable(SIGN_IN_FAILURES_TABLE))) {
9
+ await knex.schema.createTable(SIGN_IN_FAILURES_TABLE, (table) => {
10
+ table.string("email", 320).primary();
11
+ table.integer("failures").unsigned().notNullable();
12
+ table.timestamp("last_failed_at").notNullable();
13
+ table.timestamp("locked_until").nullable();
14
+ table.index(["last_failed_at"], "idx_auth_local_sign_in_failures_last");
15
+ });
16
+ }
17
+
18
+ // A registration waiting for its email to be confirmed: the account it will
19
+ // create and the hash of its link's code. Confirming deletes it.
20
+ if (!(await knex.schema.hasTable(REGISTRATIONS_TABLE))) {
21
+ await knex.schema.createTable(REGISTRATIONS_TABLE, (table) => {
22
+ table.string("email", 320).primary();
23
+ table.string("display_name", 160).notNullable();
24
+ table.string("password_algorithm", 64).notNullable();
25
+ table.string("password_version", 32).notNullable();
26
+ table.string("password_salt", 256).notNullable();
27
+ table.string("password_hash", 512).notNullable();
28
+ table.string("invitation_token", 2048).nullable();
29
+ table.string("invitation_source", 120).nullable();
30
+ table.string("token_hash", 128).notNullable();
31
+ table.timestamp("created_at").notNullable();
32
+ table.timestamp("expires_at").notNullable();
33
+ table.unique(["token_hash"], "uq_auth_local_registrations_token_hash");
34
+ table.index(["expires_at"], "idx_auth_local_registrations_expires");
35
+ });
36
+ }
37
+ };
38
+
39
+ exports.down = async function down(knex) {
40
+ await knex.schema.dropTableIfExists(REGISTRATIONS_TABLE);
41
+ await knex.schema.dropTableIfExists(SIGN_IN_FAILURES_TABLE);
42
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-db-core",
3
- "version": "0.1.151",
3
+ "version": "0.1.153",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -10,11 +10,11 @@
10
10
  "./server/lib/index": "./src/server/lib/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/auth-provider-local-core": "0.2.10",
14
- "@jskit-ai/database-runtime": "0.1.257"
13
+ "@jskit-ai/auth-provider-local-core": "0.2.12",
14
+ "@jskit-ai/database-runtime": "0.1.259"
15
15
  },
16
16
  "peerDependencies": {
17
- "@jskit-ai/kernel": "0.2.8"
17
+ "@jskit-ai/kernel": "0.2.10"
18
18
  },
19
19
  "description": "Database-backed local auth storage backend for JSKIT local auth.",
20
20
  "jskit": {
@@ -58,6 +58,12 @@
58
58
  },
59
59
  {
60
60
  "tableName": "auth_local_oauth_attempts"
61
+ },
62
+ {
63
+ "tableName": "auth_local_sign_in_failures"
64
+ },
65
+ {
66
+ "tableName": "auth_local_registrations"
61
67
  }
62
68
  ]
63
69
  }
@@ -5,7 +5,9 @@ const TABLES = Object.freeze({
5
5
  sessions: "auth_local_sessions",
6
6
  recovery: "auth_local_recovery",
7
7
  identities: "auth_local_identities",
8
- oauthAttempts: "auth_local_oauth_attempts"
8
+ oauthAttempts: "auth_local_oauth_attempts",
9
+ signInFailures: "auth_local_sign_in_failures",
10
+ registrations: "auth_local_registrations"
9
11
  });
10
12
 
11
13
  function nowIso() {
@@ -128,6 +130,47 @@ function mapOAuthAttempt(row) {
128
130
  };
129
131
  }
130
132
 
133
+ function mapSignInFailures(row) {
134
+ if (!row) {
135
+ return null;
136
+ }
137
+ 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)
142
+ };
143
+ }
144
+
145
+ function mapRegistration(row) {
146
+ if (!row) {
147
+ return null;
148
+ }
149
+ const invitationToken = String(row.invitation_token || "");
150
+ 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)
158
+ };
159
+ }
160
+
161
+ function registrationRow(record = {}) {
162
+ 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)
171
+ };
172
+ }
173
+
131
174
  function userInsert(input = {}) {
132
175
  const createdAt = requiredDateTime(input.createdAt);
133
176
  return {
@@ -200,6 +243,9 @@ function createLocalDbBackend({ knex, transactionManager }) {
200
243
  async findByEmail(email) {
201
244
  return mapUser(await table(client, TABLES.users).where({ email: String(email || "") }).first());
202
245
  },
246
+ async hasAny() {
247
+ return Boolean(await table(client, TABLES.users).first("id"));
248
+ },
203
249
  async updatePassword(userId, passwordRecord) {
204
250
  const updatedAt = requiredDateTime();
205
251
  await table(client, TABLES.users)
@@ -360,6 +406,56 @@ function createLocalDbBackend({ knex, transactionManager }) {
360
406
  .delete();
361
407
  return Number(count || 0);
362
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
+ }
363
459
  })
364
460
  });
365
461
  }
@@ -0,0 +1,24 @@
1
+ import test from "node:test";
2
+ import createKnex from "knex";
3
+ import initialMigration from "../migrations/auth_local_db_initial.cjs";
4
+ import oauthMigration from "../migrations/auth_local_db_oauth.cjs";
5
+ import protectionMigration from "../migrations/auth_local_db_protection.cjs";
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 { exerciseEmailConfirmation } from "../../auth-provider-local-core/test-support/emailConfirmationScenario.js";
9
+ import { createLocalDbBackend, LOCAL_AUTH_DB_TABLES } from "../src/server/lib/index.js";
10
+
11
+ test("registration waits for its email to be confirmed, with a hashed, single-use, expiring link (database backend)", async (t) => {
12
+ const knex = createKnex({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
13
+ t.after(() => knex.destroy());
14
+ await initialMigration.up(knex);
15
+ await oauthMigration.up(knex);
16
+ await protectionMigration.up(knex);
17
+ const backend = createLocalDbBackend({ knex, transactionManager: { inTransaction: (work) => knex.transaction(work) } });
18
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-06T10:00:00.000Z") });
19
+
20
+ // "" leaves AUTH_LOCAL_EMAIL_CONFIRMATION unset: confirmation on, its default.
21
+ const service = createLocalAuthService({ ...localServiceOptions({ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" } }), backend });
22
+ await exerciseEmailConfirmation(t, service, async () =>
23
+ JSON.stringify(await knex(LOCAL_AUTH_DB_TABLES.registrations).select()));
24
+ });
@@ -0,0 +1,47 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import createKnex from "knex";
7
+ import initialMigration from "../migrations/auth_local_db_initial.cjs";
8
+ import oauthMigration from "../migrations/auth_local_db_oauth.cjs";
9
+ import protectionMigration from "../migrations/auth_local_db_protection.cjs";
10
+ import { createFirstAccountSetup, createLocalAuthService } from "../../auth-provider-local-core/src/server/lib/index.js";
11
+ import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
12
+ import { createLocalDbBackend } from "../src/server/lib/index.js";
13
+
14
+ test("a production server whose database has no account asks its first registration for the setup code (database backend)", async (t) => {
15
+ const knex = createKnex({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
16
+ t.after(() => knex.destroy());
17
+ await initialMigration.up(knex);
18
+ await oauthMigration.up(knex);
19
+ await protectionMigration.up(knex);
20
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-db-setup-"));
21
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
22
+ const backend = createLocalDbBackend({ knex, transactionManager: { inTransaction: (work) => knex.transaction(work) } });
23
+ const options = localServiceOptions({
24
+ env: { NODE_ENV: "production", AUTH_LOCAL_STORE_DIR: storeDir, AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
25
+ });
26
+ const codes = [];
27
+ const logger = { info() {}, warn: (fields) => codes.push(fields.firstAccountSetupCode), error() {}, debug() {} };
28
+
29
+ const start = async () => {
30
+ const firstAccountSetup = createFirstAccountSetup({ backend, config: options.config, logger });
31
+ await firstAccountSetup.start();
32
+ return createLocalAuthService({ ...options, backend, logger, firstAccountSetup });
33
+ };
34
+ const service = await start();
35
+ assert.equal(codes.length, 1);
36
+ assert.equal(service.getCapabilities().features.firstAccountSetupCode, true);
37
+ await assert.rejects(service.register({ email: "owner@example.com", password: "correct horse battery staple" }), {
38
+ code: "auth.local.setup.codeRequired"
39
+ });
40
+ await service.register({ email: "owner@example.com", password: "correct horse battery staple", setupCode: codes[0] });
41
+ assert.equal(service.getCapabilities().features.firstAccountSetupCode, false);
42
+
43
+ // Restarted with an account in the database, it makes no code.
44
+ const restarted = await start();
45
+ assert.equal(codes.length, 1);
46
+ assert.equal(restarted.getCapabilities().features.firstAccountSetupCode, false);
47
+ });
@@ -57,7 +57,7 @@ function createMemoryKnex() {
57
57
  this.filters = [];
58
58
  }
59
59
 
60
- where(criteria, value) {
60
+ where(criteria, ...rest) {
61
61
  if (criteria && typeof criteria === "object") {
62
62
  for (const [key, expected] of Object.entries(criteria)) {
63
63
  this.filters.push((row) => row[key] === expected);
@@ -65,7 +65,14 @@ function createMemoryKnex() {
65
65
  return this;
66
66
  }
67
67
  const key = String(criteria || "");
68
- this.filters.push((row) => row[key] === value);
68
+ if (rest.length === 2) {
69
+ const [operator, limit] = rest;
70
+ const compare = { "<": (left, right) => left < right, "<=": (left, right) => left <= right }[operator];
71
+ assert.ok(compare, `unsupported operator ${operator}`);
72
+ this.filters.push((row) => compare(new Date(row[key]).getTime(), new Date(limit).getTime()));
73
+ return this;
74
+ }
75
+ this.filters.push((row) => row[key] === rest[0]);
69
76
  return this;
70
77
  }
71
78
 
@@ -87,10 +94,36 @@ function createMemoryKnex() {
87
94
  return clone(rowsFor(this.tableName).find((row) => this.matches(row)) || null);
88
95
  }
89
96
 
90
- async insert(row) {
91
- assertUnique(this.tableName, row);
92
- rowsFor(this.tableName).push(clone(row));
93
- return [row.id];
97
+ // insert(row) inserts when awaited; insert(row).onConflict(column).merge() replaces the row with that column's value.
98
+ insert(row) {
99
+ const rows = rowsFor(this.tableName);
100
+ const append = async () => {
101
+ assertUnique(this.tableName, row);
102
+ rows.push(clone(row));
103
+ return [row.id];
104
+ };
105
+ return {
106
+ onConflict: (column) => ({
107
+ merge: async () => {
108
+ const index = rows.findIndex((existing) => existing[column] === row[column]);
109
+ if (index < 0) {
110
+ rows.push(clone(row));
111
+ } else {
112
+ rows[index] = clone(row);
113
+ }
114
+ return [row[column]];
115
+ }
116
+ }),
117
+ then: (resolve, reject) => append().then(resolve, reject)
118
+ };
119
+ }
120
+
121
+ async delete() {
122
+ const rows = rowsFor(this.tableName);
123
+ const kept = rows.filter((row) => !this.matches(row));
124
+ const count = rows.length - kept.length;
125
+ rows.splice(0, rows.length, ...kept);
126
+ return count;
94
127
  }
95
128
 
96
129
  async update(patch) {
@@ -470,7 +503,9 @@ test("package metadata declares portable local auth DB migrations without instal
470
503
  LOCAL_AUTH_DB_TABLES.sessions,
471
504
  LOCAL_AUTH_DB_TABLES.recovery,
472
505
  LOCAL_AUTH_DB_TABLES.identities,
473
- LOCAL_AUTH_DB_TABLES.oauthAttempts
506
+ LOCAL_AUTH_DB_TABLES.oauthAttempts,
507
+ LOCAL_AUTH_DB_TABLES.signInFailures,
508
+ LOCAL_AUTH_DB_TABLES.registrations
474
509
  ]
475
510
  );
476
511
  });
@@ -493,6 +528,7 @@ test("installing the DB backend capability makes local auth database-backed", as
493
528
  AUTH_LOCAL_SESSION_SECRET: "test-secret",
494
529
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "response",
495
530
  APP_PUBLIC_URL: "http://localhost:5173",
531
+ AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
496
532
  NODE_ENV: "test"
497
533
  },
498
534
  "runtime.logger": console,
@@ -0,0 +1,25 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import createKnex from "knex";
4
+ import initialMigration from "../migrations/auth_local_db_initial.cjs";
5
+ import oauthMigration from "../migrations/auth_local_db_oauth.cjs";
6
+ import protectionMigration from "../migrations/auth_local_db_protection.cjs";
7
+ import { createLocalAuthService } from "../../auth-provider-local-core/src/server/lib/index.js";
8
+ import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
9
+ import { exerciseSignInThrottle } from "../../auth-provider-local-core/test-support/signInThrottleScenario.js";
10
+ import { createLocalDbBackend, LOCAL_AUTH_DB_TABLES } from "../src/server/lib/index.js";
11
+
12
+ test("failed sign-ins make the account wait, doubling, and a success forgets them (database backend)", async (t) => {
13
+ const knex = createKnex({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
14
+ t.after(() => knex.destroy());
15
+ await initialMigration.up(knex);
16
+ await oauthMigration.up(knex);
17
+ await protectionMigration.up(knex);
18
+ const backend = createLocalDbBackend({ knex, transactionManager: { inTransaction: (work) => knex.transaction(work) } });
19
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-06T10:00:00.000Z") });
20
+
21
+ await exerciseSignInThrottle(t, createLocalAuthService({ ...localServiceOptions(), backend }));
22
+
23
+ // The success cleared the account's record and the day-old ones were deleted.
24
+ assert.deepEqual(await knex(LOCAL_AUTH_DB_TABLES.signInFailures).select("email"), []);
25
+ });