From 8bb87f9ea4589b606dd28538038ed8bb15bafa79 Mon Sep 17 00:00:00 2001 From: Namekuji Date: Fri, 2 Jun 2023 15:01:03 -0400 Subject: [PATCH] use native generators --- packages/backend/src/misc/gen-id.ts | 19 +++++----------- packages/backend/src/misc/secure-rndstr.ts | 25 +++------------------- 2 files changed, 8 insertions(+), 36 deletions(-) diff --git a/packages/backend/src/misc/gen-id.ts b/packages/backend/src/misc/gen-id.ts index fb92dd808c..c9e52c8295 100644 --- a/packages/backend/src/misc/gen-id.ts +++ b/packages/backend/src/misc/gen-id.ts @@ -1,14 +1,9 @@ -import { init, createId } from "@paralleldrive/cuid2"; import config from "@/config/index.js"; +import { nativeCreateId, nativeInitIdGenerator } from "native-utils/built"; -const TIME2000 = 946684800000; -const TIMESTAMP_LENGTH = 8; - -const length = - Math.min(Math.max(config.cuid?.length ?? 16, 16), 24) - TIMESTAMP_LENGTH; -const fingerprint = `${config.cuid?.fingerprint ?? ""}${createId()}`; - -const genCuid2 = init({ length, fingerprint }); +const length = Math.min(Math.max(config.cuid?.length ?? 16, 16), 24); +const fingerprint = config.cuid?.fingerprint ?? ""; +nativeInitIdGenerator(length, fingerprint); /** * The generated ID results in the form of `[8 chars timestamp] + [cuid2]`. @@ -19,9 +14,5 @@ const genCuid2 = init({ length, fingerprint }); * Ref: https://github.com/paralleldrive/cuid2#parameterized-length */ export function genId(date?: Date): string { - const now = (date ?? new Date()).getTime(); - const time = Math.max(now - TIME2000, 0); - const timestamp = time.toString(36).padStart(TIMESTAMP_LENGTH, "0"); - - return `${timestamp}${genCuid2()}`; + return nativeCreateId(BigInt((date ?? new Date()).getTime())); } diff --git a/packages/backend/src/misc/secure-rndstr.ts b/packages/backend/src/misc/secure-rndstr.ts index 7f5754e1c5..4f4c9884ae 100644 --- a/packages/backend/src/misc/secure-rndstr.ts +++ b/packages/backend/src/misc/secure-rndstr.ts @@ -1,24 +1,5 @@ -import * as crypto from "node:crypto"; +import { nativeRandomStr } from "native-utils/built"; -const L_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz"; -const LU_CHARS = - "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - -export function secureRndstr(length = 32, useLU = true): string { - const chars = useLU ? LU_CHARS : L_CHARS; - const chars_len = chars.length; - - let str = ""; - - for (let i = 0; i < length; i++) { - let rand = Math.floor( - (crypto.randomBytes(1).readUInt8(0) / 0xff) * chars_len, - ); - if (rand === chars_len) { - rand = chars_len - 1; - } - str += chars.charAt(rand); - } - - return str; +export function secureRndstr(length = 32, _ = true): string { + return nativeRandomStr(length); }