|
| 1 | +import { randomBytes } from 'crypto'; |
| 2 | +import { Buffer } from 'buffer'; |
| 3 | +import { validate as validateUuidv4 } from 'uuid'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Converts a standard Base64 string into a URL-safe Base64 variant: |
| 7 | + * - Replaces all "+" characters with "-" |
| 8 | + * - Replaces all "/" characters with "_" |
| 9 | + * - Strips any trailing "=" padding characters |
| 10 | + * |
| 11 | + * @param base64 - A standard Base64–encoded string |
| 12 | + * @returns The URL-safe Base64 string |
| 13 | + */ |
| 14 | +const toBase64UrlSafe = (base64: string): string => { |
| 15 | + return base64 |
| 16 | + .replace(/\+/g, '-') // converts "+" to "-" |
| 17 | + .replace(/\//g, '_') // converts "/" to "_" |
| 18 | + .replace(/=+$/, ''); // removes trailing "=" |
| 19 | +}; |
| 20 | + |
| 21 | +/** |
| 22 | + * Converts a URL-safe Base64 string back into a standard Base64 variant: |
| 23 | + * - Replaces all "-" characters with "+" |
| 24 | + * - Replaces all "_" characters with "/" |
| 25 | + * - Adds "=" padding characters at the end until length is a multiple of 4 |
| 26 | + * |
| 27 | + * @param urlSafe - A URL-safe Base64–encoded string |
| 28 | + * @returns The standard Base64 string, including any necessary "=" padding |
| 29 | + */ |
| 30 | +const fromBase64UrlSafe = (urlSafe: string): string => { |
| 31 | + let base64 = urlSafe |
| 32 | + .replace(/-/g, '+') // convert "-" back to "+" |
| 33 | + .replace(/_/g, '/'); // convert "_" back to "/" |
| 34 | + |
| 35 | + const missingPadding = (4 - (base64.length % 4)) % 4; |
| 36 | + if (missingPadding > 0) { |
| 37 | + base64 += '='.repeat(missingPadding); |
| 38 | + } |
| 39 | + return base64; |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * Generates a cryptographically secure, URL-safe string of a given length. |
| 44 | + * |
| 45 | + * Internally: |
| 46 | + * 1. Calculates how many raw bytes are needed to generate at least `size` Base64 chars. |
| 47 | + * 2. Generates secure random bytes with `crypto.randomBytes()`. |
| 48 | + * 3. Encodes to standard Base64, then makes it URL-safe. |
| 49 | + * 4. Truncates the result to `size` characters. |
| 50 | + * |
| 51 | + * @param size - Desired length of the output string (must be ≥1) |
| 52 | + * @returns A URL-safe string exactly `size` characters long |
| 53 | + */ |
| 54 | +const generateRandomStringUrlSafe = (size: number): string => { |
| 55 | + if (size <= 0) { |
| 56 | + throw new Error('Size must be a positive integer'); |
| 57 | + } |
| 58 | + // Base64 yields 4 chars per 3 bytes, so it computes the minimum bytes required |
| 59 | + const numBytes = Math.ceil((size * 3) / 4); |
| 60 | + const buf = randomBytes(numBytes).toString('base64'); |
| 61 | + |
| 62 | + return toBase64UrlSafe(buf).substring(0, size); |
| 63 | +}; |
| 64 | + |
| 65 | +/** |
| 66 | + * Converts a base64 url safe string to uuid v4 |
| 67 | + * |
| 68 | + * @example in: `8yqR2seZThOqF4xNngMjyQ` out: `f32a91da-c799-4e13-aa17-8c4d9e0323c9` |
| 69 | + */ |
| 70 | +function base64UrlSafetoUUID(base64UrlSafe: string): string { |
| 71 | + const hex = Buffer.from(fromBase64UrlSafe(base64UrlSafe), 'base64').toString('hex'); |
| 72 | + |
| 73 | + return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}` + |
| 74 | + `-${hex.substring(16, 20)}-${hex.substring(20)}`; |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Extracts a UUIDv4 from the provided parameter. If the value is not a valid UUIDv4, it tries to convert |
| 79 | + * the parameter from a Base64 URL-safe string to a UUID. In either case, it returns the provided value. |
| 80 | + * |
| 81 | + * @value value - The input parameter, which can be either a UUIDv4 or a Base64 URL-safe string. |
| 82 | + * @returns The decoded v4 UUID string. |
| 83 | + */ |
| 84 | +const decodeV4Uuid = (value: string) => { |
| 85 | + if (!validateUuidv4(value)) { |
| 86 | + try { |
| 87 | + return base64UrlSafetoUUID(value); |
| 88 | + } catch { |
| 89 | + return value; |
| 90 | + } |
| 91 | + } |
| 92 | + return value; |
| 93 | +}; |
| 94 | + |
| 95 | +/** |
| 96 | + * Encodes a UUIDv4 by removing hyphens, converting it from hexadecimal to Base64, |
| 97 | + * and then making it URL-safe. |
| 98 | + * |
| 99 | + * @param v4Uuid - The ID to be encoded, expected to be a UUIDv4 string. |
| 100 | + * @returns The encoded send ID as a URL-safe Base64 string. |
| 101 | + * @throws {Error} If the provided UUIDv4 is not valid. |
| 102 | + */ |
| 103 | +const encodeV4Uuid = (v4Uuid: string) => { |
| 104 | + if (!validateUuidv4(v4Uuid)) { |
| 105 | + throw new Error('The provided UUIDv4 is not valid'); |
| 106 | + } |
| 107 | + const removedUuidDecoration = v4Uuid.replace(/-/g, ''); |
| 108 | + const base64endoded = Buffer.from(removedUuidDecoration, 'hex').toString('base64'); |
| 109 | + const encodedSendId = toBase64UrlSafe(base64endoded); |
| 110 | + return encodedSendId; |
| 111 | +}; |
| 112 | + |
| 113 | +export default { |
| 114 | + toBase64UrlSafe, |
| 115 | + fromBase64UrlSafe, |
| 116 | + generateRandomStringUrlSafe, |
| 117 | + base64UrlSafetoUUID, |
| 118 | + decodeV4Uuid, |
| 119 | + encodeV4Uuid, |
| 120 | +}; |
0 commit comments