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(mfa): verify-before-enable TOTP enrollment; fix status badge accuracy
Elian Doranbbd3138ffa7c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b8e5e74cb7..6768649155 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1708,9 +1708,18 @@"totp_secret_regenerate": "Regenerate TOTP Secret","no_totp_secret_warning": "To enable TOTP, you need to generate a TOTP secret first.","totp_secret_description_warning": "After generating a new TOTP secret, you will be required to login again with the new TOTP secret.",- "totp_secret_generated": "TOTP Secret Generated","totp_secret_warning": "Please save the generated secret in a secure location. It will not be shown again.","totp_secret_regenerate_confirm": "Are you sure you want to regenerate the TOTP secret? This will invalidate previous TOTP secret and all existing recovery codes.",+ "totp_enroll_title": "Confirm your authenticator",+ "totp_enroll_instructions": "Add this secret to your authenticator app, then enter the 6-digit code it generates to confirm. TOTP won't be enabled until the code checks out, so you can't lock yourself out by mistake.",+ "totp_enroll_secret_label": "TOTP secret",+ "totp_enroll_code_label": "Verification code",+ "totp_enroll_code_placeholder": "000000",+ "totp_enroll_verify": "Verify & enable",+ "totp_enroll_cancel": "Cancel",+ "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_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 1f73e87b38..8c8e25279b 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@@ -40,6 +40,13 @@color: white;}+/* Enrollment dialog: render the generated secret in a monospace face and space the characters out a+ little so the base32 string is easy to read and transcribe into an authenticator app. */+.modal.totp-enrollment-modal .totp-enroll-secret {+ font-family: var(--monospace-font-family, monospace);+ letter-spacing: 0.15em;+}+/* 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 88a796e8c3..51503220cb 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,7 +1,8 @@import "./multi_factor_authentication.css";-import { OAuthStatus, TOTPGenerate, TOTPRecoveryKeysResponse, TOTPStatus } from "@triliumnext/commons";-import { useCallback, useEffect, useState } from "preact/hooks";+import { OAuthStatus, TOTPConfirmResponse, TOTPGenerate, TOTPRecoveryKeysResponse, TOTPStatus } from "@triliumnext/commons";+import { createPortal } from "preact/compat";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { Trans } from "react-i18next";import dialog from "../../../services/dialog";@@ -13,9 +14,12 @@ import Admonition from "../../react/Admonition";import { Badge } from "../../react/Badge";import Button from "../../react/Button";import FormCheckbox from "../../react/FormCheckbox";+import FormGroup from "../../react/FormGroup";import { FormInlineRadioGroup } from "../../react/FormRadioGroup";import FormText from "../../react/FormText";+import FormTextBox from "../../react/FormTextBox";import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import Modal from "../../react/Modal";import RawHtml from "../../react/RawHtml";import OptionsPageHeader from "./components/OptionsPageHeader";import { OptionsRowWithButton } from "./components/OptionsRow";@@ -23,13 +27,38 @@ import OptionsSection from "./components/OptionsSection";export default function MultiFactorAuthenticationSettings() {const [ mfaEnabled, setMfaEnabled ] = useTriliumOptionBool("mfaEnabled");+ const [ mfaMethod, setMfaMethod ] = useTriliumOption("mfaMethod");+ const [ totpStatus, setTotpStatus ] = useState<TOTPStatus>();+ const [ oauthStatus, setOauthStatus ] = useState<OAuthStatus>();++ const refreshTotpStatus = useCallback(() => {+ server.get<TOTPStatus>("totp/status").then(setTotpStatus);+ }, []);++ useEffect(() => {+ refreshTotpStatus();+ server.get<OAuthStatus>("oauth/status").then(setOauthStatus);+ }, [ refreshTotpStatus ]);++ // MFA is genuinely active only when it's enabled AND the selected method is fully configured —+ // the enable checkbox alone isn't enough (e.g. enabled with no TOTP secret generated yet). OAuth+ // is "configured" once the server has all its environment variables (no missing vars).+ const oauthConfigured = (oauthStatus?.missingVars?.length ?? 1) === 0;+ const mfaActive = !!mfaEnabled && (+ (mfaMethod === "totp" && !!totpStatus?.set)+ || (mfaMethod === "oauth" && oauthConfigured)+ );return (!isElectron()? (<>- <OptionsPageHeader actions={<MfaStatusBadge mfaEnabled={mfaEnabled} />} />+ <OptionsPageHeader actions={<MfaStatusBadge active={mfaActive} />} /><EnableMultiFactor mfaEnabled={mfaEnabled} setMfaEnabled={setMfaEnabled} />- { mfaEnabled && <MultiFactorMethod /> }+ { mfaEnabled && <MultiFactorMethod+ mfaMethod={mfaMethod} setMfaMethod={setMfaMethod}+ totpStatus={totpStatus} oauthStatus={oauthStatus}+ refreshTotpStatus={refreshTotpStatus}+ /> }</>) : (<>@@ -40,14 +69,14 @@ export default function MultiFactorAuthenticationSettings() {);}-function MfaStatusBadge({ mfaEnabled }: { mfaEnabled: boolean }) {+function MfaStatusBadge({ active }: { active: boolean }) {return (<div className="mfa-header-actions"><Badge- className={`mfa-status-badge ${mfaEnabled ? "active" : "inactive"}`}- icon={mfaEnabled ? "bx bx-check-shield" : "bx bx-shield-x"}- text={mfaEnabled ? t("multi_factor_authentication.status_active") : t("multi_factor_authentication.status_inactive")}- tooltip={mfaEnabled ? t("multi_factor_authentication.status_active_tooltip") : t("multi_factor_authentication.status_inactive_tooltip")}+ className={`mfa-status-badge ${active ? "active" : "inactive"}`}+ icon={active ? "bx bx-check-shield" : "bx bx-shield-x"}+ text={active ? t("multi_factor_authentication.status_active") : t("multi_factor_authentication.status_inactive")}+ tooltip={active ? t("multi_factor_authentication.status_active_tooltip") : t("multi_factor_authentication.status_inactive_tooltip")}outline/></div>@@ -68,20 +97,13 @@ function EnableMultiFactor({ mfaEnabled, setMfaEnabled }: { mfaEnabled: boolean,);}-function MultiFactorMethod() {- const [ mfaMethod, setMfaMethod ] = useTriliumOption("mfaMethod");- const [ totpStatus, setTotpStatus ] = useState<TOTPStatus>();- const [ oauthStatus, setOauthStatus ] = useState<OAuthStatus>();-- const refreshTotpStatus = useCallback(() => {- server.get<TOTPStatus>("totp/status").then(setTotpStatus);- }, []);-- useEffect(() => {- refreshTotpStatus();- server.get<OAuthStatus>("oauth/status").then(setOauthStatus);- }, [ refreshTotpStatus ]);-+function MultiFactorMethod({ mfaMethod, setMfaMethod, totpStatus, oauthStatus, refreshTotpStatus }: {+ mfaMethod: string,+ setMfaMethod: (newValue: string) => Promise<void>,+ totpStatus?: TOTPStatus,+ oauthStatus?: OAuthStatus,+ refreshTotpStatus: () => void+}) {// The method selector only matters during initial setup. Switching method once one is configured// silently strands the existing setup and can leave MFA effectively off (see the remove flow),// so once the current method is set up we hide the selector — removing TOTP (or reconfiguring@@ -125,6 +147,8 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {// The plaintext codes from a generation done in this session, shown once so the user can save// them. Cleared on unmount — they can never be retrieved again, only replaced.const [ generatedKeys, setGeneratedKeys ] = useState<string[]>();+ // Whether the verify-before-enable enrollment modal is open.+ const [ showEnroll, setShowEnroll ] = useState(false);const refreshRecoveryKeys = useCallback(async () => {const result = await server.get<TOTPRecoveryKeysResponse>("totp_recovery/enabled");@@ -160,6 +184,14 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {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 () => {+ toast.showMessage(t("multi_factor_authentication.totp_enroll_enabled"));+ refreshTotpStatus();+ await generateRecoveryKeys();+ }, [ refreshTotpStatus, generateRecoveryKeys ]);+const removeTotp = useCallback(async () => {if (!await dialog.confirm(t("multi_factor_authentication.totp_remove_confirm"))) {return;@@ -194,20 +226,11 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {return;}- const result = await server.get<TOTPGenerate>("totp/generate");- if (!result.success) {- toast.showError(result.message);- return;- }-- await dialog.prompt({- title: t("multi_factor_authentication.totp_secret_generated"),- message: t("multi_factor_authentication.totp_secret_warning"),- defaultValue: result.message,- readOnly: true- });- refreshTotpStatus();- await generateRecoveryKeys();+ // Don't generate-and-persist here. The enrollment modal fetches a secret, has the+ // user confirm a code for it, and only then is it persisted server-side — so a+ // botched setup leaves the existing (or no) secret untouched instead of locking+ // the user out on next login.+ setShowEnroll(true);}}/></OptionsSection>@@ -218,9 +241,140 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {generateRecoveryKeys={generateRecoveryKeys}onRemoveTotp={totpStatus?.set ? removeTotp : undefined}/>++ {createPortal(+ <TotpEnrollmentModal+ show={showEnroll}+ onHidden={() => setShowEnroll(false)}+ onConfirmed={onEnrollmentConfirmed}+ />,+ document.body+ )}</>);}+/**+ * 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.+ */+function TotpEnrollmentModal({ show, onHidden, onConfirmed }: {+ show: boolean,+ onHidden: () => void,+ onConfirmed: () => Promise<void> | 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);+ const codeRef = useRef<HTMLInputElement>(null);++ // Each time the modal opens, reset state and request a fresh secret.+ useEffect(() => {+ if (!show) {+ return;+ }++ setSecret(undefined);+ setLoadFailed(false);+ setCode("");+ setCodeRejected(false);+ setVerifying(false);++ void server.get<TOTPGenerate>("totp/generate").then((result) => {+ if (result.success) {+ setSecret(result.message);+ } else {+ setLoadFailed(true);+ }+ });+ }, [ show ]);++ // Focus the code field once the secret has loaded.+ useEffect(() => {+ if (secret) {+ codeRef.current?.focus();+ }+ }, [ secret ]);++ const verify = useCallback(async () => {+ if (!secret || code.length === 0 || verifying) {+ return;+ }++ setVerifying(true);+ setCodeRejected(false);++ const result = await server.post<TOTPConfirmResponse>("totp/confirm", { secret, token: code });+ setVerifying(false);++ if (!result.success) {+ setCodeRejected(true);+ setCode("");+ codeRef.current?.focus();+ return;+ }++ await onConfirmed();+ onHidden();+ }, [ secret, code, verifying, onConfirmed, onHidden ]);++ return (+ <Modal+ className="totp-enrollment-modal"+ title={t("multi_factor_authentication.totp_enroll_title")}+ size="md"+ show={show}+ onHidden={onHidden}+ onSubmit={() => void verify()}+ stackable+ footer={<>+ <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}+ />+ </>}+ >+ {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>+ </>}+ </Modal>+ );+}+function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys, onRemoveTotp }: {status?: string[],generatedKeys?: string[],diff --git a/apps/server/src/routes/api/login.spec.ts b/apps/server/src/routes/api/login.spec.tsindex 584e184621..54ae5f02e9 100644--- a/apps/server/src/routes/api/login.spec.ts+++ b/apps/server/src/routes/api/login.spec.ts@@ -103,7 +103,7 @@ describe("Login (token) API", () => {it("rejects login when TOTP is enabled and the submitted token is wrong", async () => {cls.init(() => {optionService.setOption("mfaEnabled", "true");- totpService.createSecret(); // stores a secret so TOTP counts as enabled+ totpService.setSecret("JBSWY3DPEHPK3PXP"); // stores a secret so TOTP counts as enabled});const req = { body: { password: "demo1234", totpToken: "000000" } } as unknown as Request;diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.tsindex 696fee65ee..054a518475 100644--- a/apps/server/src/routes/api/totp.spec.ts+++ b/apps/server/src/routes/api/totp.spec.ts@@ -1,15 +1,61 @@import { cls } from "@triliumnext/core";-import { describe, expect, it } from "vitest";+import type { Request } from "express";+import { beforeEach, describe, expect, it, vi } from "vitest";+const { mockGenerateSecret, mockValidate } = vi.hoisted(() => ({+ mockGenerateSecret: vi.fn<() => string>(),+ mockValidate: vi.fn<(args: { passcode: string; secret: string }) => boolean>()+}));++vi.mock("time2fa", () => ({+ generateSecret: mockGenerateSecret,+ Totp: { validate: mockValidate }+}));++import totpEncryption from "../../services/encryption/totp_encryption.js";import totpRoute from "./totp.js";-// totp is disabled by default in the test fixture (no mfaEnabled option),-// so these assert the disabled-state shape plus that a fresh secret is generated.+const SECRET = "JBSWY3DPEHPK3PXP";+describe("TOTP API", () => {- it("generates and stores a base32 secret", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGenerateSecret.mockReturnValue(SECRET);+ mockValidate.mockReturnValue(true);+ // Start each test with no persisted secret so the persist/not-persist assertions are meaningful.+ cls.init(() => totpEncryption.resetTotpSecret());+ });++ 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]+$/);+ // 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.+ expect(totpRoute.getTOTPStatus().set).toBe(false);+ });++ it("confirmSecret persists the secret when the code is valid", () => {+ mockValidate.mockReturnValue(true);+ const result = cls.init(() => totpRoute.confirmSecret(confirmReq({ secret: SECRET, token: "000000" })));+ expect(result).toEqual({ success: true });+ 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(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(mockValidate).not.toHaveBeenCalled();+ expect(totpRoute.getTOTPStatus().set).toBe(false);});it("reports the TOTP status", () => {@@ -24,3 +70,7 @@ describe("TOTP API", () => {expect(result).toBeDefined();});});++function confirmReq(body: unknown) {+ return { body } as unknown as Request;+}diff --git a/apps/server/src/routes/api/totp.ts b/apps/server/src/routes/api/totp.tsindex f83da6ec59..20ad0909b9 100644--- a/apps/server/src/routes/api/totp.ts+++ b/apps/server/src/routes/api/totp.ts@@ -1,7 +1,30 @@+import type { Request } from 'express';+import totpService from '../../services/totp.js';function generateTOTPSecret() {- return totpService.createSecret();+ return totpService.generateSecret();+}++/**+ * 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).+ */+function confirmTOTPSecret(req: Request) {+ const secret = req.body?.secret;+ const token = req.body?.token;++ if (typeof secret !== "string" || !secret || typeof token !== "string" || !token) {+ return { success: false };+ }++ if (!totpService.validateTOTPForSecret(secret, token)) {+ return { success: false };+ }++ totpService.setSecret(secret);+ return { success: true };}function getTOTPStatus() {@@ -19,7 +42,8 @@ function resetTOTP() {export default {generateSecret: generateTOTPSecret,+ confirmSecret: confirmTOTPSecret,getTOTPStatus,getSecret,resetTOTP-};\ No newline at end of file+};diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 6df4fb6a8a..449cf90d59 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -66,6 +66,7 @@ function register(app: express.Application) {apiRoute(GET, '/api/totp/generate', totp.generateSecret);+ apiRoute(PST, '/api/totp/confirm', totp.confirmSecret);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/totp.spec.ts b/apps/server/src/services/totp.spec.tsindex 9f6e680eaf..f42320d80f 100644--- a/apps/server/src/services/totp.spec.ts+++ b/apps/server/src/services/totp.spec.ts@@ -51,28 +51,38 @@ describe("totp", () => {});expect(totp.isTotpEnabled()).toBe(false);- // now set a secret as well+ // now persist a secret as wellcls.init(() => {- totp.createSecret();+ totp.setSecret(SECRET);});expect(totp.isTotpEnabled()).toBe(true);});- it("createSecret stores the generated secret on success", () => {+ it("generateSecret returns a fresh secret without persisting it", () => {cls.init(() => {totpEncryption.resetTotpSecret();});let result: { success: boolean; message?: string } | undefined;cls.init(() => {- result = totp.createSecret();+ result = totp.generateSecret();});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.+ expect(totp.checkForTotpSecret()).toBe(false);+ });++ it("setSecret persists a secret so it can be retrieved", () => {+ cls.init(() => {+ totpEncryption.resetTotpSecret();+ totp.setSecret(SECRET);+ });expect(totp.checkForTotpSecret()).toBe(true);- expect(totp.getTotpSecret()).not.toBeNull();+ expect(totp.getTotpSecret()).toBe(SECRET);});- it("createSecret returns failure when secret generation throws", () => {+ it("generateSecret returns failure when secret generation throws", () => {const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});// Error instance -> the error's message is surfaced@@ -81,7 +91,7 @@ describe("totp", () => {});let result: { success: boolean; message?: string } | undefined;cls.init(() => {- result = totp.createSecret();+ result = totp.generateSecret();});expect(result?.success).toBe(false);expect(result?.message).toBe("gen failed");@@ -91,7 +101,7 @@ describe("totp", () => {throw "string failure";});cls.init(() => {- result = totp.createSecret();+ result = totp.generateSecret();});expect(result?.success).toBe(false);expect(result?.message).toBeTruthy();@@ -99,6 +109,24 @@ describe("totp", () => {errorSpy.mockRestore();});+ it("validateTOTPForSecret validates against the supplied secret, no stored secret needed", () => {+ cls.init(() => {+ totpEncryption.resetTotpSecret();+ });++ mockValidate.mockReturnValue(true);+ expect(totp.validateTOTPForSecret(SECRET, "000000")).toBe(true);+ expect(mockValidate).toHaveBeenCalledWith({ passcode: "000000", secret: SECRET });++ mockValidate.mockReturnValue(false);+ expect(totp.validateTOTPForSecret(SECRET, "000000")).toBe(false);++ // An empty secret short-circuits without invoking the validator.+ mockValidate.mockClear();+ expect(totp.validateTOTPForSecret("", "000000")).toBe(false);+ expect(mockValidate).not.toHaveBeenCalled();+ });+it("validateTOTP returns false when no secret is set", () => {cls.init(() => {totpEncryption.resetTotpSecret();@@ -109,7 +137,7 @@ describe("totp", () => {it("validateTOTP delegates to Totp.validate when a secret is set", () => {cls.init(() => {- totp.createSecret();+ totp.setSecret(SECRET);});mockValidate.mockReturnValue(true);@@ -122,7 +150,7 @@ describe("totp", () => {it("validateTOTP returns false when Totp.validate throws", () => {const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});cls.init(() => {- totp.createSecret();+ totp.setSecret(SECRET);});mockValidate.mockImplementation(() => {throw new Error("invalid");@@ -135,7 +163,7 @@ describe("totp", () => {cls.init(() => {options.setOption("mfaEnabled", "true");options.setOption("mfaMethod", "totp");- totp.createSecret();+ totp.setSecret(SECRET);recoveryCodes.setRecoveryCodes("AAAAAAAAAAAAAAAAAAAAAA==,BBBBBBBBBBBBBBBBBBBBBB==");});expect(totp.checkForTotpSecret()).toBe(true);diff --git a/apps/server/src/services/totp.ts b/apps/server/src/services/totp.tsindex a44d5f3461..3694137273 100644--- a/apps/server/src/services/totp.ts+++ b/apps/server/src/services/totp.ts@@ -1,5 +1,5 @@import { options } from '@triliumnext/core';-import { Totp, generateSecret } from 'time2fa';+import { generateSecret as generateRandomSecret, Totp } from 'time2fa';import recoveryCodesService from './encryption/recovery_codes.js';import totpEncryptionService from './encryption/totp_encryption.js';@@ -10,11 +10,16 @@ function isTotpEnabled(): boolean {totpEncryptionService.isTotpSecretSet();}-function createSecret(): { success: boolean; message?: string } {+/**+ * 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.+ */+function generateSecret(): { success: boolean; message?: string } {try {- const secret = generateSecret();-- totpEncryptionService.setTotpSecret(secret);+ const secret = generateRandomSecret();return {success: true,@@ -29,6 +34,11 @@ function createSecret(): { success: boolean; message?: string } {}}+/** Persists a (previously verified) TOTP secret, making TOTP the active second factor at login. */+function setSecret(secret: string): void {+ totpEncryptionService.setTotpSecret(secret);+}+function getTotpSecret(): string | null {return totpEncryptionService.getTotpSecret();}@@ -37,8 +47,11 @@ function checkForTotpSecret(): boolean {return totpEncryptionService.isTotpSecretSet();}-function validateTOTP(submittedPasscode: string): boolean {- const secret = getTotpSecret();+/**+ * Validates a passcode against an explicitly supplied secret. Used during enrollment to verify the+ * user's authenticator before the secret is persisted (see {@link generateSecret}).+ */+function validateTOTPForSecret(secret: string, submittedPasscode: string): boolean {if (!secret) return false;try {@@ -52,6 +65,14 @@ function validateTOTP(submittedPasscode: string): boolean {}}+/** Validates a passcode against the persisted secret. Used at login. */+function validateTOTP(submittedPasscode: string): boolean {+ const secret = getTotpSecret();+ if (!secret) return false;++ return validateTOTPForSecret(secret, submittedPasscode);+}+function resetTotp(): void {totpEncryptionService.resetTotpSecret();recoveryCodesService.clearRecoveryCodes();@@ -61,9 +82,11 @@ function resetTotp(): void {export default {isTotpEnabled,- createSecret,+ generateSecret,+ setSecret,getTotpSecret,checkForTotpSecret,validateTOTP,+ validateTOTPForSecret,resetTotp};diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex e41d5e3e04..20300eed22 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -141,6 +141,11 @@ export interface TOTPGenerate {message: string;}+export interface TOTPConfirmResponse {+ /** Whether the submitted code was valid for the secret; on success the secret is now persisted. */+ success: boolean;+}+export interface TOTPRecoveryKeysResponse {success: boolean;recoveryCodes?: string[];