@civic/auth 0.12.0 → 0.13.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 +3 -0
- package/dist/nextjs/config.d.ts +19 -0
- package/dist/nextjs/config.d.ts.map +1 -1
- package/dist/nextjs/config.js +5 -0
- package/dist/nextjs/config.js.map +1 -1
- package/dist/nextjs/hooks/useInitialAuthConfig.d.ts.map +1 -1
- package/dist/nextjs/hooks/useInitialAuthConfig.js +5 -4
- package/dist/nextjs/hooks/useInitialAuthConfig.js.map +1 -1
- package/dist/nextjs/routeHandler.d.ts.map +1 -1
- package/dist/nextjs/routeHandler.js +57 -7
- package/dist/nextjs/routeHandler.js.map +1 -1
- package/dist/nextjs/utils.d.ts.map +1 -1
- package/dist/nextjs/utils.js +20 -2
- package/dist/nextjs/utils.js.map +1 -1
- package/dist/reactjs/core/GlobalAuthManager.d.ts.map +1 -1
- package/dist/reactjs/core/GlobalAuthManager.js +3 -1
- package/dist/reactjs/core/GlobalAuthManager.js.map +1 -1
- package/dist/server/session.d.ts.map +1 -1
- package/dist/server/session.js +21 -10
- package/dist/server/session.js.map +1 -1
- package/dist/shared/lib/cookieConfig.d.ts.map +1 -1
- package/dist/shared/lib/cookieConfig.js +6 -1
- package/dist/shared/lib/cookieConfig.js.map +1 -1
- package/dist/shared/lib/types.d.ts +10 -2
- package/dist/shared/lib/types.d.ts.map +1 -1
- package/dist/shared/lib/types.js +9 -0
- package/dist/shared/lib/types.js.map +1 -1
- package/dist/shared/lib/util.d.ts +19 -0
- package/dist/shared/lib/util.d.ts.map +1 -1
- package/dist/shared/lib/util.js +118 -0
- package/dist/shared/lib/util.js.map +1 -1
- package/dist/shared/version.d.ts +1 -1
- package/dist/shared/version.d.ts.map +1 -1
- package/dist/shared/version.js +1 -1
- package/dist/shared/version.js.map +1 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.js +3 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.js.map +1 -1
- package/dist/vanillajs/types/index.d.ts +4 -0
- package/dist/vanillajs/types/index.d.ts.map +1 -1
- package/dist/vanillajs/types/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
package/dist/nextjs/config.d.ts
CHANGED
|
@@ -2,6 +2,17 @@ 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
4
|
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";
|
|
5
16
|
export declare const systemUrlsConfig: {
|
|
6
17
|
callbackUrl: {
|
|
7
18
|
defaultPath: string;
|
|
@@ -57,6 +68,12 @@ export type AuthConfigWithDefaults = {
|
|
|
57
68
|
autoRedirect: boolean;
|
|
58
69
|
disableRefresh?: boolean;
|
|
59
70
|
targetContainerElement?: HTMLElement | string;
|
|
71
|
+
/**
|
|
72
|
+
* Controls how deep links (original URLs) are handled after authentication.
|
|
73
|
+
* @see DeepLinkHandling
|
|
74
|
+
* @default "fullUrl"
|
|
75
|
+
*/
|
|
76
|
+
deepLinkHandling: DeepLinkHandling;
|
|
60
77
|
};
|
|
61
78
|
/**
|
|
62
79
|
* All possible config values for Civic Auth
|
|
@@ -85,6 +102,7 @@ export type OptionalAuthConfig = Partial<AuthConfigWithDefaults | {
|
|
|
85
102
|
autoRedirect?: boolean;
|
|
86
103
|
disableRefresh?: boolean;
|
|
87
104
|
targetContainerElement?: HTMLElement | string;
|
|
105
|
+
deepLinkHandling?: DeepLinkHandling;
|
|
88
106
|
};
|
|
89
107
|
/**
|
|
90
108
|
* Configuration values for Civic Auth.
|
|
@@ -178,6 +196,7 @@ export declare const createCivicAuthPlugin: (authConfig: AuthConfig) => (nextCon
|
|
|
178
196
|
_civic_auth_base_url: string | undefined;
|
|
179
197
|
_civic_auth_auto_redirect: string;
|
|
180
198
|
_civic_auth_disable_refresh: string | undefined;
|
|
199
|
+
_civic_auth_deep_link_handling: DeepLinkHandling;
|
|
181
200
|
};
|
|
182
201
|
allowedDevOrigins?: string[];
|
|
183
202
|
exportPathMap?: (defaultMap: import("next/dist/server/config-shared.js").ExportPathMap, ctx: {
|
|
@@ -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,EACL,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;
|
|
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,EACL,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,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+H,CAAC;;;;;;;;;;;;;;;;;;iBAA8pE,CAAC;;;;;;;6BAAg6C,CAAC;sBAAoC,CAAC;;aAAoC,CAAC;;6BAA0D,CAAC;oBAA8B,CAAC;0BAAkE,CAAC;;qBAA2C,CAAC;mBAAiC,CAAC;;wBAA+C,CAAC;eAAmD,CAAC;iBAA4C,CAAC;2BAAyC,CAAC;;;;;;;;;yBAA4zC,CAAC;6BAAwC,CAAC;;;eAAkD,CAAC;mBAAuB,CAAC;;;;CAD35Z,CAAC"}
|
package/dist/nextjs/config.js
CHANGED
|
@@ -53,6 +53,7 @@ export const defaultAuthConfig = {
|
|
|
53
53
|
baseUrl: undefined, // No default - will use request.nextUrl.origin when undefined
|
|
54
54
|
autoRedirect: true, // Default to current behavior
|
|
55
55
|
cookies: createNextJSCookieConfig(),
|
|
56
|
+
deepLinkHandling: "fullUrl", // Default to full deep link preservation
|
|
56
57
|
};
|
|
57
58
|
/**
|
|
58
59
|
* Resolves the authentication configuration by combining:
|
|
@@ -103,6 +104,9 @@ export const resolveAuthConfig = (config = {}) => {
|
|
|
103
104
|
autoRedirect: process.env._civic_auth_auto_redirect === "false" ? false : undefined,
|
|
104
105
|
disableRefresh: process.env._civic_auth_disable_refresh === "true" ? true : undefined,
|
|
105
106
|
targetContainerElement: process.env._civic_auth_target_container_element,
|
|
107
|
+
deepLinkHandling: (["fullUrl", "queryParamsOnly", "disabled"].includes(process.env._civic_auth_deep_link_handling || "")
|
|
108
|
+
? process.env._civic_auth_deep_link_handling
|
|
109
|
+
: undefined),
|
|
106
110
|
});
|
|
107
111
|
// Ensure "/api/auth/**" is always excluded
|
|
108
112
|
const finalExclude = new Set([
|
|
@@ -227,6 +231,7 @@ export const createCivicAuthPlugin = (authConfig) => {
|
|
|
227
231
|
_civic_auth_base_url: resolvedConfig.baseUrl,
|
|
228
232
|
_civic_auth_auto_redirect: resolvedConfig.autoRedirect.toString(),
|
|
229
233
|
_civic_auth_disable_refresh: resolvedConfig.disableRefresh?.toString(),
|
|
234
|
+
_civic_auth_deep_link_handling: resolvedConfig.deepLinkHandling,
|
|
230
235
|
},
|
|
231
236
|
};
|
|
232
237
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/nextjs/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAGN,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACL,wBAAwB,GAEzB,MAAM,8BAA8B,CAAC;AAKtC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AAY5C,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,WAAW,EAAE,EAAE,WAAW,EAAE,oBAAoB,EAAE,aAAa,EAAE,IAAI,EAAE;IACvE,YAAY,EAAE,EAAE,WAAW,EAAE,qBAAqB,EAAE,aAAa,EAAE,IAAI,EAAE;IACzE,UAAU,EAAE,EAAE,WAAW,EAAE,mBAAmB,EAAE,aAAa,EAAE,IAAI,EAAE;IACrE,SAAS,EAAE,EAAE,WAAW,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAE;IACnE,YAAY,EAAE,EAAE,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,IAAI,EAAE;IACrE,OAAO,EAAE,EAAE,WAAW,EAAE,gBAAgB,EAAE,aAAa,EAAE,IAAI,EAAE;IAC/D,eAAe,EAAE;QACf,WAAW,EAAE,wBAAwB;QACrC,aAAa,EAAE,IAAI;KACpB;CACF,CAAC;AACF,MAAM,UAAU,GAAmC;IACjD,GAAG,gBAA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;YACb,GAAG,EAAE;gBACH,GAAG,UAAU,EAAE,GAAG;gBAClB,6DAA6D;gBAC7D,qBAAqB,EAAE,cAAc,CAAC,QAAQ;gBAC9C,mBAAmB,EAAE,cAAc,CAAC,WAAW;gBAC/C,wBAAwB,EAAE,cAAc,CAAC,WAAW;gBACpD,6BAA6B,EAAE,cAAc,CAAC,eAAe;gBAC7D,yBAAyB,EAAE,cAAc,CAAC,YAAY;gBACtD,qBAAqB,EAAE,cAAc,CAAC,QAAQ;gBAC9C,0BAA0B,EAAE,cAAc,CAAC,YAAY;gBACvD,sBAAsB,EAAE,cAAc,CAAC,SAAS;gBAChD,+BAA+B,EAAE,cAAc,CAAC,iBAAiB;gBACjE,uBAAuB,EAAE,cAAc,CAAC,UAAU;gBAClD,oBAAoB,EAAE,cAAc,CAAC,OAAO;gBAC5C,6BAA6B,EAAE,cAAc,CAAC,eAAe;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;aACvE;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 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 * 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};\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\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};\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};\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 }) 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 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 const createCivicAuthPlugin = (authConfig: AuthConfig) => {\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 },\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,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAGN,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACL,wBAAwB,GAEzB,MAAM,8BAA8B,CAAC;AAKtC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AAwB5C,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,WAAW,EAAE,EAAE,WAAW,EAAE,oBAAoB,EAAE,aAAa,EAAE,IAAI,EAAE;IACvE,YAAY,EAAE,EAAE,WAAW,EAAE,qBAAqB,EAAE,aAAa,EAAE,IAAI,EAAE;IACzE,UAAU,EAAE,EAAE,WAAW,EAAE,mBAAmB,EAAE,aAAa,EAAE,IAAI,EAAE;IACrE,SAAS,EAAE,EAAE,WAAW,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAE;IACnE,YAAY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AAyB,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 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};\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: \"fullUrl\", // Default to full deep link preservation\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 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 const createCivicAuthPlugin = (authConfig: AuthConfig) => {\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":"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,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,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,EAAE,MAAM,CAAC;IAC3B,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB,aACtB,2BAA2B,KACnC;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;CAkKvB,CAAC"}
|
|
@@ -81,7 +81,7 @@ export const useInitialAuthConfig = (options = {}) => {
|
|
|
81
81
|
}, 100);
|
|
82
82
|
});
|
|
83
83
|
},
|
|
84
|
-
onSignIn: async ({ error }) => {
|
|
84
|
+
onSignIn: async ({ error, redirectUrl }) => {
|
|
85
85
|
if (error) {
|
|
86
86
|
loggers.nextjs.hooks.error("onSignIn: Error signing in", error);
|
|
87
87
|
return;
|
|
@@ -90,9 +90,10 @@ export const useInitialAuthConfig = (options = {}) => {
|
|
|
90
90
|
try {
|
|
91
91
|
// Trigger server-side revalidation to force NextAuthProvider to re-run
|
|
92
92
|
await revalidateUserData(pathname);
|
|
93
|
-
// Navigate if
|
|
94
|
-
|
|
95
|
-
|
|
93
|
+
// Navigate to the deep link (redirectUrl) if available, otherwise fall back to loginSuccessUrl
|
|
94
|
+
const targetUrl = redirectUrl || loginSuccessUrl;
|
|
95
|
+
if (targetUrl && targetUrl !== pathname) {
|
|
96
|
+
router.push(targetUrl);
|
|
96
97
|
}
|
|
97
98
|
}
|
|
98
99
|
catch (revalidateError) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useInitialAuthConfig.js","sourceRoot":"","sources":["../../../src/nextjs/hooks/useInitialAuthConf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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 }) => {\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 if needed\n if (loginSuccessUrl && loginSuccessUrl !== pathname) {\n router.push(loginSuccessUrl);\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,CAA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;QACjB,eAAe;QACf,sBAAsB;QACtB,OAAO;QACP,UAAU;QACV,SAAS;QACT,eAAe;QACf,QAAQ;QACR,YAAY;QACZ,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IAEH,MAAM,yBAAyB,GAAG,OAAO,CAAC,GAAG,EAAE;QAC7C,OAAO,CACL,YAA2C,EAAE,EAC3B,EAAE;YACpB,OAAO;gBACL,GAAG,UAAU;gBACb,6DAA6D;gBAC7D,GAAG,CAAC,SAAS,CAAC,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\";\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 +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;
|
|
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;AA0U9C,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"}
|
|
@@ -4,7 +4,7 @@ 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 { CodeVerifier, UserStorage } from "../shared/lib/types.js";
|
|
7
|
+
import { AuthFlowCookie, CodeVerifier, 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";
|
|
@@ -131,7 +131,7 @@ async function handleCallback(request, config) {
|
|
|
131
131
|
if (!code || !state)
|
|
132
132
|
throw new AuthError("Bad parameters", 400);
|
|
133
133
|
try {
|
|
134
|
-
const { civicAuth, appUrl, urlDetectionRequest } = createCivicAuth(request, resolvedConfigs);
|
|
134
|
+
const { civicAuth, appUrl, urlDetectionRequest, cookieStorage } = createCivicAuth(request, resolvedConfigs);
|
|
135
135
|
// Convert NextRequest to the format expected by handleCallback
|
|
136
136
|
const handleCallbackRequest = {
|
|
137
137
|
headers: Object.fromEntries(request.headers.entries()),
|
|
@@ -139,7 +139,45 @@ async function handleCallback(request, config) {
|
|
|
139
139
|
};
|
|
140
140
|
// Get loginSuccessUrl with proper baseUrl handling
|
|
141
141
|
const loginSuccessUrl = CivicAuth.getLoginSuccessUrl(urlDetectionRequest, appUrl);
|
|
142
|
-
const
|
|
142
|
+
const defaultFrontendUrl = loginSuccessUrl || resolvedConfigs.loginSuccessUrl || "/";
|
|
143
|
+
// Check for preserved deep link (returnUrl cookie)
|
|
144
|
+
const returnUrl = await cookieStorage.get(AuthFlowCookie.RETURN_URL);
|
|
145
|
+
// Delete the cookie immediately after reading (single-use)
|
|
146
|
+
if (returnUrl) {
|
|
147
|
+
await cookieStorage.delete(AuthFlowCookie.RETURN_URL);
|
|
148
|
+
logger.debug("[CALLBACK_HANDLER] Found returnUrl cookie", { returnUrl });
|
|
149
|
+
}
|
|
150
|
+
// Determine final redirect URL based on deepLinkHandling config
|
|
151
|
+
let frontendUrl;
|
|
152
|
+
if (returnUrl && resolvedConfigs.deepLinkHandling === "queryParamsOnly") {
|
|
153
|
+
// queryParamsOnly: Use loginSuccessUrl but merge query params from returnUrl
|
|
154
|
+
try {
|
|
155
|
+
const returnUrlObj = new URL(returnUrl, appUrl);
|
|
156
|
+
const baseUrlObj = new URL(defaultFrontendUrl, appUrl);
|
|
157
|
+
// Append query params from returnUrl to the base loginSuccessUrl
|
|
158
|
+
returnUrlObj.searchParams.forEach((value, key) => {
|
|
159
|
+
baseUrlObj.searchParams.set(key, value);
|
|
160
|
+
});
|
|
161
|
+
frontendUrl = baseUrlObj.pathname + baseUrlObj.search + baseUrlObj.hash;
|
|
162
|
+
logger.debug("[CALLBACK_HANDLER] deepLinkHandling=queryParamsOnly: merged returnUrl params", { frontendUrl });
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
// If URL parsing fails, fall back to default
|
|
166
|
+
logger.warn("[CALLBACK_HANDLER] Failed to merge query params from returnUrl", { error, returnUrl, defaultFrontendUrl });
|
|
167
|
+
frontendUrl = defaultFrontendUrl;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else if (returnUrl && resolvedConfigs.deepLinkHandling === "fullUrl") {
|
|
171
|
+
// fullUrl: Use the preserved deep link directly
|
|
172
|
+
frontendUrl = returnUrl;
|
|
173
|
+
logger.debug("[CALLBACK_HANDLER] deepLinkHandling=fullUrl: using preserved deep link", {
|
|
174
|
+
frontendUrl,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
// No returnUrl cookie or deepLinkHandling is "disabled" - use default loginSuccessUrl
|
|
179
|
+
frontendUrl = defaultFrontendUrl;
|
|
180
|
+
}
|
|
143
181
|
// Use CivicAuth's smart callback handler
|
|
144
182
|
const result = await civicAuth.handleCallback({
|
|
145
183
|
code,
|
|
@@ -155,12 +193,24 @@ async function handleCallback(request, config) {
|
|
|
155
193
|
if (result.content) {
|
|
156
194
|
// Handle both string content and object content
|
|
157
195
|
if (typeof result.content === "string") {
|
|
158
|
-
|
|
196
|
+
const response = new NextResponse(result.content, {
|
|
159
197
|
status: 200,
|
|
160
|
-
headers: {
|
|
161
|
-
"Content-Type": "text/html",
|
|
162
|
-
},
|
|
198
|
+
headers: { "Content-Type": "text/html" },
|
|
163
199
|
});
|
|
200
|
+
// If we had a returnUrl cookie, delete it using NextResponse's cookie API.
|
|
201
|
+
// This ensures consistent cookie attributes from the resolved config.
|
|
202
|
+
if (returnUrl) {
|
|
203
|
+
const cookieConfig = resolvedConfigs.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];
|
|
204
|
+
response.cookies.set(AuthFlowCookie.RETURN_URL, "", {
|
|
205
|
+
path: cookieConfig?.path ?? resolvedConfigs.basePath ?? "/",
|
|
206
|
+
httpOnly: cookieConfig?.httpOnly ?? true,
|
|
207
|
+
secure: cookieConfig?.secure ?? true,
|
|
208
|
+
sameSite: cookieConfig?.sameSite ?? "strict",
|
|
209
|
+
maxAge: 0, // Immediately expire the cookie
|
|
210
|
+
});
|
|
211
|
+
logger.debug("[CALLBACK_HANDLER] Clearing returnUrl cookie via NextResponse");
|
|
212
|
+
}
|
|
213
|
+
return response;
|
|
164
214
|
}
|
|
165
215
|
else {
|
|
166
216
|
// Object content (JSON response)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AC3D,OAAO,YAAY,CAAC,IAAI,CACtB,EAAE,KAAK,EAAE,uBAAuB,EAAE,EAClC,EAAE,MAAM,EAAE,GAAG,EAAE,CAChB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { CivicAuth, type UrlDetectionRequest } from \"@civic/auth/server\";\nimport { LOGOUT_SUCCESS_TEXT } from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { displayModeFromState } from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport { CodeVerifier, UserStorage } from \"@/shared/lib/types.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { prependBasePath, redirectWithBasePath } from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Helper to convert NextRequest to UrlDetectionRequest for framework-agnostic URL handling\n */\nconst toUrlDetectionRequest = (request: NextRequest): UrlDetectionRequest => ({\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n searchParams: {\n get: (name: string) => request.nextUrl.searchParams.get(name),\n },\n cookies: {\n get: (name: string) => request.cookies.get(name),\n },\n});\n\n/**\n * Helper to create CivicAuth instance for a request\n * Now handles appUrl detection for proxy environments\n */\nconst createCivicAuth = (request: NextRequest, config: AuthConfig) => {\n const resolvedConfig = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage({\n ...resolvedConfig.cookies?.tokens,\n [UserStorage.USER]: resolvedConfig.cookies?.user,\n });\n\n // Convert to framework-agnostic request format\n const urlDetectionRequest = toUrlDetectionRequest(request);\n\n // Get appUrl from client (for proxy environments)\n const clientAppUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Use baseUrl from config, then client appUrl, then request origin\n // This matches the main branch priority: config > client > request\n const appUrl =\n resolvedConfig.baseUrl ||\n clientAppUrl ||\n new URL(urlDetectionRequest.url).origin;\n\n // Build absolute URLs using detected appUrl or request origin\n const absoluteCallbackUrl = resolvedConfig.callbackUrl.startsWith(\"http\")\n ? resolvedConfig.callbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.callbackUrl,\n appUrl,\n );\n const absoluteLogoutCallbackUrl = resolvedConfig.logoutCallbackUrl.startsWith(\n \"http\",\n )\n ? resolvedConfig.logoutCallbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.logoutCallbackUrl,\n appUrl,\n );\n\n const civicAuth = new CivicAuth(cookieStorage, {\n disableRefresh: resolvedConfig.disableRefresh,\n clientId: resolvedConfig.clientId,\n redirectUrl: absoluteCallbackUrl,\n oauthServer: resolvedConfig.oauthServer,\n postLogoutRedirectUrl: absoluteLogoutCallbackUrl,\n loginSuccessUrl: request.url,\n });\n\n return {\n civicAuth,\n cookieStorage,\n appUrl, // Return appUrl for use in other functions\n urlDetectionRequest, // Return for use in handlers\n };\n};\n\n/**\n * Login handler - backend OAuth login initiation endpoint\n * Uses CivicAuth.buildLoginUrl()\n */\nasync function handleLogin(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n const frontendState = request.nextUrl.searchParams.get(\"state\");\n\n // Store appUrl in cookie if provided as query parameter\n const appUrlFromQuery = request.nextUrl.searchParams.get(\"appUrl\");\n if (appUrlFromQuery) {\n const cookieStorage = new NextjsCookieStorage(\n resolvedConfigs.cookies?.tokens ?? {},\n );\n await cookieStorage.set(CodeVerifier.APP_URL, appUrlFromQuery);\n }\n\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const url = await civicAuth.buildLoginUrl({\n state: frontendState || undefined,\n });\n\n logger.info(\"[LOGIN_HANDLER] Redirecting to OAuth login URL\", {\n loginUrl: url.toString(),\n });\n\n return NextResponse.redirect(url.toString());\n } catch (error) {\n logger.error(\"[LOGIN_HANDLER] Backend login error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=login_failed\",\n appUrl,\n ),\n );\n }\n}\n\nasync function handleRefresh(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n await civicAuth.refreshTokens();\n\n logger.info(\"[REFRESH_HANDLER] Tokens refreshed successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Tokens refreshed\",\n });\n } catch (error) {\n logger.error(\"[REFRESH_HANDLER] Token refresh error:\", error);\n return NextResponse.json(\n { error: \"Token refresh failed\" },\n { status: 500 },\n );\n }\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n const error = request.nextUrl.searchParams.get(\"error\");\n\n if (error) {\n logger.error(\"OAuth error in callback:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=oauth_error\",\n appUrl,\n ),\n );\n }\n\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n try {\n const { civicAuth, appUrl, urlDetectionRequest } = createCivicAuth(\n request,\n resolvedConfigs,\n );\n\n // Convert NextRequest to the format expected by handleCallback\n const handleCallbackRequest = {\n headers: Object.fromEntries(request.headers.entries()),\n url: request.url.toString(),\n };\n\n // Get loginSuccessUrl with proper baseUrl handling\n const loginSuccessUrl = CivicAuth.getLoginSuccessUrl(\n urlDetectionRequest,\n appUrl,\n );\n const frontendUrl =\n loginSuccessUrl || resolvedConfigs.loginSuccessUrl || \"/\";\n\n // Use CivicAuth's smart callback handler\n const result = await civicAuth.handleCallback(\n {\n code,\n state,\n req: handleCallbackRequest,\n },\n {\n // Pass the properly resolved frontendUrl\n frontendUrl: prependBasePath(frontendUrl, config.basePath || \"\"),\n },\n );\n if (result.redirectTo) {\n return redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, result.redirectTo, appUrl),\n );\n }\n\n if (result.content) {\n // Handle both string content and object content\n if (typeof result.content === \"string\") {\n return new NextResponse(result.content, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/html\",\n },\n });\n } else {\n // Object content (JSON response)\n return NextResponse.json(result.content);\n }\n }\n\n // Fallback redirect\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, \"/\", appUrl),\n );\n } catch (error) {\n logger.error(\"[CALLBACK_HANDLER] OAuth callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=callback_failed\",\n appUrl,\n ),\n );\n }\n}\n\nconst revalidateUrlPath = async (url: string) => {\n try {\n const path = new URL(url).pathname;\n revalidatePath(path);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n};\n\nexport async function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n // Get framework-agnostic request for URL utilities\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Read the state from the query parameters\n const state = request.nextUrl.searchParams.get(\"state\");\n const clientLogoutRedirectUrl =\n request.nextUrl.searchParams.get(\"logoutRedirectUrl\");\n\n try {\n logger.info(\"[LOGOUT_HANDLER] Backend logout endpoint called\");\n\n // If client provided a logoutRedirectUrl, override the config\n let configToUse = resolvedConfigs;\n if (clientLogoutRedirectUrl) {\n configToUse = {\n ...resolvedConfigs,\n logoutCallbackUrl: clientLogoutRedirectUrl,\n };\n logger.info(\"[LOGOUT_HANDLER] Overriding logout callback URL\", {\n original: resolvedConfigs.logoutCallbackUrl,\n override: clientLogoutRedirectUrl,\n });\n }\n\n const { civicAuth } = createCivicAuth(request, configToUse);\n\n // Always redirect to OAuth logout (like main branch)\n // Don't validate session - even invalid local sessions should hit OAuth logout\n logger.info(\"[LOGOUT_HANDLER] Processing logout request\", {\n state: !!state,\n });\n\n // Always redirect to OAuth logout endpoint (like main branch)\n // Client-side iframe logic will handle completion and redirect appropriately\n const logoutUrl = await civicAuth.buildLogoutRedirectUrl({\n state: state || undefined,\n });\n\n try {\n await clearAuthCookies(resolvedConfigs);\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Error clearing tokens:\", error);\n }\n\n // Remove state parameter from logout URL to prevent it from appearing in frontend URL\n const cleanLogoutUrl = new URL(logoutUrl);\n cleanLogoutUrl.searchParams.delete(\"state\");\n\n logger.info(\"[LOGOUT_HANDLER] Redirecting to OAuth logout endpoint\", {\n logoutUrl: cleanLogoutUrl.toString(),\n });\n\n return NextResponse.redirect(cleanLogoutUrl.toString());\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Logout error:\", error);\n // If logout URL generation fails, clear tokens and redirect to home\n await clearAuthCookies(resolvedConfigs);\n\n const fallbackUrl =\n clientLogoutRedirectUrl || resolvedConfigs.logoutCallbackUrl;\n const finalFallbackUrl = CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n fallbackUrl,\n appUrl,\n );\n\n return NextResponse.redirect(finalFallbackUrl);\n }\n}\n\n/**\n * Clear session handler - clears all auth cookies server-side.\n * Called by client in parallel with logout iframe to quickly clear HttpOnly cookies.\n *\n * This is part of a parallel logout strategy:\n * - Client calls clearsession (this endpoint) AND loads logout iframe simultaneously\n * - Both requests are sent while cookies are still present\n * - clearsession clears HttpOnly cookies quickly (this endpoint)\n * - logout iframe handles OAuth provider logout (slower, but had cookies when initiated)\n *\n * This ensures cookies are cleared fast (preventing race conditions if user refreshes)\n * while still performing OAuth provider logout.\n */\nasync function handleClearSession(\n _request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\"[CLEARSESSION_HANDLER] Clearing session cookies\");\n\n // Clear all auth cookies immediately\n await clearAuthCookies(resolvedConfigs);\n\n logger.info(\"[CLEARSESSION_HANDLER] Session cleared successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Session cleared\",\n });\n } catch (error) {\n logger.error(\"[CLEARSESSION_HANDLER] Error clearing session:\", error);\n return NextResponse.json(\n { error: \"Failed to clear session\" },\n { status: 500 },\n );\n }\n}\n\nexport async function handleLogoutCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Backend logout callback endpoint called\",\n );\n\n // Clear authentication cookies\n await clearAuthCookies(resolvedConfigs);\n\n // Get framework-agnostic request and create CivicAuth instance\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n // Get the state parameter for iframe detection\n const state = request.nextUrl.searchParams.get(\"state\");\n\n // If this is an iframe request, return HTML with logout success signal\n if (state && displayModeFromState(state, \"iframe\") === \"iframe\") {\n // For iframe mode, include the post-logout redirect URL in the HTML\n const postLogoutRedirectUrl =\n civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n const response = new NextResponse(\n `<html lang=\"en\"><span style=\"display:none\">${LOGOUT_SUCCESS_TEXT}<a href=\"${postLogoutRedirectUrl}\" rel=\"civic-auth-post-logout-redirect-url\"></a></span></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Returning iframe logout success HTML\",\n { postLogoutRedirectUrl },\n );\n return response;\n }\n\n // For non-iframe requests, redirect to the logout callback URL or post-logout URL\n const redirectUrl = civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Redirecting to logout callback URL\",\n {\n logoutCallbackUrl: resolvedConfigs.logoutCallbackUrl,\n redirectUrl,\n },\n );\n\n // Revalidate the redirect path to update authentication state in server components\n await revalidateUrlPath(redirectUrl);\n return redirectWithBasePath(config, redirectUrl);\n } catch (error) {\n logger.error(\"[LOGOUT_CALLBACK_HANDLER] Logout callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfigs.logoutCallbackUrl,\n appUrl,\n ),\n );\n }\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * export const POST = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n logger.debug(\"routeHandler: Auth route handler called\", config);\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n case \"login\":\n return await handleLogin(request, config);\n case \"callback\":\n return await handleCallback(request, config);\n case \"refresh\":\n return await handleRefresh(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n case \"clearsession\":\n return await handleClearSession(request, config);\n case \"logoutcallback\":\n return await handleLogoutCallback(request, config);\n case \"user\":\n return await handleUser(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n await clearAuthCookies(config);\n return response;\n }\n };\n\n/**\n * User endpoint - returns current user data as JSON\n * Uses CivicAuth.isLoggedIn() and getUser()\n */\nasync function handleUser(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n logger.debug(\n \"routeHandler: [USER_HANDLER] User endpoint called\",\n resolvedConfigs,\n );\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const isLoggedIn = await civicAuth.isLoggedIn();\n\n if (!isLoggedIn) {\n const statusCode = request.nextUrl.searchParams.get(\n \"optimisticRehydration\",\n )\n ? 202\n : 401;\n return NextResponse.json(\n { error: \"Not authenticated\" },\n { status: statusCode },\n );\n }\n\n const user = await civicAuth.getUser();\n\n return NextResponse.json({ user });\n } catch (error) {\n logger.error(\"[USER_HANDLER] User endpoint error:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"routeHandler.js","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA4B,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AA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AuB,CACxB;gBACC,CAAC,CAAC,GAAG;gBACL,CAAC,CAAC,GAAG,CAAC;YACR,OAAO,YAAY,CAAC,IAAI,CACtB,EAAE,KAAK,EAAE,mBAAmB,EAAE,EAC9B,EAAE,MAAM,EAAE,UAAU,EAAE,CACvB,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,OAAO,EAAE,CAAC;QAEvC,OAAO,YAAY,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC3D,OAAO,YAAY,CAAC,IAAI,CACtB,EAAE,KAAK,EAAE,uBAAuB,EAAE,EAClC,EAAE,MAAM,EAAE,GAAG,EAAE,CAChB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { CivicAuth, type UrlDetectionRequest } from \"@civic/auth/server\";\nimport { LOGOUT_SUCCESS_TEXT } from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { displayModeFromState } from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport {\n AuthFlowCookie,\n CodeVerifier,\n UserStorage,\n} from \"@/shared/lib/types.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { prependBasePath, redirectWithBasePath } from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Helper to convert NextRequest to UrlDetectionRequest for framework-agnostic URL handling\n */\nconst toUrlDetectionRequest = (request: NextRequest): UrlDetectionRequest => ({\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n searchParams: {\n get: (name: string) => request.nextUrl.searchParams.get(name),\n },\n cookies: {\n get: (name: string) => request.cookies.get(name),\n },\n});\n\n/**\n * Helper to create CivicAuth instance for a request\n * Now handles appUrl detection for proxy environments\n */\nconst createCivicAuth = (request: NextRequest, config: AuthConfig) => {\n const resolvedConfig = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage({\n ...resolvedConfig.cookies?.tokens,\n [UserStorage.USER]: resolvedConfig.cookies?.user,\n });\n\n // Convert to framework-agnostic request format\n const urlDetectionRequest = toUrlDetectionRequest(request);\n\n // Get appUrl from client (for proxy environments)\n const clientAppUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Use baseUrl from config, then client appUrl, then request origin\n // This matches the main branch priority: config > client > request\n const appUrl =\n resolvedConfig.baseUrl ||\n clientAppUrl ||\n new URL(urlDetectionRequest.url).origin;\n\n // Build absolute URLs using detected appUrl or request origin\n const absoluteCallbackUrl = resolvedConfig.callbackUrl.startsWith(\"http\")\n ? resolvedConfig.callbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.callbackUrl,\n appUrl,\n );\n const absoluteLogoutCallbackUrl = resolvedConfig.logoutCallbackUrl.startsWith(\n \"http\",\n )\n ? resolvedConfig.logoutCallbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.logoutCallbackUrl,\n appUrl,\n );\n\n const civicAuth = new CivicAuth(cookieStorage, {\n disableRefresh: resolvedConfig.disableRefresh,\n clientId: resolvedConfig.clientId,\n redirectUrl: absoluteCallbackUrl,\n oauthServer: resolvedConfig.oauthServer,\n postLogoutRedirectUrl: absoluteLogoutCallbackUrl,\n loginSuccessUrl: request.url,\n });\n\n return {\n civicAuth,\n cookieStorage,\n appUrl, // Return appUrl for use in other functions\n urlDetectionRequest, // Return for use in handlers\n };\n};\n\n/**\n * Login handler - backend OAuth login initiation endpoint\n * Uses CivicAuth.buildLoginUrl()\n */\nasync function handleLogin(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n const frontendState = request.nextUrl.searchParams.get(\"state\");\n\n // Store appUrl in cookie if provided as query parameter\n const appUrlFromQuery = request.nextUrl.searchParams.get(\"appUrl\");\n if (appUrlFromQuery) {\n const cookieStorage = new NextjsCookieStorage(\n resolvedConfigs.cookies?.tokens ?? {},\n );\n await cookieStorage.set(CodeVerifier.APP_URL, appUrlFromQuery);\n }\n\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const url = await civicAuth.buildLoginUrl({\n state: frontendState || undefined,\n });\n\n logger.info(\"[LOGIN_HANDLER] Redirecting to OAuth login URL\", {\n loginUrl: url.toString(),\n });\n\n return NextResponse.redirect(url.toString());\n } catch (error) {\n logger.error(\"[LOGIN_HANDLER] Backend login error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=login_failed\",\n appUrl,\n ),\n );\n }\n}\n\nasync function handleRefresh(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n await civicAuth.refreshTokens();\n\n logger.info(\"[REFRESH_HANDLER] Tokens refreshed successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Tokens refreshed\",\n });\n } catch (error) {\n logger.error(\"[REFRESH_HANDLER] Token refresh error:\", error);\n return NextResponse.json(\n { error: \"Token refresh failed\" },\n { status: 500 },\n );\n }\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n const error = request.nextUrl.searchParams.get(\"error\");\n\n if (error) {\n logger.error(\"OAuth error in callback:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=oauth_error\",\n appUrl,\n ),\n );\n }\n\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n try {\n const { civicAuth, appUrl, urlDetectionRequest, cookieStorage } =\n createCivicAuth(request, resolvedConfigs);\n\n // Convert NextRequest to the format expected by handleCallback\n const handleCallbackRequest = {\n headers: Object.fromEntries(request.headers.entries()),\n url: request.url.toString(),\n };\n\n // Get loginSuccessUrl with proper baseUrl handling\n const loginSuccessUrl = CivicAuth.getLoginSuccessUrl(\n urlDetectionRequest,\n appUrl,\n );\n const defaultFrontendUrl =\n loginSuccessUrl || resolvedConfigs.loginSuccessUrl || \"/\";\n\n // Check for preserved deep link (returnUrl cookie)\n const returnUrl = await cookieStorage.get(AuthFlowCookie.RETURN_URL);\n\n // Delete the cookie immediately after reading (single-use)\n if (returnUrl) {\n await cookieStorage.delete(AuthFlowCookie.RETURN_URL);\n logger.debug(\"[CALLBACK_HANDLER] Found returnUrl cookie\", { returnUrl });\n }\n\n // Determine final redirect URL based on deepLinkHandling config\n let frontendUrl: string;\n if (returnUrl && resolvedConfigs.deepLinkHandling === \"queryParamsOnly\") {\n // queryParamsOnly: Use loginSuccessUrl but merge query params from returnUrl\n try {\n const returnUrlObj = new URL(returnUrl, appUrl);\n const baseUrlObj = new URL(defaultFrontendUrl, appUrl);\n\n // Append query params from returnUrl to the base loginSuccessUrl\n returnUrlObj.searchParams.forEach((value, key) => {\n baseUrlObj.searchParams.set(key, value);\n });\n\n frontendUrl = baseUrlObj.pathname + baseUrlObj.search + baseUrlObj.hash;\n logger.debug(\n \"[CALLBACK_HANDLER] deepLinkHandling=queryParamsOnly: merged returnUrl params\",\n { frontendUrl },\n );\n } catch (error) {\n // If URL parsing fails, fall back to default\n logger.warn(\n \"[CALLBACK_HANDLER] Failed to merge query params from returnUrl\",\n { error, returnUrl, defaultFrontendUrl },\n );\n frontendUrl = defaultFrontendUrl;\n }\n } else if (returnUrl && resolvedConfigs.deepLinkHandling === \"fullUrl\") {\n // fullUrl: Use the preserved deep link directly\n frontendUrl = returnUrl;\n logger.debug(\n \"[CALLBACK_HANDLER] deepLinkHandling=fullUrl: using preserved deep link\",\n {\n frontendUrl,\n },\n );\n } else {\n // No returnUrl cookie or deepLinkHandling is \"disabled\" - use default loginSuccessUrl\n frontendUrl = defaultFrontendUrl;\n }\n\n // Use CivicAuth's smart callback handler\n const result = await civicAuth.handleCallback(\n {\n code,\n state,\n req: handleCallbackRequest,\n },\n {\n // Pass the properly resolved frontendUrl\n frontendUrl: prependBasePath(frontendUrl, config.basePath || \"\"),\n },\n );\n if (result.redirectTo) {\n return redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, result.redirectTo, appUrl),\n );\n }\n\n if (result.content) {\n // Handle both string content and object content\n if (typeof result.content === \"string\") {\n const response = new NextResponse(result.content, {\n status: 200,\n headers: { \"Content-Type\": \"text/html\" },\n });\n\n // If we had a returnUrl cookie, delete it using NextResponse's cookie API.\n // This ensures consistent cookie attributes from the resolved config.\n if (returnUrl) {\n const cookieConfig =\n resolvedConfigs.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];\n response.cookies.set(AuthFlowCookie.RETURN_URL, \"\", {\n path: cookieConfig?.path ?? resolvedConfigs.basePath ?? \"/\",\n httpOnly: cookieConfig?.httpOnly ?? true,\n secure: cookieConfig?.secure ?? true,\n sameSite: cookieConfig?.sameSite ?? \"strict\",\n maxAge: 0, // Immediately expire the cookie\n });\n logger.debug(\n \"[CALLBACK_HANDLER] Clearing returnUrl cookie via NextResponse\",\n );\n }\n\n return response;\n } else {\n // Object content (JSON response)\n return NextResponse.json(result.content);\n }\n }\n\n // Fallback redirect\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, \"/\", appUrl),\n );\n } catch (error) {\n logger.error(\"[CALLBACK_HANDLER] OAuth callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=callback_failed\",\n appUrl,\n ),\n );\n }\n}\n\nconst revalidateUrlPath = async (url: string) => {\n try {\n const path = new URL(url).pathname;\n revalidatePath(path);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n};\n\nexport async function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n // Get framework-agnostic request for URL utilities\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Read the state from the query parameters\n const state = request.nextUrl.searchParams.get(\"state\");\n const clientLogoutRedirectUrl =\n request.nextUrl.searchParams.get(\"logoutRedirectUrl\");\n\n try {\n logger.info(\"[LOGOUT_HANDLER] Backend logout endpoint called\");\n\n // If client provided a logoutRedirectUrl, override the config\n let configToUse = resolvedConfigs;\n if (clientLogoutRedirectUrl) {\n configToUse = {\n ...resolvedConfigs,\n logoutCallbackUrl: clientLogoutRedirectUrl,\n };\n logger.info(\"[LOGOUT_HANDLER] Overriding logout callback URL\", {\n original: resolvedConfigs.logoutCallbackUrl,\n override: clientLogoutRedirectUrl,\n });\n }\n\n const { civicAuth } = createCivicAuth(request, configToUse);\n\n // Always redirect to OAuth logout (like main branch)\n // Don't validate session - even invalid local sessions should hit OAuth logout\n logger.info(\"[LOGOUT_HANDLER] Processing logout request\", {\n state: !!state,\n });\n\n // Always redirect to OAuth logout endpoint (like main branch)\n // Client-side iframe logic will handle completion and redirect appropriately\n const logoutUrl = await civicAuth.buildLogoutRedirectUrl({\n state: state || undefined,\n });\n\n try {\n await clearAuthCookies(resolvedConfigs);\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Error clearing tokens:\", error);\n }\n\n // Remove state parameter from logout URL to prevent it from appearing in frontend URL\n const cleanLogoutUrl = new URL(logoutUrl);\n cleanLogoutUrl.searchParams.delete(\"state\");\n\n logger.info(\"[LOGOUT_HANDLER] Redirecting to OAuth logout endpoint\", {\n logoutUrl: cleanLogoutUrl.toString(),\n });\n\n return NextResponse.redirect(cleanLogoutUrl.toString());\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Logout error:\", error);\n // If logout URL generation fails, clear tokens and redirect to home\n await clearAuthCookies(resolvedConfigs);\n\n const fallbackUrl =\n clientLogoutRedirectUrl || resolvedConfigs.logoutCallbackUrl;\n const finalFallbackUrl = CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n fallbackUrl,\n appUrl,\n );\n\n return NextResponse.redirect(finalFallbackUrl);\n }\n}\n\n/**\n * Clear session handler - clears all auth cookies server-side.\n * Called by client in parallel with logout iframe to quickly clear HttpOnly cookies.\n *\n * This is part of a parallel logout strategy:\n * - Client calls clearsession (this endpoint) AND loads logout iframe simultaneously\n * - Both requests are sent while cookies are still present\n * - clearsession clears HttpOnly cookies quickly (this endpoint)\n * - logout iframe handles OAuth provider logout (slower, but had cookies when initiated)\n *\n * This ensures cookies are cleared fast (preventing race conditions if user refreshes)\n * while still performing OAuth provider logout.\n */\nasync function handleClearSession(\n _request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\"[CLEARSESSION_HANDLER] Clearing session cookies\");\n\n // Clear all auth cookies immediately\n await clearAuthCookies(resolvedConfigs);\n\n logger.info(\"[CLEARSESSION_HANDLER] Session cleared successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Session cleared\",\n });\n } catch (error) {\n logger.error(\"[CLEARSESSION_HANDLER] Error clearing session:\", error);\n return NextResponse.json(\n { error: \"Failed to clear session\" },\n { status: 500 },\n );\n }\n}\n\nexport async function handleLogoutCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Backend logout callback endpoint called\",\n );\n\n // Clear authentication cookies\n await clearAuthCookies(resolvedConfigs);\n\n // Get framework-agnostic request and create CivicAuth instance\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n // Get the state parameter for iframe detection\n const state = request.nextUrl.searchParams.get(\"state\");\n\n // If this is an iframe request, return HTML with logout success signal\n if (state && displayModeFromState(state, \"iframe\") === \"iframe\") {\n // For iframe mode, include the post-logout redirect URL in the HTML\n const postLogoutRedirectUrl =\n civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n const response = new NextResponse(\n `<html lang=\"en\"><span style=\"display:none\">${LOGOUT_SUCCESS_TEXT}<a href=\"${postLogoutRedirectUrl}\" rel=\"civic-auth-post-logout-redirect-url\"></a></span></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Returning iframe logout success HTML\",\n { postLogoutRedirectUrl },\n );\n return response;\n }\n\n // For non-iframe requests, redirect to the logout callback URL or post-logout URL\n const redirectUrl = civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Redirecting to logout callback URL\",\n {\n logoutCallbackUrl: resolvedConfigs.logoutCallbackUrl,\n redirectUrl,\n },\n );\n\n // Revalidate the redirect path to update authentication state in server components\n await revalidateUrlPath(redirectUrl);\n return redirectWithBasePath(config, redirectUrl);\n } catch (error) {\n logger.error(\"[LOGOUT_CALLBACK_HANDLER] Logout callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfigs.logoutCallbackUrl,\n appUrl,\n ),\n );\n }\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * export const POST = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n logger.debug(\"routeHandler: Auth route handler called\", config);\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n case \"login\":\n return await handleLogin(request, config);\n case \"callback\":\n return await handleCallback(request, config);\n case \"refresh\":\n return await handleRefresh(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n case \"clearsession\":\n return await handleClearSession(request, config);\n case \"logoutcallback\":\n return await handleLogoutCallback(request, config);\n case \"user\":\n return await handleUser(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n await clearAuthCookies(config);\n return response;\n }\n };\n\n/**\n * User endpoint - returns current user data as JSON\n * Uses CivicAuth.isLoggedIn() and getUser()\n */\nasync function handleUser(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n logger.debug(\n \"routeHandler: [USER_HANDLER] User endpoint called\",\n resolvedConfigs,\n );\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const isLoggedIn = await civicAuth.isLoggedIn();\n\n if (!isLoggedIn) {\n const statusCode = request.nextUrl.searchParams.get(\n \"optimisticRehydration\",\n )\n ? 202\n : 401;\n return NextResponse.json(\n { error: \"Not authenticated\" },\n { status: statusCode },\n );\n }\n\n const user = await civicAuth.getUser();\n\n return NextResponse.json({ user });\n } catch (error) {\n logger.error(\"[USER_HANDLER] User endpoint error:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/nextjs/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,sBAAsB,EAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAG9C,OAAO,
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/nextjs/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,sBAAsB,EAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAG9C,OAAO,EAKL,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,uBAAuB,CAAC;AAM/B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAKlD,eAAO,MAAM,kBAAkB,WACrB,sBAAsB,YACpB,MAAM,KACf,MAGF,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQrD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACp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AAe,QAAS,MAAM,YAAY,MAAM,WAiB5D,CAAC;AAEF,eAAO,MAAM,oBAAoB,WACvB,UAAU,aACP,MAAM,KAChB,YACuE,CAAC"}
|
package/dist/nextjs/utils.js
CHANGED
|
@@ -2,8 +2,8 @@ import { systemUrlsConfig, } from "../nextjs/config.js";
|
|
|
2
2
|
import { NextResponse } from "next/server.js";
|
|
3
3
|
import { loggers } from "../lib/logger.js";
|
|
4
4
|
import picomatch from "picomatch";
|
|
5
|
-
import { CodeVerifier, OAuthTokenTypes, UserStorage, } from "../shared/lib/types.js";
|
|
6
|
-
import { clearTokens, getCookieConfiguration } from "../shared/lib/util.js";
|
|
5
|
+
import { AuthFlowCookie, CodeVerifier, OAuthTokenTypes, UserStorage, } from "../shared/lib/types.js";
|
|
6
|
+
import { clearTokens, getCookieConfiguration, sanitizeReturnUrl, } from "../shared/lib/util.js";
|
|
7
7
|
import { CookieStorage } from "../server/index.js";
|
|
8
8
|
import { extractCookieFromRawHeader } from "../shared/lib/cookieUtils.js";
|
|
9
9
|
const logger = loggers.nextjs.middleware;
|
|
@@ -225,7 +225,25 @@ export const handleUnauthenticatedUser = async (session, request, response, stor
|
|
|
225
225
|
// The loginUrl from getOriginUrl already includes the basePath, but request.nextUrl.pathname does not. So we strip it off to enable comparison.
|
|
226
226
|
if (request.nextUrl.pathname !== loginPathWithoutBasePath) {
|
|
227
227
|
logger.debug(`→ No valid tokens found - redirecting to login "${redirectUrl}"`);
|
|
228
|
+
// Preserve the original URL as a deep link for post-authentication redirect
|
|
229
|
+
if (authConfig.deepLinkHandling !== "disabled") {
|
|
230
|
+
const originUrl = getOriginUrl(request, authConfig);
|
|
231
|
+
// Get the full path including query string
|
|
232
|
+
const fullPath = request.nextUrl.pathname +
|
|
233
|
+
request.nextUrl.search +
|
|
234
|
+
request.nextUrl.hash;
|
|
235
|
+
// Sanitize the return URL to prevent open redirect vulnerabilities
|
|
236
|
+
const sanitizedReturnUrl = sanitizeReturnUrl(fullPath, originUrl);
|
|
237
|
+
if (sanitizedReturnUrl) {
|
|
238
|
+
logger.debug(`→ Preserving deep link: "${sanitizedReturnUrl}" for post-auth redirect`);
|
|
239
|
+
await storage.set(AuthFlowCookie.RETURN_URL, sanitizedReturnUrl, {});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
228
242
|
const redirectedResponse = redirectWithBasePath(authConfig, redirectUrl);
|
|
243
|
+
// Copy any cookies that were set to the redirect response
|
|
244
|
+
response.cookies.getAll().forEach((cookie) => {
|
|
245
|
+
redirectedResponse.cookies.set(cookie);
|
|
246
|
+
});
|
|
229
247
|
return redirectedResponse;
|
|
230
248
|
}
|
|
231
249
|
return response;
|