better-auth
Version:
The most comprehensive authentication framework for TypeScript.
1 lines • 15 kB
Source Map (JSON)
{"version":3,"file":"create-context.mjs","names":["defu","logger","providers: OAuthProvider[]","generateIdFunc: AuthContext[\"generateId\"]","ctx: AuthContext","context: AuthContext"],"sources":["../../src/context/create-context.ts"],"sourcesContent":["import type { AuthContext, BetterAuthOptions } from \"@better-auth/core\";\nimport { getAuthTables } from \"@better-auth/core/db\";\nimport type { DBAdapter } from \"@better-auth/core/db/adapter\";\nimport { createLogger, env, isProduction, isTest } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport type { OAuthProvider } from \"@better-auth/core/oauth2\";\nimport type { SocialProviders } from \"@better-auth/core/social-providers\";\nimport { socialProviders } from \"@better-auth/core/social-providers\";\nimport { createTelemetry } from \"@better-auth/telemetry\";\nimport defu from \"defu\";\nimport type { Entries } from \"type-fest\";\nimport { checkEndpointConflicts } from \"../api\";\nimport { matchesOriginPattern } from \"../auth/trusted-origins\";\nimport { createCookieGetter, getCookies } from \"../cookies\";\nimport { hashPassword, verifyPassword } from \"../crypto/password\";\nimport { createInternalAdapter } from \"../db/internal-adapter\";\nimport { generateId } from \"../utils\";\nimport { DEFAULT_SECRET } from \"../utils/constants\";\nimport { isPromise } from \"../utils/is-promise\";\nimport { checkPassword } from \"../utils/password\";\nimport { getBaseURL } from \"../utils/url\";\nimport {\n\tgetInternalPlugins,\n\tgetTrustedOrigins,\n\trunPluginInit,\n} from \"./helpers\";\n\n/**\n * Estimates the entropy of a string in bits.\n * This is a simple approximation that helps detect low-entropy secrets.\n */\nfunction estimateEntropy(str: string): number {\n\tconst unique = new Set(str).size;\n\tif (unique === 0) return 0;\n\treturn Math.log2(Math.pow(unique, str.length));\n}\n\n/**\n * Validates that the secret meets minimum security requirements.\n * Throws BetterAuthError if the secret is invalid.\n * Skips validation for DEFAULT_SECRET in test environments only.\n * Only throws for DEFAULT_SECRET in production environment.\n */\nfunction validateSecret(\n\tsecret: string,\n\tlogger: ReturnType<typeof createLogger>,\n): void {\n\tconst isDefaultSecret = secret === DEFAULT_SECRET;\n\n\tif (isTest()) {\n\t\treturn;\n\t}\n\n\tif (isDefaultSecret && isProduction) {\n\t\tthrow new BetterAuthError(\n\t\t\t\"You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.\",\n\t\t);\n\t}\n\n\tif (!secret) {\n\t\tthrow new BetterAuthError(\n\t\t\t\"BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).\",\n\t\t);\n\t}\n\n\tif (secret.length < 32) {\n\t\tthrow new BetterAuthError(\n\t\t\t`Invalid BETTER_AUTH_SECRET: must be at least 32 characters long for adequate security. Generate one with \\`npx @better-auth/cli secret\\` or \\`openssl rand -base64 32\\`.`,\n\t\t);\n\t}\n\n\t// Optional high-entropy check: warn if entropy appears low\n\tconst entropy = estimateEntropy(secret);\n\tif (entropy < 120) {\n\t\tlogger.warn(\n\t\t\t\"[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.\",\n\t\t);\n\t}\n}\n\nexport async function createAuthContext(\n\tadapter: DBAdapter<BetterAuthOptions>,\n\toptions: BetterAuthOptions,\n\tgetDatabaseType: (database: BetterAuthOptions[\"database\"]) => string,\n): Promise<AuthContext> {\n\t//set default options for stateless mode\n\tif (!options.database) {\n\t\toptions = defu(options, {\n\t\t\tsession: {\n\t\t\t\tcookieCache: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tstrategy: \"jwe\" as const,\n\t\t\t\t\trefreshCache: true,\n\t\t\t\t},\n\t\t\t},\n\t\t\taccount: {\n\t\t\t\tstoreStateStrategy: \"cookie\" as const,\n\t\t\t\tstoreAccountCookie: true,\n\t\t\t},\n\t\t});\n\t}\n\tconst plugins = options.plugins || [];\n\tconst internalPlugins = getInternalPlugins(options);\n\tconst logger = createLogger(options.logger);\n\tconst baseURL = getBaseURL(options.baseURL, options.basePath);\n\n\tif (!baseURL) {\n\t\tlogger.warn(\n\t\t\t`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_BASE_URL environment variable. Without this, callbacks and redirects may not work correctly.`,\n\t\t);\n\t}\n\n\tconst secret =\n\t\toptions.secret ||\n\t\tenv.BETTER_AUTH_SECRET ||\n\t\tenv.AUTH_SECRET ||\n\t\tDEFAULT_SECRET;\n\n\tvalidateSecret(secret, logger);\n\n\toptions = {\n\t\t...options,\n\t\tsecret,\n\t\tbaseURL: baseURL ? new URL(baseURL).origin : \"\",\n\t\tbasePath: options.basePath || \"/api/auth\",\n\t\tplugins: plugins.concat(internalPlugins),\n\t};\n\n\tcheckEndpointConflicts(options, logger);\n\tconst cookies = getCookies(options);\n\tconst tables = getAuthTables(options);\n\tconst providers: OAuthProvider[] = (\n\t\tObject.entries(\n\t\t\toptions.socialProviders || {},\n\t\t) as unknown as Entries<SocialProviders>\n\t)\n\t\t.map(([key, config]) => {\n\t\t\tif (config == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (config.enabled === false) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!config.clientId) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Social provider ${key} is missing clientId or clientSecret`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst provider = socialProviders[key](config as never);\n\t\t\t(provider as OAuthProvider).disableImplicitSignUp =\n\t\t\t\tconfig.disableImplicitSignUp;\n\t\t\treturn provider;\n\t\t})\n\t\t.filter((x) => x !== null);\n\n\tconst generateIdFunc: AuthContext[\"generateId\"] = ({ model, size }) => {\n\t\tif (typeof (options.advanced as any)?.generateId === \"function\") {\n\t\t\treturn (options.advanced as any).generateId({ model, size });\n\t\t}\n\t\tif (typeof options?.advanced?.database?.generateId === \"function\") {\n\t\t\treturn options.advanced.database.generateId({ model, size });\n\t\t}\n\t\treturn generateId(size);\n\t};\n\n\tconst { publish } = await createTelemetry(options, {\n\t\tadapter: adapter.id,\n\t\tdatabase:\n\t\t\ttypeof options.database === \"function\"\n\t\t\t\t? \"adapter\"\n\t\t\t\t: getDatabaseType(options.database),\n\t});\n\n\tlet ctx: AuthContext = {\n\t\tappName: options.appName || \"Better Auth\",\n\t\tsocialProviders: providers,\n\t\toptions,\n\t\toauthConfig: {\n\t\t\tstoreStateStrategy:\n\t\t\t\toptions.account?.storeStateStrategy ||\n\t\t\t\t(options.database ? \"database\" : \"cookie\"),\n\t\t\tskipStateCookieCheck: !!options.account?.skipStateCookieCheck,\n\t\t},\n\t\ttables,\n\t\ttrustedOrigins: await getTrustedOrigins(options),\n\t\tisTrustedOrigin(\n\t\t\turl: string,\n\t\t\tsettings?: {\n\t\t\t\tallowRelativePaths: boolean;\n\t\t\t},\n\t\t) {\n\t\t\treturn ctx.trustedOrigins.some((origin) =>\n\t\t\t\tmatchesOriginPattern(url, origin, settings),\n\t\t\t);\n\t\t},\n\t\tbaseURL: baseURL || \"\",\n\t\tsessionConfig: {\n\t\t\tupdateAge:\n\t\t\t\toptions.session?.updateAge !== undefined\n\t\t\t\t\t? options.session.updateAge\n\t\t\t\t\t: 24 * 60 * 60,\n\t\t\texpiresIn: options.session?.expiresIn || 60 * 60 * 24 * 7,\n\t\t\tfreshAge:\n\t\t\t\toptions.session?.freshAge === undefined\n\t\t\t\t\t? 60 * 60 * 24\n\t\t\t\t\t: options.session.freshAge,\n\t\t\tcookieRefreshCache: (() => {\n\t\t\t\tconst refreshCache = options.session?.cookieCache?.refreshCache;\n\t\t\t\tconst maxAge = options.session?.cookieCache?.maxAge || 60 * 5;\n\n\t\t\t\t// `refreshCache` is intended for fully stateless / DB-less setups.\n\t\t\t\t// If a server-side store is configured, prefer fetching/refreshing from that source\n\t\t\t\t// and disable stateless refresh behavior to avoid confusing/unsafe configurations.\n\t\t\t\tconst isStateful = !!options.database || !!options.secondaryStorage;\n\t\t\t\tif (isStateful && refreshCache) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\"[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning.\",\n\t\t\t\t\t);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif (refreshCache === false || refreshCache === undefined) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif (refreshCache === true) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tupdateAge: Math.floor(maxAge * 0.2),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tupdateAge:\n\t\t\t\t\t\trefreshCache.updateAge !== undefined\n\t\t\t\t\t\t\t? refreshCache.updateAge\n\t\t\t\t\t\t\t: Math.floor(maxAge * 0.2),\n\t\t\t\t};\n\t\t\t})(),\n\t\t},\n\t\tsecret,\n\t\trateLimit: {\n\t\t\t...options.rateLimit,\n\t\t\tenabled: options.rateLimit?.enabled ?? isProduction,\n\t\t\twindow: options.rateLimit?.window || 10,\n\t\t\tmax: options.rateLimit?.max || 100,\n\t\t\tstorage:\n\t\t\t\toptions.rateLimit?.storage ||\n\t\t\t\t(options.secondaryStorage ? \"secondary-storage\" : \"memory\"),\n\t\t},\n\t\tauthCookies: cookies,\n\t\tlogger,\n\t\tgenerateId: generateIdFunc,\n\t\tsession: null,\n\t\tsecondaryStorage: options.secondaryStorage,\n\t\tpassword: {\n\t\t\thash: options.emailAndPassword?.password?.hash || hashPassword,\n\t\t\tverify: options.emailAndPassword?.password?.verify || verifyPassword,\n\t\t\tconfig: {\n\t\t\t\tminPasswordLength: options.emailAndPassword?.minPasswordLength || 8,\n\t\t\t\tmaxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128,\n\t\t\t},\n\t\t\tcheckPassword,\n\t\t},\n\t\tsetNewSession(session) {\n\t\t\tthis.newSession = session;\n\t\t},\n\t\tnewSession: null,\n\t\tadapter: adapter,\n\t\tinternalAdapter: createInternalAdapter(adapter, {\n\t\t\toptions,\n\t\t\tlogger,\n\t\t\thooks: options.databaseHooks ? [options.databaseHooks] : [],\n\t\t\tgenerateId: generateIdFunc,\n\t\t}),\n\t\tcreateAuthCookie: createCookieGetter(options),\n\t\tasync runMigrations() {\n\t\t\tthrow new BetterAuthError(\n\t\t\t\t\"runMigrations will be set by the specific init implementation\",\n\t\t\t);\n\t\t},\n\t\tpublishTelemetry: publish,\n\t\tskipCSRFCheck: !!options.advanced?.disableCSRFCheck,\n\t\tskipOriginCheck:\n\t\t\toptions.advanced?.disableOriginCheck !== undefined\n\t\t\t\t? options.advanced.disableOriginCheck\n\t\t\t\t: isTest()\n\t\t\t\t\t? true\n\t\t\t\t\t: false,\n\t\trunInBackground:\n\t\t\toptions.advanced?.backgroundTasks?.handler ??\n\t\t\t((p) => {\n\t\t\t\tp.catch(() => {});\n\t\t\t}),\n\t\tasync runInBackgroundOrAwait(\n\t\t\tpromise: Promise<unknown> | Promise<void> | void | unknown,\n\t\t) {\n\t\t\ttry {\n\t\t\t\tif (options.advanced?.backgroundTasks?.handler) {\n\t\t\t\t\tif (promise instanceof Promise) {\n\t\t\t\t\t\toptions.advanced.backgroundTasks.handler(\n\t\t\t\t\t\t\tpromise.catch((e) => {\n\t\t\t\t\t\t\t\tlogger.error(\"Failed to run background task:\", e);\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tawait promise;\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(\"Failed to run background task:\", e);\n\t\t\t}\n\t\t},\n\t};\n\n\tconst initOrPromise = runPluginInit(ctx);\n\tlet context: AuthContext;\n\tif (isPromise(initOrPromise)) {\n\t\t({ context } = await initOrPromise);\n\t} else {\n\t\t({ context } = initOrPromise);\n\t}\n\n\treturn context;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,gBAAgB,KAAqB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