@jskit-ai/auth-provider-local-core 0.2.25 → 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.
@@ -9,9 +9,22 @@ 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.
@@ -32,6 +45,8 @@ import { createLocalSessions } from "./sessions.js";
32
45
  * `auth.profile.projector`, or noAppProfiles.
33
46
  * @param {import("../types.js").AuthLocalRecoverySender} dependencies.recoverySender The
34
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.
35
50
  */
36
51
  function createLocalAuthService({
37
52
  backend,
@@ -43,7 +58,8 @@ function createLocalAuthService({
43
58
  logger,
44
59
  passwordStrategy,
45
60
  profileProjector,
46
- recoverySender
61
+ recoverySender,
62
+ secondFactorEvents
47
63
  }) {
48
64
  const passwords = normalizePasswordStrategy(passwordStrategy);
49
65
  const firstAccountSetup = givenFirstAccountSetup ?? createFirstAccountSetup({ backend, config, logger });
@@ -86,7 +102,8 @@ function createLocalAuthService({
86
102
  securityStatus: true,
87
103
  signOutOtherSessions: true,
88
104
  appProfileProjection,
89
- devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
105
+ devLoginAs: isDevAuthBootstrapEnabled(config.devAuth),
106
+ secondFactor: Boolean(config.secondFactorKey)
90
107
  }
91
108
  });
92
109
  // While the app has no account, its first one may register, and on a production server that asks for the setup code.
@@ -143,6 +160,10 @@ function createLocalAuthService({
143
160
  sessions
144
161
  });
145
162
 
163
+ const secondFactor = config.secondFactorKey
164
+ ? createLocalSecondFactor({ backend, config, logger, secondFactorEvents, sessions })
165
+ : NO_SECOND_FACTOR;
166
+
146
167
  function getCapabilities() {
147
168
  if (firstAccountSetup.isWaiting()) {
148
169
  return capabilitiesWaitingForFirstAccount;
@@ -206,7 +227,15 @@ function createLocalAuthService({
206
227
  startProviderLink: oauthFlows.startProviderLink,
207
228
  unlinkProvider: oauthFlows.unlinkProvider,
208
229
  signOutOtherSessions: sessions.signOutOtherSessions,
209
- 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
210
239
  });
211
240
  }
212
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
  };
@@ -15,6 +15,7 @@ import { createLocalFileBackend } from "../lib/fileBackend.js";
15
15
  import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
16
16
  import { createLoggedRecoverySender, createSimulatedRecoverySender } from "../lib/passwordFlows.js";
17
17
  import { scryptPasswordStrategy } from "../lib/passwords.js";
18
+ import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
18
19
  import { createLocalAuthService } from "../lib/service.js";
19
20
 
20
21
  const AuthLocalProvider = defineProvider({
@@ -31,7 +32,8 @@ const AuthLocalProvider = defineProvider({
31
32
  confirmationSender: "auth.local.confirmation-sender",
32
33
  passwordStrategy: "auth.local.password-strategy",
33
34
  profileProjector: "auth.profile.projector",
34
- recoverySender: "auth.local.recovery-sender"
35
+ recoverySender: "auth.local.recovery-sender",
36
+ secondFactorEvents: "auth.local.second-factor-events"
35
37
  },
36
38
  provides: {
37
39
  authService: "auth.service"
@@ -53,6 +55,8 @@ const AuthLocalProvider = defineProvider({
53
55
  * @param {import("../types.js").AuthLocalPasswordStrategy | null} dependencies.passwordStrategy The `auth.local.password-strategy`, when one is installed.
54
56
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
55
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.
56
60
  */
57
61
  async boot(
58
62
  {
@@ -65,7 +69,8 @@ const AuthLocalProvider = defineProvider({
65
69
  logger,
66
70
  passwordStrategy,
67
71
  profileProjector,
68
- recoverySender
72
+ recoverySender,
73
+ secondFactorEvents
69
74
  },
70
75
  { outputs }
71
76
  ) {
@@ -94,7 +99,8 @@ const AuthLocalProvider = defineProvider({
94
99
  profileProjector: profileProjector ?? noAppProfiles,
95
100
  recoverySender: emailRecovery
96
101
  ? (live ? recoverySender : createSimulatedRecoverySender(logger))
97
- : createLoggedRecoverySender(logger)
102
+ : createLoggedRecoverySender(logger),
103
+ secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger)
98
104
  });
99
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
100
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.
@@ -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
+ });
@@ -0,0 +1,128 @@
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 { resolveLocalAuthConfig } from "../src/server/lib/config.js";
7
+ import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
8
+ import { __testables, deriveSecondFactorKeys, openSecret, sealSecret } from "../src/server/lib/secondFactorCrypto.js";
9
+ import { localServiceOptions } from "../test-support/localService.js";
10
+ import { sessionCookies } from "../test-support/oauthHarness.js";
11
+ import {
12
+ SCENARIO_START,
13
+ SECOND_FACTOR_KEY,
14
+ codeAt,
15
+ exerciseSecondFactor,
16
+ secondFactorServiceOptions
17
+ } from "../test-support/secondFactorScenario.js";
18
+
19
+ const { fromBase32, stepAt, toBase32, totpCodeAt } = __testables;
20
+
21
+ async function storeDirFor(t) {
22
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-second-factor-"));
23
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
24
+ return storeDir;
25
+ }
26
+
27
+ test("authenticator codes are RFC 6238's: its test vectors, as six-digit codes", () => {
28
+ const secret = toBase32(Buffer.from("12345678901234567890"));
29
+ assert.equal(secret, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
30
+ assert.deepEqual(fromBase32(secret), Buffer.from("12345678901234567890"));
31
+ for (const [seconds, code] of [
32
+ [59, "287082"],
33
+ [1111111109, "081804"],
34
+ [1111111111, "050471"],
35
+ [1234567890, "005924"],
36
+ [2000000000, "279037"],
37
+ [20000000000, "353130"]
38
+ ]) {
39
+ assert.equal(totpCodeAt(secret, stepAt(seconds * 1000)), code, `T = ${seconds}`);
40
+ }
41
+ });
42
+
43
+ test("a sealed secret opens only for its own account and with the key that sealed it", () => {
44
+ const keys = deriveSecondFactorKeys(SECOND_FACTOR_KEY);
45
+ const sealed = sealSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
46
+ assert.match(sealed, /^v1\.[\w-]+\.[\w-]+\.[\w-]+$/u);
47
+ assert.equal(sealed.includes("GEZDGNBV"), false);
48
+ assert.notEqual(sealSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"), sealed, "each seal has its own nonce");
49
+ assert.equal(openSecret(keys, "usr_ada", sealed), "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
50
+ assert.throws(() => openSecret(keys, "usr_bob", sealed), /does not open with AUTH_LOCAL_SECOND_FACTOR_KEY/u);
51
+ assert.throws(() => openSecret(deriveSecondFactorKeys(`${SECOND_FACTOR_KEY}!`), "usr_ada", sealed), /does not open/u);
52
+ assert.throws(() => openSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"), /is not a sealed secret/u);
53
+ });
54
+
55
+ test("an authenticator sets up, proves sessions, refuses wrong, used and expired codes, waits, and resets (file backend)", async (t) => {
56
+ t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
57
+ const storeDir = await storeDirFor(t);
58
+ const { events, options } = secondFactorServiceOptions();
59
+ const service = createLocalAuthService({ ...options, backend: createLocalFileBackend({ storeDir }) });
60
+ await exerciseSecondFactor(t, {
61
+ service,
62
+ events,
63
+ async storedText() {
64
+ const files = await fs.readdir(storeDir);
65
+ return (await Promise.all(files.map((file) => fs.readFile(path.join(storeDir, file), "utf8")))).join("\n");
66
+ }
67
+ });
68
+ });
69
+
70
+ test("the file store keeps a factor and its session's proof across restarts, and another key cannot open it", async (t) => {
71
+ t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
72
+ const storeDir = await storeDirFor(t);
73
+ const start = (env = {}) => createLocalAuthService({ ...secondFactorServiceOptions({ env }).options, backend: createLocalFileBackend({ storeDir }) });
74
+ const first = start();
75
+ await first.register({ email: "ada@example.com", password: "correct horse battery staple" });
76
+ const cookies = sessionCookies((await first.login({ email: "ada@example.com", password: "correct horse battery staple" })).session);
77
+ const { secret } = await first.startSecondFactorSetup({ cookies });
78
+ const { recoveryCodes } = await first.confirmSecondFactorSetup({ cookies }, { code: codeAt(secret) });
79
+
80
+ const restarted = start();
81
+ assert.deepEqual(await restarted.getSecondFactorStatus({ cookies }), {
82
+ enrolled: true,
83
+ enrolledAt: new Date(SCENARIO_START).toISOString(),
84
+ recoveryCodesLeft: 10,
85
+ verifiedAt: new Date(SCENARIO_START).toISOString()
86
+ });
87
+ assert.equal((await restarted.verifySecondFactor({ cookies }, { recoveryCode: recoveryCodes[0] })).recoveryCodesLeft, 9);
88
+
89
+ t.mock.timers.tick(30_000);
90
+ const rekeyed = start({ AUTH_LOCAL_SECOND_FACTOR_KEY: `another key, also 32 characters or more` });
91
+ await assert.rejects(rekeyed.verifySecondFactor({ cookies }, { code: codeAt(secret) }), (error) => {
92
+ assert.equal(error.status, undefined, "a key that cannot open the secret is a server failure, not a refusal");
93
+ assert.match(error.message, /does not open with AUTH_LOCAL_SECOND_FACTOR_KEY/u);
94
+ return true;
95
+ });
96
+ });
97
+
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: "" };
100
+ const service = createLocalAuthService({
101
+ ...localServiceOptions({ env: production }),
102
+ backend: createLocalFileBackend({ storeDir: await storeDirFor(t) })
103
+ });
104
+ assert.equal(service.getCapabilities().features.secondFactor, false);
105
+ assert.throws(() => service.getSecondFactorStatus({ cookies: {} }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
106
+ assert.throws(() => service.listSecondFactors({ userIds: [] }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
107
+
108
+ const resolve = (env) => resolveLocalAuthConfig({
109
+ appRoot: os.tmpdir(),
110
+ env: {
111
+ AUTH_LOCAL_SESSION_SECRET: "test-session-secret",
112
+ AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
113
+ APP_PUBLIC_URL: "https://console.example.com",
114
+ ...env
115
+ },
116
+ fileBackend: false,
117
+ emailRecovery: false
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: "" }),
123
+ /APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set/u);
124
+ // Outside production the session secret stands in for the key.
125
+ assert.equal(resolve({ NODE_ENV: "development" }).secondFactorKey, "test-session-secret");
126
+ assert.equal(createLocalAuthService({ ...localServiceOptions(), backend: createLocalFileBackend({ storeDir: await storeDirFor(t) }) })
127
+ .getCapabilities().features.secondFactor, true);
128
+ });
@@ -6,6 +6,7 @@ import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
6
6
  import { createLoggedConfirmationSender } from "../src/server/lib/emailConfirmation.js";
7
7
  import { createLoggedRecoverySender } from "../src/server/lib/passwordFlows.js";
8
8
  import { scryptPasswordStrategy } from "../src/server/lib/passwords.js";
9
+ import { createLoggedSecondFactorEvents } from "../src/server/lib/secondFactor.js";
9
10
 
10
11
  /**
11
12
  * What a test passes to createLocalAuthService besides its backend: a complete
@@ -39,7 +40,8 @@ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmatio
39
40
  passwordStrategy: scryptPasswordStrategy,
40
41
  profileProjector: noAppProfiles,
41
42
  recoverySender: createLoggedRecoverySender(silentLogger),
42
- confirmationSender: createLoggedConfirmationSender(silentLogger)
43
+ confirmationSender: createLoggedConfirmationSender(silentLogger),
44
+ secondFactorEvents: createLoggedSecondFactorEvents(silentLogger)
43
45
  };
44
46
  }
45
47