Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(totp): preserve existing saved secrets while validating new input

Afloata468ff2b308d
diff --git a/server/totp.test.ts b/server/totp.test.ts
index b2b707aaa9..dcb7453100 100644
--- a/server/totp.test.ts
+++ b/server/totp.test.ts
@@ -56,6 +56,23 @@ describe("TOTP (RFC 6238)", () => {
expect(totpCode(key, 30_000)).toBe(totpCode(key, 59_999));
expect(totpCode(key, 60_000)).not.toBe(totpCode(key, 59_999));
});
+ it.each([
+ ["JBSWY3DPEHPK3PXPA", "48656c6c6f21deadbeef"],
+ ["JBSWY3DPEHPK3PXPAAA", "48656c6c6f21deadbeef00"],
+ ["JBSWY3DPEHPK3PXPAAAAAA", "48656c6c6f21deadbeef000000"],
+ ])("preserves the decoded bytes of an existing saved key (%s)", (secret, hex) => {
+ const key = { secret, algorithm: "SHA1" as const, digits: 6, period: 30 };
+ const bytes = Buffer.from(hex, "hex");
+ expect(parseTotpKey(secret)).toBeNull();
+ expect(totpCode(key, 59_000)).toBe(hotp(bytes, 1, 6));
+ expect(totpCode(key, 120_000)).toBe(hotp(bytes, 4, 6));
+ });
+
+ it("refuses invalid characters in an existing saved key", () => {
+ const key = { secret: "JBSWY3DPEHPK3PXP0", algorithm: "SHA1" as const, digits: 6, period: 30 };
+ expect(() => totpCode(key, 59_000)).toThrow("not valid base32");
+ });
+
});
describe("2FA setup keys", () => {
diff --git a/server/totp.ts b/server/totp.ts
index 4352d45f9e..3ca4fb7383 100644
--- a/server/totp.ts
+++ b/server/totp.ts
@@ -14,6 +14,10 @@ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/** RFC 4648 base32, case-insensitive; spaces, dashes and padding ignored. */
export function decodeBase32(text: string): Buffer | null {
+ return decodeBase32Secret(text, false);
+}
+
+function decodeBase32Secret(text: string, allowIncompleteGroups: boolean): Buffer | null {
const clean = text.replace(/[\s-]/gu, "").replace(/=+$/u, "").toUpperCase();
if (!clean || !/^[A-Z2-7]+$/u.test(clean)) return null;
const bytes: number[] = [];
@@ -27,7 +31,7 @@ export function decodeBase32(text: string): Buffer | null {
bytes.push((buffer >> bits) & 0xff);
}
}
- if (bits >= 5) return null;
+ if (!allowIncompleteGroups && bits >= 5) return null;
return Buffer.from(bytes);
}
@@ -69,7 +73,7 @@ export function hotp(key: Buffer, counter: number, digits: number, algorithm: To
/** The code a key shows at `nowMs` (RFC 6238, T0 = 0). */
export function totpCode(key: TotpKey, nowMs: number = Date.now()): string {
- const bytes = decodeBase32(key.secret);
+ const bytes = decodeBase32Secret(key.secret, true);
if (!bytes) throw new Error("The saved 2FA key is not valid base32.");
return hotp(bytes, Math.floor(nowMs / 1000 / key.period), key.digits, key.algorithm);
}