@nuxtjs/better-auth 0.0.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +67 -0
  2. package/dist/module.d.mts +47 -0
  3. package/dist/module.json +12 -0
  4. package/dist/module.mjs +1468 -0
  5. package/dist/runtime/app/components/BetterAuthState.d.vue.ts +20 -0
  6. package/dist/runtime/app/components/BetterAuthState.vue +9 -0
  7. package/dist/runtime/app/components/BetterAuthState.vue.d.ts +20 -0
  8. package/dist/runtime/app/composables/runWithSessionRefresh.d.ts +1 -0
  9. package/dist/runtime/app/composables/runWithSessionRefresh.js +12 -0
  10. package/dist/runtime/app/composables/useAction.d.ts +2 -0
  11. package/dist/runtime/app/composables/useAction.js +6 -0
  12. package/dist/runtime/app/composables/useAuthAsyncData.d.ts +6 -0
  13. package/dist/runtime/app/composables/useAuthAsyncData.js +16 -0
  14. package/dist/runtime/app/composables/useAuthClient.d.ts +9 -0
  15. package/dist/runtime/app/composables/useAuthClient.js +35 -0
  16. package/dist/runtime/app/composables/useAuthClientAction.d.ts +3 -0
  17. package/dist/runtime/app/composables/useAuthClientAction.js +15 -0
  18. package/dist/runtime/app/composables/useAuthRequestFetch.d.ts +11 -0
  19. package/dist/runtime/app/composables/useAuthRequestFetch.js +4 -0
  20. package/dist/runtime/app/composables/useSignIn.d.ts +16 -0
  21. package/dist/runtime/app/composables/useSignIn.js +8 -0
  22. package/dist/runtime/app/composables/useSignUp.d.ts +5 -0
  23. package/dist/runtime/app/composables/useSignUp.js +8 -0
  24. package/dist/runtime/app/composables/useUserSession.d.ts +23 -0
  25. package/dist/runtime/app/composables/useUserSession.js +247 -0
  26. package/dist/runtime/app/composables/useUserSessionState.d.ts +3 -0
  27. package/dist/runtime/app/composables/useUserSessionState.js +4 -0
  28. package/dist/runtime/app/internal/auth-action-error.d.ts +3 -0
  29. package/dist/runtime/app/internal/auth-action-error.js +33 -0
  30. package/dist/runtime/app/internal/auth-action-handles.d.ts +21 -0
  31. package/dist/runtime/app/internal/auth-action-handles.js +105 -0
  32. package/dist/runtime/app/internal/redirect-helpers.d.ts +4 -0
  33. package/dist/runtime/app/internal/redirect-helpers.js +37 -0
  34. package/dist/runtime/app/internal/session-fetch.d.ts +12 -0
  35. package/dist/runtime/app/internal/session-fetch.js +56 -0
  36. package/dist/runtime/app/internal/utils.d.ts +1 -0
  37. package/dist/runtime/app/internal/utils.js +3 -0
  38. package/dist/runtime/app/internal/vue-safe-auth-proxy.d.ts +3 -0
  39. package/dist/runtime/app/internal/vue-safe-auth-proxy.js +68 -0
  40. package/dist/runtime/app/internal/wrap-auth-method.d.ts +18 -0
  41. package/dist/runtime/app/internal/wrap-auth-method.js +69 -0
  42. package/dist/runtime/app/middleware/auth.global.d.ts +13 -0
  43. package/dist/runtime/app/middleware/auth.global.js +104 -0
  44. package/dist/runtime/app/pages/__better-auth-devtools.d.vue.ts +3 -0
  45. package/dist/runtime/app/pages/__better-auth-devtools.vue +380 -0
  46. package/dist/runtime/app/pages/__better-auth-devtools.vue.d.ts +3 -0
  47. package/dist/runtime/app/plugins/session.client.d.ts +2 -0
  48. package/dist/runtime/app/plugins/session.client.js +16 -0
  49. package/dist/runtime/app/plugins/session.server.d.ts +2 -0
  50. package/dist/runtime/app/plugins/session.server.js +24 -0
  51. package/dist/runtime/composables.d.ts +12 -0
  52. package/dist/runtime/composables.js +10 -0
  53. package/dist/runtime/config.d.ts +100 -0
  54. package/dist/runtime/config.js +13 -0
  55. package/dist/runtime/internal/auth-route-rules.d.ts +1 -0
  56. package/dist/runtime/internal/auth-route-rules.js +24 -0
  57. package/dist/runtime/server/api/_better-auth/_schema.d.ts +4 -0
  58. package/dist/runtime/server/api/_better-auth/_schema.js +12 -0
  59. package/dist/runtime/server/api/_better-auth/accounts.get.d.ts +2 -0
  60. package/dist/runtime/server/api/_better-auth/accounts.get.js +29 -0
  61. package/dist/runtime/server/api/_better-auth/config.get.d.ts +2 -0
  62. package/dist/runtime/server/api/_better-auth/config.get.js +58 -0
  63. package/dist/runtime/server/api/_better-auth/sessions.delete.d.ts +2 -0
  64. package/dist/runtime/server/api/_better-auth/sessions.delete.js +23 -0
  65. package/dist/runtime/server/api/_better-auth/sessions.get.d.ts +2 -0
  66. package/dist/runtime/server/api/_better-auth/sessions.get.js +44 -0
  67. package/dist/runtime/server/api/_better-auth/users.get.d.ts +2 -0
  68. package/dist/runtime/server/api/_better-auth/users.get.js +35 -0
  69. package/dist/runtime/server/api/auth/[...all].d.ts +2 -0
  70. package/dist/runtime/server/api/auth/[...all].js +6 -0
  71. package/dist/runtime/server/internal/nitro-compat.d.ts +1 -0
  72. package/dist/runtime/server/internal/nitro-compat.js +1 -0
  73. package/dist/runtime/server/internal/nitro2.d.ts +8 -0
  74. package/dist/runtime/server/internal/nitro2.js +29 -0
  75. package/dist/runtime/server/internal/nitro3.d.ts +10 -0
  76. package/dist/runtime/server/internal/nitro3.js +60 -0
  77. package/dist/runtime/server/middleware/route-access.d.ts +2 -0
  78. package/dist/runtime/server/middleware/route-access.js +29 -0
  79. package/dist/runtime/server/tsconfig.json +12 -0
  80. package/dist/runtime/server/utils/auth.d.ts +20 -0
  81. package/dist/runtime/server/utils/auth.js +246 -0
  82. package/dist/runtime/server/utils/custom-secondary-storage.d.ts +6 -0
  83. package/dist/runtime/server/utils/custom-secondary-storage.js +8 -0
  84. package/dist/runtime/server/utils/session.d.ts +8 -0
  85. package/dist/runtime/server/utils/session.js +280 -0
  86. package/dist/runtime/server/virtual-modules.d.ts +27 -0
  87. package/dist/runtime/types/augment.d.ts +56 -0
  88. package/dist/runtime/types/augment.js +0 -0
  89. package/dist/runtime/types.d.ts +21 -0
  90. package/dist/runtime/types.js +0 -0
  91. package/dist/runtime/utils/match-user.d.ts +2 -0
  92. package/dist/runtime/utils/match-user.js +13 -0
  93. package/dist/types.d.mts +11 -0
  94. package/package.json +111 -10
  95. package/index.js +0 -1
@@ -0,0 +1,58 @@
1
+ import { defineEventHandler, useRuntimeConfig } from "../../internal/nitro-compat.js";
2
+ import { serverAuth } from "../../utils/auth.js";
3
+ export default defineEventHandler(async (event) => {
4
+ try {
5
+ const auth = serverAuth(event);
6
+ const options = auth.options;
7
+ const authContext = await auth.$context;
8
+ const runtimeConfig = useRuntimeConfig();
9
+ const publicAuth = runtimeConfig.public?.auth;
10
+ const privateAuth = runtimeConfig.auth;
11
+ const configuredTrustedOrigins = Array.isArray(options.trustedOrigins) ? options.trustedOrigins : [];
12
+ const effectiveTrustedOrigins = authContext?.trustedOrigins || configuredTrustedOrigins;
13
+ const sessionConfig = options.session || {};
14
+ const expiresInDays = sessionConfig.expiresIn ? Math.round(sessionConfig.expiresIn / 86400) : 7;
15
+ const updateAgeDays = sessionConfig.updateAge ? Math.round(sessionConfig.updateAge / 86400) : 1;
16
+ return {
17
+ config: {
18
+ // Module config (nuxt.config.ts)
19
+ module: {
20
+ redirects: {
21
+ login: publicAuth?.redirects?.login ?? "/login",
22
+ guest: publicAuth?.redirects?.guest ?? "/",
23
+ authenticated: publicAuth?.redirects?.authenticated,
24
+ logout: publicAuth?.redirects?.logout
25
+ },
26
+ preserveRedirect: publicAuth?.preserveRedirect ?? true,
27
+ redirectQueryKey: publicAuth?.redirectQueryKey ?? "redirect",
28
+ hubSecondaryStorage: privateAuth?.hubSecondaryStorage ?? false,
29
+ useDatabase: publicAuth?.useDatabase ?? false,
30
+ databaseProvider: publicAuth?.databaseProvider ?? "none"
31
+ },
32
+ // Server config (server/auth.config.ts)
33
+ server: {
34
+ baseURL: options.baseURL,
35
+ basePath: options.basePath || "/api/auth",
36
+ socialProviders: Object.keys(options.socialProviders || {}),
37
+ plugins: (options.plugins || []).map((p) => p.id || "unknown"),
38
+ trustedOrigins: effectiveTrustedOrigins,
39
+ configuredTrustedOrigins,
40
+ session: {
41
+ expiresIn: `${expiresInDays} days`,
42
+ updateAge: `${updateAgeDays} days`,
43
+ cookieCache: sessionConfig.cookieCache?.enabled ?? false
44
+ },
45
+ emailAndPassword: !!options.emailAndPassword,
46
+ rateLimit: options.rateLimit?.enabled ?? false,
47
+ advanced: {
48
+ useSecureCookies: options.advanced?.useSecureCookies ?? "auto",
49
+ disableCSRFCheck: options.advanced?.disableCSRFCheck ?? false
50
+ }
51
+ }
52
+ }
53
+ };
54
+ } catch (error) {
55
+ console.error("[DevTools] Config fetch failed:", error);
56
+ return { config: null, error: "Failed to fetch configuration" };
57
+ }
58
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ import { createAuthError, defineEventHandler, readBody } from "../../internal/nitro-compat.js";
3
+ const deleteSessionSchema = z.object({
4
+ id: z.string().min(1, "Session ID required")
5
+ });
6
+ export default defineEventHandler(async (event) => {
7
+ try {
8
+ const body = deleteSessionSchema.parse(await readBody(event));
9
+ const { db } = await import("@nuxthub/db");
10
+ const { schema } = await import("#auth/schema");
11
+ if (!schema?.session)
12
+ throw createAuthError(500, "Session table not found");
13
+ const { eq } = await import("drizzle-orm");
14
+ await db.delete(schema.session).where(eq(schema.session.id, body.id));
15
+ return { success: true };
16
+ } catch (error) {
17
+ if (error instanceof z.ZodError) {
18
+ throw createAuthError(400, error.errors[0]?.message || "Invalid request");
19
+ }
20
+ console.error("[DevTools] Delete session failed:", error);
21
+ throw createAuthError(500, "Failed to delete session");
22
+ }
23
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,44 @@
1
+ import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
2
+ import { defineEventHandler, getQuery } from "../../internal/nitro-compat.js";
3
+ export default defineEventHandler(async (event) => {
4
+ try {
5
+ const { db } = await import("@nuxthub/db");
6
+ const { schema } = await import("#auth/schema");
7
+ if (!schema?.session)
8
+ return { sessions: [], total: 0, error: "Session table not found" };
9
+ const query = paginationQuerySchema.parse(getQuery(event));
10
+ const { page, limit, search } = query;
11
+ const offset = (page - 1) * limit;
12
+ const { count, like, or, desc } = await import("drizzle-orm");
13
+ let dbQuery = db.select().from(schema.session);
14
+ let countQuery = db.select({ count: count() }).from(schema.session);
15
+ if (search) {
16
+ const pattern = sanitizeSearchPattern(search);
17
+ const searchCondition = or(
18
+ like(schema.session.userId, pattern),
19
+ schema.session.ipAddress ? like(schema.session.ipAddress, pattern) : void 0
20
+ );
21
+ if (searchCondition) {
22
+ dbQuery = dbQuery.where(searchCondition);
23
+ countQuery = countQuery.where(searchCondition);
24
+ }
25
+ }
26
+ const [sessions, totalResult] = await Promise.all([
27
+ dbQuery.orderBy(desc(schema.session.createdAt)).limit(limit).offset(offset),
28
+ countQuery
29
+ ]);
30
+ const safeSessions = sessions.map((s) => ({
31
+ id: s.id,
32
+ userId: s.userId,
33
+ createdAt: s.createdAt,
34
+ updatedAt: s.updatedAt,
35
+ expiresAt: s.expiresAt,
36
+ ipAddress: s.ipAddress,
37
+ userAgent: s.userAgent
38
+ }));
39
+ return { sessions: safeSessions, total: totalResult[0]?.count ?? 0, page, limit };
40
+ } catch (error) {
41
+ console.error("[DevTools] Fetch sessions failed:", error);
42
+ return { sessions: [], total: 0, error: "Failed to fetch sessions" };
43
+ }
44
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,35 @@
1
+ import { paginationQuerySchema, sanitizeSearchPattern } from "./_schema.js";
2
+ import { defineEventHandler, getQuery } from "../../internal/nitro-compat.js";
3
+ export default defineEventHandler(async (event) => {
4
+ try {
5
+ const { db } = await import("@nuxthub/db");
6
+ const { schema } = await import("#auth/schema");
7
+ if (!schema?.user)
8
+ return { users: [], total: 0, error: "User table not found" };
9
+ const query = paginationQuerySchema.parse(getQuery(event));
10
+ const { page, limit, search } = query;
11
+ const offset = (page - 1) * limit;
12
+ const { count, like, or, desc } = await import("drizzle-orm");
13
+ let dbQuery = db.select().from(schema.user);
14
+ let countQuery = db.select({ count: count() }).from(schema.user);
15
+ if (search) {
16
+ const pattern = sanitizeSearchPattern(search);
17
+ const searchCondition = or(
18
+ like(schema.user.name, pattern),
19
+ like(schema.user.email, pattern)
20
+ );
21
+ if (searchCondition) {
22
+ dbQuery = dbQuery.where(searchCondition);
23
+ countQuery = countQuery.where(searchCondition);
24
+ }
25
+ }
26
+ const [users, totalResult] = await Promise.all([
27
+ dbQuery.orderBy(desc(schema.user.createdAt)).limit(limit).offset(offset),
28
+ countQuery
29
+ ]);
30
+ return { users, total: totalResult[0]?.count ?? 0, page, limit };
31
+ } catch (error) {
32
+ console.error("[DevTools] Fetch users failed:", error);
33
+ return { users: [], total: 0, error: "Failed to fetch users" };
34
+ }
35
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { defineEventHandler, toWebRequest } from "../../internal/nitro-compat.js";
2
+ import { serverAuth } from "../../utils/auth.js";
3
+ export default defineEventHandler(async (event) => {
4
+ const auth = serverAuth(event);
5
+ return auth.handler(toWebRequest(event));
6
+ });
@@ -0,0 +1 @@
1
+ export * from '#better-auth/nitro-compat';
@@ -0,0 +1 @@
1
+ export * from "#better-auth/nitro-compat";
@@ -0,0 +1,8 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { AuthRouteRules } from '../../types.js';
3
+ import { defineEventHandler, getQuery, getRequestHost, getRequestProtocol, getRequestURL, readBody, splitCookiesString, toWebRequest } from 'h3';
4
+ import { useRuntimeConfig } from 'nitropack/runtime';
5
+ export { defineEventHandler, getQuery, getRequestHost, getRequestProtocol, getRequestURL, readBody, splitCookiesString, toWebRequest, useRuntimeConfig, };
6
+ export type ServerEvent = H3Event;
7
+ export declare function getAuthRouteRules(event: ServerEvent): AuthRouteRules;
8
+ export declare function createAuthError(status: number, statusText: string): Error;
@@ -0,0 +1,29 @@
1
+ import {
2
+ createError,
3
+ defineEventHandler,
4
+ getQuery,
5
+ getRequestHost,
6
+ getRequestProtocol,
7
+ getRequestURL,
8
+ readBody,
9
+ splitCookiesString,
10
+ toWebRequest
11
+ } from "h3";
12
+ import { getRouteRules, useRuntimeConfig } from "nitropack/runtime";
13
+ export {
14
+ defineEventHandler,
15
+ getQuery,
16
+ getRequestHost,
17
+ getRequestProtocol,
18
+ getRequestURL,
19
+ readBody,
20
+ splitCookiesString,
21
+ toWebRequest,
22
+ useRuntimeConfig
23
+ };
24
+ export function getAuthRouteRules(event) {
25
+ return getRouteRules(event);
26
+ }
27
+ export function createAuthError(status, statusText) {
28
+ return createError({ statusCode: status, statusMessage: statusText });
29
+ }
@@ -0,0 +1,10 @@
1
+ import type { H3Event } from 'nitro/h3';
2
+ import type { AuthRouteRules } from '../../types.js';
3
+ import { defineEventHandler, getQuery, getRequestHost, getRequestProtocol, getRequestURL, readBody } from 'nitro/h3';
4
+ import { useRuntimeConfig } from 'nitro/runtime-config';
5
+ export { defineEventHandler, getQuery, getRequestHost, getRequestProtocol, getRequestURL, readBody, useRuntimeConfig, };
6
+ export type ServerEvent = H3Event;
7
+ export declare function getAuthRouteRules(event: ServerEvent): AuthRouteRules;
8
+ export declare function createAuthError(status: number, statusText: string): Error;
9
+ export declare function toWebRequest(event: ServerEvent): Request;
10
+ export declare function splitCookiesString(header: string): string[];
@@ -0,0 +1,60 @@
1
+ import { getRouteRules } from "nitro/app";
2
+ import {
3
+ defineEventHandler,
4
+ getQuery,
5
+ getRequestHost,
6
+ getRequestProtocol,
7
+ getRequestURL,
8
+ HTTPError,
9
+ readBody
10
+ } from "nitro/h3";
11
+ import { useRuntimeConfig } from "nitro/runtime-config";
12
+ export {
13
+ defineEventHandler,
14
+ getQuery,
15
+ getRequestHost,
16
+ getRequestProtocol,
17
+ getRequestURL,
18
+ readBody,
19
+ useRuntimeConfig
20
+ };
21
+ export function getAuthRouteRules(event) {
22
+ const auth = getRouteRules(event.req.method, getRequestURL(event).pathname).routeRules.auth?.options;
23
+ return { auth };
24
+ }
25
+ export function createAuthError(status, statusText) {
26
+ return HTTPError.status(status, statusText);
27
+ }
28
+ export function toWebRequest(event) {
29
+ return event.req;
30
+ }
31
+ export function splitCookiesString(header) {
32
+ const cookies = [];
33
+ let position = 0;
34
+ while (position < header.length) {
35
+ const start = position;
36
+ let separator;
37
+ while (position < header.length) {
38
+ if (header[position] !== ",") {
39
+ position += 1;
40
+ continue;
41
+ }
42
+ separator = position;
43
+ position += 1;
44
+ while (position < header.length && /\s/.test(header[position]))
45
+ position += 1;
46
+ const nextStart = position;
47
+ while (position < header.length && !["=", ";", ","].includes(header[position]))
48
+ position += 1;
49
+ if (header[position] === "=") {
50
+ cookies.push(header.slice(start, separator));
51
+ position = nextStart;
52
+ break;
53
+ }
54
+ position = separator + 1;
55
+ }
56
+ if (separator === void 0 || position >= header.length)
57
+ cookies.push(header.slice(start));
58
+ }
59
+ return cookies;
60
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,29 @@
1
+ import { shouldSkipAuthRouteRules } from "../../internal/auth-route-rules.js";
2
+ import { matchesUser } from "../../utils/match-user.js";
3
+ import { createAuthError, defineEventHandler, getAuthRouteRules, getRequestURL } from "../internal/nitro-compat.js";
4
+ import { getUserSession, requireUserSession } from "../utils/session.js";
5
+ export default defineEventHandler(async (event) => {
6
+ const path = getRequestURL(event).pathname;
7
+ if (!path.startsWith("/api/"))
8
+ return;
9
+ if (shouldSkipAuthRouteRules(path))
10
+ return;
11
+ const rules = getAuthRouteRules(event);
12
+ if (!rules.auth)
13
+ return;
14
+ const auth = rules.auth;
15
+ const mode = typeof auth === "string" ? auth : auth?.only ?? "user";
16
+ if (mode === "guest") {
17
+ const session = await getUserSession(event);
18
+ if (session)
19
+ throw createAuthError(403, "Authenticated users not allowed");
20
+ return;
21
+ }
22
+ if (mode === "user") {
23
+ const session = await requireUserSession(event);
24
+ if (typeof auth === "object" && auth.user) {
25
+ if (!matchesUser(session.user, auth.user))
26
+ throw createAuthError(403, "Access denied");
27
+ }
28
+ }
29
+ });
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "../../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "baseUrl": ".",
5
+ "paths": {
6
+ "#better-auth/nitro-compat": ["./internal/nitro2"],
7
+ "#nuxt-better-auth": ["../types/augment"]
8
+ }
9
+ },
10
+ "include": ["./**/*.ts", "./**/*.d.ts"],
11
+ "exclude": ["node_modules"]
12
+ }
@@ -0,0 +1,20 @@
1
+ import type { BetterAuthOptions } from 'better-auth';
2
+ import type { ServerEvent } from '../internal/nitro-compat.js';
3
+ import { betterAuth } from 'better-auth';
4
+ import createServerAuth from '#auth/server';
5
+ type AuthOptions = ReturnType<typeof createServerAuth>;
6
+ type UserAuthConfig = AuthOptions & {
7
+ secrets?: BetterAuthOptions['secrets'];
8
+ trustedOrigins?: BetterAuthOptions['trustedOrigins'];
9
+ secondaryStorage?: BetterAuthOptions['secondaryStorage'];
10
+ };
11
+ type ResolvedAuthOptions = UserAuthConfig & {
12
+ secret: string;
13
+ baseURL: string;
14
+ trustedOrigins?: BetterAuthOptions['trustedOrigins'];
15
+ database?: BetterAuthOptions['database'];
16
+ };
17
+ type AuthInstance = ReturnType<typeof betterAuth<ResolvedAuthOptions>>;
18
+ /** Returns Better Auth instance. Caches per resolved host (or single instance when siteUrl is explicit). */
19
+ export declare function serverAuth(event?: ServerEvent): AuthInstance;
20
+ export {};
@@ -0,0 +1,246 @@
1
+ import { betterAuth, env } from "better-auth";
2
+ import { withoutProtocol } from "ufo";
3
+ import { createDatabase, db } from "#auth/database";
4
+ import { createSecondaryStorage } from "#auth/secondary-storage";
5
+ import createServerAuth from "#auth/server";
6
+ import { getRequestHost, getRequestProtocol, useRuntimeConfig } from "../internal/nitro-compat.js";
7
+ import { resolveCustomSecondaryStorageRequirement } from "./custom-secondary-storage.js";
8
+ const _authCache = /* @__PURE__ */ new Map();
9
+ const requestAuthKey = Symbol.for("nuxt-better-auth.requestAuth");
10
+ let _baseURLInferenceLogged = false;
11
+ let _customSecondaryStorageMisconfigWarned = false;
12
+ const fallbackRequestAuthContext = /* @__PURE__ */ new WeakMap();
13
+ function getRequestAuthContext(event) {
14
+ const eventWithContext = event;
15
+ if (eventWithContext.context && typeof eventWithContext.context === "object")
16
+ return eventWithContext.context;
17
+ let context = fallbackRequestAuthContext.get(event);
18
+ if (!context) {
19
+ context = {};
20
+ fallbackRequestAuthContext.set(event, context);
21
+ }
22
+ return context;
23
+ }
24
+ function normalizeLoopbackOrigin(origin) {
25
+ if (!import.meta.dev)
26
+ return origin;
27
+ try {
28
+ const url = new URL(origin);
29
+ if (url.hostname === "127.0.0.1" || url.hostname === "::1" || url.hostname === "[::1]") {
30
+ url.hostname = "localhost";
31
+ return url.origin;
32
+ }
33
+ } catch {
34
+ }
35
+ return origin;
36
+ }
37
+ function logInferredBaseURL(baseURL, source) {
38
+ if (!import.meta.dev || _baseURLInferenceLogged)
39
+ return;
40
+ _baseURLInferenceLogged = true;
41
+ console.warn(`[nuxt-better-auth] Using inferred baseURL "${baseURL}" from ${source}. Set runtimeConfig.public.siteUrl for deterministic OAuth callbacks.`);
42
+ }
43
+ function validateURL(url) {
44
+ try {
45
+ return normalizeLoopbackOrigin(new URL(url).origin);
46
+ } catch {
47
+ throw new Error(`Invalid siteUrl: "${url}". Must be a valid URL.`);
48
+ }
49
+ }
50
+ function resolveConfiguredSiteUrl(config) {
51
+ if (typeof config.public.siteUrl !== "string" || !config.public.siteUrl)
52
+ return void 0;
53
+ return validateURL(config.public.siteUrl);
54
+ }
55
+ function resolveEventOrigin(event) {
56
+ if (!event)
57
+ return void 0;
58
+ const host = getRequestHost(event, { xForwardedHost: true });
59
+ const protocol = getRequestProtocol(event, { xForwardedProto: true });
60
+ if (!host || !protocol)
61
+ return void 0;
62
+ try {
63
+ return validateURL(`${protocol}://${host}`);
64
+ } catch {
65
+ return void 0;
66
+ }
67
+ }
68
+ function getNitroOrigin() {
69
+ const cert = process.env.NITRO_SSL_CERT;
70
+ const key = process.env.NITRO_SSL_KEY;
71
+ let host = process.env.NITRO_HOST || process.env.HOST;
72
+ let port;
73
+ if (import.meta.dev)
74
+ port = process.env.NITRO_PORT || process.env.PORT || "3000";
75
+ let protocol = cert && key || !import.meta.dev ? "https" : "http";
76
+ try {
77
+ if ((import.meta.dev || import.meta.prerender) && process.env.__NUXT_DEV__) {
78
+ const origin = JSON.parse(process.env.__NUXT_DEV__).proxy.url;
79
+ host = withoutProtocol(origin);
80
+ protocol = origin.includes("https") ? "https" : "http";
81
+ } else if ((import.meta.dev || import.meta.prerender) && process.env.NUXT_VITE_NODE_OPTIONS) {
82
+ const origin = JSON.parse(process.env.NUXT_VITE_NODE_OPTIONS).baseURL.replace("/__nuxt_vite_node__", "");
83
+ host = withoutProtocol(origin);
84
+ protocol = origin.includes("https") ? "https" : "http";
85
+ }
86
+ } catch {
87
+ }
88
+ if (!host)
89
+ return void 0;
90
+ if (host.startsWith("[") && host.includes("]:")) {
91
+ const lastBracketColon = host.lastIndexOf("]:");
92
+ const extractedPort = host.slice(lastBracketColon + 2);
93
+ host = host.slice(0, lastBracketColon + 1);
94
+ if (extractedPort)
95
+ port = extractedPort;
96
+ } else if (host.includes(":") && !host.startsWith("[")) {
97
+ const hostParts = host.split(":");
98
+ port = hostParts.pop();
99
+ host = hostParts.join(":");
100
+ }
101
+ const portSuffix = port ? `:${port}` : "";
102
+ return `${protocol}://${host}${portSuffix}`;
103
+ }
104
+ function resolveEnvironmentOrigin() {
105
+ const nitroOrigin = getNitroOrigin();
106
+ if (nitroOrigin)
107
+ return { origin: validateURL(nitroOrigin), source: "Nitro environment detection" };
108
+ if (process.env.VERCEL_URL)
109
+ return { origin: validateURL(`https://${process.env.VERCEL_URL}`), source: "VERCEL_URL" };
110
+ if (process.env.CF_PAGES_URL)
111
+ return { origin: validateURL(`https://${process.env.CF_PAGES_URL}`), source: "CF_PAGES_URL" };
112
+ if (process.env.URL)
113
+ return { origin: validateURL(process.env.URL.startsWith("http") ? process.env.URL : `https://${process.env.URL}`), source: "URL" };
114
+ return void 0;
115
+ }
116
+ function resolveDevFallback() {
117
+ if (!import.meta.dev)
118
+ return void 0;
119
+ return { origin: "http://localhost:3000", source: "development fallback" };
120
+ }
121
+ function getBaseURL(event) {
122
+ const config = useRuntimeConfig();
123
+ const configuredSiteUrl = resolveConfiguredSiteUrl(config);
124
+ if (configuredSiteUrl)
125
+ return configuredSiteUrl;
126
+ const eventOrigin = resolveEventOrigin(event);
127
+ if (eventOrigin) {
128
+ logInferredBaseURL(eventOrigin, "request origin");
129
+ return eventOrigin;
130
+ }
131
+ const environmentOrigin = resolveEnvironmentOrigin();
132
+ if (environmentOrigin) {
133
+ logInferredBaseURL(environmentOrigin.origin, environmentOrigin.source);
134
+ return environmentOrigin.origin;
135
+ }
136
+ const devFallback = resolveDevFallback();
137
+ if (devFallback) {
138
+ logInferredBaseURL(devFallback.origin, devFallback.source);
139
+ return devFallback.origin;
140
+ }
141
+ throw new Error("siteUrl required. Set NUXT_PUBLIC_SITE_URL.");
142
+ }
143
+ function dedupeOrigins(origins) {
144
+ return [...new Set(origins)];
145
+ }
146
+ function getDevTrustedOrigins() {
147
+ const fallbackOrigin = "http://localhost:3000";
148
+ const nitroOrigin = getNitroOrigin();
149
+ if (!nitroOrigin)
150
+ return [fallbackOrigin];
151
+ try {
152
+ const url = new URL(nitroOrigin);
153
+ const protocol = url.protocol === "https:" ? "https" : "http";
154
+ const port = url.port || "3000";
155
+ const localhostOrigin = `${protocol}://localhost:${port}`;
156
+ return dedupeOrigins([localhostOrigin, url.origin]);
157
+ } catch {
158
+ return [fallbackOrigin];
159
+ }
160
+ }
161
+ function getRequestOrigin(request) {
162
+ if (!request)
163
+ return void 0;
164
+ try {
165
+ return new URL(request.url).origin;
166
+ } catch {
167
+ return void 0;
168
+ }
169
+ }
170
+ function withDevTrustedOrigins(trustedOrigins) {
171
+ if (!import.meta.dev)
172
+ return trustedOrigins;
173
+ const devOrigins = getDevTrustedOrigins();
174
+ const mergeOrigins = (origins, request) => {
175
+ const validOrigins = origins.filter((origin) => typeof origin === "string");
176
+ const requestOrigin = getRequestOrigin(request);
177
+ return dedupeOrigins(requestOrigin ? [...validOrigins, ...devOrigins, requestOrigin] : [...validOrigins, ...devOrigins]);
178
+ };
179
+ if (typeof trustedOrigins === "function") {
180
+ return async (request) => {
181
+ const resolvedOrigins = await trustedOrigins(request);
182
+ return mergeOrigins(resolvedOrigins, request);
183
+ };
184
+ }
185
+ if (Array.isArray(trustedOrigins)) {
186
+ const baseOrigins = mergeOrigins(trustedOrigins);
187
+ return async (request) => {
188
+ return mergeOrigins(baseOrigins, request);
189
+ };
190
+ }
191
+ return async (request) => {
192
+ return mergeOrigins([], request);
193
+ };
194
+ }
195
+ export function serverAuth(event) {
196
+ const runtimeConfig = useRuntimeConfig();
197
+ const betterAuthSecret = runtimeConfig.betterAuthSecret || env.BETTER_AUTH_SECRET || "";
198
+ if (betterAuthSecret && betterAuthSecret.length < 32)
199
+ throw new Error("[nuxt-better-auth] Singular auth secret must be at least 32 characters for security");
200
+ const requestOrigin = resolveEventOrigin(event);
201
+ let userConfig;
202
+ if (!import.meta.dev && !betterAuthSecret && !env.BETTER_AUTH_SECRETS) {
203
+ userConfig = createServerAuth({ runtimeConfig, db, requestOrigin });
204
+ if (userConfig.secrets === void 0)
205
+ throw new Error("[nuxt-better-auth] An auth secret is required in production. Set NUXT_BETTER_AUTH_SECRET, BETTER_AUTH_SECRET, BETTER_AUTH_SECRETS, or defineServerAuth({ secrets }).");
206
+ }
207
+ const siteUrl = getBaseURL(event);
208
+ const hasExplicitSiteUrl = runtimeConfig.public.siteUrl && typeof runtimeConfig.public.siteUrl === "string";
209
+ const cacheKey = hasExplicitSiteUrl ? "__explicit__" : siteUrl;
210
+ const requestContext = event ? getRequestAuthContext(event) : void 0;
211
+ if (requestContext?.[requestAuthKey])
212
+ return requestContext[requestAuthKey];
213
+ userConfig ??= createServerAuth({ runtimeConfig, db, requestOrigin });
214
+ const database = createDatabase(event);
215
+ const trustedOrigins = withDevTrustedOrigins(userConfig.trustedOrigins);
216
+ const hubSecondaryStorage = runtimeConfig.auth?.hubSecondaryStorage;
217
+ const customSecondaryStorage = resolveCustomSecondaryStorageRequirement(hubSecondaryStorage, userConfig.secondaryStorage != null, Boolean(import.meta.dev));
218
+ if (customSecondaryStorage?.shouldThrow)
219
+ throw new Error(customSecondaryStorage.message);
220
+ if (customSecondaryStorage?.shouldWarn && !_customSecondaryStorageMisconfigWarned) {
221
+ _customSecondaryStorageMisconfigWarned = true;
222
+ console.warn(customSecondaryStorage.message);
223
+ }
224
+ if (!database) {
225
+ const cached = _authCache.get(cacheKey);
226
+ if (cached) {
227
+ if (requestContext)
228
+ requestContext[requestAuthKey] = cached;
229
+ return cached;
230
+ }
231
+ }
232
+ const authOptions = {
233
+ ...userConfig,
234
+ ...database ? { database } : {},
235
+ ...hubSecondaryStorage === true ? { secondaryStorage: createSecondaryStorage() } : {},
236
+ secret: betterAuthSecret,
237
+ baseURL: siteUrl,
238
+ trustedOrigins
239
+ };
240
+ const auth = betterAuth(authOptions);
241
+ if (requestContext)
242
+ requestContext[requestAuthKey] = auth;
243
+ if (!database)
244
+ _authCache.set(cacheKey, auth);
245
+ return auth;
246
+ }
@@ -0,0 +1,6 @@
1
+ export type HubSecondaryStorageMode = boolean | 'custom' | undefined;
2
+ export declare function resolveCustomSecondaryStorageRequirement(hubSecondaryStorage: HubSecondaryStorageMode, userHasSecondaryStorage: boolean, isDev: boolean): {
3
+ shouldThrow: boolean;
4
+ shouldWarn: boolean;
5
+ message: string;
6
+ } | null;
@@ -0,0 +1,8 @@
1
+ export function resolveCustomSecondaryStorageRequirement(hubSecondaryStorage, userHasSecondaryStorage, isDev) {
2
+ if (hubSecondaryStorage !== "custom")
3
+ return null;
4
+ if (userHasSecondaryStorage)
5
+ return null;
6
+ const message = '[nuxt-better-auth] hubSecondaryStorage: "custom" requires secondaryStorage in defineServerAuth().';
7
+ return { shouldThrow: !isDev, shouldWarn: isDev, message };
8
+ }
@@ -0,0 +1,8 @@
1
+ import type { AppSession, AuthSession, RequireSessionOptions } from '#nuxt-better-auth';
2
+ import type { ServerEvent } from '../internal/nitro-compat.js';
3
+ export declare function getRequestSession(event: ServerEvent): Promise<AppSession | null>;
4
+ export declare function getUserSession(event: ServerEvent): Promise<AppSession | null>;
5
+ export declare function refreshSessionCookieCache(event: ServerEvent): Promise<AppSession | null>;
6
+ export declare function setSessionCookie(event: ServerEvent, token: string): Promise<void>;
7
+ export declare function createSession(event: ServerEvent, userId: string): Promise<AuthSession>;
8
+ export declare function requireUserSession(event: ServerEvent, options?: RequireSessionOptions): Promise<AppSession>;