Personal Telegram developer console for GitHub

feat(hardening): add independent TOTP verifier

davoodmehraban89 committed Oct 5, 2026 at 09:53 UTC 0e3fa02d53e076f5c5460ba0bba71bd98ff3cc31
1 file changed +86
src/core/totp.js new
+86
@@ -0,0 +1,86 @@
1 +const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
2 +
3 +function decodeBase32(secret) {
4 + const normalized = String(secret || '').replace(/\s+/g, '').replace(/=+$/g, '').toUpperCase();
5 + if (!normalized) throw new Error('TOTP secret is not configured');
6 + let bits = '';
7 + for (const char of normalized) {
8 + const index = BASE32_ALPHABET.indexOf(char);
9 + if (index < 0) throw new Error('TOTP secret is invalid');
10 + bits += index.toString(2).padStart(5, '0');
11 + }
12 + const bytes = [];
13 + for (let offset = 0; offset + 8 <= bits.length; offset += 8) {
14 + bytes.push(Number.parseInt(bits.slice(offset, offset + 8), 2));
15 + }
16 + if (!bytes.length) throw new Error('TOTP secret is invalid');
17 + return new Uint8Array(bytes);
18 +}
19 +
20 +function counterBytes(counter) {
21 + const buffer = new ArrayBuffer(8);
22 + const view = new DataView(buffer);
23 + view.setUint32(0, Math.floor(counter / 2 ** 32));
24 + view.setUint32(4, counter >>> 0);
25 + return buffer;
26 +}
27 +
28 +function constantTimeCodeEqual(left, right) {
29 + const a = String(left || '');
30 + const b = String(right || '');
31 + if (a.length !== b.length) return false;
32 + let mismatch = 0;
33 + for (let index = 0; index < a.length; index += 1) mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
34 + return mismatch === 0;
35 +}
36 +
37 +export class TotpVerifier {
38 + constructor({ secret = '', now = () => Date.now(), periodMs = 30_000, digits = 6, window = 1 } = {}) {
39 + this.secret = String(secret || '');
40 + this.now = now;
41 + this.periodMs = periodMs;
42 + this.digits = digits;
43 + this.window = window;
44 + this.keyPromise = null;
45 + }
46 +
47 + isConfigured() {
48 + return Boolean(this.secret.trim());
49 + }
50 +
51 + async verify(code) {
52 + if (!this.isConfigured()) throw new Error('Destructive second factor is not configured');
53 + const supplied = String(code || '').trim();
54 + if (!new RegExp(`^\\d{${this.digits}}$`).test(supplied)) return false;
55 + const currentCounter = Math.floor(this.now() / this.periodMs);
56 + for (let delta = -this.window; delta <= this.window; delta += 1) {
57 + if (constantTimeCodeEqual(supplied, await this.#generate(currentCounter + delta))) return true;
58 + }
59 + return false;
60 + }
61 +
62 + async #generate(counter) {
63 + if (!Number.isSafeInteger(counter) || counter < 0) return '';
64 + const key = await this.#key();
65 + const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, counterBytes(counter)));
66 + const offset = digest[digest.length - 1] & 0x0f;
67 + const binary = ((digest[offset] & 0x7f) << 24)
68 + | (digest[offset + 1] << 16)
69 + | (digest[offset + 2] << 8)
70 + | digest[offset + 3];
71 + return String(binary % (10 ** this.digits)).padStart(this.digits, '0');
72 + }
73 +
74 + async #key() {
75 + if (!this.keyPromise) {
76 + this.keyPromise = crypto.subtle.importKey(
77 + 'raw',
78 + decodeBase32(this.secret),
79 + { name: 'HMAC', hash: 'SHA-1' },
80 + false,
81 + ['sign']
82 + );
83 + }
84 + return this.keyPromise;
85 + }
86 +}