@clerk/fastify 3.1.35 → 3.1.36-canary.v20260610190754
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.d.mts +13 -13
- package/dist/index.d.mts.map +1 -0
- package/dist/index.d.ts +13 -13
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +155 -228
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +127 -154
- package/dist/index.mjs.map +1 -1
- package/dist/types-Cd_46YLP.d.mts +31 -0
- package/dist/types-Cd_46YLP.d.mts.map +1 -0
- package/dist/types-Cd_46YLP.d.ts +31 -0
- package/dist/types-Cd_46YLP.d.ts.map +1 -0
- package/dist/types.d.mts +3 -4
- package/dist/types.d.ts +3 -4
- package/dist/types.js +0 -19
- package/dist/types.mjs +1 -1
- package/dist/utils-D0QXqL7p.js +58 -0
- package/dist/utils-D0QXqL7p.js.map +1 -0
- package/dist/utils-D8RSULf1.mjs +47 -0
- package/dist/utils-D8RSULf1.mjs.map +1 -0
- package/dist/webhooks.d.mts +7 -6
- package/dist/webhooks.d.mts.map +1 -0
- package/dist/webhooks.d.ts +7 -6
- package/dist/webhooks.d.ts.map +1 -0
- package/dist/webhooks.js +26 -61
- package/dist/webhooks.js.map +1 -1
- package/dist/webhooks.mjs +21 -14
- package/dist/webhooks.mjs.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-RY4T2JMQ.mjs +0 -53
- package/dist/chunk-RY4T2JMQ.mjs.map +0 -1
- package/dist/index-CqO2PYpu.d.mts +0 -30
- package/dist/index-CqO2PYpu.d.ts +0 -30
- package/dist/types.js.map +0 -1
- package/dist/types.mjs.map +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
export
|
|
5
|
-
import { FastifyPluginCallback, FastifyRequest } from 'fastify';
|
|
6
|
-
import { GetAuthFn } from '@clerk/backend/internal';
|
|
7
|
-
import '@clerk/shared/types';
|
|
8
|
-
import '@clerk/shared/proxy';
|
|
1
|
+
import { n as FrontendApiProxyOptions, t as ClerkFastifyOptions } from "./types-Cd_46YLP.mjs";
|
|
2
|
+
import { GetAuthFn } from "@clerk/backend/internal";
|
|
3
|
+
import { FastifyPluginCallback, FastifyRequest } from "fastify";
|
|
4
|
+
export * from "@clerk/backend";
|
|
9
5
|
|
|
6
|
+
//#region src/clerkPlugin.d.ts
|
|
10
7
|
declare const clerkPlugin: FastifyPluginCallback<ClerkFastifyOptions>;
|
|
11
|
-
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/getAuth.d.ts
|
|
12
10
|
declare const getAuth: GetAuthFn<FastifyRequest>;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/clerkClient.d.ts
|
|
13
|
+
declare const clerkClient: import("@clerk/backend").ClerkClient;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { type ClerkFastifyOptions, type FrontendApiProxyOptions, clerkClient, clerkPlugin, getAuth };
|
|
16
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/clerkPlugin.ts","../src/getAuth.ts","../src/clerkClient.ts"],"mappings":";;;;;;cA0Ba,WAAA,EAAW,qBAAA,CAAA,mBAAA;;;cCpBX,OAAA,EAAS,SAAS,CAAC,cAAA;;;cCFnB,WAAA,2BAAW,WAQtB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
export
|
|
5
|
-
import { FastifyPluginCallback, FastifyRequest } from 'fastify';
|
|
6
|
-
import { GetAuthFn } from '@clerk/backend/internal';
|
|
7
|
-
import '@clerk/shared/types';
|
|
8
|
-
import '@clerk/shared/proxy';
|
|
1
|
+
import { n as FrontendApiProxyOptions, t as ClerkFastifyOptions } from "./types-Cd_46YLP.js";
|
|
2
|
+
import { FastifyPluginCallback, FastifyRequest } from "fastify";
|
|
3
|
+
import { GetAuthFn } from "@clerk/backend/internal";
|
|
4
|
+
export * from "@clerk/backend";
|
|
9
5
|
|
|
6
|
+
//#region src/clerkPlugin.d.ts
|
|
10
7
|
declare const clerkPlugin: FastifyPluginCallback<ClerkFastifyOptions>;
|
|
11
|
-
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/getAuth.d.ts
|
|
12
10
|
declare const getAuth: GetAuthFn<FastifyRequest>;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/clerkClient.d.ts
|
|
13
|
+
declare const clerkClient: import("@clerk/backend").ClerkClient;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { type ClerkFastifyOptions, type FrontendApiProxyOptions, clerkClient, clerkPlugin, getAuth };
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/clerkPlugin.ts","../src/getAuth.ts","../src/clerkClient.ts"],"mappings":";;;;;;cA0Ba,WAAA,EAAW,qBAAA,CAAA,mBAAA;;;cCpBX,OAAA,EAAS,SAAS,CAAC,cAAA;;;cCFnB,WAAA,2BAAW,WAQtB"}
|
package/dist/index.js
CHANGED
|
@@ -1,231 +1,151 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
//#region \0rolldown/runtime.js
|
|
2
3
|
var __create = Object.create;
|
|
3
4
|
var __defProp = Object.defineProperty;
|
|
4
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
6
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
7
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
8
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
9
|
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
12
|
+
key = keys[i];
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
14
|
+
__defProp(to, key, {
|
|
15
|
+
get: ((k) => from[k]).bind(null, key),
|
|
16
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
19
22
|
};
|
|
20
|
-
var
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
-
mod
|
|
28
|
-
));
|
|
29
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
-
|
|
31
|
-
// src/index.ts
|
|
32
|
-
var src_exports = {};
|
|
33
|
-
__export(src_exports, {
|
|
34
|
-
clerkClient: () => clerkClient,
|
|
35
|
-
clerkPlugin: () => clerkPlugin,
|
|
36
|
-
getAuth: () => getAuth
|
|
37
|
-
});
|
|
38
|
-
module.exports = __toCommonJS(src_exports);
|
|
39
|
-
__reExport(src_exports, require("@clerk/backend"), module.exports);
|
|
40
|
-
|
|
41
|
-
// src/clerkPlugin.ts
|
|
42
|
-
var import_fastify_plugin = __toESM(require("fastify-plugin"));
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
24
|
+
value: mod,
|
|
25
|
+
enumerable: true
|
|
26
|
+
}) : target, mod));
|
|
43
27
|
|
|
44
|
-
|
|
45
|
-
|
|
28
|
+
//#endregion
|
|
29
|
+
const require_utils = require('./utils-D0QXqL7p.js');
|
|
30
|
+
let _clerk_backend = require("@clerk/backend");
|
|
31
|
+
let fastify_plugin = require("fastify-plugin");
|
|
32
|
+
fastify_plugin = __toESM(fastify_plugin);
|
|
33
|
+
let _clerk_backend_internal = require("@clerk/backend/internal");
|
|
34
|
+
let _clerk_backend_proxy = require("@clerk/backend/proxy");
|
|
35
|
+
let _clerk_shared_apiUrlFromPublishableKey = require("@clerk/shared/apiUrlFromPublishableKey");
|
|
36
|
+
let stream = require("stream");
|
|
46
37
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
var import_internal2 = require("@clerk/backend/internal");
|
|
50
|
-
var import_proxy = require("@clerk/backend/proxy");
|
|
51
|
-
var import_apiUrlFromPublishableKey2 = require("@clerk/shared/apiUrlFromPublishableKey");
|
|
52
|
-
var import_stream2 = require("stream");
|
|
38
|
+
//#region src/types.ts
|
|
39
|
+
const ALLOWED_HOOKS = ["onRequest", "preHandler"];
|
|
53
40
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
environment: "production"
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/constants.ts
|
|
43
|
+
const API_VERSION = process.env.CLERK_API_VERSION || "v1";
|
|
44
|
+
const SECRET_KEY = process.env.CLERK_SECRET_KEY || "";
|
|
45
|
+
const MACHINE_SECRET_KEY = process.env.CLERK_MACHINE_SECRET_KEY || "";
|
|
46
|
+
const PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || "";
|
|
47
|
+
const API_URL = process.env.CLERK_API_URL || (0, _clerk_shared_apiUrlFromPublishableKey.apiUrlFromPublishableKey)(PUBLISHABLE_KEY);
|
|
48
|
+
const JWT_KEY = process.env.CLERK_JWT_KEY || "";
|
|
49
|
+
const SDK_METADATA = {
|
|
50
|
+
name: "@clerk/fastify",
|
|
51
|
+
version: "3.1.36-canary.v20260610190754",
|
|
52
|
+
environment: "production"
|
|
67
53
|
};
|
|
68
|
-
|
|
54
|
+
const { Cookies, Headers } = _clerk_backend_internal.constants;
|
|
69
55
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
};
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/withClerkMiddleware.ts
|
|
58
|
+
const withClerkMiddleware = (options) => {
|
|
59
|
+
const { hookName: _hookName, frontendApiProxy, ...clerkOptions } = options;
|
|
60
|
+
const proxyPath = (0, _clerk_backend_proxy.stripTrailingSlashes)(frontendApiProxy?.path ?? _clerk_backend_proxy.DEFAULT_PROXY_PATH) || _clerk_backend_proxy.DEFAULT_PROXY_PATH;
|
|
61
|
+
const publishableKey = options.publishableKey || PUBLISHABLE_KEY;
|
|
62
|
+
const secretKey = options.secretKey || SECRET_KEY;
|
|
63
|
+
const apiUrl = options.apiUrl || (0, _clerk_shared_apiUrlFromPublishableKey.apiUrlFromPublishableKey)(publishableKey);
|
|
64
|
+
const clerkClient = (0, _clerk_backend.createClerkClient)({
|
|
65
|
+
...clerkOptions,
|
|
66
|
+
publishableKey,
|
|
67
|
+
secretKey,
|
|
68
|
+
machineSecretKey: options.machineSecretKey || MACHINE_SECRET_KEY,
|
|
69
|
+
apiUrl,
|
|
70
|
+
apiVersion: options.apiVersion || API_VERSION,
|
|
71
|
+
jwtKey: options.jwtKey || JWT_KEY,
|
|
72
|
+
userAgent: options.userAgent || `${SDK_METADATA.name}@${SDK_METADATA.version}`,
|
|
73
|
+
sdkMetadata: options.sdkMetadata || SDK_METADATA
|
|
74
|
+
});
|
|
75
|
+
return async (fastifyRequest, reply) => {
|
|
76
|
+
let resolvedProxyUrl = options.proxyUrl;
|
|
77
|
+
if (frontendApiProxy) {
|
|
78
|
+
const requestUrl = new URL(fastifyRequest.url, `${fastifyRequest.protocol}://${fastifyRequest.hostname || "localhost"}`);
|
|
79
|
+
if (typeof frontendApiProxy.enabled === "function" ? frontendApiProxy.enabled(requestUrl) : frontendApiProxy.enabled) {
|
|
80
|
+
if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + "/")) {
|
|
81
|
+
const proxyResponse = await (0, _clerk_backend_proxy.clerkFrontendApiProxy)(require_utils.requestToProxyRequest(fastifyRequest), {
|
|
82
|
+
proxyPath,
|
|
83
|
+
publishableKey,
|
|
84
|
+
secretKey
|
|
85
|
+
});
|
|
86
|
+
reply.code(proxyResponse.status);
|
|
87
|
+
proxyResponse.headers.forEach((value, key) => {
|
|
88
|
+
reply.header(key, value);
|
|
89
|
+
});
|
|
90
|
+
if (proxyResponse.body) {
|
|
91
|
+
const reader = proxyResponse.body.getReader();
|
|
92
|
+
const stream$1 = new stream.Readable({ async read() {
|
|
93
|
+
try {
|
|
94
|
+
const { done, value } = await reader.read();
|
|
95
|
+
if (done) this.push(null);
|
|
96
|
+
else this.push(Buffer.from(value));
|
|
97
|
+
} catch (error) {
|
|
98
|
+
this.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
99
|
+
}
|
|
100
|
+
} });
|
|
101
|
+
return reply.send(stream$1);
|
|
102
|
+
}
|
|
103
|
+
return reply.send();
|
|
104
|
+
}
|
|
105
|
+
if (!resolvedProxyUrl) resolvedProxyUrl = proxyPath;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const req = require_utils.fastifyRequestToRequest(fastifyRequest);
|
|
109
|
+
const requestState = await clerkClient.authenticateRequest(req, {
|
|
110
|
+
...options,
|
|
111
|
+
secretKey,
|
|
112
|
+
publishableKey,
|
|
113
|
+
proxyUrl: resolvedProxyUrl,
|
|
114
|
+
acceptsToken: "any"
|
|
115
|
+
});
|
|
116
|
+
requestState.headers.forEach((value, key) => reply.header(key, value));
|
|
117
|
+
if (requestState.headers.get(Headers.Location)) return reply.code(307).send();
|
|
118
|
+
else if (requestState.status === _clerk_backend_internal.AuthStatus.Handshake) throw new Error("Clerk: handshake status without redirect");
|
|
119
|
+
fastifyRequest.auth = requestState.toAuth();
|
|
120
|
+
fastifyRequest.clerk = clerkClient;
|
|
121
|
+
};
|
|
116
122
|
};
|
|
117
123
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
publishableKey,
|
|
128
|
-
secretKey,
|
|
129
|
-
machineSecretKey: options.machineSecretKey || MACHINE_SECRET_KEY,
|
|
130
|
-
apiUrl,
|
|
131
|
-
apiVersion: options.apiVersion || API_VERSION,
|
|
132
|
-
jwtKey: options.jwtKey || JWT_KEY,
|
|
133
|
-
userAgent: options.userAgent || `${SDK_METADATA.name}@${SDK_METADATA.version}`,
|
|
134
|
-
sdkMetadata: options.sdkMetadata || SDK_METADATA
|
|
135
|
-
});
|
|
136
|
-
return async (fastifyRequest, reply) => {
|
|
137
|
-
let resolvedProxyUrl = options.proxyUrl;
|
|
138
|
-
if (frontendApiProxy) {
|
|
139
|
-
const requestUrl = new URL(
|
|
140
|
-
fastifyRequest.url,
|
|
141
|
-
`${fastifyRequest.protocol}://${fastifyRequest.hostname || "localhost"}`
|
|
142
|
-
);
|
|
143
|
-
const isEnabled = typeof frontendApiProxy.enabled === "function" ? frontendApiProxy.enabled(requestUrl) : frontendApiProxy.enabled;
|
|
144
|
-
if (isEnabled) {
|
|
145
|
-
if (requestUrl.pathname === proxyPath || requestUrl.pathname.startsWith(proxyPath + "/")) {
|
|
146
|
-
const proxyRequest = requestToProxyRequest(fastifyRequest);
|
|
147
|
-
const proxyResponse = await (0, import_proxy.clerkFrontendApiProxy)(proxyRequest, {
|
|
148
|
-
proxyPath,
|
|
149
|
-
publishableKey,
|
|
150
|
-
secretKey
|
|
151
|
-
});
|
|
152
|
-
reply.code(proxyResponse.status);
|
|
153
|
-
proxyResponse.headers.forEach((value, key) => {
|
|
154
|
-
reply.header(key, value);
|
|
155
|
-
});
|
|
156
|
-
if (proxyResponse.body) {
|
|
157
|
-
const reader = proxyResponse.body.getReader();
|
|
158
|
-
const stream = new import_stream2.Readable({
|
|
159
|
-
async read() {
|
|
160
|
-
try {
|
|
161
|
-
const { done, value } = await reader.read();
|
|
162
|
-
if (done) {
|
|
163
|
-
this.push(null);
|
|
164
|
-
} else {
|
|
165
|
-
this.push(Buffer.from(value));
|
|
166
|
-
}
|
|
167
|
-
} catch (error) {
|
|
168
|
-
this.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
});
|
|
172
|
-
return reply.send(stream);
|
|
173
|
-
}
|
|
174
|
-
return reply.send();
|
|
175
|
-
}
|
|
176
|
-
if (!resolvedProxyUrl) {
|
|
177
|
-
resolvedProxyUrl = proxyPath;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
const req = fastifyRequestToRequest(fastifyRequest);
|
|
182
|
-
const requestState = await clerkClient2.authenticateRequest(req, {
|
|
183
|
-
...options,
|
|
184
|
-
secretKey,
|
|
185
|
-
publishableKey,
|
|
186
|
-
proxyUrl: resolvedProxyUrl,
|
|
187
|
-
acceptsToken: "any"
|
|
188
|
-
});
|
|
189
|
-
requestState.headers.forEach((value, key) => reply.header(key, value));
|
|
190
|
-
const locationHeader = requestState.headers.get(Headers2.Location);
|
|
191
|
-
if (locationHeader) {
|
|
192
|
-
return reply.code(307).send();
|
|
193
|
-
} else if (requestState.status === import_internal2.AuthStatus.Handshake) {
|
|
194
|
-
throw new Error("Clerk: handshake status without redirect");
|
|
195
|
-
}
|
|
196
|
-
fastifyRequest.auth = requestState.toAuth();
|
|
197
|
-
fastifyRequest.clerk = clerkClient2;
|
|
198
|
-
};
|
|
199
|
-
};
|
|
200
|
-
|
|
201
|
-
// src/clerkPlugin.ts
|
|
202
|
-
var plugin = (instance, opts, done) => {
|
|
203
|
-
instance.decorateRequest("auth", null);
|
|
204
|
-
instance.decorateRequest("clerk", null);
|
|
205
|
-
const hookName = opts.hookName || "preHandler";
|
|
206
|
-
if (!ALLOWED_HOOKS.includes(hookName)) {
|
|
207
|
-
throw new Error(`Unsupported hookName: ${hookName}`);
|
|
208
|
-
}
|
|
209
|
-
instance.addHook(hookName, withClerkMiddleware(opts));
|
|
210
|
-
done();
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/clerkPlugin.ts
|
|
126
|
+
const plugin = (instance, opts, done) => {
|
|
127
|
+
instance.decorateRequest("auth", null);
|
|
128
|
+
instance.decorateRequest("clerk", null);
|
|
129
|
+
const hookName = opts.hookName || "preHandler";
|
|
130
|
+
if (!ALLOWED_HOOKS.includes(hookName)) throw new Error(`Unsupported hookName: ${hookName}`);
|
|
131
|
+
instance.addHook(hookName, withClerkMiddleware(opts));
|
|
132
|
+
done();
|
|
211
133
|
};
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
134
|
+
const clerkPlugin = (0, fastify_plugin.default)(plugin, {
|
|
135
|
+
name: "@clerk/fastify",
|
|
136
|
+
fastify: "5.x"
|
|
215
137
|
});
|
|
216
138
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
var createErrorMessage = (msg) => {
|
|
222
|
-
return `\u{1F512} Clerk: ${msg.trim()}
|
|
139
|
+
//#endregion
|
|
140
|
+
//#region src/errors.ts
|
|
141
|
+
const createErrorMessage = (msg) => {
|
|
142
|
+
return `🔒 Clerk: ${msg.trim()}
|
|
223
143
|
|
|
224
144
|
For more info, check out the docs: https://clerk.com/docs,
|
|
225
145
|
or come say hi in our discord server: https://clerk.com/discord
|
|
226
146
|
`;
|
|
227
147
|
};
|
|
228
|
-
|
|
148
|
+
const pluginRegistrationRequired = createErrorMessage(`The "clerkPlugin" should be registered before using the "getAuth".
|
|
229
149
|
Example:
|
|
230
150
|
|
|
231
151
|
import { clerkPlugin } from '@clerk/fastify';
|
|
@@ -234,31 +154,38 @@ const server: FastifyInstance = Fastify({ logger: true });
|
|
|
234
154
|
server.register(clerkPlugin);
|
|
235
155
|
`);
|
|
236
156
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/getAuth.ts
|
|
159
|
+
const getAuth = ((req, options) => {
|
|
160
|
+
const authReq = req;
|
|
161
|
+
if (!authReq.auth) throw new Error(pluginRegistrationRequired);
|
|
162
|
+
return (0, _clerk_backend_internal.getAuthObjectForAcceptedToken)({
|
|
163
|
+
authObject: authReq.auth,
|
|
164
|
+
acceptsToken: options?.acceptsToken
|
|
165
|
+
});
|
|
244
166
|
});
|
|
245
167
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region src/clerkClient.ts
|
|
170
|
+
const clerkClient = (0, _clerk_backend.createClerkClient)({
|
|
171
|
+
secretKey: SECRET_KEY,
|
|
172
|
+
machineSecretKey: MACHINE_SECRET_KEY,
|
|
173
|
+
apiUrl: API_URL,
|
|
174
|
+
apiVersion: API_VERSION,
|
|
175
|
+
jwtKey: JWT_KEY,
|
|
176
|
+
userAgent: `@clerk/fastify@3.1.36-canary.v20260610190754`,
|
|
177
|
+
sdkMetadata: SDK_METADATA
|
|
256
178
|
});
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
179
|
+
|
|
180
|
+
//#endregion
|
|
181
|
+
exports.clerkClient = clerkClient;
|
|
182
|
+
exports.clerkPlugin = clerkPlugin;
|
|
183
|
+
exports.getAuth = getAuth;
|
|
184
|
+
Object.keys(_clerk_backend).forEach(function (k) {
|
|
185
|
+
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
186
|
+
enumerable: true,
|
|
187
|
+
get: function () { return _clerk_backend[k]; }
|
|
188
|
+
});
|
|
263
189
|
});
|
|
190
|
+
|
|
264
191
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/clerkPlugin.ts","../src/types.ts","../src/withClerkMiddleware.ts","../src/constants.ts","../src/utils.ts","../src/getAuth.ts","../src/errors.ts","../src/clerkClient.ts"],"sourcesContent":["export * from '@clerk/backend';\n\nexport type { ClerkFastifyOptions, FrontendApiProxyOptions } from './types';\n\nexport { clerkPlugin } from './clerkPlugin';\nexport { getAuth } from './getAuth';\nexport { clerkClient } from './clerkClient';\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","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 { 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 { 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 type { FastifyRequest } from 'fastify';\nimport { Readable } from 'stream';\n\nexport const fastifyRequestToRequest = (req: FastifyRequest): Request => {\n const headers = new Headers(\n Object.keys(req.headers).reduce((acc, key) => {\n const value = req.headers[key];\n if (!value) {\n return acc;\n }\n\n if (typeof value === 'string') {\n acc.set(key, value);\n } else {\n acc.set(key, value.join(','));\n }\n return acc;\n }, new Headers()),\n );\n\n // Making some manual tests it seems that FastifyRequest populates the req protocol / hostname\n // based on the forwarded headers. Nevertheless, we are gonna use a dummy base and the request\n // will be fixed by the internals of the clerk/backend package\n const dummyOriginReqUrl = new URL(req.url || '', `${req.protocol}://clerk-dummy`);\n return new Request(dummyOriginReqUrl, {\n method: req.method,\n headers,\n });\n};\n\n/**\n * Converts a Fastify request to a Fetch API Request with full headers and body streaming,\n * suitable for proxy forwarding.\n */\nexport const requestToProxyRequest = (req: FastifyRequest): Request => {\n const headers = new Headers();\n Object.entries(req.headers).forEach(([key, value]) => {\n if (value) {\n headers.set(key, Array.isArray(value) ? value.join(', ') : value);\n }\n });\n\n const forwardedProto = req.headers['x-forwarded-proto'];\n const protoHeader = Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto;\n const proto = (protoHeader || '').split(',')[0].trim();\n const protocol = proto === 'https' || req.protocol === 'https' ? 'https' : 'http';\n\n const forwardedHost = req.headers['x-forwarded-host'];\n const hostHeader = Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost;\n const host = (hostHeader || '').split(',')[0].trim() || req.hostname || 'localhost';\n\n const url = new URL(req.url || '', `${protocol}://${host}`);\n\n const hasBody = ['POST', 'PUT', 'PATCH'].includes(req.method);\n\n return new Request(url.toString(), {\n method: req.method,\n headers,\n body: hasBody ? (Readable.toWeb(req.raw) as ReadableStream) : undefined,\n // @ts-expect-error - duplex required for streaming bodies but not in all TS definitions\n duplex: hasBody ? 'half' : undefined,\n });\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","// 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 { 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,2BAAd;;;ACCA,4BAAe;;;ACQR,IAAM,gBAAgB,CAAC,aAAa,YAAY;;;ACTvD,qBAAkC;AAClC,IAAAA,mBAA2B;AAC3B,mBAAgF;AAChF,IAAAC,mCAAyC;AAEzC,IAAAC,iBAAyB;;;ACLzB,sBAA0B;AAC1B,sCAAyC;AAElC,IAAM,cAAc,QAAQ,IAAI,qBAAqB;AACrD,IAAM,aAAa,QAA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AC,QAAQ,MAAM;AACjB,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC5C;AAEA,aAAO,gDAA8B,EAAE,YAAY,QAAQ,MAAM,cAAc,SAAS,aAAa,CAAC;AACxG;;;AEdA,IAAAC,kBAAkC;AAI3B,IAAM,kBAAc,mCAAkB;AAAA,EAC3C,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,WAAW,GAAG,gBAAY,IAAI,QAAe;AAAA,EAC7C,aAAa;AACf,CAAC;","names":["import_internal","import_apiUrlFromPublishableKey","import_stream","Headers","clerkClient","Headers","fp","import_internal","import_backend"]}
|
|
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;EACA,kBAAkB,QAAQ,oBAAoBC;EAC9C;EAC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