Skip to content

Build your personal knowledge base with Trilium Notes

feat(mfa): add option to fully remove two-factor authentication

Elian Doran78efff1943fb
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index c05db4fce4..b8e5e74cb7 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1711,7 +1711,12 @@
"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.",
- "recovery_keys_title": "Single Sign-on Recovery Keys",
+ "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.",
+ "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",
diff --git a/apps/client/src/widgets/type_widgets/options/components/OptionsRow.tsx b/apps/client/src/widgets/type_widgets/options/components/OptionsRow.tsx
index e7dfe6517e..39ef9bb459 100644
--- a/apps/client/src/widgets/type_widgets/options/components/OptionsRow.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/OptionsRow.tsx
@@ -98,13 +98,15 @@ interface OptionsRowWithButtonProps {
onClick: () => void;
/** Label of the action button shown on the right of the row. */
buttonText: string;
+ /** Extra class on the action button, e.g. to tint a destructive action. */
+ buttonClassName?: string;
}
/**
* A settings row with passive label/description text and a discrete action button on the right.
* The button — not the whole row — is the affordance, which reads more clearly as clickable.
*/
-export function OptionsRowWithButton({ label, description, icon, disabled, onClick, buttonText }: OptionsRowWithButtonProps) {
+export function OptionsRowWithButton({ label, description, icon, disabled, onClick, buttonText, buttonClassName }: OptionsRowWithButtonProps) {
return (
<div className="option-row">
<div className="option-row-label">
@@ -112,7 +114,7 @@ export function OptionsRowWithButton({ label, description, icon, disabled, onCli
{description && <small className="option-row-description">{description}</small>}
</div>
<div className="option-row-input">
- <Button text={buttonText} icon={icon} disabled={disabled} onClick={onClick} />
+ <Button className={buttonClassName} text={buttonText} icon={icon} disabled={disabled} onClick={onClick} />
</div>
</div>
);
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.css
index 3d8ded2264..1f73e87b38 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
@@ -28,6 +28,18 @@
gap: 10px;
}
+/* Destructive removal action, tinted with the shared danger colour to set it apart. */
+.totp-remove-button.btn {
+ --color: var(--icon-button-danger-color, #d9534f);
+ color: var(--color);
+ border-color: var(--color);
+}
+
+.totp-remove-button.btn:hover {
+ background-color: var(--color);
+ color: white;
+}
+
/* 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.tsx
index 707fe3276b..b0f66d86d0 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
@@ -144,6 +144,19 @@ function TotpSettings() {
await refreshRecoveryKeys();
}, [ refreshRecoveryKeys ]);
+ const removeTotp = useCallback(async () => {
+ if (!await dialog.confirm(t("multi_factor_authentication.totp_remove_confirm"))) {
+ return;
+ }
+
+ await server.post("totp/reset");
+ toast.showMessage(t("multi_factor_authentication.totp_removed"));
+ // mfaEnabled/mfaMethod are reset server-side and sync back over WebSocket, collapsing this
+ // whole section; refresh locally too so the change shows immediately.
+ refreshTotpStatus();
+ refreshRecoveryKeys();
+ }, [ refreshTotpStatus, refreshRecoveryKeys ]);
+
useEffect(() => {
refreshTotpStatus();
refreshRecoveryKeys();
@@ -183,19 +196,26 @@ function TotpSettings() {
/>
</OptionsSection>
- <TotpRecoveryKeys status={recoveryStatus} generatedKeys={generatedKeys} generateRecoveryKeys={generateRecoveryKeys} />
+ <TotpRecoveryKeys
+ status={recoveryStatus}
+ generatedKeys={generatedKeys}
+ generateRecoveryKeys={generateRecoveryKeys}
+ onRemoveTotp={totpStatus?.set ? removeTotp : undefined}
+ />
</>);
}
-function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys }: {
+function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys, onRemoveTotp }: {
status?: string[],
generatedKeys?: string[],
- generateRecoveryKeys: () => Promise<void>
+ generateRecoveryKeys: () => Promise<void>,
+ /** When set, TOTP is configured and a "remove two-factor authentication" action is shown. */
+ 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.recovery_keys_title")}>
+ <OptionsSection title={t("multi_factor_authentication.totp_section_title")}>
<FormText>{t("multi_factor_authentication.recovery_keys_description")}</FormText>
<Admonition type="caution">
@@ -214,12 +234,12 @@ function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys }: {
);
}
- // Already set up: a single compact row whose label carries a dot per code (showing which are
- // spent), with the remaining count as the description and a replace action on the right.
+ // 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.recovery_keys_title")}>
+ <OptionsSection title={t("multi_factor_authentication.totp_section_title")}>
<OptionsRowWithButton
label={
<span className="recovery-codes-title">
@@ -232,13 +252,23 @@ function TotpRecoveryKeys({ status, generatedKeys, generateRecoveryKeys }: {
buttonText={t("multi_factor_authentication.recovery_keys_generate_new")}
onClick={generateRecoveryKeys}
/>
+
+ {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.recovery_keys_title")}>
+ <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>
diff --git a/apps/server/src/routes/api/totp.ts b/apps/server/src/routes/api/totp.ts
index ece982960d..f83da6ec59 100644
--- a/apps/server/src/routes/api/totp.ts
+++ b/apps/server/src/routes/api/totp.ts
@@ -12,8 +12,14 @@ function getSecret() {
return totpService.getTotpSecret();
}
+function resetTOTP() {
+ totpService.resetTotp();
+ return { success: true };
+}
+
export default {
generateSecret: generateTOTPSecret,
getTOTPStatus,
- getSecret
+ getSecret,
+ resetTOTP
};
\ No newline at end of file
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 1241057fac..6df4fb6a8a 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -68,6 +68,7 @@ function register(app: express.Application) {
apiRoute(GET, '/api/totp/generate', totp.generateSecret);
apiRoute(GET, '/api/totp/status', totp.getTOTPStatus);
apiRoute(GET, '/api/totp/get', totp.getSecret);
+ apiRoute(PST, '/api/totp/reset', totp.resetTOTP);
apiRoute(GET, '/api/oauth/status', openID.getOAuthStatus);
asyncApiRoute(GET, '/api/oauth/validate', openID.isTokenValid);
diff --git a/apps/server/src/services/encryption/recovery_codes.spec.ts b/apps/server/src/services/encryption/recovery_codes.spec.ts
index e1d5f0c136..af3d0773ed 100644
--- a/apps/server/src/services/encryption/recovery_codes.spec.ts
+++ b/apps/server/src/services/encryption/recovery_codes.spec.ts
@@ -30,6 +30,20 @@ describe("recovery_codes", () => {
expect(recoveryCodes.getRecoveryCodes()).toEqual([CODE_A, CODE_B]);
});
+ it("clearRecoveryCodes wipes the stored codes", () => {
+ cls.init(() => {
+ recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));
+ });
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
+
+ cls.init(() => {
+ recoveryCodes.clearRecoveryCodes();
+ });
+
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);
+ expect(recoveryCodes.getRecoveryCodes()).toEqual([]);
+ });
+
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.ts
index 3fa22784c1..323c35ba47 100644
--- a/apps/server/src/services/encryption/recovery_codes.ts
+++ b/apps/server/src/services/encryption/recovery_codes.ts
@@ -24,6 +24,16 @@ function setRecoveryCodes(recoveryCodes: string) {
return false;
}
+function clearRecoveryCodes() {
+ sql.transactional(() => {
+ optionService.setOption('recoveryCodeInitialVector', '');
+ optionService.setOption('recoveryCodeSecurityKey', '');
+ optionService.setOption('recoveryCodesEncrypted', '');
+ optionService.setOption('encryptedRecoveryCodes', 'false');
+ return true;
+ });
+}
+
function getRecoveryCodes() {
if (!isRecoveryCodeSet()) {
return []
@@ -78,6 +88,7 @@ function verifyRecoveryCode(recoveryCodeGuess: string) {
export default {
setRecoveryCodes,
+ clearRecoveryCodes,
getRecoveryCodes,
verifyRecoveryCode,
isRecoveryCodeSet
diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.ts
index 349c5786e9..9f6e680eaf 100644
--- a/apps/server/src/services/totp.spec.ts
+++ b/apps/server/src/services/totp.spec.ts
@@ -12,6 +12,7 @@ vi.mock("time2fa", () => ({
import { cls, options } from "@triliumnext/core";
+import recoveryCodes from "./encryption/recovery_codes.js";
import totpEncryption from "./encryption/totp_encryption.js";
import sql_init from "./sql_init.js";
import totp from "./totp.js";
@@ -130,19 +131,22 @@ describe("totp", () => {
errorSpy.mockRestore();
});
- it("resetTotp clears the secret and disables MFA", () => {
+ it("resetTotp clears the secret, recovery codes, and disables MFA", () => {
cls.init(() => {
options.setOption("mfaEnabled", "true");
options.setOption("mfaMethod", "totp");
totp.createSecret();
+ recoveryCodes.setRecoveryCodes("AAAAAAAAAAAAAAAAAAAAAA==,BBBBBBBBBBBBBBBBBBBBBB==");
});
expect(totp.checkForTotpSecret()).toBe(true);
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
cls.init(() => {
totp.resetTotp();
});
expect(totp.checkForTotpSecret()).toBe(false);
+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);
expect(options.getOptionOrNull("mfaEnabled")).toBe("false");
expect(options.getOptionOrNull("mfaMethod")).toBe("");
});
diff --git a/apps/server/src/services/totp.ts b/apps/server/src/services/totp.ts
index 55dad698ed..a44d5f3461 100644
--- a/apps/server/src/services/totp.ts
+++ b/apps/server/src/services/totp.ts
@@ -1,6 +1,7 @@
import { options } from '@triliumnext/core';
import { Totp, generateSecret } from 'time2fa';
+import recoveryCodesService from './encryption/recovery_codes.js';
import totpEncryptionService from './encryption/totp_encryption.js';
function isTotpEnabled(): boolean {
@@ -53,6 +54,7 @@ function validateTOTP(submittedPasscode: string): boolean {
function resetTotp(): void {
totpEncryptionService.resetTotpSecret();
+ recoveryCodesService.clearRecoveryCodes();
options.setOption('mfaEnabled', 'false');
options.setOption('mfaMethod', '');
}