Lightweight utility to generate a two-factor TOTP secret with QR code to be used by authenticators such as Google or Microsoft Authenticator.
npm install 2fa-util!Build Status
!License
!NPM Version
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.
* 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 otplib options.
* Zero-Dependency (Runtime): Bundles necessary logic efficiently (uses otplib and qrcode under the hood).
``bash`
npm install 2fa-util
`javascript
const { generateSecret, verify } = require('2fa-util');
(async () => {
// 1. Generate a Secret and QR Code
const { secret, qrcode, otpauth } = await generateSecret('john.doe@example.com', 'MyApp');
console.log('Secret:', secret);
console.log('QR Code Data URL:', qrcode); // Display this in an
// ... User scans QR code ...
// 2. Verify a Token
const userToken = '123456'; // Input from user
const isValid = verify(userToken, secret);
console.log('Is Valid:', isValid);
})();
`
You can pass standard otplib options to the verify function, such as window (for clock drift) or step.
`javascript`
const isValid = verify(token, secret, {
window: 1, // Allow 1 step before/after (approx +/- 30sec)
step: 60 // Custom step size in seconds
});
Generates a new TOTP secret and corresponding QR code.
* label (string): The username or account identifier (e.g., email).(string, optional)
* issuer : The name of your application or company.Promise
* Returns:
Verifies a TOTP token against a secret.
* token (string): The 6-digit token provided by the user.(string)
* secret : The user's stored secret key.(Object, optional)
* options : Configuration object passed to otplib.boolean
* Returns: (true if valid, false otherwise).
Generates the current token for a given secret (useful for testing or dev tools).
* secret (string): The secret key.string
* Returns: (The current 6-digit token).
Clone the repository and install dependencies:
`bash`
git clone https://github.com/jzhobes/2fa-util.git
cd 2fa-util
npm install
Run tests:
`bash`
npm test
Run linting:
`bash``
npm run lint
MIT © John Ho