otpts
One-Time Password generator
otpts is a library to create one-time passwords (OTP). Currently, two algorithms are implemented: HOTP and TOPT.
HOTP stands for HMAC-Based One-Time Password Algorithm. It's defined in the RFC 4226. TOTP stands for Time-Based One-Time Password Algorithm. It's defined in the RFC 6238.
OTP algorithms are mostly used for MFA (Multi-factor authentication) as codes sent to the user (SMS, mail, etc.), or generated through a custom application. Although you can use HOTP and TOTP for both usage, HOTP is regularly use for sending codes and TOTP used for generation.
Overview
// Generate a token // Verify a tokentotp.verifytoken // true // Generate an URI compatible with OTP Apps
HOTP
// This will generate a one-time password for a counter to 0 // This will compare (using crypto time safe equal) user input to a specific counter value// you can think of it as a `hotp.generate(0) === userInput`, time-attack safehotp.verifyotp, 0
Signature:
buildHotp:
TOTP
// This will generate a one-time password for the first 30 seconds after the// UNIX timestamp 0 (1970-01-01 - 00:00:00)totp.generate0 // This will generate a one-time password for the current 30 seconds intervaltotp.generate // It is equivalent tototp.generateDate.now / 1000 // This will generate a one-time password for a counter to 0 // This will compare (using crypto time safe equal) user input to a specific counter value// you can think of it as a `totp.generate() === userInput`, time-attack safetotp.verifyotp // true setTimeouttotp.verifyotp, 30 * 1000 // false
Signature:
buildTotp:
Utils
generateSecret
This function will generate a random string using the crypto
native module. This secret will be exchanged between the two sides so they can generate tokens in an offline way (you should do that in a secure way — HTTPS, etc.).
// send secret through QRCode// save secret in database
generateUri
This will generate a valid URI that can be used with QR codes.
generateUri(
| {
type: 'hotp'
secret: string
label: string
issuer?: string
hmacAlgorithm?: 'sha1' | 'sha256' | 'sha512'
digits?: number
initialCounter?: number
}
| {
type: 'totp'
secret: string
label: string
issuer?: string
hmacAlgorithm?: 'sha1' | 'sha256' | 'sha512'
digits?: number
interval?: number
}
) => string
base32Encode
This will convert a Buffer into a base32 string. This is especially useful on generated buffers as most OTP apps will ask for base32 secrets.
base32Encodesecret // Converts the buffer to a string (eg. JBSWY3DPEHPK3PXP)
base32Encode(input: Buffer) => string
base32Decode(input: string) => Buffer