@jskit-ai/auth-provider-local-core 0.2.22 → 0.2.23

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 test copy (`SIDE_EFFECTS` is not `live`) sends no email: with an installed sender, confirmation and password-reset emails are logged as simulated (with their links) instead of sent. A logged (development) sender is unchanged. Tests that prove an installed sender set `SIDE_EFFECTS: "live"`.
5
6
  - With email confirmation on, two registrations whose email is already proven sign in at once instead of waiting for a link: one through an invitation a feature's invitation context resolver resolved, still pending, that names the registering email (letter case does not matter) and has not expired (`expiresAt`), whose link reached that address; and the app's first account, admitted by the production setup code only the server's operator can read (`firstAccountSetup.admitRegistration` answers true for it). An invitation passed through as given (no resolver installed), or one whose context names no email, another email or an expiry that has passed, proves nothing: that registration still waits, as does every other sign-up, and development's first account, which needs no code. Signing in with a waiting registration's password is refused as unconfirmed (403 `auth.login.emailUnconfirmed`) whatever `AUTH_LOCAL_EMAIL_CONFIRMATION` says now, where with it off such a sign-in was an ordinary failed one; registering again with it off creates the account.
6
7
  - Completing a password reset consumes the user's other password resets (`rec_…` tokens) only, leaving an app's own kinds of recovery token, such as sign-in links, open: the backend contract's `recovery.consumeForUser(userId, { idPrefix })` takes the kind it consumes, and the file backend requires it as the database backend does.
7
8
  - Security: confirming a registration takes the password it was registered with as well as its link's code, `confirmRegistration({ token, password })`. A missing or wrong password creates nothing, keeps the registration and its link, and is refused with 400 `auth.local.register.confirmationPasswordInvalid` (on the `password` field; new message key `jskit.auth.local.register.confirmationPasswordInvalid`). Registering an email again replaces its waiting registration whole, password, display name and invitation included, and a new link from `resendRegisterConfirmation` keeps the registration's password and is no longer sent for an expired registration. So whoever registers an email, before its owner or after, the account its link creates has the password of the person who confirmed it: before, a registration that waited kept its password when the email's owner registered later, so whoever registered first could sign in to the account the owner then confirmed, and the owner's link created no account they could tell apart.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.22",
3
+ "version": "0.2.23",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -67,7 +67,7 @@
67
67
  }
68
68
  },
69
69
  "peerDependencies": {
70
- "@jskit-ai/auth-core": "0.2.19",
71
- "@jskit-ai/kernel": "0.2.19"
70
+ "@jskit-ai/auth-core": "0.2.20",
71
+ "@jskit-ai/kernel": "0.2.20"
72
72
  }
73
73
  }
@@ -1,4 +1,5 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
2
3
  import { resolveRegistrationProfileOptions, validateEmailInput } from "./accounts.js";
3
4
  import { buildAuthPayload } from "./authPayloads.js";
4
5
  import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url } from "./tokens.js";
@@ -17,6 +18,23 @@ function createLoggedConfirmationSender(logger) {
17
18
  };
18
19
  }
19
20
 
21
+ /**
22
+ * The confirmation sender of a test copy (SIDE_EFFECTS is not `live`) in place of the installed
23
+ * `auth.local.confirmation-sender`: it emails nothing and logs the link, which the person testing follows to
24
+ * confirm. The link stays out of the registration's answer, as with a real sender.
25
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
26
+ * @returns {import("../types.js").AuthLocalConfirmationSender}
27
+ */
28
+ function createSimulatedConfirmationSender(logger) {
29
+ return async function simulateConfirmationEmail({ email, confirmationUrl }) {
30
+ logSimulatedSideEffect(logger, {
31
+ kind: "email",
32
+ summary: `the email confirmation email to ${email}`,
33
+ details: { email, confirmationUrl }
34
+ });
35
+ };
36
+ }
37
+
20
38
  function emailTakenError() {
21
39
  return new AppError(409, "An account already exists for this email.", { code: "auth.local.register.emailTaken" });
22
40
  }
@@ -210,4 +228,9 @@ function createLocalEmailConfirmation({
210
228
  });
211
229
  }
212
230
 
213
- export { CONFIRMATION_TOKEN_TTL_SECONDS, createLocalEmailConfirmation, createLoggedConfirmationSender };
231
+ export {
232
+ CONFIRMATION_TOKEN_TTL_SECONDS,
233
+ createLocalEmailConfirmation,
234
+ createLoggedConfirmationSender,
235
+ createSimulatedConfirmationSender
236
+ };
@@ -1,4 +1,5 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
2
3
  import { AUTH_TEXTS, authMessageFields, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
3
4
  import { validateEmailInput, validatePasswordInput } from "./accounts.js";
4
5
  import { buildAuthPayload } from "./authPayloads.js";
@@ -22,6 +23,23 @@ function createLoggedRecoverySender(logger) {
22
23
  };
23
24
  }
24
25
 
26
+ /**
27
+ * The recovery sender of a test copy (SIDE_EFFECTS is not `live`) in place of the installed
28
+ * `auth.local.recovery-sender`: it emails nothing and logs the link, which the person testing follows to reset the
29
+ * password.
30
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
31
+ * @returns {import("../types.js").AuthLocalRecoverySender}
32
+ */
33
+ function createSimulatedRecoverySender(logger) {
34
+ return async function simulateRecoveryEmail({ email, recoveryUrl }) {
35
+ logSimulatedSideEffect(logger, {
36
+ kind: "email",
37
+ summary: `the password reset email to ${email}`,
38
+ details: { email, recoveryUrl }
39
+ });
40
+ };
41
+ }
42
+
25
43
  /**
26
44
  * Changing a password, and recovering one: a recovery link opens a short
27
45
  * recovery session, which can only set a new password.
@@ -167,4 +185,4 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
167
185
  });
168
186
  }
169
187
 
170
- export { createLocalPasswordFlows, createLoggedRecoverySender };
188
+ export { createLocalPasswordFlows, createLoggedRecoverySender, createSimulatedRecoverySender };
@@ -4,11 +4,12 @@ import {
4
4
  } from "@jskit-ai/auth-core/server/deferredAuthService";
5
5
  import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
6
6
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
+ import { sideEffectsAreLive } from "@jskit-ai/kernel/shared/support/sideEffects";
7
8
  import { resolveLocalAuthConfig } from "../lib/config.js";
8
- import { createLoggedConfirmationSender } from "../lib/emailConfirmation.js";
9
+ import { createLoggedConfirmationSender, createSimulatedConfirmationSender } from "../lib/emailConfirmation.js";
9
10
  import { createLocalFileBackend } from "../lib/fileBackend.js";
10
11
  import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
11
- import { createLoggedRecoverySender } from "../lib/passwordFlows.js";
12
+ import { createLoggedRecoverySender, createSimulatedRecoverySender } from "../lib/passwordFlows.js";
12
13
  import { scryptPasswordStrategy } from "../lib/passwords.js";
13
14
  import { createLocalAuthService } from "../lib/service.js";
14
15
 
@@ -58,16 +59,22 @@ const AuthLocalProvider = defineProvider({
58
59
  // A production server without accounts logs its setup code as it starts.
59
60
  const firstAccountSetup = createFirstAccountSetup({ backend: localBackend, config, logger });
60
61
  await firstAccountSetup.start();
62
+ // A test copy (SIDE_EFFECTS is not live) logs the emails an installed sender would send, and sends none.
63
+ const live = sideEffectsAreLive(env);
61
64
  const baseService = createLocalAuthService({
62
65
  backend: localBackend,
63
66
  config,
64
- confirmationSender: emailConfirmationSender ? confirmationSender : createLoggedConfirmationSender(logger),
67
+ confirmationSender: emailConfirmationSender
68
+ ? (live ? confirmationSender : createSimulatedConfirmationSender(logger))
69
+ : createLoggedConfirmationSender(logger),
65
70
  firstAccountSetup,
66
71
  invitationContextResolver: extensions.resolveInvitationContextResolver(),
67
72
  logger,
68
73
  passwordStrategy: passwordStrategy ?? scryptPasswordStrategy,
69
74
  profileProjector: profileProjector ?? noAppProfiles,
70
- recoverySender: emailRecovery ? recoverySender : createLoggedRecoverySender(logger)
75
+ recoverySender: emailRecovery
76
+ ? (live ? recoverySender : createSimulatedRecoverySender(logger))
77
+ : createLoggedRecoverySender(logger)
71
78
  });
72
79
  // readable-check: allow setter-seam - deferred until boot: auth.service is built after every setup has registered its auth extensions, and those setups already receive it
73
80
  attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
@@ -139,6 +139,8 @@ async function createStartedApp({
139
139
  // Registration signs in at once here; the email confirmation tests turn confirmation on.
140
140
  AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
141
141
  NODE_ENV: "test",
142
+ // An installed sender sends for real here; the test copy tests leave SIDE_EFFECTS unset.
143
+ SIDE_EFFECTS: "live",
142
144
  ...env
143
145
  },
144
146
  "runtime.logger": runtimeLogger,
@@ -1383,6 +1385,52 @@ test("local recovery uses the application sender without returning or logging it
1383
1385
  assert.equal(recovery.actor.email, "sender@example.com");
1384
1386
  });
1385
1387
 
1388
+ test("a test copy logs the emails an installed sender would send, sends none and keeps the links out of the answers", async (t) => {
1389
+ const sent = [];
1390
+ const logs = [];
1391
+ const app = await createStartedApp({
1392
+ env: {
1393
+ SIDE_EFFECTS: undefined,
1394
+ NODE_ENV: "production",
1395
+ AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1396
+ AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1397
+ AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1398
+ AUTH_LOCAL_EMAIL_CONFIRMATION: "",
1399
+ APP_PUBLIC_URL: "https://app.example.test"
1400
+ },
1401
+ recoverySender: async (message) => { sent.push(message); },
1402
+ confirmationSender: async (message) => { sent.push(message); },
1403
+ logger: { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} }
1404
+ });
1405
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1406
+ await app.authService.register({
1407
+ email: "owner@example.com",
1408
+ password: "correct horse battery staple",
1409
+ setupCode: await firstAccountSetupCode(app.storeDir)
1410
+ });
1411
+ const registered = await app.authService.register({ email: "tester@example.com", password: "correct horse battery staple" });
1412
+ assert.equal(registered.requiresEmailConfirmation, true);
1413
+ assert.equal(Object.hasOwn(registered, "confirmationUrl"), false);
1414
+ const reset = await app.authService.requestPasswordReset({ email: "owner@example.com" });
1415
+ assert.equal(reset.recoveryUrl, undefined);
1416
+ assert.deepEqual(sent, [], "nothing sent");
1417
+
1418
+ const simulated = logs.filter(({ details }) => details?.sideEffects === "simulate" && details.kind === "email");
1419
+ assert.deepEqual(simulated.map(({ details }) => details.email), ["tester@example.com", "owner@example.com"]);
1420
+ assert.match(simulated[0].message, /^Test copy: the email confirmation email to tester@example\.com was simulated, not sent/u);
1421
+ assert.match(simulated[0].details.confirmationUrl, /^https:\/\/app\.example\.test\/auth\/login\?confirmation_token=/u);
1422
+ assert.match(simulated[1].message, /^Test copy: the password reset email to owner@example\.com was simulated/u);
1423
+ // The logged links work: the tester confirms the registration and resets the password with them.
1424
+ const confirmationToken = new URL(simulated[0].details.confirmationUrl).searchParams.get("confirmation_token");
1425
+ const confirmed = await app.authService.confirmRegistration({ token: confirmationToken, password: "correct horse battery staple" });
1426
+ assert.equal(confirmed.actor.email, "tester@example.com");
1427
+ const recovery = await app.authService.completePasswordRecovery({
1428
+ code: new URL(simulated[1].details.recoveryUrl).searchParams.get("token"),
1429
+ type: "recovery"
1430
+ });
1431
+ assert.equal(recovery.actor.email, "owner@example.com");
1432
+ });
1433
+
1386
1434
  test("a failing recovery sender does not fall back to development output", async (t) => {
1387
1435
  const logs = [];
1388
1436
  const failure = new Error("delivery unavailable");