@jskit-ai/auth-provider-local-core 0.2.24 → 0.2.26

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.
@@ -4,20 +4,35 @@ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
4
4
  import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
5
5
  import { createLocalAccounts } from "./accounts.js";
6
6
  import { PROVIDER_ID } from "./authPayloads.js";
7
- import { createLocalEmailConfirmation } from "./emailConfirmation.js";
7
+ import { confirmEveryRegistrationByLink, createLocalEmailConfirmation } from "./emailConfirmation.js";
8
8
  import { createFirstAccountSetup } from "./firstAccountSetup.js";
9
9
  import { createLocalOAuthFlows } from "./oauthFlows.js";
10
10
  import { createLocalPasswordFlows } from "./passwordFlows.js";
11
11
  import { normalizePasswordStrategy } from "./passwords.js";
12
+ import { createLocalSecondFactor } from "./secondFactor.js";
12
13
  import { createLocalSecurityStatus } from "./securityStatus.js";
13
14
  import { createLocalSessions } from "./sessions.js";
14
15
 
16
+ // A production server without AUTH_LOCAL_SECOND_FACTOR_KEY has no second factor: each operation is unsupported.
17
+ const NO_SECOND_FACTOR = Object.freeze({
18
+ getSecondFactorStatus: () => throwUnsupportedAuthOperation("getSecondFactorStatus"),
19
+ startSecondFactorSetup: () => throwUnsupportedAuthOperation("startSecondFactorSetup"),
20
+ confirmSecondFactorSetup: () => throwUnsupportedAuthOperation("confirmSecondFactorSetup"),
21
+ verifySecondFactor: () => throwUnsupportedAuthOperation("verifySecondFactor"),
22
+ replaceSecondFactorRecoveryCodes: () => throwUnsupportedAuthOperation("replaceSecondFactorRecoveryCodes"),
23
+ removeSecondFactor: () => throwUnsupportedAuthOperation("removeSecondFactor"),
24
+ listSecondFactors: () => throwUnsupportedAuthOperation("listSecondFactors"),
25
+ resetSecondFactor: () => throwUnsupportedAuthOperation("resetSecondFactor")
26
+ });
27
+
15
28
  /**
16
29
  * The `auth.service` of local auth, from the collaborators its provider
17
30
  * resolved once.
18
31
  * @param {object} dependencies
19
32
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
20
33
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
34
+ * @param {import("../types.js").AuthLocalConfirmationMode} [dependencies.confirmationMode] The
35
+ * `auth.local.confirmation-mode`; by default every registration waits for its link.
21
36
  * @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
22
37
  * `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender.
23
38
  * @param {import("../types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup] The first
@@ -30,17 +45,21 @@ import { createLocalSessions } from "./sessions.js";
30
45
  * `auth.profile.projector`, or noAppProfiles.
31
46
  * @param {import("../types.js").AuthLocalRecoverySender} dependencies.recoverySender The
32
47
  * `auth.local.recovery-sender`, or one made by createLoggedRecoverySender.
48
+ * @param {import("../types.js").AuthLocalSecondFactorEvents} dependencies.secondFactorEvents The
49
+ * `auth.local.second-factor-events`, or one made by createLoggedSecondFactorEvents.
33
50
  */
34
51
  function createLocalAuthService({
35
52
  backend,
36
53
  config,
54
+ confirmationMode = confirmEveryRegistrationByLink,
37
55
  confirmationSender,
38
56
  firstAccountSetup: givenFirstAccountSetup = null,
39
57
  invitationContextResolver,
40
58
  logger,
41
59
  passwordStrategy,
42
60
  profileProjector,
43
- recoverySender
61
+ recoverySender,
62
+ secondFactorEvents
44
63
  }) {
45
64
  const passwords = normalizePasswordStrategy(passwordStrategy);
46
65
  const firstAccountSetup = givenFirstAccountSetup ?? createFirstAccountSetup({ backend, config, logger });
@@ -83,7 +102,8 @@ function createLocalAuthService({
83
102
  securityStatus: true,
84
103
  signOutOtherSessions: true,
85
104
  appProfileProjection,
86
- devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
105
+ devLoginAs: isDevAuthBootstrapEnabled(config.devAuth),
106
+ secondFactor: Boolean(config.secondFactorKey)
87
107
  }
88
108
  });
89
109
  // While the app has no account, its first one may register, and on a production server that asks for the setup code.
@@ -100,9 +120,11 @@ function createLocalAuthService({
100
120
  const emailConfirmation = createLocalEmailConfirmation({
101
121
  backend,
102
122
  config,
123
+ confirmationMode,
103
124
  confirmationSender,
104
125
  firstAccountSetup,
105
126
  invitationContextResolver,
127
+ logger,
106
128
  passwords,
107
129
  profileProjector,
108
130
  sessions
@@ -138,6 +160,10 @@ function createLocalAuthService({
138
160
  sessions
139
161
  });
140
162
 
163
+ const secondFactor = config.secondFactorKey
164
+ ? createLocalSecondFactor({ backend, config, logger, secondFactorEvents, sessions })
165
+ : NO_SECOND_FACTOR;
166
+
141
167
  function getCapabilities() {
142
168
  if (firstAccountSetup.isWaiting()) {
143
169
  return capabilitiesWaitingForFirstAccount;
@@ -201,7 +227,15 @@ function createLocalAuthService({
201
227
  startProviderLink: oauthFlows.startProviderLink,
202
228
  unlinkProvider: oauthFlows.unlinkProvider,
203
229
  signOutOtherSessions: sessions.signOutOtherSessions,
204
- logout: sessions.logout
230
+ logout: sessions.logout,
231
+ getSecondFactorStatus: secondFactor.getSecondFactorStatus,
232
+ startSecondFactorSetup: secondFactor.startSecondFactorSetup,
233
+ confirmSecondFactorSetup: secondFactor.confirmSecondFactorSetup,
234
+ verifySecondFactor: secondFactor.verifySecondFactor,
235
+ replaceSecondFactorRecoveryCodes: secondFactor.replaceSecondFactorRecoveryCodes,
236
+ removeSecondFactor: secondFactor.removeSecondFactor,
237
+ listSecondFactors: secondFactor.listSecondFactors,
238
+ resetSecondFactor: secondFactor.resetSecondFactor
205
239
  });
206
240
  }
207
241
 
@@ -75,7 +75,9 @@ function buildSessionPayload({ user, session, refreshToken, secret }) {
75
75
 
76
76
  /**
77
77
  * The sessions of local auth: creating one, authenticating a request from its
78
- * cookies, writing and clearing those cookies, and revoking sessions.
78
+ * cookies, writing and clearing those cookies, and revoking sessions. An
79
+ * authenticated request's answer names its session (`sessionId`) and when the
80
+ * session last proved its second factor (`secondFactorAt`, "" when it has not).
79
81
  * @param {object} dependencies
80
82
  * @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
81
83
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
@@ -201,6 +203,8 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
201
203
  authenticated: true,
202
204
  ...authPayload,
203
205
  session: null,
206
+ sessionId: resolved.session.id,
207
+ secondFactorAt: resolved.session.secondFactorAt || "",
204
208
  sessionPurpose: resolved.session.purpose || "normal",
205
209
  clearSession: false,
206
210
  transientFailure: false
@@ -244,6 +248,8 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
244
248
  refreshToken,
245
249
  secret: config.sessionSecret
246
250
  }),
251
+ sessionId: resolved.session.id,
252
+ secondFactorAt: resolved.session.secondFactorAt || "",
247
253
  sessionPurpose: resolved.session.purpose || "normal",
248
254
  clearSession: false,
249
255
  transientFailure: false
@@ -72,52 +72,75 @@ function signInWaitMs(record, now) {
72
72
  }
73
73
 
74
74
  /**
75
- * The account's record after one more failed sign-in.
75
+ * A record's failures after one more: how many in a row (those older than a day
76
+ * are forgotten), the last one, and until when the next attempt must wait. The
77
+ * sign-in throttle counts an account email's failed sign-ins this way, and the
78
+ * second factor an account's wrong codes.
76
79
  * @param {ReturnType<typeof resolveSignInThrottle>} throttle
77
80
  * @param {{ failures: number, lastFailedAt: string } | null} record
78
- * @param {string} email
79
81
  * @param {number} now
80
82
  */
81
- function recordSignInFailure(throttle, record, email, now) {
83
+ function nextFailures(throttle, record, now) {
82
84
  const lastFailedAt = Date.parse(record?.lastFailedAt || "");
83
85
  const recent = Number.isFinite(lastFailedAt) && now - lastFailedAt < FORGET_FAILURES_AFTER_MS;
84
86
  const failures = (recent ? record.failures : 0) + 1;
85
87
  const waits = failures - throttle.failuresBeforeWait + 1;
86
88
  const waitMs = waits > 0 ? Math.min(throttle.maxWaitMs, throttle.firstWaitMs * 2 ** (waits - 1)) : 0;
87
89
  return {
88
- email,
89
90
  failures,
90
91
  lastFailedAt: new Date(now).toISOString(),
91
92
  lockedUntil: waitMs > 0 ? new Date(now + waitMs).toISOString() : ""
92
93
  };
93
94
  }
94
95
 
96
+ /**
97
+ * The account's record after one more failed sign-in.
98
+ * @param {ReturnType<typeof resolveSignInThrottle>} throttle
99
+ * @param {{ failures: number, lastFailedAt: string } | null} record
100
+ * @param {string} email
101
+ * @param {number} now
102
+ */
103
+ function recordSignInFailure(throttle, record, email, now) {
104
+ return { email, ...nextFailures(throttle, record, now) };
105
+ }
106
+
95
107
  /** Failure records whose last failure is old enough to forget. */
96
108
  function forgottenFailuresBefore(now) {
97
109
  return new Date(now - FORGET_FAILURES_AFTER_MS).toISOString();
98
110
  }
99
111
 
112
+ /**
113
+ * A wait's refusal params: the minutes to wait, rounded up, and the exact
114
+ * seconds, which Retry-After also gives.
115
+ * @param {number} waitMs
116
+ */
117
+ function waitParams(waitMs) {
118
+ const retryAfterSeconds = Math.max(1, Math.ceil(waitMs / 1000));
119
+ return { count: Math.ceil(retryAfterSeconds / 60), retryAfterSeconds };
120
+ }
121
+
100
122
  /**
101
123
  * The refusal of a sign-in while its account waits, with the minutes to wait;
102
124
  * Retry-After gives the exact seconds.
103
125
  * @param {number} waitMs
104
126
  */
105
127
  function signInLockedError(waitMs) {
106
- const seconds = Math.max(1, Math.ceil(waitMs / 1000));
107
- const count = Math.ceil(seconds / 60);
108
- const unit = count === 1 ? "minute" : "minutes";
109
- return new AppError(429, `Too many failed sign-ins for this account. Try again in ${count} ${unit}.`, {
128
+ const params = waitParams(waitMs);
129
+ const unit = params.count === 1 ? "minute" : "minutes";
130
+ return new AppError(429, `Too many failed sign-ins for this account. Try again in ${params.count} ${unit}.`, {
110
131
  code: "auth.local.login.locked",
111
- params: { count, retryAfterSeconds: seconds },
112
- headers: { "retry-after": String(seconds) }
132
+ params,
133
+ headers: { "retry-after": String(params.retryAfterSeconds) }
113
134
  });
114
135
  }
115
136
 
116
137
  export {
117
138
  DEFAULT_SIGN_IN_THROTTLE,
118
139
  forgottenFailuresBefore,
140
+ nextFailures,
119
141
  recordSignInFailure,
120
142
  resolveSignInThrottle,
121
143
  signInLockedError,
122
- signInWaitMs
144
+ signInWaitMs,
145
+ waitParams
123
146
  };
@@ -6,11 +6,16 @@ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
6
6
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
7
  import { sideEffectsAreLive } from "@jskit-ai/kernel/shared/support/sideEffects";
8
8
  import { resolveLocalAuthConfig } from "../lib/config.js";
9
- import { createLoggedConfirmationSender, createSimulatedConfirmationSender } from "../lib/emailConfirmation.js";
9
+ import {
10
+ confirmEveryRegistrationByLink,
11
+ createLoggedConfirmationSender,
12
+ createSimulatedConfirmationSender
13
+ } from "../lib/emailConfirmation.js";
10
14
  import { createLocalFileBackend } from "../lib/fileBackend.js";
11
15
  import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
12
16
  import { createLoggedRecoverySender, createSimulatedRecoverySender } from "../lib/passwordFlows.js";
13
17
  import { scryptPasswordStrategy } from "../lib/passwords.js";
18
+ import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
14
19
  import { createLocalAuthService } from "../lib/service.js";
15
20
 
16
21
  const AuthLocalProvider = defineProvider({
@@ -23,10 +28,12 @@ const AuthLocalProvider = defineProvider({
23
28
  },
24
29
  optional: {
25
30
  backend: "auth.local.backend",
31
+ confirmationMode: "auth.local.confirmation-mode",
26
32
  confirmationSender: "auth.local.confirmation-sender",
27
33
  passwordStrategy: "auth.local.password-strategy",
28
34
  profileProjector: "auth.profile.projector",
29
- recoverySender: "auth.local.recovery-sender"
35
+ recoverySender: "auth.local.recovery-sender",
36
+ secondFactorEvents: "auth.local.second-factor-events"
30
37
  },
31
38
  provides: {
32
39
  authService: "auth.service"
@@ -38,6 +45,8 @@ const AuthLocalProvider = defineProvider({
38
45
  * @param {object} dependencies
39
46
  * @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
40
47
  * @param {import("../types.js").AuthLocalBackend | null} dependencies.backend The `auth.local.backend`, when one is installed.
48
+ * @param {import("../types.js").AuthLocalConfirmationMode | null} dependencies.confirmationMode The
49
+ * `auth.local.confirmation-mode`, when one is installed.
41
50
  * @param {import("../types.js").AuthLocalConfirmationSender | null} dependencies.confirmationSender The
42
51
  * `auth.local.confirmation-sender`, when one is installed.
43
52
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
@@ -46,9 +55,23 @@ const AuthLocalProvider = defineProvider({
46
55
  * @param {import("../types.js").AuthLocalPasswordStrategy | null} dependencies.passwordStrategy The `auth.local.password-strategy`, when one is installed.
47
56
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
48
57
  * @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
58
+ * @param {import("../types.js").AuthLocalSecondFactorEvents | null} dependencies.secondFactorEvents The
59
+ * `auth.local.second-factor-events`, when one is installed.
49
60
  */
50
61
  async boot(
51
- { appRoot, backend, confirmationSender, env, extensions, logger, passwordStrategy, profileProjector, recoverySender },
62
+ {
63
+ appRoot,
64
+ backend,
65
+ confirmationMode,
66
+ confirmationSender,
67
+ env,
68
+ extensions,
69
+ logger,
70
+ passwordStrategy,
71
+ profileProjector,
72
+ recoverySender,
73
+ secondFactorEvents
74
+ },
52
75
  { outputs }
53
76
  ) {
54
77
  const fileBackend = backend === null;
@@ -59,11 +82,13 @@ const AuthLocalProvider = defineProvider({
59
82
  // A production server without accounts logs its setup code as it starts.
60
83
  const firstAccountSetup = createFirstAccountSetup({ backend: localBackend, config, logger });
61
84
  await firstAccountSetup.start();
62
- // A test copy (SIDE_EFFECTS is not live) logs the emails an installed sender would send, and sends none.
85
+ // A test copy (SIDE_EFFECTS is not live) logs the emails an installed sender would send, and sends none, whatever
86
+ // the sender. The confirmation mode sends nothing, so a test copy keeps it.
63
87
  const live = sideEffectsAreLive(env);
64
88
  const baseService = createLocalAuthService({
65
89
  backend: localBackend,
66
90
  config,
91
+ confirmationMode: confirmationMode ?? confirmEveryRegistrationByLink,
67
92
  confirmationSender: emailConfirmationSender
68
93
  ? (live ? confirmationSender : createSimulatedConfirmationSender(logger))
69
94
  : createLoggedConfirmationSender(logger),
@@ -74,7 +99,8 @@ const AuthLocalProvider = defineProvider({
74
99
  profileProjector: profileProjector ?? noAppProfiles,
75
100
  recoverySender: emailRecovery
76
101
  ? (live ? recoverySender : createSimulatedRecoverySender(logger))
77
- : createLoggedRecoverySender(logger)
102
+ : createLoggedRecoverySender(logger),
103
+ secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger)
78
104
  });
79
105
  // 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
80
106
  attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
@@ -21,8 +21,11 @@
21
21
  * findById(sessionId: string): Promise<object | null>,
22
22
  * findByTokenHash(tokenHash: string): Promise<object | null>,
23
23
  * revoke(sessionId: string): Promise<object | null>,
24
- * revokeForUser(userId: string, options?: object): Promise<number>
25
- * }} sessions
24
+ * revokeForUser(userId: string, options?: object): Promise<number>,
25
+ * markSecondFactorProved(sessionId: string, secondFactorAt: string): Promise<object | null>,
26
+ * clearSecondFactorForUser(userId: string): Promise<number>
27
+ * }} sessions A session's `secondFactorAt` is when it last proved its second factor ("" when it has not):
28
+ * `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user.
26
29
  * @property {{
27
30
  * create(input: object): Promise<object>,
28
31
  * findByTokenHash(tokenHash: string): Promise<object | null>,
@@ -49,6 +52,14 @@
49
52
  * transaction ends, so concurrent failures count one after another, `save` replaces the email's record and
50
53
  * `deleteBefore` removes those whose last failure is older.
51
54
  * @property {{
55
+ * find(userId: string): Promise<AuthLocalSecondFactor | null>,
56
+ * findMany(userIds: string[]): Promise<AuthLocalSecondFactor[]>,
57
+ * save(record: AuthLocalSecondFactor): Promise<AuthLocalSecondFactor>,
58
+ * delete(userId: string): Promise<number>
59
+ * }} secondFactors One second factor per account; `find` holds the account's record until the transaction ends, so
60
+ * concurrent codes are checked one after another, `findMany` reads without holding, and `save` replaces the
61
+ * account's record.
62
+ * @property {{
52
63
  * save(record: AuthLocalRegistration): Promise<AuthLocalRegistration>,
53
64
  * findByEmail(email: string): Promise<AuthLocalRegistration | null>,
54
65
  * findByTokenHash(tokenHash: string): Promise<AuthLocalRegistration | null>,
@@ -73,6 +84,53 @@
73
84
  * @property {string} expiresAt
74
85
  */
75
86
 
87
+ /**
88
+ * An account's second factor: its authenticator secret sealed with the
89
+ * application's key, when the first code confirmed it ("" while it is being
90
+ * set up), the 30-second step of the last code accepted (no code of that step
91
+ * or an earlier one is accepted again), the keyed hashes of its unused recovery
92
+ * codes, and its wrong codes as failed sign-ins count them. Times are ISO
93
+ * strings.
94
+ * @typedef {object} AuthLocalSecondFactor
95
+ * @property {string} userId
96
+ * @property {string} secretSealed
97
+ * @property {string} confirmedAt
98
+ * @property {number} lastUsedStep
99
+ * @property {string[]} recoveryCodes
100
+ * @property {number} failures
101
+ * @property {string} lastFailedAt
102
+ * @property {string} lockedUntil
103
+ * @property {string} createdAt
104
+ * @property {string} updatedAt
105
+ */
106
+
107
+ /**
108
+ * One second factor event: an authenticator setup started or confirmed, a
109
+ * session's second factor verified (by a `code` or a `recoveryCode`, with the
110
+ * recovery codes left), a failed attempt (`reason`: codeInvalid, codeUsed,
111
+ * recoveryCodeInvalid or locked), the recovery codes replaced, the
112
+ * authenticator removed by its person, or reset by the application for the
113
+ * account `byUserId` names. `userId` is the local account's id, `ip` the
114
+ * request's address ("" for a reset), `at` an ISO time.
115
+ * @typedef {object} AuthLocalSecondFactorEvent
116
+ * @property {"setupStarted" | "setupConfirmed" | "verified" | "failed" | "recoveryCodesReplaced" | "removed" | "reset"} type
117
+ * @property {string} userId
118
+ * @property {string} ip
119
+ * @property {string} at
120
+ * @property {"code" | "recoveryCode"} [method]
121
+ * @property {number} [recoveryCodesLeft]
122
+ * @property {"codeInvalid" | "codeUsed" | "recoveryCodeInvalid" | "locked"} [reason]
123
+ * @property {string} [byUserId]
124
+ */
125
+
126
+ /**
127
+ * The `auth.local.second-factor-events` capability: records each second
128
+ * factor event, for an application's audit log. It runs after the change is
129
+ * stored; when it fails, local auth logs the failure and the operation still
130
+ * answers. Without one, local auth logs each event.
131
+ * @typedef {(event: AuthLocalSecondFactorEvent) => Promise<void>} AuthLocalSecondFactorEvents
132
+ */
133
+
76
134
  /**
77
135
  * An account's recent failed sign-ins: how many, the last one, and when it may
78
136
  * try again ("" when it need not wait). Times are ISO strings.
@@ -82,7 +140,7 @@
82
140
  /**
83
141
  * The `auth.local.backend` capability: where local auth keeps its users,
84
142
  * sessions, recovery tokens, linked identities, OAuth attempts, failed
85
- * sign-ins and unconfirmed registrations. Without
143
+ * sign-ins, unconfirmed registrations and second factors. Without
86
144
  * one, local auth keeps them in files under AUTH_LOCAL_STORE_DIR;
87
145
  * `@jskit-ai/auth-provider-local-db-core` provides one that keeps them in the
88
146
  * database. Each backend implements this contract.
@@ -113,6 +171,17 @@
113
171
  * @typedef {(delivery: { email: string, confirmationUrl: string }) => Promise<void>} AuthLocalConfirmationSender
114
172
  */
115
173
 
174
+ /**
175
+ * The `auth.local.confirmation-mode` capability: the application's choice, for
176
+ * one registration that would wait for its email to be confirmed, of how it is
177
+ * confirmed. "link" sends the confirmation link, as without one; "without-link"
178
+ * creates the account and signs the person in at once, with an address nobody
179
+ * proved, for example while the application's email isn't set up. Any other
180
+ * answer means "link". It sends nothing, so a test copy keeps it, where it
181
+ * replaces the confirmation sender.
182
+ * @typedef {(registration: { email: string }) => Promise<"link" | "without-link">} AuthLocalConfirmationMode
183
+ */
184
+
116
185
  /** @typedef {ReturnType<typeof import("./lib/config.js").resolveLocalAuthConfig>} AuthLocalConfig */
117
186
  /** @typedef {AuthLocalConfig["oauthProviders"][number]} AuthLocalOAuthProvider */
118
187
  /** @typedef {ReturnType<typeof import("./lib/firstAccountSetup.js").createFirstAccountSetup>} AuthLocalFirstAccountSetup */
@@ -8,6 +8,8 @@ import authCoreEnglish from "@jskit-ai/auth-core/locales/en.json" with { type: "
8
8
  import localEnglish from "../locales/en.json" with { type: "json" };
9
9
  import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
10
10
  import { localServiceOptions } from "../test-support/localService.js";
11
+ import { sessionCookies } from "../test-support/oauthHarness.js";
12
+ import { SCENARIO_START, codeAt } from "../test-support/secondFactorScenario.js";
11
13
 
12
14
  const english = mergeCatalogs(authCoreEnglish, localEnglish);
13
15
 
@@ -77,3 +79,29 @@ test("local auth success texts carry a message code next to the English", async
77
79
  assert.equal(requested.messageCode, "auth.local.recovery.requested");
78
80
  assert.equal(rendered(requested.messageCode, requested.messageParams), requested.message);
79
81
  });
82
+
83
+ test("second factor refusals carry codes whose English is the thrown message", async (t) => {
84
+ t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
85
+ const service = await createService(t);
86
+ await service.register({ email: "ada@example.com", password: "correct horse" });
87
+ const cookies = sessionCookies((await service.login({ email: "ada@example.com", password: "correct horse" })).session);
88
+ const request = () => ({ cookies });
89
+ const coded = (code) => (error) => assertCoded(error, code);
90
+
91
+ await assert.rejects(service.verifySecondFactor(request(), { code: "123456" }), coded("auth.local.secondFactor.notSetUp"));
92
+ await assert.rejects(service.confirmSecondFactorSetup(request(), { code: "123456" }), coded("auth.local.secondFactor.setupNotStarted"));
93
+ const { secret } = await service.startSecondFactorSetup(request());
94
+ await service.confirmSecondFactorSetup(request(), { code: codeAt(secret) });
95
+ await assert.rejects(service.startSecondFactorSetup(request()), coded("auth.local.secondFactor.alreadySetUp"));
96
+ await assert.rejects(service.verifySecondFactor(request(), {}), coded("auth.local.secondFactor.proofRequired"));
97
+ await assert.rejects(service.verifySecondFactor(request(), { code: codeAt(secret) }), coded("auth.local.secondFactor.codeUsed"));
98
+ await assert.rejects(service.verifySecondFactor(request(), { recoveryCode: "abcde-fghjk" }),
99
+ coded("auth.local.secondFactor.recoveryCodeInvalid"));
100
+ for (let attempt = 0; attempt < 3; attempt += 1) {
101
+ await assert.rejects(service.verifySecondFactor(request(), { code: "12345" }), coded("auth.local.secondFactor.codeInvalid"));
102
+ }
103
+ await assert.rejects(service.verifySecondFactor(request(), { code: codeAt(secret, 1) }), (error) => {
104
+ assert.equal(error.message, "Too many wrong codes. Try again in 1 minute.");
105
+ return assertCoded(error, "auth.local.secondFactor.locked");
106
+ });
107
+ });
@@ -96,6 +96,7 @@ async function createStartedApp({
96
96
  passwordStrategy = null,
97
97
  recoverySender = null,
98
98
  confirmationSender = null,
99
+ confirmationMode = null,
99
100
  invitationContextResolver = null,
100
101
  logger = null,
101
102
  configureExtensions = null
@@ -150,6 +151,7 @@ async function createStartedApp({
150
151
  ...(passwordStrategy ? { "auth.local.password-strategy": passwordStrategy } : {}),
151
152
  ...(recoverySender !== null ? { "auth.local.recovery-sender": recoverySender } : {}),
152
153
  ...(confirmationSender !== null ? { "auth.local.confirmation-sender": confirmationSender } : {}),
154
+ ...(confirmationMode !== null ? { "auth.local.confirmation-mode": confirmationMode } : {}),
153
155
  };
154
156
  const runtime = createCapabilityRuntime({
155
157
  inputs,
@@ -1599,3 +1601,152 @@ test("the confirmation sender emails the link, which is never returned or logged
1599
1601
  assert.ok(confirmed.session.access_token);
1600
1602
  assert.deepEqual(hooked, ["owner@example.com", "mail@example.com"]);
1601
1603
  });
1604
+
1605
+ const CONFIRMATION_PASSWORD = "correct horse battery staple";
1606
+ const SIDE_EFFECTS_SETTINGS = Object.freeze([
1607
+ Object.freeze({ name: "live", SIDE_EFFECTS: "live" }),
1608
+ Object.freeze({ name: "a test copy", SIDE_EFFECTS: undefined })
1609
+ ]);
1610
+
1611
+ // A logger that keeps what local auth logs and warns.
1612
+ function recordingLogger() {
1613
+ const infos = [];
1614
+ const warnings = [];
1615
+ return {
1616
+ infos,
1617
+ warnings,
1618
+ logger: {
1619
+ info: (details, message) => infos.push({ details, message }),
1620
+ warn: (details, message) => warnings.push({ details, message }),
1621
+ error() {},
1622
+ debug() {}
1623
+ }
1624
+ };
1625
+ }
1626
+
1627
+ // The emails a test copy logged as simulated, by recipient.
1628
+ function simulatedEmails(infos) {
1629
+ return infos
1630
+ .filter(({ details }) => details?.sideEffects === "simulate" && details.kind === "email")
1631
+ .map(({ details }) => details.email);
1632
+ }
1633
+
1634
+ // An app that confirms registrations at once while its email isn't set up says so, for each registration, through
1635
+ // auth.local.confirmation-mode. The mode sends nothing, so a test copy keeps it and answers as live does.
1636
+ test("a registration the app's confirmation mode confirms without a link signs in at once, live and in a test copy", async (t) => {
1637
+ for (const { name, SIDE_EFFECTS } of SIDE_EFFECTS_SETTINGS) {
1638
+ await t.test(name, async () => {
1639
+ const sent = [];
1640
+ const asked = [];
1641
+ const hooked = [];
1642
+ const { infos, logger } = recordingLogger();
1643
+ const app = await createStartedApp({
1644
+ env: { SIDE_EFFECTS, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1645
+ confirmationSender: async (message) => { sent.push(message.email); },
1646
+ confirmationMode: async ({ email }) => {
1647
+ asked.push(email);
1648
+ return "without-link";
1649
+ },
1650
+ logger,
1651
+ configureExtensions(extensions, runtimeLogger) {
1652
+ extensions.registerServiceDecorator(createLocalAuthRegisterHookDecorator({
1653
+ logger: runtimeLogger,
1654
+ hook: { hookId: "welcome", blocking: true, async handle({ actor }) { hooked.push(actor.email); } }
1655
+ }));
1656
+ }
1657
+ });
1658
+ const registered = await app.authService.register({ email: "Ada@example.com", password: CONFIRMATION_PASSWORD });
1659
+ assert.equal(registered.requiresEmailConfirmation, false);
1660
+ assert.equal(registered.actor.email, "ada@example.com");
1661
+ assert.ok(registered.session.access_token);
1662
+ assert.deepEqual(asked, ["ada@example.com"]);
1663
+ assert.deepEqual(hooked, ["ada@example.com"]);
1664
+ assert.deepEqual(sent, [], "nothing sent");
1665
+ assert.deepEqual(simulatedEmails(infos), [], "nothing simulated");
1666
+ const signedIn = await app.authService.login({ email: "ada@example.com", password: CONFIRMATION_PASSWORD });
1667
+ assert.equal(signedIn.actor.email, "ada@example.com");
1668
+ });
1669
+ }
1670
+ });
1671
+
1672
+ test("without a confirmation mode a registration waits for its link, which live sends and a test copy logs", async (t) => {
1673
+ for (const { name, SIDE_EFFECTS } of SIDE_EFFECTS_SETTINGS) {
1674
+ await t.test(name, async () => {
1675
+ const sent = [];
1676
+ const { infos, logger } = recordingLogger();
1677
+ const app = await createStartedApp({
1678
+ env: { SIDE_EFFECTS, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1679
+ confirmationSender: async (message) => { sent.push(message.email); },
1680
+ logger
1681
+ });
1682
+ const registered = await app.authService.register({ email: "bea@example.com", password: CONFIRMATION_PASSWORD });
1683
+ assert.equal(registered.requiresEmailConfirmation, true);
1684
+ assert.equal(registered.session, null);
1685
+ assert.equal(Object.hasOwn(registered, "confirmationUrl"), false);
1686
+ await assert.rejects(
1687
+ app.authService.login({ email: "bea@example.com", password: CONFIRMATION_PASSWORD }),
1688
+ { status: 403, code: "auth.login.emailUnconfirmed" }
1689
+ );
1690
+ const live = SIDE_EFFECTS === "live";
1691
+ assert.deepEqual(sent, live ? ["bea@example.com"] : []);
1692
+ assert.deepEqual(simulatedEmails(infos), live ? [] : ["bea@example.com"]);
1693
+ });
1694
+ }
1695
+ });
1696
+
1697
+ test("a test copy never sends through the app's sender, whatever its confirmation mode answers", async () => {
1698
+ const sent = [];
1699
+ let emailSetUp = true;
1700
+ const { infos, logger } = recordingLogger();
1701
+ const app = await createStartedApp({
1702
+ env: { SIDE_EFFECTS: undefined, AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1703
+ // A sender that sends real email: a test copy never calls it.
1704
+ confirmationSender: async (message) => { sent.push(message.email); },
1705
+ confirmationMode: async () => (emailSetUp ? "link" : "without-link"),
1706
+ logger
1707
+ });
1708
+ const linked = await app.authService.register({ email: "cy@example.com", password: CONFIRMATION_PASSWORD });
1709
+ assert.equal(linked.requiresEmailConfirmation, true);
1710
+ emailSetUp = false;
1711
+ const atOnce = await app.authService.register({ email: "dee@example.com", password: CONFIRMATION_PASSWORD });
1712
+ assert.equal(atOnce.requiresEmailConfirmation, false);
1713
+ assert.deepEqual(sent, [], "the app's sender never ran");
1714
+ assert.deepEqual(simulatedEmails(infos), ["cy@example.com"]);
1715
+ });
1716
+
1717
+ test("only the exact answer \"without-link\" confirms without a link, and a confirmation mode never stands in for a sender", async () => {
1718
+ const notWithoutLink = [true, "WITHOUT-LINK", "without link", "", undefined, null, 1, { mode: "without-link" }, ["without-link"]];
1719
+ let answer = "link";
1720
+ const { warnings, logger } = recordingLogger();
1721
+ const app = await createStartedApp({
1722
+ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
1723
+ confirmationSender: async () => {},
1724
+ confirmationMode: async () => answer,
1725
+ logger
1726
+ });
1727
+ const linked = await app.authService.register({ email: "link@example.com", password: CONFIRMATION_PASSWORD });
1728
+ assert.equal(linked.requiresEmailConfirmation, true);
1729
+ assert.deepEqual(warnings, []);
1730
+ for (const [index, each] of notWithoutLink.entries()) {
1731
+ answer = each;
1732
+ const registered = await app.authService.register({ email: `user${index}@example.com`, password: CONFIRMATION_PASSWORD });
1733
+ assert.equal(registered.requiresEmailConfirmation, true, `answer ${index}`);
1734
+ }
1735
+ assert.equal(warnings.length, notWithoutLink.length);
1736
+ assert.ok(warnings.every(({ message }) => message.includes("auth.local.confirmation-mode")));
1737
+
1738
+ // In production a confirmation mode leaves the sender required, as without one.
1739
+ await assert.rejects(
1740
+ () => createStartedApp({
1741
+ env: {
1742
+ NODE_ENV: "production",
1743
+ AUTH_LOCAL_SESSION_SECRET: "fixture-session-secret",
1744
+ AUTH_LOCAL_FILE_PRODUCTION_ACK: "true",
1745
+ AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "",
1746
+ AUTH_LOCAL_EMAIL_CONFIRMATION: ""
1747
+ },
1748
+ confirmationMode: async () => "without-link"
1749
+ }),
1750
+ (error) => String(error.details?.cause?.message || error.message || "").includes("no auth.local.confirmation-sender")
1751
+ );
1752
+ });