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): two-column QR enrollment layout; simplify recovery codes to read-only
Elian Doran6b64bc26830d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 22e542ea87..f383e44b9e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1710,12 +1710,14 @@"totp_secret_description_warning": "After generating a new TOTP secret, you will be required to login again with the new TOTP secret.","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 the account 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_scan": "Scan this QR code with your authenticator app:",+ "totp_enroll_instructions": "TOTP won't be enabled until you confirm a valid code below, so you can't lock yourself out by mistake.",+ "totp_enroll_step1_title": "1. Add the account to your authenticator app",+ "totp_enroll_step2_title": "2. Enter the verification code",+ "totp_enroll_scan": "Scan this QR code:","totp_enroll_secret_label": "Can't scan? Enter this code manually","totp_enroll_code_label": "Verification code","totp_enroll_code_placeholder": "000000",- "totp_enroll_verify": "Verify & enable",+ "totp_enroll_verify": "Verify & continue","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.",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 6d8c76a6db..73a802990e 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,13 +40,32 @@color: white;}-/* Enrollment dialog: the scannable QR code, centred above the manual-entry secret. */+/* Enrollment dialog step 1: QR code (left) and the manual-entry secret (right) on one row — two+ ways to add the same account. The QR takes a fixed width; the secret column fills the rest. */+.modal.totp-enrollment-modal .totp-enroll-grid {+ display: grid;+ /* Fixed QR column (180px plate + 2×10px padding) so its caption wraps within it instead of+ stretching the column and squeezing the field. */+ grid-template-columns: 200px 1fr;+ gap: 16px;+ align-items: start;+ margin-block: 12px;+}++/* Step headings ("1. …", "2. …") that break the enrollment flow into clear stages. */+.modal.totp-enrollment-modal .totp-enroll-step-title {+ margin-block: 18px 8px;+ font-size: 1em;+ font-weight: 600;+}++/* The scannable QR code with its caption stacked above it. */.modal.totp-enrollment-modal .totp-enroll-qr {display: flex;flex-direction: column;align-items: center;gap: 8px;- margin-block: 12px;+ text-align: center;}/* The QR itself sits on a white plate with quiet-zone padding so it scans reliably regardless of thediff --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 53eccc2b52..bcd2ea8812 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@@ -130,9 +130,6 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {// The per-code used/unused status loaded from the server (one entry per code). `undefined` means// no recovery codes have been set up yet.const [ recoveryStatus, setRecoveryStatus ] = useState<string[]>();- // 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);@@ -153,21 +150,6 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {setRecoveryStatus(usedResult.usedRecoveryCodes);}, []);- const generateRecoveryKeys = useCallback(async () => {- const result = await server.get<TOTPRecoveryKeysResponse>("totp_recovery/generate");- if (!result.success) {- toast.showError(t("multi_factor_authentication.recovery_keys_error"));- return;- }-- if (result.recoveryCodes) {- setGeneratedKeys(result.recoveryCodes);- }-- // `totp_recovery/generate` already persisted the codes, so no extra `set` round-trip is needed.- await refreshRecoveryKeys();- }, [ refreshRecoveryKeys ]);-// 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.@@ -220,12 +202,11 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {/></OptionsSection>- <TotpRecoveryKeys- status={recoveryStatus}- generatedKeys={generatedKeys}- generateRecoveryKeys={generateRecoveryKeys}- onRemoveTotp={totpStatus?.set ? removeTotp : undefined}- />+ {/* Recovery codes are part of TOTP, so they only appear once a secret is enrolled. They're+ issued during enrollment (and re-issued when the secret is regenerated) — never minted+ standalone — so this is a read-only view. */}+ {totpStatus?.set &&+ <TotpRecoveryKeys status={recoveryStatus} onRemoveTotp={removeTotp} />}{createPortal(<TotpEnrollmentModal@@ -402,17 +383,25 @@ function TotpVerifyStep({ secret, secretUrl, code, setCode, codeRejected, codeRe<><FormText>{t("multi_factor_authentication.totp_enroll_instructions")}</FormText>- {secretUrl && <TotpQrCode url={secretUrl} />}-- <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>+ <h5 className="totp-enroll-step-title">{t("multi_factor_authentication.totp_enroll_step1_title")}</h5>+ <div className="totp-enroll-grid">+ {secretUrl && <TotpQrCode url={secretUrl} />}++ <FormGroup+ className="totp-enroll-secret-group"+ 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>+ </div>+ <h5 className="totp-enroll-step-title">{t("multi_factor_authentication.totp_enroll_step2_title")}</h5><FormGroupname="totp-enroll-code"label={t("multi_factor_authentication.totp_enroll_code_label")}@@ -465,6 +454,23 @@ function TotpRecoveryStep({ codes, acknowledged, setAcknowledged }: {<><FormText>{t("multi_factor_authentication.totp_enroll_recovery_instructions")}</FormText>+ <RecoveryCodesList codes={codes} />++ <FormCheckbox+ name="totp-recovery-saved"+ label={t("multi_factor_authentication.totp_enroll_saved_ack")}+ currentValue={acknowledged}+ onChange={setAcknowledged}+ />+ </>+ );+}++/** The recovery codes themselves, with copy/download actions and the keep-them-safe caution. Shared+ * by enrollment (step 2) and the standalone regenerate flow. */+function RecoveryCodesList({ codes }: { codes: string[] }) {+ return (+ <><ol className="totp-recovery-codes">{codes.map((recoveryCode) => <li key={recoveryCode}><code>{recoveryCode}</code></li>)}</ol>@@ -488,13 +494,6 @@ function TotpRecoveryStep({ codes, acknowledged, setAcknowledged }: {<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}- /></>);}@@ -512,77 +511,40 @@ function downloadRecoveryCodes(codes: string[]) {URL.revokeObjectURL(url);}-function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys, onRemoveTotp }: {+/**+ * Read-only recovery-codes status for an enrolled TOTP, plus the destructive remove-TOTP action.+ * The codes themselves are shown once during enrollment; here we only report how many remain. There's+ * no generate/regenerate action — fresh codes are only issued by (re-)enrolling the secret.+ */+function TotpRecoveryKeys({ status, onRemoveTotp }: {status?: string[],- generatedKeys?: string[],- generateRecoveryKeys: () => Promise<void>,- /** When set, TOTP is configured and a "remove two-factor authentication" action is shown. */- onRemoveTotp?: () => void+ onRemoveTotp: () => void}) {- // Freshly generated in this session: show the plaintext codes once so the user can save them.- if (generatedKeys) {- return (- <OptionsSection title={t("multi_factor_authentication.totp_section_title")}>- <FormText>{t("multi_factor_authentication.recovery_keys_description")}</FormText>-- <Admonition type="caution">- <Trans i18nKey="multi_factor_authentication.recovery_keys_description_warning" />- </Admonition>-- <ol style={{ columnCount: 2 }}>- {generatedKeys.map(key => <li key={key}><code>{key}</code></li>)}- </ol>-- <Button- text={t("multi_factor_authentication.recovery_keys_regenerate")}- onClick={generateRecoveryKeys}- />- </OptionsSection>- );- }-- // Already set up: a compact recovery-codes row (a dot per code showing which are spent, the- // remaining count, and a replace action), followed by the destructive remove-TOTP action.- if (status) {- const remaining = status.filter(isUnusedRecoveryCode).length;- return (- <OptionsSection title={t("multi_factor_authentication.totp_section_title")}>- <OptionsRowWithButton- label={- <span className="recovery-codes-title">- {t("multi_factor_authentication.recovery_keys_label")}- <RecoveryCodeDots status={status} />- </span>- }- description={t("multi_factor_authentication.recovery_keys_remaining", { remaining, total: status.length })}- icon="bx-refresh"- buttonText={t("multi_factor_authentication.recovery_keys_generate_new")}- onClick={generateRecoveryKeys}- />+ const remaining = status?.filter(isUnusedRecoveryCode).length ?? 0;- {onRemoveTotp &&- <OptionsRowWithButton- label={t("multi_factor_authentication.totp_remove_label")}- description={t("multi_factor_authentication.totp_remove_description")}- icon="bx-trash"- buttonClassName="totp-remove-button"- buttonText={t("multi_factor_authentication.totp_remove_button")}- onClick={onRemoveTotp}- />}- </OptionsSection>- );- }-- // Not set up yet: the original empty state with a generate action.return (<OptionsSection title={t("multi_factor_authentication.totp_section_title")}>- <FormText>{t("multi_factor_authentication.recovery_keys_description")}</FormText>-- <p>{t("multi_factor_authentication.recovery_keys_no_key_set")}</p>+ <div className="option-row">+ <div className="option-row-label">+ <span className="recovery-codes-title">+ {t("multi_factor_authentication.recovery_keys_label")}+ {status && status.length > 0 && <RecoveryCodeDots status={status} />}+ </span>+ <small className="option-row-description">+ {status && status.length > 0+ ? t("multi_factor_authentication.recovery_keys_remaining", { remaining, total: status.length })+ : t("multi_factor_authentication.recovery_keys_no_key_set")}+ </small>+ </div>+ </div>- <Button- text={t("multi_factor_authentication.recovery_keys_generate")}- onClick={generateRecoveryKeys}+ <OptionsRowWithButton+ label={t("multi_factor_authentication.totp_remove_label")}+ description={t("multi_factor_authentication.totp_remove_description")}+ icon="bx-trash"+ buttonClassName="totp-remove-button"+ buttonText={t("multi_factor_authentication.totp_remove_button")}+ onClick={onRemoveTotp}/></OptionsSection>);diff --git a/apps/server/src/routes/api/recovery_codes.spec.ts b/apps/server/src/routes/api/recovery_codes.spec.tsindex 5cc9f14159..e12c54aa1f 100644--- a/apps/server/src/routes/api/recovery_codes.spec.ts+++ b/apps/server/src/routes/api/recovery_codes.spec.ts@@ -2,6 +2,7 @@ import { cls } from "@triliumnext/core";import type { Request } from "express";import { describe, expect, it } from "vitest";+import recoveryCodesService from "../../services/encryption/recovery_codes.js";import recoveryCodesRoute from "./recovery_codes.js";describe("Recovery codes API", () => {@@ -12,15 +13,19 @@ describe("Recovery codes API", () => {expect(recoveryCodesRoute.getUsedRecoveryCodes()).toEqual([]);});- it("generates codes, then verifies and marks one as used", () => {- const generated = cls.init(() => recoveryCodesRoute.generateRecoveryCodes());- expect(generated.success).toBe(true);- expect(generated.recoveryCodes).toHaveLength(8);+ it("verifies a code and marks it as used", () => {+ // Recovery codes are issued during TOTP enrollment, not by this route, so seed them via the+ // service to exercise the read/verify endpoints.+ const codes = cls.init(() => {+ const generated = recoveryCodesService.createRecoveryCodes();+ recoveryCodesService.setRecoveryCodes(generated.join(","));+ return generated;+ });+ expect(codes).toHaveLength(8);expect(recoveryCodesRoute.checkForRecoveryKeys()).toEqual({ success: true, keysExist: true });- const guess = generated.recoveryCodes[0];- const verifyReq = { body: { recovery_code_guess: guess } } as unknown as Request;+ const verifyReq = { body: { recovery_code_guess: codes[0] } } as unknown as Request;expect(cls.init(() => recoveryCodesRoute.verifyRecoveryCode(verifyReq))).toEqual({ success: true });// A wrong guess fails.@@ -32,11 +37,4 @@ describe("Recovery codes API", () => {// The used code is replaced by an ISO-ish timestamp; the rest stay as indices.expect(used.usedRecoveryCodes.some(c => /T/.test(c))).toBe(true);});-- it("sets recovery codes from an explicit list", () => {- const codes = Array.from({ length: 3 }, (_, i) => `code-${i}`);- const req = { body: { recoveryCodes: codes } } as unknown as Request;- const result = cls.init(() => recoveryCodesRoute.setRecoveryCodes(req));- expect(result.message).toBe("Recovery codes set!");- });});diff --git a/apps/server/src/routes/api/recovery_codes.ts b/apps/server/src/routes/api/recovery_codes.tsindex 66da2dc3d1..5b072a4a3e 100644--- a/apps/server/src/routes/api/recovery_codes.ts+++ b/apps/server/src/routes/api/recovery_codes.ts@@ -1,11 +1,6 @@import recovery_codes from '../../services/encryption/recovery_codes.js';import type { Request } from 'express';-function setRecoveryCodes(req: Request) {- const success = recovery_codes.setRecoveryCodes(req.body.recoveryCodes.join(','));- return { success: success, message: 'Recovery codes set!' };-}-function verifyRecoveryCode(req: Request) {const success = recovery_codes.verifyRecoveryCode(req.body.recovery_code_guess);@@ -18,10 +13,6 @@ function checkForRecoveryKeys() {};}-function generateRecoveryCodes() {- return { success: true, recoveryCodes: recovery_codes.generateRecoveryCodes() };-}-function getUsedRecoveryCodes() {if (!recovery_codes.isRecoveryCodeSet()) {return []@@ -41,8 +32,6 @@ function getUsedRecoveryCodes() {}export default {- setRecoveryCodes,- generateRecoveryCodes,verifyRecoveryCode,checkForRecoveryKeys,getUsedRecoveryCodesdiff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex bf6b35c78c..d951233d84 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -75,9 +75,7 @@ function register(app: express.Application) {apiRoute(GET, '/api/oauth/status', openID.getOAuthStatus);asyncApiRoute(GET, '/api/oauth/validate', openID.isTokenValid);- apiRoute(PST, '/api/totp_recovery/set', recoveryCodes.setRecoveryCodes);apiRoute(PST, '/api/totp_recovery/verify', recoveryCodes.verifyRecoveryCode);- apiRoute(GET, '/api/totp_recovery/generate', recoveryCodes.generateRecoveryCodes);apiRoute(GET, '/api/totp_recovery/enabled', recoveryCodes.checkForRecoveryKeys);apiRoute(GET, '/api/totp_recovery/used', recoveryCodes.getUsedRecoveryCodes);diff --git a/apps/server/src/services/encryption/recovery_codes.spec.ts b/apps/server/src/services/encryption/recovery_codes.spec.tsindex 9cf4a15193..32536c1d69 100644--- a/apps/server/src/services/encryption/recovery_codes.spec.ts+++ b/apps/server/src/services/encryption/recovery_codes.spec.ts@@ -57,17 +57,6 @@ describe("recovery_codes", () => {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(","));diff --git a/apps/server/src/services/encryption/recovery_codes.ts b/apps/server/src/services/encryption/recovery_codes.tsindex baf78c6500..f1227a0428 100644--- a/apps/server/src/services/encryption/recovery_codes.ts+++ b/apps/server/src/services/encryption/recovery_codes.ts@@ -29,13 +29,6 @@ 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 = createRecoveryCodes();- setRecoveryCodes(recoveryCodes.join(','));- return recoveryCodes;-}-function clearRecoveryCodes() {sql.transactional(() => {optionService.setOption('recoveryCodeInitialVector', '');@@ -101,7 +94,6 @@ function verifyRecoveryCode(recoveryCodeGuess: string) {export default {setRecoveryCodes,createRecoveryCodes,- generateRecoveryCodes,clearRecoveryCodes,getRecoveryCodes,verifyRecoveryCode,