@civic/auth 0.13.0 → 0.13.1-beta.1

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 (69) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +102 -1
  3. package/dist/lib/analytics.d.ts.map +1 -1
  4. package/dist/lib/jwt.d.ts.map +1 -1
  5. package/dist/lib/logger.d.ts.map +1 -1
  6. package/dist/lib/oauth.d.ts +12 -1
  7. package/dist/lib/oauth.d.ts.map +1 -1
  8. package/dist/lib/oauth.js +29 -1
  9. package/dist/lib/oauth.js.map +1 -1
  10. package/dist/lib/obj.d.ts.map +1 -1
  11. package/dist/lib/postMessage.d.ts.map +1 -1
  12. package/dist/lib/windowUtil.d.ts.map +1 -1
  13. package/dist/nextjs/config.d.ts +2 -11
  14. package/dist/nextjs/config.d.ts.map +1 -1
  15. package/dist/nextjs/config.js.map +1 -1
  16. package/dist/nextjs/cookies.d.ts.map +1 -1
  17. package/dist/nextjs/cookies.js +11 -10
  18. package/dist/nextjs/cookies.js.map +1 -1
  19. package/dist/nextjs/hooks/useInitialAuthConfig.d.ts.map +1 -1
  20. package/dist/nextjs/index.d.ts.map +1 -1
  21. package/dist/nextjs/middleware.d.ts.map +1 -1
  22. package/dist/nextjs/middleware.js +18 -3
  23. package/dist/nextjs/middleware.js.map +1 -1
  24. package/dist/nextjs/providers/NextAuthProviderClient.d.ts.map +1 -1
  25. package/dist/nextjs/routeHandler.d.ts.map +1 -1
  26. package/dist/nextjs/routeHandler.js +21 -92
  27. package/dist/nextjs/routeHandler.js.map +1 -1
  28. package/dist/nextjs/utils.d.ts +9 -3
  29. package/dist/nextjs/utils.d.ts.map +1 -1
  30. package/dist/nextjs/utils.js +20 -61
  31. package/dist/nextjs/utils.js.map +1 -1
  32. package/dist/react-router-7/routeHandler.d.ts.map +1 -1
  33. package/dist/reactjs/components/ButtonContentOrLoader.d.ts.map +1 -1
  34. package/dist/reactjs/components/SignInButton.d.ts.map +1 -1
  35. package/dist/reactjs/components/SignOutButton.d.ts.map +1 -1
  36. package/dist/reactjs/components/UserButton.d.ts.map +1 -1
  37. package/dist/reactjs/components/utils.d.ts.map +1 -1
  38. package/dist/reactjs/hooks/useToken.d.ts.map +1 -1
  39. package/dist/reactjs/hooks/useUser.d.ts.map +1 -1
  40. package/dist/reactjs/styles/colors.d.ts.map +1 -1
  41. package/dist/server/config.d.ts +23 -0
  42. package/dist/server/config.d.ts.map +1 -1
  43. package/dist/server/config.js.map +1 -1
  44. package/dist/server/session.d.ts +57 -0
  45. package/dist/server/session.d.ts.map +1 -1
  46. package/dist/server/session.js +222 -9
  47. package/dist/server/session.js.map +1 -1
  48. package/dist/shared/components/LoadingIcon.d.ts.map +1 -1
  49. package/dist/shared/lib/cookieConfig.d.ts.map +1 -1
  50. package/dist/shared/lib/cookieConfig.js +6 -1
  51. package/dist/shared/lib/cookieConfig.js.map +1 -1
  52. package/dist/shared/lib/iframeUtils.d.ts.map +1 -1
  53. package/dist/shared/lib/session.d.ts.map +1 -1
  54. package/dist/shared/lib/types.d.ts +5 -1
  55. package/dist/shared/lib/types.d.ts.map +1 -1
  56. package/dist/shared/lib/types.js +4 -0
  57. package/dist/shared/lib/types.js.map +1 -1
  58. package/dist/shared/lib/util.d.ts +38 -1
  59. package/dist/shared/lib/util.d.ts.map +1 -1
  60. package/dist/shared/lib/util.js +104 -0
  61. package/dist/shared/lib/util.js.map +1 -1
  62. package/dist/shared/version.d.ts +1 -1
  63. package/dist/shared/version.d.ts.map +1 -1
  64. package/dist/shared/version.js +1 -1
  65. package/dist/shared/version.js.map +1 -1
  66. package/dist/utils.d.ts.map +1 -1
  67. package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -1
  68. package/dist/vanillajs/utils/logger.d.ts.map +1 -1
  69. package/package.json +1 -1
@@ -2,9 +2,10 @@ import { NextResponse } from "next/server.js";
2
2
  import { resolveAuthConfig } from "../nextjs/config.js";
3
3
  import { loggers } from "../lib/logger.js";
4
4
  import { ServerAuthenticationResolver } from "../server/ServerAuthenticationResolver.js";
5
- import { shouldAttemptRefresh, shouldSkipAuthForSystemUrls, handleLoginUrl, shouldSkipAuthForRoutePatterns, handleUnauthenticatedUser, copyCivicCookies, } from "./utils.js";
5
+ import { shouldAttemptRefresh, shouldSkipAuthForSystemUrls, handleLoginUrl, shouldSkipAuthForRoutePatterns, handleUnauthenticatedUser, copyCivicCookies, getOriginUrl, removeBasePathFromPath, } from "./utils.js";
6
6
  import { NextjsMiddlewareCookieStorage } from "./utils.js";
7
7
  import { UserStorage } from "../shared/lib/types.js";
8
+ import { CivicAuth } from "../server/session.js";
8
9
  const logger = loggers.nextjs.middleware;
9
10
  /**
10
11
  * use a ServerAuthenticationResolver to validate the existing session
@@ -62,7 +63,9 @@ const applyAuth = async (authConfig, request) => {
62
63
  // Step 1: Understand the current authentication state
63
64
  const session = await validateAuthTokensIfPresent(authConfigWithDefaults, storage);
64
65
  const shouldSkipAuthForRoutePatternsCheck = shouldSkipAuthForRoutePatterns(request.nextUrl.pathname, authConfigWithDefaults);
65
- const pathNameIsLoginUrl = request.nextUrl.pathname === authConfigWithDefaults.loginUrl;
66
+ // Normalize loginUrl for comparison (remove basePath if present)
67
+ const loginPathWithoutBasePath = removeBasePathFromPath(authConfigWithDefaults.loginUrl, authConfigWithDefaults.basePath);
68
+ const pathNameIsLoginUrl = request.nextUrl.pathname === loginPathWithoutBasePath;
66
69
  logger.debug("Authentication state:", {
67
70
  authenticated: session.authenticated,
68
71
  pathName: request.nextUrl.pathname,
@@ -71,7 +74,19 @@ const applyAuth = async (authConfig, request) => {
71
74
  shouldSkipAuthForSystemUrls: shouldSkipAuthForSystemUrlsCheck,
72
75
  shouldSkipAuthForRoutePatterns: shouldSkipAuthForRoutePatternsCheck,
73
76
  });
74
- // Step 2: Attempt token refresh if needed (the OAuth pipeline approach) // Handle login URL with special logic
77
+ // Step 2: Handle deep link cookie for unauthenticated users using CivicAuth
78
+ // handleDeepLinking automatically detects if we're at loginUrl or a protected route
79
+ // and applies the appropriate logic for each case
80
+ if (!session.authenticated) {
81
+ const civicAuth = new CivicAuth(storage, {
82
+ ...authConfigWithDefaults,
83
+ redirectUrl: authConfigWithDefaults.callbackUrl,
84
+ });
85
+ const originUrl = getOriginUrl(request, authConfigWithDefaults);
86
+ const requestUrl = `${originUrl}${request.nextUrl.pathname}${request.nextUrl.search}${request.nextUrl.hash}`;
87
+ await civicAuth.handleDeepLinking(requestUrl, originUrl);
88
+ }
89
+ // Step 3: Handle login URL with special logic
75
90
  if (pathNameIsLoginUrl) {
76
91
  handleLoginUrl(request.nextUrl.pathname, session, authConfigWithDefaults);
77
92
  return response; // Always allow access to login URL
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAK9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AAExF,OAAO,EACL,oBAAoB,EACpB,2BAA2B,EAC3B,cAAc,EACd,8BAA8B,EAC9B,yBAAyB,EACzB,gBAAgB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;AAMzC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,KAAK,EAC9C,sBAA8C,EAC9C,OAAsC,EAChB,EAAE;IACxB,IAAI,CAAC;QACH,MAAM,kBAAkB,GAAG,MAAM,4BAA4B,CAAC,KAAK,CACjE;YACE,GAAG,sBAAsB;YACzB,WAAW,EAAE,s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AAM,kBAAkB,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;YAErD,iEAAiE;YACjE,6DAA6D;YAC7D,0BAA0B;YAC1B,IAAI,QAAQ,EAAE,CAAC;gBACb,gBAAgB,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;YACjD,CAAC;YACD,OAAO,kBAAkB,CAAC;QAC5B,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Authenticates the user on all requests by checking the token cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * logger.debug('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * logger.debug('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport type {\n AuthConfigWithDefaults,\n OptionalAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { SessionData } from \"@/types.js\";\nimport {\n shouldAttemptRefresh,\n shouldSkipAuthForSystemUrls,\n handleLoginUrl,\n shouldSkipAuthForRoutePatterns,\n handleUnauthenticatedUser,\n copyCivicCookies,\n} from \"./utils.js\";\nimport { NextjsMiddlewareCookieStorage } from \"./utils.js\";\nimport { UserStorage } from \"@/shared/lib/types.js\";\n\nconst logger = loggers.nextjs.middleware;\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n/**\n * use a ServerAuthenticationResolver to validate the existing session\n * using NextJS cookie storage\n * @param authConfigWithDefaults\n * @param request NextRequest object from middleware\n * @returns {Promise<SessionData>}\n */\nexport const validateAuthTokensIfPresent = async (\n authConfigWithDefaults: AuthConfigWithDefaults,\n storage: NextjsMiddlewareCookieStorage,\n): Promise<SessionData> => {\n try {\n const authSessionService = await ServerAuthenticationResolver.build(\n {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n },\n storage,\n );\n // validate the existing session and rehydrate and update cookies to the response if necessary\n const existingSession = await authSessionService.validateExistingSession();\n return existingSession;\n } catch (error) {\n logger.error(\"Error validating tokens\", error);\n return { authenticated: false };\n }\n};\n\n// internal - used by all exported functions\n/**\n * Core authentication middleware logic.\n *\n * The Authentication Story:\n * 1. Validate tokens to understand current authentication state\n * 2. Attempt token refresh if needed (the OAuth pipeline approach)\n * 3. Apply route-specific authentication rules based on final state\n */\nconst applyAuth = async (\n authConfig: OptionalAuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n const response = NextResponse.next({\n request, // ensure incoming request headers get propagated\n });\n const cookieConfig = {\n ...authConfigWithDefaults?.cookies?.tokens,\n [UserStorage.USER]: authConfigWithDefaults?.cookies?.user || {},\n };\n logger.debug(\"Incoming request:\", {\n pathName: request.nextUrl.pathname,\n method: request.method,\n });\n const storage = new NextjsMiddlewareCookieStorage(\n cookieConfig,\n request,\n response,\n );\n // check if the incoming path is a system URL\n const shouldSkipAuthForSystemUrlsCheck = shouldSkipAuthForSystemUrls(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Skip authentication for system URLs (callback, challenge, logout)\n // we don't want to validate the session in this case as this would\n // auto-hydrate and potential conflict with the logic of the api call\n if (shouldSkipAuthForSystemUrlsCheck) {\n return response;\n }\n\n // Step 1: Understand the current authentication state\n const session = await validateAuthTokensIfPresent(\n authConfigWithDefaults,\n storage,\n );\n\n const shouldSkipAuthForRoutePatternsCheck = shouldSkipAuthForRoutePatterns(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n const pathNameIsLoginUrl =\n request.nextUrl.pathname === authConfigWithDefaults.loginUrl;\n logger.debug(\"Authentication state:\", {\n authenticated: session.authenticated,\n pathName: request.nextUrl.pathname,\n pathNameIsLoginUrl,\n shouldAttemptRefresh: shouldAttemptRefresh(session),\n shouldSkipAuthForSystemUrls: shouldSkipAuthForSystemUrlsCheck,\n shouldSkipAuthForRoutePatterns: shouldSkipAuthForRoutePatternsCheck,\n });\n\n // Step 2: Attempt token refresh if needed (the OAuth pipeline approach) // Handle login URL with special logic\n if (pathNameIsLoginUrl) {\n handleLoginUrl(request.nextUrl.pathname, session, authConfigWithDefaults);\n return response; // Always allow access to login URL\n }\n\n // Skip authentication for routes not matching include/exclude patterns\n if (shouldSkipAuthForRoutePatternsCheck) {\n return response;\n }\n\n // Handle unauthenticated users on protected routes\n if (!session.authenticated) {\n return handleUnauthenticatedUser(\n session,\n request,\n response,\n storage,\n authConfigWithDefaults,\n );\n }\n\n // Happy ending - authentication passed\n logger.debug(\"→ Authentication successful, allowing access to\", response.url);\n copyCivicCookies(response, request);\n const authenticatedResponse = NextResponse.next({\n request, // ensure that the cookies get added to the request as well as the response\n });\n copyCivicCookies(response, authenticatedResponse);\n return authenticatedResponse;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig: OptionalAuthConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return auth()(middleware);\n}\n\nconst isRedirectResponse = (response?: NextResponse) =>\n response && response.status === 307;\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * export default auth(authConfig: AuthConfig ) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: OptionalAuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n // if the response is redirected it means that the user is not authenticated\n // so we skip the rest of the custom middleware to redirect to the login page\n if (response && isRedirectResponse(response)) {\n logger.debug(\n \"User is unauthenticated, redirecting to \",\n response.headers.get(\"location\"),\n );\n return response;\n }\n // ensure requests get the cookies in case of redirects\n if (response) {\n copyCivicCookies(response, request);\n }\n const middlewareResponse = await middleware(request);\n\n // we need to ensure that the civic cookies that were potentially\n // added by CivicAuth are set on the final response after all\n // middleware has been run\n if (response) {\n copyCivicCookies(response, middlewareResponse);\n }\n return middlewareResponse;\n };\n };\n}\n"]}
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/nextjs/middleware.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAK9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AAExF,OAAO,EACL,oBAAoB,EACpB,2BAA2B,EAC3B,cAAc,EACd,8BAA8B,EAC9B,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,sBAAsB,GACvB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB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cookie\n *\n * Usage:\n * Option 1: use if no other middleware (e.g. no next-intl etc)\n * export default authMiddleware();\n *\n * Option 2: use if other middleware is needed - default auth config\n * export default withAuth((request) => {\n * logger.debug('in custom middleware', request.nextUrl.pathname);\n * return NextResponse.next();\n * })\n *\n * Option 3: use if other middleware is needed - specifying auth config\n * const withCivicAuth = auth({ loginUrl: '/login', include: ['/[.*]/user'] })\n * export default withCivicAuth((request) => {\n * logger.debug('in custom middleware', request.url);\n * return NextResponse.next();\n * })\n *\n */\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport type {\n AuthConfigWithDefaults,\n OptionalAuthConfig,\n} from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { ServerAuthenticationResolver } from \"@/server/ServerAuthenticationResolver.js\";\nimport type { SessionData } from \"@/types.js\";\nimport {\n shouldAttemptRefresh,\n shouldSkipAuthForSystemUrls,\n handleLoginUrl,\n shouldSkipAuthForRoutePatterns,\n handleUnauthenticatedUser,\n copyCivicCookies,\n getOriginUrl,\n removeBasePathFromPath,\n} from \"./utils.js\";\nimport { NextjsMiddlewareCookieStorage } from \"./utils.js\";\nimport { UserStorage } from \"@/shared/lib/types.js\";\nimport { CivicAuth } from \"@/server/session.js\";\n\nconst logger = loggers.nextjs.middleware;\n\ntype Middleware = (\n request: NextRequest,\n) => Promise<NextResponse> | NextResponse;\n\n/**\n * use a ServerAuthenticationResolver to validate the existing session\n * using NextJS cookie storage\n * @param authConfigWithDefaults\n * @param request NextRequest object from middleware\n * @returns {Promise<SessionData>}\n */\nexport const validateAuthTokensIfPresent = async (\n authConfigWithDefaults: AuthConfigWithDefaults,\n storage: NextjsMiddlewareCookieStorage,\n): Promise<SessionData> => {\n try {\n const authSessionService = await ServerAuthenticationResolver.build(\n {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n },\n storage,\n );\n // validate the existing session and rehydrate and update cookies to the response if necessary\n const existingSession = await authSessionService.validateExistingSession();\n return existingSession;\n } catch (error) {\n logger.error(\"Error validating tokens\", error);\n return { authenticated: false };\n }\n};\n\n// internal - used by all exported functions\n/**\n * Core authentication middleware logic.\n *\n * The Authentication Story:\n * 1. Validate tokens to understand current authentication state\n * 2. Attempt token refresh if needed (the OAuth pipeline approach)\n * 3. Apply route-specific authentication rules based on final state\n */\nconst applyAuth = async (\n authConfig: OptionalAuthConfig,\n request: NextRequest,\n): Promise<NextResponse | undefined> => {\n const authConfigWithDefaults = resolveAuthConfig(authConfig);\n const response = NextResponse.next({\n request, // ensure incoming request headers get propagated\n });\n const cookieConfig = {\n ...authConfigWithDefaults?.cookies?.tokens,\n [UserStorage.USER]: authConfigWithDefaults?.cookies?.user || {},\n };\n logger.debug(\"Incoming request:\", {\n pathName: request.nextUrl.pathname,\n method: request.method,\n });\n const storage = new NextjsMiddlewareCookieStorage(\n cookieConfig,\n request,\n response,\n );\n // check if the incoming path is a system URL\n const shouldSkipAuthForSystemUrlsCheck = shouldSkipAuthForSystemUrls(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Skip authentication for system URLs (callback, challenge, logout)\n // we don't want to validate the session in this case as this would\n // auto-hydrate and potential conflict with the logic of the api call\n if (shouldSkipAuthForSystemUrlsCheck) {\n return response;\n }\n\n // Step 1: Understand the current authentication state\n const session = await validateAuthTokensIfPresent(\n authConfigWithDefaults,\n storage,\n );\n\n const shouldSkipAuthForRoutePatternsCheck = shouldSkipAuthForRoutePatterns(\n request.nextUrl.pathname,\n authConfigWithDefaults,\n );\n\n // Normalize loginUrl for comparison (remove basePath if present)\n const loginPathWithoutBasePath = removeBasePathFromPath(\n authConfigWithDefaults.loginUrl,\n authConfigWithDefaults.basePath,\n );\n const pathNameIsLoginUrl =\n request.nextUrl.pathname === loginPathWithoutBasePath;\n\n logger.debug(\"Authentication state:\", {\n authenticated: session.authenticated,\n pathName: request.nextUrl.pathname,\n pathNameIsLoginUrl,\n shouldAttemptRefresh: shouldAttemptRefresh(session),\n shouldSkipAuthForSystemUrls: shouldSkipAuthForSystemUrlsCheck,\n shouldSkipAuthForRoutePatterns: shouldSkipAuthForRoutePatternsCheck,\n });\n\n // Step 2: Handle deep link cookie for unauthenticated users using CivicAuth\n // handleDeepLinking automatically detects if we're at loginUrl or a protected route\n // and applies the appropriate logic for each case\n if (!session.authenticated) {\n const civicAuth = new CivicAuth(storage, {\n ...authConfigWithDefaults,\n redirectUrl: authConfigWithDefaults.callbackUrl,\n });\n const originUrl = getOriginUrl(request, authConfigWithDefaults);\n const requestUrl = `${originUrl}${request.nextUrl.pathname}${request.nextUrl.search}${request.nextUrl.hash}`;\n\n await civicAuth.handleDeepLinking(requestUrl, originUrl);\n }\n\n // Step 3: Handle login URL with special logic\n if (pathNameIsLoginUrl) {\n handleLoginUrl(request.nextUrl.pathname, session, authConfigWithDefaults);\n return response; // Always allow access to login URL\n }\n\n // Skip authentication for routes not matching include/exclude patterns\n if (shouldSkipAuthForRoutePatternsCheck) {\n return response;\n }\n\n // Handle unauthenticated users on protected routes\n if (!session.authenticated) {\n return handleUnauthenticatedUser(\n session,\n request,\n response,\n storage,\n authConfigWithDefaults,\n );\n }\n\n // Happy ending - authentication passed\n logger.debug(\"→ Authentication successful, allowing access to\", response.url);\n copyCivicCookies(response, request);\n const authenticatedResponse = NextResponse.next({\n request, // ensure that the cookies get added to the request as well as the response\n });\n copyCivicCookies(response, authenticatedResponse);\n return authenticatedResponse;\n};\n\n/**\n *\n * Use this when auth is the only middleware you need.\n * Usage:\n *\n * export default authMiddleware({ loginUrl = '/login' }); // or just authMiddleware();\n *\n */\nexport const authMiddleware =\n (authConfig: OptionalAuthConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n if (response) return response;\n\n // NextJS doesn't do middleware chaining yet, so this does not mean\n // \"call the next middleware\" - it means \"continue to the route handler\"\n return NextResponse.next();\n };\n\n/**\n * Usage:\n *\n * export default withAuth(async (request) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n */\n// use this when you have your own middleware to chain\nexport function withAuth(\n middleware: Middleware,\n): (request: NextRequest) => Promise<NextResponse> {\n return auth()(middleware);\n}\n\nconst isRedirectResponse = (response?: NextResponse) =>\n response && response.status === 307;\n\n/**\n * Use this when you want to configure the middleware here (an alternative is to do it in the next.config file)\n *\n * Usage:\n *\n * export default auth(authConfig: AuthConfig ) => {\n * logger.debug('my middleware');\n * return NextResponse.next();\n * })\n *\n */\nexport function auth(authConfig: OptionalAuthConfig = {}) {\n return (\n middleware: Middleware,\n ): ((request: NextRequest) => Promise<NextResponse>) => {\n return async (request: NextRequest): Promise<NextResponse> => {\n const response = await applyAuth(authConfig, request);\n // if the response is redirected it means that the user is not authenticated\n // so we skip the rest of the custom middleware to redirect to the login page\n if (response && isRedirectResponse(response)) {\n logger.debug(\n \"User is unauthenticated, redirecting to \",\n response.headers.get(\"location\"),\n );\n return response;\n }\n // ensure requests get the cookies in case of redirects\n if (response) {\n copyCivicCookies(response, request);\n }\n const middlewareResponse = await middleware(request);\n\n // we need to ensure that the civic cookies that were potentially\n // added by CivicAuth are set on the final response after all\n // middleware has been run\n if (response) {\n copyCivicCookies(response, middlewareResponse);\n }\n return middlewareResponse;\n };\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"NextAuthProviderClient.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProviderClient.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAIpD,KAAK,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;AAEtE;;;GAGG;AACH,MAAM,WAAW,gCACf,SAAQ,0BAA0B;IAClC,4EAA4E;IAC5E,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,iDAAiD;IACjD,YAAY,EAAE,WAAW,GAAG,IAAI,CAAC;CAClC;AAID,eAAO,MAAM,2BAA2B,qDAKrC,gCAAgC,4CA8ElC,CAAC"}
1
+ {"version":3,"file":"NextAuthProviderClient.d.ts","sourceRoot":"","sources":["../../../src/nextjs/providers/NextAuthProviderClient.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAIpD,KAAK,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;AAEtE;;;GAGG;AACH,MAAM,WAAW,gCACf,SAAQ,0BAA0B;IAClC,4EAA4E;IAC5E,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,iDAAiD;IACjD,YAAY,EAAE,WAAW,GAAG,IAAI,CAAC;CAClC;AAID,eAAO,MAAM,2BAA2B,GAAI,kDAKzC,gCAAgC,4CA8ElC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"routeHandler.d.ts","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AASrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AA4Y9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAwEvB;AA0CD,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CA4DvB;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,iCAEF,WAAW,KAAG,OAAO,CAAC,YAAY,CAuCjD,CAAC"}
1
+ {"version":3,"file":"routeHandler.d.ts","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AASrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAuS9C,wBAAsB,YAAY,CAChC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CAwEvB;AA0CD,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,YAAY,CAAC,CA4DvB;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,GACjB,eAAe,MACT,SAAS,WAAW,KAAG,OAAO,CAAC,YAAY,CAuCjD,CAAC"}
@@ -1,4 +1,4 @@
1
- import { CivicAuth } from "@civic/auth/server";
1
+ import { CivicAuth } from "../server/index.js";
2
2
  import { LOGOUT_SUCCESS_TEXT } from "../constants.js";
3
3
  import { loggers } from "../lib/logger.js";
4
4
  import { displayModeFromState } from "../lib/oauth.js";
@@ -7,7 +7,7 @@ import { clearAuthCookies, NextjsCookieStorage } from "../nextjs/cookies.js";
7
7
  import { AuthFlowCookie, CodeVerifier, UserStorage, } from "../shared/lib/types.js";
8
8
  import { revalidatePath } from "next/cache.js";
9
9
  import { NextResponse } from "next/server.js";
10
- import { getOriginUrl, prependBasePath, redirectWithBasePath, sanitizeReturnUrl, } from "./utils.js";
10
+ import { prependBasePath, redirectWithBasePath } from "./utils.js";
11
11
  const logger = loggers.nextjs.handlers.auth;
12
12
  class AuthError extends Error {
13
13
  status;
@@ -65,6 +65,9 @@ const createCivicAuth = (request, config) => {
65
65
  // Note: Do NOT use request.url here - during callback, that would be the callback URL itself,
66
66
  // causing an infinite redirect loop in iframe mode fallbacks.
67
67
  loginSuccessUrl: resolvedConfig.loginSuccessUrl,
68
+ // Pass basePath and deepLinkHandling for generalized deep-linking support
69
+ basePath: resolvedConfig.basePath,
70
+ deepLinkHandling: resolvedConfig.deepLinkHandling,
68
71
  });
69
72
  return {
70
73
  civicAuth,
@@ -73,30 +76,6 @@ const createCivicAuth = (request, config) => {
73
76
  urlDetectionRequest, // Return for use in handlers
74
77
  };
75
78
  };
76
- /**
77
- * Injects loginSuccessUrl into an existing base64-encoded state string, or creates
78
- * a new state if none exists. This allows the deep link destination (computed by
79
- * middleware) to be passed through the OAuth flow via the existing loginSuccessUrl
80
- * mechanism.
81
- */
82
- function injectLoginSuccessUrlIntoState(frontendState, loginSuccessUrl) {
83
- let stateObj = {};
84
- if (frontendState) {
85
- try {
86
- // Decode the existing state
87
- const jsonString = atob(frontendState);
88
- stateObj = JSON.parse(jsonString);
89
- }
90
- catch (error) {
91
- logger.warn("[LOGIN_HANDLER] Failed to parse existing state, creating new state", { error });
92
- // Continue with empty stateObj - we'll still add loginSuccessUrl
93
- }
94
- }
95
- // Set loginSuccessUrl in state (overrides any existing value for fullUrl mode)
96
- stateObj.loginSuccessUrl = loginSuccessUrl;
97
- // Encode and return the state
98
- return btoa(JSON.stringify(stateObj));
99
- }
100
79
  /**
101
80
  * Login handler - backend OAuth login initiation endpoint
102
81
  * Uses CivicAuth.buildLoginUrl()
@@ -104,37 +83,16 @@ function injectLoginSuccessUrlIntoState(frontendState, loginSuccessUrl) {
104
83
  async function handleLogin(request, config) {
105
84
  const resolvedConfigs = resolveAuthConfig(config);
106
85
  try {
107
- let frontendState = request.nextUrl.searchParams.get("state");
86
+ const frontendState = request.nextUrl.searchParams.get("state");
108
87
  // Store appUrl in cookie if provided as query parameter
109
88
  const appUrlFromQuery = request.nextUrl.searchParams.get("appUrl");
110
89
  const cookieStorage = new NextjsCookieStorage(resolvedConfigs.cookies?.tokens ?? {});
111
90
  if (appUrlFromQuery) {
112
91
  await cookieStorage.set(CodeVerifier.APP_URL, appUrlFromQuery);
113
92
  }
114
- // Read the deep link cookie (set by middleware with deepLinkHandling already applied)
115
- // and inject it into the OAuth state's loginSuccessUrl field. This ensures the
116
- // destination survives the OAuth flow even when cookies aren't available in the
117
- // callback (e.g., due to SameSite restrictions in Chromium iframes).
118
- // Note: We don't delete the cookie here because:
119
- // 1. The login handler may be called multiple times (iframe preload, mode switching)
120
- // 2. We only want to consume the cookie on successful auth (handled in callback)
121
- if (resolvedConfigs.deepLinkHandling !== "disabled") {
122
- const deepLinkDestination = await cookieStorage.get(AuthFlowCookie.RETURN_URL);
123
- if (deepLinkDestination) {
124
- // Re-validate the cookie value to guard against tampering (defense-in-depth)
125
- const originUrl = getOriginUrl(request, resolvedConfigs);
126
- const sanitized = sanitizeReturnUrl(deepLinkDestination, originUrl);
127
- if (sanitized) {
128
- // Inject the destination into state.loginSuccessUrl
129
- // Don't prepend basePath here - the callback handler's redirectWithBasePath will handle it
130
- logger.debug("[LOGIN_HANDLER] Found deep link cookie, injecting into state.loginSuccessUrl", { deepLinkDestination, sanitized });
131
- frontendState = injectLoginSuccessUrlIntoState(frontendState, sanitized);
132
- }
133
- else {
134
- logger.warn("[LOGIN_HANDLER] Rejected invalid deep link cookie value", { deepLinkDestination });
135
- }
136
- }
137
- }
93
+ // CivicAuth.buildLoginUrl() automatically reads the RETURN_URL cookie (set by middleware)
94
+ // and injects it into the OAuth state. This ensures deep link destinations survive
95
+ // the OAuth flow even when cookies aren't available in callback (SameSite restrictions).
138
96
  const { civicAuth } = createCivicAuth(request, resolvedConfigs);
139
97
  const url = await civicAuth.buildLoginUrl({
140
98
  state: frontendState || undefined,
@@ -195,61 +153,33 @@ async function handleCallback(request, config) {
195
153
  headers: Object.fromEntries(request.headers.entries()),
196
154
  url: request.url.toString(),
197
155
  };
198
- // Resolve frontendUrl BEFORE calling handleCallback so it's available for iframe completion HTML.
199
- // Priority: loginSuccessUrl from state (injected by login handler) > config loginSuccessUrl > "/"
200
- // Note: We trust the state mechanism here - the login handler should have injected the deep link
201
- // destination into state. We don't read the cookie here because:
202
- // 1. If cookies work in callback, they should have worked in login handler to inject into state
203
- // 2. If cookies don't work in callback (SameSite restrictions), reading them is pointless anyway
204
- // 3. The whole point of using state was to survive cookie-less callback scenarios
205
- let frontendUrl;
206
- // Get loginSuccessUrl from state (should have been injected by login handler from deep link cookie)
156
+ // Compute frontendUrl for iframe completion HTML
157
+ // Priority: loginSuccessUrl from state > config.loginSuccessUrl > "/"
207
158
  const loginSuccessUrlFromState = CivicAuth.getLoginSuccessUrl(urlDetectionRequest, appUrl);
208
- if (loginSuccessUrlFromState) {
209
- logger.debug("[CALLBACK_HANDLER] Using loginSuccessUrl from state", {
210
- loginSuccessUrlFromState,
211
- });
212
- frontendUrl = loginSuccessUrlFromState;
213
- }
214
- // Final fallback to config loginSuccessUrl
215
- if (!frontendUrl) {
216
- frontendUrl = resolvedConfigs.loginSuccessUrl || "/";
159
+ let frontendUrl = loginSuccessUrlFromState || resolvedConfigs.loginSuccessUrl || "/";
160
+ // Apply basePath to frontendUrl if configured
161
+ if (resolvedConfigs.basePath) {
162
+ frontendUrl = prependBasePath(frontendUrl, resolvedConfigs.basePath);
217
163
  }
218
- // Use CivicAuth's smart callback handler with resolved frontendUrl
219
164
  const result = await civicAuth.handleCallback({
220
165
  code,
221
166
  state,
222
167
  req: handleCallbackRequest,
223
168
  }, {
224
- // Pass the resolved frontendUrl - this is critical for iframe completion HTML
225
- frontendUrl: prependBasePath(frontendUrl, config.basePath || ""),
169
+ frontendUrl,
226
170
  });
227
- // Helper to clear the deep link cookie on successful auth
228
- // Always clear the cookie to handle stale cookies from previous sessions
229
- const clearDeepLinkCookie = (response) => {
230
- const cookieConfig = resolvedConfigs.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];
231
- response.cookies.set(AuthFlowCookie.RETURN_URL, "", {
232
- path: cookieConfig?.path ?? resolvedConfigs.basePath ?? "/",
233
- httpOnly: cookieConfig?.httpOnly ?? true,
234
- secure: cookieConfig?.secure ?? true,
235
- sameSite: cookieConfig?.sameSite ?? "strict",
236
- maxAge: 0, // Immediately expire the cookie
237
- });
238
- logger.debug("[CALLBACK_HANDLER] Clearing deep link cookie after successful auth");
239
- return response;
240
- };
171
+ // Note: Deep link cookie clearing is now handled centrally in CivicAuth.handleCallback
172
+ // so all framework implementations benefit from the same behavior.
241
173
  if (result.redirectTo) {
242
- const response = redirectWithBasePath(config, CivicAuth.toAbsoluteUrl(urlDetectionRequest, result.redirectTo, appUrl));
243
- return clearDeepLinkCookie(response);
174
+ return redirectWithBasePath(config, CivicAuth.toAbsoluteUrl(urlDetectionRequest, result.redirectTo, appUrl));
244
175
  }
245
176
  if (result.content) {
246
177
  // Handle both string content and object content
247
178
  if (typeof result.content === "string") {
248
- const response = new NextResponse(result.content, {
179
+ return new NextResponse(result.content, {
249
180
  status: 200,
250
181
  headers: { "Content-Type": "text/html" },
251
182
  });
252
- return clearDeepLinkCookie(response);
253
183
  }
254
184
  else {
255
185
  // Object content (JSON response)
@@ -257,8 +187,7 @@ async function handleCallback(request, config) {
257
187
  }
258
188
  }
259
189
  // Fallback redirect
260
- const response = NextResponse.redirect(CivicAuth.toAbsoluteUrl(urlDetectionRequest, "/", appUrl));
261
- return clearDeepLinkCookie(response);
190
+ return NextResponse.redirect(CivicAuth.toAbsoluteUrl(urlDetectionRequest, "/", appUrl));
262
191
  }
263
192
  catch (error) {
264
193
  logger.error("[CALLBACK_HANDLER] OAuth callback error:", error);
@@ -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,iB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C,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC3D,OAAO,YAAY,CAAC,IAAI,CACtB,EAAE,KAAK,EAAE,uBAAuB,EAAE,EAClC,EAAE,MAAM,EAAE,GAAG,EAAE,CAChB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { CivicAuth, type UrlDetectionRequest } from \"@civic/auth/server\";\nimport { LOGOUT_SUCCESS_TEXT } from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { displayModeFromState } from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport {\n AuthFlowCookie,\n CodeVerifier,\n UserStorage,\n} from \"@/shared/lib/types.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport {\n getOriginUrl,\n prependBasePath,\n redirectWithBasePath,\n sanitizeReturnUrl,\n} from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Helper to convert NextRequest to UrlDetectionRequest for framework-agnostic URL handling\n */\nconst toUrlDetectionRequest = (request: NextRequest): UrlDetectionRequest => ({\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n searchParams: {\n get: (name: string) => request.nextUrl.searchParams.get(name),\n },\n cookies: {\n get: (name: string) => request.cookies.get(name),\n },\n});\n\n/**\n * Helper to create CivicAuth instance for a request\n * Now handles appUrl detection for proxy environments\n */\nconst createCivicAuth = (request: NextRequest, config: AuthConfig) => {\n const resolvedConfig = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage({\n ...resolvedConfig.cookies?.tokens,\n [UserStorage.USER]: resolvedConfig.cookies?.user,\n });\n\n // Convert to framework-agnostic request format\n const urlDetectionRequest = toUrlDetectionRequest(request);\n\n // Get appUrl from client (for proxy environments)\n const clientAppUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Use baseUrl from config, then client appUrl, then request origin\n // This matches the main branch priority: config > client > request\n const appUrl =\n resolvedConfig.baseUrl ||\n clientAppUrl ||\n new URL(urlDetectionRequest.url).origin;\n\n // Build absolute URLs using detected appUrl or request origin\n const absoluteCallbackUrl = resolvedConfig.callbackUrl.startsWith(\"http\")\n ? resolvedConfig.callbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.callbackUrl,\n appUrl,\n );\n const absoluteLogoutCallbackUrl = resolvedConfig.logoutCallbackUrl.startsWith(\n \"http\",\n )\n ? resolvedConfig.logoutCallbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.logoutCallbackUrl,\n appUrl,\n );\n\n const civicAuth = new CivicAuth(cookieStorage, {\n disableRefresh: resolvedConfig.disableRefresh,\n clientId: resolvedConfig.clientId,\n redirectUrl: absoluteCallbackUrl,\n oauthServer: resolvedConfig.oauthServer,\n postLogoutRedirectUrl: absoluteLogoutCallbackUrl,\n // Note: Do NOT use request.url here - during callback, that would be the callback URL itself,\n // causing an infinite redirect loop in iframe mode fallbacks.\n loginSuccessUrl: resolvedConfig.loginSuccessUrl,\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 * Injects loginSuccessUrl into an existing base64-encoded state string, or creates\n * a new state if none exists. This allows the deep link destination (computed by\n * middleware) to be passed through the OAuth flow via the existing loginSuccessUrl\n * mechanism.\n */\nfunction injectLoginSuccessUrlIntoState(\n frontendState: string | null,\n loginSuccessUrl: string,\n): string {\n let stateObj: Record<string, unknown> = {};\n\n if (frontendState) {\n try {\n // Decode the existing state\n const jsonString = atob(frontendState);\n stateObj = JSON.parse(jsonString);\n } catch (error) {\n logger.warn(\n \"[LOGIN_HANDLER] Failed to parse existing state, creating new state\",\n { error },\n );\n // Continue with empty stateObj - we'll still add loginSuccessUrl\n }\n }\n\n // Set loginSuccessUrl in state (overrides any existing value for fullUrl mode)\n stateObj.loginSuccessUrl = loginSuccessUrl;\n\n // Encode and return the state\n return btoa(JSON.stringify(stateObj));\n}\n\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 let 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 const cookieStorage = new NextjsCookieStorage(\n resolvedConfigs.cookies?.tokens ?? {},\n );\n\n if (appUrlFromQuery) {\n await cookieStorage.set(CodeVerifier.APP_URL, appUrlFromQuery);\n }\n\n // Read the deep link cookie (set by middleware with deepLinkHandling already applied)\n // and inject it into the OAuth state's loginSuccessUrl field. This ensures the\n // destination survives the OAuth flow even when cookies aren't available in the\n // callback (e.g., due to SameSite restrictions in Chromium iframes).\n // Note: We don't delete the cookie here because:\n // 1. The login handler may be called multiple times (iframe preload, mode switching)\n // 2. We only want to consume the cookie on successful auth (handled in callback)\n if (resolvedConfigs.deepLinkHandling !== \"disabled\") {\n const deepLinkDestination = await cookieStorage.get(\n AuthFlowCookie.RETURN_URL,\n );\n if (deepLinkDestination) {\n // Re-validate the cookie value to guard against tampering (defense-in-depth)\n const originUrl = getOriginUrl(request, resolvedConfigs);\n const sanitized = sanitizeReturnUrl(deepLinkDestination, originUrl);\n\n if (sanitized) {\n // Inject the destination into state.loginSuccessUrl\n // Don't prepend basePath here - the callback handler's redirectWithBasePath will handle it\n logger.debug(\n \"[LOGIN_HANDLER] Found deep link cookie, injecting into state.loginSuccessUrl\",\n { deepLinkDestination, sanitized },\n );\n frontendState = injectLoginSuccessUrlIntoState(\n frontendState,\n sanitized,\n );\n } else {\n logger.warn(\n \"[LOGIN_HANDLER] Rejected invalid deep link cookie value\",\n { deepLinkDestination },\n );\n }\n }\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\n // Clean up deep link cookie on error to prevent stale cookies\n try {\n const errorCookieStorage = new NextjsCookieStorage(\n resolvedConfigs.cookies?.tokens ?? {},\n );\n await errorCookieStorage.delete(AuthFlowCookie.RETURN_URL);\n } catch (cookieError) {\n logger.warn(\n \"[LOGIN_HANDLER] Failed to clean up deep link cookie on error\",\n { cookieError },\n );\n }\n\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=login_failed\",\n appUrl,\n ),\n );\n }\n}\n\nasync function handleRefresh(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n await civicAuth.refreshTokens();\n\n logger.info(\"[REFRESH_HANDLER] Tokens refreshed successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Tokens refreshed\",\n });\n } catch (error) {\n logger.error(\"[REFRESH_HANDLER] Token refresh error:\", error);\n return NextResponse.json(\n { error: \"Token refresh failed\" },\n { status: 500 },\n );\n }\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n const error = request.nextUrl.searchParams.get(\"error\");\n\n if (error) {\n logger.error(\"OAuth error in callback:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=oauth_error\",\n appUrl,\n ),\n );\n }\n\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n try {\n const { civicAuth, appUrl, urlDetectionRequest } = createCivicAuth(\n request,\n resolvedConfigs,\n );\n\n // Convert NextRequest to the format expected by handleCallback\n const handleCallbackRequest = {\n headers: Object.fromEntries(request.headers.entries()),\n url: request.url.toString(),\n };\n\n // Resolve frontendUrl BEFORE calling handleCallback so it's available for iframe completion HTML.\n // Priority: loginSuccessUrl from state (injected by login handler) > config loginSuccessUrl > \"/\"\n // Note: We trust the state mechanism here - the login handler should have injected the deep link\n // destination into state. We don't read the cookie here because:\n // 1. If cookies work in callback, they should have worked in login handler to inject into state\n // 2. If cookies don't work in callback (SameSite restrictions), reading them is pointless anyway\n // 3. The whole point of using state was to survive cookie-less callback scenarios\n\n let frontendUrl: string | undefined;\n\n // Get loginSuccessUrl from state (should have been injected by login handler from deep link cookie)\n const loginSuccessUrlFromState = CivicAuth.getLoginSuccessUrl(\n urlDetectionRequest,\n appUrl,\n );\n if (loginSuccessUrlFromState) {\n logger.debug(\"[CALLBACK_HANDLER] Using loginSuccessUrl from state\", {\n loginSuccessUrlFromState,\n });\n frontendUrl = loginSuccessUrlFromState;\n }\n\n // Final fallback to config loginSuccessUrl\n if (!frontendUrl) {\n frontendUrl = resolvedConfigs.loginSuccessUrl || \"/\";\n }\n\n // Use CivicAuth's smart callback handler with resolved frontendUrl\n const result = await civicAuth.handleCallback(\n {\n code,\n state,\n req: handleCallbackRequest,\n },\n {\n // Pass the resolved frontendUrl - this is critical for iframe completion HTML\n frontendUrl: prependBasePath(frontendUrl, config.basePath || \"\"),\n },\n );\n\n // Helper to clear the deep link cookie on successful auth\n // Always clear the cookie to handle stale cookies from previous sessions\n const clearDeepLinkCookie = (response: NextResponse) => {\n const cookieConfig =\n resolvedConfigs.cookies?.tokens?.[AuthFlowCookie.RETURN_URL];\n response.cookies.set(AuthFlowCookie.RETURN_URL, \"\", {\n path: cookieConfig?.path ?? resolvedConfigs.basePath ?? \"/\",\n httpOnly: cookieConfig?.httpOnly ?? true,\n secure: cookieConfig?.secure ?? true,\n sameSite: cookieConfig?.sameSite ?? \"strict\",\n maxAge: 0, // Immediately expire the cookie\n });\n logger.debug(\n \"[CALLBACK_HANDLER] Clearing deep link cookie after successful auth\",\n );\n return response;\n };\n\n if (result.redirectTo) {\n const response = redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, result.redirectTo, appUrl),\n );\n return clearDeepLinkCookie(response);\n }\n\n if (result.content) {\n // Handle both string content and object content\n if (typeof result.content === \"string\") {\n const response = new NextResponse(result.content, {\n status: 200,\n headers: { \"Content-Type\": \"text/html\" },\n });\n return clearDeepLinkCookie(response);\n } else {\n // Object content (JSON response)\n return NextResponse.json(result.content);\n }\n }\n\n // Fallback redirect\n const response = NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, \"/\", appUrl),\n );\n return clearDeepLinkCookie(response);\n } catch (error) {\n logger.error(\"[CALLBACK_HANDLER] OAuth callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=callback_failed\",\n appUrl,\n ),\n );\n }\n}\n\nconst revalidateUrlPath = async (url: string) => {\n try {\n const path = new URL(url).pathname;\n revalidatePath(path);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n};\n\nexport async function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n // Get framework-agnostic request for URL utilities\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Read the state from the query parameters\n const state = request.nextUrl.searchParams.get(\"state\");\n const clientLogoutRedirectUrl =\n request.nextUrl.searchParams.get(\"logoutRedirectUrl\");\n\n try {\n logger.info(\"[LOGOUT_HANDLER] Backend logout endpoint called\");\n\n // If client provided a logoutRedirectUrl, override the config\n let configToUse = resolvedConfigs;\n if (clientLogoutRedirectUrl) {\n configToUse = {\n ...resolvedConfigs,\n logoutCallbackUrl: clientLogoutRedirectUrl,\n };\n logger.info(\"[LOGOUT_HANDLER] Overriding logout callback URL\", {\n original: resolvedConfigs.logoutCallbackUrl,\n override: clientLogoutRedirectUrl,\n });\n }\n\n const { civicAuth } = createCivicAuth(request, configToUse);\n\n // Always redirect to OAuth logout (like main branch)\n // Don't validate session - even invalid local sessions should hit OAuth logout\n logger.info(\"[LOGOUT_HANDLER] Processing logout request\", {\n state: !!state,\n });\n\n // Always redirect to OAuth logout endpoint (like main branch)\n // Client-side iframe logic will handle completion and redirect appropriately\n const logoutUrl = await civicAuth.buildLogoutRedirectUrl({\n state: state || undefined,\n });\n\n try {\n await clearAuthCookies(resolvedConfigs);\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Error clearing tokens:\", error);\n }\n\n // Remove state parameter from logout URL to prevent it from appearing in frontend URL\n const cleanLogoutUrl = new URL(logoutUrl);\n cleanLogoutUrl.searchParams.delete(\"state\");\n\n logger.info(\"[LOGOUT_HANDLER] Redirecting to OAuth logout endpoint\", {\n logoutUrl: cleanLogoutUrl.toString(),\n });\n\n return NextResponse.redirect(cleanLogoutUrl.toString());\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Logout error:\", error);\n // If logout URL generation fails, clear tokens and redirect to home\n await clearAuthCookies(resolvedConfigs);\n\n const fallbackUrl =\n clientLogoutRedirectUrl || resolvedConfigs.logoutCallbackUrl;\n const finalFallbackUrl = CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n fallbackUrl,\n appUrl,\n );\n\n return NextResponse.redirect(finalFallbackUrl);\n }\n}\n\n/**\n * Clear session handler - clears all auth cookies server-side.\n * Called by client in parallel with logout iframe to quickly clear HttpOnly cookies.\n *\n * This is part of a parallel logout strategy:\n * - Client calls clearsession (this endpoint) AND loads logout iframe simultaneously\n * - Both requests are sent while cookies are still present\n * - clearsession clears HttpOnly cookies quickly (this endpoint)\n * - logout iframe handles OAuth provider logout (slower, but had cookies when initiated)\n *\n * This ensures cookies are cleared fast (preventing race conditions if user refreshes)\n * while still performing OAuth provider logout.\n */\nasync function handleClearSession(\n _request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\"[CLEARSESSION_HANDLER] Clearing session cookies\");\n\n // Clear all auth cookies immediately\n await clearAuthCookies(resolvedConfigs);\n\n logger.info(\"[CLEARSESSION_HANDLER] Session cleared successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Session cleared\",\n });\n } catch (error) {\n logger.error(\"[CLEARSESSION_HANDLER] Error clearing session:\", error);\n return NextResponse.json(\n { error: \"Failed to clear session\" },\n { status: 500 },\n );\n }\n}\n\nexport async function handleLogoutCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Backend logout callback endpoint called\",\n );\n\n // Clear authentication cookies\n await clearAuthCookies(resolvedConfigs);\n\n // Get framework-agnostic request and create CivicAuth instance\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n // Get the state parameter for iframe detection\n const state = request.nextUrl.searchParams.get(\"state\");\n\n // If this is an iframe request, return HTML with logout success signal\n if (state && displayModeFromState(state, \"iframe\") === \"iframe\") {\n // For iframe mode, include the post-logout redirect URL in the HTML\n const postLogoutRedirectUrl =\n civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n const response = new NextResponse(\n `<html lang=\"en\"><span style=\"display:none\">${LOGOUT_SUCCESS_TEXT}<a href=\"${postLogoutRedirectUrl}\" rel=\"civic-auth-post-logout-redirect-url\"></a></span></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Returning iframe logout success HTML\",\n { postLogoutRedirectUrl },\n );\n return response;\n }\n\n // For non-iframe requests, redirect to the logout callback URL or post-logout URL\n const redirectUrl = civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Redirecting to logout callback URL\",\n {\n logoutCallbackUrl: resolvedConfigs.logoutCallbackUrl,\n redirectUrl,\n },\n );\n\n // Revalidate the redirect path to update authentication state in server components\n await revalidateUrlPath(redirectUrl);\n return redirectWithBasePath(config, redirectUrl);\n } catch (error) {\n logger.error(\"[LOGOUT_CALLBACK_HANDLER] Logout callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfigs.logoutCallbackUrl,\n appUrl,\n ),\n );\n }\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * export const POST = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n logger.debug(\"routeHandler: Auth route handler called\", config);\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n case \"login\":\n return await handleLogin(request, config);\n case \"callback\":\n return await handleCallback(request, config);\n case \"refresh\":\n return await handleRefresh(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n case \"clearsession\":\n return await handleClearSession(request, config);\n case \"logoutcallback\":\n return await handleLogoutCallback(request, config);\n case \"user\":\n return await handleUser(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n await clearAuthCookies(config);\n return response;\n }\n };\n\n/**\n * User endpoint - returns current user data as JSON\n * Uses CivicAuth.isLoggedIn() and getUser()\n */\nasync function handleUser(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n logger.debug(\n \"routeHandler: [USER_HANDLER] User endpoint called\",\n resolvedConfigs,\n );\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const isLoggedIn = await civicAuth.isLoggedIn();\n\n if (!isLoggedIn) {\n const statusCode = request.nextUrl.searchParams.get(\n \"optimisticRehydration\",\n )\n ? 202\n : 401;\n return NextResponse.json(\n { error: \"Not authenticated\" },\n { status: statusCode },\n );\n }\n\n const user = await civicAuth.getUser();\n\n return NextResponse.json({ user });\n } catch (error) {\n logger.error(\"[USER_HANDLER] User endpoint error:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n"]}
1
+ {"version":3,"file":"routeHandler.js","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA4B,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAA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AAC,CAAC,GAAG;gBACL,CAAC,CAAC,GAAG,CAAC;YACR,OAAO,YAAY,CAAC,IAAI,CACtB,EAAE,KAAK,EAAE,mBAAmB,EAAE,EAC9B,EAAE,MAAM,EAAE,UAAU,EAAE,CACvB,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,OAAO,EAAE,CAAC;QAEvC,OAAO,YAAY,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC3D,OAAO,YAAY,CAAC,IAAI,CACtB,EAAE,KAAK,EAAE,uBAAuB,EAAE,EAClC,EAAE,MAAM,EAAE,GAAG,EAAE,CAChB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { CivicAuth, type UrlDetectionRequest } from \"@/server/index.js\";\nimport { LOGOUT_SUCCESS_TEXT } from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { displayModeFromState } from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport {\n AuthFlowCookie,\n CodeVerifier,\n UserStorage,\n} from \"@/shared/lib/types.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { prependBasePath, redirectWithBasePath } from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Helper to convert NextRequest to UrlDetectionRequest for framework-agnostic URL handling\n */\nconst toUrlDetectionRequest = (request: NextRequest): UrlDetectionRequest => ({\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n searchParams: {\n get: (name: string) => request.nextUrl.searchParams.get(name),\n },\n cookies: {\n get: (name: string) => request.cookies.get(name),\n },\n});\n\n/**\n * Helper to create CivicAuth instance for a request\n * Now handles appUrl detection for proxy environments\n */\nconst createCivicAuth = (request: NextRequest, config: AuthConfig) => {\n const resolvedConfig = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage({\n ...resolvedConfig.cookies?.tokens,\n [UserStorage.USER]: resolvedConfig.cookies?.user,\n });\n\n // Convert to framework-agnostic request format\n const urlDetectionRequest = toUrlDetectionRequest(request);\n\n // Get appUrl from client (for proxy environments)\n const clientAppUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Use baseUrl from config, then client appUrl, then request origin\n // This matches the main branch priority: config > client > request\n const appUrl =\n resolvedConfig.baseUrl ||\n clientAppUrl ||\n new URL(urlDetectionRequest.url).origin;\n\n // Build absolute URLs using detected appUrl or request origin\n const absoluteCallbackUrl = resolvedConfig.callbackUrl.startsWith(\"http\")\n ? resolvedConfig.callbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.callbackUrl,\n appUrl,\n );\n const absoluteLogoutCallbackUrl = resolvedConfig.logoutCallbackUrl.startsWith(\n \"http\",\n )\n ? resolvedConfig.logoutCallbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.logoutCallbackUrl,\n appUrl,\n );\n\n const civicAuth = new CivicAuth(cookieStorage, {\n disableRefresh: resolvedConfig.disableRefresh,\n clientId: resolvedConfig.clientId,\n redirectUrl: absoluteCallbackUrl,\n oauthServer: resolvedConfig.oauthServer,\n postLogoutRedirectUrl: absoluteLogoutCallbackUrl,\n // Note: Do NOT use request.url here - during callback, that would be the callback URL itself,\n // causing an infinite redirect loop in iframe mode fallbacks.\n loginSuccessUrl: resolvedConfig.loginSuccessUrl,\n // Pass basePath and deepLinkHandling for generalized deep-linking support\n basePath: resolvedConfig.basePath,\n deepLinkHandling: resolvedConfig.deepLinkHandling,\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 const cookieStorage = new NextjsCookieStorage(\n resolvedConfigs.cookies?.tokens ?? {},\n );\n\n if (appUrlFromQuery) {\n await cookieStorage.set(CodeVerifier.APP_URL, appUrlFromQuery);\n }\n\n // CivicAuth.buildLoginUrl() automatically reads the RETURN_URL cookie (set by middleware)\n // and injects it into the OAuth state. This ensures deep link destinations survive\n // the OAuth flow even when cookies aren't available in callback (SameSite restrictions).\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\n // Clean up deep link cookie on error to prevent stale cookies\n try {\n const errorCookieStorage = new NextjsCookieStorage(\n resolvedConfigs.cookies?.tokens ?? {},\n );\n await errorCookieStorage.delete(AuthFlowCookie.RETURN_URL);\n } catch (cookieError) {\n logger.warn(\n \"[LOGIN_HANDLER] Failed to clean up deep link cookie on error\",\n { cookieError },\n );\n }\n\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=login_failed\",\n appUrl,\n ),\n );\n }\n}\n\nasync function handleRefresh(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n await civicAuth.refreshTokens();\n\n logger.info(\"[REFRESH_HANDLER] Tokens refreshed successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Tokens refreshed\",\n });\n } catch (error) {\n logger.error(\"[REFRESH_HANDLER] Token refresh error:\", error);\n return NextResponse.json(\n { error: \"Token refresh failed\" },\n { status: 500 },\n );\n }\n}\n\nasync function handleCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n const code = request.nextUrl.searchParams.get(\"code\");\n const state = request.nextUrl.searchParams.get(\"state\");\n const error = request.nextUrl.searchParams.get(\"error\");\n\n if (error) {\n logger.error(\"OAuth error in callback:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=oauth_error\",\n appUrl,\n ),\n );\n }\n\n if (!code || !state) throw new AuthError(\"Bad parameters\", 400);\n\n try {\n const { civicAuth, appUrl, urlDetectionRequest } = createCivicAuth(\n request,\n resolvedConfigs,\n );\n\n // Convert NextRequest to the format expected by handleCallback\n const handleCallbackRequest = {\n headers: Object.fromEntries(request.headers.entries()),\n url: request.url.toString(),\n };\n\n // Compute frontendUrl for iframe completion HTML\n // Priority: loginSuccessUrl from state > config.loginSuccessUrl > \"/\"\n const loginSuccessUrlFromState = CivicAuth.getLoginSuccessUrl(\n urlDetectionRequest,\n appUrl,\n );\n let frontendUrl =\n loginSuccessUrlFromState || resolvedConfigs.loginSuccessUrl || \"/\";\n\n // Apply basePath to frontendUrl if configured\n if (resolvedConfigs.basePath) {\n frontendUrl = prependBasePath(frontendUrl, resolvedConfigs.basePath);\n }\n\n const result = await civicAuth.handleCallback(\n {\n code,\n state,\n req: handleCallbackRequest,\n },\n {\n frontendUrl,\n },\n );\n\n // Note: Deep link cookie clearing is now handled centrally in CivicAuth.handleCallback\n // so all framework implementations benefit from the same behavior.\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: { \"Content-Type\": \"text/html\" },\n });\n } else {\n // Object content (JSON response)\n return NextResponse.json(result.content);\n }\n }\n\n // Fallback redirect\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(urlDetectionRequest, \"/\", appUrl),\n );\n } catch (error) {\n logger.error(\"[CALLBACK_HANDLER] OAuth callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return NextResponse.redirect(\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n \"/?error=callback_failed\",\n appUrl,\n ),\n );\n }\n}\n\nconst revalidateUrlPath = async (url: string) => {\n try {\n const path = new URL(url).pathname;\n revalidatePath(path);\n } catch (error) {\n logger.warn(\"Failed to revalidate path after logout:\", error);\n }\n};\n\nexport async function handleLogout(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n // Get framework-agnostic request for URL utilities\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Read the state from the query parameters\n const state = request.nextUrl.searchParams.get(\"state\");\n const clientLogoutRedirectUrl =\n request.nextUrl.searchParams.get(\"logoutRedirectUrl\");\n\n try {\n logger.info(\"[LOGOUT_HANDLER] Backend logout endpoint called\");\n\n // If client provided a logoutRedirectUrl, override the config\n let configToUse = resolvedConfigs;\n if (clientLogoutRedirectUrl) {\n configToUse = {\n ...resolvedConfigs,\n logoutCallbackUrl: clientLogoutRedirectUrl,\n };\n logger.info(\"[LOGOUT_HANDLER] Overriding logout callback URL\", {\n original: resolvedConfigs.logoutCallbackUrl,\n override: clientLogoutRedirectUrl,\n });\n }\n\n const { civicAuth } = createCivicAuth(request, configToUse);\n\n // Always redirect to OAuth logout (like main branch)\n // Don't validate session - even invalid local sessions should hit OAuth logout\n logger.info(\"[LOGOUT_HANDLER] Processing logout request\", {\n state: !!state,\n });\n\n // Always redirect to OAuth logout endpoint (like main branch)\n // Client-side iframe logic will handle completion and redirect appropriately\n const logoutUrl = await civicAuth.buildLogoutRedirectUrl({\n state: state || undefined,\n });\n\n try {\n await clearAuthCookies(resolvedConfigs);\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Error clearing tokens:\", error);\n }\n\n // Remove state parameter from logout URL to prevent it from appearing in frontend URL\n const cleanLogoutUrl = new URL(logoutUrl);\n cleanLogoutUrl.searchParams.delete(\"state\");\n\n logger.info(\"[LOGOUT_HANDLER] Redirecting to OAuth logout endpoint\", {\n logoutUrl: cleanLogoutUrl.toString(),\n });\n\n return NextResponse.redirect(cleanLogoutUrl.toString());\n } catch (error) {\n logger.error(\"[LOGOUT_HANDLER] Logout error:\", error);\n // If logout URL generation fails, clear tokens and redirect to home\n await clearAuthCookies(resolvedConfigs);\n\n const fallbackUrl =\n clientLogoutRedirectUrl || resolvedConfigs.logoutCallbackUrl;\n const finalFallbackUrl = CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n fallbackUrl,\n appUrl,\n );\n\n return NextResponse.redirect(finalFallbackUrl);\n }\n}\n\n/**\n * Clear session handler - clears all auth cookies server-side.\n * Called by client in parallel with logout iframe to quickly clear HttpOnly cookies.\n *\n * This is part of a parallel logout strategy:\n * - Client calls clearsession (this endpoint) AND loads logout iframe simultaneously\n * - Both requests are sent while cookies are still present\n * - clearsession clears HttpOnly cookies quickly (this endpoint)\n * - logout iframe handles OAuth provider logout (slower, but had cookies when initiated)\n *\n * This ensures cookies are cleared fast (preventing race conditions if user refreshes)\n * while still performing OAuth provider logout.\n */\nasync function handleClearSession(\n _request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\"[CLEARSESSION_HANDLER] Clearing session cookies\");\n\n // Clear all auth cookies immediately\n await clearAuthCookies(resolvedConfigs);\n\n logger.info(\"[CLEARSESSION_HANDLER] Session cleared successfully\");\n\n return NextResponse.json({\n status: \"success\",\n message: \"Session cleared\",\n });\n } catch (error) {\n logger.error(\"[CLEARSESSION_HANDLER] Error clearing session:\", error);\n return NextResponse.json(\n { error: \"Failed to clear session\" },\n { status: 500 },\n );\n }\n}\n\nexport async function handleLogoutCallback(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n\n try {\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Backend logout callback endpoint called\",\n );\n\n // Clear authentication cookies\n await clearAuthCookies(resolvedConfigs);\n\n // Get framework-agnostic request and create CivicAuth instance\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n // Get the state parameter for iframe detection\n const state = request.nextUrl.searchParams.get(\"state\");\n\n // If this is an iframe request, return HTML with logout success signal\n if (state && displayModeFromState(state, \"iframe\") === \"iframe\") {\n // For iframe mode, include the post-logout redirect URL in the HTML\n const postLogoutRedirectUrl =\n civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n const response = new NextResponse(\n `<html lang=\"en\"><span style=\"display:none\">${LOGOUT_SUCCESS_TEXT}<a href=\"${postLogoutRedirectUrl}\" rel=\"civic-auth-post-logout-redirect-url\"></a></span></html>`,\n );\n response.headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Returning iframe logout success HTML\",\n { postLogoutRedirectUrl },\n );\n return response;\n }\n\n // For non-iframe requests, redirect to the logout callback URL or post-logout URL\n const redirectUrl = civicAuth.getPostLogoutRedirectUrl(urlDetectionRequest);\n logger.info(\n \"[LOGOUT_CALLBACK_HANDLER] Redirecting to logout callback URL\",\n {\n logoutCallbackUrl: resolvedConfigs.logoutCallbackUrl,\n redirectUrl,\n },\n );\n\n // Revalidate the redirect path to update authentication state in server components\n await revalidateUrlPath(redirectUrl);\n return redirectWithBasePath(config, redirectUrl);\n } catch (error) {\n logger.error(\"[LOGOUT_CALLBACK_HANDLER] Logout callback error:\", error);\n const urlDetectionRequest = toUrlDetectionRequest(request);\n const appUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n return redirectWithBasePath(\n config,\n CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfigs.logoutCallbackUrl,\n appUrl,\n ),\n );\n }\n}\n\n/**\n * Creates an authentication handler for Next.js API routes\n *\n * Usage:\n * ```ts\n * // app/api/auth/[...civicauth]/route.ts\n * import { handler } from '@civic/auth/nextjs'\n * export const GET = handler({\n * // optional config overrides\n * })\n * export const POST = handler({\n * // optional config overrides\n * })\n * ```\n */\nexport const handler =\n (authConfig = {}) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const config = resolveAuthConfig(authConfig);\n logger.debug(\"routeHandler: Auth route handler called\", config);\n try {\n const pathname = request.nextUrl.pathname;\n const pathSegments = pathname.split(\"/\");\n const lastSegment = pathSegments[pathSegments.length - 1];\n\n switch (lastSegment) {\n case \"challenge\":\n case \"login\":\n return await handleLogin(request, config);\n case \"callback\":\n return await handleCallback(request, config);\n case \"refresh\":\n return await handleRefresh(request, config);\n case \"logout\":\n return await handleLogout(request, config);\n case \"clearsession\":\n return await handleClearSession(request, config);\n case \"logoutcallback\":\n return await handleLogoutCallback(request, config);\n case \"user\":\n return await handleUser(request, config);\n default:\n throw new AuthError(`Invalid auth route: ${pathname}`, 404);\n }\n } catch (error) {\n logger.error(\"Auth handler error:\", error);\n\n const status = error instanceof AuthError ? error.status : 500;\n const message =\n error instanceof Error ? error.message : \"Authentication failed\";\n\n const response = NextResponse.json({ error: message }, { status });\n\n await clearAuthCookies(config);\n return response;\n }\n };\n\n/**\n * User endpoint - returns current user data as JSON\n * Uses CivicAuth.isLoggedIn() and getUser()\n */\nasync function handleUser(\n request: NextRequest,\n config: AuthConfig,\n): Promise<NextResponse> {\n const resolvedConfigs = resolveAuthConfig(config);\n logger.debug(\n \"routeHandler: [USER_HANDLER] User endpoint called\",\n resolvedConfigs,\n );\n try {\n const { civicAuth } = createCivicAuth(request, resolvedConfigs);\n\n const isLoggedIn = await civicAuth.isLoggedIn();\n\n if (!isLoggedIn) {\n const statusCode = request.nextUrl.searchParams.get(\n \"optimisticRehydration\",\n )\n ? 202\n : 401;\n return NextResponse.json(\n { error: \"Not authenticated\" },\n { status: statusCode },\n );\n }\n\n const user = await civicAuth.getUser();\n\n return NextResponse.json({ user });\n } catch (error) {\n logger.error(\"[USER_HANDLER] User endpoint error:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n"]}
@@ -3,8 +3,8 @@ import type { NextRequest } from "next/server.js";
3
3
  import { NextResponse } from "next/server.js";
4
4
  import type { SessionData } from "../types.js";
5
5
  import { type CookieConfig, type KeySetter } from "../shared/lib/types.js";
6
- import { sanitizeReturnUrl } from "../shared/lib/util.js";
7
- export { sanitizeReturnUrl };
6
+ import { computeDeepLinkDestination, sanitizeReturnUrl } from "../shared/lib/util.js";
7
+ export { sanitizeReturnUrl, computeDeepLinkDestination };
8
8
  import { CookieStorage } from "../server/index.js";
9
9
  export declare const resolveCallbackUrl: (config: AuthConfigWithDefaults, baseUrl?: string) => string;
10
10
  export declare function sanitizeBasePath(path: string): string;
@@ -45,7 +45,13 @@ export declare const handleLoginUrl: (pathname: string, session: SessionData, au
45
45
  export declare const shouldSkipAuthForRoutePatterns: (pathname: string, authConfig: AuthConfigWithDefaults) => boolean;
46
46
  export declare const copyCivicCookies: (sourceResponse: NextResponse, targetCall: NextResponse | NextRequest) => void;
47
47
  /**
48
- * Handles final authentication logic for unauthenticated users on protected routes
48
+ * Handles final authentication logic for unauthenticated users on protected routes.
49
+ *
50
+ * Note: Deep link cookie setting and auth redirect marker are now handled by
51
+ * CivicAuth.handleDeepLinking which runs earlier in the middleware flow.
52
+ * This function focuses on:
53
+ * 1. Clearing expired/invalid tokens
54
+ * 2. Redirecting to the login URL
49
55
  */
50
56
  export declare const handleUnauthenticatedUser: (session: SessionData, request: NextRequest, response: NextResponse, storage: NextjsMiddlewareCookieStorage, authConfig: AuthConfigWithDefaults) => Promise<NextResponse | undefined>;
51
57
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/nextjs/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,sBAAsB,EAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAG9C,OAAO,EAKL,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGL,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAKlD,eAAO,MAAM,kBAAkB,WACrB,sBAAsB,YACpB,MAAM,KACf,MAGF,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQrD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,MAAM,EAChB,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,CAoBR;AAED,eAAO,MAAM,YAAY,YACd,WAAW,cACR,sBA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