Skip to content

Build your personal knowledge base with Trilium Notes

feat(totp): generate 160-bit secrets

Elian Doran4fed35b65b11
diff --git a/apps/client/src/widgets/type_widgets/options/totp.css b/apps/client/src/widgets/type_widgets/options/totp.css
index f01ef43aaa..99aa3c4af4 100644
--- a/apps/client/src/widgets/type_widgets/options/totp.css
+++ b/apps/client/src/widgets/type_widgets/options/totp.css
@@ -18,18 +18,6 @@
color: white;
}
-/* Enrollment dialog step 1: QR code (left) and the manual-entry secret (right) on one row — two
- ways to add the same account. The QR takes a fixed width; the secret column fills the rest. */
-.modal.totp-enrollment-modal .totp-enroll-grid {
- display: grid;
- /* Fixed QR column (180px plate + 2×10px padding) so its caption wraps within it instead of
- stretching the column and squeezing the field. */
- grid-template-columns: 200px 1fr;
- gap: 16px;
- align-items: start;
- margin-block: 12px;
-}
-
/* Step headings ("1. …", "2. …") that break the enrollment flow into clear stages. */
.modal.totp-enrollment-modal .totp-enroll-step-title {
margin-block: 18px 8px;
@@ -43,6 +31,7 @@
flex-direction: column;
align-items: center;
gap: 8px;
+ margin-block: 12px 16px;
text-align: center;
}
@@ -67,7 +56,7 @@
little so the base32 string is easy to read and transcribe into an authenticator app. */
.modal.totp-enrollment-modal .totp-enroll-secret {
font-family: var(--monospace-font-family, monospace);
- letter-spacing: 0.15em;
+ letter-spacing: 0.08em;
}
/* Recovery-codes list (shared by the enrollment dialog and the regenerate dialog): two monospaced
diff --git a/apps/client/src/widgets/type_widgets/options/totp.tsx b/apps/client/src/widgets/type_widgets/options/totp.tsx
index 3941d348fe..8803aba068 100644
--- a/apps/client/src/widgets/type_widgets/options/totp.tsx
+++ b/apps/client/src/widgets/type_widgets/options/totp.tsx
@@ -330,22 +330,20 @@ function TotpVerifyStep({ secret, secretUrl, code, setCode, codeRejected, codeRe
<FormText>{t("multi_factor_authentication.totp_enroll_instructions")}</FormText>
<h5 className="totp-enroll-step-title">{t("multi_factor_authentication.totp_enroll_step1_title")}</h5>
- <div className="totp-enroll-grid">
- {secretUrl && <TotpQrCode url={secretUrl} />}
+ {secretUrl && <TotpQrCode url={secretUrl} />}
- <FormGroup
- className="totp-enroll-secret-group"
- name="totp-enroll-secret"
- label={t("multi_factor_authentication.totp_enroll_secret_label")}
- >
- <FormTextBox
- className="totp-enroll-secret"
- currentValue={secret ?? ""}
- readOnly
- onFocus={(e) => e.currentTarget.select()}
- />
- </FormGroup>
- </div>
+ <FormGroup
+ className="totp-enroll-secret-group"
+ name="totp-enroll-secret"
+ label={t("multi_factor_authentication.totp_enroll_secret_label")}
+ >
+ <FormTextBox
+ className="totp-enroll-secret"
+ currentValue={secret ?? ""}
+ readOnly
+ onFocus={(e) => e.currentTarget.select()}
+ />
+ </FormGroup>
<h5 className="totp-enroll-step-title">{t("multi_factor_authentication.totp_enroll_step2_title")}</h5>
<FormGroup
diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.ts
index fb5810e473..968d7ba45b 100644
--- a/apps/server/src/routes/api/totp.spec.ts
+++ b/apps/server/src/routes/api/totp.spec.ts
@@ -1,9 +1,10 @@
import { cls, options } from "@triliumnext/core";
import type { Request } from "express";
+import type { TotpConfig, TotpOptions } from "time2fa";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { mockGenerateKey, mockValidate } = vi.hoisted(() => ({
- mockGenerateKey: vi.fn<(opts: { issuer: string; user: string }) => { secret: string; url: string }>(),
+ mockGenerateKey: vi.fn<GenerateKey>(),
mockValidate: vi.fn<typeof import("time2fa").Hotp.validate>()
}));
@@ -37,7 +38,8 @@ describe("TOTP API", () => {
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" });
+ expect(mockGenerateKey).toHaveBeenCalledWith(
+ { issuer: "Trilium", user: "localhost" }, expect.anything());
// Generation must not store the secret — that only happens at enable.
expect(totpRoute.getTOTPStatus().set).toBe(false);
});
@@ -114,3 +116,5 @@ function runVerify(body: unknown) {
function runEnable(body: unknown) {
return cls.init(() => totpRoute.enableSecret({ body } as unknown as Request));
}
+
+type GenerateKey = (opts: TotpOptions, config?: TotpConfig) => { secret: string; url: string };
diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.ts
index f56694b87b..0c01dd1173 100644
--- a/apps/server/src/services/totp.spec.ts
+++ b/apps/server/src/services/totp.spec.ts
@@ -1,7 +1,8 @@
+import type { TotpConfig, TotpOptions } from "time2fa";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
const { mockGenerateKey, mockValidate } = vi.hoisted(() => ({
- mockGenerateKey: vi.fn<(opts: { issuer: string; user: string }) => { secret: string; url: string }>(),
+ mockGenerateKey: vi.fn<GenerateKey>(),
mockValidate: vi.fn<typeof import("time2fa").Hotp.validate>()
}));
@@ -128,7 +129,8 @@ describe("totp", () => {
expect(result?.success).toBe(true);
expect(result?.message).toBe(SECRET);
expect(result?.url).toBe(SECRET_URL);
- expect(mockGenerateKey).toHaveBeenCalledWith({ issuer: "Trilium", user: "host" });
+ expect(mockGenerateKey).toHaveBeenCalledWith(
+ { issuer: "Trilium", user: "host" }, { secretSize: 20 });
// 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);
@@ -143,6 +145,23 @@ describe("totp", () => {
expect(totp.getTotpSecret()).toBe(SECRET);
});
+ it("generates 160-bit secrets and still validates older 80-bit ones", async () => {
+ const actual = await vi.importActual<typeof import("time2fa")>("time2fa");
+ mockGenerateKey.mockImplementation((opts, config) => actual.Totp.generateKey(opts, config));
+ mockValidate.mockImplementation(actual.Hotp.validate.bind(actual.Hotp));
+
+ const { message: secret = "", url } = totp.generateSecret("host");
+ expect(secret).toMatch(/^[A-Z2-7]{32}$/);
+ expect(url).toContain(`secret=${secret}`);
+
+ const step = Math.floor(Date.now() / 1000 / 30);
+ for (const enrolled of [ secret, SECRET ]) {
+ const config = actual.generateConfig({ secretSize: enrolled.length * 5 / 8 });
+ const code = actual.Hotp.generatePasscode({ secret: enrolled, counter: step }, config);
+ expect(totp.validateTOTPForSecret(enrolled, code)).toBe(true);
+ }
+ });
+
it("generateSecret returns failure when secret generation throws", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -319,3 +338,5 @@ async function useRealCodes() {
return (counter: number) => actual.Hotp.generatePasscode({ secret: SECRET, counter }, config);
}
+
+type GenerateKey = (opts: TotpOptions, config?: TotpConfig) => { secret: string; url: string };
diff --git a/apps/server/src/services/totp.ts b/apps/server/src/services/totp.ts
index 146d5ef32d..fe4e4772f6 100644
--- a/apps/server/src/services/totp.ts
+++ b/apps/server/src/services/totp.ts
@@ -4,6 +4,12 @@ import { generateConfig, Hotp, Totp } from "time2fa";
import recoveryCodesService from "./encryption/recovery_codes.js";
import totpEncryptionService from "./encryption/totp_encryption.js";
+/**
+ * Bytes in a new secret: 160 bits, the length RFC 4226 (section 4) recommends and the output size
+ * of HMAC-SHA-1. It encodes to 32 base32 characters with no `=` padding.
+ */
+const SECRET_SIZE = 20;
+
function isTotpEnabled(): boolean {
return options.getOptionOrNull("mfaMethod") === "totp" &&
totpEncryptionService.isTotpSecretSet();
@@ -22,7 +28,8 @@ function isTotpEnabled(): boolean {
*/
function generateSecret(accountName = "Trilium"): { success: boolean; message?: string; url?: string } {
try {
- const key = Totp.generateKey({ issuer: "Trilium", user: accountName });
+ const key = Totp.generateKey(
+ { issuer: "Trilium", user: accountName }, { secretSize: SECRET_SIZE });
return {
success: true,
@@ -68,7 +75,7 @@ function findTimeStep(
drift: number,
lastUsedStep = -Infinity
): number | null {
- const config = generateConfig();
+ const config = generateConfig({ secretSize: getSecretSize(secret) });
const currentStep = Math.floor(Date.now() / 1000 / config.period);
const firstStep = Math.max(currentStep - drift, lastUsedStep + 1);
@@ -84,6 +91,14 @@ function findTimeStep(
return null;
}
+/**
+ * Returns the byte length of a base32 `secret`. `Hotp.validate` rejects a secret whose length
+ * differs from `secretSize`, and secrets enrolled before v0.107.0 are 10 bytes long.
+ */
+function getSecretSize(secret: string): number {
+ return Math.floor(secret.trim().replace(/=+$/, "").length * 5 / 8);
+}
+
/**
* Validates a passcode against an explicitly supplied secret. Used during enrollment to verify the
* user's authenticator before the secret is persisted (see {@link generateSecret}).