Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(totp): integrate recovery codes into enrollment process
Elian Doran4ebd6cf28919
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 6768649155..0132f62bbf 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1720,6 +1720,13 @@"totp_enroll_invalid_code": "That code didn't match. Check that your device's clock is correct and enter the latest code.","totp_enroll_generate_error": "Couldn't generate a TOTP secret. Please close this dialog and try again.","totp_enroll_enabled": "Two-factor authentication is now enabled.",+ "totp_enroll_recovery_title": "Save your recovery codes",+ "totp_enroll_recovery_instructions": "Save these recovery codes somewhere safe. Each one can be used once to sign in if you lose access to your authenticator app.",+ "totp_enroll_recovery_copy": "Copy",+ "totp_enroll_recovery_copied": "Recovery codes copied to clipboard.",+ "totp_enroll_recovery_download": "Download",+ "totp_enroll_saved_ack": "I've saved my recovery codes somewhere safe",+ "totp_enroll_finish": "Finish setup","totp_section_title": "TOTP","totp_remove_label": "Remove two-factor authentication","totp_remove_description": "Completely remove your two-factor authentication setup. Unlike switching it off above, you'd have to set it up again from scratch to use it.",diff --git a/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.css b/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.cssindex 8c8e25279b..56ede6e3d9 100644--- a/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.css+++ b/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.css@@ -47,6 +47,19 @@letter-spacing: 0.15em;}+/* Recovery-codes step: two monospaced columns so all eight codes fit compactly. */+.modal.totp-enrollment-modal .totp-recovery-codes {+ column-count: 2;+ font-family: var(--monospace-font-family, monospace);+}++/* Copy / download actions sit in a row beneath the codes. */+.modal.totp-enrollment-modal .totp-recovery-actions {+ display: flex;+ gap: 8px;+ margin-block: 12px;+}+/* One dot per recovery code, shown inline right after the "Recovery codes" label. */.recovery-code-dots {display: flex;diff --git a/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.tsx b/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.tsxindex 51503220cb..23e210211a 100644--- a/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.tsx+++ b/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.tsx@@ -1,6 +1,7 @@import "./multi_factor_authentication.css";import { OAuthStatus, TOTPConfirmResponse, TOTPGenerate, TOTPRecoveryKeysResponse, TOTPStatus } from "@triliumnext/commons";+import { RefObject } from "preact";import { createPortal } from "preact/compat";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { Trans } from "react-i18next";@@ -9,7 +10,7 @@ import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import server from "../../../services/server";import toast from "../../../services/toast";-import { isElectron } from "../../../services/utils";+import utils, { isElectron } from "../../../services/utils";import Admonition from "../../react/Admonition";import { Badge } from "../../react/Badge";import Button from "../../react/Button";@@ -178,19 +179,18 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {setGeneratedKeys(result.recoveryCodes);}- await server.post("totp_recovery/set", {- recoveryCodes: result.recoveryCodes,- });+ // `totp_recovery/generate` already persisted the codes, so no extra `set` round-trip is needed.await refreshRecoveryKeys();}, [ refreshRecoveryKeys ]);- // Runs once the user has proven they can produce a valid code: the server has now persisted the- // secret, so reflect the freshly-active state and (re)generate recovery codes.- const onEnrollmentConfirmed = useCallback(async () => {+ // Runs once enrollment is finished: the secret is persisted and recovery codes were issued by+ // `totp/confirm` (and shown in the modal), so we only refresh state here — generating again would+ // invalidate the codes the user just saved.+ const onEnrollmentComplete = useCallback(() => {toast.showMessage(t("multi_factor_authentication.totp_enroll_enabled"));refreshTotpStatus();- await generateRecoveryKeys();- }, [ refreshTotpStatus, generateRecoveryKeys ]);+ void refreshRecoveryKeys();+ }, [ refreshTotpStatus, refreshRecoveryKeys ]);const removeTotp = useCallback(async () => {if (!await dialog.confirm(t("multi_factor_authentication.totp_remove_confirm"))) {@@ -246,7 +246,7 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {<TotpEnrollmentModalshow={showEnroll}onHidden={() => setShowEnroll(false)}- onConfirmed={onEnrollmentConfirmed}+ onComplete={onEnrollmentComplete}/>,document.body)}@@ -254,21 +254,29 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {}/**- * Verify-before-enable enrollment dialog. On open it fetches a fresh (not-yet-persisted) TOTP secret,- * shows it for the user to add to their authenticator, and requires them to enter a valid code for it.- * The secret is only persisted server-side on a successful `totp/confirm`, so cancelling or failing- * verification can never leave TOTP active for a secret the user can't actually generate codes for.+ * Verify-before-enable enrollment dialog with two steps:+ *+ * 1. Fetch a fresh (not-yet-persisted) secret, show it for the user to add to their authenticator,+ * and require them to enter a valid code. The secret is only persisted server-side once the code+ * checks out, so cancelling or failing verification can never enable TOTP for a secret the user+ * can't actually generate codes for.+ * 2. Show the recovery codes issued alongside the secret by `totp/confirm`, so the user can save the+ * fallback they'll need if they ever lose their authenticator, before finishing.*/-function TotpEnrollmentModal({ show, onHidden, onConfirmed }: {+function TotpEnrollmentModal({ show, onHidden, onComplete }: {show: boolean,onHidden: () => void,- onConfirmed: () => Promise<void> | void+ /** Called when the dialog closes after TOTP was enabled, so the surrounding section can refresh. */+ onComplete: () => void}) {const [ secret, setSecret ] = useState<string>();const [ loadFailed, setLoadFailed ] = useState(false);const [ code, setCode ] = useState("");const [ codeRejected, setCodeRejected ] = useState(false);const [ verifying, setVerifying ] = useState(false);+ // Set once verification succeeds: switches the dialog to the "save your recovery codes" step.+ const [ recoveryCodes, setRecoveryCodes ] = useState<string[]>();+ const [ acknowledged, setAcknowledged ] = useState(false);const codeRef = useRef<HTMLInputElement>(null);// Each time the modal opens, reset state and request a fresh secret.@@ -282,6 +290,8 @@ function TotpEnrollmentModal({ show, onHidden, onConfirmed }: {setCode("");setCodeRejected(false);setVerifying(false);+ setRecoveryCodes(undefined);+ setAcknowledged(false);void server.get<TOTPGenerate>("totp/generate").then((result) => {if (result.success) {@@ -292,12 +302,12 @@ function TotpEnrollmentModal({ show, onHidden, onConfirmed }: {});}, [ show ]);- // Focus the code field once the secret has loaded.+ // Focus the code field once the secret has loaded (verify step only).useEffect(() => {- if (secret) {+ if (secret && !recoveryCodes) {codeRef.current?.focus();}- }, [ secret ]);+ }, [ secret, recoveryCodes ]);const verify = useCallback(async () => {if (!secret || code.length === 0 || verifying) {@@ -317,64 +327,164 @@ function TotpEnrollmentModal({ show, onHidden, onConfirmed }: {return;}- await onConfirmed();+ // TOTP is now active server-side; advance to the recovery-codes step so the user can save them.+ setRecoveryCodes(result.recoveryCodes ?? []);+ }, [ secret, code, verifying ]);++ const inRecoveryStep = !!recoveryCodes;++ // The bootstrap "hidden" event is the single place we react to the dialog closing: if the user got+ // as far as the recovery step then TOTP is enabled, so refresh the surrounding section.+ const handleModalHidden = useCallback(() => {+ if (recoveryCodes) {+ onComplete();+ }onHidden();- }, [ secret, code, verifying, onConfirmed, onHidden ]);+ }, [ recoveryCodes, onComplete, onHidden ]);return (<ModalclassName="totp-enrollment-modal"- title={t("multi_factor_authentication.totp_enroll_title")}+ title={inRecoveryStep+ ? t("multi_factor_authentication.totp_enroll_recovery_title")+ : t("multi_factor_authentication.totp_enroll_title")}size="md"show={show}- onHidden={onHidden}- onSubmit={() => void verify()}+ onHidden={handleModalHidden}+ onSubmit={() => {+ if (inRecoveryStep) {+ if (acknowledged) {+ onHidden();+ }+ } else {+ void verify();+ }+ }}stackable- footer={<>- <Button text={t("multi_factor_authentication.totp_enroll_cancel")} onClick={onHidden} />- <Button- text={t("multi_factor_authentication.totp_enroll_verify")}+ footer={inRecoveryStep+ ? <Button+ text={t("multi_factor_authentication.totp_enroll_finish")}kind="primary"- disabled={!secret || code.length === 0 || verifying}+ disabled={!acknowledged}+ onClick={onHidden}/>- </>}- >- {loadFailed- ? <Admonition type="caution">{t("multi_factor_authentication.totp_enroll_generate_error")}</Admonition>: <>- <FormText>{t("multi_factor_authentication.totp_enroll_instructions")}</FormText>-- <FormGroup name="totp-enroll-secret" label={t("multi_factor_authentication.totp_enroll_secret_label")}>- <FormTextBox- className="totp-enroll-secret"- currentValue={secret ?? ""}- readOnly- onFocus={(e) => e.currentTarget.select()}- />- </FormGroup>-- <Admonition type="caution">{t("multi_factor_authentication.totp_secret_warning")}</Admonition>-- <FormGroup- name="totp-enroll-code"- label={t("multi_factor_authentication.totp_enroll_code_label")}- error={codeRejected ? t("multi_factor_authentication.totp_enroll_invalid_code") : undefined}- >- <FormTextBox- inputRef={codeRef}- currentValue={code}- onChange={(value) => setCode(value.replace(/\D/g, "").slice(0, 6))}- inputMode="numeric"- autoComplete="one-time-code"- placeholder={t("multi_factor_authentication.totp_enroll_code_placeholder")}- maxLength={6}- />- </FormGroup>+ <Button text={t("multi_factor_authentication.totp_enroll_cancel")} onClick={onHidden} />+ <Button+ text={t("multi_factor_authentication.totp_enroll_verify")}+ kind="primary"+ disabled={!secret || code.length === 0 || verifying}+ /></>}+ >+ {inRecoveryStep+ ? <TotpRecoveryStep codes={recoveryCodes} acknowledged={acknowledged} setAcknowledged={setAcknowledged} />+ : loadFailed+ ? <Admonition type="caution">{t("multi_factor_authentication.totp_enroll_generate_error")}</Admonition>+ : <TotpVerifyStep secret={secret} code={code} setCode={setCode} codeRejected={codeRejected} codeRef={codeRef} />}</Modal>);}+/** Step 1: show the generated secret and collect a verification code from the user's authenticator. */+function TotpVerifyStep({ secret, code, setCode, codeRejected, codeRef }: {+ secret?: string,+ code: string,+ setCode: (value: string) => void,+ codeRejected: boolean,+ codeRef: RefObject<HTMLInputElement>+}) {+ return (+ <>+ <FormText>{t("multi_factor_authentication.totp_enroll_instructions")}</FormText>++ <FormGroup name="totp-enroll-secret" label={t("multi_factor_authentication.totp_enroll_secret_label")}>+ <FormTextBox+ className="totp-enroll-secret"+ currentValue={secret ?? ""}+ readOnly+ onFocus={(e) => e.currentTarget.select()}+ />+ </FormGroup>++ <Admonition type="caution">{t("multi_factor_authentication.totp_secret_warning")}</Admonition>++ <FormGroup+ name="totp-enroll-code"+ label={t("multi_factor_authentication.totp_enroll_code_label")}+ error={codeRejected ? t("multi_factor_authentication.totp_enroll_invalid_code") : undefined}+ >+ <FormTextBox+ inputRef={codeRef}+ currentValue={code}+ onChange={(value) => setCode(value.replace(/\D/g, "").slice(0, 6))}+ inputMode="numeric"+ autoComplete="one-time-code"+ placeholder={t("multi_factor_authentication.totp_enroll_code_placeholder")}+ maxLength={6}+ />+ </FormGroup>+ </>+ );+}++/** Step 2: present the issued recovery codes with copy/download and require the user to acknowledge saving them. */+function TotpRecoveryStep({ codes, acknowledged, setAcknowledged }: {+ codes: string[],+ acknowledged: boolean,+ setAcknowledged: (value: boolean) => void+}) {+ return (+ <>+ <FormText>{t("multi_factor_authentication.totp_enroll_recovery_instructions")}</FormText>++ <ol className="totp-recovery-codes">+ {codes.map((recoveryCode) => <li key={recoveryCode}><code>{recoveryCode}</code></li>)}+ </ol>++ <div className="totp-recovery-actions">+ <Button+ icon="bx-copy"+ text={t("multi_factor_authentication.totp_enroll_recovery_copy")}+ onClick={() => {+ utils.copyHtmlToClipboard(codes.join("\n"));+ toast.showMessage(t("multi_factor_authentication.totp_enroll_recovery_copied"));+ }}+ />+ <Button+ icon="bx-download"+ text={t("multi_factor_authentication.totp_enroll_recovery_download")}+ onClick={() => downloadRecoveryCodes(codes)}+ />+ </div>++ <Admonition type="caution">+ <Trans i18nKey="multi_factor_authentication.recovery_keys_description_warning" />+ </Admonition>++ <FormCheckbox+ name="totp-recovery-saved"+ label={t("multi_factor_authentication.totp_enroll_saved_ack")}+ currentValue={acknowledged}+ onChange={setAcknowledged}+ />+ </>+ );+}++/** Downloads the recovery codes as a plain-text file. Uses a Blob so it works over HTTP, unlike the clipboard API. */+function downloadRecoveryCodes(codes: string[]) {+ const blob = new Blob([ `${codes.join("\n")}\n` ], { type: "text/plain" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = "trilium-recovery-codes.txt";+ document.body.appendChild(link);+ link.click();+ link.remove();+ URL.revokeObjectURL(url);+}+function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys, onRemoveTotp }: {status?: string[],generatedKeys?: string[],diff --git a/apps/server/src/routes/api/recovery_codes.ts b/apps/server/src/routes/api/recovery_codes.tsindex 3c3c135420..66da2dc3d1 100644--- a/apps/server/src/routes/api/recovery_codes.ts+++ b/apps/server/src/routes/api/recovery_codes.ts@@ -1,6 +1,5 @@import recovery_codes from '../../services/encryption/recovery_codes.js';import type { Request } from 'express';-import { randomBytes } from 'crypto';function setRecoveryCodes(req: Request) {const success = recovery_codes.setRecoveryCodes(req.body.recoveryCodes.join(','));@@ -20,11 +19,7 @@ function checkForRecoveryKeys() {}function generateRecoveryCodes() {- const recoveryKeys = Array.from({ length: 8 }, () => randomBytes(16).toString('base64'));-- recovery_codes.setRecoveryCodes(recoveryKeys.join(','));-- return { success: true, recoveryCodes: recoveryKeys };+ return { success: true, recoveryCodes: recovery_codes.generateRecoveryCodes() };}function getUsedRecoveryCodes() {diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.tsindex 054a518475..7438caa979 100644--- a/apps/server/src/routes/api/totp.spec.ts+++ b/apps/server/src/routes/api/totp.spec.ts@@ -22,7 +22,7 @@ describe("TOTP API", () => {vi.clearAllMocks();mockGenerateSecret.mockReturnValue(SECRET);mockValidate.mockReturnValue(true);- // Start each test with no persisted secret so the persist/not-persist assertions are meaningful.+ // Reset to no persisted secret each test, so persist assertions below are meaningful.cls.init(() => totpEncryption.resetTotpSecret());});@@ -30,30 +30,31 @@ describe("TOTP API", () => {const result = cls.init(() => totpRoute.generateSecret());expect(result.success).toBe(true);expect(result.message).toMatch(/^[A-Z2-7]+$/);- // The secret must not be stored until the user confirms a code for it — otherwise generating- // (then walking away) could enable TOTP for a secret they never set up, locking them out.+ // Generation must not store the secret — that only happens after the user confirms a code.expect(totpRoute.getTOTPStatus().set).toBe(false);});- it("confirmSecret persists the secret when the code is valid", () => {+ it("confirmSecret persists the secret and issues recovery codes when the code is valid", () => {mockValidate.mockReturnValue(true);- const result = cls.init(() => totpRoute.confirmSecret(confirmReq({ secret: SECRET, token: "000000" })));- expect(result).toEqual({ success: true });+ const result = runConfirm({ secret: SECRET, token: "000000" }) as+ { success: boolean; recoveryCodes?: string[] };+ expect(result.success).toBe(true);+ // Recovery codes are issued atomically with enabling TOTP, to be shown as the final step.+ expect(result.recoveryCodes).toHaveLength(8);expect(mockValidate).toHaveBeenCalledWith({ passcode: "000000", secret: SECRET });expect(totpRoute.getTOTPStatus().set).toBe(true);});it("confirmSecret rejects an invalid code and leaves nothing persisted", () => {mockValidate.mockReturnValue(false);- const result = cls.init(() => totpRoute.confirmSecret(confirmReq({ secret: SECRET, token: "999999" })));- expect(result).toEqual({ success: false });+ expect(runConfirm({ secret: SECRET, token: "999999" })).toEqual({ success: false });expect(totpRoute.getTOTPStatus().set).toBe(false);});it("confirmSecret rejects missing secret or token without validating", () => {- expect(cls.init(() => totpRoute.confirmSecret(confirmReq({ token: "000000" })))).toEqual({ success: false });- expect(cls.init(() => totpRoute.confirmSecret(confirmReq({ secret: SECRET })))).toEqual({ success: false });- expect(cls.init(() => totpRoute.confirmSecret(confirmReq({})))).toEqual({ success: false });+ expect(runConfirm({ token: "000000" })).toEqual({ success: false });+ expect(runConfirm({ secret: SECRET })).toEqual({ success: false });+ expect(runConfirm({})).toEqual({ success: false });expect(mockValidate).not.toHaveBeenCalled();expect(totpRoute.getTOTPStatus().set).toBe(false);});@@ -71,6 +72,6 @@ describe("TOTP API", () => {});});-function confirmReq(body: unknown) {- return { body } as unknown as Request;+function runConfirm(body: unknown) {+ return cls.init(() => totpRoute.confirmSecret({ body } as unknown as Request));}diff --git a/apps/server/src/routes/api/totp.ts b/apps/server/src/routes/api/totp.tsindex 20ad0909b9..638c1e792e 100644--- a/apps/server/src/routes/api/totp.ts+++ b/apps/server/src/routes/api/totp.ts@@ -1,6 +1,7 @@-import type { Request } from 'express';+import type { Request } from "express";-import totpService from '../../services/totp.js';+import recoveryCodesService from "../../services/encryption/recovery_codes.js";+import totpService from "../../services/totp.js";function generateTOTPSecret() {return totpService.generateSecret();@@ -10,6 +11,10 @@ function generateTOTPSecret() {* Confirms a freshly generated secret by checking a code the user produced for it, and only then* persists it. This is the gate that prevents enabling TOTP for a secret the user can't actually* generate codes for (which would otherwise lock them out at the next login).+ *+ * On success we also (re)generate the recovery codes so they're issued atomically with enabling+ * TOTP and can be shown as the final enrollment step — the fallback for when the authenticator is+ * lost.*/function confirmTOTPSecret(req: Request) {const secret = req.body?.secret;@@ -24,11 +29,16 @@ function confirmTOTPSecret(req: Request) {}totpService.setSecret(secret);- return { success: true };+ const recoveryCodes = recoveryCodesService.generateRecoveryCodes();+ return { success: true, recoveryCodes };}function getTOTPStatus() {- return { success: true, message: totpService.isTotpEnabled(), set: totpService.checkForTotpSecret() };+ return {+ success: true,+ message: totpService.isTotpEnabled(),+ set: totpService.checkForTotpSecret()+ };}function getSecret() {diff --git a/apps/server/src/services/encryption/recovery_codes.ts b/apps/server/src/services/encryption/recovery_codes.tsindex 323c35ba47..b5a957c04c 100644--- a/apps/server/src/services/encryption/recovery_codes.ts+++ b/apps/server/src/services/encryption/recovery_codes.ts@@ -24,6 +24,13 @@ function setRecoveryCodes(recoveryCodes: string) {return false;}+/** Generates a fresh set of recovery codes, persists them (replacing any existing ones), and returns them. */+function generateRecoveryCodes(): string[] {+ const recoveryCodes = Array.from({ length: 8 }, () => crypto.randomBytes(16).toString('base64'));+ setRecoveryCodes(recoveryCodes.join(','));+ return recoveryCodes;+}+function clearRecoveryCodes() {sql.transactional(() => {optionService.setOption('recoveryCodeInitialVector', '');@@ -88,6 +95,7 @@ function verifyRecoveryCode(recoveryCodeGuess: string) {export default {setRecoveryCodes,+ generateRecoveryCodes,clearRecoveryCodes,getRecoveryCodes,verifyRecoveryCode,diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.tsindex f42320d80f..5a6990f548 100644--- a/apps/server/src/services/totp.spec.ts+++ b/apps/server/src/services/totp.spec.ts@@ -68,8 +68,8 @@ describe("totp", () => {});expect(result?.success).toBe(true);expect(result?.message).toBe(SECRET);- // Generation alone must NOT persist the secret: it only becomes active after the user confirms- // a code for it, which is what prevents an accidental lockout.+ // Generation alone must NOT persist the secret: it only becomes active after the user+ // confirms a code for it, which is what prevents an accidental lockout.expect(totp.checkForTotpSecret()).toBe(false);});@@ -109,7 +109,7 @@ describe("totp", () => {errorSpy.mockRestore();});- it("validateTOTPForSecret validates against the supplied secret, no stored secret needed", () => {+ it("validateTOTPForSecret validates against a supplied secret without a stored one", () => {cls.init(() => {totpEncryption.resetTotpSecret();});diff --git a/apps/server/src/services/totp.ts b/apps/server/src/services/totp.tsindex 3694137273..1c34591c96 100644--- a/apps/server/src/services/totp.ts+++ b/apps/server/src/services/totp.ts@@ -1,21 +1,21 @@-import { options } from '@triliumnext/core';-import { generateSecret as generateRandomSecret, Totp } from 'time2fa';+import { options } from "@triliumnext/core";+import { generateSecret as generateRandomSecret, Totp } from "time2fa";-import recoveryCodesService from './encryption/recovery_codes.js';-import totpEncryptionService from './encryption/totp_encryption.js';+import recoveryCodesService from "./encryption/recovery_codes.js";+import totpEncryptionService from "./encryption/totp_encryption.js";function isTotpEnabled(): boolean {- return options.getOptionOrNull('mfaEnabled') === "true" &&- options.getOptionOrNull('mfaMethod') === "totp" &&+ return options.getOptionOrNull("mfaEnabled") === "true" &&+ options.getOptionOrNull("mfaMethod") === "totp" &&totpEncryptionService.isTotpSecretSet();}/*** Generates a fresh TOTP secret but deliberately does NOT persist it. The caller must first confirm- * the user can produce a valid code for this secret (via {@link validateTOTPForSecret}) and only then- * activate it with {@link setSecret}. Persisting only after this proof-of-possession check prevents- * the user from locking themselves out by enabling TOTP for a secret their authenticator never- * received correctly.+ * the user can produce a valid code for this secret (via {@link validateTOTPForSecret}) and only+ * then activate it with {@link setSecret}. Persisting only after this proof-of-possession check+ * prevents the user from locking themselves out by enabling TOTP for a secret their authenticator+ * never received correctly.*/function generateSecret(): { success: boolean; message?: string } {try {@@ -26,10 +26,10 @@ function generateSecret(): { success: boolean; message?: string } {message: secret};} catch (e) {- console.error('Failed to create TOTP secret:', e);+ console.error("Failed to create TOTP secret:", e);return {success: false,- message: e instanceof Error ? e.message : 'Unknown error occurred'+ message: e instanceof Error ? e.message : "Unknown error occurred"};}}@@ -60,7 +60,7 @@ function validateTOTPForSecret(secret: string, submittedPasscode: string): boolesecret: secret.trim()});} catch (e) {- console.error('Failed to validate TOTP:', e);+ console.error("Failed to validate TOTP:", e);return false;}}@@ -76,8 +76,8 @@ function validateTOTP(submittedPasscode: string): boolean {function resetTotp(): void {totpEncryptionService.resetTotpSecret();recoveryCodesService.clearRecoveryCodes();- options.setOption('mfaEnabled', 'false');- options.setOption('mfaMethod', '');+ options.setOption("mfaEnabled", "false");+ options.setOption("mfaMethod", "");}export default {diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 20300eed22..32b7ba095f 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -144,6 +144,8 @@ export interface TOTPGenerate {export interface TOTPConfirmResponse {/** Whether the submitted code was valid for the secret; on success the secret is now persisted. */success: boolean;+ /** Freshly issued recovery codes, returned only on success so they can be shown once for saving. */+ recoveryCodes?: string[];}export interface TOTPRecoveryKeysResponse {