@otplib/totp
v13.2.1
Published
RFC 6238 TOTP implementation for otplib
Maintainers
Readme
@otplib/totp
RFC 6238 TOTP implementation for otplib.
Installation
npm install @otplib/totp
pnpm install @otplib/totp
yarn add @otplib/totpUsage
import { generate, verify } from "@otplib/totp";
import { crypto } from "@otplib/plugin-crypto-node";
import { base32 } from "@otplib/plugin-base32-scure";
// Generate a TOTP token
const token = await generate({
secret: "GEZDGNBVGY3TQOJQGEZDGNBVGY",
crypto,
base32,
});
// Verify a TOTP token
const result = await verify({
secret: "GEZDGNBVGY3TQOJQGEZDGNBVGY",
token: "123456",
crypto,
base32,
});
// result.valid: boolean
// result.delta: number | nullFunctions
generate
Generate a TOTP code:
import { generate } from '@otplib/totp';
import { crypto } from '@otplib/plugin-crypto-node';
import { base32 } from '@otplib/plugin-base32-scure';
const token = await generate({
secret: new Uint8Array([...]), // Required: secret as bytes
crypto, // Required: crypto plugin
base32, // Optional: base32 plugin (for decoding)
algorithm: 'sha1', // Optional: 'sha1' | 'sha256' | 'sha512'
digits: 6, // Optional: 6 | 7 | 8
period: 30, // Optional: time step in seconds
epoch: Math.floor(Date.now() / 1000), // Optional: current time in seconds
});verify
Verify a TOTP code:
import { verify } from '@otplib/totp';
import { crypto } from '@otplib/plugin-crypto-node';
import { base32 } from '@otplib/plugin-base32-scure';
const result = await verify({
secret: new Uint8Array([...]), // Required: secret as bytes
token: '123456', // Required: token to verify
crypto, // Required: crypto plugin
base32, // Optional: base32 plugin (for decoding)
algorithm: 'sha1', // Optional: hash algorithm
digits: 6, // Optional: expected digits
period: 30, // Optional: time step
epoch: Math.floor(Date.now() / 1000), // Optional: current time
epochTolerance: 30, // Optional: time tolerance in seconds
});
// Returns: { valid: boolean, delta: number | null }getRemainingTime
Get the remaining time before the next TOTP period:
import { getRemainingTime } from "@otplib/totp";
const seconds = getRemainingTime(
Math.floor(Date.now() / 1000), // time
30, // period
0, // t0
);
// Returns: number of seconds remaininggetTimeStepUsed
Get the time step used for a specific time:
import { getTimeStepUsed } from "@otplib/totp";
const counter = getTimeStepUsed(
Math.floor(Date.now() / 1000), // time
30, // period
0, // t0
);
// Returns: the counter valueDocumentation
Full documentation available at otplib.yeojz.dev:
License
MIT © 2026 Gerald Yeo
