@colingreybosh/otp-lib
Version:
A TypeScript library for generating, validating, and managing one-time passwords (OTP) for authentication purposes.
34 lines • 1.44 kB
JavaScript
import { randomBytes } from 'node:crypto';
import { OTPException } from '../types';
import { decode, encode } from './base32';
export function generateSecret(length = 32) {
if (!Number.isInteger(length) || length <= 0) {
throw new OTPException('INVALID_SECRET', 'Secret length must be a positive integer');
}
if (![20, 32, 64].includes(length)) {
throw new OTPException('INVALID_SECRET', 'Secret length must be 20, 32, or 64 bytes');
}
try {
const randomBuffer = randomBytes(length);
return encode(randomBuffer);
}
catch (error) {
throw new OTPException('INVALID_SECRET', `Failed to generate secret: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
export function decodeSecretForHMAC(base32Secret) {
if (!base32Secret || typeof base32Secret !== 'string') {
throw new OTPException('INVALID_SECRET', 'Secret must be a non-empty string');
}
const cleanSecret = base32Secret.replace(/\s/g, '').toUpperCase();
if (!/^[A-Z2-7]+=*$/.test(cleanSecret)) {
throw new OTPException('INVALID_SECRET', 'Secret must be a valid base32-encoded string (A-Z, 2-7)');
}
try {
return decode(cleanSecret);
}
catch (error) {
throw new OTPException('INVALID_SECRET', `Failed to decode base32 secret: ${error instanceof Error ? error.message : 'Invalid base32 format'}`);
}
}
//# sourceMappingURL=crypto.js.map