@clerk/fastify 3.1.59 → 3.1.60-canary.v20260731161424

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/index.js CHANGED
@@ -48,7 +48,7 @@ const API_URL = process.env.CLERK_API_URL || (0, _clerk_shared_apiUrlFromPublish
48
48
  const JWT_KEY = process.env.CLERK_JWT_KEY || "";
49
49
  const SDK_METADATA = {
50
50
  name: "@clerk/fastify",
51
- version: "3.1.59",
51
+ version: "3.1.60-canary.v20260731161424",
52
52
  environment: "production"
53
53
  };
54
54
  const { Cookies, Headers } = _clerk_backend_internal.constants;
@@ -75,10 +75,21 @@ const withClerkMiddleware = (options) => {
75
75
  return async (fastifyRequest, reply) => {
76
76
  let resolvedProxyUrl = options.proxyUrl;
77
77
  if (frontendApiProxy) {
78
- const requestUrl = new URL(fastifyRequest.url, `${fastifyRequest.protocol}://${fastifyRequest.hostname || "localhost"}`);
78
+ let requestUrl;
79
+ try {
80
+ requestUrl = new URL(fastifyRequest.url, `${fastifyRequest.protocol}://${fastifyRequest.hostname || "localhost"}`);
81
+ } catch {
82
+ return reply.code(400).send();
83
+ }
79
84
  if (typeof frontendApiProxy.enabled === "function" ? frontendApiProxy.enabled(requestUrl) : frontendApiProxy.enabled) {
80
85
  if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + "/")) {
81
- const proxyResponse = await (0, _clerk_backend_proxy.clerkFrontendApiProxy)(require_utils.requestToProxyRequest(fastifyRequest), {
86
+ let proxyRequest;
87
+ try {
88
+ proxyRequest = require_utils.requestToProxyRequest(fastifyRequest);
89
+ } catch {
90
+ return reply.code(400).send();
91
+ }
92
+ const proxyResponse = await (0, _clerk_backend_proxy.clerkFrontendApiProxy)(proxyRequest, {
82
93
  proxyPath,
83
94
  publishableKey,
84
95
  secretKey
@@ -105,7 +116,12 @@ const withClerkMiddleware = (options) => {
105
116
  if (!resolvedProxyUrl) resolvedProxyUrl = proxyPath;
106
117
  }
107
118
  }
108
- const req = require_utils.fastifyRequestToRequest(fastifyRequest);
119
+ let req;
120
+ try {
121
+ req = require_utils.fastifyRequestToRequest(fastifyRequest);
122
+ } catch {
123
+ return reply.code(400).send();
124
+ }
109
125
  const requestState = await clerkClient.authenticateRequest(req, {
110
126
  ...options,
111
127
  secretKey,
@@ -173,7 +189,7 @@ const clerkClient = (0, _clerk_backend.createClerkClient)({
173
189
  apiUrl: API_URL,
174
190
  apiVersion: API_VERSION,
175
191
  jwtKey: JWT_KEY,
176
- userAgent: `@clerk/fastify@3.1.59`,
192
+ userAgent: `@clerk/fastify@3.1.60-canary.v20260731161424`,
177
193
  sdkMetadata: SDK_METADATA
178
194
  });
179
195
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["constants","DEFAULT_PROXY_PATH","constants.PUBLISHABLE_KEY","constants.SECRET_KEY","constants.MACHINE_SECRET_KEY","constants.API_VERSION","constants.JWT_KEY","constants.SDK_METADATA","requestToProxyRequest","stream","Readable","fastifyRequestToRequest","AuthStatus"],"sources":["../src/types.ts","../src/constants.ts","../src/withClerkMiddleware.ts","../src/clerkPlugin.ts","../src/errors.ts","../src/getAuth.ts","../src/clerkClient.ts"],"sourcesContent":["import type { ClerkClient, ClerkOptions } from '@clerk/backend';\nimport type { ShouldProxyFn } from '@clerk/shared/proxy';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n clerk: ClerkClient;\n }\n}\n\nexport const ALLOWED_HOOKS = ['onRequest', 'preHandler'] as const;\n\n/**\n * Options for the built-in Frontend API proxy.\n *\n * When enabled, the middleware intercepts requests that match the proxy path\n * (default `/__clerk`) and forwards them to the Clerk Frontend API, allowing\n * the Clerk frontend SDKs to communicate with Clerk without third-party\n * cookie or ad-blocker issues.\n */\nexport interface FrontendApiProxyOptions {\n /** Toggle the proxy on/off, or supply a function that decides per-request. */\n enabled: boolean | ShouldProxyFn;\n /** Custom path prefix for the proxy (default: `/__clerk`). */\n path?: string;\n}\n\nexport type ClerkFastifyOptions = ClerkOptions & {\n hookName?: (typeof ALLOWED_HOOKS)[number];\n frontendApiProxy?: FrontendApiProxyOptions;\n};\n","import { constants } from '@clerk/backend/internal';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\n\nexport const API_VERSION = process.env.CLERK_API_VERSION || 'v1';\nexport const SECRET_KEY = process.env.CLERK_SECRET_KEY || '';\nexport const MACHINE_SECRET_KEY = process.env.CLERK_MACHINE_SECRET_KEY || '';\nexport const PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || '';\nexport const API_URL = process.env.CLERK_API_URL || apiUrlFromPublishableKey(PUBLISHABLE_KEY);\nexport const JWT_KEY = process.env.CLERK_JWT_KEY || '';\nexport const SDK_METADATA = {\n name: PACKAGE_NAME,\n version: PACKAGE_VERSION,\n environment: process.env.NODE_ENV,\n};\n\nexport const { Cookies, Headers } = constants;\n","import { createClerkClient } from '@clerk/backend';\nimport { AuthStatus } from '@clerk/backend/internal';\nimport { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport { Readable } from 'stream';\n\nimport * as constants from './constants';\nimport type { ClerkFastifyOptions } from './types';\nimport { fastifyRequestToRequest, requestToProxyRequest } from './utils';\n\nexport const withClerkMiddleware = (options: ClerkFastifyOptions) => {\n const { hookName: _hookName, frontendApiProxy, ...clerkOptions } = options;\n const proxyPath = stripTrailingSlashes(frontendApiProxy?.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;\n const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;\n const secretKey = options.secretKey || constants.SECRET_KEY;\n const apiUrl = options.apiUrl || apiUrlFromPublishableKey(publishableKey);\n const clerkClient = createClerkClient({\n ...clerkOptions,\n publishableKey,\n secretKey,\n machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,\n apiUrl,\n apiVersion: options.apiVersion || constants.API_VERSION,\n jwtKey: options.jwtKey || constants.JWT_KEY,\n userAgent: options.userAgent || `${constants.SDK_METADATA.name}@${constants.SDK_METADATA.version}`,\n sdkMetadata: options.sdkMetadata || constants.SDK_METADATA,\n });\n\n return async (fastifyRequest: FastifyRequest, reply: FastifyReply) => {\n // Handle Frontend API proxy requests and auto-derive proxyUrl\n let resolvedProxyUrl = options.proxyUrl;\n if (frontendApiProxy) {\n const requestUrl = new URL(\n fastifyRequest.url,\n `${fastifyRequest.protocol}://${fastifyRequest.hostname || 'localhost'}`,\n );\n const isEnabled =\n typeof frontendApiProxy.enabled === 'function'\n ? frontendApiProxy.enabled(requestUrl)\n : frontendApiProxy.enabled;\n\n if (isEnabled) {\n if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/')) {\n const proxyRequest = requestToProxyRequest(fastifyRequest);\n\n const proxyResponse = await clerkFrontendApiProxy(proxyRequest, {\n proxyPath,\n publishableKey,\n secretKey,\n });\n\n reply.code(proxyResponse.status);\n proxyResponse.headers.forEach((value, key) => {\n reply.header(key, value);\n });\n\n if (proxyResponse.body) {\n const reader = proxyResponse.body.getReader();\n const stream = new Readable({\n async read() {\n try {\n const { done, value } = await reader.read();\n if (done) {\n this.push(null);\n } else {\n this.push(Buffer.from(value));\n }\n } catch (error) {\n this.destroy(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n return reply.send(stream);\n }\n return reply.send();\n }\n\n // Pass just the path - the backend resolves it against the request's\n // public origin (from x-forwarded-* headers).\n if (!resolvedProxyUrl) {\n resolvedProxyUrl = proxyPath;\n }\n }\n }\n\n const req = fastifyRequestToRequest(fastifyRequest);\n\n const requestState = await clerkClient.authenticateRequest(req, {\n ...options,\n secretKey,\n publishableKey,\n proxyUrl: resolvedProxyUrl,\n acceptsToken: 'any',\n });\n\n requestState.headers.forEach((value, key) => reply.header(key, value));\n\n const locationHeader = requestState.headers.get(constants.Headers.Location);\n if (locationHeader) {\n return reply.code(307).send();\n } else if (requestState.status === AuthStatus.Handshake) {\n throw new Error('Clerk: handshake status without redirect');\n }\n\n // @ts-expect-error Inject auth so getAuth can read it\n fastifyRequest.auth = requestState.toAuth();\n fastifyRequest.clerk = clerkClient;\n };\n};\n","import type { FastifyInstance, FastifyPluginCallback } from 'fastify';\nimport fp from 'fastify-plugin';\n\nimport type { ClerkFastifyOptions } from './types';\nimport { ALLOWED_HOOKS } from './types';\nimport { withClerkMiddleware } from './withClerkMiddleware';\n\nconst plugin: FastifyPluginCallback<ClerkFastifyOptions> = (\n instance: FastifyInstance,\n opts: ClerkFastifyOptions,\n done,\n) => {\n instance.decorateRequest('auth', null);\n instance.decorateRequest('clerk', null as any);\n\n // run clerk as a middleware to all scoped routes\n const hookName = opts.hookName || 'preHandler';\n if (!ALLOWED_HOOKS.includes(hookName)) {\n throw new Error(`Unsupported hookName: ${hookName}`);\n }\n\n instance.addHook(hookName, withClerkMiddleware(opts));\n\n done();\n};\n\nexport const clerkPlugin = fp(plugin, {\n name: '@clerk/fastify',\n fastify: '5.x',\n});\n","// https://github.com/clerk/javascript/blob/main/packages/remix/src/errors.ts#L1-L0\nconst createErrorMessage = (msg: string) => {\n return `🔒 Clerk: ${msg.trim()}\n\nFor more info, check out the docs: https://clerk.com/docs,\nor come say hi in our discord server: https://clerk.com/discord\n`;\n};\n\nexport const pluginRegistrationRequired =\n createErrorMessage(`The \"clerkPlugin\" should be registered before using the \"getAuth\".\nExample:\n\nimport { clerkPlugin } from '@clerk/fastify';\n\nconst server: FastifyInstance = Fastify({ logger: true });\nserver.register(clerkPlugin);\n`);\n","import type { AuthOptions, GetAuthFn, SignedInAuthObject, SignedOutAuthObject } from '@clerk/backend/internal';\nimport { getAuthObjectForAcceptedToken } from '@clerk/backend/internal';\nimport type { FastifyRequest } from 'fastify';\n\nimport { pluginRegistrationRequired } from './errors';\n\nexport const getAuth: GetAuthFn<FastifyRequest> = ((req: FastifyRequest, options?: AuthOptions) => {\n const authReq = req as FastifyRequest & { auth: SignedInAuthObject | SignedOutAuthObject };\n\n if (!authReq.auth) {\n throw new Error(pluginRegistrationRequired);\n }\n\n return getAuthObjectForAcceptedToken({ authObject: authReq.auth, acceptsToken: options?.acceptsToken });\n}) as GetAuthFn<FastifyRequest>;\n","import { createClerkClient } from '@clerk/backend';\n\nimport { API_URL, API_VERSION, JWT_KEY, MACHINE_SECRET_KEY, SDK_METADATA, SECRET_KEY } from './constants';\n\nexport const clerkClient = createClerkClient({\n secretKey: SECRET_KEY,\n machineSecretKey: MACHINE_SECRET_KEY,\n apiUrl: API_URL,\n apiVersion: API_VERSION,\n jwtKey: JWT_KEY,\n userAgent: `${PACKAGE_NAME}@${PACKAGE_VERSION}`,\n sdkMetadata: SDK_METADATA,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAa,gBAAgB,CAAC,aAAa,YAAY;;;;ACNvD,MAAa,cAAc,QAAQ,IAAI,qBAAqB;AAC5D,MAAa,aAAa,QAAQ,IAAI,oBAAoB;AAC1D,MAAa,qBAAqB,QAAQ,IAAI,4BAA4B;AAC1E,MAAa,kBAAkB,QAAQ,IAAI,yBAAyB;AACpE,MAAa,UAAU,QAAQ,IAAI,sFAA0C,eAAe;AAC5F,MAAa,UAAU,QAAQ,IAAI,iBAAiB;AACpD,MAAa,eAAe;CAC1B;CACA;CACA;AACF;AAEA,MAAa,EAAE,SAAS,YAAYA;;;;ACJpC,MAAa,uBAAuB,YAAiC;CACnE,MAAM,EAAE,UAAU,WAAW,kBAAkB,GAAG,iBAAiB;CACnE,MAAM,2DAAiC,kBAAkB,QAAQC,uCAAkB,KAAKA;CACxF,MAAM,iBAAiB,QAAQ,kBAAkBC;CACjD,MAAM,YAAY,QAAQ,aAAaC;CACvC,MAAM,SAAS,QAAQ,+EAAmC,cAAc;CACxE,MAAM,oDAAgC;EACpC,GAAG;EACH;EACA;EAC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;GAC9D,GAAG;GACH;GACA;GACA,UAAU;GACV,cAAc;EAChB,CAAC;EAED,aAAa,QAAQ,SAAS,OAAO,QAAQ,MAAM,OAAO,KAAK,KAAK,CAAC;EAGrE,IADuB,aAAa,QAAQ,YAAsB,QACjD,GACf,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK;OACvB,IAAI,aAAa,WAAWC,mCAAW,WAC5C,MAAM,IAAI,MAAM,0CAA0C;EAI5D,eAAe,OAAO,aAAa,OAAO;EAC1C,eAAe,QAAQ;CACzB;AACF;;;;ACtGA,MAAM,UACJ,UACA,MACA,SACG;CACH,SAAS,gBAAgB,QAAQ,IAAI;CACrC,SAAS,gBAAgB,SAAS,IAAW;CAG7C,MAAM,WAAW,KAAK,YAAY;CAClC,IAAI,CAAC,cAAc,SAAS,QAAQ,GAClC,MAAM,IAAI,MAAM,yBAAyB,UAAU;CAGrD,SAAS,QAAQ,UAAU,oBAAoB,IAAI,CAAC;CAEpD,KAAK;AACP;AAEA,MAAa,0CAAiB,QAAQ;CACpC,MAAM;CACN,SAAS;AACX,CAAC;;;;AC5BD,MAAM,sBAAsB,QAAgB;CAC1C,OAAO,aAAa,IAAI,KAAK,EAAE;;;;;AAKjC;AAEA,MAAa,6BACX,mBAAmB;;;;;;;CAOpB;;;;ACXD,MAAa,YAAuC,KAAqB,YAA0B;CACjG,MAAM,UAAU;CAEhB,IAAI,CAAC,QAAQ,MACX,MAAM,IAAI,MAAM,0BAA0B;CAG5C,kEAAqC;EAAE,YAAY,QAAQ;EAAM,cAAc,SAAS;CAAa,CAAC;AACxG;;;;ACVA,MAAa,oDAAgC;CAC3C,WAAW;CACX,kBAAkB;CAClB,QAAQ;CACR,YAAY;CACZ,QAAQ;CACR,WAAW;CACX,aAAa;AACf,CAAC"}
1
+ {"version":3,"file":"index.js","names":["constants","DEFAULT_PROXY_PATH","constants.PUBLISHABLE_KEY","constants.SECRET_KEY","constants.MACHINE_SECRET_KEY","constants.API_VERSION","constants.JWT_KEY","constants.SDK_METADATA","requestToProxyRequest","stream","Readable","fastifyRequestToRequest","AuthStatus"],"sources":["../src/types.ts","../src/constants.ts","../src/withClerkMiddleware.ts","../src/clerkPlugin.ts","../src/errors.ts","../src/getAuth.ts","../src/clerkClient.ts"],"sourcesContent":["import type { ClerkClient, ClerkOptions } from '@clerk/backend';\nimport type { ShouldProxyFn } from '@clerk/shared/proxy';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n clerk: ClerkClient;\n }\n}\n\nexport const ALLOWED_HOOKS = ['onRequest', 'preHandler'] as const;\n\n/**\n * Options for the built-in Frontend API proxy.\n *\n * When enabled, the middleware intercepts requests that match the proxy path\n * (default `/__clerk`) and forwards them to the Clerk Frontend API, allowing\n * the Clerk frontend SDKs to communicate with Clerk without third-party\n * cookie or ad-blocker issues.\n */\nexport interface FrontendApiProxyOptions {\n /** Toggle the proxy on/off, or supply a function that decides per-request. */\n enabled: boolean | ShouldProxyFn;\n /** Custom path prefix for the proxy (default: `/__clerk`). */\n path?: string;\n}\n\nexport type ClerkFastifyOptions = ClerkOptions & {\n hookName?: (typeof ALLOWED_HOOKS)[number];\n frontendApiProxy?: FrontendApiProxyOptions;\n};\n","import { constants } from '@clerk/backend/internal';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\n\nexport const API_VERSION = process.env.CLERK_API_VERSION || 'v1';\nexport const SECRET_KEY = process.env.CLERK_SECRET_KEY || '';\nexport const MACHINE_SECRET_KEY = process.env.CLERK_MACHINE_SECRET_KEY || '';\nexport const PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || '';\nexport const API_URL = process.env.CLERK_API_URL || apiUrlFromPublishableKey(PUBLISHABLE_KEY);\nexport const JWT_KEY = process.env.CLERK_JWT_KEY || '';\nexport const SDK_METADATA = {\n name: PACKAGE_NAME,\n version: PACKAGE_VERSION,\n environment: process.env.NODE_ENV,\n};\n\nexport const { Cookies, Headers } = constants;\n","import { createClerkClient } from '@clerk/backend';\nimport { AuthStatus } from '@clerk/backend/internal';\nimport { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport { Readable } from 'stream';\n\nimport * as constants from './constants';\nimport type { ClerkFastifyOptions } from './types';\nimport { fastifyRequestToRequest, requestToProxyRequest } from './utils';\n\nexport const withClerkMiddleware = (options: ClerkFastifyOptions) => {\n const { hookName: _hookName, frontendApiProxy, ...clerkOptions } = options;\n const proxyPath = stripTrailingSlashes(frontendApiProxy?.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;\n const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;\n const secretKey = options.secretKey || constants.SECRET_KEY;\n const apiUrl = options.apiUrl || apiUrlFromPublishableKey(publishableKey);\n const clerkClient = createClerkClient({\n ...clerkOptions,\n publishableKey,\n secretKey,\n machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,\n apiUrl,\n apiVersion: options.apiVersion || constants.API_VERSION,\n jwtKey: options.jwtKey || constants.JWT_KEY,\n userAgent: options.userAgent || `${constants.SDK_METADATA.name}@${constants.SDK_METADATA.version}`,\n sdkMetadata: options.sdkMetadata || constants.SDK_METADATA,\n });\n\n return async (fastifyRequest: FastifyRequest, reply: FastifyReply) => {\n // Handle Frontend API proxy requests and auto-derive proxyUrl\n let resolvedProxyUrl = options.proxyUrl;\n if (frontendApiProxy) {\n let requestUrl: URL;\n try {\n requestUrl = new URL(\n fastifyRequest.url,\n `${fastifyRequest.protocol}://${fastifyRequest.hostname || 'localhost'}`,\n );\n } catch {\n return reply.code(400).send();\n }\n const isEnabled =\n typeof frontendApiProxy.enabled === 'function'\n ? frontendApiProxy.enabled(requestUrl)\n : frontendApiProxy.enabled;\n\n if (isEnabled) {\n if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/')) {\n let proxyRequest: Request;\n try {\n proxyRequest = requestToProxyRequest(fastifyRequest);\n } catch {\n return reply.code(400).send();\n }\n\n const proxyResponse = await clerkFrontendApiProxy(proxyRequest, {\n proxyPath,\n publishableKey,\n secretKey,\n });\n\n reply.code(proxyResponse.status);\n proxyResponse.headers.forEach((value, key) => {\n reply.header(key, value);\n });\n\n if (proxyResponse.body) {\n const reader = proxyResponse.body.getReader();\n const stream = new Readable({\n async read() {\n try {\n const { done, value } = await reader.read();\n if (done) {\n this.push(null);\n } else {\n this.push(Buffer.from(value));\n }\n } catch (error) {\n this.destroy(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n return reply.send(stream);\n }\n return reply.send();\n }\n\n // Pass just the path - the backend resolves it against the request's\n // public origin (from x-forwarded-* headers).\n if (!resolvedProxyUrl) {\n resolvedProxyUrl = proxyPath;\n }\n }\n }\n\n // Node accepts request targets/methods (`//`, TRACE) the fetch spec cannot represent; reject those instead of 500ing.\n let req: Request;\n try {\n req = fastifyRequestToRequest(fastifyRequest);\n } catch {\n return reply.code(400).send();\n }\n\n const requestState = await clerkClient.authenticateRequest(req, {\n ...options,\n secretKey,\n publishableKey,\n proxyUrl: resolvedProxyUrl,\n acceptsToken: 'any',\n });\n\n requestState.headers.forEach((value, key) => reply.header(key, value));\n\n const locationHeader = requestState.headers.get(constants.Headers.Location);\n if (locationHeader) {\n return reply.code(307).send();\n } else if (requestState.status === AuthStatus.Handshake) {\n throw new Error('Clerk: handshake status without redirect');\n }\n\n // @ts-expect-error Inject auth so getAuth can read it\n fastifyRequest.auth = requestState.toAuth();\n fastifyRequest.clerk = clerkClient;\n };\n};\n","import type { FastifyInstance, FastifyPluginCallback } from 'fastify';\nimport fp from 'fastify-plugin';\n\nimport type { ClerkFastifyOptions } from './types';\nimport { ALLOWED_HOOKS } from './types';\nimport { withClerkMiddleware } from './withClerkMiddleware';\n\nconst plugin: FastifyPluginCallback<ClerkFastifyOptions> = (\n instance: FastifyInstance,\n opts: ClerkFastifyOptions,\n done,\n) => {\n instance.decorateRequest('auth', null);\n instance.decorateRequest('clerk', null as any);\n\n // run clerk as a middleware to all scoped routes\n const hookName = opts.hookName || 'preHandler';\n if (!ALLOWED_HOOKS.includes(hookName)) {\n throw new Error(`Unsupported hookName: ${hookName}`);\n }\n\n instance.addHook(hookName, withClerkMiddleware(opts));\n\n done();\n};\n\nexport const clerkPlugin = fp(plugin, {\n name: '@clerk/fastify',\n fastify: '5.x',\n});\n","// https://github.com/clerk/javascript/blob/main/packages/remix/src/errors.ts#L1-L0\nconst createErrorMessage = (msg: string) => {\n return `🔒 Clerk: ${msg.trim()}\n\nFor more info, check out the docs: https://clerk.com/docs,\nor come say hi in our discord server: https://clerk.com/discord\n`;\n};\n\nexport const pluginRegistrationRequired =\n createErrorMessage(`The \"clerkPlugin\" should be registered before using the \"getAuth\".\nExample:\n\nimport { clerkPlugin } from '@clerk/fastify';\n\nconst server: FastifyInstance = Fastify({ logger: true });\nserver.register(clerkPlugin);\n`);\n","import type { AuthOptions, GetAuthFn, SignedInAuthObject, SignedOutAuthObject } from '@clerk/backend/internal';\nimport { getAuthObjectForAcceptedToken } from '@clerk/backend/internal';\nimport type { FastifyRequest } from 'fastify';\n\nimport { pluginRegistrationRequired } from './errors';\n\nexport const getAuth: GetAuthFn<FastifyRequest> = ((req: FastifyRequest, options?: AuthOptions) => {\n const authReq = req as FastifyRequest & { auth: SignedInAuthObject | SignedOutAuthObject };\n\n if (!authReq.auth) {\n throw new Error(pluginRegistrationRequired);\n }\n\n return getAuthObjectForAcceptedToken({ authObject: authReq.auth, acceptsToken: options?.acceptsToken });\n}) as GetAuthFn<FastifyRequest>;\n","import { createClerkClient } from '@clerk/backend';\n\nimport { API_URL, API_VERSION, JWT_KEY, MACHINE_SECRET_KEY, SDK_METADATA, SECRET_KEY } from './constants';\n\nexport const clerkClient = createClerkClient({\n secretKey: SECRET_KEY,\n machineSecretKey: MACHINE_SECRET_KEY,\n apiUrl: API_URL,\n apiVers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,YAAsB,QACjD,GACf,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK;OACvB,IAAI,aAAa,WAAWC,mCAAW,WAC5C,MAAM,IAAI,MAAM,0CAA0C;EAI5D,eAAe,OAAO,aAAa,OAAO;EAC1C,eAAe,QAAQ;CACzB;AACF;;;;ACtHA,MAAM,UACJ,UACA,MACA,SACG;CACH,SAAS,gBAAgB,QAAQ,IAAI;CACrC,SAAS,gBAAgB,SAAS,IAAW;CAG7C,MAAM,WAAW,KAAK,YAAY;CAClC,IAAI,CAAC,cAAc,SAAS,QAAQ,GAClC,MAAM,IAAI,MAAM,yBAAyB,UAAU;CAGrD,SAAS,QAAQ,UAAU,oBAAoB,IAAI,CAAC;CAEpD,KAAK;AACP;AAEA,MAAa,0CAAiB,QAAQ;CACpC,MAAM;CACN,SAAS;AACX,CAAC;;;;AC5BD,MAAM,sBAAsB,QAAgB;CAC1C,OAAO,aAAa,IAAI,KAAK,EAAE;;;;;AAKjC;AAEA,MAAa,6BACX,mBAAmB;;;;;;;CAOpB;;;;ACXD,MAAa,YAAuC,KAAqB,YAA0B;CACjG,MAAM,UAAU;CAEhB,IAAI,CAAC,QAAQ,MACX,MAAM,IAAI,MAAM,0BAA0B;CAG5C,kEAAqC;EAAE,YAAY,QAAQ;EAAM,cAAc,SAAS;CAAa,CAAC;AACxG;;;;ACVA,MAAa,oDAAgC;CAC3C,WAAW;CACX,kBAAkB;CAClB,QAAQ;CACR,YAAY;CACZ,QAAQ;CACR,WAAW;CACX,aAAa;AACf,CAAC"}
package/dist/index.mjs CHANGED
@@ -21,7 +21,7 @@ const API_URL = process.env.CLERK_API_URL || apiUrlFromPublishableKey(PUBLISHABL
21
21
  const JWT_KEY = process.env.CLERK_JWT_KEY || "";
22
22
  const SDK_METADATA = {
23
23
  name: "@clerk/fastify",
24
- version: "3.1.59",
24
+ version: "3.1.60-canary.v20260731161424",
25
25
  environment: "production"
26
26
  };
27
27
  const { Cookies, Headers } = constants;
@@ -48,10 +48,21 @@ const withClerkMiddleware = (options) => {
48
48
  return async (fastifyRequest, reply) => {
49
49
  let resolvedProxyUrl = options.proxyUrl;
50
50
  if (frontendApiProxy) {
51
- const requestUrl = new URL(fastifyRequest.url, `${fastifyRequest.protocol}://${fastifyRequest.hostname || "localhost"}`);
51
+ let requestUrl;
52
+ try {
53
+ requestUrl = new URL(fastifyRequest.url, `${fastifyRequest.protocol}://${fastifyRequest.hostname || "localhost"}`);
54
+ } catch {
55
+ return reply.code(400).send();
56
+ }
52
57
  if (typeof frontendApiProxy.enabled === "function" ? frontendApiProxy.enabled(requestUrl) : frontendApiProxy.enabled) {
53
58
  if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + "/")) {
54
- const proxyResponse = await clerkFrontendApiProxy(requestToProxyRequest(fastifyRequest), {
59
+ let proxyRequest;
60
+ try {
61
+ proxyRequest = requestToProxyRequest(fastifyRequest);
62
+ } catch {
63
+ return reply.code(400).send();
64
+ }
65
+ const proxyResponse = await clerkFrontendApiProxy(proxyRequest, {
55
66
  proxyPath,
56
67
  publishableKey,
57
68
  secretKey
@@ -78,7 +89,12 @@ const withClerkMiddleware = (options) => {
78
89
  if (!resolvedProxyUrl) resolvedProxyUrl = proxyPath;
79
90
  }
80
91
  }
81
- const req = fastifyRequestToRequest(fastifyRequest);
92
+ let req;
93
+ try {
94
+ req = fastifyRequestToRequest(fastifyRequest);
95
+ } catch {
96
+ return reply.code(400).send();
97
+ }
82
98
  const requestState = await clerkClient.authenticateRequest(req, {
83
99
  ...options,
84
100
  secretKey,
@@ -146,7 +162,7 @@ const clerkClient = createClerkClient({
146
162
  apiUrl: API_URL,
147
163
  apiVersion: API_VERSION,
148
164
  jwtKey: JWT_KEY,
149
- userAgent: `@clerk/fastify@3.1.59`,
165
+ userAgent: `@clerk/fastify@3.1.60-canary.v20260731161424`,
150
166
  sdkMetadata: SDK_METADATA
151
167
  });
152
168
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["constants.PUBLISHABLE_KEY","constants.SECRET_KEY","constants.MACHINE_SECRET_KEY","constants.API_VERSION","constants.JWT_KEY","constants.SDK_METADATA"],"sources":["../src/types.ts","../src/constants.ts","../src/withClerkMiddleware.ts","../src/clerkPlugin.ts","../src/errors.ts","../src/getAuth.ts","../src/clerkClient.ts"],"sourcesContent":["import type { ClerkClient, ClerkOptions } from '@clerk/backend';\nimport type { ShouldProxyFn } from '@clerk/shared/proxy';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n clerk: ClerkClient;\n }\n}\n\nexport const ALLOWED_HOOKS = ['onRequest', 'preHandler'] as const;\n\n/**\n * Options for the built-in Frontend API proxy.\n *\n * When enabled, the middleware intercepts requests that match the proxy path\n * (default `/__clerk`) and forwards them to the Clerk Frontend API, allowing\n * the Clerk frontend SDKs to communicate with Clerk without third-party\n * cookie or ad-blocker issues.\n */\nexport interface FrontendApiProxyOptions {\n /** Toggle the proxy on/off, or supply a function that decides per-request. */\n enabled: boolean | ShouldProxyFn;\n /** Custom path prefix for the proxy (default: `/__clerk`). */\n path?: string;\n}\n\nexport type ClerkFastifyOptions = ClerkOptions & {\n hookName?: (typeof ALLOWED_HOOKS)[number];\n frontendApiProxy?: FrontendApiProxyOptions;\n};\n","import { constants } from '@clerk/backend/internal';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\n\nexport const API_VERSION = process.env.CLERK_API_VERSION || 'v1';\nexport const SECRET_KEY = process.env.CLERK_SECRET_KEY || '';\nexport const MACHINE_SECRET_KEY = process.env.CLERK_MACHINE_SECRET_KEY || '';\nexport const PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || '';\nexport const API_URL = process.env.CLERK_API_URL || apiUrlFromPublishableKey(PUBLISHABLE_KEY);\nexport const JWT_KEY = process.env.CLERK_JWT_KEY || '';\nexport const SDK_METADATA = {\n name: PACKAGE_NAME,\n version: PACKAGE_VERSION,\n environment: process.env.NODE_ENV,\n};\n\nexport const { Cookies, Headers } = constants;\n","import { createClerkClient } from '@clerk/backend';\nimport { AuthStatus } from '@clerk/backend/internal';\nimport { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport { Readable } from 'stream';\n\nimport * as constants from './constants';\nimport type { ClerkFastifyOptions } from './types';\nimport { fastifyRequestToRequest, requestToProxyRequest } from './utils';\n\nexport const withClerkMiddleware = (options: ClerkFastifyOptions) => {\n const { hookName: _hookName, frontendApiProxy, ...clerkOptions } = options;\n const proxyPath = stripTrailingSlashes(frontendApiProxy?.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;\n const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;\n const secretKey = options.secretKey || constants.SECRET_KEY;\n const apiUrl = options.apiUrl || apiUrlFromPublishableKey(publishableKey);\n const clerkClient = createClerkClient({\n ...clerkOptions,\n publishableKey,\n secretKey,\n machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,\n apiUrl,\n apiVersion: options.apiVersion || constants.API_VERSION,\n jwtKey: options.jwtKey || constants.JWT_KEY,\n userAgent: options.userAgent || `${constants.SDK_METADATA.name}@${constants.SDK_METADATA.version}`,\n sdkMetadata: options.sdkMetadata || constants.SDK_METADATA,\n });\n\n return async (fastifyRequest: FastifyRequest, reply: FastifyReply) => {\n // Handle Frontend API proxy requests and auto-derive proxyUrl\n let resolvedProxyUrl = options.proxyUrl;\n if (frontendApiProxy) {\n const requestUrl = new URL(\n fastifyRequest.url,\n `${fastifyRequest.protocol}://${fastifyRequest.hostname || 'localhost'}`,\n );\n const isEnabled =\n typeof frontendApiProxy.enabled === 'function'\n ? frontendApiProxy.enabled(requestUrl)\n : frontendApiProxy.enabled;\n\n if (isEnabled) {\n if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/')) {\n const proxyRequest = requestToProxyRequest(fastifyRequest);\n\n const proxyResponse = await clerkFrontendApiProxy(proxyRequest, {\n proxyPath,\n publishableKey,\n secretKey,\n });\n\n reply.code(proxyResponse.status);\n proxyResponse.headers.forEach((value, key) => {\n reply.header(key, value);\n });\n\n if (proxyResponse.body) {\n const reader = proxyResponse.body.getReader();\n const stream = new Readable({\n async read() {\n try {\n const { done, value } = await reader.read();\n if (done) {\n this.push(null);\n } else {\n this.push(Buffer.from(value));\n }\n } catch (error) {\n this.destroy(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n return reply.send(stream);\n }\n return reply.send();\n }\n\n // Pass just the path - the backend resolves it against the request's\n // public origin (from x-forwarded-* headers).\n if (!resolvedProxyUrl) {\n resolvedProxyUrl = proxyPath;\n }\n }\n }\n\n const req = fastifyRequestToRequest(fastifyRequest);\n\n const requestState = await clerkClient.authenticateRequest(req, {\n ...options,\n secretKey,\n publishableKey,\n proxyUrl: resolvedProxyUrl,\n acceptsToken: 'any',\n });\n\n requestState.headers.forEach((value, key) => reply.header(key, value));\n\n const locationHeader = requestState.headers.get(constants.Headers.Location);\n if (locationHeader) {\n return reply.code(307).send();\n } else if (requestState.status === AuthStatus.Handshake) {\n throw new Error('Clerk: handshake status without redirect');\n }\n\n // @ts-expect-error Inject auth so getAuth can read it\n fastifyRequest.auth = requestState.toAuth();\n fastifyRequest.clerk = clerkClient;\n };\n};\n","import type { FastifyInstance, FastifyPluginCallback } from 'fastify';\nimport fp from 'fastify-plugin';\n\nimport type { ClerkFastifyOptions } from './types';\nimport { ALLOWED_HOOKS } from './types';\nimport { withClerkMiddleware } from './withClerkMiddleware';\n\nconst plugin: FastifyPluginCallback<ClerkFastifyOptions> = (\n instance: FastifyInstance,\n opts: ClerkFastifyOptions,\n done,\n) => {\n instance.decorateRequest('auth', null);\n instance.decorateRequest('clerk', null as any);\n\n // run clerk as a middleware to all scoped routes\n const hookName = opts.hookName || 'preHandler';\n if (!ALLOWED_HOOKS.includes(hookName)) {\n throw new Error(`Unsupported hookName: ${hookName}`);\n }\n\n instance.addHook(hookName, withClerkMiddleware(opts));\n\n done();\n};\n\nexport const clerkPlugin = fp(plugin, {\n name: '@clerk/fastify',\n fastify: '5.x',\n});\n","// https://github.com/clerk/javascript/blob/main/packages/remix/src/errors.ts#L1-L0\nconst createErrorMessage = (msg: string) => {\n return `🔒 Clerk: ${msg.trim()}\n\nFor more info, check out the docs: https://clerk.com/docs,\nor come say hi in our discord server: https://clerk.com/discord\n`;\n};\n\nexport const pluginRegistrationRequired =\n createErrorMessage(`The \"clerkPlugin\" should be registered before using the \"getAuth\".\nExample:\n\nimport { clerkPlugin } from '@clerk/fastify';\n\nconst server: FastifyInstance = Fastify({ logger: true });\nserver.register(clerkPlugin);\n`);\n","import type { AuthOptions, GetAuthFn, SignedInAuthObject, SignedOutAuthObject } from '@clerk/backend/internal';\nimport { getAuthObjectForAcceptedToken } from '@clerk/backend/internal';\nimport type { FastifyRequest } from 'fastify';\n\nimport { pluginRegistrationRequired } from './errors';\n\nexport const getAuth: GetAuthFn<FastifyRequest> = ((req: FastifyRequest, options?: AuthOptions) => {\n const authReq = req as FastifyRequest & { auth: SignedInAuthObject | SignedOutAuthObject };\n\n if (!authReq.auth) {\n throw new Error(pluginRegistrationRequired);\n }\n\n return getAuthObjectForAcceptedToken({ authObject: authReq.auth, acceptsToken: options?.acceptsToken });\n}) as GetAuthFn<FastifyRequest>;\n","import { createClerkClient } from '@clerk/backend';\n\nimport { API_URL, API_VERSION, JWT_KEY, MACHINE_SECRET_KEY, SDK_METADATA, SECRET_KEY } from './constants';\n\nexport const clerkClient = createClerkClient({\n secretKey: SECRET_KEY,\n machineSecretKey: MACHINE_SECRET_KEY,\n apiUrl: API_URL,\n apiVersion: API_VERSION,\n jwtKey: JWT_KEY,\n userAgent: `${PACKAGE_NAME}@${PACKAGE_VERSION}`,\n sdkMetadata: SDK_METADATA,\n});\n"],"mappings":";;;;;;;;;;;AASA,MAAa,gBAAgB,CAAC,a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AAoB,IAAI,CAAC;CAEpD,KAAK;AACP;AAEA,MAAa,cAAc,GAAG,QAAQ;CACpC,MAAM;CACN,SAAS;AACX,CAAC;;;;AC5BD,MAAM,sBAAsB,QAAgB;CAC1C,OAAO,aAAa,IAAI,KAAK,EAAE;;;;;AAKjC;AAEA,MAAa,6BACX,mBAAmB;;;;;;;CAOpB;;;;ACXD,MAAa,YAAuC,KAAqB,YAA0B;CACjG,MAAM,UAAU;CAEhB,IAAI,CAAC,QAAQ,MACX,MAAM,IAAI,MAAM,0BAA0B;CAG5C,OAAO,8BAA8B;EAAE,YAAY,QAAQ;EAAM,cAAc,SAAS;CAAa,CAAC;AACxG;;;;ACVA,MAAa,cAAc,kBAAkB;CAC3C,WAAW;CACX,kBAAkB;CAClB,QAAQ;CACR,YAAY;CACZ,QAAQ;CACR,WAAW;CACX,aAAa;AACf,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["constants.PUBLISHABLE_KEY","constants.SECRET_KEY","constants.MACHINE_SECRET_KEY","constants.API_VERSION","constants.JWT_KEY","constants.SDK_METADATA"],"sources":["../src/types.ts","../src/constants.ts","../src/withClerkMiddleware.ts","../src/clerkPlugin.ts","../src/errors.ts","../src/getAuth.ts","../src/clerkClient.ts"],"sourcesContent":["import type { ClerkClient, ClerkOptions } from '@clerk/backend';\nimport type { ShouldProxyFn } from '@clerk/shared/proxy';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n clerk: ClerkClient;\n }\n}\n\nexport const ALLOWED_HOOKS = ['onRequest', 'preHandler'] as const;\n\n/**\n * Options for the built-in Frontend API proxy.\n *\n * When enabled, the middleware intercepts requests that match the proxy path\n * (default `/__clerk`) and forwards them to the Clerk Frontend API, allowing\n * the Clerk frontend SDKs to communicate with Clerk without third-party\n * cookie or ad-blocker issues.\n */\nexport interface FrontendApiProxyOptions {\n /** Toggle the proxy on/off, or supply a function that decides per-request. */\n enabled: boolean | ShouldProxyFn;\n /** Custom path prefix for the proxy (default: `/__clerk`). */\n path?: string;\n}\n\nexport type ClerkFastifyOptions = ClerkOptions & {\n hookName?: (typeof ALLOWED_HOOKS)[number];\n frontendApiProxy?: FrontendApiProxyOptions;\n};\n","import { constants } from '@clerk/backend/internal';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\n\nexport const API_VERSION = process.env.CLERK_API_VERSION || 'v1';\nexport const SECRET_KEY = process.env.CLERK_SECRET_KEY || '';\nexport const MACHINE_SECRET_KEY = process.env.CLERK_MACHINE_SECRET_KEY || '';\nexport const PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || '';\nexport const API_URL = process.env.CLERK_API_URL || apiUrlFromPublishableKey(PUBLISHABLE_KEY);\nexport const JWT_KEY = process.env.CLERK_JWT_KEY || '';\nexport const SDK_METADATA = {\n name: PACKAGE_NAME,\n version: PACKAGE_VERSION,\n environment: process.env.NODE_ENV,\n};\n\nexport const { Cookies, Headers } = constants;\n","import { createClerkClient } from '@clerk/backend';\nimport { AuthStatus } from '@clerk/backend/internal';\nimport { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';\nimport { apiUrlFromPublishableKey } from '@clerk/shared/apiUrlFromPublishableKey';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport { Readable } from 'stream';\n\nimport * as constants from './constants';\nimport type { ClerkFastifyOptions } from './types';\nimport { fastifyRequestToRequest, requestToProxyRequest } from './utils';\n\nexport const withClerkMiddleware = (options: ClerkFastifyOptions) => {\n const { hookName: _hookName, frontendApiProxy, ...clerkOptions } = options;\n const proxyPath = stripTrailingSlashes(frontendApiProxy?.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;\n const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;\n const secretKey = options.secretKey || constants.SECRET_KEY;\n const apiUrl = options.apiUrl || apiUrlFromPublishableKey(publishableKey);\n const clerkClient = createClerkClient({\n ...clerkOptions,\n publishableKey,\n secretKey,\n machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,\n apiUrl,\n apiVersion: options.apiVersion || constants.API_VERSION,\n jwtKey: options.jwtKey || constants.JWT_KEY,\n userAgent: options.userAgent || `${constants.SDK_METADATA.name}@${constants.SDK_METADATA.version}`,\n sdkMetadata: options.sdkMetadata || constants.SDK_METADATA,\n });\n\n return async (fastifyRequest: FastifyRequest, reply: FastifyReply) => {\n // Handle Frontend API proxy requests and auto-derive proxyUrl\n let resolvedProxyUrl = options.proxyUrl;\n if (frontendApiProxy) {\n let requestUrl: URL;\n try {\n requestUrl = new URL(\n fastifyRequest.url,\n `${fastifyRequest.protocol}://${fastifyRequest.hostname || 'localhost'}`,\n );\n } catch {\n return reply.code(400).send();\n }\n const isEnabled =\n typeof frontendApiProxy.enabled === 'function'\n ? frontendApiProxy.enabled(requestUrl)\n : frontendApiProxy.enabled;\n\n if (isEnabled) {\n if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + '/')) {\n let proxyRequest: Request;\n try {\n proxyRequest = requestToProxyRequest(fastifyRequest);\n } catch {\n return reply.code(400).send();\n }\n\n const proxyResponse = await clerkFrontendApiProxy(proxyRequest, {\n proxyPath,\n publishableKey,\n secretKey,\n });\n\n reply.code(proxyResponse.status);\n proxyResponse.headers.forEach((value, key) => {\n reply.header(key, value);\n });\n\n if (proxyResponse.body) {\n const reader = proxyResponse.body.getReader();\n const stream = new Readable({\n async read() {\n try {\n const { done, value } = await reader.read();\n if (done) {\n this.push(null);\n } else {\n this.push(Buffer.from(value));\n }\n } catch (error) {\n this.destroy(error instanceof Error ? error : new Error(String(error)));\n }\n },\n });\n return reply.send(stream);\n }\n return reply.send();\n }\n\n // Pass just the path - the backend resolves it against the request's\n // public origin (from x-forwarded-* headers).\n if (!resolvedProxyUrl) {\n resolvedProxyUrl = proxyPath;\n }\n }\n }\n\n // Node accepts request targets/methods (`//`, TRACE) the fetch spec cannot represent; reject those instead of 500ing.\n let req: Request;\n try {\n req = fastifyRequestToRequest(fastifyRequest);\n } catch {\n return reply.code(400).send();\n }\n\n const requestState = await clerkClient.authenticateRequest(req, {\n ...options,\n secretKey,\n publishableKey,\n proxyUrl: resolvedProxyUrl,\n acceptsToken: 'any',\n });\n\n requestState.headers.forEach((value, key) => reply.header(key, value));\n\n const locationHeader = requestState.headers.get(constants.Headers.Location);\n if (locationHeader) {\n return reply.code(307).send();\n } else if (requestState.status === AuthStatus.Handshake) {\n throw new Error('Clerk: handshake status without redirect');\n }\n\n // @ts-expect-error Inject auth so getAuth can read it\n fastifyRequest.auth = requestState.toAuth();\n fastifyRequest.clerk = clerkClient;\n };\n};\n","import type { FastifyInstance, FastifyPluginCallback } from 'fastify';\nimport fp from 'fastify-plugin';\n\nimport type { ClerkFastifyOptions } from './types';\nimport { ALLOWED_HOOKS } from './types';\nimport { withClerkMiddleware } from './withClerkMiddleware';\n\nconst plugin: FastifyPluginCallback<ClerkFastifyOptions> = (\n instance: FastifyInstance,\n opts: ClerkFastifyOptions,\n done,\n) => {\n instance.decorateRequest('auth', null);\n instance.decorateRequest('clerk', null as any);\n\n // run clerk as a middleware to all scoped routes\n const hookName = opts.hookName || 'preHandler';\n if (!ALLOWED_HOOKS.includes(hookName)) {\n throw new Error(`Unsupported hookName: ${hookName}`);\n }\n\n instance.addHook(hookName, withClerkMiddleware(opts));\n\n done();\n};\n\nexport const clerkPlugin = fp(plugin, {\n name: '@clerk/fastify',\n fastify: '5.x',\n});\n","// https://github.com/clerk/javascript/blob/main/packages/remix/src/errors.ts#L1-L0\nconst createErrorMessage = (msg: string) => {\n return `🔒 Clerk: ${msg.trim()}\n\nFor more info, check out the docs: https://clerk.com/docs,\nor come say hi in our discord server: https://clerk.com/discord\n`;\n};\n\nexport const pluginRegistrationRequired =\n createErrorMessage(`The \"clerkPlugin\" should be registered before using the \"getAuth\".\nExample:\n\nimport { clerkPlugin } from '@clerk/fastify';\n\nconst server: FastifyInstance = Fastify({ logger: true });\nserver.register(clerkPlugin);\n`);\n","import type { AuthOptions, GetAuthFn, SignedInAuthObject, SignedOutAuthObject } from '@clerk/backend/internal';\nimport { getAuthObjectForAcceptedToken } from '@clerk/backend/internal';\nimport type { FastifyRequest } from 'fastify';\n\nimport { pluginRegistrationRequired } from './errors';\n\nexport const getAuth: GetAuthFn<FastifyRequest> = ((req: FastifyRequest, options?: AuthOptions) => {\n const authReq = req as FastifyRequest & { auth: SignedInAuthObject | SignedOutAuthObject };\n\n if (!authReq.auth) {\n throw new Error(pluginRegistrationRequired);\n }\n\n return getAuthObjectForAcceptedToken({ authObject: authReq.auth, acceptsToken: options?.acceptsToken });\n}) as GetAuthFn<FastifyRequest>;\n","import { createClerkClient } from '@clerk/backend';\n\nimport { API_URL, API_VERSION, JWT_KEY, MACHINE_SECRET_KEY, SDK_METADATA, SECRET_KEY } from './constants';\n\nexport const clerkClient = createClerkClient({\n secretKey: SECRET_KEY,\n machineSecretKey: MACHINE_SECRET_KEY,\n apiUrl: API_URL,\n apiVersion: API_VERSION,\n jwtKey: JWT_KEY,\n userAgent: `${PACKAGE_NAME}@${PACKAGE_VERSION}`,\n sdkMetadata: SDK_METADATA,\n});\n"],"mappings":";;;;;;;;;;;AASA,MAAa,gBAAgB,CAAC,aAAa,YAAY;;;;ACNvD,MAAa,cAAc,QAAQ,IAAI,qBAAqB;AAC5D,MAAa,aAAa,QAAQ,IAAI,oBAAoB;AAC1D,MAAa,qBAAqB,QAAQ,IAAI,4BAA4B;AAC1E,MAAa,kBAAkB,QAAQ,IAAI,yBAAyB;AACpE,MAAa,UAAU,QAAQ,IAAI,iBAAiB,yBAAyB,eAAe;AAC5F,MAAa,UAAU,QAAQ,IAAI,iBAAiB;AACpD,MAAa,eAAe;CAC1B;CACA;CACA;AACF;AAEA,MAAa,EAAE,SAAS,YAAY;;;;ACJpC,MAAa,uBAAuB,YAAiC;CACnE,MAAM,EAAE,UAAU,WAAW,kBAAkB,GAAG,iBAAiB;CACnE,MAAM,YAAY,qBAAqB,kBAAkB,QAAQ,k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;;;;;;;CAOpB;;;;ACXD,MAAa,YAAuC,KAAqB,YAA0B;CACjG,MAAM,UAAU;CAEhB,IAAI,CAAC,QAAQ,MACX,MAAM,IAAI,MAAM,0BAA0B;CAG5C,OAAO,8BAA8B;EAAE,YAAY,QAAQ;EAAM,cAAc,SAAS;CAAa,CAAC;AACxG;;;;ACVA,MAAa,cAAc,kBAAkB;CAC3C,WAAW;CACX,kBAAkB;CAClB,QAAQ;CACR,YAAY;CACZ,QAAQ;CACR,WAAW;CACX,aAAa;AACf,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerk/fastify",
3
- "version": "3.1.59",
3
+ "version": "3.1.60-canary.v20260731161424",
4
4
  "description": "Clerk SDK for Fastify",
5
5
  "keywords": [
6
6
  "auth",
@@ -61,8 +61,8 @@
61
61
  ],
62
62
  "dependencies": {
63
63
  "fastify-plugin": "^5.1.0",
64
- "@clerk/backend": "^3.15.0",
65
- "@clerk/shared": "^4.25.10"
64
+ "@clerk/backend": "3.15.1-canary.v20260731161424",
65
+ "@clerk/shared": "4.25.11-canary.v20260731161424"
66
66
  },
67
67
  "devDependencies": {
68
68
  "fastify": "^5.8.5"