@civic/auth 0.13.3 → 0.14.0-beta.0

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,22 @@
1
+ # 0.14.0 - Deep link cookie fixes (breaking change)
2
+
3
+ ### Bug Fixes
4
+ - Prevent `/api/*` paths from being stored in the return URL cookie
5
+ - Fixed stale return URL cookies being preserved after logout
6
+ - Fixed cookie clearing using consistent `secure`/`sameSite` attributes
7
+ - Fixed logout cookie clearing when `logoutCallbackUrl` is configured
8
+
9
+ ### Breaking Changes
10
+ - **`handleDeepLinking()` now requires a `method` parameter**: Deep linking only activates for GET requests. This prevents POST/PUT/DELETE requests from incorrectly setting the return URL cookie.
11
+
12
+ ```typescript
13
+ // Before
14
+ await civicAuth.handleDeepLinking(requestUrl, originUrl);
15
+
16
+ // After
17
+ await civicAuth.handleDeepLinking(requestUrl, originUrl, request.method);
18
+ ```
19
+
1
20
  # 0.13.3 - More fixes for deep-linking
2
21
  - Fix bug where basePath was not correctly handled when evaluating deeplink destinations.
3
22
 
package/README.md CHANGED
@@ -350,6 +350,8 @@ export default authMiddleware();
350
350
  export const config = {
351
351
  // include the paths you wish to secure here
352
352
  matcher: [
353
+ // Explicitly include root path - required for deep linking with query params at basePath level
354
+ "/",
353
355
  /*
354
356
  * Match all request paths except:
355
357
  * - _next directory (Next.js static files)
@@ -361,6 +363,8 @@ export const config = {
361
363
  }
362
364
  ```
363
365
 
366
+ > **Note:** When using Next.js `basePath`, the root path `"/"` must be explicitly included in the matcher to ensure query parameters at the basePath level are captured for deep linking.
367
+
364
368
  > **Note:** If you have analytics proxy rewrites in your `next.config.js` (e.g., for Google Analytics, PostHog, or other tracking services), you should add those paths to the `exclude` configuration option. See [Advanced Configuration](#advanced-configuration) for details.
365
369
 
366
370
  **Token Handling Behavior:**
@@ -458,6 +462,38 @@ Here are the available configuration options:
458
462
 
459
463
  <table><thead><tr><th width="133">Field</th><th width="100">Required</th><th width="171">Default</th><th>Example</th><th>Description</th></tr></thead><tbody><tr><td>clientId</td><td>Yes</td><td>-</td><td><code>2cc5633d-2c92-48da-86aa-449634f274b9</code></td><td>The key obtained on signup to <a href="https://auth.civic.com">auth.civic.com</a></td></tr><tr><td>callbackUrl</td><td>No</td><td>/api/auth/callback</td><td>/api/myroute/callback</td><td>The path to route the browser to after a succesful login. Set this value if you are hosting your civic auth API route somewhere other than the default recommended <a href="next.js.md#create-an-api-route">above</a>.</td></tr><tr><td>loginUrl</td><td>No</td><td>/</td><td>/admin</td><td>The path your user will be sent to if they access a resource that needs them to be logged in. If you have a dedicated login page, you can set it here.</td></tr><tr><td>logoutUrl</td><td>No</td><td>/</td><td>/goodbye</td><td>The path your user will be sent to after a successful log-out.</td></tr><tr><td>baseUrl</td><td>No</td><td>-</td><td>https://myapp.com</td><td>The public-facing base URL for apps deployed behind reverse proxies (e.g., Cloudfront + Vercel). When your app is behind a reverse proxy, the middleware may construct redirect URLs using internal origins instead of your public domain. Set this to ensure authentication redirects use the correct public URL.</td></tr><tr><td>autoRedirect</td><td>No</td><td>true</td><td>autoRedirect: false</td><td>When enabled, automatically uses the 'redirect' mode for authentication in browsers that don't support iframe-based authentication (e.g., Safari with passkeys). Instead of users performing authentication in an iframe, the current page will load the login page and they user will be redirected back upon succesfull login completion.</td></tr><tr><td>deepLinkConfig</td><td>No</td><td>"fullUrl"</td><td>"queryParamsOnly"</td><td>Controls how deep links are preserved during authentication. See <a href="#deep-linking">Deep Linking</a> below.</td></tr><tr><td>include</td><td>No</td><td>['/*']</td><td><p>[</p><p> '/admin/*', '/api/admin/*'</p><p>]</p></td><td>An array of path <a href="https://man7.org/linux/man-pages/man7/glob.7.html">globs</a> that require a user to be logged-in to access. If not set, will include all paths matched by your Next.js <a href="next.js.md#middleware">middleware</a>.</td></tr><tr><td>exclude</td><td>No</td><td>-</td><td>['/ga/**/*', '/gtm/**/*', '/ingest/**/*']</td><td>An array of path <a href="https://man7.org/linux/man-pages/man7/glob.7.html">globs</a> that are excluded from the Civic Auth <a href="next.js.md#middleware">middleware</a>. <b>Important:</b> If you have analytics proxy rewrites (e.g., for Google Analytics, GTM, or PostHog), add those paths here to prevent them from being captured as return URLs during authentication.</td></tr></tbody></table>
460
464
 
465
+ ### basePath Support
466
+
467
+ Civic Auth fully supports Next.js applications configured with a `basePath`. The SDK automatically detects and applies the basePath from your `next.config.js` to all authentication URLs.
468
+
469
+ **How it works:**
470
+
471
+ 1. The `createCivicAuthPlugin` reads `basePath` from your Next.js config
472
+ 2. Internal API routes (callback, login, logout, etc.) automatically include the basePath
473
+ 3. User-facing redirect URLs (like `logoutCallbackUrl`) have basePath prepended for relative paths
474
+
475
+ **Example:**
476
+
477
+ ```typescript
478
+ // next.config.js
479
+ const nextConfig = {
480
+ basePath: '/app',
481
+ };
482
+
483
+ const withCivicAuth = createCivicAuthPlugin({
484
+ clientId: 'YOUR CLIENT ID',
485
+ logoutCallbackUrl: '/unauthenticated', // Will redirect to /app/unauthenticated
486
+ });
487
+
488
+ export default withCivicAuth(nextConfig);
489
+ ```
490
+
491
+ **Important notes:**
492
+
493
+ - basePath is automatically applied to relative URLs - absolute URLs (starting with `http://` or `https://`) are used as-is
494
+ - The basePath handling is specific to the Next.js integration; other framework integrations (React Router, Express, etc.) don't have this concept
495
+ - Cookie paths are also configured to respect basePath to avoid conflicts when running multiple instances
496
+
461
497
  ### Deep Linking
462
498
 
463
499
  Deep linking allows users to be redirected back to their original destination (including query parameters) after completing authentication. This is useful when users access deep links like `/dashboard?tab=settings` while unauthenticated.
@@ -612,7 +648,7 @@ The CivicAuth interface provides the following methods:
612
648
  | `isLoggedIn()` | Checks if the user is currently logged in |
613
649
  | `buildLoginUrl(options?)` | Builds a login URL to redirect the user to |
614
650
  | `buildLogoutRedirectUrl(options?)` | Builds a logout URL to redirect the user to |
615
- | `handleDeepLinking(requestUrl, originUrl)` | Stores the current URL for post-login redirect |
651
+ | `handleDeepLinking(requestUrl, originUrl, method)` | Stores the current URL for post-login redirect (GET requests only) |
616
652
  | `handleCallback()` | Handles OAuth callback and redirects to stored deep link |
617
653
  | `refreshTokens()` | Refreshes the current set of OIDC tokens |
618
654
  | `clearTokens()` | Clears all authentication tokens from storage |
@@ -623,6 +659,8 @@ Each method is designed to be used in a server-side context and includes proper
623
659
 
624
660
  Deep linking allows users to be redirected back to their original destination after completing authentication. For server frameworks (Express, Fastify, Hono, etc.), you can use the `handleDeepLinking` method to preserve deep links across the authentication flow.
625
661
 
662
+ > **Note:** Deep linking only activates for GET requests. POST, PUT, DELETE, and other HTTP methods are ignored because they represent programmatic actions rather than user navigation intent.
663
+
626
664
  **Configuration:**
627
665
 
628
666
  When creating your CivicAuth instance, you can configure deep linking behavior:
@@ -654,7 +692,7 @@ app.use(async (req, res, next) => {
654
692
  const requestUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
655
693
  const originUrl = `${req.protocol}://${req.get("host")}`;
656
694
 
657
- await req.civicAuth.handleDeepLinking(requestUrl, originUrl);
695
+ await req.civicAuth.handleDeepLinking(requestUrl, originUrl, req.method);
658
696
 
659
697
  const loginUrl = await req.civicAuth.buildLoginUrl();
660
698
  return res.redirect(loginUrl.toString());
@@ -672,7 +710,7 @@ fastify.addHook('preHandler', async (request, reply) => {
672
710
  const requestUrl = `${protocol}://${host}${request.url}`;
673
711
  const originUrl = `${protocol}://${host}`;
674
712
 
675
- await request.civicAuth.handleDeepLinking(requestUrl, originUrl);
713
+ await request.civicAuth.handleDeepLinking(requestUrl, originUrl, request.method);
676
714
 
677
715
  const loginUrl = await request.civicAuth.buildLoginUrl();
678
716
  return reply.redirect(loginUrl.toString());
@@ -1 +1 @@
1
- {"version":3,"file":"cookies.d.ts","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAC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;gBAAhD,MAAM,GAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,CAAM;IAOlE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAqBxC,GAAG,CACP,GAAG,EAAE,SAAS,EACd,KAAK,EAAE,MAAM,EACb,oBAAoB,GAAE,OAAO,CAAC,YAAY,CAAM,GAC/C,OAAO,CAAC,IAAI,CAAC;IAsBV,MAAM,CAAC,GAAG,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;CAc5C;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC"}
@@ -51,12 +51,13 @@ const clearAuthCookies = async (config) => {
51
51
  const returnUrlCookieConfig = config?.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];
52
52
  const cookiePath = returnUrlCookieConfig?.path ?? config?.basePath ?? "/";
53
53
  const cookieStore = await cookies();
54
+ // Use set() with maxAge: 0 to delete
55
+ // Keep httpOnly but omit secure/sameSite to avoid dynamic value mismatch issues
56
+ // (secure/sameSite were computed dynamically and could differ between set/delete contexts)
54
57
  cookieStore.set(AuthFlowCookie.RETURN_URL, "", {
55
58
  maxAge: 0, // Immediately expire the cookie
56
59
  path: cookiePath,
57
60
  httpOnly: returnUrlCookieConfig?.httpOnly ?? true,
58
- secure: returnUrlCookieConfig?.secure ?? true,
59
- sameSite: returnUrlCookieConfig?.sameSite ?? "strict",
60
61
  });
61
62
  };
62
63
  class NextjsCookieStorage extends CookieStorage {
@@ -108,16 +109,12 @@ class NextjsCookieStorage extends CookieStorage {
108
109
  const cookieStore = await cookies();
109
110
  // Get cookie configuration for this key to respect the path setting
110
111
  const cookieSettings = this.config?.[key] || {};
111
- // IMPORTANT: Use getCookieConfiguration to match the dynamic secure/sameSite
112
- // values used when setting the cookie, otherwise the browser won't recognize
113
- // it as the same cookie and won't delete it.
114
- const request = await createRequestFromHeaders();
115
- const dynamicConfig = getCookieConfiguration(request);
112
+ // Use set() with maxAge: 0 to delete
113
+ // Keep httpOnly from config but omit secure/sameSite to avoid dynamic value mismatch issues
116
114
  cookieStore.set(key, "", {
117
115
  maxAge: 0, // Immediately expire the cookie
118
116
  path: cookieSettings.path || "/",
119
- secure: dynamicConfig.secure,
120
- sameSite: dynamicConfig.sameSite,
117
+ httpOnly: cookieSettings.httpOnly ?? this.settings.httpOnly,
121
118
  });
122
119
  }
123
120
  }
@@ -1 +1 @@
1
- {"version":3,"file":"cookies.js","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAGzE,OAAO,EACL,cAAc,EACd,WAAW,GAEZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAG9D;;GAEG;AACH,MAAM,wBAAwB,GAAG,KAAK,IAAkC,EAAE;IACxE,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAChD,MAAM,QAAQ,GACZ,WAAW,CAAC,GAAG,CAAC,mBAAmB,CAAC;YACpC,WAAW,CAAC,GAAG,CAAC,sBAAsB,CAAC;YACvC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAE7D,IAAI,CAAC,IAAI;YAAE,OAAO,SAAS,CAAC;QAE5B,MAAM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E,mBAAmB,EAAE,CAAC","sourcesContent":["import { cookies, headers } from \"next/headers.js\";\nimport { extractCookieFromRawHeader } from \"@/shared/lib/cookieUtils.js\";\n\nimport type { KeySetter } from \"@/shared/lib/types.js\";\nimport {\n AuthFlowCookie,\n UserStorage,\n type CookieConfig,\n} from \"@/shared/lib/types.js\";\nimport { CookieStorage } from \"@/shared/lib/storage.js\";\nimport * as session from \"@/shared/lib/session.js\";\nimport { getCookieConfiguration } from \"@/shared/lib/util.js\";\nimport type { AuthConfigWithDefaults } from \"@/nextjs/config.js\";\n\n/**\n * Create a mock Request object from Next.js headers for cookie configuration\n */\nconst createRequestFromHeaders = async (): Promise<Request | undefined> => {\n try {\n const headerStore = await headers();\n const host = headerStore.get(\"host\");\n const userAgent = headerStore.get(\"user-agent\");\n const protocol =\n headerStore.get(\"x-forwarded-proto\") ||\n headerStore.get(\"x-forwarded-protocol\") ||\n (process.env.NODE_ENV === \"production\" ? \"https\" : \"http\");\n\n if (!host) return undefined;\n\n const url = `${protocol}://${host}/`;\n\n // Create a minimal Request object with the headers we need\n const request = new Request(url, {\n headers: {\n \"user-agent\": userAgent || \"\",\n \"x-forwarded-proto\": headerStore.get(\"x-forwarded-proto\") || \"\",\n \"x-forwarded-protocol\": headerStore.get(\"x-forwarded-protocol\") || \"\",\n forwarded: headerStore.get(\"forwarded\") || \"\",\n },\n });\n\n return request;\n } catch (error) {\n console.error(\"Error creating request from headers\", error);\n // Headers might not be available in all contexts\n return undefined;\n }\n};\n\n/**\n * Clears all authentication cookies on server. Note, this can only be called by the server\n */\nconst clearAuthCookies = async (config?: Partial<AuthConfigWithDefaults>) => {\n // Use resolved config cookies if available, otherwise use default\n const cookieStorage = new NextjsCookieStorage({\n ...config?.cookies?.tokens,\n [UserStorage.USER]: config?.cookies?.user,\n });\n await session.clearAuthCookies(cookieStorage);\n\n // Also clear auth flow cookies (like returnUrl) that are not part of the session\n // This prevents stale deep-link cookies from being re-instated during logout\n // Use the same path fallback chain as handleCallback's clearReturnUrlCookie\n const returnUrlCookieConfig =\n config?.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];\n const cookiePath = returnUrlCookieConfig?.path ?? config?.basePath ?? \"/\";\n const cookieStore = await cookies();\n cookieStore.set(AuthFlowCookie.RETURN_URL, \"\", {\n maxAge: 0, // Immediately expire the cookie\n path: cookiePath,\n httpOnly: returnUrlCookieConfig?.httpOnly ?? true,\n secure: returnUrlCookieConfig?.secure ?? true,\n sameSite: returnUrlCookieConfig?.sameSite ?? \"strict\",\n });\n};\n\nclass NextjsCookieStorage extends CookieStorage {\n constructor(public config: Partial<Record<KeySetter, CookieConfig>> = {}) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {};\n const configuredPath = cookieSettings.path;\n\n // If we have a non-root basePath, use raw header parsing to get the first cookie\n // which should be from the most specific path, avoiding duplicate cookie conflicts\n if (configuredPath && configuredPath !== \"/\") {\n const headerStore = await headers();\n const cookieHeader = headerStore.get(\"cookie\");\n const rawValue = extractCookieFromRawHeader(cookieHeader, key);\n if (rawValue) {\n return rawValue;\n }\n }\n\n // Fallback to standard Next.js cookie store\n const cookieValue = cookieStore.get(key);\n return cookieValue?.value || null;\n }\n\n async set(\n key: KeySetter,\n value: string,\n cookieConfigOverride: Partial<CookieConfig> = {},\n ): Promise<void> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n\n // Get dynamic cookie configuration based on environment and browser\n const request = await createRequestFromHeaders();\n const dynamicConfig = getCookieConfiguration(request);\n\n const useCookieSettings = {\n ...cookieSettings,\n ...cookieConfigOverride,\n // Apply dynamic configuration for secure and sameSite\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n };\n\n // Respect the httpOnly setting from configuration instead of hardcoding it\n await cookieStore.set(key, value, useCookieSettings);\n }\n\n async delete(key: KeySetter): Promise<void> {\n const cookieStore = await cookies();\n\n // Get cookie configuration for this key to respect the path setting\n const cookieSettings = this.config?.[key as KeySetter] || {};\n\n // IMPORTANT: Use getCookieConfiguration to match the dynamic secure/sameSite\n // values used when setting the cookie, otherwise the browser won't recognize\n // it as the same cookie and won't delete it.\n const request = await createRequestFromHeaders();\n const dynamicConfig = getCookieConfiguration(request);\n\n cookieStore.set(key, \"\", {\n maxAge: 0, // Immediately expire the cookie\n path: cookieSettings.path || \"/\",\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n });\n }\n}\n\nexport { clearAuthCookies, NextjsCookieStorage };\n"]}
1
+ {"version":3,"file":"cookies.js","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAGzE,OAAO,EACL,cAAc,EACd,WAAW,GAEZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAG9D;;GAEG;AACH,MAAM,wBAAwB,GAAG,KAAK,IAAkC,EAAE;IACxE,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAChD,MAAM,QAAQ,GACZ,WAAW,CAAC,GAAG,CAAC,mBAAmB,CAAC;YACpC,WAAW,CAAC,GAAG,CAAC,sBAAsB,CAAC;YACvC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAA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Utils.js\";\n\nimport type { KeySetter } from \"@/shared/lib/types.js\";\nimport {\n AuthFlowCookie,\n UserStorage,\n type CookieConfig,\n} from \"@/shared/lib/types.js\";\nimport { CookieStorage } from \"@/shared/lib/storage.js\";\nimport * as session from \"@/shared/lib/session.js\";\nimport { getCookieConfiguration } from \"@/shared/lib/util.js\";\nimport type { AuthConfigWithDefaults } from \"@/nextjs/config.js\";\n\n/**\n * Create a mock Request object from Next.js headers for cookie configuration\n */\nconst createRequestFromHeaders = async (): Promise<Request | undefined> => {\n try {\n const headerStore = await headers();\n const host = headerStore.get(\"host\");\n const userAgent = headerStore.get(\"user-agent\");\n const protocol =\n headerStore.get(\"x-forwarded-proto\") ||\n headerStore.get(\"x-forwarded-protocol\") ||\n (process.env.NODE_ENV === \"production\" ? \"https\" : \"http\");\n\n if (!host) return undefined;\n\n const url = `${protocol}://${host}/`;\n\n // Create a minimal Request object with the headers we need\n const request = new Request(url, {\n headers: {\n \"user-agent\": userAgent || \"\",\n \"x-forwarded-proto\": headerStore.get(\"x-forwarded-proto\") || \"\",\n \"x-forwarded-protocol\": headerStore.get(\"x-forwarded-protocol\") || \"\",\n forwarded: headerStore.get(\"forwarded\") || \"\",\n },\n });\n\n return request;\n } catch (error) {\n console.error(\"Error creating request from headers\", error);\n // Headers might not be available in all contexts\n return undefined;\n }\n};\n\n/**\n * Clears all authentication cookies on server. Note, this can only be called by the server\n */\nconst clearAuthCookies = async (config?: Partial<AuthConfigWithDefaults>) => {\n // Use resolved config cookies if available, otherwise use default\n const cookieStorage = new NextjsCookieStorage({\n ...config?.cookies?.tokens,\n [UserStorage.USER]: config?.cookies?.user,\n });\n await session.clearAuthCookies(cookieStorage);\n\n // Also clear auth flow cookies (like returnUrl) that are not part of the session\n // This prevents stale deep-link cookies from being re-instated during logout\n // Use the same path fallback chain as handleCallback's clearReturnUrlCookie\n const returnUrlCookieConfig =\n config?.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];\n const cookiePath = returnUrlCookieConfig?.path ?? config?.basePath ?? \"/\";\n const cookieStore = await cookies();\n\n // Use set() with maxAge: 0 to delete\n // Keep httpOnly but omit secure/sameSite to avoid dynamic value mismatch issues\n // (secure/sameSite were computed dynamically and could differ between set/delete contexts)\n cookieStore.set(AuthFlowCookie.RETURN_URL, \"\", {\n maxAge: 0, // Immediately expire the cookie\n path: cookiePath,\n httpOnly: returnUrlCookieConfig?.httpOnly ?? true,\n });\n};\n\nclass NextjsCookieStorage extends CookieStorage {\n constructor(public config: Partial<Record<KeySetter, CookieConfig>> = {}) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {};\n const configuredPath = cookieSettings.path;\n\n // If we have a non-root basePath, use raw header parsing to get the first cookie\n // which should be from the most specific path, avoiding duplicate cookie conflicts\n if (configuredPath && configuredPath !== \"/\") {\n const headerStore = await headers();\n const cookieHeader = headerStore.get(\"cookie\");\n const rawValue = extractCookieFromRawHeader(cookieHeader, key);\n if (rawValue) {\n return rawValue;\n }\n }\n\n // Fallback to standard Next.js cookie store\n const cookieValue = cookieStore.get(key);\n return cookieValue?.value || null;\n }\n\n async set(\n key: KeySetter,\n value: string,\n cookieConfigOverride: Partial<CookieConfig> = {},\n ): Promise<void> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n\n // Get dynamic cookie configuration based on environment and browser\n const request = await createRequestFromHeaders();\n const dynamicConfig = getCookieConfiguration(request);\n\n const useCookieSettings = {\n ...cookieSettings,\n ...cookieConfigOverride,\n // Apply dynamic configuration for secure and sameSite\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n };\n\n // Respect the httpOnly setting from configuration instead of hardcoding it\n await cookieStore.set(key, value, useCookieSettings);\n }\n\n async delete(key: KeySetter): Promise<void> {\n const cookieStore = await cookies();\n\n // Get cookie configuration for this key to respect the path setting\n const cookieSettings = this.config?.[key as KeySetter] || {};\n\n // Use set() with maxAge: 0 to delete\n // Keep httpOnly from config but omit secure/sameSite to avoid dynamic value mismatch issues\n cookieStore.set(key, \"\", {\n maxAge: 0, // Immediately expire the cookie\n path: cookieSettings.path || \"/\",\n httpOnly: cookieSettings.httpOnly ?? this.settings.httpOnly,\n });\n }\n}\n\nexport { clearAuthCookies, NextjsCookieStorage };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"useInitialAuthConfig.d.ts","sourceRoot":"","sources":["../../../src/nextjs/hooks/useInitialAuthConfig.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,KAAK,EACV,aAAa,EACb,oBAAoB,EACrB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAKnD,MAAM,WAAW,2BAA2B;IAC1C,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,UAAU,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sBAAsB,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;IAC9C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACrD,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,6BAA6B;IAC5C,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EA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B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB,GAC/B,UAAS,2BAAgC,KACxC;IACD,aAAa,EAAE,gBAAgB,CAAC;IAChC,yBAAyB,EAAE,CACzB,SAAS,CAAC,EAAE,6BAA6B,KACtC,gBAAgB,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;CAyKvB,CAAC"}
@@ -9,6 +9,7 @@ import { resolveAuthConfig } from "../../nextjs/config.js";
9
9
  import { BrowserCookieStorage } from "../../shared/index.js";
10
10
  import { loggers } from "../../lib/logger.js";
11
11
  import { revalidateUserData } from "../actions.js";
12
+ import { prependBasePath } from "../../shared/lib/util.js";
12
13
  /**
13
14
  * Hook that creates the initial auth configuration
14
15
  * Can be used standalone or merged with overrides
@@ -21,6 +22,11 @@ export const useInitialAuthConfig = (options = {}) => {
21
22
  // so that client-side hooks and event listeners are properly initialized
22
23
  const [hasSignedOut, setHasSignedOut] = useState(false);
23
24
  const { clientId, oauthServer, loginSuccessUrl, loginInitUrl, logoutUrl, refreshUrl, userUrl, clearSessionUrl, logoutCallbackUrl, callbackUrl, targetContainerElement, basePath, } = resolvedConfig;
25
+ // Prepend basePath to logoutCallbackUrl for frontend redirect
26
+ // The environment variable doesn't include basePath, so we add it here
27
+ const logoutCallbackUrlWithBasePath = basePath && logoutCallbackUrl && !logoutCallbackUrl.startsWith("http")
28
+ ? prependBasePath(logoutCallbackUrl, basePath)
29
+ : logoutCallbackUrl;
24
30
  const baseConfig = useMemo(() => {
25
31
  return {
26
32
  disableRefresh: options.disableRefresh,
@@ -38,12 +44,12 @@ export const useInitialAuthConfig = (options = {}) => {
38
44
  oauthServer: oauthServer,
39
45
  oauthServerBaseUrl: oauthServer,
40
46
  },
41
- logoutRedirectUrl: logoutCallbackUrl,
47
+ logoutRedirectUrl: logoutCallbackUrlWithBasePath,
42
48
  loginSuccessUrl: loginSuccessUrl,
43
49
  targetContainerElement: targetContainerElement,
44
50
  displayMode: options.displayMode,
45
51
  iframeMode: options.iframeMode,
46
- logoutCallbackUrl: logoutCallbackUrl,
52
+ logoutCallbackUrl: logoutCallbackUrlWithBasePath,
47
53
  framework: "nextjs",
48
54
  logging: options.logging,
49
55
  backendEndpoints: {
@@ -117,7 +123,7 @@ export const useInitialAuthConfig = (options = {}) => {
117
123
  loginInitUrl,
118
124
  callbackUrl,
119
125
  oauthServer,
120
- logoutCallbackUrl,
126
+ logoutCallbackUrlWithBasePath,
121
127
  loginSuccessUrl,
122
128
  targetContainerElement,
123
129
  userUrl,
@@ -1 +1 @@
1
- {"version":3,"file":"useInitialAuthConfig.js","sourceRoot":"","sources":["../../../src/nextjs/hooks/useInitialAuthConfig.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,YAAY,CAAC;AAEb,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAOvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAwBnD;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,UAAuC,EAAE,EAQzC,EAAE;IACF,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,QAAQ,GAAG,WAAW,EAAE,CAAC;IAC/B,MAAM,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAClD,0EAA0E;IAC1E,yEAAyE;IACzE,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,G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ACjC,CAAC;gBACF,GAAG,CAAC,SAAS,CAAC,QAAQ,IAAI,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC;gBAC3D,GAAG,CAAC,SAAS,CAAC,WAAW,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC;gBACpE,GAAG,CAAC,SAAS,CAAC,iBAAiB,IAAI;oBACjC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;iBAC/C,CAAC;gBACF,GAAG,CAAC,SAAS,CAAC,sBAAsB,IAAI;oBACtC,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;iBACzD,CAAC;aACH,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAEjB,OAAO;QACL,aAAa,EAAE,UAAU;QACzB,yBAAyB;QACzB,SAAS;QACT,YAAY;KACb,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * Hook for creating the initial auth configuration\n * Reusable across NextJS components that need to initialize GlobalAuthManager\n */\n\"use client\";\n\nimport { useMemo, useState } from \"react\";\nimport { useRouter, usePathname } from \"next/navigation.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport type { GlobalAuthConfig } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport type {\n LoggingConfig,\n VanillaJSDisplayMode,\n} from \"@/vanillajs/auth/types/AuthTypes.js\";\nimport type { User, IframeMode } from \"@/types.js\";\nimport { BrowserCookieStorage } from \"@/shared/index.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { revalidateUserData } from \"../actions.js\";\n\nexport interface UseInitialAuthConfigOptions {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n serverUser?: User | null;\n nonce?: string;\n targetContainerElement?: HTMLElement | string;\n oauthServer?: string;\n loginSuccessUrl?: string;\n onUrlChange?: (url: string, source?: string) => void;\n logging?: LoggingConfig;\n disableRefresh?: boolean;\n}\n\nexport interface UseInitialAuthConfigOverrides {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n clientId?: string;\n redirectUrl?: string;\n logoutRedirectUrl?: string;\n targetContainerElement?: string;\n}\n\n/**\n * Hook that creates the initial auth configuration\n * Can be used standalone or merged with overrides\n */\nexport const useInitialAuthConfig = (\n options: UseInitialAuthConfigOptions = {},\n): {\n initialConfig: GlobalAuthConfig;\n createConfigWithOverrides: (\n overrides?: UseInitialAuthConfigOverrides,\n ) => GlobalAuthConfig;\n logoutUrl: string;\n hasSignedOut: boolean;\n} => {\n const router = useRouter();\n const pathname = usePathname();\n const resolvedConfig = resolveAuthConfig(options);\n // Force a re-render when the page gets re-rendered after sign-in/sign-out\n // so that client-side hooks and event listeners are properly initialized\n const [hasSignedOut, setHasSignedOut] = useState<boolean>(false);\n const {\n clientId,\n oauthServer,\n loginSuccessUrl,\n loginInitUrl,\n logoutUrl,\n refreshUrl,\n userUrl,\n clearSessionUrl,\n logoutCallbackUrl,\n callbackUrl,\n targetContainerElement,\n basePath,\n } = resolvedConfig;\n\n const baseConfig: GlobalAuthConfig = useMemo(() => {\n return {\n disableRefresh: options.disableRefresh,\n // we need this to retrieve client-available cookies for auto-refresh etc.\n // Pass basePath to ensure cookies are set/read with the correct path\n storage: new BrowserCookieStorage({ path: basePath || \"/\" }),\n clientId: clientId,\n loginUrl:\n typeof window !== \"undefined\"\n ? window.location.origin + loginInitUrl\n : undefined,\n redirectUrl:\n typeof window !== \"undefined\"\n ? window.location.origin + callbackUrl\n : undefined,\n config: {\n oauthServer: oauthServer,\n oauthServerBaseUrl: oauthServer,\n },\n logoutRedirectUrl: logoutCallbackUrl,\n loginSuccessUrl: loginSuccessUrl,\n targetContainerElement: targetContainerElement,\n displayMode: options.displayMode,\n iframeMode: options.iframeMode,\n logoutCallbackUrl: logoutCallbackUrl,\n framework: \"nextjs\",\n logging: options.logging,\n backendEndpoints: {\n user: userUrl,\n refresh: refreshUrl,\n logout: logoutUrl,\n clearSession: clearSessionUrl,\n },\n onSignOut: async () => {\n setHasSignedOut(true);\n await new Promise((resolve) => {\n setTimeout(async () => {\n try {\n // Trigger server-side revalidation to force NextAuthProvider to re-run\n await revalidateUserData(pathname);\n } catch (revalidateError) {\n console.error(\"onSignIn: Revalidation failed:\", revalidateError);\n // Fallback to router.refresh() if server action fails\n router.refresh();\n }\n resolve(true);\n }, 100);\n });\n },\n onRefresh: async (error) => {\n if (error) {\n loggers.nextjs.hooks.error(\"onRefresh: Error refreshing\", error);\n }\n setHasSignedOut(false);\n\n await new Promise((resolve) => {\n setTimeout(async () => {\n router.refresh();\n resolve(true);\n }, 100);\n });\n },\n onSignIn: async ({ error, redirectUrl }) => {\n if (error) {\n loggers.nextjs.hooks.error(\"onSignIn: Error signing in\", error);\n return;\n }\n setHasSignedOut(false);\n try {\n // Trigger server-side revalidation to force NextAuthProvider to re-run\n await revalidateUserData(pathname);\n // Navigate to the deep link (redirectUrl) if available, otherwise fall back to loginSuccessUrl\n const targetUrl = redirectUrl || loginSuccessUrl;\n if (targetUrl && targetUrl !== pathname) {\n router.push(targetUrl);\n }\n } catch (revalidateError) {\n console.error(\"onSignIn: Revalidation failed:\", revalidateError);\n // Fallback to router.refresh() if server action fails\n router.refresh();\n }\n },\n onUrlChange: options.onUrlChange,\n initialUser: (!hasSignedOut && options.serverUser) || null,\n initialIdToken: null, // ID token is httpOnly and not accessible\n };\n }, [\n options.disableRefresh,\n options.displayMode,\n options.iframeMode,\n options.logging,\n options.onUrlChange,\n options.serverUser,\n clientId,\n loginInitUrl,\n callbackUrl,\n oauthServer,\n logoutCallbackUrl,\n loginSuccessUrl,\n targetContainerElement,\n userUrl,\n refreshUrl,\n logoutUrl,\n clearSessionUrl,\n basePath,\n hasSignedOut,\n pathname,\n router,\n ]);\n\n const createConfigWithOverrides = useMemo(() => {\n return (\n overrides: UseInitialAuthConfigOverrides = {},\n ): GlobalAuthConfig => {\n return {\n ...baseConfig,\n // Override specific properties while keeping the base config\n ...(overrides.displayMode && { displayMode: overrides.displayMode }),\n ...(overrides.iframeMode !== undefined && {\n iframeMode: overrides.iframeMode,\n }),\n ...(overrides.clientId && { clientId: overrides.clientId }),\n ...(overrides.redirectUrl && { redirectUrl: overrides.redirectUrl }),\n ...(overrides.logoutRedirectUrl && {\n logoutRedirectUrl: overrides.logoutRedirectUrl,\n }),\n ...(overrides.targetContainerElement && {\n targetContainerElement: overrides.targetContainerElement,\n }),\n };\n };\n }, [baseConfig]);\n\n return {\n initialConfig: baseConfig,\n createConfigWithOverrides,\n logoutUrl,\n hasSignedOut,\n };\n};\n"]}
1
+ {"version":3,"file":"useInitialAuthConfig.js","sourceRoot":"","sources":["../../../src/nextjs/hooks/useInitialAuthConfig.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,YAAY,CAAC;AAEb,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAOvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAwBvD;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,UAAuC,EAAE,EAQzC,EAAE;IACF,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,QAAQ,GAAG,WAAW,EAAE,CAAC;IAC/B,MAAM,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAClD,0EAA0E;IAC1E,yEAAyE;IACzE,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,QAAQ,CAAU,KAAK,CAAC,CAAC;IACjE,MAAM,EACJ,QAAQ,EAC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C,WAAW,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC;gBACpE,GAAG,CAAC,SAAS,CAAC,UAAU,KAAK,SAAS,IAAI;oBACxC,UAAU,EAAE,SAAS,CAAC,UAAU;iBACjC,CAAC;gBACF,GAAG,CAAC,SAAS,CAAC,QAAQ,IAAI,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC;gBAC3D,GAAG,CAAC,SAAS,CAAC,WAAW,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC;gBACpE,GAAG,CAAC,SAAS,CAAC,iBAAiB,IAAI;oBACjC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;iBAC/C,CAAC;gBACF,GAAG,CAAC,SAAS,CAAC,sBAAsB,IAAI;oBACtC,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;iBACzD,CAAC;aACH,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAEjB,OAAO;QACL,aAAa,EAAE,UAAU;QACzB,yBAAyB;QACzB,SAAS;QACT,YAAY;KACb,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * Hook for creating the initial auth configuration\n * Reusable across NextJS components that need to initialize GlobalAuthManager\n */\n\"use client\";\n\nimport { useMemo, useState } from \"react\";\nimport { useRouter, usePathname } from \"next/navigation.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport type { GlobalAuthConfig } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport type {\n LoggingConfig,\n VanillaJSDisplayMode,\n} from \"@/vanillajs/auth/types/AuthTypes.js\";\nimport type { User, IframeMode } from \"@/types.js\";\nimport { BrowserCookieStorage } from \"@/shared/index.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { revalidateUserData } from \"../actions.js\";\nimport { prependBasePath } from \"@/shared/lib/util.js\";\n\nexport interface UseInitialAuthConfigOptions {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n serverUser?: User | null;\n nonce?: string;\n targetContainerElement?: HTMLElement | string;\n oauthServer?: string;\n loginSuccessUrl?: string;\n onUrlChange?: (url: string, source?: string) => void;\n logging?: LoggingConfig;\n disableRefresh?: boolean;\n}\n\nexport interface UseInitialAuthConfigOverrides {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n clientId?: string;\n redirectUrl?: string;\n logoutRedirectUrl?: string;\n targetContainerElement?: string;\n}\n\n/**\n * Hook that creates the initial auth configuration\n * Can be used standalone or merged with overrides\n */\nexport const useInitialAuthConfig = (\n options: UseInitialAuthConfigOptions = {},\n): {\n initialConfig: GlobalAuthConfig;\n createConfigWithOverrides: (\n overrides?: UseInitialAuthConfigOverrides,\n ) => GlobalAuthConfig;\n logoutUrl: string;\n hasSignedOut: boolean;\n} => {\n const router = useRouter();\n const pathname = usePathname();\n const resolvedConfig = resolveAuthConfig(options);\n // Force a re-render when the page gets re-rendered after sign-in/sign-out\n // so that client-side hooks and event listeners are properly initialized\n const [hasSignedOut, setHasSignedOut] = useState<boolean>(false);\n const {\n clientId,\n oauthServer,\n loginSuccessUrl,\n loginInitUrl,\n logoutUrl,\n refreshUrl,\n userUrl,\n clearSessionUrl,\n logoutCallbackUrl,\n callbackUrl,\n targetContainerElement,\n basePath,\n } = resolvedConfig;\n\n // Prepend basePath to logoutCallbackUrl for frontend redirect\n // The environment variable doesn't include basePath, so we add it here\n const logoutCallbackUrlWithBasePath =\n basePath && logoutCallbackUrl && !logoutCallbackUrl.startsWith(\"http\")\n ? prependBasePath(logoutCallbackUrl, basePath)\n : logoutCallbackUrl;\n\n const baseConfig: GlobalAuthConfig = useMemo(() => {\n return {\n disableRefresh: options.disableRefresh,\n // we need this to retrieve client-available cookies for auto-refresh etc.\n // Pass basePath to ensure cookies are set/read with the correct path\n storage: new BrowserCookieStorage({ path: basePath || \"/\" }),\n clientId: clientId,\n loginUrl:\n typeof window !== \"undefined\"\n ? window.location.origin + loginInitUrl\n : undefined,\n redirectUrl:\n typeof window !== \"undefined\"\n ? window.location.origin + callbackUrl\n : undefined,\n config: {\n oauthServer: oauthServer,\n oauthServerBaseUrl: oauthServer,\n },\n logoutRedirectUrl: logoutCallbackUrlWithBasePath,\n loginSuccessUrl: loginSuccessUrl,\n targetContainerElement: targetContainerElement,\n displayMode: options.displayMode,\n iframeMode: options.iframeMode,\n logoutCallbackUrl: logoutCallbackUrlWithBasePath,\n framework: \"nextjs\",\n logging: options.logging,\n backendEndpoints: {\n user: userUrl,\n refresh: refreshUrl,\n logout: logoutUrl,\n clearSession: clearSessionUrl,\n },\n onSignOut: async () => {\n setHasSignedOut(true);\n await new Promise((resolve) => {\n setTimeout(async () => {\n try {\n // Trigger server-side revalidation to force NextAuthProvider to re-run\n await revalidateUserData(pathname);\n } catch (revalidateError) {\n console.error(\"onSignIn: Revalidation failed:\", revalidateError);\n // Fallback to router.refresh() if server action fails\n router.refresh();\n }\n resolve(true);\n }, 100);\n });\n },\n onRefresh: async (error) => {\n if (error) {\n loggers.nextjs.hooks.error(\"onRefresh: Error refreshing\", error);\n }\n setHasSignedOut(false);\n\n await new Promise((resolve) => {\n setTimeout(async () => {\n router.refresh();\n resolve(true);\n }, 100);\n });\n },\n onSignIn: async ({ error, redirectUrl }) => {\n if (error) {\n loggers.nextjs.hooks.error(\"onSignIn: Error signing in\", error);\n return;\n }\n setHasSignedOut(false);\n try {\n // Trigger server-side revalidation to force NextAuthProvider to re-run\n await revalidateUserData(pathname);\n // Navigate to the deep link (redirectUrl) if available, otherwise fall back to loginSuccessUrl\n const targetUrl = redirectUrl || loginSuccessUrl;\n if (targetUrl && targetUrl !== pathname) {\n router.push(targetUrl);\n }\n } catch (revalidateError) {\n console.error(\"onSignIn: Revalidation failed:\", revalidateError);\n // Fallback to router.refresh() if server action fails\n router.refresh();\n }\n },\n onUrlChange: options.onUrlChange,\n initialUser: (!hasSignedOut && options.serverUser) || null,\n initialIdToken: null, // ID token is httpOnly and not accessible\n };\n }, [\n options.disableRefresh,\n options.displayMode,\n options.iframeMode,\n options.logging,\n options.onUrlChange,\n options.serverUser,\n clientId,\n loginInitUrl,\n callbackUrl,\n oauthServer,\n logoutCallbackUrlWithBasePath,\n loginSuccessUrl,\n targetContainerElement,\n userUrl,\n refreshUrl,\n logoutUrl,\n clearSessionUrl,\n basePath,\n hasSignedOut,\n pathname,\n router,\n ]);\n\n const createConfigWithOverrides = useMemo(() => {\n return (\n overrides: UseInitialAuthConfigOverrides = {},\n ): GlobalAuthConfig => {\n return {\n ...baseConfig,\n // Override specific properties while keeping the base config\n ...(overrides.displayMode && { displayMode: overrides.displayMode }),\n ...(overrides.iframeMode !== undefined && {\n iframeMode: overrides.iframeMode,\n }),\n ...(overrides.clientId && { clientId: overrides.clientId }),\n ...(overrides.redirectUrl && { redirectUrl: overrides.redirectUrl }),\n ...(overrides.logoutRedirectUrl && {\n logoutRedirectUrl: overrides.logoutRedirectUrl,\n }),\n ...(overrides.targetContainerElement && {\n targetContainerElement: overrides.targetContainerElement,\n }),\n };\n };\n }, [baseConfig]);\n\n return {\n initialConfig: baseConfig,\n createConfigWithOverrides,\n logoutUrl,\n hasSignedOut,\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EACV,sBAAsB,EACtB,kBAAkB,EACnB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAW9C,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAM3D,KAAK,UAAU,GAAG,CAChB,OAAO,EAAE,WAAW,KACjB,OAAO,CAAC,YAAY,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MAAM,cAAc,GACxB,aAAY,kBAAuB,MAC7B,SAAS,WAAW,KAAG,OAAO,CAAC,YAAY,CAOjD,CAAC;AAEJ;;;;;;;GAOG;AAEH,wBAAgB,QAAQ,CACtB,UAAU,EAAE,UAAU,GACrB,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAEjD;AAKD;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,UAAU,GAAE,kBAAuB,IAEpD,YAAY,UAAU,KACrB,CAAC,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC,CA2BrD"}
@@ -84,6 +84,7 @@ const applyAuth = async (authConfig, request) => {
84
84
  // Step 2: Handle deep link cookie for unauthenticated users using CivicAuth
85
85
  // handleDeepLinking automatically detects if we're at loginUrl or a protected route
86
86
  // and applies the appropriate logic for each case
87
+ // Note: handleDeepLinking internally skips non-GET requests (POST/PUT/DELETE etc.)
87
88
  if (!session.authenticated) {
88
89
  const civicAuth = new CivicAuth(storage, {
89
90
  ...authConfigWithDefaults,
@@ -91,7 +92,7 @@ const applyAuth = async (authConfig, request) => {
91
92
  });
92
93
  const originUrl = getOriginUrl(request, authConfigWithDefaults);
93
94
  const requestUrl = `${originUrl}${request.nextUrl.pathname}${request.nextUrl.search}${request.nextUrl.hash}`;
94
- await civicAuth.handleDeepLinking(requestUrl, originUrl);
95
+ await civicAuth.handleDeepLinking(requestUrl, originUrl, request.method);
95
96
  }
96
97
  // Step 3: Handle login URL with special logic
97
98
  if (pathNameIsLoginUrl) {
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAK9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE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QAAQ,EAAE,CAAC;gBACb,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACtC,CAAC;YACD,MAAM,kBAAkB,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;YAErD,iEAAiE;YACjE,6DAA6D;YAC7D,0BAA0B;YAC1B,IAAI,QAAQ,EAAE,CAAC;gBACb,gBAAgB,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;YACjD,CAAC;YACD,OAAO,kBAAkB,CAAC;QAC5B,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * logger.debug('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * logger.debug('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport type {\n AuthConfigWithDefaults,\n OptionalAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { SessionData } from \"@/types.js\";\nimport {\n shouldAttemptRefresh,\n shouldSkipAuthForSystemUrls,\n handleLoginUrl,\n shouldSkipAuthForRoutePatterns,\n handleUnauthenticatedUser,\n copyCivicCookies,\n getOriginUrl,\n removeBasePathFromPath,\n} from \"./utils.js\";\nimport { NextjsMiddlewareCookieStorage } from \"./utils.js\";\nimport { UserStorage } from \"@/shared/lib/types.js\";\nimport { CivicAuth } from \"@/server/session.js\";\n\nconst logger = loggers.nextjs.middleware;\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n/**\n * use a ServerAuthenticationResolver to validate the existing session\n * using NextJS cookie storage\n * @param authConfigWithDefaults\n * @param request NextRequest object from middleware\n * @returns {Promise<SessionData>}\n */\nexport const validateAuthTokensIfPresent = async (\n authConfigWithDefaults: AuthConfigWithDefaults,\n storage: NextjsMiddlewareCookieStorage,\n): Promise<SessionData> => {\n try {\n const authSessionService = await ServerAuthenticationResolver.build(\n {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n },\n storage,\n );\n // validate the existing session and rehydrate and update cookies to the response if necessary\n const existingSession = await authSessionService.validateExistingSession();\n return existingSession;\n } catch (error) {\n logger.error(\"Error validating tokens\", error);\n return { authenticated: false };\n }\n};\n\n// internal - used by all exported functions\n/**\n * Core authentication middleware logic.\n *\n * The Authentication Story:\n * 1. Validate tokens to understand current authentication state\n * 2. Attempt token refresh if needed (the OAuth pipeline approach)\n * 3. Apply route-specific authentication rules based on final state\n */\nconst applyAuth = async (\n authConfig: OptionalAuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n const response = NextResponse.next({\n request, // ensure incoming request headers get propagated\n });\n const cookieConfig = {\n ...authConfigWithDefaults?.cookies?.tokens,\n [UserStorage.USER]: authConfigWithDefaults?.cookies?.user || {},\n };\n logger.debug(\"Incoming request:\", {\n pathName: request.nextUrl.pathname,\n method: request.method,\n });\n const storage = new NextjsMiddlewareCookieStorage(\n cookieConfig,\n request,\n response,\n );\n // check if the incoming path is a system URL\n const shouldSkipAuthForSystemUrlsCheck = shouldSkipAuthForSystemUrls(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Skip authentication for system URLs (callback, challenge, logout)\n // we don't want to validate the session in this case as this would\n // auto-hydrate and potential conflict with the logic of the api call\n if (shouldSkipAuthForSystemUrlsCheck) {\n return response;\n }\n\n // Step 1: Understand the current authentication state\n const session = await validateAuthTokensIfPresent(\n authConfigWithDefaults,\n storage,\n );\n\n const shouldSkipAuthForRoutePatternsCheck = shouldSkipAuthForRoutePatterns(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Normalize loginUrl for comparison (remove basePath if present)\n const loginPathWithoutBasePath = removeBasePathFromPath(\n authConfigWithDefaults.loginUrl,\n authConfigWithDefaults.basePath,\n );\n const pathNameIsLoginUrl =\n request.nextUrl.pathname === loginPathWithoutBasePath;\n\n logger.debug(\"Authentication state:\", {\n authenticated: session.authenticated,\n pathName: request.nextUrl.pathname,\n pathNameIsLoginUrl,\n shouldAttemptRefresh: shouldAttemptRefresh(session),\n shouldSkipAuthForSystemUrls: shouldSkipAuthForSystemUrlsCheck,\n shouldSkipAuthForRoutePatterns: shouldSkipAuthForRoutePatternsCheck,\n });\n\n // Skip authentication for routes not matching include/exclude patterns\n // This must happen BEFORE deep linking to prevent capturing excluded paths\n // (e.g., analytics proxy paths like /ga/*, /gtm/*, /ingest/*) as return URLs\n // BUT we still allow the login URL through, as it needs deep linking support\n if (shouldSkipAuthForRoutePatternsCheck && !pathNameIsLoginUrl) {\n return response;\n }\n\n // Step 2: Handle deep link cookie for unauthenticated users using CivicAuth\n // handleDeepLinking automatically detects if we're at loginUrl or a protected route\n // and applies the appropriate logic for each case\n if (!session.authenticated) {\n const civicAuth = new CivicAuth(storage, {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n });\n const originUrl = getOriginUrl(request, authConfigWithDefaults);\n const requestUrl = `${originUrl}${request.nextUrl.pathname}${request.nextUrl.search}${request.nextUrl.hash}`;\n\n await civicAuth.handleDeepLinking(requestUrl, originUrl);\n }\n\n // Step 3: Handle login URL with special logic\n if (pathNameIsLoginUrl) {\n handleLoginUrl(request.nextUrl.pathname, session, authConfigWithDefaults);\n return response; // Always allow access to login URL\n }\n\n // Handle unauthenticated users on protected routes\n if (!session.authenticated) {\n return handleUnauthenticatedUser(\n session,\n request,\n response,\n storage,\n authConfigWithDefaults,\n );\n }\n\n // Happy ending - authentication passed\n logger.debug(\"→ Authentication successful, allowing access to\", response.url);\n copyCivicCookies(response, request);\n const authenticatedResponse = NextResponse.next({\n request, // ensure that the cookies get added to the request as well as the response\n });\n copyCivicCookies(response, authenticatedResponse);\n return authenticatedResponse;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig: OptionalAuthConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return auth()(middleware);\n}\n\nconst isRedirectResponse = (response?: NextResponse) =>\n response && response.status === 307;\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * export default auth(authConfig: AuthConfig ) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: OptionalAuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n // if the response is redirected it means that the user is not authenticated\n // so we skip the rest of the custom middleware to redirect to the login page\n if (response && isRedirectResponse(response)) {\n logger.debug(\n \"User is unauthenticated, redirecting to \",\n response.headers.get(\"location\"),\n );\n return response;\n }\n // ensure requests get the cookies in case of redirects\n if (response) {\n copyCivicCookies(response, request);\n }\n const middlewareResponse = await middleware(request);\n\n // we need to ensure that the civic cookies that were potentially\n // added by CivicAuth are set on the final response after all\n // middleware has been run\n if (response) {\n copyCivicCookies(response, middlewareResponse);\n }\n return middlewareResponse;\n };\n };\n}\n"]}
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAK9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AAExF,OAAO,EACL,oBAAoB,EACpB,2BAA2B,EAC3B,cAAc,EACd,8BAA8B,EAC9B,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,sBAAsB,GACvB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;AAMzC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,KAAK,EAC9C,sBAA8C,EAC9C,OAAsC,EAChB,EAAE;IACxB,IAAI,CAAC;QACH,MAAM,kBAAkB,GAAG,MAAM,4BAA4B,CAAC,KAAK,CACjE;YACE,GAAG,sBAAsB;YACzB,WAAW,EAAE,sBAAsB,CAAC,WAAW;SAChD,EACD,OAAO,CACR,CAAC;QACF,8FAA8F;QAC9F,MAAM,eAAe,GAAG,MAAM,kBAAkB,CAAC,uBAAuB,EAAE,CAAC;QAC3E,OAAO,eAAe,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;Q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AC6B,EAAE;QACrD,OAAO,KAAK,EAAE,OAAoB,EAAyB,EAAE;YAC3D,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;YACtD,4EAA4E;YAC5E,6EAA6E;YAC7E,IAAI,QAAQ,IAAI,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAC7C,MAAM,CAAC,KAAK,CACV,0CAA0C,EAC1C,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CACjC,CAAC;gBACF,OAAO,QAAQ,CAAC;YAClB,CAAC;YACD,uDAAuD;YACvD,IAAI,QAAQ,EAAE,CAAC;gBACb,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACtC,CAAC;YACD,MAAM,kBAAkB,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;YAErD,iEAAiE;YACjE,6DAA6D;YAC7D,0BAA0B;YAC1B,IAAI,QAAQ,EAAE,CAAC;gBACb,gBAAgB,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;YACjD,CAAC;YACD,OAAO,kBAAkB,CAAC;QAC5B,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * logger.debug('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * logger.debug('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport type {\n AuthConfigWithDefaults,\n OptionalAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { SessionData } from \"@/types.js\";\nimport {\n shouldAttemptRefresh,\n shouldSkipAuthForSystemUrls,\n handleLoginUrl,\n shouldSkipAuthForRoutePatterns,\n handleUnauthenticatedUser,\n copyCivicCookies,\n getOriginUrl,\n removeBasePathFromPath,\n} from \"./utils.js\";\nimport { NextjsMiddlewareCookieStorage } from \"./utils.js\";\nimport { UserStorage } from \"@/shared/lib/types.js\";\nimport { CivicAuth } from \"@/server/session.js\";\n\nconst logger = loggers.nextjs.middleware;\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n/**\n * use a ServerAuthenticationResolver to validate the existing session\n * using NextJS cookie storage\n * @param authConfigWithDefaults\n * @param request NextRequest object from middleware\n * @returns {Promise<SessionData>}\n */\nexport const validateAuthTokensIfPresent = async (\n authConfigWithDefaults: AuthConfigWithDefaults,\n storage: NextjsMiddlewareCookieStorage,\n): Promise<SessionData> => {\n try {\n const authSessionService = await ServerAuthenticationResolver.build(\n {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n },\n storage,\n );\n // validate the existing session and rehydrate and update cookies to the response if necessary\n const existingSession = await authSessionService.validateExistingSession();\n return existingSession;\n } catch (error) {\n logger.error(\"Error validating tokens\", error);\n return { authenticated: false };\n }\n};\n\n// internal - used by all exported functions\n/**\n * Core authentication middleware logic.\n *\n * The Authentication Story:\n * 1. Validate tokens to understand current authentication state\n * 2. Attempt token refresh if needed (the OAuth pipeline approach)\n * 3. Apply route-specific authentication rules based on final state\n */\nconst applyAuth = async (\n authConfig: OptionalAuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n const response = NextResponse.next({\n request, // ensure incoming request headers get propagated\n });\n const cookieConfig = {\n ...authConfigWithDefaults?.cookies?.tokens,\n [UserStorage.USER]: authConfigWithDefaults?.cookies?.user || {},\n };\n logger.debug(\"Incoming request:\", {\n pathName: request.nextUrl.pathname,\n method: request.method,\n });\n const storage = new NextjsMiddlewareCookieStorage(\n cookieConfig,\n request,\n response,\n );\n // check if the incoming path is a system URL\n const shouldSkipAuthForSystemUrlsCheck = shouldSkipAuthForSystemUrls(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Skip authentication for system URLs (callback, challenge, logout)\n // we don't want to validate the session in this case as this would\n // auto-hydrate and potential conflict with the logic of the api call\n if (shouldSkipAuthForSystemUrlsCheck) {\n return response;\n }\n\n // Step 1: Understand the current authentication state\n const session = await validateAuthTokensIfPresent(\n authConfigWithDefaults,\n storage,\n );\n\n const shouldSkipAuthForRoutePatternsCheck = shouldSkipAuthForRoutePatterns(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Normalize loginUrl for comparison (remove basePath if present)\n const loginPathWithoutBasePath = removeBasePathFromPath(\n authConfigWithDefaults.loginUrl,\n authConfigWithDefaults.basePath,\n );\n const pathNameIsLoginUrl =\n request.nextUrl.pathname === loginPathWithoutBasePath;\n\n logger.debug(\"Authentication state:\", {\n authenticated: session.authenticated,\n pathName: request.nextUrl.pathname,\n pathNameIsLoginUrl,\n shouldAttemptRefresh: shouldAttemptRefresh(session),\n shouldSkipAuthForSystemUrls: shouldSkipAuthForSystemUrlsCheck,\n shouldSkipAuthForRoutePatterns: shouldSkipAuthForRoutePatternsCheck,\n });\n\n // Skip authentication for routes not matching include/exclude patterns\n // This must happen BEFORE deep linking to prevent capturing excluded paths\n // (e.g., analytics proxy paths like /ga/*, /gtm/*, /ingest/*) as return URLs\n // BUT we still allow the login URL through, as it needs deep linking support\n if (shouldSkipAuthForRoutePatternsCheck && !pathNameIsLoginUrl) {\n return response;\n }\n\n // Step 2: Handle deep link cookie for unauthenticated users using CivicAuth\n // handleDeepLinking automatically detects if we're at loginUrl or a protected route\n // and applies the appropriate logic for each case\n // Note: handleDeepLinking internally skips non-GET requests (POST/PUT/DELETE etc.)\n if (!session.authenticated) {\n const civicAuth = new CivicAuth(storage, {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n });\n const originUrl = getOriginUrl(request, authConfigWithDefaults);\n const requestUrl = `${originUrl}${request.nextUrl.pathname}${request.nextUrl.search}${request.nextUrl.hash}`;\n\n await civicAuth.handleDeepLinking(requestUrl, originUrl, request.method);\n }\n\n // Step 3: Handle login URL with special logic\n if (pathNameIsLoginUrl) {\n handleLoginUrl(request.nextUrl.pathname, session, authConfigWithDefaults);\n return response; // Always allow access to login URL\n }\n\n // Handle unauthenticated users on protected routes\n if (!session.authenticated) {\n return handleUnauthenticatedUser(\n session,\n request,\n response,\n storage,\n authConfigWithDefaults,\n );\n }\n\n // Happy ending - authentication passed\n logger.debug(\"→ Authentication successful, allowing access to\", response.url);\n copyCivicCookies(response, request);\n const authenticatedResponse = NextResponse.next({\n request, // ensure that the cookies get added to the request as well as the response\n });\n copyCivicCookies(response, authenticatedResponse);\n return authenticatedResponse;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig: OptionalAuthConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return auth()(middleware);\n}\n\nconst isRedirectResponse = (response?: NextResponse) =>\n response && response.status === 307;\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * export default auth(authConfig: AuthConfig ) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: OptionalAuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n // if the response is redirected it means that the user is not authenticated\n // so we skip the rest of the custom middleware to redirect to the login page\n if (response && isRedirectResponse(response)) {\n logger.debug(\n \"User is unauthenticated, redirecting to \",\n response.headers.get(\"location\"),\n );\n return response;\n }\n // ensure requests get the cookies in case of redirects\n if (response) {\n copyCivicCookies(response, request);\n }\n const middlewareResponse = await middleware(request);\n\n // we need to ensure that the civic cookies that were potentially\n // added by CivicAuth are set on the final response after all\n // middleware has been run\n if (response) {\n copyCivicCookies(response, middlewareResponse);\n }\n return middlewareResponse;\n };\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"routeHandler.d.ts","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AASrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAuS9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAwEvB;AA0CD,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CA4DvB;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,GACjB,eAAe,MACT,SAAS,WAAW,KAAG,OAAO,CAAC,YAAY,CAuCjD,CAAC"}
1
+ {"version":3,"file":"routeHandler.d.ts","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,oBAAoB,CAAC;AAU7E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AA8W9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CA6FvB;AA0CD,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CA4DvB;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,GACjB,eAAe,MACT,SAAS,WAAW,KAAG,OAAO,CAAC,YAAY,CAuCjD,CAAC"}
@@ -4,11 +4,48 @@ import { loggers } from "../lib/logger.js";
4
4
  import { displayModeFromState } from "../lib/oauth.js";
5
5
  import { resolveAuthConfig } from "../nextjs/config.js";
6
6
  import { clearAuthCookies, NextjsCookieStorage } from "../nextjs/cookies.js";
7
- import { AuthFlowCookie, CodeVerifier, UserStorage, } from "../shared/lib/types.js";
7
+ import { AuthFlowCookie, CodeVerifier, OAuthTokenTypes, UserStorage, } from "../shared/lib/types.js";
8
8
  import { revalidatePath } from "next/cache.js";
9
9
  import { NextResponse } from "next/server.js";
10
10
  import { prependBasePath, redirectWithBasePath } from "./utils.js";
11
11
  const logger = loggers.nextjs.handlers.auth;
12
+ /**
13
+ * Helper to clear auth cookies directly on a NextResponse object.
14
+ * This is needed because cookies().set() writes to a separate response context
15
+ * that gets discarded when returning a NextResponse.redirect().
16
+ */
17
+ const clearAuthCookiesOnResponse = (response, config) => {
18
+ const basePath = config.basePath || "/";
19
+ // List of all auth cookies to clear (as strings for type safety)
20
+ const cookiesToClear = [
21
+ OAuthTokenTypes.ID_TOKEN,
22
+ OAuthTokenTypes.ACCESS_TOKEN,
23
+ OAuthTokenTypes.REFRESH_TOKEN,
24
+ OAuthTokenTypes.OIDC_SESSION_EXPIRES_AT,
25
+ CodeVerifier.COOKIE_NAME,
26
+ CodeVerifier.APP_URL,
27
+ UserStorage.USER,
28
+ AuthFlowCookie.RETURN_URL,
29
+ AuthFlowCookie.AUTH_REDIRECT_MARKER,
30
+ ];
31
+ for (const cookieName of cookiesToClear) {
32
+ // Get config for this cookie to respect path and httpOnly settings
33
+ const tokenConfig = config.cookies?.tokens?.[cookieName];
34
+ const cookiePath = (tokenConfig && "path" in tokenConfig ? tokenConfig.path : undefined) ||
35
+ basePath;
36
+ const cookieHttpOnly = (tokenConfig && "httpOnly" in tokenConfig
37
+ ? tokenConfig.httpOnly
38
+ : undefined) ?? true;
39
+ // Use set() with maxAge: 0 to delete
40
+ // Keep httpOnly from config but omit secure/sameSite to avoid dynamic value mismatch
41
+ response.cookies.set(cookieName, "", {
42
+ maxAge: 0,
43
+ path: cookiePath,
44
+ httpOnly: cookieHttpOnly,
45
+ });
46
+ }
47
+ logger.debug("[clearAuthCookiesOnResponse] Cleared auth cookies on response");
48
+ };
12
49
  class AuthError extends Error {
13
50
  status;
14
51
  constructor(message, status = 401) {
@@ -53,9 +90,22 @@ const createCivicAuth = (request, config) => {
53
90
  const absoluteCallbackUrl = resolvedConfig.callbackUrl.startsWith("http")
54
91
  ? resolvedConfig.callbackUrl
55
92
  : CivicAuth.toAbsoluteUrl(urlDetectionRequest, resolvedConfig.callbackUrl, appUrl);
56
- const absoluteLogoutCallbackUrl = resolvedConfig.logoutCallbackUrl.startsWith("http")
57
- ? resolvedConfig.logoutCallbackUrl
58
- : CivicAuth.toAbsoluteUrl(urlDetectionRequest, resolvedConfig.logoutCallbackUrl, appUrl);
93
+ // For logoutCallbackUrl, prepend basePath if it's a relative path
94
+ // This ensures the OAuth server redirects to the correct URL with basePath
95
+ const logoutCallbackWithBasePath = resolvedConfig.basePath &&
96
+ !resolvedConfig.logoutCallbackUrl.startsWith("http")
97
+ ? prependBasePath(resolvedConfig.logoutCallbackUrl, resolvedConfig.basePath)
98
+ : resolvedConfig.logoutCallbackUrl;
99
+ const absoluteLogoutCallbackUrl = logoutCallbackWithBasePath.startsWith("http")
100
+ ? logoutCallbackWithBasePath
101
+ : CivicAuth.toAbsoluteUrl(urlDetectionRequest, logoutCallbackWithBasePath, appUrl);
102
+ // For loginSuccessUrl, prepend basePath if it's a relative path
103
+ // This ensures post-login redirects go to the correct URL with basePath
104
+ const loginSuccessUrlWithBasePath = resolvedConfig.loginSuccessUrl &&
105
+ resolvedConfig.basePath &&
106
+ !resolvedConfig.loginSuccessUrl.startsWith("http")
107
+ ? prependBasePath(resolvedConfig.loginSuccessUrl, resolvedConfig.basePath)
108
+ : resolvedConfig.loginSuccessUrl;
59
109
  const civicAuth = new CivicAuth(cookieStorage, {
60
110
  disableRefresh: resolvedConfig.disableRefresh,
61
111
  clientId: resolvedConfig.clientId,
@@ -64,7 +114,7 @@ const createCivicAuth = (request, config) => {
64
114
  postLogoutRedirectUrl: absoluteLogoutCallbackUrl,
65
115
  // Note: Do NOT use request.url here - during callback, that would be the callback URL itself,
66
116
  // causing an infinite redirect loop in iframe mode fallbacks.
67
- loginSuccessUrl: resolvedConfig.loginSuccessUrl,
117
+ loginSuccessUrl: loginSuccessUrlWithBasePath,
68
118
  // Pass basePath and deepLinkHandling for generalized deep-linking support
69
119
  basePath: resolvedConfig.basePath,
70
120
  deepLinkHandling: resolvedConfig.deepLinkHandling,
@@ -238,27 +288,42 @@ export async function handleLogout(request, config) {
238
288
  const logoutUrl = await civicAuth.buildLogoutRedirectUrl({
239
289
  state: state || undefined,
240
290
  });
291
+ // Remove state parameter from logout URL to prevent it from appearing in frontend URL
292
+ const cleanLogoutUrl = new URL(logoutUrl);
293
+ cleanLogoutUrl.searchParams.delete("state");
294
+ // Create the redirect response FIRST, then clear cookies ON that response.
295
+ // This is critical because cookies().set() writes to a separate response context
296
+ // that gets discarded when returning NextResponse.redirect().
297
+ const redirectResponse = NextResponse.redirect(cleanLogoutUrl.toString());
298
+ // Clear auth cookies directly on the redirect response
299
+ clearAuthCookiesOnResponse(redirectResponse, resolvedConfigs);
300
+ // Also call the original clearAuthCookies for any non-redirect contexts (e.g., API calls)
241
301
  try {
242
302
  await clearAuthCookies(resolvedConfigs);
243
303
  }
244
304
  catch (error) {
245
- logger.error("[LOGOUT_HANDLER] Error clearing tokens:", error);
305
+ logger.error("[LOGOUT_HANDLER] Error clearing tokens via cookies():", error);
246
306
  }
247
- // Remove state parameter from logout URL to prevent it from appearing in frontend URL
248
- const cleanLogoutUrl = new URL(logoutUrl);
249
- cleanLogoutUrl.searchParams.delete("state");
250
307
  logger.info("[LOGOUT_HANDLER] Redirecting to OAuth logout endpoint", {
251
308
  logoutUrl: cleanLogoutUrl.toString(),
252
309
  });
253
- return NextResponse.redirect(cleanLogoutUrl.toString());
310
+ return redirectResponse;
254
311
  }
255
312
  catch (error) {
256
313
  logger.error("[LOGOUT_HANDLER] Logout error:", error);
257
- // If logout URL generation fails, clear tokens and redirect to home
258
- await clearAuthCookies(resolvedConfigs);
259
314
  const fallbackUrl = clientLogoutRedirectUrl || resolvedConfigs.logoutCallbackUrl;
260
315
  const finalFallbackUrl = CivicAuth.toAbsoluteUrl(urlDetectionRequest, fallbackUrl, appUrl);
261
- return NextResponse.redirect(finalFallbackUrl);
316
+ // Create redirect response and clear cookies on it
317
+ const fallbackResponse = NextResponse.redirect(finalFallbackUrl);
318
+ clearAuthCookiesOnResponse(fallbackResponse, resolvedConfigs);
319
+ // Also try the original method
320
+ try {
321
+ await clearAuthCookies(resolvedConfigs);
322
+ }
323
+ catch (clearError) {
324
+ logger.error("[LOGOUT_HANDLER] Error clearing tokens:", clearError);
325
+ }
326
+ return fallbackResponse;
262
327
  }
263
328
  }
264
329
  /**