@civic/auth 0.13.0 → 0.13.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/README.md +102 -1
- package/dist/lib/oauth.d.ts +12 -1
- package/dist/lib/oauth.d.ts.map +1 -1
- package/dist/lib/oauth.js +29 -1
- package/dist/lib/oauth.js.map +1 -1
- package/dist/nextjs/config.d.ts +2 -11
- package/dist/nextjs/config.d.ts.map +1 -1
- package/dist/nextjs/config.js.map +1 -1
- package/dist/nextjs/middleware.d.ts.map +1 -1
- package/dist/nextjs/middleware.js +18 -3
- package/dist/nextjs/middleware.js.map +1 -1
- package/dist/nextjs/routeHandler.d.ts.map +1 -1
- package/dist/nextjs/routeHandler.js +15 -71
- package/dist/nextjs/routeHandler.js.map +1 -1
- package/dist/nextjs/utils.d.ts +9 -3
- package/dist/nextjs/utils.d.ts.map +1 -1
- package/dist/nextjs/utils.js +10 -52
- package/dist/nextjs/utils.js.map +1 -1
- package/dist/server/config.d.ts +23 -0
- package/dist/server/config.d.ts.map +1 -1
- package/dist/server/config.js.map +1 -1
- package/dist/server/session.d.ts +57 -0
- package/dist/server/session.d.ts.map +1 -1
- package/dist/server/session.js +205 -9
- package/dist/server/session.js.map +1 -1
- package/dist/shared/lib/cookieConfig.d.ts.map +1 -1
- package/dist/shared/lib/cookieConfig.js +6 -1
- package/dist/shared/lib/cookieConfig.js.map +1 -1
- package/dist/shared/lib/types.d.ts +5 -1
- package/dist/shared/lib/types.d.ts.map +1 -1
- package/dist/shared/lib/types.js +4 -0
- package/dist/shared/lib/types.js.map +1 -1
- package/dist/shared/lib/util.d.ts +38 -1
- package/dist/shared/lib/util.d.ts.map +1 -1
- package/dist/shared/lib/util.js +95 -0
- package/dist/shared/lib/util.js.map +1 -1
- package/dist/shared/version.d.ts +1 -1
- package/dist/shared/version.d.ts.map +1 -1
- package/dist/shared/version.js +1 -1
- package/dist/shared/version.js.map +1 -1
- package/package.json +3 -3
|
@@ -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 {
|
|
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
|
-
|
|
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
|
-
//
|
|
115
|
-
// and
|
|
116
|
-
//
|
|
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,34 +153,20 @@ async function handleCallback(request, config) {
|
|
|
195
153
|
headers: Object.fromEntries(request.headers.entries()),
|
|
196
154
|
url: request.url.toString(),
|
|
197
155
|
};
|
|
198
|
-
//
|
|
199
|
-
// Priority: loginSuccessUrl from state
|
|
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
|
-
|
|
209
|
-
|
|
210
|
-
|
|
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
|
-
|
|
225
|
-
frontendUrl: prependBasePath(frontendUrl, config.basePath || ""),
|
|
169
|
+
frontendUrl,
|
|
226
170
|
});
|
|
227
171
|
// Helper to clear the deep link cookie on successful auth
|
|
228
172
|
// Always clear the cookie to handle stale cookies from previous sessions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routeHandler.js","sourceRoot":"","sources":["../../src/nextjs/routeHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA4B,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,iBAAiB,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C;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,oBAAoB,CAAC;AACzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBA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,KAAK,EAAE,uBAAuB,EAAE,EAClC,EAAE,MAAM,EAAE,GAAG,EAAE,CAChB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { CivicAuth, type UrlDetectionRequest } from \"@civic/auth/server\";\nimport { LOGOUT_SUCCESS_TEXT } from \"@/constants.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { displayModeFromState } from \"@/lib/oauth.js\";\nimport type { AuthConfig } from \"@/nextjs/config.js\";\nimport { resolveAuthConfig } from \"@/nextjs/config.js\";\nimport { clearAuthCookies, NextjsCookieStorage } from \"@/nextjs/cookies.js\";\nimport {\n AuthFlowCookie,\n CodeVerifier,\n UserStorage,\n} from \"@/shared/lib/types.js\";\nimport { revalidatePath } from \"next/cache.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { prependBasePath, redirectWithBasePath } from \"./utils.js\";\n\nconst logger = loggers.nextjs.handlers.auth;\n\nclass AuthError extends Error {\n constructor(\n message: string,\n public readonly status: number = 401,\n ) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Helper to convert NextRequest to UrlDetectionRequest for framework-agnostic URL handling\n */\nconst toUrlDetectionRequest = (request: NextRequest): UrlDetectionRequest => ({\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n searchParams: {\n get: (name: string) => request.nextUrl.searchParams.get(name),\n },\n cookies: {\n get: (name: string) => request.cookies.get(name),\n },\n});\n\n/**\n * Helper to create CivicAuth instance for a request\n * Now handles appUrl detection for proxy environments\n */\nconst createCivicAuth = (request: NextRequest, config: AuthConfig) => {\n const resolvedConfig = resolveAuthConfig(config);\n const cookieStorage = new NextjsCookieStorage({\n ...resolvedConfig.cookies?.tokens,\n [UserStorage.USER]: resolvedConfig.cookies?.user,\n });\n\n // Convert to framework-agnostic request format\n const urlDetectionRequest = toUrlDetectionRequest(request);\n\n // Get appUrl from client (for proxy environments)\n const clientAppUrl = CivicAuth.getAppUrl(urlDetectionRequest);\n\n // Use baseUrl from config, then client appUrl, then request origin\n // This matches the main branch priority: config > client > request\n const appUrl =\n resolvedConfig.baseUrl ||\n clientAppUrl ||\n new URL(urlDetectionRequest.url).origin;\n\n // Build absolute URLs using detected appUrl or request origin\n const absoluteCallbackUrl = resolvedConfig.callbackUrl.startsWith(\"http\")\n ? resolvedConfig.callbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.callbackUrl,\n appUrl,\n );\n const absoluteLogoutCallbackUrl = resolvedConfig.logoutCallbackUrl.startsWith(\n \"http\",\n )\n ? resolvedConfig.logoutCallbackUrl\n : CivicAuth.toAbsoluteUrl(\n urlDetectionRequest,\n resolvedConfig.logoutCallbackUrl,\n appUrl,\n );\n\n const civicAuth = new CivicAuth(cookieStorage, {\n disableRefresh: resolvedConfig.disableRefresh,\n clientId: resolvedConfig.clientId,\n redirectUrl: absoluteCallbackUrl,\n oauthServer: resolvedConfig.oauthServer,\n postLogoutRedirectUrl: absoluteLogoutCallbackUrl,\n // 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 // 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"]}
|
package/dist/nextjs/utils.d.ts
CHANGED
|
@@ -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,
|
|
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,M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V,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAczC;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,aACf,MAAM,WACP,WAAW,cACR,sBAAsB,KACjC,IAWF,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,8BAA8B,aAC/B,MAAM,cACJ,sBAAsB,KACjC,OAiBF,CAAC;AAEF,eAAO,MAAM,gBAAgB,mBACX,YAAY,cAChB,YAAY,GAAG,WAAW,SAoBvC,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,yBAAyB,YAC3B,WAAW,WACX,WAAW,YACV,YAAY,WACb,6BAA6B,cAC1B,sBAAsB,KACjC,OAAO,CAAC,YAAY,GAAG,SAAS,CAmClC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,eAAe,QAAS,MAAM,YAAY,MAAM,WAiB5D,CAAC;AAEF,eAAO,MAAM,oBAAoB,WACvB,UAAU,aACP,MAAM,KAChB,YACuE,CAAC"}
|
package/dist/nextjs/utils.js
CHANGED
|
@@ -2,10 +2,10 @@ import { systemUrlsConfig, } from "../nextjs/config.js";
|
|
|
2
2
|
import { NextResponse } from "next/server.js";
|
|
3
3
|
import { loggers } from "../lib/logger.js";
|
|
4
4
|
import picomatch from "picomatch";
|
|
5
|
-
import {
|
|
6
|
-
import { clearTokens, getCookieConfiguration, sanitizeReturnUrl, } from "../shared/lib/util.js";
|
|
5
|
+
import { CodeVerifier, OAuthTokenTypes, UserStorage, } from "../shared/lib/types.js";
|
|
6
|
+
import { clearTokens, computeDeepLinkDestination, getCookieConfiguration, sanitizeReturnUrl, } from "../shared/lib/util.js";
|
|
7
7
|
// Re-export for use by routeHandler
|
|
8
|
-
export { sanitizeReturnUrl };
|
|
8
|
+
export { sanitizeReturnUrl, computeDeepLinkDestination };
|
|
9
9
|
import { CookieStorage } from "../server/index.js";
|
|
10
10
|
import { extractCookieFromRawHeader } from "../shared/lib/cookieUtils.js";
|
|
11
11
|
const logger = loggers.nextjs.middleware;
|
|
@@ -210,7 +210,13 @@ export const copyCivicCookies = (sourceResponse, targetCall) => {
|
|
|
210
210
|
});
|
|
211
211
|
};
|
|
212
212
|
/**
|
|
213
|
-
* Handles final authentication logic for unauthenticated users on protected routes
|
|
213
|
+
* Handles final authentication logic for unauthenticated users on protected routes.
|
|
214
|
+
*
|
|
215
|
+
* Note: Deep link cookie setting and auth redirect marker are now handled by
|
|
216
|
+
* CivicAuth.handleDeepLinking which runs earlier in the middleware flow.
|
|
217
|
+
* This function focuses on:
|
|
218
|
+
* 1. Clearing expired/invalid tokens
|
|
219
|
+
* 2. Redirecting to the login URL
|
|
214
220
|
*/
|
|
215
221
|
export const handleUnauthenticatedUser = async (session, request, response, storage, authConfig) => {
|
|
216
222
|
// Clear expired/invalid tokens if they exist
|
|
@@ -227,54 +233,6 @@ export const handleUnauthenticatedUser = async (session, request, response, stor
|
|
|
227
233
|
// The loginUrl from getOriginUrl already includes the basePath, but request.nextUrl.pathname does not. So we strip it off to enable comparison.
|
|
228
234
|
if (request.nextUrl.pathname !== loginPathWithoutBasePath) {
|
|
229
235
|
logger.debug(`→ No valid tokens found - redirecting to login "${redirectUrl}"`);
|
|
230
|
-
// Preserve the original URL as a deep link for post-authentication redirect
|
|
231
|
-
// Apply deepLinkHandling logic here to compute the final redirect URL
|
|
232
|
-
if (authConfig.deepLinkHandling !== "disabled") {
|
|
233
|
-
const originUrl = getOriginUrl(request, authConfig);
|
|
234
|
-
// Get the full path including query string
|
|
235
|
-
const fullPath = request.nextUrl.pathname +
|
|
236
|
-
request.nextUrl.search +
|
|
237
|
-
request.nextUrl.hash;
|
|
238
|
-
// Sanitize the return URL to prevent open redirect vulnerabilities
|
|
239
|
-
const sanitizedReturnUrl = sanitizeReturnUrl(fullPath, originUrl);
|
|
240
|
-
if (sanitizedReturnUrl) {
|
|
241
|
-
let returnTo;
|
|
242
|
-
if (authConfig.deepLinkHandling === "queryParamsOnly") {
|
|
243
|
-
// queryParamsOnly: Merge query params from original URL into loginSuccessUrl
|
|
244
|
-
const loginSuccessUrl = authConfig.loginSuccessUrl || "/";
|
|
245
|
-
try {
|
|
246
|
-
const returnUrlObj = new URL(sanitizedReturnUrl, originUrl);
|
|
247
|
-
// If no query params, use loginSuccessUrl directly
|
|
248
|
-
if (returnUrlObj.searchParams.size === 0) {
|
|
249
|
-
logger.debug(`→ deepLinkHandling=queryParamsOnly: no query params to preserve, using loginSuccessUrl "${loginSuccessUrl}"`);
|
|
250
|
-
returnTo = loginSuccessUrl;
|
|
251
|
-
}
|
|
252
|
-
else {
|
|
253
|
-
const baseUrlObj = new URL(loginSuccessUrl, originUrl);
|
|
254
|
-
// Append query params from original URL to loginSuccessUrl
|
|
255
|
-
returnUrlObj.searchParams.forEach((value, key) => {
|
|
256
|
-
baseUrlObj.searchParams.set(key, value);
|
|
257
|
-
});
|
|
258
|
-
returnTo =
|
|
259
|
-
baseUrlObj.pathname + baseUrlObj.search + baseUrlObj.hash;
|
|
260
|
-
logger.debug(`→ deepLinkHandling=queryParamsOnly: merged params into "${returnTo}"`);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
catch {
|
|
264
|
-
// If URL parsing fails, fall back to loginSuccessUrl
|
|
265
|
-
logger.warn(`→ Failed to merge query params, falling back to loginSuccessUrl`);
|
|
266
|
-
returnTo = loginSuccessUrl;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
else {
|
|
270
|
-
// fullUrl: Use the full path directly
|
|
271
|
-
returnTo = sanitizedReturnUrl;
|
|
272
|
-
logger.debug(`→ deepLinkHandling=fullUrl: preserving deep link "${returnTo}"`);
|
|
273
|
-
}
|
|
274
|
-
// Set the cookie with the computed return URL
|
|
275
|
-
await storage.set(AuthFlowCookie.RETURN_URL, returnTo, {});
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
236
|
const redirectedResponse = redirectWithBasePath(authConfig, redirectUrl);
|
|
279
237
|
// Copy any cookies that were set to the redirect response
|
|
280
238
|
response.cookies.getAll().forEach((cookie) => {
|
package/dist/nextjs/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/nextjs/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,GAGjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EACL,cAAc,EACd,YAAY,EACZ,eAAe,EACf,WAAW,GAGZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,WAAW,EACX,sBAAsB,EACtB,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,oCAAoC;AACpC,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;AAEzC,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,MAA8B,EAC9B,OAAgB,EACR,EAAE;IACV,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;IACrE,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAC;AAChC,CAAC,CAAC;AAEF,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,IAAI,CAAC,IAAI,IAAI,IAAI,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IAErC,gCAAgC;IAChC,MAAM,gBAAgB,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC;IAElE,6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C,QAAQ,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YACrC,CAAC,CAAC,QAAQ;gBACR,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC;QACpE,CAAC;QACD,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;IACtB,CAAC;IAED,OAAO,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC;QAC7B,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,QAAQ,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACxD,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,MAAkB,EAClB,SAAiB,EACH,EAAE,CAChB,YAAY,CAAC,QAAQ,CAAC,eAAe,CAAC,SAAS,EAAE,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,CAAC","sourcesContent":["import {\n systemUrlsConfig,\n type AuthConfig,\n type AuthConfigWithDefaults,\n} from \"@/nextjs/config.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport type { SessionData } from \"@/types.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport picomatch from \"picomatch\";\nimport {\n AuthFlowCookie,\n CodeVerifier,\n OAuthTokenTypes,\n UserStorage,\n type CookieConfig,\n type KeySetter,\n} from \"@/shared/lib/types.js\";\nimport {\n clearTokens,\n getCookieConfiguration,\n sanitizeReturnUrl,\n} from \"@/shared/lib/util.js\";\n\n// Re-export for use by routeHandler\nexport { sanitizeReturnUrl };\nimport { CookieStorage } from \"@/server/index.js\";\nimport { extractCookieFromRawHeader } from \"@/shared/lib/cookieUtils.js\";\n\nconst logger = loggers.nextjs.middleware;\n\nexport const resolveCallbackUrl = (\n config: AuthConfigWithDefaults,\n baseUrl?: string,\n): string => {\n const callbackUrl = new URL(config?.callbackUrl, baseUrl).toString();\n return callbackUrl.toString();\n};\n\nexport function sanitizeBasePath(path: string): string {\n if (!path || path === \"/\") return \"\";\n\n // Ensure it starts with a slash\n const withLeadingSlash = path.startsWith(\"/\") ? path : `/${path}`;\n\n // Remove all trailing slashes (not just one)\n return withLeadingSlash.replace(/\\/+$/, \"\");\n}\n\n/**\n * Removes the basePath prefix from a pathname, properly handling edge cases\n * This is the inverse operation of adding basePath to a URL\n */\nexport function removeBasePathFromPath(\n pathname: string,\n basePath?: string,\n): string {\n if (!basePath || basePath === \"\" || basePath === \"/\") {\n return pathname;\n }\n\n // Sanitize the basePath to ensure consistent format\n const sanitizedBasePath = sanitizeBasePath(basePath);\n\n // Check if pathname starts with the basePath followed by a slash or end of string\n // This prevents partial matches like \"/app\" matching \"/application\"\n if (pathname === sanitizedBasePath) {\n // Exact match - return root\n return \"/\";\n } else if (pathname.startsWith(sanitizedBasePath + \"/\")) {\n // basePath followed by slash - remove basePath but keep the slash\n return pathname.slice(sanitizedBasePath.length);\n }\n\n // If basePath doesn't match as a complete path segment, return pathname as-is\n return pathname;\n}\n\nexport const getOriginUrl = (\n request: NextRequest,\n authConfig: AuthConfigWithDefaults,\n): string => {\n // Use configured baseUrl if provided (for reverse proxy scenarios)\n if (authConfig.baseUrl) {\n return authConfig.baseUrl;\n }\n\n // Fallback to nextUrl.origin (includes port automatically)\n return request.nextUrl.origin;\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n return matchGlob(pathname, pattern);\n });\n\n/**\n * Determines if we should attempt token refresh based on session state\n */\nexport const shouldAttemptRefresh = (session: SessionData): boolean => {\n return !session.authenticated && !!session.refreshToken;\n};\n\nconst stripBasePathPrefix = (path: string, basePath: string = \"\") => {\n return path.replace(new RegExp(`^${basePath}`), \"\");\n};\n/**\n * Checks if the current path is a system URL that should skip auth\n */\nexport const shouldSkipAuthForSystemUrls = (\n pathname: string,\n authConfig: AuthConfigWithDefaults,\n): boolean => {\n // make an array of all system URLs from authConfig using the systemUrlsConfig keys\n const systemUrls = Object.keys(systemUrlsConfig).map(\n (key) => authConfig[key as keyof AuthConfigWithDefaults] as string,\n );\n\n // check if any of the urls in systemUrls has a substring match with pathname\n // the systemUrl or incoming path could have a basePath, i.e. /dashboard/api/auth/callback\n // therefore we check if the systemUrl equals the pathname after stripping the basePath prefix\n const strippedPathname = stripBasePathPrefix(pathname, authConfig.basePath);\n const strippedSystemUrls = systemUrls.map((url) =>\n stripBasePathPrefix(url, authConfig.basePath),\n );\n const isSystemUrl = strippedSystemUrls.some(\n (url) => url && pathname && pathname !== \"/\" && url === strippedPathname,\n );\n logger.debug(\"→ isSystemUrl check\", { pathname, isSystemUrl, systemUrls });\n if (isSystemUrl) {\n logger.debug(\n \"→ Skipping auth check - this a URL defined in authConfig\",\n pathname,\n );\n }\n\n return isSystemUrl;\n};\n\n/**\n * CookieStorage implementation for NextJS middleware context that works with NextRequest\n */\nexport class NextjsMiddlewareCookieStorage extends CookieStorage {\n constructor(\n public config: Partial<Record<KeySetter, CookieConfig>> = {},\n private request: NextRequest,\n private response: NextResponse,\n ) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n // First try to get cookies from the response if it has already been set\n const cookieValue = this.response.cookies.get(key)?.value;\n if (cookieValue) {\n return cookieValue;\n }\n\n const cookieSettings = this.config?.[key as KeySetter] || {};\n const configuredPath = cookieSettings.path;\n\n // If we have a non-root basePath, use raw header parsing to get the first cookie\n // which should be from the most specific path, avoiding duplicate cookie conflicts\n if (configuredPath && configuredPath !== \"/\") {\n const cookieHeader = this.request.headers.get(\"cookie\");\n const rawValue = extractCookieFromRawHeader(cookieHeader, key);\n if (rawValue) {\n return rawValue;\n }\n }\n\n // Fallback to standard Next.js request cookies\n return this.request.cookies.get(key)?.value || null;\n }\n\n async set(\n key: string,\n value: string,\n cookieConfigOverride: CookieConfig,\n ): Promise<void> {\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n const dynamicConfig = getCookieConfiguration(this.request);\n\n const useCookieSettings = {\n ...cookieSettings,\n ...cookieConfigOverride,\n // Apply dynamic configuration for secure and sameSite\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n };\n\n // Respect the httpOnly setting from configuration instead of hardcoding it\n this.response.cookies.set(key, value, useCookieSettings);\n }\n\n async delete(key: string): Promise<void> {\n // Get cookie configuration for this key to respect the path setting\n const cookieSettings = this.config?.[key as KeySetter] || {};\n\n // If we have a path configured, use it when deleting the cookie\n if (cookieSettings.path) {\n this.response.cookies.set(key, \"\", {\n maxAge: 0, // Immediately expire the cookie\n path: cookieSettings.path,\n });\n } else {\n this.response.cookies.delete(key);\n }\n }\n}\n\n/**\n * Handles authentication logic specifically for the login URL\n * Provides logging for login URL access patterns\n */\nexport const handleLoginUrl = (\n pathname: string,\n session: SessionData,\n authConfig: AuthConfigWithDefaults,\n): void => {\n if (pathname !== authConfig.loginUrl) {\n return;\n }\n\n // We are on the login URL - log the access pattern\n if (session.authenticated) {\n logger.debug(`→ Authenticated user accessing login page`);\n } else {\n logger.debug(`→ Unauthenticated user accessing login page`);\n }\n};\n\n/**\n * Checks if the current path should skip auth based on include/exclude patterns\n */\nexport const shouldSkipAuthForRoutePatterns = (\n pathname: string,\n authConfig: AuthConfigWithDefaults,\n): boolean => {\n // Check include patterns\n if (!matchesGlobs(pathname, authConfig.include)) {\n logger.debug(\n \"→ Skipping auth check - path not in include patterns\",\n pathname,\n );\n return true;\n }\n\n // Check exclude patterns\n if (matchesGlobs(pathname, authConfig.exclude)) {\n logger.debug(\"→ Skipping auth check - path in exclude patterns\", pathname);\n return true;\n }\n\n return false;\n};\n\nexport const copyCivicCookies = (\n sourceResponse: NextResponse,\n targetCall: NextResponse | NextRequest,\n) => {\n const civicCookieNames = [\n ...Object.values(OAuthTokenTypes),\n ...Object.values(UserStorage),\n ...Object.values(CodeVerifier),\n ];\n logger.debug(\"Copying Civic cookies:\", {\n src: sourceResponse.url,\n target: targetCall.url,\n });\n sourceResponse?.cookies\n .getAll()\n .filter((cookie) =>\n civicCookieNames.includes(cookie.name as OAuthTokenTypes),\n )\n .forEach((cookie) => {\n logger.debug(\"Setting middlewareResponse cookie:\", cookie);\n targetCall.cookies.set(cookie);\n });\n};\n/**\n * Handles final authentication logic for unauthenticated users on protected routes\n */\nexport const handleUnauthenticatedUser = async (\n session: SessionData,\n request: NextRequest,\n response: NextResponse,\n storage: NextjsMiddlewareCookieStorage,\n authConfig: AuthConfigWithDefaults,\n): Promise<NextResponse | undefined> => {\n // Clear expired/invalid tokens if they exist\n if (session.accessToken || session.idToken || session.refreshToken) {\n logger.debug(`→ Clearing expired/invalid tokens`);\n await clearTokens(storage);\n }\n\n // Final fallback: redirect to login unless we're already there.\n const loginUrl = new URL(\n authConfig.loginUrl,\n getOriginUrl(request, authConfig),\n );\n const redirectUrl = `${loginUrl.toString()}`;\n const loginPathWithoutBasePath = removeBasePathFromPath(\n loginUrl.pathname,\n authConfig.basePath,\n );\n\n // If we're already at the login URL, the middleware will just return undefined.\n // This is to prevent an infinite redirect loop if middleware is applied to the login route itself.\n // The loginUrl from getOriginUrl already includes the basePath, but request.nextUrl.pathname does not. So we strip it off to enable comparison.\n if (request.nextUrl.pathname !== loginPathWithoutBasePath) {\n logger.debug(\n `→ No valid tokens found - redirecting to login \"${redirectUrl}\"`,\n );\n\n // Preserve the original URL as a deep link for post-authentication redirect\n // Apply deepLinkHandling logic here to compute the final redirect URL\n if (authConfig.deepLinkHandling !== \"disabled\") {\n const originUrl = getOriginUrl(request, authConfig);\n // Get the full path including query string\n const fullPath =\n request.nextUrl.pathname +\n request.nextUrl.search +\n request.nextUrl.hash;\n\n // Sanitize the return URL to prevent open redirect vulnerabilities\n const sanitizedReturnUrl = sanitizeReturnUrl(fullPath, originUrl);\n\n if (sanitizedReturnUrl) {\n let returnTo: string;\n\n if (authConfig.deepLinkHandling === \"queryParamsOnly\") {\n // queryParamsOnly: Merge query params from original URL into loginSuccessUrl\n const loginSuccessUrl = authConfig.loginSuccessUrl || \"/\";\n try {\n const returnUrlObj = new URL(sanitizedReturnUrl, originUrl);\n\n // If no query params, use loginSuccessUrl directly\n if (returnUrlObj.searchParams.size === 0) {\n logger.debug(\n `→ deepLinkHandling=queryParamsOnly: no query params to preserve, using loginSuccessUrl \"${loginSuccessUrl}\"`,\n );\n returnTo = loginSuccessUrl;\n } else {\n const baseUrlObj = new URL(loginSuccessUrl, originUrl);\n\n // Append query params from original URL to loginSuccessUrl\n returnUrlObj.searchParams.forEach((value, key) => {\n baseUrlObj.searchParams.set(key, value);\n });\n\n returnTo =\n baseUrlObj.pathname + baseUrlObj.search + baseUrlObj.hash;\n logger.debug(\n `→ deepLinkHandling=queryParamsOnly: merged params into \"${returnTo}\"`,\n );\n }\n } catch {\n // If URL parsing fails, fall back to loginSuccessUrl\n logger.warn(\n `→ Failed to merge query params, falling back to loginSuccessUrl`,\n );\n returnTo = loginSuccessUrl;\n }\n } else {\n // fullUrl: Use the full path directly\n returnTo = sanitizedReturnUrl;\n logger.debug(\n `→ deepLinkHandling=fullUrl: preserving deep link \"${returnTo}\"`,\n );\n }\n\n // Set the cookie with the computed return URL\n await storage.set(AuthFlowCookie.RETURN_URL, returnTo, {});\n }\n }\n\n const redirectedResponse = redirectWithBasePath(authConfig, redirectUrl);\n // Copy any cookies that were set to the redirect response\n response.cookies.getAll().forEach((cookie) => {\n redirectedResponse.cookies.set(cookie);\n });\n return redirectedResponse;\n }\n\n return response;\n};\n\n/**\n * Prepends the basePath onto a given URL if it's not already there. Works for both relative and absolute URLs.\n * @param url\n * @param basePath\n * @returns\n */\nexport const prependBasePath = (url: string, basePath: string) => {\n basePath = \"/\" + basePath.replace(/^\\/|\\/$/g, \"\"); // normalize basePath\n\n const isAbsolute = /^https?:\\/\\//.test(url);\n\n if (isAbsolute) {\n const u = new URL(url);\n if (!u.pathname.startsWith(basePath)) {\n u.pathname =\n basePath + (u.pathname.startsWith(\"/\") ? \"\" : \"/\") + u.pathname;\n }\n return u.toString();\n }\n\n return url.startsWith(basePath)\n ? url\n : basePath + (url.startsWith(\"/\") ? \"\" : \"/\") + url;\n};\n\nexport const redirectWithBasePath = (\n config: AuthConfig,\n targetUrl: string,\n): NextResponse =>\n NextResponse.redirect(prependBasePath(targetUrl, config.basePath || \"\"));\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/nextjs/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,GAGjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EACL,YAAY,EACZ,eAAe,EACf,WAAW,GAGZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,WAAW,EACX,0BAA0B,EAC1B,sBAAsB,EACtB,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,oCAAoC;AACpC,OAAO,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;AAEzC,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,MAA8B,EAC9B,OAAgB,EACR,EAAE;IACV,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE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AAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC;QACpE,CAAC;QACD,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;IACtB,CAAC;IAED,OAAO,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC;QAC7B,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,QAAQ,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACxD,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,MAAkB,EAClB,SAAiB,EACH,EAAE,CAChB,YAAY,CAAC,QAAQ,CAAC,eAAe,CAAC,SAAS,EAAE,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,CAAC","sourcesContent":["import {\n systemUrlsConfig,\n type AuthConfig,\n type AuthConfigWithDefaults,\n} from \"@/nextjs/config.js\";\nimport type { NextRequest } from \"next/server.js\";\nimport { NextResponse } from \"next/server.js\";\nimport type { SessionData } from \"@/types.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport picomatch from \"picomatch\";\nimport {\n CodeVerifier,\n OAuthTokenTypes,\n UserStorage,\n type CookieConfig,\n type KeySetter,\n} from \"@/shared/lib/types.js\";\nimport {\n clearTokens,\n computeDeepLinkDestination,\n getCookieConfiguration,\n sanitizeReturnUrl,\n} from \"@/shared/lib/util.js\";\n\n// Re-export for use by routeHandler\nexport { sanitizeReturnUrl, computeDeepLinkDestination };\nimport { CookieStorage } from \"@/server/index.js\";\nimport { extractCookieFromRawHeader } from \"@/shared/lib/cookieUtils.js\";\n\nconst logger = loggers.nextjs.middleware;\n\nexport const resolveCallbackUrl = (\n config: AuthConfigWithDefaults,\n baseUrl?: string,\n): string => {\n const callbackUrl = new URL(config?.callbackUrl, baseUrl).toString();\n return callbackUrl.toString();\n};\n\nexport function sanitizeBasePath(path: string): string {\n if (!path || path === \"/\") return \"\";\n\n // Ensure it starts with a slash\n const withLeadingSlash = path.startsWith(\"/\") ? path : `/${path}`;\n\n // Remove all trailing slashes (not just one)\n return withLeadingSlash.replace(/\\/+$/, \"\");\n}\n\n/**\n * Removes the basePath prefix from a pathname, properly handling edge cases\n * This is the inverse operation of adding basePath to a URL\n */\nexport function removeBasePathFromPath(\n pathname: string,\n basePath?: string,\n): string {\n if (!basePath || basePath === \"\" || basePath === \"/\") {\n return pathname;\n }\n\n // Sanitize the basePath to ensure consistent format\n const sanitizedBasePath = sanitizeBasePath(basePath);\n\n // Check if pathname starts with the basePath followed by a slash or end of string\n // This prevents partial matches like \"/app\" matching \"/application\"\n if (pathname === sanitizedBasePath) {\n // Exact match - return root\n return \"/\";\n } else if (pathname.startsWith(sanitizedBasePath + \"/\")) {\n // basePath followed by slash - remove basePath but keep the slash\n return pathname.slice(sanitizedBasePath.length);\n }\n\n // If basePath doesn't match as a complete path segment, return pathname as-is\n return pathname;\n}\n\nexport const getOriginUrl = (\n request: NextRequest,\n authConfig: AuthConfigWithDefaults,\n): string => {\n // Use configured baseUrl if provided (for reverse proxy scenarios)\n if (authConfig.baseUrl) {\n return authConfig.baseUrl;\n }\n\n // Fallback to nextUrl.origin (includes port automatically)\n return request.nextUrl.origin;\n};\n\n// Matches globs:\n// Examples:\n// /user\n// /user/*\n// /user/**/info\nconst matchGlob = (pathname: string, globPattern: string) => {\n const matches = picomatch(globPattern);\n return matches(pathname);\n};\n\nconst matchesGlobs = (pathname: string, patterns: string[]) =>\n patterns.some((pattern) => {\n if (!pattern) return false;\n return matchGlob(pathname, pattern);\n });\n\n/**\n * Determines if we should attempt token refresh based on session state\n */\nexport const shouldAttemptRefresh = (session: SessionData): boolean => {\n return !session.authenticated && !!session.refreshToken;\n};\n\nconst stripBasePathPrefix = (path: string, basePath: string = \"\") => {\n return path.replace(new RegExp(`^${basePath}`), \"\");\n};\n/**\n * Checks if the current path is a system URL that should skip auth\n */\nexport const shouldSkipAuthForSystemUrls = (\n pathname: string,\n authConfig: AuthConfigWithDefaults,\n): boolean => {\n // make an array of all system URLs from authConfig using the systemUrlsConfig keys\n const systemUrls = Object.keys(systemUrlsConfig).map(\n (key) => authConfig[key as keyof AuthConfigWithDefaults] as string,\n );\n\n // check if any of the urls in systemUrls has a substring match with pathname\n // the systemUrl or incoming path could have a basePath, i.e. /dashboard/api/auth/callback\n // therefore we check if the systemUrl equals the pathname after stripping the basePath prefix\n const strippedPathname = stripBasePathPrefix(pathname, authConfig.basePath);\n const strippedSystemUrls = systemUrls.map((url) =>\n stripBasePathPrefix(url, authConfig.basePath),\n );\n const isSystemUrl = strippedSystemUrls.some(\n (url) => url && pathname && pathname !== \"/\" && url === strippedPathname,\n );\n logger.debug(\"→ isSystemUrl check\", { pathname, isSystemUrl, systemUrls });\n if (isSystemUrl) {\n logger.debug(\n \"→ Skipping auth check - this a URL defined in authConfig\",\n pathname,\n );\n }\n\n return isSystemUrl;\n};\n\n/**\n * CookieStorage implementation for NextJS middleware context that works with NextRequest\n */\nexport class NextjsMiddlewareCookieStorage extends CookieStorage {\n constructor(\n public config: Partial<Record<KeySetter, CookieConfig>> = {},\n private request: NextRequest,\n private response: NextResponse,\n ) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n async get(key: string): Promise<string | null> {\n // First try to get cookies from the response if it has already been set\n const cookieValue = this.response.cookies.get(key)?.value;\n if (cookieValue) {\n return cookieValue;\n }\n\n const cookieSettings = this.config?.[key as KeySetter] || {};\n const configuredPath = cookieSettings.path;\n\n // If we have a non-root basePath, use raw header parsing to get the first cookie\n // which should be from the most specific path, avoiding duplicate cookie conflicts\n if (configuredPath && configuredPath !== \"/\") {\n const cookieHeader = this.request.headers.get(\"cookie\");\n const rawValue = extractCookieFromRawHeader(cookieHeader, key);\n if (rawValue) {\n return rawValue;\n }\n }\n\n // Fallback to standard Next.js request cookies\n return this.request.cookies.get(key)?.value || null;\n }\n\n async set(\n key: string,\n value: string,\n cookieConfigOverride: CookieConfig,\n ): Promise<void> {\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n const dynamicConfig = getCookieConfiguration(this.request);\n\n const useCookieSettings = {\n ...cookieSettings,\n ...cookieConfigOverride,\n // Apply dynamic configuration for secure and sameSite\n secure: dynamicConfig.secure,\n sameSite: dynamicConfig.sameSite,\n };\n\n // Respect the httpOnly setting from configuration instead of hardcoding it\n this.response.cookies.set(key, value, useCookieSettings);\n }\n\n async delete(key: string): Promise<void> {\n // Get cookie configuration for this key to respect the path setting\n const cookieSettings = this.config?.[key as KeySetter] || {};\n\n // If we have a path configured, use it when deleting the cookie\n if (cookieSettings.path) {\n this.response.cookies.set(key, \"\", {\n maxAge: 0, // Immediately expire the cookie\n path: cookieSettings.path,\n });\n } else {\n this.response.cookies.delete(key);\n }\n }\n}\n\n/**\n * Handles authentication logic specifically for the login URL\n * Provides logging for login URL access patterns\n */\nexport const handleLoginUrl = (\n pathname: string,\n session: SessionData,\n authConfig: AuthConfigWithDefaults,\n): void => {\n if (pathname !== authConfig.loginUrl) {\n return;\n }\n\n // We are on the login URL - log the access pattern\n if (session.authenticated) {\n logger.debug(`→ Authenticated user accessing login page`);\n } else {\n logger.debug(`→ Unauthenticated user accessing login page`);\n }\n};\n\n/**\n * Checks if the current path should skip auth based on include/exclude patterns\n */\nexport const shouldSkipAuthForRoutePatterns = (\n pathname: string,\n authConfig: AuthConfigWithDefaults,\n): boolean => {\n // Check include patterns\n if (!matchesGlobs(pathname, authConfig.include)) {\n logger.debug(\n \"→ Skipping auth check - path not in include patterns\",\n pathname,\n );\n return true;\n }\n\n // Check exclude patterns\n if (matchesGlobs(pathname, authConfig.exclude)) {\n logger.debug(\"→ Skipping auth check - path in exclude patterns\", pathname);\n return true;\n }\n\n return false;\n};\n\nexport const copyCivicCookies = (\n sourceResponse: NextResponse,\n targetCall: NextResponse | NextRequest,\n) => {\n const civicCookieNames = [\n ...Object.values(OAuthTokenTypes),\n ...Object.values(UserStorage),\n ...Object.values(CodeVerifier),\n ];\n logger.debug(\"Copying Civic cookies:\", {\n src: sourceResponse.url,\n target: targetCall.url,\n });\n sourceResponse?.cookies\n .getAll()\n .filter((cookie) =>\n civicCookieNames.includes(cookie.name as OAuthTokenTypes),\n )\n .forEach((cookie) => {\n logger.debug(\"Setting middlewareResponse cookie:\", cookie);\n targetCall.cookies.set(cookie);\n });\n};\n\n/**\n * Handles final authentication logic for unauthenticated users on protected routes.\n *\n * Note: Deep link cookie setting and auth redirect marker are now handled by\n * CivicAuth.handleDeepLinking which runs earlier in the middleware flow.\n * This function focuses on:\n * 1. Clearing expired/invalid tokens\n * 2. Redirecting to the login URL\n */\nexport const handleUnauthenticatedUser = async (\n session: SessionData,\n request: NextRequest,\n response: NextResponse,\n storage: NextjsMiddlewareCookieStorage,\n authConfig: AuthConfigWithDefaults,\n): Promise<NextResponse | undefined> => {\n // Clear expired/invalid tokens if they exist\n if (session.accessToken || session.idToken || session.refreshToken) {\n logger.debug(`→ Clearing expired/invalid tokens`);\n await clearTokens(storage);\n }\n\n // Final fallback: redirect to login unless we're already there.\n const loginUrl = new URL(\n authConfig.loginUrl,\n getOriginUrl(request, authConfig),\n );\n const redirectUrl = `${loginUrl.toString()}`;\n const loginPathWithoutBasePath = removeBasePathFromPath(\n loginUrl.pathname,\n authConfig.basePath,\n );\n\n // If we're already at the login URL, the middleware will just return undefined.\n // This is to prevent an infinite redirect loop if middleware is applied to the login route itself.\n // The loginUrl from getOriginUrl already includes the basePath, but request.nextUrl.pathname does not. So we strip it off to enable comparison.\n if (request.nextUrl.pathname !== loginPathWithoutBasePath) {\n logger.debug(\n `→ No valid tokens found - redirecting to login \"${redirectUrl}\"`,\n );\n\n const redirectedResponse = redirectWithBasePath(authConfig, redirectUrl);\n // Copy any cookies that were set to the redirect response\n response.cookies.getAll().forEach((cookie) => {\n redirectedResponse.cookies.set(cookie);\n });\n return redirectedResponse;\n }\n\n return response;\n};\n\n/**\n * Prepends the basePath onto a given URL if it's not already there. Works for both relative and absolute URLs.\n * @param url\n * @param basePath\n * @returns\n */\nexport const prependBasePath = (url: string, basePath: string) => {\n basePath = \"/\" + basePath.replace(/^\\/|\\/$/g, \"\"); // normalize basePath\n\n const isAbsolute = /^https?:\\/\\//.test(url);\n\n if (isAbsolute) {\n const u = new URL(url);\n if (!u.pathname.startsWith(basePath)) {\n u.pathname =\n basePath + (u.pathname.startsWith(\"/\") ? \"\" : \"/\") + u.pathname;\n }\n return u.toString();\n }\n\n return url.startsWith(basePath)\n ? url\n : basePath + (url.startsWith(\"/\") ? \"\" : \"/\") + url;\n};\n\nexport const redirectWithBasePath = (\n config: AuthConfig,\n targetUrl: string,\n): NextResponse =>\n NextResponse.redirect(prependBasePath(targetUrl, config.basePath || \"\"));\n"]}
|
package/dist/server/config.d.ts
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
import type { Endpoints } from "../types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Controls how deep links (original URLs) are handled after authentication.
|
|
4
|
+
*
|
|
5
|
+
* - `"fullUrl"`: Redirect to the original URL the user tried to access.
|
|
6
|
+
* `loginSuccessUrl` is used as fallback only when no deep link exists.
|
|
7
|
+
* - `"queryParamsOnly"`: Redirect to `loginSuccessUrl`, but merge query params from original URL.
|
|
8
|
+
* - `"disabled"`: No deep link preservation. Always use `loginSuccessUrl`.
|
|
9
|
+
*
|
|
10
|
+
* @default "fullUrl"
|
|
11
|
+
*/
|
|
12
|
+
export type DeepLinkHandling = "fullUrl" | "queryParamsOnly" | "disabled";
|
|
2
13
|
/**
|
|
3
14
|
* Configuration for backend authentication endpoints
|
|
4
15
|
* Allows customization of API endpoints when using backend integration (loginUrl)
|
|
@@ -64,6 +75,18 @@ export type AuthConfig = {
|
|
|
64
75
|
* Useful for applications that want to handle token lifecycle manually.
|
|
65
76
|
*/
|
|
66
77
|
disableRefresh?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Optional base path for URL handling.
|
|
80
|
+
* When set, this will be prepended to relative URLs in handleCallback responses.
|
|
81
|
+
* Commonly used with NextJS basePath configuration.
|
|
82
|
+
*/
|
|
83
|
+
basePath?: string;
|
|
84
|
+
/**
|
|
85
|
+
* Controls how deep links (original URLs) are handled after authentication.
|
|
86
|
+
* @see DeepLinkHandling
|
|
87
|
+
* @default "fullUrl"
|
|
88
|
+
*/
|
|
89
|
+
deepLinkHandling?: DeepLinkHandling;
|
|
67
90
|
} & ({
|
|
68
91
|
/** OAuth client ID - required for standard OAuth flow */
|
|
69
92
|
clientId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/server/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oDAAoD;IACpD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wFAAwF;IACxF,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,UAAU,GAAG;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACnD,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IACpC;;;;;OAKG;IACH,eAAe,CAAC,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