Skip to content

Build your personal knowledge base with Trilium Notes

feat(mfa): remove the enable checkbox; QR-based TOTP enrollment

Elian Doran69022d2cb89a
diff --git a/apps/client/package.json b/apps/client/package.json
index 45ce08b6ab..216153dfe1 100644
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@ -69,6 +69,7 @@
"mind-elixir": "5.12.2",
"panzoom": "9.4.4",
"preact": "10.29.2",
+ "qrcode-generator": "2.0.4",
"react-i18next": "17.0.8",
"react-window": "2.2.7",
"react-zoom-pan-pinch": "4.0.3",
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index d1f6480236..22e542ea87 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1708,11 +1708,11 @@
"totp_secret_regenerate": "Regenerate TOTP Secret",
"no_totp_secret_warning": "To enable TOTP, you need to generate a TOTP secret first.",
"totp_secret_description_warning": "After generating a new TOTP secret, you will be required to login again with the new TOTP secret.",
- "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.",
"totp_enroll_title": "Confirm your authenticator",
- "totp_enroll_instructions": "Add this secret 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_secret_label": "TOTP secret",
+ "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_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",
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 56ede6e3d9..6d8c76a6db 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,6 +40,32 @@
color: white;
}
+/* Enrollment dialog: the scannable QR code, centred above the manual-entry secret. */
+.modal.totp-enrollment-modal .totp-enroll-qr {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ margin-block: 12px;
+}
+
+/* The QR itself sits on a white plate with quiet-zone padding so it scans reliably regardless of the
+ surrounding theme (QR readers expect dark modules on a light background). The SVG is viewBox-only
+ (scalable), so its size is fixed here. */
+.modal.totp-enrollment-modal .totp-enroll-qr-code {
+ width: 180px;
+ height: 180px;
+ padding: 10px;
+ background: #fff;
+ border-radius: 6px;
+}
+
+.modal.totp-enrollment-modal .totp-enroll-qr-code svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+}
+
/* Enrollment dialog: render the generated secret in a monospace face and space the characters out a
little so the base32 string is easy to read and transcribe into an authenticator app. */
.modal.totp-enrollment-modal .totp-enroll-secret {
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 11b08b6c38..53eccc2b52 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
@@ -3,7 +3,8 @@ import "./multi_factor_authentication.css";
import { OAuthStatus, TOTPEnableResponse, TOTPGenerate, TOTPRecoveryKeysResponse, TOTPStatus, TOTPVerifyResponse } from "@triliumnext/commons";
import { RefObject } from "preact";
import { createPortal } from "preact/compat";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import qrcode from "qrcode-generator";
import { Trans } from "react-i18next";
import dialog from "../../../services/dialog";
@@ -19,15 +20,14 @@ import FormGroup from "../../react/FormGroup";
import { FormInlineRadioGroup } from "../../react/FormRadioGroup";
import FormText from "../../react/FormText";
import FormTextBox from "../../react/FormTextBox";
-import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { useTriliumOption } from "../../react/hooks";
import Modal from "../../react/Modal";
-import RawHtml from "../../react/RawHtml";
+import RawHtml, { RawHtmlBlock } from "../../react/RawHtml";
import OptionsPageHeader from "./components/OptionsPageHeader";
import { OptionsRowWithButton } from "./components/OptionsRow";
import OptionsSection from "./components/OptionsSection";
export default function MultiFactorAuthenticationSettings() {
- const [ mfaEnabled, setMfaEnabled ] = useTriliumOptionBool("mfaEnabled");
const [ mfaMethod, setMfaMethod ] = useTriliumOption("mfaMethod");
const [ totpStatus, setTotpStatus ] = useState<TOTPStatus>();
const [ oauthStatus, setOauthStatus ] = useState<OAuthStatus>();
@@ -41,25 +41,22 @@ export default function MultiFactorAuthenticationSettings() {
server.get<OAuthStatus>("oauth/status").then(setOauthStatus);
}, [ refreshTotpStatus ]);
- // MFA is genuinely active only when it's enabled AND the selected method is fully configured —
- // the enable checkbox alone isn't enough (e.g. enabled with no TOTP secret generated yet). OAuth
- // is "configured" once the server has all its environment variables (no missing vars).
+ // MFA is active when the selected method is fully set up: a TOTP secret has been enrolled, or
+ // OAuth has all its server-side environment variables (no missing vars). There's no separate
+ // enable switch — enrolling a method is what turns it on, and removing it is what turns it off.
const oauthConfigured = (oauthStatus?.missingVars?.length ?? 1) === 0;
- const mfaActive = !!mfaEnabled && (
- (mfaMethod === "totp" && !!totpStatus?.set)
- || (mfaMethod === "oauth" && oauthConfigured)
- );
+ const mfaActive = (mfaMethod === "totp" && !!totpStatus?.set)
+ || (mfaMethod === "oauth" && oauthConfigured);
return (!isElectron()
? (
<>
<OptionsPageHeader actions={<MfaStatusBadge active={mfaActive} />} />
- <EnableMultiFactor mfaEnabled={mfaEnabled} setMfaEnabled={setMfaEnabled} />
- { mfaEnabled && <MultiFactorMethod
+ <MultiFactorMethod
mfaMethod={mfaMethod} setMfaMethod={setMfaMethod}
totpStatus={totpStatus} oauthStatus={oauthStatus}
refreshTotpStatus={refreshTotpStatus}
- /> }
+ />
</>
) : (
<>
@@ -84,20 +81,6 @@ function MfaStatusBadge({ active }: { active: boolean }) {
);
}
-function EnableMultiFactor({ mfaEnabled, setMfaEnabled }: { mfaEnabled: boolean, setMfaEnabled: (newValue: boolean) => Promise<void>}) {
- return (
- <OptionsSection title={t("multi_factor_authentication.title")}>
- <FormText><Trans i18nKey="multi_factor_authentication.description" /></FormText>
-
- <FormCheckbox
- name="mfa-enabled"
- label={t("multi_factor_authentication.mfa_enabled")}
- currentValue={mfaEnabled} onChange={setMfaEnabled}
- />
- </OptionsSection>
- );
-}
-
function MultiFactorMethod({ mfaMethod, setMfaMethod, totpStatus, oauthStatus, refreshTotpStatus }: {
mfaMethod: string,
setMfaMethod: (newValue: string) => Promise<void>,
@@ -113,6 +96,8 @@ function MultiFactorMethod({ mfaMethod, setMfaMethod, totpStatus, oauthStatus, r
return (
<>
+ <FormText><Trans i18nKey="multi_factor_authentication.description" /></FormText>
+
{!methodSetUp &&
<OptionsSection className="mfa-options" title={t("multi_factor_authentication.mfa_method")}>
<FormInlineRadioGroup
@@ -199,8 +184,8 @@ function TotpSettings({ totpStatus, refreshTotpStatus }: {
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.
+ // The secret and recovery codes are gone server-side; refresh so the section drops back to
+ // its "not set up" state (badge inactive, method selector shown) right away.
refreshTotpStatus();
refreshRecoveryKeys();
}, [ refreshTotpStatus, refreshRecoveryKeys ]);
@@ -270,6 +255,8 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
onComplete: () => void
}) {
const [ secret, setSecret ] = useState<string>();
+ // The `otpauth://` URL for the secret, rendered as a scannable QR code alongside the manual secret.
+ const [ secretUrl, setSecretUrl ] = useState<string>();
const [ loadFailed, setLoadFailed ] = useState(false);
const [ code, setCode ] = useState("");
const [ codeRejected, setCodeRejected ] = useState(false);
@@ -289,6 +276,7 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
}
setSecret(undefined);
+ setSecretUrl(undefined);
setLoadFailed(false);
setCode("");
setCodeRejected(false);
@@ -300,6 +288,7 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
void server.get<TOTPGenerate>("totp/generate").then((result) => {
if (result.success) {
setSecret(result.message);
+ setSecretUrl(result.url);
} else {
setLoadFailed(true);
}
@@ -395,14 +384,15 @@ function TotpEnrollmentModal({ show, onHidden, onComplete }: {
? <TotpRecoveryStep codes={recoveryCodes} acknowledged={acknowledged} setAcknowledged={setAcknowledged} />
: loadFailed
? <Admonition type="caution">{t("multi_factor_authentication.totp_enroll_generate_error")}</Admonition>
- : <TotpVerifyStep secret={secret} code={code} setCode={setCode} codeRejected={codeRejected} codeRef={codeRef} />}
+ : <TotpVerifyStep secret={secret} secretUrl={secretUrl} code={code} setCode={setCode} codeRejected={codeRejected} codeRef={codeRef} />}
</Modal>
);
}
/** Step 1: show the generated secret and collect a verification code from the user's authenticator. */
-function TotpVerifyStep({ secret, code, setCode, codeRejected, codeRef }: {
+function TotpVerifyStep({ secret, secretUrl, code, setCode, codeRejected, codeRef }: {
secret?: string,
+ secretUrl?: string,
code: string,
setCode: (value: string) => void,
codeRejected: boolean,
@@ -412,6 +402,8 @@ function TotpVerifyStep({ secret, code, setCode, codeRejected, codeRef }: {
<>
<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"
@@ -421,8 +413,6 @@ function TotpVerifyStep({ secret, code, setCode, codeRejected, codeRef }: {
/>
</FormGroup>
- <Admonition type="caution">{t("multi_factor_authentication.totp_secret_warning")}</Admonition>
-
<FormGroup
name="totp-enroll-code"
label={t("multi_factor_authentication.totp_enroll_code_label")}
@@ -442,6 +432,29 @@ function TotpVerifyStep({ secret, code, setCode, codeRejected, codeRef }: {
);
}
+/**
+ * Renders an `otpauth://` URL as an inline SVG QR code for scanning into an authenticator app. The URL
+ * is generated from our own secret (not user input), so the SVG is trusted and rendered via RawHtml.
+ */
+function TotpQrCode({ url }: { url: string }) {
+ const svg = useMemo(() => {
+ // typeNumber 0 lets the library pick the smallest version that fits; "M" error correction is
+ // the authenticator-app standard. cellSize/margin set the viewBox units — actual display size
+ // is controlled by CSS via the `scalable` (viewBox-only) output.
+ const qr = qrcode(0, "M");
+ qr.addData(url);
+ qr.make();
+ return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
+ }, [ url ]);
+
+ return (
+ <div className="totp-enroll-qr">
+ <FormText>{t("multi_factor_authentication.totp_enroll_scan")}</FormText>
+ <RawHtmlBlock className="totp-enroll-qr-code" html={svg} />
+ </div>
+ );
+}
+
/** Step 2: present the issued recovery codes with copy/download and require the user to acknowledge saving them. */
function TotpRecoveryStep({ codes, acknowledged, setAcknowledged }: {
codes: string[],
diff --git a/apps/server/src/routes/api/login.spec.ts b/apps/server/src/routes/api/login.spec.ts
index 54ae5f02e9..28709a08ad 100644
--- a/apps/server/src/routes/api/login.spec.ts
+++ b/apps/server/src/routes/api/login.spec.ts
@@ -1,4 +1,4 @@
-import { app_info as appInfo, cls, date_utils as dateUtils, options, options as optionService } from "@triliumnext/core";
+import { app_info as appInfo, cls, date_utils as dateUtils, options } from "@triliumnext/core";
import type { Application, Request } from "express";
import supertest from "supertest";
import { beforeAll, describe, expect, it } from "vitest";
@@ -102,7 +102,6 @@ describe("Login (token) API", () => {
it("rejects login when TOTP is enabled and the submitted token is wrong", async () => {
cls.init(() => {
- optionService.setOption("mfaEnabled", "true");
totpService.setSecret("JBSWY3DPEHPK3PXP"); // stores a secret so TOTP counts as enabled
});
diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.ts
index 98c0e7aa4b..77f8965be8 100644
--- a/apps/server/src/routes/api/totp.spec.ts
+++ b/apps/server/src/routes/api/totp.spec.ts
@@ -2,14 +2,13 @@ import { cls } from "@triliumnext/core";
import type { Request } from "express";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { mockGenerateSecret, mockValidate } = vi.hoisted(() => ({
- mockGenerateSecret: vi.fn<() => string>(),
+const { mockGenerateKey, mockValidate } = vi.hoisted(() => ({
+ mockGenerateKey: vi.fn<(opts: { issuer: string; user: string }) => { secret: string; url: string }>(),
mockValidate: vi.fn<(args: { passcode: string; secret: string }) => boolean>()
}));
vi.mock("time2fa", () => ({
- generateSecret: mockGenerateSecret,
- Totp: { validate: mockValidate }
+ Totp: { generateKey: mockGenerateKey, validate: mockValidate }
}));
import recoveryCodes from "../../services/encryption/recovery_codes.js";
@@ -21,7 +20,7 @@ const SECRET = "JBSWY3DPEHPK3PXP";
describe("TOTP API", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockGenerateSecret.mockReturnValue(SECRET);
+ mockGenerateKey.mockReturnValue({ secret: SECRET, url: `otpauth://totp/Trilium:localhost?issuer=Trilium&secret=${SECRET}` });
mockValidate.mockReturnValue(true);
// Reset secret + codes each test, so the persist assertions below are meaningful.
cls.init(() => {
@@ -30,10 +29,13 @@ describe("TOTP API", () => {
});
});
- it("generates a base32 secret without persisting it", () => {
- const result = cls.init(() => totpRoute.generateSecret());
+ it("generates a base32 secret and otpauth URL without persisting it", () => {
+ const result = cls.init(() => totpRoute.generateSecret({ hostname: "localhost" } as Request));
expect(result.success).toBe(true);
expect(result.message).toMatch(/^[A-Z2-7]+$/);
+ expect(result.url).toContain("otpauth://");
+ // The request hostname is used as the account label under the "Trilium" issuer.
+ expect(mockGenerateKey).toHaveBeenCalledWith({ issuer: "Trilium", user: "localhost" });
// Generation must not store the secret — that only happens at enable.
expect(totpRoute.getTOTPStatus().set).toBe(false);
});
diff --git a/apps/server/src/routes/api/totp.ts b/apps/server/src/routes/api/totp.ts
index 04fd4145c1..608d840f7e 100644
--- a/apps/server/src/routes/api/totp.ts
+++ b/apps/server/src/routes/api/totp.ts
@@ -3,8 +3,10 @@ import type { Request } from "express";
import recoveryCodesService from "../../services/encryption/recovery_codes.js";
import totpService from "../../services/totp.js";
-function generateTOTPSecret() {
- return totpService.generateSecret();
+function generateTOTPSecret(req: Request) {
+ // The hostname is only a human-readable account label in the authenticator app (under the
+ // "Trilium" issuer), helping users with several instances tell them apart.
+ return totpService.generateSecret(req.hostname);
}
/**
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index 24b6f1cf2a..09b0dd66ab 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -28,7 +28,6 @@ describe("Auth", () => {
it("goes to login and asks for TOTP if enabled", async () => {
cls.init(() => {
- options.setOption("mfaEnabled", "true");
options.setOption("mfaMethod", "totp");
options.setOption("totpVerificationHash", "hi");
});
@@ -41,7 +40,7 @@ describe("Auth", () => {
it("goes to login and doesn't ask for TOTP is disabled", async () => {
cls.init(() => {
- options.setOption("mfaEnabled", "false");
+ options.setOption("totpVerificationHash", "");
});
const response = await supertest(app)
.get("/")
@@ -59,7 +58,6 @@ describe("Auth", () => {
it("doesn't ask for authentication when disabled, even if TOTP is enabled", async () => {
cls.init(() => {
- options.setOption("mfaEnabled", "true");
options.setOption("mfaMethod", "totp");
options.setOption("totpVerificationHash", "hi");
});
@@ -70,7 +68,7 @@ describe("Auth", () => {
it("doesn't ask for authentication when disabled, with TOTP disabled", async () => {
cls.init(() => {
- options.setOption("mfaEnabled", "false");
+ options.setOption("totpVerificationHash", "");
});
await supertest(app)
.get("/")
diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.ts
index 5a6990f548..2ac1e2cfd5 100644
--- a/apps/server/src/services/totp.spec.ts
+++ b/apps/server/src/services/totp.spec.ts
@@ -1,13 +1,12 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-const { mockGenerateSecret, mockValidate } = vi.hoisted(() => ({
- mockGenerateSecret: vi.fn<() => string>(),
+const { mockGenerateKey, mockValidate } = vi.hoisted(() => ({
+ mockGenerateKey: vi.fn<(opts: { issuer: string; user: string }) => { secret: string; url: string }>(),
mockValidate: vi.fn<(args: { passcode: string; secret: string }) => boolean>()
}));
vi.mock("time2fa", () => ({
- generateSecret: mockGenerateSecret,
- Totp: { validate: mockValidate }
+ Totp: { generateKey: mockGenerateKey, validate: mockValidate }
}));
import { cls, options } from "@triliumnext/core";
@@ -18,6 +17,7 @@ import sql_init from "./sql_init.js";
import totp from "./totp.js";
const SECRET = "JBSWY3DPEHPK3PXP";
+const SECRET_URL = `otpauth://totp/Trilium:host?issuer=Trilium&secret=${SECRET}`;
describe("totp", () => {
beforeAll(async () => {
@@ -27,47 +27,44 @@ describe("totp", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockGenerateSecret.mockReturnValue(SECRET);
+ mockGenerateKey.mockReturnValue({ secret: SECRET, url: SECRET_URL });
mockValidate.mockReturnValue(true);
});
- it("isTotpEnabled requires mfaEnabled+totp method+secret set", () => {
+ it("isTotpEnabled requires totp method + secret set", () => {
+ // method is totp but no secret yet
cls.init(() => {
totpEncryption.resetTotpSecret();
- options.setOption("mfaEnabled", "false");
options.setOption("mfaMethod", "totp");
});
expect(totp.isTotpEnabled()).toBe(false);
+ // secret set, but method is oauth
cls.init(() => {
- options.setOption("mfaEnabled", "true");
options.setOption("mfaMethod", "oauth");
+ totp.setSecret(SECRET);
});
expect(totp.isTotpEnabled()).toBe(false);
- // method is totp + enabled, but no secret yet
+ // method totp + secret set
cls.init(() => {
options.setOption("mfaMethod", "totp");
});
- expect(totp.isTotpEnabled()).toBe(false);
-
- // now persist a secret as well
- cls.init(() => {
- totp.setSecret(SECRET);
- });
expect(totp.isTotpEnabled()).toBe(true);
});
- it("generateSecret returns a fresh secret without persisting it", () => {
+ it("generateSecret returns a fresh secret and otpauth URL without persisting it", () => {
cls.init(() => {
totpEncryption.resetTotpSecret();
});
- let result: { success: boolean; message?: string } | undefined;
+ let result: { success: boolean; message?: string; url?: string } | undefined;
cls.init(() => {
- result = totp.generateSecret();
+ result = totp.generateSecret("host");
});
expect(result?.success).toBe(true);
expect(result?.message).toBe(SECRET);
+ expect(result?.url).toBe(SECRET_URL);
+ expect(mockGenerateKey).toHaveBeenCalledWith({ issuer: "Trilium", user: "host" });
// Generation alone must NOT persist the secret: it only becomes active after the user
// confirms a code for it, which is what prevents an accidental lockout.
expect(totp.checkForTotpSecret()).toBe(false);
@@ -86,7 +83,7 @@ describe("totp", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
// Error instance -> the error's message is surfaced
- mockGenerateSecret.mockImplementation(() => {
+ mockGenerateKey.mockImplementation(() => {
throw new Error("gen failed");
});
let result: { success: boolean; message?: string } | undefined;
@@ -97,7 +94,7 @@ describe("totp", () => {
expect(result?.message).toBe("gen failed");
// non-Error throw -> falls back to a generic message
- mockGenerateSecret.mockImplementation(() => {
+ mockGenerateKey.mockImplementation(() => {
throw "string failure";
});
cls.init(() => {
@@ -159,9 +156,8 @@ describe("totp", () => {
errorSpy.mockRestore();
});
- it("resetTotp clears the secret, recovery codes, and disables MFA", () => {
+ it("resetTotp clears the secret and recovery codes", () => {
cls.init(() => {
- options.setOption("mfaEnabled", "true");
options.setOption("mfaMethod", "totp");
totp.setSecret(SECRET);
recoveryCodes.setRecoveryCodes("AAAAAAAAAAAAAAAAAAAAAA==,BBBBBBBBBBBBBBBBBBBBBB==");
@@ -175,7 +171,5 @@ describe("totp", () => {
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 1c34591c96..01f7192065 100644
--- a/apps/server/src/services/totp.ts
+++ b/apps/server/src/services/totp.ts
@@ -1,12 +1,11 @@
import { options } from "@triliumnext/core";
-import { generateSecret as generateRandomSecret, Totp } from "time2fa";
+import { Totp } from "time2fa";
import recoveryCodesService from "./encryption/recovery_codes.js";
import totpEncryptionService from "./encryption/totp_encryption.js";
function isTotpEnabled(): boolean {
- return options.getOptionOrNull("mfaEnabled") === "true" &&
- options.getOptionOrNull("mfaMethod") === "totp" &&
+ return options.getOptionOrNull("mfaMethod") === "totp" &&
totpEncryptionService.isTotpSecretSet();
}
@@ -16,14 +15,19 @@ function isTotpEnabled(): boolean {
* then activate it with {@link setSecret}. Persisting only after this proof-of-possession check
* prevents the user from locking themselves out by enabling TOTP for a secret their authenticator
* never received correctly.
+ *
+ * Returns both the bare secret (for manual entry) and the `otpauth://` URL the authenticator expects,
+ * which the client renders as a scannable QR code. `accountName` is only the human-readable label
+ * shown next to the "Trilium" issuer in the authenticator app (typically the instance host).
*/
-function generateSecret(): { success: boolean; message?: string } {
+function generateSecret(accountName = "Trilium"): { success: boolean; message?: string; url?: string } {
try {
- const secret = generateRandomSecret();
+ const key = Totp.generateKey({ issuer: "Trilium", user: accountName });
return {
success: true,
- message: secret
+ message: key.secret,
+ url: key.url
};
} catch (e) {
console.error("Failed to create TOTP secret:", e);
@@ -76,8 +80,6 @@ function validateTOTP(submittedPasscode: string): boolean {
function resetTotp(): void {
totpEncryptionService.resetTotpSecret();
recoveryCodesService.clearRecoveryCodes();
- options.setOption("mfaEnabled", "false");
- options.setOption("mfaMethod", "");
}
export default {
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index a812302d6b..156d259cbc 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -90,7 +90,6 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
customDateTimeFormat: string;
// Multi-Factor Authentication
- mfaEnabled: boolean;
mfaMethod: string;
totpEncryptionSalt: string;
totpEncryptedSecret: string;
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 15a46779f5..1420d534ed 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -138,7 +138,10 @@ export interface TOTPStatus {
export interface TOTPGenerate {
success: boolean;
+ /** The bare base32 secret, shown for manual entry. */
message: string;
+ /** The `otpauth://` URL for the secret, rendered as a scannable QR code. Absent on failure. */
+ url?: string;
}
export interface TOTPVerifyResponse {
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 5d3ba8a51c..1c96e88e1c 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -122,7 +122,6 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([
"seenCallToActions",
"experimentalFeatures",
"newLayout",
- "mfaEnabled",
"mfaMethod",
// LLM options
"aiEnabled",
diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.ts
index c8624e03c9..cb0969d14c 100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@ -179,7 +179,6 @@ const defaultOptions: DefaultOption[] = [
{ name: "searchAutocompleteFuzzy", value: "false", isSynced: true },
{ name: "editedNotesOpenInRibbon", value: "true", isSynced: true },
- { name: "mfaEnabled", value: "false", isSynced: false },
{ name: "mfaMethod", value: "totp", isSynced: false },
{ name: "encryptedRecoveryCodes", value: "false", isSynced: false },
{ name: "userSubjectIdentifierSaved", value: "false", isSynced: false },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9f672b7106..093079c33b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -352,6 +352,9 @@ importers:
preact:
specifier: 10.29.2
version: 10.29.2
+ qrcode-generator:
+ specifier: 2.0.4
+ version: 2.0.4
react-i18next:
specifier: 17.0.8
@@ -11804,6 +11807,9 @@ packages:
resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==}
+
resolution: {integrity: sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==}
engines: {node: '>=0.6'}
@@ -27102,6 +27108,8 @@ snapshots:
dependencies:
hookified: 2.2.0
+
dependencies:
side-channel: 1.1.0