Skip to content

Build your personal knowledge base with Trilium Notes

fix(recovery-codes): report consecutive used codes correctly

Elian Doran5b64f848aac9
diff --git a/apps/server/src/routes/api/recovery_codes.spec.ts b/apps/server/src/routes/api/recovery_codes.spec.ts
index 57803df758..4a775695b7 100644
--- a/apps/server/src/routes/api/recovery_codes.spec.ts
+++ b/apps/server/src/routes/api/recovery_codes.spec.ts
@@ -84,4 +84,24 @@ describe("Recovery codes API", () => {
const newReq = { body: { recovery_code_guess: newCode } } as unknown as Request;
expect(cls.init(() => recoveryCodesRoute.verifyRecoveryCode(newReq))).toEqual({ success: true });
});
+
+ it("getUsedRecoveryCodes marks every consumed code as used, including adjacent ones", () => {
+ // Seed a batch and consume the first TWO codes, which sit next to each other in the stored
+ // order. A used code is stored as a timestamp; an unused one is reported as its numeric index.
+ const codes = cls.init(() => {
+ totpService.setSecret("JBSWY3DPEHPK3PXP");
+ const generated = recoveryCodesService.createRecoveryCodes();
+ recoveryCodesService.setRecoveryCodes(generated.join(","));
+ return generated;
+ });
+ cls.init(() => recoveryCodesService.verifyRecoveryCode(codes[0]));
+ cls.init(() => recoveryCodesService.verifyRecoveryCode(codes[1]));
+
+ const used = recoveryCodesRoute.getUsedRecoveryCodes() as { success: boolean; usedRecoveryCodes: string[] };
+ // Both consumed codes must be reported as used (non-numeric timestamp entries), mirroring the
+ // client's isUnusedRecoveryCode check (/^\d+$/). Catches a stateful global regex that would
+ // advance past the first match and misclassify the adjacent second code as still available.
+ const usedCount = used.usedRecoveryCodes.filter((entry) => !/^\d+$/.test(entry)).length;
+ expect(usedCount).toBe(2);
+ });
});
diff --git a/apps/server/src/routes/api/recovery_codes.ts b/apps/server/src/routes/api/recovery_codes.ts
index e856b47b20..290004065b 100644
--- a/apps/server/src/routes/api/recovery_codes.ts
+++ b/apps/server/src/routes/api/recovery_codes.ts
@@ -34,7 +34,10 @@ function getUsedRecoveryCodes() {
return []
}
- const dateRegex = RegExp(/^\d{4}\/\d{2}\/\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/gm);
+ // No global/multiline flags: RegExp.test() on a /g regex is stateful (it advances lastIndex), so
+ // reusing one instance across the .map() below would skip past a used code that immediately
+ // follows another used one and misreport it as still available.
+ const dateRegex = /^\d{4}\/\d{2}\/\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/;
const recoveryCodes = recovery_codes.getRecoveryCodes();
const usedStatus = recoveryCodes.map(recoveryKey => {