diff --git a/common/util/random.ts b/common/util/random.ts index f52294f1..3026dcde 100644 --- a/common/util/random.ts +++ b/common/util/random.ts @@ -1,7 +1,11 @@ -export const randomString = (length = 12) => - Math.random() - .toString(16) - .substring(2, length + 2) +// Returns a cryptographically random hexadecimal string of length `length` +// (thus containing 4*`length` bits of entropy). +export const randomString = (length = 12) => { + const bytes = new Uint8Array(Math.ceil(length / 2)) + crypto.getRandomValues(bytes) + const hex = bytes.reduce((s, b) => s + ('0' + b.toString(16)).slice(-2), '') + return hex.substring(0, length) +} export function genHash(str: string) { // xmur3 diff --git a/functions/src/create-user.ts b/functions/src/create-user.ts index f73b868b..fdbb0edd 100644 --- a/functions/src/create-user.ts +++ b/functions/src/create-user.ts @@ -42,8 +42,7 @@ export const createUser = functions const name = cleanDisplayName(rawName) let username = cleanUsername(name) - const sameNameUser = await getUserByUsername(username) - if (sameNameUser) { + while (await getUserByUsername(username)) { username += randomString(4) }