@civic/auth 0.13.0 → 0.13.1-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.
Files changed (42) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +102 -1
  3. package/dist/lib/oauth.d.ts +12 -1
  4. package/dist/lib/oauth.d.ts.map +1 -1
  5. package/dist/lib/oauth.js +29 -1
  6. package/dist/lib/oauth.js.map +1 -1
  7. package/dist/nextjs/config.d.ts +2 -11
  8. package/dist/nextjs/config.d.ts.map +1 -1
  9. package/dist/nextjs/config.js.map +1 -1
  10. package/dist/nextjs/middleware.d.ts.map +1 -1
  11. package/dist/nextjs/middleware.js +18 -3
  12. package/dist/nextjs/middleware.js.map +1 -1
  13. package/dist/nextjs/routeHandler.d.ts.map +1 -1
  14. package/dist/nextjs/routeHandler.js +15 -71
  15. package/dist/nextjs/routeHandler.js.map +1 -1
  16. package/dist/nextjs/utils.d.ts +9 -3
  17. package/dist/nextjs/utils.d.ts.map +1 -1
  18. package/dist/nextjs/utils.js +10 -52
  19. package/dist/nextjs/utils.js.map +1 -1
  20. package/dist/server/config.d.ts +23 -0
  21. package/dist/server/config.d.ts.map +1 -1
  22. package/dist/server/config.js.map +1 -1
  23. package/dist/server/session.d.ts +57 -0
  24. package/dist/server/session.d.ts.map +1 -1
  25. package/dist/server/session.js +205 -9
  26. package/dist/server/session.js.map +1 -1
  27. package/dist/shared/lib/cookieConfig.d.ts.map +1 -1
  28. package/dist/shared/lib/cookieConfig.js +6 -1
  29. package/dist/shared/lib/cookieConfig.js.map +1 -1
  30. package/dist/shared/lib/types.d.ts +5 -1
  31. package/dist/shared/lib/types.d.ts.map +1 -1
  32. package/dist/shared/lib/types.js +4 -0
  33. package/dist/shared/lib/types.js.map +1 -1
  34. package/dist/shared/lib/util.d.ts +38 -1
  35. package/dist/shared/lib/util.d.ts.map +1 -1
  36. package/dist/shared/lib/util.js +95 -0
  37. package/dist/shared/lib/util.js.map +1 -1
  38. package/dist/shared/version.d.ts +1 -1
  39. package/dist/shared/version.d.ts.map +1 -1
  40. package/dist/shared/version.js +1 -1
  41. package/dist/shared/version.js.map +1 -1
  42. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ # 0.13.1 - Generalised server support for deep-linking
2
+ - support deep-linking in all servers by setting a return_to cookie and propagating it via state through the OAuth flow
3
+ - add `deepLinkHandling` configuration option for all server SDKs with three modes: `"fullUrl"`, `"queryParamsOnly"`, `"disabled"`
4
+
1
5
  # 0.13.0 - NextJS support for deep-linking
2
6
  - support NextJS deep-linking by setting a return_to cookie and propagating it via state through the OAuth flow
3
7
  - add `deepLinkHandling` configuration option with three modes: `"fullUrl"`, `"queryParamsOnly"`, `"disabled"`
package/README.md CHANGED
@@ -30,6 +30,7 @@
30
30
  - [Getting User Information on the Frontend](#getting-user-information-on-the-frontend-1)
31
31
  - [Getting User Information on the Backend](#getting-user-information-on-the-backend)
32
32
  - [Advanced Configuration](#advanced-configuration-1)
33
+ - [Deep Linking](#deep-linking)
33
34
  - [Server Integration](#server-integration)
34
35
  - [Client Secret Support](#client-secret-support)
35
36
  - [Using the CivicAuth Interface](#using-the-civicauth-interface)
@@ -37,6 +38,7 @@
37
38
  - [Framework Examples](#framework-examples)
38
39
  - [Express Example](#express-example)
39
40
  - [Available Methods](#available-methods)
41
+ - [Deep Linking for Server Frameworks](#deep-linking-for-server-frameworks)
40
42
  - [Server-Side Token Validation](#server-side-token-validation)
41
43
  - [Authentication Storage and State](#authentication-storage-and-state)
42
44
  - [Storage Entries](#storage-entries)
@@ -452,7 +454,36 @@ export default withCivicAuth(nextConfig) // your next config here
452
454
 
453
455
  Here are the available configuration options:
454
456
 
455
- <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>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>['public/home']</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>. In some cases, it might be easier and safer to specify exceptions rather than keep an inclusion list up to date.</td></tr></tbody></table>
457
+ <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>['public/home']</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>. In some cases, it might be easier and safer to specify exceptions rather than keep an inclusion list up to date.</td></tr></tbody></table>
458
+
459
+ ### Deep Linking
460
+
461
+ 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.
462
+
463
+ **Configuration Options:**
464
+
465
+ | Value | Description |
466
+ |-------|-------------|
467
+ | `"fullUrl"` (default) | Preserves the full URL including path and query parameters |
468
+ | `"queryParamsOnly"` | Preserves only query parameters, redirects to root path |
469
+ | `"disabled"` | Disables deep linking entirely |
470
+
471
+ **Example:**
472
+
473
+ ```typescript
474
+ const withCivicAuth = createCivicAuthPlugin({
475
+ clientId: 'YOUR CLIENT ID',
476
+ deepLinkConfig: 'fullUrl' // or 'queryParamsOnly' or 'disabled'
477
+ });
478
+ ```
479
+
480
+ **How it works:**
481
+
482
+ 1. User visits `/dashboard?tab=settings` (unauthenticated)
483
+ 2. Middleware stores the URL in a cookie and redirects to login
484
+ 3. After successful authentication, user is redirected back to `/dashboard?tab=settings`
485
+
486
+ This is handled automatically by the Civic Auth middleware - no additional code required.
456
487
 
457
488
  # Server Integration
458
489
 
@@ -579,11 +610,81 @@ The CivicAuth interface provides the following methods:
579
610
  | `isLoggedIn()` | Checks if the user is currently logged in |
580
611
  | `buildLoginUrl(options?)` | Builds a login URL to redirect the user to |
581
612
  | `buildLogoutRedirectUrl(options?)` | Builds a logout URL to redirect the user to |
613
+ | `handleDeepLinking(requestUrl, originUrl)` | Stores the current URL for post-login redirect |
614
+ | `handleCallback()` | Handles OAuth callback and redirects to stored deep link |
582
615
  | `refreshTokens()` | Refreshes the current set of OIDC tokens |
583
616
  | `clearTokens()` | Clears all authentication tokens from storage |
584
617
 
585
618
  Each method is designed to be used in a server-side context and includes proper validation of tokens to ensure security.
586
619
 
620
+ ### Deep Linking for Server Frameworks
621
+
622
+ 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.
623
+
624
+ **Configuration:**
625
+
626
+ When creating your CivicAuth instance, you can configure deep linking behavior:
627
+
628
+ ```typescript
629
+ const config = {
630
+ clientId: 'YOUR_CLIENT_ID',
631
+ redirectUrl: 'http://yoursite.com/auth/callback',
632
+ // ... other config
633
+ deepLinkConfig: 'fullUrl' // or 'queryParamsOnly' or 'disabled'
634
+ };
635
+ ```
636
+
637
+ | Value | Description |
638
+ |-------|-------------|
639
+ | `"fullUrl"` (default) | Preserves the full URL including path and query parameters |
640
+ | `"queryParamsOnly"` | Preserves only query parameters, redirects to root path |
641
+ | `"disabled"` | Disables deep linking entirely |
642
+
643
+ **Usage in Protected Routes:**
644
+
645
+ Call `handleDeepLinking` before redirecting unauthenticated users to login:
646
+
647
+ ```typescript
648
+ // Express example
649
+ app.use(async (req, res, next) => {
650
+ if (!(await req.civicAuth.isLoggedIn())) {
651
+ // Set up deep linking before redirecting to login
652
+ const requestUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
653
+ const originUrl = `${req.protocol}://${req.get("host")}`;
654
+
655
+ await req.civicAuth.handleDeepLinking(requestUrl, originUrl);
656
+
657
+ const loginUrl = await req.civicAuth.buildLoginUrl();
658
+ return res.redirect(loginUrl.toString());
659
+ }
660
+ next();
661
+ });
662
+ ```
663
+
664
+ ```typescript
665
+ // Fastify example
666
+ fastify.addHook('preHandler', async (request, reply) => {
667
+ if (!(await request.civicAuth.isLoggedIn())) {
668
+ const protocol = request.headers["x-forwarded-proto"] || request.protocol || "http";
669
+ const host = request.headers.host || "localhost";
670
+ const requestUrl = `${protocol}://${host}${request.url}`;
671
+ const originUrl = `${protocol}://${host}`;
672
+
673
+ await request.civicAuth.handleDeepLinking(requestUrl, originUrl);
674
+
675
+ const loginUrl = await request.civicAuth.buildLoginUrl();
676
+ return reply.redirect(loginUrl.toString());
677
+ }
678
+ });
679
+ ```
680
+
681
+ **How it works:**
682
+
683
+ 1. User visits `/dashboard?tab=settings` (unauthenticated)
684
+ 2. `handleDeepLinking()` stores the URL in a cookie
685
+ 3. `buildLoginUrl()` encodes the return URL into OAuth state
686
+ 4. After authentication, `handleCallback()` redirects to the original URL
687
+
587
688
  ### Server-Side Token Validation
588
689
 
589
690
  The CivicAuth interface automatically validates tokens for you when using `getUser()` or `getTokens()` methods, providing an extra layer of security for your server-side authentication logic.
@@ -27,5 +27,16 @@ declare const displayModeFromState: (state: string, sessionDisplayMode: DisplayM
27
27
  declare const serverTokenExchangeFromState: (state: string) => boolean | undefined;
28
28
  declare const loginSuccessUrlFromState: (state: string | null) => string | undefined;
29
29
  declare const iframeDisplayModeFromState: (state: string) => "modal" | "embedded" | undefined;
30
- export { serverTokenExchangeFromState, loginSuccessUrlFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, iframeDisplayModeFromState, generateState, addSlashIfNeeded, };
30
+ /**
31
+ * Injects loginSuccessUrl into an existing base64-encoded state string, or creates
32
+ * a new state if none exists. This allows the deep link destination (computed by
33
+ * middleware) to be passed through the OAuth flow via the existing loginSuccessUrl
34
+ * mechanism.
35
+ *
36
+ * @param frontendState - The existing base64-encoded state string (can be null)
37
+ * @param loginSuccessUrl - The URL to inject into the state
38
+ * @returns The updated base64-encoded state string
39
+ */
40
+ declare const injectLoginSuccessUrlIntoState: (frontendState: string | null, loginSuccessUrl: string) => string;
41
+ export { serverTokenExchangeFromState, loginSuccessUrlFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, iframeDisplayModeFromState, generateState, addSlashIfNeeded, injectLoginSuccessUrlIntoState, };
31
42
  //# sourceMappingURL=oauth.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EAET,aAAa,EACd,MAAM,YAAY,CAAC;AAGpB,QAAA,MAAM,mBAAmB,WAAY,MAAM,KAAG,MAAM,EAQnD,CAAC;AAEF,QAAA,MAAM,gBAAgB,QAAS,MAAM,KAAG,MACH,CAAC;AAGtC,QAAA,MAAM,iBAAiB,gBAAuB,MAAM,KAAG,OAAO,CAAC,SAAS,C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C;AAEF;;;;GAIG;AACH,KAAK,kBAAkB,GAAG;IACxB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,iBAAiB,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;IACzC,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AACF,QAAA,MAAM,aAAa,2HAQhB,kBAAkB,KAAG,MAYvB,CAAC;AAEF;;;;;GAKG;AACH,QAAA,MAAM,oBAAoB,UACjB,MAAM,sBACO,WAAW,GAAG,SAAS,KAC1C,WAAW,GAAG,SAQhB,CAAC;AAsBF,QAAA,MAAM,4BAA4B,UAAW,MAAM,KAAG,OAAO,GAAG,SACvB,CAAC;AAE1C,QAAA,MAAM,wBAAwB,UAAW,MAAM,GAAG,IAAI,KAAG,MAAM,GAAG,SACT,CAAC;AAE1D,QAAA,MAAM,0BAA0B,UACvB,MAAM,KACZ,OAAO,GAAG,UAAU,GAAG,SAAkD,CAAC;AAE7E;;;;;;;;;GASG;AACH,QAAA,MAAM,8BAA8B,kBACnB,MAAM,GAAG,IAAI,mBACX,MAAM,KACtB,MAqBF,CAAC;AAEF,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,0BAA0B,EAC1B,aAAa,EACb,gBAAgB,EAChB,8BAA8B,GAC/B,CAAC"}
package/dist/lib/oauth.js CHANGED
@@ -66,5 +66,33 @@ const decodeState = (state) => {
66
66
  const serverTokenExchangeFromState = (state) => decodeState(state)?.serverTokenExchange;
67
67
  const loginSuccessUrlFromState = (state) => state ? decodeState(state)?.loginSuccessUrl : undefined;
68
68
  const iframeDisplayModeFromState = (state) => decodeState(state)?.iframeDisplayMode;
69
- export { serverTokenExchangeFromState, loginSuccessUrlFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, iframeDisplayModeFromState, generateState, addSlashIfNeeded, };
69
+ /**
70
+ * Injects loginSuccessUrl into an existing base64-encoded state string, or creates
71
+ * a new state if none exists. This allows the deep link destination (computed by
72
+ * middleware) to be passed through the OAuth flow via the existing loginSuccessUrl
73
+ * mechanism.
74
+ *
75
+ * @param frontendState - The existing base64-encoded state string (can be null)
76
+ * @param loginSuccessUrl - The URL to inject into the state
77
+ * @returns The updated base64-encoded state string
78
+ */
79
+ const injectLoginSuccessUrlIntoState = (frontendState, loginSuccessUrl) => {
80
+ let stateObj = {};
81
+ if (frontendState) {
82
+ try {
83
+ // Decode the existing state
84
+ const jsonString = atob(frontendState);
85
+ stateObj = JSON.parse(jsonString);
86
+ }
87
+ catch {
88
+ // Continue with empty stateObj - we'll still add loginSuccessUrl
89
+ console.warn("[injectLoginSuccessUrlIntoState] Failed to parse existing state, creating new state");
90
+ }
91
+ }
92
+ // Set loginSuccessUrl in state (overrides any existing value for fullUrl mode)
93
+ stateObj.loginSuccessUrl = loginSuccessUrl;
94
+ // Encode and return the state
95
+ return btoa(JSON.stringify(stateObj));
96
+ };
97
+ export { serverTokenExchangeFromState, loginSuccessUrlFromState, getIssuerVariations, getOauthEndpoints, displayModeFromState, iframeDisplayModeFromState, generateState, addSlashIfNeeded, injectLoginSuccessUrlIntoState, };
70
98
  //# sourceMappingURL=oauth.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAElC,MAAM,mBAAmB,GAAG,CAAC,MAAc,EAAY,EAAE;IACvD,MAAM,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;QAC7C,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC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AC;QAC/B,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,KAAK,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;QAC9D,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,4BAA4B,GAAG,CAAC,KAAa,EAAuB,EAAE,CAC1E,WAAW,CAAC,KAAK,CAAC,EAAE,mBAAmB,CAAC;AAE1C,MAAM,wBAAwB,GAAG,CAAC,KAAoB,EAAsB,EAAE,CAC5E,KAAK,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;AAE1D,MAAM,0BAA0B,GAAG,CACjC,KAAa,EACqB,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,iBAAiB,CAAC;AAE7E,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,0BAA0B,EAC1B,aAAa,EACb,gBAAgB,GACjB,CAAC","sourcesContent":["import type {\n DisplayMode,\n Endpoints,\n OpenIdConfiguration,\n FrameworkType,\n} from \"@/types.js\";\nimport { v4 as uuid } from \"uuid\";\n\nconst getIssuerVariations = (issuer: string): string[] => {\n const issuerWithoutSlash = issuer.endsWith(\"/\")\n ? issuer.slice(0, issuer.length - 1)\n : issuer;\n\n const issuerWithSlash = `${issuerWithoutSlash}/`;\n\n return [issuerWithoutSlash, issuerWithSlash];\n};\n\nconst addSlashIfNeeded = (url: string): string =>\n url.endsWith(\"/\") ? url : `${url}/`;\n\nconst cache: { [key: string]: Endpoints } = {};\nconst getOauthEndpoints = async (oauthServer: string): Promise<Endpoints> => {\n if (cache[oauthServer]) {\n return cache[oauthServer];\n }\n\n const openIdConfigResponse = await fetch(\n `${addSlashIfNeeded(oauthServer)}.well-known/openid-configuration`,\n );\n const openIdConfig =\n (await openIdConfigResponse.json()) as OpenIdConfiguration;\n const endpoints: Endpoints = {\n jwks: openIdConfig.jwks_uri,\n auth: openIdConfig.authorization_endpoint,\n token: openIdConfig.token_endpoint,\n userinfo: openIdConfig.userinfo_endpoint,\n endsession: openIdConfig.end_session_endpoint,\n };\n\n cache[oauthServer] = endpoints;\n return endpoints;\n};\n\n/**\n * creates a state string for the OAuth2 flow, encoding the display mode too for future use\n * @param {DisplayMode} displayMode\n * @returns {string}\n */\ntype GenerateStateInput = {\n displayMode?: DisplayMode;\n iframeDisplayMode?: \"modal\" | \"embedded\";\n serverTokenExchange?: boolean;\n loginSuccessUrl?: string;\n framework?: FrameworkType;\n sdkVersion?: string;\n previousSessionStale?: boolean;\n};\nconst generateState = ({\n displayMode,\n iframeDisplayMode,\n serverTokenExchange,\n loginSuccessUrl,\n framework,\n sdkVersion,\n previousSessionStale,\n}: GenerateStateInput): string => {\n const jsonString = JSON.stringify({\n uuid: uuid(),\n ...(displayMode ? { displayMode } : {}),\n ...(iframeDisplayMode ? { iframeDisplayMode } : {}),\n ...(serverTokenExchange ? { serverTokenExchange } : {}),\n ...(loginSuccessUrl ? { loginSuccessUrl } : {}),\n ...(framework ? { framework } : {}),\n ...(sdkVersion ? { sdkVersion } : {}),\n ...(previousSessionStale ? { previousSessionStale } : {}),\n });\n return btoa(jsonString);\n};\n\n/**\n * parses the state string from the OAuth2 flow, decoding the display mode too\n * @param state\n * @param sessionDisplayMode\n * @returns { uuid: string, displayMode: DisplayMode }\n */\nconst displayModeFromState = (\n state: string,\n sessionDisplayMode: DisplayMode | undefined,\n): DisplayMode | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString).displayMode;\n } catch (e) {\n console.error(\"Failed to parse displayMode from state:\", state, e);\n return sessionDisplayMode;\n }\n};\n\nconst decodeState = (\n state: string,\n):\n | {\n serverTokenExchange?: boolean;\n loginSuccessUrl?: string;\n framework?: FrameworkType;\n sdkVersion?: string;\n iframeDisplayMode?: \"modal\" | \"embedded\";\n }\n | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString);\n } catch {\n console.error(\"Failed to parse state string to json:\", state);\n return undefined;\n }\n};\n\nconst serverTokenExchangeFromState = (state: string): boolean | undefined =>\n decodeState(state)?.serverTokenExchange;\n\nconst loginSuccessUrlFromState = (state: string | null): string | undefined =>\n state ? decodeState(state)?.loginSuccessUrl : undefined;\n\nconst iframeDisplayModeFromState = (\n state: string,\n): \"modal\" | \"embedded\" | undefined => decodeState(state)?.iframeDisplayMode;\n\nexport {\n serverTokenExchangeFromState,\n loginSuccessUrlFromState,\n getIssuerVariations,\n getOauthEndpoints,\n displayModeFromState,\n iframeDisplayModeFromState,\n generateState,\n addSlashIfNeeded,\n};\n"]}
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/lib/oauth.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAElC,MAAM,mBAAmB,GAAG,CAAC,MAAc,EAAY,EAAE;IACvD,MAAM,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;QAC7C,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QACpC,CAAC,CAAC,MAAM,CAAC;IAEX,MAAM,eAAe,GAAG,GAAG,kBAAkB,GAAG,CAAC;IAEjD,OAAO,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;AAC/C,CAAC,CAAC;AAEF,MAAM,gBAAgB,GAAG,CAAC,GAAW,EAAU,EAAE,CAC/C,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC;AAEtC,MAAM,KAAK,GAAiC,EAAE,CAAC;AAC/C,MAAM,iBAAiB,GAAG,KAAK,EAAE,WAAmB,EAAsB,EAAE;IAC1E,IAAI,KAAK,CAAC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AAC,SAAS,CAAC;AAE1D,MAAM,0BAA0B,GAAG,CACjC,KAAa,EACqB,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,iBAAiB,CAAC;AAE7E;;;;;;;;;GASG;AACH,MAAM,8BAA8B,GAAG,CACrC,aAA4B,EAC5B,eAAuB,EACf,EAAE;IACV,IAAI,QAAQ,GAA4B,EAAE,CAAC;IAE3C,IAAI,aAAa,EAAE,CAAC;QAClB,IAAI,CAAC;YACH,4BAA4B;YAC5B,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,CAAC,CAAC;YACvC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACpC,CAAC;QAAC,MAAM,CAAC;YACP,iEAAiE;YACjE,OAAO,CAAC,IAAI,CACV,qFAAqF,CACtF,CAAC;QACJ,CAAC;IACH,CAAC;IAED,+EAA+E;IAC/E,QAAQ,CAAC,eAAe,GAAG,eAAe,CAAC;IAE3C,8BAA8B;IAC9B,OAAO,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;AACxC,CAAC,CAAC;AAEF,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,0BAA0B,EAC1B,aAAa,EACb,gBAAgB,EAChB,8BAA8B,GAC/B,CAAC","sourcesContent":["import type {\n DisplayMode,\n Endpoints,\n OpenIdConfiguration,\n FrameworkType,\n} from \"@/types.js\";\nimport { v4 as uuid } from \"uuid\";\n\nconst getIssuerVariations = (issuer: string): string[] => {\n const issuerWithoutSlash = issuer.endsWith(\"/\")\n ? issuer.slice(0, issuer.length - 1)\n : issuer;\n\n const issuerWithSlash = `${issuerWithoutSlash}/`;\n\n return [issuerWithoutSlash, issuerWithSlash];\n};\n\nconst addSlashIfNeeded = (url: string): string =>\n url.endsWith(\"/\") ? url : `${url}/`;\n\nconst cache: { [key: string]: Endpoints } = {};\nconst getOauthEndpoints = async (oauthServer: string): Promise<Endpoints> => {\n if (cache[oauthServer]) {\n return cache[oauthServer];\n }\n\n const openIdConfigResponse = await fetch(\n `${addSlashIfNeeded(oauthServer)}.well-known/openid-configuration`,\n );\n const openIdConfig =\n (await openIdConfigResponse.json()) as OpenIdConfiguration;\n const endpoints: Endpoints = {\n jwks: openIdConfig.jwks_uri,\n auth: openIdConfig.authorization_endpoint,\n token: openIdConfig.token_endpoint,\n userinfo: openIdConfig.userinfo_endpoint,\n endsession: openIdConfig.end_session_endpoint,\n };\n\n cache[oauthServer] = endpoints;\n return endpoints;\n};\n\n/**\n * creates a state string for the OAuth2 flow, encoding the display mode too for future use\n * @param {DisplayMode} displayMode\n * @returns {string}\n */\ntype GenerateStateInput = {\n displayMode?: DisplayMode;\n iframeDisplayMode?: \"modal\" | \"embedded\";\n serverTokenExchange?: boolean;\n loginSuccessUrl?: string;\n framework?: FrameworkType;\n sdkVersion?: string;\n previousSessionStale?: boolean;\n};\nconst generateState = ({\n displayMode,\n iframeDisplayMode,\n serverTokenExchange,\n loginSuccessUrl,\n framework,\n sdkVersion,\n previousSessionStale,\n}: GenerateStateInput): string => {\n const jsonString = JSON.stringify({\n uuid: uuid(),\n ...(displayMode ? { displayMode } : {}),\n ...(iframeDisplayMode ? { iframeDisplayMode } : {}),\n ...(serverTokenExchange ? { serverTokenExchange } : {}),\n ...(loginSuccessUrl ? { loginSuccessUrl } : {}),\n ...(framework ? { framework } : {}),\n ...(sdkVersion ? { sdkVersion } : {}),\n ...(previousSessionStale ? { previousSessionStale } : {}),\n });\n return btoa(jsonString);\n};\n\n/**\n * parses the state string from the OAuth2 flow, decoding the display mode too\n * @param state\n * @param sessionDisplayMode\n * @returns { uuid: string, displayMode: DisplayMode }\n */\nconst displayModeFromState = (\n state: string,\n sessionDisplayMode: DisplayMode | undefined,\n): DisplayMode | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString).displayMode;\n } catch (e) {\n console.error(\"Failed to parse displayMode from state:\", state, e);\n return sessionDisplayMode;\n }\n};\n\nconst decodeState = (\n state: string,\n):\n | {\n serverTokenExchange?: boolean;\n loginSuccessUrl?: string;\n framework?: FrameworkType;\n sdkVersion?: string;\n iframeDisplayMode?: \"modal\" | \"embedded\";\n }\n | undefined => {\n try {\n const jsonString = atob(state);\n return JSON.parse(jsonString);\n } catch {\n console.error(\"Failed to parse state string to json:\", state);\n return undefined;\n }\n};\n\nconst serverTokenExchangeFromState = (state: string): boolean | undefined =>\n decodeState(state)?.serverTokenExchange;\n\nconst loginSuccessUrlFromState = (state: string | null): string | undefined =>\n state ? decodeState(state)?.loginSuccessUrl : undefined;\n\nconst iframeDisplayModeFromState = (\n state: string,\n): \"modal\" | \"embedded\" | undefined => decodeState(state)?.iframeDisplayMode;\n\n/**\n * Injects loginSuccessUrl into an existing base64-encoded state string, or creates\n * a new state if none exists. This allows the deep link destination (computed by\n * middleware) to be passed through the OAuth flow via the existing loginSuccessUrl\n * mechanism.\n *\n * @param frontendState - The existing base64-encoded state string (can be null)\n * @param loginSuccessUrl - The URL to inject into the state\n * @returns The updated base64-encoded state string\n */\nconst injectLoginSuccessUrlIntoState = (\n frontendState: string | null,\n loginSuccessUrl: string,\n): string => {\n let stateObj: Record<string, unknown> = {};\n\n if (frontendState) {\n try {\n // Decode the existing state\n const jsonString = atob(frontendState);\n stateObj = JSON.parse(jsonString);\n } catch {\n // Continue with empty stateObj - we'll still add loginSuccessUrl\n console.warn(\n \"[injectLoginSuccessUrlIntoState] Failed to parse existing state, creating new state\",\n );\n }\n }\n\n // Set loginSuccessUrl in state (overrides any existing value for fullUrl mode)\n stateObj.loginSuccessUrl = loginSuccessUrl;\n\n // Encode and return the state\n return btoa(JSON.stringify(stateObj));\n};\n\nexport {\n serverTokenExchangeFromState,\n loginSuccessUrlFromState,\n getIssuerVariations,\n getOauthEndpoints,\n displayModeFromState,\n iframeDisplayModeFromState,\n generateState,\n addSlashIfNeeded,\n injectLoginSuccessUrlIntoState,\n};\n"]}
@@ -1,18 +1,9 @@
1
1
  import type { NextConfig } from "next";
2
2
  import { type CookieConfig, type TokensCookieConfig } from "../shared/lib/types.js";
3
3
  import { type CookiesConfigObject } from "../shared/lib/cookieConfig.js";
4
+ import type { DeepLinkHandling } from "../server/config.js";
4
5
  export type { CookiesConfigObject };
5
- /**
6
- * Controls how deep links (original URLs) are handled after authentication.
7
- *
8
- * - `"fullUrl"`: Redirect to the original URL the user tried to access.
9
- * `loginSuccessUrl` is used as fallback only when no deep link exists.
10
- * - `"queryParamsOnly"`: Redirect to `loginSuccessUrl`, but merge query params from original URL.
11
- * - `"disabled"`: No deep link preservation. Always use `loginSuccessUrl`.
12
- *
13
- * @default "fullUrl"
14
- */
15
- export type DeepLinkHandling = "fullUrl" | "queryParamsOnly" | "disabled";
6
+ export type { DeepLinkHandling } from "../server/config.js";
16
7
  export declare const systemUrlsConfig: {
17
8
  callbackUrl: {
18
9
  defaultPath: string;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/nextjs/config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAGvC,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACxB,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAEL,KAAK,mBAAmB,EACzB,MAAM,8BAA8B,CAAC;AAGtC,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAIpC;;;;;;;;;GASG;AACH,MAAM,MAAM,gBAAgB,GAAG,SAAS,GAAG,iBAAiB,GAAG,UAAU,CAAC;AAY1E,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAW5B,CAAC;AAsBF;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IAEpB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IAC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AAe;gBAC7D,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,yBAAyB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC;gBACjE,qBAAqB,EAAE,cAAc,CAAC,QAAQ;gBAC9C,oBAAoB,EAAE,cAAc,CAAC,OAAO;gBAC5C,yBAAyB,EAAE,cAAc,CAAC,YAAY,CAAC,QAAQ,EAAE;gBACjE,2BAA2B,EAAE,cAAc,CAAC,cAAc,EAAE,QAAQ,EAAE;gBACtE,8BAA8B,EAAE,cAAc,CAAC,gBAAgB;aAChE;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/* eslint-disable turbo/no-undeclared-env-vars */\nimport type { NextConfig } from \"next\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { withoutUndefined } from \"@/utils.js\";\nimport {\n AuthFlowCookie,\n type CookieConfig,\n type TokensCookieConfig,\n} from \"@/shared/lib/types.js\";\nimport { DEFAULT_AUTH_SERVER } from \"@/constants.js\";\nimport { merge } from \"ts-deepmerge\";\nimport { sanitizeBasePath } from \"./utils.js\";\nimport {\n createNextJSCookieConfig,\n type CookiesConfigObject,\n} from \"@/shared/lib/cookieConfig.js\";\n\n// Re-export the shared type for public API\nexport type { CookiesConfigObject };\n\nconst logger = loggers.nextjs.handlers.auth;\n\n/**\n * Controls how deep links (original URLs) are handled after authentication.\n *\n * - `\"fullUrl\"`: Redirect to the original URL the user tried to access.\n * `loginSuccessUrl` is used as fallback only when no deep link exists.\n * - `\"queryParamsOnly\"`: Redirect to `loginSuccessUrl`, but merge query params from original URL.\n * - `\"disabled\"`: No deep link preservation. Always use `loginSuccessUrl`.\n *\n * @default \"fullUrl\"\n */\nexport type DeepLinkHandling = \"fullUrl\" | \"queryParamsOnly\" | \"disabled\";\n\n/**\n * URL configuration mapping for applying basePath\n */\ntype UrlConfigEntry = {\n defaultPath: string;\n applyBasePath: boolean;\n useBasePathOnly?: boolean;\n checkEmpty?: boolean;\n};\n\nexport const systemUrlsConfig = {\n callbackUrl: { defaultPath: \"/api/auth/callback\", applyBasePath: true },\n challengeUrl: { defaultPath: \"/api/auth/challenge\", applyBasePath: true },\n refreshUrl: { defaultPath: \"/api/auth/refresh\", applyBasePath: true },\n logoutUrl: { defaultPath: \"/api/auth/logout\", applyBasePath: true },\n loginInitUrl: { defaultPath: \"/api/auth/login\", applyBasePath: true },\n userUrl: { defaultPath: \"/api/auth/user\", applyBasePath: true },\n clearSessionUrl: {\n defaultPath: \"/api/auth/clearsession\",\n applyBasePath: true,\n },\n};\nconst URL_CONFIG: Record<string, UrlConfigEntry> = {\n ...systemUrlsConfig,\n logoutCallbackUrl: {\n defaultPath: \"\",\n applyBasePath: true,\n useBasePathOnly: true,\n },\n loginUrl: {\n defaultPath: \"\",\n applyBasePath: true,\n useBasePathOnly: true,\n checkEmpty: true,\n },\n loginSuccessUrl: {\n defaultPath: \"\",\n applyBasePath: true,\n useBasePathOnly: true,\n checkEmpty: true,\n },\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfigWithDefaults = {\n clientId: string;\n oauthServer: string;\n // Internal API routes\n callbackUrl: string; // where Civic's internal OAuth callback is hosted\n loginInitUrl: string; // Internal auth route for initiating login flow (e.g., /api/auth/login)\n logoutUrl: string;\n challengeUrl: string;\n refreshUrl: string;\n userUrl: string;\n clearSessionUrl: string;\n // User-facing routes\n loginSuccessUrl?: string; // where the user should be sent after the entire login completes, including the token exchange\n // The path the user will be sent to if they access a resource that needs\n // them to be logged in. If there is a dedicated login page, it can be set here.\n // Note: This is NOT for internal auth routes - see loginInitUrl for that.\n loginUrl: string;\n logoutCallbackUrl: string;\n include: string[];\n exclude: string[];\n cookies: CookiesConfigObject;\n basePath?: string;\n baseUrl?: string; // Public domain for apps behind reverse proxies (e.g., \"https://myapp.com\")\n autoRedirect: boolean;\n disableRefresh?: boolean; // Disable automatic token refresh\n targetContainerElement?: HTMLElement | string;\n /**\n * Controls how deep links (original URLs) are handled after authentication.\n * @see DeepLinkHandling\n * @default \"fullUrl\"\n */\n deepLinkHandling: DeepLinkHandling;\n};\n\n/**\n * All possible config values for Civic Auth\n */\nexport type OptionalAuthConfig = Partial<\n | AuthConfigWithDefaults\n | {\n cookies?: {\n tokens?: Partial<TokensCookieConfig>;\n user?: CookieConfig;\n };\n }\n> & {\n // Ensure TypeScript understands these properties are available\n // This doesn't change the public API, just helps TypeScript internally\n callbackUrl?: string; // where Civic's internal OAuth callback is hosted\n loginSuccessUrl?: string; // where the user should be sent after the entire login completes, including the token exchange\n loginUrl?: string;\n loginInitUrl?: string;\n logoutUrl?: string;\n logoutCallbackUrl?: string;\n challengeUrl?: string;\n refreshUrl?: string;\n userUrl?: string;\n clearSessionUrl?: string;\n include?: string[];\n exclude?: string[];\n basePath?: string;\n baseUrl?: string;\n oauthServer?: string;\n autoRedirect?: boolean;\n disableRefresh?: boolean;\n targetContainerElement?: HTMLElement | string;\n deepLinkHandling?: DeepLinkHandling;\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfig = OptionalAuthConfig & {\n clientId: string;\n exclude?: string[];\n};\n\n/**\n * Default configuration values that will be used if not overridden\n */\nexport const defaultAuthConfig: Omit<AuthConfigWithDefaults, \"clientId\"> = {\n oauthServer: DEFAULT_AUTH_SERVER,\n // Internal API routes\n // deconstruct systemUrls to set the keys and default values\n ...(Object.fromEntries(\n Object.entries(systemUrlsConfig).map(([key, value]) => [\n key,\n value.defaultPath,\n ]),\n ) as {\n [key in keyof typeof systemUrlsConfig]: string;\n }),\n // User-facing routes\n loginSuccessUrl: undefined, // By default, the user is sent to the redirect_url\n loginUrl: \"/\",\n logoutCallbackUrl: \"/\",\n include: [\"/**\"],\n exclude: [\"/api/auth/**\"],\n basePath: \"\",\n baseUrl: undefined, // No default - will use request.nextUrl.origin when undefined\n autoRedirect: true, // Default to current behavior\n cookies: createNextJSCookieConfig(),\n deepLinkHandling: \"queryParamsOnly\", // Default to preserving query params while respecting loginSuccessUrl\n};\n\n/**\n * Resolves the authentication configuration by combining:\n * 1. Default values\n * 2. Environment variables (set internally by the plugin)\n * 3. Explicitly passed configuration\n *\n * Config will be merged deeply, with arrays not merged, so that the\n * default include list (for example) [\"/*\"] will not be added\n *\n * Note: Developers should not set _civic_auth_* environment variables directly.\n * Instead, pass configuration to the createCivicAuthPlugin in next.config.js:\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * callbackUrl: '/custom/callback',\n * })\n * ```\n */\nexport const resolveAuthConfig = (\n config: Partial<AuthConfig> = {},\n): AuthConfigWithDefaults => {\n // Read configuration that was set by the plugin via environment variables\n // Don't load environment cookies if explicit cookies are provided\n const hasExplicitCookies = config.cookies;\n\n const configFromEnv = withoutUndefined({\n clientId: process.env._civic_auth_client_id,\n oauthServer: process.env._civic_oauth_server,\n callbackUrl: process.env._civic_auth_callback_url,\n loginSuccessUrl: process.env._civic_auth_login_success_url,\n challengeUrl: process.env._civic_auth_challenge_url,\n loginUrl: process.env._civic_auth_login_url,\n loginInitUrl: process.env._civic_auth_login_init_url,\n logoutUrl: process.env._civic_auth_logout_url,\n logoutCallbackUrl: process.env._civic_auth_logout_callback_url,\n refreshUrl: process.env._civic_auth_refresh_url,\n userUrl: process.env._civic_auth_user_url,\n clearSessionUrl: process.env._civic_auth_clear_session_url,\n include: process.env._civic_auth_includes?.split(\",\"),\n exclude: process.env._civic_auth_excludes?.split(\",\"),\n cookies: hasExplicitCookies\n ? undefined\n : process.env._civic_auth_cookie_config\n ? JSON.parse(process.env._civic_auth_cookie_config)\n : undefined,\n basePath: process.env._civic_auth_base_path || \"\",\n baseUrl: process.env._civic_auth_base_url,\n autoRedirect:\n process.env._civic_auth_auto_redirect === \"false\" ? false : undefined,\n disableRefresh:\n process.env._civic_auth_disable_refresh === \"true\" ? true : undefined,\n targetContainerElement: process.env._civic_auth_target_container_element,\n deepLinkHandling: ([\"fullUrl\", \"queryParamsOnly\", \"disabled\"].includes(\n process.env._civic_auth_deep_link_handling || \"\",\n )\n ? process.env._civic_auth_deep_link_handling\n : undefined) as DeepLinkHandling | undefined,\n }) as AuthConfig;\n\n // Ensure \"/api/auth/**\" is always excluded\n const finalExclude = new Set([\n ...defaultAuthConfig.exclude,\n ...(configFromEnv.exclude || []),\n ...(config.exclude ?? []),\n ]);\n\n // Store explicit cookies config before merge to preserve it\n const explicitCookies = config.cookies;\n\n // Perform a deep merge of the configurations\n const mergedConfig = merge.withOptions(\n { mergeArrays: false },\n defaultAuthConfig,\n configFromEnv,\n config,\n );\n\n // Override the exclude list with the ensured list\n mergedConfig.exclude = Array.from(finalExclude);\n\n // Update cookie configuration with basePath if it wasn't explicitly provided\n // Only auto-configure if no explicit cookies are provided anywhere\n if (!config.cookies && !configFromEnv.cookies && mergedConfig.basePath) {\n mergedConfig.cookies = createNextJSCookieConfig(mergedConfig.basePath);\n }\n\n // Merge explicit cookies with merged config to preserve both explicit settings and defaults\n if (explicitCookies && mergedConfig.cookies) {\n mergedConfig.cookies = merge.withOptions(\n { mergeArrays: false },\n mergedConfig.cookies,\n explicitCookies,\n );\n }\n\n // Security warnings for insecure cookie configurations\n const returnUrlCookieConfig =\n mergedConfig.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];\n if (returnUrlCookieConfig) {\n if (returnUrlCookieConfig.httpOnly === false) {\n logger.warn(\n \"SECURITY WARNING: RETURN_URL cookie httpOnly is disabled. This exposes the cookie to XSS attacks.\",\n );\n }\n if (returnUrlCookieConfig.secure === false) {\n logger.warn(\n \"SECURITY WARNING: RETURN_URL cookie secure is disabled. This allows cookie theft over HTTP.\",\n );\n }\n if (returnUrlCookieConfig.sameSite === \"none\") {\n logger.warn(\n \"SECURITY WARNING: RETURN_URL cookie sameSite is set to 'none'. This allows cross-site request access.\",\n );\n }\n }\n\n if (mergedConfig.clientId === undefined) {\n throw new Error(\"Civic Auth client ID is required\");\n }\n\n return mergedConfig as AuthConfigWithDefaults & { clientId: string };\n};\n\n/**\n * Applies basePath to URLs based on URL_CONFIG rules\n */\nfunction applyBasePathToUrls(\n authConfig: AuthConfig,\n basePath: string,\n): Partial<AuthConfig> {\n const defaultUrlsWithBasePath: Record<string, string> = {};\n\n if (!basePath) return defaultUrlsWithBasePath;\n\n Object.entries(URL_CONFIG).forEach(([key, config]) => {\n // Skip if explicitly set in authConfig\n const currentValue = authConfig[key as keyof AuthConfig];\n if (\n currentValue !== undefined &&\n !(config.checkEmpty && currentValue === \"\")\n ) {\n return;\n }\n\n // Apply basePath based on config rules\n const urlValue = config.useBasePathOnly\n ? basePath\n : `${basePath}${config.defaultPath}`;\n\n defaultUrlsWithBasePath[key] = urlValue;\n });\n\n return defaultUrlsWithBasePath as Partial<AuthConfig>;\n}\n\n/**\n * Creates a Next.js plugin that handles auth configuration.\n *\n * This is the main configuration point for the auth system.\n * Do not set _civic_auth_* environment variables directly - instead,\n * pass your configuration here.\n *\n * The only required field is clientId.\n *\n * Notes:\n * - If you provide explicit URLs, they will be used exactly as provided.\n * - Default URLs will automatically include the basePath from your Next.js config.\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * });\n * ```\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * callbackUrl: '/custom/callback',\n * loginUrl: '/custom/login',\n * logoutUrl: '/custom/logout',\n * logoutCallbackUrl: '/custom/logoutcallback',\n * include: ['/protected/*'],\n * exclude: ['/public/*']\n * })\n * ```\n *\n * The plugin sets internal environment variables that are used by\n * the auth system. These variables should not be set manually.\n */\nexport type NextJSPluginFn = (nextConfig?: NextConfig) => NextConfig;\n\nexport const createCivicAuthPlugin = (\n authConfig: AuthConfig,\n): NextJSPluginFn => {\n return (nextConfig?: NextConfig) => {\n logger.debug(\n \"createCivicAuthPlugin nextConfig\",\n JSON.stringify(nextConfig, null, 2),\n );\n\n // Extract basePath from Next.js config\n const basePath = sanitizeBasePath(nextConfig?.basePath || \"\");\n\n // Apply basePath to URLs using the configuration mapping\n const defaultUrlsWithBasePath = applyBasePathToUrls(authConfig, basePath);\n\n // Create final config with basePath and possibly modified URLs\n const resolvedConfig = resolveAuthConfig({\n ...defaultUrlsWithBasePath,\n ...authConfig,\n basePath,\n });\n\n return {\n ...nextConfig,\n env: {\n ...nextConfig?.env,\n // Internal environment variables - do not set these manually\n _civic_auth_client_id: resolvedConfig.clientId,\n _civic_oauth_server: resolvedConfig.oauthServer,\n _civic_auth_callback_url: resolvedConfig.callbackUrl,\n _civic_auth_login_success_url: resolvedConfig.loginSuccessUrl,\n _civic_auth_challenge_url: resolvedConfig.challengeUrl,\n _civic_auth_login_url: resolvedConfig.loginUrl,\n _civic_auth_login_init_url: resolvedConfig.loginInitUrl,\n _civic_auth_logout_url: resolvedConfig.logoutUrl,\n _civic_auth_logout_callback_url: resolvedConfig.logoutCallbackUrl,\n _civic_auth_refresh_url: resolvedConfig.refreshUrl,\n _civic_auth_user_url: resolvedConfig.userUrl,\n _civic_auth_clear_session_url: resolvedConfig.clearSessionUrl,\n _civic_auth_includes: resolvedConfig.include.join(\",\"),\n _civic_auth_excludes: resolvedConfig.exclude.join(\",\"),\n _civic_auth_cookie_config: JSON.stringify(resolvedConfig.cookies),\n _civic_auth_base_path: resolvedConfig.basePath,\n _civic_auth_base_url: resolvedConfig.baseUrl,\n _civic_auth_auto_redirect: resolvedConfig.autoRedirect.toString(),\n _civic_auth_disable_refresh: resolvedConfig.disableRefresh?.toString(),\n _civic_auth_deep_link_handling: resolvedConfig.deepLinkHandling,\n },\n };\n };\n};\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/nextjs/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,O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D,oBAAoB,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;gBACtD,yBAAyB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC;gBACjE,qBAAqB,EAAE,cAAc,CAAC,QAAQ;gBAC9C,oBAAoB,EAAE,cAAc,CAAC,OAAO;gBAC5C,yBAAyB,EAAE,cAAc,CAAC,YAAY,CAAC,QAAQ,EAAE;gBACjE,2BAA2B,EAAE,cAAc,CAAC,cAAc,EAAE,QAAQ,EAAE;gBACtE,8BAA8B,EAAE,cAAc,CAAC,gBAAgB;aAChE;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/* eslint-disable turbo/no-undeclared-env-vars */\nimport type { NextConfig } from \"next\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { withoutUndefined } from \"@/utils.js\";\nimport {\n AuthFlowCookie,\n type CookieConfig,\n type TokensCookieConfig,\n} from \"@/shared/lib/types.js\";\nimport { DEFAULT_AUTH_SERVER } from \"@/constants.js\";\nimport { merge } from \"ts-deepmerge\";\nimport { sanitizeBasePath } from \"./utils.js\";\nimport {\n createNextJSCookieConfig,\n type CookiesConfigObject,\n} from \"@/shared/lib/cookieConfig.js\";\nimport type { DeepLinkHandling } from \"@/server/config.js\";\n\n// Re-export the shared type for public API\nexport type { CookiesConfigObject };\n// Re-export DeepLinkHandling for backward compatibility\nexport type { DeepLinkHandling } from \"@/server/config.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\n/**\n * URL configuration mapping for applying basePath\n */\ntype UrlConfigEntry = {\n defaultPath: string;\n applyBasePath: boolean;\n useBasePathOnly?: boolean;\n checkEmpty?: boolean;\n};\n\nexport const systemUrlsConfig = {\n callbackUrl: { defaultPath: \"/api/auth/callback\", applyBasePath: true },\n challengeUrl: { defaultPath: \"/api/auth/challenge\", applyBasePath: true },\n refreshUrl: { defaultPath: \"/api/auth/refresh\", applyBasePath: true },\n logoutUrl: { defaultPath: \"/api/auth/logout\", applyBasePath: true },\n loginInitUrl: { defaultPath: \"/api/auth/login\", applyBasePath: true },\n userUrl: { defaultPath: \"/api/auth/user\", applyBasePath: true },\n clearSessionUrl: {\n defaultPath: \"/api/auth/clearsession\",\n applyBasePath: true,\n },\n};\nconst URL_CONFIG: Record<string, UrlConfigEntry> = {\n ...systemUrlsConfig,\n logoutCallbackUrl: {\n defaultPath: \"\",\n applyBasePath: true,\n useBasePathOnly: true,\n },\n loginUrl: {\n defaultPath: \"\",\n applyBasePath: true,\n useBasePathOnly: true,\n checkEmpty: true,\n },\n loginSuccessUrl: {\n defaultPath: \"\",\n applyBasePath: true,\n useBasePathOnly: true,\n checkEmpty: true,\n },\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfigWithDefaults = {\n clientId: string;\n oauthServer: string;\n // Internal API routes\n callbackUrl: string; // where Civic's internal OAuth callback is hosted\n loginInitUrl: string; // Internal auth route for initiating login flow (e.g., /api/auth/login)\n logoutUrl: string;\n challengeUrl: string;\n refreshUrl: string;\n userUrl: string;\n clearSessionUrl: string;\n // User-facing routes\n loginSuccessUrl?: string; // where the user should be sent after the entire login completes, including the token exchange\n // The path the user will be sent to if they access a resource that needs\n // them to be logged in. If there is a dedicated login page, it can be set here.\n // Note: This is NOT for internal auth routes - see loginInitUrl for that.\n loginUrl: string;\n logoutCallbackUrl: string;\n include: string[];\n exclude: string[];\n cookies: CookiesConfigObject;\n basePath?: string;\n baseUrl?: string; // Public domain for apps behind reverse proxies (e.g., \"https://myapp.com\")\n autoRedirect: boolean;\n disableRefresh?: boolean; // Disable automatic token refresh\n targetContainerElement?: HTMLElement | string;\n /**\n * Controls how deep links (original URLs) are handled after authentication.\n * @see DeepLinkHandling\n * @default \"fullUrl\"\n */\n deepLinkHandling: DeepLinkHandling;\n};\n\n/**\n * All possible config values for Civic Auth\n */\nexport type OptionalAuthConfig = Partial<\n | AuthConfigWithDefaults\n | {\n cookies?: {\n tokens?: Partial<TokensCookieConfig>;\n user?: CookieConfig;\n };\n }\n> & {\n // Ensure TypeScript understands these properties are available\n // This doesn't change the public API, just helps TypeScript internally\n callbackUrl?: string; // where Civic's internal OAuth callback is hosted\n loginSuccessUrl?: string; // where the user should be sent after the entire login completes, including the token exchange\n loginUrl?: string;\n loginInitUrl?: string;\n logoutUrl?: string;\n logoutCallbackUrl?: string;\n challengeUrl?: string;\n refreshUrl?: string;\n userUrl?: string;\n clearSessionUrl?: string;\n include?: string[];\n exclude?: string[];\n basePath?: string;\n baseUrl?: string;\n oauthServer?: string;\n autoRedirect?: boolean;\n disableRefresh?: boolean;\n targetContainerElement?: HTMLElement | string;\n deepLinkHandling?: DeepLinkHandling;\n};\n\n/**\n * Configuration values for Civic Auth.\n * Only clientId is required, all others are optional.\n */\nexport type AuthConfig = OptionalAuthConfig & {\n clientId: string;\n exclude?: string[];\n};\n\n/**\n * Default configuration values that will be used if not overridden\n */\nexport const defaultAuthConfig: Omit<AuthConfigWithDefaults, \"clientId\"> = {\n oauthServer: DEFAULT_AUTH_SERVER,\n // Internal API routes\n // deconstruct systemUrls to set the keys and default values\n ...(Object.fromEntries(\n Object.entries(systemUrlsConfig).map(([key, value]) => [\n key,\n value.defaultPath,\n ]),\n ) as {\n [key in keyof typeof systemUrlsConfig]: string;\n }),\n // User-facing routes\n loginSuccessUrl: undefined, // By default, the user is sent to the redirect_url\n loginUrl: \"/\",\n logoutCallbackUrl: \"/\",\n include: [\"/**\"],\n exclude: [\"/api/auth/**\"],\n basePath: \"\",\n baseUrl: undefined, // No default - will use request.nextUrl.origin when undefined\n autoRedirect: true, // Default to current behavior\n cookies: createNextJSCookieConfig(),\n deepLinkHandling: \"queryParamsOnly\", // Default to preserving query params while respecting loginSuccessUrl\n};\n\n/**\n * Resolves the authentication configuration by combining:\n * 1. Default values\n * 2. Environment variables (set internally by the plugin)\n * 3. Explicitly passed configuration\n *\n * Config will be merged deeply, with arrays not merged, so that the\n * default include list (for example) [\"/*\"] will not be added\n *\n * Note: Developers should not set _civic_auth_* environment variables directly.\n * Instead, pass configuration to the createCivicAuthPlugin in next.config.js:\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * callbackUrl: '/custom/callback',\n * })\n * ```\n */\nexport const resolveAuthConfig = (\n config: Partial<AuthConfig> = {},\n): AuthConfigWithDefaults => {\n // Read configuration that was set by the plugin via environment variables\n // Don't load environment cookies if explicit cookies are provided\n const hasExplicitCookies = config.cookies;\n\n const configFromEnv = withoutUndefined({\n clientId: process.env._civic_auth_client_id,\n oauthServer: process.env._civic_oauth_server,\n callbackUrl: process.env._civic_auth_callback_url,\n loginSuccessUrl: process.env._civic_auth_login_success_url,\n challengeUrl: process.env._civic_auth_challenge_url,\n loginUrl: process.env._civic_auth_login_url,\n loginInitUrl: process.env._civic_auth_login_init_url,\n logoutUrl: process.env._civic_auth_logout_url,\n logoutCallbackUrl: process.env._civic_auth_logout_callback_url,\n refreshUrl: process.env._civic_auth_refresh_url,\n userUrl: process.env._civic_auth_user_url,\n clearSessionUrl: process.env._civic_auth_clear_session_url,\n include: process.env._civic_auth_includes?.split(\",\"),\n exclude: process.env._civic_auth_excludes?.split(\",\"),\n cookies: hasExplicitCookies\n ? undefined\n : process.env._civic_auth_cookie_config\n ? JSON.parse(process.env._civic_auth_cookie_config)\n : undefined,\n basePath: process.env._civic_auth_base_path || \"\",\n baseUrl: process.env._civic_auth_base_url,\n autoRedirect:\n process.env._civic_auth_auto_redirect === \"false\" ? false : undefined,\n disableRefresh:\n process.env._civic_auth_disable_refresh === \"true\" ? true : undefined,\n targetContainerElement: process.env._civic_auth_target_container_element,\n deepLinkHandling: ([\"fullUrl\", \"queryParamsOnly\", \"disabled\"].includes(\n process.env._civic_auth_deep_link_handling || \"\",\n )\n ? process.env._civic_auth_deep_link_handling\n : undefined) as DeepLinkHandling | undefined,\n }) as AuthConfig;\n\n // Ensure \"/api/auth/**\" is always excluded\n const finalExclude = new Set([\n ...defaultAuthConfig.exclude,\n ...(configFromEnv.exclude || []),\n ...(config.exclude ?? []),\n ]);\n\n // Store explicit cookies config before merge to preserve it\n const explicitCookies = config.cookies;\n\n // Perform a deep merge of the configurations\n const mergedConfig = merge.withOptions(\n { mergeArrays: false },\n defaultAuthConfig,\n configFromEnv,\n config,\n );\n\n // Override the exclude list with the ensured list\n mergedConfig.exclude = Array.from(finalExclude);\n\n // Update cookie configuration with basePath if it wasn't explicitly provided\n // Only auto-configure if no explicit cookies are provided anywhere\n if (!config.cookies && !configFromEnv.cookies && mergedConfig.basePath) {\n mergedConfig.cookies = createNextJSCookieConfig(mergedConfig.basePath);\n }\n\n // Merge explicit cookies with merged config to preserve both explicit settings and defaults\n if (explicitCookies && mergedConfig.cookies) {\n mergedConfig.cookies = merge.withOptions(\n { mergeArrays: false },\n mergedConfig.cookies,\n explicitCookies,\n );\n }\n\n // Security warnings for insecure cookie configurations\n const returnUrlCookieConfig =\n mergedConfig.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];\n if (returnUrlCookieConfig) {\n if (returnUrlCookieConfig.httpOnly === false) {\n logger.warn(\n \"SECURITY WARNING: RETURN_URL cookie httpOnly is disabled. This exposes the cookie to XSS attacks.\",\n );\n }\n if (returnUrlCookieConfig.secure === false) {\n logger.warn(\n \"SECURITY WARNING: RETURN_URL cookie secure is disabled. This allows cookie theft over HTTP.\",\n );\n }\n if (returnUrlCookieConfig.sameSite === \"none\") {\n logger.warn(\n \"SECURITY WARNING: RETURN_URL cookie sameSite is set to 'none'. This allows cross-site request access.\",\n );\n }\n }\n\n if (mergedConfig.clientId === undefined) {\n throw new Error(\"Civic Auth client ID is required\");\n }\n\n return mergedConfig as AuthConfigWithDefaults & { clientId: string };\n};\n\n/**\n * Applies basePath to URLs based on URL_CONFIG rules\n */\nfunction applyBasePathToUrls(\n authConfig: AuthConfig,\n basePath: string,\n): Partial<AuthConfig> {\n const defaultUrlsWithBasePath: Record<string, string> = {};\n\n if (!basePath) return defaultUrlsWithBasePath;\n\n Object.entries(URL_CONFIG).forEach(([key, config]) => {\n // Skip if explicitly set in authConfig\n const currentValue = authConfig[key as keyof AuthConfig];\n if (\n currentValue !== undefined &&\n !(config.checkEmpty && currentValue === \"\")\n ) {\n return;\n }\n\n // Apply basePath based on config rules\n const urlValue = config.useBasePathOnly\n ? basePath\n : `${basePath}${config.defaultPath}`;\n\n defaultUrlsWithBasePath[key] = urlValue;\n });\n\n return defaultUrlsWithBasePath as Partial<AuthConfig>;\n}\n\n/**\n * Creates a Next.js plugin that handles auth configuration.\n *\n * This is the main configuration point for the auth system.\n * Do not set _civic_auth_* environment variables directly - instead,\n * pass your configuration here.\n *\n * The only required field is clientId.\n *\n * Notes:\n * - If you provide explicit URLs, they will be used exactly as provided.\n * - Default URLs will automatically include the basePath from your Next.js config.\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * });\n * ```\n *\n * @example\n * ```js\n * // next.config.js\n * export default createCivicAuthPlugin({\n * clientId: 'my-client-id',\n * callbackUrl: '/custom/callback',\n * loginUrl: '/custom/login',\n * logoutUrl: '/custom/logout',\n * logoutCallbackUrl: '/custom/logoutcallback',\n * include: ['/protected/*'],\n * exclude: ['/public/*']\n * })\n * ```\n *\n * The plugin sets internal environment variables that are used by\n * the auth system. These variables should not be set manually.\n */\nexport type NextJSPluginFn = (nextConfig?: NextConfig) => NextConfig;\n\nexport const createCivicAuthPlugin = (\n authConfig: AuthConfig,\n): NextJSPluginFn => {\n return (nextConfig?: NextConfig) => {\n logger.debug(\n \"createCivicAuthPlugin nextConfig\",\n JSON.stringify(nextConfig, null, 2),\n );\n\n // Extract basePath from Next.js config\n const basePath = sanitizeBasePath(nextConfig?.basePath || \"\");\n\n // Apply basePath to URLs using the configuration mapping\n const defaultUrlsWithBasePath = applyBasePathToUrls(authConfig, basePath);\n\n // Create final config with basePath and possibly modified URLs\n const resolvedConfig = resolveAuthConfig({\n ...defaultUrlsWithBasePath,\n ...authConfig,\n basePath,\n });\n\n return {\n ...nextConfig,\n env: {\n ...nextConfig?.env,\n // Internal environment variables - do not set these manually\n _civic_auth_client_id: resolvedConfig.clientId,\n _civic_oauth_server: resolvedConfig.oauthServer,\n _civic_auth_callback_url: resolvedConfig.callbackUrl,\n _civic_auth_login_success_url: resolvedConfig.loginSuccessUrl,\n _civic_auth_challenge_url: resolvedConfig.challengeUrl,\n _civic_auth_login_url: resolvedConfig.loginUrl,\n _civic_auth_login_init_url: resolvedConfig.loginInitUrl,\n _civic_auth_logout_url: resolvedConfig.logoutUrl,\n _civic_auth_logout_callback_url: resolvedConfig.logoutCallbackUrl,\n _civic_auth_refresh_url: resolvedConfig.refreshUrl,\n _civic_auth_user_url: resolvedConfig.userUrl,\n _civic_auth_clear_session_url: resolvedConfig.clearSessionUrl,\n _civic_auth_includes: resolvedConfig.include.join(\",\"),\n _civic_auth_excludes: resolvedConfig.exclude.join(\",\"),\n _civic_auth_cookie_config: JSON.stringify(resolvedConfig.cookies),\n _civic_auth_base_path: resolvedConfig.basePath,\n _civic_auth_base_url: resolvedConfig.baseUrl,\n _civic_auth_auto_redirect: resolvedConfig.autoRedirect.toString(),\n _civic_auth_disable_refresh: resolvedConfig.disableRefresh?.toString(),\n _civic_auth_deep_link_handling: resolvedConfig.deepLinkHandling,\n },\n };\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;AAS9C,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAA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AAuHF;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,gBACZ,kBAAkB,eACf,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,gBAExC,UAAU,KACrB,CAAC,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC,CA2BrD"}
@@ -2,9 +2,10 @@ import { NextResponse } from "next/server.js";
2
2
  import { resolveAuthConfig } from "../nextjs/config.js";
3
3
  import { loggers } from "../lib/logger.js";
4
4
  import { ServerAuthenticationResolver } from "../server/ServerAuthenticationResolver.js";
5
- import { shouldAttemptRefresh, shouldSkipAuthForSystemUrls, handleLoginUrl, shouldSkipAuthForRoutePatterns, handleUnauthenticatedUser, copyCivicCookies, } from "./utils.js";
5
+ import { shouldAttemptRefresh, shouldSkipAuthForSystemUrls, handleLoginUrl, shouldSkipAuthForRoutePatterns, handleUnauthenticatedUser, copyCivicCookies, getOriginUrl, removeBasePathFromPath, } from "./utils.js";
6
6
  import { NextjsMiddlewareCookieStorage } from "./utils.js";
7
7
  import { UserStorage } from "../shared/lib/types.js";
8
+ import { CivicAuth } from "../server/session.js";
8
9
  const logger = loggers.nextjs.middleware;
9
10
  /**
10
11
  * use a ServerAuthenticationResolver to validate the existing session
@@ -62,7 +63,9 @@ const applyAuth = async (authConfig, request) => {
62
63
  // Step 1: Understand the current authentication state
63
64
  const session = await validateAuthTokensIfPresent(authConfigWithDefaults, storage);
64
65
  const shouldSkipAuthForRoutePatternsCheck = shouldSkipAuthForRoutePatterns(request.nextUrl.pathname, authConfigWithDefaults);
65
- const pathNameIsLoginUrl = request.nextUrl.pathname === authConfigWithDefaults.loginUrl;
66
+ // Normalize loginUrl for comparison (remove basePath if present)
67
+ const loginPathWithoutBasePath = removeBasePathFromPath(authConfigWithDefaults.loginUrl, authConfigWithDefaults.basePath);
68
+ const pathNameIsLoginUrl = request.nextUrl.pathname === loginPathWithoutBasePath;
66
69
  logger.debug("Authentication state:", {
67
70
  authenticated: session.authenticated,
68
71
  pathName: request.nextUrl.pathname,
@@ -71,7 +74,19 @@ const applyAuth = async (authConfig, request) => {
71
74
  shouldSkipAuthForSystemUrls: shouldSkipAuthForSystemUrlsCheck,
72
75
  shouldSkipAuthForRoutePatterns: shouldSkipAuthForRoutePatternsCheck,
73
76
  });
74
- // Step 2: Attempt token refresh if needed (the OAuth pipeline approach) // Handle login URL with special logic
77
+ // Step 2: Handle deep link cookie for unauthenticated users using CivicAuth
78
+ // handleDeepLinking automatically detects if we're at loginUrl or a protected route
79
+ // and applies the appropriate logic for each case
80
+ if (!session.authenticated) {
81
+ const civicAuth = new CivicAuth(storage, {
82
+ ...authConfigWithDefaults,
83
+ redirectUrl: authConfigWithDefaults.callbackUrl,
84
+ });
85
+ const originUrl = getOriginUrl(request, authConfigWithDefaults);
86
+ const requestUrl = `${originUrl}${request.nextUrl.pathname}${request.nextUrl.search}${request.nextUrl.hash}`;
87
+ await civicAuth.handleDeepLinking(requestUrl, originUrl);
88
+ }
89
+ // Step 3: Handle login URL with special logic
75
90
  if (pathNameIsLoginUrl) {
76
91
  handleLoginUrl(request.nextUrl.pathname, session, authConfigWithDefaults);
77
92
  return response; // Always allow access to login URL
@@ -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,4BAA4B,EAAE,MAAM,0CAA0C,CAAC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AO,CACL,UAAsB,EAC6B,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} from \"./utils.js\";\nimport { NextjsMiddlewareCookieStorage } from \"./utils.js\";\nimport { UserStorage } from \"@/shared/lib/types.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 const pathNameIsLoginUrl =\n request.nextUrl.pathname === authConfigWithDefaults.loginUrl;\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 // Step 2: Attempt token refresh if needed (the OAuth pipeline approach) // 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 // Skip authentication for routes not matching include/exclude patterns\n if (shouldSkipAuthForRoutePatternsCheck) {\n return response;\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":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O,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 // 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 // Skip authentication for routes not matching include/exclude patterns\n if (shouldSkipAuthForRoutePatternsCheck) {\n return response;\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;AA4Y9C,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,iCAEF,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,EAAE,MAAM,oBAAoB,CAAC;AASrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAyT9C,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,iCAEF,WAAW,KAAG,OAAO,CAAC,YAAY,CAuCjD,CAAC"}