Skip to content

Build your personal knowledge base with Trilium Notes

fix(totp): accept each code only once at login

José M. Requena Plens0b005d40ffe3
diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.ts
index 304cfe7661..fb5810e473 100644
--- a/apps/server/src/routes/api/totp.spec.ts
+++ b/apps/server/src/routes/api/totp.spec.ts
@@ -4,11 +4,13 @@ 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 }>(),
- mockValidate: vi.fn<(args: { passcode: string; secret: string }) => boolean>()
+ mockValidate: vi.fn<typeof import("time2fa").Hotp.validate>()
}));
-vi.mock("time2fa", () => ({
- Totp: { generateKey: mockGenerateKey, validate: mockValidate }
+vi.mock("time2fa", async (importOriginal) => ({
+ ...await importOriginal<typeof import("time2fa")>(),
+ Totp: { generateKey: mockGenerateKey },
+ Hotp: { validate: mockValidate }
}));
import recoveryCodes from "../../services/encryption/recovery_codes.js";
@@ -46,7 +48,8 @@ describe("TOTP API", () => {
{ success: boolean; recoveryCodes?: string[] };
expect(result.success).toBe(true);
expect(result.recoveryCodes).toHaveLength(8);
- expect(mockValidate).toHaveBeenCalledWith({ passcode: "000000", secret: SECRET });
+ expect(mockValidate).toHaveBeenCalledWith(
+ { passcode: "000000", secret: SECRET, counter: expect.any(Number) }, expect.anything());
// Verifying alone must neither enable TOTP nor store the recovery codes.
expect(totpRoute.getTOTPStatus().set).toBe(false);
expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index f9cc96a55b..aab4b70f34 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -493,7 +493,7 @@ describe("Auth", () => {
it("does not consume a recovery code when the password is wrong", async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(false as never);
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
- const validateSpy = vi.spyOn(totp, "validateTOTP").mockReturnValue(false);
+ const validateSpy = vi.spyOn(totp, "verifyTOTP").mockReturnValue(false);
const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(true);
expect(await verifyLoginCredentials("wrong-password", RECOVERY_CODE)).toBe("password");
@@ -508,7 +508,7 @@ describe("Auth", () => {
it("returns null for a correct password when TOTP is disabled", async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);
- const validateSpy = vi.spyOn(totp, "validateTOTP").mockReturnValue(false);
+ const validateSpy = vi.spyOn(totp, "verifyTOTP").mockReturnValue(false);
expect(await verifyLoginCredentials("correct", "")).toBeNull();
// With TOTP disabled the second factor is skipped entirely.
@@ -518,7 +518,7 @@ describe("Auth", () => {
it("returns null for a correct password with a valid TOTP token, without touching recovery codes", async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
- vi.spyOn(totp, "validateTOTP").mockReturnValue(true);
+ vi.spyOn(totp, "verifyTOTP").mockReturnValue(true);
const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(false);
expect(await verifyLoginCredentials("correct", "123456")).toBeNull();
@@ -529,7 +529,7 @@ describe("Auth", () => {
it("consumes a recovery code only after the password is verified", async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
- vi.spyOn(totp, "validateTOTP").mockReturnValue(false);
+ vi.spyOn(totp, "verifyTOTP").mockReturnValue(false);
const recoverySpy = vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(true);
expect(await verifyLoginCredentials("correct", RECOVERY_CODE)).toBeNull();
@@ -539,7 +539,7 @@ describe("Auth", () => {
it("rejects a correct password paired with an invalid second factor", async () => {
vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);
- vi.spyOn(totp, "validateTOTP").mockReturnValue(false);
+ vi.spyOn(totp, "verifyTOTP").mockReturnValue(false);
vi.spyOn(recoveryCodeService, "verifyRecoveryCode").mockReturnValue(false);
expect(await verifyLoginCredentials("correct", "000000")).toBe("totp");
diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.ts
index 3c16058d4b..0c0fa54706 100644
--- a/apps/server/src/services/auth.ts
+++ b/apps/server/src/services/auth.ts
@@ -300,7 +300,7 @@ export async function verifyLoginCredentials(password: string, totpToken: string
}
function verifyTOTP(submittedTotpToken: string) {
- if (totp.validateTOTP(submittedTotpToken)) {
+ if (totp.verifyTOTP(submittedTotpToken)) {
return true;
}
diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.ts
index d9a512d714..66fc8490d6 100644
--- a/apps/server/src/services/totp.spec.ts
+++ b/apps/server/src/services/totp.spec.ts
@@ -2,11 +2,13 @@ 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 }>(),
- mockValidate: vi.fn<(args: { passcode: string; secret: string }) => boolean>()
+ mockValidate: vi.fn<typeof import("time2fa").Hotp.validate>()
}));
-vi.mock("time2fa", () => ({
- Totp: { generateKey: mockGenerateKey, validate: mockValidate }
+vi.mock("time2fa", async (importOriginal) => ({
+ ...await importOriginal<typeof import("time2fa")>(),
+ Totp: { generateKey: mockGenerateKey },
+ Hotp: { validate: mockValidate }
}));
import type { OptionNames } from "@triliumnext/commons";
@@ -175,7 +177,8 @@ describe("totp", () => {
mockValidate.mockReturnValue(true);
expect(totp.validateTOTPForSecret(SECRET, "000000")).toBe(true);
- expect(mockValidate).toHaveBeenCalledWith({ passcode: "000000", secret: SECRET });
+ expect(mockValidate).toHaveBeenCalledWith(
+ { passcode: "000000", secret: SECRET, counter: expect.any(Number) }, expect.anything());
mockValidate.mockReturnValue(false);
expect(totp.validateTOTPForSecret(SECRET, "000000")).toBe(false);
@@ -194,7 +197,7 @@ describe("totp", () => {
expect(mockValidate).not.toHaveBeenCalled();
});
- it("validateTOTP delegates to Totp.validate when a secret is set", () => {
+ it("validateTOTP delegates to Hotp.validate when a secret is set", () => {
cls.init(() => {
totp.setSecret(SECRET);
});
@@ -206,7 +209,7 @@ describe("totp", () => {
expect(totp.validateTOTP("000000")).toBe(false);
});
- it("validateTOTP returns false when Totp.validate throws", () => {
+ it("validateTOTP returns false when Hotp.validate throws", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
cls.init(() => {
totp.setSecret(SECRET);
@@ -218,6 +221,30 @@ describe("totp", () => {
errorSpy.mockRestore();
});
+ it("verifyTOTP accepts a code only once, while validateTOTP records nothing", async () => {
+ const codeFor = await useRealCodes();
+ const verify = (counter: number) => cls.init(() => totp.verifyTOTP(codeFor(counter)));
+ vi.useFakeTimers({ toFake: [ "Date" ] });
+ try {
+ cls.init(() => totp.setSecret(SECRET));
+ vi.setSystemTime(new Date("2026-01-01T00:00:10Z"));
+ const step = Math.floor(Date.now() / 1000 / 30);
+
+ expect(cls.init(() => totp.validateTOTP(codeFor(step)))).toBe(true);
+ expect(verify(step)).toBe(true);
+ expect(verify(step)).toBe(false);
+
+ vi.setSystemTime(new Date("2026-01-01T00:00:40Z"));
+ expect(verify(step + 1)).toBe(true);
+
+ // Enrolling a secret clears the recorded step.
+ cls.init(() => totp.setSecret(SECRET));
+ expect(verify(step + 1)).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("resetTotp clears the secret and recovery codes", () => {
cls.init(() => {
options.setOption("mfaMethod", "totp");
@@ -235,3 +262,12 @@ describe("totp", () => {
expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);
});
});
+
+/** Routes the mocked `Hotp.validate` to the real one and returns the real code for a time step. */
+async function useRealCodes() {
+ const actual = await vi.importActual<typeof import("time2fa")>("time2fa");
+ const config = actual.generateConfig();
+ mockValidate.mockImplementation(actual.Hotp.validate.bind(actual.Hotp));
+
+ return (counter: number) => actual.Hotp.generatePasscode({ secret: SECRET, counter }, config);
+}
diff --git a/apps/server/src/services/totp.ts b/apps/server/src/services/totp.ts
index 01f7192065..1a68c0572f 100644
--- a/apps/server/src/services/totp.ts
+++ b/apps/server/src/services/totp.ts
@@ -1,5 +1,5 @@
import { options } from "@triliumnext/core";
-import { Totp } from "time2fa";
+import { generateConfig, Hotp, Totp } from "time2fa";
import recoveryCodesService from "./encryption/recovery_codes.js";
import totpEncryptionService from "./encryption/totp_encryption.js";
@@ -38,9 +38,13 @@ function generateSecret(accountName = "Trilium"): { success: boolean; message?:
}
}
-/** Persists a (previously verified) TOTP secret, making TOTP the active second factor at login. */
+/**
+ * Persists a (previously verified) TOTP secret, making TOTP the active second factor at login, and
+ * clears the time step the previous secret last used (see {@link verifyTOTP}).
+ */
function setSecret(secret: string): void {
totpEncryptionService.setTotpSecret(secret);
+ options.setOption("totpLastUsedStep", "");
}
function getTotpSecret(): string | null {
@@ -51,6 +55,20 @@ function checkForTotpSecret(): boolean {
return totpEncryptionService.isTotpSecretSet();
}
+/** Returns the time step `submittedPasscode` was generated for, or `null` if it matches none. */
+function findTimeStep(secret: string, submittedPasscode: string): number | null {
+ const config = generateConfig();
+ const currentStep = Math.floor(Date.now() / 1000 / config.period);
+
+ try {
+ const code = { passcode: submittedPasscode, secret: secret.trim(), counter: currentStep };
+ return Hotp.validate(code, config) ? currentStep : null;
+ } catch (e) {
+ console.error("Failed to validate TOTP:", e);
+ return null;
+ }
+}
+
/**
* 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}).
@@ -58,18 +76,13 @@ function checkForTotpSecret(): boolean {
function validateTOTPForSecret(secret: string, submittedPasscode: string): boolean {
if (!secret) return false;
- try {
- return Totp.validate({
- passcode: submittedPasscode,
- secret: secret.trim()
- });
- } catch (e) {
- console.error("Failed to validate TOTP:", e);
- return false;
- }
+ return findTimeStep(secret, submittedPasscode) !== null;
}
-/** Validates a passcode against the persisted secret. Used at login. */
+/**
+ * Validates a passcode against the persisted secret and records nothing. Used by the setup wizard,
+ * which must not write options while becca is unloaded (see `SetupSecondFactor.verify`).
+ */
function validateTOTP(submittedPasscode: string): boolean {
const secret = getTotpSecret();
if (!secret) return false;
@@ -77,6 +90,22 @@ function validateTOTP(submittedPasscode: string): boolean {
return validateTOTPForSecret(secret, submittedPasscode);
}
+/**
+ * Validates a passcode against the persisted secret and records its time step, so that neither it
+ * nor a code from an earlier step is accepted again (RFC 6238, section 5.2). Used at login.
+ */
+function verifyTOTP(submittedPasscode: string): boolean {
+ const secret = getTotpSecret();
+ if (!secret) return false;
+
+ const step = findTimeStep(secret, submittedPasscode);
+ const lastUsedStep = options.getOptionOrNull("totpLastUsedStep");
+ if (step === null || (lastUsedStep && step <= Number(lastUsedStep))) return false;
+
+ options.setOption("totpLastUsedStep", String(step));
+ return true;
+}
+
function resetTotp(): void {
totpEncryptionService.resetTotpSecret();
recoveryCodesService.clearRecoveryCodes();
@@ -90,5 +119,6 @@ export default {
checkForTotpSecret,
validateTOTP,
validateTOTPForSecret,
+ verifyTOTP,
resetTotp
};
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index ee6f69ff8d..edf7a27a41 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -116,6 +116,7 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
totpEncryptionSalt: string;
totpEncryptedSecret: string;
totpVerificationHash: string;
+ totpLastUsedStep: number;
encryptedRecoveryCodes: boolean;
recoveryCodeInitialVector: string;
recoveryCodeSecurityKey: string;