@dhaneshpurohit/mockstar 0.3.0 → 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 (41) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/cli.js +589 -169
  3. package/dist/core/config/schema.d.ts +197 -165
  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/event-registry.d.ts +7 -0
  29. package/dist/features/webhooks/event-registry.d.ts.map +1 -1
  30. package/dist/features/webhooks/journal.d.ts +23 -0
  31. package/dist/features/webhooks/journal.d.ts.map +1 -1
  32. package/dist/features/webhooks/queue.d.ts +18 -0
  33. package/dist/features/webhooks/queue.d.ts.map +1 -1
  34. package/dist/features/webhooks/types.d.ts +15 -2
  35. package/dist/features/webhooks/types.d.ts.map +1 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +426 -123
  38. package/dist/server.d.ts +17 -0
  39. package/dist/server.d.ts.map +1 -1
  40. package/dist/version.d.ts +1 -1
  41. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2203,20 +2203,64 @@ JSONPath.prototype.safeVm = {
2203
2203
  JSONPath.prototype.vm = vm;
2204
2204
 
2205
2205
  // src/core/matching/discriminators.ts
2206
- 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) {
2207
2251
  if (pred.query) {
2208
- for (const [field, expected] of Object.entries(pred.query)) {
2252
+ for (const [field, expected] of pred.query) {
2209
2253
  const got = req.query.get(field);
2210
- if (!stringMatchOk(expected, got)) {
2211
- return { kind: "query", field, expected: describe(expected), got };
2254
+ if (!compiledMatchOk(expected, got)) {
2255
+ return { kind: "query", field, expected: describeCompiled(expected), got };
2212
2256
  }
2213
2257
  }
2214
2258
  }
2215
2259
  if (pred.headers) {
2216
- for (const [field, expected] of Object.entries(pred.headers)) {
2260
+ for (const [field, expected] of pred.headers) {
2217
2261
  const got = req.headers.get(field.toLowerCase());
2218
- if (!stringMatchOk(expected, got)) {
2219
- return { kind: "headers", field, expected: describe(expected), got };
2262
+ if (!compiledMatchOk(expected, got)) {
2263
+ return { kind: "headers", field, expected: describeCompiled(expected), got };
2220
2264
  }
2221
2265
  }
2222
2266
  }
@@ -2241,34 +2285,6 @@ function evaluateDiscriminators(pred, req) {
2241
2285
  }
2242
2286
  return null;
2243
2287
  }
2244
- function stringMatchOk(spec, got) {
2245
- if (typeof spec === "string")
2246
- return got === spec;
2247
- if ("equals" in spec)
2248
- return got === spec.equals;
2249
- if (got === undefined)
2250
- return false;
2251
- if ("regex" in spec)
2252
- return new RegExp(spec.regex).test(got);
2253
- if ("startsWith" in spec)
2254
- return got.startsWith(spec.startsWith);
2255
- if ("contains" in spec)
2256
- return got.includes(spec.contains);
2257
- return false;
2258
- }
2259
- function describe(spec) {
2260
- if (typeof spec === "string")
2261
- return `=${spec}`;
2262
- if ("equals" in spec)
2263
- return `=${spec.equals}`;
2264
- if ("regex" in spec)
2265
- return `~/${spec.regex}/`;
2266
- if ("startsWith" in spec)
2267
- return `^${spec.startsWith}`;
2268
- if ("contains" in spec)
2269
- return `*${spec.contains}*`;
2270
- return "?";
2271
- }
2272
2288
  function deepEquals(a, b) {
2273
2289
  if (a === b)
2274
2290
  return true;
@@ -2380,7 +2396,7 @@ function buildMatchIndex(entries) {
2380
2396
  const byMethod = new Map;
2381
2397
  const wildcardMethodRoot = createNode();
2382
2398
  entries.forEach((e, i) => {
2383
- const indexed = { entry: e, order: i };
2399
+ const indexed = { entry: e, order: i, compiled: compilePredicate(e.match) };
2384
2400
  if (e.match.method === "*") {
2385
2401
  insertPattern(wildcardMethodRoot, e.match.path, indexed);
2386
2402
  return;
@@ -2414,7 +2430,7 @@ function buildMatchIndex(entries) {
2414
2430
  match(method, path, req) {
2415
2431
  const hits = orderCandidates(candidates(method, path));
2416
2432
  for (const hit of hits) {
2417
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2433
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2418
2434
  if (!failure) {
2419
2435
  return { entry: hit.value.entry, params: hit.params };
2420
2436
  }
@@ -2427,7 +2443,7 @@ function buildMatchIndex(entries) {
2427
2443
  for (const hit of hits) {
2428
2444
  if (out.length >= limit)
2429
2445
  break;
2430
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2446
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2431
2447
  if (failure)
2432
2448
  out.push({ entry: hit.value.entry, params: hit.params, failure });
2433
2449
  }
@@ -2437,7 +2453,7 @@ function buildMatchIndex(entries) {
2437
2453
  }
2438
2454
 
2439
2455
  // src/core/scenarios/evaluator.ts
2440
- function compileMatcher(spec) {
2456
+ function compileMatcher2(spec) {
2441
2457
  if (typeof spec === "string")
2442
2458
  return { kind: "exact", value: spec };
2443
2459
  if ("equals" in spec)
@@ -2448,15 +2464,15 @@ function compileMatcher(spec) {
2448
2464
  return { kind: "startsWith", value: spec.startsWith };
2449
2465
  return { kind: "contains", value: spec.contains };
2450
2466
  }
2451
- function compileDim(record) {
2452
- 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)]));
2453
2469
  }
2454
- function compilePredicate(pred) {
2470
+ function compilePredicate2(pred) {
2455
2471
  return {
2456
- ...pred.params && { params: compileDim(pred.params) },
2457
- ...pred.query && { query: compileDim(pred.query) },
2458
- ...pred.headers && { headers: compileDim(pred.headers) },
2459
- ...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) }
2460
2476
  };
2461
2477
  }
2462
2478
  function compileResponse(resp) {
@@ -2485,7 +2501,7 @@ function compileResponse(resp) {
2485
2501
  function compileScenarioRules(rules) {
2486
2502
  return rules.map((rule) => ({
2487
2503
  id: rule.id,
2488
- predicate: compilePredicate(rule.when),
2504
+ predicate: compilePredicate2(rule.when),
2489
2505
  response: compileResponse(rule.response)
2490
2506
  }));
2491
2507
  }
@@ -6596,13 +6612,6 @@ function timestampUnitFor(scheme) {
6596
6612
 
6597
6613
  // src/core/config/schema.ts
6598
6614
  var MatchMethod = exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "*"]);
6599
- var StringMatch = exports_external.union([
6600
- exports_external.string(),
6601
- exports_external.object({ equals: exports_external.string() }).strict(),
6602
- exports_external.object({ regex: exports_external.string() }).strict(),
6603
- exports_external.object({ startsWith: exports_external.string() }).strict(),
6604
- exports_external.object({ contains: exports_external.string() }).strict()
6605
- ]);
6606
6615
  function isUnsafeRegex(pattern) {
6607
6616
  return /\([^)]*[*+{][^)]*\)[*+{]/.test(pattern) || /\([^)]*\|[^)]*\)[*+{]/.test(pattern);
6608
6617
  }
@@ -6610,7 +6619,7 @@ var StringMatchWithRegexGuard = exports_external.union([
6610
6619
  exports_external.string(),
6611
6620
  exports_external.object({ equals: exports_external.string() }).strict(),
6612
6621
  exports_external.object({ regex: exports_external.string() }).strict().refine((v) => !isUnsafeRegex(v.regex), (v) => ({
6613
- 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`
6614
6623
  })),
6615
6624
  exports_external.object({ startsWith: exports_external.string() }).strict(),
6616
6625
  exports_external.object({ contains: exports_external.string() }).strict()
@@ -6623,8 +6632,8 @@ var BodyMatch = exports_external.object({
6623
6632
  var MatchPredicate = exports_external.object({
6624
6633
  method: MatchMethod.default("*"),
6625
6634
  path: exports_external.string().min(1),
6626
- query: exports_external.record(StringMatch).optional(),
6627
- headers: exports_external.record(StringMatch).optional(),
6635
+ query: exports_external.record(StringMatchWithRegexGuard).optional(),
6636
+ headers: exports_external.record(StringMatchWithRegexGuard).optional(),
6628
6637
  body: BodyMatch.optional(),
6629
6638
  priority: exports_external.number().int().default(0)
6630
6639
  }).strict();
@@ -6834,7 +6843,7 @@ var MocksFile = exports_external.object({
6834
6843
  var TenantLimits = exports_external.object({
6835
6844
  maxBodyBytes: exports_external.number().int().positive().default(1048576),
6836
6845
  maxResponseBytes: exports_external.number().int().positive().default(1048576),
6837
- requestsPerSecond: exports_external.number().int().positive().default(1000),
6846
+ requestsPerSecond: exports_external.number().int().positive().default(1e4),
6838
6847
  journalSize: exports_external.number().int().positive().default(1000)
6839
6848
  }).strict();
6840
6849
  var TenantConfig = exports_external.object({
@@ -8778,6 +8787,77 @@ function installProcessHandlers(opts) {
8778
8787
  process.off("uncaughtException", excHandler);
8779
8788
  };
8780
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
+
8781
8861
  // src/core/journal/ring-buffer.ts
8782
8862
  class RingBuffer {
8783
8863
  capacity;
@@ -11368,7 +11448,11 @@ var PRIVATE_IPV4_RANGES = [
11368
11448
  [127, 0, 0, 8],
11369
11449
  [169, 254, 0, 16],
11370
11450
  [100, 64, 0, 10],
11371
- [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]
11372
11456
  ];
11373
11457
  function validateUpstreamUrl(raw2, opts = {}) {
11374
11458
  const allowedSchemes = opts.allowedSchemes ?? ["https"];
@@ -11431,12 +11515,49 @@ async function validateUpstreamUrlResolved(raw2, opts = {}) {
11431
11515
  });
11432
11516
  return parsed;
11433
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
+ }
11434
11555
  function isPrivateHost(hostname) {
11435
11556
  const stripped = hostname.replace(/^\[/, "").replace(/\]$/, "");
11436
11557
  const lowered = stripped.toLowerCase();
11437
11558
  if (lowered === "localhost" || lowered === "ip6-localhost" || lowered === "ip6-loopback")
11438
11559
  return true;
11439
- if (lowered === "::1" || lowered.startsWith("fe80:") || lowered.startsWith("fc") || lowered.startsWith("fd")) {
11560
+ if (isIpLiteral(stripped) && isPrivateIpv6(lowered)) {
11440
11561
  return true;
11441
11562
  }
11442
11563
  const ipv4MappedDotted = lowered.match(/^::ffff:([0-9.]+)$/);
@@ -11457,6 +11578,75 @@ function isPrivateHost(hostname) {
11457
11578
  }
11458
11579
  return false;
11459
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
+ }
11460
11650
  function isPrivateIpv4(ip) {
11461
11651
  const parts = ip.split(".").map((p3) => Number.parseInt(p3, 10));
11462
11652
  if (parts.length !== 4 || parts.some((p3) => Number.isNaN(p3) || p3 < 0 || p3 > 255))
@@ -11468,16 +11658,13 @@ function isPrivateIpv4(ip) {
11468
11658
  }
11469
11659
  return false;
11470
11660
  }
11471
- function matchesIpv4(a2, _b, _c, _d, ra2, _rb, _rc, mask) {
11472
- if (mask === 8)
11473
- return a2 === ra2;
11474
- if (mask === 16)
11475
- return a2 === ra2 && _b === _rb;
11476
- if (mask === 12)
11477
- return a2 === ra2 && (_b & 240) === (_rb & 240);
11478
- if (mask === 10)
11479
- return a2 === ra2 && (_b & 192) === (_rb & 192);
11480
- 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;
11481
11668
  }
11482
11669
 
11483
11670
  // src/features/pass-through.ts
@@ -11486,12 +11673,13 @@ async function renderPassThrough(entry, ctx, opts) {
11486
11673
  throw new Error(`renderPassThrough called for non-passthrough entry '${entry.id}'`);
11487
11674
  }
11488
11675
  const spec = entry.response;
11676
+ const validationOpts = {
11677
+ allowedSchemes: ["https", "http"],
11678
+ allowPrivateUpstreams: opts.allowPrivateUpstreams
11679
+ };
11489
11680
  let upstreamUrl;
11490
11681
  try {
11491
- upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, {
11492
- allowedSchemes: ["https", "http"],
11493
- allowPrivateUpstreams: opts.allowPrivateUpstreams
11494
- });
11682
+ upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, validationOpts);
11495
11683
  } catch (err) {
11496
11684
  opts.logger.error({
11497
11685
  event: "passthrough_url_rejected",
@@ -11518,14 +11706,16 @@ async function renderPassThrough(entry, ctx, opts) {
11518
11706
  const controller = new AbortController;
11519
11707
  const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
11520
11708
  timer.unref?.();
11709
+ const bodyCap = ctx.req.method === "GET" || ctx.req.method === "HEAD" ? null : capRequestBodyStream(ctx, opts.maxBodyBytes);
11521
11710
  const started = performance.now();
11522
11711
  try {
11523
- const upstreamRes = await fetch(targetUrl, {
11712
+ const requestBody = bodyCap ? await ctx.req.raw.arrayBuffer() : null;
11713
+ const { response: upstreamRes } = await fetchWithRedirectGuard(targetUrl, {
11524
11714
  method: ctx.req.method,
11525
11715
  headers,
11526
- body: ctx.req.method === "GET" || ctx.req.method === "HEAD" ? undefined : await ctx.req.raw.arrayBuffer(),
11716
+ body: requestBody,
11527
11717
  signal: controller.signal
11528
- });
11718
+ }, validationOpts);
11529
11719
  clearTimeout(timer);
11530
11720
  return new Response(upstreamRes.body, {
11531
11721
  status: upstreamRes.status,
@@ -11533,7 +11723,23 @@ async function renderPassThrough(entry, ctx, opts) {
11533
11723
  });
11534
11724
  } catch (err) {
11535
11725
  clearTimeout(timer);
11726
+ if (bodyCap?.tooLarge()) {
11727
+ return bodyTooLargeResponse(opts.maxBodyBytes);
11728
+ }
11536
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
+ }
11537
11743
  const aborted = err instanceof DOMException && err.name === "AbortError";
11538
11744
  opts.logger.error({
11539
11745
  event: "passthrough_upstream_error",
@@ -12019,12 +12225,39 @@ class BoundedRetryQueue {
12019
12225
  #cap;
12020
12226
  #onDropped;
12021
12227
  #onSizeChange;
12228
+ #timers = new Map;
12229
+ #stopped = false;
12022
12230
  constructor(opts = {}) {
12023
12231
  this.#pq = new PQueue({ concurrency: opts.concurrency ?? DEFAULT_CONCURRENCY });
12024
12232
  this.#cap = opts.cap ?? DEFAULT_CAP;
12025
12233
  this.#onDropped = opts.onDropped;
12026
12234
  this.#onSizeChange = opts.onSizeChange;
12027
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
+ }
12028
12261
  #fireSizeChange() {
12029
12262
  if (!this.#onSizeChange)
12030
12263
  return;
@@ -12043,7 +12276,14 @@ class BoundedRetryQueue {
12043
12276
  inflight() {
12044
12277
  return this.#pq.pending;
12045
12278
  }
12279
+ liveTimerCount() {
12280
+ return this.#timers.size;
12281
+ }
12046
12282
  enqueue(req) {
12283
+ if (this.#stopped) {
12284
+ this.#dropDelivery(req);
12285
+ return;
12286
+ }
12047
12287
  while (this.size() >= this.#cap) {
12048
12288
  const oldest = this.#waiting.shift();
12049
12289
  if (oldest) {
@@ -12076,7 +12316,17 @@ class BoundedRetryQueue {
12076
12316
  if (attempt > 1) {
12077
12317
  const baseMs = req.retry.backoff[attempt - 2] ?? 0;
12078
12318
  const delayMs = applyJitter(baseMs, req.retry.jitterRatio);
12079
- 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
+ }
12080
12330
  }
12081
12331
  const gate = req.circuitGate();
12082
12332
  if (gate === "open") {
@@ -12118,7 +12368,7 @@ class BoundedRetryQueue {
12118
12368
  lastError = errorToString(err);
12119
12369
  req.onAttempt({
12120
12370
  attempt,
12121
- outcome: attempt === req.retry.attempts ? "failed" : "success",
12371
+ outcome: attempt === req.retry.attempts ? "failed" : "retrying",
12122
12372
  durationUs: 0,
12123
12373
  error: lastError
12124
12374
  });
@@ -12156,11 +12406,6 @@ function applyJitter(baseMs, ratio) {
12156
12406
  const delta = baseMs * ratio;
12157
12407
  return Math.max(0, Math.round(baseMs - delta + Math.random() * 2 * delta));
12158
12408
  }
12159
- function sleep(ms) {
12160
- if (ms <= 0)
12161
- return Promise.resolve();
12162
- return new Promise((resolve4) => setTimeout(resolve4, ms));
12163
- }
12164
12409
  function errorToString(err) {
12165
12410
  if (err instanceof Error)
12166
12411
  return `${err.name}: ${err.message}`;
@@ -12280,6 +12525,13 @@ class DeliveryEventRegistry {
12280
12525
  this.#completed.delete(id);
12281
12526
  }
12282
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
+ }
12283
12535
  pendingCount() {
12284
12536
  return this.#pending.size;
12285
12537
  }
@@ -12289,6 +12541,25 @@ class DeliveryEventRegistry {
12289
12541
  }
12290
12542
  // src/features/webhooks/journal.ts
12291
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
+
12292
12563
  class WebhookJournalRegistry {
12293
12564
  #buffers = new Map;
12294
12565
  #capacityFor;
@@ -12298,11 +12569,12 @@ class WebhookJournalRegistry {
12298
12569
  this.#journalFile = opts.journalFile;
12299
12570
  }
12300
12571
  record(entry) {
12301
- const buf = this.#bufferFor(entry.tenant);
12302
- buf.push(entry);
12572
+ const redacted = redactEntry(entry);
12573
+ const buf = this.#bufferFor(redacted.tenant);
12574
+ buf.push(redacted);
12303
12575
  if (this.#journalFile) {
12304
12576
  try {
12305
- appendFileSync(this.#journalFile, `${JSON.stringify(entry)}
12577
+ appendFileSync(this.#journalFile, `${JSON.stringify(redacted)}
12306
12578
  `);
12307
12579
  } catch (err) {
12308
12580
  console.warn(`[mockstar] webhook journal file write failed: ${err.message ?? err}`);
@@ -12426,14 +12698,13 @@ function dispatchWebhooks(deps, input) {
12426
12698
  }
12427
12699
  async function performAttempt(spec, input, _deps) {
12428
12700
  const attemptStart = performance.now();
12429
- let urlString;
12430
12701
  const headerUrl = _deps.allowWebhookUrlHeader && spec.acceptHeaderOverride ? input.requestHeaders.get("x-mockstar-webhook-url") : undefined;
12431
- urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12432
- const allowedSchemes = spec.allowHttp ? ["http", "https"] : ["https"];
12433
- await validateUpstreamUrlResolved(urlString, {
12434
- allowedSchemes,
12702
+ const urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12703
+ const validationOpts = {
12704
+ allowedSchemes: spec.allowHttp ? ["http", "https"] : ["https"],
12435
12705
  allowPrivateUpstreams: spec.allowPrivateNetworks
12436
- });
12706
+ };
12707
+ const validatedUrl = await validateUpstreamUrlResolved(urlString, validationOpts);
12437
12708
  const renderedHeaders = new Headers;
12438
12709
  for (const [key, tmpl] of spec.headers) {
12439
12710
  renderedHeaders.set(key, tmpl.render(input.templateContext));
@@ -12465,14 +12736,20 @@ async function performAttempt(spec, input, _deps) {
12465
12736
  }
12466
12737
  const signal = AbortSignal.timeout(spec.timeoutMs);
12467
12738
  let response;
12739
+ let finalUrl;
12468
12740
  try {
12469
- response = await fetch(urlString, {
12741
+ const result = await fetchWithRedirectGuard(validatedUrl, {
12470
12742
  method: spec.method,
12471
12743
  headers: renderedHeaders,
12472
- body: spec.method === "GET" || spec.method === "DELETE" ? undefined : rawBody,
12744
+ body: spec.method === "GET" || spec.method === "DELETE" ? null : rawBody,
12473
12745
  signal
12474
- });
12746
+ }, validationOpts);
12747
+ response = result.response;
12748
+ finalUrl = result.finalUrl;
12475
12749
  } catch (err) {
12750
+ if (err instanceof UrlValidationError) {
12751
+ throw new Error(`webhook delivery redirect rejected: ${err.message}`);
12752
+ }
12476
12753
  throw new Error(`webhook delivery network error: ${err.message ?? err}`);
12477
12754
  }
12478
12755
  if (!isSuccessStatus(response.status, spec.expectResponse)) {
@@ -12487,7 +12764,7 @@ async function performAttempt(spec, input, _deps) {
12487
12764
  return {
12488
12765
  httpStatus: response.status,
12489
12766
  durationUs: Math.round((performance.now() - attemptStart) * 1000),
12490
- resolvedUrl: urlString
12767
+ resolvedUrl: finalUrl.href
12491
12768
  };
12492
12769
  }
12493
12770
  function isSuccessStatus(status, expect) {
@@ -12538,6 +12815,8 @@ function makeDeliveryId() {
12538
12815
  return crypto.randomUUID();
12539
12816
  }
12540
12817
  // src/server.ts
12818
+ var UNKNOWN_TENANT_BUCKET = ":unknown:";
12819
+ var DEFAULT_REQUESTS_PER_SECOND = 1e4;
12541
12820
  function createServer(opts) {
12542
12821
  const logger = opts.logger ?? createLogger({ deterministic: opts.deterministic });
12543
12822
  const metrics = new Metrics;
@@ -12545,6 +12824,7 @@ function createServer(opts) {
12545
12824
  const snap = opts.holder.get().tenants.get(tenant);
12546
12825
  return snap?.limits.journalSize ?? 1000;
12547
12826
  });
12827
+ const rateLimiter = new TenantRateLimiter({ now: opts.rateLimiterNow });
12548
12828
  const webhookJournal = new WebhookJournalRegistry((tenant) => {
12549
12829
  const snap = opts.holder.get().tenants.get(tenant);
12550
12830
  return snap?.limits.journalSize ?? 1000;
@@ -12655,6 +12935,7 @@ function createServer(opts) {
12655
12935
  clock,
12656
12936
  journal,
12657
12937
  metrics,
12938
+ rateLimiter,
12658
12939
  handlerTimeoutMs,
12659
12940
  genRequestId,
12660
12941
  webhookJournal,
@@ -12663,15 +12944,22 @@ function createServer(opts) {
12663
12944
  circuitFor,
12664
12945
  allowWebhookUrlHeader
12665
12946
  }));
12947
+ const stopWebhooks = () => {
12948
+ for (const q3 of webhookQueues.values())
12949
+ q3.stop();
12950
+ webhookEvents.stop();
12951
+ };
12666
12952
  return {
12667
12953
  hono: app,
12668
12954
  journal,
12669
12955
  metrics,
12956
+ rateLimiter,
12670
12957
  ready,
12671
12958
  uninstallCrashHandlers,
12672
12959
  webhookJournal,
12673
12960
  webhookEvents,
12674
- replayWebhook
12961
+ replayWebhook,
12962
+ stopWebhooks
12675
12963
  };
12676
12964
  }
12677
12965
  async function dispatch(ctx, deps) {
@@ -12683,28 +12971,35 @@ async function dispatch(ctx, deps) {
12683
12971
  const startedUs = performance.now() * 1000;
12684
12972
  const matchPath = effectivePath(ctx);
12685
12973
  const method = ctx.req.method;
12974
+ const observedTenant = tenantSnap ? tenant : UNKNOWN_TENANT_BUCKET;
12686
12975
  let response;
12687
12976
  let matchedMockId = null;
12688
12977
  let scenarioId;
12689
12978
  let scenarioMissReason;
12690
12979
  let webhookTrigger;
12691
12980
  try {
12692
- 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) {
12693
12986
  response = notFoundUnknownTenant(tenant, method, matchPath);
12694
12987
  } else {
12695
12988
  const contentLength = Number.parseInt(ctx.req.header("content-length") ?? "0", 10);
12696
12989
  if (contentLength > tenantSnap.limits.maxBodyBytes) {
12697
- response = new Response(JSON.stringify({ error: "body_too_large", limit: tenantSnap.limits.maxBodyBytes }), {
12698
- status: 413,
12699
- headers: { "content-type": "application/json" }
12700
- });
12990
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
12701
12991
  } else {
12702
- const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps);
12703
- response = result.response;
12704
- matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
12705
- scenarioId = result.scenarioId;
12706
- scenarioMissReason = result.scenarioMissReason;
12707
- 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
+ }
12708
13003
  }
12709
13004
  }
12710
13005
  } catch (err) {
@@ -12725,7 +13020,7 @@ async function dispatch(ctx, deps) {
12725
13020
  const durationUs = Math.round(performance.now() * 1000 - startedUs);
12726
13021
  const entry = {
12727
13022
  timestamp: Date.now(),
12728
- tenant,
13023
+ tenant: observedTenant,
12729
13024
  requestId,
12730
13025
  method,
12731
13026
  path: matchPath,
@@ -12737,15 +13032,15 @@ async function dispatch(ctx, deps) {
12737
13032
  };
12738
13033
  deps.journal.record(entry);
12739
13034
  deps.metrics.incCounter("mockstar_requests_total", {
12740
- tenant,
13035
+ tenant: observedTenant,
12741
13036
  method,
12742
13037
  status: String(response.status),
12743
13038
  matched: matchedMockId ? "1" : "0"
12744
13039
  });
12745
- deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant }, durationUs);
13040
+ deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant: observedTenant }, durationUs);
12746
13041
  deps.logger.info({
12747
13042
  event: "request",
12748
- tenant,
13043
+ tenant: observedTenant,
12749
13044
  method,
12750
13045
  path: matchPath,
12751
13046
  status: response.status,
@@ -12794,9 +13089,8 @@ async function dispatch(ctx, deps) {
12794
13089
  });
12795
13090
  return response;
12796
13091
  }
12797
- async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps) {
13092
+ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, body) {
12798
13093
  const url = new URL(ctx.req.url);
12799
- const body = await safeParseBody(ctx);
12800
13094
  const req = {
12801
13095
  query: new Map(Array.from(url.searchParams)),
12802
13096
  headers: new Map(Array.from(ctx.req.raw.headers).map(([k2, v3]) => [k2.toLowerCase(), v3])),
@@ -12908,7 +13202,8 @@ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap,
12908
13202
  case "passthrough":
12909
13203
  response = await renderPassThrough(hit.entry, ctx, {
12910
13204
  allowPrivateUpstreams: tenantSnap.allowPrivateUpstreams,
12911
- logger: deps.logger
13205
+ logger: deps.logger,
13206
+ maxBodyBytes: tenantSnap.limits.maxBodyBytes
12912
13207
  });
12913
13208
  break;
12914
13209
  }
@@ -12926,20 +13221,27 @@ function notFoundUnknownTenant(tenant, method, path) {
12926
13221
  headers: { "content-type": "application/json" }
12927
13222
  });
12928
13223
  }
12929
- async function safeParseBody(ctx) {
13224
+ async function safeParseBody(ctx, maxBodyBytes) {
12930
13225
  const method = ctx.req.method;
12931
13226
  if (method === "GET" || method === "HEAD")
12932
- return null;
13227
+ return { ok: true, body: null };
12933
13228
  const contentType = ctx.req.header("content-type") ?? "";
12934
13229
  if (!contentType.includes("json"))
12935
- return null;
13230
+ return { ok: true, body: null };
13231
+ const { tooLarge } = capRequestBodyStream(ctx, maxBodyBytes);
12936
13232
  try {
12937
13233
  const text = await ctx.req.text();
12938
13234
  if (text.length === 0)
12939
- return null;
12940
- return JSON.parse(text);
12941
- } catch {
12942
- 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;
12943
13245
  }
12944
13246
  }
12945
13247
  function createRequestIdGenerator(deterministic) {
@@ -12991,6 +13293,7 @@ async function launch(opts) {
12991
13293
  holder,
12992
13294
  async stop() {
12993
13295
  watcher?.stop();
13296
+ server.stopWebhooks();
12994
13297
  server.uninstallCrashHandlers();
12995
13298
  }
12996
13299
  };