@neondatabase/auth 0.1.0-beta.15 → 0.1.0-beta.17

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 (40) hide show
  1. package/README.md +1 -0
  2. package/dist/{adapter-core-ChIlSbGg.mjs → adapter-core-BQ6ga1zK.mjs} +2 -28
  3. package/dist/{better-auth-react-adapter-C3_WRaIy.mjs → better-auth-react-adapter-BLKXYcWM.mjs} +1 -1
  4. package/dist/{better-auth-react-adapter-AucJqubr.d.mts → better-auth-react-adapter-BWH-XVdf.d.mts} +1 -1
  5. package/dist/constants-2bpp2_-f.mjs +30 -0
  6. package/dist/index-B4dy0AqC.d.mts +49 -0
  7. package/dist/index.d.mts +5 -105
  8. package/dist/index.mjs +2 -2
  9. package/dist/middleware-DPLYghmx.mjs +303 -0
  10. package/dist/{neon-auth-sSiNq4zM.mjs → neon-auth-ClDZNB9a.mjs} +1 -1
  11. package/dist/neon-auth-DDPaciiS.d.mts +105 -0
  12. package/dist/next/index.d.mts +63 -98
  13. package/dist/next/index.mjs +26 -301
  14. package/dist/next/server/index.d.mts +389 -0
  15. package/dist/next/server/index.mjs +432 -0
  16. package/dist/react/adapters/index.d.mts +4 -4
  17. package/dist/react/adapters/index.mjs +2 -2
  18. package/dist/react/index.d.mts +5 -5
  19. package/dist/react/index.mjs +4 -5
  20. package/dist/react/ui/index.d.mts +1 -1
  21. package/dist/react/ui/index.mjs +2 -3
  22. package/dist/react/ui/server.mjs +2 -2
  23. package/dist/{supabase-adapter-DhlcXYb9.mjs → supabase-adapter-Bl576usk.mjs} +2 -1
  24. package/dist/{supabase-adapter-Bbn88gZj.d.mts → supabase-adapter-k8RBezY9.d.mts} +1 -1
  25. package/dist/types/index.d.mts +2 -2
  26. package/dist/ui-DLtIc4wi.mjs +4 -0
  27. package/dist/vanilla/adapters/index.d.mts +4 -4
  28. package/dist/vanilla/adapters/index.mjs +2 -2
  29. package/dist/vanilla/index.d.mts +4 -4
  30. package/dist/vanilla/index.mjs +2 -2
  31. package/package.json +5 -1
  32. package/dist/chunk-5DLVHPZS-Bxj7snpZ-EhdAQJMu.mjs +0 -533
  33. package/dist/ui-C1IRQzLY.mjs +0 -9449
  34. /package/dist/{adapter-core-CtcS7ex8.d.mts → adapter-core-Sx7jkLdB.d.mts} +0 -0
  35. /package/dist/{adapters-D0mxG3F-.mjs → adapters-CUvhsAvY.mjs} +0 -0
  36. /package/dist/{adapters-Df6Dd3KK.mjs → adapters-CivF9wql.mjs} +0 -0
  37. /package/dist/{better-auth-types-VqadyqlG.d.mts → better-auth-types-Kq3kGuiz.d.mts} +0 -0
  38. /package/dist/{index-ClXLQ1fw.d.mts → index-D8dPsry7.d.mts} +0 -0
  39. /package/dist/{index-BXlAjlSt.d.mts → index-D_HDtZfY.d.mts} +0 -0
  40. /package/dist/{index-DCQ5Y2ED.d.mts → index-OEBbnNdr.d.mts} +0 -0
package/README.md CHANGED
@@ -242,6 +242,7 @@ For Next.js projects, this package provides built-in integration via `@neondatab
242
242
  - Importing styles (with or without Tailwind CSS)
243
243
  - Accessing session data with `neonAuth()` in server components
244
244
  - Using `authClient.useSession()` hook in client components
245
+ - Server-side auth operations with `createAuthServer()` from `@neondatabase/auth/next/server`
245
246
 
246
247
  ## CSS for UI Components
247
248
 
@@ -1,3 +1,4 @@
1
+ import { a as NEON_AUTH_POPUP_CALLBACK_ROUTE, c as OAUTH_POPUP_MESSAGE_TYPE, i as NEON_AUTH_POPUP_CALLBACK_PARAM_NAME, l as SESSION_CACHE_TTL_MS, o as NEON_AUTH_POPUP_PARAM_NAME, s as NEON_AUTH_SESSION_VERIFIER_PARAM_NAME, t as CLOCK_SKEW_BUFFER_MS } from "./constants-2bpp2_-f.mjs";
1
2
  import { getGlobalBroadcastChannel } from "better-auth/client";
2
3
  import { adminClient, emailOTPClient, jwtClient, organizationClient } from "better-auth/client/plugins";
3
4
  import z from "zod";
@@ -100,33 +101,6 @@ var InFlightRequestManager = class {
100
101
  }
101
102
  };
102
103
 
103
- //#endregion
104
- //#region src/core/constants.ts
105
- /**
106
- * Session caching configuration constants
107
- *
108
- * Uses industry-standard 60s cache TTL (common across auth providers).
109
- *
110
- * Note: Token refresh detection is now automatic via Better Auth's
111
- * fetchOptions.onSuccess callback. No polling is needed.
112
- */
113
- /** Session cache TTL in milliseconds (60 seconds) */
114
- const SESSION_CACHE_TTL_MS = 6e4;
115
- /** Clock skew buffer for token expiration checks in milliseconds (10 seconds) */
116
- const CLOCK_SKEW_BUFFER_MS = 1e4;
117
- /** Default session expiry duration in milliseconds (1 hour) */
118
- const DEFAULT_SESSION_EXPIRY_MS = 36e5;
119
- /** Name of the session verifier parameter in the URL, used for the OAUTH flow */
120
- const NEON_AUTH_SESSION_VERIFIER_PARAM_NAME = "neon_auth_session_verifier";
121
- /** Name of the popup marker parameter in the URL, used for OAuth popup flow in iframes */
122
- const NEON_AUTH_POPUP_PARAM_NAME = "neon_popup";
123
- /** Name of the original callback URL parameter, used in OAuth popup flow */
124
- const NEON_AUTH_POPUP_CALLBACK_PARAM_NAME = "neon_popup_callback";
125
- /** The callback route used for OAuth popup completion (must be in middleware SKIP_ROUTES) */
126
- const NEON_AUTH_POPUP_CALLBACK_ROUTE = "/auth/callback";
127
- /** Message type for OAuth popup completion postMessage */
128
- const OAUTH_POPUP_MESSAGE_TYPE = "neon-auth:oauth-complete";
129
-
130
104
  //#endregion
131
105
  //#region src/utils/jwt.ts
132
106
  /**
@@ -740,4 +714,4 @@ var NeonAuthAdapterCore = class {
740
714
  };
741
715
 
742
716
  //#endregion
743
- export { DEFAULT_SESSION_EXPIRY_MS as a, CURRENT_TAB_CLIENT_ID as i, BETTER_AUTH_METHODS_CACHE as n, NEON_AUTH_SESSION_VERIFIER_PARAM_NAME as o, BETTER_AUTH_METHODS_HOOKS as r, NeonAuthAdapterCore as t };
717
+ export { CURRENT_TAB_CLIENT_ID as i, BETTER_AUTH_METHODS_CACHE as n, BETTER_AUTH_METHODS_HOOKS as r, NeonAuthAdapterCore as t };
@@ -1,4 +1,4 @@
1
- import { t as NeonAuthAdapterCore } from "./adapter-core-ChIlSbGg.mjs";
1
+ import { t as NeonAuthAdapterCore } from "./adapter-core-BQ6ga1zK.mjs";
2
2
  import { createAuthClient } from "better-auth/react";
3
3
 
4
4
  //#region src/adapters/better-auth-react/better-auth-react-adapter.ts
@@ -1,4 +1,4 @@
1
- import { n as NeonAuthAdapterCoreAuthOptions, t as NeonAuthAdapterCore } from "./adapter-core-CtcS7ex8.mjs";
1
+ import { n as NeonAuthAdapterCoreAuthOptions, t as NeonAuthAdapterCore } from "./adapter-core-Sx7jkLdB.mjs";
2
2
  import * as better_auth_client11 from "better-auth/client";
3
3
  import * as better_auth_client_plugins5 from "better-auth/client/plugins";
4
4
  import * as jose0 from "jose";
@@ -0,0 +1,30 @@
1
+ //#region src/core/constants.ts
2
+ /**
3
+ * Session caching configuration constants
4
+ *
5
+ * Uses industry-standard 60s cache TTL (common across auth providers).
6
+ *
7
+ * Note: Token refresh detection is now automatic via Better Auth's
8
+ * fetchOptions.onSuccess callback. No polling is needed.
9
+ */
10
+ /** Session cache TTL in milliseconds (60 seconds) */
11
+ const SESSION_CACHE_TTL_MS = 6e4;
12
+ /** Clock skew buffer for token expiration checks in milliseconds (10 seconds) */
13
+ const CLOCK_SKEW_BUFFER_MS = 1e4;
14
+ /** Default session expiry duration in milliseconds (1 hour) */
15
+ const DEFAULT_SESSION_EXPIRY_MS = 36e5;
16
+ /** Name of the session verifier parameter in the URL, used for the OAUTH flow */
17
+ const NEON_AUTH_SESSION_VERIFIER_PARAM_NAME = "neon_auth_session_verifier";
18
+ /** Name of the popup marker parameter in the URL, used for OAuth popup flow in iframes */
19
+ const NEON_AUTH_POPUP_PARAM_NAME = "neon_popup";
20
+ /** Name of the original callback URL parameter, used in OAuth popup flow */
21
+ const NEON_AUTH_POPUP_CALLBACK_PARAM_NAME = "neon_popup_callback";
22
+ /** The callback route used for OAuth popup completion (must be in middleware SKIP_ROUTES) */
23
+ const NEON_AUTH_POPUP_CALLBACK_ROUTE = "/auth/callback";
24
+ /** Message type for OAuth popup completion postMessage */
25
+ const OAUTH_POPUP_MESSAGE_TYPE = "neon-auth:oauth-complete";
26
+ /** Prefix for all Neon Auth cookies */
27
+ const NEON_AUTH_COOKIE_PREFIX = "__Secure-neon-auth";
28
+
29
+ //#endregion
30
+ export { NEON_AUTH_POPUP_CALLBACK_ROUTE as a, OAUTH_POPUP_MESSAGE_TYPE as c, NEON_AUTH_POPUP_CALLBACK_PARAM_NAME as i, SESSION_CACHE_TTL_MS as l, DEFAULT_SESSION_EXPIRY_MS as n, NEON_AUTH_POPUP_PARAM_NAME as o, NEON_AUTH_COOKIE_PREFIX as r, NEON_AUTH_SESSION_VERIFIER_PARAM_NAME as s, CLOCK_SKEW_BUFFER_MS as t };
@@ -0,0 +1,49 @@
1
+ import { n as BetterAuthSession, r as BetterAuthUser } from "./better-auth-types-Kq3kGuiz.mjs";
2
+ import { NextRequest, NextResponse } from "next/server";
3
+
4
+ //#region src/next/auth/session.d.ts
5
+ type SessionData = {
6
+ session: BetterAuthSession;
7
+ user: BetterAuthUser;
8
+ } | {
9
+ session: null;
10
+ user: null;
11
+ };
12
+ /**
13
+ * A utility function to be used in react server components fetch the session details from the Neon Auth API, if session token is available in cookie.
14
+ *
15
+ * @returns - `{ session: Session, user: User }` | `{ session: null, user: null}`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { neonAuth } from "@neondatabase/auth/next"
20
+ *
21
+ * const { session, user } = await neonAuth()
22
+ * ```
23
+ */
24
+ declare const neonAuth: () => Promise<SessionData>;
25
+ //#endregion
26
+ //#region src/next/middleware/index.d.ts
27
+ type NeonAuthMiddlewareOptions = {
28
+ loginUrl?: string;
29
+ };
30
+ /**
31
+ * A Next.js middleware to protect routes from unauthenticated requests and refresh the session if required.
32
+ *
33
+ * @param loginUrl - The URL to redirect to when the user is not authenticated.
34
+ * @returns A middleware function that can be used in the Next.js app.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { neonAuthMiddleware } from "@neondatabase/auth/next"
39
+ *
40
+ * export default neonAuthMiddleware({
41
+ * loginUrl: '/auth/sign-in',
42
+ * });
43
+ * ```
44
+ */
45
+ declare function neonAuthMiddleware({
46
+ loginUrl
47
+ }: NeonAuthMiddlewareOptions): (request: NextRequest) => Promise<NextResponse<unknown>>;
48
+ //#endregion
49
+ export { SessionData as n, neonAuth as r, neonAuthMiddleware as t };
package/dist/index.d.mts CHANGED
@@ -1,106 +1,6 @@
1
- import "./better-auth-types-VqadyqlG.mjs";
2
- import { r as SupportedBetterAuthClientPlugins } from "./adapter-core-CtcS7ex8.mjs";
3
- import { r as BetterAuthReactAdapterInstance } from "./better-auth-react-adapter-AucJqubr.mjs";
4
- import { r as SupabaseAuthAdapterInstance, s as BetterAuthVanillaAdapterInstance } from "./supabase-adapter-Bbn88gZj.mjs";
5
- import { createAuthClient as createAuthClient$1 } from "better-auth/react";
6
- import { createAuthClient as createAuthClient$2 } from "better-auth/client";
7
-
8
- //#region src/neon-auth.d.ts
9
-
10
- /**
11
- * Type representing the Better Auth React client
12
- */
13
- type ReactBetterAuthClient = ReturnType<typeof createAuthClient$1<{
14
- plugins: SupportedBetterAuthClientPlugins;
15
- }>>;
16
- /**`
17
- * Type representing the Better Auth Vanilla client
18
- */
19
- type VanillaBetterAuthClient = ReturnType<typeof createAuthClient$2<{
20
- plugins: SupportedBetterAuthClientPlugins;
21
- }>>;
22
- /**
23
- * Union type of all supported auth adapter instances
24
- */
25
- type NeonAuthAdapter = BetterAuthVanillaAdapterInstance | BetterAuthReactAdapterInstance | SupabaseAuthAdapterInstance;
26
- /**
27
- * Configuration for createAuthClient
28
- */
29
- interface NeonAuthConfig<T extends NeonAuthAdapter> {
30
- /** The adapter builder to use. Defaults to BetterAuthVanillaAdapter() if not specified. */
31
- adapter?: (url: string) => T;
32
- /**
33
- * When true, automatically uses an anonymous token when no user session exists.
34
- * This enables RLS-based data access for users with the anonymous role.
35
- * @default false
36
- */
37
- allowAnonymous?: boolean;
38
- }
39
- /**
40
- * Resolves the public API type for an adapter.
41
- * - SupabaseAuthAdapter: exposes its own methods directly (Supabase-compatible API)
42
- * - BetterAuth adapters: expose the Better Auth client directly
43
- */
44
- type NeonAuthPublicApi<T extends NeonAuthAdapter> = T extends BetterAuthVanillaAdapterInstance ? VanillaBetterAuthClient : T extends BetterAuthReactAdapterInstance ? ReactBetterAuthClient : T;
45
- /**
46
- * NeonAuth type - combines base functionality with the appropriate public API
47
- * This is the return type of createAuthClient()
48
- *
49
- * For SupabaseAuthAdapter: exposes Supabase-compatible methods (signInWithPassword, getSession, etc.)
50
- * For BetterAuth adapters: exposes the Better Auth client directly (signIn.email, signUp.email, etc.)
51
- */
52
- type NeonAuth<T extends NeonAuthAdapter> = {
53
- adapter: NeonAuthPublicApi<T>;
54
- getJWTToken: () => Promise<string | null>;
55
- };
56
- /**
57
- * Create a NeonAuth instance that exposes the appropriate API based on the adapter.
58
- *
59
- * @param url - The auth service URL (e.g., 'https://auth.example.com')
60
- * @param config - Configuration with adapter builder
61
- * @returns NeonAuth instance with the adapter's API exposed directly
62
- *
63
- * @example SupabaseAuthAdapter - Supabase-compatible API
64
- * ```typescript
65
- * import { createAuthClient, SupabaseAuthAdapter } from '@neondatabase/auth';
66
- *
67
- * const auth = createAuthClient('https://auth.example.com', {
68
- * adapter: SupabaseAuthAdapter(),
69
- * });
70
- *
71
- * // Supabase-compatible methods
72
- * await auth.signInWithPassword({ email, password });
73
- * await auth.getSession();
74
- * ```
75
- *
76
- * @example BetterAuthVanillaAdapter - Direct Better Auth API
77
- * ```typescript
78
- * import { createAuthClient, BetterAuthVanillaAdapter } from '@neondatabase/auth';
79
- *
80
- * const auth = createAuthClient('https://auth.example.com', {
81
- * adapter: BetterAuthVanillaAdapter(),
82
- * });
83
- *
84
- * // Direct Better Auth API access
85
- * await auth.signIn.email({ email, password });
86
- * await auth.signUp.email({ email, password, name: 'John' });
87
- * await auth.getSession();
88
- * ```
89
- *
90
- * @example BetterAuthReactAdapter - Better Auth with React hooks
91
- * ```typescript
92
- * import { createAuthClient, BetterAuthReactAdapter } from '@neondatabase/auth';
93
- *
94
- * const auth = createAuthClient('https://auth.example.com', {
95
- * adapter: BetterAuthReactAdapter(),
96
- * });
97
- *
98
- * // Direct Better Auth API with React hooks
99
- * await auth.signIn.email({ email, password });
100
- * const session = auth.useSession(); // React hook
101
- * ```
102
- */
103
- declare function createInternalNeonAuth<T extends NeonAuthAdapter = BetterAuthVanillaAdapterInstance>(url: string, config?: NeonAuthConfig<T>): NeonAuth<T>;
104
- declare function createAuthClient<T extends NeonAuthAdapter = BetterAuthVanillaAdapterInstance>(url: string, config?: NeonAuthConfig<T>): NeonAuthPublicApi<T>;
105
- //#endregion
1
+ import "./better-auth-types-Kq3kGuiz.mjs";
2
+ import "./adapter-core-Sx7jkLdB.mjs";
3
+ import "./better-auth-react-adapter-BWH-XVdf.mjs";
4
+ import "./supabase-adapter-k8RBezY9.mjs";
5
+ import { a as ReactBetterAuthClient, c as createInternalNeonAuth, i as NeonAuthPublicApi, n as NeonAuthAdapter, o as VanillaBetterAuthClient, r as NeonAuthConfig, s as createAuthClient, t as NeonAuth } from "./neon-auth-DDPaciiS.mjs";
106
6
  export { type NeonAuth, type NeonAuthAdapter, type NeonAuthConfig, type NeonAuthPublicApi, type ReactBetterAuthClient, type VanillaBetterAuthClient, createAuthClient, createInternalNeonAuth };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import "./adapter-core-ChIlSbGg.mjs";
2
- import { n as createInternalNeonAuth, t as createAuthClient } from "./neon-auth-sSiNq4zM.mjs";
1
+ import "./adapter-core-BQ6ga1zK.mjs";
2
+ import { n as createInternalNeonAuth, t as createAuthClient } from "./neon-auth-ClDZNB9a.mjs";
3
3
 
4
4
  export { createAuthClient, createInternalNeonAuth };
@@ -0,0 +1,303 @@
1
+ import { r as NEON_AUTH_COOKIE_PREFIX, s as NEON_AUTH_SESSION_VERIFIER_PARAM_NAME } from "./constants-2bpp2_-f.mjs";
2
+ import { parseCookies, parseSetCookieHeader } from "better-auth/cookies";
3
+ import { NextRequest, NextResponse } from "next/server";
4
+ import { cookies, headers } from "next/headers";
5
+
6
+ //#region src/next/errors.ts
7
+ const ERRORS = { MISSING_AUTH_BASE_URL: "Missing environment variable: NEON_AUTH_BASE_URL. \n You must provide the auth url of your Neon Auth instance in environment variables" };
8
+
9
+ //#endregion
10
+ //#region src/utils/cookies.ts
11
+ /**
12
+ * Extract the Neon Auth cookies from the request headers.
13
+ * Only returns cookies that start with the NEON_AUTH_COOKIE_PREFIX.
14
+ *
15
+ * @param headers - The request headers or cookie header string.
16
+ * @returns The cookie string with all Neon Auth cookies (e.g., "name=value; name2=value2").
17
+ */
18
+ const extractNeonAuthCookies = (headers$1) => {
19
+ const cookieHeader = typeof headers$1 === "string" ? headers$1 : headers$1.get("cookie");
20
+ if (!cookieHeader) return "";
21
+ const parsedCookies = parseCookies(cookieHeader);
22
+ const result = [];
23
+ for (const [name, value] of parsedCookies.entries()) if (name.startsWith(NEON_AUTH_COOKIE_PREFIX)) result.push(`${name}=${value}`);
24
+ return result.join("; ");
25
+ };
26
+ /**
27
+ * Parses the `set-cookie` header from Neon Auth response into a list of cookies.
28
+ *
29
+ * @param setCookieHeader - The `set-cookie` header from Neon Auth response.
30
+ * @returns The list of parsed cookies with their options.
31
+ */
32
+ const parseSetCookies = (setCookieHeader) => {
33
+ const parsedCookies = parseSetCookieHeader(setCookieHeader);
34
+ const cookies$1 = [];
35
+ for (const entry of parsedCookies.entries()) {
36
+ const [name, parsedCookie] = entry;
37
+ cookies$1.push({
38
+ name,
39
+ value: decodeURIComponent(parsedCookie.value),
40
+ path: parsedCookie.path,
41
+ maxAge: parsedCookie["max-age"] ?? parsedCookie.maxAge,
42
+ httpOnly: parsedCookie.httponly ?? true,
43
+ secure: parsedCookie.secure ?? true,
44
+ sameSite: parsedCookie.samesite ?? "lax",
45
+ partitioned: parsedCookie.partitioned
46
+ });
47
+ }
48
+ return cookies$1;
49
+ };
50
+
51
+ //#endregion
52
+ //#region src/next/constants.ts
53
+ const NEON_AUTH_SESSION_COOKIE_NAME = `${NEON_AUTH_COOKIE_PREFIX}.session_token`;
54
+ const NEON_AUTH_SESSION_CHALLENGE_COOKIE_NAME = `${NEON_AUTH_COOKIE_PREFIX}.session_challange`;
55
+ const NEON_AUTH_HEADER_MIDDLEWARE_NAME = "X-Neon-Auth-Next-Middleware";
56
+
57
+ //#endregion
58
+ //#region src/next/handler/request.ts
59
+ const PROXY_HEADERS = [
60
+ "user-agent",
61
+ "authorization",
62
+ "referer",
63
+ "content-type"
64
+ ];
65
+ const handleAuthRequest = async (baseUrl, request, path) => {
66
+ const headers$1 = prepareRequestHeaders(request);
67
+ const body = await parseRequestBody(request);
68
+ try {
69
+ const upstreamURL = getUpstreamURL(baseUrl, path, { originalUrl: new URL(request.url) });
70
+ return await fetch(upstreamURL.toString(), {
71
+ method: request.method,
72
+ headers: headers$1,
73
+ body
74
+ });
75
+ } catch (error) {
76
+ const message = error instanceof Error ? error.message : "Internal Server Error";
77
+ console.error(`[AuthError] ${message}`, error);
78
+ return new Response(`[AuthError] ${message}`, { status: 500 });
79
+ }
80
+ };
81
+ const getUpstreamURL = (baseUrl, path, { originalUrl }) => {
82
+ const url = new URL(`${baseUrl}/${path}`);
83
+ if (originalUrl) {
84
+ url.search = originalUrl.search;
85
+ return url;
86
+ }
87
+ return url;
88
+ };
89
+ const prepareRequestHeaders = (request) => {
90
+ const headers$1 = new Headers();
91
+ for (const header of PROXY_HEADERS) if (request.headers.get(header)) headers$1.set(header, request.headers.get(header));
92
+ headers$1.set("Origin", getOrigin(request));
93
+ headers$1.set("Cookie", extractNeonAuthCookies(request.headers));
94
+ headers$1.set(NEON_AUTH_HEADER_MIDDLEWARE_NAME, "true");
95
+ return headers$1;
96
+ };
97
+ const getOrigin = (request) => {
98
+ return request.headers.get("origin") || request.headers.get("referer")?.split("/").slice(0, 3).join("/") || new URL(request.url).origin;
99
+ };
100
+ const parseRequestBody = async (request) => {
101
+ if (request.body) return request.text();
102
+ };
103
+
104
+ //#endregion
105
+ //#region src/next/handler/response.ts
106
+ const RESPONSE_HEADERS_ALLOWLIST = [
107
+ "content-type",
108
+ "content-length",
109
+ "content-encoding",
110
+ "transfer-encoding",
111
+ "connection",
112
+ "date",
113
+ "set-cookie",
114
+ "set-auth-jwt",
115
+ "set-auth-token",
116
+ "x-neon-ret-request-id"
117
+ ];
118
+ const handleAuthResponse = async (response) => {
119
+ return new Response(response.body, {
120
+ status: response.status,
121
+ statusText: response.statusText,
122
+ headers: prepareResponseHeaders(response)
123
+ });
124
+ };
125
+ const prepareResponseHeaders = (response) => {
126
+ const headers$1 = new Headers();
127
+ for (const header of RESPONSE_HEADERS_ALLOWLIST) {
128
+ const value = response.headers.get(header);
129
+ if (value) headers$1.set(header, value);
130
+ }
131
+ return headers$1;
132
+ };
133
+
134
+ //#endregion
135
+ //#region src/next/handler/index.ts
136
+ /**
137
+ *
138
+ * An API route handler to handle the auth requests from the client and proxy them to the Neon Auth.
139
+ *
140
+ * @returns A Next.js API handler functions those can be used in a Next.js route.
141
+ *
142
+ * @example
143
+ * Mount the `authApiHandler` to an API route. Create a route file inside `/api/auth/[...all]/route.ts` directory.
144
+ * And add the following code:
145
+ *
146
+ * ```ts
147
+ * // app/api/auth/[...all]/route.ts
148
+ * import { authApiHandler } from '@neondatabase/auth/next';
149
+ *
150
+ * export const { GET, POST } = authApiHandler();
151
+ * ```
152
+ */
153
+ function authApiHandler() {
154
+ const baseURL = process.env.NEON_AUTH_BASE_URL;
155
+ if (!baseURL) throw new Error(ERRORS.MISSING_AUTH_BASE_URL);
156
+ const handler = async (request, { params }) => {
157
+ return await handleAuthResponse(await handleAuthRequest(baseURL, request, (await params).path.join("/")));
158
+ };
159
+ return {
160
+ GET: handler,
161
+ POST: handler,
162
+ PUT: handler,
163
+ DELETE: handler,
164
+ PATCH: handler
165
+ };
166
+ }
167
+
168
+ //#endregion
169
+ //#region src/next/auth/cookies.ts
170
+ /**
171
+ * Extract the Neon Auth cookies from the response headers.
172
+ * @deprecated Use parseSetCookies instead
173
+ */
174
+ const extractResponseCookies = (headers$1) => {
175
+ const cookieHeader = headers$1.get("set-cookie");
176
+ if (!cookieHeader) return [];
177
+ return cookieHeader.split(", ").map((c) => c.trim());
178
+ };
179
+
180
+ //#endregion
181
+ //#region src/next/middleware/oauth.ts
182
+ const needsSessionVerification = (request) => {
183
+ const hasVerifier = request.nextUrl.searchParams.has(NEON_AUTH_SESSION_VERIFIER_PARAM_NAME);
184
+ const hasChallenge = request.cookies.get(NEON_AUTH_SESSION_CHALLENGE_COOKIE_NAME);
185
+ return hasVerifier && hasChallenge;
186
+ };
187
+ const exchangeOAuthToken = async (request, baseUrl) => {
188
+ const url = request.nextUrl;
189
+ const verifier = url.searchParams.get(NEON_AUTH_SESSION_VERIFIER_PARAM_NAME);
190
+ const challenge = request.cookies.get(NEON_AUTH_SESSION_CHALLENGE_COOKIE_NAME);
191
+ if (!verifier || !challenge) return null;
192
+ const response = await handleAuthResponse(await handleAuthRequest(baseUrl, new Request(request.url, {
193
+ method: "GET",
194
+ headers: request.headers
195
+ }), "get-session"));
196
+ if (response.ok) {
197
+ const headers$1 = new Headers();
198
+ const cookies$1 = extractResponseCookies(response.headers);
199
+ for (const cookie of cookies$1) headers$1.append("Set-Cookie", cookie);
200
+ url.searchParams.delete(NEON_AUTH_SESSION_VERIFIER_PARAM_NAME);
201
+ return NextResponse.redirect(url, { headers: headers$1 });
202
+ }
203
+ return null;
204
+ };
205
+
206
+ //#endregion
207
+ //#region src/next/env-variables.ts
208
+ const NEON_AUTH_BASE_URL = process.env.NEON_AUTH_BASE_URL;
209
+
210
+ //#endregion
211
+ //#region src/next/auth/session.ts
212
+ /**
213
+ * A utility function to be used in react server components fetch the session details from the Neon Auth API, if session token is available in cookie.
214
+ *
215
+ * @returns - `{ session: Session, user: User }` | `{ session: null, user: null}`.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * import { neonAuth } from "@neondatabase/auth/next"
220
+ *
221
+ * const { session, user } = await neonAuth()
222
+ * ```
223
+ */
224
+ const neonAuth = async () => {
225
+ return await fetchSession();
226
+ };
227
+ /**
228
+ * A utility function to fetch the session details from the Neon Auth API, if session token is available in cookie.
229
+ *
230
+ * @returns - `{ session: Session, user: User }` | `{ session: null, user: null}`.
231
+ */
232
+ const fetchSession = async () => {
233
+ const baseUrl = NEON_AUTH_BASE_URL;
234
+ const requestHeaders = await headers();
235
+ const upstreamURL = getUpstreamURL(baseUrl, "get-session", { originalUrl: new URL("get-session", baseUrl) });
236
+ const response = await fetch(upstreamURL.toString(), {
237
+ method: "GET",
238
+ headers: { Cookie: extractNeonAuthCookies(requestHeaders) }
239
+ });
240
+ const body = await response.json();
241
+ const cookieHeader = response.headers.get("set-cookie");
242
+ if (cookieHeader) {
243
+ const cookieStore = await cookies();
244
+ parseSetCookies(cookieHeader).map((cookie) => {
245
+ cookieStore.set(cookie.name, cookie.value, cookie);
246
+ });
247
+ }
248
+ if (!response.ok || body === null) return {
249
+ session: null,
250
+ user: null
251
+ };
252
+ return {
253
+ session: body.session,
254
+ user: body.user
255
+ };
256
+ };
257
+
258
+ //#endregion
259
+ //#region src/next/middleware/index.ts
260
+ const SKIP_ROUTES = [
261
+ "/api/auth",
262
+ "/auth/callback",
263
+ "/auth/sign-in",
264
+ "/auth/sign-up",
265
+ "/auth/magic-link",
266
+ "/auth/email-otp",
267
+ "/auth/forgot-password"
268
+ ];
269
+ /**
270
+ * A Next.js middleware to protect routes from unauthenticated requests and refresh the session if required.
271
+ *
272
+ * @param loginUrl - The URL to redirect to when the user is not authenticated.
273
+ * @returns A middleware function that can be used in the Next.js app.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * import { neonAuthMiddleware } from "@neondatabase/auth/next"
278
+ *
279
+ * export default neonAuthMiddleware({
280
+ * loginUrl: '/auth/sign-in',
281
+ * });
282
+ * ```
283
+ */
284
+ function neonAuthMiddleware({ loginUrl = "/auth/sign-in" }) {
285
+ const baseUrl = NEON_AUTH_BASE_URL;
286
+ if (!baseUrl) throw new Error(ERRORS.MISSING_AUTH_BASE_URL);
287
+ return async (request) => {
288
+ const { pathname } = request.nextUrl;
289
+ if (pathname.startsWith(loginUrl)) return NextResponse.next();
290
+ if (needsSessionVerification(request)) {
291
+ const response = await exchangeOAuthToken(request, baseUrl);
292
+ if (response !== null) return response;
293
+ }
294
+ if (SKIP_ROUTES.some((route) => pathname.startsWith(route))) return NextResponse.next();
295
+ if ((await fetchSession()).session === null) return NextResponse.redirect(new URL(loginUrl, request.url));
296
+ const reqHeaders = new Headers(request.headers);
297
+ reqHeaders.set(NEON_AUTH_HEADER_MIDDLEWARE_NAME, "true");
298
+ return NextResponse.next({ request: { headers: reqHeaders } });
299
+ };
300
+ }
301
+
302
+ //#endregion
303
+ export { parseSetCookies as a, extractNeonAuthCookies as i, neonAuth as n, authApiHandler as r, neonAuthMiddleware as t };
@@ -1,4 +1,4 @@
1
- import { n as BetterAuthVanillaAdapter } from "./supabase-adapter-DhlcXYb9.mjs";
1
+ import { n as BetterAuthVanillaAdapter } from "./supabase-adapter-Bl576usk.mjs";
2
2
 
3
3
  //#region src/neon-auth.ts
4
4
  /**