@jskit-ai/auth-provider-local-core 0.2.25 → 0.2.27

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.
@@ -0,0 +1,408 @@
1
+ import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
2
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
3
+ import {
4
+ buildOtpauthUrl,
5
+ deriveSecondFactorKeys,
6
+ findRecoveryCodeHash,
7
+ hashRecoveryCode,
8
+ matchCodeStep,
9
+ newAuthenticatorSecret,
10
+ newRecoveryCode,
11
+ normalizeAuthenticatorCode,
12
+ normalizeRecoveryCode,
13
+ openSecret,
14
+ sealSecret
15
+ } from "./secondFactorCrypto.js";
16
+ import { nextFailures, signInWaitMs, waitParams } from "./signInThrottle.js";
17
+
18
+ const RECOVERY_CODE_COUNT = 10;
19
+
20
+ // The refusals of the second factor's operations. A wrong code, a used code and a wrong recovery code count as failed
21
+ // attempts, which make the account wait as failed sign-ins do.
22
+ const REFUSALS = Object.freeze({
23
+ notSetUp: Object.freeze({ status: 409, code: "auth.local.secondFactor.notSetUp", message: "No authenticator is set up for this account." }),
24
+ alreadySetUp: Object.freeze({
25
+ status: 409,
26
+ code: "auth.local.secondFactor.alreadySetUp",
27
+ message: "An authenticator is already set up for this account. Remove it before setting up another."
28
+ }),
29
+ setupNotStarted: Object.freeze({
30
+ status: 409,
31
+ code: "auth.local.secondFactor.setupNotStarted",
32
+ message: "Start setting up the authenticator again."
33
+ }),
34
+ proofRequired: Object.freeze({
35
+ status: 400,
36
+ code: "auth.local.secondFactor.proofRequired",
37
+ message: "Enter a code from your authenticator app or one of your recovery codes."
38
+ }),
39
+ codeInvalid: Object.freeze({
40
+ status: 400,
41
+ code: "auth.local.secondFactor.codeInvalid",
42
+ message: "That code is not right. Enter the code your authenticator app shows now.",
43
+ reason: "codeInvalid"
44
+ }),
45
+ codeUsed: Object.freeze({
46
+ status: 400,
47
+ code: "auth.local.secondFactor.codeUsed",
48
+ message: "That code was already used. Wait for the next code from your authenticator app.",
49
+ reason: "codeUsed"
50
+ }),
51
+ recoveryCodeInvalid: Object.freeze({
52
+ status: 400,
53
+ code: "auth.local.secondFactor.recoveryCodeInvalid",
54
+ message: "That recovery code is not right, or it was already used.",
55
+ reason: "recoveryCodeInvalid"
56
+ })
57
+ });
58
+
59
+ /** @param {{ status: number, code: string, message: string }} refusal */
60
+ function secondFactorError(refusal) {
61
+ return new AppError(refusal.status, refusal.message, { code: refusal.code });
62
+ }
63
+
64
+ /**
65
+ * The refusal of a code while the account waits after wrong ones, with the
66
+ * minutes to wait; Retry-After gives the exact seconds.
67
+ * @param {number} waitMs
68
+ */
69
+ function secondFactorLockedError(waitMs) {
70
+ const params = waitParams(waitMs);
71
+ const unit = params.count === 1 ? "minute" : "minutes";
72
+ return new AppError(429, `Too many wrong codes. Try again in ${params.count} ${unit}.`, {
73
+ code: "auth.local.secondFactor.locked",
74
+ params,
75
+ headers: { "retry-after": String(params.retryAfterSeconds) }
76
+ });
77
+ }
78
+
79
+ /**
80
+ * A proof as the person gave it: exactly one of a code and a recovery code.
81
+ * @param {import("@jskit-ai/auth-core/server/types").AuthSecondFactorProof} input
82
+ */
83
+ function readProof(input) {
84
+ const code = String(input.code ?? "").trim();
85
+ const recoveryCode = String(input.recoveryCode ?? "").trim();
86
+ if (Boolean(code) === Boolean(recoveryCode)) {
87
+ throw secondFactorError(REFUSALS.proofRequired);
88
+ }
89
+ return code ? { code } : { recoveryCode };
90
+ }
91
+
92
+ /** The factor's fields once an attempt succeeded: its failures forgotten. */
93
+ const NO_FAILURES = Object.freeze({ failures: 0, lastFailedAt: "", lockedUntil: "" });
94
+
95
+ /**
96
+ * The `auth.local.second-factor-events` default when no feature provides one:
97
+ * local auth logs each second factor event.
98
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
99
+ * @returns {import("../types.js").AuthLocalSecondFactorEvents}
100
+ */
101
+ function createLoggedSecondFactorEvents(logger) {
102
+ return async function logSecondFactorEvent(event) {
103
+ logger.info({ secondFactorEvent: event }, `Local auth second factor: ${event.type}.`);
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Second factors of local auth: an authenticator app's codes (TOTP) with
109
+ * recovery codes, one factor per account. Its secret is kept sealed with the
110
+ * application's AUTH_LOCAL_SECOND_FACTOR_KEY and its recovery codes as keyed
111
+ * hashes. An accepted code marks the request's session with the time, which
112
+ * routes and actions that ask for a second factor compare; a code is accepted
113
+ * once. Every change and every failed attempt is an event for the
114
+ * application's `auth.local.second-factor-events`.
115
+ * @param {object} dependencies
116
+ * @param {import("../types.js").AuthLocalBackend} dependencies.backend
117
+ * @param {import("../types.js").AuthLocalConfig} dependencies.config
118
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
119
+ * @param {import("../types.js").AuthLocalSecondFactorEvents} dependencies.secondFactorEvents
120
+ * @param {import("../types.js").AuthLocalSessions} dependencies.sessions
121
+ */
122
+ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents, sessions }) {
123
+ const keys = deriveSecondFactorKeys(config.secondFactorKey);
124
+ const issuer = new URL(config.appPublicUrl).host;
125
+
126
+ /** The request's signed-in session, whose second factor the operation works with. */
127
+ async function signedInSession(request) {
128
+ const authResult = await sessions.authenticateRequest(request);
129
+ if (authResult.authenticated !== true) {
130
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
131
+ }
132
+ return {
133
+ userId: authResult.actor.providerUserId,
134
+ email: authResult.actor.email,
135
+ sessionId: authResult.sessionId,
136
+ secondFactorAt: authResult.secondFactorAt,
137
+ ip: String(request.ip || "")
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Hands one event to the application; a recorder that fails is logged and changes nothing that happened.
143
+ * @param {import("../types.js").AuthLocalSecondFactorEvent["type"]} type
144
+ * @param {{ userId: string, ip: string }} subject
145
+ * @param {object} [details]
146
+ */
147
+ async function recordEvent(type, { userId, ip }, details = {}) {
148
+ try {
149
+ await secondFactorEvents({ type, userId, ip, at: new Date().toISOString(), ...details });
150
+ } catch (error) {
151
+ logger.warn({ err: error, secondFactorEvent: type, userId }, "Recording a local auth second factor event failed.");
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Checks a code against the factor: the step of the code it accepts, or the refusal.
157
+ * @param {string} userId
158
+ * @param {object} factor
159
+ * @param {string} typed
160
+ * @param {number} now
161
+ */
162
+ function checkCode(userId, factor, typed, now) {
163
+ const code = normalizeAuthenticatorCode(typed);
164
+ const step = code ? matchCodeStep(openSecret(keys, userId, factor.secretSealed), code, now) : null;
165
+ if (step === null) {
166
+ return { refusal: REFUSALS.codeInvalid };
167
+ }
168
+ // A code is accepted once: one from the step of an accepted code, or an earlier one, is refused.
169
+ if (step <= factor.lastUsedStep) {
170
+ return { refusal: REFUSALS.codeUsed };
171
+ }
172
+ return { method: "code", changes: { lastUsedStep: step } };
173
+ }
174
+
175
+ /**
176
+ * Checks a recovery code against the factor's: the codes left once it is used, or the refusal.
177
+ * @param {string} userId
178
+ * @param {object} factor
179
+ * @param {string} typed
180
+ */
181
+ function checkRecoveryCode(userId, factor, typed) {
182
+ const code = normalizeRecoveryCode(typed);
183
+ const index = code ? findRecoveryCodeHash(factor.recoveryCodes, hashRecoveryCode(keys, userId, code)) : -1;
184
+ if (index < 0) {
185
+ return { refusal: REFUSALS.recoveryCodeInvalid };
186
+ }
187
+ return { method: "recoveryCode", changes: { recoveryCodes: factor.recoveryCodes.filter((_, at) => at !== index) } };
188
+ }
189
+
190
+ /**
191
+ * Proves the session's second factor in the caller's transaction. While the
192
+ * account waits after wrong codes, nothing is checked. A refused proof counts
193
+ * one more failure; an accepted one forgets them, uses up its code, confirms
194
+ * a factor still being set up, applies the caller's changes and marks the
195
+ * session.
196
+ * @param {import("../types.js").AuthLocalBackendTransaction} tx
197
+ * @param {{ userId: string, sessionId: string }} session
198
+ * @param {object} factor The account's factor, as `secondFactors.find` held it.
199
+ * @param {{ code: string } | { recoveryCode: string }} proof
200
+ * @param {object} [changes]
201
+ */
202
+ async function prove(tx, session, factor, proof, changes = {}) {
203
+ const now = Date.now();
204
+ const waitMs = signInWaitMs(factor, now);
205
+ if (waitMs > 0) {
206
+ return { waitMs };
207
+ }
208
+ const checked = Object.hasOwn(proof, "recoveryCode")
209
+ ? checkRecoveryCode(session.userId, factor, proof.recoveryCode)
210
+ : checkCode(session.userId, factor, proof.code, now);
211
+ const at = new Date(now).toISOString();
212
+ if (checked.refusal) {
213
+ await tx.secondFactors.save({ ...factor, ...nextFailures(config.signInThrottle, factor, now), updatedAt: at });
214
+ return { refusal: checked.refusal };
215
+ }
216
+ const proved = { ...factor, ...checked.changes, ...changes, ...NO_FAILURES, confirmedAt: factor.confirmedAt || at, updatedAt: at };
217
+ await tx.secondFactors.save(proved);
218
+ await tx.sessions.markSecondFactorProved(session.sessionId, at);
219
+ return { factor: proved, method: checked.method, verifiedAt: at };
220
+ }
221
+
222
+ /**
223
+ * Proves the session's second factor with the account's confirmed factor.
224
+ * @param {import("../types.js").AuthLocalBackendTransaction} tx
225
+ * @param {{ userId: string, sessionId: string }} session
226
+ * @param {{ code: string } | { recoveryCode: string }} proof
227
+ * @param {object} [changes]
228
+ */
229
+ async function proveConfirmed(tx, session, proof, changes = {}) {
230
+ const factor = await tx.secondFactors.find(session.userId);
231
+ return factor?.confirmedAt ? prove(tx, session, factor, proof, changes) : { refusal: REFUSALS.notSetUp };
232
+ }
233
+
234
+ /** Throws a refused outcome's error after its transaction, so the failure it counted is kept, and records it. */
235
+ async function refuseFailed(outcome, session) {
236
+ if (outcome.waitMs) {
237
+ await recordEvent("failed", session, { reason: "locked" });
238
+ throw secondFactorLockedError(outcome.waitMs);
239
+ }
240
+ if (outcome.refusal) {
241
+ if (outcome.refusal.reason) {
242
+ await recordEvent("failed", session, { reason: outcome.refusal.reason });
243
+ }
244
+ throw secondFactorError(outcome.refusal);
245
+ }
246
+ }
247
+
248
+ /** New recovery codes: the codes to show once, and the hashes to keep. */
249
+ function newRecoveryCodes(userId) {
250
+ const recoveryCodes = Array.from({ length: RECOVERY_CODE_COUNT }, () => newRecoveryCode());
251
+ return { recoveryCodes, hashes: recoveryCodes.map((code) => hashRecoveryCode(keys, userId, normalizeRecoveryCode(code))) };
252
+ }
253
+
254
+ async function getSecondFactorStatus(request) {
255
+ const session = await signedInSession(request);
256
+ const [factor] = await backend.withTransaction((tx) => tx.secondFactors.findMany([session.userId]));
257
+ const enrolled = Boolean(factor?.confirmedAt);
258
+ return {
259
+ enrolled,
260
+ enrolledAt: enrolled ? factor.confirmedAt : null,
261
+ recoveryCodesLeft: enrolled ? factor.recoveryCodes.length : 0,
262
+ verifiedAt: session.secondFactorAt || null
263
+ };
264
+ }
265
+
266
+ /** Starts setting up an authenticator, replacing a setup the person never confirmed; its failures are kept. */
267
+ async function startSecondFactorSetup(request) {
268
+ const session = await signedInSession(request);
269
+ const secret = newAuthenticatorSecret();
270
+ const started = await backend.withTransaction(async (tx) => {
271
+ const existing = await tx.secondFactors.find(session.userId);
272
+ if (existing?.confirmedAt) {
273
+ return false;
274
+ }
275
+ const now = new Date().toISOString();
276
+ await tx.secondFactors.save({
277
+ userId: session.userId,
278
+ secretSealed: sealSecret(keys, session.userId, secret),
279
+ confirmedAt: "",
280
+ lastUsedStep: 0,
281
+ recoveryCodes: [],
282
+ failures: existing?.failures ?? 0,
283
+ lastFailedAt: existing?.lastFailedAt ?? "",
284
+ lockedUntil: existing?.lockedUntil ?? "",
285
+ createdAt: now,
286
+ updatedAt: now
287
+ });
288
+ return true;
289
+ });
290
+ if (!started) {
291
+ throw secondFactorError(REFUSALS.alreadySetUp);
292
+ }
293
+ await recordEvent("setupStarted", session);
294
+ return {
295
+ secret,
296
+ otpauthUrl: buildOtpauthUrl({ secret, issuer, accountName: session.email }),
297
+ issuer,
298
+ accountName: session.email
299
+ };
300
+ }
301
+
302
+ /** Confirms a started setup with the authenticator's first code, and answers its recovery codes once. */
303
+ async function confirmSecondFactorSetup(request, input) {
304
+ const session = await signedInSession(request);
305
+ const { recoveryCodes, hashes } = newRecoveryCodes(session.userId);
306
+ const outcome = await backend.withTransaction(async (tx) => {
307
+ const factor = await tx.secondFactors.find(session.userId);
308
+ if (!factor) {
309
+ return { refusal: REFUSALS.setupNotStarted };
310
+ }
311
+ if (factor.confirmedAt) {
312
+ return { refusal: REFUSALS.alreadySetUp };
313
+ }
314
+ return prove(tx, session, factor, { code: String(input.code ?? "") }, { recoveryCodes: hashes });
315
+ });
316
+ await refuseFailed(outcome, session);
317
+ sessions.forgetRequestAuthentication(request);
318
+ await recordEvent("setupConfirmed", session);
319
+ return { recoveryCodes, verifiedAt: outcome.verifiedAt };
320
+ }
321
+
322
+ async function verifySecondFactor(request, input) {
323
+ const session = await signedInSession(request);
324
+ const proof = readProof(input);
325
+ const outcome = await backend.withTransaction((tx) => proveConfirmed(tx, session, proof));
326
+ await refuseFailed(outcome, session);
327
+ sessions.forgetRequestAuthentication(request);
328
+ const recoveryCodesLeft = outcome.factor.recoveryCodes.length;
329
+ await recordEvent("verified", session, { method: outcome.method, recoveryCodesLeft });
330
+ return { verifiedAt: outcome.verifiedAt, method: outcome.method, recoveryCodesLeft };
331
+ }
332
+
333
+ async function replaceSecondFactorRecoveryCodes(request, input) {
334
+ const session = await signedInSession(request);
335
+ const proof = readProof(input);
336
+ const { recoveryCodes, hashes } = newRecoveryCodes(session.userId);
337
+ const outcome = await backend.withTransaction((tx) => proveConfirmed(tx, session, proof, { recoveryCodes: hashes }));
338
+ await refuseFailed(outcome, session);
339
+ sessions.forgetRequestAuthentication(request);
340
+ await recordEvent("recoveryCodesReplaced", session, { method: outcome.method });
341
+ return { recoveryCodes, verifiedAt: outcome.verifiedAt };
342
+ }
343
+
344
+ /** Removes the person's authenticator; every session of theirs must prove a second factor again. */
345
+ async function removeSecondFactor(request, input) {
346
+ const session = await signedInSession(request);
347
+ const proof = readProof(input);
348
+ const outcome = await backend.withTransaction(async (tx) => {
349
+ const proved = await proveConfirmed(tx, session, proof);
350
+ if (proved.factor) {
351
+ await tx.secondFactors.delete(session.userId);
352
+ await tx.sessions.clearSecondFactorForUser(session.userId);
353
+ }
354
+ return proved;
355
+ });
356
+ await refuseFailed(outcome, session);
357
+ sessions.forgetRequestAuthentication(request);
358
+ await recordEvent("removed", session, { method: outcome.method });
359
+ return { ok: true };
360
+ }
361
+
362
+ /**
363
+ * The given accounts that have an authenticator set up.
364
+ * @param {{ userIds: string[] }} input
365
+ */
366
+ async function listSecondFactors({ userIds }) {
367
+ if (!Array.isArray(userIds)) {
368
+ throw new TypeError("listSecondFactors() takes { userIds } with an array of local account ids.");
369
+ }
370
+ const factors = await backend.withTransaction((tx) => tx.secondFactors.findMany(userIds.map(String)));
371
+ return factors.filter((factor) => factor.confirmedAt).map((factor) => ({ userId: factor.userId, enrolledAt: factor.confirmedAt }));
372
+ }
373
+
374
+ /**
375
+ * Removes an account's authenticator for the application, which decides who
376
+ * may; every session of the account must prove a second factor again.
377
+ * @param {{ userId: string, byUserId: string }} input
378
+ */
379
+ async function resetSecondFactor({ userId, byUserId }) {
380
+ const id = String(userId ?? "").trim();
381
+ const by = String(byUserId ?? "").trim();
382
+ if (!id || !by) {
383
+ throw new TypeError("resetSecondFactor() takes the userId whose second factor it removes and the byUserId who removes it.");
384
+ }
385
+ const reset = await backend.withTransaction(async (tx) => {
386
+ const removed = await tx.secondFactors.delete(id);
387
+ await tx.sessions.clearSecondFactorForUser(id);
388
+ return removed > 0;
389
+ });
390
+ if (reset) {
391
+ await recordEvent("reset", { userId: id, ip: "" }, { byUserId: by });
392
+ }
393
+ return { reset };
394
+ }
395
+
396
+ return Object.freeze({
397
+ getSecondFactorStatus,
398
+ startSecondFactorSetup,
399
+ confirmSecondFactorSetup,
400
+ verifySecondFactor,
401
+ replaceSecondFactorRecoveryCodes,
402
+ removeSecondFactor,
403
+ listSecondFactors,
404
+ resetSecondFactor
405
+ });
406
+ }
407
+
408
+ export { createLocalSecondFactor, createLoggedSecondFactorEvents };
@@ -0,0 +1,239 @@
1
+ import { createCipheriv, createDecipheriv, createHmac, hkdfSync, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
2
+
3
+ // Authenticator codes as RFC 6238 defines them and every authenticator app makes them by default: HMAC-SHA1 over
4
+ // 30-second steps, six digits. One step either side is accepted, for a phone whose clock drifts.
5
+ const STEP_SECONDS = 30;
6
+ const CODE_DIGITS = 6;
7
+ const ACCEPTED_STEP_OFFSETS = Object.freeze([-1, 0, 1]);
8
+ // RFC 4226 recommends a 160-bit secret.
9
+ const SECRET_BYTES = 20;
10
+ const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
11
+ // Recovery codes: ten characters of Crockford's base32 (no i, l, o or u), 50 random bits each, shown as xxxxx-xxxxx.
12
+ const RECOVERY_CODE_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
13
+ const RECOVERY_CODE_LENGTH = 10;
14
+ const RECOVERY_CODE_PATTERN = /^[0-9a-hjkmnp-tv-z]{10}$/u;
15
+ const CODE_PATTERN = new RegExp(`^\\d{${CODE_DIGITS}}$`, "u");
16
+ // A sealed secret: AES-256-GCM, its version, nonce, ciphertext and tag in base64url, bound to its account's id.
17
+ const SEALED_VERSION = "v1";
18
+
19
+ /** @param {Buffer} bytes */
20
+ function toBase32(bytes) {
21
+ let bits = 0;
22
+ let value = 0;
23
+ let text = "";
24
+ for (const byte of bytes) {
25
+ value = (value << 8) | byte;
26
+ bits += 8;
27
+ while (bits >= 5) {
28
+ text += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
29
+ bits -= 5;
30
+ }
31
+ }
32
+ if (bits > 0) {
33
+ text += BASE32_ALPHABET[(value << (5 - bits)) & 31];
34
+ }
35
+ return text;
36
+ }
37
+
38
+ /** @param {string} text Base32 without padding, as toBase32 writes it. */
39
+ function fromBase32(text) {
40
+ let bits = 0;
41
+ let value = 0;
42
+ const bytes = [];
43
+ for (const character of text) {
44
+ const digit = BASE32_ALPHABET.indexOf(character);
45
+ if (digit < 0) {
46
+ throw new Error("A second factor secret is not base32.");
47
+ }
48
+ value = (value << 5) | digit;
49
+ bits += 5;
50
+ if (bits >= 8) {
51
+ bytes.push((value >>> (bits - 8)) & 255);
52
+ bits -= 8;
53
+ }
54
+ }
55
+ return Buffer.from(bytes);
56
+ }
57
+
58
+ /** A new authenticator secret, in base32. */
59
+ function newAuthenticatorSecret() {
60
+ return toBase32(randomBytes(SECRET_BYTES));
61
+ }
62
+
63
+ /** The 30-second step a time falls in. @param {number} nowMs */
64
+ function stepAt(nowMs) {
65
+ return Math.floor(nowMs / 1000 / STEP_SECONDS);
66
+ }
67
+
68
+ /**
69
+ * The code an authenticator shows in one step (RFC 4226's HOTP of the step).
70
+ * @param {string} secret Base32.
71
+ * @param {number} step
72
+ */
73
+ function totpCodeAt(secret, step) {
74
+ const counter = Buffer.alloc(8);
75
+ counter.writeBigUInt64BE(BigInt(step));
76
+ const digest = createHmac("sha1", fromBase32(secret)).update(counter).digest();
77
+ const offset = digest[digest.length - 1] & 15;
78
+ const binary = digest.readUInt32BE(offset) & 0x7fffffff;
79
+ return String(binary % 10 ** CODE_DIGITS).padStart(CODE_DIGITS, "0");
80
+ }
81
+
82
+ /**
83
+ * A typed code as six digits, with the spaces and hyphens a person may type
84
+ * removed, or "" when it is not one.
85
+ * @param {unknown} value
86
+ */
87
+ function normalizeAuthenticatorCode(value) {
88
+ const code = String(value ?? "").replace(/[\s-]/gu, "");
89
+ return CODE_PATTERN.test(code) ? code : "";
90
+ }
91
+
92
+ /**
93
+ * The step of the accepted window whose code the person typed, or null. Every
94
+ * step of the window is compared, in constant time.
95
+ * @param {string} secret Base32.
96
+ * @param {string} code Six digits.
97
+ * @param {number} nowMs
98
+ */
99
+ function matchCodeStep(secret, code, nowMs) {
100
+ const typed = Buffer.from(code);
101
+ let matched = null;
102
+ for (const offset of ACCEPTED_STEP_OFFSETS) {
103
+ const step = stepAt(nowMs) + offset;
104
+ const expected = Buffer.from(totpCodeAt(secret, step));
105
+ if (typed.length === expected.length && timingSafeEqual(typed, expected)) {
106
+ matched = step;
107
+ }
108
+ }
109
+ return matched;
110
+ }
111
+
112
+ /**
113
+ * The otpauth:// address an authenticator app reads from a QR code.
114
+ * @param {{ secret: string, issuer: string, accountName: string }} input
115
+ */
116
+ function buildOtpauthUrl({ secret, issuer, accountName }) {
117
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(accountName)}`;
118
+ const query = new URLSearchParams({ secret, issuer, algorithm: "SHA1", digits: String(CODE_DIGITS), period: String(STEP_SECONDS) });
119
+ return `otpauth://totp/${label}?${query}`;
120
+ }
121
+
122
+ /**
123
+ * The keys the application's second factor key derives: one seals authenticator
124
+ * secrets, the other hashes recovery codes.
125
+ * @param {string} secondFactorKey AUTH_LOCAL_SECOND_FACTOR_KEY.
126
+ */
127
+ function deriveSecondFactorKeys(secondFactorKey) {
128
+ const derive = (purpose) => Buffer.from(hkdfSync("sha256", secondFactorKey, "", `jskit auth.local ${purpose}`, 32));
129
+ return Object.freeze({
130
+ seal: derive("second factor secrets"),
131
+ recoveryCodes: derive("second factor recovery codes")
132
+ });
133
+ }
134
+
135
+ /**
136
+ * An authenticator secret sealed for storage, bound to its account: a sealed
137
+ * secret copied to another account does not open.
138
+ * @param {ReturnType<typeof deriveSecondFactorKeys>} keys
139
+ * @param {string} userId
140
+ * @param {string} secret
141
+ */
142
+ function sealSecret(keys, userId, secret) {
143
+ const nonce = randomBytes(12);
144
+ const cipher = createCipheriv("aes-256-gcm", keys.seal, nonce);
145
+ cipher.setAAD(Buffer.from(userId));
146
+ const sealed = Buffer.concat([cipher.update(secret, "utf8"), cipher.final()]);
147
+ return [SEALED_VERSION, nonce.toString("base64url"), sealed.toString("base64url"), cipher.getAuthTag().toString("base64url")].join(".");
148
+ }
149
+
150
+ /**
151
+ * The secret sealSecret sealed for the account. It fails when the key is not
152
+ * the one that sealed it.
153
+ * @param {ReturnType<typeof deriveSecondFactorKeys>} keys
154
+ * @param {string} userId
155
+ * @param {string} sealed
156
+ */
157
+ function openSecret(keys, userId, sealed) {
158
+ const [version, nonce, body, tag] = String(sealed).split(".");
159
+ if (version !== SEALED_VERSION) {
160
+ throw new Error(`The second factor secret of account ${userId} is not a sealed secret.`);
161
+ }
162
+ try {
163
+ const decipher = createDecipheriv("aes-256-gcm", keys.seal, Buffer.from(nonce, "base64url"));
164
+ decipher.setAAD(Buffer.from(userId));
165
+ decipher.setAuthTag(Buffer.from(tag, "base64url"));
166
+ return Buffer.concat([decipher.update(Buffer.from(body, "base64url")), decipher.final()]).toString("utf8");
167
+ } catch (error) {
168
+ throw new Error(
169
+ `The second factor secret of account ${userId} does not open with AUTH_LOCAL_SECOND_FACTOR_KEY. ` +
170
+ "Restore the key that sealed it, or reset the account's second factor.",
171
+ { cause: error }
172
+ );
173
+ }
174
+ }
175
+
176
+ /** A new recovery code, as the person sees it: xxxxx-xxxxx. */
177
+ function newRecoveryCode() {
178
+ let code = "";
179
+ for (let index = 0; index < RECOVERY_CODE_LENGTH; index += 1) {
180
+ code += RECOVERY_CODE_ALPHABET[randomInt(RECOVERY_CODE_ALPHABET.length)];
181
+ }
182
+ return `${code.slice(0, 5)}-${code.slice(5)}`;
183
+ }
184
+
185
+ /**
186
+ * A typed recovery code in lower case without spaces or hyphens, or "" when it
187
+ * is not one.
188
+ * @param {unknown} value
189
+ */
190
+ function normalizeRecoveryCode(value) {
191
+ const code = String(value ?? "").replace(/[\s-]/gu, "").toLowerCase();
192
+ return RECOVERY_CODE_PATTERN.test(code) ? code : "";
193
+ }
194
+
195
+ /**
196
+ * The stored form of an account's recovery code: a keyed hash, so a copy of
197
+ * the store cannot be searched for codes without the key.
198
+ * @param {ReturnType<typeof deriveSecondFactorKeys>} keys
199
+ * @param {string} userId
200
+ * @param {string} code A normalized recovery code.
201
+ */
202
+ function hashRecoveryCode(keys, userId, code) {
203
+ return createHmac("sha256", keys.recoveryCodes).update(`${userId}:${code}`).digest("base64url");
204
+ }
205
+
206
+ /**
207
+ * The index of the hash among the stored ones, or -1; every stored hash is
208
+ * compared, in constant time.
209
+ * @param {readonly string[]} hashes
210
+ * @param {string} hash
211
+ */
212
+ function findRecoveryCodeHash(hashes, hash) {
213
+ const wanted = Buffer.from(hash);
214
+ let found = -1;
215
+ hashes.forEach((stored, index) => {
216
+ const candidate = Buffer.from(stored);
217
+ if (candidate.length === wanted.length && timingSafeEqual(candidate, wanted)) {
218
+ found = index;
219
+ }
220
+ });
221
+ return found;
222
+ }
223
+
224
+ const __testables = Object.freeze({ fromBase32, stepAt, toBase32, totpCodeAt });
225
+
226
+ export {
227
+ __testables,
228
+ buildOtpauthUrl,
229
+ deriveSecondFactorKeys,
230
+ findRecoveryCodeHash,
231
+ hashRecoveryCode,
232
+ matchCodeStep,
233
+ newAuthenticatorSecret,
234
+ newRecoveryCode,
235
+ normalizeAuthenticatorCode,
236
+ normalizeRecoveryCode,
237
+ openSecret,
238
+ sealSecret
239
+ };
@@ -4,7 +4,8 @@ import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authText
4
4
  import { hasPassword } from "./accounts.js";
5
5
 
6
6
  /**
7
- * The sign-in methods of an account: its password and each configured provider.
7
+ * The sign-in methods of an account: its password and each configured provider,
8
+ * and whether it has an authenticator set up as its second factor.
8
9
  * @param {object} dependencies
9
10
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
10
11
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
@@ -15,10 +16,12 @@ function createLocalSecurityStatus({ backend, config, oauthProvidersById, sessio
15
16
  const { oauthProviders, oauthEnabled } = config;
16
17
 
17
18
  async function securityStatusForUser(userId) {
18
- const { user, identities } = await backend.withTransaction(async (tx) => ({
19
+ const { user, identities, secondFactors } = await backend.withTransaction(async (tx) => ({
19
20
  user: await tx.users.findById(userId),
20
- identities: oauthEnabled ? await tx.identities.listForUser(userId) : []
21
+ identities: oauthEnabled ? await tx.identities.listForUser(userId) : [],
22
+ secondFactors: config.secondFactorKey ? await tx.secondFactors.findMany([userId]) : []
21
23
  }));
24
+ const secondFactorEnrolled = secondFactors.some((factor) => factor.confirmedAt);
22
25
  const passwordSet = hasPassword(user);
23
26
  // Identities of a provider the app no longer configures cannot sign in.
24
27
  const linkedProviders = new Set(identities.map((identity) => identity.provider).filter((id) => oauthProvidersById.has(id)));
@@ -64,6 +67,11 @@ function createLocalSecurityStatus({ backend, config, oauthProvidersById, sessio
64
67
  signOutOtherSessions: true,
65
68
  linkProvider: oauthEnabled,
66
69
  unlinkProvider: oauthEnabled
70
+ },
71
+ mfa: {
72
+ status: secondFactorEnrolled ? "enabled" : "not_enabled",
73
+ enrolled: secondFactorEnrolled,
74
+ methods: secondFactorEnrolled ? ["totp"] : []
67
75
  }
68
76
  }
69
77
  );