HMAC-based (HOTP) and Time-based (TOTP) One-Time Password library compatible with Google Authenticator
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
OTPLib provides different preset packages optimized for specific environments. Each preset includes pre-configured crypto and base32 implementations suitable for their target platform.
The main otplib package and @otplib/preset-default provide Node.js optimized implementations.
// Main package (re-exports preset-default)
import { authenticator, totp, hotp } from "otplib";
// Direct preset import
import { authenticator, totp, hotp } from "@otplib/preset-default";Features:
crypto module for HMAC operationsthirty-two library for Base32 encoding/decodingUsage Example:
import { authenticator, totp, hotp } from "otplib";
// All instances pre-configured for Node.js
const secret = authenticator.generateSecret();
const token = authenticator.generate(secret);
const isValid = authenticator.check(token, secret);
// Direct usage without additional setup
const totpToken = totp.generate("secret-key");
const hotpToken = hotp.generate("secret-key", 0);Browser-compatible preset using pure JavaScript crypto implementations.
import { authenticator, totp, hotp } from "@otplib/preset-browser";Features:
crypto-js library for HMAC operations (no Node.js dependencies)base32-encode/base32-decode for Base32 operationsInstallation:
npm install @otplib/preset-browserBrowser Usage:
<!-- Include Buffer polyfill first -->
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/buffer.js"></script>
<!-- Include OTPLib browser preset -->
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/index.js"></script>
<script>
// Available as window.otplib
const secret = window.otplib.authenticator.generateSecret();
const token = window.otplib.authenticator.generate(secret);
const isValid = window.otplib.authenticator.check(token, secret);
console.log('Secret:', secret);
console.log('Token:', token);
console.log('Valid:', isValid);
</script>Module Usage:
import { authenticator, totp, hotp } from "@otplib/preset-browser";
// Works in browser environments without Node.js dependencies
const secret = authenticator.generateSecret();
const token = authenticator.generate(secret);
// All functionality available as in Node.js preset
totp.options = { digits: 8 };
const totpToken = totp.generate("browser-secret");Backward compatibility preset providing v11.x API compatibility.
import { authenticator, totp, hotp } from "@otplib/preset-v11";Features:
Installation:
npm install @otplib/preset-v11Usage Example:
import { authenticator, totp, hotp } from "@otplib/preset-v11";
// v11 API compatibility
const secret = 'KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD';
const token = authenticator.generate(secret);
const isValid = authenticator.check(token, secret);
// Deprecated methods will show console warnings but still work
// This helps with gradual migration to v12 APIMigration Pattern:
// Old v11 code
import { authenticator } from 'otplib';
// Migration step 1: Use v11 preset
import { authenticator } from '@otplib/preset-v11';
// Migration step 2: Update to v12 API
import { authenticator } from 'otplib';Async-compatible preset for environments requiring async crypto operations.
import { authenticator, totp, hotp } from "@otplib/preset-default-async";Features:
Usage Example:
import { authenticator, totp, hotp } from "@otplib/preset-default-async";
async function handleOTP() {
// All operations are async
const secret = await authenticator.generateSecret();
const token = await authenticator.generate(secret);
const isValid = await authenticator.check(token, secret);
console.log('Generated:', token);
console.log('Valid:', isValid);
}
// TOTP async usage
async function handleTOTP() {
const token = await totp.generate("secret-key");
const isValid = await totp.check(token, "secret-key");
return { token, isValid };
}Create custom presets with specific crypto and base32 implementations.
import { HOTP, TOTP, Authenticator } from "@otplib/core";
import { createDigest, createRandomBytes } from "custom-crypto-plugin";
import { keyEncoder, keyDecoder } from "custom-base32-plugin";
// Create custom instances
const customHOTP = new HOTP({ createDigest });
const customTOTP = new TOTP({ createDigest });
const customAuthenticator = new Authenticator({
createDigest,
createRandomBytes,
keyEncoder,
keyDecoder
});
export { customHOTP as hotp, customTOTP as totp, customAuthenticator as authenticator };| Feature | Default | Browser | v11 | Async |
|---|---|---|---|---|
| Node.js | ✅ | ❌ | ✅ | ✅ |
| Browser | ❌ | ✅ | ❌ | ⚠️ |
| TypeScript | ✅ | ✅ | ✅ | ✅ |
| Bundle Size | Small | Medium | Small | Small |
| Async Methods | ❌ | ❌ | ❌ | ✅ |
| v11 Compatibility | ❌ | ❌ | ✅ | ❌ |
// Default preset - Fastest (Node.js crypto)
import { authenticator } from "otplib";
// Browser preset - Slower (pure JS crypto)
import { authenticator } from "@otplib/preset-browser";
// Async preset - Variable (depends on crypto implementation)
import { authenticator } from "@otplib/preset-default-async";// Use browser preset or create custom with React Native crypto
import { authenticator } from "@otplib/preset-browser";
// Or with async preset if using crypto-js async
import { authenticator } from "@otplib/preset-default-async";// Browser preset recommended for webpack builds
import { authenticator } from "@otplib/preset-browser";
// Avoid Node.js preset in browser bundles
// import { authenticator } from "otplib"; // ❌ Will bundle Node.js dependencies// Main process (Node.js)
import { authenticator } from "otplib";
// Renderer process (Browser-like)
import { authenticator } from "@otplib/preset-browser";// Use browser preset in web workers
import { authenticator } from "@otplib/preset-browser";
self.onmessage = function(e) {
const token = authenticator.generate(e.data.secret);
self.postMessage({ token });
};// All presets export the same interface types
interface PresetExports {
authenticator: Authenticator;
totp: TOTP;
hotp: HOTP;
}
// Async preset returns Promise-wrapped methods
interface AsyncPresetExports {
authenticator: AsyncAuthenticator;
totp: AsyncTOTP;
hotp: AsyncHOTP;
}
interface AsyncAuthenticator {
generate(secret: string): Promise<string>;
check(token: string, secret: string): Promise<boolean>;
verify(opts: { token: string; secret: string }): Promise<boolean>;
generateSecret(numberOfBytes?: number): Promise<string>;
keyuri(accountName: string, issuer: string, secret: string): Promise<string>;
}Install with Tessl CLI
npx tessl i tessl/npm-otplib