Skip to content

Build your personal knowledge base with Trilium Notes

feat(mfa): add a regenerate action for TOTP recovery codes

Elian Doran1fa145c4f7e3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f383e44b9e..c07f342b0b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1736,15 +1736,15 @@
"totp_remove_button": "Remove",
"totp_remove_confirm": "Permanently remove two-factor authentication? This erases your setup, not just switches it off, so you'd have to set it up again from scratch to use it. Until then, you'll sign in with just your password.",
"totp_removed": "Two-factor authentication has been removed.",
- "recovery_keys_description": "Single sign-on recovery keys are used to login in the even you cannot access your Authenticator codes.",
"recovery_keys_description_warning": "Recovery keys won't be shown again after leaving the page, keep them somewhere safe and secure.<br>After a recovery key is used it cannot be used again.",
"recovery_keys_error": "Error generating recovery codes",
"recovery_keys_no_key_set": "No recovery codes set",
- "recovery_keys_generate": "Generate Recovery Codes",
- "recovery_keys_regenerate": "Regenerate Recovery Codes",
+ "recovery_keys_regenerate": "Regenerate recovery codes",
+ "recovery_keys_regenerate_confirm": "Regenerate recovery codes? Your current recovery codes will stop working immediately, and you'll need to save the new ones.",
+ "recovery_keys_regenerated_instructions": "Here are your new recovery codes. Save them now: they replace your previous codes and won't be shown again.",
+ "recovery_keys_done": "Done",
"recovery_keys_label": "Recovery codes",
"recovery_keys_remaining": "{{remaining}} of {{total}} remaining. Can't be shown again, only replaced.",
- "recovery_keys_generate_new": "Generate new",
"recovery_keys_dot_available": "Available",
"recovery_keys_dot_used": "Used on {{date}}",
"oauth_title": "OAuth/OpenID",
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 bcd2ea8812..75c8640a18 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
@@ -132,6 +132,8 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {
const [ recoveryStatus, setRecoveryStatus ] = useState<string[]>();
// Whether the verify-before-enable enrollment modal is open.
const [ showEnroll, setShowEnroll ] = useState(false);
+ // Freshly regenerated recovery codes, shown once so the user can save them (dismissed with "Done").
+ const [ regeneratedCodes, setRegeneratedCodes ] = useState<string[]>();
const refreshRecoveryKeys = useCallback(async () => {
const result = await server.get<TOTPRecoveryKeysResponse>("totp_recovery/enabled");
@@ -172,6 +174,23 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {
refreshRecoveryKeys();
}, [ refreshTotpStatus, refreshRecoveryKeys ]);
+ // Issues a fresh batch of recovery codes for the (already enrolled) secret, replacing the old
+ // ones. The server refuses if no secret is set, so this can't mint codes for an inactive TOTP.
+ const regenerateRecoveryCodes = useCallback(async () => {
+ if (!await dialog.confirm(t("multi_factor_authentication.recovery_keys_regenerate_confirm"))) {
+ return;
+ }
+
+ const result = await server.post<TOTPRecoveryKeysResponse>("totp_recovery/regenerate");
+ if (!result.success || !result.recoveryCodes) {
+ toast.showError(t("multi_factor_authentication.recovery_keys_error"));
+ return;
+ }
+
+ setRegeneratedCodes(result.recoveryCodes);
+ refreshRecoveryKeys();
+ }, [ refreshRecoveryKeys ]);
+
useEffect(() => {
// The TOTP secret status is fetched by the parent; here we only load the recovery codes.
refreshRecoveryKeys();
@@ -202,11 +221,16 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {
/>
</OptionsSection>
- {/* 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. */}
+ {/* Recovery codes are part of TOTP, so they only appear once a secret is enrolled. They can
+ be regenerated for the existing secret, but never minted while TOTP is inactive. */}
{totpStatus?.set &&
- <TotpRecoveryKeys status={recoveryStatus} onRemoveTotp={removeTotp} />}
+ <TotpRecoveryKeys
+ status={recoveryStatus}
+ generatedCodes={regeneratedCodes}
+ onRegenerate={regenerateRecoveryCodes}
+ onDismissGenerated={() => setRegeneratedCodes(undefined)}
+ onRemoveTotp={removeTotp}
+ />}
{createPortal(
<TotpEnrollmentModal
@@ -512,31 +536,49 @@ function downloadRecoveryCodes(codes: string[]) {
}
/**
- * 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.
+ * Recovery-codes management for an enrolled TOTP: a read-only status (how many remain), a confirmed
+ * regenerate action (which replaces the codes for the existing secret), and the destructive
+ * remove-TOTP action. Codes are only ever shown once — right after enrollment or regeneration.
*/
-function TotpRecoveryKeys({ status, onRemoveTotp }: {
+function TotpRecoveryKeys({ status, generatedCodes, onRegenerate, onDismissGenerated, onRemoveTotp }: {
status?: string[],
+ /** Freshly regenerated codes to show once; when set, the section switches to the save-them view. */
+ generatedCodes?: string[],
+ onRegenerate: () => void,
+ onDismissGenerated: () => void,
onRemoveTotp: () => void
}) {
+ // Just regenerated: show the new codes once so the user can save them, then return to the status.
+ if (generatedCodes) {
+ return (
+ <OptionsSection title={t("multi_factor_authentication.totp_section_title")}>
+ <FormText>{t("multi_factor_authentication.recovery_keys_regenerated_instructions")}</FormText>
+
+ <RecoveryCodesList codes={generatedCodes} />
+
+ <Button text={t("multi_factor_authentication.recovery_keys_done")} onClick={onDismissGenerated} />
+ </OptionsSection>
+ );
+ }
+
const remaining = status?.filter(isUnusedRecoveryCode).length ?? 0;
return (
<OptionsSection title={t("multi_factor_authentication.totp_section_title")}>
- <div className="option-row">
- <div className="option-row-label">
+ <OptionsRowWithButton
+ 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>
+ }
+ 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")}
+ icon="bx-refresh"
+ buttonText={t("multi_factor_authentication.recovery_keys_regenerate")}
+ onClick={onRegenerate}
+ />
<OptionsRowWithButton
label={t("multi_factor_authentication.totp_remove_label")}
diff --git a/apps/server/src/routes/api/recovery_codes.spec.ts b/apps/server/src/routes/api/recovery_codes.spec.ts
index e12c54aa1f..22a024b084 100644
--- a/apps/server/src/routes/api/recovery_codes.spec.ts
+++ b/apps/server/src/routes/api/recovery_codes.spec.ts
@@ -3,6 +3,7 @@ import type { Request } from "express";
import { describe, expect, it } from "vitest";
import recoveryCodesService from "../../services/encryption/recovery_codes.js";
+import totpService from "../../services/totp.js";
import recoveryCodesRoute from "./recovery_codes.js";
describe("Recovery codes API", () => {
@@ -37,4 +38,24 @@ 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("regenerateRecoveryCodes refuses when no TOTP secret is set", () => {
+ const result = cls.init(() => {
+ totpService.resetTotp(); // clears any secret + codes
+ return recoveryCodesRoute.regenerateRecoveryCodes();
+ });
+ expect(result.success).toBe(false);
+ expect(result.recoveryCodes).toBeUndefined();
+ expect(recoveryCodesRoute.checkForRecoveryKeys()).toEqual({ success: true, keysExist: false });
+ });
+
+ it("regenerateRecoveryCodes issues and persists fresh codes when a secret is set", () => {
+ const result = cls.init(() => {
+ totpService.setSecret("JBSWY3DPEHPK3PXP");
+ return recoveryCodesRoute.regenerateRecoveryCodes();
+ });
+ expect(result.success).toBe(true);
+ expect(result.recoveryCodes).toHaveLength(8);
+ expect(recoveryCodesRoute.checkForRecoveryKeys()).toEqual({ success: true, keysExist: true });
+ });
});
diff --git a/apps/server/src/routes/api/recovery_codes.ts b/apps/server/src/routes/api/recovery_codes.ts
index 5b072a4a3e..e856b47b20 100644
--- a/apps/server/src/routes/api/recovery_codes.ts
+++ b/apps/server/src/routes/api/recovery_codes.ts
@@ -1,4 +1,5 @@
import recovery_codes from '../../services/encryption/recovery_codes.js';
+import totp from '../../services/totp.js';
import type { Request } from 'express';
function verifyRecoveryCode(req: Request) {
@@ -7,6 +8,21 @@ function verifyRecoveryCode(req: Request) {
return { success: success };
}
+/**
+ * Issues a fresh batch of recovery codes for the already-enrolled TOTP secret, replacing any existing
+ * ones, and returns them for one-time display. Refuses when no TOTP secret is set, so recovery codes
+ * can never be minted for an inactive second factor — the only other way to get codes is enrollment.
+ */
+function regenerateRecoveryCodes() {
+ if (!totp.checkForTotpSecret()) {
+ return { success: false };
+ }
+
+ const recoveryCodes = recovery_codes.createRecoveryCodes();
+ recovery_codes.setRecoveryCodes(recoveryCodes.join(','));
+ return { success: true, recoveryCodes };
+}
+
function checkForRecoveryKeys() {
return {
success: true, keysExist: recovery_codes.isRecoveryCodeSet()
@@ -33,6 +49,7 @@ function getUsedRecoveryCodes() {
export default {
verifyRecoveryCode,
+ regenerateRecoveryCodes,
checkForRecoveryKeys,
getUsedRecoveryCodes
};
\ No newline at end of file
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index d951233d84..02d2143bff 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -76,6 +76,7 @@ function register(app: express.Application) {
asyncApiRoute(GET, '/api/oauth/validate', openID.isTokenValid);
apiRoute(PST, '/api/totp_recovery/verify', recoveryCodes.verifyRecoveryCode);
+ apiRoute(PST, '/api/totp_recovery/regenerate', recoveryCodes.regenerateRecoveryCodes);
apiRoute(GET, '/api/totp_recovery/enabled', recoveryCodes.checkForRecoveryKeys);
apiRoute(GET, '/api/totp_recovery/used', recoveryCodes.getUsedRecoveryCodes);