@clerk/backend 3.2.4-snapshot.v20260331162920 → 3.2.4

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/dist/internal.mjs CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  stripPrivateDataFromObject,
23
23
  unauthenticatedMachineObject,
24
24
  verifyMachineAuthToken
25
- } from "./chunk-KDO3PPKO.mjs";
25
+ } from "./chunk-QR37SKMP.mjs";
26
26
  import "./chunk-YBVFDYDR.mjs";
27
27
  import "./chunk-7KLH7JRZ.mjs";
28
28
  import "./chunk-I4B6KCGC.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,2BAA2B,GAAG,qBAAqB,GAAG,sBAAsB,CAAC;AAE1G;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;CACjB;AAqBD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAcxE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKxD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,uBAAuB,EAAE,WAAW,CAAC,GAAG,OAAO,CAI9G;AAsDD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6JlH"}
1
+ {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,2BAA2B,GAAG,qBAAqB,GAAG,sBAAsB,CAAC;AAE1G;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;CACjB;AAuCD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAcxE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKxD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,uBAAuB,EAAE,WAAW,CAAC,GAAG,OAAO,CAI9G;AAuDD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwKlH"}
package/dist/proxy.js CHANGED
@@ -30,7 +30,7 @@ module.exports = __toCommonJS(proxy_exports);
30
30
  var import_constants = require("@clerk/shared/constants");
31
31
  var import_keys = require("@clerk/shared/keys");
32
32
  var import_constants2 = require("@clerk/shared/constants");
33
- var HOP_BY_HOP_HEADERS = [
33
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
34
34
  "connection",
35
35
  "keep-alive",
36
36
  "proxy-authenticate",
@@ -39,8 +39,17 @@ var HOP_BY_HOP_HEADERS = [
39
39
  "trailer",
40
40
  "transfer-encoding",
41
41
  "upgrade"
42
- ];
43
- var RESPONSE_HEADERS_TO_STRIP = ["content-encoding", "content-length"];
42
+ ]);
43
+ function getDynamicHopByHopHeaders(headers) {
44
+ const connectionValue = headers.get("connection");
45
+ if (!connectionValue) {
46
+ return /* @__PURE__ */ new Set();
47
+ }
48
+ return new Set(
49
+ connectionValue.split(",").map((h) => h.trim().toLowerCase()).filter((h) => h.length > 0)
50
+ );
51
+ }
52
+ var RESPONSE_HEADERS_TO_STRIP = /* @__PURE__ */ new Set(["content-encoding", "content-length"]);
44
53
  function fapiUrlFromPublishableKey(publishableKey) {
45
54
  const frontendApi = (0, import_keys.parsePublishableKey)(publishableKey)?.frontendApi;
46
55
  if (frontendApi?.startsWith("clerk.") && import_constants.LEGACY_DEV_INSTANCE_SUFFIXES.some((suffix) => frontendApi?.endsWith(suffix))) {
@@ -70,7 +79,8 @@ function createErrorResponse(code, message, status) {
70
79
  return new Response(JSON.stringify({ errors: [error] }), {
71
80
  status,
72
81
  headers: {
73
- "Content-Type": "application/json"
82
+ "Content-Type": "application/json",
83
+ "Cache-Control": "no-store"
74
84
  }
75
85
  });
76
86
  }
@@ -133,8 +143,10 @@ async function clerkFrontendApiProxy(request, options) {
133
143
  return createErrorResponse("proxy_request_failed", "Resolved target does not match the expected host", 400);
134
144
  }
135
145
  const headers = new Headers();
146
+ const dynamicHopByHop = getDynamicHopByHopHeaders(request.headers);
136
147
  request.headers.forEach((value, key) => {
137
- if (!HOP_BY_HOP_HEADERS.includes(key.toLowerCase())) {
148
+ const lower = key.toLowerCase();
149
+ if (!HOP_BY_HOP_HEADERS.has(lower) && !dynamicHopByHop.has(lower)) {
138
150
  headers.set(key, value);
139
151
  }
140
152
  });
@@ -154,23 +166,24 @@ async function clerkFrontendApiProxy(request, options) {
154
166
  if (clientIp) {
155
167
  headers.set("X-Forwarded-For", clientIp);
156
168
  }
157
- const hasBody = ["POST", "PUT", "PATCH"].includes(request.method);
169
+ const hasBody = request.body !== null;
158
170
  try {
159
171
  const fetchOptions = {
160
172
  method: request.method,
161
173
  headers,
162
174
  redirect: "manual",
163
- // @ts-expect-error - duplex is required for streaming bodies but not in all TS definitions
164
- duplex: hasBody ? "half" : void 0
175
+ signal: request.signal
165
176
  };
166
- if (hasBody && request.body) {
177
+ if (hasBody) {
178
+ fetchOptions.duplex = "half";
167
179
  fetchOptions.body = request.body;
168
180
  }
169
181
  const response = await fetch(targetUrl.toString(), fetchOptions);
182
+ const responseDynamicHopByHop = getDynamicHopByHopHeaders(response.headers);
170
183
  const responseHeaders = new Headers();
171
184
  response.headers.forEach((value, key) => {
172
185
  const lower = key.toLowerCase();
173
- if (!HOP_BY_HOP_HEADERS.includes(lower) && !RESPONSE_HEADERS_TO_STRIP.includes(lower)) {
186
+ if (!HOP_BY_HOP_HEADERS.has(lower) && !RESPONSE_HEADERS_TO_STRIP.has(lower) && !responseDynamicHopByHop.has(lower)) {
174
187
  if (lower === "set-cookie") {
175
188
  responseHeaders.append(key, value);
176
189
  } else {
package/dist/proxy.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["import {\n DEFAULT_PROXY_PATH,\n LEGACY_DEV_INSTANCE_SUFFIXES,\n LOCAL_ENV_SUFFIXES,\n LOCAL_FAPI_URL,\n PROD_FAPI_URL,\n STAGING_ENV_SUFFIXES,\n STAGING_FAPI_URL,\n} from '@clerk/shared/constants';\nimport { parsePublishableKey } from '@clerk/shared/keys';\n\nexport { DEFAULT_PROXY_PATH } from '@clerk/shared/constants';\n\n/**\n * Options for the Frontend API proxy\n */\nexport interface FrontendApiProxyOptions {\n /**\n * The path prefix for proxy requests. Defaults to `/__clerk`.\n */\n proxyPath?: string;\n /**\n * The Clerk publishable key. Falls back to CLERK_PUBLISHABLE_KEY env var.\n */\n publishableKey?: string;\n /**\n * The Clerk secret key. Falls back to CLERK_SECRET_KEY env var.\n */\n secretKey?: string;\n}\n\n/**\n * Error codes for proxy errors\n */\nexport type ProxyErrorCode = 'proxy_configuration_error' | 'proxy_path_mismatch' | 'proxy_request_failed';\n\n/**\n * Error response structure for proxy errors\n */\nexport interface ProxyError {\n code: ProxyErrorCode;\n message: string;\n}\n\n// Hop-by-hop headers that should not be forwarded\nconst HOP_BY_HOP_HEADERS = [\n 'connection',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n];\n\n// Headers to strip from proxied responses. fetch() auto-decompresses\n// response bodies, so Content-Encoding no longer describes the body\n// and Content-Length reflects the compressed size. We request identity\n// encoding upstream to avoid the double compression pass, but strip\n// these defensively since servers may ignore Accept-Encoding: identity.\nconst RESPONSE_HEADERS_TO_STRIP = ['content-encoding', 'content-length'];\n\n/**\n * Derives the Frontend API URL from a publishable key.\n * @param publishableKey - The Clerk publishable key\n * @returns The Frontend API URL for the environment\n */\nexport function fapiUrlFromPublishableKey(publishableKey: string): string {\n const frontendApi = parsePublishableKey(publishableKey)?.frontendApi;\n\n if (frontendApi?.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return PROD_FAPI_URL;\n }\n\n if (LOCAL_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return LOCAL_FAPI_URL;\n }\n if (STAGING_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return STAGING_FAPI_URL;\n }\n return PROD_FAPI_URL;\n}\n\n/**\n * Removes trailing slashes from a string without using regex\n * to avoid potential ReDoS concerns flagged by security scanners.\n */\nexport function stripTrailingSlashes(str: string): string {\n while (str.endsWith('/')) {\n str = str.slice(0, -1);\n }\n return str;\n}\n\n/**\n * Checks if a request path matches the proxy path.\n * @param request - The incoming request\n * @param options - Proxy options including the proxy path\n * @returns True if the request matches the proxy path\n */\nexport function matchProxyPath(request: Request, options?: Pick<FrontendApiProxyOptions, 'proxyPath'>): boolean {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const url = new URL(request.url);\n return url.pathname === proxyPath || url.pathname.startsWith(proxyPath + '/');\n}\n\n/**\n * Creates a JSON error response\n */\nfunction createErrorResponse(code: ProxyErrorCode, message: string, status: number): Response {\n const error: ProxyError = { code, message };\n return new Response(JSON.stringify({ errors: [error] }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n}\n\n/**\n * Derives the public-facing origin from forwarded headers, falling back to the raw request URL.\n * Behind a reverse proxy, request.url is typically localhost, but the Clerk-Proxy-Url header\n * and Location rewrites must use the origin visible to the browser.\n */\nfunction derivePublicOrigin(request: Request, requestUrl: URL): string {\n const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();\n const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim();\n\n if (forwardedProto && forwardedHost) {\n return `${forwardedProto}://${forwardedHost}`;\n }\n\n return requestUrl.origin;\n}\n\n/**\n * Gets the client IP address from various headers\n */\nfunction getClientIp(request: Request): string | undefined {\n const cfConnectingIp = request.headers.get('cf-connecting-ip');\n if (cfConnectingIp) {\n return cfConnectingIp;\n }\n\n const xRealIp = request.headers.get('x-real-ip');\n if (xRealIp) {\n return xRealIp;\n }\n\n const xForwardedFor = request.headers.get('x-forwarded-for');\n if (xForwardedFor) {\n // Take the first IP in the chain\n return xForwardedFor.split(',')[0]?.trim();\n }\n\n return undefined;\n}\n\n/**\n * Proxies a request to Clerk's Frontend API.\n *\n * This function handles forwarding requests from your application to Clerk's\n * Frontend API, enabling scenarios where direct communication with Clerk's API\n * is blocked or needs to go through your application server.\n *\n * @param request - The incoming request to proxy\n * @param options - Proxy configuration options\n * @returns A Response from Clerk's Frontend API\n *\n * @example\n * ```typescript\n * import { clerkFrontendApiProxy } from '@clerk/backend/proxy';\n *\n * // In a route handler\n * const response = await clerkFrontendApiProxy(request, {\n * proxyPath: '/__clerk',\n * publishableKey: process.env.CLERK_PUBLISHABLE_KEY,\n * secretKey: process.env.CLERK_SECRET_KEY,\n * });\n * ```\n */\nexport async function clerkFrontendApiProxy(request: Request, options?: FrontendApiProxyOptions): Promise<Response> {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const publishableKey =\n options?.publishableKey || (typeof process !== 'undefined' ? process.env?.CLERK_PUBLISHABLE_KEY : undefined);\n const secretKey = options?.secretKey || (typeof process !== 'undefined' ? process.env?.CLERK_SECRET_KEY : undefined);\n\n // Validate configuration\n if (!publishableKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing publishableKey. Provide it in options or set CLERK_PUBLISHABLE_KEY environment variable.',\n 500,\n );\n }\n\n if (!secretKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing secretKey. Provide it in options or set CLERK_SECRET_KEY environment variable.',\n 500,\n );\n }\n\n // Get the request URL and validate path\n const requestUrl = new URL(request.url);\n const pathMatches = requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/');\n if (!pathMatches) {\n return createErrorResponse(\n 'proxy_path_mismatch',\n `Request path \"${requestUrl.pathname}\" does not match proxy path \"${proxyPath}\"`,\n 400,\n );\n }\n\n // Derive the FAPI URL and construct the target URL.\n // Use string concatenation instead of `new URL(path, base)` to avoid\n // protocol-relative resolution (e.g., \"//evil.com\" resolving to a different host).\n const fapiBaseUrl = fapiUrlFromPublishableKey(publishableKey);\n const fapiHost = new URL(fapiBaseUrl).host;\n const targetPath = requestUrl.pathname.slice(proxyPath.length) || '/';\n const targetUrl = new URL(`${fapiBaseUrl}${targetPath}`);\n targetUrl.search = requestUrl.search;\n\n if (targetUrl.host !== fapiHost) {\n return createErrorResponse('proxy_request_failed', 'Resolved target does not match the expected host', 400);\n }\n\n // Build headers for the proxied request\n const headers = new Headers();\n\n // Copy original headers, excluding hop-by-hop headers\n request.headers.forEach((value, key) => {\n if (!HOP_BY_HOP_HEADERS.includes(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n // Set required Clerk proxy headers\n // Use the public origin (from forwarded headers) so the Clerk-Proxy-Url\n // points to the browser-visible host, not localhost behind a reverse proxy.\n const publicOrigin = derivePublicOrigin(request, requestUrl);\n const proxyUrl = `${publicOrigin}${proxyPath}`;\n headers.set('Clerk-Proxy-Url', proxyUrl);\n headers.set('Clerk-Secret-Key', secretKey);\n\n // Set the host header to the FAPI host\n headers.set('Host', fapiHost);\n\n // Request uncompressed responses to avoid a double compression pass.\n // fetch() auto-decompresses, so without this FAPI compresses → fetch\n // decompresses → the serving layer re-compresses for the browser.\n headers.set('Accept-Encoding', 'identity');\n\n // Set X-Forwarded-* headers for proxy awareness\n // Only set these if not already present (preserve values from upstream proxies)\n if (!headers.has('X-Forwarded-Host')) {\n headers.set('X-Forwarded-Host', requestUrl.host);\n }\n if (!headers.has('X-Forwarded-Proto')) {\n headers.set('X-Forwarded-Proto', requestUrl.protocol.replace(':', ''));\n }\n\n // Set X-Forwarded-For to the client IP\n // In multi-proxy scenarios, we prefer authoritative headers (CF-Connecting-IP, X-Real-IP)\n // over the existing X-Forwarded-For chain, as they provide the true client IP\n const clientIp = getClientIp(request);\n if (clientIp) {\n headers.set('X-Forwarded-For', clientIp);\n }\n\n // Determine if request has a body\n const hasBody = ['POST', 'PUT', 'PATCH'].includes(request.method);\n\n try {\n // Make the proxied request\n const fetchOptions: RequestInit = {\n method: request.method,\n headers,\n redirect: 'manual',\n // @ts-expect-error - duplex is required for streaming bodies but not in all TS definitions\n duplex: hasBody ? 'half' : undefined,\n };\n\n // Only include body for methods that support it\n if (hasBody && request.body) {\n fetchOptions.body = request.body;\n }\n\n const response = await fetch(targetUrl.toString(), fetchOptions);\n\n // Build response headers, excluding hop-by-hop and encoding headers\n const responseHeaders = new Headers();\n response.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (!HOP_BY_HOP_HEADERS.includes(lower) && !RESPONSE_HEADERS_TO_STRIP.includes(lower)) {\n if (lower === 'set-cookie') {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n });\n\n // Rewrite Location header for redirects to go through the proxy\n const locationHeader = response.headers.get('location');\n if (locationHeader) {\n try {\n const locationUrl = new URL(locationHeader, fapiBaseUrl);\n // Check if the redirect points to the FAPI host\n if (locationUrl.host === fapiHost) {\n // Rewrite to go through the proxy\n const rewrittenLocation = `${proxyUrl}${locationUrl.pathname}${locationUrl.search}${locationUrl.hash}`;\n responseHeaders.set('Location', rewrittenLocation);\n }\n } catch {\n // If URL parsing fails, leave the Location header as-is (could be a relative URL)\n }\n }\n\n const proxyResponse = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n\n // Some runtimes may re-add Content-Length when constructing the Response.\n // Delete explicitly since fetch() decoded the body and the original values\n // no longer reflect the actual content.\n for (const header of RESPONSE_HEADERS_TO_STRIP) {\n proxyResponse.headers.delete(header);\n }\n\n return proxyResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return createErrorResponse('proxy_request_failed', `Failed to proxy request to Clerk FAPI: ${message}`, 502);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAQO;AACP,kBAAoC;AAEpC,IAAAA,oBAAmC;AAkCnC,IAAM,qBAAqB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOA,IAAM,4BAA4B,CAAC,oBAAoB,gBAAgB;AAOhE,SAAS,0BAA0B,gBAAgC;AACxE,QAAM,kBAAc,iCAAoB,cAAc,GAAG;AAEzD,M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KAAK,KAAK,CAAC,0BAA0B,SAAS,KAAK,GAAG;AACrF,YAAI,UAAU,cAAc;AAC1B,0BAAgB,OAAO,KAAK,KAAK;AAAA,QACnC,OAAO;AACL,0BAAgB,IAAI,KAAK,KAAK;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC;AAGD,UAAM,iBAAiB,SAAS,QAAQ,IAAI,UAAU;AACtD,QAAI,gBAAgB;AAClB,UAAI;AACF,cAAM,cAAc,IAAI,IAAI,gBAAgB,WAAW;AAEvD,YAAI,YAAY,SAAS,UAAU;AAEjC,gBAAM,oBAAoB,GAAG,QAAQ,GAAG,YAAY,QAAQ,GAAG,YAAY,MAAM,GAAG,YAAY,IAAI;AACpG,0BAAgB,IAAI,YAAY,iBAAiB;AAAA,QACnD;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,UAAM,gBAAgB,IAAI,SAAS,SAAS,MAAM;AAAA,MAChD,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS;AAAA,IACX,CAAC;AAKD,eAAW,UAAU,2BAA2B;AAC9C,oBAAc,QAAQ,OAAO,MAAM;AAAA,IACrC;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,WAAO,oBAAoB,wBAAwB,0CAA0C,OAAO,IAAI,GAAG;AAAA,EAC7G;AACF;","names":["import_constants"]}
1
+ {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["import {\n DEFAULT_PROXY_PATH,\n LEGACY_DEV_INSTANCE_SUFFIXES,\n LOCAL_ENV_SUFFIXES,\n LOCAL_FAPI_URL,\n PROD_FAPI_URL,\n STAGING_ENV_SUFFIXES,\n STAGING_FAPI_URL,\n} from '@clerk/shared/constants';\nimport { parsePublishableKey } from '@clerk/shared/keys';\n\nexport { DEFAULT_PROXY_PATH } from '@clerk/shared/constants';\n\n/**\n * Options for the Frontend API proxy\n */\nexport interface FrontendApiProxyOptions {\n /**\n * The path prefix for proxy requests. Defaults to `/__clerk`.\n */\n proxyPath?: string;\n /**\n * The Clerk publishable key. Falls back to CLERK_PUBLISHABLE_KEY env var.\n */\n publishableKey?: string;\n /**\n * The Clerk secret key. Falls back to CLERK_SECRET_KEY env var.\n */\n secretKey?: string;\n}\n\n/**\n * Error codes for proxy errors\n */\nexport type ProxyErrorCode = 'proxy_configuration_error' | 'proxy_path_mismatch' | 'proxy_request_failed';\n\n/**\n * Error response structure for proxy errors\n */\nexport interface ProxyError {\n code: ProxyErrorCode;\n message: string;\n}\n\n// Hop-by-hop headers that should not be forwarded\nconst HOP_BY_HOP_HEADERS = new Set([\n 'connection',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n]);\n\n/**\n * Parses the Connection header to extract dynamically-nominated hop-by-hop\n * header names (RFC 7230 Section 6.1). These headers are specific to the\n * current connection and must not be forwarded by proxies.\n */\nfunction getDynamicHopByHopHeaders(headers: Headers): Set<string> {\n const connectionValue = headers.get('connection');\n if (!connectionValue) {\n return new Set();\n }\n return new Set(\n connectionValue\n .split(',')\n .map(h => h.trim().toLowerCase())\n .filter(h => h.length > 0),\n );\n}\n\n// Headers to strip from proxied responses. fetch() auto-decompresses\n// response bodies, so Content-Encoding no longer describes the body\n// and Content-Length reflects the compressed size. We request identity\n// encoding upstream to avoid the double compression pass, but strip\n// these defensively since servers may ignore Accept-Encoding: identity.\nconst RESPONSE_HEADERS_TO_STRIP = new Set(['content-encoding', 'content-length']);\n\n/**\n * Derives the Frontend API URL from a publishable key.\n * @param publishableKey - The Clerk publishable key\n * @returns The Frontend API URL for the environment\n */\nexport function fapiUrlFromPublishableKey(publishableKey: string): string {\n const frontendApi = parsePublishableKey(publishableKey)?.frontendApi;\n\n if (frontendApi?.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return PROD_FAPI_URL;\n }\n\n if (LOCAL_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return LOCAL_FAPI_URL;\n }\n if (STAGING_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return STAGING_FAPI_URL;\n }\n return PROD_FAPI_URL;\n}\n\n/**\n * Removes trailing slashes from a string without using regex\n * to avoid potential ReDoS concerns flagged by security scanners.\n */\nexport function stripTrailingSlashes(str: string): string {\n while (str.endsWith('/')) {\n str = str.slice(0, -1);\n }\n return str;\n}\n\n/**\n * Checks if a request path matches the proxy path.\n * @param request - The incoming request\n * @param options - Proxy options including the proxy path\n * @returns True if the request matches the proxy path\n */\nexport function matchProxyPath(request: Request, options?: Pick<FrontendApiProxyOptions, 'proxyPath'>): boolean {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const url = new URL(request.url);\n return url.pathname === proxyPath || url.pathname.startsWith(proxyPath + '/');\n}\n\n/**\n * Creates a JSON error response\n */\nfunction createErrorResponse(code: ProxyErrorCode, message: string, status: number): Response {\n const error: ProxyError = { code, message };\n return new Response(JSON.stringify({ errors: [error] }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n },\n });\n}\n\n/**\n * Derives the public-facing origin from forwarded headers, falling back to the raw request URL.\n * Behind a reverse proxy, request.url is typically localhost, but the Clerk-Proxy-Url header\n * and Location rewrites must use the origin visible to the browser.\n */\nfunction derivePublicOrigin(request: Request, requestUrl: URL): string {\n const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();\n const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim();\n\n if (forwardedProto && forwardedHost) {\n return `${forwardedProto}://${forwardedHost}`;\n }\n\n return requestUrl.origin;\n}\n\n/**\n * Gets the client IP address from various headers\n */\nfunction getClientIp(request: Request): string | undefined {\n const cfConnectingIp = request.headers.get('cf-connecting-ip');\n if (cfConnectingIp) {\n return cfConnectingIp;\n }\n\n const xRealIp = request.headers.get('x-real-ip');\n if (xRealIp) {\n return xRealIp;\n }\n\n const xForwardedFor = request.headers.get('x-forwarded-for');\n if (xForwardedFor) {\n // Take the first IP in the chain\n return xForwardedFor.split(',')[0]?.trim();\n }\n\n return undefined;\n}\n\n/**\n * Proxies a request to Clerk's Frontend API.\n *\n * This function handles forwarding requests from your application to Clerk's\n * Frontend API, enabling scenarios where direct communication with Clerk's API\n * is blocked or needs to go through your application server.\n *\n * @param request - The incoming request to proxy\n * @param options - Proxy configuration options\n * @returns A Response from Clerk's Frontend API\n *\n * @example\n * ```typescript\n * import { clerkFrontendApiProxy } from '@clerk/backend/proxy';\n *\n * // In a route handler\n * const response = await clerkFrontendApiProxy(request, {\n * proxyPath: '/__clerk',\n * publishableKey: process.env.CLERK_PUBLISHABLE_KEY,\n * secretKey: process.env.CLERK_SECRET_KEY,\n * });\n * ```\n */\nexport async function clerkFrontendApiProxy(request: Request, options?: FrontendApiProxyOptions): Promise<Response> {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const publishableKey =\n options?.publishableKey || (typeof process !== 'undefined' ? process.env?.CLERK_PUBLISHABLE_KEY : undefined);\n const secretKey = options?.secretKey || (typeof process !== 'undefined' ? process.env?.CLERK_SECRET_KEY : undefined);\n\n // Validate configuration\n if (!publishableKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing publishableKey. Provide it in options or set CLERK_PUBLISHABLE_KEY environment variable.',\n 500,\n );\n }\n\n if (!secretKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing secretKey. Provide it in options or set CLERK_SECRET_KEY environment variable.',\n 500,\n );\n }\n\n // Get the request URL and validate path\n const requestUrl = new URL(request.url);\n const pathMatches = requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/');\n if (!pathMatches) {\n return createErrorResponse(\n 'proxy_path_mismatch',\n `Request path \"${requestUrl.pathname}\" does not match proxy path \"${proxyPath}\"`,\n 400,\n );\n }\n\n // Derive the FAPI URL and construct the target URL.\n // Use string concatenation instead of `new URL(path, base)` to avoid\n // protocol-relative resolution (e.g., \"//evil.com\" resolving to a different host).\n const fapiBaseUrl = fapiUrlFromPublishableKey(publishableKey);\n const fapiHost = new URL(fapiBaseUrl).host;\n const targetPath = requestUrl.pathname.slice(proxyPath.length) || '/';\n const targetUrl = new URL(`${fapiBaseUrl}${targetPath}`);\n targetUrl.search = requestUrl.search;\n\n if (targetUrl.host !== fapiHost) {\n return createErrorResponse('proxy_request_failed', 'Resolved target does not match the expected host', 400);\n }\n\n // Build headers for the proxied request\n const headers = new Headers();\n\n // Copy original headers, excluding hop-by-hop headers and any\n // dynamically-nominated hop-by-hop headers listed in the Connection header (RFC 7230 Section 6.1).\n const dynamicHopByHop = getDynamicHopByHopHeaders(request.headers);\n request.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (!HOP_BY_HOP_HEADERS.has(lower) && !dynamicHopByHop.has(lower)) {\n headers.set(key, value);\n }\n });\n\n // Set required Clerk proxy headers\n // Use the public origin (from forwarded headers) so the Clerk-Proxy-Url\n // points to the browser-visible host, not localhost behind a reverse proxy.\n const publicOrigin = derivePublicOrigin(request, requestUrl);\n const proxyUrl = `${publicOrigin}${proxyPath}`;\n headers.set('Clerk-Proxy-Url', proxyUrl);\n headers.set('Clerk-Secret-Key', secretKey);\n\n // Set the host header to the FAPI host\n headers.set('Host', fapiHost);\n\n // Request uncompressed responses to avoid a double compression pass.\n // fetch() auto-decompresses, so without this FAPI compresses → fetch\n // decompresses → the serving layer re-compresses for the browser.\n headers.set('Accept-Encoding', 'identity');\n\n // Set X-Forwarded-* headers for proxy awareness\n // Only set these if not already present (preserve values from upstream proxies)\n if (!headers.has('X-Forwarded-Host')) {\n headers.set('X-Forwarded-Host', requestUrl.host);\n }\n if (!headers.has('X-Forwarded-Proto')) {\n headers.set('X-Forwarded-Proto', requestUrl.protocol.replace(':', ''));\n }\n\n // Set X-Forwarded-For to the client IP\n // In multi-proxy scenarios, we prefer authoritative headers (CF-Connecting-IP, X-Real-IP)\n // over the existing X-Forwarded-For chain, as they provide the true client IP\n const clientIp = getClientIp(request);\n if (clientIp) {\n headers.set('X-Forwarded-For', clientIp);\n }\n\n // Determine if request has a body (handles DELETE-with-body and any other method)\n const hasBody = request.body !== null;\n\n try {\n // Make the proxied request\n // TODO: Consider adding AbortSignal.timeout(30_000) via AbortSignal.any()\n const fetchOptions: RequestInit = {\n method: request.method,\n headers,\n redirect: 'manual',\n signal: request.signal,\n };\n\n // Only set duplex when body is present (required for streaming bodies)\n if (hasBody) {\n // @ts-expect-error - duplex is required for streaming bodies, but not present on the RequestInit type from undici\n fetchOptions.duplex = 'half';\n fetchOptions.body = request.body;\n }\n\n const response = await fetch(targetUrl.toString(), fetchOptions);\n\n // Build response headers, excluding hop-by-hop and encoding headers.\n // Also strip dynamically-nominated hop-by-hop headers from the response Connection header.\n const responseDynamicHopByHop = getDynamicHopByHopHeaders(response.headers);\n const responseHeaders = new Headers();\n response.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (\n !HOP_BY_HOP_HEADERS.has(lower) &&\n !RESPONSE_HEADERS_TO_STRIP.has(lower) &&\n !responseDynamicHopByHop.has(lower)\n ) {\n if (lower === 'set-cookie') {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n });\n\n // Rewrite Location header for redirects to go through the proxy\n const locationHeader = response.headers.get('location');\n if (locationHeader) {\n try {\n const locationUrl = new URL(locationHeader, fapiBaseUrl);\n // Check if the redirect points to the FAPI host\n if (locationUrl.host === fapiHost) {\n // Rewrite to go through the proxy\n const rewrittenLocation = `${proxyUrl}${locationUrl.pathname}${locationUrl.search}${locationUrl.hash}`;\n responseHeaders.set('Location', rewrittenLocation);\n }\n } catch {\n // If URL parsing fails, leave the Location header as-is (could be a relative URL)\n }\n }\n\n const proxyResponse = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n\n // Some runtimes may re-add Content-Length when constructing the Response.\n // Delete explicitly since fetch() decoded the body and the original values\n // no longer reflect the actual content.\n for (const header of RESPONSE_HEADERS_TO_STRIP) {\n proxyResponse.headers.delete(header);\n }\n\n return proxyResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return createErrorResponse('proxy_request_failed', `Failed to proxy request to Clerk FAPI: ${message}`, 502);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAQO;AACP,kBAAoC;AAEpC,IAAAA,oBAAmC;AAkCnC,IAAM,qBAAqB,oBAAI,IAAI;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,SAAS,0BAA0B,SAA+B;AAChE,QAAM,kBAAkB,QAAQ,IAAI,YAAY;AAChD,MAAI,CAAC,iBAAiB;AACpB,WAAO,oBAAI,IAAI;AAAA,EACjB;AACA,SAAO,IAAI;AAAA,IACT,gBACG,MAAM,GAAG,EACT,IAAI,OAAK,EAAE,KAAK,EAAE,YAAY,CAAC,EAC/B,OAAO,OAAK,EAAE,SAAS,CAAC;AAAA,EAC7B;AACF;AAOA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,oBAAoB,gBAAgB,CAAC;AAOzE,SAAS,0BAA0B,gBAAgC;AACxE,QAAM,kBAAc,iCAAoB,cAAc,GAAG;AAEzD,MAAI,aAAa,WAAW,QAAQ,KAAK,8CAA6B,KAAK,YAAU,aAAa,SAAS,MAAM,CAAC,GAAG;AACnH,WAAO;AAAA,EACT;AAEA,MAAI,oCAAmB,KAAK,YAAU,aAAa,SAAS,MAAM,CAAC,GAAG;AACpE,WAAO;AAAA,EACT;AACA,MAAI,sCAAqB,KAAK,YAAU,aAAa,SAAS,MAAM,CAAC,GAAG;AACtE,WAAO;AAAA,EACT;AACA,SAAO;AACT;A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AAK;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC;AAGD,UAAM,iBAAiB,SAAS,QAAQ,IAAI,UAAU;AACtD,QAAI,gBAAgB;AAClB,UAAI;AACF,cAAM,cAAc,IAAI,IAAI,gBAAgB,WAAW;AAEvD,YAAI,YAAY,SAAS,UAAU;AAEjC,gBAAM,oBAAoB,GAAG,QAAQ,GAAG,YAAY,QAAQ,GAAG,YAAY,MAAM,GAAG,YAAY,IAAI;AACpG,0BAAgB,IAAI,YAAY,iBAAiB;AAAA,QACnD;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,UAAM,gBAAgB,IAAI,SAAS,SAAS,MAAM;AAAA,MAChD,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS;AAAA,IACX,CAAC;AAKD,eAAW,UAAU,2BAA2B;AAC9C,oBAAc,QAAQ,OAAO,MAAM;AAAA,IACrC;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,WAAO,oBAAoB,wBAAwB,0CAA0C,OAAO,IAAI,GAAG;AAAA,EAC7G;AACF;","names":["import_constants"]}
package/dist/proxy.mjs CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  } from "@clerk/shared/constants";
13
13
  import { parsePublishableKey } from "@clerk/shared/keys";
14
14
  import { DEFAULT_PROXY_PATH as DEFAULT_PROXY_PATH2 } from "@clerk/shared/constants";
15
- var HOP_BY_HOP_HEADERS = [
15
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
16
16
  "connection",
17
17
  "keep-alive",
18
18
  "proxy-authenticate",
@@ -21,8 +21,17 @@ var HOP_BY_HOP_HEADERS = [
21
21
  "trailer",
22
22
  "transfer-encoding",
23
23
  "upgrade"
24
- ];
25
- var RESPONSE_HEADERS_TO_STRIP = ["content-encoding", "content-length"];
24
+ ]);
25
+ function getDynamicHopByHopHeaders(headers) {
26
+ const connectionValue = headers.get("connection");
27
+ if (!connectionValue) {
28
+ return /* @__PURE__ */ new Set();
29
+ }
30
+ return new Set(
31
+ connectionValue.split(",").map((h) => h.trim().toLowerCase()).filter((h) => h.length > 0)
32
+ );
33
+ }
34
+ var RESPONSE_HEADERS_TO_STRIP = /* @__PURE__ */ new Set(["content-encoding", "content-length"]);
26
35
  function fapiUrlFromPublishableKey(publishableKey) {
27
36
  const frontendApi = parsePublishableKey(publishableKey)?.frontendApi;
28
37
  if (frontendApi?.startsWith("clerk.") && LEGACY_DEV_INSTANCE_SUFFIXES.some((suffix) => frontendApi?.endsWith(suffix))) {
@@ -52,7 +61,8 @@ function createErrorResponse(code, message, status) {
52
61
  return new Response(JSON.stringify({ errors: [error] }), {
53
62
  status,
54
63
  headers: {
55
- "Content-Type": "application/json"
64
+ "Content-Type": "application/json",
65
+ "Cache-Control": "no-store"
56
66
  }
57
67
  });
58
68
  }
@@ -115,8 +125,10 @@ async function clerkFrontendApiProxy(request, options) {
115
125
  return createErrorResponse("proxy_request_failed", "Resolved target does not match the expected host", 400);
116
126
  }
117
127
  const headers = new Headers();
128
+ const dynamicHopByHop = getDynamicHopByHopHeaders(request.headers);
118
129
  request.headers.forEach((value, key) => {
119
- if (!HOP_BY_HOP_HEADERS.includes(key.toLowerCase())) {
130
+ const lower = key.toLowerCase();
131
+ if (!HOP_BY_HOP_HEADERS.has(lower) && !dynamicHopByHop.has(lower)) {
120
132
  headers.set(key, value);
121
133
  }
122
134
  });
@@ -136,23 +148,24 @@ async function clerkFrontendApiProxy(request, options) {
136
148
  if (clientIp) {
137
149
  headers.set("X-Forwarded-For", clientIp);
138
150
  }
139
- const hasBody = ["POST", "PUT", "PATCH"].includes(request.method);
151
+ const hasBody = request.body !== null;
140
152
  try {
141
153
  const fetchOptions = {
142
154
  method: request.method,
143
155
  headers,
144
156
  redirect: "manual",
145
- // @ts-expect-error - duplex is required for streaming bodies but not in all TS definitions
146
- duplex: hasBody ? "half" : void 0
157
+ signal: request.signal
147
158
  };
148
- if (hasBody && request.body) {
159
+ if (hasBody) {
160
+ fetchOptions.duplex = "half";
149
161
  fetchOptions.body = request.body;
150
162
  }
151
163
  const response = await fetch(targetUrl.toString(), fetchOptions);
164
+ const responseDynamicHopByHop = getDynamicHopByHopHeaders(response.headers);
152
165
  const responseHeaders = new Headers();
153
166
  response.headers.forEach((value, key) => {
154
167
  const lower = key.toLowerCase();
155
- if (!HOP_BY_HOP_HEADERS.includes(lower) && !RESPONSE_HEADERS_TO_STRIP.includes(lower)) {
168
+ if (!HOP_BY_HOP_HEADERS.has(lower) && !RESPONSE_HEADERS_TO_STRIP.has(lower) && !responseDynamicHopByHop.has(lower)) {
156
169
  if (lower === "set-cookie") {
157
170
  responseHeaders.append(key, value);
158
171
  } else {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["import {\n DEFAULT_PROXY_PATH,\n LEGACY_DEV_INSTANCE_SUFFIXES,\n LOCAL_ENV_SUFFIXES,\n LOCAL_FAPI_URL,\n PROD_FAPI_URL,\n STAGING_ENV_SUFFIXES,\n STAGING_FAPI_URL,\n} from '@clerk/shared/constants';\nimport { parsePublishableKey } from '@clerk/shared/keys';\n\nexport { DEFAULT_PROXY_PATH } from '@clerk/shared/constants';\n\n/**\n * Options for the Frontend API proxy\n */\nexport interface FrontendApiProxyOptions {\n /**\n * The path prefix for proxy requests. Defaults to `/__clerk`.\n */\n proxyPath?: string;\n /**\n * The Clerk publishable key. Falls back to CLERK_PUBLISHABLE_KEY env var.\n */\n publishableKey?: string;\n /**\n * The Clerk secret key. Falls back to CLERK_SECRET_KEY env var.\n */\n secretKey?: string;\n}\n\n/**\n * Error codes for proxy errors\n */\nexport type ProxyErrorCode = 'proxy_configuration_error' | 'proxy_path_mismatch' | 'proxy_request_failed';\n\n/**\n * Error response structure for proxy errors\n */\nexport interface ProxyError {\n code: ProxyErrorCode;\n message: string;\n}\n\n// Hop-by-hop headers that should not be forwarded\nconst HOP_BY_HOP_HEADERS = [\n 'connection',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n];\n\n// Headers to strip from proxied responses. fetch() auto-decompresses\n// response bodies, so Content-Encoding no longer describes the body\n// and Content-Length reflects the compressed size. We request identity\n// encoding upstream to avoid the double compression pass, but strip\n// these defensively since servers may ignore Accept-Encoding: identity.\nconst RESPONSE_HEADERS_TO_STRIP = ['content-encoding', 'content-length'];\n\n/**\n * Derives the Frontend API URL from a publishable key.\n * @param publishableKey - The Clerk publishable key\n * @returns The Frontend API URL for the environment\n */\nexport function fapiUrlFromPublishableKey(publishableKey: string): string {\n const frontendApi = parsePublishableKey(publishableKey)?.frontendApi;\n\n if (frontendApi?.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return PROD_FAPI_URL;\n }\n\n if (LOCAL_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return LOCAL_FAPI_URL;\n }\n if (STAGING_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return STAGING_FAPI_URL;\n }\n return PROD_FAPI_URL;\n}\n\n/**\n * Removes trailing slashes from a string without using regex\n * to avoid potential ReDoS concerns flagged by security scanners.\n */\nexport function stripTrailingSlashes(str: string): string {\n while (str.endsWith('/')) {\n str = str.slice(0, -1);\n }\n return str;\n}\n\n/**\n * Checks if a request path matches the proxy path.\n * @param request - The incoming request\n * @param options - Proxy options including the proxy path\n * @returns True if the request matches the proxy path\n */\nexport function matchProxyPath(request: Request, options?: Pick<FrontendApiProxyOptions, 'proxyPath'>): boolean {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const url = new URL(request.url);\n return url.pathname === proxyPath || url.pathname.startsWith(proxyPath + '/');\n}\n\n/**\n * Creates a JSON error response\n */\nfunction createErrorResponse(code: ProxyErrorCode, message: string, status: number): Response {\n const error: ProxyError = { code, message };\n return new Response(JSON.stringify({ errors: [error] }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n}\n\n/**\n * Derives the public-facing origin from forwarded headers, falling back to the raw request URL.\n * Behind a reverse proxy, request.url is typically localhost, but the Clerk-Proxy-Url header\n * and Location rewrites must use the origin visible to the browser.\n */\nfunction derivePublicOrigin(request: Request, requestUrl: URL): string {\n const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();\n const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim();\n\n if (forwardedProto && forwardedHost) {\n return `${forwardedProto}://${forwardedHost}`;\n }\n\n return requestUrl.origin;\n}\n\n/**\n * Gets the client IP address from various headers\n */\nfunction getClientIp(request: Request): string | undefined {\n const cfConnectingIp = request.headers.get('cf-connecting-ip');\n if (cfConnectingIp) {\n return cfConnectingIp;\n }\n\n const xRealIp = request.headers.get('x-real-ip');\n if (xRealIp) {\n return xRealIp;\n }\n\n const xForwardedFor = request.headers.get('x-forwarded-for');\n if (xForwardedFor) {\n // Take the first IP in the chain\n return xForwardedFor.split(',')[0]?.trim();\n }\n\n return undefined;\n}\n\n/**\n * Proxies a request to Clerk's Frontend API.\n *\n * This function handles forwarding requests from your application to Clerk's\n * Frontend API, enabling scenarios where direct communication with Clerk's API\n * is blocked or needs to go through your application server.\n *\n * @param request - The incoming request to proxy\n * @param options - Proxy configuration options\n * @returns A Response from Clerk's Frontend API\n *\n * @example\n * ```typescript\n * import { clerkFrontendApiProxy } from '@clerk/backend/proxy';\n *\n * // In a route handler\n * const response = await clerkFrontendApiProxy(request, {\n * proxyPath: '/__clerk',\n * publishableKey: process.env.CLERK_PUBLISHABLE_KEY,\n * secretKey: process.env.CLERK_SECRET_KEY,\n * });\n * ```\n */\nexport async function clerkFrontendApiProxy(request: Request, options?: FrontendApiProxyOptions): Promise<Response> {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const publishableKey =\n options?.publishableKey || (typeof process !== 'undefined' ? process.env?.CLERK_PUBLISHABLE_KEY : undefined);\n const secretKey = options?.secretKey || (typeof process !== 'undefined' ? process.env?.CLERK_SECRET_KEY : undefined);\n\n // Validate configuration\n if (!publishableKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing publishableKey. Provide it in options or set CLERK_PUBLISHABLE_KEY environment variable.',\n 500,\n );\n }\n\n if (!secretKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing secretKey. Provide it in options or set CLERK_SECRET_KEY environment variable.',\n 500,\n );\n }\n\n // Get the request URL and validate path\n const requestUrl = new URL(request.url);\n const pathMatches = requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/');\n if (!pathMatches) {\n return createErrorResponse(\n 'proxy_path_mismatch',\n `Request path \"${requestUrl.pathname}\" does not match proxy path \"${proxyPath}\"`,\n 400,\n );\n }\n\n // Derive the FAPI URL and construct the target URL.\n // Use string concatenation instead of `new URL(path, base)` to avoid\n // protocol-relative resolution (e.g., \"//evil.com\" resolving to a different host).\n const fapiBaseUrl = fapiUrlFromPublishableKey(publishableKey);\n const fapiHost = new URL(fapiBaseUrl).host;\n const targetPath = requestUrl.pathname.slice(proxyPath.length) || '/';\n const targetUrl = new URL(`${fapiBaseUrl}${targetPath}`);\n targetUrl.search = requestUrl.search;\n\n if (targetUrl.host !== fapiHost) {\n return createErrorResponse('proxy_request_failed', 'Resolved target does not match the expected host', 400);\n }\n\n // Build headers for the proxied request\n const headers = new Headers();\n\n // Copy original headers, excluding hop-by-hop headers\n request.headers.forEach((value, key) => {\n if (!HOP_BY_HOP_HEADERS.includes(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n // Set required Clerk proxy headers\n // Use the public origin (from forwarded headers) so the Clerk-Proxy-Url\n // points to the browser-visible host, not localhost behind a reverse proxy.\n const publicOrigin = derivePublicOrigin(request, requestUrl);\n const proxyUrl = `${publicOrigin}${proxyPath}`;\n headers.set('Clerk-Proxy-Url', proxyUrl);\n headers.set('Clerk-Secret-Key', secretKey);\n\n // Set the host header to the FAPI host\n headers.set('Host', fapiHost);\n\n // Request uncompressed responses to avoid a double compression pass.\n // fetch() auto-decompresses, so without this FAPI compresses → fetch\n // decompresses → the serving layer re-compresses for the browser.\n headers.set('Accept-Encoding', 'identity');\n\n // Set X-Forwarded-* headers for proxy awareness\n // Only set these if not already present (preserve values from upstream proxies)\n if (!headers.has('X-Forwarded-Host')) {\n headers.set('X-Forwarded-Host', requestUrl.host);\n }\n if (!headers.has('X-Forwarded-Proto')) {\n headers.set('X-Forwarded-Proto', requestUrl.protocol.replace(':', ''));\n }\n\n // Set X-Forwarded-For to the client IP\n // In multi-proxy scenarios, we prefer authoritative headers (CF-Connecting-IP, X-Real-IP)\n // over the existing X-Forwarded-For chain, as they provide the true client IP\n const clientIp = getClientIp(request);\n if (clientIp) {\n headers.set('X-Forwarded-For', clientIp);\n }\n\n // Determine if request has a body\n const hasBody = ['POST', 'PUT', 'PATCH'].includes(request.method);\n\n try {\n // Make the proxied request\n const fetchOptions: RequestInit = {\n method: request.method,\n headers,\n redirect: 'manual',\n // @ts-expect-error - duplex is required for streaming bodies but not in all TS definitions\n duplex: hasBody ? 'half' : undefined,\n };\n\n // Only include body for methods that support it\n if (hasBody && request.body) {\n fetchOptions.body = request.body;\n }\n\n const response = await fetch(targetUrl.toString(), fetchOptions);\n\n // Build response headers, excluding hop-by-hop and encoding headers\n const responseHeaders = new Headers();\n response.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (!HOP_BY_HOP_HEADERS.includes(lower) && !RESPONSE_HEADERS_TO_STRIP.includes(lower)) {\n if (lower === 'set-cookie') {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n });\n\n // Rewrite Location header for redirects to go through the proxy\n const locationHeader = response.headers.get('location');\n if (locationHeader) {\n try {\n const locationUrl = new URL(locationHeader, fapiBaseUrl);\n // Check if the redirect points to the FAPI host\n if (locationUrl.host === fapiHost) {\n // Rewrite to go through the proxy\n const rewrittenLocation = `${proxyUrl}${locationUrl.pathname}${locationUrl.search}${locationUrl.hash}`;\n responseHeaders.set('Location', rewrittenLocation);\n }\n } catch {\n // If URL parsing fails, leave the Location header as-is (could be a relative URL)\n }\n }\n\n const proxyResponse = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n\n // Some runtimes may re-add Content-Length when constructing the Response.\n // Delete explicitly since fetch() decoded the body and the original values\n // no longer reflect the actual content.\n for (const header of RESPONSE_HEADERS_TO_STRIP) {\n proxyResponse.headers.delete(header);\n }\n\n return proxyResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return createErrorResponse('proxy_request_failed', `Failed to proxy request to Clerk FAPI: ${message}`, 502);\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AAEpC,SAAS,sBAAAA,2BAA0B;AAkCnC,IAAM,qBAAqB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOA,IAAM,4BAA4B,CAAC,oBAAoB,gBAAgB;AAOhE,SAAS,0BAA0B,gBAAgC;AACxE,QAAM,cAAc,oBAAoB,cAAc,GAAG;AAEzD,MAAI,aAAa,WAAW,QAAQ,KAAK,6BAA6B,KAAK,YAAU,aAAa,SAAS,MAAM,CAAC,GAAG;AACnH,WAAO;AAAA,EACT;AAEA,MAAI,mBAAmB,KAAK,YAAU,aAAa,SAAS,MAAM,CAAC,GAAG;AACpE,WAAO;AAAA,EACT;AACA,MAAI,qBAAqB,KAAK,YAAU,aAAa,SAAS,MAAM,CAAC,GAAG;AACtE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAMO,SAAS,qBAAqB,KAAqB;AACxD,SAAO,IAAI,SAAS,GAAG,GAAG;AACx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M,oBAAoB,GAAG,QAAQ,GAAG,YAAY,QAAQ,GAAG,YAAY,MAAM,GAAG,YAAY,IAAI;AACpG,0BAAgB,IAAI,YAAY,iBAAiB;AAAA,QACnD;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,UAAM,gBAAgB,IAAI,SAAS,SAAS,MAAM;AAAA,MAChD,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS;AAAA,IACX,CAAC;AAKD,eAAW,UAAU,2BAA2B;AAC9C,oBAAc,QAAQ,OAAO,MAAM;AAAA,IACrC;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,WAAO,oBAAoB,wBAAwB,0CAA0C,OAAO,IAAI,GAAG;AAAA,EAC7G;AACF;","names":["DEFAULT_PROXY_PATH"]}
1
+ {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["import {\n DEFAULT_PROXY_PATH,\n LEGACY_DEV_INSTANCE_SUFFIXES,\n LOCAL_ENV_SUFFIXES,\n LOCAL_FAPI_URL,\n PROD_FAPI_URL,\n STAGING_ENV_SUFFIXES,\n STAGING_FAPI_URL,\n} from '@clerk/shared/constants';\nimport { parsePublishableKey } from '@clerk/shared/keys';\n\nexport { DEFAULT_PROXY_PATH } from '@clerk/shared/constants';\n\n/**\n * Options for the Frontend API proxy\n */\nexport interface FrontendApiProxyOptions {\n /**\n * The path prefix for proxy requests. Defaults to `/__clerk`.\n */\n proxyPath?: string;\n /**\n * The Clerk publishable key. Falls back to CLERK_PUBLISHABLE_KEY env var.\n */\n publishableKey?: string;\n /**\n * The Clerk secret key. Falls back to CLERK_SECRET_KEY env var.\n */\n secretKey?: string;\n}\n\n/**\n * Error codes for proxy errors\n */\nexport type ProxyErrorCode = 'proxy_configuration_error' | 'proxy_path_mismatch' | 'proxy_request_failed';\n\n/**\n * Error response structure for proxy errors\n */\nexport interface ProxyError {\n code: ProxyErrorCode;\n message: string;\n}\n\n// Hop-by-hop headers that should not be forwarded\nconst HOP_BY_HOP_HEADERS = new Set([\n 'connection',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n]);\n\n/**\n * Parses the Connection header to extract dynamically-nominated hop-by-hop\n * header names (RFC 7230 Section 6.1). These headers are specific to the\n * current connection and must not be forwarded by proxies.\n */\nfunction getDynamicHopByHopHeaders(headers: Headers): Set<string> {\n const connectionValue = headers.get('connection');\n if (!connectionValue) {\n return new Set();\n }\n return new Set(\n connectionValue\n .split(',')\n .map(h => h.trim().toLowerCase())\n .filter(h => h.length > 0),\n );\n}\n\n// Headers to strip from proxied responses. fetch() auto-decompresses\n// response bodies, so Content-Encoding no longer describes the body\n// and Content-Length reflects the compressed size. We request identity\n// encoding upstream to avoid the double compression pass, but strip\n// these defensively since servers may ignore Accept-Encoding: identity.\nconst RESPONSE_HEADERS_TO_STRIP = new Set(['content-encoding', 'content-length']);\n\n/**\n * Derives the Frontend API URL from a publishable key.\n * @param publishableKey - The Clerk publishable key\n * @returns The Frontend API URL for the environment\n */\nexport function fapiUrlFromPublishableKey(publishableKey: string): string {\n const frontendApi = parsePublishableKey(publishableKey)?.frontendApi;\n\n if (frontendApi?.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return PROD_FAPI_URL;\n }\n\n if (LOCAL_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return LOCAL_FAPI_URL;\n }\n if (STAGING_ENV_SUFFIXES.some(suffix => frontendApi?.endsWith(suffix))) {\n return STAGING_FAPI_URL;\n }\n return PROD_FAPI_URL;\n}\n\n/**\n * Removes trailing slashes from a string without using regex\n * to avoid potential ReDoS concerns flagged by security scanners.\n */\nexport function stripTrailingSlashes(str: string): string {\n while (str.endsWith('/')) {\n str = str.slice(0, -1);\n }\n return str;\n}\n\n/**\n * Checks if a request path matches the proxy path.\n * @param request - The incoming request\n * @param options - Proxy options including the proxy path\n * @returns True if the request matches the proxy path\n */\nexport function matchProxyPath(request: Request, options?: Pick<FrontendApiProxyOptions, 'proxyPath'>): boolean {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const url = new URL(request.url);\n return url.pathname === proxyPath || url.pathname.startsWith(proxyPath + '/');\n}\n\n/**\n * Creates a JSON error response\n */\nfunction createErrorResponse(code: ProxyErrorCode, message: string, status: number): Response {\n const error: ProxyError = { code, message };\n return new Response(JSON.stringify({ errors: [error] }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n },\n });\n}\n\n/**\n * Derives the public-facing origin from forwarded headers, falling back to the raw request URL.\n * Behind a reverse proxy, request.url is typically localhost, but the Clerk-Proxy-Url header\n * and Location rewrites must use the origin visible to the browser.\n */\nfunction derivePublicOrigin(request: Request, requestUrl: URL): string {\n const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();\n const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim();\n\n if (forwardedProto && forwardedHost) {\n return `${forwardedProto}://${forwardedHost}`;\n }\n\n return requestUrl.origin;\n}\n\n/**\n * Gets the client IP address from various headers\n */\nfunction getClientIp(request: Request): string | undefined {\n const cfConnectingIp = request.headers.get('cf-connecting-ip');\n if (cfConnectingIp) {\n return cfConnectingIp;\n }\n\n const xRealIp = request.headers.get('x-real-ip');\n if (xRealIp) {\n return xRealIp;\n }\n\n const xForwardedFor = request.headers.get('x-forwarded-for');\n if (xForwardedFor) {\n // Take the first IP in the chain\n return xForwardedFor.split(',')[0]?.trim();\n }\n\n return undefined;\n}\n\n/**\n * Proxies a request to Clerk's Frontend API.\n *\n * This function handles forwarding requests from your application to Clerk's\n * Frontend API, enabling scenarios where direct communication with Clerk's API\n * is blocked or needs to go through your application server.\n *\n * @param request - The incoming request to proxy\n * @param options - Proxy configuration options\n * @returns A Response from Clerk's Frontend API\n *\n * @example\n * ```typescript\n * import { clerkFrontendApiProxy } from '@clerk/backend/proxy';\n *\n * // In a route handler\n * const response = await clerkFrontendApiProxy(request, {\n * proxyPath: '/__clerk',\n * publishableKey: process.env.CLERK_PUBLISHABLE_KEY,\n * secretKey: process.env.CLERK_SECRET_KEY,\n * });\n * ```\n */\nexport async function clerkFrontendApiProxy(request: Request, options?: FrontendApiProxyOptions): Promise<Response> {\n const proxyPath = stripTrailingSlashes(options?.proxyPath || DEFAULT_PROXY_PATH);\n const publishableKey =\n options?.publishableKey || (typeof process !== 'undefined' ? process.env?.CLERK_PUBLISHABLE_KEY : undefined);\n const secretKey = options?.secretKey || (typeof process !== 'undefined' ? process.env?.CLERK_SECRET_KEY : undefined);\n\n // Validate configuration\n if (!publishableKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing publishableKey. Provide it in options or set CLERK_PUBLISHABLE_KEY environment variable.',\n 500,\n );\n }\n\n if (!secretKey) {\n return createErrorResponse(\n 'proxy_configuration_error',\n 'Missing secretKey. Provide it in options or set CLERK_SECRET_KEY environment variable.',\n 500,\n );\n }\n\n // Get the request URL and validate path\n const requestUrl = new URL(request.url);\n const pathMatches = requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/');\n if (!pathMatches) {\n return createErrorResponse(\n 'proxy_path_mismatch',\n `Request path \"${requestUrl.pathname}\" does not match proxy path \"${proxyPath}\"`,\n 400,\n );\n }\n\n // Derive the FAPI URL and construct the target URL.\n // Use string concatenation instead of `new URL(path, base)` to avoid\n // protocol-relative resolution (e.g., \"//evil.com\" resolving to a different host).\n const fapiBaseUrl = fapiUrlFromPublishableKey(publishableKey);\n const fapiHost = new URL(fapiBaseUrl).host;\n const targetPath = requestUrl.pathname.slice(proxyPath.length) || '/';\n const targetUrl = new URL(`${fapiBaseUrl}${targetPath}`);\n targetUrl.search = requestUrl.search;\n\n if (targetUrl.host !== fapiHost) {\n return createErrorResponse('proxy_request_failed', 'Resolved target does not match the expected host', 400);\n }\n\n // Build headers for the proxied request\n const headers = new Headers();\n\n // Copy original headers, excluding hop-by-hop headers and any\n // dynamically-nominated hop-by-hop headers listed in the Connection header (RFC 7230 Section 6.1).\n const dynamicHopByHop = getDynamicHopByHopHeaders(request.headers);\n request.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (!HOP_BY_HOP_HEADERS.has(lower) && !dynamicHopByHop.has(lower)) {\n headers.set(key, value);\n }\n });\n\n // Set required Clerk proxy headers\n // Use the public origin (from forwarded headers) so the Clerk-Proxy-Url\n // points to the browser-visible host, not localhost behind a reverse proxy.\n const publicOrigin = derivePublicOrigin(request, requestUrl);\n const proxyUrl = `${publicOrigin}${proxyPath}`;\n headers.set('Clerk-Proxy-Url', proxyUrl);\n headers.set('Clerk-Secret-Key', secretKey);\n\n // Set the host header to the FAPI host\n headers.set('Host', fapiHost);\n\n // Request uncompressed responses to avoid a double compression pass.\n // fetch() auto-decompresses, so without this FAPI compresses → fetch\n // decompresses → the serving layer re-compresses for the browser.\n headers.set('Accept-Encoding', 'identity');\n\n // Set X-Forwarded-* headers for proxy awareness\n // Only set these if not already present (preserve values from upstream proxies)\n if (!headers.has('X-Forwarded-Host')) {\n headers.set('X-Forwarded-Host', requestUrl.host);\n }\n if (!headers.has('X-Forwarded-Proto')) {\n headers.set('X-Forwarded-Proto', requestUrl.protocol.replace(':', ''));\n }\n\n // Set X-Forwarded-For to the client IP\n // In multi-proxy scenarios, we prefer authoritative headers (CF-Connecting-IP, X-Real-IP)\n // over the existing X-Forwarded-For chain, as they provide the true client IP\n const clientIp = getClientIp(request);\n if (clientIp) {\n headers.set('X-Forwarded-For', clientIp);\n }\n\n // Determine if request has a body (handles DELETE-with-body and any other method)\n const hasBody = request.body !== null;\n\n try {\n // Make the proxied request\n // TODO: Consider adding AbortSignal.timeout(30_000) via AbortSignal.any()\n const fetchOptions: RequestInit = {\n method: request.method,\n headers,\n redirect: 'manual',\n signal: request.signal,\n };\n\n // Only set duplex when body is present (required for streaming bodies)\n if (hasBody) {\n // @ts-expect-error - duplex is required for streaming bodies, but not present on the RequestInit type from undici\n fetchOptions.duplex = 'half';\n fetchOptions.body = request.body;\n }\n\n const response = await fetch(targetUrl.toString(), fetchOptions);\n\n // Build response headers, excluding hop-by-hop and encoding headers.\n // Also strip dynamically-nominated hop-by-hop headers from the response Connection header.\n const responseDynamicHopByHop = getDynamicHopByHopHeaders(response.headers);\n const responseHeaders = new Headers();\n response.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (\n !HOP_BY_HOP_HEADERS.has(lower) &&\n !RESPONSE_HEADERS_TO_STRIP.has(lower) &&\n !responseDynamicHopByHop.has(lower)\n ) {\n if (lower === 'set-cookie') {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n });\n\n // Rewrite Location header for redirects to go through the proxy\n const locationHeader = response.headers.get('location');\n if (locationHeader) {\n try {\n const locationUrl = new URL(locationHeader, fapiBaseUrl);\n // Check if the redirect points to the FAPI host\n if (locationUrl.host === fapiHost) {\n // Rewrite to go through the proxy\n const rewrittenLocation = `${proxyUrl}${locationUrl.pathname}${locationUrl.search}${locationUrl.hash}`;\n responseHeaders.set('Location', rewrittenLocation);\n }\n } catch {\n // If URL parsing fails, leave the Location header as-is (could be a relative URL)\n }\n }\n\n const proxyResponse = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n\n // Some runtimes may re-add Content-Length when constructing the Response.\n // Delete explicitly since fetch() decoded the body and the original values\n // no longer reflect the actual content.\n for (const header of RESPONSE_HEADERS_TO_STRIP) {\n proxyResponse.headers.delete(header);\n }\n\n return proxyResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n return createErrorResponse('proxy_request_failed', `Failed to proxy request to Clerk FAPI: ${message}`, 502);\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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AA,QACnD;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,UAAM,gBAAgB,IAAI,SAAS,SAAS,MAAM;AAAA,MAChD,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS;AAAA,IACX,CAAC;AAKD,eAAW,UAAU,2BAA2B;AAC9C,oBAAc,QAAQ,OAAO,MAAM;AAAA,IACrC;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,WAAO,oBAAoB,wBAAwB,0CAA0C,OAAO,IAAI,GAAG;AAAA,EAC7G;AACF;","names":["DEFAULT_PROXY_PATH"]}
@@ -2,6 +2,6 @@ export { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';
2
2
  export { getCookieSuffix, getSuffixedCookieName, isDevelopmentFromSecretKey, isProductionFromSecretKey, parsePublishableKey, } from '@clerk/shared/keys';
3
3
  export { retry } from '@clerk/shared/retry';
4
4
  export { addClerkPrefix, getClerkJsMajorVersionOrTag, getScriptUrl } from '@clerk/shared/url';
5
- export declare const errorThrower: import("@clerk/shared/index-C3NHVLOQ").rr;
5
+ export declare const errorThrower: import("@clerk/shared/index-BK_NVS1t").rr;
6
6
  export declare const isDevOrStagingUrl: (url: string | URL) => boolean;
7
7
  //# sourceMappingURL=shared.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerk/backend",
3
- "version": "3.2.4-snapshot.v20260331162920",
3
+ "version": "3.2.4",
4
4
  "description": "Clerk Backend SDK - REST Client for Backend API & JWT verification utilities",
5
5
  "homepage": "https://clerk.com/",
6
6
  "bugs": {
@@ -99,7 +99,7 @@
99
99
  "dependencies": {
100
100
  "standardwebhooks": "^1.0.0",
101
101
  "tslib": "2.8.1",
102
- "@clerk/shared": "4.4.0-snapshot.v20260331162920"
102
+ "@clerk/shared": "^4.4.0"
103
103
  },
104
104
  "devDependencies": {
105
105
  "@edge-runtime/vm": "5.0.0",