Skip to content

Build your personal knowledge base with Trilium Notes

fix(totp): accept a code from the adjacent time step

José M. Requena Plens0e43d33744b2
diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.ts
index 66fc8490d6..e3f2c162bc 100644
--- a/apps/server/src/services/totp.spec.ts
+++ b/apps/server/src/services/totp.spec.ts
@@ -237,9 +237,37 @@ describe("totp", () => {
vi.setSystemTime(new Date("2026-01-01T00:00:40Z"));
expect(verify(step + 1)).toBe(true);
+ // At step + 2 the window reaches back to step + 1, whose code is already used.
+ vi.setSystemTime(new Date("2026-01-01T00:01:10Z"));
+ expect(verify(step + 1)).toBe(false);
+ // A code from an authenticator one step ahead passes, and after it nothing older does.
+ expect(verify(step + 3)).toBe(true);
+ expect(verify(step + 2)).toBe(false);
+
// Enrolling a secret clears the recorded step.
cls.init(() => totp.setSecret(SECRET));
- expect(verify(step + 1)).toBe(true);
+ expect(verify(step + 2)).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("enrollment accepts a step either side, the wizard only the current one", async () => {
+ const codeFor = await useRealCodes();
+ vi.useFakeTimers({ toFake: [ "Date" ] });
+ try {
+ cls.init(() => totp.setSecret(SECRET));
+ vi.setSystemTime(new Date("2026-01-01T00:00:40Z"));
+ const step = Math.floor(Date.now() / 1000 / 30);
+
+ expect(totp.validateTOTPForSecret(SECRET, codeFor(step - 1))).toBe(true);
+ expect(totp.validateTOTPForSecret(SECRET, codeFor(step + 1))).toBe(true);
+ expect(totp.validateTOTPForSecret(SECRET, codeFor(step - 2))).toBe(false);
+ expect(totp.validateTOTPForSecret(SECRET, codeFor(step + 2))).toBe(false);
+
+ expect(cls.init(() => totp.validateTOTP(codeFor(step)))).toBe(true);
+ expect(cls.init(() => totp.validateTOTP(codeFor(step - 1)))).toBe(false);
+ expect(cls.init(() => totp.validateTOTP(codeFor(step + 1)))).toBe(false);
} finally {
vi.useRealTimers();
}
diff --git a/apps/server/src/services/totp.ts b/apps/server/src/services/totp.ts
index 1a68c0572f..631ee2a0db 100644
--- a/apps/server/src/services/totp.ts
+++ b/apps/server/src/services/totp.ts
@@ -55,18 +55,27 @@ 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 {
+/** Time steps accepted on either side of the current one, so clocks a step apart still agree. */
+const CLOCK_DRIFT_STEPS = 1;
+
+/**
+ * Returns the time step `submittedPasscode` was generated for, or `null` if it matches none of the
+ * steps within `drift` of the current one.
+ */
+function findTimeStep(secret: string, submittedPasscode: string, drift: number): 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;
+ for (let step = currentStep - drift; step <= currentStep + drift; step++) {
+ const code = { passcode: submittedPasscode, secret: secret.trim(), counter: step };
+ if (Hotp.validate(code, config)) return step;
+ }
} catch (e) {
console.error("Failed to validate TOTP:", e);
- return null;
}
+
+ return null;
}
/**
@@ -76,18 +85,18 @@ function findTimeStep(secret: string, submittedPasscode: string): number | null
function validateTOTPForSecret(secret: string, submittedPasscode: string): boolean {
if (!secret) return false;
- return findTimeStep(secret, submittedPasscode) !== null;
+ return findTimeStep(secret, submittedPasscode, CLOCK_DRIFT_STEPS) !== null;
}
/**
- * 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`).
+ * Validates a passcode for the current step only, since it 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;
- return validateTOTPForSecret(secret, submittedPasscode);
+ return findTimeStep(secret, submittedPasscode, 0) !== null;
}
/**
@@ -98,7 +107,7 @@ function verifyTOTP(submittedPasscode: string): boolean {
const secret = getTotpSecret();
if (!secret) return false;
- const step = findTimeStep(secret, submittedPasscode);
+ const step = findTimeStep(secret, submittedPasscode, CLOCK_DRIFT_STEPS);
const lastUsedStep = options.getOptionOrNull("totpLastUsedStep");
if (step === null || (lastUsedStep && step <= Number(lastUsedStep))) return false;