Zero-Dependency RFC 6238 TOTP (2FA) Engine
By (author)Usaid Ullah Qureshi
read more
Read Me
# Zero-Dependency RFC 6238 TOTP (2FA) Engine
A lightweight, zero-dependency TypeScript implementation of RFC 6238 / RFC 4226 Time-based One-Time Passwords (TOTP) built using only Node.js native `node:crypto`.
## ✨ Features
- **Zero External Dependencies:** Built entirely with native `node:crypto`. No external npm bloat.
- **RFC 6238 & RFC 4226 Compliant:** Compatible with Google Authenticator, Microsoft Authenticator, Authy, and 1Password.
- **Built-in Base32:** Includes pure TypeScript Base32 encoder and decoder.
- **Timing-Safe Verification:** Uses `timingSafeEqual` to prevent timing attacks.
- **Clock Drift Tolerance:** Automatically checks ±1 step (±30 seconds) to tolerate client-server clock drift.
- **Replay Attack Protection:** Rejects replayed codes at or before `lastUsedStep`.
## 🚀 Setup & Installation
1. Copy `totp.ts` into your project (e.g. `src/lib/totp.ts`).
2. No packages to install — standard Node.js runtime supported.
## 💡 Quick Usage Example
```typescript
import { generateTotpSecret, otpauthUri, verifyTotp } from "./totp";
// Step 1: Generate user secret
const secret = generateTotpSecret();
// Step 2: Generate URI for QR code
const uri = otpauthUri("user@example.com", secret, "MyApp");
// Step 3: Verify user's code on login
const userEnteredCode = "123456";
const matchedStep = verifyTotp(secret, userEnteredCode, Date.now());
if (matchedStep !== null) {
console.log("Authentication successful! Step:", matchedStep);
} else {
console.error("Invalid or expired 2FA code.");
}