@civic/auth 0.10.0-beta.5 → 0.10.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  - NextJS Refactor with Vanillajs
4
4
  - increase SDK wrapper width to 360px
5
+ - Fix bug where basePath was not honored when redirecting back from the refresh endpoint, as well as in the loginSuccessUrl.
6
+ - Fix redirect loop if page was loaded with no cookies set and middleware enabled.
5
7
 
6
8
  # 0.9.5
7
9
 
@@ -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;AAIpC;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IAEpB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IAEnB,eAAe,CAAC,EAAE,MAAM,CAAC;IAIzB,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,mBAAmB,CAAC;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,OAAO,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iB,EAAE,IAAI,CAAC,sBAAsB,EAAE,UAAU,CAkBtE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,iBAAiB,YACpB,OAAO,CAAC,UAAU,CAAC,KAC1B,sBAuEF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,eAAO,MAAM,qBAAqB,eAAgB,UAAU,mBACrC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8Dm1S,CAAC;6BAAsG,CAAC;;;sBAAke,CAAC;yBAA4H,CAAC;;;qBAA+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;;;;CAD5pf,CAAC"}
@@ -50,6 +50,8 @@ export const defaultAuthConfig = {
50
50
  */
51
51
  export const resolveAuthConfig = (config = {}) => {
52
52
  // Read configuration that was set by the plugin via environment variables
53
+ // Don't load environment cookies if explicit cookies are provided
54
+ const hasExplicitCookies = config.cookies;
53
55
  const configFromEnv = withoutUndefined({
54
56
  clientId: process.env._civic_auth_client_id,
55
57
  oauthServer: process.env._civic_oauth_server,
@@ -63,9 +65,11 @@ export const resolveAuthConfig = (config = {}) => {
63
65
  refreshUrl: process.env._civic_auth_refresh_url,
64
66
  include: process.env._civic_auth_includes?.split(","),
65
67
  exclude: process.env._civic_auth_excludes?.split(","),
66
- cookies: process.env._civic_auth_cookie_config
67
- ? JSON.parse(process.env._civic_auth_cookie_config)
68
- : undefined,
68
+ cookies: hasExplicitCookies
69
+ ? undefined
70
+ : process.env._civic_auth_cookie_config
71
+ ? JSON.parse(process.env._civic_auth_cookie_config)
72
+ : undefined,
69
73
  basePath: process.env._civic_auth_base_path || "",
70
74
  baseUrl: process.env._civic_auth_base_url,
71
75
  autoRedirect: process.env._civic_auth_auto_redirect === "false" ? false : undefined,
@@ -77,14 +81,21 @@ export const resolveAuthConfig = (config = {}) => {
77
81
  ...(configFromEnv.exclude || []),
78
82
  ...(config.exclude ?? []),
79
83
  ]);
84
+ // Store explicit cookies config before merge to preserve it
85
+ const explicitCookies = config.cookies;
80
86
  // Perform a deep merge of the configurations
81
87
  const mergedConfig = merge.withOptions({ mergeArrays: false }, defaultAuthConfig, configFromEnv, config);
82
88
  // Override the exclude list with the ensured list
83
89
  mergedConfig.exclude = Array.from(finalExclude);
84
90
  // Update cookie configuration with basePath if it wasn't explicitly provided
85
- if (!config.cookies && mergedConfig.basePath) {
91
+ // Only auto-configure if no explicit cookies are provided anywhere
92
+ if (!config.cookies && !configFromEnv.cookies && mergedConfig.basePath) {
86
93
  mergedConfig.cookies = createNextJSCookieConfig(mergedConfig.basePath);
87
94
  }
95
+ // Merge explicit cookies with merged config to preserve both explicit settings and defaults
96
+ if (explicitCookies && mergedConfig.cookies) {
97
+ mergedConfig.cookies = merge.withOptions({ mergeArrays: false }, mergedConfig.cookies, explicitCookies);
98
+ }
88
99
  if (mergedConfig.clientId === undefined) {
89
100
  throw new Error("Civic Auth client ID is required");
90
101
  }
@@ -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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EAAE,cAAc,CAAC,YAAY,CAAC,QAAQ,EAAE;aAClE;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 * 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 // 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 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 include?: string[];\n exclude?: string[];\n basePath?: string;\n baseUrl?: string;\n oauthServer?: string;\n autoRedirect?: 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 callbackUrl: \"/api/auth/callback\",\n loginInitUrl: \"/api/auth/login\",\n logoutUrl: \"/api/auth/logout\",\n challengeUrl: \"/api/auth/challenge\",\n refreshUrl: \"/api/auth/refresh\",\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 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 include: process.env._civic_auth_includes?.split(\",\"),\n exclude: process.env._civic_auth_excludes?.split(\",\"),\n cookies: 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 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 // 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 if (!config.cookies && mergedConfig.basePath) {\n mergedConfig.cookies = createNextJSCookieConfig(mergedConfig.basePath);\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 * 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 // Create a copy of default URLs with basePath added\n const defaultUrlsWithBasePath: Partial<AuthConfig> = {};\n\n // Only apply to URLs that aren't explicitly set in authConfig\n if (basePath) {\n if (!authConfig.callbackUrl)\n defaultUrlsWithBasePath.callbackUrl = `${basePath}/api/auth/callback`;\n if (!authConfig.challengeUrl)\n defaultUrlsWithBasePath.challengeUrl = `${basePath}/api/auth/challenge`;\n if (!authConfig.refreshUrl)\n defaultUrlsWithBasePath.refreshUrl = `${basePath}/api/auth/refresh`;\n if (!authConfig.logoutUrl)\n defaultUrlsWithBasePath.logoutUrl = `${basePath}/api/auth/logout`;\n if (!authConfig.loginInitUrl)\n defaultUrlsWithBasePath.loginInitUrl = `${basePath}/api/auth/login`;\n if (!authConfig.logoutCallbackUrl)\n defaultUrlsWithBasePath.logoutCallbackUrl = `${basePath}`;\n if (!authConfig.loginUrl && authConfig.loginUrl !== \"\")\n defaultUrlsWithBasePath.loginUrl = basePath;\n }\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_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 },\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;AAuE5C;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAA6C;IACzE,WAAW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,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;aAClE;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 * 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 // 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 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 include?: string[];\n exclude?: string[];\n basePath?: string;\n baseUrl?: string;\n oauthServer?: string;\n autoRedirect?: 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 callbackUrl: \"/api/auth/callback\",\n loginInitUrl: \"/api/auth/login\",\n logoutUrl: \"/api/auth/logout\",\n challengeUrl: \"/api/auth/challenge\",\n refreshUrl: \"/api/auth/refresh\",\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 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 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 * 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 // Create a copy of default URLs with basePath added\n const defaultUrlsWithBasePath: Partial<AuthConfig> = {};\n\n // Only apply to URLs that aren't explicitly set in authConfig\n if (basePath) {\n if (!authConfig.callbackUrl)\n defaultUrlsWithBasePath.callbackUrl = `${basePath}/api/auth/callback`;\n if (!authConfig.challengeUrl)\n defaultUrlsWithBasePath.challengeUrl = `${basePath}/api/auth/challenge`;\n if (!authConfig.refreshUrl)\n defaultUrlsWithBasePath.refreshUrl = `${basePath}/api/auth/refresh`;\n if (!authConfig.logoutUrl)\n defaultUrlsWithBasePath.logoutUrl = `${basePath}/api/auth/logout`;\n if (!authConfig.loginInitUrl)\n defaultUrlsWithBasePath.loginInitUrl = `${basePath}/api/auth/login`;\n if (!authConfig.logoutCallbackUrl)\n defaultUrlsWithBasePath.logoutCallbackUrl = `${basePath}`;\n if (!authConfig.loginUrl && authConfig.loginUrl !== \"\")\n defaultUrlsWithBasePath.loginUrl = basePath;\n }\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_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 },\n };\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"cookies.d.ts","sourceRo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AAO,CAAC,sBAAsB,CAAC,kBAOvE,CAAC;AAEF,cAAM,mBAAoB,SAAQ,aAAa;IAC1B,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;gBAAhD,MAAM,GAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,CAAM;IAOlE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAKxC,GAAG,CACP,GAAG,EAAE,SAAS,EACd,KAAK,EAAE,MAAM,EACb,oBAAoB,GAAE,OAAO,CAAC,YAAY,CAAM,GAC/C,OAAO,CAAC,IAAI,CAAC;IAsBV,MAAM,CAAC,GAAG,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;CAgB5C;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { cookies, headers } from "next/headers.js";
2
- import {} from "../shared/lib/types.js";
2
+ import { UserStorage } from "../shared/lib/types.js";
3
3
  import { CookieStorage } from "../shared/lib/storage.js";
4
4
  import * as session from "../shared/lib/session.js";
5
5
  import { getCookieConfiguration } from "../shared/lib/util.js";
@@ -39,8 +39,10 @@ const createRequestFromHeaders = async () => {
39
39
  */
40
40
  const clearAuthCookies = async (config) => {
41
41
  // Use resolved config cookies if available, otherwise use default
42
- const cookieConfig = config?.cookies || {};
43
- const cookieStorage = new NextjsCookieStorage(cookieConfig);
42
+ const cookieStorage = new NextjsCookieStorage({
43
+ ...config?.cookies?.tokens,
44
+ [UserStorage.USER]: config?.cookies?.user,
45
+ });
44
46
  await session.clearAuthCookies(cookieStorage);
45
47
  };
46
48
  class NextjsCookieStorage extends CookieStorage {
@@ -1 +1 @@
1
- {"version":3,"file":"cookies.js","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,i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Aa,CAAC,MAAM;YAC5B,QAAQ,EAAE,aAAa,CAAC,QAAQ;SACjC,CAAC;QAEF,2EAA2E;QAC3E,MAAM,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAc;QACzB,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QAEpC,oEAAoE;QACpE,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,GAAgB,CAAC,IAAI,EAAE,CAAC;QAE7D,gEAAgE;QAChE,IAAI,cAAc,CAAC,IAAI,EAAE,CAAC;YACxB,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,EAAE;gBACvB,OAAO,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,qBAAqB;gBAC3C,IAAI,EAAE,cAAc,CAAC,IAAI;aAC1B,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;CACF;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import { cookies, headers } from \"next/headers.js\";\n\nimport type { KeySetter } from \"@/shared/lib/types.js\";\nimport { type CookieConfig } from \"@/shared/lib/types.js\";\nimport { CookieStorage } from \"@/shared/lib/storage.js\";\nimport * as session from \"@/shared/lib/session.js\";\nimport { getCookieConfiguration } from \"@/shared/lib/util.js\";\nimport type { AuthConfigWithDefaults } from \"@/nextjs/config.js\";\n\n/**\n * Create a mock Request object from Next.js headers for cookie configuration\n */\nconst createRequestFromHeaders = async (): Promise<Request | undefined> => {\n try {\n const headerStore = await headers();\n const host = headerStore.get(\"host\");\n const userAgent = headerStore.get(\"user-agent\");\n const protocol =\n headerStore.get(\"x-forwarded-proto\") ||\n headerStore.get(\"x-forwarded-protocol\") ||\n (process.env.NODE_ENV === \"production\" ? \"https\" : \"http\");\n\n if (!host) return undefined;\n\n const url = `${protocol}://${host}/`;\n\n // Create a minimal Request object with the headers we need\n const request = new Request(url, {\n headers: {\n \"user-agent\": userAgent || \"\",\n \"x-forwarded-proto\": headerStore.get(\"x-forwarded-proto\") || \"\",\n \"x-forwarded-protocol\": headerStore.get(\"x-forwarded-protocol\") || \"\",\n forwarded: headerStore.get(\"forwarded\") || \"\",\n },\n });\n\n return request;\n } catch (error) {\n console.error(\"Error creating request from headers\", error);\n // Headers might not be available in all contexts\n return undefined;\n }\n};\n\n/**\n * Clears all authentication cookies on server. Note, this can only be called by the server\n */\nconst clearAuthCookies = async (config?: Partial<AuthConfigWithDefaults>) => {\n // Use resolved config cookies if available, otherwise use default\n const cookieConfig = config?.cookies || {};\n const cookieStorage = new NextjsCookieStorage(cookieConfig);\n await session.clearAuthCookies(cookieStorage);\n};\n\nclass NextjsCookieStorage extends CookieStorage {\n constructor(public config: Partial<Record<KeySetter, CookieConfig>> = {}) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n const cookieStore = await cookies();\n return cookieStore.get(key)?.value || null;\n }\n\n async set(\n key: KeySetter,\n value: string,\n cookieConfigOverride: Partial<CookieConfig> = {},\n ): Promise<void> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n\n // Get dynamic cookie configuration based on environment and browser\n const request = await createRequestFromHeaders();\n const dynamicConfig = getCookieConfiguration(request);\n\n const useCookieSettings = {\n ...cookieSettings,\n ...cookieConfigOverride,\n // Apply dynamic configuration for secure and sameSite\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n };\n\n // Respect the httpOnly setting from configuration instead of hardcoding it\n await cookieStore.set(key, value, useCookieSettings);\n }\n\n async delete(key: KeySetter): Promise<void> {\n const cookieStore = await cookies();\n\n // Get cookie configuration for this key to respect the path setting\n const cookieSettings = this.config?.[key as KeySetter] || {};\n\n // If we have a path configured, use it when deleting the cookie\n if (cookieSettings.path) {\n cookieStore.set(key, \"\", {\n expires: new Date(0), // Expire in the past\n path: cookieSettings.path,\n });\n } else {\n cookieStore.delete(key);\n }\n }\n}\n\nexport { clearAuthCookies, NextjsCookieStorage };\n"]}
1
+ {"version":3,"file":"cookies.js","sourceRoot":"","sources":["../../src/nextjs/cookies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAqB,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAG9D;;GAEG;AACH,MAAM,wBAAwB,GAAG,KAAK,IAAkC,EAAE;IACxE,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAChD,MAAM,QAAQ,GACZ,WAAW,CAAC,GAAG,CAAC,mBAAmB,CAAC;YACpC,WAAW,CAAC,GAAG,CAAC,sBAAsB,CAAC;YACvC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAE7D,IAAI,CAAC,IAAI;YAAE,OAAO,SAAS,CAAC;QAE5B,MAAM,GAAG,GAAG,GAAG,QAAQ,MAAM,IAAI,GAAG,CAAC;QAErC,2DAA2D;QAC3D,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;YAC/B,OAAO,EAAE;gBACP,YAAY,EAAE,SAAS,IAAI,EAAE;gBAC7B,mBAAmB,EAAE,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AC;QACpC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,GAAgB,CAAC,IAAI;YACxD,GAAG,IAAI,CAAC,QAAQ;SACjB,CAAC;QAEF,oEAAoE;QACpE,MAAM,OAAO,GAAG,MAAM,wBAAwB,EAAE,CAAC;QACjD,MAAM,aAAa,GAAG,sBAAsB,CAAC,OAAO,CAAC,CAAC;QAEtD,MAAM,iBAAiB,GAAG;YACxB,GAAG,cAAc;YACjB,GAAG,oBAAoB;YACvB,sDAAsD;YACtD,MAAM,EAAE,aAAa,CAAC,MAAM;YAC5B,QAAQ,EAAE,aAAa,CAAC,QAAQ;SACjC,CAAC;QAEF,2EAA2E;QAC3E,MAAM,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAc;QACzB,MAAM,WAAW,GAAG,MAAM,OAAO,EAAE,CAAC;QAEpC,oEAAoE;QACpE,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,GAAgB,CAAC,IAAI,EAAE,CAAC;QAE7D,gEAAgE;QAChE,IAAI,cAAc,CAAC,IAAI,EAAE,CAAC;YACxB,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,EAAE;gBACvB,OAAO,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,qBAAqB;gBAC3C,IAAI,EAAE,cAAc,CAAC,IAAI;aAC1B,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;CACF;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import { cookies, headers } from \"next/headers.js\";\n\nimport type { KeySetter } from \"@/shared/lib/types.js\";\nimport { UserStorage, type CookieConfig } from \"@/shared/lib/types.js\";\nimport { CookieStorage } from \"@/shared/lib/storage.js\";\nimport * as session from \"@/shared/lib/session.js\";\nimport { getCookieConfiguration } from \"@/shared/lib/util.js\";\nimport type { AuthConfigWithDefaults } from \"@/nextjs/config.js\";\n\n/**\n * Create a mock Request object from Next.js headers for cookie configuration\n */\nconst createRequestFromHeaders = async (): Promise<Request | undefined> => {\n try {\n const headerStore = await headers();\n const host = headerStore.get(\"host\");\n const userAgent = headerStore.get(\"user-agent\");\n const protocol =\n headerStore.get(\"x-forwarded-proto\") ||\n headerStore.get(\"x-forwarded-protocol\") ||\n (process.env.NODE_ENV === \"production\" ? \"https\" : \"http\");\n\n if (!host) return undefined;\n\n const url = `${protocol}://${host}/`;\n\n // Create a minimal Request object with the headers we need\n const request = new Request(url, {\n headers: {\n \"user-agent\": userAgent || \"\",\n \"x-forwarded-proto\": headerStore.get(\"x-forwarded-proto\") || \"\",\n \"x-forwarded-protocol\": headerStore.get(\"x-forwarded-protocol\") || \"\",\n forwarded: headerStore.get(\"forwarded\") || \"\",\n },\n });\n\n return request;\n } catch (error) {\n console.error(\"Error creating request from headers\", error);\n // Headers might not be available in all contexts\n return undefined;\n }\n};\n\n/**\n * Clears all authentication cookies on server. Note, this can only be called by the server\n */\nconst clearAuthCookies = async (config?: Partial<AuthConfigWithDefaults>) => {\n // Use resolved config cookies if available, otherwise use default\n const cookieStorage = new NextjsCookieStorage({\n ...config?.cookies?.tokens,\n [UserStorage.USER]: config?.cookies?.user,\n });\n await session.clearAuthCookies(cookieStorage);\n};\n\nclass NextjsCookieStorage extends CookieStorage {\n constructor(public config: Partial<Record<KeySetter, CookieConfig>> = {}) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n const cookieStore = await cookies();\n return cookieStore.get(key)?.value || null;\n }\n\n async set(\n key: KeySetter,\n value: string,\n cookieConfigOverride: Partial<CookieConfig> = {},\n ): Promise<void> {\n const cookieStore = await cookies();\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n\n // Get dynamic cookie configuration based on environment and browser\n const request = await createRequestFromHeaders();\n const dynamicConfig = getCookieConfiguration(request);\n\n const useCookieSettings = {\n ...cookieSettings,\n ...cookieConfigOverride,\n // Apply dynamic configuration for secure and sameSite\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n };\n\n // Respect the httpOnly setting from configuration instead of hardcoding it\n await cookieStore.set(key, value, useCookieSettings);\n }\n\n async delete(key: KeySetter): Promise<void> {\n const cookieStore = await cookies();\n\n // Get cookie configuration for this key to respect the path setting\n const cookieSettings = this.config?.[key as KeySetter] || {};\n\n // If we have a path configured, use it when deleting the cookie\n if (cookieSettings.path) {\n cookieStore.set(key, \"\", {\n expires: new Date(0), // Expire in the past\n path: cookieSettings.path,\n });\n } else {\n cookieStore.delete(key);\n }\n }\n}\n\nexport { clearAuthCookies, NextjsCookieStorage };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProvider.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAGrE,KAAK,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;AAGtE,wBAAsB,qBAAqB,CAAC,EAC1C,QAAQ,EACR,GAAG,KAAK,EACT,EAAE,0BAA0B,GAAG;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,oDAgBA;AAGD,YAAY,EAAE,0BAA0B,EAAE,CAAC"}
1
+ {"version":3,"file":"NextAuthProvider.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAGrE,KAAK,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;AAGtE,wBAAsB,qBAAqB,CAAC,EAC1C,QAAQ,EACR,GAAG,KAAK,EACT,EAAE,0BAA0B,GAAG;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,oDAwBA;AAGD,YAAY,EAAE,0BAA0B,EAAE,CAAC"}
@@ -1,20 +1,23 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  /** @jsxImportSource react */
3
3
  import React from "react";
4
- import { getUser } from "../../nextjs/index.js";
4
+ import { getUser, getTokens } from "../../nextjs/index.js";
5
5
  import { CivicNextAuthProviderClient } from "./NextAuthProviderClient.js";
6
6
  // Server component that reads user data and passes it to client component
7
7
  export async function CivicNextAuthProvider({ children, ...props }) {
8
- // Read user data server-side to prevent hydration mismatch
8
+ // Read user data and tokens server-side to prevent hydration mismatch
9
9
  let serverUser = null;
10
+ let serverTokens = null;
10
11
  try {
11
12
  serverUser = await getUser();
13
+ serverTokens = await getTokens();
12
14
  }
13
15
  catch (error) {
14
- // If server-side user reading fails, just use null
15
- console.warn("Failed to read user server-side:", error);
16
+ // If server-side reading fails, just use null
17
+ console.warn("Failed to read user/tokens server-side:", error);
16
18
  serverUser = null;
19
+ serverTokens = null;
17
20
  }
18
- return (_jsx(CivicNextAuthProviderClient, { serverUser: serverUser, ...props, children: children }));
21
+ return (_jsx(CivicNextAuthProviderClient, { serverUser: serverUser, serverTokens: serverTokens, ...props, children: children }));
19
22
  }
20
23
  //# sourceMappingURL=NextAuthProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProvider.js","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":";AAAA,6BAA6B;AAC7B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG5C,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAI1E,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,EAC1C,QAAQ,EACR,GAAG,KAAK,EAIT;IACC,2DAA2D;IAC3D,IAAI,UAAU,GAAgB,IAAI,CAAC;IACnC,IAAI,CAAC;QACH,UAAU,GAAG,MAAM,OAAO,EAAE,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mDAAmD;QACnD,OAAO,CAAC,IAAI,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;QACxD,UAAU,GAAG,IAAI,CAAC;IACpB,CAAC;IAED,OAAO,CACL,KAAC,2BAA2B,IAAC,UAAU,EAAE,UAAU,KAAM,KAAK,YAC3D,QAAQ,GACmB,CAC/B,CAAC;AACJ,CAAC","sourcesContent":["/** @jsxImportSource react */\nimport React from \"react\";\nimport { getUser } from \"@/nextjs/index.js\";\nimport type { User } from \"@/types.js\";\nimport type { AuthProviderProps } from \"@/shared/providers/types.js\";\nimport { CivicNextAuthProviderClient } from \"./NextAuthProviderClient.js\";\n\ntype NextCivicAuthProviderProps = Omit<AuthProviderProps, \"clientId\">;\n\n// Server component that reads user data and passes it to client component\nexport async function CivicNextAuthProvider({\n children,\n ...props\n}: NextCivicAuthProviderProps & {\n redirectOnLogin?: string;\n redirectOnLogout?: string;\n}) {\n // Read user data server-side to prevent hydration mismatch\n let serverUser: User | null = null;\n try {\n serverUser = await getUser();\n } catch (error) {\n // If server-side user reading fails, just use null\n console.warn(\"Failed to read user server-side:\", error);\n serverUser = null;\n }\n\n return (\n <CivicNextAuthProviderClient serverUser={serverUser} {...props}>\n {children}\n </CivicNextAuthProviderClient>\n );\n}\n\n// Export the type for external use\nexport type { NextCivicAuthProviderProps };\n"]}
1
+ {"version":3,"file":"NextAuthProvider.js","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProvider.tsx"],"names":[],"mappings":";AAAA,6BAA6B;AAC7B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAGvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAI1E,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,EAC1C,QAAQ,EACR,GAAG,KAAK,EAIT;IACC,sEAAsE;IACtE,IAAI,UAAU,GAAgB,IAAI,CAAC;IACnC,IAAI,YAAY,GAAuB,IAAI,CAAC;IAE5C,IAAI,CAAC;QACH,UAAU,GAAG,MAAM,OAAO,EAAE,CAAC;QAC7B,YAAY,GAAG,MAAM,SAAS,EAAE,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,8CAA8C;QAC9C,OAAO,CAAC,IAAI,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;QAC/D,UAAU,GAAG,IAAI,CAAC;QAClB,YAAY,GAAG,IAAI,CAAC;IACtB,CAAC;IAED,OAAO,CACL,KAAC,2BAA2B,IAC1B,UAAU,EAAE,UAAU,EACtB,YAAY,EAAE,YAAY,KACtB,KAAK,YAER,QAAQ,GACmB,CAC/B,CAAC;AACJ,CAAC","sourcesContent":["/** @jsxImportSource react */\nimport React from \"react\";\nimport { getUser, getTokens } from \"@/nextjs/index.js\";\nimport type { User, OAuthTokens } from \"@/types.js\";\nimport type { AuthProviderProps } from \"@/shared/providers/types.js\";\nimport { CivicNextAuthProviderClient } from \"./NextAuthProviderClient.js\";\n\ntype NextCivicAuthProviderProps = Omit<AuthProviderProps, \"clientId\">;\n\n// Server component that reads user data and passes it to client component\nexport async function CivicNextAuthProvider({\n children,\n ...props\n}: NextCivicAuthProviderProps & {\n redirectOnLogin?: string;\n redirectOnLogout?: string;\n}) {\n // Read user data and tokens server-side to prevent hydration mismatch\n let serverUser: User | null = null;\n let serverTokens: OAuthTokens | null = null;\n\n try {\n serverUser = await getUser();\n serverTokens = await getTokens();\n } catch (error) {\n // If server-side reading fails, just use null\n console.warn(\"Failed to read user/tokens server-side:\", error);\n serverUser = null;\n serverTokens = null;\n }\n\n return (\n <CivicNextAuthProviderClient\n serverUser={serverUser}\n serverTokens={serverTokens}\n {...props}\n >\n {children}\n </CivicNextAuthProviderClient>\n );\n}\n\n// Export the type for external use\nexport type { NextCivicAuthProviderProps };\n"]}
@@ -1,11 +1,12 @@
1
1
  import type { AuthProviderProps } from "../../shared/providers/types.js";
2
- import type { User } from "../../types.js";
2
+ import type { User, OAuthTokens } from "../../types.js";
3
3
  type NextCivicAuthProviderProps = Omit<AuthProviderProps, "clientId">;
4
4
  export interface CivicNextAuthProviderClientProps extends NextCivicAuthProviderProps {
5
5
  serverUser: User | null;
6
+ serverTokens: OAuthTokens | null;
6
7
  redirectOnLogin?: string;
7
8
  redirectOnLogout?: string;
8
9
  }
9
- export declare const CivicNextAuthProviderClient: ({ children, serverUser, ...props }: CivicNextAuthProviderClientProps) => import("react/jsx-runtime").JSX.Element;
10
+ export declare const CivicNextAuthProviderClient: ({ children, serverUser, serverTokens, ...props }: CivicNextAuthProviderClientProps) => import("react/jsx-runtime").JSX.Element;
10
11
  export {};
11
12
  //# sourceMappingURL=NextAuthProviderClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProviderClient.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProviderClient.tsx"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAGvC,KAAK,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;AAEtE,MAAM,WAAW,gCACf,SAAQ,0BAA0B;IAClC,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAID,eAAO,MAAM,2BAA2B,uCAIrC,gCAAgC,4CA8ElC,CAAC"}
1
+ {"version":3,"file":"NextAuthProviderClient.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProviderClient.tsx"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAGpD,KAAK,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;AAEtE,MAAM,WAAW,gCACf,SAAQ,0BAA0B;IAClC,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,YAAY,EAAE,WAAW,GAAG,IAAI,CAAC;IACjC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAID,eAAO,MAAM,2BAA2B,qDAKrC,gCAAgC,4CAgFlC,CAAC"}
@@ -13,7 +13,7 @@ import { useInitialAuthConfig } from "../../nextjs/hooks/useInitialAuthConfig.js
13
13
  import { useEffect } from "react";
14
14
  import { useRouter } from "next/navigation.js";
15
15
  // Context to provide server user data immediately to useUser hook
16
- export const CivicNextAuthProviderClient = ({ children, serverUser, ...props }) => {
16
+ export const CivicNextAuthProviderClient = ({ children, serverUser, serverTokens, ...props }) => {
17
17
  const router = useRouter();
18
18
  const resolvedConfig = resolveAuthConfig();
19
19
  const { clientId, oauthServer, loginSuccessUrl, challengeUrl, refreshUrl, logoutCallbackUrl, } = resolvedConfig;
@@ -57,6 +57,6 @@ export const CivicNextAuthProviderClient = ({ children, serverUser, ...props })
57
57
  };
58
58
  initialize();
59
59
  }, [initialConfig, router]);
60
- return (_jsx(ServerUserContext.Provider, { value: serverUser, children: _jsx(CivicAuthConfigProvider, { oauthServer: oauthServer, clientId: clientId, loginSuccessUrl: loginSuccessUrl, logoutRedirectUrl: logoutCallbackUrl, nonce: props?.nonce, challengeUrl: challengeUrl, refreshUrl: refreshUrl, displayMode: props.displayMode, autoRedirect: resolvedConfig.autoRedirect, framework: "nextjs", children: _jsx(AuthStatusProvider, { children: children }) }) }));
60
+ return (_jsx(ServerUserContext.Provider, { value: { user: serverUser, tokens: serverTokens }, children: _jsx(CivicAuthConfigProvider, { oauthServer: oauthServer, clientId: clientId, loginSuccessUrl: loginSuccessUrl, logoutRedirectUrl: logoutCallbackUrl, nonce: props?.nonce, challengeUrl: challengeUrl, refreshUrl: refreshUrl, displayMode: props.displayMode, autoRedirect: resolvedConfig.autoRedirect, framework: "nextjs", children: _jsx(AuthStatusProvider, { children: children }) }) }));
61
61
  };
62
62
  //# sourceMappingURL=NextAuthProviderClient.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProviderClient.js","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProviderClient.tsx"],"names":[],"mappings":"AAAA,6BAA6B;AAC7B,YAAY,CAAC;;AAEb;;GAEG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,8CAA8C,CAAC;AACvF,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAE9E,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAW/C,kEAAkE;AAElE,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,EAC1C,QAAQ,EACR,UAAU,EACV,GAAG,KAAK,EACyB,EAAE,EAAE;IACrC,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,cAAc,GAAG,iBAAiB,EAAE,CAAC;IAC3C,MAAM,EACJ,QAAQ,EACR,WAAW,EACX,eAAe,EACf,YAAY,EACZ,UAA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vD,KAAK,CACN,CAAC;YACJ,CAAC;QACH,CAAC,CAAC;QAEF,UAAU,EAAE,CAAC;IACf,CAAC,EAAE,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC;IAE5B,OAAO,CACL,KAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,UAAU,YAC3C,KAAC,uBAAuB,IACtB,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,QAAQ,EAClB,eAAe,EAAE,eAAe,EAChC,iBAAiB,EAAE,iBAAiB,EACpC,KAAK,EAAE,KAAK,EAAE,KAAK,EACnB,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,KAAK,CAAC,WAAW,EAC9B,YAAY,EAAE,cAAc,CAAC,YAAY,EACzC,SAAS,EAAC,QAAQ,YAElB,KAAC,kBAAkB,cAAE,QAAQ,GAAsB,GAC3B,GACC,CAC9B,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/** @jsxImportSource react */\n\"use client\";\n\n/**\n * Client component for NextAuth provider that receives server-provided user data\n */\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { GlobalAuthManager } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport { AuthStatusProvider } from \"@/shared/providers/AuthStatusContext.js\";\nimport { CivicAuthConfigProvider } from \"@/shared/providers/CivicAuthConfigContext.js\";\nimport { ServerUserContext } from \"./ServerUserContext.js\";\nimport { useInitialAuthConfig } from \"@/nextjs/hooks/useInitialAuthConfig.js\";\nimport type { AuthProviderProps } from \"@/shared/providers/types.js\";\nimport { useEffect } from \"react\";\nimport type { User } from \"@/types.js\";\nimport { useRouter } from \"next/navigation.js\";\n\ntype NextCivicAuthProviderProps = Omit<AuthProviderProps, \"clientId\">;\n\nexport interface CivicNextAuthProviderClientProps\n extends NextCivicAuthProviderProps {\n serverUser: User | null;\n redirectOnLogin?: string;\n redirectOnLogout?: string;\n}\n\n// Context to provide server user data immediately to useUser hook\n\nexport const CivicNextAuthProviderClient = ({\n children,\n serverUser,\n ...props\n}: CivicNextAuthProviderClientProps) => {\n const router = useRouter();\n const resolvedConfig = resolveAuthConfig();\n const {\n clientId,\n oauthServer,\n loginSuccessUrl,\n challengeUrl,\n refreshUrl,\n logoutCallbackUrl,\n } = resolvedConfig;\n\n // Initialize GlobalAuthManager synchronously with server user data\n // This ensures the server user is available immediately when useUser() is called\n const { initialConfig } = useInitialAuthConfig({\n displayMode: props.displayMode,\n iframeMode: props.iframeMode,\n serverUser: serverUser,\n nonce: props.nonce,\n targetContainerElement: props.targetContainerElement,\n oauthServer: oauthServer,\n loginSuccessUrl: loginSuccessUrl,\n onUrlChange: (url: string, source?: string) => {\n // Handle different URL change sources\n switch (source) {\n case \"login\":\n console.log(`[NextAuthProvider] Authentication redirect: ${url}`);\n window.location.href = url;\n break;\n case \"login_app\":\n console.log(`[NextAuthProvider] Login app redirect: ${url}`);\n window.location.href = url;\n break;\n default:\n console.log(\n `[NextAuthProvider] Navigating to: ${url} (source: ${source || \"unknown\"})`,\n );\n router.push(url);\n }\n },\n });\n\n // Initialize auth manager with server-provided data\n useEffect(() => {\n const initialize = async () => {\n try {\n const manager = GlobalAuthManager.getInstance();\n\n await manager.initialize(initialConfig);\n } catch (error) {\n console.error(\n \"[NextAuthProvider] Failed to initialize auth manager:\",\n error,\n );\n }\n };\n\n initialize();\n }, [initialConfig, router]);\n\n return (\n <ServerUserContext.Provider value={serverUser}>\n <CivicAuthConfigProvider\n oauthServer={oauthServer}\n clientId={clientId}\n loginSuccessUrl={loginSuccessUrl}\n logoutRedirectUrl={logoutCallbackUrl}\n nonce={props?.nonce}\n challengeUrl={challengeUrl}\n refreshUrl={refreshUrl}\n displayMode={props.displayMode}\n autoRedirect={resolvedConfig.autoRedirect}\n framework=\"nextjs\"\n >\n <AuthStatusProvider>{children}</AuthStatusProvider>\n </CivicAuthConfigProvider>\n </ServerUserContext.Provider>\n );\n};\n"]}
1
+ {"version":3,"file":"NextAuthProviderClient.js","source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,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,KAAK,CAAC,WAAW,EAC9B,YAAY,EAAE,cAAc,CAAC,YAAY,EACzC,SAAS,EAAC,QAAQ,YAElB,KAAC,kBAAkB,cAAE,QAAQ,GAAsB,GAC3B,GACC,CAC9B,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/** @jsxImportSource react */\n\"use client\";\n\n/**\n * Client component for NextAuth provider that receives server-provided user data\n */\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { GlobalAuthManager } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport { AuthStatusProvider } from \"@/shared/providers/AuthStatusContext.js\";\nimport { CivicAuthConfigProvider } from \"@/shared/providers/CivicAuthConfigContext.js\";\nimport { ServerUserContext } from \"./ServerUserContext.js\";\nimport { useInitialAuthConfig } from \"@/nextjs/hooks/useInitialAuthConfig.js\";\nimport type { AuthProviderProps } from \"@/shared/providers/types.js\";\nimport { useEffect } from \"react\";\nimport type { User, OAuthTokens } from \"@/types.js\";\nimport { useRouter } from \"next/navigation.js\";\n\ntype NextCivicAuthProviderProps = Omit<AuthProviderProps, \"clientId\">;\n\nexport interface CivicNextAuthProviderClientProps\n extends NextCivicAuthProviderProps {\n serverUser: User | null;\n serverTokens: OAuthTokens | null;\n redirectOnLogin?: string;\n redirectOnLogout?: string;\n}\n\n// Context to provide server user data immediately to useUser hook\n\nexport const CivicNextAuthProviderClient = ({\n children,\n serverUser,\n serverTokens,\n ...props\n}: CivicNextAuthProviderClientProps) => {\n const router = useRouter();\n const resolvedConfig = resolveAuthConfig();\n const {\n clientId,\n oauthServer,\n loginSuccessUrl,\n challengeUrl,\n refreshUrl,\n logoutCallbackUrl,\n } = resolvedConfig;\n\n // Initialize GlobalAuthManager synchronously with server user data\n // This ensures the server user is available immediately when useUser() is called\n const { initialConfig } = useInitialAuthConfig({\n displayMode: props.displayMode,\n iframeMode: props.iframeMode,\n serverUser: serverUser,\n nonce: props.nonce,\n targetContainerElement: props.targetContainerElement,\n oauthServer: oauthServer,\n loginSuccessUrl: loginSuccessUrl,\n onUrlChange: (url: string, source?: string) => {\n // Handle different URL change sources\n switch (source) {\n case \"login\":\n console.log(`[NextAuthProvider] Authentication redirect: ${url}`);\n window.location.href = url;\n break;\n case \"login_app\":\n console.log(`[NextAuthProvider] Login app redirect: ${url}`);\n window.location.href = url;\n break;\n default:\n console.log(\n `[NextAuthProvider] Navigating to: ${url} (source: ${source || \"unknown\"})`,\n );\n router.push(url);\n }\n },\n });\n\n // Initialize auth manager with server-provided data\n useEffect(() => {\n const initialize = async () => {\n try {\n const manager = GlobalAuthManager.getInstance();\n\n await manager.initialize(initialConfig);\n } catch (error) {\n console.error(\n \"[NextAuthProvider] Failed to initialize auth manager:\",\n error,\n );\n }\n };\n\n initialize();\n }, [initialConfig, router]);\n\n return (\n <ServerUserContext.Provider\n value={{ user: serverUser, tokens: serverTokens }}\n >\n <CivicAuthConfigProvider\n oauthServer={oauthServer}\n clientId={clientId}\n loginSuccessUrl={loginSuccessUrl}\n logoutRedirectUrl={logoutCallbackUrl}\n nonce={props?.nonce}\n challengeUrl={challengeUrl}\n refreshUrl={refreshUrl}\n displayMode={props.displayMode}\n autoRedirect={resolvedConfig.autoRedirect}\n framework=\"nextjs\"\n >\n <AuthStatusProvider>{children}</AuthStatusProvider>\n </CivicAuthConfigProvider>\n </ServerUserContext.Provider>\n );\n};\n"]}
@@ -1,2 +1,7 @@
1
- export declare const ServerUserContext: import("react").Context<import("../../types.js").BaseUser | null>;
1
+ import type { User, OAuthTokens } from "../../types.js";
2
+ export interface ServerAuthData {
3
+ user: User | null;
4
+ tokens: OAuthTokens | null;
5
+ }
6
+ export declare const ServerUserContext: import("react").Context<ServerAuthData | null>;
2
7
  //# sourceMappingURL=ServerUserContext.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServerUserContext.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/ServerUserContext.tsx"],"names":[],"mappings":"AAMA,eAAO,MAAM,iBAAiB,+DAAmC,CAAC"}
1
+ {"version":3,"file":"ServerUserContext.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/ServerUserContext.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAClB,MAAM,EAAE,WAAW,GAAG,IAAI,CAAC;CAC5B;AAED,eAAO,MAAM,iBAAiB,gDAA6C,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ServerUserContext.js","sourceRoot":"","sources":["../../../src/nextjs/providers/ServerUserContext.tsx"],"names":[],"mappings":"AAAA,6BAA6B;AAC7B,YAAY,CAAC;AAEb,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAGtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAc,IAAI,CAAC,CAAC","sourcesContent":["/** @jsxImportSource react */\n\"use client\";\n\nimport { createContext } from \"react\";\nimport type { User } from \"@/types.js\";\n\nexport const ServerUserContext = createContext<User | null>(null);\n"]}
1
+ {"version":3,"file":"ServerUserContext.js","sourceRoot":"","sources":["../../../src/nextjs/providers/ServerUserContext.tsx"],"names":[],"mappings":"AAAA,6BAA6B;AAC7B,YAAY,CAAC;AAEb,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAQtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAwB,IAAI,CAAC,CAAC","sourcesContent":["/** @jsxImportSource react */\n\"use client\";\n\nimport { createContext } from \"react\";\nimport type { User, OAuthTokens } from \"@/types.js\";\n\nexport interface ServerAuthData {\n user: User | null;\n tokens: OAuthTokens | null;\n}\n\nexport const ServerUserContext = createContext<ServerAuthData | null>(null);\n"]}
@@ -230,7 +230,7 @@ export async function handleLogout(request, config) {
230
230
  state: state || undefined,
231
231
  });
232
232
  try {
233
- await civicAuth.clearTokens();
233
+ await clearAuthCookies(resolvedConfigs);
234
234
  // Revalidate current path to update authentication state in server components
235
235
  await revalidateUrlPath(request.url);
236
236
  }
@@ -1 +1 @@
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;AAC5E,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAEnE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AAE5C,MAAM,SAAU,SAAQ,KAAK;IAGT;IAFlB,YACE,OAAe,EACC,SAAiB,GAAG;QAEpC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,WAAM,GAAN,MAAM,CAAc;QAGpC,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;IAC1B,CAAC;CACF;AAED;;GAEG;AACH,MAAM,qBAAqB,GAAG,CAAC,OAAoB,EAAuB,EAAE,CAAC,CAAC;IAC5E,GAAG,EAAE,OAAO,CAAC,GAAG;IAChB,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,C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EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QAEnE,MAAM,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAC/B,OAAO,QAAQ,CAAC;IAClB,CAAC;AACH,CAAC,CAAC;AAEJ;;;GAGG;AACH,KAAK,UAAU,UAAU,CACvB,OAAoB,EACpB,MAAkB;IAElB,MAAM,eAAe,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;IAElD,IAAI,CAAC;QACH,MAAM,EAAE,SAAS,EAAE,GAAG,eAAe,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAEhE,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,UAAU,EAAE,CAAC;QAEhD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,YAAY,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,mBAAmB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAC5E,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 { 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 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 const targetUrl = request.nextUrl.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n // Success: clear the refresh attempt tracking cookie and redirect to target\n const response = NextResponse.redirect(targetUrl);\n response.cookies.delete(\"_civic_last_refresh\");\n return response;\n }\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 const targetUrl = request.nextUrl.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n return NextResponse.redirect(targetUrl);\n }\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\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 civicAuth.clearTokens();\n\n // Revalidate current path to update authentication state in server components\n await revalidateUrlPath(request.url);\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\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 * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\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 \"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\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const isLoggedIn = await civicAuth.isLoggedIn();\n\n if (!isLoggedIn) {\n return NextResponse.json({ error: \"Not authenticated\" }, { status: 401 });\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,CAA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AAO,EAAE,eAAe,CAAC,CAAC;QAEhE,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,UAAU,EAAE,CAAC;QAEhD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,YAAY,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,mBAAmB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAC5E,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 { 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 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 const targetUrl = request.nextUrl.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n // Success: clear the refresh attempt tracking cookie and redirect to target\n const response = NextResponse.redirect(targetUrl);\n response.cookies.delete(\"_civic_last_refresh\");\n return response;\n }\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 const targetUrl = request.nextUrl.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n return NextResponse.redirect(targetUrl);\n }\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\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\n // Revalidate current path to update authentication state in server components\n await revalidateUrlPath(request.url);\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\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 * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n\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 \"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\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const isLoggedIn = await civicAuth.isLoggedIn();\n\n if (!isLoggedIn) {\n return NextResponse.json({ error: \"Not authenticated\" }, { status: 401 });\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":"useUser.d.ts","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAEL,KAAK,gBAAgB,EAEtB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAGjD,MAAM,WAAW,YAAY;IAC3B,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,QAAQ,CAAC,E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extractTokensFromSession } from "../../vanillajs/utils/auth-utils.js";
45
45
  const useUser = (config) => {
46
46
  // Always call context hooks unconditionally (rules of hooks)
47
47
  const sharedContext = useContext(UserContext);
48
- const serverUser = useContext(ServerUserContext);
48
+ const serverAuthData = useContext(ServerUserContext);
49
49
  // State for global manager approach
50
50
  const [globalState, setGlobalState] = useState(null);
51
51
  // Determine which approach to use
@@ -200,13 +200,14 @@ const useUser = (config) => {
200
200
  // ========================================================================
201
201
  // 0. NextJS ServerUserContext (HIGHEST PRIORITY - Fresh server data)
202
202
  // This ensures client components sync with server data after revalidation
203
- if (serverUser !== null) {
203
+ if (serverAuthData !== null) {
204
+ const { user: serverUser, tokens: serverTokens } = serverAuthData;
204
205
  return {
205
206
  user: serverUser,
206
- idToken: null, // Not available with server-only data
207
- accessToken: null, // Not available with server-only data
208
- refreshToken: null, // Not available with server-only data
209
- forwardedTokens: undefined, // Not available with server-only data
207
+ idToken: serverTokens?.idToken || null,
208
+ accessToken: serverTokens?.accessToken || null,
209
+ refreshToken: serverTokens?.refreshToken || null,
210
+ forwardedTokens: serverUser?.forwardedTokens,
210
211
  isLoading: false, // Server data is immediately available
211
212
  authStatus: (serverUser
212
213
  ? "authenticated"
@@ -1 +1 @@
1
- {"version":3,"file":"useUser.js","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,YAAY,CAAC;AACb,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAIhF,OAAO,EACL,iBAAiB,GAGlB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAyC/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,OAAO;YACL,IAAI,EAAE,WAAW,CAAC,IAAsB;YACxC,OAAO,EAAE,YAAY,CAAC,OAAO;YAC7B,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,YAAY,EAAE,YAAY,CAAC,YAAY;YACvC,eAAe,EAAE,YAAY,CAAC,eAAe;YAC7C,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,UAAU,EAAE,WAAW,CAAC,UAAwB;YAChD,KAAK,EAAE,WAAW,CAAC,KAAK;YACxB,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,aAAa;YACtB,yBAAyB,EAAE,+BAA+B;YAC1D,iBAAiB,EAAE,uBAAuB;YAC1C,iBAAiB,EAAE,uBAAuB;YAC1C,WAAW,EAAE,WAAW,CAAC,WAA0B;SACpD,CAAC;IACJ,CAAC;IAED,mEAAmE;IACnE,8FAA8F;IAC9F,OAAO;QACL,IAAI,EAAE,IAAI;QACV,OAAO,EAAE,IAAI;QACb,WAAW,EAAE,IAAI;QACjB,YAAY,EAAE,IAAI;QAClB,eAAe,EAAE,SAAS;QAC1B,SAAS,EAAE,IAAI;QACf,UAAU,EAAE,iBAA+B;QAC3C,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,aAAa;QACtB,yBAAyB,EAAE,+BAA+B;QAC1D,iBAAiB,EAAE,uBAAuB;QAC1C,iBAAiB,EAAE,uBAAuB;QAC1C,WAAW,EAAE,MAAM,EAAE,WAA0B;KAChD,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC","sourcesContent":["/**\n * useUser Hook\n *\n * A comprehensive user session hook that provides full user data including profile information,\n * authentication tokens, and authentication state. Supports generic typing for custom user data.\n *\n * Use this hook when you:\n * - Need access to user profile information (user object)\n * - Need authentication tokens (JWT, access, refresh tokens)\n * - Are working with custom user data types\n * - Need comprehensive user session data\n * - Want backward compatibility with legacy UserContext\n *\n * This hook supports two authentication patterns with automatic fallback:\n * 1. Provider-based (legacy): Uses CivicAuthProvider or CivicNextAuthProvider\n * 2. Provider-free (modern): Direct configuration via useUser(config)\n *\n * Usage Examples:\n *\n * // With provider (existing approach - NextJS/React providers)\n * <CivicAuthProvider clientId=\"...\" config={{ oauthServer: \"...\" }}>\n * const { user, isLoading, signIn } = useUser();\n * </CivicAuthProvider>\n *\n * // Without provider (new approach) - direct configuration\n * const { user, authStatus, signOut } = useUser({\n * clientId: \"your-client-id\",\n * config: { oauthServer: \"https://auth.civic.com/oauth/\" },\n * displayMode: \"iframe\", // or \"redirect\", \"popup\", etc.\n * scopes: [\"openid\", \"profile\", \"email\"],\n * onSignIn: (error) => console.log(\"Sign in completed\", error),\n * onSignOut: () => console.log(\"Sign out completed\")\n * });\n *\n * // Generic typing for custom user data\n * interface CustomUser { customField: string; }\n * const { user } = useUser<CustomUser>(); // user will be User<CustomUser> | null\n */\n\"use client\";\nimport { useContext, useState, useEffect, useCallback, useMemo } from \"react\";\nimport { UserContext } from \"../../shared/providers/UserProvider.js\";\nimport { ServerUserContext } from \"../../nextjs/providers/ServerUserContext.js\";\nimport type { User, ForwardedTokens } from \"../../types.js\";\nimport type { AuthStatus } from \"../../types.js\";\nimport type { DisplayMode } from \"../../types.js\";\nimport {\n GlobalAuthManager,\n type GlobalAuthConfig,\n type GlobalAuthState,\n} from \"../core/GlobalAuthManager.js\";\nimport { extractTokensFromSession } from \"../../vanillajs/utils/auth-utils.js\";\nimport type { VanillaJSDisplayMode } from \"../../vanillajs/auth/types/AuthTypes.js\";\nimport type { IframeMode } from \"../../types.js\";\n\n// Configuration type for signIn and signOut functions\nexport interface SignInConfig {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n clientId?: string;\n redirectUrl?: string;\n logoutRedirectUrl?: string;\n targetContainerElement?: HTMLElement | string;\n scopes?: string[];\n authProcessTimeout?: number;\n preloadIframe?: boolean;\n autoRedirect?: boolean;\n onSignIn?: (error?: Error) => void;\n onSignOut?: () => void;\n onUrlChange?: (url: string, source?: string) => void;\n}\n\nexport interface UserContextType<\n T extends Record<string, unknown> = Record<string, never>,\n> {\n user: User<T> | null;\n idToken?: string | null;\n accessToken?: string | null;\n refreshToken?: string | null;\n forwardedTokens?: ForwardedTokens;\n isLoading: boolean;\n authStatus: AuthStatus;\n error: Error | null;\n signIn: (config?: SignInConfig) => Promise<{ user: User<T> }>;\n signOut: (config?: SignInConfig) => Promise<void>;\n // Preloading methods\n isAuthenticationPreloaded: () => boolean;\n setPreloadEnabled: (enabled: boolean) => void;\n getPreloadEnabled: () => boolean;\n displayMode?: DisplayMode;\n}\n\nconst useUser = <T extends Record<string, unknown> = Record<string, never>>(\n config?: GlobalAuthConfig,\n): UserContextType<T> => {\n // Always call context hooks unconditionally (rules of hooks)\n const sharedContext = useContext(UserContext);\n const serverUser = useContext(ServerUserContext);\n\n // State for global manager approach\n const [globalState, setGlobalState] = useState<GlobalAuthState | null>(null);\n\n // Determine which approach to use\n const hasProviderContext = sharedContext;\n const shouldUseGlobal = !hasProviderContext;\n\n // Helper to merge config overrides with current manager config\n const createConfigWithOverrides = useCallback(\n (overrides: SignInConfig): GlobalAuthConfig => {\n const manager = GlobalAuthManager.getInstance();\n const currentConfig = manager.getConfig();\n\n // Use current config from manager, or fall back to initial config if manager not initialized\n const baseConfig = currentConfig || config || {};\n\n return {\n ...baseConfig, // Complete current config from GlobalAuthManager\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 ...(overrides.scopes && { scopes: overrides.scopes }),\n ...(overrides.authProcessTimeout && {\n authProcessTimeout: overrides.authProcessTimeout,\n }),\n ...(overrides.preloadIframe !== undefined && {\n preloadIframe: overrides.preloadIframe,\n }),\n ...(overrides.autoRedirect !== undefined && {\n autoRedirect: overrides.autoRedirect,\n }),\n ...(overrides.onSignIn && { onSignIn: overrides.onSignIn }),\n ...(overrides.onSignOut && { onSignOut: overrides.onSignOut }),\n ...(overrides.onUrlChange && { onUrlChange: overrides.onUrlChange }),\n };\n },\n [config],\n );\n\n // Initialize global manager if no provider context\n useEffect(() => {\n if (!shouldUseGlobal) return;\n\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, initialize with it\n if (config) {\n const initializeAuth = async () => {\n try {\n await manager.initialize(config);\n } catch (error) {\n console.error(\"Failed to initialize auth:\", error);\n }\n };\n initializeAuth();\n }\n\n // Subscribe to state changes\n const unsubscribe = manager.subscribe((newState) => {\n setGlobalState(newState);\n });\n\n // Get current state\n setGlobalState(manager.getState());\n\n return unsubscribe;\n }, [shouldUseGlobal, config]);\n\n // Global manager sign in/out functions\n const globalSignIn = useCallback(\n async (signInConfig?: SignInConfig) => {\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, reinitialize with merged config\n if (signInConfig) {\n const mergedConfig = createConfigWithOverrides(signInConfig);\n await manager.initialize(mergedConfig);\n }\n\n await manager.signIn();\n\n // Get the user after sign in\n const state = manager.getState();\n if (!state.user) {\n throw new Error(\"Authentication succeeded but no user was returned\");\n }\n\n return { user: state.user as User<T> };\n },\n [createConfigWithOverrides],\n );\n\n const globalSignOut = useCallback(\n async (signOutConfig?: SignInConfig) => {\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, reinitialize with merged config\n if (signOutConfig) {\n const mergedConfig = createConfigWithOverrides(signOutConfig);\n await manager.initialize(mergedConfig);\n }\n\n await manager.signOut();\n },\n [createConfigWithOverrides],\n );\n\n // Global manager preloading functions\n const globalIsAuthenticationPreloaded = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.isAuthenticationPreloaded();\n }, []);\n\n const globalSetPreloadEnabled = useCallback((enabled: boolean) => {\n const manager = GlobalAuthManager.getInstance();\n manager.setPreloadEnabled(enabled);\n }, []);\n\n const globalGetPreloadEnabled = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.getPreloadEnabled();\n }, []);\n\n // Extract tokens from global state\n const globalTokens = useMemo(() => {\n return extractTokensFromSession(globalState?.session || null);\n }, [globalState?.session]);\n\n // Create wrapper functions for different signIn signatures\n const wrapSharedSignIn = useCallback(\n async (sharedConfig?: SignInConfig): Promise<{ user: User<T> }> => {\n if (sharedContext) {\n // Note: Shared context doesn't support config overrides yet\n // This is a limitation of the legacy provider system\n if (sharedConfig) {\n console.warn(\n \"Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.\",\n );\n }\n\n await sharedContext.signIn(); // This returns void\n // Get user from context after sign in\n if (sharedContext.user) {\n return { user: sharedContext.user as User<T> };\n }\n\n // We don't return a user yet in nextjs until the next refactor\n return { user: null as unknown as User<T> };\n }\n throw new Error(\"Shared context not available\");\n },\n [sharedContext],\n );\n\n // Shared context preloading stubs (not implemented for legacy context)\n const sharedIsAuthenticationPreloaded = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n const sharedSetPreloadEnabled = useCallback((_enabled: boolean) => {\n console.warn(\n \"Preloading not available with legacy UserContext. Use GlobalAuthManager instead.\",\n _enabled,\n );\n }, []);\n\n const sharedGetPreloadEnabled = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n // Create wrapper for sharedContext signOut with config support\n const wrapSharedSignOut = useCallback(\n async (sharedConfig?: SignInConfig): Promise<void> => {\n if (sharedContext) {\n // Note: Shared context doesn't support config overrides yet\n if (sharedConfig) {\n console.warn(\n \"Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.\",\n );\n }\n\n await sharedContext.signOut();\n } else {\n throw new Error(\"Shared context not available\");\n }\n },\n [sharedContext],\n );\n\n // ========================================================================\n // FALLBACK PRIORITY SYSTEM - Three authentication context approaches\n // ========================================================================\n\n // 0. NextJS ServerUserContext (HIGHEST PRIORITY - Fresh server data)\n // This ensures client components sync with server data after revalidation\n if (serverUser !== null) {\n return {\n user: serverUser as User<T> | null,\n idToken: null, // Not available with server-only data\n accessToken: null, // Not available with server-only data\n refreshToken: null, // Not available with server-only data\n forwardedTokens: undefined, // Not available with server-only data\n isLoading: false, // Server data is immediately available\n authStatus: (serverUser\n ? \"authenticated\"\n : \"unauthenticated\") as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n }\n\n // 1. DEPRECATED UserContext (ACTIVE - Used by NextJS)\n // Framework-agnostic shared context from UserProvider\n // Location: shared/providers/UserProvider.tsx\n // Usage: NextJS example uses CivicNextAuthProvider → UserProvider → UserContext\n if (sharedContext) {\n return {\n user: sharedContext.user as User<T> | null,\n idToken: sharedContext.idToken,\n accessToken: sharedContext.accessToken,\n refreshToken: undefined, // Not available in shared context\n forwardedTokens: sharedContext.forwardedTokens,\n isLoading: sharedContext.isLoading,\n authStatus: sharedContext.authStatus,\n error: sharedContext.error,\n signIn: wrapSharedSignIn,\n signOut: wrapSharedSignOut,\n isAuthenticationPreloaded: sharedIsAuthenticationPreloaded,\n setPreloadEnabled: sharedSetPreloadEnabled,\n getPreloadEnabled: sharedGetPreloadEnabled,\n displayMode: sharedContext.displayMode,\n };\n }\n\n // 2. GlobalAuthManager (MODERN - Provider-free approach)\n // Singleton-based state management, eliminates need for React providers\n // Location: reactjs/core/GlobalAuthManager.ts\n // Usage: React example uses CivicAuthProvider → GlobalAuthManager internally\n // Can also be used directly: useUser({ clientId: \"...\", config: {...} })\n if (globalState) {\n return {\n user: globalState.user as User<T> | null,\n idToken: globalTokens.idToken,\n accessToken: globalTokens.accessToken,\n refreshToken: globalTokens.refreshToken,\n forwardedTokens: globalTokens.forwardedTokens,\n isLoading: globalState.isLoading,\n authStatus: globalState.authStatus as AuthStatus,\n error: globalState.error,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: globalState.displayMode as DisplayMode,\n };\n }\n\n // If no context and no global state, provide default loading state\n // This happens when CivicAuthProvider is present but GlobalAuthManager hasn't initialized yet\n return {\n user: null,\n idToken: null,\n accessToken: null,\n refreshToken: null,\n forwardedTokens: undefined,\n isLoading: true,\n authStatus: \"unauthenticated\" as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n};\n\nexport { useUser };\n"]}
1
+ {"version":3,"file":"useUser.js","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,YAAY,CAAC;AACb,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAIhF,OAAO,EACL,iBAAiB,GAGlB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AA8C/E,MAAM,OAAO,GAAG,CACd,MAAyB,EACL,EAAE;IACtB,6DAA6D;IAC7D,MAAM,aAAa,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9C,MAAM,cAAc,GAAG,UAAU,CAAC,iBAAiB,CAAC,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O,EAAE,YAAY,CAAC,OAAO;YAC7B,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,YAAY,EAAE,YAAY,CAAC,YAAY;YACvC,eAAe,EAAE,YAAY,CAAC,eAAe;YAC7C,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,UAAU,EAAE,WAAW,CAAC,UAAwB;YAChD,KAAK,EAAE,WAAW,CAAC,KAAK;YACxB,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,aAAa;YACtB,yBAAyB,EAAE,+BAA+B;YAC1D,iBAAiB,EAAE,uBAAuB;YAC1C,iBAAiB,EAAE,uBAAuB;YAC1C,WAAW,EAAE,WAAW,CAAC,WAA0B;SACpD,CAAC;IACJ,CAAC;IAED,mEAAmE;IACnE,8FAA8F;IAC9F,OAAO;QACL,IAAI,EAAE,IAAI;QACV,OAAO,EAAE,IAAI;QACb,WAAW,EAAE,IAAI;QACjB,YAAY,EAAE,IAAI;QAClB,eAAe,EAAE,SAAS;QAC1B,SAAS,EAAE,IAAI;QACf,UAAU,EAAE,iBAA+B;QAC3C,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,aAAa;QACtB,yBAAyB,EAAE,+BAA+B;QAC1D,iBAAiB,EAAE,uBAAuB;QAC1C,iBAAiB,EAAE,uBAAuB;QAC1C,WAAW,EAAE,MAAM,EAAE,WAA0B;KAChD,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC","sourcesContent":["/**\n * useUser Hook\n *\n * A comprehensive user session hook that provides full user data including profile information,\n * authentication tokens, and authentication state. Supports generic typing for custom user data.\n *\n * Use this hook when you:\n * - Need access to user profile information (user object)\n * - Need authentication tokens (JWT, access, refresh tokens)\n * - Are working with custom user data types\n * - Need comprehensive user session data\n * - Want backward compatibility with legacy UserContext\n *\n * This hook supports two authentication patterns with automatic fallback:\n * 1. Provider-based (legacy): Uses CivicAuthProvider or CivicNextAuthProvider\n * 2. Provider-free (modern): Direct configuration via useUser(config)\n *\n * Usage Examples:\n *\n * // With provider (existing approach - NextJS/React providers)\n * <CivicAuthProvider clientId=\"...\" config={{ oauthServer: \"...\" }}>\n * const { user, isLoading, signIn } = useUser();\n * </CivicAuthProvider>\n *\n * // Without provider (new approach) - direct configuration\n * const { user, authStatus, signOut } = useUser({\n * clientId: \"your-client-id\",\n * config: { oauthServer: \"https://auth.civic.com/oauth/\" },\n * displayMode: \"iframe\", // or \"redirect\", \"popup\", etc.\n * scopes: [\"openid\", \"profile\", \"email\"],\n * onSignIn: (error) => console.log(\"Sign in completed\", error),\n * onSignOut: () => console.log(\"Sign out completed\")\n * });\n *\n * // Generic typing for custom user data\n * interface CustomUser { customField: string; }\n * const { user } = useUser<CustomUser>(); // user will be User<CustomUser> | null\n */\n\"use client\";\nimport { useContext, useState, useEffect, useCallback, useMemo } from \"react\";\nimport { UserContext } from \"../../shared/providers/UserProvider.js\";\nimport { ServerUserContext } from \"../../nextjs/providers/ServerUserContext.js\";\nimport type { User, ForwardedTokens } from \"../../types.js\";\nimport type { AuthStatus } from \"../../types.js\";\nimport type { DisplayMode } from \"../../types.js\";\nimport {\n GlobalAuthManager,\n type GlobalAuthConfig,\n type GlobalAuthState,\n} from \"../core/GlobalAuthManager.js\";\nimport { extractTokensFromSession } from \"../../vanillajs/utils/auth-utils.js\";\nimport type { VanillaJSDisplayMode } from \"../../vanillajs/auth/types/AuthTypes.js\";\nimport type { IframeMode } from \"../../types.js\";\n\n// Type for server user data that may include forwardedTokens from session storage\ntype ServerUserWithTokens<\n T extends Record<string, unknown> = Record<string, never>,\n> = User<T> & { forwardedTokens?: ForwardedTokens };\n\n// Configuration type for signIn and signOut functions\nexport interface SignInConfig {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n clientId?: string;\n redirectUrl?: string;\n logoutRedirectUrl?: string;\n targetContainerElement?: HTMLElement | string;\n scopes?: string[];\n authProcessTimeout?: number;\n preloadIframe?: boolean;\n autoRedirect?: boolean;\n onSignIn?: (error?: Error) => void;\n onSignOut?: () => void;\n onUrlChange?: (url: string, source?: string) => void;\n}\n\nexport interface UserContextType<\n T extends Record<string, unknown> = Record<string, never>,\n> {\n user: User<T> | null;\n idToken?: string | null;\n accessToken?: string | null;\n refreshToken?: string | null;\n forwardedTokens?: ForwardedTokens;\n isLoading: boolean;\n authStatus: AuthStatus;\n error: Error | null;\n signIn: (config?: SignInConfig) => Promise<{ user: User<T> }>;\n signOut: (config?: SignInConfig) => Promise<void>;\n // Preloading methods\n isAuthenticationPreloaded: () => boolean;\n setPreloadEnabled: (enabled: boolean) => void;\n getPreloadEnabled: () => boolean;\n displayMode?: DisplayMode;\n}\n\nconst useUser = <T extends Record<string, unknown> = Record<string, never>>(\n config?: GlobalAuthConfig,\n): UserContextType<T> => {\n // Always call context hooks unconditionally (rules of hooks)\n const sharedContext = useContext(UserContext);\n const serverAuthData = useContext(ServerUserContext);\n\n // State for global manager approach\n const [globalState, setGlobalState] = useState<GlobalAuthState | null>(null);\n\n // Determine which approach to use\n const hasProviderContext = sharedContext;\n const shouldUseGlobal = !hasProviderContext;\n\n // Helper to merge config overrides with current manager config\n const createConfigWithOverrides = useCallback(\n (overrides: SignInConfig): GlobalAuthConfig => {\n const manager = GlobalAuthManager.getInstance();\n const currentConfig = manager.getConfig();\n\n // Use current config from manager, or fall back to initial config if manager not initialized\n const baseConfig = currentConfig || config || {};\n\n return {\n ...baseConfig, // Complete current config from GlobalAuthManager\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 ...(overrides.scopes && { scopes: overrides.scopes }),\n ...(overrides.authProcessTimeout && {\n authProcessTimeout: overrides.authProcessTimeout,\n }),\n ...(overrides.preloadIframe !== undefined && {\n preloadIframe: overrides.preloadIframe,\n }),\n ...(overrides.autoRedirect !== undefined && {\n autoRedirect: overrides.autoRedirect,\n }),\n ...(overrides.onSignIn && { onSignIn: overrides.onSignIn }),\n ...(overrides.onSignOut && { onSignOut: overrides.onSignOut }),\n ...(overrides.onUrlChange && { onUrlChange: overrides.onUrlChange }),\n };\n },\n [config],\n );\n\n // Initialize global manager if no provider context\n useEffect(() => {\n if (!shouldUseGlobal) return;\n\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, initialize with it\n if (config) {\n const initializeAuth = async () => {\n try {\n await manager.initialize(config);\n } catch (error) {\n console.error(\"Failed to initialize auth:\", error);\n }\n };\n initializeAuth();\n }\n\n // Subscribe to state changes\n const unsubscribe = manager.subscribe((newState) => {\n setGlobalState(newState);\n });\n\n // Get current state\n setGlobalState(manager.getState());\n\n return unsubscribe;\n }, [shouldUseGlobal, config]);\n\n // Global manager sign in/out functions\n const globalSignIn = useCallback(\n async (signInConfig?: SignInConfig) => {\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, reinitialize with merged config\n if (signInConfig) {\n const mergedConfig = createConfigWithOverrides(signInConfig);\n await manager.initialize(mergedConfig);\n }\n\n await manager.signIn();\n\n // Get the user after sign in\n const state = manager.getState();\n if (!state.user) {\n throw new Error(\"Authentication succeeded but no user was returned\");\n }\n\n return { user: state.user as User<T> };\n },\n [createConfigWithOverrides],\n );\n\n const globalSignOut = useCallback(\n async (signOutConfig?: SignInConfig) => {\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, reinitialize with merged config\n if (signOutConfig) {\n const mergedConfig = createConfigWithOverrides(signOutConfig);\n await manager.initialize(mergedConfig);\n }\n\n await manager.signOut();\n },\n [createConfigWithOverrides],\n );\n\n // Global manager preloading functions\n const globalIsAuthenticationPreloaded = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.isAuthenticationPreloaded();\n }, []);\n\n const globalSetPreloadEnabled = useCallback((enabled: boolean) => {\n const manager = GlobalAuthManager.getInstance();\n manager.setPreloadEnabled(enabled);\n }, []);\n\n const globalGetPreloadEnabled = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.getPreloadEnabled();\n }, []);\n\n // Extract tokens from global state\n const globalTokens = useMemo(() => {\n return extractTokensFromSession(globalState?.session || null);\n }, [globalState?.session]);\n\n // Create wrapper functions for different signIn signatures\n const wrapSharedSignIn = useCallback(\n async (sharedConfig?: SignInConfig): Promise<{ user: User<T> }> => {\n if (sharedContext) {\n // Note: Shared context doesn't support config overrides yet\n // This is a limitation of the legacy provider system\n if (sharedConfig) {\n console.warn(\n \"Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.\",\n );\n }\n\n await sharedContext.signIn(); // This returns void\n // Get user from context after sign in\n if (sharedContext.user) {\n return { user: sharedContext.user as User<T> };\n }\n\n // We don't return a user yet in nextjs until the next refactor\n return { user: null as unknown as User<T> };\n }\n throw new Error(\"Shared context not available\");\n },\n [sharedContext],\n );\n\n // Shared context preloading stubs (not implemented for legacy context)\n const sharedIsAuthenticationPreloaded = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n const sharedSetPreloadEnabled = useCallback((_enabled: boolean) => {\n console.warn(\n \"Preloading not available with legacy UserContext. Use GlobalAuthManager instead.\",\n _enabled,\n );\n }, []);\n\n const sharedGetPreloadEnabled = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n // Create wrapper for sharedContext signOut with config support\n const wrapSharedSignOut = useCallback(\n async (sharedConfig?: SignInConfig): Promise<void> => {\n if (sharedContext) {\n // Note: Shared context doesn't support config overrides yet\n if (sharedConfig) {\n console.warn(\n \"Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.\",\n );\n }\n\n await sharedContext.signOut();\n } else {\n throw new Error(\"Shared context not available\");\n }\n },\n [sharedContext],\n );\n\n // ========================================================================\n // FALLBACK PRIORITY SYSTEM - Three authentication context approaches\n // ========================================================================\n\n // 0. NextJS ServerUserContext (HIGHEST PRIORITY - Fresh server data)\n // This ensures client components sync with server data after revalidation\n if (serverAuthData !== null) {\n const { user: serverUser, tokens: serverTokens } = serverAuthData;\n\n return {\n user: serverUser as User<T> | null,\n idToken: serverTokens?.idToken || null,\n accessToken: serverTokens?.accessToken || null,\n refreshToken: serverTokens?.refreshToken || null,\n forwardedTokens: (serverUser as ServerUserWithTokens<T>)?.forwardedTokens,\n isLoading: false, // Server data is immediately available\n authStatus: (serverUser\n ? \"authenticated\"\n : \"unauthenticated\") as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n }\n\n // 1. DEPRECATED UserContext (ACTIVE - Used by NextJS)\n // Framework-agnostic shared context from UserProvider\n // Location: shared/providers/UserProvider.tsx\n // Usage: NextJS example uses CivicNextAuthProvider → UserProvider → UserContext\n if (sharedContext) {\n return {\n user: sharedContext.user as User<T> | null,\n idToken: sharedContext.idToken,\n accessToken: sharedContext.accessToken,\n refreshToken: undefined, // Not available in shared context\n forwardedTokens: sharedContext.forwardedTokens,\n isLoading: sharedContext.isLoading,\n authStatus: sharedContext.authStatus,\n error: sharedContext.error,\n signIn: wrapSharedSignIn,\n signOut: wrapSharedSignOut,\n isAuthenticationPreloaded: sharedIsAuthenticationPreloaded,\n setPreloadEnabled: sharedSetPreloadEnabled,\n getPreloadEnabled: sharedGetPreloadEnabled,\n displayMode: sharedContext.displayMode,\n };\n }\n\n // 2. GlobalAuthManager (MODERN - Provider-free approach)\n // Singleton-based state management, eliminates need for React providers\n // Location: reactjs/core/GlobalAuthManager.ts\n // Usage: React example uses CivicAuthProvider → GlobalAuthManager internally\n // Can also be used directly: useUser({ clientId: \"...\", config: {...} })\n if (globalState) {\n return {\n user: globalState.user as User<T> | null,\n idToken: globalTokens.idToken,\n accessToken: globalTokens.accessToken,\n refreshToken: globalTokens.refreshToken,\n forwardedTokens: globalTokens.forwardedTokens,\n isLoading: globalState.isLoading,\n authStatus: globalState.authStatus as AuthStatus,\n error: globalState.error,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: globalState.displayMode as DisplayMode,\n };\n }\n\n // If no context and no global state, provide default loading state\n // This happens when CivicAuthProvider is present but GlobalAuthManager hasn't initialized yet\n return {\n user: null,\n idToken: null,\n accessToken: null,\n refreshToken: null,\n forwardedTokens: undefined,\n isLoading: true,\n authStatus: \"unauthenticated\" as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n};\n\nexport { useUser };\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "@civic/auth:0.10.0-beta.5";
1
+ export declare const VERSION = "@civic/auth:0.10.0-beta.6";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
1
  // This is an auto-generated file. Do not edit.
2
- export const VERSION = "@civic/auth:0.10.0-beta.5";
2
+ export const VERSION = "@civic/auth:0.10.0-beta.6";
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAE/C,MAAM,CAAC,MAAM,OAAO,GAAG,2BAA2B,CAAC","sourcesContent":["// This is an auto-generated file. Do not edit.\n\nexport const VERSION = \"@civic/auth:0.10.0-beta.5\";\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAE/C,MAAM,CAAC,MAAM,OAAO,GAAG,2BAA2B,CAAC","sourcesContent":["// This is an auto-generated file. Do not edit.\n\nexport const VERSION = \"@civic/auth:0.10.0-beta.6\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@civic/auth",
3
- "version": "0.10.0-beta.5",
3
+ "version": "0.10.0-beta.6",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",