@civic/auth 0.10.0-beta.10 → 0.10.0-beta.11
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.
|
@@ -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,EAIL,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAKlD,eAAO,MAAM,kBAAkB,WACrB,sBAAsB,YACpB,MAAM,KACf,MAGF,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQrD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,MAAM,EAChB,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,CAoBR;AA+BD;;GAEG;AACH,eAAO,MAAM,oBAAoB,YAAa,WAAW,KAAG,OAE3D,CAAC;
|
|
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;A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AM,cACJ,sBAAsB,KACjC,OAiBF,CAAC;AAEF,eAAO,MAAM,gBAAgB,mBACX,YAAY,cAChB,YAAY,GAAG,WAAW,SAoBvC,CAAC;AACF;;GAEG;AACH,eAAO,MAAM,yBAAyB,YAC3B,WAAW,WACX,WAAW,YACV,YAAY,WACb,6BAA6B,cAC1B,sBAAsB,KACjC,OAAO,CAAC,YAAY,GAAG,SAAS,CA8BlC,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
|
@@ -70,6 +70,9 @@ const matchesGlobs = (pathname, patterns) => patterns.some((pattern) => {
|
|
|
70
70
|
export const shouldAttemptRefresh = (session) => {
|
|
71
71
|
return !session.authenticated && !!session.refreshToken;
|
|
72
72
|
};
|
|
73
|
+
const stripBasePathPrefix = (path, basePath = "") => {
|
|
74
|
+
return path.replace(new RegExp(`^${basePath}`), "");
|
|
75
|
+
};
|
|
73
76
|
/**
|
|
74
77
|
* Checks if the current path is a system URL that should skip auth
|
|
75
78
|
*/
|
|
@@ -77,9 +80,11 @@ export const shouldSkipAuthForSystemUrls = (pathname, authConfig) => {
|
|
|
77
80
|
// make an array of all system URLs from authConfig using the systemUrlsConfig keys
|
|
78
81
|
const systemUrls = Object.keys(systemUrlsConfig).map((key) => authConfig[key]);
|
|
79
82
|
// check if any of the urls in systemUrls has a substring match with pathname
|
|
80
|
-
// the systemUrl could have a basePath, i.e. /dashboard/api/auth/callback
|
|
81
|
-
// therefore we check if the systemUrl
|
|
82
|
-
const
|
|
83
|
+
// the systemUrl or incoming path could have a basePath, i.e. /dashboard/api/auth/callback
|
|
84
|
+
// therefore we check if the systemUrl equals the pathname after stripping the basePath prefix
|
|
85
|
+
const strippedPathname = stripBasePathPrefix(pathname, authConfig.basePath);
|
|
86
|
+
const strippedSystemUrls = systemUrls.map((url) => stripBasePathPrefix(url, authConfig.basePath));
|
|
87
|
+
const isSystemUrl = strippedSystemUrls.some((url) => url && pathname && pathname !== "/" && url === strippedPathname);
|
|
83
88
|
logger.debug("→ isSystemUrl check", { pathname, isSystemUrl, systemUrls });
|
|
84
89
|
if (isSystemUrl) {
|
|
85
90
|
logger.debug("→ Skipping auth check - this a URL defined in authConfig", pathname);
|
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,YAAY,EACZ,eAAe,EACf,WAAW,GAGZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC3E,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,CA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CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,qBAAqB;IAExE,MAAM,UAAU,GAAG,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE5C,IAAI,UAAU,EAAE,CAAC;QACf,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,CAAC,CAAC,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 CodeVerifier,\n OAuthTokenTypes,\n UserStorage,\n type CookieConfig,\n type KeySetter,\n} from \"@/shared/lib/types.js\";\nimport { clearTokens, getCookieConfiguration } from \"@/shared/lib/util.js\";\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\nconst 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\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 could have a basePath, i.e. /dashboard/api/auth/callback, whereas the pathname will not\n // therefore we check if the systemUrl includes the pathname\n const isSystemUrl = systemUrls.some((url) => url && url.includes(pathname));\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 expires: new Date(0), // Expire in the past\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 const redirectedResponse = redirectWithBasePath(authConfig, redirectUrl);\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,EAAE,WAAW,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC3E,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,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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 { clearTokens, getCookieConfiguration } from \"@/shared/lib/util.js\";\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\nconst 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 expires: new Date(0), // Expire in the past\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 const redirectedResponse = redirectWithBasePath(authConfig, redirectUrl);\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/shared/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const VERSION = "@civic/auth:0.10.0-beta.
|
|
1
|
+
export declare const VERSION = "@civic/auth:0.10.0-beta.11";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/shared/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAE/C,MAAM,CAAC,MAAM,OAAO,GAAG,4BAA4B,CAAC","sourcesContent":["// This is an auto-generated file. Do not edit.\n\nexport const VERSION = \"@civic/auth:0.10.0-beta.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAE/C,MAAM,CAAC,MAAM,OAAO,GAAG,4BAA4B,CAAC","sourcesContent":["// This is an auto-generated file. Do not edit.\n\nexport const VERSION = \"@civic/auth:0.10.0-beta.11\";\n"]}
|