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
TOTP implements RFC 6238 time-based one-time passwords. Unlike the Authenticator class, TOTP works with raw secret keys in various encodings and provides more direct control over time-based token generation.
Generates time-based tokens using the current timestamp and configured time step.
/**
* Generate a TOTP token based on current time
* @param secret - Secret key in the configured encoding
* @returns Token string with configured digit length
*/
generate(secret: string): string;Usage Example:
import { totp } from "otplib";
const secret = "your-secret-key";
const token = totp.generate(secret);
console.log(token); // "123456"
// Generate with custom options
totp.options = { digits: 8, step: 60 };
const longToken = totp.generate(secret);
console.log(longToken); // "12345678"Verifies tokens with configurable time window tolerance for network delays and clock skew.
/**
* Verify a TOTP token with time window tolerance
* @param token - Token to verify
* @param secret - Secret key
* @returns true if token is valid within configured window
*/
check(token: string, secret: string): boolean;
/**
* Object-based token verification
* @param opts - Object containing token and secret
* @returns true if token is valid within configured window
*/
verify(opts: { token: string; secret: string }): boolean;Usage Examples:
import { totp } from "otplib";
const secret = "your-secret-key";
const token = "123456";
// Method 1: Direct parameters
const isValid = totp.check(token, secret);
// Method 2: Object parameters
const isValid2 = totp.verify({ token, secret });
// Configure time window (±1 time step = ±30 seconds by default)
totp.options = { window: 1 };
const isValidWithWindow = totp.check(token, secret);
// Asymmetric window: 2 steps past, 1 step future
totp.options = { window: [2, 1] };
const isValidAsymmetric = totp.check(token, secret);Advanced verification that returns timing information about when the token was valid.
/**
* Check token with detailed timing information
* @param token - Token to verify
* @param secret - Secret key
* @returns Delta value: 0 = current window, negative = past, positive = future, null = invalid
*/
checkDelta(token: string, secret: string): number | null;Usage Example:
import { totp } from "otplib";
const secret = "your-secret-key";
const token = "123456";
const delta = totp.checkDelta(token, secret);
if (delta === 0) {
console.log("Token is from current time window");
} else if (delta && delta < 0) {
console.log(`Token was valid ${Math.abs(delta)} window(s) ago`);
} else if (delta && delta > 0) {
console.log(`Token will be valid in ${delta} window(s)`);
} else {
console.log("Token is invalid");
}Get timing information about the current token period.
/**
* Get seconds remaining in current time window
* @returns Seconds until next token
*/
timeRemaining(): number;
/**
* Get seconds used in current time window
* @returns Seconds since current token became valid
*/
timeUsed(): number;Usage Example:
import { totp } from "otplib";
const remaining = totp.timeRemaining();
const used = totp.timeUsed();
console.log(`Token expires in ${remaining} seconds`);
console.log(`Token has been valid for ${used} seconds`);
// Useful for showing countdown timers in UIs
setInterval(() => {
const remaining = totp.timeRemaining();
if (remaining === 30) { // Start of new period
console.log("New token generated");
}
}, 1000);Generate otpauth:// URIs for TOTP configuration.
/**
* Generate an otpauth URI for TOTP setup
* @param accountName - User identifier
* @param issuer - Service name
* @param secret - Secret key
* @returns otpauth://totp/ URI string
*/
keyuri(accountName: string, issuer: string, secret: string): string;Usage Example:
import { totp } from "otplib";
const secret = "your-secret-key";
const user = "user@example.com";
const service = "My Service";
const otpauth = totp.keyuri(user, service, secret);
console.log(otpauth);
// "otpauth://totp/My%20Service:user@example.com?secret=your-secret-key&issuer=My%20Service"Manage TOTP-specific configuration options.
/**
* Get/set configuration options
*/
options: Partial<TOTPOptions>;
/**
* Reset options to default values
*/
resetOptions(): void;
/**
* Get all options with defaults applied
* @returns Complete options object
*/
allOptions(): Readonly<TOTPOptions>;
/**
* Create new instance with custom defaults
* @param defaultOptions - Custom default options
* @returns New TOTP instance
*/
create(defaultOptions?: Partial<TOTPOptions>): TOTP;Usage Examples:
import { totp } from "otplib";
// Configure options
totp.options = {
digits: 8, // 8-digit tokens
step: 60, // 60-second time step
window: [2, 1], // Allow 2 past, 1 future window
algorithm: 'sha256'
};
// Create instance with custom defaults
const customTotp = totp.create({
digits: 6,
step: 30,
algorithm: 'sha1'
});
// Reset to library defaults
totp.resetOptions();
// View complete configuration
const config = totp.allOptions();
console.log(config.step); // 30
console.log(config.digits); // 6import { totp } from "otplib";
totp.options = {
digits: 6,
step: 30,
algorithm: 'sha1',
encoding: 'ascii',
window: 1
};import { totp } from "otplib";
totp.options = {
digits: 8,
step: 15, // Shorter validity period
algorithm: 'sha256', // Stronger hash
window: 0 // No time tolerance
};import { totp } from "otplib";
totp.options = {
window: [3, 2] // Allow more past/future tolerance
};interface TOTPOptions extends HOTPOptions {
/** Starting time in milliseconds since JavaScript epoch */
epoch: number;
/** Time step in seconds */
step: number;
/** Time window tolerance: number or [past, future] */
window: number | [number, number];
}
interface HOTPOptions {
algorithm: 'sha1' | 'sha256' | 'sha512';
digits: number;
encoding: 'ascii' | 'base64' | 'hex' | 'latin1' | 'utf8';
createDigest: (algorithm: string, key: string, data: string) => string;
createHmacKey: (algorithm: string, secret: string, encoding: string) => string;
digest?: string;
}Install with Tessl CLI
npx tessl i tessl/npm-otplib