Skip to content

Build your personal knowledge base with Trilium Notes

fix(mfa): activate TOTP method when committing an enrolled secret

Elian Doran10f2076e9134
diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.ts
index 77f8965be8..304cfe7661 100644
--- a/apps/server/src/routes/api/totp.spec.ts
+++ b/apps/server/src/routes/api/totp.spec.ts
@@ -1,4 +1,4 @@
-import { cls } from "@triliumnext/core";
+import { cls, options } from "@triliumnext/core";
import type { Request } from "express";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -69,9 +69,21 @@ describe("TOTP API", () => {
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(totpRoute.getTOTPStatus().message).toBe(true);
expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);
});
+ it("enableSecret enforces TOTP at login even when the stored mfaMethod is stale", () => {
+ // Simulates an upgraded install where an older resetTotp left mfaMethod = "" behind. The
+ // sign-in dropdown reads "" as "local" and never rewrites it during enrollment, so the
+ // commit itself must select the TOTP method — otherwise isTotpEnabled() stays false and
+ // login would silently skip the second factor the user believes is active.
+ cls.init(() => options.setOption("mfaMethod", ""));
+ const codes = Array.from({ length: 8 }, (_, i) => `recovery-code-${i}`);
+ expect(runEnable({ secret: SECRET, recoveryCodes: codes })).toEqual({ success: true });
+ expect(totpRoute.getTOTPStatus().message).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 });
diff --git a/apps/server/src/routes/api/totp.ts b/apps/server/src/routes/api/totp.ts
index 608d840f7e..e9e30473d7 100644
--- a/apps/server/src/routes/api/totp.ts
+++ b/apps/server/src/routes/api/totp.ts
@@ -1,3 +1,4 @@
+import { options } from "@triliumnext/core";
import type { Request } from "express";
import recoveryCodesService from "../../services/encryption/recovery_codes.js";
@@ -46,6 +47,12 @@ function enableTOTP(req: Request) {
return { success: false };
}
+ // Committing a secret must also select TOTP as the MFA method: login enforcement
+ // (totpService.isTotpEnabled) gates on mfaMethod === "totp", and an upgraded install can carry a
+ // stale value (e.g. the "" an older resetTotp left behind) that the sign-in dropdown never
+ // rewrites while it already reads as "local". Setting it here makes "secret committed" always
+ // imply "TOTP enforced at login".
+ options.setOption("mfaMethod", "totp");
totpService.setSecret(secret);
recoveryCodesService.setRecoveryCodes(recoveryCodes.join(","));
return { success: true };