otplib API Documentation / otplib / OTP
Class: OTP
Defined in: otplib/src/class.ts:254
OTP Class
A wrapper class that dynamically handles TOTP and HOTP strategies.
Examples
import { OTP } from 'otplib';
// Create OTP instance with TOTP strategy (default)
const otp = new OTP({ strategy: 'totp' });
// Generate and verify
const secret = otp.generateSecret();
const token = await otp.generate({ secret });
const result = await otp.verify({ secret, token });import { OTP } from 'otplib';
const otp = new OTP({ strategy: 'hotp' });
const token = await otp.generate({ secret: 'ABC123', counter: 0 });import { OTP } from 'otplib';
const otp = new OTP({ strategy: 'totp' });
const uri = otp.generateURI({
issuer: 'MyApp',
label: 'user@example.com',
secret: 'ABC123',
});Constructors
Constructor
new OTP(
options):OTP
Defined in: otplib/src/class.ts:259
Parameters
options
OTPClassOptions = {}
Returns
OTP
Methods
generate()
generate(
options):Promise<string>
Defined in: otplib/src/class.ts:290
Generate an OTP token based on the configured strategy
Parameters
options
Generation options
Returns
Promise<string>
OTP code
generateSecret()
generateSecret(
length):string
Defined in: otplib/src/class.ts:280
Generate a random secret key
Parameters
length
number = 20
Number of random bytes (default: 20)
Returns
string
Base32-encoded secret key
generateSync()
generateSync(
options):string
Defined in: otplib/src/class.ts:306
Generate an OTP token based on the configured strategy synchronously
Parameters
options
Generation options
Returns
string
OTP code
Throws
If the crypto plugin doesn't support sync operations
generateURI()
generateURI(
options):string
Defined in: otplib/src/class.ts:354
Generate an otpauth:// URI for QR code generation
Supports both TOTP and HOTP strategies.
Parameters
options
URI generation options
Returns
string
otpauth:// URI string
getStrategy()
getStrategy():
OTPStrategy
Defined in: otplib/src/class.ts:270
Get the current strategy
Returns
verify()
verify(
options):Promise<VerifyResult>
Defined in: otplib/src/class.ts:321
Verify an OTP token based on the configured strategy
Parameters
options
Verification options
Returns
Promise<VerifyResult>
Verification result with validity and optional delta
verifySync()
verifySync(
options):VerifyResult
Defined in: otplib/src/class.ts:337
Verify an OTP token based on the configured strategy synchronously
Parameters
options
Verification options
Returns
VerifyResult
Verification result with validity and optional delta
Throws
If the crypto plugin doesn't support sync operations