/** * Two-factor codes from an authenticator app (RFC 6238 TOTP: SHA-1, 6 digits, 30 s), so * logging in to the Hub doesn't depend on email being set up. */ const crypto = require('crypto'); const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; const STEP = 30; function base32Encode(buf) { let bits = 0; let value = 0; let out = ''; for (const byte of buf) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { out += BASE32[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) out += BASE32[(value << (5 - bits)) & 31]; return out; } function base32Decode(str) { let bits = 0; let value = 0; const out = []; for (const ch of String(str).toUpperCase().replace(/=+$/, '')) { const idx = BASE32.indexOf(ch); if (idx === -1) continue; value = (value << 5) | idx; bits += 5; if (bits >= 8) { out.push((value >>> (bits - 8)) & 255); bits -= 8; } } return Buffer.from(out); } function generateSecret() { return base32Encode(crypto.randomBytes(20)); } function codeAt(secret, counter) { const buf = Buffer.alloc(8); buf.writeBigUInt64BE(BigInt(counter)); const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest(); const offset = hmac[hmac.length - 1] & 0xf; const num = ((hmac[offset] & 0x7f) << 24) | (hmac[offset + 1] << 16) | (hmac[offset + 2] << 8) | hmac[offset + 3]; return String(num % 1_000_000).padStart(6, '0'); } /** True if `code` is right for now, or one 30-second step either side (clock drift). */ function verifyCode(secret, code, now = Date.now()) { const clean = String(code || '').replace(/\D/g, ''); if (clean.length !== 6) return false; const counter = Math.floor(now / 1000 / STEP); for (const c of [counter - 1, counter, counter + 1]) { const expected = codeAt(secret, c); if (crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(clean))) return true; } return false; } /** The otpauth:// link an authenticator app scans (as a QR code). */ function otpauthUrl(secret, account, issuer = 'Cross Code Hub') { return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`; } module.exports = { generateSecret, verifyCode, otpauthUrl, codeAt, base32Encode, base32Decode, STEP };