@jskit-ai/auth-provider-local-core 0.2.42 → 0.2.43

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
+ - A session keeps where it was signed in from, the sign-in request's address and browser, written once at its creation: the backend contract's sessions take `signInIp` and `signInUserAgent`, and `touch` never changes them (the file store keeps them in a fourteenth and fifteenth field of each session line; older lines read ""). An account keeps when its password and email last changed: `users.updatePassword` (a reset and a change alike) sets `passwordChangedAt` and `users.updateEmail` (a used email-change link) `emailChangedAt`, in the same write; registering and confirming a new account's email set neither (the file store keeps them in a fourteenth and fifteenth field of each account line; older lines read ""). An authenticated request's answer gives them as `signIn` (`{ at, ip, userAgent, purpose }`, `at` the session's creation) and `credentialsChangedAt` (`{ password, email }`), which auth-core's policy sets as `request.sessionSignIn` and `request.credentialsChangedAt`. A session signed in before this release has `ip` and `userAgent` "": an action that asks for them makes its person sign in again.
5
6
  - A provider sign-in started from an invitation (`oauthStart({ provider, returnTo, invitationToken })`) keeps the token with its attempt (a thirteenth field of `oauth-attempts.passwd`; twelve-field records still read) and, at the end, resolves it through the invitation context resolver for the signed-in account and hands the result to profile synchronization (`source` and `invitation`), as a registration's invitation is handed on. An invitation the resolver refuses never fails the sign-in, which continues as one without; a failure that is not a refusal is logged.
6
7
  - The password lockout names the email address, never an account: 429 `auth.local.login.locked` says "Password sign-in for this email address is paused for N minute(s) after too many failed attempts. Try again after that." (it said "Too many failed sign-ins for this account."). An address without an account waits the same way. Code, params (`count`, `retryAfterSeconds`) and `Retry-After` are unchanged.
7
8
  - **Breaking:** the local file auth backend in staging and production needs `AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK=true`, in place of `AUTH_LOCAL_FILE_PRODUCTION_ACK`, which it always needed in staging too; a server with the old variable set refuses to start, naming the new one. The resolved configuration (`resolveLocalAuthConfig`) names whether it runs in staging or production `isStagingOrProduction`, in place of `isDeployed`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.42",
3
+ "version": "0.2.43",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -73,7 +73,7 @@
73
73
  }
74
74
  },
75
75
  "peerDependencies": {
76
- "@jskit-ai/auth-core": "0.2.36",
76
+ "@jskit-ai/auth-core": "0.2.37",
77
77
  "@jskit-ai/kernel": "0.2.32"
78
78
  }
79
79
  }
@@ -225,7 +225,9 @@ function createTx(state, touched) {
225
225
  createdAt: input.createdAt || nowIso(),
226
226
  updatedAt: input.updatedAt || nowIso(),
227
227
  disabled: input.disabled === true,
228
- pendingEmail: input.pendingEmail || ""
228
+ pendingEmail: input.pendingEmail || "",
229
+ passwordChangedAt: input.passwordChangedAt || "",
230
+ emailChangedAt: input.emailChangedAt || ""
229
231
  };
230
232
  state.users.push(user);
231
233
  mark("users");
@@ -246,7 +248,9 @@ function createTx(state, touched) {
246
248
  return null;
247
249
  }
248
250
  user.password = clone(passwordRecord);
249
- user.updatedAt = nowIso();
251
+ // A reset and a change alike: the password changed now.
252
+ user.passwordChangedAt = nowIso();
253
+ user.updatedAt = user.passwordChangedAt;
250
254
  mark("users");
251
255
  return clone(user);
252
256
  },
@@ -282,7 +286,8 @@ function createTx(state, touched) {
282
286
  }
283
287
  user.email = email;
284
288
  user.pendingEmail = "";
285
- user.updatedAt = nowIso();
289
+ user.emailChangedAt = nowIso();
290
+ user.updatedAt = user.emailChangedAt;
286
291
  mark("users");
287
292
  return clone(user);
288
293
  }
@@ -297,7 +302,9 @@ function createTx(state, touched) {
297
302
  secondFactorAt: input.secondFactorAt || "",
298
303
  ip: input.ip || "",
299
304
  userAgent: input.userAgent || "",
300
- lastSeenAt: input.lastSeenAt || ""
305
+ lastSeenAt: input.lastSeenAt || "",
306
+ signInIp: input.signInIp || "",
307
+ signInUserAgent: input.signInUserAgent || ""
301
308
  };
302
309
  state.sessions.push(session);
303
310
  mark("sessions");
@@ -354,6 +361,7 @@ function createTx(state, touched) {
354
361
  }
355
362
  return count;
356
363
  },
364
+ // Where the session was signed in from never changes.
357
365
  async touch(sessionId, { lastSeenAt, ip, userAgent }) {
358
366
  const session = state.sessions.find((entry) => entry.id === sessionId);
359
367
  if (!session) {
@@ -21,8 +21,9 @@ function parseUsers(content) {
21
21
  const users = [];
22
22
  for (const line of String(content || "").split("\n").filter(Boolean)) {
23
23
  const parts = splitLine(line, "user");
24
- // Twelve fields, or thirteen since an account keeps its waiting email change.
25
- if (parts.length !== 12 && parts.length !== 13) {
24
+ // Twelve fields, thirteen since an account keeps its waiting email change, or fifteen since it keeps when its
25
+ // password and email last changed.
26
+ if (parts.length !== 12 && parts.length !== 13 && parts.length !== 15) {
26
27
  throw new Error("Invalid user record field count.");
27
28
  }
28
29
  users.push({
@@ -38,7 +39,9 @@ function parseUsers(content) {
38
39
  createdAt: decodeField(parts[9]),
39
40
  updatedAt: decodeField(parts[10]),
40
41
  disabled: parts[11] === "1",
41
- pendingEmail: decodeField(parts[12])
42
+ pendingEmail: decodeField(parts[12]),
43
+ passwordChangedAt: decodeField(parts[13]),
44
+ emailChangedAt: decodeField(parts[14])
42
45
  });
43
46
  }
44
47
  return users;
@@ -61,7 +64,9 @@ function serializeUsers(users) {
61
64
  encodeField(user.createdAt),
62
65
  encodeField(user.updatedAt),
63
66
  user.disabled ? "1" : "0",
64
- encodeField(user.pendingEmail)
67
+ encodeField(user.pendingEmail),
68
+ encodeField(user.passwordChangedAt),
69
+ encodeField(user.emailChangedAt)
65
70
  ].join(":")
66
71
  )
67
72
  .join("\n") + (users.length > 0 ? "\n" : "");
@@ -72,8 +77,9 @@ function parseSessions(content) {
72
77
  for (const line of String(content || "").split("\n").filter(Boolean)) {
73
78
  const parts = splitLine(line, "session");
74
79
  // A session written before second factors has no tenth field: it has not proved one. One written before sessions
75
- // kept where they were seen has no eleventh to thirteenth: nobody knows where or when it was last seen.
76
- if (parts.length !== 9 && parts.length !== 10 && parts.length !== 13) {
80
+ // kept where they were seen has no eleventh to thirteenth: nobody knows where or when it was last seen. One written
81
+ // before sessions kept where they were signed in from has no fourteenth and fifteenth: nobody knows.
82
+ if (parts.length !== 9 && parts.length !== 10 && parts.length !== 13 && parts.length !== 15) {
77
83
  throw new Error("Invalid session record field count.");
78
84
  }
79
85
  sessions.push({
@@ -87,7 +93,9 @@ function parseSessions(content) {
87
93
  secondFactorAt: decodeField(parts[9] || ""),
88
94
  ip: decodeField(parts[10] || ""),
89
95
  userAgent: decodeField(parts[11] || ""),
90
- lastSeenAt: decodeField(parts[12] || "")
96
+ lastSeenAt: decodeField(parts[12] || ""),
97
+ signInIp: decodeField(parts[13] || ""),
98
+ signInUserAgent: decodeField(parts[14] || "")
91
99
  });
92
100
  }
93
101
  return sessions;
@@ -110,7 +118,9 @@ function serializeSessions(sessions) {
110
118
  encodeField(session.secondFactorAt || ""),
111
119
  encodeField(session.ip || ""),
112
120
  encodeField(session.userAgent || ""),
113
- encodeField(session.lastSeenAt || "")
121
+ encodeField(session.lastSeenAt || ""),
122
+ encodeField(session.signInIp || ""),
123
+ encodeField(session.signInUserAgent || "")
114
124
  ].join(":")
115
125
  )
116
126
  .join("\n") + (sessions.length > 0 ? "\n" : "");
@@ -33,6 +33,35 @@ function requestClient(request) {
33
33
  };
34
34
  }
35
35
 
36
+ /**
37
+ * How a session was signed in, as an authenticated request's answer gives it: when (`at`, the session's creation, which
38
+ * a refresh never renews), from where (`ip` and `userAgent`, the request that signed it in, each "" when unknown, as
39
+ * for a session from before sessions kept them or one signed in without a request) and why (`purpose`).
40
+ * @param {{ createdAt?: string, signInIp?: string, signInUserAgent?: string, purpose?: string }} session
41
+ * @returns {import("@jskit-ai/auth-core/server/types").AuthSessionSignIn}
42
+ */
43
+ function sessionSignIn(session) {
44
+ return Object.freeze({
45
+ at: session.createdAt || "",
46
+ ip: session.signInIp || "",
47
+ userAgent: session.signInUserAgent || "",
48
+ purpose: session.purpose || "normal"
49
+ });
50
+ }
51
+
52
+ /**
53
+ * When the account's password and email last changed, as an authenticated request's answer gives it: each "" when it
54
+ * has not since local auth kept it.
55
+ * @param {{ passwordChangedAt?: string, emailChangedAt?: string }} user
56
+ * @returns {import("@jskit-ai/auth-core/server/types").AuthCredentialsChangedAt}
57
+ */
58
+ function credentialsChangedAt(user) {
59
+ return Object.freeze({
60
+ password: user.passwordChangedAt || "",
61
+ email: user.emailChangedAt || ""
62
+ });
63
+ }
64
+
36
65
  /**
37
66
  * The `auth.local.sign-in-events` default when no feature provides one: local auth logs each sign-in event.
38
67
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
@@ -107,12 +136,15 @@ function buildSessionPayload({ user, session, refreshToken, secret }) {
107
136
  /**
108
137
  * The sessions of local auth: creating one, authenticating a request from its
109
138
  * cookies, writing and clearing those cookies, and revoking sessions. An
110
- * authenticated request's answer names its session (`sessionId`) and when the
111
- * session last proved its second factor (`secondFactorAt`, "" when it has not).
112
- * A session keeps where it was last seen from (`ip`, `userAgent`) and when
113
- * (`lastSeenAt`): the request that signed it in, then one that finds it more
114
- * than five minutes later. Each sign-in, and each refused one, is an event for
115
- * the application's `auth.local.sign-in-events` (recordSignInEvent).
139
+ * authenticated request's answer names its session (`sessionId`), when the
140
+ * session last proved its second factor (`secondFactorAt`, "" when it has not),
141
+ * how it was signed in (`signIn`) and when the account's password and email
142
+ * last changed (`credentialsChangedAt`). A session keeps where it was last seen
143
+ * from (`ip`, `userAgent`) and when (`lastSeenAt`): the request that signed it
144
+ * in, then one that finds it more than five minutes later. It also keeps where
145
+ * it was signed in from (`signInIp`, `signInUserAgent`), written once and never
146
+ * again. Each sign-in, and each refused one, is an event for the application's
147
+ * `auth.local.sign-in-events` (recordSignInEvent).
116
148
  * @param {object} dependencies
117
149
  * @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
118
150
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
@@ -134,21 +166,24 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
134
166
  const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isStagingOrProduction);
135
167
 
136
168
  /**
137
- * A new session of the user, seen now from where the request that signs it in comes from.
169
+ * A new session of the user, signed in and seen now from where the request that signs it in comes from.
138
170
  * @param {import("../types.js").AuthLocalBackendTransaction} tx
139
171
  * @param {{ id: string }} user
140
172
  * @param {{ purpose?: string, ttlSeconds?: number, request?: object | null }} [options]
141
173
  */
142
174
  async function createSessionForUser(tx, user, { purpose = "normal", ttlSeconds = REFRESH_TTL_SECONDS, request = null } = {}) {
143
175
  const refreshToken = randomToken(36);
176
+ const client = requestClient(request);
144
177
  const session = await tx.sessions.create({
145
178
  id: createId("ses"),
146
179
  userId: user.id,
147
180
  tokenHash: sha256Base64url(refreshToken),
148
181
  purpose,
149
182
  expiresAt: isoFromNow(ttlSeconds),
150
- ...requestClient(request),
151
- lastSeenAt: new Date().toISOString()
183
+ ...client,
184
+ lastSeenAt: new Date().toISOString(),
185
+ signInIp: client.ip,
186
+ signInUserAgent: client.userAgent
152
187
  });
153
188
  return buildSessionPayload({
154
189
  user,
@@ -160,7 +195,7 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
160
195
 
161
196
  /**
162
197
  * A session found more than five minutes after it was last seen is seen again now, from where the request comes
163
- * from; a request that does not say keeps where it was last seen from.
198
+ * from; a request that does not say keeps where it was last seen from. Where it was signed in from stays.
164
199
  * @param {import("../types.js").AuthLocalBackendTransaction} tx
165
200
  * @param {{ id: string, lastSeenAt?: string }} session
166
201
  * @param {object | null} request
@@ -273,6 +308,8 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
273
308
  sessionId: resolved.session.id,
274
309
  secondFactorAt: resolved.session.secondFactorAt || "",
275
310
  sessionPurpose: resolved.session.purpose || "normal",
311
+ signIn: sessionSignIn(resolved.session),
312
+ credentialsChangedAt: credentialsChangedAt(resolved.user),
276
313
  clearSession: false,
277
314
  transientFailure: false
278
315
  };
@@ -318,6 +355,8 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
318
355
  sessionId: resolved.session.id,
319
356
  secondFactorAt: resolved.session.secondFactorAt || "",
320
357
  sessionPurpose: resolved.session.purpose || "normal",
358
+ signIn: sessionSignIn(resolved.session),
359
+ credentialsChangedAt: credentialsChangedAt(resolved.user),
321
360
  clearSession: false,
322
361
  transientFailure: false
323
362
  };
@@ -22,7 +22,9 @@
22
22
  * `disabledMessage`, or that the account is disabled when it has none; the file backend keeps no message. A user's
23
23
  * `pendingEmail` is the address its email change waits to confirm ("" when none): `updatePendingEmail` sets it, and
24
24
  * `updateEmail` changes the email to a confirmed address and clears it, refusing an email another account has with
25
- * a ConflictError.
25
+ * a ConflictError. A user's `passwordChangedAt` is when its password last changed and `emailChangedAt` when its
26
+ * email did ("" when it has not since they were kept): `updatePassword` (a reset and a change alike) and
27
+ * `updateEmail` set them now, in the same write; creating an account sets neither.
26
28
  * @property {{
27
29
  * create(input: object): Promise<object>,
28
30
  * findById(sessionId: string): Promise<object | null>,
@@ -35,7 +37,9 @@
35
37
  * }} sessions A session's `secondFactorAt` is when it last proved its second factor ("" when it has not):
36
38
  * `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user. A session keeps
37
39
  * where it was last seen from, `ip` and `userAgent` (`create` takes them with `lastSeenAt`), and when, `lastSeenAt`,
38
- * each "" when unknown; `touch` notes it seen again, keeping its `ip` or `userAgent` when the new one is "".
40
+ * each "" when unknown; `touch` notes it seen again, keeping its `ip` or `userAgent` when the new one is "". It also
41
+ * keeps where it was signed in from, `signInIp` and `signInUserAgent` ("" when unknown): `create` takes them, and
42
+ * nothing changes them after.
39
43
  * @property {{
40
44
  * create(input: object): Promise<object>,
41
45
  * findByTokenHash(tokenHash: string): Promise<object | null>,
@@ -270,6 +270,7 @@ test("local file auth login-as issues native cookies for an existing user", asyn
270
270
  assert.equal(authenticated.authenticated, true);
271
271
  assert.equal(authenticated.actor.email, "ada@example.com");
272
272
  assert.equal(authenticated.sessionPurpose, "dev-auth");
273
+ assert.equal(authenticated.signIn.purpose, "dev-auth", "a development sign-in says so where its sign-in is told");
273
274
  });
274
275
 
275
276
  test("local login-as never invokes the mutating profile projector", async () => {
@@ -33,6 +33,8 @@ test("a session the file backend stored before it kept where sessions are seen r
33
33
  secondFactorAt: "",
34
34
  ip: "",
35
35
  userAgent: "",
36
- lastSeenAt: ""
36
+ lastSeenAt: "",
37
+ signInIp: "",
38
+ signInUserAgent: ""
37
39
  });
38
40
  });
@@ -0,0 +1,89 @@
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 Fastify from "fastify";
7
+ import { authPolicyPlugin } from "@jskit-ai/auth-core/server/lib/plugin";
8
+ import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
9
+ import { sha256Base64url } from "../src/server/lib/tokens.js";
10
+ import { localServiceOptions } from "../test-support/localService.js";
11
+ import { sessionCookies } from "../test-support/passSignInScenario.js";
12
+ import { FIREFOX, PHONE, exerciseSignInFacts } from "../test-support/signInFactsScenario.js";
13
+ import { requestFrom } from "../test-support/sessionMetadataScenario.js";
14
+
15
+ const PASSWORD = "correct horse battery staple";
16
+
17
+ async function temporaryStore(t) {
18
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-facts-"));
19
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
20
+ return storeDir;
21
+ }
22
+
23
+ test("a session keeps how it was signed in, and an account when its credentials changed (file backend)", async (t) => {
24
+ await exerciseSignInFacts(t, createLocalFileBackend({ storeDir: await temporaryStore(t) }));
25
+ });
26
+
27
+ test("a session and an account the file backend stored before it kept these facts have none, and visits add none", async (t) => {
28
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-23T09:00:00.000Z") });
29
+ const storeDir = await temporaryStore(t);
30
+ const field = (value) => Buffer.from(value, "utf8").toString("base64url");
31
+ const refreshToken = "a refresh token from before";
32
+ // A thirteen-field account and a thirteen-field session, as the release before wrote them.
33
+ const user = ["user", "v1", "usr_old", field("old@example.com"), field("Old"), "scrypt", "1", "salt", "hash",
34
+ field("2026-11-01T09:00:00.000Z"), field("2026-11-01T09:00:00.000Z"), "0", field("")].join(":");
35
+ const session = ["session", "v1", "ses_old", "usr_old", sha256Base64url(refreshToken), "normal",
36
+ field("2026-11-20T09:00:00.000Z"), field("2026-12-20T09:00:00.000Z"), field(""), field(""),
37
+ field("203.0.113.7"), field(FIREFOX), field("2026-11-20T09:00:00.000Z")].join(":");
38
+ await fs.writeFile(path.join(storeDir, "users.passwd"), `${user}\n`);
39
+ await fs.writeFile(path.join(storeDir, "sessions.passwd"), `${session}\n`);
40
+ const backend = createLocalFileBackend({ storeDir });
41
+ const service = createLocalAuthService({ ...localServiceOptions(), backend });
42
+
43
+ const visit = () => service.authenticateRequest(requestFrom("203.0.113.7", FIREFOX, { jskit_local_refresh_token: refreshToken }));
44
+ const first = await visit();
45
+ assert.equal(first.authenticated, true);
46
+ assert.deepEqual(first.signIn, { at: "2026-11-20T09:00:00.000Z", ip: "", userAgent: "", purpose: "normal" },
47
+ "an older session has no sign-in address or browser, so an action that asks for them refuses it");
48
+ assert.deepEqual(first.credentialsChangedAt, { password: "", email: "" });
49
+ // The visit rewrote the records in the current form; where it was signed in from stays unknown.
50
+ const stored = await backend.withTransaction((tx) => tx.sessions.findById("ses_old"));
51
+ assert.deepEqual([stored.ip, stored.userAgent, stored.signInIp, stored.signInUserAgent], ["203.0.113.7", FIREFOX, "", ""]);
52
+ assert.equal((await fs.readFile(path.join(storeDir, "sessions.passwd"), "utf8")).trim().split(":").length, 15);
53
+ assert.deepEqual((await visit()).signIn, first.signIn);
54
+ });
55
+
56
+ test("the auth policy hands a route the session's sign-in and the account's credential changes", async (t) => {
57
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-23T09:00:00.000Z") });
58
+ const backend = createLocalFileBackend({ storeDir: await temporaryStore(t) });
59
+ const service = createLocalAuthService({ ...localServiceOptions(), backend });
60
+ const app = Fastify();
61
+ t.after(() => app.close());
62
+ await authPolicyPlugin({
63
+ resolveActor: (request) => service.authenticateRequest(request),
64
+ hasPermission: () => true
65
+ }, { appEnv: "test" })(app);
66
+ const facts = (request) => ({ sessionSignIn: request.sessionSignIn, credentialsChangedAt: request.credentialsChangedAt });
67
+ app.get("/api/account/facts", { config: { authPolicy: "required" } }, (request) => facts(request));
68
+ app.get("/api/public/facts", { config: { authPolicy: "public" } }, (request) => facts(request));
69
+
70
+ await service.register({ email: "ada@example.com", password: PASSWORD }, requestFrom("192.0.2.1", PHONE));
71
+ const signedIn = await service.login({ email: "ada@example.com", password: PASSWORD }, requestFrom("203.0.113.7", FIREFOX));
72
+ const asked = await app.inject({
73
+ method: "GET",
74
+ url: "/api/account/facts",
75
+ remoteAddress: "198.51.100.9",
76
+ headers: { "user-agent": PHONE },
77
+ cookies: sessionCookies(signedIn.session)
78
+ });
79
+ assert.equal(asked.statusCode, 200);
80
+ assert.deepEqual(asked.json(), {
81
+ sessionSignIn: { at: "2026-11-23T09:00:00.000Z", ip: "203.0.113.7", userAgent: FIREFOX, purpose: "normal" },
82
+ credentialsChangedAt: { password: "", email: "" }
83
+ }, "the sign-in's address and browser, not the asking request's");
84
+
85
+ const signedOut = await app.inject({ method: "GET", url: "/api/account/facts" });
86
+ assert.equal(signedOut.statusCode, 401);
87
+ const publicRoute = await app.inject({ method: "GET", url: "/api/public/facts", cookies: sessionCookies(signedIn.session) });
88
+ assert.deepEqual(publicRoute.json(), { sessionSignIn: null, credentialsChangedAt: null }, "a public route signs nobody in");
89
+ });
@@ -0,0 +1,145 @@
1
+ import assert from "node:assert/strict";
2
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
3
+ import { createLocalAuthService, createLocalDeliveries } from "../src/server/lib/index.js";
4
+ import { sha256Base64url } from "../src/server/lib/tokens.js";
5
+ import { localServiceOptions } from "./localService.js";
6
+ import { sessionCookies } from "./passSignInScenario.js";
7
+ import { requestFrom } from "./sessionMetadataScenario.js";
8
+
9
+ const PASSWORD = "correct horse battery staple";
10
+ const CHANGED_PASSWORD = "a changed password value";
11
+ const RESET_PASSWORD = "a reset password value";
12
+ const FIREFOX = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
13
+ const PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148 Safari/604.1";
14
+ const MINUTE = 60_000;
15
+
16
+ /**
17
+ * A local auth service over the backend whose email-change sender keeps what it is given, sent through deliveries the
18
+ * test waits for.
19
+ * @param {import("../src/server/types.js").AuthLocalBackend} backend
20
+ * @param {Record<string, string>} [env]
21
+ */
22
+ function signInFactsService(backend, env = {}) {
23
+ const deliveries = createLocalDeliveries({ logger: silentLogger });
24
+ const sent = [];
25
+ const service = createLocalAuthService({
26
+ ...localServiceOptions({ env, emailChangeSender: true }),
27
+ backend,
28
+ deliveries,
29
+ emailChangeSender: async (delivery) => {
30
+ sent.push(delivery);
31
+ }
32
+ });
33
+ /** What was sent so far, once every send finished; it forgets them. */
34
+ async function takeSent() {
35
+ await deliveries.settled();
36
+ return sent.splice(0);
37
+ }
38
+ return { service, takeSent };
39
+ }
40
+
41
+ /**
42
+ * How a session was signed in, and when its account's credentials last changed, against any backend, with Date
43
+ * mocked through `t.mock.timers`. A session keeps the address, browser and time of the request that signed it in:
44
+ * later requests from elsewhere, and a refresh, move where it was last seen and never where it was signed in from.
45
+ * Registering, and confirming a registration's email, change no credential; a password change, a password reset and a
46
+ * used email-change link each set when that credential changed, and asking for an email change does not. A sign-in
47
+ * without a request has no address or browser, as a session from before sessions kept them.
48
+ * @param {import("node:test").TestContext} t
49
+ * @param {import("../src/server/types.js").AuthLocalBackend} backend
50
+ */
51
+ async function exerciseSignInFacts(t, backend) {
52
+ const start = Date.parse("2026-11-23T09:00:00.000Z");
53
+ const at = (minutes) => new Date(start + minutes * MINUTE).toISOString();
54
+ t.mock.timers.enable({ apis: ["Date"], now: start });
55
+ const { service, takeSent } = signInFactsService(backend);
56
+ const answerFor = async (request) => {
57
+ const answer = await service.authenticateRequest(request);
58
+ assert.equal(answer.authenticated, true);
59
+ return answer;
60
+ };
61
+ const storedSession = (refreshToken) => backend.withTransaction((tx) => tx.sessions.findByTokenHash(sha256Base64url(refreshToken)));
62
+ const seenAndSignedIn = async (refreshToken) => {
63
+ const session = await storedSession(refreshToken);
64
+ return { ip: session.ip, userAgent: session.userAgent, signInIp: session.signInIp, signInUserAgent: session.signInUserAgent };
65
+ };
66
+
67
+ // Registering signs in from its request and changes no credential.
68
+ const registered = await service.register({ email: "ada@example.com", password: PASSWORD }, requestFrom("192.0.2.1", PHONE));
69
+ const registeredAnswer = await answerFor(requestFrom("192.0.2.1", PHONE, sessionCookies(registered.session)));
70
+ assert.deepEqual(registeredAnswer.signIn, { at: at(0), ip: "192.0.2.1", userAgent: PHONE, purpose: "normal" });
71
+ assert.deepEqual(registeredAnswer.credentialsChangedAt, { password: "", email: "" });
72
+
73
+ // A sign-in keeps its own request's address and browser, and its time.
74
+ t.mock.timers.tick(MINUTE);
75
+ const signedIn = await service.login({ email: "ada@example.com", password: PASSWORD }, requestFrom("203.0.113.7", FIREFOX));
76
+ const cookies = sessionCookies(signedIn.session);
77
+ const signIn = { at: at(1), ip: "203.0.113.7", userAgent: FIREFOX, purpose: "normal" };
78
+ assert.deepEqual((await answerFor(requestFrom("203.0.113.7", FIREFOX, cookies))).signIn, signIn);
79
+
80
+ // A visit from elsewhere after five minutes moves where the session was last seen, never where it was signed in from.
81
+ t.mock.timers.tick(6 * MINUTE);
82
+ assert.deepEqual((await answerFor(requestFrom("198.51.100.9", PHONE, cookies))).signIn, signIn);
83
+ assert.deepEqual(await seenAndSignedIn(cookies.jskit_local_refresh_token),
84
+ { ip: "198.51.100.9", userAgent: PHONE, signInIp: "203.0.113.7", signInUserAgent: FIREFOX });
85
+ // Nor does a refresh, once the access token has expired: the session is signed in as long ago as before.
86
+ t.mock.timers.tick(20 * MINUTE);
87
+ const refreshed = await answerFor(requestFrom("198.51.100.10", PHONE, { jskit_local_refresh_token: cookies.jskit_local_refresh_token }));
88
+ assert.ok(refreshed.session, "the refresh answers new cookies");
89
+ assert.deepEqual(refreshed.signIn, signIn);
90
+ assert.deepEqual(await seenAndSignedIn(cookies.jskit_local_refresh_token),
91
+ { ip: "198.51.100.10", userAgent: PHONE, signInIp: "203.0.113.7", signInUserAgent: FIREFOX });
92
+ assert.deepEqual(refreshed.credentialsChangedAt, { password: "", email: "" });
93
+
94
+ // A password change sets when the password changed.
95
+ t.mock.timers.tick(MINUTE);
96
+ const changeRequest = requestFrom("203.0.113.7", FIREFOX, sessionCookies(refreshed.session));
97
+ await service.changePassword(changeRequest, { currentPassword: PASSWORD, newPassword: CHANGED_PASSWORD });
98
+ assert.deepEqual((await answerFor(requestFrom("203.0.113.7", FIREFOX, sessionCookies(refreshed.session)))).credentialsChangedAt,
99
+ { password: at(28), email: "" });
100
+
101
+ // A password reset sets it too. Its recovery session keeps its own sign-in, as purpose recovery.
102
+ t.mock.timers.tick(MINUTE);
103
+ const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
104
+ const recovery = await service.completePasswordRecovery({ code: new URL(recoveryUrl).searchParams.get("token") },
105
+ requestFrom("192.0.2.50", PHONE));
106
+ const recoverySession = await storedSession(recovery.session.refresh_token);
107
+ assert.deepEqual([recoverySession.purpose, recoverySession.signInIp, recoverySession.signInUserAgent], ["recovery", "192.0.2.50", PHONE]);
108
+ t.mock.timers.tick(MINUTE);
109
+ await service.resetPassword({ password: RESET_PASSWORD }, { cookies: { jskit_local_recovery_token: recovery.session.access_token } });
110
+ const afterReset = await service.login({ email: "ada@example.com", password: RESET_PASSWORD }, requestFrom("203.0.113.7", FIREFOX));
111
+ const afterResetCookies = sessionCookies(afterReset.session);
112
+ assert.deepEqual((await answerFor(requestFrom("203.0.113.7", FIREFOX, afterResetCookies))).credentialsChangedAt,
113
+ { password: at(30), email: "" });
114
+
115
+ // Asking for an email change changes nothing yet; using its link sets when the email changed.
116
+ t.mock.timers.tick(MINUTE);
117
+ await service.requestEmailChange(requestFrom("203.0.113.7", FIREFOX, afterResetCookies), { email: "ada.new@example.com", password: RESET_PASSWORD });
118
+ assert.deepEqual((await answerFor(requestFrom("203.0.113.7", FIREFOX, afterResetCookies))).credentialsChangedAt,
119
+ { password: at(30), email: "" });
120
+ t.mock.timers.tick(MINUTE);
121
+ const [confirmation] = await takeSent();
122
+ await service.confirmEmailChange({ token: new URL(confirmation.confirmationUrl).searchParams.get("token") });
123
+ const afterEmailChange = await answerFor(requestFrom("203.0.113.7", FIREFOX, afterResetCookies));
124
+ assert.deepEqual(afterEmailChange.credentialsChangedAt, { password: at(30), email: at(32) });
125
+ assert.deepEqual(afterEmailChange.signIn, { at: at(30), ip: "203.0.113.7", userAgent: FIREFOX, purpose: "normal" },
126
+ "no credential change moves a session's sign-in");
127
+
128
+ // A sign-in without a request keeps no address or browser, as a session from before sessions kept them.
129
+ const internal = await service.login({ email: "ada.new@example.com", password: RESET_PASSWORD });
130
+ assert.deepEqual((await answerFor(requestFrom("203.0.113.7", FIREFOX, sessionCookies(internal.session)))).signIn,
131
+ { at: at(32), ip: "", userAgent: "", purpose: "normal" });
132
+
133
+ // A registration confirmed by its email's link changes no credential either.
134
+ const confirming = signInFactsService(backend, { AUTH_LOCAL_EMAIL_CONFIRMATION: "" }).service;
135
+ const waiting = await confirming.register({ email: "bob@example.com", password: PASSWORD }, requestFrom("192.0.2.7", PHONE));
136
+ const confirmed = await confirming.confirmRegistration({
137
+ token: new URL(waiting.confirmationUrl).searchParams.get("confirmation_token"),
138
+ password: PASSWORD
139
+ }, requestFrom("192.0.2.8", FIREFOX));
140
+ const confirmedAnswer = await confirming.authenticateRequest(requestFrom("192.0.2.8", FIREFOX, sessionCookies(confirmed.session)));
141
+ assert.deepEqual(confirmedAnswer.signIn, { at: at(32), ip: "192.0.2.8", userAgent: FIREFOX, purpose: "normal" });
142
+ assert.deepEqual(confirmedAnswer.credentialsChangedAt, { password: "", email: "" });
143
+ }
144
+
145
+ export { FIREFOX, PHONE, exerciseSignInFacts };