@forklaunch/core 3.4.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/agent/index.js +43 -1
- package/lib/agent/index.js.map +1 -1
- package/lib/agent/index.mjs +43 -1
- package/lib/agent/index.mjs.map +1 -1
- package/lib/cache/interfaces/ttlCache.interface.d.ts +12 -0
- package/lib/cache/interfaces/ttlCache.interface.d.ts.map +1 -1
- package/lib/http/application/expressLikeApplication.d.ts.map +1 -1
- package/lib/http/bindRuntimeAuth.d.ts +27 -1
- package/lib/http/bindRuntimeAuth.d.ts.map +1 -1
- package/lib/http/discriminateAuthMethod.d.ts +2 -1
- package/lib/http/discriminateAuthMethod.d.ts.map +1 -1
- package/lib/http/hmacReplayProtection.d.ts +111 -0
- package/lib/http/hmacReplayProtection.d.ts.map +1 -0
- package/lib/http/index.d.ts +3 -0
- package/lib/http/index.d.ts.map +1 -1
- package/lib/http/index.js +739 -115
- package/lib/http/index.js.map +1 -1
- package/lib/http/index.mjs +682 -77
- package/lib/http/index.mjs.map +1 -1
- package/lib/http/instanceGateway.d.ts.map +1 -1
- package/lib/http/jwtAlgorithms.d.ts +44 -0
- package/lib/http/jwtAlgorithms.d.ts.map +1 -0
- package/lib/http/mcpGenerator/mcpGenerator.d.ts.map +1 -1
- package/lib/http/mcpGenerator/mcpHttpHandler.d.ts +57 -0
- package/lib/http/mcpGenerator/mcpHttpHandler.d.ts.map +1 -0
- package/lib/http/middleware/request/auth.middleware.d.ts.map +1 -1
- package/lib/http/middleware/request/cors.middleware.d.ts +45 -0
- package/lib/http/middleware/request/cors.middleware.d.ts.map +1 -1
- package/lib/http/telemetry/openTelemetryCollector.d.ts.map +1 -1
- package/lib/http/types/contractDetails.types.d.ts +42 -2
- package/lib/http/types/contractDetails.types.d.ts.map +1 -1
- package/lib/http/types/expressLikeOptions.d.ts +22 -1
- package/lib/http/types/expressLikeOptions.d.ts.map +1 -1
- package/package.json +29 -34
package/lib/http/index.js
CHANGED
|
@@ -38,12 +38,17 @@ __export(http_exports, {
|
|
|
38
38
|
ATTR_HTTP_ROUTE: () => import_semantic_conventions.ATTR_HTTP_ROUTE,
|
|
39
39
|
ATTR_SERVICE_NAME: () => import_semantic_conventions.ATTR_SERVICE_NAME,
|
|
40
40
|
AuditLogger: () => AuditLogger,
|
|
41
|
+
DEFAULT_HMAC_MAX_SKEW_MS: () => DEFAULT_HMAC_MAX_SKEW_MS,
|
|
42
|
+
DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES: () => DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES,
|
|
43
|
+
DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS: () => DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
|
|
44
|
+
DEFAULT_SHARED_SECRET_JWT_ALGORITHMS: () => DEFAULT_SHARED_SECRET_JWT_ALGORITHMS,
|
|
41
45
|
EMAIL_LIMITS: () => EMAIL_LIMITS,
|
|
42
46
|
EmailRequestError: () => EmailRequestError,
|
|
43
47
|
ForklaunchExpressLikeApplication: () => ForklaunchExpressLikeApplication,
|
|
44
48
|
ForklaunchExpressLikeRouter: () => ForklaunchExpressLikeRouter,
|
|
45
49
|
HTTPStatuses: () => HTTPStatuses,
|
|
46
50
|
INSTANCE_GATEWAY_MOUNT: () => INSTANCE_GATEWAY_MOUNT,
|
|
51
|
+
InMemoryHmacNonceStore: () => InMemoryHmacNonceStore,
|
|
47
52
|
InstanceGatewayRequestError: () => InstanceGatewayRequestError,
|
|
48
53
|
ModelGatewayRequestError: () => ModelGatewayRequestError,
|
|
49
54
|
OPENAPI_DEFAULT_VERSION: () => OPENAPI_DEFAULT_VERSION,
|
|
@@ -54,6 +59,7 @@ __export(http_exports, {
|
|
|
54
59
|
PinoLogger: () => PinoLogger,
|
|
55
60
|
PlatformEventVerificationError: () => PlatformEventVerificationError,
|
|
56
61
|
RateLimiter: () => RateLimiter,
|
|
62
|
+
SHARED_SECRET_JWT_ALGORITHMS: () => SHARED_SECRET_JWT_ALGORITHMS,
|
|
57
63
|
SMS_MAX_SEGMENTS: () => SMS_MAX_SEGMENTS,
|
|
58
64
|
STRIPE_GATEWAY_ROUTE: () => STRIPE_GATEWAY_ROUTE,
|
|
59
65
|
SmsClient: () => SmsClient,
|
|
@@ -72,6 +78,7 @@ __export(http_exports, {
|
|
|
72
78
|
createHmacToken: () => createHmacToken,
|
|
73
79
|
createInstanceGatewayTransport: () => createInstanceGatewayTransport,
|
|
74
80
|
createLocalModelGatewayClient: () => createLocalModelGatewayClient,
|
|
81
|
+
createMcpHttpHandler: () => createMcpHttpHandler,
|
|
75
82
|
createModelGatewayClient: () => createModelGatewayClient,
|
|
76
83
|
createPaymentsClient: () => createPaymentsClient,
|
|
77
84
|
createPreviewModelGatewayClient: () => createPreviewModelGatewayClient,
|
|
@@ -92,7 +99,10 @@ __export(http_exports, {
|
|
|
92
99
|
get: () => get,
|
|
93
100
|
getCachedJwks: () => getCachedJwks,
|
|
94
101
|
getCodeForStatus: () => getCodeForStatus,
|
|
102
|
+
getMcpTransportHeaders: () => getMcpTransportHeaders,
|
|
95
103
|
head: () => head,
|
|
104
|
+
hmacNonceKey: () => hmacNonceKey,
|
|
105
|
+
hmacNonceTtlMs: () => hmacNonceTtlMs,
|
|
96
106
|
httpErrorsTotalCounter: () => httpErrorsTotalCounter,
|
|
97
107
|
httpRequestDurationMsHistogram: () => httpRequestDurationMsHistogram,
|
|
98
108
|
httpRequestsInFlightCounter: () => httpRequestsInFlightCounter,
|
|
@@ -104,13 +114,18 @@ __export(http_exports, {
|
|
|
104
114
|
isEmailAddress: () => isEmailAddress,
|
|
105
115
|
isForklaunchRequest: () => isForklaunchRequest,
|
|
106
116
|
isForklaunchRouter: () => isForklaunchRouter,
|
|
117
|
+
isHmacTimestampFresh: () => isHmacTimestampFresh,
|
|
107
118
|
isInformational: () => isInformational,
|
|
108
119
|
isManagedInstance: () => isManagedInstance,
|
|
109
120
|
isPortBound: () => isPortBound,
|
|
110
121
|
isRedirection: () => isRedirection,
|
|
122
|
+
isSeparateMcpListener: () => isSeparateMcpListener,
|
|
111
123
|
isServerError: () => isServerError,
|
|
112
124
|
isSuccessful: () => isSuccessful,
|
|
113
125
|
isValidStatusCode: () => isValidStatusCode,
|
|
126
|
+
jwtAlgorithmsForPublicKey: () => jwtAlgorithmsForPublicKey,
|
|
127
|
+
jwtAlgorithmsForSharedSecret: () => jwtAlgorithmsForSharedSecret,
|
|
128
|
+
jwtClaimChecks: () => jwtClaimChecks,
|
|
114
129
|
logger: () => logger,
|
|
115
130
|
meta: () => meta,
|
|
116
131
|
metricsDefinitions: () => metricsDefinitions,
|
|
@@ -123,10 +138,14 @@ __export(http_exports, {
|
|
|
123
138
|
recordRequestAudit: () => recordRequestAudit,
|
|
124
139
|
registerDelegatedSurface: () => registerDelegatedSurface,
|
|
125
140
|
resetProcessHandlersForTesting: () => resetProcessHandlersForTesting,
|
|
141
|
+
resolveHmacMaxSkewMs: () => resolveHmacMaxSkewMs,
|
|
142
|
+
resolveHmacNonceStore: () => resolveHmacNonceStore,
|
|
126
143
|
signPlatformEvent: () => signPlatformEvent,
|
|
127
144
|
smsSegments: () => smsSegments,
|
|
128
145
|
stripeGatewayFetch: () => stripeGatewayFetch,
|
|
146
|
+
timingSafeEqualStrings: () => timingSafeEqualStrings,
|
|
129
147
|
trace: () => trace3,
|
|
148
|
+
ttlCacheHmacNonceStore: () => ttlCacheHmacNonceStore,
|
|
130
149
|
typedAuthHandler: () => typedAuthHandler,
|
|
131
150
|
typedHandler: () => typedHandler,
|
|
132
151
|
validateEmailSendRequest: () => validateEmailSendRequest,
|
|
@@ -138,6 +157,10 @@ __export(http_exports, {
|
|
|
138
157
|
module.exports = __toCommonJS(http_exports);
|
|
139
158
|
|
|
140
159
|
// src/http/bindRuntimeAuth.ts
|
|
160
|
+
var JWT_VERIFICATION_KEYS = ["algorithms", "issuer", "audience"];
|
|
161
|
+
var HMAC_VERIFICATION_KEYS = ["maxSkewMs", "nonceStore"];
|
|
162
|
+
var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
|
|
163
|
+
var isNonEmptyStringList = (value) => Array.isArray(value) && value.length > 0 && value.every(isNonEmptyString);
|
|
141
164
|
function bindRuntimeAuth(details, binding) {
|
|
142
165
|
const policy = { ...details.auth };
|
|
143
166
|
const keys = Object.keys(binding);
|
|
@@ -164,10 +187,26 @@ function bindRuntimeAuth(details, binding) {
|
|
|
164
187
|
let authentication;
|
|
165
188
|
if (policy.scheme === "jwt") {
|
|
166
189
|
if (keys.some(
|
|
167
|
-
(key) => ![
|
|
190
|
+
(key) => ![
|
|
191
|
+
"jwksPublicKeyUrl",
|
|
192
|
+
"signatureKey",
|
|
193
|
+
"decodeResource",
|
|
194
|
+
...JWT_VERIFICATION_KEYS
|
|
195
|
+
].includes(key)
|
|
168
196
|
))
|
|
169
197
|
invalid();
|
|
170
|
-
|
|
198
|
+
for (const key of JWT_VERIFICATION_KEYS) {
|
|
199
|
+
if (credentials[key] === void 0) {
|
|
200
|
+
delete credentials[key];
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const value = credentials[key];
|
|
204
|
+
if (key === "algorithms" ? !isNonEmptyStringList(value) : !isNonEmptyString(value) && !isNonEmptyStringList(value))
|
|
205
|
+
invalid();
|
|
206
|
+
}
|
|
207
|
+
const keyFields = keys.filter(
|
|
208
|
+
(key) => key !== "decodeResource" && !JWT_VERIFICATION_KEYS.includes(key)
|
|
209
|
+
);
|
|
171
210
|
if (keyFields.length !== 1 || typeof credentials[keyFields[0]] !== "string" || !credentials[keyFields[0]])
|
|
172
211
|
invalid();
|
|
173
212
|
const decodeResource = credentials.decodeResource;
|
|
@@ -179,7 +218,13 @@ function bindRuntimeAuth(details, binding) {
|
|
|
179
218
|
...decodeResource === void 0 ? {} : { decodeResource }
|
|
180
219
|
};
|
|
181
220
|
} else if (policy.scheme === "hmac") {
|
|
182
|
-
|
|
221
|
+
const maxSkewMs = credentials.maxSkewMs;
|
|
222
|
+
if (maxSkewMs === void 0) delete credentials.maxSkewMs;
|
|
223
|
+
const nonceStore = credentials.nonceStore;
|
|
224
|
+
if (nonceStore === void 0) delete credentials.nonceStore;
|
|
225
|
+
if (keys.some(
|
|
226
|
+
(key) => key !== "secretKeys" && !HMAC_VERIFICATION_KEYS.includes(key)
|
|
227
|
+
) || maxSkewMs !== void 0 && (typeof maxSkewMs !== "number" || !Number.isFinite(maxSkewMs) || maxSkewMs <= 0) || nonceStore !== void 0 && (nonceStore === null || typeof nonceStore !== "object" || typeof nonceStore.claim !== "function" && typeof nonceStore.putRecordIfAbsent !== "function" && (typeof nonceStore.peekRecord !== "function" || typeof nonceStore.putRecord !== "function")) || !credentials.secretKeys || typeof credentials.secretKeys !== "object" || Array.isArray(credentials.secretKeys) || Object.keys(credentials.secretKeys).length === 0 || Object.values(credentials.secretKeys).some(
|
|
183
228
|
(key) => typeof key !== "string" || !key
|
|
184
229
|
))
|
|
185
230
|
invalid();
|
|
@@ -201,7 +246,72 @@ function bindRuntimeAuth(details, binding) {
|
|
|
201
246
|
|
|
202
247
|
// src/http/middleware/request/cors.middleware.ts
|
|
203
248
|
var import_cors = __toESM(require("cors"));
|
|
249
|
+
var CORS_ORIGINS_ENV = "CORS_ORIGINS";
|
|
250
|
+
var LOCAL_DEVELOPMENT_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/;
|
|
251
|
+
function parseCorsOrigins(value) {
|
|
252
|
+
const origins = [];
|
|
253
|
+
for (const entry of (value ?? "").split(",")) {
|
|
254
|
+
let origin = entry.trim();
|
|
255
|
+
while (origin.length > 1 && origin.endsWith("/")) {
|
|
256
|
+
origin = origin.slice(0, -1);
|
|
257
|
+
}
|
|
258
|
+
if (origin && !origins.includes(origin)) origins.push(origin);
|
|
259
|
+
}
|
|
260
|
+
return origins;
|
|
261
|
+
}
|
|
262
|
+
function isWildcardOrigin(origin) {
|
|
263
|
+
return origin === void 0 || origin === "*";
|
|
264
|
+
}
|
|
265
|
+
function defaultCorsOrigin(env) {
|
|
266
|
+
const listed = parseCorsOrigins(env[CORS_ORIGINS_ENV]);
|
|
267
|
+
if (listed.includes("*")) {
|
|
268
|
+
return { origin: "*", configured: true };
|
|
269
|
+
}
|
|
270
|
+
if (listed.length > 0) {
|
|
271
|
+
return { origin: listed, configured: true };
|
|
272
|
+
}
|
|
273
|
+
return {
|
|
274
|
+
origin: env.NODE_ENV === "production" ? false : LOCAL_DEVELOPMENT_ORIGIN,
|
|
275
|
+
configured: false
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function withoutWildcardCredentials(options2) {
|
|
279
|
+
return options2.credentials === true && isWildcardOrigin(options2.origin) ? { ...options2, credentials: false } : options2;
|
|
280
|
+
}
|
|
281
|
+
function resolveCorsOptions(appCors, env = process.env) {
|
|
282
|
+
const howToConfigure = `Set ${CORS_ORIGINS_ENV} to a comma separated list of allowed origins (for example ${CORS_ORIGINS_ENV}=https://app.example.com), or pass \`cors: { origin: [...] }\` in the application options.`;
|
|
283
|
+
if (appCors !== void 0) {
|
|
284
|
+
if (appCors.credentials === true && isWildcardOrigin(appCors.origin)) {
|
|
285
|
+
return {
|
|
286
|
+
options: appCors,
|
|
287
|
+
warning: "CORS: `credentials: true` is configured with a wildcard origin. Browsers reject that combination, so Access-Control-Allow-Credentials is not sent. To allow credentialed requests, name the origins: pass `cors: { origin: [...], credentials: true }` in the application options."
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
if (appCors.origin === void 0) {
|
|
291
|
+
return {
|
|
292
|
+
options: appCors,
|
|
293
|
+
warning: `CORS: the \`cors\` option was passed without an \`origin\`, which allows EVERY origin (Access-Control-Allow-Origin: *). An empty \`cors: {}\` does this too. To restrict access, pass \`cors: { origin: [...] }\`, or remove the \`cors\` option and set ${CORS_ORIGINS_ENV}. To keep it and silence this warning, say so explicitly with \`cors: { origin: '*' }\`.`
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
return { options: appCors };
|
|
297
|
+
}
|
|
298
|
+
const { origin, configured } = defaultCorsOrigin(env);
|
|
299
|
+
if (configured) {
|
|
300
|
+
return { options: { origin } };
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
options: { origin },
|
|
304
|
+
warning: "CORS: no allowed origins are configured, so " + (env.NODE_ENV === "production" ? "browsers on other origins cannot call this service. " : "only browsers on localhost can call this service (and none will in production). ") + howToConfigure
|
|
305
|
+
};
|
|
306
|
+
}
|
|
204
307
|
function cors(corsOptions) {
|
|
308
|
+
const configuredOrigin = corsOptions.origin;
|
|
309
|
+
const staticHandler = (0, import_cors.default)(withoutWildcardCredentials(corsOptions));
|
|
310
|
+
const wildcardHandler = (0, import_cors.default)({
|
|
311
|
+
...corsOptions,
|
|
312
|
+
origin: "*",
|
|
313
|
+
credentials: false
|
|
314
|
+
});
|
|
205
315
|
return (req, res, next) => {
|
|
206
316
|
if (req.method === "OPTIONS") {
|
|
207
317
|
res.cors = true;
|
|
@@ -211,17 +321,27 @@ function cors(corsOptions) {
|
|
|
211
321
|
return res.getHeaders()[key];
|
|
212
322
|
};
|
|
213
323
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
324
|
+
const corsRequest = req;
|
|
325
|
+
const done = next ?? (() => {
|
|
326
|
+
});
|
|
327
|
+
if (corsOptions.credentials === true && typeof configuredOrigin === "function") {
|
|
328
|
+
configuredOrigin(corsRequest.headers.origin, (error, origin) => {
|
|
329
|
+
if (error || !origin) {
|
|
330
|
+
done(error ?? void 0);
|
|
331
|
+
} else if (origin === "*") {
|
|
332
|
+
wildcardHandler(corsRequest, res, done);
|
|
333
|
+
} else {
|
|
334
|
+
(0, import_cors.default)({ ...corsOptions, origin })(corsRequest, res, done);
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
staticHandler(corsRequest, res, done);
|
|
220
340
|
};
|
|
221
341
|
}
|
|
222
342
|
|
|
223
343
|
// src/http/router/expressLikeRouter.ts
|
|
224
|
-
var
|
|
344
|
+
var import_common11 = require("@forklaunch/common");
|
|
225
345
|
|
|
226
346
|
// src/http/guards/hasPermissionChecks.ts
|
|
227
347
|
function hasPermissionChecks(maybePermissionedAuth) {
|
|
@@ -570,13 +690,15 @@ new import_sdk_node.NodeSDK({
|
|
|
570
690
|
url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/traces`,
|
|
571
691
|
headers: otelHeaders
|
|
572
692
|
}),
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
693
|
+
metricReaders: [
|
|
694
|
+
new import_sdk_metrics.PeriodicExportingMetricReader({
|
|
695
|
+
exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter({
|
|
696
|
+
url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/metrics`,
|
|
697
|
+
headers: otelHeaders
|
|
698
|
+
}),
|
|
699
|
+
exportIntervalMillis: 5e3
|
|
700
|
+
})
|
|
701
|
+
],
|
|
580
702
|
logRecordProcessors: [
|
|
581
703
|
new import_sdk_logs.BatchLogRecordProcessor({
|
|
582
704
|
exporter: new import_exporter_logs_otlp_http.OTLPLogExporter({
|
|
@@ -791,7 +913,7 @@ function discriminateResponseBodies(schemaValidator, responses) {
|
|
|
791
913
|
}
|
|
792
914
|
|
|
793
915
|
// src/http/router/routerSharedLogic.ts
|
|
794
|
-
var
|
|
916
|
+
var import_common10 = require("@forklaunch/common");
|
|
795
917
|
|
|
796
918
|
// src/http/guards/hasVersionedSchema.ts
|
|
797
919
|
function hasVersionedSchema(contractDetails) {
|
|
@@ -818,11 +940,10 @@ function isHttpContractDetails(maybeContractDetails) {
|
|
|
818
940
|
}
|
|
819
941
|
|
|
820
942
|
// src/http/middleware/request/auth.middleware.ts
|
|
821
|
-
var
|
|
943
|
+
var import_common6 = require("@forklaunch/common");
|
|
822
944
|
var import_validator = require("@forklaunch/validator");
|
|
823
945
|
|
|
824
946
|
// src/http/discriminateAuthMethod.ts
|
|
825
|
-
var import_common6 = require("@forklaunch/common");
|
|
826
947
|
var import_jose = require("jose");
|
|
827
948
|
|
|
828
949
|
// src/http/createHmacToken.ts
|
|
@@ -848,6 +969,227 @@ ${nonce}`
|
|
|
848
969
|
return hmac.digest("base64");
|
|
849
970
|
}
|
|
850
971
|
|
|
972
|
+
// src/http/hmacReplayProtection.ts
|
|
973
|
+
var import_crypto2 = require("crypto");
|
|
974
|
+
var DEFAULT_HMAC_MAX_SKEW_MS = 5 * 60 * 1e3;
|
|
975
|
+
var DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES = 1e5;
|
|
976
|
+
function timingSafeEqualStrings(expected, received) {
|
|
977
|
+
if (typeof expected !== "string" || typeof received !== "string") {
|
|
978
|
+
return false;
|
|
979
|
+
}
|
|
980
|
+
const expectedBytes = Buffer.from(expected);
|
|
981
|
+
const receivedBytes = Buffer.from(received);
|
|
982
|
+
return expectedBytes.length === receivedBytes.length && (0, import_crypto2.timingSafeEqual)(expectedBytes, receivedBytes);
|
|
983
|
+
}
|
|
984
|
+
function resolveHmacMaxSkewMs(maxSkewMs) {
|
|
985
|
+
return typeof maxSkewMs === "number" && Number.isFinite(maxSkewMs) && maxSkewMs > 0 ? maxSkewMs : DEFAULT_HMAC_MAX_SKEW_MS;
|
|
986
|
+
}
|
|
987
|
+
function isHmacTimestampFresh(timestamp, nowMs, maxSkewMs = DEFAULT_HMAC_MAX_SKEW_MS) {
|
|
988
|
+
if (!(timestamp instanceof Date)) return false;
|
|
989
|
+
const at = timestamp.getTime();
|
|
990
|
+
return !Number.isNaN(at) && Math.abs(nowMs - at) <= maxSkewMs;
|
|
991
|
+
}
|
|
992
|
+
function hmacNonceTtlMs(timestamp, nowMs, maxSkewMs) {
|
|
993
|
+
return Math.max(1, timestamp.getTime() + maxSkewMs - nowMs);
|
|
994
|
+
}
|
|
995
|
+
function hmacNonceKey(keyId, nonce) {
|
|
996
|
+
const id = keyId ?? "";
|
|
997
|
+
return `${id.length}:${id}${nonce}`;
|
|
998
|
+
}
|
|
999
|
+
var InMemoryHmacNonceStore = class {
|
|
1000
|
+
entries = /* @__PURE__ */ new Map();
|
|
1001
|
+
maxEntries;
|
|
1002
|
+
sweepIntervalMs;
|
|
1003
|
+
lastSweepAt = 0;
|
|
1004
|
+
constructor(options2 = {}) {
|
|
1005
|
+
this.maxEntries = typeof options2.maxEntries === "number" && options2.maxEntries >= 1 ? Math.floor(options2.maxEntries) : DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES;
|
|
1006
|
+
this.sweepIntervalMs = options2.sweepIntervalMs ?? 3e4;
|
|
1007
|
+
}
|
|
1008
|
+
/** Number of nonces currently held (expired ones may linger until swept). */
|
|
1009
|
+
get size() {
|
|
1010
|
+
return this.entries.size;
|
|
1011
|
+
}
|
|
1012
|
+
claim(key, ttlMs, nowMs = Date.now()) {
|
|
1013
|
+
const expiresAt = this.entries.get(key);
|
|
1014
|
+
if (expiresAt !== void 0 && expiresAt > nowMs) {
|
|
1015
|
+
return false;
|
|
1016
|
+
}
|
|
1017
|
+
if (this.entries.size >= this.maxEntries || nowMs - this.lastSweepAt >= this.sweepIntervalMs) {
|
|
1018
|
+
this.sweep(nowMs);
|
|
1019
|
+
}
|
|
1020
|
+
this.entries.delete(key);
|
|
1021
|
+
while (this.entries.size >= this.maxEntries) {
|
|
1022
|
+
const oldest = this.entries.keys().next();
|
|
1023
|
+
if (oldest.done) break;
|
|
1024
|
+
this.entries.delete(oldest.value);
|
|
1025
|
+
}
|
|
1026
|
+
this.entries.set(key, nowMs + Math.max(1, ttlMs));
|
|
1027
|
+
return true;
|
|
1028
|
+
}
|
|
1029
|
+
sweep(nowMs) {
|
|
1030
|
+
this.lastSweepAt = nowMs;
|
|
1031
|
+
for (const [key, expiresAt] of this.entries) {
|
|
1032
|
+
if (expiresAt <= nowMs) this.entries.delete(key);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
function ttlCacheHmacNonceStore(cache, keyPrefix = "hmac-nonce:") {
|
|
1037
|
+
return {
|
|
1038
|
+
async claim(key, ttlMs) {
|
|
1039
|
+
const record2 = {
|
|
1040
|
+
key: `${keyPrefix}${key}`,
|
|
1041
|
+
value: 1,
|
|
1042
|
+
ttlMilliseconds: Math.max(1, Math.ceil(ttlMs))
|
|
1043
|
+
};
|
|
1044
|
+
if (typeof cache.putRecordIfAbsent === "function") {
|
|
1045
|
+
return await cache.putRecordIfAbsent(record2) === true;
|
|
1046
|
+
}
|
|
1047
|
+
if (await cache.peekRecord(record2.key)) {
|
|
1048
|
+
return false;
|
|
1049
|
+
}
|
|
1050
|
+
await cache.putRecord(record2);
|
|
1051
|
+
return true;
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
var defaultHmacNonceStore = new InMemoryHmacNonceStore();
|
|
1056
|
+
var adaptedTtlCaches = /* @__PURE__ */ new WeakMap();
|
|
1057
|
+
function resolveHmacNonceStore(configured) {
|
|
1058
|
+
if (configured == null) {
|
|
1059
|
+
return defaultHmacNonceStore;
|
|
1060
|
+
}
|
|
1061
|
+
if (typeof configured.claim === "function") {
|
|
1062
|
+
return configured;
|
|
1063
|
+
}
|
|
1064
|
+
const cache = configured;
|
|
1065
|
+
if (typeof cache.putRecordIfAbsent !== "function" && (typeof cache.peekRecord !== "function" || typeof cache.putRecord !== "function")) {
|
|
1066
|
+
throw new Error(
|
|
1067
|
+
"hmac.nonceStore must be an HmacNonceStore ({ claim }) or a TtlCache"
|
|
1068
|
+
);
|
|
1069
|
+
}
|
|
1070
|
+
let adapted = adaptedTtlCaches.get(cache);
|
|
1071
|
+
if (!adapted) {
|
|
1072
|
+
adapted = ttlCacheHmacNonceStore(cache);
|
|
1073
|
+
adaptedTtlCaches.set(cache, adapted);
|
|
1074
|
+
}
|
|
1075
|
+
return adapted;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// src/http/jwtAlgorithms.ts
|
|
1079
|
+
var SHARED_SECRET_JWT_ALGORITHMS = [
|
|
1080
|
+
"HS256",
|
|
1081
|
+
"HS384",
|
|
1082
|
+
"HS512"
|
|
1083
|
+
];
|
|
1084
|
+
var DEFAULT_SHARED_SECRET_JWT_ALGORITHMS = [
|
|
1085
|
+
"HS256"
|
|
1086
|
+
];
|
|
1087
|
+
var RSA_JWT_ALGORITHMS = [
|
|
1088
|
+
"RS256",
|
|
1089
|
+
"RS384",
|
|
1090
|
+
"RS512",
|
|
1091
|
+
"PS256",
|
|
1092
|
+
"PS384",
|
|
1093
|
+
"PS512"
|
|
1094
|
+
];
|
|
1095
|
+
var EC_CURVE_JWT_ALGORITHMS = {
|
|
1096
|
+
"P-256": ["ES256"],
|
|
1097
|
+
"P-384": ["ES384"],
|
|
1098
|
+
"P-521": ["ES512"]
|
|
1099
|
+
};
|
|
1100
|
+
var OKP_CURVE_JWT_ALGORITHMS = {
|
|
1101
|
+
Ed25519: ["EdDSA", "Ed25519"]
|
|
1102
|
+
};
|
|
1103
|
+
function isSymmetricOrUnsigned(algorithm) {
|
|
1104
|
+
const normalized = algorithm.toUpperCase();
|
|
1105
|
+
return normalized === "NONE" || normalized.startsWith("HS");
|
|
1106
|
+
}
|
|
1107
|
+
function configuredList(configured) {
|
|
1108
|
+
if (configured == null) return void 0;
|
|
1109
|
+
if (!Array.isArray(configured)) {
|
|
1110
|
+
throw new Error("JWT `algorithms` must be an array of algorithm names");
|
|
1111
|
+
}
|
|
1112
|
+
return configured.filter(
|
|
1113
|
+
(algorithm) => typeof algorithm === "string"
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
function jwtAlgorithmsForSharedSecret(configured) {
|
|
1117
|
+
const requested = configuredList(configured);
|
|
1118
|
+
if (requested === void 0) {
|
|
1119
|
+
return [...DEFAULT_SHARED_SECRET_JWT_ALGORITHMS];
|
|
1120
|
+
}
|
|
1121
|
+
const allowed = SHARED_SECRET_JWT_ALGORITHMS.filter(
|
|
1122
|
+
(algorithm) => requested.includes(algorithm)
|
|
1123
|
+
);
|
|
1124
|
+
if (allowed.length === 0) {
|
|
1125
|
+
throw new Error(
|
|
1126
|
+
"No usable JWT algorithm: a `signatureKey` verifies only HS256, HS384 or HS512"
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
return allowed;
|
|
1130
|
+
}
|
|
1131
|
+
function algorithmsFittingPublicKey(key) {
|
|
1132
|
+
let fitting;
|
|
1133
|
+
switch (key.kty) {
|
|
1134
|
+
case "RSA":
|
|
1135
|
+
fitting = RSA_JWT_ALGORITHMS;
|
|
1136
|
+
break;
|
|
1137
|
+
case "EC":
|
|
1138
|
+
fitting = EC_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
|
|
1139
|
+
break;
|
|
1140
|
+
case "OKP":
|
|
1141
|
+
fitting = OKP_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
|
|
1142
|
+
break;
|
|
1143
|
+
case "AKP":
|
|
1144
|
+
fitting = typeof key.alg === "string" ? [key.alg] : [];
|
|
1145
|
+
break;
|
|
1146
|
+
default:
|
|
1147
|
+
fitting = [];
|
|
1148
|
+
}
|
|
1149
|
+
if (typeof key.alg === "string") {
|
|
1150
|
+
fitting = fitting.filter((algorithm) => algorithm === key.alg);
|
|
1151
|
+
}
|
|
1152
|
+
return fitting.filter((algorithm) => !isSymmetricOrUnsigned(algorithm));
|
|
1153
|
+
}
|
|
1154
|
+
function jwtAlgorithmsForPublicKey(key, configured) {
|
|
1155
|
+
if (key == null || typeof key !== "object") {
|
|
1156
|
+
throw new Error("No usable JWT algorithm: the verification key is missing");
|
|
1157
|
+
}
|
|
1158
|
+
if (key.kty === "oct") {
|
|
1159
|
+
throw new Error(
|
|
1160
|
+
"No usable JWT algorithm: a symmetric (oct) key cannot be used as a public key; use `signatureKey` for a shared secret"
|
|
1161
|
+
);
|
|
1162
|
+
}
|
|
1163
|
+
const requested = configuredList(configured);
|
|
1164
|
+
const allowed = algorithmsFittingPublicKey(key).filter(
|
|
1165
|
+
(algorithm) => requested === void 0 || requested.includes(algorithm)
|
|
1166
|
+
);
|
|
1167
|
+
if (allowed.length === 0) {
|
|
1168
|
+
throw new Error(
|
|
1169
|
+
"No usable JWT algorithm: none of the permitted asymmetric algorithms fits this public key"
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
return allowed;
|
|
1173
|
+
}
|
|
1174
|
+
function claimExpectation(name, value) {
|
|
1175
|
+
if (value === void 0) return void 0;
|
|
1176
|
+
const values = typeof value === "string" ? [value] : value;
|
|
1177
|
+
if (!Array.isArray(values) || values.length === 0 || values.some((entry) => typeof entry !== "string" || entry.length === 0)) {
|
|
1178
|
+
throw new Error(
|
|
1179
|
+
`JWT \`${name}\` is configured but empty; set it to the expected value or remove it`
|
|
1180
|
+
);
|
|
1181
|
+
}
|
|
1182
|
+
return typeof value === "string" ? value : [...values];
|
|
1183
|
+
}
|
|
1184
|
+
function jwtClaimChecks(config) {
|
|
1185
|
+
const issuer = claimExpectation("issuer", config.issuer);
|
|
1186
|
+
const audience = claimExpectation("audience", config.audience);
|
|
1187
|
+
return {
|
|
1188
|
+
...issuer === void 0 ? {} : { issuer },
|
|
1189
|
+
...audience === void 0 ? {} : { audience }
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
|
|
851
1193
|
// src/http/guards/isBasicAuthMethod.ts
|
|
852
1194
|
function isBasicAuthMethod(maybeBasicAuthMethod) {
|
|
853
1195
|
return typeof maybeBasicAuthMethod === "object" && maybeBasicAuthMethod !== null && "basic" in maybeBasicAuthMethod && maybeBasicAuthMethod.basic != null;
|
|
@@ -901,11 +1243,16 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
901
1243
|
} else if (isJwtAuthMethod(auth)) {
|
|
902
1244
|
const jwt = auth.jwt;
|
|
903
1245
|
let verificationFunction;
|
|
1246
|
+
const claimChecks = () => jwtClaimChecks(jwt);
|
|
904
1247
|
if ("signatureKey" in jwt) {
|
|
905
1248
|
verificationFunction = async (token) => {
|
|
906
1249
|
const { payload } = await (0, import_jose.jwtVerify)(
|
|
907
1250
|
token,
|
|
908
|
-
new Uint8Array(Buffer.from(jwt.signatureKey))
|
|
1251
|
+
new Uint8Array(Buffer.from(jwt.signatureKey)),
|
|
1252
|
+
{
|
|
1253
|
+
...claimChecks(),
|
|
1254
|
+
algorithms: jwtAlgorithmsForSharedSecret(jwt.algorithms)
|
|
1255
|
+
}
|
|
909
1256
|
);
|
|
910
1257
|
return payload;
|
|
911
1258
|
};
|
|
@@ -920,7 +1267,10 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
920
1267
|
let lastError;
|
|
921
1268
|
for (const key of jwks) {
|
|
922
1269
|
try {
|
|
923
|
-
const { payload } = await (0, import_jose.jwtVerify)(token, key
|
|
1270
|
+
const { payload } = await (0, import_jose.jwtVerify)(token, key, {
|
|
1271
|
+
...claimChecks(),
|
|
1272
|
+
algorithms: jwtAlgorithmsForPublicKey(key, jwt.algorithms)
|
|
1273
|
+
});
|
|
924
1274
|
return payload;
|
|
925
1275
|
} catch (error) {
|
|
926
1276
|
lastError = error;
|
|
@@ -941,10 +1291,19 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
941
1291
|
}
|
|
942
1292
|
};
|
|
943
1293
|
} else if (isHmacMethod(auth)) {
|
|
1294
|
+
const maxSkewMs = resolveHmacMaxSkewMs(auth.hmac.maxSkewMs);
|
|
1295
|
+
const configuredNonceStore = auth.hmac.nonceStore;
|
|
944
1296
|
authMethod = {
|
|
945
1297
|
type: "hmac",
|
|
946
1298
|
auth: {
|
|
947
1299
|
secretKeys: auth.hmac.secretKeys,
|
|
1300
|
+
/**
|
|
1301
|
+
* Accepts a signed request only when its timestamp is inside the
|
|
1302
|
+
* skew window, its signature matches (constant-time compare) and
|
|
1303
|
+
* its nonce has not been used before. The nonce is claimed last, and
|
|
1304
|
+
* only for a valid signature, so a `false` for one candidate path
|
|
1305
|
+
* never burns the nonce for the next.
|
|
1306
|
+
*/
|
|
948
1307
|
verificationFunction: async ({
|
|
949
1308
|
method,
|
|
950
1309
|
path,
|
|
@@ -952,8 +1311,30 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
952
1311
|
timestamp,
|
|
953
1312
|
nonce,
|
|
954
1313
|
signature,
|
|
955
|
-
secretKey
|
|
1314
|
+
secretKey,
|
|
1315
|
+
keyId
|
|
956
1316
|
}) => {
|
|
1317
|
+
const reject = (reason) => {
|
|
1318
|
+
openTelemetryCollector?.debug("[HMAC Verification Failed]", {
|
|
1319
|
+
reason,
|
|
1320
|
+
method,
|
|
1321
|
+
path,
|
|
1322
|
+
keyId,
|
|
1323
|
+
timestamp: timestamp instanceof Date && !Number.isNaN(timestamp.getTime()) ? timestamp.toISOString() : "invalid",
|
|
1324
|
+
bodyType: body ? typeof body : "undefined"
|
|
1325
|
+
});
|
|
1326
|
+
return false;
|
|
1327
|
+
};
|
|
1328
|
+
if (typeof secretKey !== "string" || secretKey.length === 0) {
|
|
1329
|
+
return reject("unknown key");
|
|
1330
|
+
}
|
|
1331
|
+
if (typeof nonce !== "string" || nonce.length === 0 || typeof signature !== "string") {
|
|
1332
|
+
return reject("missing nonce or signature");
|
|
1333
|
+
}
|
|
1334
|
+
const now = Date.now();
|
|
1335
|
+
if (!isHmacTimestampFresh(timestamp, now, maxSkewMs)) {
|
|
1336
|
+
return reject("stale or invalid timestamp");
|
|
1337
|
+
}
|
|
957
1338
|
const computedSignature = createHmacToken({
|
|
958
1339
|
method,
|
|
959
1340
|
path,
|
|
@@ -962,23 +1343,26 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
962
1343
|
nonce,
|
|
963
1344
|
secretKey
|
|
964
1345
|
});
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
const errorInfo = {
|
|
968
|
-
method,
|
|
969
|
-
path,
|
|
970
|
-
timestamp: timestamp.toISOString(),
|
|
971
|
-
nonce,
|
|
972
|
-
receivedSignature: signature,
|
|
973
|
-
computedSignature
|
|
974
|
-
};
|
|
975
|
-
openTelemetryCollector?.debug("[HMAC Verification Failed]", {
|
|
976
|
-
...errorInfo,
|
|
977
|
-
bodyType: body ? typeof body : "undefined",
|
|
978
|
-
body: body ? (0, import_common6.safeStringify)(body) : "undefined"
|
|
979
|
-
});
|
|
1346
|
+
if (!timingSafeEqualStrings(computedSignature, signature)) {
|
|
1347
|
+
return reject("signature mismatch");
|
|
980
1348
|
}
|
|
981
|
-
|
|
1349
|
+
let firstUse;
|
|
1350
|
+
try {
|
|
1351
|
+
firstUse = await resolveHmacNonceStore(configuredNonceStore).claim(
|
|
1352
|
+
hmacNonceKey(keyId, nonce),
|
|
1353
|
+
hmacNonceTtlMs(timestamp, now, maxSkewMs)
|
|
1354
|
+
);
|
|
1355
|
+
} catch (error) {
|
|
1356
|
+
openTelemetryCollector?.error(
|
|
1357
|
+
"[HMAC Nonce Store Failed]",
|
|
1358
|
+
error instanceof Error ? error.message : String(error)
|
|
1359
|
+
);
|
|
1360
|
+
return reject("nonce store unavailable");
|
|
1361
|
+
}
|
|
1362
|
+
if (firstUse !== true) {
|
|
1363
|
+
return reject("replayed nonce");
|
|
1364
|
+
}
|
|
1365
|
+
return true;
|
|
982
1366
|
}
|
|
983
1367
|
}
|
|
984
1368
|
};
|
|
@@ -1000,7 +1384,7 @@ function hasSubscriptionChecks(maybeSubscriptionAuth) {
|
|
|
1000
1384
|
}
|
|
1001
1385
|
|
|
1002
1386
|
// src/http/middleware/request/authLogContext.ts
|
|
1003
|
-
var
|
|
1387
|
+
var import_crypto3 = require("crypto");
|
|
1004
1388
|
var import_jose2 = require("jose");
|
|
1005
1389
|
var FINGERPRINT_LENGTH = 8;
|
|
1006
1390
|
var MAX_CLAIM_LENGTH = 128;
|
|
@@ -1013,7 +1397,7 @@ function authLogContext(headerValue) {
|
|
|
1013
1397
|
}
|
|
1014
1398
|
const context2 = {
|
|
1015
1399
|
hasToken: true,
|
|
1016
|
-
tokenFingerprint: (0,
|
|
1400
|
+
tokenFingerprint: (0, import_crypto3.createHash)("sha256").update(headerValue).digest("hex").slice(0, FINGERPRINT_LENGTH)
|
|
1017
1401
|
};
|
|
1018
1402
|
const parts = headerValue.trim().split(/\s+/);
|
|
1019
1403
|
const candidate = parts[parts.length - 1];
|
|
@@ -1139,6 +1523,18 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
|
|
|
1139
1523
|
if (!parsedKeyId || !parsedTimestamp || !parsedNonce || !parsedSignature) {
|
|
1140
1524
|
return invalidAuthorizationTokenFormat;
|
|
1141
1525
|
}
|
|
1526
|
+
const requestTimestamp = new Date(parsedTimestamp);
|
|
1527
|
+
if (Number.isNaN(requestTimestamp.getTime())) {
|
|
1528
|
+
return invalidAuthorizationTokenFormat;
|
|
1529
|
+
}
|
|
1530
|
+
const secretKeys = collapsedAuthorizationMethod.hmac.secretKeys;
|
|
1531
|
+
const secretKey = Object.prototype.hasOwnProperty.call(
|
|
1532
|
+
secretKeys,
|
|
1533
|
+
parsedKeyId
|
|
1534
|
+
) ? secretKeys[parsedKeyId] : void 0;
|
|
1535
|
+
if (typeof secretKey !== "string" || secretKey.length === 0) {
|
|
1536
|
+
return invalidAuthorizationSignature;
|
|
1537
|
+
}
|
|
1142
1538
|
let verificationResult = false;
|
|
1143
1539
|
const signedPaths = hmacSignedPaths(req);
|
|
1144
1540
|
for (const path of signedPaths) {
|
|
@@ -1146,10 +1542,11 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
|
|
|
1146
1542
|
method: req?.method ?? "",
|
|
1147
1543
|
path,
|
|
1148
1544
|
body: req?._rawBody ?? req?.body,
|
|
1149
|
-
timestamp:
|
|
1545
|
+
timestamp: requestTimestamp,
|
|
1150
1546
|
nonce: parsedNonce,
|
|
1151
1547
|
signature: parsedSignature,
|
|
1152
|
-
secretKey
|
|
1548
|
+
secretKey,
|
|
1549
|
+
keyId: parsedKeyId
|
|
1153
1550
|
}));
|
|
1154
1551
|
if (verificationResult) {
|
|
1155
1552
|
if (path !== signedPaths[0]) warnMountRelativeHmacPath();
|
|
@@ -1210,7 +1607,7 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
|
|
|
1210
1607
|
break;
|
|
1211
1608
|
}
|
|
1212
1609
|
default:
|
|
1213
|
-
(0,
|
|
1610
|
+
(0, import_common6.isNever)(type);
|
|
1214
1611
|
return [401, "Invalid Authorization method."];
|
|
1215
1612
|
}
|
|
1216
1613
|
if (isHmacMethod(collapsedAuthorizationMethod) && sessionPayload == null) {
|
|
@@ -1368,10 +1765,10 @@ async function parseRequestAuth(req, res, next) {
|
|
|
1368
1765
|
}
|
|
1369
1766
|
|
|
1370
1767
|
// src/http/middleware/request/enrichDetails.middleware.ts
|
|
1371
|
-
var
|
|
1768
|
+
var import_common8 = require("@forklaunch/common");
|
|
1372
1769
|
|
|
1373
1770
|
// src/http/telemetry/requestAudit.ts
|
|
1374
|
-
var
|
|
1771
|
+
var import_common7 = require("@forklaunch/common");
|
|
1375
1772
|
|
|
1376
1773
|
// src/persistence/encryptedType.ts
|
|
1377
1774
|
var import_core = require("@mikro-orm/core");
|
|
@@ -1402,7 +1799,7 @@ var SLOTS = globalThis[/* @__PURE__ */ Symbol.for("forklaunch.compliance.slots")
|
|
|
1402
1799
|
var LOADED_TENANTS = globalThis[/* @__PURE__ */ Symbol.for("forklaunch.compliance.loadedTenants")] ??= /* @__PURE__ */ new WeakMap();
|
|
1403
1800
|
|
|
1404
1801
|
// src/http/telemetry/auditLogger.ts
|
|
1405
|
-
var
|
|
1802
|
+
var import_crypto4 = require("crypto");
|
|
1406
1803
|
var AuditLogger = class {
|
|
1407
1804
|
_otel;
|
|
1408
1805
|
constructor(otel) {
|
|
@@ -1435,13 +1832,13 @@ var AuditLogger = class {
|
|
|
1435
1832
|
if (body === void 0 || body === null || body === "") {
|
|
1436
1833
|
return "";
|
|
1437
1834
|
}
|
|
1438
|
-
return (0,
|
|
1835
|
+
return (0, import_crypto4.createHash)("sha256").update(body).digest("hex");
|
|
1439
1836
|
}
|
|
1440
1837
|
};
|
|
1441
1838
|
|
|
1442
1839
|
// src/http/telemetry/requestAudit.ts
|
|
1443
1840
|
function auditEnabled() {
|
|
1444
|
-
return (0,
|
|
1841
|
+
return (0, import_common7.getEnvVar)("FORKLAUNCH_AUDIT") !== "off";
|
|
1445
1842
|
}
|
|
1446
1843
|
var loggers = /* @__PURE__ */ new WeakMap();
|
|
1447
1844
|
function loggerFor(otel) {
|
|
@@ -1548,8 +1945,8 @@ function enrichDetails(path, contractDetails, requestSchema, responseSchemas, op
|
|
|
1548
1945
|
const [seconds, nanoseconds] = process.hrtime(startTime);
|
|
1549
1946
|
const durationMs = seconds + nanoseconds / 1e9;
|
|
1550
1947
|
httpServerDurationHistogram.record(durationMs, {
|
|
1551
|
-
[import_semantic_conventions.ATTR_SERVICE_NAME]: (0,
|
|
1552
|
-
[ATTR_APPLICATION_ID]: (0,
|
|
1948
|
+
[import_semantic_conventions.ATTR_SERVICE_NAME]: (0, import_common8.getEnvVar)("OTEL_SERVICE_NAME") || "unknown",
|
|
1949
|
+
[ATTR_APPLICATION_ID]: (0, import_common8.getEnvVar)("OTEL_APPLICATION_ID"),
|
|
1553
1950
|
[ATTR_API_NAME]: req.contractDetails?.name || "unknown",
|
|
1554
1951
|
[import_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: req.method,
|
|
1555
1952
|
[import_semantic_conventions.ATTR_HTTP_ROUTE]: req.originalPath || "unknown",
|
|
@@ -1561,7 +1958,7 @@ function enrichDetails(path, contractDetails, requestSchema, responseSchemas, op
|
|
|
1561
1958
|
}
|
|
1562
1959
|
|
|
1563
1960
|
// src/http/middleware/request/parse.middleware.ts
|
|
1564
|
-
var
|
|
1961
|
+
var import_common9 = require("@forklaunch/common");
|
|
1565
1962
|
var import_validator2 = require("@forklaunch/validator");
|
|
1566
1963
|
|
|
1567
1964
|
// src/http/guards/hasSend.ts
|
|
@@ -1605,7 +2002,7 @@ function parse(req, res, next) {
|
|
|
1605
2002
|
let parsedRequest;
|
|
1606
2003
|
let collectedParseErrors;
|
|
1607
2004
|
if (req.contractDetails.versions) {
|
|
1608
|
-
if ((0,
|
|
2005
|
+
if ((0, import_common9.isRecord)(req.requestSchema)) {
|
|
1609
2006
|
let runningParseErrors = "";
|
|
1610
2007
|
matchedVersions = [];
|
|
1611
2008
|
Object.entries(req.requestSchema).forEach(([version, schema]) => {
|
|
@@ -1835,13 +2232,13 @@ function compileRouteSchemas(contractDetails, schemaValidator) {
|
|
|
1835
2232
|
versionedContractDetails,
|
|
1836
2233
|
contractDetails.params
|
|
1837
2234
|
);
|
|
1838
|
-
if ((0,
|
|
2235
|
+
if ((0, import_common10.isRecord)(requestSchema)) {
|
|
1839
2236
|
requestSchema = {
|
|
1840
2237
|
...requestSchema,
|
|
1841
2238
|
[version]: versionedRequestSchema
|
|
1842
2239
|
};
|
|
1843
2240
|
}
|
|
1844
|
-
if ((0,
|
|
2241
|
+
if ((0, import_common10.isRecord)(responseSchemas)) {
|
|
1845
2242
|
responseSchemas = {
|
|
1846
2243
|
...responseSchemas,
|
|
1847
2244
|
[version]: versionedResponseSchemas
|
|
@@ -2237,8 +2634,8 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2237
2634
|
...middlewares,
|
|
2238
2635
|
this.#parseAndRunControllerHandler(controllerHandler)
|
|
2239
2636
|
);
|
|
2240
|
-
(0,
|
|
2241
|
-
...this._fetchMap[(0,
|
|
2637
|
+
(0, import_common11.toRecord)(this._fetchMap)[(0, import_common11.sanitizePathSlashes)(`${this.basePath}${path}`)] = {
|
|
2638
|
+
...this._fetchMap[(0, import_common11.sanitizePathSlashes)(`${this.basePath}${path}`)] ?? {},
|
|
2242
2639
|
[method.toUpperCase()]: contractDetails.versions ? Object.fromEntries(
|
|
2243
2640
|
Object.keys(contractDetails.versions).map((version) => [
|
|
2244
2641
|
version,
|
|
@@ -2261,7 +2658,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2261
2658
|
};
|
|
2262
2659
|
const contractDetailsName = contractDetails.name;
|
|
2263
2660
|
if (contractDetailsName) {
|
|
2264
|
-
(0,
|
|
2661
|
+
(0, import_common11.toRecord)(this.sdk)[(0, import_common11.toPrettyCamelCase)(contractDetailsName)] = contractDetails.versions ? Object.fromEntries(
|
|
2265
2662
|
Object.keys(contractDetails.versions).map((version) => [
|
|
2266
2663
|
version,
|
|
2267
2664
|
(req) => this.#localParamRequest(
|
|
@@ -2365,10 +2762,10 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2365
2762
|
}
|
|
2366
2763
|
addRouterToSdk(router) {
|
|
2367
2764
|
Object.entries(router._fetchMap).map(
|
|
2368
|
-
([key, value]) => (0,
|
|
2765
|
+
([key, value]) => (0, import_common11.toRecord)(this._fetchMap)[(0, import_common11.sanitizePathSlashes)(`${this.basePath}${key}`)] = value
|
|
2369
2766
|
);
|
|
2370
|
-
const existingSdk = this.sdk[router.sdkName ?? (0,
|
|
2371
|
-
(0,
|
|
2767
|
+
const existingSdk = this.sdk[router.sdkName ?? (0, import_common11.toPrettyCamelCase)(router.basePath)];
|
|
2768
|
+
(0, import_common11.toRecord)(this.sdk)[router.sdkName ?? (0, import_common11.toPrettyCamelCase)(router.basePath)] = {
|
|
2372
2769
|
...typeof existingSdk === "object" ? existingSdk : {},
|
|
2373
2770
|
...router.sdk
|
|
2374
2771
|
};
|
|
@@ -2700,7 +3097,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2700
3097
|
unpackSdks(sdks, path, routerUniquenessCache) {
|
|
2701
3098
|
Object.entries(sdks).forEach(([key, maybeHandler]) => {
|
|
2702
3099
|
if (isSdkHandler(maybeHandler)) {
|
|
2703
|
-
const cacheKey = (0,
|
|
3100
|
+
const cacheKey = (0, import_common11.hashString)((0, import_common11.safeStringify)(maybeHandler));
|
|
2704
3101
|
if (routerUniquenessCache.has(cacheKey)) {
|
|
2705
3102
|
throw new Error(`SDK handler ${key} is already registered`);
|
|
2706
3103
|
}
|
|
@@ -2745,6 +3142,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2745
3142
|
};
|
|
2746
3143
|
|
|
2747
3144
|
// src/http/application/expressLikeApplication.ts
|
|
3145
|
+
var warnedAboutCorsDefaults = false;
|
|
2748
3146
|
var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter {
|
|
2749
3147
|
/**
|
|
2750
3148
|
* Creates an instance of the Application class.
|
|
@@ -2769,7 +3167,14 @@ var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter
|
|
|
2769
3167
|
this.postEnrichMiddleware = postEnrichMiddleware;
|
|
2770
3168
|
this.openTelemetryCollector = openTelemetryCollector;
|
|
2771
3169
|
this.appOptions = appOptions;
|
|
2772
|
-
|
|
3170
|
+
const { options: corsOptions, warning: corsWarning } = resolveCorsOptions(
|
|
3171
|
+
this.appOptions?.cors
|
|
3172
|
+
);
|
|
3173
|
+
if (corsWarning && !warnedAboutCorsDefaults) {
|
|
3174
|
+
warnedAboutCorsDefaults = true;
|
|
3175
|
+
this.openTelemetryCollector.warn(corsWarning);
|
|
3176
|
+
}
|
|
3177
|
+
this.internal.use(cors(corsOptions));
|
|
2773
3178
|
}
|
|
2774
3179
|
schemaValidator;
|
|
2775
3180
|
internal;
|
|
@@ -2807,7 +3212,7 @@ function isPortBound(port, host = "localhost") {
|
|
|
2807
3212
|
}
|
|
2808
3213
|
|
|
2809
3214
|
// src/http/generateHmacAuthHeaders.ts
|
|
2810
|
-
var
|
|
3215
|
+
var import_crypto5 = require("crypto");
|
|
2811
3216
|
function generateHmacAuthHeaders({
|
|
2812
3217
|
secretKey,
|
|
2813
3218
|
method,
|
|
@@ -2816,7 +3221,7 @@ function generateHmacAuthHeaders({
|
|
|
2816
3221
|
keyId = "default"
|
|
2817
3222
|
}) {
|
|
2818
3223
|
const timestamp = /* @__PURE__ */ new Date();
|
|
2819
|
-
const nonce = (0,
|
|
3224
|
+
const nonce = (0, import_crypto5.randomUUID)();
|
|
2820
3225
|
const signature = createHmacToken({
|
|
2821
3226
|
secretKey,
|
|
2822
3227
|
method,
|
|
@@ -2831,11 +3236,10 @@ function generateHmacAuthHeaders({
|
|
|
2831
3236
|
}
|
|
2832
3237
|
|
|
2833
3238
|
// src/http/instanceGateway.ts
|
|
2834
|
-
var import_crypto5 = require("crypto");
|
|
2835
3239
|
var INSTANCE_GATEWAY_MOUNT = "/instance-gateway";
|
|
2836
3240
|
var PLATFORM_EVENT_KEY_ID = "platform";
|
|
2837
3241
|
var PLATFORM_EVENTS_PATH = "/platform-events";
|
|
2838
|
-
var MAX_SKEW_MS =
|
|
3242
|
+
var MAX_SKEW_MS = DEFAULT_HMAC_MAX_SKEW_MS;
|
|
2839
3243
|
var InstanceGatewayRequestError = class extends Error {
|
|
2840
3244
|
constructor(status, message, retryAfterSeconds) {
|
|
2841
3245
|
super(message);
|
|
@@ -2914,7 +3318,7 @@ function createInstanceGatewayTransport(options2 = {}, feature) {
|
|
|
2914
3318
|
var PlatformEventVerificationError = class extends Error {
|
|
2915
3319
|
name = "PlatformEventVerificationError";
|
|
2916
3320
|
};
|
|
2917
|
-
var seenEventNonces =
|
|
3321
|
+
var seenEventNonces = new InMemoryHmacNonceStore();
|
|
2918
3322
|
function verifyPlatformEvent(request, options2 = {}) {
|
|
2919
3323
|
const hmacKey = options2.hmacKey ?? process.env.INSTANCE_HMAC_KEY;
|
|
2920
3324
|
if (!hmacKey) {
|
|
@@ -2938,30 +3342,27 @@ function verifyPlatformEvent(request, options2 = {}) {
|
|
|
2938
3342
|
}
|
|
2939
3343
|
const timestamp = new Date(ts);
|
|
2940
3344
|
const now = (options2.now ?? Date.now)();
|
|
2941
|
-
if (
|
|
3345
|
+
if (!isHmacTimestampFresh(timestamp, now, MAX_SKEW_MS)) {
|
|
2942
3346
|
throw new PlatformEventVerificationError("Stale or invalid timestamp");
|
|
2943
3347
|
}
|
|
2944
|
-
const expected =
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
);
|
|
2954
|
-
const received = Buffer.from(signature);
|
|
2955
|
-
if (expected.length !== received.length || !(0, import_crypto5.timingSafeEqual)(expected, received)) {
|
|
3348
|
+
const expected = createHmacToken({
|
|
3349
|
+
secretKey: hmacKey,
|
|
3350
|
+
method: request.method.toUpperCase(),
|
|
3351
|
+
path: request.path,
|
|
3352
|
+
body: request.body,
|
|
3353
|
+
timestamp,
|
|
3354
|
+
nonce
|
|
3355
|
+
});
|
|
3356
|
+
if (!timingSafeEqualStrings(expected, signature)) {
|
|
2956
3357
|
throw new PlatformEventVerificationError("Invalid signature");
|
|
2957
3358
|
}
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
3359
|
+
if (!seenEventNonces.claim(
|
|
3360
|
+
hmacNonceKey(keyId, nonce),
|
|
3361
|
+
hmacNonceTtlMs(timestamp, now, MAX_SKEW_MS),
|
|
3362
|
+
now
|
|
3363
|
+
)) {
|
|
2962
3364
|
throw new PlatformEventVerificationError("Replayed delivery");
|
|
2963
3365
|
}
|
|
2964
|
-
seenEventNonces.set(nonce, now);
|
|
2965
3366
|
const parsed = typeof request.body === "string" || Buffer.isBuffer(request.body) ? JSON.parse(request.body.toString()) : request.body;
|
|
2966
3367
|
const event = parsed;
|
|
2967
3368
|
if (!event || typeof event.id !== "string" || typeof event.type !== "string" || typeof event.feature !== "string") {
|
|
@@ -4877,7 +5278,7 @@ var getCodeForStatus = (status) => {
|
|
|
4877
5278
|
var httpStatusCodes_default = HTTPStatuses;
|
|
4878
5279
|
|
|
4879
5280
|
// src/http/mcpGenerator/mcpGenerator.ts
|
|
4880
|
-
var
|
|
5281
|
+
var import_common12 = require("@forklaunch/common");
|
|
4881
5282
|
var import_zod = require("@forklaunch/validator/zod");
|
|
4882
5283
|
var import_fastmcp = require("fastmcp");
|
|
4883
5284
|
|
|
@@ -4899,6 +5300,182 @@ function unpackRouters(routers, recursiveBasePath = []) {
|
|
|
4899
5300
|
}, []);
|
|
4900
5301
|
}
|
|
4901
5302
|
|
|
5303
|
+
// src/http/mcpGenerator/mcpHttpHandler.ts
|
|
5304
|
+
var import_webStandardStreamableHttp = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
|
|
5305
|
+
var import_async_hooks = require("async_hooks");
|
|
5306
|
+
var import_crypto6 = require("crypto");
|
|
5307
|
+
var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
|
|
5308
|
+
var mcpTransportHeaders = new import_async_hooks.AsyncLocalStorage();
|
|
5309
|
+
function getMcpTransportHeaders() {
|
|
5310
|
+
return mcpTransportHeaders.getStore();
|
|
5311
|
+
}
|
|
5312
|
+
function createMcpHttpHandler(mcpServer, options2) {
|
|
5313
|
+
const mode = options2?.sessions ?? "stateless";
|
|
5314
|
+
if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
|
|
5315
|
+
throw new Error(
|
|
5316
|
+
"Stateful MCP sessions live in one process's memory and cannot be shared across workers. Use mcp.sessions: 'stateless' or a single worker."
|
|
5317
|
+
);
|
|
5318
|
+
}
|
|
5319
|
+
const idleTimeoutMs = options2?.sessionIdleTimeoutMs ?? DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS;
|
|
5320
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
5321
|
+
const jsonRpcError = (status, code, message, headers) => new Response(
|
|
5322
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }),
|
|
5323
|
+
{
|
|
5324
|
+
status,
|
|
5325
|
+
headers: { "Content-Type": "application/json", ...headers }
|
|
5326
|
+
}
|
|
5327
|
+
);
|
|
5328
|
+
let sweepTimer;
|
|
5329
|
+
if (mode === "stateful") {
|
|
5330
|
+
sweepTimer = setInterval(
|
|
5331
|
+
() => {
|
|
5332
|
+
const cutoff = Date.now() - idleTimeoutMs;
|
|
5333
|
+
for (const [id, entry] of sessions) {
|
|
5334
|
+
if (entry.lastSeen < cutoff) {
|
|
5335
|
+
sessions.delete(id);
|
|
5336
|
+
entry.session.close().catch(() => void 0);
|
|
5337
|
+
}
|
|
5338
|
+
}
|
|
5339
|
+
},
|
|
5340
|
+
Math.min(idleTimeoutMs, 6e4)
|
|
5341
|
+
);
|
|
5342
|
+
sweepTimer.unref();
|
|
5343
|
+
}
|
|
5344
|
+
async function authenticateRequest(authRequest) {
|
|
5345
|
+
if (!options2?.authenticate) {
|
|
5346
|
+
return { ok: true, auth: void 0 };
|
|
5347
|
+
}
|
|
5348
|
+
try {
|
|
5349
|
+
const auth = await options2.authenticate(authRequest);
|
|
5350
|
+
return auth ? { ok: true, auth } : { ok: false };
|
|
5351
|
+
} catch {
|
|
5352
|
+
return { ok: false };
|
|
5353
|
+
}
|
|
5354
|
+
}
|
|
5355
|
+
async function handleStateless(request, auth) {
|
|
5356
|
+
if (request.method !== "POST") {
|
|
5357
|
+
return jsonRpcError(405, -32e3, "Method not allowed", {
|
|
5358
|
+
Allow: "POST"
|
|
5359
|
+
});
|
|
5360
|
+
}
|
|
5361
|
+
const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
|
|
5362
|
+
sessionIdGenerator: void 0
|
|
5363
|
+
});
|
|
5364
|
+
const session = await mcpServer.connect(transport, auth);
|
|
5365
|
+
let closed = false;
|
|
5366
|
+
const closeSession = () => {
|
|
5367
|
+
if (!closed) {
|
|
5368
|
+
closed = true;
|
|
5369
|
+
session.close().catch(() => void 0);
|
|
5370
|
+
}
|
|
5371
|
+
};
|
|
5372
|
+
try {
|
|
5373
|
+
const response = await mcpTransportHeaders.run(
|
|
5374
|
+
request.headers,
|
|
5375
|
+
() => transport.handleRequest(request)
|
|
5376
|
+
);
|
|
5377
|
+
return closeWhenBodyEnds(response, closeSession);
|
|
5378
|
+
} catch (error) {
|
|
5379
|
+
closeSession();
|
|
5380
|
+
throw error;
|
|
5381
|
+
}
|
|
5382
|
+
}
|
|
5383
|
+
async function handleStateful(request, auth) {
|
|
5384
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
5385
|
+
if (sessionId) {
|
|
5386
|
+
const entry = sessions.get(sessionId);
|
|
5387
|
+
if (!entry) {
|
|
5388
|
+
return jsonRpcError(404, -32001, "Session not found");
|
|
5389
|
+
}
|
|
5390
|
+
entry.lastSeen = Date.now();
|
|
5391
|
+
if (auth) {
|
|
5392
|
+
entry.session.updateAuth(auth);
|
|
5393
|
+
}
|
|
5394
|
+
return mcpTransportHeaders.run(
|
|
5395
|
+
request.headers,
|
|
5396
|
+
() => entry.transport.handleRequest(request)
|
|
5397
|
+
);
|
|
5398
|
+
}
|
|
5399
|
+
const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
|
|
5400
|
+
sessionIdGenerator: () => (0, import_crypto6.randomUUID)(),
|
|
5401
|
+
onsessioninitialized: (id) => {
|
|
5402
|
+
sessions.set(id, { transport, session, lastSeen: Date.now() });
|
|
5403
|
+
},
|
|
5404
|
+
onsessionclosed: (id) => {
|
|
5405
|
+
sessions.delete(id);
|
|
5406
|
+
}
|
|
5407
|
+
});
|
|
5408
|
+
const session = await mcpServer.connect(transport, auth);
|
|
5409
|
+
transport.onclose = /* @__PURE__ */ ((onclose) => () => {
|
|
5410
|
+
if (transport.sessionId) {
|
|
5411
|
+
sessions.delete(transport.sessionId);
|
|
5412
|
+
}
|
|
5413
|
+
onclose?.();
|
|
5414
|
+
})(transport.onclose);
|
|
5415
|
+
const response = await mcpTransportHeaders.run(
|
|
5416
|
+
request.headers,
|
|
5417
|
+
() => transport.handleRequest(request)
|
|
5418
|
+
);
|
|
5419
|
+
if (!transport.sessionId) {
|
|
5420
|
+
await session.close();
|
|
5421
|
+
}
|
|
5422
|
+
return response;
|
|
5423
|
+
}
|
|
5424
|
+
async function handle(request, authRequest) {
|
|
5425
|
+
const authResult = await authenticateRequest(authRequest);
|
|
5426
|
+
if (!authResult.ok) {
|
|
5427
|
+
return jsonRpcError(401, -32001, "Unauthorized", {
|
|
5428
|
+
"WWW-Authenticate": "Bearer"
|
|
5429
|
+
});
|
|
5430
|
+
}
|
|
5431
|
+
return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
|
|
5432
|
+
}
|
|
5433
|
+
async function close() {
|
|
5434
|
+
if (sweepTimer) {
|
|
5435
|
+
clearInterval(sweepTimer);
|
|
5436
|
+
}
|
|
5437
|
+
const entries = [...sessions.values()];
|
|
5438
|
+
sessions.clear();
|
|
5439
|
+
await Promise.all(entries.map(({ session }) => session.close()));
|
|
5440
|
+
}
|
|
5441
|
+
return { handle, close, sessions };
|
|
5442
|
+
}
|
|
5443
|
+
function closeWhenBodyEnds(response, done) {
|
|
5444
|
+
if (!response.body) {
|
|
5445
|
+
done();
|
|
5446
|
+
return response;
|
|
5447
|
+
}
|
|
5448
|
+
const reader = response.body.getReader();
|
|
5449
|
+
const body = new ReadableStream({
|
|
5450
|
+
async pull(controller) {
|
|
5451
|
+
try {
|
|
5452
|
+
const { done: finished, value } = await reader.read();
|
|
5453
|
+
if (finished) {
|
|
5454
|
+
controller.close();
|
|
5455
|
+
done();
|
|
5456
|
+
} else {
|
|
5457
|
+
controller.enqueue(value);
|
|
5458
|
+
}
|
|
5459
|
+
} catch (error) {
|
|
5460
|
+
controller.error(error);
|
|
5461
|
+
done();
|
|
5462
|
+
}
|
|
5463
|
+
},
|
|
5464
|
+
cancel(reason) {
|
|
5465
|
+
done();
|
|
5466
|
+
return reader.cancel(reason);
|
|
5467
|
+
}
|
|
5468
|
+
});
|
|
5469
|
+
return new Response(body, {
|
|
5470
|
+
status: response.status,
|
|
5471
|
+
statusText: response.statusText,
|
|
5472
|
+
headers: response.headers
|
|
5473
|
+
});
|
|
5474
|
+
}
|
|
5475
|
+
function isSeparateMcpListener(configuredPort) {
|
|
5476
|
+
return process.env.MCP_LISTENER === "separate" || configuredPort != null || Boolean(Number(process.env.MCP_PORT));
|
|
5477
|
+
}
|
|
5478
|
+
|
|
4902
5479
|
// src/http/mcpGenerator/mcpGenerator.ts
|
|
4903
5480
|
function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
|
|
4904
5481
|
let discriminatedBody;
|
|
@@ -4928,6 +5505,36 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
|
|
|
4928
5505
|
} : {}
|
|
4929
5506
|
});
|
|
4930
5507
|
}
|
|
5508
|
+
function buildRouteHeaders(toolHeaders, contentType) {
|
|
5509
|
+
const transportHeaders = getMcpTransportHeaders();
|
|
5510
|
+
const routeHeaders = new Headers();
|
|
5511
|
+
const authorization = transportHeaders?.get("authorization");
|
|
5512
|
+
if (authorization) {
|
|
5513
|
+
routeHeaders.set("authorization", authorization);
|
|
5514
|
+
}
|
|
5515
|
+
for (const [name, value] of Object.entries(toolHeaders ?? {})) {
|
|
5516
|
+
if (value != null) {
|
|
5517
|
+
routeHeaders.set(name, String(value));
|
|
5518
|
+
}
|
|
5519
|
+
}
|
|
5520
|
+
const correlationId = transportHeaders?.get("x-correlation-id");
|
|
5521
|
+
if (correlationId) {
|
|
5522
|
+
routeHeaders.set("x-correlation-id", correlationId);
|
|
5523
|
+
}
|
|
5524
|
+
const traceparent = transportHeaders?.get("traceparent");
|
|
5525
|
+
if (traceparent) {
|
|
5526
|
+
routeHeaders.set("traceparent", traceparent);
|
|
5527
|
+
routeHeaders.delete("tracestate");
|
|
5528
|
+
const tracestate = transportHeaders?.get("tracestate");
|
|
5529
|
+
if (tracestate) {
|
|
5530
|
+
routeHeaders.set("tracestate", tracestate);
|
|
5531
|
+
}
|
|
5532
|
+
}
|
|
5533
|
+
if (contentType !== void 0) {
|
|
5534
|
+
routeHeaders.set("content-type", contentType);
|
|
5535
|
+
}
|
|
5536
|
+
return routeHeaders;
|
|
5537
|
+
}
|
|
4931
5538
|
function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate) {
|
|
4932
5539
|
if (!(schemaValidator instanceof import_zod.ZodSchemaValidator)) {
|
|
4933
5540
|
throw new Error(
|
|
@@ -5020,12 +5627,12 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
5020
5627
|
break;
|
|
5021
5628
|
}
|
|
5022
5629
|
case "file": {
|
|
5023
|
-
parsedBody = Buffer.from((0,
|
|
5630
|
+
parsedBody = Buffer.from((0, import_common12.safeStringify)(body));
|
|
5024
5631
|
break;
|
|
5025
5632
|
}
|
|
5026
5633
|
case "multipart": {
|
|
5027
5634
|
const formData = new FormData();
|
|
5028
|
-
if ((0,
|
|
5635
|
+
if ((0, import_common12.isRecord)(body)) {
|
|
5029
5636
|
for (const key in body) {
|
|
5030
5637
|
if (typeof body[key] === "string") {
|
|
5031
5638
|
if (schemaValidator.isInstanceOf(
|
|
@@ -5050,11 +5657,11 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
5050
5657
|
break;
|
|
5051
5658
|
}
|
|
5052
5659
|
case "urlEncoded": {
|
|
5053
|
-
if ((0,
|
|
5660
|
+
if ((0, import_common12.isRecord)(body)) {
|
|
5054
5661
|
parsedBody = new URLSearchParams(
|
|
5055
5662
|
Object.entries(body).map(([key, value]) => [
|
|
5056
5663
|
key,
|
|
5057
|
-
(0,
|
|
5664
|
+
(0, import_common12.safeStringify)(value)
|
|
5058
5665
|
])
|
|
5059
5666
|
);
|
|
5060
5667
|
} else {
|
|
@@ -5063,8 +5670,8 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
5063
5670
|
break;
|
|
5064
5671
|
}
|
|
5065
5672
|
default: {
|
|
5066
|
-
(0,
|
|
5067
|
-
parsedBody = (0,
|
|
5673
|
+
(0, import_common12.isNever)(discriminatedBody.parserType);
|
|
5674
|
+
parsedBody = (0, import_common12.safeStringify)(body);
|
|
5068
5675
|
break;
|
|
5069
5676
|
}
|
|
5070
5677
|
}
|
|
@@ -5073,19 +5680,17 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
5073
5680
|
const queryString = new URLSearchParams(
|
|
5074
5681
|
Object.entries(query).map(([key, value]) => [
|
|
5075
5682
|
key,
|
|
5076
|
-
(0,
|
|
5683
|
+
(0, import_common12.safeStringify)(value)
|
|
5077
5684
|
])
|
|
5078
5685
|
).toString();
|
|
5079
5686
|
url += queryString ? `?${queryString}` : "";
|
|
5080
5687
|
}
|
|
5081
5688
|
const response = await fetch(url, {
|
|
5082
5689
|
method: route.method.toUpperCase(),
|
|
5083
|
-
headers:
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
} : {}
|
|
5088
|
-
},
|
|
5690
|
+
headers: buildRouteHeaders(
|
|
5691
|
+
headers,
|
|
5692
|
+
discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
|
|
5693
|
+
),
|
|
5089
5694
|
body: parsedBody
|
|
5090
5695
|
});
|
|
5091
5696
|
if (response.status >= 300) {
|
|
@@ -5106,7 +5711,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
5106
5711
|
content: [
|
|
5107
5712
|
{
|
|
5108
5713
|
type: "text",
|
|
5109
|
-
text: (0,
|
|
5714
|
+
text: (0, import_common12.safeStringify)(await response.json())
|
|
5110
5715
|
}
|
|
5111
5716
|
]
|
|
5112
5717
|
};
|
|
@@ -5289,20 +5894,20 @@ ${parseErrors.join("\n\n")}`
|
|
|
5289
5894
|
}
|
|
5290
5895
|
|
|
5291
5896
|
// src/http/middleware/response/enrichExpressLikeSend.middleware.ts
|
|
5292
|
-
var
|
|
5897
|
+
var import_common14 = require("@forklaunch/common");
|
|
5293
5898
|
var import_stream = require("stream");
|
|
5294
5899
|
|
|
5295
5900
|
// src/http/telemetry/recordMetric.ts
|
|
5296
|
-
var
|
|
5901
|
+
var import_common13 = require("@forklaunch/common");
|
|
5297
5902
|
var import_semantic_conventions4 = require("@opentelemetry/semantic-conventions");
|
|
5298
5903
|
function recordMetric(req, res) {
|
|
5299
5904
|
if (res.metricRecorded) {
|
|
5300
5905
|
return;
|
|
5301
5906
|
}
|
|
5302
|
-
const serviceName = (0,
|
|
5907
|
+
const serviceName = (0, import_common13.getEnvVar)("OTEL_SERVICE_NAME") || "unknown";
|
|
5303
5908
|
const attrs = {
|
|
5304
5909
|
[import_semantic_conventions4.ATTR_SERVICE_NAME]: serviceName,
|
|
5305
|
-
[ATTR_APPLICATION_ID]: (0,
|
|
5910
|
+
[ATTR_APPLICATION_ID]: (0, import_common13.getEnvVar)("OTEL_APPLICATION_ID"),
|
|
5306
5911
|
[ATTR_API_NAME]: req.contractDetails?.name,
|
|
5307
5912
|
[import_semantic_conventions4.ATTR_HTTP_REQUEST_METHOD]: req.method,
|
|
5308
5913
|
[import_semantic_conventions4.ATTR_HTTP_ROUTE]: req.originalPath,
|
|
@@ -5354,15 +5959,15 @@ function enrichExpressLikeSend(instance, req, res, originalOperation, originalSe
|
|
|
5354
5959
|
`attachment; filename="${data.name}"`
|
|
5355
5960
|
);
|
|
5356
5961
|
}
|
|
5357
|
-
if ((0,
|
|
5358
|
-
import_stream.Readable.from((0,
|
|
5962
|
+
if ((0, import_common14.isNodeJsWriteableStream)(res)) {
|
|
5963
|
+
import_stream.Readable.from((0, import_common14.readableStreamToAsyncIterable)(data.stream())).pipe(res);
|
|
5359
5964
|
} else {
|
|
5360
5965
|
res.type("text/plain");
|
|
5361
5966
|
res.status(500);
|
|
5362
5967
|
originalSend.call(instance, "Not a NodeJS WritableStream");
|
|
5363
5968
|
errorSent = true;
|
|
5364
5969
|
}
|
|
5365
|
-
} else if ((0,
|
|
5970
|
+
} else if ((0, import_common14.isAsyncGenerator)(data)) {
|
|
5366
5971
|
let firstPass = true;
|
|
5367
5972
|
const transformer = new import_stream.Transform({
|
|
5368
5973
|
objectMode: true,
|
|
@@ -5386,7 +5991,7 @@ ${res.locals.errorMessage}`;
|
|
|
5386
5991
|
} else {
|
|
5387
5992
|
let data2 = "";
|
|
5388
5993
|
for (const [key, value] of Object.entries(chunk)) {
|
|
5389
|
-
data2 += `${key}: ${typeof value === "string" ? value : (0,
|
|
5994
|
+
data2 += `${key}: ${typeof value === "string" ? value : (0, import_common14.safeStringify)(value)}
|
|
5390
5995
|
`;
|
|
5391
5996
|
}
|
|
5392
5997
|
data2 += "\n";
|
|
@@ -5397,7 +6002,7 @@ ${res.locals.errorMessage}`;
|
|
|
5397
6002
|
} else if (!errorSent) {
|
|
5398
6003
|
let data2 = "";
|
|
5399
6004
|
for (const [key, value] of Object.entries(chunk)) {
|
|
5400
|
-
data2 += `${key}: ${typeof value === "string" ? value : (0,
|
|
6005
|
+
data2 += `${key}: ${typeof value === "string" ? value : (0, import_common14.safeStringify)(value)}
|
|
5401
6006
|
`;
|
|
5402
6007
|
}
|
|
5403
6008
|
data2 += "\n";
|
|
@@ -5405,7 +6010,7 @@ ${res.locals.errorMessage}`;
|
|
|
5405
6010
|
}
|
|
5406
6011
|
}
|
|
5407
6012
|
});
|
|
5408
|
-
if ((0,
|
|
6013
|
+
if ((0, import_common14.isNodeJsWriteableStream)(res)) {
|
|
5409
6014
|
import_stream.Readable.from(data).pipe(transformer).pipe(res);
|
|
5410
6015
|
} else {
|
|
5411
6016
|
res.type("text/plain");
|
|
@@ -5416,7 +6021,7 @@ ${res.locals.errorMessage}`;
|
|
|
5416
6021
|
} else {
|
|
5417
6022
|
const parserType = responseBodies?.[Number(res.statusCode)]?.parserType;
|
|
5418
6023
|
res.bodyData = data;
|
|
5419
|
-
if ((0,
|
|
6024
|
+
if ((0, import_common14.isRecord)(data)) {
|
|
5420
6025
|
switch (parserType) {
|
|
5421
6026
|
case "json":
|
|
5422
6027
|
res.bodyData = "json" in data ? data.json : data;
|
|
@@ -5437,7 +6042,7 @@ ${res.locals.errorMessage}`;
|
|
|
5437
6042
|
res.bodyData = data;
|
|
5438
6043
|
break;
|
|
5439
6044
|
default:
|
|
5440
|
-
(0,
|
|
6045
|
+
(0, import_common14.isNever)(parserType);
|
|
5441
6046
|
res.bodyData = data;
|
|
5442
6047
|
break;
|
|
5443
6048
|
}
|
|
@@ -5472,7 +6077,7 @@ ${res.locals.errorMessage}`;
|
|
|
5472
6077
|
}
|
|
5473
6078
|
|
|
5474
6079
|
// src/http/openApiV3Generator/openApiV3Generator.ts
|
|
5475
|
-
var
|
|
6080
|
+
var import_common15 = require("@forklaunch/common");
|
|
5476
6081
|
var OPENAPI_DEFAULT_VERSION = /* @__PURE__ */ Symbol("default");
|
|
5477
6082
|
function toUpperCase(str) {
|
|
5478
6083
|
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
@@ -5699,7 +6304,7 @@ function generateOpenApiSpecs(schemaValidator, serverUrls, serverDescriptions, a
|
|
|
5699
6304
|
].forEach(({ fullPath, router }) => {
|
|
5700
6305
|
const controllerName = transformBasePath(fullPath);
|
|
5701
6306
|
router.routes.forEach((route) => {
|
|
5702
|
-
const openApiPath = (0,
|
|
6307
|
+
const openApiPath = (0, import_common15.openApiCompliantPath)(
|
|
5703
6308
|
`${fullPath}${route.path === "/" ? "" : route.path}`
|
|
5704
6309
|
);
|
|
5705
6310
|
const { name, summary, params, versions, auth, options: options2 } = route.contractDetails;
|
|
@@ -6045,12 +6650,17 @@ function createLocalModelGatewayClient(options2 = {}) {
|
|
|
6045
6650
|
ATTR_HTTP_ROUTE,
|
|
6046
6651
|
ATTR_SERVICE_NAME,
|
|
6047
6652
|
AuditLogger,
|
|
6653
|
+
DEFAULT_HMAC_MAX_SKEW_MS,
|
|
6654
|
+
DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES,
|
|
6655
|
+
DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
|
|
6656
|
+
DEFAULT_SHARED_SECRET_JWT_ALGORITHMS,
|
|
6048
6657
|
EMAIL_LIMITS,
|
|
6049
6658
|
EmailRequestError,
|
|
6050
6659
|
ForklaunchExpressLikeApplication,
|
|
6051
6660
|
ForklaunchExpressLikeRouter,
|
|
6052
6661
|
HTTPStatuses,
|
|
6053
6662
|
INSTANCE_GATEWAY_MOUNT,
|
|
6663
|
+
InMemoryHmacNonceStore,
|
|
6054
6664
|
InstanceGatewayRequestError,
|
|
6055
6665
|
ModelGatewayRequestError,
|
|
6056
6666
|
OPENAPI_DEFAULT_VERSION,
|
|
@@ -6061,6 +6671,7 @@ function createLocalModelGatewayClient(options2 = {}) {
|
|
|
6061
6671
|
PinoLogger,
|
|
6062
6672
|
PlatformEventVerificationError,
|
|
6063
6673
|
RateLimiter,
|
|
6674
|
+
SHARED_SECRET_JWT_ALGORITHMS,
|
|
6064
6675
|
SMS_MAX_SEGMENTS,
|
|
6065
6676
|
STRIPE_GATEWAY_ROUTE,
|
|
6066
6677
|
SmsClient,
|
|
@@ -6079,6 +6690,7 @@ function createLocalModelGatewayClient(options2 = {}) {
|
|
|
6079
6690
|
createHmacToken,
|
|
6080
6691
|
createInstanceGatewayTransport,
|
|
6081
6692
|
createLocalModelGatewayClient,
|
|
6693
|
+
createMcpHttpHandler,
|
|
6082
6694
|
createModelGatewayClient,
|
|
6083
6695
|
createPaymentsClient,
|
|
6084
6696
|
createPreviewModelGatewayClient,
|
|
@@ -6099,7 +6711,10 @@ function createLocalModelGatewayClient(options2 = {}) {
|
|
|
6099
6711
|
get,
|
|
6100
6712
|
getCachedJwks,
|
|
6101
6713
|
getCodeForStatus,
|
|
6714
|
+
getMcpTransportHeaders,
|
|
6102
6715
|
head,
|
|
6716
|
+
hmacNonceKey,
|
|
6717
|
+
hmacNonceTtlMs,
|
|
6103
6718
|
httpErrorsTotalCounter,
|
|
6104
6719
|
httpRequestDurationMsHistogram,
|
|
6105
6720
|
httpRequestsInFlightCounter,
|
|
@@ -6111,13 +6726,18 @@ function createLocalModelGatewayClient(options2 = {}) {
|
|
|
6111
6726
|
isEmailAddress,
|
|
6112
6727
|
isForklaunchRequest,
|
|
6113
6728
|
isForklaunchRouter,
|
|
6729
|
+
isHmacTimestampFresh,
|
|
6114
6730
|
isInformational,
|
|
6115
6731
|
isManagedInstance,
|
|
6116
6732
|
isPortBound,
|
|
6117
6733
|
isRedirection,
|
|
6734
|
+
isSeparateMcpListener,
|
|
6118
6735
|
isServerError,
|
|
6119
6736
|
isSuccessful,
|
|
6120
6737
|
isValidStatusCode,
|
|
6738
|
+
jwtAlgorithmsForPublicKey,
|
|
6739
|
+
jwtAlgorithmsForSharedSecret,
|
|
6740
|
+
jwtClaimChecks,
|
|
6121
6741
|
logger,
|
|
6122
6742
|
meta,
|
|
6123
6743
|
metricsDefinitions,
|
|
@@ -6130,10 +6750,14 @@ function createLocalModelGatewayClient(options2 = {}) {
|
|
|
6130
6750
|
recordRequestAudit,
|
|
6131
6751
|
registerDelegatedSurface,
|
|
6132
6752
|
resetProcessHandlersForTesting,
|
|
6753
|
+
resolveHmacMaxSkewMs,
|
|
6754
|
+
resolveHmacNonceStore,
|
|
6133
6755
|
signPlatformEvent,
|
|
6134
6756
|
smsSegments,
|
|
6135
6757
|
stripeGatewayFetch,
|
|
6758
|
+
timingSafeEqualStrings,
|
|
6136
6759
|
trace,
|
|
6760
|
+
ttlCacheHmacNonceStore,
|
|
6137
6761
|
typedAuthHandler,
|
|
6138
6762
|
typedHandler,
|
|
6139
6763
|
validateEmailSendRequest,
|