@civic/auth 0.12.0 → 0.13.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/dist/nextjs/config.d.ts +19 -0
  3. package/dist/nextjs/config.d.ts.map +1 -1
  4. package/dist/nextjs/config.js +5 -0
  5. package/dist/nextjs/config.js.map +1 -1
  6. package/dist/nextjs/hooks/useInitialAuthConfig.d.ts.map +1 -1
  7. package/dist/nextjs/hooks/useInitialAuthConfig.js +5 -4
  8. package/dist/nextjs/hooks/useInitialAuthConfig.js.map +1 -1
  9. package/dist/nextjs/routeHandler.d.ts.map +1 -1
  10. package/dist/nextjs/routeHandler.js +57 -7
  11. package/dist/nextjs/routeHandler.js.map +1 -1
  12. package/dist/nextjs/utils.d.ts.map +1 -1
  13. package/dist/nextjs/utils.js +20 -2
  14. package/dist/nextjs/utils.js.map +1 -1
  15. package/dist/reactjs/core/GlobalAuthManager.d.ts.map +1 -1
  16. package/dist/reactjs/core/GlobalAuthManager.js +3 -1
  17. package/dist/reactjs/core/GlobalAuthManager.js.map +1 -1
  18. package/dist/server/session.d.ts.map +1 -1
  19. package/dist/server/session.js +21 -10
  20. package/dist/server/session.js.map +1 -1
  21. package/dist/shared/lib/cookieConfig.d.ts.map +1 -1
  22. package/dist/shared/lib/cookieConfig.js +6 -1
  23. package/dist/shared/lib/cookieConfig.js.map +1 -1
  24. package/dist/shared/lib/types.d.ts +10 -2
  25. package/dist/shared/lib/types.d.ts.map +1 -1
  26. package/dist/shared/lib/types.js +9 -0
  27. package/dist/shared/lib/types.js.map +1 -1
  28. package/dist/shared/lib/util.d.ts +19 -0
  29. package/dist/shared/lib/util.d.ts.map +1 -1
  30. package/dist/shared/lib/util.js +118 -0
  31. package/dist/shared/lib/util.js.map +1 -1
  32. package/dist/shared/version.d.ts +1 -1
  33. package/dist/shared/version.d.ts.map +1 -1
  34. package/dist/shared/version.js +1 -1
  35. package/dist/shared/version.js.map +1 -1
  36. package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -1
  37. package/dist/vanillajs/auth/handlers/MessageHandler.js +3 -1
  38. package/dist/vanillajs/auth/handlers/MessageHandler.js.map +1 -1
  39. package/dist/vanillajs/types/index.d.ts +4 -0
  40. package/dist/vanillajs/types/index.d.ts.map +1 -1
  41. package/dist/vanillajs/types/index.js.map +1 -1
  42. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/server/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,SAAS,GACV,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,OAAO,IAAI,iBAAiB,EAC5B,SAAS,IAAI,mBAAmB,GACjC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,WAAW,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AACxF,OAAO,EACL,mBAAmB,EACnB,4BAA4B,GAC7B,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAChF,OAAO,EAAE,SAAS,EAAmB,MAAM,MAAM,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAA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AAI;gBACb,IAAI;aACL;SACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,4BAA4B,CAClC,IAAU,EACV,WAAoB;QAEpB,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC9D,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC;QAE1C,kCAAkC;QAClC,MAAM,WAAW,GACf,WAAW;YACX,IAAI,CAAC,UAAU,CAAC,WAAW;YAC3B,IAAI,CAAC,UAAU,CAAC,qBAAqB;YACrC,GAAG,CAAC;QAEN,OAAO;;;;;;;;;qFAS0E,WAAW;YACpF,2BAA2B;;;;;;;;;;;0BAWb,WAAW;;;;;;;;;;;;6BAYR,QAAQ;;0BAEX,WAAW;;;;;;;;;;;;;;;8DAeyB,WAAW;sCACnC,WAAW;;;;;KAK5C,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,8BAA8B,GAAG,CACvC,WAAmB,EACnB,WAAoB,EACZ,EAAE;QACV,MAAM,mBAAmB,GAAG,WAAW;YACrC,CAAC,CAAC,oBAAoB,kBAAkB,CAAC,WAAW,CAAC,EAAE;YACvD,CAAC,CAAC,EAAE,CAAC;QAEP,OAAO;;;;;;;;;;;2BAWgB,WAAW,qEAAqE,mBAAmB;;;;;;;;;;;;;;CAc7H,CAAC;IACA,CAAC,CAAC;CACH","sourcesContent":["import {\n type OAuthTokens,\n type User,\n type EmptyObject,\n type UnknownObject,\n type OIDCTokenResponseBody,\n tokenKeys,\n} from \"@/types.js\";\nimport type { AuthConfig } from \"@/server/config.js\";\nimport {\n getUser as getUserFromShared,\n getTokens as getTokensFromShared,\n} from \"@/shared/lib/session.js\";\nimport { clearTokens as clearTokensUtil } from \"@/shared/lib/util.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { buildLoginUrl } from \"@/server/login.js\";\nimport { buildLogoutRedirectUrl } from \"@/server/logout.js\";\nimport {\n TOKEN_EXCHANGE_SUCCESS_TEXT,\n TOKEN_EXCHANGE_TRIGGER_TEXT,\n} from \"@/constants.js\";\nimport { refreshTokens } from \"@/server/refresh.js\";\nimport { getVersion } from \"@/shared/index.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport {\n DEFAULT_AUTH_SERVER,\n JWT_PAYLOAD_KNOWN_CLAIM_KEYS,\n} from \"@/constants.js\";\nimport type { AuthenticationResolver } from \"@/services/types.js\";\nimport { displayModeFromState, loginSuccessUrlFromState } from \"@/lib/oauth.js\";\nimport { decodeJwt, type JWTPayload } from \"jose\";\nimport { generateOauthLogoutUrl } from \"@/shared/lib/util.js\";\nimport { CodeVerifier } from \"@/shared/lib/types.js\";\nimport { getBackendEndpoints, resolveEndpointUrl } from \"@/shared/lib/util.js\";\nimport type { CookieStorage } from \"./index.js\";\nimport { loggers } from \"@/lib/logger.js\";\n\n// Generic request interface for framework-agnostic URL detection\nexport type UrlDetectionRequest = {\n url: string;\n headers: Record<string, string | string[] | undefined>;\n searchParams: {\n get(name: string): string | null;\n };\n cookies: {\n get(name: string): { value: string } | undefined;\n };\n};\n\nexport type HandleCallbackRequest = {\n headers: {\n [key: string]: string | string[] | undefined;\n referer?: string;\n origin?: string;\n \"user-agent\"?: string;\n accept?: string;\n \"sec-fetch-dest\"?: string;\n };\n url?: string;\n};\n\nexport type HandleCallbackParams = {\n code: string;\n state: string;\n req: HandleCallbackRequest;\n};\n\n// Function to omit keys from an object\nconst omitKeys = <K extends keyof T, T extends Record<string, unknown>>(\n keys: K[],\n obj: T,\n): Omit<T, K> => {\n const result = { ...obj };\n keys.forEach((key) => {\n delete result[key];\n });\n return result;\n};\n\n/**\n * Helper to detect if this is a same-domain callback request (for iframe workaround)\n */\nconst isSameDomainCallback = (req: HandleCallbackRequest): boolean => {\n if (!req.url) return false;\n return req.url.includes(\"sameDomainCallback=true\");\n};\n\n/**\n * Extract user information directly from OIDC tokens\n * @param tokens The OIDC tokens response\n * @returns The user object or null if no valid ID token\n */\nfunction getUserFromTokens<T extends UnknownObject = EmptyObject>(\n tokens: OIDCTokenResponseBody,\n): User<T> | null {\n if (!tokens.id_token) return null;\n\n const parsedToken = decodeJwt(tokens.id_token) as JWTPayload & T;\n if (!parsedToken.sub) return null;\n\n // set the user ID from the token sub\n const userWithAdditionalTokenFields = {\n ...(parsedToken as T),\n id: parsedToken.sub,\n };\n\n // Remove the token keys from the user object to stop it getting too large\n return omitKeys(\n [...JWT_PAYLOAD_KNOWN_CLAIM_KEYS, ...tokenKeys],\n userWithAdditionalTokenFields,\n ) as User<T>;\n}\n\n/**\n * CivicAuth is the main entry point for server-side authentication operations.\n * It provides a unified interface to all the authentication functions.\n */\nexport class CivicAuth {\n _authResolver: AuthenticationResolver | null = null;\n constructor(\n readonly storage: CookieStorage,\n readonly authConfig: AuthConfig,\n ) {}\n\n get oauthServer(): string {\n return this.authConfig.oauthServer || DEFAULT_AUTH_SERVER;\n }\n\n async getAuthResolver(): Promise<AuthenticationResolver> {\n if (this._authResolver) {\n loggers.server.debug(\"Reusing existing auth resolver\", this.authConfig);\n return Promise.resolve(this._authResolver);\n }\n loggers.server.debug(\"Creating new auth resolver\", this.authConfig);\n this._authResolver = await ServerAuthenticationResolver.build(\n {\n ...this.authConfig,\n oauthServer: this.oauthServer,\n },\n this.storage,\n );\n return this._authResolver;\n }\n /**\n * Gets the authenticated user with token validation\n * @returns The user object if authenticated, null otherwise\n */\n async getUser<\n T extends UnknownObject = EmptyObject,\n >(): Promise<User<T> | null> {\n const resolver = await this.getAuthResolver();\n\n try {\n // Validate the session before returning the user\n const session = await resolver.validateExistingSession();\n if (!session?.authenticated) {\n return null;\n }\n\n // If session is valid, use the shared implementation to get the user\n return getUserFromShared<T>(this.storage);\n } catch (error) {\n console.error(\"Token validation failed during getUser\", error);\n return null;\n }\n }\n\n /**\n * Gets the authentication tokens with token validation\n * @returns The tokens if authenticated, null otherwise\n */\n async getTokens(): Promise<OAuthTokens | null> {\n const resolver = await this.getAuthResolver();\n\n try {\n // Validate the session before returning the tokens\n const session = await resolver.validateExistingSession();\n\n if (!session?.authenticated) {\n return null;\n }\n\n // If session is valid, use the shared implementation to get the tokens\n const tokens = await getTokensFromShared(this.storage);\n return tokens;\n } catch (error) {\n console.error(\"❌ Token validation failed during getTokens\", error);\n return null;\n }\n }\n\n /**\n * Resolve an OAuth access code to a set of OIDC tokens\n * @param code The access code from the query parameter\n * @param state The OAuth state parameter\n * @returns OIDC tokens\n */\n async resolveOAuthAccessCode(\n code: string,\n state: string,\n ): Promise<OIDCTokenResponseBody> {\n return resolveOAuthAccessCode(code, state, this.storage, this.authConfig);\n }\n\n /**\n * Check if the user is currently logged in\n * @returns true if logged in, false otherwise\n */\n async isLoggedIn(): Promise<boolean> {\n const resolver = await this.getAuthResolver();\n const session = await resolver.validateExistingSession();\n return session?.authenticated ?? false;\n }\n\n /**\n * Build a login URL to redirect the user to\n * @param options Additional options for building the login URL\n * @returns The login URL\n */\n async buildLoginUrl(options?: {\n scopes?: string[];\n state?: string;\n nonce?: string;\n }): Promise<URL> {\n return buildLoginUrl(\n {\n ...this.authConfig,\n scopes: options?.scopes,\n state: options?.state,\n nonce: options?.nonce,\n framework: \"server\",\n sdkVersion: getVersion(),\n },\n this.storage,\n );\n }\n\n /**\n * Build a logout URL to redirect the user to\n * @param options Additional options for building the logout URL\n * @returns The logout URL\n */\n async buildLogoutRedirectUrl(options?: {\n scopes?: string[];\n state?: string;\n }): Promise<URL> {\n // Check if this is backend integration mode (loginUrl provided)\n if (this.authConfig.loginUrl) {\n // Backend integration mode: redirect to backend logout endpoint\n // This matches the vanilla client's logout logic for backend integration\n const backendUrl = new URL(this.authConfig.loginUrl).origin;\n const endpoints = getBackendEndpoints(this.authConfig.backendEndpoints);\n const backendLogoutUrl = resolveEndpointUrl(backendUrl, endpoints.logout);\n\n const logoutUrl = new URL(backendLogoutUrl);\n\n // Include logoutRedirectUrl as query parameter if configured\n if (this.authConfig.postLogoutRedirectUrl) {\n logoutUrl.searchParams.set(\n \"logoutRedirectUrl\",\n this.authConfig.postLogoutRedirectUrl,\n );\n }\n\n // Include state if provided\n if (options?.state) {\n logoutUrl.searchParams.set(\"state\", options.state);\n }\n\n return logoutUrl;\n }\n\n // Standard OAuth flow - redirect to OAuth provider's logout endpoint\n try {\n // Use the shared getTokens function directly - this bypasses session validation\n // since for logout we just need the raw ID token, not validated tokens\n const tokens = await getTokensFromShared(this.storage);\n\n if (tokens?.idToken) {\n // Ensure clientId is present for OAuth operations\n if (!this.authConfig.clientId) {\n throw new Error(\"clientId is required for OAuth logout operations\");\n }\n\n // We have access to the ID token from HTTP-only cookies\n // Build the logout URL manually using the shared utility\n\n const logoutUrl = await generateOauthLogoutUrl({\n clientId: this.authConfig.clientId,\n redirectUrl: this.authConfig.postLogoutRedirectUrl || \"/\",\n idToken: tokens.idToken,\n state: options?.state ?? Math.random().toString(36).substring(2),\n oauthServer: this.oauthServer,\n });\n\n return logoutUrl;\n }\n } catch (error) {\n // If direct token access fails, fall back to the generic function\n console.warn(\n \"❌ Could not get tokens directly from storage, falling back to generic logout method:\",\n error,\n );\n }\n\n // Fallback to the generic function for other storage types or when tokens aren't accessible\n return buildLogoutRedirectUrl(\n {\n ...this.authConfig,\n scopes: options?.scopes,\n state: options?.state,\n },\n this.storage,\n );\n }\n\n /**\n * Refresh the current set of OIDC tokens\n * @returns The refreshed tokens or null for backend flows where tokens are managed in HTTP-only cookies\n */\n async refreshTokens(): Promise<OIDCTokenResponseBody | null> {\n return refreshTokens(this.storage, this.authConfig);\n }\n\n /**\n * Clear all authentication tokens from storage\n */\n async clearTokens(): Promise<void> {\n return clearTokensUtil(this.storage);\n }\n\n /**\n * Framework-agnostic URL detection and resolution helpers\n * These methods handle proxy environments and can be used by any framework\n */\n\n /**\n * Try to URI decode a value, returning the original value on error\n */\n static tryUriDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch (e) {\n console.error(\"Error decoding URI component:\", e);\n return value;\n }\n }\n\n /**\n * Get decoded query parameter from request\n */\n static getDecodedQueryParam(\n request: UrlDetectionRequest,\n paramName: string,\n ): string | null {\n const queryParam = request.searchParams.get(paramName);\n if (queryParam) {\n return CivicAuth.tryUriDecode(queryParam);\n }\n return null;\n }\n\n /**\n * Get value from cookie or query parameter (cookie takes precedence)\n */\n static getCookieOrQueryParam(\n request: UrlDetectionRequest,\n cookieName: string,\n queryName: string,\n ): string | null {\n // First check the cookie as it might have the full path with base directory\n const cookieValue = request.cookies.get(cookieName)?.value;\n if (cookieValue) {\n return CivicAuth.tryUriDecode(cookieValue);\n }\n\n // Fallback to query parameter\n return CivicAuth.getDecodedQueryParam(request, queryName);\n }\n\n /**\n * Get app URL from request (for proxy environment support)\n * Checks cookies first, then query parameters\n */\n static getAppUrl(request: UrlDetectionRequest): string | null {\n return CivicAuth.getCookieOrQueryParam(\n request,\n CodeVerifier.APP_URL,\n \"appUrl\",\n );\n }\n\n /**\n * Get login success URL with proper base URL handling\n * Extracts from state parameter or query parameters, resolves with baseUrl if provided\n */\n static getLoginSuccessUrl(\n request: UrlDetectionRequest,\n baseUrl?: string | null,\n ): string | null {\n const state = request.searchParams.get(\"state\");\n const loginSuccessUrl =\n loginSuccessUrlFromState(state) ||\n CivicAuth.getDecodedQueryParam(request, \"loginSuccessUrl\");\n\n if (!loginSuccessUrl) {\n return null;\n }\n\n return baseUrl ? new URL(loginSuccessUrl, baseUrl).href : loginSuccessUrl;\n }\n\n /**\n * Convert relative URL to absolute URL using appUrl for proxy environments\n */\n static toAbsoluteUrl(\n request: UrlDetectionRequest,\n url: string,\n appUrl?: string | null,\n ): string {\n if (url.startsWith(\"http\")) {\n return url;\n }\n\n // Use appUrl if available (for proxy environments), otherwise fall back to request origin\n const baseUrl = appUrl || new URL(request.url).origin;\n return new URL(url, baseUrl).href;\n }\n\n /**\n * Get post-logout redirect URL with proxy environment support\n */\n getPostLogoutRedirectUrl(request: UrlDetectionRequest): string {\n // Check if we have a target URL in the request (from middleware)\n const targetUrl = request.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n return targetUrl;\n }\n\n const redirectTarget = this.authConfig.loginSuccessUrl ?? \"/\";\n\n // If loginSuccessUrl is absolute, use it as-is\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n if (isAbsoluteRedirect) {\n return redirectTarget;\n }\n\n // Use appUrl from client for proxy environments\n const appUrl = CivicAuth.getAppUrl(request);\n if (appUrl) {\n return new URL(redirectTarget, appUrl).href;\n }\n\n // Fallback to request origin\n return new URL(request.url).origin;\n }\n\n /**\n * Smart callback handler that automatically detects frontend vs backend requests\n * and redirects appropriately. Use this instead of resolveOAuthAccessCode + manual redirect.\n *\n * @param params An object containing the authorization code, state, and the incoming request.\n * @param params.code The authorization code from query parameters.\n * @param params.state The OAuth state parameter.\n * @param params.req The incoming request object (e.g., from Express).\n * @param options Configuration options (frontendUrl override, apiResponse flag).\n * @returns Object with redirect information or HTML content for iframe completion.\n *\n * @example\n * ```javascript\n * app.get('/auth/callback', async (req, res) => {\n * const { code, state } = req.query;\n * // The request object 'req' is passed directly\n * const result = await req.civicAuth.handleCallback({ code, state, req });\n *\n * if (result.htmlContent) {\n * res.setHeader('Content-Type', 'text/html');\n * res.send(result.htmlContent);\n * } else if (result.redirectTo) {\n * res.redirect(result.redirectTo);\n * } else {\n * res.json({ success: true, user: result.user });\n * }\n * });\n * ```\n */\n async handleCallback(\n { code, state, req }: HandleCallbackParams,\n options?: {\n frontendUrl?: string;\n apiResponse?: boolean;\n },\n ): Promise<{\n redirectTo?: string;\n content?: string | { success: boolean; user?: User | null };\n }> {\n // Handle same-domain callback for iframe workaround\n if (isSameDomainCallback(req)) {\n try {\n // Check if user is already authenticated before attempting token exchange\n const isAlreadyLoggedIn = await this.isLoggedIn();\n let user: User | null = null;\n\n if (isAlreadyLoggedIn) {\n // User is already authenticated, get existing user data\n user = await this.getUser();\n console.log(\n \"User already authenticated in same-domain callback:\",\n !!user,\n );\n } else {\n // For same-domain callbacks, we should have access to cookies\n const tokens = await this.resolveOAuthAccessCode(code, state);\n user = getUserFromTokens(tokens);\n console.log(\n \"Completed token exchange in same-domain callback:\",\n !!user,\n );\n }\n\n // Return JSON response for same-domain callback\n const currentUrl = new URL(req.url || \"\");\n const newSearchParams = new URLSearchParams(currentUrl.search);\n newSearchParams.delete(\"sameDomainCallback\");\n newSearchParams.delete(\"appUrl\");\n newSearchParams.delete(\"loginSuccessUrl\");\n\n const redirectUrl = `${currentUrl.pathname}?${newSearchParams.toString()}${currentUrl.hash}`;\n return {\n content: {\n success: true,\n redirectUrl,\n } as { success: boolean; redirectUrl: string },\n };\n } catch (error) {\n console.error(\"Same-domain callback failed:\", error);\n throw error;\n }\n }\n\n // Try to resolve the OAuth code and create session\n let tokens: OIDCTokenResponseBody;\n let user: User | null;\n\n try {\n tokens = await this.resolveOAuthAccessCode(code, state);\n user = getUserFromTokens(tokens);\n } catch (error) {\n // Check if this is a code verifier error and we're in iframe mode\n const isCodeVerifierError =\n error instanceof Error &&\n error.message.includes(\"Code verifier not found in storage\");\n\n if (isCodeVerifierError) {\n // First check if user is already authenticated before trying iframe workaround\n try {\n const isAlreadyLoggedIn = await this.isLoggedIn();\n\n if (isAlreadyLoggedIn) {\n // \"User already authenticated, skipping iframe workaround\",\n const user = await this.getUser();\n const loginSuccessUrlFromStateValue =\n loginSuccessUrlFromState(state);\n const frontendUrl =\n options?.frontendUrl ||\n loginSuccessUrlFromStateValue ||\n this.authConfig.loginSuccessUrl;\n\n // Check if this is an iframe context - if so, generate iframe completion HTML\n const stateDisplayMode = displayModeFromState(state, undefined);\n const isConfiguredForIframe = stateDisplayMode === \"iframe\";\n\n if (\n isConfiguredForIframe &&\n !this.authConfig.disableIframeDetection &&\n user &&\n frontendUrl\n ) {\n // Generating iframe completion HTML for already authenticated user\",\n const completionHtml = this.generateIframeCompletionHtml(\n user,\n frontendUrl,\n );\n return { content: completionHtml };\n }\n\n if (frontendUrl) {\n return { redirectTo: frontendUrl };\n } else {\n return { content: { success: true, user } };\n }\n }\n } catch (authCheckError) {\n console.warn(\n \"Failed to check authentication status:\",\n authCheckError,\n );\n // Continue with iframe workaround if auth check fails\n }\n\n const stateDisplayMode = displayModeFromState(state, undefined);\n const isConfiguredForIframe = stateDisplayMode === \"iframe\";\n\n if (isConfiguredForIframe && !this.authConfig.disableIframeDetection) {\n // Generate HTML that will trigger same-domain callback\n const loginSuccessUrlFromStateValue = loginSuccessUrlFromState(state);\n const frontendUrl =\n options?.frontendUrl ||\n loginSuccessUrlFromStateValue ||\n this.authConfig.loginSuccessUrl;\n\n const callbackUrl = req.url || \"\";\n const sameDomainHtml = this.generateSameDomainCallbackHtml(\n callbackUrl,\n frontendUrl,\n );\n return { content: sameDomainHtml };\n }\n\n // For non-iframe mode or when iframe detection is disabled, return trigger text\n return {\n content: `<html lang=\"en\"><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n };\n }\n\n // Re-throw other errors\n throw error;\n }\n\n // Extract loginSuccessUrl from state if present\n const loginSuccessUrlFromStateValue = loginSuccessUrlFromState(state);\n\n // Priority: options.frontendUrl > loginSuccessUrl from state > config loginSuccessUrl\n const frontendUrl =\n options?.frontendUrl ||\n loginSuccessUrlFromStateValue ||\n this.authConfig.loginSuccessUrl;\n\n // Priority 1: Check state for display mode configuration\n const stateDisplayMode = displayModeFromState(state, undefined);\n const isConfiguredForIframe = stateDisplayMode === \"iframe\";\n\n // Determine if this should be treated as an iframe request\n // Configuration (from state) takes precedence over auto-detection\n const shouldTreatAsIframe =\n isConfiguredForIframe && !this.authConfig.disableIframeDetection;\n\n const isTopLevelRedirect = req.headers[\"sec-fetch-dest\"] === \"document\";\n const isIframeRequest = req.headers[\"sec-fetch-dest\"] === \"iframe\";\n const isApiRequest =\n options?.apiResponse || req.headers.accept?.includes(\"application/json\");\n\n // Detect Safari or other browsers where iframe postMessage may fail due to cross-origin restrictions\n //TODO: Find a better way to detect this\n const userAgent = req.headers[\"user-agent\"] || \"\";\n const isSafari =\n userAgent.includes(\"Safari\") && !userAgent.includes(\"Chrome\");\n const isLikelyCrossOriginIframe =\n isSafari ||\n (userAgent.includes(\"WebKit\") && !userAgent.includes(\"Chrome\"));\n\n // Case 1: The request should be treated as iframe. Return HTML content.\n // Unless iframe detection is disabled via configuration OR we detect cross-origin issues\n if (\n shouldTreatAsIframe &&\n user &&\n frontendUrl &&\n !isLikelyCrossOriginIframe\n ) {\n const completionHtml = this.generateIframeCompletionHtml(\n user,\n frontendUrl,\n );\n return { content: completionHtml };\n }\n\n // Case 1b: Safari/cross-origin iframe case - redirect instead of HTML\n if (\n shouldTreatAsIframe &&\n user &&\n frontendUrl &&\n isLikelyCrossOriginIframe\n ) {\n return { redirectTo: frontendUrl };\n }\n\n // Case 2: The request is a top-level navigation. Return redirect URL.\n if (isTopLevelRedirect && frontendUrl) {\n return { redirectTo: frontendUrl };\n }\n\n // Case 2a: The request is from an iframe (detected by sec-fetch-dest)\n // Even if not configured for iframe in state, we should still generate iframe completion HTML\n if (isIframeRequest && user && frontendUrl) {\n if (isLikelyCrossOriginIframe) {\n console.log(\n \"Iframe request detected but cross-origin issues likely - redirecting\",\n );\n return { redirectTo: frontendUrl };\n } else {\n console.log(\n \"Generating iframe completion HTML for iframe request (detected by sec-fetch-dest)\",\n );\n const completionHtml = this.generateIframeCompletionHtml(\n user,\n frontendUrl,\n );\n return { content: completionHtml };\n }\n }\n\n // Case 3: The request is an API call. Return JSON content.\n if (isApiRequest) {\n return {\n content: {\n success: true,\n user,\n },\n };\n }\n\n // Fallback for older browsers or other contexts: if a frontend URL is configured,\n // assume a redirect to it.\n if (frontendUrl) {\n return { redirectTo: frontendUrl };\n }\n\n // Server-side fallback: if no frontend URL is configured but we have a postLogoutRedirectUrl,\n // redirect there instead of returning JSON content\n if (this.authConfig.postLogoutRedirectUrl) {\n return { redirectTo: this.authConfig.postLogoutRedirectUrl };\n }\n\n // Absolute fallback: return success as JSON content if no other conditions are met.\n // This could happen if no loginSuccessUrl or postLogoutRedirectUrl is configured.\n return {\n content: {\n success: true,\n user,\n },\n };\n }\n\n /**\n * Generate HTML content for iframe completion that sends postMessage to parent\n */\n private generateIframeCompletionHtml(\n user: User,\n frontendUrl?: string,\n ): string {\n const escapedUser = JSON.stringify(user).replace(/'/g, \"\\\\'\");\n const clientId = this.authConfig.clientId;\n\n // Determine fallback redirect URL\n const fallbackUrl =\n frontendUrl ||\n this.authConfig.redirectUrl ||\n this.authConfig.postLogoutRedirectUrl ||\n \"/\";\n\n return `\n <!DOCTYPE html>\n <html>\n <head>\n <title>Authentication Complete</title>\n <meta charset=\"utf-8\">\n </head>\n <body> \n <!-- Success signal for SignalObserver -->\n <div id=\"civic-auth-success-signal\" style=\"display: none;\" data-user-info='${escapedUser}'>\n ${TOKEN_EXCHANGE_SUCCESS_TEXT}\n </div>\n \n <script> \n // Send postMessage to parent to resolve authentication promise\n if (window.parent && window.parent !== window) {\n try {\n window.parent.postMessage({\n type: 'auth_success',\n detail: 'Authentication successful',\n data: {\n user: ${escapedUser}\n }\n }, '*');\n } catch (error) {\n console.error('❌ Failed to send postMessage:', error);\n }\n \n // Also send civicloginApp format message for compatibility\n try {\n window.parent.postMessage({\n source: 'civicloginApp',\n type: 'auth_success',\n clientId: '${clientId}',\n data: {\n user: ${escapedUser}\n }\n }, '*');\n } catch (error) {\n console.error('❌ Failed to send civicloginApp message:', error);\n }\n } else {\n console.log('❌ Not in iframe context or no parent window');\n }\n \n // Fallback redirect after 500ms delay to handle cases where:\n // 1. postMessage fails or parent doesn't respond\n // 2. Not in iframe context\n // 3. Any other edge cases where the user gets stuck\n setTimeout(function() {\n console.log('🔄 Executing fallback redirect to: ${fallbackUrl}');\n window.location.href = '${fallbackUrl}';\n }, 500);\n </script>\n </body>\n </html>\n `;\n }\n\n /**\n * Generate HTML response that triggers same-domain callback for iframe workaround\n */\n private generateSameDomainCallbackHtml = (\n callbackUrl: string,\n frontendUrl?: string,\n ): string => {\n const loginSuccessSegment = frontendUrl\n ? `&loginSuccessUrl=${encodeURIComponent(frontendUrl)}`\n : \"\";\n\n return `<html lang=\"en\">\n <body>\n <span style=\"display:none\">\n <script>\n window.onload = function () {\n // Get the complete URL including origin and path\n // This ensures we capture any base path like /directory\n const appUrl = window.location.href.substring(\n 0,\n window.location.href.indexOf(\"/api/auth\")\n );\n fetch('${callbackUrl}&sameDomainCallback=true&appUrl=' + encodeURIComponent(appUrl) + '${loginSuccessSegment}').then((response) => {\n response.json().then((jsonResponse) => {\n // For login: Redirect back to the callback route, so Case 2 in handleTokenExchangeComplete will be triggered\n // For logout: Redirect to the postLogoutRedirectUrl\n if(jsonResponse.redirectUrl) {\n window.location.href = jsonResponse.redirectUrl;\n }\n });\n });\n };\n </script>\n </span>\n </body>\n</html>\n`;\n };\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/server/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,SAAS,GACV,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,OAAO,IAAI,iBAAiB,EAC5B,SAAS,IAAI,mBAAmB,GACjC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,WAAW,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AACxF,OAAO,EACL,mBAAmB,EACnB,4BAA4B,GAC7B,MAAM,gBAAgB,CAAC;AA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AC,WAAW,CAAC;;;;;;;;;;;;;;;mCAezB,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC;;;;;;;KAOzD,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,8BAA8B,GAAG,CACvC,WAAmB,EACnB,WAAoB,EACZ,EAAE;QACV,MAAM,mBAAmB,GAAG,WAAW;YACrC,CAAC,CAAC,oBAAoB,kBAAkB,CAAC,WAAW,CAAC,EAAE;YACvD,CAAC,CAAC,EAAE,CAAC;QAEP,OAAO;;;;;;;;;;;2BAWgB,WAAW,qEAAqE,mBAAmB;;;;;;;;;;;;;;CAc7H,CAAC;IACA,CAAC,CAAC;CACH","sourcesContent":["import {\n type OAuthTokens,\n type User,\n type EmptyObject,\n type UnknownObject,\n type OIDCTokenResponseBody,\n tokenKeys,\n} from \"@/types.js\";\nimport type { AuthConfig } from \"@/server/config.js\";\nimport {\n getUser as getUserFromShared,\n getTokens as getTokensFromShared,\n} from \"@/shared/lib/session.js\";\nimport { clearTokens as clearTokensUtil } from \"@/shared/lib/util.js\";\nimport { resolveOAuthAccessCode } from \"@/server/login.js\";\nimport { buildLoginUrl } from \"@/server/login.js\";\nimport { buildLogoutRedirectUrl } from \"@/server/logout.js\";\nimport {\n TOKEN_EXCHANGE_SUCCESS_TEXT,\n TOKEN_EXCHANGE_TRIGGER_TEXT,\n} from \"@/constants.js\";\nimport { refreshTokens } from \"@/server/refresh.js\";\nimport { getVersion } from \"@/shared/index.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport {\n DEFAULT_AUTH_SERVER,\n JWT_PAYLOAD_KNOWN_CLAIM_KEYS,\n} from \"@/constants.js\";\nimport type { AuthenticationResolver } from \"@/services/types.js\";\nimport { displayModeFromState, loginSuccessUrlFromState } from \"@/lib/oauth.js\";\nimport { decodeJwt, type JWTPayload } from \"jose\";\nimport {\n generateOauthLogoutUrl,\n getBackendEndpoints,\n resolveEndpointUrl,\n sanitizeReturnUrl,\n} from \"@/shared/lib/util.js\";\nimport { CodeVerifier } from \"@/shared/lib/types.js\";\nimport type { CookieStorage } from \"./index.js\";\nimport { loggers } from \"@/lib/logger.js\";\n\n// Generic request interface for framework-agnostic URL detection\nexport type UrlDetectionRequest = {\n url: string;\n headers: Record<string, string | string[] | undefined>;\n searchParams: {\n get(name: string): string | null;\n };\n cookies: {\n get(name: string): { value: string } | undefined;\n };\n};\n\nexport type HandleCallbackRequest = {\n headers: {\n [key: string]: string | string[] | undefined;\n referer?: string;\n origin?: string;\n \"user-agent\"?: string;\n accept?: string;\n \"sec-fetch-dest\"?: string;\n };\n url?: string;\n};\n\nexport type HandleCallbackParams = {\n code: string;\n state: string;\n req: HandleCallbackRequest;\n};\n\n// Function to omit keys from an object\nconst omitKeys = <K extends keyof T, T extends Record<string, unknown>>(\n keys: K[],\n obj: T,\n): Omit<T, K> => {\n const result = { ...obj };\n keys.forEach((key) => {\n delete result[key];\n });\n return result;\n};\n\n/**\n * Helper to detect if this is a same-domain callback request (for iframe workaround)\n */\nconst isSameDomainCallback = (req: HandleCallbackRequest): boolean => {\n if (!req.url) return false;\n return req.url.includes(\"sameDomainCallback=true\");\n};\n\n/**\n * Extract user information directly from OIDC tokens\n * @param tokens The OIDC tokens response\n * @returns The user object or null if no valid ID token\n */\nfunction getUserFromTokens<T extends UnknownObject = EmptyObject>(\n tokens: OIDCTokenResponseBody,\n): User<T> | null {\n if (!tokens.id_token) return null;\n\n const parsedToken = decodeJwt(tokens.id_token) as JWTPayload & T;\n if (!parsedToken.sub) return null;\n\n // set the user ID from the token sub\n const userWithAdditionalTokenFields = {\n ...(parsedToken as T),\n id: parsedToken.sub,\n };\n\n // Remove the token keys from the user object to stop it getting too large\n return omitKeys(\n [...JWT_PAYLOAD_KNOWN_CLAIM_KEYS, ...tokenKeys],\n userWithAdditionalTokenFields,\n ) as User<T>;\n}\n\n/**\n * CivicAuth is the main entry point for server-side authentication operations.\n * It provides a unified interface to all the authentication functions.\n */\nexport class CivicAuth {\n _authResolver: AuthenticationResolver | null = null;\n constructor(\n readonly storage: CookieStorage,\n readonly authConfig: AuthConfig,\n ) {}\n\n get oauthServer(): string {\n return this.authConfig.oauthServer || DEFAULT_AUTH_SERVER;\n }\n\n async getAuthResolver(): Promise<AuthenticationResolver> {\n if (this._authResolver) {\n loggers.server.debug(\"Reusing existing auth resolver\", this.authConfig);\n return Promise.resolve(this._authResolver);\n }\n loggers.server.debug(\"Creating new auth resolver\", this.authConfig);\n this._authResolver = await ServerAuthenticationResolver.build(\n {\n ...this.authConfig,\n oauthServer: this.oauthServer,\n },\n this.storage,\n );\n return this._authResolver;\n }\n /**\n * Gets the authenticated user with token validation\n * @returns The user object if authenticated, null otherwise\n */\n async getUser<\n T extends UnknownObject = EmptyObject,\n >(): Promise<User<T> | null> {\n const resolver = await this.getAuthResolver();\n\n try {\n // Validate the session before returning the user\n const session = await resolver.validateExistingSession();\n if (!session?.authenticated) {\n return null;\n }\n\n // If session is valid, use the shared implementation to get the user\n return getUserFromShared<T>(this.storage);\n } catch (error) {\n console.error(\"Token validation failed during getUser\", error);\n return null;\n }\n }\n\n /**\n * Gets the authentication tokens with token validation\n * @returns The tokens if authenticated, null otherwise\n */\n async getTokens(): Promise<OAuthTokens | null> {\n const resolver = await this.getAuthResolver();\n\n try {\n // Validate the session before returning the tokens\n const session = await resolver.validateExistingSession();\n\n if (!session?.authenticated) {\n return null;\n }\n\n // If session is valid, use the shared implementation to get the tokens\n const tokens = await getTokensFromShared(this.storage);\n return tokens;\n } catch (error) {\n console.error(\"❌ Token validation failed during getTokens\", error);\n return null;\n }\n }\n\n /**\n * Resolve an OAuth access code to a set of OIDC tokens\n * @param code The access code from the query parameter\n * @param state The OAuth state parameter\n * @returns OIDC tokens\n */\n async resolveOAuthAccessCode(\n code: string,\n state: string,\n ): Promise<OIDCTokenResponseBody> {\n return resolveOAuthAccessCode(code, state, this.storage, this.authConfig);\n }\n\n /**\n * Check if the user is currently logged in\n * @returns true if logged in, false otherwise\n */\n async isLoggedIn(): Promise<boolean> {\n const resolver = await this.getAuthResolver();\n const session = await resolver.validateExistingSession();\n return session?.authenticated ?? false;\n }\n\n /**\n * Build a login URL to redirect the user to\n * @param options Additional options for building the login URL\n * @returns The login URL\n */\n async buildLoginUrl(options?: {\n scopes?: string[];\n state?: string;\n nonce?: string;\n }): Promise<URL> {\n return buildLoginUrl(\n {\n ...this.authConfig,\n scopes: options?.scopes,\n state: options?.state,\n nonce: options?.nonce,\n framework: \"server\",\n sdkVersion: getVersion(),\n },\n this.storage,\n );\n }\n\n /**\n * Build a logout URL to redirect the user to\n * @param options Additional options for building the logout URL\n * @returns The logout URL\n */\n async buildLogoutRedirectUrl(options?: {\n scopes?: string[];\n state?: string;\n }): Promise<URL> {\n // Check if this is backend integration mode (loginUrl provided)\n if (this.authConfig.loginUrl) {\n // Backend integration mode: redirect to backend logout endpoint\n // This matches the vanilla client's logout logic for backend integration\n const backendUrl = new URL(this.authConfig.loginUrl).origin;\n const endpoints = getBackendEndpoints(this.authConfig.backendEndpoints);\n const backendLogoutUrl = resolveEndpointUrl(backendUrl, endpoints.logout);\n\n const logoutUrl = new URL(backendLogoutUrl);\n\n // Include logoutRedirectUrl as query parameter if configured\n if (this.authConfig.postLogoutRedirectUrl) {\n logoutUrl.searchParams.set(\n \"logoutRedirectUrl\",\n this.authConfig.postLogoutRedirectUrl,\n );\n }\n\n // Include state if provided\n if (options?.state) {\n logoutUrl.searchParams.set(\"state\", options.state);\n }\n\n return logoutUrl;\n }\n\n // Standard OAuth flow - redirect to OAuth provider's logout endpoint\n try {\n // Use the shared getTokens function directly - this bypasses session validation\n // since for logout we just need the raw ID token, not validated tokens\n const tokens = await getTokensFromShared(this.storage);\n\n if (tokens?.idToken) {\n // Ensure clientId is present for OAuth operations\n if (!this.authConfig.clientId) {\n throw new Error(\"clientId is required for OAuth logout operations\");\n }\n\n // We have access to the ID token from HTTP-only cookies\n // Build the logout URL manually using the shared utility\n\n const logoutUrl = await generateOauthLogoutUrl({\n clientId: this.authConfig.clientId,\n redirectUrl: this.authConfig.postLogoutRedirectUrl || \"/\",\n idToken: tokens.idToken,\n state: options?.state ?? Math.random().toString(36).substring(2),\n oauthServer: this.oauthServer,\n });\n\n return logoutUrl;\n }\n } catch (error) {\n // If direct token access fails, fall back to the generic function\n console.warn(\n \"❌ Could not get tokens directly from storage, falling back to generic logout method:\",\n error,\n );\n }\n\n // Fallback to the generic function for other storage types or when tokens aren't accessible\n return buildLogoutRedirectUrl(\n {\n ...this.authConfig,\n scopes: options?.scopes,\n state: options?.state,\n },\n this.storage,\n );\n }\n\n /**\n * Refresh the current set of OIDC tokens\n * @returns The refreshed tokens or null for backend flows where tokens are managed in HTTP-only cookies\n */\n async refreshTokens(): Promise<OIDCTokenResponseBody | null> {\n return refreshTokens(this.storage, this.authConfig);\n }\n\n /**\n * Clear all authentication tokens from storage\n */\n async clearTokens(): Promise<void> {\n return clearTokensUtil(this.storage);\n }\n\n /**\n * Framework-agnostic URL detection and resolution helpers\n * These methods handle proxy environments and can be used by any framework\n */\n\n /**\n * Try to URI decode a value, returning the original value on error\n */\n static tryUriDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch (e) {\n console.error(\"Error decoding URI component:\", e);\n return value;\n }\n }\n\n /**\n * Get decoded query parameter from request\n */\n static getDecodedQueryParam(\n request: UrlDetectionRequest,\n paramName: string,\n ): string | null {\n const queryParam = request.searchParams.get(paramName);\n if (queryParam) {\n return CivicAuth.tryUriDecode(queryParam);\n }\n return null;\n }\n\n /**\n * Get value from cookie or query parameter (cookie takes precedence)\n */\n static getCookieOrQueryParam(\n request: UrlDetectionRequest,\n cookieName: string,\n queryName: string,\n ): string | null {\n // First check the cookie as it might have the full path with base directory\n const cookieValue = request.cookies.get(cookieName)?.value;\n if (cookieValue) {\n return CivicAuth.tryUriDecode(cookieValue);\n }\n\n // Fallback to query parameter\n return CivicAuth.getDecodedQueryParam(request, queryName);\n }\n\n /**\n * Get app URL from request (for proxy environment support)\n * Checks cookies first, then query parameters\n */\n static getAppUrl(request: UrlDetectionRequest): string | null {\n return CivicAuth.getCookieOrQueryParam(\n request,\n CodeVerifier.APP_URL,\n \"appUrl\",\n );\n }\n\n /**\n * Get login success URL with proper base URL handling\n * Extracts from state parameter or query parameters, resolves with baseUrl if provided\n */\n static getLoginSuccessUrl(\n request: UrlDetectionRequest,\n baseUrl?: string | null,\n ): string | null {\n const state = request.searchParams.get(\"state\");\n const loginSuccessUrl =\n loginSuccessUrlFromState(state) ||\n CivicAuth.getDecodedQueryParam(request, \"loginSuccessUrl\");\n\n if (!loginSuccessUrl) {\n return null;\n }\n\n return baseUrl ? new URL(loginSuccessUrl, baseUrl).href : loginSuccessUrl;\n }\n\n /**\n * Convert relative URL to absolute URL using appUrl for proxy environments\n */\n static toAbsoluteUrl(\n request: UrlDetectionRequest,\n url: string,\n appUrl?: string | null,\n ): string {\n if (url.startsWith(\"http\")) {\n return url;\n }\n\n // Use appUrl if available (for proxy environments), otherwise fall back to request origin\n const baseUrl = appUrl || new URL(request.url).origin;\n return new URL(url, baseUrl).href;\n }\n\n /**\n * Get post-logout redirect URL with proxy environment support\n */\n getPostLogoutRedirectUrl(request: UrlDetectionRequest): string {\n // Check if we have a target URL in the request (from middleware)\n const targetUrl = request.searchParams.get(\"targetUrl\");\n if (targetUrl) {\n return targetUrl;\n }\n\n const redirectTarget = this.authConfig.loginSuccessUrl ?? \"/\";\n\n // If loginSuccessUrl is absolute, use it as-is\n const isAbsoluteRedirect = /^(https?:\\/\\/|www\\.).+/i.test(redirectTarget);\n if (isAbsoluteRedirect) {\n return redirectTarget;\n }\n\n // Use appUrl from client for proxy environments\n const appUrl = CivicAuth.getAppUrl(request);\n if (appUrl) {\n return new URL(redirectTarget, appUrl).href;\n }\n\n // Fallback to request origin\n return new URL(request.url).origin;\n }\n\n /**\n * Smart callback handler that automatically detects frontend vs backend requests\n * and redirects appropriately. Use this instead of resolveOAuthAccessCode + manual redirect.\n *\n * @param params An object containing the authorization code, state, and the incoming request.\n * @param params.code The authorization code from query parameters.\n * @param params.state The OAuth state parameter.\n * @param params.req The incoming request object (e.g., from Express).\n * @param options Configuration options (frontendUrl override, apiResponse flag).\n * @returns Object with redirect information or HTML content for iframe completion.\n *\n * @example\n * ```javascript\n * app.get('/auth/callback', async (req, res) => {\n * const { code, state } = req.query;\n * // The request object 'req' is passed directly\n * const result = await req.civicAuth.handleCallback({ code, state, req });\n *\n * if (result.htmlContent) {\n * res.setHeader('Content-Type', 'text/html');\n * res.send(result.htmlContent);\n * } else if (result.redirectTo) {\n * res.redirect(result.redirectTo);\n * } else {\n * res.json({ success: true, user: result.user });\n * }\n * });\n * ```\n */\n async handleCallback(\n { code, state, req }: HandleCallbackParams,\n options?: {\n frontendUrl?: string;\n apiResponse?: boolean;\n },\n ): Promise<{\n redirectTo?: string;\n content?: string | { success: boolean; user?: User | null };\n }> {\n // Handle same-domain callback for iframe workaround\n if (isSameDomainCallback(req)) {\n try {\n // Check if user is already authenticated before attempting token exchange\n const isAlreadyLoggedIn = await this.isLoggedIn();\n let user: User | null = null;\n\n if (isAlreadyLoggedIn) {\n // User is already authenticated, get existing user data\n user = await this.getUser();\n console.log(\n \"User already authenticated in same-domain callback:\",\n !!user,\n );\n } else {\n // For same-domain callbacks, we should have access to cookies\n const tokens = await this.resolveOAuthAccessCode(code, state);\n user = getUserFromTokens(tokens);\n console.log(\n \"Completed token exchange in same-domain callback:\",\n !!user,\n );\n }\n\n // Return JSON response for same-domain callback\n const currentUrl = new URL(req.url || \"\");\n\n // Extract and sanitize loginSuccessUrl (deep link) BEFORE cleaning up search params\n // Sanitization prevents open redirect attacks via malicious URLs in the query param\n const rawLoginSuccessUrl =\n currentUrl.searchParams.get(\"loginSuccessUrl\");\n const loginSuccessUrl = rawLoginSuccessUrl\n ? sanitizeReturnUrl(rawLoginSuccessUrl, currentUrl.origin)\n : null;\n\n const newSearchParams = new URLSearchParams(currentUrl.search);\n newSearchParams.delete(\"sameDomainCallback\");\n newSearchParams.delete(\"appUrl\");\n newSearchParams.delete(\"loginSuccessUrl\");\n\n // Use preserved deep link if available and valid, otherwise fall back to cleaned callback URL\n const cleanedSearch = newSearchParams.toString();\n const fallbackUrl = `${currentUrl.pathname}${cleanedSearch ? \"?\" + cleanedSearch : \"\"}${currentUrl.hash}`;\n const redirectUrl = loginSuccessUrl || fallbackUrl;\n return {\n content: {\n success: true,\n redirectUrl,\n } as { success: boolean; redirectUrl: string },\n };\n } catch (error) {\n console.error(\"Same-domain callback failed:\", error);\n throw error;\n }\n }\n\n // Try to resolve the OAuth code and create session\n let tokens: OIDCTokenResponseBody;\n let user: User | null;\n\n try {\n tokens = await this.resolveOAuthAccessCode(code, state);\n user = getUserFromTokens(tokens);\n } catch (error) {\n // Check if this is a code verifier error and we're in iframe mode\n const isCodeVerifierError =\n error instanceof Error &&\n error.message.includes(\"Code verifier not found in storage\");\n\n if (isCodeVerifierError) {\n // First check if user is already authenticated before trying iframe workaround\n try {\n const isAlreadyLoggedIn = await this.isLoggedIn();\n\n if (isAlreadyLoggedIn) {\n // \"User already authenticated, skipping iframe workaround\",\n const user = await this.getUser();\n const loginSuccessUrlFromStateValue =\n loginSuccessUrlFromState(state);\n const frontendUrl =\n options?.frontendUrl ||\n loginSuccessUrlFromStateValue ||\n this.authConfig.loginSuccessUrl;\n\n // Check if this is an iframe context - if so, generate iframe completion HTML\n const stateDisplayMode = displayModeFromState(state, undefined);\n const isConfiguredForIframe = stateDisplayMode === \"iframe\";\n\n if (\n isConfiguredForIframe &&\n !this.authConfig.disableIframeDetection &&\n user &&\n frontendUrl\n ) {\n // Generating iframe completion HTML for already authenticated user\",\n const completionHtml = this.generateIframeCompletionHtml(\n user,\n frontendUrl,\n );\n return { content: completionHtml };\n }\n\n if (frontendUrl) {\n return { redirectTo: frontendUrl };\n } else {\n return { content: { success: true, user } };\n }\n }\n } catch (authCheckError) {\n console.warn(\n \"Failed to check authentication status:\",\n authCheckError,\n );\n // Continue with iframe workaround if auth check fails\n }\n\n const stateDisplayMode = displayModeFromState(state, undefined);\n const isConfiguredForIframe = stateDisplayMode === \"iframe\";\n\n if (isConfiguredForIframe && !this.authConfig.disableIframeDetection) {\n // Generate HTML that will trigger same-domain callback\n const loginSuccessUrlFromStateValue = loginSuccessUrlFromState(state);\n const frontendUrl =\n options?.frontendUrl ||\n loginSuccessUrlFromStateValue ||\n this.authConfig.loginSuccessUrl;\n\n const callbackUrl = req.url || \"\";\n const sameDomainHtml = this.generateSameDomainCallbackHtml(\n callbackUrl,\n frontendUrl,\n );\n return { content: sameDomainHtml };\n }\n\n // For non-iframe mode or when iframe detection is disabled, return trigger text\n return {\n content: `<html lang=\"en\"><body><span style=\"display:none\">${TOKEN_EXCHANGE_TRIGGER_TEXT}</span></body></html>`,\n };\n }\n\n // Re-throw other errors\n throw error;\n }\n\n // Extract loginSuccessUrl from state if present\n const loginSuccessUrlFromStateValue = loginSuccessUrlFromState(state);\n\n // Priority: options.frontendUrl > loginSuccessUrl from state > config loginSuccessUrl\n const frontendUrl =\n options?.frontendUrl ||\n loginSuccessUrlFromStateValue ||\n this.authConfig.loginSuccessUrl;\n\n // Priority 1: Check state for display mode configuration\n const stateDisplayMode = displayModeFromState(state, undefined);\n const isConfiguredForIframe = stateDisplayMode === \"iframe\";\n\n // Determine if this should be treated as an iframe request\n // Configuration (from state) takes precedence over auto-detection\n const shouldTreatAsIframe =\n isConfiguredForIframe && !this.authConfig.disableIframeDetection;\n\n const isTopLevelRedirect = req.headers[\"sec-fetch-dest\"] === \"document\";\n const isIframeRequest = req.headers[\"sec-fetch-dest\"] === \"iframe\";\n const isApiRequest =\n options?.apiResponse || req.headers.accept?.includes(\"application/json\");\n\n // Detect Safari or other browsers where iframe postMessage may fail due to cross-origin restrictions\n //TODO: Find a better way to detect this\n const userAgent = req.headers[\"user-agent\"] || \"\";\n const isSafari =\n userAgent.includes(\"Safari\") && !userAgent.includes(\"Chrome\");\n const isLikelyCrossOriginIframe =\n isSafari ||\n (userAgent.includes(\"WebKit\") && !userAgent.includes(\"Chrome\"));\n\n // Case 1: The request should be treated as iframe. Return HTML content.\n // Unless iframe detection is disabled via configuration OR we detect cross-origin issues\n if (\n shouldTreatAsIframe &&\n user &&\n frontendUrl &&\n !isLikelyCrossOriginIframe\n ) {\n const completionHtml = this.generateIframeCompletionHtml(\n user,\n frontendUrl,\n );\n return { content: completionHtml };\n }\n\n // Case 1b: Safari/cross-origin iframe case - redirect instead of HTML\n if (\n shouldTreatAsIframe &&\n user &&\n frontendUrl &&\n isLikelyCrossOriginIframe\n ) {\n return { redirectTo: frontendUrl };\n }\n\n // Case 2: The request is a top-level navigation. Return redirect URL.\n if (isTopLevelRedirect && frontendUrl) {\n return { redirectTo: frontendUrl };\n }\n\n // Case 2a: The request is from an iframe (detected by sec-fetch-dest)\n // Even if not configured for iframe in state, we should still generate iframe completion HTML\n if (isIframeRequest && user && frontendUrl) {\n if (isLikelyCrossOriginIframe) {\n console.log(\n \"Iframe request detected but cross-origin issues likely - redirecting\",\n );\n return { redirectTo: frontendUrl };\n } else {\n console.log(\n \"Generating iframe completion HTML for iframe request (detected by sec-fetch-dest)\",\n );\n const completionHtml = this.generateIframeCompletionHtml(\n user,\n frontendUrl,\n );\n return { content: completionHtml };\n }\n }\n\n // Case 3: The request is an API call. Return JSON content.\n if (isApiRequest) {\n return {\n content: {\n success: true,\n user,\n },\n };\n }\n\n // Fallback for older browsers or other contexts: if a frontend URL is configured,\n // assume a redirect to it.\n if (frontendUrl) {\n return { redirectTo: frontendUrl };\n }\n\n // Server-side fallback: if no frontend URL is configured but we have a postLogoutRedirectUrl,\n // redirect there instead of returning JSON content\n if (this.authConfig.postLogoutRedirectUrl) {\n return { redirectTo: this.authConfig.postLogoutRedirectUrl };\n }\n\n // Absolute fallback: return success as JSON content if no other conditions are met.\n // This could happen if no loginSuccessUrl or postLogoutRedirectUrl is configured.\n return {\n content: {\n success: true,\n user,\n },\n };\n }\n\n /**\n * Generate HTML content for iframe completion that sends postMessage to parent\n */\n private generateIframeCompletionHtml(\n user: User,\n frontendUrl?: string,\n ): string {\n const escapedUser = JSON.stringify(user).replace(/'/g, \"\\\\'\");\n const clientId = this.authConfig.clientId;\n\n // Determine fallback redirect URL\n const fallbackUrl =\n frontendUrl ||\n this.authConfig.redirectUrl ||\n this.authConfig.postLogoutRedirectUrl ||\n \"/\";\n\n return `\n <!DOCTYPE html>\n <html>\n <head>\n <title>Authentication Complete</title>\n <meta charset=\"utf-8\">\n </head>\n <body> \n <!-- Success signal for SignalObserver -->\n <div id=\"civic-auth-success-signal\" style=\"display: none;\" data-user-info='${escapedUser}'>\n ${TOKEN_EXCHANGE_SUCCESS_TEXT}\n </div>\n \n <script>\n // Send postMessage to parent to resolve authentication promise\n if (window.parent && window.parent !== window) {\n try {\n window.parent.postMessage({\n type: 'auth_success',\n detail: 'Authentication successful',\n data: {\n user: ${escapedUser},\n redirectUrl: ${JSON.stringify(fallbackUrl)}\n }\n }, '*');\n } catch (error) {\n console.error('❌ Failed to send postMessage:', error);\n }\n\n // Also send civicloginApp format message for compatibility\n try {\n window.parent.postMessage({\n source: 'civicloginApp',\n type: 'auth_success',\n clientId: ${JSON.stringify(clientId)},\n data: {\n user: ${escapedUser},\n redirectUrl: ${JSON.stringify(fallbackUrl)}\n }\n }, '*');\n } catch (error) {\n console.error('❌ Failed to send civicloginApp message:', error);\n }\n } else {\n console.log('❌ Not in iframe context or no parent window');\n }\n \n // Fallback redirect after 500ms delay to handle cases where:\n // 1. postMessage fails or parent doesn't respond\n // 2. Not in iframe context\n // 3. Any other edge cases where the user gets stuck\n setTimeout(function() {\n var redirectTarget = ${JSON.stringify(fallbackUrl)};\n console.log('🔄 Executing fallback redirect to:', redirectTarget);\n window.location.href = redirectTarget;\n }, 500);\n </script>\n </body>\n </html>\n `;\n }\n\n /**\n * Generate HTML response that triggers same-domain callback for iframe workaround\n */\n private generateSameDomainCallbackHtml = (\n callbackUrl: string,\n frontendUrl?: string,\n ): string => {\n const loginSuccessSegment = frontendUrl\n ? `&loginSuccessUrl=${encodeURIComponent(frontendUrl)}`\n : \"\";\n\n return `<html lang=\"en\">\n <body>\n <span style=\"display:none\">\n <script>\n window.onload = function () {\n // Get the complete URL including origin and path\n // This ensures we capture any base path like /directory\n const appUrl = window.location.href.substring(\n 0,\n window.location.href.indexOf(\"/api/auth\")\n );\n fetch('${callbackUrl}&sameDomainCallback=true&appUrl=' + encodeURIComponent(appUrl) + '${loginSuccessSegment}').then((response) => {\n response.json().then((jsonResponse) => {\n // For login: Redirect back to the callback route, so Case 2 in handleTokenExchangeComplete will be triggered\n // For logout: Redirect to the postLogoutRedirectUrl\n if(jsonResponse.redirectUrl) {\n window.location.href = jsonResponse.redirectUrl;\n }\n });\n });\n };\n </script>\n </span>\n </body>\n</html>\n`;\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"cookieConfig.d.ts","sourceRoot":"","sources":["../../../src/shared/lib/cookieConfig.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,WAAW,EACX,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACxB,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,mBAAmB;IAClC,oDAAoD;IACpD,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,qCAAqC;IACrC,QAAQ,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,MAAM,CAAC;IACrC,kDAAkD;IAClD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,4CAA4C;IAC5C,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,+CAA+C;IAC/C,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,uBAAuB;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,kBAAkB,CAAC;IAC3B,IAAI,EAAE,YAAY,CAAC;CACpB;AAED,MAAM,WAAW,8BAA8B;IAC7C,MAAM,EAAE,kBAAkB,GAAG;QAC3B,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,YAAY,CAAC;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gB,kBAAkB,CAChC,OAAO,GAAE,mBAAwB,GAChC,mBAAmB,CAwDrB;AAED;;GAEG;AACH,wBAAgB,4CAA4C,CAC1D,OAAO,GAAE,mBAAwB,GAChC,8BAA8B,CAsBhC;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,CAAC,EAAE,MAAM,GAChB,mBAAmB,CAQrB;AAED;;GAEG;AACH,wBAAgB,6BAA6B,IAAI,8BAA8B,CAM9E;AAED;;GAEG;AACH,wBAAgB,6BAA6B,IAAI,mBAAmB,CAKnE"}
@@ -1,5 +1,5 @@
1
1
  import { MAX_COOKIE_AGE_SECONDS } from "../../constants.js";
2
- import { CodeVerifier, OAuthTokenTypes, UserStorage, } from "./types.js";
2
+ import { AuthFlowCookie, CodeVerifier, OAuthTokenTypes, UserStorage, } from "./types.js";
3
3
  /**
4
4
  * Creates a standardized cookie configuration for NextJS
5
5
  */
@@ -40,6 +40,11 @@ export function createCookieConfig(options = {}) {
40
40
  ...baseCookieConfig,
41
41
  httpOnly,
42
42
  },
43
+ [AuthFlowCookie.RETURN_URL]: {
44
+ ...baseCookieConfig,
45
+ maxAge: 30 * 60, // 30 minutes
46
+ httpOnly,
47
+ },
43
48
  },
44
49
  user: {
45
50
  ...baseCookieConfig,
@@ -1 +1 @@
1
- {"version":3,"file":"cookieConfig.js","sourceRoot":"","sources":["../../../src/shared/lib/cookieConfig.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,eAAe,EACf,WAAW,GAGZ,MAAM,YAAY,CAAC;AA6BpB;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAChC,UAA+B,EAAE;IAEjC,MAAM,EACJ,MAAM,GAAG,IAAI,EACb,QAAQ,GAAG,QAAQ,EACnB,aAAa,GAAG,EAAE,GAAG,EAAE,EAAE,SAAS;IAClC,kBAAkB,GAAG,sBAAsB,EAC3C,QAAQ,GAAG,IAAI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AAC,MAAM;YACrB,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE;gBAClB,MAAM;gBACN,QAAQ;gBACR,IAAI;gBACJ,MAAM,EAAE,aAAa;gBACrB,QAAQ,EAAE,KAAK,EAAE,2CAA2C;aAC7D;SACF;KACF,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CACtC,QAAiB;IAEjB,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,CAAC;IAE5D,OAAO,kBAAkB,CAAC;QACxB,MAAM,EAAE,YAAY;QACpB,QAAQ,EAAE,QAAQ;QAClB,IAAI,EAAE,QAAQ,IAAI,GAAG,EAAE,8BAA8B;KACtD,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,4CAA4C,CAAC;QAClD,MAAM,EAAE,IAAI,EAAE,oCAAoC;QAClD,QAAQ,EAAE,MAAM,EAAE,0CAA0C;QAC5D,kBAAkB,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,4BAA4B;KACpE,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,kBAAkB,CAAC;QACxB,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MAX_COOKIE_AGE_SECONDS } from \"@/constants.js\";\nimport {\n CodeVerifier,\n OAuthTokenTypes,\n UserStorage,\n type CookieConfig,\n type TokensCookieConfig,\n} from \"./types.js\";\n\nexport interface CookieConfigOptions {\n /** Whether cookies should be secure (HTTPS only) */\n secure?: boolean;\n /** SameSite attribute for cookies */\n sameSite?: \"strict\" | \"lax\" | \"none\";\n /** Default max age in seconds for most cookies */\n defaultMaxAge?: number;\n /** Max age in seconds for refresh tokens */\n refreshTokenMaxAge?: number;\n /** Whether to use httpOnly for most cookies */\n httpOnly?: boolean;\n /** Path for cookies */\n path?: string;\n}\n\nexport interface CookiesConfigObject {\n tokens: TokensCookieConfig;\n user: CookieConfig;\n}\n\nexport interface ReactRouterCookiesConfigObject {\n tokens: TokensCookieConfig & {\n [UserStorage.USER]: CookieConfig;\n };\n user: CookieConfig;\n}\n\n/**\n * Creates a standardized cookie configuration for NextJS\n */\nexport function createCookieConfig(\n options: CookieConfigOptions = {},\n): CookiesConfigObject {\n const {\n secure = true,\n sameSite = \"strict\",\n defaultMaxAge = 60 * 60, // 1 hour\n refreshTokenMaxAge = MAX_COOKIE_AGE_SECONDS,\n httpOnly = true,\n path = \"/\",\n } = options;\n\n const baseCookieConfig: CookieConfig = {\n secure,\n sameSite,\n path,\n maxAge: defaultMaxAge,\n };\n\n return {\n tokens: {\n [OAuthTokenTypes.ID_TOKEN]: {\n ...baseCookieConfig,\n httpOnly,\n },\n [OAuthTokenTypes.ACCESS_TOKEN]: {\n ...baseCookieConfig,\n httpOnly,\n },\n [OAuthTokenTypes.REFRESH_TOKEN]: {\n ...baseCookieConfig,\n httpOnly,\n maxAge: refreshTokenMaxAge,\n },\n [OAuthTokenTypes.OIDC_SESSION_EXPIRES_AT]: {\n ...baseCookieConfig,\n httpOnly: false, // we need this to be available client-side\n },\n [CodeVerifier.COOKIE_NAME]: {\n ...baseCookieConfig,\n maxAge: 30 * 60, // 30 minutes\n httpOnly,\n },\n [CodeVerifier.APP_URL]: {\n ...baseCookieConfig,\n httpOnly,\n },\n },\n user: {\n ...baseCookieConfig,\n httpOnly: false, // we need this to be available client-side\n },\n };\n}\n\n/**\n * Creates a standardized cookie configuration for React Router with UserStorage\n */\nexport function createReactRouterCookieConfigWithUserStorage(\n options: CookieConfigOptions = {},\n): ReactRouterCookiesConfigObject {\n const basicConfig = createCookieConfig(options);\n const {\n secure = true,\n sameSite = \"strict\",\n defaultMaxAge = 60 * 60, // 1 hour\n path = \"/\",\n } = options;\n\n return {\n ...basicConfig,\n tokens: {\n ...basicConfig.tokens,\n [UserStorage.USER]: {\n secure,\n sameSite,\n path,\n maxAge: defaultMaxAge,\n httpOnly: false, // we need this to be available client-side\n },\n },\n };\n}\n\n/**\n * Creates cookie configuration optimized for NextJS\n */\nexport function createNextJSCookieConfig(\n basePath?: string,\n): CookiesConfigObject {\n const isProduction = process.env.NODE_ENV !== \"development\";\n\n return createCookieConfig({\n secure: isProduction,\n sameSite: \"strict\",\n path: basePath || \"/\", // Use basePath as cookie path\n });\n}\n\n/**\n * Creates cookie configuration optimized for React Router (iframe compatibility)\n */\nexport function createReactRouterCookieConfig(): ReactRouterCookiesConfigObject {\n return createReactRouterCookieConfigWithUserStorage({\n secure: true, // Required for iframe compatibility\n sameSite: \"none\", // Required for cross-site iframe requests\n refreshTokenMaxAge: 60 * 60 * 24 * 30, // 30 days for refresh token\n });\n}\n\n/**\n * Creates cookie configuration for development environments\n */\nexport function createDevelopmentCookieConfig(): CookiesConfigObject {\n return createCookieConfig({\n secure: false,\n sameSite: \"lax\",\n });\n}\n"]}
1
+ {"version":3,"file":"cookieConfig.js","sourceRoot":"","sources":["../../../src/shared/lib/cookieConfig.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EACL,cAAc,EACd,YAAY,EACZ,eAAe,EACf,WAAW,GAGZ,MAAM,YAAY,CAAC;AA6BpB;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAChC,UAA+B,EAAE;IAEjC,MAAM,EACJ,MAAM,GAAG,IAAI,EACb,QAAQ,GAAG,QAAQ,EACnB,aAAa,GAAG,EAAE,GAAG,EAAE,EAAE,SAAS;IAClC,kBAAkB,GAAG,sBAAsB,EAC3C,QAAQ,GAAG,IAAI,EACf,IAAI,GAAG,GAAG,GACX,GAAG,OAAO,CAAC;IAEZ,MAAM,gBAAgB,GAAiB;QACrC,MAAM;QACN,QAAQ;QACR,IAAI;QACJ,MAAM,EAAE,aAAa;KACtB,CAAC;IAEF,OAAO;QACL,MAAM,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AAI,CAAC,EAAE;gBAClB,MAAM;gBACN,QAAQ;gBACR,IAAI;gBACJ,MAAM,EAAE,aAAa;gBACrB,QAAQ,EAAE,KAAK,EAAE,2CAA2C;aAC7D;SACF;KACF,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CACtC,QAAiB;IAEjB,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,CAAC;IAE5D,OAAO,kBAAkB,CAAC;QACxB,MAAM,EAAE,YAAY;QACpB,QAAQ,EAAE,QAAQ;QAClB,IAAI,EAAE,QAAQ,IAAI,GAAG,EAAE,8BAA8B;KACtD,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,4CAA4C,CAAC;QAClD,MAAM,EAAE,IAAI,EAAE,oCAAoC;QAClD,QAAQ,EAAE,MAAM,EAAE,0CAA0C;QAC5D,kBAAkB,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,4BAA4B;KACpE,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,kBAAkB,CAAC;QACxB,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MAX_COOKIE_AGE_SECONDS } from \"@/constants.js\";\nimport {\n AuthFlowCookie,\n CodeVerifier,\n OAuthTokenTypes,\n UserStorage,\n type CookieConfig,\n type TokensCookieConfig,\n} from \"./types.js\";\n\nexport interface CookieConfigOptions {\n /** Whether cookies should be secure (HTTPS only) */\n secure?: boolean;\n /** SameSite attribute for cookies */\n sameSite?: \"strict\" | \"lax\" | \"none\";\n /** Default max age in seconds for most cookies */\n defaultMaxAge?: number;\n /** Max age in seconds for refresh tokens */\n refreshTokenMaxAge?: number;\n /** Whether to use httpOnly for most cookies */\n httpOnly?: boolean;\n /** Path for cookies */\n path?: string;\n}\n\nexport interface CookiesConfigObject {\n tokens: TokensCookieConfig;\n user: CookieConfig;\n}\n\nexport interface ReactRouterCookiesConfigObject {\n tokens: TokensCookieConfig & {\n [UserStorage.USER]: CookieConfig;\n };\n user: CookieConfig;\n}\n\n/**\n * Creates a standardized cookie configuration for NextJS\n */\nexport function createCookieConfig(\n options: CookieConfigOptions = {},\n): CookiesConfigObject {\n const {\n secure = true,\n sameSite = \"strict\",\n defaultMaxAge = 60 * 60, // 1 hour\n refreshTokenMaxAge = MAX_COOKIE_AGE_SECONDS,\n httpOnly = true,\n path = \"/\",\n } = options;\n\n const baseCookieConfig: CookieConfig = {\n secure,\n sameSite,\n path,\n maxAge: defaultMaxAge,\n };\n\n return {\n tokens: {\n [OAuthTokenTypes.ID_TOKEN]: {\n ...baseCookieConfig,\n httpOnly,\n },\n [OAuthTokenTypes.ACCESS_TOKEN]: {\n ...baseCookieConfig,\n httpOnly,\n },\n [OAuthTokenTypes.REFRESH_TOKEN]: {\n ...baseCookieConfig,\n httpOnly,\n maxAge: refreshTokenMaxAge,\n },\n [OAuthTokenTypes.OIDC_SESSION_EXPIRES_AT]: {\n ...baseCookieConfig,\n httpOnly: false, // we need this to be available client-side\n },\n [CodeVerifier.COOKIE_NAME]: {\n ...baseCookieConfig,\n maxAge: 30 * 60, // 30 minutes\n httpOnly,\n },\n [CodeVerifier.APP_URL]: {\n ...baseCookieConfig,\n httpOnly,\n },\n [AuthFlowCookie.RETURN_URL]: {\n ...baseCookieConfig,\n maxAge: 30 * 60, // 30 minutes\n httpOnly,\n },\n },\n user: {\n ...baseCookieConfig,\n httpOnly: false, // we need this to be available client-side\n },\n };\n}\n\n/**\n * Creates a standardized cookie configuration for React Router with UserStorage\n */\nexport function createReactRouterCookieConfigWithUserStorage(\n options: CookieConfigOptions = {},\n): ReactRouterCookiesConfigObject {\n const basicConfig = createCookieConfig(options);\n const {\n secure = true,\n sameSite = \"strict\",\n defaultMaxAge = 60 * 60, // 1 hour\n path = \"/\",\n } = options;\n\n return {\n ...basicConfig,\n tokens: {\n ...basicConfig.tokens,\n [UserStorage.USER]: {\n secure,\n sameSite,\n path,\n maxAge: defaultMaxAge,\n httpOnly: false, // we need this to be available client-side\n },\n },\n };\n}\n\n/**\n * Creates cookie configuration optimized for NextJS\n */\nexport function createNextJSCookieConfig(\n basePath?: string,\n): CookiesConfigObject {\n const isProduction = process.env.NODE_ENV !== \"development\";\n\n return createCookieConfig({\n secure: isProduction,\n sameSite: \"strict\",\n path: basePath || \"/\", // Use basePath as cookie path\n });\n}\n\n/**\n * Creates cookie configuration optimized for React Router (iframe compatibility)\n */\nexport function createReactRouterCookieConfig(): ReactRouterCookiesConfigObject {\n return createReactRouterCookieConfigWithUserStorage({\n secure: true, // Required for iframe compatibility\n sameSite: \"none\", // Required for cross-site iframe requests\n refreshTokenMaxAge: 60 * 60 * 24 * 30, // 30 days for refresh token\n });\n}\n\n/**\n * Creates cookie configuration for development environments\n */\nexport function createDevelopmentCookieConfig(): CookiesConfigObject {\n return createCookieConfig({\n secure: false,\n sameSite: \"lax\",\n });\n}\n"]}
@@ -11,6 +11,14 @@ export declare enum CodeVerifier {
11
11
  COOKIE_NAME = "code_verifier",
12
12
  APP_URL = "app_url"
13
13
  }
14
+ /**
15
+ * Cookies used during the authentication flow that are temporary/transient.
16
+ * These cookies are set during the auth process and cleared after use.
17
+ */
18
+ export declare enum AuthFlowCookie {
19
+ /** Stores the original URL the user was trying to access before being redirected to login */
20
+ RETURN_URL = "civic_return_url"
21
+ }
14
22
  export declare enum UserStorage {
15
23
  USER = "user"
16
24
  }
@@ -22,8 +30,8 @@ export interface CookieConfig {
22
30
  maxAge?: number;
23
31
  httpOnly?: boolean;
24
32
  }
25
- export type KeySetter = OAuthTokenTypes | CodeVerifier | UserStorage;
26
- export type TokensCookieConfig = Record<OAuthTokenTypes | CodeVerifier, CookieConfig>;
33
+ export type KeySetter = OAuthTokenTypes | CodeVerifier | AuthFlowCookie | UserStorage;
34
+ export type TokensCookieConfig = Record<OAuthTokenTypes | CodeVerifier | AuthFlowCookie, CookieConfig>;
27
35
  export type CivicAuthConfig = null | {
28
36
  clientId: string;
29
37
  redirectUrl: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/shared/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAExE,oBAAY,eAAe;IACzB,QAAQ,aAAa;IACrB,YAAY,iBAAiB;IAC7B,aAAa,kBAAkB;IAC/B,uBAAuB,4BAA4B;CACpD;AAED,eAAO,MAAM,mBAAmB,aAAa,CAAC;AAC9C,eAAO,MAAM,0BAA0B,oBAAoB,CAAC;AAE5D,oBAAY,YAAY;IACtB,WAAW,kBAAkB;IAC7B,OAAO,YAAY;CACpB;AACD,oBAAY,WAAW;IACrB,IAAI,SAAS;CACd;AACD,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,MAAM,CAAC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AACD,MAAM,MAAM,SAAS,GAAG,eAAe,GAAG,YAAY,GAAG,WAAW,CAAC;AAErE,MAAM,MAAM,kBAAkB,GAAG,MAAM,CACrC,eAAe,GAAG,YAAY,EAC9B,YAAY,CACb,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,IAAI,GAAG;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,SAAS,CA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AAG,YAAY,GAAG,cAAc,EAC/C,YAAY,CACb,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,IAAI,GAAG;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,SAAS,CAAC;IACrB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC"}
@@ -12,6 +12,15 @@ export var CodeVerifier;
12
12
  CodeVerifier["COOKIE_NAME"] = "code_verifier";
13
13
  CodeVerifier["APP_URL"] = "app_url";
14
14
  })(CodeVerifier || (CodeVerifier = {}));
15
+ /**
16
+ * Cookies used during the authentication flow that are temporary/transient.
17
+ * These cookies are set during the auth process and cleared after use.
18
+ */
19
+ export var AuthFlowCookie;
20
+ (function (AuthFlowCookie) {
21
+ /** Stores the original URL the user was trying to access before being redirected to login */
22
+ AuthFlowCookie["RETURN_URL"] = "civic_return_url";
23
+ })(AuthFlowCookie || (AuthFlowCookie = {}));
15
24
  export var UserStorage;
16
25
  (function (UserStorage) {
17
26
  UserStorage["USER"] = "user";
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/shared/lib/types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,eAKX;AALD,WAAY,eAAe;IACzB,wCAAqB,CAAA;IACrB,gDAA6B,CAAA;IAC7B,kDAA+B,CAAA;IAC/B,sEAAmD,CAAA;AACrD,CAAC,EALW,eAAe,KAAf,eAAe,QAK1B;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAC9C,MAAM,CAAC,MAAM,0BAA0B,GAAG,iBAAiB,CAAC;AAE5D,MAAM,CAAN,IAAY,YAGX;AAHD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,mCAAmB,CAAA;AACrB,CAAC,EAHW,YAAY,KAAZ,YAAY,QAGvB;AACD,MAAM,CAAN,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,4BAAa,CAAA;AACf,CAAC,EAFW,WAAW,KAAX,WAAW,QAEtB","sourcesContent":["import type { DisplayMode, Endpoints, FrameworkType } from \"@/types.js\";\n\nexport enum OAuthTokenTypes {\n ID_TOKEN = \"id_token\",\n ACCESS_TOKEN = \"access_token\",\n REFRESH_TOKEN = \"refresh_token\",\n OIDC_SESSION_EXPIRES_AT = \"oidc_session_expires_at\",\n}\n\nexport const AUTH_SERVER_SESSION = \"_session\";\nexport const AUTH_SERVER_LEGACY_SESSION = \"_session.legacy\";\n\nexport enum CodeVerifier {\n COOKIE_NAME = \"code_verifier\",\n APP_URL = \"app_url\",\n}\nexport enum UserStorage {\n USER = \"user\",\n}\nexport interface CookieConfig {\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n domain?: string;\n path?: string;\n maxAge?: number;\n httpOnly?: boolean;\n}\nexport type KeySetter = OAuthTokenTypes | CodeVerifier | UserStorage;\n\nexport type TokensCookieConfig = Record<\n OAuthTokenTypes | CodeVerifier,\n CookieConfig\n>;\n\nexport type CivicAuthConfig = null | {\n clientId: string;\n redirectUrl: string;\n loginSuccessUrl?: string;\n logoutRedirectUrl: string;\n oauthServer: string;\n endpoints: Endpoints;\n scopes: string[];\n nonce?: string;\n challengeUrl?: string;\n refreshUrl?: string;\n logoutUrl?: string;\n displayMode?: DisplayMode;\n framework?: FrameworkType;\n autoRedirect?: boolean;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/shared/lib/types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,eAKX;AALD,WAAY,eAAe;IACzB,wCAAqB,CAAA;IACrB,gDAA6B,CAAA;IAC7B,kDAA+B,CAAA;IAC/B,sEAAmD,CAAA;AACrD,CAAC,EALW,eAAe,KAAf,eAAe,QAK1B;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAC9C,MAAM,CAAC,MAAM,0BAA0B,GAAG,iBAAiB,CAAC;AAE5D,MAAM,CAAN,IAAY,YAGX;AAHD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,mCAAmB,CAAA;AACrB,CAAC,EAHW,YAAY,KAAZ,YAAY,QAGvB;AAED;;;GAGG;AACH,MAAM,CAAN,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,6FAA6F;IAC7F,iDAA+B,CAAA;AACjC,CAAC,EAHW,cAAc,KAAd,cAAc,QAGzB;AAED,MAAM,CAAN,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,4BAAa,CAAA;AACf,CAAC,EAFW,WAAW,KAAX,WAAW,QAEtB","sourcesContent":["import type { DisplayMode, Endpoints, FrameworkType } from \"@/types.js\";\n\nexport enum OAuthTokenTypes {\n ID_TOKEN = \"id_token\",\n ACCESS_TOKEN = \"access_token\",\n REFRESH_TOKEN = \"refresh_token\",\n OIDC_SESSION_EXPIRES_AT = \"oidc_session_expires_at\",\n}\n\nexport const AUTH_SERVER_SESSION = \"_session\";\nexport const AUTH_SERVER_LEGACY_SESSION = \"_session.legacy\";\n\nexport enum CodeVerifier {\n COOKIE_NAME = \"code_verifier\",\n APP_URL = \"app_url\",\n}\n\n/**\n * Cookies used during the authentication flow that are temporary/transient.\n * These cookies are set during the auth process and cleared after use.\n */\nexport enum AuthFlowCookie {\n /** Stores the original URL the user was trying to access before being redirected to login */\n RETURN_URL = \"civic_return_url\",\n}\n\nexport enum UserStorage {\n USER = \"user\",\n}\nexport interface CookieConfig {\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n domain?: string;\n path?: string;\n maxAge?: number;\n httpOnly?: boolean;\n}\nexport type KeySetter =\n | OAuthTokenTypes\n | CodeVerifier\n | AuthFlowCookie\n | UserStorage;\n\nexport type TokensCookieConfig = Record<\n OAuthTokenTypes | CodeVerifier | AuthFlowCookie,\n CookieConfig\n>;\n\nexport type CivicAuthConfig = null | {\n clientId: string;\n redirectUrl: string;\n loginSuccessUrl?: string;\n logoutRedirectUrl: string;\n oauthServer: string;\n endpoints: Endpoints;\n scopes: string[];\n nonce?: string;\n challengeUrl?: string;\n refreshUrl?: string;\n logoutUrl?: string;\n displayMode?: DisplayMode;\n framework?: FrameworkType;\n autoRedirect?: boolean;\n};\n"]}
@@ -75,6 +75,25 @@ export declare function resolveEndpointUrl(baseUrl: string, endpoint: string | u
75
75
  * Checks common proxy headers before falling back to URL or environment
76
76
  */
77
77
  export declare function getProtocolFromRequest(request?: Request): string;
78
+ /**
79
+ * Sanitizes and validates a return URL to prevent open redirect vulnerabilities.
80
+ * Only allows relative paths or same-origin URLs.
81
+ *
82
+ * @param url - The URL to validate (e.g., "/admin/dashboard?tab=settings")
83
+ * @param baseUrl - The base URL of the application (e.g., "https://example.com")
84
+ * @returns The sanitized URL if valid, or null if the URL fails validation
85
+ *
86
+ * @example
87
+ * // Valid relative path
88
+ * sanitizeReturnUrl("/admin/chat?param=123", "https://example.com")
89
+ * // Returns: "/admin/chat?param=123"
90
+ *
91
+ * @example
92
+ * // Invalid - different domain
93
+ * sanitizeReturnUrl("https://evil.com/phish", "https://example.com")
94
+ * // Returns: null
95
+ */
96
+ export declare function sanitizeReturnUrl(url: string | null | undefined, baseUrl: string): string | null;
78
97
  /**
79
98
  * Detect Safari browser from user agent
80
99
  */
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../../src/shared/lib/util.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,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G,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC9B,OAAO,EAAE,MAAM,GACd,MAAM,GAAG,IAAI,CAyGf;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAK1D;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAKzD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG;IACzD,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,KAAK,GAAG,MAAM,CAAC;CAC1B,CA4BA"}
@@ -374,6 +374,124 @@ export function getProtocolFromRequest(request) {
374
374
  const url = new URL(request.url);
375
375
  return url.protocol;
376
376
  }
377
+ // Maximum URL length to prevent cookie size issues (~4KB browser limit)
378
+ const MAX_RETURN_URL_LENGTH = 2048;
379
+ /**
380
+ * Sanitizes and validates a return URL to prevent open redirect vulnerabilities.
381
+ * Only allows relative paths or same-origin URLs.
382
+ *
383
+ * @param url - The URL to validate (e.g., "/admin/dashboard?tab=settings")
384
+ * @param baseUrl - The base URL of the application (e.g., "https://example.com")
385
+ * @returns The sanitized URL if valid, or null if the URL fails validation
386
+ *
387
+ * @example
388
+ * // Valid relative path
389
+ * sanitizeReturnUrl("/admin/chat?param=123", "https://example.com")
390
+ * // Returns: "/admin/chat?param=123"
391
+ *
392
+ * @example
393
+ * // Invalid - different domain
394
+ * sanitizeReturnUrl("https://evil.com/phish", "https://example.com")
395
+ * // Returns: null
396
+ */
397
+ export function sanitizeReturnUrl(url, baseUrl) {
398
+ // Handle null/undefined/empty input
399
+ if (!url || typeof url !== "string") {
400
+ return null;
401
+ }
402
+ const trimmedUrl = url.trim();
403
+ if (!trimmedUrl) {
404
+ return null;
405
+ }
406
+ // Check URL length to prevent cookie size issues
407
+ if (trimmedUrl.length > MAX_RETURN_URL_LENGTH) {
408
+ logger.warn("Return URL too long, rejecting", {
409
+ length: trimmedUrl.length,
410
+ maxLength: MAX_RETURN_URL_LENGTH,
411
+ });
412
+ return null;
413
+ }
414
+ // Block dangerous URL schemes
415
+ const lowerUrl = trimmedUrl.toLowerCase();
416
+ const dangerousSchemes = [
417
+ "javascript:",
418
+ "data:",
419
+ "vbscript:",
420
+ "file:",
421
+ "about:",
422
+ ];
423
+ for (const scheme of dangerousSchemes) {
424
+ if (lowerUrl.startsWith(scheme)) {
425
+ logger.warn("Rejected URL with dangerous scheme", {
426
+ scheme,
427
+ url: trimmedUrl.substring(0, 50),
428
+ });
429
+ return null;
430
+ }
431
+ }
432
+ // Block protocol-relative URLs (//evil.com) - these inherit the current protocol
433
+ // and can redirect to any domain
434
+ if (trimmedUrl.startsWith("//")) {
435
+ logger.warn("Rejected protocol-relative URL", {
436
+ url: trimmedUrl.substring(0, 50),
437
+ });
438
+ return null;
439
+ }
440
+ // Check if it's a relative path (starts with / but not //)
441
+ if (trimmedUrl.startsWith("/") && !trimmedUrl.startsWith("//")) {
442
+ // Relative paths are safe - they stay on the same origin
443
+ // Normalize by removing any .. or . segments to prevent path traversal confusion
444
+ // Note: Path traversal on URLs doesn't cross origins, but we clean it up anyway
445
+ try {
446
+ // Use URL constructor to normalize the path
447
+ const baseUrlObj = new URL(baseUrl);
448
+ const fullUrl = new URL(trimmedUrl, baseUrlObj);
449
+ // Verify we're still on the same origin after normalization
450
+ if (fullUrl.origin !== baseUrlObj.origin) {
451
+ logger.warn("Rejected URL after normalization changed origin", {
452
+ original: trimmedUrl.substring(0, 50),
453
+ normalizedOrigin: fullUrl.origin,
454
+ expectedOrigin: baseUrlObj.origin,
455
+ });
456
+ return null;
457
+ }
458
+ // Return just the path + query + hash (relative URL)
459
+ return fullUrl.pathname + fullUrl.search + fullUrl.hash;
460
+ }
461
+ catch {
462
+ // Invalid URL format
463
+ logger.warn("Rejected malformed relative URL", {
464
+ url: trimmedUrl.substring(0, 50),
465
+ });
466
+ return null;
467
+ }
468
+ }
469
+ // Check if it's an absolute URL
470
+ try {
471
+ const parsedUrl = new URL(trimmedUrl);
472
+ const parsedBase = new URL(baseUrl);
473
+ // Only allow same-origin URLs
474
+ if (parsedUrl.origin === parsedBase.origin) {
475
+ // Return relative path to avoid storing full URLs unnecessarily
476
+ return parsedUrl.pathname + parsedUrl.search + parsedUrl.hash;
477
+ }
478
+ // Different origin - reject to prevent open redirect
479
+ logger.warn("Rejected URL with different origin", {
480
+ url: trimmedUrl.substring(0, 50),
481
+ urlOrigin: parsedUrl.origin,
482
+ expectedOrigin: parsedBase.origin,
483
+ });
484
+ return null;
485
+ }
486
+ catch {
487
+ // Not a valid absolute URL - might be a malformed URL
488
+ // Reject to be safe
489
+ logger.warn("Rejected invalid absolute URL", {
490
+ url: trimmedUrl.substring(0, 50),
491
+ });
492
+ return null;
493
+ }
494
+ }
377
495
  /**
378
496
  * Detect Safari browser from user agent
379
497
  */