otplib
- Version 13.0.2
- Published
- 197 kB
- 6 dependencies
- MIT license
Install
npm i otplibyarn add otplibpnpm add otplibOverview
TypeScript-first library for TOTP and HOTP with multi-runtime and plugin support
Index
Functions
Classes
Type Aliases
Functions
function generate
generate: (options: OTPGenerateOptions) => Promise<string>;Generate an OTP code
Generates a one-time password based on the specified strategy. - 'totp': Time-based OTP (default) - 'hotp': HMAC-based OTP
Parameter options
OTP generation options
Returns
OTP code
Example 1
TOTP
import { generate } from 'otplib';const token = await generate({secret: 'JBSWY3DPEHPK3PXP',});// Returns: '123456'Example 2
HOTP
import { generate } from 'otplib';const token = await generate({secret: 'JBSWY3DPEHPK3PXP',strategy: 'hotp',counter: 0,});Example 3
With custom plugins
import { generate, NodeCryptoPlugin } from 'otplib';const token = await generate({secret: 'JBSWY3DPEHPK3PXP',crypto: new NodeCryptoPlugin(),});
function generateSecret
generateSecret: (options?: { length?: number; crypto?: CryptoPlugin; base32?: Base32Plugin;}) => string;Generate a random secret key for use with OTP
The secret is encoded in Base32 format for compatibility with Google Authenticator and other authenticator apps.
Parameter options
Secret generation options
Returns
Base32-encoded secret key
Example 1
import { generateSecret } from 'otplib';const secret = generateSecret();// Returns: 'JBSWY3DPEHPK3PXP'Example 2
With custom plugins
import { generateSecret, NodeCryptoPlugin } from 'otplib';const secret = generateSecret({crypto: new NodeCryptoPlugin(),});
function generateSync
generateSync: (options: OTPGenerateOptions) => string;Generate an OTP code synchronously
This is the synchronous version of generate. It requires a crypto plugin that supports synchronous HMAC operations.
Parameter options
OTP generation options
Returns
OTP code
Throws
{HMACError} If the crypto plugin doesn't support sync operations
Example 1
import { generateSync } from 'otplib';const token = generateSync({secret: 'JBSWY3DPEHPK3PXP',});
function generateURI
generateURI: (options: { issuer: string; label: string; secret: string; algorithm?: HashAlgorithm; digits?: Digits; period?: number;}) => string;Generate an otpauth:// URI for QR code generation
This URI can be used to generate a QR code that can be scanned by Google Authenticator and other authenticator apps.
Parameter options
URI generation options
Returns
otpauth:// URI string
Example 1
import { generateURI } from 'otplib';const uri = generateURI({issuer: 'ACME Co',label: 'john@example.com',secret: 'JBSWY3DPEHPK3PXP',});// Returns: 'otpauth://totp/ACME%20Co:john%40example.com?secret=...'
function verify
verify: (options: OTPVerifyOptions) => Promise<VerifyResult>;Verify an OTP code
Verifies a provided OTP code against the expected value based on the strategy. - 'totp': Time-based OTP (default, Google Authenticator compatible) - 'hotp': HMAC-based OTP
Uses constant-time comparison to prevent timing attacks.
Parameter options
OTP verification options
Returns
Verification result with validity and optional delta
Example 1
TOTP
import { verify } from 'otplib';const result = await verify({secret: 'JBSWY3DPEHPK3PXP',token: '123456',});// Returns: { valid: true, delta: 0 }Example 2
HOTP
import { verify } from 'otplib';const result = await verify({secret: 'JBSWY3DPEHPK3PXP',token: '123456',strategy: 'hotp',counter: 0,});Example 3
With epochTolerance for TOTP
import { verify, NodeCryptoPlugin } from 'otplib';const result = await verify({secret: 'JBSWY3DPEHPK3PXP',token: '123456',epochTolerance: 30,crypto: new NodeCryptoPlugin(),});
function verifySync
verifySync: (options: OTPVerifyOptions) => VerifyResult;Verify an OTP code synchronously
This is the synchronous version of verify. It requires a crypto plugin that supports synchronous HMAC operations.
Parameter options
OTP verification options
Returns
Verification result with validity and optional delta
Throws
{HMACError} If the crypto plugin doesn't support sync operations
Example 1
import { verifySync } from 'otplib';const result = verifySync({secret: 'JBSWY3DPEHPK3PXP',token: '123456',});
Classes
class OTP
class OTP {}OTP Class
A wrapper class that dynamically handles TOTP and HOTP strategies.
Example 1
import { OTP } from 'otplib';// Create OTP instance with TOTP strategy (default)const otp = new OTP({ strategy: 'totp' });// Generate and verifyconst secret = otp.generateSecret();const token = await otp.generate({ secret });const result = await otp.verify({ secret, token });Example 2
With HOTP strategy
import { OTP } from 'otplib';const otp = new OTP({ strategy: 'hotp' });const token = await otp.generate({ secret: 'ABC123', counter: 0 });Example 3
Generating otpauth:// URI for authenticator apps
import { OTP } from 'otplib';const otp = new OTP({ strategy: 'totp' });const uri = otp.generateURI({issuer: 'MyApp',label: 'user@example.com',secret: 'ABC123',});
constructor
constructor(options?: OTPClassOptions);method generate
generate: (options: OTPGenerateOptions) => Promise<string>;Generate an OTP token based on the configured strategy
Parameter options
Generation options
Returns
OTP code
method generateSecret
generateSecret: (length?: number) => string;Generate a random secret key
Parameter length
Number of random bytes (default: 20)
Returns
Base32-encoded secret key
method generateSync
generateSync: (options: OTPGenerateOptions) => string;Generate an OTP token based on the configured strategy synchronously
Parameter options
Generation options
Returns
OTP code
Throws
{HMACError} If the crypto plugin doesn't support sync operations
method generateURI
generateURI: (options: OTPURIGenerateOptions) => string;Generate an otpauth:// URI for QR code generation
Only available for TOTP strategy.
Parameter options
URI generation options
Returns
otpauth:// URI string
method getStrategy
getStrategy: () => OTPStrategy;Get the current strategy
method verify
verify: (options: OTPVerifyOptions) => Promise<VerifyResult>;Verify an OTP token based on the configured strategy
Parameter options
Verification options
Returns
Verification result with validity and optional delta
method verifySync
verifySync: (options: OTPVerifyOptions) => VerifyResult;Verify an OTP token based on the configured strategy synchronously
Parameter options
Verification options
Returns
Verification result with validity and optional delta
Throws
{HMACError} If the crypto plugin doesn't support sync operations
Type Aliases
type OTPAuthOptions
type OTPAuthOptions = { /** * Crypto plugin to use (default: NobleCryptoPlugin) */ readonly crypto?: CryptoPlugin; /** * Base32 plugin to use (default: ScureBase32Plugin) */ readonly base32?: Base32Plugin;};Options with plugin overrides
type OTPClassOptions
type OTPClassOptions = { /** * OTP strategy to use * - 'totp': Time-based OTP (default) * - 'hotp': HMAC-based OTP */ strategy?: OTPStrategy; /** * Crypto plugin to use (default: NobleCryptoPlugin) */ crypto?: CryptoPlugin; /** * Base32 plugin to use (default: ScureBase32Plugin) */ base32?: Base32Plugin;};Options for the OTP class
type OTPFunctionalOptions
type OTPGenerateOptions = { /** * Base32-encoded secret key */ secret: string; /** * OTP strategy to use (default: 'totp') * - 'totp': Time-based OTP * - 'hotp': HMAC-based OTP */ strategy?: OTPStrategy; /** * Crypto plugin to use (default: NobleCryptoPlugin) */ crypto?: CryptoPlugin; /** * Base32 plugin to use (default: ScureBase32Plugin) */ base32?: Base32Plugin; /** * Hash algorithm (default: 'sha1') */ algorithm?: HashAlgorithm; /** * Number of digits (default: 6) */ digits?: Digits; /** * Time step in seconds (default: 30) * Used by TOTP strategy */ period?: number; /** * Current Unix epoch timestamp in seconds (default: now) * Used by TOTP strategy */ epoch?: number; /** * Initial Unix time to start counting time steps (default: 0) * Used by TOTP strategy */ t0?: number; /** * Counter value * Used by HOTP strategy (required) */ counter?: number;};Common options for OTP generation
These options apply to both TOTP and HOTP strategies.
type OTPGenerateOptions
type OTPGenerateOptions = { /** * Base32-encoded secret key */ secret: string; /** * Hash algorithm (default: 'sha1') */ algorithm?: HashAlgorithm; /** * Number of digits (default: 6) */ digits?: Digits; /** * Current Unix epoch timestamp in seconds (default: now) * Used by TOTP strategy */ epoch?: number; /** * Initial Unix time to start counting time steps (default: 0) * Used by TOTP strategy */ t0?: number; /** * Time step in seconds (default: 30) * Used by TOTP strategy */ period?: number; /** * Counter value * Used by HOTP strategy (required) */ counter?: number;};Options for generating a token with the OTP class
type OTPStrategy
type OTPStrategy = 'totp' | 'hotp';OTP Strategy Type
type OTPURIGenerateOptions
type OTPURIGenerateOptions = { /** * Issuer name (e.g., 'ACME Co') */ issuer: string; /** * Label/Account name (e.g., 'john@example.com') */ label: string; /** * Base32-encoded secret key */ secret: string; /** * Hash algorithm (default: 'sha1') */ algorithm?: HashAlgorithm; /** * Number of digits (default: 6) */ digits?: Digits; /** * Time step in seconds (default: 30) */ period?: number;};Options for generating URI with the OTP class
type OTPVerifyFunctionalOptions
type OTPVerifyOptions = OTPGenerateOptions & { /** * OTP code to verify */ token: string; /** * Time tolerance in seconds for TOTP verification (default: 0) * - Number: symmetric tolerance (same for past and future) * - Tuple [past, future]: asymmetric tolerance * Use [5, 0] for RFC-compliant past-only verification. */ epochTolerance?: number | [number, number]; /** * Counter tolerance for HOTP verification (default: 0) * - Number: symmetric look-ahead window * - Array: asymmetric window */ counterTolerance?: number | number[];};Options for OTP verification
Extends OTPFunctionalOptions with token and tolerance parameters.
type OTPVerifyOptions
type OTPVerifyOptions = { /** * Base32-encoded secret key */ secret: string; /** * OTP code to verify */ token: string; /** * Hash algorithm (default: 'sha1') */ algorithm?: HashAlgorithm; /** * Number of digits (default: 6) */ digits?: Digits; /** * Current Unix epoch timestamp in seconds (default: now) * Used by TOTP strategy */ epoch?: number; /** * Initial Unix time to start counting time steps (default: 0) * Used by TOTP strategy */ t0?: number; /** * Time step in seconds (default: 30) * Used by TOTP strategy */ period?: number; /** * Counter value * Used by HOTP strategy (required) */ counter?: number; /** * Time tolerance in seconds for TOTP verification (default: 0) * - Number: symmetric tolerance (same for past and future) * - Tuple [past, future]: asymmetric tolerance * Use [5, 0] for RFC-compliant past-only verification. */ epochTolerance?: number | [number, number]; /** * Counter tolerance for HOTP verification (default: 0) * - Number: symmetric look-ahead window * - Array: asymmetric window */ counterTolerance?: number | number[];};Options for verifying a token with the OTP class
Package Files (4)
Dependencies (6)
Dev Dependencies (5)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/otplib.
- Markdown[](https://www.jsdocs.io/package/otplib)
- HTML<a href="https://www.jsdocs.io/package/otplib"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 3039 ms. - Missing or incorrect documentation? Open an issue for this package.
