@jskit-ai/auth-provider-local-core 0.2.35 → 0.2.37

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/locales/en.json +9 -1
  3. package/package.json +8 -6
  4. package/src/server/lib/accounts.js +41 -11
  5. package/src/server/lib/config.js +70 -51
  6. package/src/server/lib/deliveries.js +4 -2
  7. package/src/server/lib/emailChange.js +183 -0
  8. package/src/server/lib/emailConfirmation.js +5 -22
  9. package/src/server/lib/fileBackend.js +40 -2
  10. package/src/server/lib/fileRecords.js +17 -7
  11. package/src/server/lib/firstAccountSetup.js +4 -4
  12. package/src/server/lib/index.js +2 -0
  13. package/src/server/lib/oauthFlows.js +18 -7
  14. package/src/server/lib/passSignIn.js +16 -6
  15. package/src/server/lib/passwordFlows.js +7 -23
  16. package/src/server/lib/registerHookDecorator.js +4 -4
  17. package/src/server/lib/service.js +30 -9
  18. package/src/server/lib/sessions.js +97 -19
  19. package/src/server/providers/AuthLocalProvider.js +64 -16
  20. package/src/server/types.js +75 -10
  21. package/test/accountEnumeration.test.js +12 -3
  22. package/test/codedTexts.test.js +1 -1
  23. package/test/cookieSameSite.test.js +1 -1
  24. package/test/emailChange.test.js +37 -0
  25. package/test/firstAccountSetup.test.js +6 -6
  26. package/test/oauthSignIn.test.js +14 -2
  27. package/test/passSignIn.test.js +1 -1
  28. package/test/providerRuntime.test.js +250 -95
  29. package/test/secondFactor.test.js +6 -6
  30. package/test/sessionMetadata.test.js +38 -0
  31. package/test/signInEvents.test.js +206 -0
  32. package/test/signInThrottle.test.js +1 -1
  33. package/test-support/emailChangeScenario.js +139 -0
  34. package/test-support/localService.js +10 -4
  35. package/test-support/passSignInScenario.js +10 -4
  36. package/test-support/sessionMetadataScenario.js +76 -0
@@ -22,6 +22,16 @@ import {
22
22
  } from "../src/server/lib/index.js";
23
23
 
24
24
  const DEV_AUTH_SECRET = "local-preview-exchange-secret";
25
+ // A production server's settings: its secrets and no development output. Only production sends an installed sender's
26
+ // email to its address.
27
+ const PRODUCTION = Object.freeze({
28
+ APP_ENV: "production",
29
+ NODE_ENV: "production",
30
+ AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
31
+ AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
32
+ AUTH_LOCAL_RECOVERY_DEV_OUTPUT: ""
33
+ });
34
+ const STAGING = Object.freeze({ ...PRODUCTION, APP_ENV: "staging" });
25
35
  const temporaryStoreDirs = [];
26
36
 
27
37
  async function temporaryStoreDir(prefix) {
@@ -107,7 +117,9 @@ async function createStartedApp({
107
117
  confirmationMode = null,
108
118
  invitationContextResolver = null,
109
119
  logger = null,
110
- configureExtensions = null
120
+ configureExtensions = null,
121
+ signInEvents = null,
122
+ emailChangeSender = null
111
123
  } = {}) {
112
124
  const storeDir = await temporaryStoreDir("jskit-auth-local-");
113
125
  const backend = createLocalFileBackend({ storeDir });
@@ -147,9 +159,7 @@ async function createStartedApp({
147
159
  APP_PUBLIC_URL: "http://localhost:5173",
148
160
  // Registration signs in at once here; the email confirmation tests turn confirmation on.
149
161
  AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
150
- NODE_ENV: "test",
151
- // An installed sender sends for real here; the test copy tests leave SIDE_EFFECTS unset.
152
- SIDE_EFFECTS: "live",
162
+ APP_ENV: "test",
153
163
  ...env
154
164
  },
155
165
  "runtime.logger": runtimeLogger,
@@ -160,6 +170,8 @@ async function createStartedApp({
160
170
  ...(recoverySender !== null ? { "auth.local.recovery-sender": recoverySender } : {}),
161
171
  ...(confirmationSender !== null ? { "auth.local.confirmation-sender": confirmationSender } : {}),
162
172
  ...(confirmationMode !== null ? { "auth.local.confirmation-mode": confirmationMode } : {}),
173
+ ...(signInEvents !== null ? { "auth.local.sign-in-events": signInEvents } : {}),
174
+ ...(emailChangeSender !== null ? { "auth.local.email-change-sender": emailChangeSender } : {}),
163
175
  };
164
176
  const runtime = createCapabilityRuntime({
165
177
  inputs,
@@ -429,21 +441,24 @@ test("local login-as rejects missing, incorrect, and non-loopback exchange autho
429
441
  );
430
442
  });
431
443
 
432
- test("local auth provider rejects dev login-as enablement in production", async () => {
433
- await assert.rejects(
434
- () => createStartedApp({
435
- env: {
436
- ...devAuthEnv(),
437
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
438
- AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
439
- AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
440
- NODE_ENV: "production"
441
- }
442
- }),
443
- (error) => /must not be enabled in production/.test(
444
- String(error.details?.cause?.message || error.message || "")
445
- )
446
- );
444
+ test("local auth provider rejects dev login-as enablement in staging and production", async () => {
445
+ for (const APP_ENV of ["staging", "production"]) {
446
+ await assert.rejects(
447
+ () => createStartedApp({
448
+ env: {
449
+ ...devAuthEnv(),
450
+ AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
451
+ AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
452
+ AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
453
+ APP_ENV, NODE_ENV: "production"
454
+ }
455
+ }),
456
+ (error) => /^AUTH_DEV_BYPASS_ENABLED is for development only: remove it from staging and production\.$/u.test(
457
+ String(error.details?.cause?.message || error.message || "")
458
+ ),
459
+ APP_ENV
460
+ );
461
+ }
447
462
  });
448
463
 
449
464
  test("a production server with AUTH_LOCAL_RECOVERY_DEV_OUTPUT set refuses to start, saying what to remove", async () => {
@@ -453,11 +468,11 @@ test("a production server with AUTH_LOCAL_RECOVERY_DEV_OUTPUT set refuses to sta
453
468
  AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
454
469
  AUTH_LOCAL_SESSION_SECRET: "production-session-secret",
455
470
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "log",
456
- NODE_ENV: "production"
471
+ APP_ENV: "production", NODE_ENV: "production"
457
472
  }
458
473
  }),
459
474
  (error) => String(error.details?.cause?.message || error.message || "") ===
460
- "AUTH_LOCAL_RECOVERY_DEV_OUTPUT is for development only and NODE_ENV is production. " +
475
+ "AUTH_LOCAL_RECOVERY_DEV_OUTPUT is for development only and APP_ENV is production. " +
461
476
  "Remove it from the production environment."
462
477
  );
463
478
  });
@@ -1324,7 +1339,7 @@ test("local file backend replays a pending multi-file transaction journal before
1324
1339
 
1325
1340
  test("a production server without accounts refuses a first registration without its setup code", async () => {
1326
1341
  const app = await createStartedApp({
1327
- env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
1342
+ env: { APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
1328
1343
  });
1329
1344
  assert.equal(app.authService.getCapabilities().features.firstAccountSetupCode, true);
1330
1345
  await assert.rejects(
@@ -1342,7 +1357,7 @@ test("a production server without accounts refuses a first registration without
1342
1357
 
1343
1358
  test("production sessions use host-only __Host- cookies and ignore the old names", async (t) => {
1344
1359
  const app = await createStartedApp({
1345
- env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
1360
+ env: { APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
1346
1361
  });
1347
1362
  t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1348
1363
  const registered = await app.authService.register({
@@ -1366,11 +1381,98 @@ test("production sessions use host-only __Host- cookies and ignore the old names
1366
1381
  assert.equal((await app.authService.authenticateRequest({ cookies: oldNames })).authenticated, false);
1367
1382
  });
1368
1383
 
1384
+ test("an installed auth.local.sign-in-events is given each sign-in event, and without one each is logged", async (t) => {
1385
+ const PASSWORD = "correct horse battery staple";
1386
+ const events = [];
1387
+ const app = await createStartedApp({ signInEvents: async (event) => { events.push(event); } });
1388
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1389
+ const ada = (await app.authService.register({ email: "ada@example.com", password: PASSWORD })).actor.providerUserId;
1390
+ await assert.rejects(app.authService.login({ email: "ada@example.com", password: "a wrong password" }), { status: 401 });
1391
+ // Stopping waits for the events still being handed over.
1392
+ await app.runtime.shutdown();
1393
+ assert.deepEqual(events.map(({ type, method, reason = "", userId }) => [type, method, reason, userId]), [
1394
+ ["signedIn", "registration", "", ada],
1395
+ ["failed", "password", "invalidCredentials", ada]
1396
+ ]);
1397
+
1398
+ const logs = [];
1399
+ const logged = await createStartedApp({
1400
+ logger: { info: (fields, message) => logs.push([message, fields?.signInEvent?.method]), warn() {}, error() {}, debug() {} }
1401
+ });
1402
+ t.after(() => fs.rm(logged.storeDir, { recursive: true, force: true }));
1403
+ await logged.authService.register({ email: "ada@example.com", password: PASSWORD });
1404
+ await logged.runtime.shutdown();
1405
+ assert.deepEqual(logs.filter(([message]) => String(message).startsWith("Local auth sign-in")),
1406
+ [["Local auth sign-in: signedIn.", "registration"]]);
1407
+ });
1408
+
1409
+ test("an installed auth.local.email-change-sender sends as APP_ENV says; without one, development and test log the links and a deployed server has none",
1410
+ async (t) => {
1411
+ const PASSWORD = "correct horse battery staple";
1412
+ const account = async (app, id, email) => {
1413
+ await app.backend.withTransaction(async (tx) => tx.users.create({ id, email, displayName: id, password: await hashPassword(PASSWORD) }));
1414
+ return id;
1415
+ };
1416
+ const deployed = { AUTH_LOCAL_EMAIL_CONFIRMATION: "", AUTH_LOCAL_SELF_REGISTRATION: "false" };
1417
+
1418
+ // Production sends each link to its address.
1419
+ const sent = [];
1420
+ const production = await createStartedApp({ env: { ...PRODUCTION, ...deployed }, emailChangeSender: async (delivery) => { sent.push(delivery); } });
1421
+ t.after(() => fs.rm(production.storeDir, { recursive: true, force: true }));
1422
+ assert.equal(production.authService.getCapabilities().features.emailChange, true);
1423
+ await production.authService.requestEmailChangeForUser({ userId: await account(production, "usr_ada", "ada@example.com"), email: "ada.new@example.com" });
1424
+ // Stopping waits for the links still being sent.
1425
+ await production.runtime.shutdown();
1426
+ assert.deepEqual(sent.map(({ type, email, originalEmail, currentEmail }) => [type, email, originalEmail, currentEmail]),
1427
+ [["confirmation", "ada.new@example.com", "", "ada@example.com"]]);
1428
+ assert.match(sent[0].confirmationUrl, /^http:\/\/localhost:5173\/auth\/email-change\?token=/u);
1429
+
1430
+ // Test (as development) logs the link an installed sender would send, and sends nothing.
1431
+ const logs = [];
1432
+ const logger = { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} };
1433
+ const copy = await createStartedApp({ emailChangeSender: async (delivery) => { sent.push(delivery); }, logger });
1434
+ t.after(() => fs.rm(copy.storeDir, { recursive: true, force: true }));
1435
+ await copy.authService.requestEmailChangeForUser({ userId: await account(copy, "usr_bob", "bob@example.com"), email: "bob.new@example.com" });
1436
+ await copy.runtime.shutdown();
1437
+ assert.equal(sent.length, 1, "nothing more sent");
1438
+ const [link] = logs.filter(({ message }) => String(message).includes("the email change email"));
1439
+ assert.equal(link.message, "Test: the email change email to bob.new@example.com was logged, not sent.");
1440
+ assert.match(link.details.confirmationUrl, /\/auth\/email-change\?token=/u);
1441
+
1442
+ // Without one, development and test log each link.
1443
+ logs.length = 0;
1444
+ const logged = await createStartedApp({ logger });
1445
+ t.after(() => fs.rm(logged.storeDir, { recursive: true, force: true }));
1446
+ await logged.authService.requestEmailChangeForUser({ userId: await account(logged, "usr_eve", "eve@example.com"), email: "eve.new@example.com" });
1447
+ await logged.runtime.shutdown();
1448
+ assert.deepEqual(logs.filter(({ message }) => String(message).startsWith("Local auth email change")).map(({ details, message }) => [message, details.email]),
1449
+ [["Local auth email change: confirmation.", "eve.new@example.com"]]);
1450
+
1451
+ // Staging and production without one offer no email change, and a sender needs the public URL its links name.
1452
+ for (const env of [STAGING, PRODUCTION]) {
1453
+ const without = await createStartedApp({ env: { ...env, ...deployed } });
1454
+ t.after(() => fs.rm(without.storeDir, { recursive: true, force: true }));
1455
+ assert.equal(without.authService.getCapabilities().features.emailChange, false, env.APP_ENV);
1456
+ for (const asked of [
1457
+ without.authService.requestEmailChange({ cookies: {} }, { email: "x@example.com", password: PASSWORD }),
1458
+ without.authService.requestEmailChangeForUser({ userId: "usr_any", email: "x@example.com" }),
1459
+ without.authService.confirmEmailChange({ token: "any" })
1460
+ ]) {
1461
+ await assert.rejects(asked, { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
1462
+ }
1463
+ await without.runtime.shutdown();
1464
+ }
1465
+ await assert.rejects(
1466
+ () => createStartedApp({ env: { APP_PUBLIC_URL: "" }, emailChangeSender: async () => {} }),
1467
+ /APP_PUBLIC_URL is required when local auth emails email change links/u
1468
+ );
1469
+ });
1470
+
1369
1471
  test("local recovery uses the application sender without returning or logging its token", async (t) => {
1370
1472
  const messages = [];
1371
1473
  const logs = [];
1372
1474
  const app = await createStartedApp({
1373
- env: { NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" },
1475
+ env: { APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" },
1374
1476
  recoverySender: async (message) => { messages.push(message); },
1375
1477
  logger: { info: (...args) => logs.push(args), warn() {}, error() {}, debug() {} }
1376
1478
  });
@@ -1398,19 +1500,11 @@ test("local recovery uses the application sender without returning or logging it
1398
1500
  assert.equal(messages.length, 1);
1399
1501
  });
1400
1502
 
1401
- test("a test copy logs the emails an installed sender would send, sends none and keeps the links out of the answers", async (t) => {
1503
+ test("staging sends an installed sender's emails only to STAGING_EMAIL_TO, naming whom each was for, and keeps the links out of the answers", async (t) => {
1402
1504
  const sent = [];
1403
1505
  const logs = [];
1404
1506
  const app = await createStartedApp({
1405
- env: {
1406
- SIDE_EFFECTS: undefined,
1407
- NODE_ENV: "production",
1408
- AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1409
- AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1410
- AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1411
- AUTH_LOCAL_EMAIL_CONFIRMATION: "",
1412
- APP_PUBLIC_URL: "https://app.example.test"
1413
- },
1507
+ env: { ...STAGING, AUTH_LOCAL_EMAIL_CONFIRMATION: "", APP_PUBLIC_URL: "https://app.example.test", STAGING_EMAIL_TO: "qa@example.test" },
1414
1508
  recoverySender: async (message) => { sent.push(message); },
1415
1509
  confirmationSender: async (message) => { sent.push(message); },
1416
1510
  logger: { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} }
@@ -1426,38 +1520,80 @@ test("a test copy logs the emails an installed sender would send, sends none and
1426
1520
  assert.equal(Object.hasOwn(registered, "confirmationUrl"), false);
1427
1521
  const reset = await app.authService.requestPasswordReset({ email: "owner@example.com" });
1428
1522
  assert.equal(reset.recoveryUrl, undefined);
1429
- // The reset's email is simulated after the answer.
1430
- const simulatedLogs = () => logs.filter(({ details }) => details?.sideEffects === "simulate" && details.kind === "email");
1431
- await eventually(() => simulatedLogs().length === 2);
1432
- assert.deepEqual(sent, [], "nothing sent");
1433
-
1434
- const simulated = simulatedLogs();
1435
- assert.deepEqual(simulated.map(({ details }) => details.email), ["tester@example.com", "owner@example.com"]);
1436
- assert.match(simulated[0].message, /^Test copy: the email confirmation email to tester@example\.com was simulated, not sent/u);
1437
- assert.match(simulated[0].details.confirmationUrl, /^https:\/\/app\.example\.test\/auth\/login\?confirmation_token=/u);
1438
- assert.match(simulated[1].message, /^Test copy: the password reset email to owner@example\.com was simulated/u);
1439
- // The logged links work: the tester confirms the registration and resets the password with them.
1440
- const confirmationToken = new URL(simulated[0].details.confirmationUrl).searchParams.get("confirmation_token");
1523
+ // The reset's email is sent after the answer.
1524
+ await eventually(() => sent.length === 2);
1525
+ assert.deepEqual(sent.map(({ email, originalEmail }) => [email, originalEmail]), [
1526
+ ["qa@example.test", "tester@example.com"],
1527
+ ["qa@example.test", "owner@example.com"]
1528
+ ], "every email goes to STAGING_EMAIL_TO, naming whom it was for");
1529
+ assert.deepEqual(logs.filter(({ details }) => details?.kind === "email").map(({ message }) => message), [
1530
+ "Staging: the email confirmation email to tester@example.com was sent to qa@example.test (STAGING_EMAIL_TO) instead.",
1531
+ "Staging: the password reset email to owner@example.com was sent to qa@example.test (STAGING_EMAIL_TO) instead."
1532
+ ]);
1533
+ // The links reach the tester's inbox: they confirm the registration and reset the password.
1534
+ const confirmationToken = new URL(sent[0].confirmationUrl).searchParams.get("confirmation_token");
1441
1535
  const confirmed = await app.authService.confirmRegistration({ token: confirmationToken, password: "correct horse battery staple" });
1442
1536
  assert.equal(confirmed.actor.email, "tester@example.com");
1443
1537
  const recovery = await app.authService.completePasswordRecovery({
1444
- code: new URL(simulated[1].details.recoveryUrl).searchParams.get("token"),
1538
+ code: new URL(sent[1].recoveryUrl).searchParams.get("token"),
1445
1539
  type: "recovery"
1446
1540
  });
1447
1541
  assert.equal(recovery.actor.email, "owner@example.com");
1448
1542
  });
1449
1543
 
1450
- test("a failing recovery sender is logged, never answered, and does not fall back to development output", async (t) => {
1544
+ test("staging without STAGING_EMAIL_TO, development and test log the emails an installed sender would send, and send none", async (t) => {
1545
+ for (const [name, env] of [
1546
+ ["staging", { ...STAGING, APP_PUBLIC_URL: "https://app.example.test" }],
1547
+ ["development", { APP_ENV: "development", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }],
1548
+ ["test", { AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }]
1549
+ ]) {
1550
+ await t.test(name, async () => {
1551
+ const sent = [];
1552
+ const logs = [];
1553
+ const app = await createStartedApp({
1554
+ env,
1555
+ recoverySender: async (message) => { sent.push(message); },
1556
+ logger: { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} }
1557
+ });
1558
+ await app.authService.register({
1559
+ email: "owner@example.com",
1560
+ password: "correct horse battery staple",
1561
+ ...(name === "staging" ? { setupCode: await firstAccountSetupCode(app.storeDir) } : {})
1562
+ });
1563
+ const reset = await app.authService.requestPasswordReset({ email: "owner@example.com" });
1564
+ assert.equal(reset.recoveryUrl, undefined);
1565
+ const logged = () => logs.filter(({ details }) => details?.kind === "email");
1566
+ await eventually(() => logged().length === 1);
1567
+ await app.runtime.shutdown();
1568
+ assert.deepEqual(sent, [], "nothing sent");
1569
+ const [{ details, message }] = logged();
1570
+ assert.equal(details.to, "owner@example.com");
1571
+ assert.equal(message, {
1572
+ staging: "Staging: the password reset email to owner@example.com was logged, not sent: STAGING_EMAIL_TO is not set.",
1573
+ development: "Development: the password reset email to owner@example.com was logged, not sent.",
1574
+ test: "Test: the password reset email to owner@example.com was logged, not sent."
1575
+ }[name]);
1576
+ // The logged link works: the tester follows it.
1577
+ assert.match(details.recoveryUrl, /\/auth\/reset-password\?/u);
1578
+ });
1579
+ }
1580
+ });
1581
+
1582
+ test("a failing recovery sender is logged, never answered", async (t) => {
1451
1583
  const logs = [];
1452
1584
  const errors = [];
1453
1585
  const failure = new Error("delivery unavailable");
1454
1586
  const app = await createStartedApp({
1455
- env: { AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "log" },
1587
+ env: PRODUCTION,
1456
1588
  recoverySender: async () => { throw failure; },
1457
1589
  logger: { info: (...args) => logs.push(args), warn() {}, error: (...args) => errors.push(args), debug() {} }
1458
1590
  });
1459
1591
  t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1460
- await app.authService.register({ email: "failure@example.com", password: "correct horse battery staple" });
1592
+ await app.authService.register({
1593
+ email: "failure@example.com",
1594
+ password: "correct horse battery staple",
1595
+ setupCode: await firstAccountSetupCode(app.storeDir)
1596
+ });
1461
1597
  // The requester gets the answer every email gets: a failure only an account's email can have says nothing.
1462
1598
  const answer = await app.authService.requestPasswordReset({ email: "failure@example.com" });
1463
1599
  assert.deepEqual(answer, await app.authService.requestPasswordReset({ email: "nobody@example.com" }));
@@ -1473,6 +1609,7 @@ test("stopping the server waits for a password reset email still being sent", as
1473
1609
  const sent = [];
1474
1610
  const { promise: sending, resolve: finishSending } = Promise.withResolvers();
1475
1611
  const app = await createStartedApp({
1612
+ env: PRODUCTION,
1476
1613
  recoverySender: async ({ email }) => {
1477
1614
  started.push(email);
1478
1615
  await sending;
@@ -1480,7 +1617,11 @@ test("stopping the server waits for a password reset email still being sent", as
1480
1617
  }
1481
1618
  });
1482
1619
  t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1483
- await app.authService.register({ email: "late@example.com", password: "correct horse battery staple" });
1620
+ await app.authService.register({
1621
+ email: "late@example.com",
1622
+ password: "correct horse battery staple",
1623
+ setupCode: await firstAccountSetupCode(app.storeDir)
1624
+ });
1484
1625
  await app.authService.requestPasswordReset({ email: "late@example.com" });
1485
1626
  await eventually(() => started.length === 1);
1486
1627
 
@@ -1497,7 +1638,7 @@ test("stopping the server waits for a password reset email still being sent", as
1497
1638
 
1498
1639
  test("in production, email confirmation needs an auth.local.confirmation-sender, or startup stops saying what to do", async () => {
1499
1640
  const production = {
1500
- NODE_ENV: "production",
1641
+ APP_ENV: "production", NODE_ENV: "production",
1501
1642
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1502
1643
  AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1503
1644
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
@@ -1506,8 +1647,9 @@ test("in production, email confirmation needs an auth.local.confirmation-sender,
1506
1647
  await assert.rejects(
1507
1648
  () => createStartedApp({ env: production }),
1508
1649
  (error) => String(error.details?.cause?.message || error.message || "") ===
1509
- "Local auth confirms each new account's email address in production, and no auth.local.confirmation-sender " +
1510
- "is installed to email the confirmation links. Install one, set AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
1650
+ "Local auth confirms each new account's email address in staging and production, and no " +
1651
+ "auth.local.confirmation-sender is installed to email the confirmation links. Install one, set " +
1652
+ "AUTH_LOCAL_EMAIL_CONFIRMATION=false " +
1511
1653
  "to let accounts register without confirming their email, or set AUTH_LOCAL_SELF_REGISTRATION=false " +
1512
1654
  "when accounts are only invited."
1513
1655
  );
@@ -1520,7 +1662,7 @@ test("in production, email confirmation needs an auth.local.confirmation-sender,
1520
1662
  test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confirmation sender and only invitations register", async (t) => {
1521
1663
  const app = await createStartedApp({
1522
1664
  env: {
1523
- NODE_ENV: "production",
1665
+ APP_ENV: "production", NODE_ENV: "production",
1524
1666
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1525
1667
  AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1526
1668
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
@@ -1586,7 +1728,7 @@ test("the confirmation sender emails the link, which is never returned or logged
1586
1728
  const hooked = [];
1587
1729
  const app = await createStartedApp({
1588
1730
  env: {
1589
- NODE_ENV: "production",
1731
+ APP_ENV: "production", NODE_ENV: "production",
1590
1732
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1591
1733
  AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1592
1734
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
@@ -1651,11 +1793,21 @@ test("the confirmation sender emails the link, which is never returned or logged
1651
1793
  });
1652
1794
 
1653
1795
  const CONFIRMATION_PASSWORD = "correct horse battery staple";
1654
- const SIDE_EFFECTS_SETTINGS = Object.freeze([
1655
- Object.freeze({ name: "live", SIDE_EFFECTS: "live" }),
1656
- Object.freeze({ name: "a test copy", SIDE_EFFECTS: undefined })
1796
+ // Where an installed confirmation sender's emails go, by environment: production sends each to its address, staging
1797
+ // only to STAGING_EMAIL_TO, test logs it. A staging or production app's first account registers with its setup code.
1798
+ const CONFIRMATION_ENVIRONMENTS = Object.freeze([
1799
+ Object.freeze({ name: "production", env: PRODUCTION, sendsTo: (email) => [email, ""] }),
1800
+ Object.freeze({ name: "staging", env: { ...STAGING, STAGING_EMAIL_TO: "qa@example.test" }, sendsTo: (email) => ["qa@example.test", email] }),
1801
+ Object.freeze({ name: "test", env: {}, sendsTo: null })
1657
1802
  ]);
1658
1803
 
1804
+ // The first account of a staging or production app, which registers with the setup code its server logged.
1805
+ async function registerFirstAccount(app, name) {
1806
+ if (name === "test") return [];
1807
+ await app.authService.register({ email: "owner@example.com", password: CONFIRMATION_PASSWORD, setupCode: await firstAccountSetupCode(app.storeDir) });
1808
+ return ["owner@example.com"];
1809
+ }
1810
+
1659
1811
  // A logger that keeps what local auth logs and warns.
1660
1812
  function recordingLogger() {
1661
1813
  const infos = [];
@@ -1672,24 +1824,24 @@ function recordingLogger() {
1672
1824
  };
1673
1825
  }
1674
1826
 
1675
- // The emails a test copy logged as simulated, by recipient.
1676
- function simulatedEmails(infos) {
1827
+ // The emails logged instead of sent, by recipient.
1828
+ function loggedEmails(infos) {
1677
1829
  return infos
1678
- .filter(({ details }) => details?.sideEffects === "simulate" && details.kind === "email")
1679
- .map(({ details }) => details.email);
1830
+ .filter(({ details, message }) => details?.kind === "email" && message.includes("was logged, not sent"))
1831
+ .map(({ details }) => details.to);
1680
1832
  }
1681
1833
 
1682
1834
  // An app that confirms registrations at once while its email isn't set up says so, for each registration, through
1683
- // auth.local.confirmation-mode. The mode sends nothing, so a test copy keeps it and answers as live does.
1684
- test("a registration the app's confirmation mode confirms without a link signs in at once, live and in a test copy", async (t) => {
1685
- for (const { name, SIDE_EFFECTS } of SIDE_EFFECTS_SETTINGS) {
1835
+ // auth.local.confirmation-mode. The mode sends nothing, so it applies in every environment.
1836
+ test("a registration the app's confirmation mode confirms without a link signs in at once, in every environment", async (t) => {
1837
+ for (const { name, env } of CONFIRMATION_ENVIRONMENTS) {
1686
1838
  await t.test(name, async () => {
1687
1839
  const sent = [];
1688
1840
  const asked = [];
1689
1841
  const hooked = [];
1690
1842
  const { infos, logger } = recordingLogger();
1691
1843
  const app = await createStartedApp({
1692
- env: { SIDE_EFFECTS, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1844
+ env: { ...env, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1693
1845
  confirmationSender: async (message) => { sent.push(message.email); },
1694
1846
  confirmationMode: async ({ email }) => {
1695
1847
  asked.push(email);
@@ -1703,30 +1855,32 @@ test("a registration the app's confirmation mode confirms without a link signs i
1703
1855
  }));
1704
1856
  }
1705
1857
  });
1858
+ const owners = await registerFirstAccount(app, name);
1706
1859
  const registered = await app.authService.register({ email: "Ada@example.com", password: CONFIRMATION_PASSWORD });
1707
1860
  assert.equal(registered.requiresEmailConfirmation, false);
1708
1861
  assert.equal(registered.actor.email, "ada@example.com");
1709
1862
  assert.ok(registered.session.access_token);
1710
1863
  assert.deepEqual(asked, ["ada@example.com"]);
1711
- assert.deepEqual(hooked, ["ada@example.com"]);
1864
+ assert.deepEqual(hooked, [...owners, "ada@example.com"]);
1712
1865
  assert.deepEqual(sent, [], "nothing sent");
1713
- assert.deepEqual(simulatedEmails(infos), [], "nothing simulated");
1866
+ assert.deepEqual(loggedEmails(infos), [], "nothing logged");
1714
1867
  const signedIn = await app.authService.login({ email: "ada@example.com", password: CONFIRMATION_PASSWORD });
1715
1868
  assert.equal(signedIn.actor.email, "ada@example.com");
1716
1869
  });
1717
1870
  }
1718
1871
  });
1719
1872
 
1720
- test("without a confirmation mode a registration waits for its link, which live sends and a test copy logs", async (t) => {
1721
- for (const { name, SIDE_EFFECTS } of SIDE_EFFECTS_SETTINGS) {
1873
+ test("without a confirmation mode a registration waits for its link, which production sends, staging sends to STAGING_EMAIL_TO and test logs", async (t) => {
1874
+ for (const { name, env, sendsTo } of CONFIRMATION_ENVIRONMENTS) {
1722
1875
  await t.test(name, async () => {
1723
1876
  const sent = [];
1724
1877
  const { infos, logger } = recordingLogger();
1725
1878
  const app = await createStartedApp({
1726
- env: { SIDE_EFFECTS, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1727
- confirmationSender: async (message) => { sent.push(message.email); },
1879
+ env: { ...env, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1880
+ confirmationSender: async (message) => { sent.push([message.email, message.originalEmail]); },
1728
1881
  logger
1729
1882
  });
1883
+ await registerFirstAccount(app, name);
1730
1884
  const registered = await app.authService.register({ email: "bea@example.com", password: CONFIRMATION_PASSWORD });
1731
1885
  assert.equal(registered.requiresEmailConfirmation, true);
1732
1886
  assert.equal(registered.session, null);
@@ -1735,31 +1889,32 @@ test("without a confirmation mode a registration waits for its link, which live
1735
1889
  app.authService.login({ email: "bea@example.com", password: CONFIRMATION_PASSWORD }),
1736
1890
  { status: 403, code: "auth.login.emailUnconfirmed" }
1737
1891
  );
1738
- const live = SIDE_EFFECTS === "live";
1739
- assert.deepEqual(sent, live ? ["bea@example.com"] : []);
1740
- assert.deepEqual(simulatedEmails(infos), live ? [] : ["bea@example.com"]);
1892
+ assert.deepEqual(sent, sendsTo ? [sendsTo("bea@example.com")] : []);
1893
+ assert.deepEqual(loggedEmails(infos), sendsTo ? [] : ["bea@example.com"]);
1741
1894
  });
1742
1895
  }
1743
1896
  });
1744
1897
 
1745
- test("a test copy never sends through the app's sender, whatever its confirmation mode answers", async () => {
1746
- const sent = [];
1747
- let emailSetUp = true;
1748
- const { infos, logger } = recordingLogger();
1749
- const app = await createStartedApp({
1750
- env: { SIDE_EFFECTS: undefined, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1751
- // A sender that sends real email: a test copy never calls it.
1752
- confirmationSender: async (message) => { sent.push(message.email); },
1753
- confirmationMode: async () => (emailSetUp ? "link" : "without-link"),
1754
- logger
1755
- });
1756
- const linked = await app.authService.register({ email: "cy@example.com", password: CONFIRMATION_PASSWORD });
1757
- assert.equal(linked.requiresEmailConfirmation, true);
1758
- emailSetUp = false;
1759
- const atOnce = await app.authService.register({ email: "dee@example.com", password: CONFIRMATION_PASSWORD });
1760
- assert.equal(atOnce.requiresEmailConfirmation, false);
1761
- assert.deepEqual(sent, [], "the app's sender never ran");
1762
- assert.deepEqual(simulatedEmails(infos), ["cy@example.com"]);
1898
+ test("development and test never send through the app's sender, whatever its confirmation mode answers", async () => {
1899
+ for (const APP_ENV of ["development", "test"]) {
1900
+ const sent = [];
1901
+ let emailSetUp = true;
1902
+ const { infos, logger } = recordingLogger();
1903
+ const app = await createStartedApp({
1904
+ env: { APP_ENV, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1905
+ // A sender that sends real email: development and test never call it.
1906
+ confirmationSender: async (message) => { sent.push(message.email); },
1907
+ confirmationMode: async () => (emailSetUp ? "link" : "without-link"),
1908
+ logger
1909
+ });
1910
+ const linked = await app.authService.register({ email: "cy@example.com", password: CONFIRMATION_PASSWORD });
1911
+ assert.equal(linked.requiresEmailConfirmation, true);
1912
+ emailSetUp = false;
1913
+ const atOnce = await app.authService.register({ email: "dee@example.com", password: CONFIRMATION_PASSWORD });
1914
+ assert.equal(atOnce.requiresEmailConfirmation, false);
1915
+ assert.deepEqual(sent, [], `${APP_ENV}: the app's sender never ran`);
1916
+ assert.deepEqual(loggedEmails(infos), ["cy@example.com"], APP_ENV);
1917
+ }
1763
1918
  });
1764
1919
 
1765
1920
  test("only the exact answer \"without-link\" confirms without a link, and a confirmation mode never stands in for a sender", async () => {
@@ -1787,7 +1942,7 @@ test("only the exact answer \"without-link\" confirms without a link, and a conf
1787
1942
  await assert.rejects(
1788
1943
  () => createStartedApp({
1789
1944
  env: {
1790
- NODE_ENV: "production",
1945
+ APP_ENV: "production", NODE_ENV: "production",
1791
1946
  AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1792
1947
  AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1793
1948
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
@@ -96,7 +96,7 @@ test("the file store keeps a factor and its session's proof across restarts, and
96
96
  });
97
97
 
98
98
  test("a production server has a second factor only with its key, at least 32 characters, and APP_PUBLIC_URL", async (t) => {
99
- const production = { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "", AUTH_LOCAL_SECOND_FACTOR_KEY: "" };
99
+ const production = { APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "", AUTH_LOCAL_SECOND_FACTOR_KEY: "" };
100
100
  const service = createLocalAuthService({
101
101
  ...localServiceOptions({ env: production }),
102
102
  backend: createLocalFileBackend({ storeDir: await storeDirFor(t) })
@@ -116,13 +116,13 @@ test("a production server has a second factor only with its key, at least 32 cha
116
116
  fileBackend: false,
117
117
  emailRecovery: false
118
118
  });
119
- assert.equal(resolve({ NODE_ENV: "production" }).secondFactorKey, "");
120
- assert.equal(resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY }).secondFactorKey, SECOND_FACTOR_KEY);
121
- assert.throws(() => resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: "too short" }), /at least 32 characters/u);
122
- assert.throws(() => resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY, APP_PUBLIC_URL: "" }),
119
+ assert.equal(resolve({ APP_ENV: "production", NODE_ENV: "production" }).secondFactorKey, "");
120
+ assert.equal(resolve({ APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY }).secondFactorKey, SECOND_FACTOR_KEY);
121
+ assert.throws(() => resolve({ APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: "too short" }), /at least 32 characters/u);
122
+ assert.throws(() => resolve({ APP_ENV: "production", NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY, APP_PUBLIC_URL: "" }),
123
123
  /APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set/u);
124
124
  // Outside production the session secret stands in for the key.
125
- assert.equal(resolve({ NODE_ENV: "development" }).secondFactorKey, "test-session-secret");
125
+ assert.equal(resolve({ APP_ENV: "development" }).secondFactorKey, "test-session-secret");
126
126
  assert.equal(createLocalAuthService({ ...localServiceOptions(), backend: createLocalFileBackend({ storeDir: await storeDirFor(t) }) })
127
127
  .getCapabilities().features.secondFactor, true);
128
128
  });
@@ -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
+ });