From b8a656efc8c63edf3d5edcc2992076c078482b73 Mon Sep 17 00:00:00 2001 From: Bereket Engida <86073083+Bekacru@users.noreply.github.com> Date: Thu, 20 Nov 2025 14:54:17 -0800 Subject: [PATCH] chore: use generate random string helper (#6140) --- packages/better-auth/src/plugins/api-key/index.ts | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/packages/better-auth/src/plugins/api-key/index.ts b/packages/better-auth/src/plugins/api-key/index.ts index a4f9c17092..4d7f05df81 100644 --- a/packages/better-auth/src/plugins/api-key/index.ts +++ b/packages/better-auth/src/plugins/api-key/index.ts @@ -4,6 +4,7 @@ import { defineErrorCodes } from "@better-auth/core/utils"; import { base64Url } from "@better-auth/utils/base64"; import { createHash } from "@better-auth/utils/hash"; import { APIError } from "../../api"; +import { generateRandomString } from "../../crypto/random"; import { mergeSchema } from "../../db"; import { getDate } from "../../utils/date"; import { getIp } from "../../utils/get-request-ip"; @@ -119,14 +120,8 @@ export const apiKey = (options?: ApiKeyOptions | undefined) => { const keyGenerator = opts.customKeyGenerator || (async (options: { length: number; prefix: string | undefined }) => { - const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - let apiKey = `${options.prefix || ""}`; - for (let i = 0; i < options.length; i++) { - const randomIndex = Math.floor(Math.random() * characters.length); - apiKey += characters[randomIndex]; - } - - return apiKey; + const key = generateRandomString(options.length, "a-z", "A-Z"); + return `${options.prefix || ""}${key}`; }); const routes = createApiKeyRoutes({ keyGenerator, opts, schema });