@jskit-ai/auth-provider-local-db-core 0.1.198 → 0.1.200

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
+ - The migration `auth_local_db_sign_in_facts` adds nullable `sign_in_ip` and `sign_in_user_agent` columns to `auth_local_sessions` (where a session was signed in from, written once at its creation) and nullable `password_changed_at` and `email_changed_at` timestamps to `auth_local_users` (set by `updatePassword`, a reset or a change, and by a used email-change link). Run `npm run db:migrate`. Rows from before it keep null: their sessions answer no sign-in address or browser, so an action that asks for them makes their people sign in again. The owner APIs carry them: `auth.local.sessions.create` takes `signInIp` and `signInUserAgent`, sessions answer them, accounts answer `passwordChangedAt` and `emailChangedAt`, and `auth.local.accounts.updatePassword` sets `passwordChangedAt`.
5
6
  - The migration `auth_local_db_oauth_invitation` adds a nullable `invitation_token` text column to `auth_local_oauth_attempts`, where a provider sign-in started from an invitation keeps its token until the sign-in ends. Run `npm run db:migrate`.
6
7
  - Each table migration has a companion that Knex runs just before it, `auth_local_db_initial-collation`, `auth_local_db_oauth-collation`, `auth_local_db_protection-collation`, `auth_local_db_used_passes-collation` and `auth_local_db_users_second_factors-collation` (run `npm run db:migrate`): on MySQL and MariaDB each creates its migration's tables in the collation of `auth_local_users` (or `users`), not the database's default. On a database whose default differs from its tables', `auth_local_db_users_second_factors` failed (errno 150) and left an empty, unrecorded `auth_local_second_factors`, after recording `auth_local_used_passes` in the database's default; the next migrate creates the first again with its key to `auth_local_users`, converts the second keeping its rows, and adds the key a second try recorded without. A database whose tables match its default changes nothing. No released migration changed.
7
8
  - A user's waiting email change, in the new nullable column `auth_local_users.pending_email` (migration `auth_local_db_users_pending_email`; run `npm run db:migrate`), behind the backend contract's `pendingEmail`, `users.updatePendingEmail` and `users.updateEmail`. Changing the email clears the waiting change and sets `email_verified_at`, which the link sent to the address proves; an email another account has is refused with `auth.local.accounts.exists`.
@@ -0,0 +1,34 @@
1
+ // How each session was signed in, and when each account's credentials last changed, kept as they happened, for an
2
+ // action that asks more of the session that requests it. A session's sign_in_ip and sign_in_user_agent are the
3
+ // address and browser of the request that signed it in, written once (ip and user_agent are where it was last seen).
4
+ // An account's password_changed_at is when its password was last reset or changed, and email_changed_at when its
5
+ // email last changed to a confirmed address. Null when unknown, as for sessions and changes from before.
6
+ const SESSIONS_TABLE = "auth_local_sessions";
7
+ const USERS_TABLE = "auth_local_users";
8
+ const IP_MAX_LENGTH = 64;
9
+ const USER_AGENT_MAX_LENGTH = 512;
10
+
11
+ const COLUMNS = Object.freeze([
12
+ [SESSIONS_TABLE, "sign_in_ip", (table) => table.string("sign_in_ip", IP_MAX_LENGTH).nullable()],
13
+ [SESSIONS_TABLE, "sign_in_user_agent", (table) => table.string("sign_in_user_agent", USER_AGENT_MAX_LENGTH).nullable()],
14
+ [USERS_TABLE, "password_changed_at", (table) => table.timestamp("password_changed_at").nullable()],
15
+ [USERS_TABLE, "email_changed_at", (table) => table.timestamp("email_changed_at").nullable()]
16
+ ]);
17
+
18
+ exports.up = async function up(knex) {
19
+ for (const [tableName, name, add] of COLUMNS) {
20
+ if (!(await knex.schema.hasColumn(tableName, name))) {
21
+ await knex.schema.alterTable(tableName, add);
22
+ }
23
+ }
24
+ };
25
+
26
+ exports.down = async function down(knex) {
27
+ for (const [tableName, name] of COLUMNS) {
28
+ if (await knex.schema.hasColumn(tableName, name)) {
29
+ await knex.schema.alterTable(tableName, (table) => {
30
+ table.dropColumn(name);
31
+ });
32
+ }
33
+ }
34
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-db-core",
3
- "version": "0.1.198",
3
+ "version": "0.1.200",
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.42",
15
- "@jskit-ai/resource-core": "0.1.223"
14
+ "@jskit-ai/auth-provider-local-core": "0.2.44",
15
+ "@jskit-ai/resource-core": "0.1.224"
16
16
  },
17
17
  "peerDependencies": {
18
- "@jskit-ai/auth-core": "0.2.36",
19
- "@jskit-ai/database-runtime": "0.1.282",
20
- "@jskit-ai/kernel": "0.2.32",
21
- "@jskit-ai/resource-runtime": "0.2.46"
18
+ "@jskit-ai/auth-core": "0.2.38",
19
+ "@jskit-ai/database-runtime": "0.1.283",
20
+ "@jskit-ai/kernel": "0.2.33",
21
+ "@jskit-ai/resource-runtime": "0.2.47"
22
22
  },
23
23
  "description": "Database-backed local auth storage backend for JSKIT local auth.",
24
24
  "jskit": {
@@ -103,7 +103,9 @@ function mapUser(record) {
103
103
  emailVerifiedAt: readDateTime(record.emailVerifiedAt),
104
104
  disabled: record.disabled === true || record.disabled === 1 || record.disabled === "1",
105
105
  disabledMessage: text(record.disabledMessage),
106
- pendingEmail: text(record.pendingEmail)
106
+ pendingEmail: text(record.pendingEmail),
107
+ passwordChangedAt: readDateTime(record.passwordChangedAt),
108
+ emailChangedAt: readDateTime(record.emailChangedAt)
107
109
  };
108
110
  }
109
111
 
@@ -122,7 +124,9 @@ function mapSession(record) {
122
124
  secondFactorAt: readDateTime(record.secondFactorAt),
123
125
  ip: text(record.ip),
124
126
  userAgent: text(record.userAgent),
125
- lastSeenAt: readDateTime(record.lastSeenAt)
127
+ lastSeenAt: readDateTime(record.lastSeenAt),
128
+ signInIp: text(record.signInIp),
129
+ signInUserAgent: text(record.signInUserAgent)
126
130
  };
127
131
  }
128
132
 
@@ -227,6 +231,8 @@ function sessionRecord(input = {}) {
227
231
  ip: input.ip ? String(input.ip) : null,
228
232
  userAgent: input.userAgent ? String(input.userAgent) : null,
229
233
  lastSeenAt: optionalDateTime(input.lastSeenAt),
234
+ signInIp: input.signInIp ? String(input.signInIp) : null,
235
+ signInUserAgent: input.signInUserAgent ? String(input.signInUserAgent) : null,
230
236
  createdAt,
231
237
  updatedAt: requiredDateTime(input.updatedAt, createdAt)
232
238
  };
@@ -289,8 +295,11 @@ function userRecords(users, options) {
289
295
  async hasAny() {
290
296
  return (await users.query({ page: { size: 1 } }, options)).records.length > 0;
291
297
  },
298
+ // A reset and a change alike: the password changed now.
292
299
  async updatePassword(userId, passwordRecord) {
293
- return mapUser(await patchExisting(users, userId, { ...writePassword(passwordRecord), updatedAt: requiredDateTime() }, options));
300
+ const now = requiredDateTime();
301
+ const changes = { ...writePassword(passwordRecord), passwordChangedAt: now, updatedAt: now };
302
+ return mapUser(await patchExisting(users, userId, changes, options));
294
303
  },
295
304
  async updateProfile(userId, updates = {}) {
296
305
  const changes = { updatedAt: requiredDateTime() };
@@ -324,10 +333,11 @@ function userRecords(users, options) {
324
333
  const changes = { pendingEmail: text(pendingEmail) || null, updatedAt: requiredDateTime() };
325
334
  return mapUser(await patchExisting(users, userId, changes, options));
326
335
  },
327
- // The email changes to an address its link proved, confirmed from now; another account's email is refused.
336
+ // The email changes to an address its link proved, confirmed and changed from now; another account's email is
337
+ // refused.
328
338
  async updateEmail(userId, email) {
329
339
  const now = requiredDateTime();
330
- const changes = { email: text(email), pendingEmail: null, emailVerifiedAt: now, updatedAt: now };
340
+ const changes = { email: text(email), pendingEmail: null, emailVerifiedAt: now, emailChangedAt: now, updatedAt: now };
331
341
  try {
332
342
  return mapUser(await patchExisting(users, userId, changes, options));
333
343
  } catch (error) {
@@ -419,7 +429,8 @@ function sessionRecords(sessions, options) {
419
429
  { ...options, returning: "count" }
420
430
  );
421
431
  },
422
- // The session seen again: when, and from where when the request said; a missing one changes nothing.
432
+ // The session seen again: when, and from where when the request said; a missing one changes nothing. Where it was
433
+ // signed in from never changes.
423
434
  async touch(sessionId, { lastSeenAt, ip, userAgent } = {}) {
424
435
  const id = text(sessionId);
425
436
  if (!id) {
@@ -691,7 +702,7 @@ function createLocalDbOwners({ resources, identities, context }) {
691
702
  // options.exceptSessionId keeps that session.
692
703
  revokeForUser: (userId, { exceptSessionId, ...options } = {}) => records(options).sessions.revokeForUser(userId, { exceptSessionId }),
693
704
  // The account's live sessions, the newest first, each with where (ip, userAgent) and when (lastSeenAt) it was
694
- // last seen.
705
+ // last seen, and where it was signed in from (signInIp, signInUserAgent).
695
706
  listForUser: (userId, options = {}) => records(options).sessions.listForUser(userId),
696
707
  deleteExpired: (now, options = {}) => records(options).sessions.deleteExpired(now)
697
708
  });
@@ -48,7 +48,11 @@ const localAuthUserResource = defineTableResource({
48
48
  createdAt: dateTime,
49
49
  updatedAt: dateTime,
50
50
  emailVerifiedAt: optionalDateTime,
51
- pendingEmail: { ...text, nullable: true }
51
+ pendingEmail: { ...text, nullable: true },
52
+ // When the password was last reset or changed, and the email last changed to a confirmed address: null when
53
+ // unknown.
54
+ passwordChangedAt: optionalDateTime,
55
+ emailChangedAt: optionalDateTime
52
56
  }
53
57
  });
54
58
 
@@ -69,6 +73,9 @@ const localAuthSessionResource = defineTableResource({
69
73
  ip: { ...text, nullable: true },
70
74
  userAgent: { ...text, nullable: true },
71
75
  lastSeenAt: optionalDateTime,
76
+ // Where the session was signed in from, written once: null when unknown.
77
+ signInIp: { ...text, nullable: true },
78
+ signInUserAgent: { ...text, nullable: true },
72
79
  createdAt: dateTime,
73
80
  updatedAt: dateTime
74
81
  },
@@ -17,8 +17,10 @@ const NEXT_PASSWORD = Object.freeze({ algorithm: "scrypt", version: "2", salt: "
17
17
  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
- const ACCOUNT_KEYS = ["id", "email", "displayName", "password", "createdAt", "updatedAt", "emailVerifiedAt", "disabled", "disabledMessage", "pendingEmail"];
21
- const SESSION_KEYS = ["id", "userId", "tokenHash", "purpose", "createdAt", "expiresAt", "revokedAt", "secondFactorAt", "ip", "userAgent", "lastSeenAt"];
20
+ const ACCOUNT_KEYS = ["id", "email", "displayName", "password", "createdAt", "updatedAt", "emailVerifiedAt", "disabled", "disabledMessage", "pendingEmail",
21
+ "passwordChangedAt", "emailChangedAt"];
22
+ const SESSION_KEYS = ["id", "userId", "tokenHash", "purpose", "createdAt", "expiresAt", "revokedAt", "secondFactorAt", "ip", "userAgent", "lastSeenAt",
23
+ "signInIp", "signInUserAgent"];
22
24
  const RECOVERY_KEYS = ["id", "userId", "tokenHash", "createdAt", "expiresAt", "usedAt"];
23
25
 
24
26
  /** The current second, as the second-precision timestamps keep it. */
@@ -62,7 +64,9 @@ test("accounts: create answers the account it wrote, reads find it by id and ema
62
64
  emailVerifiedAt: "",
63
65
  disabled: false,
64
66
  disabledMessage: "",
65
- pendingEmail: ""
67
+ pendingEmail: "",
68
+ passwordChangedAt: "",
69
+ emailChangedAt: ""
66
70
  }, "create answers what it wrote, to the millisecond, and updatedAt defaults to createdAt");
67
71
 
68
72
  const before = thisSecond();
@@ -113,8 +117,9 @@ test("accounts: password, profile and email-proof updates answer the account aft
113
117
  let before = thisSecond();
114
118
  const repassworded = await backend.withTransaction((tx) => tx.users.updatePassword("usr_ada", NEXT_PASSWORD));
115
119
  assert.deepEqual(Object.keys(repassworded), ACCOUNT_KEYS);
116
- assert.deepEqual({ ...repassworded, updatedAt: "" }, { ...created, password: NEXT_PASSWORD, updatedAt: "" });
120
+ assert.deepEqual({ ...repassworded, updatedAt: "", passwordChangedAt: "" }, { ...created, password: NEXT_PASSWORD, updatedAt: "" });
117
121
  assertStoredSince(repassworded.updatedAt, before, "updatePassword touches updatedAt");
122
+ assert.equal(repassworded.passwordChangedAt, repassworded.updatedAt, "updatePassword stamps when the password changed");
118
123
  assert.deepEqual((await backend.withTransaction((tx) => tx.users.updatePassword("usr_ada", { hash: "only" }))).password,
119
124
  { algorithm: "", version: "", salt: "", hash: "only" }, "missing password fields are written empty");
120
125
  assert.equal(await backend.withTransaction((tx) => tx.users.updatePassword("usr_missing", NEXT_PASSWORD)), null);
@@ -133,6 +138,7 @@ test("accounts: password, profile and email-proof updates answer the account aft
133
138
  before = thisSecond();
134
139
  const verified = await backend.withTransaction((tx) => tx.users.markEmailVerified("usr_ada"));
135
140
  assertStoredSince(verified.emailVerifiedAt, before, "markEmailVerified stamps the proof");
141
+ assert.equal(verified.emailChangedAt, "", "a first proof of the email is no change of it");
136
142
  const updatedAt = verified.updatedAt;
137
143
  const again = await backend.withTransaction((tx) => tx.users.markEmailVerified("usr_ada"));
138
144
  assert.equal(again.emailVerifiedAt, verified.emailVerifiedAt, "the first proof is kept");
@@ -159,7 +165,9 @@ test("sessions: create, reads, revoke once, revoke a user's live sessions but on
159
165
  secondFactorAt: "",
160
166
  ip: "",
161
167
  userAgent: "",
162
- lastSeenAt: ""
168
+ lastSeenAt: "",
169
+ signInIp: "",
170
+ signInUserAgent: ""
163
171
  }, "a session without a purpose is a normal one");
164
172
  const preview = await backend.withTransaction((tx) => tx.sessions.create(session("ses_two", "usr_ada", "2026-12-01T00:00:00.000Z", { purpose: "dev-auth" })));
165
173
  assert.equal(preview.purpose, "dev-auth");
@@ -158,11 +158,13 @@ test("a database the released migrations left half-migrated recovers on the next
158
158
  const knex = await database.restoredWithDefault(OTHER_DEFAULT);
159
159
  await assert.rejects(migrateReleased(knex, RELEASED), /errno: 150|incorrectly formed/u);
160
160
 
161
- // The state the refused key left, as dogandgroom's database measured it.
161
+ // The state the refused key left, as dogandgroom's database measured it, with the migrations released since that
162
+ // sort before the refused one (auth_local_db_sign_in_facts.cjs).
162
163
  assert.deepEqual(await recorded(knex), [
163
164
  ...EARLY,
164
165
  "auth_local_db_oauth_invitation.cjs",
165
166
  "auth_local_db_sessions_metadata.cjs",
167
+ "auth_local_db_sign_in_facts.cjs",
166
168
  "auth_local_db_used_passes.cjs",
167
169
  "auth_local_db_users_disabled_message.cjs",
168
170
  "auth_local_db_users_email_verified.cjs",
@@ -268,6 +268,7 @@ test("local database auth uses the shared native login-as session contract", asy
268
268
  assert.equal(authenticated.authenticated, true);
269
269
  assert.equal(authenticated.actor.email, "preview-db@example.com");
270
270
  assert.equal(authenticated.sessionPurpose, "dev-auth");
271
+ assert.equal(authenticated.signIn.purpose, "dev-auth", "a development sign-in says so where its sign-in is told");
271
272
  });
272
273
 
273
274
  // The application's profiles, read and synchronized on the database's own pool outside local auth's transactions, as
@@ -0,0 +1,49 @@
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 signInFactsMigration from "../migrations/auth_local_db_sign_in_facts.cjs";
5
+ import { openLocalAuthDatabase } from "./support/mysqlLocalAuth.js";
6
+ import { COLUMNS, signInFactsCases } from "./support/signInFactsCases.js";
7
+
8
+ const PASSWORD = Object.freeze({ algorithm: "scrypt", version: "1", salt: "salt-one", hash: "hash-one" });
9
+
10
+ // On MariaDB the new columns are nullable timestamps that no other write of their row sets: the scenario's waiting
11
+ // email change and visits leave them as they were.
12
+ signInFactsCases(openLocalAuthDatabase, { database: true });
13
+
14
+ // MySQL 5.7 and MariaDB before 10.10 default explicit_defaults_for_timestamp to OFF, under which a TIMESTAMP column
15
+ // that is not NULL takes DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP: every write of an account would then
16
+ // say its password had just changed. The migration's columns are NULL, so there too they take no default and no
17
+ // ON UPDATE, and a write of their row leaves them unset.
18
+ test("the sign-in facts migration adds no default and no ON UPDATE where timestamps default the old way (MariaDB)", async (context) => {
19
+ requireTestDatabase(process.env);
20
+ const { knex, accounts } = await openLocalAuthDatabase(context, "da_local_facts_legacy");
21
+ await accounts.create({ id: "usr_ada", email: "ada@example.com", displayName: "Ada", password: PASSWORD, createdAt: "2026-11-01T08:00:00.000Z" });
22
+ await signInFactsMigration.down(knex);
23
+ await knex.transaction(async (trx) => {
24
+ await trx.raw("SET SESSION explicit_defaults_for_timestamp = OFF");
25
+ try {
26
+ await signInFactsMigration.up(trx);
27
+ } finally {
28
+ await trx.raw("SET SESSION explicit_defaults_for_timestamp = DEFAULT");
29
+ }
30
+ });
31
+ const described = await knex("information_schema.COLUMNS")
32
+ .select({ table: "TABLE_NAME", column: "COLUMN_NAME", nullable: "IS_NULLABLE", fallback: "COLUMN_DEFAULT", extra: "EXTRA" })
33
+ .where("TABLE_SCHEMA", knex.client.database())
34
+ .whereIn("COLUMN_NAME", COLUMNS.map(([, column]) => column))
35
+ .orderBy(["TABLE_NAME", "COLUMN_NAME"]);
36
+ assert.deepEqual(described.map(({ table, column, nullable, fallback, extra }) =>
37
+ [table, column, nullable, fallback === "NULL" ? null : fallback, extra]), [
38
+ ["auth_local_sessions", "sign_in_ip", "YES", null, ""],
39
+ ["auth_local_sessions", "sign_in_user_agent", "YES", null, ""],
40
+ ["auth_local_users", "email_changed_at", "YES", null, ""],
41
+ ["auth_local_users", "password_changed_at", "YES", null, ""]
42
+ ]);
43
+
44
+ await knex("auth_local_users").where({ id: "usr_ada" }).update({ display_name: "Ada L." });
45
+ assert.deepEqual(await knex("auth_local_users").where({ id: "usr_ada" }).first("password_changed_at", "email_changed_at"),
46
+ { password_changed_at: null, email_changed_at: null }, "a write of the account sets neither");
47
+ const ada = await accounts.findById("usr_ada");
48
+ assert.deepEqual([ada.displayName, ada.passwordChangedAt, ada.emailChangedAt], ["Ada L.", "", ""]);
49
+ });
@@ -0,0 +1,4 @@
1
+ import { POSTGRES_ELSEWHERE, openPostgresLocalAuth } from "./support/postgresLocalAuth.js";
2
+ import { signInFactsCases } from "./support/signInFactsCases.js";
3
+
4
+ signInFactsCases(openPostgresLocalAuth, { database: true, skip: POSTGRES_ELSEWHERE });
@@ -0,0 +1,4 @@
1
+ import { openSqliteLocalAuth } from "./support/localAuthRuntime.js";
2
+ import { signInFactsCases } from "./support/signInFactsCases.js";
3
+
4
+ signInFactsCases((context) => openSqliteLocalAuth(context));
@@ -8,6 +8,7 @@ import oauthMigration from "../../migrations/auth_local_db_oauth.cjs";
8
8
  import oauthInvitationMigration from "../../migrations/auth_local_db_oauth_invitation.cjs";
9
9
  import protectionMigration from "../../migrations/auth_local_db_protection.cjs";
10
10
  import sessionsMetadataMigration from "../../migrations/auth_local_db_sessions_metadata.cjs";
11
+ import signInFactsMigration from "../../migrations/auth_local_db_sign_in_facts.cjs";
11
12
  import usedPassesMigration from "../../migrations/auth_local_db_used_passes.cjs";
12
13
  import disabledMessageMigration from "../../migrations/auth_local_db_users_disabled_message.cjs";
13
14
  import emailVerifiedMigration from "../../migrations/auth_local_db_users_email_verified.cjs";
@@ -22,6 +23,7 @@ const LOCAL_AUTH_MIGRATIONS = Object.freeze([
22
23
  oauthInvitationMigration,
23
24
  protectionMigration,
24
25
  sessionsMetadataMigration,
26
+ signInFactsMigration,
25
27
  usedPassesMigration,
26
28
  disabledMessageMigration,
27
29
  emailVerifiedMigration,
@@ -0,0 +1,116 @@
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, hashPassword } from "../../../auth-provider-local-core/src/server/lib/index.js";
5
+ import { localServiceOptions } from "../../../auth-provider-local-core/test-support/localService.js";
6
+ import { sessionCookies } from "../../../auth-provider-local-core/test-support/passSignInScenario.js";
7
+ import { requestFrom } from "../../../auth-provider-local-core/test-support/sessionMetadataScenario.js";
8
+ import { FIREFOX, PHONE, exerciseSignInFacts } from "../../../auth-provider-local-core/test-support/signInFactsScenario.js";
9
+ import signInFactsMigration from "../../migrations/auth_local_db_sign_in_facts.cjs";
10
+
11
+ // How a session was signed in, and when an account's credentials last changed, in the database, on SQLite,
12
+ // MariaDB/MySQL and PostgreSQL alike: the whole scenario through local auth, and the migration going down and up over
13
+ // sessions and accounts that already exist.
14
+
15
+ const PASSWORD = "listed password value";
16
+ // Each column the migration adds, and the longest text it keeps (null for a time).
17
+ const COLUMNS = Object.freeze([
18
+ ["auth_local_sessions", "sign_in_ip", 64],
19
+ ["auth_local_sessions", "sign_in_user_agent", 512],
20
+ ["auth_local_users", "password_changed_at", null],
21
+ ["auth_local_users", "email_changed_at", null]
22
+ ]);
23
+
24
+ async function hasColumns(knex) {
25
+ return Promise.all(COLUMNS.map(([table, column]) => knex.schema.hasColumn(table, column)));
26
+ }
27
+
28
+ /**
29
+ * Each added column as the database describes it: text of its length or a time, nullable, with no default, so that no
30
+ * write but local auth's own sets it.
31
+ * @param {import("knex").Knex} knex
32
+ */
33
+ async function assertColumnShapes(knex) {
34
+ for (const [table, column, maxLength] of COLUMNS) {
35
+ const info = await knex(table).columnInfo(column);
36
+ const name = `${table}.${column}`;
37
+ assert.equal(info.nullable, true, `${name} is nullable`);
38
+ assert.equal(info.defaultValue, null, `${name} has no default`);
39
+ if (maxLength) {
40
+ assert.match(info.type, /^(character varying|varchar)$/u, `${name} is text`);
41
+ assert.equal(Number(info.maxLength), maxLength, `${name} keeps up to ${maxLength} characters`);
42
+ } else {
43
+ assert.match(info.type, /^(timestamp|datetime)/u, `${name} is a time`);
44
+ }
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Registers the tests on the records `open(context, suffix)` answers, as startLocalAuthRecords() gives them, with the
50
+ * migrated Knex as `knex`.
51
+ * @param {(context: import("node:test").TestContext, suffix: string) => Promise<any>} open
52
+ * @param {{ database?: boolean, skip?: string | false }} [options] `database`: the records need TEST_DB_NAME.
53
+ */
54
+ function signInFactsCases(open, { database = false, skip = false } = {}) {
55
+ test("a session keeps how it was signed in, and an account when its credentials changed (database backend)", { skip }, async (t) => {
56
+ if (database) requireTestDatabase(process.env);
57
+ const { backend, knex } = await open(t, "da_local_sign_in_facts");
58
+ // The migration runs again on a database that has its columns, as a rerun deploy does.
59
+ await signInFactsMigration.up(knex);
60
+ await exerciseSignInFacts(t, backend);
61
+ });
62
+
63
+ test("the sign-in facts migration goes down and up over existing sessions and accounts, which then have no facts, and visits add none", { skip }, async (t) => {
64
+ if (database) requireTestDatabase(process.env);
65
+ const { accounts, backend, knex, sessions } = await open(t, "da_local_facts_migration");
66
+ await assertColumnShapes(knex);
67
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-23T09:00:00.000Z") });
68
+ const service = createLocalAuthService({ ...localServiceOptions(), backend });
69
+ await service.register({ email: "ada@example.com", password: PASSWORD }, requestFrom("192.0.2.1", PHONE));
70
+ const signedIn = await service.login({ email: "ada@example.com", password: PASSWORD }, requestFrom("203.0.113.7", FIREFOX));
71
+ await service.changePassword(requestFrom("203.0.113.7", FIREFOX, sessionCookies(signedIn.session)),
72
+ { currentPassword: PASSWORD, newPassword: `${PASSWORD} again` });
73
+ const rows = async () => [await knex("auth_local_users").pluck("id"), (await knex("auth_local_sessions").pluck("id")).sort()];
74
+ const before = await rows();
75
+ assert.deepEqual(before.map((ids) => ids.length), [1, 2], "one account, signed in by registering and by a sign-in");
76
+
77
+ // The database as it was before this release: the migration's down drops its columns, keeping the rows; up adds
78
+ // them again, empty, as it does on a database whose sessions and accounts were made before it.
79
+ await signInFactsMigration.down(knex);
80
+ assert.deepEqual(await hasColumns(knex), [false, false, false, false]);
81
+ assert.deepEqual(await rows(), before, "down keeps every account and session");
82
+ await signInFactsMigration.down(knex);
83
+ await signInFactsMigration.up(knex);
84
+ await signInFactsMigration.up(knex);
85
+ assert.deepEqual(await hasColumns(knex), [true, true, true, true]);
86
+ assert.deepEqual(await rows(), before, "up keeps every account and session");
87
+ await assertColumnShapes(knex);
88
+ assert.deepEqual(await knex("auth_local_sessions").whereNotNull("sign_in_ip").orWhereNotNull("sign_in_user_agent").pluck("id"), []);
89
+ assert.deepEqual(await knex("auth_local_users").whereNotNull("password_changed_at").orWhereNotNull("email_changed_at").pluck("id"), []);
90
+
91
+ t.mock.timers.tick(10 * 60_000);
92
+ const visit = () => service.authenticateRequest(requestFrom("203.0.113.7", FIREFOX, sessionCookies(signedIn.session)));
93
+ const answer = await visit();
94
+ assert.equal(answer.authenticated, true);
95
+ assert.deepEqual(answer.signIn, { at: "2026-11-23T09:00:00.000Z", ip: "", userAgent: "", purpose: "normal" },
96
+ "an older session has no sign-in address or browser, so an action that asks for them refuses it");
97
+ assert.deepEqual(answer.credentialsChangedAt, { password: "", email: "" }, "a change from before the migration is unknown");
98
+ // Registering made a session at the same moment, so the list's order between the two is the ids'.
99
+ const listed = (await sessions.listForUser(answer.actor.providerUserId)).find(({ id }) => id === answer.sessionId);
100
+ assert.deepEqual([listed.ip, listed.userAgent, listed.signInIp, listed.signInUserAgent], ["203.0.113.7", FIREFOX, "", ""],
101
+ "the visit moved where it was last seen and left where it was signed in from unknown");
102
+ assert.deepEqual((await visit()).signIn, answer.signIn);
103
+
104
+ // The owner APIs carry the facts: an application's own session takes them, and a password set through them is a
105
+ // change.
106
+ await accounts.create({ id: "usr_owner", email: "owner@example.com", displayName: "Owner", password: await hashPassword(PASSWORD) });
107
+ const created = await sessions.create({ id: "ses_owner", userId: "usr_owner", tokenHash: "hash-owner", expiresAt: "2026-12-23T09:00:00.000Z",
108
+ signInIp: "198.51.100.4", signInUserAgent: PHONE });
109
+ assert.deepEqual([created.signInIp, created.signInUserAgent], ["198.51.100.4", PHONE]);
110
+ assert.equal((await accounts.findById("usr_owner")).passwordChangedAt, "");
111
+ assert.equal((await accounts.updatePassword("usr_owner", await hashPassword(`${PASSWORD} reset`))).passwordChangedAt,
112
+ "2026-11-23T09:10:00.000Z");
113
+ });
114
+ }
115
+
116
+ export { COLUMNS, signInFactsCases };