@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.mjs
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
// src/http/bindRuntimeAuth.ts
|
|
2
|
+
var JWT_VERIFICATION_KEYS = ["algorithms", "issuer", "audience"];
|
|
3
|
+
var HMAC_VERIFICATION_KEYS = ["maxSkewMs", "nonceStore"];
|
|
4
|
+
var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
|
|
5
|
+
var isNonEmptyStringList = (value) => Array.isArray(value) && value.length > 0 && value.every(isNonEmptyString);
|
|
2
6
|
function bindRuntimeAuth(details, binding) {
|
|
3
7
|
const policy = { ...details.auth };
|
|
4
8
|
const keys = Object.keys(binding);
|
|
@@ -25,10 +29,26 @@ function bindRuntimeAuth(details, binding) {
|
|
|
25
29
|
let authentication;
|
|
26
30
|
if (policy.scheme === "jwt") {
|
|
27
31
|
if (keys.some(
|
|
28
|
-
(key) => ![
|
|
32
|
+
(key) => ![
|
|
33
|
+
"jwksPublicKeyUrl",
|
|
34
|
+
"signatureKey",
|
|
35
|
+
"decodeResource",
|
|
36
|
+
...JWT_VERIFICATION_KEYS
|
|
37
|
+
].includes(key)
|
|
29
38
|
))
|
|
30
39
|
invalid();
|
|
31
|
-
|
|
40
|
+
for (const key of JWT_VERIFICATION_KEYS) {
|
|
41
|
+
if (credentials[key] === void 0) {
|
|
42
|
+
delete credentials[key];
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const value = credentials[key];
|
|
46
|
+
if (key === "algorithms" ? !isNonEmptyStringList(value) : !isNonEmptyString(value) && !isNonEmptyStringList(value))
|
|
47
|
+
invalid();
|
|
48
|
+
}
|
|
49
|
+
const keyFields = keys.filter(
|
|
50
|
+
(key) => key !== "decodeResource" && !JWT_VERIFICATION_KEYS.includes(key)
|
|
51
|
+
);
|
|
32
52
|
if (keyFields.length !== 1 || typeof credentials[keyFields[0]] !== "string" || !credentials[keyFields[0]])
|
|
33
53
|
invalid();
|
|
34
54
|
const decodeResource = credentials.decodeResource;
|
|
@@ -40,7 +60,13 @@ function bindRuntimeAuth(details, binding) {
|
|
|
40
60
|
...decodeResource === void 0 ? {} : { decodeResource }
|
|
41
61
|
};
|
|
42
62
|
} else if (policy.scheme === "hmac") {
|
|
43
|
-
|
|
63
|
+
const maxSkewMs = credentials.maxSkewMs;
|
|
64
|
+
if (maxSkewMs === void 0) delete credentials.maxSkewMs;
|
|
65
|
+
const nonceStore = credentials.nonceStore;
|
|
66
|
+
if (nonceStore === void 0) delete credentials.nonceStore;
|
|
67
|
+
if (keys.some(
|
|
68
|
+
(key) => key !== "secretKeys" && !HMAC_VERIFICATION_KEYS.includes(key)
|
|
69
|
+
) || 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(
|
|
44
70
|
(key) => typeof key !== "string" || !key
|
|
45
71
|
))
|
|
46
72
|
invalid();
|
|
@@ -62,7 +88,72 @@ function bindRuntimeAuth(details, binding) {
|
|
|
62
88
|
|
|
63
89
|
// src/http/middleware/request/cors.middleware.ts
|
|
64
90
|
import corsMiddleware from "cors";
|
|
91
|
+
var CORS_ORIGINS_ENV = "CORS_ORIGINS";
|
|
92
|
+
var LOCAL_DEVELOPMENT_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/;
|
|
93
|
+
function parseCorsOrigins(value) {
|
|
94
|
+
const origins = [];
|
|
95
|
+
for (const entry of (value ?? "").split(",")) {
|
|
96
|
+
let origin = entry.trim();
|
|
97
|
+
while (origin.length > 1 && origin.endsWith("/")) {
|
|
98
|
+
origin = origin.slice(0, -1);
|
|
99
|
+
}
|
|
100
|
+
if (origin && !origins.includes(origin)) origins.push(origin);
|
|
101
|
+
}
|
|
102
|
+
return origins;
|
|
103
|
+
}
|
|
104
|
+
function isWildcardOrigin(origin) {
|
|
105
|
+
return origin === void 0 || origin === "*";
|
|
106
|
+
}
|
|
107
|
+
function defaultCorsOrigin(env) {
|
|
108
|
+
const listed = parseCorsOrigins(env[CORS_ORIGINS_ENV]);
|
|
109
|
+
if (listed.includes("*")) {
|
|
110
|
+
return { origin: "*", configured: true };
|
|
111
|
+
}
|
|
112
|
+
if (listed.length > 0) {
|
|
113
|
+
return { origin: listed, configured: true };
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
origin: env.NODE_ENV === "production" ? false : LOCAL_DEVELOPMENT_ORIGIN,
|
|
117
|
+
configured: false
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function withoutWildcardCredentials(options2) {
|
|
121
|
+
return options2.credentials === true && isWildcardOrigin(options2.origin) ? { ...options2, credentials: false } : options2;
|
|
122
|
+
}
|
|
123
|
+
function resolveCorsOptions(appCors, env = process.env) {
|
|
124
|
+
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.`;
|
|
125
|
+
if (appCors !== void 0) {
|
|
126
|
+
if (appCors.credentials === true && isWildcardOrigin(appCors.origin)) {
|
|
127
|
+
return {
|
|
128
|
+
options: appCors,
|
|
129
|
+
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."
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (appCors.origin === void 0) {
|
|
133
|
+
return {
|
|
134
|
+
options: appCors,
|
|
135
|
+
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: '*' }\`.`
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
return { options: appCors };
|
|
139
|
+
}
|
|
140
|
+
const { origin, configured } = defaultCorsOrigin(env);
|
|
141
|
+
if (configured) {
|
|
142
|
+
return { options: { origin } };
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
options: { origin },
|
|
146
|
+
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
|
|
147
|
+
};
|
|
148
|
+
}
|
|
65
149
|
function cors(corsOptions) {
|
|
150
|
+
const configuredOrigin = corsOptions.origin;
|
|
151
|
+
const staticHandler = corsMiddleware(withoutWildcardCredentials(corsOptions));
|
|
152
|
+
const wildcardHandler = corsMiddleware({
|
|
153
|
+
...corsOptions,
|
|
154
|
+
origin: "*",
|
|
155
|
+
credentials: false
|
|
156
|
+
});
|
|
66
157
|
return (req, res, next) => {
|
|
67
158
|
if (req.method === "OPTIONS") {
|
|
68
159
|
res.cors = true;
|
|
@@ -72,19 +163,29 @@ function cors(corsOptions) {
|
|
|
72
163
|
return res.getHeaders()[key];
|
|
73
164
|
};
|
|
74
165
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
166
|
+
const corsRequest = req;
|
|
167
|
+
const done = next ?? (() => {
|
|
168
|
+
});
|
|
169
|
+
if (corsOptions.credentials === true && typeof configuredOrigin === "function") {
|
|
170
|
+
configuredOrigin(corsRequest.headers.origin, (error, origin) => {
|
|
171
|
+
if (error || !origin) {
|
|
172
|
+
done(error ?? void 0);
|
|
173
|
+
} else if (origin === "*") {
|
|
174
|
+
wildcardHandler(corsRequest, res, done);
|
|
175
|
+
} else {
|
|
176
|
+
corsMiddleware({ ...corsOptions, origin })(corsRequest, res, done);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
staticHandler(corsRequest, res, done);
|
|
81
182
|
};
|
|
82
183
|
}
|
|
83
184
|
|
|
84
185
|
// src/http/router/expressLikeRouter.ts
|
|
85
186
|
import {
|
|
86
187
|
hashString,
|
|
87
|
-
safeStringify as
|
|
188
|
+
safeStringify as safeStringify2,
|
|
88
189
|
sanitizePathSlashes,
|
|
89
190
|
toPrettyCamelCase,
|
|
90
191
|
toRecord
|
|
@@ -446,13 +547,15 @@ new NodeSDK({
|
|
|
446
547
|
url: `${getEnvVar("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/traces`,
|
|
447
548
|
headers: otelHeaders
|
|
448
549
|
}),
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
550
|
+
metricReaders: [
|
|
551
|
+
new PeriodicExportingMetricReader({
|
|
552
|
+
exporter: new OTLPMetricExporter({
|
|
553
|
+
url: `${getEnvVar("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/metrics`,
|
|
554
|
+
headers: otelHeaders
|
|
555
|
+
}),
|
|
556
|
+
exportIntervalMillis: 5e3
|
|
557
|
+
})
|
|
558
|
+
],
|
|
456
559
|
logRecordProcessors: [
|
|
457
560
|
new BatchLogRecordProcessor({
|
|
458
561
|
exporter: new OTLPLogExporter({
|
|
@@ -700,7 +803,6 @@ import {
|
|
|
700
803
|
} from "@forklaunch/validator";
|
|
701
804
|
|
|
702
805
|
// src/http/discriminateAuthMethod.ts
|
|
703
|
-
import { safeStringify as safeStringify2 } from "@forklaunch/common";
|
|
704
806
|
import { jwtVerify } from "jose";
|
|
705
807
|
|
|
706
808
|
// src/http/createHmacToken.ts
|
|
@@ -726,6 +828,227 @@ ${nonce}`
|
|
|
726
828
|
return hmac.digest("base64");
|
|
727
829
|
}
|
|
728
830
|
|
|
831
|
+
// src/http/hmacReplayProtection.ts
|
|
832
|
+
import { timingSafeEqual } from "crypto";
|
|
833
|
+
var DEFAULT_HMAC_MAX_SKEW_MS = 5 * 60 * 1e3;
|
|
834
|
+
var DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES = 1e5;
|
|
835
|
+
function timingSafeEqualStrings(expected, received) {
|
|
836
|
+
if (typeof expected !== "string" || typeof received !== "string") {
|
|
837
|
+
return false;
|
|
838
|
+
}
|
|
839
|
+
const expectedBytes = Buffer.from(expected);
|
|
840
|
+
const receivedBytes = Buffer.from(received);
|
|
841
|
+
return expectedBytes.length === receivedBytes.length && timingSafeEqual(expectedBytes, receivedBytes);
|
|
842
|
+
}
|
|
843
|
+
function resolveHmacMaxSkewMs(maxSkewMs) {
|
|
844
|
+
return typeof maxSkewMs === "number" && Number.isFinite(maxSkewMs) && maxSkewMs > 0 ? maxSkewMs : DEFAULT_HMAC_MAX_SKEW_MS;
|
|
845
|
+
}
|
|
846
|
+
function isHmacTimestampFresh(timestamp, nowMs, maxSkewMs = DEFAULT_HMAC_MAX_SKEW_MS) {
|
|
847
|
+
if (!(timestamp instanceof Date)) return false;
|
|
848
|
+
const at = timestamp.getTime();
|
|
849
|
+
return !Number.isNaN(at) && Math.abs(nowMs - at) <= maxSkewMs;
|
|
850
|
+
}
|
|
851
|
+
function hmacNonceTtlMs(timestamp, nowMs, maxSkewMs) {
|
|
852
|
+
return Math.max(1, timestamp.getTime() + maxSkewMs - nowMs);
|
|
853
|
+
}
|
|
854
|
+
function hmacNonceKey(keyId, nonce) {
|
|
855
|
+
const id = keyId ?? "";
|
|
856
|
+
return `${id.length}:${id}${nonce}`;
|
|
857
|
+
}
|
|
858
|
+
var InMemoryHmacNonceStore = class {
|
|
859
|
+
entries = /* @__PURE__ */ new Map();
|
|
860
|
+
maxEntries;
|
|
861
|
+
sweepIntervalMs;
|
|
862
|
+
lastSweepAt = 0;
|
|
863
|
+
constructor(options2 = {}) {
|
|
864
|
+
this.maxEntries = typeof options2.maxEntries === "number" && options2.maxEntries >= 1 ? Math.floor(options2.maxEntries) : DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES;
|
|
865
|
+
this.sweepIntervalMs = options2.sweepIntervalMs ?? 3e4;
|
|
866
|
+
}
|
|
867
|
+
/** Number of nonces currently held (expired ones may linger until swept). */
|
|
868
|
+
get size() {
|
|
869
|
+
return this.entries.size;
|
|
870
|
+
}
|
|
871
|
+
claim(key, ttlMs, nowMs = Date.now()) {
|
|
872
|
+
const expiresAt = this.entries.get(key);
|
|
873
|
+
if (expiresAt !== void 0 && expiresAt > nowMs) {
|
|
874
|
+
return false;
|
|
875
|
+
}
|
|
876
|
+
if (this.entries.size >= this.maxEntries || nowMs - this.lastSweepAt >= this.sweepIntervalMs) {
|
|
877
|
+
this.sweep(nowMs);
|
|
878
|
+
}
|
|
879
|
+
this.entries.delete(key);
|
|
880
|
+
while (this.entries.size >= this.maxEntries) {
|
|
881
|
+
const oldest = this.entries.keys().next();
|
|
882
|
+
if (oldest.done) break;
|
|
883
|
+
this.entries.delete(oldest.value);
|
|
884
|
+
}
|
|
885
|
+
this.entries.set(key, nowMs + Math.max(1, ttlMs));
|
|
886
|
+
return true;
|
|
887
|
+
}
|
|
888
|
+
sweep(nowMs) {
|
|
889
|
+
this.lastSweepAt = nowMs;
|
|
890
|
+
for (const [key, expiresAt] of this.entries) {
|
|
891
|
+
if (expiresAt <= nowMs) this.entries.delete(key);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
function ttlCacheHmacNonceStore(cache, keyPrefix = "hmac-nonce:") {
|
|
896
|
+
return {
|
|
897
|
+
async claim(key, ttlMs) {
|
|
898
|
+
const record2 = {
|
|
899
|
+
key: `${keyPrefix}${key}`,
|
|
900
|
+
value: 1,
|
|
901
|
+
ttlMilliseconds: Math.max(1, Math.ceil(ttlMs))
|
|
902
|
+
};
|
|
903
|
+
if (typeof cache.putRecordIfAbsent === "function") {
|
|
904
|
+
return await cache.putRecordIfAbsent(record2) === true;
|
|
905
|
+
}
|
|
906
|
+
if (await cache.peekRecord(record2.key)) {
|
|
907
|
+
return false;
|
|
908
|
+
}
|
|
909
|
+
await cache.putRecord(record2);
|
|
910
|
+
return true;
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
var defaultHmacNonceStore = new InMemoryHmacNonceStore();
|
|
915
|
+
var adaptedTtlCaches = /* @__PURE__ */ new WeakMap();
|
|
916
|
+
function resolveHmacNonceStore(configured) {
|
|
917
|
+
if (configured == null) {
|
|
918
|
+
return defaultHmacNonceStore;
|
|
919
|
+
}
|
|
920
|
+
if (typeof configured.claim === "function") {
|
|
921
|
+
return configured;
|
|
922
|
+
}
|
|
923
|
+
const cache = configured;
|
|
924
|
+
if (typeof cache.putRecordIfAbsent !== "function" && (typeof cache.peekRecord !== "function" || typeof cache.putRecord !== "function")) {
|
|
925
|
+
throw new Error(
|
|
926
|
+
"hmac.nonceStore must be an HmacNonceStore ({ claim }) or a TtlCache"
|
|
927
|
+
);
|
|
928
|
+
}
|
|
929
|
+
let adapted = adaptedTtlCaches.get(cache);
|
|
930
|
+
if (!adapted) {
|
|
931
|
+
adapted = ttlCacheHmacNonceStore(cache);
|
|
932
|
+
adaptedTtlCaches.set(cache, adapted);
|
|
933
|
+
}
|
|
934
|
+
return adapted;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// src/http/jwtAlgorithms.ts
|
|
938
|
+
var SHARED_SECRET_JWT_ALGORITHMS = [
|
|
939
|
+
"HS256",
|
|
940
|
+
"HS384",
|
|
941
|
+
"HS512"
|
|
942
|
+
];
|
|
943
|
+
var DEFAULT_SHARED_SECRET_JWT_ALGORITHMS = [
|
|
944
|
+
"HS256"
|
|
945
|
+
];
|
|
946
|
+
var RSA_JWT_ALGORITHMS = [
|
|
947
|
+
"RS256",
|
|
948
|
+
"RS384",
|
|
949
|
+
"RS512",
|
|
950
|
+
"PS256",
|
|
951
|
+
"PS384",
|
|
952
|
+
"PS512"
|
|
953
|
+
];
|
|
954
|
+
var EC_CURVE_JWT_ALGORITHMS = {
|
|
955
|
+
"P-256": ["ES256"],
|
|
956
|
+
"P-384": ["ES384"],
|
|
957
|
+
"P-521": ["ES512"]
|
|
958
|
+
};
|
|
959
|
+
var OKP_CURVE_JWT_ALGORITHMS = {
|
|
960
|
+
Ed25519: ["EdDSA", "Ed25519"]
|
|
961
|
+
};
|
|
962
|
+
function isSymmetricOrUnsigned(algorithm) {
|
|
963
|
+
const normalized = algorithm.toUpperCase();
|
|
964
|
+
return normalized === "NONE" || normalized.startsWith("HS");
|
|
965
|
+
}
|
|
966
|
+
function configuredList(configured) {
|
|
967
|
+
if (configured == null) return void 0;
|
|
968
|
+
if (!Array.isArray(configured)) {
|
|
969
|
+
throw new Error("JWT `algorithms` must be an array of algorithm names");
|
|
970
|
+
}
|
|
971
|
+
return configured.filter(
|
|
972
|
+
(algorithm) => typeof algorithm === "string"
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
function jwtAlgorithmsForSharedSecret(configured) {
|
|
976
|
+
const requested = configuredList(configured);
|
|
977
|
+
if (requested === void 0) {
|
|
978
|
+
return [...DEFAULT_SHARED_SECRET_JWT_ALGORITHMS];
|
|
979
|
+
}
|
|
980
|
+
const allowed = SHARED_SECRET_JWT_ALGORITHMS.filter(
|
|
981
|
+
(algorithm) => requested.includes(algorithm)
|
|
982
|
+
);
|
|
983
|
+
if (allowed.length === 0) {
|
|
984
|
+
throw new Error(
|
|
985
|
+
"No usable JWT algorithm: a `signatureKey` verifies only HS256, HS384 or HS512"
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
return allowed;
|
|
989
|
+
}
|
|
990
|
+
function algorithmsFittingPublicKey(key) {
|
|
991
|
+
let fitting;
|
|
992
|
+
switch (key.kty) {
|
|
993
|
+
case "RSA":
|
|
994
|
+
fitting = RSA_JWT_ALGORITHMS;
|
|
995
|
+
break;
|
|
996
|
+
case "EC":
|
|
997
|
+
fitting = EC_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
|
|
998
|
+
break;
|
|
999
|
+
case "OKP":
|
|
1000
|
+
fitting = OKP_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
|
|
1001
|
+
break;
|
|
1002
|
+
case "AKP":
|
|
1003
|
+
fitting = typeof key.alg === "string" ? [key.alg] : [];
|
|
1004
|
+
break;
|
|
1005
|
+
default:
|
|
1006
|
+
fitting = [];
|
|
1007
|
+
}
|
|
1008
|
+
if (typeof key.alg === "string") {
|
|
1009
|
+
fitting = fitting.filter((algorithm) => algorithm === key.alg);
|
|
1010
|
+
}
|
|
1011
|
+
return fitting.filter((algorithm) => !isSymmetricOrUnsigned(algorithm));
|
|
1012
|
+
}
|
|
1013
|
+
function jwtAlgorithmsForPublicKey(key, configured) {
|
|
1014
|
+
if (key == null || typeof key !== "object") {
|
|
1015
|
+
throw new Error("No usable JWT algorithm: the verification key is missing");
|
|
1016
|
+
}
|
|
1017
|
+
if (key.kty === "oct") {
|
|
1018
|
+
throw new Error(
|
|
1019
|
+
"No usable JWT algorithm: a symmetric (oct) key cannot be used as a public key; use `signatureKey` for a shared secret"
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
const requested = configuredList(configured);
|
|
1023
|
+
const allowed = algorithmsFittingPublicKey(key).filter(
|
|
1024
|
+
(algorithm) => requested === void 0 || requested.includes(algorithm)
|
|
1025
|
+
);
|
|
1026
|
+
if (allowed.length === 0) {
|
|
1027
|
+
throw new Error(
|
|
1028
|
+
"No usable JWT algorithm: none of the permitted asymmetric algorithms fits this public key"
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
return allowed;
|
|
1032
|
+
}
|
|
1033
|
+
function claimExpectation(name, value) {
|
|
1034
|
+
if (value === void 0) return void 0;
|
|
1035
|
+
const values = typeof value === "string" ? [value] : value;
|
|
1036
|
+
if (!Array.isArray(values) || values.length === 0 || values.some((entry) => typeof entry !== "string" || entry.length === 0)) {
|
|
1037
|
+
throw new Error(
|
|
1038
|
+
`JWT \`${name}\` is configured but empty; set it to the expected value or remove it`
|
|
1039
|
+
);
|
|
1040
|
+
}
|
|
1041
|
+
return typeof value === "string" ? value : [...values];
|
|
1042
|
+
}
|
|
1043
|
+
function jwtClaimChecks(config) {
|
|
1044
|
+
const issuer = claimExpectation("issuer", config.issuer);
|
|
1045
|
+
const audience = claimExpectation("audience", config.audience);
|
|
1046
|
+
return {
|
|
1047
|
+
...issuer === void 0 ? {} : { issuer },
|
|
1048
|
+
...audience === void 0 ? {} : { audience }
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
|
|
729
1052
|
// src/http/guards/isBasicAuthMethod.ts
|
|
730
1053
|
function isBasicAuthMethod(maybeBasicAuthMethod) {
|
|
731
1054
|
return typeof maybeBasicAuthMethod === "object" && maybeBasicAuthMethod !== null && "basic" in maybeBasicAuthMethod && maybeBasicAuthMethod.basic != null;
|
|
@@ -779,11 +1102,16 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
779
1102
|
} else if (isJwtAuthMethod(auth)) {
|
|
780
1103
|
const jwt = auth.jwt;
|
|
781
1104
|
let verificationFunction;
|
|
1105
|
+
const claimChecks = () => jwtClaimChecks(jwt);
|
|
782
1106
|
if ("signatureKey" in jwt) {
|
|
783
1107
|
verificationFunction = async (token) => {
|
|
784
1108
|
const { payload } = await jwtVerify(
|
|
785
1109
|
token,
|
|
786
|
-
new Uint8Array(Buffer.from(jwt.signatureKey))
|
|
1110
|
+
new Uint8Array(Buffer.from(jwt.signatureKey)),
|
|
1111
|
+
{
|
|
1112
|
+
...claimChecks(),
|
|
1113
|
+
algorithms: jwtAlgorithmsForSharedSecret(jwt.algorithms)
|
|
1114
|
+
}
|
|
787
1115
|
);
|
|
788
1116
|
return payload;
|
|
789
1117
|
};
|
|
@@ -798,7 +1126,10 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
798
1126
|
let lastError;
|
|
799
1127
|
for (const key of jwks) {
|
|
800
1128
|
try {
|
|
801
|
-
const { payload } = await jwtVerify(token, key
|
|
1129
|
+
const { payload } = await jwtVerify(token, key, {
|
|
1130
|
+
...claimChecks(),
|
|
1131
|
+
algorithms: jwtAlgorithmsForPublicKey(key, jwt.algorithms)
|
|
1132
|
+
});
|
|
802
1133
|
return payload;
|
|
803
1134
|
} catch (error) {
|
|
804
1135
|
lastError = error;
|
|
@@ -819,10 +1150,19 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
819
1150
|
}
|
|
820
1151
|
};
|
|
821
1152
|
} else if (isHmacMethod(auth)) {
|
|
1153
|
+
const maxSkewMs = resolveHmacMaxSkewMs(auth.hmac.maxSkewMs);
|
|
1154
|
+
const configuredNonceStore = auth.hmac.nonceStore;
|
|
822
1155
|
authMethod = {
|
|
823
1156
|
type: "hmac",
|
|
824
1157
|
auth: {
|
|
825
1158
|
secretKeys: auth.hmac.secretKeys,
|
|
1159
|
+
/**
|
|
1160
|
+
* Accepts a signed request only when its timestamp is inside the
|
|
1161
|
+
* skew window, its signature matches (constant-time compare) and
|
|
1162
|
+
* its nonce has not been used before. The nonce is claimed last, and
|
|
1163
|
+
* only for a valid signature, so a `false` for one candidate path
|
|
1164
|
+
* never burns the nonce for the next.
|
|
1165
|
+
*/
|
|
826
1166
|
verificationFunction: async ({
|
|
827
1167
|
method,
|
|
828
1168
|
path,
|
|
@@ -830,8 +1170,30 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
830
1170
|
timestamp,
|
|
831
1171
|
nonce,
|
|
832
1172
|
signature,
|
|
833
|
-
secretKey
|
|
1173
|
+
secretKey,
|
|
1174
|
+
keyId
|
|
834
1175
|
}) => {
|
|
1176
|
+
const reject = (reason) => {
|
|
1177
|
+
openTelemetryCollector?.debug("[HMAC Verification Failed]", {
|
|
1178
|
+
reason,
|
|
1179
|
+
method,
|
|
1180
|
+
path,
|
|
1181
|
+
keyId,
|
|
1182
|
+
timestamp: timestamp instanceof Date && !Number.isNaN(timestamp.getTime()) ? timestamp.toISOString() : "invalid",
|
|
1183
|
+
bodyType: body ? typeof body : "undefined"
|
|
1184
|
+
});
|
|
1185
|
+
return false;
|
|
1186
|
+
};
|
|
1187
|
+
if (typeof secretKey !== "string" || secretKey.length === 0) {
|
|
1188
|
+
return reject("unknown key");
|
|
1189
|
+
}
|
|
1190
|
+
if (typeof nonce !== "string" || nonce.length === 0 || typeof signature !== "string") {
|
|
1191
|
+
return reject("missing nonce or signature");
|
|
1192
|
+
}
|
|
1193
|
+
const now = Date.now();
|
|
1194
|
+
if (!isHmacTimestampFresh(timestamp, now, maxSkewMs)) {
|
|
1195
|
+
return reject("stale or invalid timestamp");
|
|
1196
|
+
}
|
|
835
1197
|
const computedSignature = createHmacToken({
|
|
836
1198
|
method,
|
|
837
1199
|
path,
|
|
@@ -840,23 +1202,26 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
|
|
|
840
1202
|
nonce,
|
|
841
1203
|
secretKey
|
|
842
1204
|
});
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
const errorInfo = {
|
|
846
|
-
method,
|
|
847
|
-
path,
|
|
848
|
-
timestamp: timestamp.toISOString(),
|
|
849
|
-
nonce,
|
|
850
|
-
receivedSignature: signature,
|
|
851
|
-
computedSignature
|
|
852
|
-
};
|
|
853
|
-
openTelemetryCollector?.debug("[HMAC Verification Failed]", {
|
|
854
|
-
...errorInfo,
|
|
855
|
-
bodyType: body ? typeof body : "undefined",
|
|
856
|
-
body: body ? safeStringify2(body) : "undefined"
|
|
857
|
-
});
|
|
1205
|
+
if (!timingSafeEqualStrings(computedSignature, signature)) {
|
|
1206
|
+
return reject("signature mismatch");
|
|
858
1207
|
}
|
|
859
|
-
|
|
1208
|
+
let firstUse;
|
|
1209
|
+
try {
|
|
1210
|
+
firstUse = await resolveHmacNonceStore(configuredNonceStore).claim(
|
|
1211
|
+
hmacNonceKey(keyId, nonce),
|
|
1212
|
+
hmacNonceTtlMs(timestamp, now, maxSkewMs)
|
|
1213
|
+
);
|
|
1214
|
+
} catch (error) {
|
|
1215
|
+
openTelemetryCollector?.error(
|
|
1216
|
+
"[HMAC Nonce Store Failed]",
|
|
1217
|
+
error instanceof Error ? error.message : String(error)
|
|
1218
|
+
);
|
|
1219
|
+
return reject("nonce store unavailable");
|
|
1220
|
+
}
|
|
1221
|
+
if (firstUse !== true) {
|
|
1222
|
+
return reject("replayed nonce");
|
|
1223
|
+
}
|
|
1224
|
+
return true;
|
|
860
1225
|
}
|
|
861
1226
|
}
|
|
862
1227
|
};
|
|
@@ -1017,6 +1382,18 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
|
|
|
1017
1382
|
if (!parsedKeyId || !parsedTimestamp || !parsedNonce || !parsedSignature) {
|
|
1018
1383
|
return invalidAuthorizationTokenFormat;
|
|
1019
1384
|
}
|
|
1385
|
+
const requestTimestamp = new Date(parsedTimestamp);
|
|
1386
|
+
if (Number.isNaN(requestTimestamp.getTime())) {
|
|
1387
|
+
return invalidAuthorizationTokenFormat;
|
|
1388
|
+
}
|
|
1389
|
+
const secretKeys = collapsedAuthorizationMethod.hmac.secretKeys;
|
|
1390
|
+
const secretKey = Object.prototype.hasOwnProperty.call(
|
|
1391
|
+
secretKeys,
|
|
1392
|
+
parsedKeyId
|
|
1393
|
+
) ? secretKeys[parsedKeyId] : void 0;
|
|
1394
|
+
if (typeof secretKey !== "string" || secretKey.length === 0) {
|
|
1395
|
+
return invalidAuthorizationSignature;
|
|
1396
|
+
}
|
|
1020
1397
|
let verificationResult = false;
|
|
1021
1398
|
const signedPaths = hmacSignedPaths(req);
|
|
1022
1399
|
for (const path of signedPaths) {
|
|
@@ -1024,10 +1401,11 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
|
|
|
1024
1401
|
method: req?.method ?? "",
|
|
1025
1402
|
path,
|
|
1026
1403
|
body: req?._rawBody ?? req?.body,
|
|
1027
|
-
timestamp:
|
|
1404
|
+
timestamp: requestTimestamp,
|
|
1028
1405
|
nonce: parsedNonce,
|
|
1029
1406
|
signature: parsedSignature,
|
|
1030
|
-
secretKey
|
|
1407
|
+
secretKey,
|
|
1408
|
+
keyId: parsedKeyId
|
|
1031
1409
|
}));
|
|
1032
1410
|
if (verificationResult) {
|
|
1033
1411
|
if (path !== signedPaths[0]) warnMountRelativeHmacPath();
|
|
@@ -2582,7 +2960,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2582
2960
|
unpackSdks(sdks, path, routerUniquenessCache) {
|
|
2583
2961
|
Object.entries(sdks).forEach(([key, maybeHandler]) => {
|
|
2584
2962
|
if (isSdkHandler(maybeHandler)) {
|
|
2585
|
-
const cacheKey = hashString(
|
|
2963
|
+
const cacheKey = hashString(safeStringify2(maybeHandler));
|
|
2586
2964
|
if (routerUniquenessCache.has(cacheKey)) {
|
|
2587
2965
|
throw new Error(`SDK handler ${key} is already registered`);
|
|
2588
2966
|
}
|
|
@@ -2627,6 +3005,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
|
|
|
2627
3005
|
};
|
|
2628
3006
|
|
|
2629
3007
|
// src/http/application/expressLikeApplication.ts
|
|
3008
|
+
var warnedAboutCorsDefaults = false;
|
|
2630
3009
|
var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter {
|
|
2631
3010
|
/**
|
|
2632
3011
|
* Creates an instance of the Application class.
|
|
@@ -2651,7 +3030,14 @@ var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter
|
|
|
2651
3030
|
this.postEnrichMiddleware = postEnrichMiddleware;
|
|
2652
3031
|
this.openTelemetryCollector = openTelemetryCollector;
|
|
2653
3032
|
this.appOptions = appOptions;
|
|
2654
|
-
|
|
3033
|
+
const { options: corsOptions, warning: corsWarning } = resolveCorsOptions(
|
|
3034
|
+
this.appOptions?.cors
|
|
3035
|
+
);
|
|
3036
|
+
if (corsWarning && !warnedAboutCorsDefaults) {
|
|
3037
|
+
warnedAboutCorsDefaults = true;
|
|
3038
|
+
this.openTelemetryCollector.warn(corsWarning);
|
|
3039
|
+
}
|
|
3040
|
+
this.internal.use(cors(corsOptions));
|
|
2655
3041
|
}
|
|
2656
3042
|
schemaValidator;
|
|
2657
3043
|
internal;
|
|
@@ -2713,11 +3099,10 @@ function generateHmacAuthHeaders({
|
|
|
2713
3099
|
}
|
|
2714
3100
|
|
|
2715
3101
|
// src/http/instanceGateway.ts
|
|
2716
|
-
import { timingSafeEqual } from "crypto";
|
|
2717
3102
|
var INSTANCE_GATEWAY_MOUNT = "/instance-gateway";
|
|
2718
3103
|
var PLATFORM_EVENT_KEY_ID = "platform";
|
|
2719
3104
|
var PLATFORM_EVENTS_PATH = "/platform-events";
|
|
2720
|
-
var MAX_SKEW_MS =
|
|
3105
|
+
var MAX_SKEW_MS = DEFAULT_HMAC_MAX_SKEW_MS;
|
|
2721
3106
|
var InstanceGatewayRequestError = class extends Error {
|
|
2722
3107
|
constructor(status, message, retryAfterSeconds) {
|
|
2723
3108
|
super(message);
|
|
@@ -2796,7 +3181,7 @@ function createInstanceGatewayTransport(options2 = {}, feature) {
|
|
|
2796
3181
|
var PlatformEventVerificationError = class extends Error {
|
|
2797
3182
|
name = "PlatformEventVerificationError";
|
|
2798
3183
|
};
|
|
2799
|
-
var seenEventNonces =
|
|
3184
|
+
var seenEventNonces = new InMemoryHmacNonceStore();
|
|
2800
3185
|
function verifyPlatformEvent(request, options2 = {}) {
|
|
2801
3186
|
const hmacKey = options2.hmacKey ?? process.env.INSTANCE_HMAC_KEY;
|
|
2802
3187
|
if (!hmacKey) {
|
|
@@ -2820,30 +3205,27 @@ function verifyPlatformEvent(request, options2 = {}) {
|
|
|
2820
3205
|
}
|
|
2821
3206
|
const timestamp = new Date(ts);
|
|
2822
3207
|
const now = (options2.now ?? Date.now)();
|
|
2823
|
-
if (
|
|
3208
|
+
if (!isHmacTimestampFresh(timestamp, now, MAX_SKEW_MS)) {
|
|
2824
3209
|
throw new PlatformEventVerificationError("Stale or invalid timestamp");
|
|
2825
3210
|
}
|
|
2826
|
-
const expected =
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
);
|
|
2836
|
-
const received = Buffer.from(signature);
|
|
2837
|
-
if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
|
|
3211
|
+
const expected = createHmacToken({
|
|
3212
|
+
secretKey: hmacKey,
|
|
3213
|
+
method: request.method.toUpperCase(),
|
|
3214
|
+
path: request.path,
|
|
3215
|
+
body: request.body,
|
|
3216
|
+
timestamp,
|
|
3217
|
+
nonce
|
|
3218
|
+
});
|
|
3219
|
+
if (!timingSafeEqualStrings(expected, signature)) {
|
|
2838
3220
|
throw new PlatformEventVerificationError("Invalid signature");
|
|
2839
3221
|
}
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
3222
|
+
if (!seenEventNonces.claim(
|
|
3223
|
+
hmacNonceKey(keyId, nonce),
|
|
3224
|
+
hmacNonceTtlMs(timestamp, now, MAX_SKEW_MS),
|
|
3225
|
+
now
|
|
3226
|
+
)) {
|
|
2844
3227
|
throw new PlatformEventVerificationError("Replayed delivery");
|
|
2845
3228
|
}
|
|
2846
|
-
seenEventNonces.set(nonce, now);
|
|
2847
3229
|
const parsed = typeof request.body === "string" || Buffer.isBuffer(request.body) ? JSON.parse(request.body.toString()) : request.body;
|
|
2848
3230
|
const event = parsed;
|
|
2849
3231
|
if (!event || typeof event.id !== "string" || typeof event.type !== "string" || typeof event.feature !== "string") {
|
|
@@ -4758,7 +5140,7 @@ var getCodeForStatus = (status) => {
|
|
|
4758
5140
|
var httpStatusCodes_default = HTTPStatuses;
|
|
4759
5141
|
|
|
4760
5142
|
// src/http/mcpGenerator/mcpGenerator.ts
|
|
4761
|
-
import { isNever as isNever3, isRecord as isRecord3, safeStringify as
|
|
5143
|
+
import { isNever as isNever3, isRecord as isRecord3, safeStringify as safeStringify3 } from "@forklaunch/common";
|
|
4762
5144
|
import { string, ZodSchemaValidator } from "@forklaunch/validator/zod";
|
|
4763
5145
|
import { FastMCP } from "fastmcp";
|
|
4764
5146
|
|
|
@@ -4780,6 +5162,182 @@ function unpackRouters(routers, recursiveBasePath = []) {
|
|
|
4780
5162
|
}, []);
|
|
4781
5163
|
}
|
|
4782
5164
|
|
|
5165
|
+
// src/http/mcpGenerator/mcpHttpHandler.ts
|
|
5166
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
5167
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
5168
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
5169
|
+
var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
|
|
5170
|
+
var mcpTransportHeaders = new AsyncLocalStorage2();
|
|
5171
|
+
function getMcpTransportHeaders() {
|
|
5172
|
+
return mcpTransportHeaders.getStore();
|
|
5173
|
+
}
|
|
5174
|
+
function createMcpHttpHandler(mcpServer, options2) {
|
|
5175
|
+
const mode = options2?.sessions ?? "stateless";
|
|
5176
|
+
if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
|
|
5177
|
+
throw new Error(
|
|
5178
|
+
"Stateful MCP sessions live in one process's memory and cannot be shared across workers. Use mcp.sessions: 'stateless' or a single worker."
|
|
5179
|
+
);
|
|
5180
|
+
}
|
|
5181
|
+
const idleTimeoutMs = options2?.sessionIdleTimeoutMs ?? DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS;
|
|
5182
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
5183
|
+
const jsonRpcError = (status, code, message, headers) => new Response(
|
|
5184
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }),
|
|
5185
|
+
{
|
|
5186
|
+
status,
|
|
5187
|
+
headers: { "Content-Type": "application/json", ...headers }
|
|
5188
|
+
}
|
|
5189
|
+
);
|
|
5190
|
+
let sweepTimer;
|
|
5191
|
+
if (mode === "stateful") {
|
|
5192
|
+
sweepTimer = setInterval(
|
|
5193
|
+
() => {
|
|
5194
|
+
const cutoff = Date.now() - idleTimeoutMs;
|
|
5195
|
+
for (const [id, entry] of sessions) {
|
|
5196
|
+
if (entry.lastSeen < cutoff) {
|
|
5197
|
+
sessions.delete(id);
|
|
5198
|
+
entry.session.close().catch(() => void 0);
|
|
5199
|
+
}
|
|
5200
|
+
}
|
|
5201
|
+
},
|
|
5202
|
+
Math.min(idleTimeoutMs, 6e4)
|
|
5203
|
+
);
|
|
5204
|
+
sweepTimer.unref();
|
|
5205
|
+
}
|
|
5206
|
+
async function authenticateRequest(authRequest) {
|
|
5207
|
+
if (!options2?.authenticate) {
|
|
5208
|
+
return { ok: true, auth: void 0 };
|
|
5209
|
+
}
|
|
5210
|
+
try {
|
|
5211
|
+
const auth = await options2.authenticate(authRequest);
|
|
5212
|
+
return auth ? { ok: true, auth } : { ok: false };
|
|
5213
|
+
} catch {
|
|
5214
|
+
return { ok: false };
|
|
5215
|
+
}
|
|
5216
|
+
}
|
|
5217
|
+
async function handleStateless(request, auth) {
|
|
5218
|
+
if (request.method !== "POST") {
|
|
5219
|
+
return jsonRpcError(405, -32e3, "Method not allowed", {
|
|
5220
|
+
Allow: "POST"
|
|
5221
|
+
});
|
|
5222
|
+
}
|
|
5223
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
5224
|
+
sessionIdGenerator: void 0
|
|
5225
|
+
});
|
|
5226
|
+
const session = await mcpServer.connect(transport, auth);
|
|
5227
|
+
let closed = false;
|
|
5228
|
+
const closeSession = () => {
|
|
5229
|
+
if (!closed) {
|
|
5230
|
+
closed = true;
|
|
5231
|
+
session.close().catch(() => void 0);
|
|
5232
|
+
}
|
|
5233
|
+
};
|
|
5234
|
+
try {
|
|
5235
|
+
const response = await mcpTransportHeaders.run(
|
|
5236
|
+
request.headers,
|
|
5237
|
+
() => transport.handleRequest(request)
|
|
5238
|
+
);
|
|
5239
|
+
return closeWhenBodyEnds(response, closeSession);
|
|
5240
|
+
} catch (error) {
|
|
5241
|
+
closeSession();
|
|
5242
|
+
throw error;
|
|
5243
|
+
}
|
|
5244
|
+
}
|
|
5245
|
+
async function handleStateful(request, auth) {
|
|
5246
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
5247
|
+
if (sessionId) {
|
|
5248
|
+
const entry = sessions.get(sessionId);
|
|
5249
|
+
if (!entry) {
|
|
5250
|
+
return jsonRpcError(404, -32001, "Session not found");
|
|
5251
|
+
}
|
|
5252
|
+
entry.lastSeen = Date.now();
|
|
5253
|
+
if (auth) {
|
|
5254
|
+
entry.session.updateAuth(auth);
|
|
5255
|
+
}
|
|
5256
|
+
return mcpTransportHeaders.run(
|
|
5257
|
+
request.headers,
|
|
5258
|
+
() => entry.transport.handleRequest(request)
|
|
5259
|
+
);
|
|
5260
|
+
}
|
|
5261
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
5262
|
+
sessionIdGenerator: () => randomUUID2(),
|
|
5263
|
+
onsessioninitialized: (id) => {
|
|
5264
|
+
sessions.set(id, { transport, session, lastSeen: Date.now() });
|
|
5265
|
+
},
|
|
5266
|
+
onsessionclosed: (id) => {
|
|
5267
|
+
sessions.delete(id);
|
|
5268
|
+
}
|
|
5269
|
+
});
|
|
5270
|
+
const session = await mcpServer.connect(transport, auth);
|
|
5271
|
+
transport.onclose = /* @__PURE__ */ ((onclose) => () => {
|
|
5272
|
+
if (transport.sessionId) {
|
|
5273
|
+
sessions.delete(transport.sessionId);
|
|
5274
|
+
}
|
|
5275
|
+
onclose?.();
|
|
5276
|
+
})(transport.onclose);
|
|
5277
|
+
const response = await mcpTransportHeaders.run(
|
|
5278
|
+
request.headers,
|
|
5279
|
+
() => transport.handleRequest(request)
|
|
5280
|
+
);
|
|
5281
|
+
if (!transport.sessionId) {
|
|
5282
|
+
await session.close();
|
|
5283
|
+
}
|
|
5284
|
+
return response;
|
|
5285
|
+
}
|
|
5286
|
+
async function handle(request, authRequest) {
|
|
5287
|
+
const authResult = await authenticateRequest(authRequest);
|
|
5288
|
+
if (!authResult.ok) {
|
|
5289
|
+
return jsonRpcError(401, -32001, "Unauthorized", {
|
|
5290
|
+
"WWW-Authenticate": "Bearer"
|
|
5291
|
+
});
|
|
5292
|
+
}
|
|
5293
|
+
return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
|
|
5294
|
+
}
|
|
5295
|
+
async function close() {
|
|
5296
|
+
if (sweepTimer) {
|
|
5297
|
+
clearInterval(sweepTimer);
|
|
5298
|
+
}
|
|
5299
|
+
const entries = [...sessions.values()];
|
|
5300
|
+
sessions.clear();
|
|
5301
|
+
await Promise.all(entries.map(({ session }) => session.close()));
|
|
5302
|
+
}
|
|
5303
|
+
return { handle, close, sessions };
|
|
5304
|
+
}
|
|
5305
|
+
function closeWhenBodyEnds(response, done) {
|
|
5306
|
+
if (!response.body) {
|
|
5307
|
+
done();
|
|
5308
|
+
return response;
|
|
5309
|
+
}
|
|
5310
|
+
const reader = response.body.getReader();
|
|
5311
|
+
const body = new ReadableStream({
|
|
5312
|
+
async pull(controller) {
|
|
5313
|
+
try {
|
|
5314
|
+
const { done: finished, value } = await reader.read();
|
|
5315
|
+
if (finished) {
|
|
5316
|
+
controller.close();
|
|
5317
|
+
done();
|
|
5318
|
+
} else {
|
|
5319
|
+
controller.enqueue(value);
|
|
5320
|
+
}
|
|
5321
|
+
} catch (error) {
|
|
5322
|
+
controller.error(error);
|
|
5323
|
+
done();
|
|
5324
|
+
}
|
|
5325
|
+
},
|
|
5326
|
+
cancel(reason) {
|
|
5327
|
+
done();
|
|
5328
|
+
return reader.cancel(reason);
|
|
5329
|
+
}
|
|
5330
|
+
});
|
|
5331
|
+
return new Response(body, {
|
|
5332
|
+
status: response.status,
|
|
5333
|
+
statusText: response.statusText,
|
|
5334
|
+
headers: response.headers
|
|
5335
|
+
});
|
|
5336
|
+
}
|
|
5337
|
+
function isSeparateMcpListener(configuredPort) {
|
|
5338
|
+
return process.env.MCP_LISTENER === "separate" || configuredPort != null || Boolean(Number(process.env.MCP_PORT));
|
|
5339
|
+
}
|
|
5340
|
+
|
|
4783
5341
|
// src/http/mcpGenerator/mcpGenerator.ts
|
|
4784
5342
|
function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
|
|
4785
5343
|
let discriminatedBody;
|
|
@@ -4809,6 +5367,36 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
|
|
|
4809
5367
|
} : {}
|
|
4810
5368
|
});
|
|
4811
5369
|
}
|
|
5370
|
+
function buildRouteHeaders(toolHeaders, contentType) {
|
|
5371
|
+
const transportHeaders = getMcpTransportHeaders();
|
|
5372
|
+
const routeHeaders = new Headers();
|
|
5373
|
+
const authorization = transportHeaders?.get("authorization");
|
|
5374
|
+
if (authorization) {
|
|
5375
|
+
routeHeaders.set("authorization", authorization);
|
|
5376
|
+
}
|
|
5377
|
+
for (const [name, value] of Object.entries(toolHeaders ?? {})) {
|
|
5378
|
+
if (value != null) {
|
|
5379
|
+
routeHeaders.set(name, String(value));
|
|
5380
|
+
}
|
|
5381
|
+
}
|
|
5382
|
+
const correlationId = transportHeaders?.get("x-correlation-id");
|
|
5383
|
+
if (correlationId) {
|
|
5384
|
+
routeHeaders.set("x-correlation-id", correlationId);
|
|
5385
|
+
}
|
|
5386
|
+
const traceparent = transportHeaders?.get("traceparent");
|
|
5387
|
+
if (traceparent) {
|
|
5388
|
+
routeHeaders.set("traceparent", traceparent);
|
|
5389
|
+
routeHeaders.delete("tracestate");
|
|
5390
|
+
const tracestate = transportHeaders?.get("tracestate");
|
|
5391
|
+
if (tracestate) {
|
|
5392
|
+
routeHeaders.set("tracestate", tracestate);
|
|
5393
|
+
}
|
|
5394
|
+
}
|
|
5395
|
+
if (contentType !== void 0) {
|
|
5396
|
+
routeHeaders.set("content-type", contentType);
|
|
5397
|
+
}
|
|
5398
|
+
return routeHeaders;
|
|
5399
|
+
}
|
|
4812
5400
|
function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate) {
|
|
4813
5401
|
if (!(schemaValidator instanceof ZodSchemaValidator)) {
|
|
4814
5402
|
throw new Error(
|
|
@@ -4901,7 +5489,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
4901
5489
|
break;
|
|
4902
5490
|
}
|
|
4903
5491
|
case "file": {
|
|
4904
|
-
parsedBody = Buffer.from(
|
|
5492
|
+
parsedBody = Buffer.from(safeStringify3(body));
|
|
4905
5493
|
break;
|
|
4906
5494
|
}
|
|
4907
5495
|
case "multipart": {
|
|
@@ -4935,7 +5523,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
4935
5523
|
parsedBody = new URLSearchParams(
|
|
4936
5524
|
Object.entries(body).map(([key, value]) => [
|
|
4937
5525
|
key,
|
|
4938
|
-
|
|
5526
|
+
safeStringify3(value)
|
|
4939
5527
|
])
|
|
4940
5528
|
);
|
|
4941
5529
|
} else {
|
|
@@ -4945,7 +5533,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
4945
5533
|
}
|
|
4946
5534
|
default: {
|
|
4947
5535
|
isNever3(discriminatedBody.parserType);
|
|
4948
|
-
parsedBody =
|
|
5536
|
+
parsedBody = safeStringify3(body);
|
|
4949
5537
|
break;
|
|
4950
5538
|
}
|
|
4951
5539
|
}
|
|
@@ -4954,19 +5542,17 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
4954
5542
|
const queryString = new URLSearchParams(
|
|
4955
5543
|
Object.entries(query).map(([key, value]) => [
|
|
4956
5544
|
key,
|
|
4957
|
-
|
|
5545
|
+
safeStringify3(value)
|
|
4958
5546
|
])
|
|
4959
5547
|
).toString();
|
|
4960
5548
|
url += queryString ? `?${queryString}` : "";
|
|
4961
5549
|
}
|
|
4962
5550
|
const response = await fetch(url, {
|
|
4963
5551
|
method: route.method.toUpperCase(),
|
|
4964
|
-
headers:
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
} : {}
|
|
4969
|
-
},
|
|
5552
|
+
headers: buildRouteHeaders(
|
|
5553
|
+
headers,
|
|
5554
|
+
discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
|
|
5555
|
+
),
|
|
4970
5556
|
body: parsedBody
|
|
4971
5557
|
});
|
|
4972
5558
|
if (response.status >= 300) {
|
|
@@ -4987,7 +5573,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
4987
5573
|
content: [
|
|
4988
5574
|
{
|
|
4989
5575
|
type: "text",
|
|
4990
|
-
text:
|
|
5576
|
+
text: safeStringify3(await response.json())
|
|
4991
5577
|
}
|
|
4992
5578
|
]
|
|
4993
5579
|
};
|
|
@@ -5178,7 +5764,7 @@ import {
|
|
|
5178
5764
|
isNodeJsWriteableStream,
|
|
5179
5765
|
isRecord as isRecord4,
|
|
5180
5766
|
readableStreamToAsyncIterable,
|
|
5181
|
-
safeStringify as
|
|
5767
|
+
safeStringify as safeStringify4
|
|
5182
5768
|
} from "@forklaunch/common";
|
|
5183
5769
|
import { Readable, Transform } from "stream";
|
|
5184
5770
|
|
|
@@ -5281,7 +5867,7 @@ ${res.locals.errorMessage}`;
|
|
|
5281
5867
|
} else {
|
|
5282
5868
|
let data2 = "";
|
|
5283
5869
|
for (const [key, value] of Object.entries(chunk)) {
|
|
5284
|
-
data2 += `${key}: ${typeof value === "string" ? value :
|
|
5870
|
+
data2 += `${key}: ${typeof value === "string" ? value : safeStringify4(value)}
|
|
5285
5871
|
`;
|
|
5286
5872
|
}
|
|
5287
5873
|
data2 += "\n";
|
|
@@ -5292,7 +5878,7 @@ ${res.locals.errorMessage}`;
|
|
|
5292
5878
|
} else if (!errorSent) {
|
|
5293
5879
|
let data2 = "";
|
|
5294
5880
|
for (const [key, value] of Object.entries(chunk)) {
|
|
5295
|
-
data2 += `${key}: ${typeof value === "string" ? value :
|
|
5881
|
+
data2 += `${key}: ${typeof value === "string" ? value : safeStringify4(value)}
|
|
5296
5882
|
`;
|
|
5297
5883
|
}
|
|
5298
5884
|
data2 += "\n";
|
|
@@ -5939,12 +6525,17 @@ export {
|
|
|
5939
6525
|
ATTR_HTTP_ROUTE,
|
|
5940
6526
|
ATTR_SERVICE_NAME,
|
|
5941
6527
|
AuditLogger,
|
|
6528
|
+
DEFAULT_HMAC_MAX_SKEW_MS,
|
|
6529
|
+
DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES,
|
|
6530
|
+
DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
|
|
6531
|
+
DEFAULT_SHARED_SECRET_JWT_ALGORITHMS,
|
|
5942
6532
|
EMAIL_LIMITS,
|
|
5943
6533
|
EmailRequestError,
|
|
5944
6534
|
ForklaunchExpressLikeApplication,
|
|
5945
6535
|
ForklaunchExpressLikeRouter,
|
|
5946
6536
|
HTTPStatuses,
|
|
5947
6537
|
INSTANCE_GATEWAY_MOUNT,
|
|
6538
|
+
InMemoryHmacNonceStore,
|
|
5948
6539
|
InstanceGatewayRequestError,
|
|
5949
6540
|
ModelGatewayRequestError,
|
|
5950
6541
|
OPENAPI_DEFAULT_VERSION,
|
|
@@ -5955,6 +6546,7 @@ export {
|
|
|
5955
6546
|
PinoLogger,
|
|
5956
6547
|
PlatformEventVerificationError,
|
|
5957
6548
|
RateLimiter,
|
|
6549
|
+
SHARED_SECRET_JWT_ALGORITHMS,
|
|
5958
6550
|
SMS_MAX_SEGMENTS,
|
|
5959
6551
|
STRIPE_GATEWAY_ROUTE,
|
|
5960
6552
|
SmsClient,
|
|
@@ -5973,6 +6565,7 @@ export {
|
|
|
5973
6565
|
createHmacToken,
|
|
5974
6566
|
createInstanceGatewayTransport,
|
|
5975
6567
|
createLocalModelGatewayClient,
|
|
6568
|
+
createMcpHttpHandler,
|
|
5976
6569
|
createModelGatewayClient,
|
|
5977
6570
|
createPaymentsClient,
|
|
5978
6571
|
createPreviewModelGatewayClient,
|
|
@@ -5993,7 +6586,10 @@ export {
|
|
|
5993
6586
|
get,
|
|
5994
6587
|
getCachedJwks,
|
|
5995
6588
|
getCodeForStatus,
|
|
6589
|
+
getMcpTransportHeaders,
|
|
5996
6590
|
head,
|
|
6591
|
+
hmacNonceKey,
|
|
6592
|
+
hmacNonceTtlMs,
|
|
5997
6593
|
httpErrorsTotalCounter,
|
|
5998
6594
|
httpRequestDurationMsHistogram,
|
|
5999
6595
|
httpRequestsInFlightCounter,
|
|
@@ -6005,13 +6601,18 @@ export {
|
|
|
6005
6601
|
isEmailAddress,
|
|
6006
6602
|
isForklaunchRequest,
|
|
6007
6603
|
isForklaunchRouter,
|
|
6604
|
+
isHmacTimestampFresh,
|
|
6008
6605
|
isInformational,
|
|
6009
6606
|
isManagedInstance,
|
|
6010
6607
|
isPortBound,
|
|
6011
6608
|
isRedirection,
|
|
6609
|
+
isSeparateMcpListener,
|
|
6012
6610
|
isServerError,
|
|
6013
6611
|
isSuccessful,
|
|
6014
6612
|
isValidStatusCode,
|
|
6613
|
+
jwtAlgorithmsForPublicKey,
|
|
6614
|
+
jwtAlgorithmsForSharedSecret,
|
|
6615
|
+
jwtClaimChecks,
|
|
6015
6616
|
logger,
|
|
6016
6617
|
meta,
|
|
6017
6618
|
metricsDefinitions,
|
|
@@ -6024,10 +6625,14 @@ export {
|
|
|
6024
6625
|
recordRequestAudit,
|
|
6025
6626
|
registerDelegatedSurface,
|
|
6026
6627
|
resetProcessHandlersForTesting,
|
|
6628
|
+
resolveHmacMaxSkewMs,
|
|
6629
|
+
resolveHmacNonceStore,
|
|
6027
6630
|
signPlatformEvent,
|
|
6028
6631
|
smsSegments,
|
|
6029
6632
|
stripeGatewayFetch,
|
|
6633
|
+
timingSafeEqualStrings,
|
|
6030
6634
|
trace3 as trace,
|
|
6635
|
+
ttlCacheHmacNonceStore,
|
|
6031
6636
|
typedAuthHandler,
|
|
6032
6637
|
typedHandler,
|
|
6033
6638
|
validateEmailSendRequest,
|