@jskit-ai/auth-provider-local-core 0.2.36 → 0.2.38

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.
@@ -18,6 +18,7 @@ import {
18
18
  createLocalFileBackend,
19
19
  hashPassword,
20
20
  normalizePasswordStrategy,
21
+ resolveLocalAuthConfig,
21
22
  verifyPassword
22
23
  } from "../src/server/lib/index.js";
23
24
 
@@ -28,7 +29,7 @@ const PRODUCTION = Object.freeze({
28
29
  APP_ENV: "production",
29
30
  NODE_ENV: "production",
30
31
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
31
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
32
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
32
33
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: ""
33
34
  });
34
35
  const STAGING = Object.freeze({ ...PRODUCTION, APP_ENV: "staging" });
@@ -117,7 +118,9 @@ async function createStartedApp({
117
118
  confirmationMode = null,
118
119
  invitationContextResolver = null,
119
120
  logger = null,
120
- configureExtensions = null
121
+ configureExtensions = null,
122
+ signInEvents = null,
123
+ emailChangeSender = null
121
124
  } = {}) {
122
125
  const storeDir = await temporaryStoreDir("jskit-auth-local-");
123
126
  const backend = createLocalFileBackend({ storeDir });
@@ -168,6 +171,8 @@ async function createStartedApp({
168
171
  ...(recoverySender !== null ? { "auth.local.recovery-sender": recoverySender } : {}),
169
172
  ...(confirmationSender !== null ? { "auth.local.confirmation-sender": confirmationSender } : {}),
170
173
  ...(confirmationMode !== null ? { "auth.local.confirmation-mode": confirmationMode } : {}),
174
+ ...(signInEvents !== null ? { "auth.local.sign-in-events": signInEvents } : {}),
175
+ ...(emailChangeSender !== null ? { "auth.local.email-change-sender": emailChangeSender } : {}),
171
176
  };
172
177
  const runtime = createCapabilityRuntime({
173
178
  inputs,
@@ -443,7 +448,7 @@ test("local auth provider rejects dev login-as enablement in staging and product
443
448
  () => createStartedApp({
444
449
  env: {
445
450
  ...devAuthEnv(),
446
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
451
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
447
452
  AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
448
453
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
449
454
  APP_ENV, NODE_ENV: "production"
@@ -461,7 +466,7 @@ test("a production server with AUTH_LOCAL_RECOVERY_DEV_OUTPUT set refuses to sta
461
466
  await assert.rejects(
462
467
  () => createStartedApp({
463
468
  env: {
464
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
469
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
465
470
  AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
466
471
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "log",
467
472
  APP_ENV: "production", NODE_ENV: "production"
@@ -473,6 +478,39 @@ test("a production server with AUTH_LOCAL_RECOVERY_DEV_OUTPUT set refuses to sta
473
478
  );
474
479
  });
475
480
 
481
+ test("staging and production need AUTH_LOCAL_SESSION_SECRET, and AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK on the file " +
482
+ "backend, and have no password recovery without a sender", async () => {
483
+ const appRoot = await temporaryStoreDir("jskit-auth-local-config-");
484
+ const resolve = (env, { fileBackend = false, emailRecovery = false } = {}) => resolveLocalAuthConfig({
485
+ appRoot,
486
+ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "false", APP_PUBLIC_URL: "https://app.example.test", ...env },
487
+ fileBackend,
488
+ emailRecovery
489
+ });
490
+ for (const env of [STAGING, PRODUCTION]) {
491
+ const { AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: _acknowledged, ...unacknowledged } = env;
492
+ assert.throws(() => resolve(unacknowledged, { fileBackend: true }), {
493
+ message: "AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK is required to use the local file auth backend in staging and production."
494
+ }, env.APP_ENV);
495
+ assert.throws(() => resolve({ ...env, AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "false" }, { fileBackend: true }),
496
+ { message: /^AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK is required/u }, env.APP_ENV);
497
+ assert.equal(resolve(env, { fileBackend: true }).isStagingOrProduction, true, env.APP_ENV);
498
+ assert.equal(resolve(unacknowledged).isStagingOrProduction, true, `${env.APP_ENV}: an installed backend needs no acknowledgement`);
499
+ assert.throws(() => resolve({ ...env, AUTH_LOCAL_SESSION_SECRET: "" }), {
500
+ message: "AUTH_LOCAL_SESSION_SECRET is required for local auth in staging and production."
501
+ }, env.APP_ENV);
502
+ assert.equal(resolve(env).recoveryEnabled, false, `${env.APP_ENV} without a recovery sender`);
503
+ assert.equal(resolve(env, { emailRecovery: true }).recoveryEnabled, true, `${env.APP_ENV} with one`);
504
+ }
505
+ // Development and test need neither: they keep a generated session secret and recover through the log.
506
+ for (const APP_ENV of ["development", "test"]) {
507
+ const config = resolve({ APP_ENV }, { fileBackend: true });
508
+ assert.equal(config.isStagingOrProduction, false, APP_ENV);
509
+ assert.match(config.sessionSecret, /^[\w-]{43}$/u, APP_ENV);
510
+ assert.equal(config.recoveryEnabled, true, APP_ENV);
511
+ }
512
+ });
513
+
476
514
  test("local auth provider applies auth service decorators for blocking and non-blocking hooks", async () => {
477
515
  const calls = [];
478
516
  const errors = [];
@@ -1377,6 +1415,93 @@ test("production sessions use host-only __Host- cookies and ignore the old names
1377
1415
  assert.equal((await app.authService.authenticateRequest({ cookies: oldNames })).authenticated, false);
1378
1416
  });
1379
1417
 
1418
+ test("an installed auth.local.sign-in-events is given each sign-in event, and without one each is logged", async (t) => {
1419
+ const PASSWORD = "correct horse battery staple";
1420
+ const events = [];
1421
+ const app = await createStartedApp({ signInEvents: async (event) => { events.push(event); } });
1422
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1423
+ const ada = (await app.authService.register({ email: "ada@example.com", password: PASSWORD })).actor.providerUserId;
1424
+ await assert.rejects(app.authService.login({ email: "ada@example.com", password: "a wrong password" }), { status: 401 });
1425
+ // Stopping waits for the events still being handed over.
1426
+ await app.runtime.shutdown();
1427
+ assert.deepEqual(events.map(({ type, method, reason = "", userId }) => [type, method, reason, userId]), [
1428
+ ["signedIn", "registration", "", ada],
1429
+ ["failed", "password", "invalidCredentials", ada]
1430
+ ]);
1431
+
1432
+ const logs = [];
1433
+ const logged = await createStartedApp({
1434
+ logger: { info: (fields, message) => logs.push([message, fields?.signInEvent?.method]), warn() {}, error() {}, debug() {} }
1435
+ });
1436
+ t.after(() => fs.rm(logged.storeDir, { recursive: true, force: true }));
1437
+ await logged.authService.register({ email: "ada@example.com", password: PASSWORD });
1438
+ await logged.runtime.shutdown();
1439
+ assert.deepEqual(logs.filter(([message]) => String(message).startsWith("Local auth sign-in")),
1440
+ [["Local auth sign-in: signedIn.", "registration"]]);
1441
+ });
1442
+
1443
+ test("an installed auth.local.email-change-sender sends as APP_ENV says; without one, development and test log the links and staging and production have none",
1444
+ async (t) => {
1445
+ const PASSWORD = "correct horse battery staple";
1446
+ const account = async (app, id, email) => {
1447
+ await app.backend.withTransaction(async (tx) => tx.users.create({ id, email, displayName: id, password: await hashPassword(PASSWORD) }));
1448
+ return id;
1449
+ };
1450
+ const stagingOrProduction = { AUTH_LOCAL_EMAIL_CONFIRMATION: "", AUTH_LOCAL_SELF_REGISTRATION: "false" };
1451
+
1452
+ // Production sends each link to its address.
1453
+ const sent = [];
1454
+ const production = await createStartedApp({ env: { ...PRODUCTION, ...stagingOrProduction }, emailChangeSender: async (delivery) => { sent.push(delivery); } });
1455
+ t.after(() => fs.rm(production.storeDir, { recursive: true, force: true }));
1456
+ assert.equal(production.authService.getCapabilities().features.emailChange, true);
1457
+ await production.authService.requestEmailChangeForUser({ userId: await account(production, "usr_ada", "ada@example.com"), email: "ada.new@example.com" });
1458
+ // Stopping waits for the links still being sent.
1459
+ await production.runtime.shutdown();
1460
+ assert.deepEqual(sent.map(({ type, email, originalEmail, currentEmail }) => [type, email, originalEmail, currentEmail]),
1461
+ [["confirmation", "ada.new@example.com", "", "ada@example.com"]]);
1462
+ assert.match(sent[0].confirmationUrl, /^http:\/\/localhost:5173\/auth\/email-change\?token=/u);
1463
+
1464
+ // Test (as development) logs the link an installed sender would send, and sends nothing.
1465
+ const logs = [];
1466
+ const logger = { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} };
1467
+ const copy = await createStartedApp({ emailChangeSender: async (delivery) => { sent.push(delivery); }, logger });
1468
+ t.after(() => fs.rm(copy.storeDir, { recursive: true, force: true }));
1469
+ await copy.authService.requestEmailChangeForUser({ userId: await account(copy, "usr_bob", "bob@example.com"), email: "bob.new@example.com" });
1470
+ await copy.runtime.shutdown();
1471
+ assert.equal(sent.length, 1, "nothing more sent");
1472
+ const [link] = logs.filter(({ message }) => String(message).includes("the email change email"));
1473
+ assert.equal(link.message, "Test: the email change email to bob.new@example.com was logged, not sent.");
1474
+ assert.match(link.details.confirmationUrl, /\/auth\/email-change\?token=/u);
1475
+
1476
+ // Without one, development and test log each link.
1477
+ logs.length = 0;
1478
+ const logged = await createStartedApp({ logger });
1479
+ t.after(() => fs.rm(logged.storeDir, { recursive: true, force: true }));
1480
+ await logged.authService.requestEmailChangeForUser({ userId: await account(logged, "usr_eve", "eve@example.com"), email: "eve.new@example.com" });
1481
+ await logged.runtime.shutdown();
1482
+ assert.deepEqual(logs.filter(({ message }) => String(message).startsWith("Local auth email change")).map(({ details, message }) => [message, details.email]),
1483
+ [["Local auth email change: confirmation.", "eve.new@example.com"]]);
1484
+
1485
+ // Staging and production without one offer no email change, and a sender needs the public URL its links name.
1486
+ for (const env of [STAGING, PRODUCTION]) {
1487
+ const without = await createStartedApp({ env: { ...env, ...stagingOrProduction } });
1488
+ t.after(() => fs.rm(without.storeDir, { recursive: true, force: true }));
1489
+ assert.equal(without.authService.getCapabilities().features.emailChange, false, env.APP_ENV);
1490
+ for (const asked of [
1491
+ without.authService.requestEmailChange({ cookies: {} }, { email: "x@example.com", password: PASSWORD }),
1492
+ without.authService.requestEmailChangeForUser({ userId: "usr_any", email: "x@example.com" }),
1493
+ without.authService.confirmEmailChange({ token: "any" })
1494
+ ]) {
1495
+ await assert.rejects(asked, { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
1496
+ }
1497
+ await without.runtime.shutdown();
1498
+ }
1499
+ await assert.rejects(
1500
+ () => createStartedApp({ env: { APP_PUBLIC_URL: "" }, emailChangeSender: async () => {} }),
1501
+ /APP_PUBLIC_URL is required when local auth emails email change links/u
1502
+ );
1503
+ });
1504
+
1380
1505
  test("local recovery uses the application sender without returning or logging its token", async (t) => {
1381
1506
  const messages = [];
1382
1507
  const logs = [];
@@ -1549,7 +1674,7 @@ test("in production, email confirmation needs an auth.local.confirmation-sender,
1549
1674
  const production = {
1550
1675
  APP_ENV: "production", NODE_ENV: "production",
1551
1676
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1552
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1677
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
1553
1678
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1554
1679
  AUTH_LOCAL_EMAIL_CONFIRMATION: ""
1555
1680
  };
@@ -1573,7 +1698,7 @@ test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confi
1573
1698
  env: {
1574
1699
  APP_ENV: "production", NODE_ENV: "production",
1575
1700
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1576
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1701
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
1577
1702
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1578
1703
  AUTH_LOCAL_EMAIL_CONFIRMATION: "",
1579
1704
  AUTH_LOCAL_SELF_REGISTRATION: "false"
@@ -1639,7 +1764,7 @@ test("the confirmation sender emails the link, which is never returned or logged
1639
1764
  env: {
1640
1765
  APP_ENV: "production", NODE_ENV: "production",
1641
1766
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1642
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1767
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
1643
1768
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1644
1769
  AUTH_LOCAL_EMAIL_CONFIRMATION: "",
1645
1770
  APP_PUBLIC_URL: "https://app.example.test"
@@ -1853,7 +1978,7 @@ test("only the exact answer \"without-link\" confirms without a link, and a conf
1853
1978
  env: {
1854
1979
  APP_ENV: "production", NODE_ENV: "production",
1855
1980
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1856
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1981
+ AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK: "true",
1857
1982
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1858
1983
  AUTH_LOCAL_EMAIL_CONFIRMATION: ""
1859
1984
  },
@@ -0,0 +1,38 @@
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 { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
7
+ import { localServiceOptions } from "../test-support/localService.js";
8
+ import { exerciseSessionMetadata } from "../test-support/sessionMetadataScenario.js";
9
+
10
+ test("a session keeps where and when it was last seen, at most every five minutes (file backend)", async (t) => {
11
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-session-metadata-"));
12
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
13
+ const backend = createLocalFileBackend({ storeDir });
14
+ await exerciseSessionMetadata(t, { service: createLocalAuthService({ ...localServiceOptions(), backend }), backend });
15
+ });
16
+
17
+ test("a session the file backend stored before it kept where sessions are seen reads as never seen", async (t) => {
18
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-session-metadata-"));
19
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
20
+ const field = (value) => Buffer.from(value, "utf8").toString("base64url");
21
+ const line = ["session", "v1", "ses_old", "usr_old", "hash-old", "normal",
22
+ field("2026-11-01T09:00:00.000Z"), field("2026-12-01T09:00:00.000Z"), field(""), field("")].join(":");
23
+ await fs.writeFile(path.join(storeDir, "sessions.passwd"), `${line}\n`);
24
+ const backend = createLocalFileBackend({ storeDir });
25
+ assert.deepEqual(await backend.withTransaction((tx) => tx.sessions.findById("ses_old")), {
26
+ id: "ses_old",
27
+ userId: "usr_old",
28
+ tokenHash: "hash-old",
29
+ purpose: "normal",
30
+ createdAt: "2026-11-01T09:00:00.000Z",
31
+ expiresAt: "2026-12-01T09:00:00.000Z",
32
+ revokedAt: "",
33
+ secondFactorAt: "",
34
+ ip: "",
35
+ userAgent: "",
36
+ lastSeenAt: ""
37
+ });
38
+ });
@@ -0,0 +1,206 @@
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 { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
7
+ import {
8
+ createLocalAuthService,
9
+ createLocalDeliveries,
10
+ createLocalFileBackend,
11
+ createLoggedSignInEvents,
12
+ hashPassword
13
+ } from "../src/server/lib/index.js";
14
+ import { NO_PASSWORD } from "../src/server/lib/accounts.js";
15
+ import { APP_URL, approveAtProvider, oidcProviderEntry, startOidcProvider } from "../test-support/oauthHarness.js";
16
+ import { localServiceOptions } from "../test-support/localService.js";
17
+ import { createPassIssuer, passIdentityByEmail, passwordlessAccount } from "../test-support/passSignInScenario.js";
18
+ import { requestFrom } from "../test-support/sessionMetadataScenario.js";
19
+
20
+ const PASSWORD = "correct horse battery staple";
21
+ const BROWSER = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
22
+ const START = Date.parse("2026-11-15T09:00:00.000Z");
23
+ const FROM = requestFrom("203.0.113.7", BROWSER);
24
+ const WHERE = Object.freeze({ ip: "203.0.113.7", userAgent: BROWSER });
25
+
26
+ /**
27
+ * A local auth service over a file store of the test's own that keeps every sign-in event it is given, sent through
28
+ * deliveries the test waits for.
29
+ * @param {import("node:test").TestContext} t
30
+ * @param {{ env?: Record<string, string>, signInEvents?: (event: object) => Promise<void>, config?: (config: object) => object, passIdentity?: boolean }} [options]
31
+ */
32
+ async function startService(t, { env = {}, signInEvents = null, config = (given) => given, passIdentity = false } = {}) {
33
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-events-"));
34
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
35
+ const backend = createLocalFileBackend({ storeDir });
36
+ const deliveries = createLocalDeliveries({ logger: silentLogger });
37
+ const events = [];
38
+ const options = localServiceOptions({ env });
39
+ const service = createLocalAuthService({
40
+ ...options,
41
+ backend,
42
+ config: config(options.config),
43
+ deliveries,
44
+ ...(passIdentity ? { passIdentity: passIdentityByEmail(backend) } : {}),
45
+ signInEvents: signInEvents ?? (async (event) => {
46
+ events.push(event);
47
+ })
48
+ });
49
+ /** The events sent so far, once every one of them was handed over; it forgets them. */
50
+ async function takeEvents() {
51
+ await deliveries.settled();
52
+ return events.splice(0);
53
+ }
54
+ return { backend, service, takeEvents };
55
+ }
56
+
57
+ const at = (ms = 0) => new Date(START + ms).toISOString();
58
+
59
+ test("each sign-in and each refused password sign-in is an event, with the account, where it came from and when", async (t) => {
60
+ t.mock.timers.enable({ apis: ["Date"], now: START });
61
+ const { backend, service, takeEvents } = await startService(t, { env: { AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT: "1" } });
62
+ const ada = await service.register({ email: "ada@example.com", password: PASSWORD }, FROM);
63
+ const adaId = ada.actor.providerUserId;
64
+ await service.login({ email: "ada@example.com", password: PASSWORD }, FROM);
65
+ await backend.withTransaction(async (tx) => tx.users.create({
66
+ id: "usr_off", email: "off@example.com", displayName: "Off", password: await hashPassword(PASSWORD), disabled: true
67
+ }));
68
+ await assert.rejects(service.login({ email: "off@example.com", password: PASSWORD }, FROM), { code: "auth.local.login.disabled" });
69
+ await assert.rejects(service.login({ email: "nobody@example.com", password: "a wrong password" }, FROM), { status: 401 });
70
+ await assert.rejects(service.login({ email: "ada@example.com", password: "a wrong password" }, FROM), { status: 401 });
71
+ // One failure makes ada wait: then even the right password is refused, unchecked.
72
+ await assert.rejects(service.login({ email: "ada@example.com", password: PASSWORD }, FROM), { status: 429 });
73
+ // A sign-in with no request says nothing of where it came from.
74
+ t.mock.timers.tick(31_000);
75
+ await service.login({ email: "ada@example.com", password: PASSWORD });
76
+
77
+ assert.deepEqual(await takeEvents(), [
78
+ { type: "signedIn", method: "registration", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
79
+ { type: "signedIn", method: "password", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
80
+ { type: "failed", method: "password", reason: "disabled", userId: "usr_off", email: "off@example.com", ...WHERE, at: at() },
81
+ { type: "failed", method: "password", reason: "invalidCredentials", userId: "", email: "nobody@example.com", ...WHERE, at: at() },
82
+ { type: "failed", method: "password", reason: "invalidCredentials", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
83
+ { type: "failed", method: "password", reason: "locked", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
84
+ { type: "signedIn", method: "password", userId: adaId, email: "ada@example.com", ip: "", userAgent: "", at: at(31_000) }
85
+ ]);
86
+
87
+ // A password reset's link signs in too, for the reset.
88
+ const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
89
+ await service.completePasswordRecovery({ code: new URL(recoveryUrl).searchParams.get("token") }, FROM);
90
+ assert.deepEqual(await takeEvents(), [
91
+ { type: "signedIn", method: "recovery", userId: adaId, email: "ada@example.com", ...WHERE, at: at(31_000) }
92
+ ]);
93
+ });
94
+
95
+ test("a registration waiting for its email is an event when its right password is refused, and when its link signs in", async (t) => {
96
+ t.mock.timers.enable({ apis: ["Date"], now: START });
97
+ const { service, takeEvents } = await startService(t, { env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" } });
98
+ const waiting = await service.register({ email: "eve@example.com", password: PASSWORD }, FROM);
99
+ await assert.rejects(service.login({ email: "eve@example.com", password: PASSWORD }, FROM), { code: "auth.login.emailUnconfirmed" });
100
+ const token = new URL(waiting.confirmationUrl).searchParams.get("confirmation_token");
101
+ const confirmed = await service.confirmRegistration({ token, password: PASSWORD }, FROM);
102
+ assert.deepEqual(await takeEvents(), [
103
+ { type: "failed", method: "password", reason: "unconfirmed", userId: "", email: "eve@example.com", ...WHERE, at: at() },
104
+ { type: "signedIn", method: "confirmation", userId: confirmed.actor.providerUserId, email: "eve@example.com", ...WHERE, at: at() }
105
+ ]);
106
+ });
107
+
108
+ test("a one-time pass's sign-in, and its refusal for a disabled account, are events", async (t) => {
109
+ t.mock.timers.enable({ apis: ["Date"], now: START });
110
+ const issuer = createPassIssuer();
111
+ const { backend, service, takeEvents } = await startService(t, { env: issuer.env, passIdentity: true });
112
+ await backend.withTransaction(async (tx) => {
113
+ await tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" }));
114
+ await tx.users.create(passwordlessAccount({ id: "usr_off", email: "off@example.com", displayName: "Off", disabled: true }));
115
+ });
116
+ await service.signInWithPass({ pass: issuer.pass("ada@example.com") }, FROM);
117
+ await assert.rejects(service.signInWithPass({ pass: issuer.pass("off@example.com") }, FROM), { code: "auth.local.login.disabled" });
118
+ // A pass that names nobody signs no account in or out: no event.
119
+ await assert.rejects(service.signInWithPass({ pass: issuer.pass("nobody@example.com") }, FROM), { code: "auth.pass.unmapped" });
120
+ assert.deepEqual(await takeEvents(), [
121
+ { type: "signedIn", method: "pass", userId: "usr_ada", email: "ada@example.com", ...WHERE, at: at() },
122
+ { type: "failed", method: "pass", reason: "disabled", userId: "usr_off", email: "off@example.com", ...WHERE, at: at() }
123
+ ]);
124
+ });
125
+
126
+ test("a provider's sign-in, and its refusal for a disabled account, are events naming the provider", async (t) => {
127
+ const issuer = await startOidcProvider();
128
+ t.after(() => issuer.close());
129
+ const withGoogle = { env: { APP_PUBLIC_URL: APP_URL }, config: (given) => ({ ...given, oauthProviders: [oidcProviderEntry(issuer)], oauthEnabled: true }) };
130
+ const fromBrowser = (request) => ({ ...request, ...FROM, cookies: request.cookies });
131
+ const { service, takeEvents } = await startService(t, withGoogle);
132
+ const approved = await approveAtProvider(service);
133
+ const signedIn = await service.oauthComplete(approved.input, fromBrowser(approved.request));
134
+ const [event] = await takeEvents();
135
+ assert.deepEqual({ ...event, at: "" }, {
136
+ type: "signedIn",
137
+ method: "provider",
138
+ provider: "google",
139
+ userId: signedIn.actor.providerUserId,
140
+ email: issuer.account.email,
141
+ ...WHERE,
142
+ at: ""
143
+ });
144
+
145
+ const off = await startService(t, withGoogle);
146
+ await off.backend.withTransaction((tx) => tx.users.create({
147
+ id: "usr_off", email: issuer.account.email, displayName: "Off", password: NO_PASSWORD, disabled: true
148
+ }));
149
+ const refused = await approveAtProvider(off.service);
150
+ await assert.rejects(off.service.oauthComplete(refused.input, fromBrowser(refused.request)), { code: "auth.local.login.disabled" });
151
+ const [refusal] = await off.takeEvents();
152
+ assert.deepEqual({ ...refusal, at: "" }, {
153
+ type: "failed",
154
+ method: "provider",
155
+ provider: "google",
156
+ reason: "disabled",
157
+ userId: "usr_off",
158
+ email: issuer.account.email,
159
+ ...WHERE,
160
+ at: ""
161
+ });
162
+ });
163
+
164
+ test("a refused sign-in answers without waiting for its event, and an event that fails is logged, never the sign-in's failure", async (t) => {
165
+ const warnings = [];
166
+ const logger = { ...silentLogger, error: (fields, message) => warnings.push({ fields, message }) };
167
+ const stalled = await startService(t, { signInEvents: () => new Promise(() => {}) });
168
+ await stalled.service.register({ email: "ada@example.com", password: PASSWORD });
169
+ for (const email of ["ada@example.com", "nobody@example.com"]) {
170
+ await assert.rejects(stalled.service.login({ email, password: "a wrong password" }), { status: 401 }, email);
171
+ }
172
+
173
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-events-"));
174
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
175
+ const deliveries = createLocalDeliveries({ logger });
176
+ const failing = createLocalAuthService({
177
+ ...localServiceOptions(),
178
+ backend: createLocalFileBackend({ storeDir }),
179
+ deliveries,
180
+ logger,
181
+ signInEvents: async () => {
182
+ throw new Error("The audit log is unavailable.");
183
+ }
184
+ });
185
+ assert.equal((await failing.register({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
186
+ await deliveries.settled();
187
+ assert.deepEqual(warnings.map(({ fields, message }) => [fields.err.message, fields.email, message]), [
188
+ ["The audit log is unavailable.", "ada@example.com", "Sending the sign-in event failed."]
189
+ ]);
190
+ });
191
+
192
+ test("a local auth service given no sign-in events recorder is refused when it is made", async (t) => {
193
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-events-"));
194
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
195
+ const backend = createLocalFileBackend({ storeDir });
196
+ assert.throws(() => createLocalAuthService({ ...localServiceOptions(), backend, signInEvents: undefined }),
197
+ { name: "TypeError", message: /signInEvents/u });
198
+ });
199
+
200
+ test("without an application's own, each sign-in event is logged", async () => {
201
+ const logged = [];
202
+ const logSignInEvent = createLoggedSignInEvents({ ...silentLogger, info: (fields, message) => logged.push({ fields, message }) });
203
+ const event = { type: "failed", method: "password", reason: "invalidCredentials", userId: "", email: "nobody@example.com", ip: "", userAgent: "", at: at() };
204
+ await logSignInEvent(event);
205
+ assert.deepEqual(logged, [{ fields: { signInEvent: event }, message: "Local auth sign-in: failed." }]);
206
+ });
@@ -0,0 +1,139 @@
1
+ import assert from "node:assert/strict";
2
+ import { createLocalAuthService, createLocalDeliveries } from "../src/server/lib/index.js";
3
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
4
+ import { AUTH_TEXTS } from "@jskit-ai/auth-core/server/authTexts";
5
+ import { localServiceOptions } from "./localService.js";
6
+
7
+ const PASSWORD = "correct horse battery staple";
8
+ const DAY = 24 * 60 * 60 * 1000;
9
+
10
+ /**
11
+ * A local auth service over the backend whose email-change sender keeps what it is given, sent through deliveries the
12
+ * test waits for.
13
+ * @param {import("../src/server/types.js").AuthLocalBackend} backend
14
+ */
15
+ function emailChangeService(backend) {
16
+ const deliveries = createLocalDeliveries({ logger: silentLogger });
17
+ const sent = [];
18
+ const service = createLocalAuthService({
19
+ ...localServiceOptions({ emailChangeSender: true }),
20
+ backend,
21
+ deliveries,
22
+ emailChangeSender: async (delivery) => {
23
+ sent.push(delivery);
24
+ }
25
+ });
26
+ /** What was sent so far, once every send finished; it forgets them. */
27
+ async function takeSent() {
28
+ await deliveries.settled();
29
+ return sent.splice(0);
30
+ }
31
+ return { service, takeSent };
32
+ }
33
+
34
+ function sessionCookies(session) {
35
+ return { jskit_local_access_token: session.access_token, jskit_local_refresh_token: session.refresh_token };
36
+ }
37
+
38
+ const tokenOf = (delivery) => new URL(delivery.confirmationUrl).searchParams.get("token");
39
+
40
+ /**
41
+ * An account's email change, against any backend, with Date mocked through `t.mock.timers`: the signed-in person
42
+ * asks with their password, or the application asks for an account; a link goes to the new address, and using it
43
+ * changes the email and tells the old address. A newer request, a used link, an expired one and one for an email
44
+ * taken since are refused; refusals change and send nothing.
45
+ * @param {import("node:test").TestContext} t
46
+ * @param {import("../src/server/types.js").AuthLocalBackend} backend
47
+ * @returns {Promise<{ adaId: string, bobId: string }>} The accounts it changed, for the backend's own checks.
48
+ */
49
+ async function exerciseEmailChange(t, backend) {
50
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-15T09:00:00.000Z") });
51
+ const { service, takeSent } = emailChangeService(backend);
52
+ const ada = await service.register({ email: "ada@example.com", password: PASSWORD });
53
+ const bob = await service.register({ email: "bob@example.com", password: PASSWORD });
54
+ const adaId = ada.actor.providerUserId;
55
+ const bobId = bob.actor.providerUserId;
56
+ const signedIn = { cookies: sessionCookies(ada.session) };
57
+ const user = (id) => backend.withTransaction((tx) => tx.users.findById(id));
58
+
59
+ // Refused: no session, a wrong password, no email or not an email, the same email, another account's email.
60
+ await assert.rejects(service.requestEmailChange({ cookies: {} }, { email: "new@example.com", password: PASSWORD }),
61
+ AUTH_TEXTS.sessionRequired);
62
+ await assert.rejects(service.requestEmailChange(signedIn, { email: "new@example.com", password: "a wrong password" }),
63
+ { status: 400, code: "auth.local.emailChange.passwordInvalid" });
64
+ for (const email of ["", "not an email"]) {
65
+ await assert.rejects(service.requestEmailChange(signedIn, { email, password: PASSWORD }),
66
+ { status: 400, code: "auth.local.email.invalid" }, email);
67
+ }
68
+ await assert.rejects(service.requestEmailChange(signedIn, { email: "Ada@Example.com", password: PASSWORD }),
69
+ { status: 400, code: "auth.local.emailChange.sameEmail" });
70
+ await assert.rejects(service.requestEmailChange(signedIn, { email: "bob@example.com", password: PASSWORD }),
71
+ { status: 409, code: "auth.local.emailChange.emailTaken" });
72
+ assert.deepEqual(await takeSent(), []);
73
+ assert.equal((await user(adaId)).pendingEmail, "");
74
+
75
+ // A request answers the new address and sends it a link; the email is unchanged until the link is used. A userId
76
+ // in the request changes nothing: the session names the account.
77
+ assert.deepEqual(
78
+ await service.requestEmailChange(signedIn, { email: "Ada.First@example.com", password: PASSWORD, userId: bobId }),
79
+ { ok: true, email: "ada.first@example.com" }
80
+ );
81
+ const [first] = await takeSent();
82
+ assert.deepEqual({ ...first, confirmationUrl: "" },
83
+ { type: "confirmation", email: "ada.first@example.com", currentEmail: "ada@example.com", confirmationUrl: "" });
84
+ assert.match(first.confirmationUrl, /^http:\/\/localhost:5173\/auth\/email-change\?token=/u);
85
+ assert.equal((await user(adaId)).email, "ada@example.com");
86
+ assert.equal((await user(adaId)).pendingEmail, "ada.first@example.com");
87
+ assert.equal((await user(bobId)).pendingEmail, "");
88
+
89
+ // A newer request replaces it, so the first link no longer works.
90
+ await service.requestEmailChange(signedIn, { email: "ada.second@example.com", password: PASSWORD });
91
+ const [second] = await takeSent();
92
+ await assert.rejects(service.confirmEmailChange({ token: tokenOf(first) }), { status: 400, code: "auth.local.emailChange.linkInvalid" });
93
+ // A password reset sent to the old address before the change stops working once the email changes.
94
+ const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
95
+
96
+ assert.deepEqual(await service.confirmEmailChange({ token: tokenOf(second) }), { ok: true, email: "ada.second@example.com" });
97
+ assert.deepEqual(await takeSent(), [{ type: "notice", email: "ada@example.com", newEmail: "ada.second@example.com" }]);
98
+ const changed = await user(adaId);
99
+ assert.deepEqual([changed.email, changed.pendingEmail], ["ada.second@example.com", ""]);
100
+ await assert.rejects(service.completePasswordRecovery({ code: new URL(recoveryUrl).searchParams.get("token") }),
101
+ { code: "auth.local.recovery.tokenInvalid" });
102
+ await assert.rejects(service.login({ email: "ada@example.com", password: PASSWORD }), { status: 401 });
103
+ assert.equal((await service.login({ email: "ada.second@example.com", password: PASSWORD })).actor.email, "ada.second@example.com");
104
+ // The session stays signed in, with the new email from its next request on.
105
+ assert.equal((await service.authenticateRequest({ cookies: signedIn.cookies })).actor.email, "ada.second@example.com");
106
+ // A used link, a link that is not one, and a link changed by hand are refused.
107
+ for (const token of [tokenOf(second), "", "not-a-link", `${tokenOf(second)}x`]) {
108
+ await assert.rejects(service.confirmEmailChange({ token }), { status: 400, code: "auth.local.emailChange.linkInvalid" }, token);
109
+ }
110
+
111
+ // The application asks for an account, without a password; a missing id is a programming error, a missing account
112
+ // is refused.
113
+ assert.deepEqual(await service.requestEmailChangeForUser({ userId: bobId, email: "bob.new@example.com" }),
114
+ { ok: true, email: "bob.new@example.com" });
115
+ const [bobLink] = await takeSent();
116
+ assert.deepEqual([bobLink.type, bobLink.email, bobLink.currentEmail], ["confirmation", "bob.new@example.com", "bob@example.com"]);
117
+ await assert.rejects(service.requestEmailChangeForUser({ userId: "", email: "x@example.com" }), TypeError);
118
+ await assert.rejects(service.requestEmailChangeForUser({ userId: "usr_missing", email: "x@example.com" }),
119
+ { status: 404, code: "auth.local.emailChange.accountNotFound" });
120
+ await assert.rejects(service.requestEmailChangeForUser({ userId: bobId, email: "ada.second@example.com" }),
121
+ { status: 409, code: "auth.local.emailChange.emailTaken" });
122
+ assert.deepEqual(await takeSent(), []);
123
+
124
+ // A link expires after a day.
125
+ t.mock.timers.tick(DAY + 1000);
126
+ await assert.rejects(service.confirmEmailChange({ token: tokenOf(bobLink) }), { status: 400, code: "auth.local.emailChange.linkInvalid" });
127
+ assert.equal((await user(bobId)).email, "bob@example.com");
128
+
129
+ // An address an account took since the request is refused, and nothing changes.
130
+ await service.requestEmailChangeForUser({ userId: bobId, email: "carol@example.com" });
131
+ const [toCarol] = await takeSent();
132
+ await service.register({ email: "carol@example.com", password: PASSWORD });
133
+ await assert.rejects(service.confirmEmailChange({ token: tokenOf(toCarol) }), { status: 409, code: "auth.local.emailChange.emailTaken" });
134
+ assert.equal((await user(bobId)).email, "bob@example.com");
135
+ assert.deepEqual(await takeSent(), []);
136
+ return { adaId, bobId };
137
+ }
138
+
139
+ export { emailChangeService, exerciseEmailChange };
@@ -3,10 +3,12 @@ import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
3
3
  import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
4
4
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
5
  import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
6
+ import { createLoggedEmailChangeSender } from "../src/server/lib/emailChange.js";
6
7
  import { createLoggedConfirmationSender } from "../src/server/lib/emailConfirmation.js";
7
8
  import { createLoggedRecoverySender } from "../src/server/lib/passwordFlows.js";
8
9
  import { scryptPasswordStrategy } from "../src/server/lib/passwords.js";
9
10
  import { createLoggedSecondFactorEvents } from "../src/server/lib/secondFactor.js";
11
+ import { createLoggedSignInEvents } from "../src/server/lib/sessions.js";
10
12
 
11
13
  /**
12
14
  * What a test passes to createLocalAuthService besides its backend: a complete
@@ -18,8 +20,9 @@ import { createLoggedSecondFactorEvents } from "../src/server/lib/secondFactor.j
18
20
  * @param {Record<string, string>} [options.env] Environment values over the test ones.
19
21
  * @param {boolean} [options.emailRecovery] True when the test passes its own recoverySender.
20
22
  * @param {boolean} [options.emailConfirmationSender] True when the test passes its own confirmationSender.
23
+ * @param {boolean} [options.emailChangeSender] True when the test passes its own emailChangeSender.
21
24
  */
22
- function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmationSender = false } = {}) {
25
+ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmationSender = false, emailChangeSender = false } = {}) {
23
26
  return {
24
27
  config: resolveLocalAuthConfig({
25
28
  appRoot: os.tmpdir(),
@@ -33,7 +36,8 @@ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmatio
33
36
  },
34
37
  fileBackend: false,
35
38
  emailRecovery,
36
- emailConfirmationSender
39
+ emailConfirmationSender,
40
+ emailChangeSender
37
41
  }),
38
42
  invitationContextResolver: invitationAsGiven,
39
43
  logger: silentLogger,
@@ -41,7 +45,9 @@ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmatio
41
45
  profileProjector: noAppProfiles,
42
46
  recoverySender: createLoggedRecoverySender(silentLogger),
43
47
  confirmationSender: createLoggedConfirmationSender(silentLogger),
44
- secondFactorEvents: createLoggedSecondFactorEvents(silentLogger)
48
+ emailChangeSender: createLoggedEmailChangeSender(silentLogger),
49
+ secondFactorEvents: createLoggedSecondFactorEvents(silentLogger),
50
+ signInEvents: createLoggedSignInEvents(silentLogger)
45
51
  };
46
52
  }
47
53