Skip to content

otplib API Documentation / otplib / class / OTP

Class: OTP

Defined in: otplib/src/class.ts:287

OTP Class

A wrapper class that dynamically handles TOTP and HOTP strategies.

Examples

ts
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 });
ts
import { OTP } from 'otplib';

const otp = new OTP({ strategy: 'hotp' });
const token = await otp.generate({ secret: 'ABC123', counter: 0 });
ts
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:293

Parameters

options?

OTPClassOptions = {}

Returns

OTP

Methods

generate()

generate(options): Promise<string>

Defined in: otplib/src/class.ts:330

Generate an OTP token based on the configured strategy

Parameters

options

OTPGenerateOptions

Generation options

Returns

Promise<string>

OTP code


generateSecret()

generateSecret(length?): string

Defined in: otplib/src/class.ts:320

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:347

Generate an OTP token based on the configured strategy synchronously

Parameters

options

OTPGenerateOptions

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:398

Generate an otpauth:// URI for QR code generation

Supports both TOTP and HOTP strategies.

Parameters

options

OTPURIGenerateOptions

URI generation options

Returns

string

otpauth:// URI string


getStrategy()

getStrategy(): OTPStrategy

Defined in: otplib/src/class.ts:310

Get the current strategy

Returns

OTPStrategy


verify()

verify(options): Promise<VerifyResult>

Defined in: otplib/src/class.ts:363

Verify an OTP token based on the configured strategy

Parameters

options

OTPVerifyOptions

Verification options

Returns

Promise<VerifyResult>

Verification result with validity and optional delta


verifySync()

verifySync(options): VerifyResult

Defined in: otplib/src/class.ts:380

Verify an OTP token based on the configured strategy synchronously

Parameters

options

OTPVerifyOptions

Verification options

Returns

VerifyResult

Verification result with validity and optional delta

Throws

If the crypto plugin doesn't support sync operations

Released under the MIT License.