@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.
@@ -1,4 +1,8 @@
1
1
  // src/http/bindRuntimeAuth.ts
2
+ var JWT_VERIFICATION_KEYS = ["algorithms", "issuer", "audience"];
3
+ var HMAC_VERIFICATION_KEYS = ["maxSkewMs", "nonceStore"];
4
+ var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
5
+ var isNonEmptyStringList = (value) => Array.isArray(value) && value.length > 0 && value.every(isNonEmptyString);
2
6
  function bindRuntimeAuth(details, binding) {
3
7
  const policy = { ...details.auth };
4
8
  const keys = Object.keys(binding);
@@ -25,10 +29,26 @@ function bindRuntimeAuth(details, binding) {
25
29
  let authentication;
26
30
  if (policy.scheme === "jwt") {
27
31
  if (keys.some(
28
- (key) => !["jwksPublicKeyUrl", "signatureKey", "decodeResource"].includes(key)
32
+ (key) => ![
33
+ "jwksPublicKeyUrl",
34
+ "signatureKey",
35
+ "decodeResource",
36
+ ...JWT_VERIFICATION_KEYS
37
+ ].includes(key)
29
38
  ))
30
39
  invalid();
31
- const keyFields = keys.filter((key) => key !== "decodeResource");
40
+ for (const key of JWT_VERIFICATION_KEYS) {
41
+ if (credentials[key] === void 0) {
42
+ delete credentials[key];
43
+ continue;
44
+ }
45
+ const value = credentials[key];
46
+ if (key === "algorithms" ? !isNonEmptyStringList(value) : !isNonEmptyString(value) && !isNonEmptyStringList(value))
47
+ invalid();
48
+ }
49
+ const keyFields = keys.filter(
50
+ (key) => key !== "decodeResource" && !JWT_VERIFICATION_KEYS.includes(key)
51
+ );
32
52
  if (keyFields.length !== 1 || typeof credentials[keyFields[0]] !== "string" || !credentials[keyFields[0]])
33
53
  invalid();
34
54
  const decodeResource = credentials.decodeResource;
@@ -40,7 +60,13 @@ function bindRuntimeAuth(details, binding) {
40
60
  ...decodeResource === void 0 ? {} : { decodeResource }
41
61
  };
42
62
  } else if (policy.scheme === "hmac") {
43
- 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(
63
+ const maxSkewMs = credentials.maxSkewMs;
64
+ if (maxSkewMs === void 0) delete credentials.maxSkewMs;
65
+ const nonceStore = credentials.nonceStore;
66
+ if (nonceStore === void 0) delete credentials.nonceStore;
67
+ if (keys.some(
68
+ (key) => key !== "secretKeys" && !HMAC_VERIFICATION_KEYS.includes(key)
69
+ ) || maxSkewMs !== void 0 && (typeof maxSkewMs !== "number" || !Number.isFinite(maxSkewMs) || maxSkewMs <= 0) || nonceStore !== void 0 && (nonceStore === null || typeof nonceStore !== "object" || typeof nonceStore.claim !== "function" && typeof nonceStore.putRecordIfAbsent !== "function" && (typeof nonceStore.peekRecord !== "function" || typeof nonceStore.putRecord !== "function")) || !credentials.secretKeys || typeof credentials.secretKeys !== "object" || Array.isArray(credentials.secretKeys) || Object.keys(credentials.secretKeys).length === 0 || Object.values(credentials.secretKeys).some(
44
70
  (key) => typeof key !== "string" || !key
45
71
  ))
46
72
  invalid();
@@ -62,7 +88,74 @@ function bindRuntimeAuth(details, binding) {
62
88
 
63
89
  // src/http/middleware/request/cors.middleware.ts
64
90
  import corsMiddleware from "cors";
91
+ var CORS_ORIGINS_ENV = "CORS_ORIGINS";
92
+ var CORS_FROM_ENVIRONMENT = "environment";
93
+ var LOCAL_DEVELOPMENT_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/;
94
+ function parseCorsOrigins(value) {
95
+ const origins = [];
96
+ for (const entry of (value ?? "").split(",")) {
97
+ let origin = entry.trim();
98
+ while (origin.length > 1 && origin.endsWith("/")) {
99
+ origin = origin.slice(0, -1);
100
+ }
101
+ if (origin && !origins.includes(origin)) origins.push(origin);
102
+ }
103
+ return origins;
104
+ }
105
+ function isWildcardOrigin(origin) {
106
+ return origin === void 0 || origin === "*";
107
+ }
108
+ function defaultCorsOrigin(env) {
109
+ const listed = parseCorsOrigins(env[CORS_ORIGINS_ENV]);
110
+ if (listed.includes("*")) {
111
+ return { origin: "*", configured: true };
112
+ }
113
+ if (listed.length > 0) {
114
+ return { origin: listed, configured: true };
115
+ }
116
+ return {
117
+ origin: env.NODE_ENV === "production" ? false : LOCAL_DEVELOPMENT_ORIGIN,
118
+ configured: false
119
+ };
120
+ }
121
+ function withoutWildcardCredentials(options2) {
122
+ return options2.credentials === true && isWildcardOrigin(options2.origin) ? { ...options2, credentials: false } : options2;
123
+ }
124
+ function resolveCorsOptions(appCorsOption, env = process.env) {
125
+ const appCors = appCorsOption === CORS_FROM_ENVIRONMENT ? void 0 : appCorsOption;
126
+ 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.`;
127
+ if (appCors !== void 0) {
128
+ if (appCors.credentials === true && isWildcardOrigin(appCors.origin)) {
129
+ return {
130
+ options: appCors,
131
+ 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."
132
+ };
133
+ }
134
+ if (appCors.origin === void 0) {
135
+ return {
136
+ options: appCors,
137
+ 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: '*' }\`.`
138
+ };
139
+ }
140
+ return { options: appCors };
141
+ }
142
+ const { origin, configured } = defaultCorsOrigin(env);
143
+ if (configured) {
144
+ return { options: { origin } };
145
+ }
146
+ return {
147
+ options: { origin },
148
+ 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
149
+ };
150
+ }
65
151
  function cors(corsOptions) {
152
+ const configuredOrigin = corsOptions.origin;
153
+ const staticHandler = corsMiddleware(withoutWildcardCredentials(corsOptions));
154
+ const wildcardHandler = corsMiddleware({
155
+ ...corsOptions,
156
+ origin: "*",
157
+ credentials: false
158
+ });
66
159
  return (req, res, next) => {
67
160
  if (req.method === "OPTIONS") {
68
161
  res.cors = true;
@@ -72,19 +165,29 @@ function cors(corsOptions) {
72
165
  return res.getHeaders()[key];
73
166
  };
74
167
  }
75
- corsMiddleware(corsOptions)(
76
- req,
77
- res,
78
- next ?? (() => {
79
- })
80
- );
168
+ const corsRequest = req;
169
+ const done = next ?? (() => {
170
+ });
171
+ if (corsOptions.credentials === true && typeof configuredOrigin === "function") {
172
+ configuredOrigin(corsRequest.headers.origin, (error, origin) => {
173
+ if (error || !origin) {
174
+ done(error ?? void 0);
175
+ } else if (origin === "*") {
176
+ wildcardHandler(corsRequest, res, done);
177
+ } else {
178
+ corsMiddleware({ ...corsOptions, origin })(corsRequest, res, done);
179
+ }
180
+ });
181
+ return;
182
+ }
183
+ staticHandler(corsRequest, res, done);
81
184
  };
82
185
  }
83
186
 
84
187
  // src/http/router/expressLikeRouter.ts
85
188
  import {
86
189
  hashString,
87
- safeStringify as safeStringify3,
190
+ safeStringify as safeStringify2,
88
191
  sanitizePathSlashes,
89
192
  toPrettyCamelCase,
90
193
  toRecord
@@ -702,7 +805,6 @@ import {
702
805
  } from "@forklaunch/validator";
703
806
 
704
807
  // src/http/discriminateAuthMethod.ts
705
- import { safeStringify as safeStringify2 } from "@forklaunch/common";
706
808
  import { jwtVerify } from "jose";
707
809
 
708
810
  // src/http/createHmacToken.ts
@@ -728,6 +830,227 @@ ${nonce}`
728
830
  return hmac.digest("base64");
729
831
  }
730
832
 
833
+ // src/http/hmacReplayProtection.ts
834
+ import { timingSafeEqual } from "crypto";
835
+ var DEFAULT_HMAC_MAX_SKEW_MS = 5 * 60 * 1e3;
836
+ var DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES = 1e5;
837
+ function timingSafeEqualStrings(expected, received) {
838
+ if (typeof expected !== "string" || typeof received !== "string") {
839
+ return false;
840
+ }
841
+ const expectedBytes = Buffer.from(expected);
842
+ const receivedBytes = Buffer.from(received);
843
+ return expectedBytes.length === receivedBytes.length && timingSafeEqual(expectedBytes, receivedBytes);
844
+ }
845
+ function resolveHmacMaxSkewMs(maxSkewMs) {
846
+ return typeof maxSkewMs === "number" && Number.isFinite(maxSkewMs) && maxSkewMs > 0 ? maxSkewMs : DEFAULT_HMAC_MAX_SKEW_MS;
847
+ }
848
+ function isHmacTimestampFresh(timestamp, nowMs, maxSkewMs = DEFAULT_HMAC_MAX_SKEW_MS) {
849
+ if (!(timestamp instanceof Date)) return false;
850
+ const at = timestamp.getTime();
851
+ return !Number.isNaN(at) && Math.abs(nowMs - at) <= maxSkewMs;
852
+ }
853
+ function hmacNonceTtlMs(timestamp, nowMs, maxSkewMs) {
854
+ return Math.max(1, timestamp.getTime() + maxSkewMs - nowMs);
855
+ }
856
+ function hmacNonceKey(keyId, nonce) {
857
+ const id = keyId ?? "";
858
+ return `${id.length}:${id}${nonce}`;
859
+ }
860
+ var InMemoryHmacNonceStore = class {
861
+ entries = /* @__PURE__ */ new Map();
862
+ maxEntries;
863
+ sweepIntervalMs;
864
+ lastSweepAt = 0;
865
+ constructor(options2 = {}) {
866
+ this.maxEntries = typeof options2.maxEntries === "number" && options2.maxEntries >= 1 ? Math.floor(options2.maxEntries) : DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES;
867
+ this.sweepIntervalMs = options2.sweepIntervalMs ?? 3e4;
868
+ }
869
+ /** Number of nonces currently held (expired ones may linger until swept). */
870
+ get size() {
871
+ return this.entries.size;
872
+ }
873
+ claim(key, ttlMs, nowMs = Date.now()) {
874
+ const expiresAt = this.entries.get(key);
875
+ if (expiresAt !== void 0 && expiresAt > nowMs) {
876
+ return false;
877
+ }
878
+ if (this.entries.size >= this.maxEntries || nowMs - this.lastSweepAt >= this.sweepIntervalMs) {
879
+ this.sweep(nowMs);
880
+ }
881
+ this.entries.delete(key);
882
+ while (this.entries.size >= this.maxEntries) {
883
+ const oldest = this.entries.keys().next();
884
+ if (oldest.done) break;
885
+ this.entries.delete(oldest.value);
886
+ }
887
+ this.entries.set(key, nowMs + Math.max(1, ttlMs));
888
+ return true;
889
+ }
890
+ sweep(nowMs) {
891
+ this.lastSweepAt = nowMs;
892
+ for (const [key, expiresAt] of this.entries) {
893
+ if (expiresAt <= nowMs) this.entries.delete(key);
894
+ }
895
+ }
896
+ };
897
+ function ttlCacheHmacNonceStore(cache, keyPrefix = "hmac-nonce:") {
898
+ return {
899
+ async claim(key, ttlMs) {
900
+ const record2 = {
901
+ key: `${keyPrefix}${key}`,
902
+ value: 1,
903
+ ttlMilliseconds: Math.max(1, Math.ceil(ttlMs))
904
+ };
905
+ if (typeof cache.putRecordIfAbsent === "function") {
906
+ return await cache.putRecordIfAbsent(record2) === true;
907
+ }
908
+ if (await cache.peekRecord(record2.key)) {
909
+ return false;
910
+ }
911
+ await cache.putRecord(record2);
912
+ return true;
913
+ }
914
+ };
915
+ }
916
+ var defaultHmacNonceStore = new InMemoryHmacNonceStore();
917
+ var adaptedTtlCaches = /* @__PURE__ */ new WeakMap();
918
+ function resolveHmacNonceStore(configured) {
919
+ if (configured == null) {
920
+ return defaultHmacNonceStore;
921
+ }
922
+ if (typeof configured.claim === "function") {
923
+ return configured;
924
+ }
925
+ const cache = configured;
926
+ if (typeof cache.putRecordIfAbsent !== "function" && (typeof cache.peekRecord !== "function" || typeof cache.putRecord !== "function")) {
927
+ throw new Error(
928
+ "hmac.nonceStore must be an HmacNonceStore ({ claim }) or a TtlCache"
929
+ );
930
+ }
931
+ let adapted = adaptedTtlCaches.get(cache);
932
+ if (!adapted) {
933
+ adapted = ttlCacheHmacNonceStore(cache);
934
+ adaptedTtlCaches.set(cache, adapted);
935
+ }
936
+ return adapted;
937
+ }
938
+
939
+ // src/http/jwtAlgorithms.ts
940
+ var SHARED_SECRET_JWT_ALGORITHMS = [
941
+ "HS256",
942
+ "HS384",
943
+ "HS512"
944
+ ];
945
+ var DEFAULT_SHARED_SECRET_JWT_ALGORITHMS = [
946
+ "HS256"
947
+ ];
948
+ var RSA_JWT_ALGORITHMS = [
949
+ "RS256",
950
+ "RS384",
951
+ "RS512",
952
+ "PS256",
953
+ "PS384",
954
+ "PS512"
955
+ ];
956
+ var EC_CURVE_JWT_ALGORITHMS = {
957
+ "P-256": ["ES256"],
958
+ "P-384": ["ES384"],
959
+ "P-521": ["ES512"]
960
+ };
961
+ var OKP_CURVE_JWT_ALGORITHMS = {
962
+ Ed25519: ["EdDSA", "Ed25519"]
963
+ };
964
+ function isSymmetricOrUnsigned(algorithm) {
965
+ const normalized = algorithm.toUpperCase();
966
+ return normalized === "NONE" || normalized.startsWith("HS");
967
+ }
968
+ function configuredList(configured) {
969
+ if (configured == null) return void 0;
970
+ if (!Array.isArray(configured)) {
971
+ throw new Error("JWT `algorithms` must be an array of algorithm names");
972
+ }
973
+ return configured.filter(
974
+ (algorithm) => typeof algorithm === "string"
975
+ );
976
+ }
977
+ function jwtAlgorithmsForSharedSecret(configured) {
978
+ const requested = configuredList(configured);
979
+ if (requested === void 0) {
980
+ return [...DEFAULT_SHARED_SECRET_JWT_ALGORITHMS];
981
+ }
982
+ const allowed = SHARED_SECRET_JWT_ALGORITHMS.filter(
983
+ (algorithm) => requested.includes(algorithm)
984
+ );
985
+ if (allowed.length === 0) {
986
+ throw new Error(
987
+ "No usable JWT algorithm: a `signatureKey` verifies only HS256, HS384 or HS512"
988
+ );
989
+ }
990
+ return allowed;
991
+ }
992
+ function algorithmsFittingPublicKey(key) {
993
+ let fitting;
994
+ switch (key.kty) {
995
+ case "RSA":
996
+ fitting = RSA_JWT_ALGORITHMS;
997
+ break;
998
+ case "EC":
999
+ fitting = EC_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
1000
+ break;
1001
+ case "OKP":
1002
+ fitting = OKP_CURVE_JWT_ALGORITHMS[key.crv ?? ""] ?? [];
1003
+ break;
1004
+ case "AKP":
1005
+ fitting = typeof key.alg === "string" ? [key.alg] : [];
1006
+ break;
1007
+ default:
1008
+ fitting = [];
1009
+ }
1010
+ if (typeof key.alg === "string") {
1011
+ fitting = fitting.filter((algorithm) => algorithm === key.alg);
1012
+ }
1013
+ return fitting.filter((algorithm) => !isSymmetricOrUnsigned(algorithm));
1014
+ }
1015
+ function jwtAlgorithmsForPublicKey(key, configured) {
1016
+ if (key == null || typeof key !== "object") {
1017
+ throw new Error("No usable JWT algorithm: the verification key is missing");
1018
+ }
1019
+ if (key.kty === "oct") {
1020
+ throw new Error(
1021
+ "No usable JWT algorithm: a symmetric (oct) key cannot be used as a public key; use `signatureKey` for a shared secret"
1022
+ );
1023
+ }
1024
+ const requested = configuredList(configured);
1025
+ const allowed = algorithmsFittingPublicKey(key).filter(
1026
+ (algorithm) => requested === void 0 || requested.includes(algorithm)
1027
+ );
1028
+ if (allowed.length === 0) {
1029
+ throw new Error(
1030
+ "No usable JWT algorithm: none of the permitted asymmetric algorithms fits this public key"
1031
+ );
1032
+ }
1033
+ return allowed;
1034
+ }
1035
+ function claimExpectation(name, value) {
1036
+ if (value === void 0) return void 0;
1037
+ const values = typeof value === "string" ? [value] : value;
1038
+ if (!Array.isArray(values) || values.length === 0 || values.some((entry) => typeof entry !== "string" || entry.length === 0)) {
1039
+ throw new Error(
1040
+ `JWT \`${name}\` is configured but empty; set it to the expected value or remove it`
1041
+ );
1042
+ }
1043
+ return typeof value === "string" ? value : [...values];
1044
+ }
1045
+ function jwtClaimChecks(config) {
1046
+ const issuer = claimExpectation("issuer", config.issuer);
1047
+ const audience = claimExpectation("audience", config.audience);
1048
+ return {
1049
+ ...issuer === void 0 ? {} : { issuer },
1050
+ ...audience === void 0 ? {} : { audience }
1051
+ };
1052
+ }
1053
+
731
1054
  // src/http/guards/isBasicAuthMethod.ts
732
1055
  function isBasicAuthMethod(maybeBasicAuthMethod) {
733
1056
  return typeof maybeBasicAuthMethod === "object" && maybeBasicAuthMethod !== null && "basic" in maybeBasicAuthMethod && maybeBasicAuthMethod.basic != null;
@@ -781,11 +1104,16 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
781
1104
  } else if (isJwtAuthMethod(auth)) {
782
1105
  const jwt = auth.jwt;
783
1106
  let verificationFunction;
1107
+ const claimChecks = () => jwtClaimChecks(jwt);
784
1108
  if ("signatureKey" in jwt) {
785
1109
  verificationFunction = async (token) => {
786
1110
  const { payload } = await jwtVerify(
787
1111
  token,
788
- new Uint8Array(Buffer.from(jwt.signatureKey))
1112
+ new Uint8Array(Buffer.from(jwt.signatureKey)),
1113
+ {
1114
+ ...claimChecks(),
1115
+ algorithms: jwtAlgorithmsForSharedSecret(jwt.algorithms)
1116
+ }
789
1117
  );
790
1118
  return payload;
791
1119
  };
@@ -800,7 +1128,10 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
800
1128
  let lastError;
801
1129
  for (const key of jwks) {
802
1130
  try {
803
- const { payload } = await jwtVerify(token, key);
1131
+ const { payload } = await jwtVerify(token, key, {
1132
+ ...claimChecks(),
1133
+ algorithms: jwtAlgorithmsForPublicKey(key, jwt.algorithms)
1134
+ });
804
1135
  return payload;
805
1136
  } catch (error) {
806
1137
  lastError = error;
@@ -821,10 +1152,19 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
821
1152
  }
822
1153
  };
823
1154
  } else if (isHmacMethod(auth)) {
1155
+ const maxSkewMs = resolveHmacMaxSkewMs(auth.hmac.maxSkewMs);
1156
+ const configuredNonceStore = auth.hmac.nonceStore;
824
1157
  authMethod = {
825
1158
  type: "hmac",
826
1159
  auth: {
827
1160
  secretKeys: auth.hmac.secretKeys,
1161
+ /**
1162
+ * Accepts a signed request only when its timestamp is inside the
1163
+ * skew window, its signature matches (constant-time compare) and
1164
+ * its nonce has not been used before. The nonce is claimed last, and
1165
+ * only for a valid signature, so a `false` for one candidate path
1166
+ * never burns the nonce for the next.
1167
+ */
828
1168
  verificationFunction: async ({
829
1169
  method,
830
1170
  path,
@@ -832,8 +1172,30 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
832
1172
  timestamp,
833
1173
  nonce,
834
1174
  signature,
835
- secretKey
1175
+ secretKey,
1176
+ keyId
836
1177
  }) => {
1178
+ const reject = (reason) => {
1179
+ openTelemetryCollector?.debug("[HMAC Verification Failed]", {
1180
+ reason,
1181
+ method,
1182
+ path,
1183
+ keyId,
1184
+ timestamp: timestamp instanceof Date && !Number.isNaN(timestamp.getTime()) ? timestamp.toISOString() : "invalid",
1185
+ bodyType: body ? typeof body : "undefined"
1186
+ });
1187
+ return false;
1188
+ };
1189
+ if (typeof secretKey !== "string" || secretKey.length === 0) {
1190
+ return reject("unknown key");
1191
+ }
1192
+ if (typeof nonce !== "string" || nonce.length === 0 || typeof signature !== "string") {
1193
+ return reject("missing nonce or signature");
1194
+ }
1195
+ const now = Date.now();
1196
+ if (!isHmacTimestampFresh(timestamp, now, maxSkewMs)) {
1197
+ return reject("stale or invalid timestamp");
1198
+ }
837
1199
  const computedSignature = createHmacToken({
838
1200
  method,
839
1201
  path,
@@ -842,23 +1204,26 @@ async function discriminateAuthMethod(auth, openTelemetryCollector) {
842
1204
  nonce,
843
1205
  secretKey
844
1206
  });
845
- const isValid = computedSignature === signature;
846
- if (!isValid) {
847
- const errorInfo = {
848
- method,
849
- path,
850
- timestamp: timestamp.toISOString(),
851
- nonce,
852
- receivedSignature: signature,
853
- computedSignature
854
- };
855
- openTelemetryCollector?.debug("[HMAC Verification Failed]", {
856
- ...errorInfo,
857
- bodyType: body ? typeof body : "undefined",
858
- body: body ? safeStringify2(body) : "undefined"
859
- });
1207
+ if (!timingSafeEqualStrings(computedSignature, signature)) {
1208
+ return reject("signature mismatch");
1209
+ }
1210
+ let firstUse;
1211
+ try {
1212
+ firstUse = await resolveHmacNonceStore(configuredNonceStore).claim(
1213
+ hmacNonceKey(keyId, nonce),
1214
+ hmacNonceTtlMs(timestamp, now, maxSkewMs)
1215
+ );
1216
+ } catch (error) {
1217
+ openTelemetryCollector?.error(
1218
+ "[HMAC Nonce Store Failed]",
1219
+ error instanceof Error ? error.message : String(error)
1220
+ );
1221
+ return reject("nonce store unavailable");
860
1222
  }
861
- return isValid;
1223
+ if (firstUse !== true) {
1224
+ return reject("replayed nonce");
1225
+ }
1226
+ return true;
862
1227
  }
863
1228
  }
864
1229
  };
@@ -1019,6 +1384,18 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
1019
1384
  if (!parsedKeyId || !parsedTimestamp || !parsedNonce || !parsedSignature) {
1020
1385
  return invalidAuthorizationTokenFormat;
1021
1386
  }
1387
+ const requestTimestamp = new Date(parsedTimestamp);
1388
+ if (Number.isNaN(requestTimestamp.getTime())) {
1389
+ return invalidAuthorizationTokenFormat;
1390
+ }
1391
+ const secretKeys = collapsedAuthorizationMethod.hmac.secretKeys;
1392
+ const secretKey = Object.prototype.hasOwnProperty.call(
1393
+ secretKeys,
1394
+ parsedKeyId
1395
+ ) ? secretKeys[parsedKeyId] : void 0;
1396
+ if (typeof secretKey !== "string" || secretKey.length === 0) {
1397
+ return invalidAuthorizationSignature;
1398
+ }
1022
1399
  let verificationResult = false;
1023
1400
  const signedPaths = hmacSignedPaths(req);
1024
1401
  for (const path of signedPaths) {
@@ -1026,10 +1403,11 @@ async function checkAuthorizationToken(req, authorizationMethod, authorizationTo
1026
1403
  method: req?.method ?? "",
1027
1404
  path,
1028
1405
  body: req?._rawBody ?? req?.body,
1029
- timestamp: new Date(parsedTimestamp),
1406
+ timestamp: requestTimestamp,
1030
1407
  nonce: parsedNonce,
1031
1408
  signature: parsedSignature,
1032
- secretKey: collapsedAuthorizationMethod.hmac.secretKeys[parsedKeyId]
1409
+ secretKey,
1410
+ keyId: parsedKeyId
1033
1411
  }));
1034
1412
  if (verificationResult) {
1035
1413
  if (path !== signedPaths[0]) warnMountRelativeHmacPath();
@@ -2584,7 +2962,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2584
2962
  unpackSdks(sdks, path, routerUniquenessCache) {
2585
2963
  Object.entries(sdks).forEach(([key, maybeHandler]) => {
2586
2964
  if (isSdkHandler(maybeHandler)) {
2587
- const cacheKey = hashString(safeStringify3(maybeHandler));
2965
+ const cacheKey = hashString(safeStringify2(maybeHandler));
2588
2966
  if (routerUniquenessCache.has(cacheKey)) {
2589
2967
  throw new Error(`SDK handler ${key} is already registered`);
2590
2968
  }
@@ -2629,6 +3007,7 @@ var ForklaunchExpressLikeRouter = class _ForklaunchExpressLikeRouter {
2629
3007
  };
2630
3008
 
2631
3009
  // src/http/application/expressLikeApplication.ts
3010
+ var warnedAboutCorsDefaults = false;
2632
3011
  var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter {
2633
3012
  /**
2634
3013
  * Creates an instance of the Application class.
@@ -2653,7 +3032,14 @@ var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter
2653
3032
  this.postEnrichMiddleware = postEnrichMiddleware;
2654
3033
  this.openTelemetryCollector = openTelemetryCollector;
2655
3034
  this.appOptions = appOptions;
2656
- this.internal.use(cors(this.appOptions?.cors ?? {}));
3035
+ const { options: corsOptions, warning: corsWarning } = resolveCorsOptions(
3036
+ this.appOptions?.cors
3037
+ );
3038
+ if (corsWarning && !warnedAboutCorsDefaults) {
3039
+ warnedAboutCorsDefaults = true;
3040
+ this.openTelemetryCollector.warn(corsWarning);
3041
+ }
3042
+ this.internal.use(cors(corsOptions));
2657
3043
  }
2658
3044
  schemaValidator;
2659
3045
  internal;
@@ -2715,11 +3101,10 @@ function generateHmacAuthHeaders({
2715
3101
  }
2716
3102
 
2717
3103
  // src/http/instanceGateway.ts
2718
- import { timingSafeEqual } from "crypto";
2719
3104
  var INSTANCE_GATEWAY_MOUNT = "/instance-gateway";
2720
3105
  var PLATFORM_EVENT_KEY_ID = "platform";
2721
3106
  var PLATFORM_EVENTS_PATH = "/platform-events";
2722
- var MAX_SKEW_MS = 5 * 60 * 1e3;
3107
+ var MAX_SKEW_MS = DEFAULT_HMAC_MAX_SKEW_MS;
2723
3108
  var InstanceGatewayRequestError = class extends Error {
2724
3109
  constructor(status, message, retryAfterSeconds) {
2725
3110
  super(message);
@@ -2798,7 +3183,7 @@ function createInstanceGatewayTransport(options2 = {}, feature) {
2798
3183
  var PlatformEventVerificationError = class extends Error {
2799
3184
  name = "PlatformEventVerificationError";
2800
3185
  };
2801
- var seenEventNonces = /* @__PURE__ */ new Map();
3186
+ var seenEventNonces = new InMemoryHmacNonceStore();
2802
3187
  function verifyPlatformEvent(request, options2 = {}) {
2803
3188
  const hmacKey = options2.hmacKey ?? process.env.INSTANCE_HMAC_KEY;
2804
3189
  if (!hmacKey) {
@@ -2822,30 +3207,27 @@ function verifyPlatformEvent(request, options2 = {}) {
2822
3207
  }
2823
3208
  const timestamp = new Date(ts);
2824
3209
  const now = (options2.now ?? Date.now)();
2825
- if (Number.isNaN(timestamp.getTime()) || Math.abs(now - timestamp.getTime()) > MAX_SKEW_MS) {
3210
+ if (!isHmacTimestampFresh(timestamp, now, MAX_SKEW_MS)) {
2826
3211
  throw new PlatformEventVerificationError("Stale or invalid timestamp");
2827
3212
  }
2828
- const expected = Buffer.from(
2829
- createHmacToken({
2830
- secretKey: hmacKey,
2831
- method: request.method.toUpperCase(),
2832
- path: request.path,
2833
- body: request.body,
2834
- timestamp,
2835
- nonce
2836
- })
2837
- );
2838
- const received = Buffer.from(signature);
2839
- if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
3213
+ const expected = createHmacToken({
3214
+ secretKey: hmacKey,
3215
+ method: request.method.toUpperCase(),
3216
+ path: request.path,
3217
+ body: request.body,
3218
+ timestamp,
3219
+ nonce
3220
+ });
3221
+ if (!timingSafeEqualStrings(expected, signature)) {
2840
3222
  throw new PlatformEventVerificationError("Invalid signature");
2841
3223
  }
2842
- for (const [seen, at] of seenEventNonces) {
2843
- if (now - at > MAX_SKEW_MS) seenEventNonces.delete(seen);
2844
- }
2845
- if (seenEventNonces.has(nonce)) {
3224
+ if (!seenEventNonces.claim(
3225
+ hmacNonceKey(keyId, nonce),
3226
+ hmacNonceTtlMs(timestamp, now, MAX_SKEW_MS),
3227
+ now
3228
+ )) {
2846
3229
  throw new PlatformEventVerificationError("Replayed delivery");
2847
3230
  }
2848
- seenEventNonces.set(nonce, now);
2849
3231
  const parsed = typeof request.body === "string" || Buffer.isBuffer(request.body) ? JSON.parse(request.body.toString()) : request.body;
2850
3232
  const event = parsed;
2851
3233
  if (!event || typeof event.id !== "string" || typeof event.type !== "string" || typeof event.feature !== "string") {
@@ -4760,7 +5142,7 @@ var getCodeForStatus = (status) => {
4760
5142
  var httpStatusCodes_default = HTTPStatuses;
4761
5143
 
4762
5144
  // src/http/mcpGenerator/mcpGenerator.ts
4763
- import { isNever as isNever3, isRecord as isRecord3, safeStringify as safeStringify4 } from "@forklaunch/common";
5145
+ import { isNever as isNever3, isRecord as isRecord3, safeStringify as safeStringify3 } from "@forklaunch/common";
4764
5146
  import { string, ZodSchemaValidator } from "@forklaunch/validator/zod";
4765
5147
  import { FastMCP } from "fastmcp";
4766
5148
 
@@ -5109,7 +5491,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5109
5491
  break;
5110
5492
  }
5111
5493
  case "file": {
5112
- parsedBody = Buffer.from(safeStringify4(body));
5494
+ parsedBody = Buffer.from(safeStringify3(body));
5113
5495
  break;
5114
5496
  }
5115
5497
  case "multipart": {
@@ -5143,7 +5525,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5143
5525
  parsedBody = new URLSearchParams(
5144
5526
  Object.entries(body).map(([key, value]) => [
5145
5527
  key,
5146
- safeStringify4(value)
5528
+ safeStringify3(value)
5147
5529
  ])
5148
5530
  );
5149
5531
  } else {
@@ -5153,7 +5535,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5153
5535
  }
5154
5536
  default: {
5155
5537
  isNever3(discriminatedBody.parserType);
5156
- parsedBody = safeStringify4(body);
5538
+ parsedBody = safeStringify3(body);
5157
5539
  break;
5158
5540
  }
5159
5541
  }
@@ -5162,7 +5544,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5162
5544
  const queryString = new URLSearchParams(
5163
5545
  Object.entries(query).map(([key, value]) => [
5164
5546
  key,
5165
- safeStringify4(value)
5547
+ safeStringify3(value)
5166
5548
  ])
5167
5549
  ).toString();
5168
5550
  url += queryString ? `?${queryString}` : "";
@@ -5193,7 +5575,7 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
5193
5575
  content: [
5194
5576
  {
5195
5577
  type: "text",
5196
- text: safeStringify4(await response.json())
5578
+ text: safeStringify3(await response.json())
5197
5579
  }
5198
5580
  ]
5199
5581
  };
@@ -5384,7 +5766,7 @@ import {
5384
5766
  isNodeJsWriteableStream,
5385
5767
  isRecord as isRecord4,
5386
5768
  readableStreamToAsyncIterable,
5387
- safeStringify as safeStringify5
5769
+ safeStringify as safeStringify4
5388
5770
  } from "@forklaunch/common";
5389
5771
  import { Readable, Transform } from "stream";
5390
5772
 
@@ -5487,7 +5869,7 @@ ${res.locals.errorMessage}`;
5487
5869
  } else {
5488
5870
  let data2 = "";
5489
5871
  for (const [key, value] of Object.entries(chunk)) {
5490
- data2 += `${key}: ${typeof value === "string" ? value : safeStringify5(value)}
5872
+ data2 += `${key}: ${typeof value === "string" ? value : safeStringify4(value)}
5491
5873
  `;
5492
5874
  }
5493
5875
  data2 += "\n";
@@ -5498,7 +5880,7 @@ ${res.locals.errorMessage}`;
5498
5880
  } else if (!errorSent) {
5499
5881
  let data2 = "";
5500
5882
  for (const [key, value] of Object.entries(chunk)) {
5501
- data2 += `${key}: ${typeof value === "string" ? value : safeStringify5(value)}
5883
+ data2 += `${key}: ${typeof value === "string" ? value : safeStringify4(value)}
5502
5884
  `;
5503
5885
  }
5504
5886
  data2 += "\n";
@@ -6145,13 +6527,17 @@ export {
6145
6527
  ATTR_HTTP_ROUTE,
6146
6528
  ATTR_SERVICE_NAME,
6147
6529
  AuditLogger,
6530
+ DEFAULT_HMAC_MAX_SKEW_MS,
6531
+ DEFAULT_HMAC_NONCE_STORE_MAX_ENTRIES,
6148
6532
  DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
6533
+ DEFAULT_SHARED_SECRET_JWT_ALGORITHMS,
6149
6534
  EMAIL_LIMITS,
6150
6535
  EmailRequestError,
6151
6536
  ForklaunchExpressLikeApplication,
6152
6537
  ForklaunchExpressLikeRouter,
6153
6538
  HTTPStatuses,
6154
6539
  INSTANCE_GATEWAY_MOUNT,
6540
+ InMemoryHmacNonceStore,
6155
6541
  InstanceGatewayRequestError,
6156
6542
  ModelGatewayRequestError,
6157
6543
  OPENAPI_DEFAULT_VERSION,
@@ -6162,6 +6548,7 @@ export {
6162
6548
  PinoLogger,
6163
6549
  PlatformEventVerificationError,
6164
6550
  RateLimiter,
6551
+ SHARED_SECRET_JWT_ALGORITHMS,
6165
6552
  SMS_MAX_SEGMENTS,
6166
6553
  STRIPE_GATEWAY_ROUTE,
6167
6554
  SmsClient,
@@ -6203,6 +6590,8 @@ export {
6203
6590
  getCodeForStatus,
6204
6591
  getMcpTransportHeaders,
6205
6592
  head,
6593
+ hmacNonceKey,
6594
+ hmacNonceTtlMs,
6206
6595
  httpErrorsTotalCounter,
6207
6596
  httpRequestDurationMsHistogram,
6208
6597
  httpRequestsInFlightCounter,
@@ -6214,6 +6603,7 @@ export {
6214
6603
  isEmailAddress,
6215
6604
  isForklaunchRequest,
6216
6605
  isForklaunchRouter,
6606
+ isHmacTimestampFresh,
6217
6607
  isInformational,
6218
6608
  isManagedInstance,
6219
6609
  isPortBound,
@@ -6222,6 +6612,9 @@ export {
6222
6612
  isServerError,
6223
6613
  isSuccessful,
6224
6614
  isValidStatusCode,
6615
+ jwtAlgorithmsForPublicKey,
6616
+ jwtAlgorithmsForSharedSecret,
6617
+ jwtClaimChecks,
6225
6618
  logger,
6226
6619
  meta,
6227
6620
  metricsDefinitions,
@@ -6234,10 +6627,14 @@ export {
6234
6627
  recordRequestAudit,
6235
6628
  registerDelegatedSurface,
6236
6629
  resetProcessHandlersForTesting,
6630
+ resolveHmacMaxSkewMs,
6631
+ resolveHmacNonceStore,
6237
6632
  signPlatformEvent,
6238
6633
  smsSegments,
6239
6634
  stripeGatewayFetch,
6635
+ timingSafeEqualStrings,
6240
6636
  trace3 as trace,
6637
+ ttlCacheHmacNonceStore,
6241
6638
  typedAuthHandler,
6242
6639
  typedHandler,
6243
6640
  validateEmailSendRequest,