Lightweight, secure MFA (TOTP) + backup codes utility for Node.js / NestJS apps.
npm install mfa-lib> Lightweight, secure MFA (TOTP) + backup codes utility for Node.js / NestJS apps.


---
- 🔐 Time-based One-Time Password (TOTP)
- 📱 Works with Google Authenticator, Microsoft Authenticator, Authy, etc.
- 📷 QR code for TOTP setup.
- 🔁 Backup codes generation and validation
- 🔒 SHA-256 hashing for secure storage
- 🧩 Minimal dependencies and TypeScript support
---
``bash`
npm install mfa-lib
or
`bash`
yarn add mfa-lib
---
`ts
import { authenticator, generateQrCode } from 'mfa-lib';
const secret = authenticator.generateSecret()
const otpAuth = authenticator.keyuri("username-or-id", "your-app-name", secret)
const qrCode = await generateQrCode(otpAuth) // return base64 image
`
`ts
import { authenticator } from 'mfa-lib';
const secret = authenticator.generateSecret();
const token = authenticator.generate(secret);
const isValid = authenticator.check(token, secret); // true or false
`
`ts
import { generateBackupCodes } from 'mfa-lib';
const { backupCodes, hashedCodes } = generateBackupCodes(5);
// Store hashedCodes in your database; backupCodes can be shown once to the user
`
`ts
import { validateBackupCode } from 'mfa-lib';
const result = validateBackupCode(hashedCodes, inputCode);
if (result.status) {
// code is valid
// result.backupCodes contains remaining valid codes (after removing the used one)
} else {
// invalid code
}
`
---
Generates a set of backup codes and their hashed equivalents.
- count: Number of backup codes (default = 10){ backupCodes: string[], hashedCodes: string[] }
- Returns:
Validates a backup code against the list of stored (hashed) codes.
- Returns: { status: boolean, backupCodes?: string[] }
---
- Always store only hashed versions of backup codes
- Treat backup codes as one-time use
- Securely store the TOTP secret (e.g., in a secret manager)
- Regenerate codes if compromised
---
`ts
interface BackupCode {
backupCodes: string[];
hashedCodes: string[];
}
interface UpdatedBackupCode {
status: boolean;
backupCodes?: string[];
}
``
---
MIT © 2025 Collins Ihezie
---
---
---
Issues and PRs welcome! Submit here.