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
fix(mfa): keep TOTP off after upgrading an install that disabled it, closes #10576
Elian Doran079cf23cc61d
diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.tsindex 2ac1e2cfd5..d9a512d714 100644--- a/apps/server/src/services/totp.spec.ts+++ b/apps/server/src/services/totp.spec.ts@@ -9,7 +9,9 @@ vi.mock("time2fa", () => ({Totp: { generateKey: mockGenerateKey, validate: mockValidate }}));-import { cls, options } from "@triliumnext/core";+import type { OptionNames } from "@triliumnext/commons";+import { becca_loader, cls, options } from "@triliumnext/core";+import migrateDisableTotpWhenMfaWasTurnedOff from "@triliumnext/core/src/migrations/0239__disable_totp_when_mfa_was_turned_off";import recoveryCodes from "./encryption/recovery_codes.js";import totpEncryption from "./encryption/totp_encryption.js";@@ -53,6 +55,66 @@ describe("totp", () => {expect(totp.isTotpEnabled()).toBe(true);});+ /**+ * Regression cover for #10576. Up to v0.103.x, `mfaEnabled` was the master switch and+ * {@link totp.isTotpEnabled} read it alongside the method and the secret:+ *+ * mfaEnabled === "true" && mfaMethod === "totp" && isTotpSecretSet()+ *+ * v0.104.0 removed the enable checkbox (69022d2cb8), making enrollment itself the switch, and+ * dropped the first term. Disabling MFA on v0.103 never cleared the secret — it only set the flag+ * — so an upgraded install can carry a live secret plus `mfaMethod` at its "totp" default. With the+ * flag no longer read, the two surviving terms are both true and TOTP silently switches back on,+ * locking the owner out of the web UI behind a prompt they deliberately turned off.+ *+ * These two tests bracket that: the upgrade must preserve whichever intent the user had recorded.+ */+ describe("upgrading from a v0.103.x install that used mfaEnabled", () => {+ /** Recreates the on-disk state such an install is upgraded with. */+ function seedLegacyInstall(mfaEnabled: "true" | "false") {+ cls.init(() => {+ // `mfaEnabled` was dropped from OptionDefinitions in v0.104.0, so the name has to be cast+ // back in. setOption creates the row when it is missing and writes through becca, leaving+ // it visible whether the migration reads the cache or the table directly.+ options.setOption("mfaEnabled" as OptionNames, mfaEnabled);+ // Both installs kept a usable secret: v0.103's disable path cleared neither.+ totp.setSecret(SECRET);+ // The default, and what any install that enrolled TOTP carries.+ options.setOption("mfaMethod", "totp");+ });+ }++ /**+ * Runs the upgrade the way startup does: the migration first, then becca. The migration works in+ * raw SQL because migrations run before the options cache exists, so the reload is what makes its+ * writes visible to {@link totp.isTotpEnabled} — exactly as the real boot sequence does.+ */+ function upgradeToCurrentVersion() {+ cls.init(() => {+ migrateDisableTotpWhenMfaWasTurnedOff();+ becca_loader.load();+ });+ }++ it("keeps prompting when MFA was left enabled", () => {+ seedLegacyInstall("true");++ upgradeToCurrentVersion();++ expect(totp.isTotpEnabled()).toBe(true);+ });++ it("does not prompt when MFA was explicitly disabled", () => {+ seedLegacyInstall("false");++ upgradeToCurrentVersion();++ // The owner turned MFA off on v0.103 and was never prompted again. An upgrade must not+ // resurrect it from the secret their disable left behind.+ expect(totp.isTotpEnabled()).toBe(false);+ });+ });+it("generateSecret returns a fresh secret and otpauth URL without persisting it", () => {cls.init(() => {totpEncryption.resetTotpSecret();diff --git a/packages/trilium-core/src/migrations/0239__disable_totp_when_mfa_was_turned_off.ts b/packages/trilium-core/src/migrations/0239__disable_totp_when_mfa_was_turned_off.tsnew file mode 100644index 0000000000..7a5bad33ec--- /dev/null+++ b/packages/trilium-core/src/migrations/0239__disable_totp_when_mfa_was_turned_off.ts@@ -0,0 +1,48 @@+import { getSql } from "../services/sql";++/**+ * Restores the intent of anyone who had turned MFA off before v0.104.0 removed the switch that+ * expressed it.+ *+ * Up to v0.103.x, `mfaEnabled` was the master switch and login gated on all three of:+ *+ * mfaEnabled === "true" && mfaMethod === "totp" && isTotpSecretSet()+ *+ * v0.104.0 removed the enable checkbox (69022d2cb8) and made enrolment itself the switch, dropping+ * the first term. But v0.103's disable path only ever set the flag — it never cleared the secret — so+ * an upgraded install can carry a live secret alongside `mfaMethod` at its `"totp"` default. With the+ * flag no longer read, the two surviving terms are both true and TOTP silently switches back on,+ * confronting the owner with a prompt they deliberately turned off and, without an authenticator+ * still enrolled, locking them out of the web UI entirely (#10576).+ *+ * Clearing the secret is the right expression of "off" under the new model, where a secret being set+ * *is* what enables TOTP. Recovery codes are deliberately left alone: they are only ever consulted+ * behind `isTotpEnabled()` (see `verifyTOTP` in services/auth), so they become unreachable along with+ * the secret, and re-enrolling overwrites them anyway.+ *+ * Deliberately raw SQL: migrations run before becca is populated, so the options service is not yet+ * usable here. The rows are read back into the cache when becca loads later in startup.+ */+export default () => {+ const sql = getSql();++ const legacyMfaEnabled = sql.getValue<string | null>(+ "SELECT value FROM options WHERE name = 'mfaEnabled'"+ );++ // Only an explicit "false" is acted on. A missing row means the install predates the flag or has+ // already been migrated, and "true" means MFA was wanted — in both cases enrolment stands.+ if (legacyMfaEnabled === "false") {+ sql.execute(`+ UPDATE options+ SET value = '', utcDateModified = ?+ WHERE name IN ('totpEncryptionSalt', 'totpEncryptedSecret', 'totpVerificationHash')`,+ [new Date().toISOString()]+ );+ }++ // The flag no longer means anything to any version we can upgrade to, so drop it rather than+ // leave a row that reads as meaningful. Options are keyed by name, so this is idempotent.+ sql.execute("DELETE FROM options WHERE name = 'mfaEnabled'");+ sql.execute("DELETE FROM entity_changes WHERE entityName = 'options' AND entityId = 'mfaEnabled'");+};diff --git a/packages/trilium-core/src/migrations/migrations.ts b/packages/trilium-core/src/migrations/migrations.tsindex 237d5ed307..7faf7a9a41 100644--- a/packages/trilium-core/src/migrations/migrations.ts+++ b/packages/trilium-core/src/migrations/migrations.ts@@ -9,6 +9,11 @@ export function getMaxMigrationVersion() {// Migrations should be kept in descending order, so the latest migration is first.export const MIGRATIONS: (SqlMigration | JsMigration)[] = [+ // Turn TOTP back off for installs that had disabled MFA before the enable flag was removed+ {+ version: 239,+ module: () => import("./0239__disable_totp_when_mfa_was_turned_off.js")+ },// Add description column to revisions table for manual revision comments{version: 238,diff --git a/packages/trilium-core/src/test/fixtures/document.db b/packages/trilium-core/src/test/fixtures/document.dbindex 273ae05fe0..5c2ba0797a 100644Binary files a/packages/trilium-core/src/test/fixtures/document.db and b/packages/trilium-core/src/test/fixtures/document.db differ