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