Skip to content

Build your personal knowledge base with Trilium Notes

fix(mfa): defer TOTP activation until enrollment is finished

Elian Doran02ec9e69d4b1
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 0132f62bbf..d1f6480236 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1727,6 +1727,7 @@
"totp_enroll_recovery_download": "Download",
"totp_enroll_saved_ack": "I've saved my recovery codes somewhere safe",
"totp_enroll_finish": "Finish setup",
+ "totp_enroll_enable_error": "Couldn't enable two-factor authentication. Please try again.",
"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.tsx b/apps/client/src/widgets/type_widgets/options/multi_factor_authentication.tsx
index 23e210211a..11b08b6c38 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,6 @@
import "./multi_factor_authentication.css";
-import { OAuthStatus, TOTPConfirmResponse, TOTPGenerate, TOTPRecoveryKeysResponse, TOTPStatus } from "@triliumnext/commons";
+import { OAuthStatus, TOTPEnableResponse, TOTPGenerate, TOTPRecoveryKeysResponse, TOTPStatus, TOTPVerifyResponse } from "@triliumnext/commons";
import { RefObject } from "preact";
import { createPortal } from "preact/compat";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
@@ -183,9 +183,9 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {
await refreshRecoveryKeys();
}, [ refreshRecoveryKeys ]);
- // 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.
+ // Runs once enrollment is committed (the modal's Finish step persisted the secret and the recovery
+ // codes it already showed), 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();
@@ -254,19 +254,19 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {
}
/**
- * Verify-before-enable enrollment dialog with two steps:
+ * Verify-before-enable enrollment dialog with two steps, and crucially nothing is persisted until the
+ * user finishes — so dismissing at any point leaves TOTP exactly as it was:
*
- * 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.
+ * 1. Fetch a fresh secret, show it for the user to add to their authenticator, and require a valid
+ * code (`totp/verify`). This proves possession but commits nothing.
+ * 2. Show the recovery codes `totp/verify` issued so the user can save the fallback they'll need if
+ * they lose their authenticator. Finishing (`totp/enable`) is the single point that persists the
+ * secret + codes and actually enables TOTP.
*/
function TotpEnrollmentModal({ show, onHidden, onComplete }: {
show: boolean,
onHidden: () => void,
- /** Called when the dialog closes after TOTP was enabled, so the surrounding section can refresh. */
+ /** Called when TOTP has been committed (enabled), so the surrounding section can refresh. */
onComplete: () => void
}) {
const [ secret, setSecret ] = useState<string>();
@@ -275,8 +275,11 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
const [ codeRejected, setCodeRejected ] = useState(false);
const [ verifying, setVerifying ] = useState(false);
// Set once verification succeeds: switches the dialog to the "save your recovery codes" step.
+ // Nothing is persisted server-side at this point — the secret and these codes are only committed
+ // when the user finishes (see `enable`), so dismissing here leaves TOTP exactly as it was.
const [ recoveryCodes, setRecoveryCodes ] = useState<string[]>();
const [ acknowledged, setAcknowledged ] = useState(false);
+ const [ enabling, setEnabling ] = useState(false);
const codeRef = useRef<HTMLInputElement>(null);
// Each time the modal opens, reset state and request a fresh secret.
@@ -292,6 +295,7 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
setVerifying(false);
setRecoveryCodes(undefined);
setAcknowledged(false);
+ setEnabling(false);
void server.get<TOTPGenerate>("totp/generate").then((result) => {
if (result.success) {
@@ -309,6 +313,8 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
}
}, [ secret, recoveryCodes ]);
+ // Step 1: check the code against the secret. Persists nothing — on success we only advance to the
+ // recovery-codes step with the codes the server issued.
const verify = useCallback(async () => {
if (!secret || code.length === 0 || verifying) {
return;
@@ -317,7 +323,7 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
setVerifying(true);
setCodeRejected(false);
- const result = await server.post<TOTPConfirmResponse>("totp/confirm", { secret, token: code });
+ const result = await server.post<TOTPVerifyResponse>("totp/verify", { secret, token: code });
setVerifying(false);
if (!result.success) {
@@ -327,20 +333,29 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
return;
}
- // 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;
+ // Step 2 (Finish): the single commit point — persist the secret and recovery codes, enabling TOTP.
+ const enable = useCallback(async () => {
+ if (!secret || !recoveryCodes || !acknowledged || enabling) {
+ return;
+ }
- // 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();
+ setEnabling(true);
+ const result = await server.post<TOTPEnableResponse>("totp/enable", { secret, recoveryCodes });
+ setEnabling(false);
+
+ if (!result.success) {
+ toast.showError(t("multi_factor_authentication.totp_enroll_enable_error"));
+ return;
}
+
+ onComplete();
onHidden();
- }, [ recoveryCodes, onComplete, onHidden ]);
+ }, [ secret, recoveryCodes, acknowledged, enabling, onComplete, onHidden ]);
+
+ const inRecoveryStep = !!recoveryCodes;
return (
<Modal
@@ -350,12 +365,11 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
: t("multi_factor_authentication.totp_enroll_title")}
size="md"
show={show}
- onHidden={handleModalHidden}
+ // Dismissing simply closes; nothing was persisted unless the user finished (see `enable`).
+ onHidden={onHidden}
onSubmit={() => {
if (inRecoveryStep) {
- if (acknowledged) {
- onHidden();
- }
+ void enable();
} else {
void verify();
}
@@ -365,8 +379,8 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
? <Button
text={t("multi_factor_authentication.totp_enroll_finish")}
kind="primary"
- disabled={!acknowledged}
- onClick={onHidden}
+ disabled={!acknowledged || enabling}
+ onClick={() => void enable()}
/>
: <>
<Button text={t("multi_factor_authentication.totp_enroll_cancel")} onClick={onHidden} />
diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.ts
index 7438caa979..98c0e7aa4b 100644
--- a/apps/server/src/routes/api/totp.spec.ts
+++ b/apps/server/src/routes/api/totp.spec.ts
@@ -12,6 +12,7 @@ vi.mock("time2fa", () => ({
Totp: { validate: mockValidate }
}));
+import recoveryCodes from "../../services/encryption/recovery_codes.js";
import totpEncryption from "../../services/encryption/totp_encryption.js";
import totpRoute from "./totp.js";
@@ -22,40 +23,57 @@ describe("TOTP API", () => {
vi.clearAllMocks();
mockGenerateSecret.mockReturnValue(SECRET);
mockValidate.mockReturnValue(true);
- // Reset to no persisted secret each test, so persist assertions below are meaningful.
- cls.init(() => totpEncryption.resetTotpSecret());
+ // Reset secret + codes each test, so the persist assertions below are meaningful.
+ cls.init(() => {
+ totpEncryption.resetTotpSecret();
+ recoveryCodes.clearRecoveryCodes();
+ });
});
it("generates a base32 secret without persisting it", () => {
const result = cls.init(() => totpRoute.generateSecret());
expect(result.success).toBe(true);
expect(result.message).toMatch(/^[A-Z2-7]+$/);
- // Generation must not store the secret — that only happens after the user confirms a code.
+ // Generation must not store the secret — that only happens at enable.
expect(totpRoute.getTOTPStatus().set).toBe(false);
});
- it("confirmSecret persists the secret and issues recovery codes when the code is valid", () => {
+ it("verifySecret issues recovery codes but persists nothing when the code is valid", () => {
mockValidate.mockReturnValue(true);
- const result = runConfirm({ secret: SECRET, token: "000000" }) as
+ const result = runVerify({ 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);
+ // Verifying alone must neither enable TOTP nor store the recovery codes.
+ expect(totpRoute.getTOTPStatus().set).toBe(false);
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);
});
- it("confirmSecret rejects an invalid code and leaves nothing persisted", () => {
+ it("verifySecret rejects an invalid code", () => {
mockValidate.mockReturnValue(false);
- expect(runConfirm({ secret: SECRET, token: "999999" })).toEqual({ success: false });
+ expect(runVerify({ secret: SECRET, token: "999999" })).toEqual({ success: false });
expect(totpRoute.getTOTPStatus().set).toBe(false);
});
- it("confirmSecret rejects missing secret or token without validating", () => {
- expect(runConfirm({ token: "000000" })).toEqual({ success: false });
- expect(runConfirm({ secret: SECRET })).toEqual({ success: false });
- expect(runConfirm({})).toEqual({ success: false });
+ it("verifySecret rejects missing secret or token without validating", () => {
+ expect(runVerify({ token: "000000" })).toEqual({ success: false });
+ expect(runVerify({ secret: SECRET })).toEqual({ success: false });
+ expect(runVerify({})).toEqual({ success: false });
expect(mockValidate).not.toHaveBeenCalled();
+ });
+
+ it("enableSecret commits the secret and recovery codes, activating TOTP", () => {
+ const codes = Array.from({ length: 8 }, (_, i) => `recovery-code-${i}`);
+ expect(runEnable({ secret: SECRET, recoveryCodes: codes })).toEqual({ success: true });
+ expect(totpRoute.getTOTPStatus().set).toBe(true);
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
+ });
+
+ it("enableSecret rejects a missing secret or empty recovery codes without persisting", () => {
+ expect(runEnable({ recoveryCodes: [ "a" ] })).toEqual({ success: false });
+ expect(runEnable({ secret: SECRET })).toEqual({ success: false });
+ expect(runEnable({ secret: SECRET, recoveryCodes: [] })).toEqual({ success: false });
expect(totpRoute.getTOTPStatus().set).toBe(false);
});
@@ -72,6 +90,10 @@ describe("TOTP API", () => {
});
});
-function runConfirm(body: unknown) {
- return cls.init(() => totpRoute.confirmSecret({ body } as unknown as Request));
+function runVerify(body: unknown) {
+ return cls.init(() => totpRoute.verifySecret({ body } as unknown as Request));
+}
+
+function runEnable(body: unknown) {
+ return cls.init(() => totpRoute.enableSecret({ body } as unknown as Request));
}
diff --git a/apps/server/src/routes/api/totp.ts b/apps/server/src/routes/api/totp.ts
index 638c1e792e..04fd4145c1 100644
--- a/apps/server/src/routes/api/totp.ts
+++ b/apps/server/src/routes/api/totp.ts
@@ -8,15 +8,13 @@ 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.
+ * Verifies a freshly generated secret by checking a code the user produced for it, WITHOUT
+ * persisting anything. On success we issue recovery codes (also unpersisted) so they can be shown as
+ * the next enrollment step. The secret only becomes active once {@link enableTOTP} commits it — so
+ * abandoning the flow here (e.g. closing the dialog without saving the recovery codes) leaves TOTP
+ * disabled and can never lock the user out.
*/
-function confirmTOTPSecret(req: Request) {
+function verifyTOTPSecret(req: Request) {
const secret = req.body?.secret;
const token = req.body?.token;
@@ -28,9 +26,27 @@ function confirmTOTPSecret(req: Request) {
return { success: false };
}
+ return { success: true, recoveryCodes: recoveryCodesService.createRecoveryCodes() };
+}
+
+/**
+ * Commits a verified secret together with its recovery codes, activating TOTP. This is the final
+ * enrollment step, reached only after the user confirms they've saved the recovery codes, so this
+ * is the single point where anything is persisted.
+ */
+function enableTOTP(req: Request) {
+ const secret = req.body?.secret;
+ const recoveryCodes = req.body?.recoveryCodes;
+
+ const hasSecret = typeof secret === "string" && secret.length > 0;
+ const hasCodes = Array.isArray(recoveryCodes) && recoveryCodes.length > 0;
+ if (!hasSecret || !hasCodes) {
+ return { success: false };
+ }
+
totpService.setSecret(secret);
- const recoveryCodes = recoveryCodesService.generateRecoveryCodes();
- return { success: true, recoveryCodes };
+ recoveryCodesService.setRecoveryCodes(recoveryCodes.join(","));
+ return { success: true };
}
function getTOTPStatus() {
@@ -52,7 +68,8 @@ function resetTOTP() {
export default {
generateSecret: generateTOTPSecret,
- confirmSecret: confirmTOTPSecret,
+ verifySecret: verifyTOTPSecret,
+ enableSecret: enableTOTP,
getTOTPStatus,
getSecret,
resetTOTP
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 449cf90d59..bf6b35c78c 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -66,7 +66,8 @@ function register(app: express.Application) {
apiRoute(GET, '/api/totp/generate', totp.generateSecret);
- apiRoute(PST, '/api/totp/confirm', totp.confirmSecret);
+ apiRoute(PST, '/api/totp/verify', totp.verifySecret);
+ apiRoute(PST, '/api/totp/enable', totp.enableSecret);
apiRoute(GET, '/api/totp/status', totp.getTOTPStatus);
apiRoute(GET, '/api/totp/get', totp.getSecret);
apiRoute(PST, '/api/totp/reset', totp.resetTOTP);
diff --git a/apps/server/src/services/encryption/recovery_codes.spec.ts b/apps/server/src/services/encryption/recovery_codes.spec.ts
index af3d0773ed..9cf4a15193 100644
--- a/apps/server/src/services/encryption/recovery_codes.spec.ts
+++ b/apps/server/src/services/encryption/recovery_codes.spec.ts
@@ -23,16 +23,16 @@ describe("recovery_codes", () => {
expect(recoveryCodes.getRecoveryCodes()).toEqual([]);
cls.init(() => {
- recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));
+ recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));
});
expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
- expect(recoveryCodes.getRecoveryCodes()).toEqual([CODE_A, CODE_B]);
+ expect(recoveryCodes.getRecoveryCodes()).toEqual([ CODE_A, CODE_B ]);
});
it("clearRecoveryCodes wipes the stored codes", () => {
cls.init(() => {
- recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));
+ recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));
});
expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
@@ -44,9 +44,33 @@ describe("recovery_codes", () => {
expect(recoveryCodes.getRecoveryCodes()).toEqual([]);
});
+ it("createRecoveryCodes returns 8 well-formed codes without persisting them", () => {
+ cls.init(() => {
+ recoveryCodes.clearRecoveryCodes();
+ });
+
+ const codes = recoveryCodes.createRecoveryCodes();
+ expect(codes).toHaveLength(8);
+ // Each code matches the verification format (24 chars ending in "==").
+ expect(codes.every((c) => /^.{22}==$/.test(c))).toBe(true);
+ // Creating must not store anything — that's what enrollment's "enable" step is for.
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);
+ });
+
+ it("generateRecoveryCodes returns 8 codes and persists them", () => {
+ let codes: string[] = [];
+ cls.init(() => {
+ recoveryCodes.clearRecoveryCodes();
+ codes = recoveryCodes.generateRecoveryCodes();
+ });
+ expect(codes).toHaveLength(8);
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
+ expect(recoveryCodes.getRecoveryCodes()).toEqual(codes);
+ });
+
it("rejects codes failing the format regex without consuming a code", () => {
cls.init(() => {
- recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));
+ recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));
});
let result: boolean | undefined;
@@ -55,12 +79,12 @@ describe("recovery_codes", () => {
});
expect(result).toBe(false);
// both codes still present
- expect(recoveryCodes.getRecoveryCodes()).toEqual([CODE_A, CODE_B]);
+ expect(recoveryCodes.getRecoveryCodes()).toEqual([ CODE_A, CODE_B ]);
});
it("matches a valid code, consumes it (replaced with a date), and rejects reuse", () => {
cls.init(() => {
- recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));
+ recoveryCodes.setRecoveryCodes([ CODE_A, CODE_B ].join(","));
});
let firstMatch: boolean | undefined;
diff --git a/apps/server/src/services/encryption/recovery_codes.ts b/apps/server/src/services/encryption/recovery_codes.ts
index b5a957c04c..baf78c6500 100644
--- a/apps/server/src/services/encryption/recovery_codes.ts
+++ b/apps/server/src/services/encryption/recovery_codes.ts
@@ -24,9 +24,14 @@ function setRecoveryCodes(recoveryCodes: string) {
return false;
}
+/** Generates a fresh set of recovery codes WITHOUT persisting them (the caller decides when to commit). */
+function createRecoveryCodes(): string[] {
+ return Array.from({ length: 8 }, () => crypto.randomBytes(16).toString('base64'));
+}
+
/** 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'));
+ const recoveryCodes = createRecoveryCodes();
setRecoveryCodes(recoveryCodes.join(','));
return recoveryCodes;
}
@@ -95,6 +100,7 @@ function verifyRecoveryCode(recoveryCodeGuess: string) {
export default {
setRecoveryCodes,
+ createRecoveryCodes,
generateRecoveryCodes,
clearRecoveryCodes,
getRecoveryCodes,
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 32b7ba095f..15a46779f5 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -141,13 +141,18 @@ export interface TOTPGenerate {
message: string;
}
-export interface TOTPConfirmResponse {
- /** Whether the submitted code was valid for the secret; on success the secret is now persisted. */
+export interface TOTPVerifyResponse {
+ /** Whether the submitted code was valid for the secret. Verification persists nothing on its own. */
success: boolean;
- /** Freshly issued recovery codes, returned only on success so they can be shown once for saving. */
+ /** Freshly issued (not yet persisted) recovery codes, returned only on success for the user to save. */
recoveryCodes?: string[];
}
+export interface TOTPEnableResponse {
+ /** Whether the secret and recovery codes were committed, activating TOTP. */
+ success: boolean;
+}
+
export interface TOTPRecoveryKeysResponse {
success: boolean;
recoveryCodes?: string[];