2fa-util
v1.5.0
Published
Lightweight utility to generate a two-factor TOTP secret with QR code to be used by authenticators such as Google or Microsoft Authenticator.
Maintainers
Readme
2fa-util
A lightweight, robust Node.js utility for generating Two-Factor Authentication (TOTP) secrets, QR codes, and verifying tokens. Compatible with Google Authenticator, Microsoft Authenticator, and Authy.
🚀 Live Demo
Features
- Easy Setup: Generate a secret and QR code in one function call.
- Standard Compatible: Works with any RFC 6238 compliant authenticator app.
- Flexible Verification: Supports custom windows, steps, and other
otpliboptions. - Zero-Dependency (Runtime): Bundles necessary logic efficiently (uses
otplibandqrcodeunder the hood).
Installation
npm install 2fa-utilUsage
Basic Example
const { generateSecret, verify } = require('2fa-util');
(async () => {
// 1. Generate a Secret and QR Code
const { secret, qrcode, otpauth } = await generateSecret('[email protected]', 'MyApp');
console.log('Secret:', secret);
console.log('QR Code Data URL:', qrcode); // Display this in an <img src="...">
// ... User scans QR code ...
// 2. Verify a Token
const userToken = '123456'; // Input from user
const isValid = verify(userToken, secret);
console.log('Is Valid:', isValid);
})();Advanced Verification (Custom Options)
You can pass standard otplib options to the verify function, such as window (for clock drift) or step.
const isValid = verify(token, secret, {
window: 1, // Allow 1 step before/after (approx +/- 30sec)
step: 60 // Custom step size in seconds
});API Reference
generateSecret(label, [issuer])
Generates a new TOTP secret and corresponding QR code.
- label
(string): The username or account identifier (e.g., email). - issuer
(string, optional): The name of your application or company. - Returns:
Promise<Object>secret: The base32 encoded secret key.qrcode: A Data URI string (base64) of the QR code image.otpauth: The rawotpauth://URL.
verify(token, secret, [options])
Verifies a TOTP token against a secret.
- token
(string): The 6-digit token provided by the user. - secret
(string): The user's stored secret key. - options
(Object, optional): Configuration object passed tootplib. - Returns:
boolean(trueif valid,falseotherwise).
generate(secret)
Generates the current token for a given secret (useful for testing or dev tools).
- secret
(string): The secret key. - Returns:
string(The current 6-digit token).
Development
Clone the repository and install dependencies:
git clone https://github.com/jzhobes/2fa-util.git
cd 2fa-util
npm installRun tests:
npm testRun linting:
npm run lintLicense
MIT © John Ho
