@dhaneshpurohit/mockstar 0.2.2 → 0.4.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/cli.js +786 -178
  3. package/dist/core/config/schema.d.ts +486 -320
  4. package/dist/core/config/schema.d.ts.map +1 -1
  5. package/dist/core/http/body-cap.d.ts +37 -0
  6. package/dist/core/http/body-cap.d.ts.map +1 -0
  7. package/dist/core/http/rate-limit.d.ts +55 -0
  8. package/dist/core/http/rate-limit.d.ts.map +1 -0
  9. package/dist/core/matching/discriminators.d.ts +25 -0
  10. package/dist/core/matching/discriminators.d.ts.map +1 -1
  11. package/dist/core/matching/index.d.ts +3 -1
  12. package/dist/core/matching/index.d.ts.map +1 -1
  13. package/dist/features/openapi/converter.d.ts.map +1 -1
  14. package/dist/features/pass-through.d.ts +7 -0
  15. package/dist/features/pass-through.d.ts.map +1 -1
  16. package/dist/features/proxy/cli.d.ts +11 -0
  17. package/dist/features/proxy/cli.d.ts.map +1 -1
  18. package/dist/features/proxy/dns.d.ts +21 -3
  19. package/dist/features/proxy/dns.d.ts.map +1 -1
  20. package/dist/features/proxy/index.d.ts +1 -1
  21. package/dist/features/proxy/index.d.ts.map +1 -1
  22. package/dist/features/proxy/port-bind.d.ts +18 -1
  23. package/dist/features/proxy/port-bind.d.ts.map +1 -1
  24. package/dist/features/proxy/sni-gate.d.ts +4 -3
  25. package/dist/features/proxy/sni-gate.d.ts.map +1 -1
  26. package/dist/features/url-validator.d.ts +48 -0
  27. package/dist/features/url-validator.d.ts.map +1 -1
  28. package/dist/features/webhooks/dispatcher.d.ts.map +1 -1
  29. package/dist/features/webhooks/event-registry.d.ts +7 -0
  30. package/dist/features/webhooks/event-registry.d.ts.map +1 -1
  31. package/dist/features/webhooks/index.d.ts +3 -1
  32. package/dist/features/webhooks/index.d.ts.map +1 -1
  33. package/dist/features/webhooks/journal.d.ts +23 -0
  34. package/dist/features/webhooks/journal.d.ts.map +1 -1
  35. package/dist/features/webhooks/queue.d.ts +18 -0
  36. package/dist/features/webhooks/queue.d.ts.map +1 -1
  37. package/dist/features/webhooks/scheme.d.ts +46 -0
  38. package/dist/features/webhooks/scheme.d.ts.map +1 -0
  39. package/dist/features/webhooks/signing.d.ts +24 -13
  40. package/dist/features/webhooks/signing.d.ts.map +1 -1
  41. package/dist/features/webhooks/types.d.ts +32 -5
  42. package/dist/features/webhooks/types.d.ts.map +1 -1
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +628 -133
  46. package/dist/server.d.ts +17 -0
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/version.d.ts +1 -1
  49. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -667,9 +667,13 @@ function compileOne(spec) {
667
667
  jitterRatio: spec.retry.jitterRatio
668
668
  },
669
669
  signing: spec.signing ? {
670
+ mode: spec.signing.mode,
670
671
  enabled: spec.signing.enabled,
671
672
  algorithm: spec.signing.algorithm,
672
673
  secretRef: spec.signing.secretRef,
674
+ signedPayload: spec.signing.signedPayload,
675
+ signatureTemplate: spec.signing.signatureTemplate,
676
+ digestEncoding: spec.signing.digestEncoding,
673
677
  signatureHeader: spec.signing.signatureHeader,
674
678
  timestampHeader: spec.signing.timestampHeader,
675
679
  replayWindowMs: spec.signing.replayWindowMs
@@ -2199,20 +2203,64 @@ JSONPath.prototype.safeVm = {
2199
2203
  JSONPath.prototype.vm = vm;
2200
2204
 
2201
2205
  // src/core/matching/discriminators.ts
2202
- function evaluateDiscriminators(pred, req) {
2206
+ function compileMatcher(spec) {
2207
+ if (typeof spec === "string")
2208
+ return { kind: "exact", value: spec };
2209
+ if ("equals" in spec)
2210
+ return { kind: "exact", value: spec.equals };
2211
+ if ("regex" in spec)
2212
+ return { kind: "regex", re: new RegExp(spec.regex) };
2213
+ if ("startsWith" in spec)
2214
+ return { kind: "startsWith", value: spec.startsWith };
2215
+ return { kind: "contains", value: spec.contains };
2216
+ }
2217
+ function compileDim(record) {
2218
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2219
+ }
2220
+ function compilePredicate(pred) {
2221
+ return {
2222
+ ...pred.query && { query: compileDim(pred.query) },
2223
+ ...pred.headers && { headers: compileDim(pred.headers) },
2224
+ ...pred.body && { body: pred.body }
2225
+ };
2226
+ }
2227
+ function compiledMatchOk(compiled, got) {
2228
+ if (compiled.kind === "exact")
2229
+ return got === compiled.value;
2230
+ if (got === undefined)
2231
+ return false;
2232
+ if (compiled.kind === "regex")
2233
+ return compiled.re.test(got);
2234
+ if (compiled.kind === "startsWith")
2235
+ return got.startsWith(compiled.value);
2236
+ return got.includes(compiled.value);
2237
+ }
2238
+ function describeCompiled(m) {
2239
+ switch (m.kind) {
2240
+ case "exact":
2241
+ return `=${m.value}`;
2242
+ case "regex":
2243
+ return `~/${m.re.source}/`;
2244
+ case "startsWith":
2245
+ return `^${m.value}`;
2246
+ case "contains":
2247
+ return `*${m.value}*`;
2248
+ }
2249
+ }
2250
+ function evaluateCompiledDiscriminators(pred, req) {
2203
2251
  if (pred.query) {
2204
- for (const [field, expected] of Object.entries(pred.query)) {
2252
+ for (const [field, expected] of pred.query) {
2205
2253
  const got = req.query.get(field);
2206
- if (!stringMatchOk(expected, got)) {
2207
- return { kind: "query", field, expected: describe(expected), got };
2254
+ if (!compiledMatchOk(expected, got)) {
2255
+ return { kind: "query", field, expected: describeCompiled(expected), got };
2208
2256
  }
2209
2257
  }
2210
2258
  }
2211
2259
  if (pred.headers) {
2212
- for (const [field, expected] of Object.entries(pred.headers)) {
2260
+ for (const [field, expected] of pred.headers) {
2213
2261
  const got = req.headers.get(field.toLowerCase());
2214
- if (!stringMatchOk(expected, got)) {
2215
- return { kind: "headers", field, expected: describe(expected), got };
2262
+ if (!compiledMatchOk(expected, got)) {
2263
+ return { kind: "headers", field, expected: describeCompiled(expected), got };
2216
2264
  }
2217
2265
  }
2218
2266
  }
@@ -2237,34 +2285,6 @@ function evaluateDiscriminators(pred, req) {
2237
2285
  }
2238
2286
  return null;
2239
2287
  }
2240
- function stringMatchOk(spec, got) {
2241
- if (typeof spec === "string")
2242
- return got === spec;
2243
- if ("equals" in spec)
2244
- return got === spec.equals;
2245
- if (got === undefined)
2246
- return false;
2247
- if ("regex" in spec)
2248
- return new RegExp(spec.regex).test(got);
2249
- if ("startsWith" in spec)
2250
- return got.startsWith(spec.startsWith);
2251
- if ("contains" in spec)
2252
- return got.includes(spec.contains);
2253
- return false;
2254
- }
2255
- function describe(spec) {
2256
- if (typeof spec === "string")
2257
- return `=${spec}`;
2258
- if ("equals" in spec)
2259
- return `=${spec.equals}`;
2260
- if ("regex" in spec)
2261
- return `~/${spec.regex}/`;
2262
- if ("startsWith" in spec)
2263
- return `^${spec.startsWith}`;
2264
- if ("contains" in spec)
2265
- return `*${spec.contains}*`;
2266
- return "?";
2267
- }
2268
2288
  function deepEquals(a, b) {
2269
2289
  if (a === b)
2270
2290
  return true;
@@ -2376,7 +2396,7 @@ function buildMatchIndex(entries) {
2376
2396
  const byMethod = new Map;
2377
2397
  const wildcardMethodRoot = createNode();
2378
2398
  entries.forEach((e, i) => {
2379
- const indexed = { entry: e, order: i };
2399
+ const indexed = { entry: e, order: i, compiled: compilePredicate(e.match) };
2380
2400
  if (e.match.method === "*") {
2381
2401
  insertPattern(wildcardMethodRoot, e.match.path, indexed);
2382
2402
  return;
@@ -2410,7 +2430,7 @@ function buildMatchIndex(entries) {
2410
2430
  match(method, path, req) {
2411
2431
  const hits = orderCandidates(candidates(method, path));
2412
2432
  for (const hit of hits) {
2413
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2433
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2414
2434
  if (!failure) {
2415
2435
  return { entry: hit.value.entry, params: hit.params };
2416
2436
  }
@@ -2423,7 +2443,7 @@ function buildMatchIndex(entries) {
2423
2443
  for (const hit of hits) {
2424
2444
  if (out.length >= limit)
2425
2445
  break;
2426
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2446
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2427
2447
  if (failure)
2428
2448
  out.push({ entry: hit.value.entry, params: hit.params, failure });
2429
2449
  }
@@ -2433,7 +2453,7 @@ function buildMatchIndex(entries) {
2433
2453
  }
2434
2454
 
2435
2455
  // src/core/scenarios/evaluator.ts
2436
- function compileMatcher(spec) {
2456
+ function compileMatcher2(spec) {
2437
2457
  if (typeof spec === "string")
2438
2458
  return { kind: "exact", value: spec };
2439
2459
  if ("equals" in spec)
@@ -2444,15 +2464,15 @@ function compileMatcher(spec) {
2444
2464
  return { kind: "startsWith", value: spec.startsWith };
2445
2465
  return { kind: "contains", value: spec.contains };
2446
2466
  }
2447
- function compileDim(record) {
2448
- return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2467
+ function compileDim2(record) {
2468
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher2(v)]));
2449
2469
  }
2450
- function compilePredicate(pred) {
2470
+ function compilePredicate2(pred) {
2451
2471
  return {
2452
- ...pred.params && { params: compileDim(pred.params) },
2453
- ...pred.query && { query: compileDim(pred.query) },
2454
- ...pred.headers && { headers: compileDim(pred.headers) },
2455
- ...pred.body && { body: compileDim(pred.body) }
2472
+ ...pred.params && { params: compileDim2(pred.params) },
2473
+ ...pred.query && { query: compileDim2(pred.query) },
2474
+ ...pred.headers && { headers: compileDim2(pred.headers) },
2475
+ ...pred.body && { body: compileDim2(pred.body) }
2456
2476
  };
2457
2477
  }
2458
2478
  function compileResponse(resp) {
@@ -2481,7 +2501,7 @@ function compileResponse(resp) {
2481
2501
  function compileScenarioRules(rules) {
2482
2502
  return rules.map((rule) => ({
2483
2503
  id: rule.id,
2484
- predicate: compilePredicate(rule.when),
2504
+ predicate: compilePredicate2(rule.when),
2485
2505
  response: compileResponse(rule.response)
2486
2506
  }));
2487
2507
  }
@@ -6533,15 +6553,65 @@ var coerce = {
6533
6553
  date: (arg) => ZodDate.create({ ...arg, coerce: true })
6534
6554
  };
6535
6555
  var NEVER = INVALID;
6556
+ // src/features/webhooks/scheme.ts
6557
+ var DEFAULT_SIGNED_PAYLOAD = "{timestamp}.{body}";
6558
+ var DEFAULT_SIGNATURE_TEMPLATE = "{algorithm}={signature}";
6559
+ var SIGNED_PAYLOAD_PLACEHOLDERS = ["body", "timestamp", "timestampSeconds"];
6560
+ var SIGNATURE_TEMPLATE_PLACEHOLDERS = [
6561
+ "signature",
6562
+ "algorithm",
6563
+ "timestamp",
6564
+ "timestampSeconds"
6565
+ ];
6566
+ var PLACEHOLDER_RE = /\{([A-Za-z][A-Za-z0-9]*)\}/g;
6567
+ var UNKNOWN_PLACEHOLDER_SCAN_RE = /\{[^{}]*\}/g;
6568
+ function unknownPlaceholders(template, allowed) {
6569
+ const seen = new Set;
6570
+ const out = [];
6571
+ for (const match of template.matchAll(UNKNOWN_PLACEHOLDER_SCAN_RE)) {
6572
+ const name = match[0].slice(1, -1);
6573
+ if (name === "")
6574
+ continue;
6575
+ if (allowed.includes(name) || seen.has(name))
6576
+ continue;
6577
+ seen.add(name);
6578
+ out.push(name);
6579
+ }
6580
+ return out;
6581
+ }
6582
+ function hasUnbalancedPlaceholder(template) {
6583
+ const residue = template.replace(UNKNOWN_PLACEHOLDER_SCAN_RE, "");
6584
+ return /\{[A-Za-z]/.test(residue);
6585
+ }
6586
+ function substitute(template, values) {
6587
+ return template.replace(PLACEHOLDER_RE, (match, name) => Object.hasOwn(values, name) ? values[name] : match);
6588
+ }
6589
+ function renderSignedPayload(template, v) {
6590
+ return substitute(template, {
6591
+ body: v.body,
6592
+ timestamp: String(v.timestampMs),
6593
+ timestampSeconds: String(Math.floor(v.timestampMs / 1000))
6594
+ });
6595
+ }
6596
+ function renderSignatureHeader(template, v) {
6597
+ return substitute(template, {
6598
+ signature: v.signature,
6599
+ algorithm: v.algorithm,
6600
+ timestamp: String(v.timestampMs),
6601
+ timestampSeconds: String(Math.floor(v.timestampMs / 1000))
6602
+ });
6603
+ }
6604
+ function timestampUnitFor(scheme) {
6605
+ const combined = `${scheme.signedPayload} ${scheme.signatureTemplate}`;
6606
+ if (combined.includes("{timestamp}"))
6607
+ return "ms";
6608
+ if (combined.includes("{timestampSeconds}"))
6609
+ return "s";
6610
+ return null;
6611
+ }
6612
+
6536
6613
  // src/core/config/schema.ts
6537
6614
  var MatchMethod = exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "*"]);
6538
- var StringMatch = exports_external.union([
6539
- exports_external.string(),
6540
- exports_external.object({ equals: exports_external.string() }).strict(),
6541
- exports_external.object({ regex: exports_external.string() }).strict(),
6542
- exports_external.object({ startsWith: exports_external.string() }).strict(),
6543
- exports_external.object({ contains: exports_external.string() }).strict()
6544
- ]);
6545
6615
  function isUnsafeRegex(pattern) {
6546
6616
  return /\([^)]*[*+{][^)]*\)[*+{]/.test(pattern) || /\([^)]*\|[^)]*\)[*+{]/.test(pattern);
6547
6617
  }
@@ -6549,7 +6619,7 @@ var StringMatchWithRegexGuard = exports_external.union([
6549
6619
  exports_external.string(),
6550
6620
  exports_external.object({ equals: exports_external.string() }).strict(),
6551
6621
  exports_external.object({ regex: exports_external.string() }).strict().refine((v) => !isUnsafeRegex(v.regex), (v) => ({
6552
- message: `scenario regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
6622
+ message: `regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
6553
6623
  })),
6554
6624
  exports_external.object({ startsWith: exports_external.string() }).strict(),
6555
6625
  exports_external.object({ contains: exports_external.string() }).strict()
@@ -6562,8 +6632,8 @@ var BodyMatch = exports_external.object({
6562
6632
  var MatchPredicate = exports_external.object({
6563
6633
  method: MatchMethod.default("*"),
6564
6634
  path: exports_external.string().min(1),
6565
- query: exports_external.record(StringMatch).optional(),
6566
- headers: exports_external.record(StringMatch).optional(),
6635
+ query: exports_external.record(StringMatchWithRegexGuard).optional(),
6636
+ headers: exports_external.record(StringMatchWithRegexGuard).optional(),
6567
6637
  body: BodyMatch.optional(),
6568
6638
  priority: exports_external.number().int().default(0)
6569
6639
  }).strict();
@@ -6614,16 +6684,105 @@ var ScenarioRule = exports_external.object({
6614
6684
  response: ScenarioResponse
6615
6685
  }).strict();
6616
6686
  var SECRET_REF_RE = /^(\{\{\s*env\.[A-Z_][A-Z0-9_]*\s*\}\}|file:.+)$/;
6617
- var WebhookSigning = exports_external.object({
6687
+ var HmacSigning = exports_external.object({
6688
+ mode: exports_external.literal("hmac").default("hmac"),
6618
6689
  enabled: exports_external.boolean().default(false),
6619
6690
  algorithm: exports_external.literal("sha256").default("sha256"),
6620
6691
  secretRef: exports_external.string().regex(SECRET_REF_RE, {
6621
6692
  message: "webhook signing.secretRef must be `{{ env.NAME }}` or `file:/path`; inline secrets rejected (S3)"
6622
6693
  }),
6694
+ signedPayload: exports_external.string().min(1).default(DEFAULT_SIGNED_PAYLOAD),
6695
+ signatureTemplate: exports_external.string().min(1).default(DEFAULT_SIGNATURE_TEMPLATE),
6696
+ digestEncoding: exports_external.enum(["hex", "base64"]).default("hex"),
6623
6697
  signatureHeader: exports_external.string().min(1).default("x-mockstar-signature"),
6624
- timestampHeader: exports_external.string().min(1).default("x-mockstar-timestamp"),
6698
+ timestampHeader: exports_external.string().min(1).nullable().default("x-mockstar-timestamp"),
6625
6699
  replayWindowMs: exports_external.number().int().positive().default(300000)
6626
6700
  }).strict();
6701
+ var WebhookSigning = exports_external.preprocess((raw) => raw !== null && typeof raw === "object" && !Array.isArray(raw) && !("mode" in raw) ? { ...raw, mode: "hmac" } : raw, exports_external.discriminatedUnion("mode", [HmacSigning])).superRefine((v, ctx) => {
6702
+ if (typeof v.signedPayload !== "string" || typeof v.signatureTemplate !== "string")
6703
+ return;
6704
+ const fmt = (names) => names.map((n) => `{${n}}`).join(", ");
6705
+ const signedPayloadHasDoubleBrace = v.signedPayload.includes("{{");
6706
+ if (signedPayloadHasDoubleBrace) {
6707
+ ctx.addIssue({
6708
+ code: exports_external.ZodIssueCode.custom,
6709
+ path: ["signedPayload"],
6710
+ message: "signedPayload uses single-brace placeholders (e.g. {body}), not the {{ }} request-template syntax \u2014 did you mean {body} instead of {{ body }}?"
6711
+ });
6712
+ }
6713
+ const signatureTemplateHasDoubleBrace = v.signatureTemplate.includes("{{");
6714
+ if (signatureTemplateHasDoubleBrace) {
6715
+ ctx.addIssue({
6716
+ code: exports_external.ZodIssueCode.custom,
6717
+ path: ["signatureTemplate"],
6718
+ message: "signatureTemplate uses single-brace placeholders (e.g. {signature}), not the {{ }} request-template syntax \u2014 did you mean {signature} instead of {{ signature }}?"
6719
+ });
6720
+ }
6721
+ const signedPayloadHasTemplateLiteral = v.signedPayload.includes("${");
6722
+ if (signedPayloadHasTemplateLiteral) {
6723
+ ctx.addIssue({
6724
+ code: exports_external.ZodIssueCode.custom,
6725
+ path: ["signedPayload"],
6726
+ message: "signedPayload uses single-brace placeholders (e.g. {body}), not JS template-literal syntax \u2014 did you mean {body} instead of ${body}?"
6727
+ });
6728
+ }
6729
+ const signatureTemplateHasTemplateLiteral = v.signatureTemplate.includes("${");
6730
+ if (signatureTemplateHasTemplateLiteral) {
6731
+ ctx.addIssue({
6732
+ code: exports_external.ZodIssueCode.custom,
6733
+ path: ["signatureTemplate"],
6734
+ message: "signatureTemplate uses single-brace placeholders (e.g. {signature}), not JS template-literal syntax \u2014 did you mean {signature} instead of ${signature}?"
6735
+ });
6736
+ }
6737
+ if (!signedPayloadHasDoubleBrace && !signedPayloadHasTemplateLiteral) {
6738
+ const badPayload = unknownPlaceholders(v.signedPayload, SIGNED_PAYLOAD_PLACEHOLDERS);
6739
+ if (badPayload.length > 0) {
6740
+ ctx.addIssue({
6741
+ code: exports_external.ZodIssueCode.custom,
6742
+ path: ["signedPayload"],
6743
+ message: `unknown placeholder(s) ${fmt(badPayload)} \u2014 allowed: ${fmt(SIGNED_PAYLOAD_PLACEHOLDERS)}`
6744
+ });
6745
+ }
6746
+ if (!v.signedPayload.includes("{body}")) {
6747
+ ctx.addIssue({
6748
+ code: exports_external.ZodIssueCode.custom,
6749
+ path: ["signedPayload"],
6750
+ message: "signedPayload must contain {body} \u2014 otherwise the signature covers no request content"
6751
+ });
6752
+ }
6753
+ if (hasUnbalancedPlaceholder(v.signedPayload)) {
6754
+ ctx.addIssue({
6755
+ code: exports_external.ZodIssueCode.custom,
6756
+ path: ["signedPayload"],
6757
+ message: "signedPayload has an unmatched { that looks like an unterminated placeholder \u2014 check for a missing closing brace"
6758
+ });
6759
+ }
6760
+ }
6761
+ if (!signatureTemplateHasDoubleBrace && !signatureTemplateHasTemplateLiteral) {
6762
+ const badTemplate = unknownPlaceholders(v.signatureTemplate, SIGNATURE_TEMPLATE_PLACEHOLDERS);
6763
+ if (badTemplate.length > 0) {
6764
+ ctx.addIssue({
6765
+ code: exports_external.ZodIssueCode.custom,
6766
+ path: ["signatureTemplate"],
6767
+ message: `unknown placeholder(s) ${fmt(badTemplate)} \u2014 allowed: ${fmt(SIGNATURE_TEMPLATE_PLACEHOLDERS)}`
6768
+ });
6769
+ }
6770
+ if (!v.signatureTemplate.includes("{signature}")) {
6771
+ ctx.addIssue({
6772
+ code: exports_external.ZodIssueCode.custom,
6773
+ path: ["signatureTemplate"],
6774
+ message: "signatureTemplate must contain {signature} \u2014 otherwise the signature header carries no digest"
6775
+ });
6776
+ }
6777
+ if (hasUnbalancedPlaceholder(v.signatureTemplate)) {
6778
+ ctx.addIssue({
6779
+ code: exports_external.ZodIssueCode.custom,
6780
+ path: ["signatureTemplate"],
6781
+ message: "signatureTemplate has an unmatched { that looks like an unterminated placeholder \u2014 check for a missing closing brace"
6782
+ });
6783
+ }
6784
+ }
6785
+ });
6627
6786
  var WebhookRetry = exports_external.object({
6628
6787
  attempts: exports_external.number().int().min(1).max(20).default(6),
6629
6788
  backoff: exports_external.array(exports_external.number().int().nonnegative()).default([1000, 2000, 4000, 8000, 16000]),
@@ -6684,7 +6843,7 @@ var MocksFile = exports_external.object({
6684
6843
  var TenantLimits = exports_external.object({
6685
6844
  maxBodyBytes: exports_external.number().int().positive().default(1048576),
6686
6845
  maxResponseBytes: exports_external.number().int().positive().default(1048576),
6687
- requestsPerSecond: exports_external.number().int().positive().default(1000),
6846
+ requestsPerSecond: exports_external.number().int().positive().default(1e4),
6688
6847
  journalSize: exports_external.number().int().positive().default(1000)
6689
6848
  }).strict();
6690
6849
  var TenantConfig = exports_external.object({
@@ -8628,6 +8787,77 @@ function installProcessHandlers(opts) {
8628
8787
  process.off("uncaughtException", excHandler);
8629
8788
  };
8630
8789
  }
8790
+ // src/core/http/body-cap.ts
8791
+ function capRequestBodyStream(ctx, maxBodyBytes) {
8792
+ const original = ctx.req.raw;
8793
+ let tooLarge = false;
8794
+ if (original.body && !original.bodyUsed) {
8795
+ let total = 0;
8796
+ const limited = original.body.pipeThrough(new TransformStream({
8797
+ transform(chunk, controller) {
8798
+ total += chunk.byteLength;
8799
+ if (total > maxBodyBytes) {
8800
+ tooLarge = true;
8801
+ controller.error(new Error("body_too_large"));
8802
+ return;
8803
+ }
8804
+ controller.enqueue(chunk);
8805
+ }
8806
+ }));
8807
+ ctx.req.raw = new Request(original, { body: limited, duplex: "half" });
8808
+ }
8809
+ return { tooLarge: () => tooLarge };
8810
+ }
8811
+ function bodyTooLargeResponse(limit) {
8812
+ return new Response(JSON.stringify({ error: "body_too_large", limit }), {
8813
+ status: 413,
8814
+ headers: { "content-type": "application/json" }
8815
+ });
8816
+ }
8817
+
8818
+ // src/core/http/rate-limit.ts
8819
+ class TenantRateLimiter {
8820
+ buckets = new Map;
8821
+ now;
8822
+ constructor(opts = {}) {
8823
+ this.now = opts.now ?? (() => Date.now());
8824
+ }
8825
+ get bucketCount() {
8826
+ return this.buckets.size;
8827
+ }
8828
+ tryAcquire(tenant, limitPerSecond) {
8829
+ const nowMs = this.now();
8830
+ let bucket = this.buckets.get(tenant);
8831
+ if (!bucket) {
8832
+ bucket = { tokens: limitPerSecond, lastRefillMs: nowMs };
8833
+ this.buckets.set(tenant, bucket);
8834
+ } else {
8835
+ const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);
8836
+ if (elapsedMs > 0) {
8837
+ const refill = elapsedMs * limitPerSecond / 1000;
8838
+ bucket.tokens = Math.min(limitPerSecond, bucket.tokens + refill);
8839
+ bucket.lastRefillMs = nowMs;
8840
+ }
8841
+ }
8842
+ if (bucket.tokens >= 1) {
8843
+ bucket.tokens -= 1;
8844
+ return { allowed: true, retryAfterSeconds: 0 };
8845
+ }
8846
+ const deficitMs = (1 - bucket.tokens) / limitPerSecond * 1000;
8847
+ const retryAfterSeconds = Math.max(1, Math.ceil(deficitMs / 1000));
8848
+ return { allowed: false, retryAfterSeconds };
8849
+ }
8850
+ }
8851
+ function rateLimitedResponse(limit, retryAfterSeconds) {
8852
+ return new Response(JSON.stringify({ error: "rate_limited", limit }), {
8853
+ status: 429,
8854
+ headers: {
8855
+ "content-type": "application/json",
8856
+ "retry-after": String(retryAfterSeconds)
8857
+ }
8858
+ });
8859
+ }
8860
+
8631
8861
  // src/core/journal/ring-buffer.ts
8632
8862
  class RingBuffer {
8633
8863
  capacity;
@@ -11109,7 +11339,7 @@ function adminRouter(deps) {
11109
11339
  entryId,
11110
11340
  id: spec.id,
11111
11341
  method: spec.method,
11112
- signing: spec.signing ? { enabled: spec.signing.enabled, algorithm: spec.signing.algorithm } : null,
11342
+ signing: spec.signing ? { mode: spec.signing.mode, enabled: spec.signing.enabled, algorithm: spec.signing.algorithm } : null,
11113
11343
  retry: { attempts: spec.retry.attempts },
11114
11344
  circuit: spec.circuit,
11115
11345
  timeoutMs: spec.timeoutMs,
@@ -11218,7 +11448,11 @@ var PRIVATE_IPV4_RANGES = [
11218
11448
  [127, 0, 0, 8],
11219
11449
  [169, 254, 0, 16],
11220
11450
  [100, 64, 0, 10],
11221
- [0, 0, 0, 8]
11451
+ [0, 0, 0, 8],
11452
+ [192, 0, 0, 24],
11453
+ [198, 18, 0, 15],
11454
+ [224, 0, 0, 4],
11455
+ [240, 0, 0, 4]
11222
11456
  ];
11223
11457
  function validateUpstreamUrl(raw2, opts = {}) {
11224
11458
  const allowedSchemes = opts.allowedSchemes ?? ["https"];
@@ -11281,12 +11515,49 @@ async function validateUpstreamUrlResolved(raw2, opts = {}) {
11281
11515
  });
11282
11516
  return parsed;
11283
11517
  }
11518
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11519
+ var DEFAULT_MAX_REDIRECT_HOPS = 5;
11520
+ async function fetchWithRedirectGuard(initialUrl, init, validation, maxRedirects = DEFAULT_MAX_REDIRECT_HOPS) {
11521
+ let currentUrl = initialUrl;
11522
+ let method = init.method;
11523
+ let body = init.body;
11524
+ let redirectsFollowed = 0;
11525
+ for (;; ) {
11526
+ const response = await fetch(currentUrl, {
11527
+ method,
11528
+ headers: init.headers,
11529
+ body: method === "GET" || method === "HEAD" ? undefined : body ?? undefined,
11530
+ redirect: "manual",
11531
+ signal: init.signal
11532
+ });
11533
+ const location = response.headers.get("location");
11534
+ if (!REDIRECT_STATUSES.has(response.status) || !location) {
11535
+ return { response, finalUrl: currentUrl, redirectsFollowed };
11536
+ }
11537
+ await response.body?.cancel();
11538
+ if (redirectsFollowed >= maxRedirects) {
11539
+ throw new UrlValidationError(currentUrl.href, `redirect chain exceeded ${maxRedirects} hop(s); blocked before following Location '${location}'`);
11540
+ }
11541
+ redirectsFollowed++;
11542
+ let nextUrl;
11543
+ try {
11544
+ nextUrl = new URL(location, currentUrl);
11545
+ } catch {
11546
+ throw new UrlValidationError(location, "redirect Location header is not a resolvable URL");
11547
+ }
11548
+ currentUrl = await validateUpstreamUrlResolved(nextUrl.href, validation);
11549
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") {
11550
+ method = "GET";
11551
+ body = null;
11552
+ }
11553
+ }
11554
+ }
11284
11555
  function isPrivateHost(hostname) {
11285
11556
  const stripped = hostname.replace(/^\[/, "").replace(/\]$/, "");
11286
11557
  const lowered = stripped.toLowerCase();
11287
11558
  if (lowered === "localhost" || lowered === "ip6-localhost" || lowered === "ip6-loopback")
11288
11559
  return true;
11289
- if (lowered === "::1" || lowered.startsWith("fe80:") || lowered.startsWith("fc") || lowered.startsWith("fd")) {
11560
+ if (isIpLiteral(stripped) && isPrivateIpv6(lowered)) {
11290
11561
  return true;
11291
11562
  }
11292
11563
  const ipv4MappedDotted = lowered.match(/^::ffff:([0-9.]+)$/);
@@ -11307,6 +11578,75 @@ function isPrivateHost(hostname) {
11307
11578
  }
11308
11579
  return false;
11309
11580
  }
11581
+ function expandIpv6(addr) {
11582
+ const halves = addr.split("::");
11583
+ if (halves.length > 2)
11584
+ return null;
11585
+ const parseGroups = (segment) => {
11586
+ if (segment === "")
11587
+ return [];
11588
+ const pieces = segment.split(":");
11589
+ const groups = [];
11590
+ for (let i2 = 0;i2 < pieces.length; i2++) {
11591
+ const piece = pieces[i2] ?? "";
11592
+ if (i2 === pieces.length - 1 && piece.includes(".")) {
11593
+ const octets = piece.split(".").map((o2) => Number.parseInt(o2, 10));
11594
+ if (octets.length !== 4 || octets.some((o2) => Number.isNaN(o2) || o2 < 0 || o2 > 255) || piece.split(".").some((o2) => !/^\d{1,3}$/.test(o2))) {
11595
+ return null;
11596
+ }
11597
+ const [a2 = 0, b2 = 0, c2 = 0, d2 = 0] = octets;
11598
+ groups.push(a2 << 8 | b2, c2 << 8 | d2);
11599
+ continue;
11600
+ }
11601
+ if (piece.length === 0 || piece.length > 4 || !/^[0-9a-f]+$/.test(piece))
11602
+ return null;
11603
+ const value = Number.parseInt(piece, 16);
11604
+ if (Number.isNaN(value))
11605
+ return null;
11606
+ groups.push(value);
11607
+ }
11608
+ return groups;
11609
+ };
11610
+ if (halves.length === 1) {
11611
+ const groups = parseGroups(halves[0] ?? "");
11612
+ return groups && groups.length === 8 ? groups : null;
11613
+ }
11614
+ const head = parseGroups(halves[0] ?? "");
11615
+ const tail = parseGroups(halves[1] ?? "");
11616
+ if (!head || !tail)
11617
+ return null;
11618
+ const missing = 8 - head.length - tail.length;
11619
+ if (missing < 0)
11620
+ return null;
11621
+ return [...head, ...Array(missing).fill(0), ...tail];
11622
+ }
11623
+ function ipv6PrefixMatch(groups, prefixGroups, prefixBits) {
11624
+ let bitsLeft = prefixBits;
11625
+ for (let i2 = 0;i2 < prefixGroups.length && bitsLeft > 0; i2++) {
11626
+ const bits = Math.min(16, bitsLeft);
11627
+ const mask = bits === 16 ? 65535 : 65535 << 16 - bits & 65535;
11628
+ if (((groups[i2] ?? 0) & mask) !== ((prefixGroups[i2] ?? 0) & mask))
11629
+ return false;
11630
+ bitsLeft -= bits;
11631
+ }
11632
+ return true;
11633
+ }
11634
+ function isPrivateIpv6(lowered) {
11635
+ const groups = expandIpv6(lowered);
11636
+ if (!groups)
11637
+ return false;
11638
+ if (groups.every((g2) => g2 === 0))
11639
+ return true;
11640
+ if (groups.slice(0, 7).every((g2) => g2 === 0) && groups[7] === 1)
11641
+ return true;
11642
+ if (ipv6PrefixMatch(groups, [64512], 7))
11643
+ return true;
11644
+ if (ipv6PrefixMatch(groups, [65152], 10))
11645
+ return true;
11646
+ if (ipv6PrefixMatch(groups, [100, 65435, 0, 0, 0, 0], 96))
11647
+ return true;
11648
+ return false;
11649
+ }
11310
11650
  function isPrivateIpv4(ip) {
11311
11651
  const parts = ip.split(".").map((p3) => Number.parseInt(p3, 10));
11312
11652
  if (parts.length !== 4 || parts.some((p3) => Number.isNaN(p3) || p3 < 0 || p3 > 255))
@@ -11318,16 +11658,13 @@ function isPrivateIpv4(ip) {
11318
11658
  }
11319
11659
  return false;
11320
11660
  }
11321
- function matchesIpv4(a2, _b, _c, _d, ra2, _rb, _rc, mask) {
11322
- if (mask === 8)
11323
- return a2 === ra2;
11324
- if (mask === 16)
11325
- return a2 === ra2 && _b === _rb;
11326
- if (mask === 12)
11327
- return a2 === ra2 && (_b & 240) === (_rb & 240);
11328
- if (mask === 10)
11329
- return a2 === ra2 && (_b & 192) === (_rb & 192);
11330
- return false;
11661
+ function matchesIpv4(a2, b2, c2, d2, ra2, rb, rc, mask) {
11662
+ if (mask <= 0 || mask > 32)
11663
+ return false;
11664
+ const value = (a2 << 24 | b2 << 16 | c2 << 8 | d2) >>> 0;
11665
+ const rangeValue = (ra2 << 24 | rb << 16 | rc << 8 | 0) >>> 0;
11666
+ const maskBits = mask === 32 ? 4294967295 : 4294967295 << 32 - mask >>> 0;
11667
+ return (value & maskBits) >>> 0 === (rangeValue & maskBits) >>> 0;
11331
11668
  }
11332
11669
 
11333
11670
  // src/features/pass-through.ts
@@ -11336,12 +11673,13 @@ async function renderPassThrough(entry, ctx, opts) {
11336
11673
  throw new Error(`renderPassThrough called for non-passthrough entry '${entry.id}'`);
11337
11674
  }
11338
11675
  const spec = entry.response;
11676
+ const validationOpts = {
11677
+ allowedSchemes: ["https", "http"],
11678
+ allowPrivateUpstreams: opts.allowPrivateUpstreams
11679
+ };
11339
11680
  let upstreamUrl;
11340
11681
  try {
11341
- upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, {
11342
- allowedSchemes: ["https", "http"],
11343
- allowPrivateUpstreams: opts.allowPrivateUpstreams
11344
- });
11682
+ upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, validationOpts);
11345
11683
  } catch (err) {
11346
11684
  opts.logger.error({
11347
11685
  event: "passthrough_url_rejected",
@@ -11368,14 +11706,16 @@ async function renderPassThrough(entry, ctx, opts) {
11368
11706
  const controller = new AbortController;
11369
11707
  const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
11370
11708
  timer.unref?.();
11709
+ const bodyCap = ctx.req.method === "GET" || ctx.req.method === "HEAD" ? null : capRequestBodyStream(ctx, opts.maxBodyBytes);
11371
11710
  const started = performance.now();
11372
11711
  try {
11373
- const upstreamRes = await fetch(targetUrl, {
11712
+ const requestBody = bodyCap ? await ctx.req.raw.arrayBuffer() : null;
11713
+ const { response: upstreamRes } = await fetchWithRedirectGuard(targetUrl, {
11374
11714
  method: ctx.req.method,
11375
11715
  headers,
11376
- body: ctx.req.method === "GET" || ctx.req.method === "HEAD" ? undefined : await ctx.req.raw.arrayBuffer(),
11716
+ body: requestBody,
11377
11717
  signal: controller.signal
11378
- });
11718
+ }, validationOpts);
11379
11719
  clearTimeout(timer);
11380
11720
  return new Response(upstreamRes.body, {
11381
11721
  status: upstreamRes.status,
@@ -11383,7 +11723,23 @@ async function renderPassThrough(entry, ctx, opts) {
11383
11723
  });
11384
11724
  } catch (err) {
11385
11725
  clearTimeout(timer);
11726
+ if (bodyCap?.tooLarge()) {
11727
+ return bodyTooLargeResponse(opts.maxBodyBytes);
11728
+ }
11386
11729
  const durationMs = performance.now() - started;
11730
+ if (err instanceof UrlValidationError) {
11731
+ opts.logger.error({
11732
+ event: "passthrough_redirect_rejected",
11733
+ entryId: entry.id,
11734
+ upstream: String(upstreamUrl),
11735
+ reason: err.reason
11736
+ });
11737
+ return new Response(JSON.stringify({
11738
+ error: "passthrough_upstream",
11739
+ upstream: String(upstreamUrl),
11740
+ reason: "upstream redirected to a URL rejected by validator"
11741
+ }), { status: 502, headers: { "content-type": "application/json" } });
11742
+ }
11387
11743
  const aborted = err instanceof DOMException && err.name === "AbortError";
11388
11744
  opts.logger.error({
11389
11745
  event: "passthrough_upstream_error",
@@ -11869,12 +12225,39 @@ class BoundedRetryQueue {
11869
12225
  #cap;
11870
12226
  #onDropped;
11871
12227
  #onSizeChange;
12228
+ #timers = new Map;
12229
+ #stopped = false;
11872
12230
  constructor(opts = {}) {
11873
12231
  this.#pq = new PQueue({ concurrency: opts.concurrency ?? DEFAULT_CONCURRENCY });
11874
12232
  this.#cap = opts.cap ?? DEFAULT_CAP;
11875
12233
  this.#onDropped = opts.onDropped;
11876
12234
  this.#onSizeChange = opts.onSizeChange;
11877
12235
  }
12236
+ stop() {
12237
+ if (this.#stopped)
12238
+ return;
12239
+ this.#stopped = true;
12240
+ for (const [timer, resolve4] of this.#timers) {
12241
+ clearTimeout(timer);
12242
+ resolve4();
12243
+ }
12244
+ this.#timers.clear();
12245
+ const abandoned = this.#waiting.splice(0, this.#waiting.length);
12246
+ for (const req of abandoned) {
12247
+ this.#dropDelivery(req);
12248
+ }
12249
+ }
12250
+ #sleep(ms) {
12251
+ if (ms <= 0 || this.#stopped)
12252
+ return Promise.resolve();
12253
+ return new Promise((resolve4) => {
12254
+ const timer = setTimeout(() => {
12255
+ this.#timers.delete(timer);
12256
+ resolve4();
12257
+ }, ms);
12258
+ this.#timers.set(timer, resolve4);
12259
+ });
12260
+ }
11878
12261
  #fireSizeChange() {
11879
12262
  if (!this.#onSizeChange)
11880
12263
  return;
@@ -11893,7 +12276,14 @@ class BoundedRetryQueue {
11893
12276
  inflight() {
11894
12277
  return this.#pq.pending;
11895
12278
  }
12279
+ liveTimerCount() {
12280
+ return this.#timers.size;
12281
+ }
11896
12282
  enqueue(req) {
12283
+ if (this.#stopped) {
12284
+ this.#dropDelivery(req);
12285
+ return;
12286
+ }
11897
12287
  while (this.size() >= this.#cap) {
11898
12288
  const oldest = this.#waiting.shift();
11899
12289
  if (oldest) {
@@ -11926,7 +12316,17 @@ class BoundedRetryQueue {
11926
12316
  if (attempt > 1) {
11927
12317
  const baseMs = req.retry.backoff[attempt - 2] ?? 0;
11928
12318
  const delayMs = applyJitter(baseMs, req.retry.jitterRatio);
11929
- await sleep(delayMs);
12319
+ await this.#sleep(delayMs);
12320
+ if (this.#stopped) {
12321
+ req.onTerminal({
12322
+ deliveryId: req.deliveryId,
12323
+ outcome: "failed",
12324
+ totalAttempts: attempt - 1,
12325
+ lastHttpStatus,
12326
+ totalDurationUs: Math.round((performance.now() - totalStart) * 1000)
12327
+ });
12328
+ return;
12329
+ }
11930
12330
  }
11931
12331
  const gate = req.circuitGate();
11932
12332
  if (gate === "open") {
@@ -11968,7 +12368,7 @@ class BoundedRetryQueue {
11968
12368
  lastError = errorToString(err);
11969
12369
  req.onAttempt({
11970
12370
  attempt,
11971
- outcome: attempt === req.retry.attempts ? "failed" : "success",
12371
+ outcome: attempt === req.retry.attempts ? "failed" : "retrying",
11972
12372
  durationUs: 0,
11973
12373
  error: lastError
11974
12374
  });
@@ -12006,11 +12406,6 @@ function applyJitter(baseMs, ratio) {
12006
12406
  const delta = baseMs * ratio;
12007
12407
  return Math.max(0, Math.round(baseMs - delta + Math.random() * 2 * delta));
12008
12408
  }
12009
- function sleep(ms) {
12010
- if (ms <= 0)
12011
- return Promise.resolve();
12012
- return new Promise((resolve4) => setTimeout(resolve4, ms));
12013
- }
12014
12409
  function errorToString(err) {
12015
12410
  if (err instanceof Error)
12016
12411
  return `${err.name}: ${err.message}`;
@@ -12130,6 +12525,13 @@ class DeliveryEventRegistry {
12130
12525
  this.#completed.delete(id);
12131
12526
  }
12132
12527
  }
12528
+ stop() {
12529
+ const pending = Array.from(this.#pending.values());
12530
+ for (const deferred of pending) {
12531
+ deferred.resolve(null);
12532
+ }
12533
+ this.#pending.clear();
12534
+ }
12133
12535
  pendingCount() {
12134
12536
  return this.#pending.size;
12135
12537
  }
@@ -12139,6 +12541,25 @@ class DeliveryEventRegistry {
12139
12541
  }
12140
12542
  // src/features/webhooks/journal.ts
12141
12543
  import { appendFileSync } from "fs";
12544
+ function redactUrlForJournal(rawUrl) {
12545
+ try {
12546
+ return `${new URL(rawUrl).origin}/[redacted]`;
12547
+ } catch {
12548
+ return "[redacted:unparseable-url]";
12549
+ }
12550
+ }
12551
+ var EMBEDDED_URL_PATTERN = /\bhttps?:\/\/[^\s'"()<>[\]{}]+/gi;
12552
+ function redactUrlsInText(text) {
12553
+ return text.replace(EMBEDDED_URL_PATTERN, (match2) => redactUrlForJournal(match2));
12554
+ }
12555
+ function redactEntry(entry) {
12556
+ return {
12557
+ ...entry,
12558
+ ...entry.resolvedUrl !== undefined && { resolvedUrl: redactUrlForJournal(entry.resolvedUrl) },
12559
+ ...entry.error !== undefined && { error: redactUrlsInText(entry.error) }
12560
+ };
12561
+ }
12562
+
12142
12563
  class WebhookJournalRegistry {
12143
12564
  #buffers = new Map;
12144
12565
  #capacityFor;
@@ -12148,11 +12569,12 @@ class WebhookJournalRegistry {
12148
12569
  this.#journalFile = opts.journalFile;
12149
12570
  }
12150
12571
  record(entry) {
12151
- const buf = this.#bufferFor(entry.tenant);
12152
- buf.push(entry);
12572
+ const redacted = redactEntry(entry);
12573
+ const buf = this.#bufferFor(redacted.tenant);
12574
+ buf.push(redacted);
12153
12575
  if (this.#journalFile) {
12154
12576
  try {
12155
- appendFileSync(this.#journalFile, `${JSON.stringify(entry)}
12577
+ appendFileSync(this.#journalFile, `${JSON.stringify(redacted)}
12156
12578
  `);
12157
12579
  } catch (err) {
12158
12580
  console.warn(`[mockstar] webhook journal file write failed: ${err.message ?? err}`);
@@ -12185,9 +12607,33 @@ class WebhookJournalRegistry {
12185
12607
  }
12186
12608
  // src/features/webhooks/signing.ts
12187
12609
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
12188
- function signPayload(rawBody, secret, timestampMs) {
12189
- const stringToSign = `${timestampMs}.${rawBody}`;
12190
- return createHmac("sha256", secret).update(stringToSign, "utf8").digest("hex");
12610
+ var LEGACY_SCHEME = Object.freeze({
12611
+ signedPayload: DEFAULT_SIGNED_PAYLOAD,
12612
+ signatureTemplate: DEFAULT_SIGNATURE_TEMPLATE,
12613
+ digestEncoding: "hex",
12614
+ algorithm: "sha256"
12615
+ });
12616
+ function signPayload(rawBody, secret, timestampMs, scheme = LEGACY_SCHEME) {
12617
+ const stringToSign = renderSignedPayload(scheme.signedPayload, { body: rawBody, timestampMs });
12618
+ return createHmac(scheme.algorithm, secret).update(stringToSign, "utf8").digest(scheme.digestEncoding);
12619
+ }
12620
+ function verifySignature(rawBody, secret, timestampMs, signature, scheme = LEGACY_SCHEME) {
12621
+ try {
12622
+ const expected = signPayload(rawBody, secret, timestampMs, scheme);
12623
+ if (expected.length !== signature.length)
12624
+ return false;
12625
+ const a2 = Buffer.from(expected, scheme.digestEncoding);
12626
+ const b2 = Buffer.from(signature, scheme.digestEncoding);
12627
+ if (a2.length !== b2.length || a2.length === 0)
12628
+ return false;
12629
+ return timingSafeEqual2(a2, b2);
12630
+ } catch {
12631
+ return false;
12632
+ }
12633
+ }
12634
+ function withinReplayWindow(timestampMs, windowMs, nowMs = Date.now(), futureSkewMs = 60000) {
12635
+ const delta = nowMs - timestampMs;
12636
+ return delta <= windowMs && delta >= -futureSkewMs;
12191
12637
  }
12192
12638
  function resolveSecret(secretRef) {
12193
12639
  const envMatch = secretRef.match(/^\{\{\s*env\.([A-Z_][A-Z0-9_]*)\s*\}\}$/);
@@ -12252,14 +12698,13 @@ function dispatchWebhooks(deps, input) {
12252
12698
  }
12253
12699
  async function performAttempt(spec, input, _deps) {
12254
12700
  const attemptStart = performance.now();
12255
- let urlString;
12256
12701
  const headerUrl = _deps.allowWebhookUrlHeader && spec.acceptHeaderOverride ? input.requestHeaders.get("x-mockstar-webhook-url") : undefined;
12257
- urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12258
- const allowedSchemes = spec.allowHttp ? ["http", "https"] : ["https"];
12259
- await validateUpstreamUrlResolved(urlString, {
12260
- allowedSchemes,
12702
+ const urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12703
+ const validationOpts = {
12704
+ allowedSchemes: spec.allowHttp ? ["http", "https"] : ["https"],
12261
12705
  allowPrivateUpstreams: spec.allowPrivateNetworks
12262
- });
12706
+ };
12707
+ const validatedUrl = await validateUpstreamUrlResolved(urlString, validationOpts);
12263
12708
  const renderedHeaders = new Headers;
12264
12709
  for (const [key, tmpl] of spec.headers) {
12265
12710
  renderedHeaders.set(key, tmpl.render(input.templateContext));
@@ -12268,23 +12713,43 @@ async function performAttempt(spec, input, _deps) {
12268
12713
  if (spec.signing?.enabled) {
12269
12714
  const secret = resolveSecret(spec.signing.secretRef);
12270
12715
  const timestampMs = Date.now();
12271
- const signature = signPayload(rawBody, secret, timestampMs);
12272
- renderedHeaders.set(spec.signing.signatureHeader, `${spec.signing.algorithm}=${signature}`);
12273
- renderedHeaders.set(spec.signing.timestampHeader, String(timestampMs));
12716
+ const scheme = {
12717
+ signedPayload: spec.signing.signedPayload,
12718
+ signatureTemplate: spec.signing.signatureTemplate,
12719
+ digestEncoding: spec.signing.digestEncoding,
12720
+ algorithm: spec.signing.algorithm
12721
+ };
12722
+ const signature = signPayload(rawBody, secret, timestampMs, scheme);
12723
+ renderedHeaders.set(spec.signing.signatureHeader, renderSignatureHeader(scheme.signatureTemplate, {
12724
+ signature,
12725
+ algorithm: scheme.algorithm,
12726
+ timestampMs
12727
+ }));
12728
+ const unit = timestampUnitFor(scheme);
12729
+ if (unit !== null && spec.signing.timestampHeader !== null) {
12730
+ const value = unit === "s" ? Math.floor(timestampMs / 1000) : timestampMs;
12731
+ renderedHeaders.set(spec.signing.timestampHeader, String(value));
12732
+ }
12274
12733
  }
12275
12734
  if (!renderedHeaders.has("x-mockstar-delivery-id")) {
12276
12735
  renderedHeaders.set("x-mockstar-delivery-id", input.triggerRequestId);
12277
12736
  }
12278
12737
  const signal = AbortSignal.timeout(spec.timeoutMs);
12279
12738
  let response;
12739
+ let finalUrl;
12280
12740
  try {
12281
- response = await fetch(urlString, {
12741
+ const result = await fetchWithRedirectGuard(validatedUrl, {
12282
12742
  method: spec.method,
12283
12743
  headers: renderedHeaders,
12284
- body: spec.method === "GET" || spec.method === "DELETE" ? undefined : rawBody,
12744
+ body: spec.method === "GET" || spec.method === "DELETE" ? null : rawBody,
12285
12745
  signal
12286
- });
12746
+ }, validationOpts);
12747
+ response = result.response;
12748
+ finalUrl = result.finalUrl;
12287
12749
  } catch (err) {
12750
+ if (err instanceof UrlValidationError) {
12751
+ throw new Error(`webhook delivery redirect rejected: ${err.message}`);
12752
+ }
12288
12753
  throw new Error(`webhook delivery network error: ${err.message ?? err}`);
12289
12754
  }
12290
12755
  if (!isSuccessStatus(response.status, spec.expectResponse)) {
@@ -12299,7 +12764,7 @@ async function performAttempt(spec, input, _deps) {
12299
12764
  return {
12300
12765
  httpStatus: response.status,
12301
12766
  durationUs: Math.round((performance.now() - attemptStart) * 1000),
12302
- resolvedUrl: urlString
12767
+ resolvedUrl: finalUrl.href
12303
12768
  };
12304
12769
  }
12305
12770
  function isSuccessStatus(status, expect) {
@@ -12350,6 +12815,8 @@ function makeDeliveryId() {
12350
12815
  return crypto.randomUUID();
12351
12816
  }
12352
12817
  // src/server.ts
12818
+ var UNKNOWN_TENANT_BUCKET = ":unknown:";
12819
+ var DEFAULT_REQUESTS_PER_SECOND = 1e4;
12353
12820
  function createServer(opts) {
12354
12821
  const logger = opts.logger ?? createLogger({ deterministic: opts.deterministic });
12355
12822
  const metrics = new Metrics;
@@ -12357,6 +12824,7 @@ function createServer(opts) {
12357
12824
  const snap = opts.holder.get().tenants.get(tenant);
12358
12825
  return snap?.limits.journalSize ?? 1000;
12359
12826
  });
12827
+ const rateLimiter = new TenantRateLimiter({ now: opts.rateLimiterNow });
12360
12828
  const webhookJournal = new WebhookJournalRegistry((tenant) => {
12361
12829
  const snap = opts.holder.get().tenants.get(tenant);
12362
12830
  return snap?.limits.journalSize ?? 1000;
@@ -12467,6 +12935,7 @@ function createServer(opts) {
12467
12935
  clock,
12468
12936
  journal,
12469
12937
  metrics,
12938
+ rateLimiter,
12470
12939
  handlerTimeoutMs,
12471
12940
  genRequestId,
12472
12941
  webhookJournal,
@@ -12475,15 +12944,22 @@ function createServer(opts) {
12475
12944
  circuitFor,
12476
12945
  allowWebhookUrlHeader
12477
12946
  }));
12947
+ const stopWebhooks = () => {
12948
+ for (const q3 of webhookQueues.values())
12949
+ q3.stop();
12950
+ webhookEvents.stop();
12951
+ };
12478
12952
  return {
12479
12953
  hono: app,
12480
12954
  journal,
12481
12955
  metrics,
12956
+ rateLimiter,
12482
12957
  ready,
12483
12958
  uninstallCrashHandlers,
12484
12959
  webhookJournal,
12485
12960
  webhookEvents,
12486
- replayWebhook
12961
+ replayWebhook,
12962
+ stopWebhooks
12487
12963
  };
12488
12964
  }
12489
12965
  async function dispatch(ctx, deps) {
@@ -12495,28 +12971,35 @@ async function dispatch(ctx, deps) {
12495
12971
  const startedUs = performance.now() * 1000;
12496
12972
  const matchPath = effectivePath(ctx);
12497
12973
  const method = ctx.req.method;
12974
+ const observedTenant = tenantSnap ? tenant : UNKNOWN_TENANT_BUCKET;
12498
12975
  let response;
12499
12976
  let matchedMockId = null;
12500
12977
  let scenarioId;
12501
12978
  let scenarioMissReason;
12502
12979
  let webhookTrigger;
12503
12980
  try {
12504
- if (!tenantSnap) {
12981
+ const rpsLimit = tenantSnap?.limits.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;
12982
+ const rateResult = deps.rateLimiter.tryAcquire(observedTenant, rpsLimit);
12983
+ if (!rateResult.allowed) {
12984
+ response = rateLimitedResponse(rpsLimit, rateResult.retryAfterSeconds);
12985
+ } else if (!tenantSnap) {
12505
12986
  response = notFoundUnknownTenant(tenant, method, matchPath);
12506
12987
  } else {
12507
12988
  const contentLength = Number.parseInt(ctx.req.header("content-length") ?? "0", 10);
12508
12989
  if (contentLength > tenantSnap.limits.maxBodyBytes) {
12509
- response = new Response(JSON.stringify({ error: "body_too_large", limit: tenantSnap.limits.maxBodyBytes }), {
12510
- status: 413,
12511
- headers: { "content-type": "application/json" }
12512
- });
12990
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
12513
12991
  } else {
12514
- const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps);
12515
- response = result.response;
12516
- matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
12517
- scenarioId = result.scenarioId;
12518
- scenarioMissReason = result.scenarioMissReason;
12519
- webhookTrigger = result.webhookTrigger;
12992
+ const bodyResult = await safeParseBody(ctx, tenantSnap.limits.maxBodyBytes);
12993
+ if (!bodyResult.ok) {
12994
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
12995
+ } else {
12996
+ const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, bodyResult.body);
12997
+ response = result.response;
12998
+ matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
12999
+ scenarioId = result.scenarioId;
13000
+ scenarioMissReason = result.scenarioMissReason;
13001
+ webhookTrigger = result.webhookTrigger;
13002
+ }
12520
13003
  }
12521
13004
  }
12522
13005
  } catch (err) {
@@ -12537,7 +13020,7 @@ async function dispatch(ctx, deps) {
12537
13020
  const durationUs = Math.round(performance.now() * 1000 - startedUs);
12538
13021
  const entry = {
12539
13022
  timestamp: Date.now(),
12540
- tenant,
13023
+ tenant: observedTenant,
12541
13024
  requestId,
12542
13025
  method,
12543
13026
  path: matchPath,
@@ -12549,15 +13032,15 @@ async function dispatch(ctx, deps) {
12549
13032
  };
12550
13033
  deps.journal.record(entry);
12551
13034
  deps.metrics.incCounter("mockstar_requests_total", {
12552
- tenant,
13035
+ tenant: observedTenant,
12553
13036
  method,
12554
13037
  status: String(response.status),
12555
13038
  matched: matchedMockId ? "1" : "0"
12556
13039
  });
12557
- deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant }, durationUs);
13040
+ deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant: observedTenant }, durationUs);
12558
13041
  deps.logger.info({
12559
13042
  event: "request",
12560
- tenant,
13043
+ tenant: observedTenant,
12561
13044
  method,
12562
13045
  path: matchPath,
12563
13046
  status: response.status,
@@ -12606,9 +13089,8 @@ async function dispatch(ctx, deps) {
12606
13089
  });
12607
13090
  return response;
12608
13091
  }
12609
- async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps) {
13092
+ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, body) {
12610
13093
  const url = new URL(ctx.req.url);
12611
- const body = await safeParseBody(ctx);
12612
13094
  const req = {
12613
13095
  query: new Map(Array.from(url.searchParams)),
12614
13096
  headers: new Map(Array.from(ctx.req.raw.headers).map(([k2, v3]) => [k2.toLowerCase(), v3])),
@@ -12720,7 +13202,8 @@ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap,
12720
13202
  case "passthrough":
12721
13203
  response = await renderPassThrough(hit.entry, ctx, {
12722
13204
  allowPrivateUpstreams: tenantSnap.allowPrivateUpstreams,
12723
- logger: deps.logger
13205
+ logger: deps.logger,
13206
+ maxBodyBytes: tenantSnap.limits.maxBodyBytes
12724
13207
  });
12725
13208
  break;
12726
13209
  }
@@ -12738,20 +13221,27 @@ function notFoundUnknownTenant(tenant, method, path) {
12738
13221
  headers: { "content-type": "application/json" }
12739
13222
  });
12740
13223
  }
12741
- async function safeParseBody(ctx) {
13224
+ async function safeParseBody(ctx, maxBodyBytes) {
12742
13225
  const method = ctx.req.method;
12743
13226
  if (method === "GET" || method === "HEAD")
12744
- return null;
13227
+ return { ok: true, body: null };
12745
13228
  const contentType = ctx.req.header("content-type") ?? "";
12746
13229
  if (!contentType.includes("json"))
12747
- return null;
13230
+ return { ok: true, body: null };
13231
+ const { tooLarge } = capRequestBodyStream(ctx, maxBodyBytes);
12748
13232
  try {
12749
13233
  const text = await ctx.req.text();
12750
13234
  if (text.length === 0)
12751
- return null;
12752
- return JSON.parse(text);
12753
- } catch {
12754
- return null;
13235
+ return { ok: true, body: null };
13236
+ try {
13237
+ return { ok: true, body: JSON.parse(text) };
13238
+ } catch {
13239
+ return { ok: true, body: null };
13240
+ }
13241
+ } catch (err) {
13242
+ if (tooLarge())
13243
+ return { ok: false };
13244
+ throw err;
12755
13245
  }
12756
13246
  }
12757
13247
  function createRequestIdGenerator(deterministic) {
@@ -12803,11 +13293,16 @@ async function launch(opts) {
12803
13293
  holder,
12804
13294
  async stop() {
12805
13295
  watcher?.stop();
13296
+ server.stopWebhooks();
12806
13297
  server.uninstallCrashHandlers();
12807
13298
  }
12808
13299
  };
12809
13300
  }
12810
13301
  export {
13302
+ withinReplayWindow,
13303
+ verifySignature,
13304
+ signPayload,
12811
13305
  launch,
12812
- SnapshotHolder
13306
+ SnapshotHolder,
13307
+ LEGACY_SCHEME
12813
13308
  };