|
| 1 | +/** |
| 2 | + * @fileoverview |
| 3 | + * A powerful and flexible OTP (One-Time Password) generator |
| 4 | + * Supports digits, uppercase, lowercase, symbols, and custom length |
| 5 | + */ |
| 6 | + |
| 7 | +export interface OTPOptions { |
| 8 | + /** Include digits like 0–9 (default: true) */ |
| 9 | + digits?: boolean; |
| 10 | + /** Include lowercase letters like a–z */ |
| 11 | + lowerCase?: boolean; |
| 12 | + /** Include uppercase letters like A–Z */ |
| 13 | + upperCase?: boolean; |
| 14 | + /** Include symbols like @, #, $, %, etc. */ |
| 15 | + symbols?: boolean; |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Generate a secure, random OTP using specified options. |
| 20 | + * Uses crypto.getRandomValues() for cryptographically secure randomness. |
| 21 | + * |
| 22 | + * @param length - Total length of the OTP (e.g., 6) |
| 23 | + * @param options - Character type options to include |
| 24 | + * @returns A string containing the generated OTP |
| 25 | + */ |
| 26 | +export function generateOTP(length: number, options: OTPOptions = { digits: true }): string { |
| 27 | + // Character pools |
| 28 | + const digitChars = '0123456789'; |
| 29 | + const lowerChars = 'abcdefghijklmnopqrstuvwxyz'; |
| 30 | + const upperChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 31 | + const symbolChars = '!@#$%^&*()_+[]{}<>?'; |
| 32 | + |
| 33 | + // Combine selected character types into one string |
| 34 | + let characters = ''; |
| 35 | + |
| 36 | + if (options.digits) characters += digitChars; |
| 37 | + if (options.lowerCase) characters += lowerChars; |
| 38 | + if (options.upperCase) characters += upperChars; |
| 39 | + if (options.symbols) characters += symbolChars; |
| 40 | + |
| 41 | + // Ensure at least one type is selected |
| 42 | + if (!characters) { |
| 43 | + throw new Error('At least one character type must be enabled in options.'); |
| 44 | + } |
| 45 | + |
| 46 | + let otp = ''; |
| 47 | + |
| 48 | + // Secure randomness: get 'length' random numbers using crypto API |
| 49 | + const cryptoObj = window.crypto || (window as any).msCrypto; // msCrypto fallback for old Edge |
| 50 | + const randomValues = new Uint32Array(length); |
| 51 | + cryptoObj.getRandomValues(randomValues); |
| 52 | + |
| 53 | + // Build OTP by mapping each random number to character in pool |
| 54 | + for (let i = 0; i < length; i++) { |
| 55 | + const index = randomValues[i] % characters.length; |
| 56 | + otp += characters.charAt(index); |
| 57 | + } |
| 58 | + |
| 59 | + return otp; |
| 60 | +} |
0 commit comments