|
| 1 | +import { randomBytes } from "./deps.ts"; |
| 2 | +import { promisify } from "./deps.ts"; |
| 3 | +import { |
| 4 | + ALLOWED_TYPES, |
| 5 | + ALPHANUMERIC_CHARACTERS, |
| 6 | + ASCII_PRINTABLE_CHARACTERS, |
| 7 | + DISTINGUISHABLE_CHARACTERS, |
| 8 | + NUMERIC_CHARACTERS, |
| 9 | + URL_SAFE_CHARACTERS, |
| 10 | +} from "./constants.ts"; |
| 11 | + |
| 12 | +const randomBytesAsync = promisify(randomBytes); |
| 13 | + |
| 14 | +const generateForCustomCharacters = (length: number, characters: string[]) => { |
| 15 | + // Generating entropy is faster than complex math operations, so we use the simplest way |
| 16 | + const characterCount = characters.length; |
| 17 | + const maxValidSelector = |
| 18 | + (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division |
| 19 | + const entropyLength = 2 * Math.ceil(1.1 * length); // Generating a bit more than required so chances we need more than one pass will be really low |
| 20 | + let string = ""; |
| 21 | + let stringLength = 0; |
| 22 | + |
| 23 | + while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it |
| 24 | + const entropy = randomBytes(entropyLength); |
| 25 | + let entropyPosition = 0; |
| 26 | + |
| 27 | + while (entropyPosition < entropyLength && stringLength < length) { |
| 28 | + const entropyValue = entropy.readUInt16LE(entropyPosition); |
| 29 | + entropyPosition += 2; |
| 30 | + if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division |
| 31 | + continue; |
| 32 | + } |
| 33 | + |
| 34 | + string += characters[entropyValue % characterCount]; |
| 35 | + stringLength++; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return string; |
| 40 | +}; |
| 41 | + |
| 42 | +const generateForCustomCharactersAsync = async ( |
| 43 | + length: number, |
| 44 | + characters: string[], |
| 45 | +) => { |
| 46 | + // Generating entropy is faster than complex math operations, so we use the simplest way |
| 47 | + const characterCount = characters.length; |
| 48 | + const maxValidSelector = |
| 49 | + (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division |
| 50 | + const entropyLength = 2 * Math.ceil(1.1 * length); // Generating a bit more than required so chances we need more than one pass will be really low |
| 51 | + let string = ""; |
| 52 | + let stringLength = 0; |
| 53 | + |
| 54 | + while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it |
| 55 | + const entropy = await randomBytesAsync(entropyLength); // eslint-disable-line no-await-in-loop |
| 56 | + let entropyPosition = 0; |
| 57 | + |
| 58 | + while (entropyPosition < entropyLength && stringLength < length) { |
| 59 | + const entropyValue = entropy.readUInt16LE(entropyPosition); |
| 60 | + entropyPosition += 2; |
| 61 | + if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + string += characters[entropyValue % characterCount]; |
| 66 | + stringLength++; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return string; |
| 71 | +}; |
| 72 | + |
| 73 | +const generateRandomBytes = ( |
| 74 | + byteLength: number, |
| 75 | + type: string, |
| 76 | + length: number, |
| 77 | +) => randomBytes(byteLength).toString(type).slice(0, length); |
| 78 | + |
| 79 | +const generateRandomBytesAsync = async ( |
| 80 | + byteLength: number, |
| 81 | + type: string, |
| 82 | + length: number, |
| 83 | +) => { |
| 84 | + const buffer = await randomBytesAsync(byteLength); |
| 85 | + return buffer.toString(type).slice(0, length); |
| 86 | +}; |
| 87 | + |
| 88 | +const createGenerator = ( |
| 89 | + generateForCustomCharacters: Function, |
| 90 | + generateRandomBytes: Function, |
| 91 | +) => |
| 92 | + ( |
| 93 | + { length, type, characters }: { |
| 94 | + length: number; |
| 95 | + type?: string; |
| 96 | + characters?: string; |
| 97 | + }, |
| 98 | + ) => { |
| 99 | + if (!(length >= 0 && Number.isFinite(length))) { |
| 100 | + throw new TypeError( |
| 101 | + "Expected a `length` to be a non-negative finite number", |
| 102 | + ); |
| 103 | + } |
| 104 | + |
| 105 | + if (type !== undefined && characters !== undefined) { |
| 106 | + throw new TypeError("Expected either `type` or `characters`"); |
| 107 | + } |
| 108 | + |
| 109 | + if (characters !== undefined && typeof characters !== "string") { |
| 110 | + throw new TypeError("Expected `characters` to be string"); |
| 111 | + } |
| 112 | + |
| 113 | + if (!ALLOWED_TYPES.includes(type)) { |
| 114 | + throw new TypeError(`Unknown type: ${type}`); |
| 115 | + } |
| 116 | + |
| 117 | + if (type === undefined && characters === undefined) { |
| 118 | + type = "hex"; |
| 119 | + } |
| 120 | + |
| 121 | + if (type === "hex") { |
| 122 | + return generateRandomBytes(Math.ceil(length * 0.5), "hex", length); // Need 0.5 byte entropy per character |
| 123 | + } |
| 124 | + |
| 125 | + if (type === "base64") { |
| 126 | + return generateRandomBytes(Math.ceil(length * 0.75), "base64", length); // Need 0.75 byte of entropy per character |
| 127 | + } |
| 128 | + |
| 129 | + if (type === "url-safe") { |
| 130 | + return generateForCustomCharacters(length, URL_SAFE_CHARACTERS); |
| 131 | + } |
| 132 | + |
| 133 | + if (type === "numeric") { |
| 134 | + return generateForCustomCharacters(length, NUMERIC_CHARACTERS); |
| 135 | + } |
| 136 | + |
| 137 | + if (type === "distinguishable") { |
| 138 | + return generateForCustomCharacters(length, DISTINGUISHABLE_CHARACTERS); |
| 139 | + } |
| 140 | + |
| 141 | + if (type === "ascii-printable") { |
| 142 | + return generateForCustomCharacters(length, ASCII_PRINTABLE_CHARACTERS); |
| 143 | + } |
| 144 | + |
| 145 | + if (type === "alphanumeric") { |
| 146 | + return generateForCustomCharacters(length, ALPHANUMERIC_CHARACTERS); |
| 147 | + } |
| 148 | + |
| 149 | + if (characters !== undefined && characters.length === 0) { |
| 150 | + throw new TypeError( |
| 151 | + "Expected `characters` string length to be greater than or equal to 1", |
| 152 | + ); |
| 153 | + } |
| 154 | + |
| 155 | + if (characters !== undefined && characters.length > 0x10000) { |
| 156 | + throw new TypeError( |
| 157 | + "Expected `characters` string length to be less or equal to 65536", |
| 158 | + ); |
| 159 | + } |
| 160 | + |
| 161 | + return generateForCustomCharacters(length, characters!.split("")); |
| 162 | + }; |
| 163 | + |
| 164 | +const cryptoRandomString = createGenerator( |
| 165 | + generateForCustomCharacters, |
| 166 | + generateRandomBytes, |
| 167 | +); |
| 168 | +const cryptoRandomStringAsync = createGenerator( |
| 169 | + generateForCustomCharactersAsync, |
| 170 | + generateRandomBytesAsync, |
| 171 | +); |
| 172 | + |
| 173 | +export { cryptoRandomString, cryptoRandomStringAsync }; |
0 commit comments