UNPKG

@colingreybosh/otp-lib

Version:

A TypeScript library for generating, validating, and managing one-time passwords (OTP) for authentication purposes.

62 lines 2.38 kB
import { OTPException } from '../types'; import { decodeSecretForHMAC } from './crypto'; export function validateSecret(secret, algorithm) { if (!secret || typeof secret !== 'string') { throw new OTPException('INVALID_SECRET', 'Secret must be a non-empty string'); } const decodedSecret = decodeSecretForHMAC(secret); const expectedLength = getSecretLength(algorithm); if (decodedSecret.length !== expectedLength) { throw new OTPException('INVALID_SECRET', `Secret must be ${expectedLength.toString()} bytes long for ${algorithm} algorithm`); } } export function getSecretLength(algorithm) { switch (algorithm) { case 'SHA1': return 20; case 'SHA256': return 32; case 'SHA512': return 64; default: throw new UnexpectedCaseError(algorithm); } } class UnexpectedCaseError extends Error { constructor(value) { super(`Unexpected case: ${value}`); } } export function validateAlgorithm(algorithm) { const validAlgorithms = ['SHA1', 'SHA256', 'SHA512']; if (!validAlgorithms.includes(algorithm)) { throw new OTPException('INVALID_ALGORITHM', `Algorithm must be one of: ${validAlgorithms.join(', ')}`); } } export function validateDigits(digits) { if (!Number.isInteger(digits) || digits < 6 || digits > 8) { throw new OTPException('INVALID_DIGITS', 'Digits must be an integer between 6 and 8'); } } export function validatePeriod(period) { if (!Number.isInteger(period) || period <= 0) { throw new OTPException('INVALID_PERIOD', 'Period must be a positive integer'); } } export function validateCounter(counter) { if (!Number.isInteger(counter) || counter < 0) { throw new OTPException('INVALID_COUNTER', 'Counter must be a non-negative integer'); } } export function validateToken(token, expectedLength) { if (!token || typeof token !== 'string') { throw new OTPException('INVALID_TOKEN', 'Token must be a non-empty string'); } if (!/^\d+$/.test(token)) { throw new OTPException('INVALID_TOKEN', 'Token must contain only digits'); } if (token.length !== expectedLength) { throw new OTPException('INVALID_TOKEN', `Token must be exactly ${expectedLength.toString()} digits long`); } } //# sourceMappingURL=validation.js.map