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