otplib API Documentation / @otplib/core / types / OTPHooks
Type Alias: OTPHooks
OTPHooks =
object
Defined in: packages/core/src/types.ts:35
Hooks for customizing OTP token encoding and validation.
These allow non-standard OTP variants (e.g., Steam Guard) to hook into the generation and verification pipeline, replacing the default numeric encoding with custom schemes without modifying core behavior.
When not provided, the standard RFC 4226 numeric encoding is used.
Example
import { generate } from '@otplib/totp';
import { steam } from '@otplib/community-plugin-steam';
const code = await generate({
secret,
crypto,
...steam, // { digits: 5, hooks: { encodeToken, validateToken } }
});Properties
encodeToken()?
readonlyoptionalencodeToken: (truncatedValue,digits) =>string
Defined in: packages/core/src/types.ts:46
Custom token encoder. Replaces the default numeric encoding (truncateDigits).
Receives the 31-bit truncated HMAC integer and the desired code length, and must return the formatted token string.
Parameters
truncatedValue
number
31-bit unsigned integer from dynamic truncation
digits
number
Desired token length
Returns
string
Encoded token string
truncateDigest()?
readonlyoptionaltruncateDigest: (hmacResult) =>number
Defined in: packages/core/src/types.ts:75
Custom HMAC digest truncation. Replaces the default RFC 4226 dynamic truncation.
Receives the raw HMAC digest and must return a 31-bit unsigned integer (0–2,147,483,647). The integer is then passed to encodeToken (or the default truncateDigits) to produce the final token string.
Parameters
hmacResult
Uint8Array
Raw HMAC digest as a byte array
Returns
number
31-bit unsigned integer (0 to 0x7FFFFFFF)
Example
const truncateDigest = (hmac: Uint8Array): number =>
((hmac[0] & 0x7f) << 24) | (hmac[1] << 16) | (hmac[2] << 8) | hmac[3];validateToken()?
readonlyoptionalvalidateToken: (token,digits) =>void
Defined in: packages/core/src/types.ts:57
Custom token validator. Replaces the default digit-only format check.
Should throw an error if the token is malformed for this encoding scheme.
Parameters
token
string
Token string to validate
digits
number
Expected token length
Returns
void
Throws
If token format is invalid