Skip to content

Commit ce6ea39

Browse files
authored
fix: use Random Number from crypto to generate AutoId
This reverts commit 05b3363.
1 parent 05b3363 commit ce6ea39

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

dev/src/util.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17+
import {randomBytes} from 'crypto';
1718
import {GoogleError, ServiceConfig, Status} from 'google-gax';
1819

1920
import {DocumentData} from './types';
@@ -52,8 +53,17 @@ export function autoId(): string {
5253
const chars =
5354
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
5455
let autoId = '';
55-
for (let i = 0; i < 20; i++) {
56-
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
56+
while (autoId.length < 20) {
57+
const bytes = randomBytes(40);
58+
bytes.forEach(b => {
59+
// Length of `chars` is 62. We only take bytes between 0 and 62*4-1
60+
// (both inclusive). The value is then evenly mapped to indices of `char`
61+
// via a modulo operation.
62+
const maxValue = 62 * 4 - 1;
63+
if (autoId.length < 20 && b <= maxValue) {
64+
autoId += chars.charAt(b % 62);
65+
}
66+
});
5767
}
5868
return autoId;
5969
}

0 commit comments

Comments
 (0)