otplib API Documentation / otplib / TOTP
Class: TOTP
Defined in: totp/src/class.ts:45
TOTP class for time-based one-time password generation
Example
import { TOTP } from '@otplib/totp';
import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node';
import { ScureBase32Plugin } from '@otplib/plugin-base32-scure';
const totp = new TOTP({
issuer: 'MyApp',
label: 'user@example.com',
crypto: new NodeCryptoPlugin(),
base32: new ScureBase32Plugin(),
});
const secret = totp.generateSecret();
const token = await totp.generate();
const isValid = await totp.verify(token);Constructors
Constructor
new TOTP(
options):TOTP
Defined in: totp/src/class.ts:49
Parameters
options
TOTPOptions = {}
Returns
TOTP
Methods
generate()
generate(
options?):Promise<string>
Defined in: totp/src/class.ts:74
Generate a TOTP code
Parameters
options?
Partial<TOTPOptions>
Optional overrides
Returns
Promise<string>
The TOTP code
generateSecret()
generateSecret():
string
Defined in: totp/src/class.ts:59
Generate a random Base32-encoded secret
Returns
string
Base32-encoded secret
toURI()
toURI(
options?):string
Defined in: totp/src/class.ts:191
Generate an otpauth:// URI for QR codes
When called with parameters, merges them with instance options. This preserves algorithm, digits, and period settings from the instance while allowing label, issuer, and secret to be overridden.
Parameters
options?
Optional overrides for label, issuer, and secret
issuer?
string
label?
string
secret?
string
Returns
string
The otpauth:// URI
Examples
const totp = new TOTP({
label: 'user@example.com',
issuer: 'MyApp',
secret: 'JBSWY3DPEHPK3PXP',
crypto: new NodeCryptoPlugin(),
base32: new ScureBase32Plugin(),
});
const uri = totp.toURI();const totp = new TOTP({
algorithm: 'sha256',
digits: 8,
crypto: new NodeCryptoPlugin(),
base32: new ScureBase32Plugin(),
});
// Uses instance's algorithm and digits with provided label/issuer/secret
const uri = totp.toURI({
label: 'user@example.com',
issuer: 'MyApp',
secret: 'JBSWY3DPEHPK3PXP',
});verify()
verify(
token,options?):Promise<VerifyResult>
Defined in: totp/src/class.ts:114
Verify a TOTP code
Parameters
token
string
The token to verify
options?
Partial<Omit<TOTPVerifyOptions, "token">>
Optional verification options
Returns
Promise<VerifyResult>
Verification result with validity and optional delta