Time-based one-time password (TOTP) is a computer algorithm that generates a one-time password (OTP) that uses the current time as a source of uniqueness. As an extension of the HMAC-based one-time password algorithm (HOTP), it has been adopted as Internet Engineering Task Force (IETF) standard RFC 6238.
TOTP is the cornerstone of Initiative for Open Authentication (OATH), and is used in a number of two-factor authentication (2FA) systems.
The server generates a private key that is used with HMAC-SHA1 to encrypt the epoch timer, then the generated cryptographic HMAC hash is used to calculate the password of typically 6 or 8 digits. The private key is encoded in Base32 to deliver it in a human-readable form to the user.
QR codes are used to encode a secret key as a URI so that it can be easily added to any authenticator application.
Secret keys may be encoded in QR codes as a URI with the following format:
otpauth://TYPE/LABEL?PARAMETERS
Example with all optional parameters supplied:
otpauth://totp/NodeJS:example@email.com?secret=XXXXX&issuer=NodeJS&algorithm=SHA1&digits=6&period=30
Use OTP Authenticator Migration URL Parser to parse the exported QR code data from the Google Authenticator application.
Reference: Google Authenticator - Key Uri Format.
npm install flipeador/node-otp-2fa
import { setInterval } from 'node:timers';
import {
generateSecret,
generateTOTP,
otpauthURL
} from '@flipeador/node-otp-2fa';
const secret = generateSecret(24);
setInterval(() => {
const totp = generateTOTP(secret);
totp.remaining = `Expires in ${totp.period-totp.time%totp.period}s`;
totp.url = otpauthURL({
label: 'example@email.com',
issuer: 'Node',
...totp
});
console.log(totp);
}, 1000);
{
secret: 'N23Y253JQO7VDN7VBTP64N33',
buffer: <Buffer 6e b7 8d 77 69 83 bf 51 b7 f5 0c df ee 37 7b>,
algorithm: 'sha1',
digits: 6,
period: 30,
time: 1668889958,
password: '586899',
remaining: 'Expires in 22s',
url: 'otpauth://totp/Node%3Aexample%40email.com?secret=N23Y253JQO7VDN7VBTP64N33&issuer=Node&algorithm=sha1&digits=6&period=30'
}
This project is licensed under the Apache License 2.0. See the license file for details.