@forklaunch/core 3.5.0 → 4.1.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/http/index.js CHANGED
@@ -38,13 +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,
41
43
  DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS: () => DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
44
+ DEFAULT_SHARED_SECRET_JWT_ALGORITHMS: () => DEFAULT_SHARED_SECRET_JWT_ALGORITHMS,
42
45
  EMAIL_LIMITS: () => EMAIL_LIMITS,
43
46
  EmailRequestError: () => EmailRequestError,
44
47
  ForklaunchExpressLikeApplication: () => ForklaunchExpressLikeApplication,
45
48
  ForklaunchExpressLikeRouter: () => ForklaunchExpressLikeRouter,
46
49
  HTTPStatuses: () => HTTPStatuses,
47
50
  INSTANCE_GATEWAY_MOUNT: () => INSTANCE_GATEWAY_MOUNT,
51
+ InMemoryHmacNonceStore: () => InMemoryHmacNonceStore,
48
52
  InstanceGatewayRequestError: () => InstanceGatewayRequestError,
49
53
  ModelGatewayRequestError: () => ModelGatewayRequestError,
50
54
  OPENAPI_DEFAULT_VERSION: () => OPENAPI_DEFAULT_VERSION,
@@ -55,6 +59,7 @@ __export(http_exports, {
55
59
  PinoLogger: () => PinoLogger,
56
60
  PlatformEventVerificationError: () => PlatformEventVerificationError,
57
61
  RateLimiter: () => RateLimiter,
62
+ SHARED_SECRET_JWT_ALGORITHMS: () => SHARED_SECRET_JWT_ALGORITHMS,
58
63
  SMS_MAX_SEGMENTS: () => SMS_MAX_SEGMENTS,
59
64
  STRIPE_GATEWAY_ROUTE: () => STRIPE_GATEWAY_ROUTE,
60
65
  SmsClient: () => SmsClient,
@@ -96,6 +101,8 @@ __export(http_exports, {
96
101
  getCodeForStatus: () => getCodeForStatus,
97
102
  getMcpTransportHeaders: () => getMcpTransportHeaders,
98
103
  head: () => head,
104
+ hmacNonceKey: () => hmacNonceKey,
105
+ hmacNonceTtlMs: () => hmacNonceTtlMs,
99
106
  httpErrorsTotalCounter: () => httpErrorsTotalCounter,
100
107
  httpRequestDurationMsHistogram: () => httpRequestDurationMsHistogram,
101
108
  httpRequestsInFlightCounter: () => httpRequestsInFlightCounter,
@@ -107,6 +114,7 @@ __export(http_exports, {
107
114
  isEmailAddress: () => isEmailAddress,
108
115
  isForklaunchRequest: () => isForklaunchRequest,
109
116
  isForklaunchRouter: () => isForklaunchRouter,
117
+ isHmacTimestampFresh: () => isHmacTimestampFresh,
110
118
  isInformational: () => isInformational,
111
119
  isManagedInstance: () => isManagedInstance,
112
120
  isPortBound: () => isPortBound,
@@ -115,6 +123,9 @@ __export(http_exports, {
115
123
  isServerError: () => isServerError,
116
124
  isSuccessful: () => isSuccessful,
117
125
  isValidStatusCode: () => isValidStatusCode,
126
+ jwtAlgorithmsForPublicKey: () => jwtAlgorithmsForPublicKey,
127
+ jwtAlgorithmsForSharedSecret: () => jwtAlgorithmsForSharedSecret,
128
+ jwtClaimChecks: () => jwtClaimChecks,
118
129
  logger: () => logger,
119
130
  meta: () => meta,
120
131
  metricsDefinitions: () => metricsDefinitions,
@@ -127,10 +138,14 @@ __export(http_exports, {
127
138
  recordRequestAudit: () => recordRequestAudit,
128
139
  registerDelegatedSurface: () => registerDelegatedSurface,
129
140
  resetProcessHandlersForTesting: () => resetProcessHandlersForTesting,
141
+ resolveHmacMaxSkewMs: () => resolveHmacMaxSkewMs,
142
+ resolveHmacNonceStore: () => resolveHmacNonceStore,
130
143
  signPlatformEvent: () => signPlatformEvent,
131
144
  smsSegments: () => smsSegments,
132
145
  stripeGatewayFetch: () => stripeGatewayFetch,
146
+ timingSafeEqualStrings: () => timingSafeEqualStrings,
133
147
  trace: () => trace3,
148
+ ttlCacheHmacNonceStore: () => ttlCacheHmacNonceStore,
134
149
  typedAuthHandler: () => typedAuthHandler,
135
150
  typedHandler: () => typedHandler,
136
151
  validateEmailSendRequest: () => validateEmailSendRequest,
@@ -142,6 +157,10 @@ __export(http_exports, {
142
157
  module.exports = __toCommonJS(http_exports);
143
158
 
144
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);
145
164
  function bindRuntimeAuth(details, binding) {
146
165
  const policy = { ...details.auth };
147
166
  const keys = Object.keys(binding);
@@ -168,10 +187,26 @@ function bindRuntimeAuth(details, binding) {
168
187
  let authentication;
169
188
  if (policy.scheme === "jwt") {
170
189
  if (keys.some(
171
- (key) => !["jwksPublicKeyUrl", "signatureKey", "decodeResource"].includes(key)
190
+ (key) => ![
191
+ "jwksPublicKeyUrl",
192
+ "signatureKey",
193
+ "decodeResource",
194
+ ...JWT_VERIFICATION_KEYS
195
+ ].includes(key)
172
196
  ))
173
197
  invalid();
174
- const keyFields = keys.filter((key) => key !== "decodeResource");
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
+ );
175
210
  if (keyFields.length !== 1 || typeof credentials[keyFields[0]] !== "string" || !credentials[keyFields[0]])
176
211
  invalid();
177
212
  const decodeResource = credentials.decodeResource;
@@ -183,7 +218,13 @@ function bindRuntimeAuth(details, binding) {
183
218
  ...decodeResource === void 0 ? {} : { decodeResource }
184
219
  };
185
220
  } else if (policy.scheme === "hmac") {
186
- if (keys.length !== 1 || keys[0] !== "secretKeys" || !credentials.secretKeys || typeof credentials.secretKeys !== "object" || Array.isArray(credentials.secretKeys) || Object.keys(credentials.secretKeys).length === 0 || Object.values(credentials.secretKeys).some(
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(
187
228
  (key) => typeof key !== "string" || !key
188
229
  ))
189
230
  invalid();
@@ -205,7 +246,74 @@ function bindRuntimeAuth(details, binding) {
205
246
 
206
247
  // src/http/middleware/request/cors.middleware.ts
207
248
  var import_cors = __toESM(require("cors"));
249
+ var CORS_ORIGINS_ENV = "CORS_ORIGINS";
250
+ var CORS_FROM_ENVIRONMENT = "environment";
251
+ var LOCAL_DEVELOPMENT_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/;
252
+ function parseCorsOrigins(value) {
253
+ const origins = [];
254
+ for (const entry of (value ?? "").split(",")) {
255
+ let origin = entry.trim();
256
+ while (origin.length > 1 && origin.endsWith("/")) {
257
+ origin = origin.slice(0, -1);
258
+ }
259
+ if (origin && !origins.includes(origin)) origins.push(origin);
260
+ }
261
+ return origins;
262
+ }
263
+ function isWildcardOrigin(origin) {
264
+ return origin === void 0 || origin === "*";
265
+ }
266
+ function defaultCorsOrigin(env) {
267
+ const listed = parseCorsOrigins(env[CORS_ORIGINS_ENV]);
268
+ if (listed.includes("*")) {
269
+ return { origin: "*", configured: true };
270
+ }
271
+ if (listed.length > 0) {
272
+ return { origin: listed, configured: true };
273
+ }
274
+ return {
275
+ origin: env.NODE_ENV === "production" ? false : LOCAL_DEVELOPMENT_ORIGIN,
276
+ configured: false
277
+ };
278
+ }
279
+ function withoutWildcardCredentials(options2) {
280
+ return options2.credentials === true && isWildcardOrigin(options2.origin) ? { ...options2, credentials: false } : options2;
281
+ }
282
+ function resolveCorsOptions(appCorsOption, env = process.env) {
283
+ const appCors = appCorsOption === CORS_FROM_ENVIRONMENT ? void 0 : appCorsOption;
284
+ 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.`;
285
+ if (appCors !== void 0) {
286
+ if (appCors.credentials === true && isWildcardOrigin(appCors.origin)) {
287
+ return {
288
+ options: appCors,
289
+ 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."
290
+ };
291
+ }
292
+ if (appCors.origin === void 0) {
293
+ return {
294
+ options: appCors,
295
+ 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: '*' }\`.`
296
+ };
297
+ }
298
+ return { options: appCors };
299
+ }
300
+ const { origin, configured } = defaultCorsOrigin(env);
301
+ if (configured) {
302
+ return { options: { origin } };
303
+ }
304
+ return {
305
+ options: { origin },
306
+ 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
307
+ };
308
+ }
208
309
  function cors(corsOptions) {
310
+ const configuredOrigin = corsOptions.origin;
311
+ const staticHandler = (0, import_cors.default)(withoutWildcardCredentials(corsOptions));
312
+ const wildcardHandler = (0, import_cors.default)({
313
+ ...corsOptions,
314
+ origin: "*",
315
+ credentials: false
316
+ });
209
317
  return (req, res, next) => {
210
318
  if (req.method === "OPTIONS") {
211
319
  res.cors = true;
@@ -215,17 +323,27 @@ function cors(corsOptions) {
215
323
  return res.getHeaders()[key];
216
324
  };
217
325
  }
218
- (0, import_cors.default)(corsOptions)(
219
- req,
220
- res,
221
- next ?? (() => {
222
- })
223
- );
326
+ const corsRequest = req;
327
+ const done = next ?? (() => {
328
+ });
329
+ if (corsOptions.credentials === true && typeof configuredOrigin === "function") {
330
+ configuredOrigin(corsRequest.headers.origin, (error, origin) => {
331
+ if (error || !origin) {
332
+ done(error ?? void 0);
333
+ } else if (origin === "*") {
334
+ wildcardHandler(corsRequest, res, done);
335
+ } else {
336
+ (0, import_cors.default)({ ...corsOptions, origin })(corsRequest, res, done);
337
+ }
338
+ });
339
+ return;
340
+ }
341
+ staticHandler(corsRequest, res, done);
224
342
  };
225
343
  }
226
344
 
227
345
  // src/http/router/expressLikeRouter.ts
228
- var import_common12 = require("@forklaunch/common");
346
+ var import_common11 = require("@forklaunch/common");
229
347
 
230
348
  // src/http/guards/hasPermissionChecks.ts
231
349
  function hasPermissionChecks(maybePermissionedAuth) {
@@ -797,7 +915,7 @@ function discriminateResponseBodies(schemaValidator, responses) {
797
915
  }
798
916
 
799
917
  // src/http/router/routerSharedLogic.ts
800
- var import_common11 = require("@forklaunch/common");
918
+ var import_common10 = require("@forklaunch/common");
801
919
 
802
920
  // src/http/guards/hasVersionedSchema.ts
803
921
  function hasVersionedSchema(contractDetails) {
@@ -824,11 +942,10 @@ function isHttpContractDetails(maybeContractDetails) {
824
942
  }
825
943
 
826
944
  // src/http/middleware/request/auth.middleware.ts
827
- var import_common7 = require("@forklaunch/common");
945
+ var import_common6 = require("@forklaunch/common");
828
946
  var import_validator = require("@forklaunch/validator");
829
947
 
830
948
  // src/http/discriminateAuthMethod.ts
831
- var import_common6 = require("@forklaunch/common");
832
949
  var import_jose = require("jose");
833
950
 
834
951
  // src/http/createHmacToken.ts
@@ -854,6 +971,227 @@ ${nonce}`
854
971
  return hmac.digest("base64");
855
972
  }
856
973
 
974
+ // src/http/hmacReplayProtection.ts
975
+ var import_crypto2 = require("crypto");
976
+ var DEFAULT_HMAC_MAX_SKEW_MS = 5 * 60 * 1e3;
977
+ var DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES = 1e5;
978
+ function timingSafeEqualStrings(expected, received) {
979
+ if (typeof expected !== "string" || typeof received !== "string") {
980
+ return false;
981
+ }
982
+ const expectedBytes = Buffer.from(expected);
983
+ const receivedBytes = Buffer.from(received);
984
+ return expectedBytes.length === receivedBytes.length && (0, import_crypto2.timingSafeEqual)(expectedBytes, receivedBytes);
985
+ }
986
+ function resolveHmacMaxSkewMs(maxSkewMs) {
987
+ return typeof maxSkewMs === "number" && Number.isFinite(maxSkewMs) && maxSkewMs > 0 ? maxSkewMs : DEFAULT_HMAC_MAX_SKEW_MS;
988
+ }
989
+ function isHmacTimestampFresh(timestamp, nowMs, maxSkewMs = DEFAULT_HMAC_MAX_SKEW_MS) {
990
+ if (!(timestamp instanceof Date)) return false;
991
+ const at = timestamp.getTime();
992
+ return !Number.isNaN(at) && Math.abs(nowMs - at) <= maxSkewMs;
993
+ }
994
+ function hmacNonceTtlMs(timestamp, nowMs, maxSkewMs) {
995
+ return Math.max(1, timestamp.getTime() + maxSkewMs - nowMs);
996
+ }
997
+ function hmacNonceKey(keyId, nonce) {
998
+ const id = keyId ?? "";
999
+ return `${id.length}:${id}${nonce}`;
1000
+ }
1001
+ var InMemoryHmacNonceStore = class {
1002
+ entries = /* @__PURE__ */ new Map();
1003
+ maxEntries;
1004
+ sweepIntervalMs;
1005
+ lastSweepAt = 0;
1006
+ constructor(options2 = {}) {
1007
+ this.maxEntries = typeof options2.maxEntries === "number" && options2.maxEntries >= 1 ? Math.floor(options2.maxEntries) : DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES;
1008
+ this.sweepIntervalMs = options2.sweepIntervalMs ?? 3e4;
1009
+ }
1010
+ /** Number of nonces currently held (expired ones may linger until swept). */
1011
+ get size() {
1012
+ return this.entries.size;
1013
+ }
1014
+ claim(key, ttlMs, nowMs = Date.now()) {
1015
+ const expiresAt = this.entries.get(key);
1016
+ if (expiresAt !== void 0 && expiresAt > nowMs) {
1017
+ return false;
1018
+ }
1019
+ if (this.entries.size >= this.maxEntries || nowMs - this.lastSweepAt >= this.sweepIntervalMs) {
1020
+ this.sweep(nowMs);
1021
+ }
1022
+ this.entries.delete(key);
1023
+ while (this.entries.size >= this.maxEntries) {
1024
+ const oldest = this.entries.keys().next();
1025
+ if (oldest.done) break;
1026
+ this.entries.delete(oldest.value);
1027
+ }
1028
+ this.entries.set(key, nowMs + Math.max(1, ttlMs));
1029
+ return true;
1030
+ }
1031
+ sweep(nowMs) {
1032
+ this.lastSweepAt = nowMs;
1033
+ for (const [key, expiresAt] of this.entries) {
1034
+ if (expiresAt <= nowMs) this.entries.delete(key);
1035
+ }
1036
+ }
1037
+ };
1038
+ function ttlCacheHmacNonceStore(cache, keyPrefix = "hmac-nonce:") {
1039
+ return {
1040
+ async claim(key, ttlMs) {
1041
+ const record2 = {
1042
+ key: `${keyPrefix}${key}`,
1043
+ value: 1,
1044
+ ttlMilliseconds: Math.max(1, Math.ceil(ttlMs))
1045
+ };
1046
+ if (typeof cache.putRecordIfAbsent === "function") {
1047
+ return await cache.putRecordIfAbsent(record2) === true;
1048
+ }
1049
+ if (await cache.peekRecord(record2.key)) {
1050
+ return false;
1051
+ }
1052
+ await cache.putRecord(record2);
1053
+ return true;
1054
+ }
1055
+ };
1056
+ }
1057
+ var defaultHmacNonceStore = new InMemoryHmacNonceStore();
1058
+ var adaptedTtlCaches = /* @__PURE__ */ new WeakMap();
1059
+ function resolveHmacNonceStore(configured) {
1060
+ if (configured == null) {
1061
+ return defaultHmacNonceStore;
1062
+ }
1063
+ if (typeof configured.claim === "function") {
1064
+ return configured;
1065
+ }
1066
+ const cache = configured;
1067
+ if (typeof cache.putRecordIfAbsent !== "function" && (typeof cache.peekRecord !== "function" || typeof cache.putRecord !== "function")) {
1068
+ throw new Error(
1069
+ "hmac.nonceStore must be an HmacNonceStore ({ claim }) or a TtlCache"
1070
+ );
1071
+ }
1072
+ let adapted = adaptedTtlCaches.get(cache);
1073
+ if (!adapted) {
1074
+ adapted = ttlCacheHmacNonceStore(cache);
1075
+ adaptedTtlCaches.set(cache, adapted);
1076
+ }
1077
+ return adapted;
1078
+ }
1079
+
1080
+ // src/http/jwtAlgorithms.ts
1081
+ var SHARED_SECRET_JWT_ALGORITHMS = [
1082
+ "HS256",
1083
+ "HS384",
1084
+ "HS512"
1085
+ ];
1086
+ var DEFAULT_SHARED_SECRET_JWT_ALGORITHMS = [
1087
+ "HS256"
1088
+ ];
1089
+ var RSA_JWT_ALGORITHMS = [
1090
+ "RS256",
1091
+ "RS384",
1092
+ "RS512",
1093
+ "PS256",
1094
+ "PS384",
1095
+ "PS512"
1096
+ ];
1097
+ var EC_CURVE_JWT_ALGORITHMS = {
1098
+ "P-256": ["ES256"],
1099
+ "P-384": ["ES384"],
1100
+ "P-521": ["ES512"]
1101
+ };
1102
+ var OKP_CURVE_JWT_ALGORITHMS = {
1103
+ Ed25519: ["EdDSA", "Ed25519"]
1104
+ };
1105
+ function isSymmetricOrUnsigned(algorithm) {
1106
+ const normalized = algorithm.toUpperCase();
1107
+ return normalized === "NONE" || normalized.startsWith("HS");
1108
+ }
1109
+ function configuredList(configured) {
1110
+ if (configured == null) return void 0;
1111
+ if (!Array.isArray(configured)) {
1112
+ throw new Error("JWT `algorithms` must be an array of algorithm names");
1113
+ }
1114
+ return configured.filter(
1115
+ (algorithm) => typeof algorithm === "string"
1116
+ );
1117
+ }
1118
+ function jwtAlgorithmsForSharedSecret(configured) {
1119
+ const requested = configuredList(configured);
1120
+ if (requested === void 0) {
1121
+ return [...DEFAULT_SHARED_SECRET_JWT_ALGORITHMS];
1122
+ }
1123
+ const allowed = SHARED_SECRET_JWT_ALGORITHMS.filter(
1124
+ (algorithm) => requested.includes(algorithm)
1125
+ );
1126
+ if (allowed.length === 0) {
1127
+ throw new Error(
1128
+ "No usable JWT algorithm: a `signatureKey` verifies only HS256, HS384 or HS512"
1129
+ );
1130
+ }
1131
+ return allowed;
1132
+ }
1133
+ function algorithmsFittingPublicKey(key) {
1134
+ let fitting;
1135
+ switch (key.kty) {
1136
+ case "RSA":
1137
+ fitting = RSA_JWT_ALGORITHMS;
1138
+ break;
1139
+ case "EC":
1140
+ fitting = EC_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
1141
+ break;
1142
+ case "OKP":
1143
+ fitting = OKP_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
1144
+ break;
1145
+ case "AKP":
1146
+ fitting = typeof key.alg === "string" ? [key.alg] : [];
1147
+ break;
1148
+ default:
1149
+ fitting = [];
1150
+ }
1151
+ if (typeof key.alg === "string") {
1152
+ fitting = fitting.filter((algorithm) => algorithm === key.alg);
1153
+ }
1154
+ return fitting.filter((algorithm) => !isSymmetricOrUnsigned(algorithm));
1155
+ }
1156
+ function jwtAlgorithmsForPublicKey(key, configured) {
1157
+ if (key == null || typeof key !== "object") {
1158
+ throw new Error("No usable JWT algorithm: the verification key is missing");
1159
+ }
1160
+ if (key.kty === "oct") {
1161
+ throw new Error(
1162
+ "No usable JWT algorithm: a symmetric (oct) key cannot be used as a public key; use `signatureKey` for a shared secret"
1163
+ );
1164
+ }
1165
+ const requested = configuredList(configured);
1166
+ const allowed = algorithmsFittingPublicKey(key).filter(
1167
+ (algorithm) => requested === void 0 || requested.includes(algorithm)
1168
+ );
1169
+ if (allowed.length === 0) {
1170
+ throw new Error(
1171
+ "No usable JWT algorithm: none of the permitted asymmetric algorithms fits this public key"
1172
+ );
1173
+ }
1174
+ return allowed;
1175
+ }
1176
+ function claimExpectation(name, value) {
1177
+ if (value === void 0) return void 0;
1178
+ const values = typeof value === "string" ? [value] : value;
1179
+ if (!Array.isArray(values) || values.length === 0 || values.some((entry) => typeof entry !== "string" || entry.length === 0)) {
1180
+ throw new Error(
1181
+ `JWT \`${name}\` is configured but empty; set it to the expected value or remove it`
1182
+ );
1183
+ }
1184
+ return typeof value === "string" ? value : [...values];
1185
+ }
1186
+ function jwtClaimChecks(config) {
1187
+ const issuer = claimExpectation("issuer", config.issuer);
1188
+ const audience = claimExpectation("audience", config.audience);
1189
+ return {
1190
+ ...issuer === void 0 ? {} : { issuer },
1191
+ ...audience === void 0 ? {} : { audience }
1192
+ };
1193
+ }
1194
+
857
1195
  // src/http/guards/isBasicAuthMethod.ts
858
1196
  function isBasicAuthMethod(maybeBasicAuthMethod) {
859
1197
  return typeof maybeBasicAuthMethod === "object" && maybeBasicAuthMethod !== null && "basic" in maybeBasicAuthMethod && maybeBasicAuthMethod.basic != null;
@@ -907,11 +1245,16 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
907
1245
  } else if (isJwtAuthMethod(auth)) {
908
1246
  const jwt = auth.jwt;
909
1247
  let verificationFunction;
1248
+ const claimChecks = () => jwtClaimChecks(jwt);
910
1249
  if ("signatureKey" in jwt) {
911
1250
  verificationFunction = async (token) => {
912
1251
  const { payload } = await (0, import_jose.jwtVerify)(
913
1252
  token,
914
- new Uint8Array(Buffer.from(jwt.signatureKey))
1253
+ new Uint8Array(Buffer.from(jwt.signatureKey)),
1254
+ {
1255
+ ...claimChecks(),
1256
+ algorithms: jwtAlgorithmsForSharedSecret(jwt.algorithms)
1257
+ }
915
1258
  );
916
1259
  return payload;
917
1260
  };
@@ -926,7 +1269,10 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
926
1269
  let lastError;
927
1270
  for (const key of jwks) {
928
1271
  try {
929
- const { payload } = await (0, import_jose.jwtVerify)(token, key);
1272
+ const { payload } = await (0, import_jose.jwtVerify)(token, key, {
1273
+ ...claimChecks(),
1274
+ algorithms: jwtAlgorithmsForPublicKey(key, jwt.algorithms)
1275
+ });
930
1276
  return payload;
931
1277
  } catch (error) {
932
1278
  lastError = error;
@@ -947,10 +1293,19 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
947
1293
  }
948
1294
  };
949
1295
  } else if (isHmacMethod(auth)) {
1296
+ const maxSkewMs = resolveHmacMaxSkewMs(auth.hmac.maxSkewMs);
1297
+ const configuredNonceStore = auth.hmac.nonceStore;
950
1298
  authMethod = {
951
1299
  type: "hmac",
952
1300
  auth: {
953
1301
  secretKeys: auth.hmac.secretKeys,
1302
+ /**
1303
+ * Accepts a signed request only when its timestamp is inside the
1304
+ * skew window, its signature matches (constant-time compare) and
1305
+ * its nonce has not been used before. The nonce is claimed last, and
1306
+ * only for a valid signature, so a `false` for one candidate path
1307
+ * never burns the nonce for the next.
1308
+ */
954
1309
  verificationFunction: async ({
955
1310
  method,
956
1311
  path,
@@ -958,8 +1313,30 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
958
1313
  timestamp,
959
1314
  nonce,
960
1315
  signature,
961
- secretKey
1316
+ secretKey,
1317
+ keyId
962
1318
  }) => {
1319
+ const reject = (reason) => {
1320
+ openTelemetryCollector?.debug("[HMAC Verification Failed]", {
1321
+ reason,
1322
+ method,
1323
+ path,
1324
+ keyId,
1325
+ timestamp: timestamp instanceof Date && !Number.isNaN(timestamp.getTime()) ? timestamp.toISOString() : "invalid",
1326
+ bodyType: body ? typeof body : "undefined"
1327
+ });
1328
+ return false;
1329
+ };
1330
+ if (typeof secretKey !== "string" || secretKey.length === 0) {
1331
+ return reject("unknown key");
1332
+ }
1333
+ if (typeof nonce !== "string" || nonce.length === 0 || typeof signature !== "string") {
1334
+ return reject("missing nonce or signature");
1335
+ }
1336
+ const now = Date.now();
1337
+ if (!isHmacTimestampFresh(timestamp, now, maxSkewMs)) {
1338
+ return reject("stale or invalid timestamp");
1339
+ }
963
1340
  const computedSignature = createHmacToken({
964
1341
  method,
965
1342
  path,
@@ -968,23 +1345,26 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
968
1345
  nonce,
969
1346
  secretKey
970
1347
  });
971
- const isValid = computedSignature === signature;
972
- if (!isValid) {
973
- const errorInfo = {
974
- method,
975
- path,
976
- timestamp: timestamp.toISOString(),
977
- nonce,
978
- receivedSignature: signature,
979
- computedSignature
980
- };
981
- openTelemetryCollector?.debug("[HMAC Verification Failed]", {
982
- ...errorInfo,
983
- bodyType: body ? typeof body : "undefined",
984
- body: body ? (0, import_common6.safeStringify)(body) : "undefined"
985
- });
1348
+ if (!timingSafeEqualStrings(computedSignature, signature)) {
1349
+ return reject("signature mismatch");
986
1350
  }
987
- return isValid;
1351
+ let firstUse;
1352
+ try {
1353
+ firstUse = await resolveHmacNonceStore(configuredNonceStore).claim(
1354
+ hmacNonceKey(keyId, nonce),
1355
+ hmacNonceTtlMs(timestamp, now, maxSkewMs)
1356
+ );
1357
+ } catch (error) {
1358
+ openTelemetryCollector?.error(
1359
+ "[HMAC Nonce Store Failed]",
1360
+ error instanceof Error ? error.message : String(error)
1361
+ );
1362
+ return reject("nonce store unavailable");
1363
+ }
1364
+ if (firstUse !== true) {
1365
+ return reject("replayed nonce");
1366
+ }
1367
+ return true;
988
1368
  }
989
1369
  }
990
1370
  };
@@ -1006,7 +1386,7 @@ function hasSubscriptionChecks(maybeSubscriptionAuth) {
1006
1386
  }
1007
1387
 
1008
1388
  // src/http/middleware/request/authLogContext.ts
1009
- var import_crypto2 = require("crypto");
1389
+ var import_crypto3 = require("crypto");
1010
1390
  var import_jose2 = require("jose");
1011
1391
  var FINGERPRINT_LENGTH = 8;
1012
1392
  var MAX_CLAIM_LENGTH = 128;
@@ -1019,7 +1399,7 @@ function authLogContext(headerValue) {
1019
1399
  }
1020
1400
  const context2 = {
1021
1401
  hasToken: true,
1022
- tokenFingerprint: (0, import_crypto2.createHash)("sha256").update(headerValue).digest("hex").slice(0, FINGERPRINT_LENGTH)
1402
+ tokenFingerprint: (0, import_crypto3.createHash)("sha256").update(headerValue).digest("hex").slice(0, FINGERPRINT_LENGTH)
1023
1403
  };
1024
1404
  const parts = headerValue.trim().split(/\s+/);
1025
1405
  const candidate = parts[parts.length - 1];
@@ -1145,6 +1525,18 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
1145
1525
  if (!parsedKeyId || !parsedTimestamp || !parsedNonce || !parsedSignature) {
1146
1526
  return invalidAuthorizationTokenFormat;
1147
1527
  }
1528
+ const requestTimestamp = new Date(parsedTimestamp);
1529
+ if (Number.isNaN(requestTimestamp.getTime())) {
1530
+ return invalidAuthorizationTokenFormat;
1531
+ }
1532
+ const secretKeys = collapsedAuthorizationMethod.hmac.secretKeys;
1533
+ const secretKey = Object.prototype.hasOwnProperty.call(
1534
+ secretKeys,
1535
+ parsedKeyId
1536
+ ) ? secretKeys[parsedKeyId] : void 0;
1537
+ if (typeof secretKey !== "string" || secretKey.length === 0) {
1538
+ return invalidAuthorizationSignature;
1539
+ }
1148
1540
  let verificationResult = false;
1149
1541
  const signedPaths = hmacSignedPaths(req);
1150
1542
  for (const path of signedPaths) {
@@ -1152,10 +1544,11 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
1152
1544
  method: req?.method ?? "",
1153
1545
  path,
1154
1546
  body: req?._rawBody ?? req?.body,
1155
- timestamp: new Date(parsedTimestamp),
1547
+ timestamp: requestTimestamp,
1156
1548
  nonce: parsedNonce,
1157
1549
  signature: parsedSignature,
1158
- secretKey: collapsedAuthorizationMethod.hmac.secretKeys[parsedKeyId]
1550
+ secretKey,
1551
+ keyId: parsedKeyId
1159
1552
  }));
1160
1553
  if (verificationResult) {
1161
1554
  if (path !== signedPaths[0]) warnMountRelativeHmacPath();
@@ -1216,7 +1609,7 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
1216
1609
  break;
1217
1610
  }
1218
1611
  default:
1219
- (0, import_common7.isNever)(type);
1612
+ (0, import_common6.isNever)(type);
1220
1613
  return [401, "Invalid Authorization method."];
1221
1614
  }
1222
1615
  if (isHmacMethod(collapsedAuthorizationMethod) && sessionPayload == null) {
@@ -1374,10 +1767,10 @@ async function parseRequestAuth(req, res, next) {
1374
1767
  }
1375
1768
 
1376
1769
  // src/http/middleware/request/enrichDetails.middleware.ts
1377
- var import_common9 = require("@forklaunch/common");
1770
+ var import_common8 = require("@forklaunch/common");
1378
1771
 
1379
1772
  // src/http/telemetry/requestAudit.ts
1380
- var import_common8 = require("@forklaunch/common");
1773
+ var import_common7 = require("@forklaunch/common");
1381
1774
 
1382
1775
  // src/persistence/encryptedType.ts
1383
1776
  var import_core = require("@mikro-orm/core");
@@ -1408,7 +1801,7 @@ var SLOTS = globalThis[/* @__PURE__ */ Symbol.for("forklaunch.compliance.slots")
1408
1801
  var LOADED_TENANTS = globalThis[/* @__PURE__ */ Symbol.for("forklaunch.compliance.loadedTenants")] ??= /* @__PURE__ */ new WeakMap();
1409
1802
 
1410
1803
  // src/http/telemetry/auditLogger.ts
1411
- var import_crypto3 = require("crypto");
1804
+ var import_crypto4 = require("crypto");
1412
1805
  var AuditLogger = class {
1413
1806
  _otel;
1414
1807
  constructor(otel) {
@@ -1441,13 +1834,13 @@ var AuditLogger = class {
1441
1834
  if (body === void 0 || body === null || body === "") {
1442
1835
  return "";
1443
1836
  }
1444
- return (0, import_crypto3.createHash)("sha256").update(body).digest("hex");
1837
+ return (0, import_crypto4.createHash)("sha256").update(body).digest("hex");
1445
1838
  }
1446
1839
  };
1447
1840
 
1448
1841
  // src/http/telemetry/requestAudit.ts
1449
1842
  function auditEnabled() {
1450
- return (0, import_common8.getEnvVar)("FORKLAUNCH_AUDIT") !== "off";
1843
+ return (0, import_common7.getEnvVar)("FORKLAUNCH_AUDIT") !== "off";
1451
1844
  }
1452
1845
  var loggers = /* @__PURE__ */ new WeakMap();
1453
1846
  function loggerFor(otel) {
@@ -1554,8 +1947,8 @@ function enrichDetails(path, contractDetails, requestSchema, responseSchemas, op
1554
1947
  const [seconds, nanoseconds] = process.hrtime(startTime);
1555
1948
  const durationMs = seconds + nanoseconds / 1e9;
1556
1949
  httpServerDurationHistogram.record(durationMs, {
1557
- [import_semantic_conventions.ATTR_SERVICE_NAME]: (0, import_common9.getEnvVar)("OTEL_SERVICE_NAME") || "unknown",
1558
- [ATTR_APPLICATION_ID]: (0, import_common9.getEnvVar)("OTEL_APPLICATION_ID"),
1950
+ [import_semantic_conventions.ATTR_SERVICE_NAME]: (0, import_common8.getEnvVar)("OTEL_SERVICE_NAME") || "unknown",
1951
+ [ATTR_APPLICATION_ID]: (0, import_common8.getEnvVar)("OTEL_APPLICATION_ID"),
1559
1952
  [ATTR_API_NAME]: req.contractDetails?.name || "unknown",
1560
1953
  [import_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: req.method,
1561
1954
  [import_semantic_conventions.ATTR_HTTP_ROUTE]: req.originalPath || "unknown",
@@ -1567,7 +1960,7 @@ function enrichDetails(path, contractDetails, requestSchema, responseSchemas, op
1567
1960
  }
1568
1961
 
1569
1962
  // src/http/middleware/request/parse.middleware.ts
1570
- var import_common10 = require("@forklaunch/common");
1963
+ var import_common9 = require("@forklaunch/common");
1571
1964
  var import_validator2 = require("@forklaunch/validator");
1572
1965
 
1573
1966
  // src/http/guards/hasSend.ts
@@ -1611,7 +2004,7 @@ function parse(req, res, next) {
1611
2004
  let parsedRequest;
1612
2005
  let collectedParseErrors;
1613
2006
  if (req.contractDetails.versions) {
1614
- if ((0, import_common10.isRecord)(req.requestSchema)) {
2007
+ if ((0, import_common9.isRecord)(req.requestSchema)) {
1615
2008
  let runningParseErrors = "";
1616
2009
  matchedVersions = [];
1617
2010
  Object.entries(req.requestSchema).forEach(([version, schema]) => {
@@ -1841,13 +2234,13 @@ function compileRouteSchemas(contractDetails, schemaValidator) {
1841
2234
  versionedContractDetails,
1842
2235
  contractDetails.params
1843
2236
  );
1844
- if ((0, import_common11.isRecord)(requestSchema)) {
2237
+ if ((0, import_common10.isRecord)(requestSchema)) {
1845
2238
  requestSchema = {
1846
2239
  ...requestSchema,
1847
2240
  [version]: versionedRequestSchema
1848
2241
  };
1849
2242
  }
1850
- if ((0, import_common11.isRecord)(responseSchemas)) {
2243
+ if ((0, import_common10.isRecord)(responseSchemas)) {
1851
2244
  responseSchemas = {
1852
2245
  ...responseSchemas,
1853
2246
  [version]: versionedResponseSchemas
@@ -2243,8 +2636,8 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2243
2636
  ...middlewares,
2244
2637
  this.#parseAndRunControllerHandler(controllerHandler)
2245
2638
  );
2246
- (0, import_common12.toRecord)(this._fetchMap)[(0, import_common12.sanitizePathSlashes)(`${this.basePath}${path}`)] = {
2247
- ...this._fetchMap[(0, import_common12.sanitizePathSlashes)(`${this.basePath}${path}`)] ?? {},
2639
+ (0, import_common11.toRecord)(this._fetchMap)[(0, import_common11.sanitizePathSlashes)(`${this.basePath}${path}`)] = {
2640
+ ...this._fetchMap[(0, import_common11.sanitizePathSlashes)(`${this.basePath}${path}`)] ?? {},
2248
2641
  [method.toUpperCase()]: contractDetails.versions ? Object.fromEntries(
2249
2642
  Object.keys(contractDetails.versions).map((version) => [
2250
2643
  version,
@@ -2267,7 +2660,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2267
2660
  };
2268
2661
  const contractDetailsName = contractDetails.name;
2269
2662
  if (contractDetailsName) {
2270
- (0, import_common12.toRecord)(this.sdk)[(0, import_common12.toPrettyCamelCase)(contractDetailsName)] = contractDetails.versions ? Object.fromEntries(
2663
+ (0, import_common11.toRecord)(this.sdk)[(0, import_common11.toPrettyCamelCase)(contractDetailsName)] = contractDetails.versions ? Object.fromEntries(
2271
2664
  Object.keys(contractDetails.versions).map((version) => [
2272
2665
  version,
2273
2666
  (req) => this.#localParamRequest(
@@ -2371,10 +2764,10 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2371
2764
  }
2372
2765
  addRouterToSdk(router) {
2373
2766
  Object.entries(router._fetchMap).map(
2374
- ([key, value]) => (0, import_common12.toRecord)(this._fetchMap)[(0, import_common12.sanitizePathSlashes)(`${this.basePath}${key}`)] = value
2767
+ ([key, value]) => (0, import_common11.toRecord)(this._fetchMap)[(0, import_common11.sanitizePathSlashes)(`${this.basePath}${key}`)] = value
2375
2768
  );
2376
- const existingSdk = this.sdk[router.sdkName ?? (0, import_common12.toPrettyCamelCase)(router.basePath)];
2377
- (0, import_common12.toRecord)(this.sdk)[router.sdkName ?? (0, import_common12.toPrettyCamelCase)(router.basePath)] = {
2769
+ const existingSdk = this.sdk[router.sdkName ?? (0, import_common11.toPrettyCamelCase)(router.basePath)];
2770
+ (0, import_common11.toRecord)(this.sdk)[router.sdkName ?? (0, import_common11.toPrettyCamelCase)(router.basePath)] = {
2378
2771
  ...typeof existingSdk === "object" ? existingSdk : {},
2379
2772
  ...router.sdk
2380
2773
  };
@@ -2706,7 +3099,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2706
3099
  unpackSdks(sdks, path, routerUniquenessCache) {
2707
3100
  Object.entries(sdks).forEach(([key, maybeHandler]) => {
2708
3101
  if (isSdkHandler(maybeHandler)) {
2709
- const cacheKey = (0, import_common12.hashString)((0, import_common12.safeStringify)(maybeHandler));
3102
+ const cacheKey = (0, import_common11.hashString)((0, import_common11.safeStringify)(maybeHandler));
2710
3103
  if (routerUniquenessCache.has(cacheKey)) {
2711
3104
  throw new Error(`SDK handler ${key} is already registered`);
2712
3105
  }
@@ -2751,6 +3144,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2751
3144
  };
2752
3145
 
2753
3146
  // src/http/application/expressLikeApplication.ts
3147
+ var warnedAboutCorsDefaults = false;
2754
3148
  var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter {
2755
3149
  /**
2756
3150
  * Creates an instance of the Application class.
@@ -2775,7 +3169,14 @@ var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter
2775
3169
  this.postEnrichMiddleware = postEnrichMiddleware;
2776
3170
  this.openTelemetryCollector = openTelemetryCollector;
2777
3171
  this.appOptions = appOptions;
2778
- this.internal.use(cors(this.appOptions?.cors ?? {}));
3172
+ const { options: corsOptions, warning: corsWarning } = resolveCorsOptions(
3173
+ this.appOptions?.cors
3174
+ );
3175
+ if (corsWarning && !warnedAboutCorsDefaults) {
3176
+ warnedAboutCorsDefaults = true;
3177
+ this.openTelemetryCollector.warn(corsWarning);
3178
+ }
3179
+ this.internal.use(cors(corsOptions));
2779
3180
  }
2780
3181
  schemaValidator;
2781
3182
  internal;
@@ -2813,7 +3214,7 @@ function isPortBound(port, host = "localhost") {
2813
3214
  }
2814
3215
 
2815
3216
  // src/http/generateHmacAuthHeaders.ts
2816
- var import_crypto4 = require("crypto");
3217
+ var import_crypto5 = require("crypto");
2817
3218
  function generateHmacAuthHeaders({
2818
3219
  secretKey,
2819
3220
  method,
@@ -2822,7 +3223,7 @@ function generateHmacAuthHeaders({
2822
3223
  keyId = "default"
2823
3224
  }) {
2824
3225
  const timestamp = /* @__PURE__ */ new Date();
2825
- const nonce = (0, import_crypto4.randomUUID)();
3226
+ const nonce = (0, import_crypto5.randomUUID)();
2826
3227
  const signature = createHmacToken({
2827
3228
  secretKey,
2828
3229
  method,
@@ -2837,11 +3238,10 @@ function generateHmacAuthHeaders({
2837
3238
  }
2838
3239
 
2839
3240
  // src/http/instanceGateway.ts
2840
- var import_crypto5 = require("crypto");
2841
3241
  var INSTANCE_GATEWAY_MOUNT = "/instance-gateway";
2842
3242
  var PLATFORM_EVENT_KEY_ID = "platform";
2843
3243
  var PLATFORM_EVENTS_PATH = "/platform-events";
2844
- var MAX_SKEW_MS = 5 * 60 * 1e3;
3244
+ var MAX_SKEW_MS = DEFAULT_HMAC_MAX_SKEW_MS;
2845
3245
  var InstanceGatewayRequestError = class extends Error {
2846
3246
  constructor(status, message, retryAfterSeconds) {
2847
3247
  super(message);
@@ -2920,7 +3320,7 @@ function createInstanceGatewayTransport(options2 = {}, feature) {
2920
3320
  var PlatformEventVerificationError = class extends Error {
2921
3321
  name = "PlatformEventVerificationError";
2922
3322
  };
2923
- var seenEventNonces = /* @__PURE__ */ new Map();
3323
+ var seenEventNonces = new InMemoryHmacNonceStore();
2924
3324
  function verifyPlatformEvent(request, options2 = {}) {
2925
3325
  const hmacKey = options2.hmacKey ?? process.env.INSTANCE_HMAC_KEY;
2926
3326
  if (!hmacKey) {
@@ -2944,30 +3344,27 @@ function verifyPlatformEvent(request, options2 = {}) {
2944
3344
  }
2945
3345
  const timestamp = new Date(ts);
2946
3346
  const now = (options2.now ?? Date.now)();
2947
- if (Number.isNaN(timestamp.getTime()) || Math.abs(now - timestamp.getTime()) > MAX_SKEW_MS) {
3347
+ if (!isHmacTimestampFresh(timestamp, now, MAX_SKEW_MS)) {
2948
3348
  throw new PlatformEventVerificationError("Stale or invalid timestamp");
2949
3349
  }
2950
- const expected = Buffer.from(
2951
- createHmacToken({
2952
- secretKey: hmacKey,
2953
- method: request.method.toUpperCase(),
2954
- path: request.path,
2955
- body: request.body,
2956
- timestamp,
2957
- nonce
2958
- })
2959
- );
2960
- const received = Buffer.from(signature);
2961
- if (expected.length !== received.length || !(0, import_crypto5.timingSafeEqual)(expected, received)) {
3350
+ const expected = createHmacToken({
3351
+ secretKey: hmacKey,
3352
+ method: request.method.toUpperCase(),
3353
+ path: request.path,
3354
+ body: request.body,
3355
+ timestamp,
3356
+ nonce
3357
+ });
3358
+ if (!timingSafeEqualStrings(expected, signature)) {
2962
3359
  throw new PlatformEventVerificationError("Invalid signature");
2963
3360
  }
2964
- for (const [seen, at] of seenEventNonces) {
2965
- if (now - at > MAX_SKEW_MS) seenEventNonces.delete(seen);
2966
- }
2967
- if (seenEventNonces.has(nonce)) {
3361
+ if (!seenEventNonces.claim(
3362
+ hmacNonceKey(keyId, nonce),
3363
+ hmacNonceTtlMs(timestamp, now, MAX_SKEW_MS),
3364
+ now
3365
+ )) {
2968
3366
  throw new PlatformEventVerificationError("Replayed delivery");
2969
3367
  }
2970
- seenEventNonces.set(nonce, now);
2971
3368
  const parsed = typeof request.body === "string" || Buffer.isBuffer(request.body) ? JSON.parse(request.body.toString()) : request.body;
2972
3369
  const event = parsed;
2973
3370
  if (!event || typeof event.id !== "string" || typeof event.type !== "string" || typeof event.feature !== "string") {
@@ -4883,7 +5280,7 @@ var getCodeForStatus = (status) => {
4883
5280
  var httpStatusCodes_default = HTTPStatuses;
4884
5281
 
4885
5282
  // src/http/mcpGenerator/mcpGenerator.ts
4886
- var import_common13 = require("@forklaunch/common");
5283
+ var import_common12 = require("@forklaunch/common");
4887
5284
  var import_zod = require("@forklaunch/validator/zod");
4888
5285
  var import_fastmcp = require("fastmcp");
4889
5286
 
@@ -5232,12 +5629,12 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5232
5629
  break;
5233
5630
  }
5234
5631
  case "file": {
5235
- parsedBody = Buffer.from((0, import_common13.safeStringify)(body));
5632
+ parsedBody = Buffer.from((0, import_common12.safeStringify)(body));
5236
5633
  break;
5237
5634
  }
5238
5635
  case "multipart": {
5239
5636
  const formData = new FormData();
5240
- if ((0, import_common13.isRecord)(body)) {
5637
+ if ((0, import_common12.isRecord)(body)) {
5241
5638
  for (const key in body) {
5242
5639
  if (typeof body[key] === "string") {
5243
5640
  if (schemaValidator.isInstanceOf(
@@ -5262,11 +5659,11 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5262
5659
  break;
5263
5660
  }
5264
5661
  case "urlEncoded": {
5265
- if ((0, import_common13.isRecord)(body)) {
5662
+ if ((0, import_common12.isRecord)(body)) {
5266
5663
  parsedBody = new URLSearchParams(
5267
5664
  Object.entries(body).map(([key, value]) => [
5268
5665
  key,
5269
- (0, import_common13.safeStringify)(value)
5666
+ (0, import_common12.safeStringify)(value)
5270
5667
  ])
5271
5668
  );
5272
5669
  } else {
@@ -5275,8 +5672,8 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5275
5672
  break;
5276
5673
  }
5277
5674
  default: {
5278
- (0, import_common13.isNever)(discriminatedBody.parserType);
5279
- parsedBody = (0, import_common13.safeStringify)(body);
5675
+ (0, import_common12.isNever)(discriminatedBody.parserType);
5676
+ parsedBody = (0, import_common12.safeStringify)(body);
5280
5677
  break;
5281
5678
  }
5282
5679
  }
@@ -5285,7 +5682,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5285
5682
  const queryString = new URLSearchParams(
5286
5683
  Object.entries(query).map(([key, value]) => [
5287
5684
  key,
5288
- (0, import_common13.safeStringify)(value)
5685
+ (0, import_common12.safeStringify)(value)
5289
5686
  ])
5290
5687
  ).toString();
5291
5688
  url += queryString ? `?${queryString}` : "";
@@ -5316,7 +5713,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5316
5713
  content: [
5317
5714
  {
5318
5715
  type: "text",
5319
- text: (0, import_common13.safeStringify)(await response.json())
5716
+ text: (0, import_common12.safeStringify)(await response.json())
5320
5717
  }
5321
5718
  ]
5322
5719
  };
@@ -5499,20 +5896,20 @@ ${parseErrors.join("\n\n")}`
5499
5896
  }
5500
5897
 
5501
5898
  // src/http/middleware/response/enrichExpressLikeSend.middleware.ts
5502
- var import_common15 = require("@forklaunch/common");
5899
+ var import_common14 = require("@forklaunch/common");
5503
5900
  var import_stream = require("stream");
5504
5901
 
5505
5902
  // src/http/telemetry/recordMetric.ts
5506
- var import_common14 = require("@forklaunch/common");
5903
+ var import_common13 = require("@forklaunch/common");
5507
5904
  var import_semantic_conventions4 = require("@opentelemetry/semantic-conventions");
5508
5905
  function recordMetric(req, res) {
5509
5906
  if (res.metricRecorded) {
5510
5907
  return;
5511
5908
  }
5512
- const serviceName = (0, import_common14.getEnvVar)("OTEL_SERVICE_NAME") || "unknown";
5909
+ const serviceName = (0, import_common13.getEnvVar)("OTEL_SERVICE_NAME") || "unknown";
5513
5910
  const attrs = {
5514
5911
  [import_semantic_conventions4.ATTR_SERVICE_NAME]: serviceName,
5515
- [ATTR_APPLICATION_ID]: (0, import_common14.getEnvVar)("OTEL_APPLICATION_ID"),
5912
+ [ATTR_APPLICATION_ID]: (0, import_common13.getEnvVar)("OTEL_APPLICATION_ID"),
5516
5913
  [ATTR_API_NAME]: req.contractDetails?.name,
5517
5914
  [import_semantic_conventions4.ATTR_HTTP_REQUEST_METHOD]: req.method,
5518
5915
  [import_semantic_conventions4.ATTR_HTTP_ROUTE]: req.originalPath,
@@ -5564,15 +5961,15 @@ function enrichExpressLikeSend(instance, req, res, originalOperation, originalSe
5564
5961
  `attachment; filename="${data.name}"`
5565
5962
  );
5566
5963
  }
5567
- if ((0, import_common15.isNodeJsWriteableStream)(res)) {
5568
- import_stream.Readable.from((0, import_common15.readableStreamToAsyncIterable)(data.stream())).pipe(res);
5964
+ if ((0, import_common14.isNodeJsWriteableStream)(res)) {
5965
+ import_stream.Readable.from((0, import_common14.readableStreamToAsyncIterable)(data.stream())).pipe(res);
5569
5966
  } else {
5570
5967
  res.type("text/plain");
5571
5968
  res.status(500);
5572
5969
  originalSend.call(instance, "Not a NodeJS WritableStream");
5573
5970
  errorSent = true;
5574
5971
  }
5575
- } else if ((0, import_common15.isAsyncGenerator)(data)) {
5972
+ } else if ((0, import_common14.isAsyncGenerator)(data)) {
5576
5973
  let firstPass = true;
5577
5974
  const transformer = new import_stream.Transform({
5578
5975
  objectMode: true,
@@ -5596,7 +5993,7 @@ ${res.locals.errorMessage}`;
5596
5993
  } else {
5597
5994
  let data2 = "";
5598
5995
  for (const [key, value] of Object.entries(chunk)) {
5599
- data2 += `${key}: ${typeof value === "string" ? value : (0, import_common15.safeStringify)(value)}
5996
+ data2 += `${key}: ${typeof value === "string" ? value : (0, import_common14.safeStringify)(value)}
5600
5997
  `;
5601
5998
  }
5602
5999
  data2 += "\n";
@@ -5607,7 +6004,7 @@ ${res.locals.errorMessage}`;
5607
6004
  } else if (!errorSent) {
5608
6005
  let data2 = "";
5609
6006
  for (const [key, value] of Object.entries(chunk)) {
5610
- data2 += `${key}: ${typeof value === "string" ? value : (0, import_common15.safeStringify)(value)}
6007
+ data2 += `${key}: ${typeof value === "string" ? value : (0, import_common14.safeStringify)(value)}
5611
6008
  `;
5612
6009
  }
5613
6010
  data2 += "\n";
@@ -5615,7 +6012,7 @@ ${res.locals.errorMessage}`;
5615
6012
  }
5616
6013
  }
5617
6014
  });
5618
- if ((0, import_common15.isNodeJsWriteableStream)(res)) {
6015
+ if ((0, import_common14.isNodeJsWriteableStream)(res)) {
5619
6016
  import_stream.Readable.from(data).pipe(transformer).pipe(res);
5620
6017
  } else {
5621
6018
  res.type("text/plain");
@@ -5626,7 +6023,7 @@ ${res.locals.errorMessage}`;
5626
6023
  } else {
5627
6024
  const parserType = responseBodies?.[Number(res.statusCode)]?.parserType;
5628
6025
  res.bodyData = data;
5629
- if ((0, import_common15.isRecord)(data)) {
6026
+ if ((0, import_common14.isRecord)(data)) {
5630
6027
  switch (parserType) {
5631
6028
  case "json":
5632
6029
  res.bodyData = "json" in data ? data.json : data;
@@ -5647,7 +6044,7 @@ ${res.locals.errorMessage}`;
5647
6044
  res.bodyData = data;
5648
6045
  break;
5649
6046
  default:
5650
- (0, import_common15.isNever)(parserType);
6047
+ (0, import_common14.isNever)(parserType);
5651
6048
  res.bodyData = data;
5652
6049
  break;
5653
6050
  }
@@ -5682,7 +6079,7 @@ ${res.locals.errorMessage}`;
5682
6079
  }
5683
6080
 
5684
6081
  // src/http/openApiV3Generator/openApiV3Generator.ts
5685
- var import_common16 = require("@forklaunch/common");
6082
+ var import_common15 = require("@forklaunch/common");
5686
6083
  var OPENAPI_DEFAULT_VERSION = /* @__PURE__ */ Symbol("default");
5687
6084
  function toUpperCase(str) {
5688
6085
  return str.charAt(0).toUpperCase() + str.slice(1);
@@ -5909,7 +6306,7 @@ function generateOpenApiSpecs(schemaValidator, serverUrls, serverDescriptions, a
5909
6306
  ].forEach(({ fullPath, router }) => {
5910
6307
  const controllerName = transformBasePath(fullPath);
5911
6308
  router.routes.forEach((route) => {
5912
- const openApiPath = (0, import_common16.openApiCompliantPath)(
6309
+ const openApiPath = (0, import_common15.openApiCompliantPath)(
5913
6310
  `${fullPath}${route.path === "/" ? "" : route.path}`
5914
6311
  );
5915
6312
  const { name, summary, params, versions, auth, options: options2 } = route.contractDetails;
@@ -6255,13 +6652,17 @@ function createLocalModelGatewayClient(options2 = {}) {
6255
6652
  ATTR_HTTP_ROUTE,
6256
6653
  ATTR_SERVICE_NAME,
6257
6654
  AuditLogger,
6655
+ DEFAULT_HMAC_MAX_SKEW_MS,
6656
+ DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES,
6258
6657
  DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
6658
+ DEFAULT_SHARED_SECRET_JWT_ALGORITHMS,
6259
6659
  EMAIL_LIMITS,
6260
6660
  EmailRequestError,
6261
6661
  ForklaunchExpressLikeApplication,
6262
6662
  ForklaunchExpressLikeRouter,
6263
6663
  HTTPStatuses,
6264
6664
  INSTANCE_GATEWAY_MOUNT,
6665
+ InMemoryHmacNonceStore,
6265
6666
  InstanceGatewayRequestError,
6266
6667
  ModelGatewayRequestError,
6267
6668
  OPENAPI_DEFAULT_VERSION,
@@ -6272,6 +6673,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6272
6673
  PinoLogger,
6273
6674
  PlatformEventVerificationError,
6274
6675
  RateLimiter,
6676
+ SHARED_SECRET_JWT_ALGORITHMS,
6275
6677
  SMS_MAX_SEGMENTS,
6276
6678
  STRIPE_GATEWAY_ROUTE,
6277
6679
  SmsClient,
@@ -6313,6 +6715,8 @@ function createLocalModelGatewayClient(options2 = {}) {
6313
6715
  getCodeForStatus,
6314
6716
  getMcpTransportHeaders,
6315
6717
  head,
6718
+ hmacNonceKey,
6719
+ hmacNonceTtlMs,
6316
6720
  httpErrorsTotalCounter,
6317
6721
  httpRequestDurationMsHistogram,
6318
6722
  httpRequestsInFlightCounter,
@@ -6324,6 +6728,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6324
6728
  isEmailAddress,
6325
6729
  isForklaunchRequest,
6326
6730
  isForklaunchRouter,
6731
+ isHmacTimestampFresh,
6327
6732
  isInformational,
6328
6733
  isManagedInstance,
6329
6734
  isPortBound,
@@ -6332,6 +6737,9 @@ function createLocalModelGatewayClient(options2 = {}) {
6332
6737
  isServerError,
6333
6738
  isSuccessful,
6334
6739
  isValidStatusCode,
6740
+ jwtAlgorithmsForPublicKey,
6741
+ jwtAlgorithmsForSharedSecret,
6742
+ jwtClaimChecks,
6335
6743
  logger,
6336
6744
  meta,
6337
6745
  metricsDefinitions,
@@ -6344,10 +6752,14 @@ function createLocalModelGatewayClient(options2 = {}) {
6344
6752
  recordRequestAudit,
6345
6753
  registerDelegatedSurface,
6346
6754
  resetProcessHandlersForTesting,
6755
+ resolveHmacMaxSkewMs,
6756
+ resolveHmacNonceStore,
6347
6757
  signPlatformEvent,
6348
6758
  smsSegments,
6349
6759
  stripeGatewayFetch,
6760
+ timingSafeEqualStrings,
6350
6761
  trace,
6762
+ ttlCacheHmacNonceStore,
6351
6763
  typedAuthHandler,
6352
6764
  typedHandler,
6353
6765
  validateEmailSendRequest,