@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/cli.js CHANGED
@@ -375,35 +375,57 @@ var exports_port_bind = {};
375
375
  __export(exports_port_bind, {
376
376
  runPrivileged: () => runPrivileged,
377
377
  portBindMutation: () => portBindMutation,
378
- isPlatformSupported: () => isPlatformSupported
378
+ isPlatformSupported: () => isPlatformSupported,
379
+ ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG: () => ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG,
380
+ ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV: () => ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV
379
381
  });
380
382
  import { spawn as spawn3 } from "child_process";
381
383
  import { writeFile as writeFile5 } from "fs/promises";
382
384
  import { platform as platform2 } from "os";
385
+ import { basename as basename3 } from "path";
386
+ function isInterpreterBinary(binaryPath) {
387
+ return INTERPRETER_BASENAMES.has(basename3(binaryPath).toLowerCase());
388
+ }
389
+ function assertPackagedBinary(binaryPath, allowInterpreter) {
390
+ if (!isInterpreterBinary(binaryPath))
391
+ return;
392
+ const base = basename3(binaryPath).toLowerCase();
393
+ if (!allowInterpreter) {
394
+ throw new ProxyError(`Refusing to grant the network-bind capability to '${binaryPath}': it resolves to the ` + `${base} interpreter, not a packaged mockstar binary.`, "binary_path_is_interpreter", `Build and use a packaged binary instead of running from source: \`bun run build && bun run build:binary\`, then run \`./dist/mockstar-<platform>-<arch> proxy install\` (or use a downloaded release binary / the Docker image). Granting this capability to the interpreter itself would let every program it runs bind privileged ports. If this is a single-purpose, ephemeral host (CI runner, throwaway VM/container) where that risk doesn't apply, opt in explicitly with ${ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG} or ${ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV}=1 \u2014 do not use either on a developer's own machine.`);
395
+ }
396
+ process.stderr.write(`
397
+ WARNING: granting cap_net_bind_service to '${binaryPath}' \u2014 the ${base} interpreter, not a packaged mockstar binary (${ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG} / ${ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV}=1 was set). This grants EVERY program run by this interpreter on this host the ability to bind privileged ports, until 'mockstar proxy uninstall' or 'sudo setcap -r ${binaryPath}' reverses it. Only acceptable on a single-purpose, ephemeral host (CI runner, throwaway VM/container).
398
+
399
+ `);
400
+ }
383
401
  function portBindMutation(params) {
402
+ const allowInterpreter = params.allowInterpreter ?? false;
403
+ assertPackagedBinary(params.binaryPath, allowInterpreter);
404
+ const interpreterGrant = allowInterpreter && isInterpreterBinary(params.binaryPath);
384
405
  const os = platform2();
385
406
  if (os === "linux") {
386
- return linuxSetcapMutation(params.binaryPath);
407
+ return linuxSetcapMutation(params.binaryPath, interpreterGrant);
387
408
  }
388
409
  if (os === "darwin") {
389
410
  return macosLaunchdMutation({
390
411
  plistPath: params.plistPath ?? `${process.env.HOME}/Library/LaunchAgents/com.mockstar.proxy.plist`,
391
412
  label: params.launchdLabel ?? "com.mockstar.proxy",
392
- binaryPath: params.binaryPath
413
+ binaryPath: params.binaryPath,
414
+ interpreterGrant
393
415
  });
394
416
  }
395
417
  throw new ProxyError(`Unsupported platform for port 443 bind: ${os}. macOS and Linux only in v1 (B2).`, "unsupported_platform");
396
418
  }
397
- function runPrivileged(argv) {
398
- return runCmd3("sudo", argv);
419
+ function runPrivileged(argv, opts = {}) {
420
+ return runCmd3("sudo", argv, opts);
399
421
  }
400
422
  function isPlatformSupported() {
401
423
  const os = platform2();
402
424
  return os === "linux" || os === "darwin";
403
425
  }
404
- function linuxSetcapMutation(binaryPath) {
426
+ function linuxSetcapMutation(binaryPath, interpreterGrant) {
405
427
  return {
406
- action: `setcap cap_net_bind_service=+ep ${binaryPath}`,
428
+ action: `setcap cap_net_bind_service=+ep ${binaryPath}${interpreterGrant ? " [INTERPRETER GRANT \u2014 #39 escape hatch used, see install output]" : ""}`,
407
429
  reverseCommand: { kind: "setcap_drop", path: binaryPath },
408
430
  async apply() {
409
431
  const result = await runPrivileged(["setcap", "cap_net_bind_service=+ep", binaryPath]);
@@ -416,7 +438,7 @@ function linuxSetcapMutation(binaryPath) {
416
438
  function macosLaunchdMutation(params) {
417
439
  const plistContents = macosPlist(params.label, params.binaryPath);
418
440
  return {
419
- action: `install launchd plist at ${params.plistPath}`,
441
+ action: `install launchd plist at ${params.plistPath}${params.interpreterGrant ? ` [INTERPRETER GRANT for ${params.binaryPath} \u2014 #39 escape hatch used, see install output]` : ""}`,
420
442
  reverseCommand: { kind: "launchctl_unload_and_remove", plistPath: params.plistPath },
421
443
  async apply() {
422
444
  await writeFile5(params.plistPath, plistContents, { encoding: "utf8", mode: 420 });
@@ -462,23 +484,30 @@ function macosPlist(label, binaryPath) {
462
484
  </plist>
463
485
  `;
464
486
  }
465
- function runCmd3(cmd, argv) {
487
+ function runCmd3(cmd, argv, opts = {}) {
466
488
  return new Promise((resolve8, reject) => {
467
- const child = spawn3(cmd, argv, { stdio: ["inherit", "pipe", "pipe"] });
489
+ const child = spawn3(cmd, argv, {
490
+ stdio: [opts.stdin === undefined ? "inherit" : "pipe", "pipe", "pipe"]
491
+ });
492
+ if (opts.stdin !== undefined) {
493
+ child.stdin?.end(opts.stdin, "utf8");
494
+ }
468
495
  let stdout = "";
469
496
  let stderr = "";
470
- child.stdout.on("data", (c2) => {
497
+ child.stdout?.on("data", (c2) => {
471
498
  stdout += c2.toString("utf8");
472
499
  });
473
- child.stderr.on("data", (c2) => {
500
+ child.stderr?.on("data", (c2) => {
474
501
  stderr += c2.toString("utf8");
475
502
  });
476
503
  child.on("error", reject);
477
504
  child.on("close", (code) => resolve8({ exitCode: code ?? 1, stdout, stderr }));
478
505
  });
479
506
  }
507
+ var INTERPRETER_BASENAMES, ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG = "--allow-interpreter-capability-grant", ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV = "MOCKSTAR_ALLOW_INTERPRETER_CAPABILITY_GRANT";
480
508
  var init_port_bind = __esm(() => {
481
509
  init_types();
510
+ INTERPRETER_BASENAMES = new Set(["bun", "bun-debug", "node", "deno"]);
482
511
  });
483
512
 
484
513
  // src/features/proxy/dns.ts
@@ -487,13 +516,14 @@ __export(exports_dns, {
487
516
  stopAndRemoveDnsmasq: () => stopAndRemoveDnsmasq,
488
517
  revertHostsBlock: () => revertHostsBlock,
489
518
  join: () => join6,
519
+ buildDnsmasqMutations: () => buildDnsmasqMutations,
490
520
  buildDnsMutations: () => buildDnsMutations,
491
521
  HOSTS_PATH: () => HOSTS_PATH,
492
522
  HOSTS_BLOCK_MARKER: () => HOSTS_BLOCK_MARKER,
493
523
  HOSTS_BLOCK_END: () => HOSTS_BLOCK_END
494
524
  });
495
- import { appendFile, readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
496
- import { platform as platform3 } from "os";
525
+ import { appendFile, mkdtemp as mkdtemp2, readFile as readFile7, rm as rm2, writeFile as writeFile6 } from "fs/promises";
526
+ import { platform as platform3, tmpdir as tmpdir2 } from "os";
497
527
  import { join as join6 } from "path";
498
528
  async function buildDnsMutations(config) {
499
529
  if (config.dnsMode === "hosts-fallback") {
@@ -501,22 +531,61 @@ async function buildDnsMutations(config) {
501
531
  }
502
532
  return buildDnsmasqMutations(config.hosts);
503
533
  }
504
- async function revertHostsBlock(marker) {
534
+ async function revertHostsBlock(marker, opts = {}) {
535
+ const hostsPath = opts.hostsPath ?? HOSTS_PATH;
505
536
  let existing = "";
506
537
  try {
507
- existing = await readFile7(HOSTS_PATH, "utf8");
538
+ existing = await readFile7(hostsPath, "utf8");
508
539
  } catch {
509
540
  return;
510
541
  }
511
- const start = existing.indexOf(marker);
542
+ const markerStart = existing.indexOf(marker);
512
543
  const end = existing.indexOf(HOSTS_BLOCK_END);
513
- if (start === -1 || end === -1)
514
- return;
515
- const next = existing.slice(0, start) + existing.slice(end + HOSTS_BLOCK_END.length).replace(/^\n+/, "");
516
- await runPrivileged(["tee", HOSTS_PATH]).catch(() => {
544
+ if (markerStart === -1 || end === -1)
517
545
  return;
546
+ const blockStart = existing[markerStart - 1] === `
547
+ ` ? markerStart - 1 : markerStart;
548
+ let blockEnd = end + HOSTS_BLOCK_END.length;
549
+ if (existing[blockEnd] === `
550
+ `)
551
+ blockEnd += 1;
552
+ const next = existing.slice(0, blockStart) + existing.slice(blockEnd);
553
+ await privilegedWriteFile(hostsPath, next, {
554
+ runner: opts.runner,
555
+ errorCode: "hosts_revert_failed",
556
+ hint: `Manually remove the block between '${HOSTS_BLOCK_MARKER}' and '${HOSTS_BLOCK_END}' in ${hostsPath}.`
518
557
  });
519
558
  }
559
+ async function privilegedWriteFile(path, content, opts = {
560
+ errorCode: "privileged_write_failed"
561
+ }) {
562
+ const runner = opts.runner ?? runPrivileged;
563
+ const dir = await mkdtemp2(join6(tmpdir2(), "mockstar-proxy-"));
564
+ const tmpFile = join6(dir, "content");
565
+ try {
566
+ await writeFile6(tmpFile, content, "utf8");
567
+ const mvResult = await runner(["mv", tmpFile, path]);
568
+ if (mvResult.exitCode === 0) {
569
+ process.stderr.write(`mockstar-proxy: wrote ${path} via 'mv' (atomic rename).
570
+ `);
571
+ return;
572
+ }
573
+ const mvError = mvResult.stderr.trim() || mvResult.stdout.trim() || `mv exited with code ${mvResult.exitCode}`;
574
+ const teeResult = await runner(["tee", path], { stdin: content });
575
+ if (teeResult.exitCode === 0) {
576
+ const why = "target is likely a bind mount, e.g. inside a container";
577
+ process.stderr.write(`mockstar-proxy: 'mv' failed for ${path} (${mvError}); wrote via piped 'tee' instead (${why}).
578
+ `);
579
+ return;
580
+ }
581
+ const teeError = teeResult.stderr.trim() || teeResult.stdout.trim() || `tee exited with code ${teeResult.exitCode}`;
582
+ throw new ProxyError(`Failed to write ${path}: mv failed (${mvError}); piped tee fallback also failed (${teeError})`, opts.errorCode, opts.hint);
583
+ } finally {
584
+ await rm2(dir, { recursive: true, force: true }).catch(() => {
585
+ return;
586
+ });
587
+ }
588
+ }
520
589
  async function stopAndRemoveDnsmasq() {
521
590
  const os = platform3();
522
591
  if (os === "darwin") {
@@ -554,7 +623,7 @@ ${HOSTS_BLOCK_END}
554
623
  }
555
624
  ];
556
625
  }
557
- function buildDnsmasqMutations(hosts) {
626
+ function buildDnsmasqMutations(hosts, overrides = {}) {
558
627
  const os = platform3();
559
628
  if (os !== "darwin" && os !== "linux") {
560
629
  throw new ProxyError(`dnsmasq mode not supported on platform '${os}' in v1. Use hosts-fallback mode.`, "dnsmasq_platform_unsupported");
@@ -584,10 +653,12 @@ ${hosts.map((h2) => `address=/${h2.host}/127.0.0.1`).join(`
584
653
  const content = `nameserver 127.0.0.1
585
654
  port 53
586
655
  `;
587
- const result = await runPrivileged(["tee", resolverPath]);
588
- if (result.exitCode !== 0) {
589
- throw new ProxyError(`Failed to write ${resolverPath}`, "resolver_write_failed");
590
- }
656
+ await privilegedWriteFile(resolverPath, content, {
657
+ runner: overrides.runner,
658
+ errorCode: "resolver_write_failed",
659
+ hint: `Manually create ${resolverPath} with:
660
+ ${content}`
661
+ });
591
662
  }
592
663
  });
593
664
  }
@@ -2596,20 +2667,64 @@ JSONPath.prototype.safeVm = {
2596
2667
  JSONPath.prototype.vm = vm;
2597
2668
 
2598
2669
  // src/core/matching/discriminators.ts
2599
- function evaluateDiscriminators(pred, req) {
2670
+ function compileMatcher(spec) {
2671
+ if (typeof spec === "string")
2672
+ return { kind: "exact", value: spec };
2673
+ if ("equals" in spec)
2674
+ return { kind: "exact", value: spec.equals };
2675
+ if ("regex" in spec)
2676
+ return { kind: "regex", re: new RegExp(spec.regex) };
2677
+ if ("startsWith" in spec)
2678
+ return { kind: "startsWith", value: spec.startsWith };
2679
+ return { kind: "contains", value: spec.contains };
2680
+ }
2681
+ function compileDim(record) {
2682
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2683
+ }
2684
+ function compilePredicate(pred) {
2685
+ return {
2686
+ ...pred.query && { query: compileDim(pred.query) },
2687
+ ...pred.headers && { headers: compileDim(pred.headers) },
2688
+ ...pred.body && { body: pred.body }
2689
+ };
2690
+ }
2691
+ function compiledMatchOk(compiled, got) {
2692
+ if (compiled.kind === "exact")
2693
+ return got === compiled.value;
2694
+ if (got === undefined)
2695
+ return false;
2696
+ if (compiled.kind === "regex")
2697
+ return compiled.re.test(got);
2698
+ if (compiled.kind === "startsWith")
2699
+ return got.startsWith(compiled.value);
2700
+ return got.includes(compiled.value);
2701
+ }
2702
+ function describeCompiled(m) {
2703
+ switch (m.kind) {
2704
+ case "exact":
2705
+ return `=${m.value}`;
2706
+ case "regex":
2707
+ return `~/${m.re.source}/`;
2708
+ case "startsWith":
2709
+ return `^${m.value}`;
2710
+ case "contains":
2711
+ return `*${m.value}*`;
2712
+ }
2713
+ }
2714
+ function evaluateCompiledDiscriminators(pred, req) {
2600
2715
  if (pred.query) {
2601
- for (const [field, expected] of Object.entries(pred.query)) {
2716
+ for (const [field, expected] of pred.query) {
2602
2717
  const got = req.query.get(field);
2603
- if (!stringMatchOk(expected, got)) {
2604
- return { kind: "query", field, expected: describe(expected), got };
2718
+ if (!compiledMatchOk(expected, got)) {
2719
+ return { kind: "query", field, expected: describeCompiled(expected), got };
2605
2720
  }
2606
2721
  }
2607
2722
  }
2608
2723
  if (pred.headers) {
2609
- for (const [field, expected] of Object.entries(pred.headers)) {
2724
+ for (const [field, expected] of pred.headers) {
2610
2725
  const got = req.headers.get(field.toLowerCase());
2611
- if (!stringMatchOk(expected, got)) {
2612
- return { kind: "headers", field, expected: describe(expected), got };
2726
+ if (!compiledMatchOk(expected, got)) {
2727
+ return { kind: "headers", field, expected: describeCompiled(expected), got };
2613
2728
  }
2614
2729
  }
2615
2730
  }
@@ -2634,34 +2749,6 @@ function evaluateDiscriminators(pred, req) {
2634
2749
  }
2635
2750
  return null;
2636
2751
  }
2637
- function stringMatchOk(spec, got) {
2638
- if (typeof spec === "string")
2639
- return got === spec;
2640
- if ("equals" in spec)
2641
- return got === spec.equals;
2642
- if (got === undefined)
2643
- return false;
2644
- if ("regex" in spec)
2645
- return new RegExp(spec.regex).test(got);
2646
- if ("startsWith" in spec)
2647
- return got.startsWith(spec.startsWith);
2648
- if ("contains" in spec)
2649
- return got.includes(spec.contains);
2650
- return false;
2651
- }
2652
- function describe(spec) {
2653
- if (typeof spec === "string")
2654
- return `=${spec}`;
2655
- if ("equals" in spec)
2656
- return `=${spec.equals}`;
2657
- if ("regex" in spec)
2658
- return `~/${spec.regex}/`;
2659
- if ("startsWith" in spec)
2660
- return `^${spec.startsWith}`;
2661
- if ("contains" in spec)
2662
- return `*${spec.contains}*`;
2663
- return "?";
2664
- }
2665
2752
  function deepEquals(a, b) {
2666
2753
  if (a === b)
2667
2754
  return true;
@@ -2773,7 +2860,7 @@ function buildMatchIndex(entries) {
2773
2860
  const byMethod = new Map;
2774
2861
  const wildcardMethodRoot = createNode();
2775
2862
  entries.forEach((e, i) => {
2776
- const indexed = { entry: e, order: i };
2863
+ const indexed = { entry: e, order: i, compiled: compilePredicate(e.match) };
2777
2864
  if (e.match.method === "*") {
2778
2865
  insertPattern(wildcardMethodRoot, e.match.path, indexed);
2779
2866
  return;
@@ -2807,7 +2894,7 @@ function buildMatchIndex(entries) {
2807
2894
  match(method, path, req) {
2808
2895
  const hits = orderCandidates(candidates(method, path));
2809
2896
  for (const hit of hits) {
2810
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2897
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2811
2898
  if (!failure) {
2812
2899
  return { entry: hit.value.entry, params: hit.params };
2813
2900
  }
@@ -2820,7 +2907,7 @@ function buildMatchIndex(entries) {
2820
2907
  for (const hit of hits) {
2821
2908
  if (out.length >= limit)
2822
2909
  break;
2823
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2910
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2824
2911
  if (failure)
2825
2912
  out.push({ entry: hit.value.entry, params: hit.params, failure });
2826
2913
  }
@@ -2830,7 +2917,7 @@ function buildMatchIndex(entries) {
2830
2917
  }
2831
2918
 
2832
2919
  // src/core/scenarios/evaluator.ts
2833
- function compileMatcher(spec) {
2920
+ function compileMatcher2(spec) {
2834
2921
  if (typeof spec === "string")
2835
2922
  return { kind: "exact", value: spec };
2836
2923
  if ("equals" in spec)
@@ -2841,15 +2928,15 @@ function compileMatcher(spec) {
2841
2928
  return { kind: "startsWith", value: spec.startsWith };
2842
2929
  return { kind: "contains", value: spec.contains };
2843
2930
  }
2844
- function compileDim(record) {
2845
- return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2931
+ function compileDim2(record) {
2932
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher2(v)]));
2846
2933
  }
2847
- function compilePredicate(pred) {
2934
+ function compilePredicate2(pred) {
2848
2935
  return {
2849
- ...pred.params && { params: compileDim(pred.params) },
2850
- ...pred.query && { query: compileDim(pred.query) },
2851
- ...pred.headers && { headers: compileDim(pred.headers) },
2852
- ...pred.body && { body: compileDim(pred.body) }
2936
+ ...pred.params && { params: compileDim2(pred.params) },
2937
+ ...pred.query && { query: compileDim2(pred.query) },
2938
+ ...pred.headers && { headers: compileDim2(pred.headers) },
2939
+ ...pred.body && { body: compileDim2(pred.body) }
2853
2940
  };
2854
2941
  }
2855
2942
  function compileResponse(resp) {
@@ -2878,7 +2965,7 @@ function compileResponse(resp) {
2878
2965
  function compileScenarioRules(rules) {
2879
2966
  return rules.map((rule) => ({
2880
2967
  id: rule.id,
2881
- predicate: compilePredicate(rule.when),
2968
+ predicate: compilePredicate2(rule.when),
2882
2969
  response: compileResponse(rule.response)
2883
2970
  }));
2884
2971
  }
@@ -6989,13 +7076,6 @@ function timestampUnitFor(scheme) {
6989
7076
 
6990
7077
  // src/core/config/schema.ts
6991
7078
  var MatchMethod = exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "*"]);
6992
- var StringMatch = exports_external.union([
6993
- exports_external.string(),
6994
- exports_external.object({ equals: exports_external.string() }).strict(),
6995
- exports_external.object({ regex: exports_external.string() }).strict(),
6996
- exports_external.object({ startsWith: exports_external.string() }).strict(),
6997
- exports_external.object({ contains: exports_external.string() }).strict()
6998
- ]);
6999
7079
  function isUnsafeRegex(pattern) {
7000
7080
  return /\([^)]*[*+{][^)]*\)[*+{]/.test(pattern) || /\([^)]*\|[^)]*\)[*+{]/.test(pattern);
7001
7081
  }
@@ -7003,7 +7083,7 @@ var StringMatchWithRegexGuard = exports_external.union([
7003
7083
  exports_external.string(),
7004
7084
  exports_external.object({ equals: exports_external.string() }).strict(),
7005
7085
  exports_external.object({ regex: exports_external.string() }).strict().refine((v) => !isUnsafeRegex(v.regex), (v) => ({
7006
- message: `scenario regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
7086
+ message: `regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
7007
7087
  })),
7008
7088
  exports_external.object({ startsWith: exports_external.string() }).strict(),
7009
7089
  exports_external.object({ contains: exports_external.string() }).strict()
@@ -7016,8 +7096,8 @@ var BodyMatch = exports_external.object({
7016
7096
  var MatchPredicate = exports_external.object({
7017
7097
  method: MatchMethod.default("*"),
7018
7098
  path: exports_external.string().min(1),
7019
- query: exports_external.record(StringMatch).optional(),
7020
- headers: exports_external.record(StringMatch).optional(),
7099
+ query: exports_external.record(StringMatchWithRegexGuard).optional(),
7100
+ headers: exports_external.record(StringMatchWithRegexGuard).optional(),
7021
7101
  body: BodyMatch.optional(),
7022
7102
  priority: exports_external.number().int().default(0)
7023
7103
  }).strict();
@@ -7227,7 +7307,7 @@ var MocksFile = exports_external.object({
7227
7307
  var TenantLimits = exports_external.object({
7228
7308
  maxBodyBytes: exports_external.number().int().positive().default(1048576),
7229
7309
  maxResponseBytes: exports_external.number().int().positive().default(1048576),
7230
- requestsPerSecond: exports_external.number().int().positive().default(1000),
7310
+ requestsPerSecond: exports_external.number().int().positive().default(1e4),
7231
7311
  journalSize: exports_external.number().int().positive().default(1000)
7232
7312
  }).strict();
7233
7313
  var TenantConfig = exports_external.object({
@@ -9171,6 +9251,77 @@ function installProcessHandlers(opts) {
9171
9251
  process.off("uncaughtException", excHandler);
9172
9252
  };
9173
9253
  }
9254
+ // src/core/http/body-cap.ts
9255
+ function capRequestBodyStream(ctx, maxBodyBytes) {
9256
+ const original = ctx.req.raw;
9257
+ let tooLarge = false;
9258
+ if (original.body && !original.bodyUsed) {
9259
+ let total = 0;
9260
+ const limited = original.body.pipeThrough(new TransformStream({
9261
+ transform(chunk, controller) {
9262
+ total += chunk.byteLength;
9263
+ if (total > maxBodyBytes) {
9264
+ tooLarge = true;
9265
+ controller.error(new Error("body_too_large"));
9266
+ return;
9267
+ }
9268
+ controller.enqueue(chunk);
9269
+ }
9270
+ }));
9271
+ ctx.req.raw = new Request(original, { body: limited, duplex: "half" });
9272
+ }
9273
+ return { tooLarge: () => tooLarge };
9274
+ }
9275
+ function bodyTooLargeResponse(limit) {
9276
+ return new Response(JSON.stringify({ error: "body_too_large", limit }), {
9277
+ status: 413,
9278
+ headers: { "content-type": "application/json" }
9279
+ });
9280
+ }
9281
+
9282
+ // src/core/http/rate-limit.ts
9283
+ class TenantRateLimiter {
9284
+ buckets = new Map;
9285
+ now;
9286
+ constructor(opts = {}) {
9287
+ this.now = opts.now ?? (() => Date.now());
9288
+ }
9289
+ get bucketCount() {
9290
+ return this.buckets.size;
9291
+ }
9292
+ tryAcquire(tenant, limitPerSecond) {
9293
+ const nowMs = this.now();
9294
+ let bucket = this.buckets.get(tenant);
9295
+ if (!bucket) {
9296
+ bucket = { tokens: limitPerSecond, lastRefillMs: nowMs };
9297
+ this.buckets.set(tenant, bucket);
9298
+ } else {
9299
+ const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);
9300
+ if (elapsedMs > 0) {
9301
+ const refill = elapsedMs * limitPerSecond / 1000;
9302
+ bucket.tokens = Math.min(limitPerSecond, bucket.tokens + refill);
9303
+ bucket.lastRefillMs = nowMs;
9304
+ }
9305
+ }
9306
+ if (bucket.tokens >= 1) {
9307
+ bucket.tokens -= 1;
9308
+ return { allowed: true, retryAfterSeconds: 0 };
9309
+ }
9310
+ const deficitMs = (1 - bucket.tokens) / limitPerSecond * 1000;
9311
+ const retryAfterSeconds = Math.max(1, Math.ceil(deficitMs / 1000));
9312
+ return { allowed: false, retryAfterSeconds };
9313
+ }
9314
+ }
9315
+ function rateLimitedResponse(limit, retryAfterSeconds) {
9316
+ return new Response(JSON.stringify({ error: "rate_limited", limit }), {
9317
+ status: 429,
9318
+ headers: {
9319
+ "content-type": "application/json",
9320
+ "retry-after": String(retryAfterSeconds)
9321
+ }
9322
+ });
9323
+ }
9324
+
9174
9325
  // src/core/journal/ring-buffer.ts
9175
9326
  class RingBuffer {
9176
9327
  capacity;
@@ -11761,7 +11912,11 @@ var PRIVATE_IPV4_RANGES = [
11761
11912
  [127, 0, 0, 8],
11762
11913
  [169, 254, 0, 16],
11763
11914
  [100, 64, 0, 10],
11764
- [0, 0, 0, 8]
11915
+ [0, 0, 0, 8],
11916
+ [192, 0, 0, 24],
11917
+ [198, 18, 0, 15],
11918
+ [224, 0, 0, 4],
11919
+ [240, 0, 0, 4]
11765
11920
  ];
11766
11921
  function validateUpstreamUrl(raw2, opts = {}) {
11767
11922
  const allowedSchemes = opts.allowedSchemes ?? ["https"];
@@ -11824,12 +11979,49 @@ async function validateUpstreamUrlResolved(raw2, opts = {}) {
11824
11979
  });
11825
11980
  return parsed;
11826
11981
  }
11982
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11983
+ var DEFAULT_MAX_REDIRECT_HOPS = 5;
11984
+ async function fetchWithRedirectGuard(initialUrl, init, validation, maxRedirects = DEFAULT_MAX_REDIRECT_HOPS) {
11985
+ let currentUrl = initialUrl;
11986
+ let method = init.method;
11987
+ let body = init.body;
11988
+ let redirectsFollowed = 0;
11989
+ for (;; ) {
11990
+ const response = await fetch(currentUrl, {
11991
+ method,
11992
+ headers: init.headers,
11993
+ body: method === "GET" || method === "HEAD" ? undefined : body ?? undefined,
11994
+ redirect: "manual",
11995
+ signal: init.signal
11996
+ });
11997
+ const location = response.headers.get("location");
11998
+ if (!REDIRECT_STATUSES.has(response.status) || !location) {
11999
+ return { response, finalUrl: currentUrl, redirectsFollowed };
12000
+ }
12001
+ await response.body?.cancel();
12002
+ if (redirectsFollowed >= maxRedirects) {
12003
+ throw new UrlValidationError(currentUrl.href, `redirect chain exceeded ${maxRedirects} hop(s); blocked before following Location '${location}'`);
12004
+ }
12005
+ redirectsFollowed++;
12006
+ let nextUrl;
12007
+ try {
12008
+ nextUrl = new URL(location, currentUrl);
12009
+ } catch {
12010
+ throw new UrlValidationError(location, "redirect Location header is not a resolvable URL");
12011
+ }
12012
+ currentUrl = await validateUpstreamUrlResolved(nextUrl.href, validation);
12013
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") {
12014
+ method = "GET";
12015
+ body = null;
12016
+ }
12017
+ }
12018
+ }
11827
12019
  function isPrivateHost(hostname) {
11828
12020
  const stripped = hostname.replace(/^\[/, "").replace(/\]$/, "");
11829
12021
  const lowered = stripped.toLowerCase();
11830
12022
  if (lowered === "localhost" || lowered === "ip6-localhost" || lowered === "ip6-loopback")
11831
12023
  return true;
11832
- if (lowered === "::1" || lowered.startsWith("fe80:") || lowered.startsWith("fc") || lowered.startsWith("fd")) {
12024
+ if (isIpLiteral(stripped) && isPrivateIpv6(lowered)) {
11833
12025
  return true;
11834
12026
  }
11835
12027
  const ipv4MappedDotted = lowered.match(/^::ffff:([0-9.]+)$/);
@@ -11850,6 +12042,75 @@ function isPrivateHost(hostname) {
11850
12042
  }
11851
12043
  return false;
11852
12044
  }
12045
+ function expandIpv6(addr) {
12046
+ const halves = addr.split("::");
12047
+ if (halves.length > 2)
12048
+ return null;
12049
+ const parseGroups = (segment) => {
12050
+ if (segment === "")
12051
+ return [];
12052
+ const pieces = segment.split(":");
12053
+ const groups = [];
12054
+ for (let i2 = 0;i2 < pieces.length; i2++) {
12055
+ const piece = pieces[i2] ?? "";
12056
+ if (i2 === pieces.length - 1 && piece.includes(".")) {
12057
+ const octets = piece.split(".").map((o2) => Number.parseInt(o2, 10));
12058
+ if (octets.length !== 4 || octets.some((o2) => Number.isNaN(o2) || o2 < 0 || o2 > 255) || piece.split(".").some((o2) => !/^\d{1,3}$/.test(o2))) {
12059
+ return null;
12060
+ }
12061
+ const [a2 = 0, b2 = 0, c2 = 0, d2 = 0] = octets;
12062
+ groups.push(a2 << 8 | b2, c2 << 8 | d2);
12063
+ continue;
12064
+ }
12065
+ if (piece.length === 0 || piece.length > 4 || !/^[0-9a-f]+$/.test(piece))
12066
+ return null;
12067
+ const value = Number.parseInt(piece, 16);
12068
+ if (Number.isNaN(value))
12069
+ return null;
12070
+ groups.push(value);
12071
+ }
12072
+ return groups;
12073
+ };
12074
+ if (halves.length === 1) {
12075
+ const groups = parseGroups(halves[0] ?? "");
12076
+ return groups && groups.length === 8 ? groups : null;
12077
+ }
12078
+ const head = parseGroups(halves[0] ?? "");
12079
+ const tail = parseGroups(halves[1] ?? "");
12080
+ if (!head || !tail)
12081
+ return null;
12082
+ const missing = 8 - head.length - tail.length;
12083
+ if (missing < 0)
12084
+ return null;
12085
+ return [...head, ...Array(missing).fill(0), ...tail];
12086
+ }
12087
+ function ipv6PrefixMatch(groups, prefixGroups, prefixBits) {
12088
+ let bitsLeft = prefixBits;
12089
+ for (let i2 = 0;i2 < prefixGroups.length && bitsLeft > 0; i2++) {
12090
+ const bits = Math.min(16, bitsLeft);
12091
+ const mask = bits === 16 ? 65535 : 65535 << 16 - bits & 65535;
12092
+ if (((groups[i2] ?? 0) & mask) !== ((prefixGroups[i2] ?? 0) & mask))
12093
+ return false;
12094
+ bitsLeft -= bits;
12095
+ }
12096
+ return true;
12097
+ }
12098
+ function isPrivateIpv6(lowered) {
12099
+ const groups = expandIpv6(lowered);
12100
+ if (!groups)
12101
+ return false;
12102
+ if (groups.every((g2) => g2 === 0))
12103
+ return true;
12104
+ if (groups.slice(0, 7).every((g2) => g2 === 0) && groups[7] === 1)
12105
+ return true;
12106
+ if (ipv6PrefixMatch(groups, [64512], 7))
12107
+ return true;
12108
+ if (ipv6PrefixMatch(groups, [65152], 10))
12109
+ return true;
12110
+ if (ipv6PrefixMatch(groups, [100, 65435, 0, 0, 0, 0], 96))
12111
+ return true;
12112
+ return false;
12113
+ }
11853
12114
  function isPrivateIpv4(ip) {
11854
12115
  const parts = ip.split(".").map((p3) => Number.parseInt(p3, 10));
11855
12116
  if (parts.length !== 4 || parts.some((p3) => Number.isNaN(p3) || p3 < 0 || p3 > 255))
@@ -11861,16 +12122,13 @@ function isPrivateIpv4(ip) {
11861
12122
  }
11862
12123
  return false;
11863
12124
  }
11864
- function matchesIpv4(a2, _b, _c, _d, ra2, _rb, _rc, mask) {
11865
- if (mask === 8)
11866
- return a2 === ra2;
11867
- if (mask === 16)
11868
- return a2 === ra2 && _b === _rb;
11869
- if (mask === 12)
11870
- return a2 === ra2 && (_b & 240) === (_rb & 240);
11871
- if (mask === 10)
11872
- return a2 === ra2 && (_b & 192) === (_rb & 192);
11873
- return false;
12125
+ function matchesIpv4(a2, b2, c2, d2, ra2, rb, rc, mask) {
12126
+ if (mask <= 0 || mask > 32)
12127
+ return false;
12128
+ const value = (a2 << 24 | b2 << 16 | c2 << 8 | d2) >>> 0;
12129
+ const rangeValue = (ra2 << 24 | rb << 16 | rc << 8 | 0) >>> 0;
12130
+ const maskBits = mask === 32 ? 4294967295 : 4294967295 << 32 - mask >>> 0;
12131
+ return (value & maskBits) >>> 0 === (rangeValue & maskBits) >>> 0;
11874
12132
  }
11875
12133
 
11876
12134
  // src/features/pass-through.ts
@@ -11879,12 +12137,13 @@ async function renderPassThrough(entry, ctx, opts) {
11879
12137
  throw new Error(`renderPassThrough called for non-passthrough entry '${entry.id}'`);
11880
12138
  }
11881
12139
  const spec = entry.response;
12140
+ const validationOpts = {
12141
+ allowedSchemes: ["https", "http"],
12142
+ allowPrivateUpstreams: opts.allowPrivateUpstreams
12143
+ };
11882
12144
  let upstreamUrl;
11883
12145
  try {
11884
- upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, {
11885
- allowedSchemes: ["https", "http"],
11886
- allowPrivateUpstreams: opts.allowPrivateUpstreams
11887
- });
12146
+ upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, validationOpts);
11888
12147
  } catch (err) {
11889
12148
  opts.logger.error({
11890
12149
  event: "passthrough_url_rejected",
@@ -11911,14 +12170,16 @@ async function renderPassThrough(entry, ctx, opts) {
11911
12170
  const controller = new AbortController;
11912
12171
  const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
11913
12172
  timer.unref?.();
12173
+ const bodyCap = ctx.req.method === "GET" || ctx.req.method === "HEAD" ? null : capRequestBodyStream(ctx, opts.maxBodyBytes);
11914
12174
  const started = performance.now();
11915
12175
  try {
11916
- const upstreamRes = await fetch(targetUrl, {
12176
+ const requestBody = bodyCap ? await ctx.req.raw.arrayBuffer() : null;
12177
+ const { response: upstreamRes } = await fetchWithRedirectGuard(targetUrl, {
11917
12178
  method: ctx.req.method,
11918
12179
  headers,
11919
- body: ctx.req.method === "GET" || ctx.req.method === "HEAD" ? undefined : await ctx.req.raw.arrayBuffer(),
12180
+ body: requestBody,
11920
12181
  signal: controller.signal
11921
- });
12182
+ }, validationOpts);
11922
12183
  clearTimeout(timer);
11923
12184
  return new Response(upstreamRes.body, {
11924
12185
  status: upstreamRes.status,
@@ -11926,7 +12187,23 @@ async function renderPassThrough(entry, ctx, opts) {
11926
12187
  });
11927
12188
  } catch (err) {
11928
12189
  clearTimeout(timer);
12190
+ if (bodyCap?.tooLarge()) {
12191
+ return bodyTooLargeResponse(opts.maxBodyBytes);
12192
+ }
11929
12193
  const durationMs = performance.now() - started;
12194
+ if (err instanceof UrlValidationError) {
12195
+ opts.logger.error({
12196
+ event: "passthrough_redirect_rejected",
12197
+ entryId: entry.id,
12198
+ upstream: String(upstreamUrl),
12199
+ reason: err.reason
12200
+ });
12201
+ return new Response(JSON.stringify({
12202
+ error: "passthrough_upstream",
12203
+ upstream: String(upstreamUrl),
12204
+ reason: "upstream redirected to a URL rejected by validator"
12205
+ }), { status: 502, headers: { "content-type": "application/json" } });
12206
+ }
11930
12207
  const aborted = err instanceof DOMException && err.name === "AbortError";
11931
12208
  opts.logger.error({
11932
12209
  event: "passthrough_upstream_error",
@@ -12412,12 +12689,39 @@ class BoundedRetryQueue {
12412
12689
  #cap;
12413
12690
  #onDropped;
12414
12691
  #onSizeChange;
12692
+ #timers = new Map;
12693
+ #stopped = false;
12415
12694
  constructor(opts = {}) {
12416
12695
  this.#pq = new PQueue({ concurrency: opts.concurrency ?? DEFAULT_CONCURRENCY });
12417
12696
  this.#cap = opts.cap ?? DEFAULT_CAP;
12418
12697
  this.#onDropped = opts.onDropped;
12419
12698
  this.#onSizeChange = opts.onSizeChange;
12420
12699
  }
12700
+ stop() {
12701
+ if (this.#stopped)
12702
+ return;
12703
+ this.#stopped = true;
12704
+ for (const [timer, resolve4] of this.#timers) {
12705
+ clearTimeout(timer);
12706
+ resolve4();
12707
+ }
12708
+ this.#timers.clear();
12709
+ const abandoned = this.#waiting.splice(0, this.#waiting.length);
12710
+ for (const req of abandoned) {
12711
+ this.#dropDelivery(req);
12712
+ }
12713
+ }
12714
+ #sleep(ms) {
12715
+ if (ms <= 0 || this.#stopped)
12716
+ return Promise.resolve();
12717
+ return new Promise((resolve4) => {
12718
+ const timer = setTimeout(() => {
12719
+ this.#timers.delete(timer);
12720
+ resolve4();
12721
+ }, ms);
12722
+ this.#timers.set(timer, resolve4);
12723
+ });
12724
+ }
12421
12725
  #fireSizeChange() {
12422
12726
  if (!this.#onSizeChange)
12423
12727
  return;
@@ -12436,7 +12740,14 @@ class BoundedRetryQueue {
12436
12740
  inflight() {
12437
12741
  return this.#pq.pending;
12438
12742
  }
12743
+ liveTimerCount() {
12744
+ return this.#timers.size;
12745
+ }
12439
12746
  enqueue(req) {
12747
+ if (this.#stopped) {
12748
+ this.#dropDelivery(req);
12749
+ return;
12750
+ }
12440
12751
  while (this.size() >= this.#cap) {
12441
12752
  const oldest = this.#waiting.shift();
12442
12753
  if (oldest) {
@@ -12469,7 +12780,17 @@ class BoundedRetryQueue {
12469
12780
  if (attempt > 1) {
12470
12781
  const baseMs = req.retry.backoff[attempt - 2] ?? 0;
12471
12782
  const delayMs = applyJitter(baseMs, req.retry.jitterRatio);
12472
- await sleep(delayMs);
12783
+ await this.#sleep(delayMs);
12784
+ if (this.#stopped) {
12785
+ req.onTerminal({
12786
+ deliveryId: req.deliveryId,
12787
+ outcome: "failed",
12788
+ totalAttempts: attempt - 1,
12789
+ lastHttpStatus,
12790
+ totalDurationUs: Math.round((performance.now() - totalStart) * 1000)
12791
+ });
12792
+ return;
12793
+ }
12473
12794
  }
12474
12795
  const gate = req.circuitGate();
12475
12796
  if (gate === "open") {
@@ -12511,7 +12832,7 @@ class BoundedRetryQueue {
12511
12832
  lastError = errorToString(err);
12512
12833
  req.onAttempt({
12513
12834
  attempt,
12514
- outcome: attempt === req.retry.attempts ? "failed" : "success",
12835
+ outcome: attempt === req.retry.attempts ? "failed" : "retrying",
12515
12836
  durationUs: 0,
12516
12837
  error: lastError
12517
12838
  });
@@ -12549,11 +12870,6 @@ function applyJitter(baseMs, ratio) {
12549
12870
  const delta = baseMs * ratio;
12550
12871
  return Math.max(0, Math.round(baseMs - delta + Math.random() * 2 * delta));
12551
12872
  }
12552
- function sleep(ms) {
12553
- if (ms <= 0)
12554
- return Promise.resolve();
12555
- return new Promise((resolve4) => setTimeout(resolve4, ms));
12556
- }
12557
12873
  function errorToString(err) {
12558
12874
  if (err instanceof Error)
12559
12875
  return `${err.name}: ${err.message}`;
@@ -12673,6 +12989,13 @@ class DeliveryEventRegistry {
12673
12989
  this.#completed.delete(id);
12674
12990
  }
12675
12991
  }
12992
+ stop() {
12993
+ const pending = Array.from(this.#pending.values());
12994
+ for (const deferred of pending) {
12995
+ deferred.resolve(null);
12996
+ }
12997
+ this.#pending.clear();
12998
+ }
12676
12999
  pendingCount() {
12677
13000
  return this.#pending.size;
12678
13001
  }
@@ -12682,6 +13005,25 @@ class DeliveryEventRegistry {
12682
13005
  }
12683
13006
  // src/features/webhooks/journal.ts
12684
13007
  import { appendFileSync } from "fs";
13008
+ function redactUrlForJournal(rawUrl) {
13009
+ try {
13010
+ return `${new URL(rawUrl).origin}/[redacted]`;
13011
+ } catch {
13012
+ return "[redacted:unparseable-url]";
13013
+ }
13014
+ }
13015
+ var EMBEDDED_URL_PATTERN = /\bhttps?:\/\/[^\s'"()<>[\]{}]+/gi;
13016
+ function redactUrlsInText(text) {
13017
+ return text.replace(EMBEDDED_URL_PATTERN, (match2) => redactUrlForJournal(match2));
13018
+ }
13019
+ function redactEntry(entry) {
13020
+ return {
13021
+ ...entry,
13022
+ ...entry.resolvedUrl !== undefined && { resolvedUrl: redactUrlForJournal(entry.resolvedUrl) },
13023
+ ...entry.error !== undefined && { error: redactUrlsInText(entry.error) }
13024
+ };
13025
+ }
13026
+
12685
13027
  class WebhookJournalRegistry {
12686
13028
  #buffers = new Map;
12687
13029
  #capacityFor;
@@ -12691,11 +13033,12 @@ class WebhookJournalRegistry {
12691
13033
  this.#journalFile = opts.journalFile;
12692
13034
  }
12693
13035
  record(entry) {
12694
- const buf = this.#bufferFor(entry.tenant);
12695
- buf.push(entry);
13036
+ const redacted = redactEntry(entry);
13037
+ const buf = this.#bufferFor(redacted.tenant);
13038
+ buf.push(redacted);
12696
13039
  if (this.#journalFile) {
12697
13040
  try {
12698
- appendFileSync(this.#journalFile, `${JSON.stringify(entry)}
13041
+ appendFileSync(this.#journalFile, `${JSON.stringify(redacted)}
12699
13042
  `);
12700
13043
  } catch (err) {
12701
13044
  console.warn(`[mockstar] webhook journal file write failed: ${err.message ?? err}`);
@@ -12819,14 +13162,13 @@ function dispatchWebhooks(deps, input) {
12819
13162
  }
12820
13163
  async function performAttempt(spec, input, _deps) {
12821
13164
  const attemptStart = performance.now();
12822
- let urlString;
12823
13165
  const headerUrl = _deps.allowWebhookUrlHeader && spec.acceptHeaderOverride ? input.requestHeaders.get("x-mockstar-webhook-url") : undefined;
12824
- urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12825
- const allowedSchemes = spec.allowHttp ? ["http", "https"] : ["https"];
12826
- await validateUpstreamUrlResolved(urlString, {
12827
- allowedSchemes,
13166
+ const urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
13167
+ const validationOpts = {
13168
+ allowedSchemes: spec.allowHttp ? ["http", "https"] : ["https"],
12828
13169
  allowPrivateUpstreams: spec.allowPrivateNetworks
12829
- });
13170
+ };
13171
+ const validatedUrl = await validateUpstreamUrlResolved(urlString, validationOpts);
12830
13172
  const renderedHeaders = new Headers;
12831
13173
  for (const [key, tmpl] of spec.headers) {
12832
13174
  renderedHeaders.set(key, tmpl.render(input.templateContext));
@@ -12858,14 +13200,20 @@ async function performAttempt(spec, input, _deps) {
12858
13200
  }
12859
13201
  const signal = AbortSignal.timeout(spec.timeoutMs);
12860
13202
  let response;
13203
+ let finalUrl;
12861
13204
  try {
12862
- response = await fetch(urlString, {
13205
+ const result = await fetchWithRedirectGuard(validatedUrl, {
12863
13206
  method: spec.method,
12864
13207
  headers: renderedHeaders,
12865
- body: spec.method === "GET" || spec.method === "DELETE" ? undefined : rawBody,
13208
+ body: spec.method === "GET" || spec.method === "DELETE" ? null : rawBody,
12866
13209
  signal
12867
- });
13210
+ }, validationOpts);
13211
+ response = result.response;
13212
+ finalUrl = result.finalUrl;
12868
13213
  } catch (err) {
13214
+ if (err instanceof UrlValidationError) {
13215
+ throw new Error(`webhook delivery redirect rejected: ${err.message}`);
13216
+ }
12869
13217
  throw new Error(`webhook delivery network error: ${err.message ?? err}`);
12870
13218
  }
12871
13219
  if (!isSuccessStatus(response.status, spec.expectResponse)) {
@@ -12880,7 +13228,7 @@ async function performAttempt(spec, input, _deps) {
12880
13228
  return {
12881
13229
  httpStatus: response.status,
12882
13230
  durationUs: Math.round((performance.now() - attemptStart) * 1000),
12883
- resolvedUrl: urlString
13231
+ resolvedUrl: finalUrl.href
12884
13232
  };
12885
13233
  }
12886
13234
  function isSuccessStatus(status, expect) {
@@ -12931,6 +13279,8 @@ function makeDeliveryId() {
12931
13279
  return crypto.randomUUID();
12932
13280
  }
12933
13281
  // src/server.ts
13282
+ var UNKNOWN_TENANT_BUCKET = ":unknown:";
13283
+ var DEFAULT_REQUESTS_PER_SECOND = 1e4;
12934
13284
  function createServer(opts) {
12935
13285
  const logger = opts.logger ?? createLogger({ deterministic: opts.deterministic });
12936
13286
  const metrics = new Metrics;
@@ -12938,6 +13288,7 @@ function createServer(opts) {
12938
13288
  const snap = opts.holder.get().tenants.get(tenant);
12939
13289
  return snap?.limits.journalSize ?? 1000;
12940
13290
  });
13291
+ const rateLimiter = new TenantRateLimiter({ now: opts.rateLimiterNow });
12941
13292
  const webhookJournal = new WebhookJournalRegistry((tenant) => {
12942
13293
  const snap = opts.holder.get().tenants.get(tenant);
12943
13294
  return snap?.limits.journalSize ?? 1000;
@@ -13048,6 +13399,7 @@ function createServer(opts) {
13048
13399
  clock,
13049
13400
  journal,
13050
13401
  metrics,
13402
+ rateLimiter,
13051
13403
  handlerTimeoutMs,
13052
13404
  genRequestId,
13053
13405
  webhookJournal,
@@ -13056,15 +13408,22 @@ function createServer(opts) {
13056
13408
  circuitFor,
13057
13409
  allowWebhookUrlHeader
13058
13410
  }));
13411
+ const stopWebhooks = () => {
13412
+ for (const q3 of webhookQueues.values())
13413
+ q3.stop();
13414
+ webhookEvents.stop();
13415
+ };
13059
13416
  return {
13060
13417
  hono: app,
13061
13418
  journal,
13062
13419
  metrics,
13420
+ rateLimiter,
13063
13421
  ready,
13064
13422
  uninstallCrashHandlers,
13065
13423
  webhookJournal,
13066
13424
  webhookEvents,
13067
- replayWebhook
13425
+ replayWebhook,
13426
+ stopWebhooks
13068
13427
  };
13069
13428
  }
13070
13429
  async function dispatch(ctx, deps) {
@@ -13076,28 +13435,35 @@ async function dispatch(ctx, deps) {
13076
13435
  const startedUs = performance.now() * 1000;
13077
13436
  const matchPath = effectivePath(ctx);
13078
13437
  const method = ctx.req.method;
13438
+ const observedTenant = tenantSnap ? tenant : UNKNOWN_TENANT_BUCKET;
13079
13439
  let response;
13080
13440
  let matchedMockId = null;
13081
13441
  let scenarioId;
13082
13442
  let scenarioMissReason;
13083
13443
  let webhookTrigger;
13084
13444
  try {
13085
- if (!tenantSnap) {
13445
+ const rpsLimit = tenantSnap?.limits.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;
13446
+ const rateResult = deps.rateLimiter.tryAcquire(observedTenant, rpsLimit);
13447
+ if (!rateResult.allowed) {
13448
+ response = rateLimitedResponse(rpsLimit, rateResult.retryAfterSeconds);
13449
+ } else if (!tenantSnap) {
13086
13450
  response = notFoundUnknownTenant(tenant, method, matchPath);
13087
13451
  } else {
13088
13452
  const contentLength = Number.parseInt(ctx.req.header("content-length") ?? "0", 10);
13089
13453
  if (contentLength > tenantSnap.limits.maxBodyBytes) {
13090
- response = new Response(JSON.stringify({ error: "body_too_large", limit: tenantSnap.limits.maxBodyBytes }), {
13091
- status: 413,
13092
- headers: { "content-type": "application/json" }
13093
- });
13454
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
13094
13455
  } else {
13095
- const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps);
13096
- response = result.response;
13097
- matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
13098
- scenarioId = result.scenarioId;
13099
- scenarioMissReason = result.scenarioMissReason;
13100
- webhookTrigger = result.webhookTrigger;
13456
+ const bodyResult = await safeParseBody(ctx, tenantSnap.limits.maxBodyBytes);
13457
+ if (!bodyResult.ok) {
13458
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
13459
+ } else {
13460
+ const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, bodyResult.body);
13461
+ response = result.response;
13462
+ matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
13463
+ scenarioId = result.scenarioId;
13464
+ scenarioMissReason = result.scenarioMissReason;
13465
+ webhookTrigger = result.webhookTrigger;
13466
+ }
13101
13467
  }
13102
13468
  }
13103
13469
  } catch (err) {
@@ -13118,7 +13484,7 @@ async function dispatch(ctx, deps) {
13118
13484
  const durationUs = Math.round(performance.now() * 1000 - startedUs);
13119
13485
  const entry = {
13120
13486
  timestamp: Date.now(),
13121
- tenant,
13487
+ tenant: observedTenant,
13122
13488
  requestId,
13123
13489
  method,
13124
13490
  path: matchPath,
@@ -13130,15 +13496,15 @@ async function dispatch(ctx, deps) {
13130
13496
  };
13131
13497
  deps.journal.record(entry);
13132
13498
  deps.metrics.incCounter("mockstar_requests_total", {
13133
- tenant,
13499
+ tenant: observedTenant,
13134
13500
  method,
13135
13501
  status: String(response.status),
13136
13502
  matched: matchedMockId ? "1" : "0"
13137
13503
  });
13138
- deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant }, durationUs);
13504
+ deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant: observedTenant }, durationUs);
13139
13505
  deps.logger.info({
13140
13506
  event: "request",
13141
- tenant,
13507
+ tenant: observedTenant,
13142
13508
  method,
13143
13509
  path: matchPath,
13144
13510
  status: response.status,
@@ -13187,9 +13553,8 @@ async function dispatch(ctx, deps) {
13187
13553
  });
13188
13554
  return response;
13189
13555
  }
13190
- async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps) {
13556
+ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, body) {
13191
13557
  const url = new URL(ctx.req.url);
13192
- const body = await safeParseBody(ctx);
13193
13558
  const req = {
13194
13559
  query: new Map(Array.from(url.searchParams)),
13195
13560
  headers: new Map(Array.from(ctx.req.raw.headers).map(([k2, v3]) => [k2.toLowerCase(), v3])),
@@ -13301,7 +13666,8 @@ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap,
13301
13666
  case "passthrough":
13302
13667
  response = await renderPassThrough(hit.entry, ctx, {
13303
13668
  allowPrivateUpstreams: tenantSnap.allowPrivateUpstreams,
13304
- logger: deps.logger
13669
+ logger: deps.logger,
13670
+ maxBodyBytes: tenantSnap.limits.maxBodyBytes
13305
13671
  });
13306
13672
  break;
13307
13673
  }
@@ -13319,20 +13685,27 @@ function notFoundUnknownTenant(tenant, method, path) {
13319
13685
  headers: { "content-type": "application/json" }
13320
13686
  });
13321
13687
  }
13322
- async function safeParseBody(ctx) {
13688
+ async function safeParseBody(ctx, maxBodyBytes) {
13323
13689
  const method = ctx.req.method;
13324
13690
  if (method === "GET" || method === "HEAD")
13325
- return null;
13691
+ return { ok: true, body: null };
13326
13692
  const contentType = ctx.req.header("content-type") ?? "";
13327
13693
  if (!contentType.includes("json"))
13328
- return null;
13694
+ return { ok: true, body: null };
13695
+ const { tooLarge } = capRequestBodyStream(ctx, maxBodyBytes);
13329
13696
  try {
13330
13697
  const text = await ctx.req.text();
13331
13698
  if (text.length === 0)
13332
- return null;
13333
- return JSON.parse(text);
13334
- } catch {
13335
- return null;
13699
+ return { ok: true, body: null };
13700
+ try {
13701
+ return { ok: true, body: JSON.parse(text) };
13702
+ } catch {
13703
+ return { ok: true, body: null };
13704
+ }
13705
+ } catch (err) {
13706
+ if (tooLarge())
13707
+ return { ok: false };
13708
+ throw err;
13336
13709
  }
13337
13710
  }
13338
13711
  function createRequestIdGenerator(deterministic) {
@@ -13384,6 +13757,7 @@ async function launch(opts) {
13384
13757
  holder,
13385
13758
  async stop() {
13386
13759
  watcher?.stop();
13760
+ server.stopWebhooks();
13387
13761
  server.uninstallCrashHandlers();
13388
13762
  }
13389
13763
  };
@@ -13900,10 +14274,10 @@ function convertOpenApi(doc, opts = {}) {
13900
14274
  if (!doc || typeof doc !== "object") {
13901
14275
  throw new OpenApiImportError("OpenAPI document root must be an object");
13902
14276
  }
13903
- const refs = findRefs(doc);
13904
- for (const ref of refs) {
14277
+ const refs = findRefs(doc, "$");
14278
+ for (const { ref, path } of refs) {
13905
14279
  if (!ref.startsWith("#")) {
13906
- throw new OpenApiImportError(`External $ref rejected: '${ref}'. Only in-document ($ref starting with '#') references are permitted.`, { ref });
14280
+ throw new OpenApiImportError(`External $ref rejected: '${ref}' at ${path}. Only in-document ($ref starting with '#') references are permitted.`, { ref, path });
13907
14281
  }
13908
14282
  }
13909
14283
  const openapi = doc;
@@ -13950,18 +14324,39 @@ function convertOpenApi(doc, opts = {}) {
13950
14324
  }
13951
14325
  return entries;
13952
14326
  }
13953
- function findRefs(value, acc = []) {
14327
+ function findRefs(value, path, acc = []) {
13954
14328
  if (value === null || typeof value !== "object")
13955
14329
  return acc;
13956
14330
  if (Array.isArray(value)) {
13957
- for (const v3 of value)
13958
- findRefs(v3, acc);
14331
+ value.forEach((v3, i2) => findRefs(v3, `${path}[${i2}]`, acc));
13959
14332
  return acc;
13960
14333
  }
13961
- for (const [k2, v3] of Object.entries(value)) {
13962
- if (k2 === "$ref" && typeof v3 === "string")
13963
- acc.push(v3);
13964
- findRefs(v3, acc);
14334
+ const obj = value;
14335
+ for (const [k2, v3] of Object.entries(obj)) {
14336
+ if (k2 === "$ref" && typeof v3 === "string") {
14337
+ acc.push({ ref: v3, path: `${path}.$ref` });
14338
+ continue;
14339
+ }
14340
+ if (k2 === "example")
14341
+ continue;
14342
+ if (k2 === "examples" && v3 !== null && typeof v3 === "object" && !Array.isArray(v3)) {
14343
+ for (const [name, member] of Object.entries(v3)) {
14344
+ const memberPath = `${path}.examples.${name}`;
14345
+ if (member === null || typeof member !== "object" || Array.isArray(member))
14346
+ continue;
14347
+ for (const [mk, mv] of Object.entries(member)) {
14348
+ if (mk === "value")
14349
+ continue;
14350
+ if (mk === "$ref" && typeof mv === "string") {
14351
+ acc.push({ ref: mv, path: `${memberPath}.$ref` });
14352
+ continue;
14353
+ }
14354
+ findRefs(mv, `${memberPath}.${mk}`, acc);
14355
+ }
14356
+ }
14357
+ continue;
14358
+ }
14359
+ findRefs(v3, `${path}.${k2}`, acc);
13965
14360
  }
13966
14361
  return acc;
13967
14362
  }
@@ -13969,7 +14364,7 @@ function pickExemplar(op, doc) {
13969
14364
  const responses = op.responses ?? {};
13970
14365
  const preferred = ["200", "201", "202", "204", "default"];
13971
14366
  for (const code of preferred) {
13972
- const res = responses[code];
14367
+ const res = responses[code] ?? (code === "default" ? undefined : responses[`${code[0]}XX`]);
13973
14368
  if (!res)
13974
14369
  continue;
13975
14370
  const status = code === "default" ? 200 : Number.parseInt(code, 10);
@@ -14669,7 +15064,7 @@ init_port_bind();
14669
15064
  // src/features/proxy/install-journal.ts
14670
15065
  init_types();
14671
15066
  import { createHash } from "crypto";
14672
- import { appendFile as appendFile2, mkdir as mkdir3, readFile as readFile8, rm as rm2, stat as stat4 } from "fs/promises";
15067
+ import { appendFile as appendFile2, mkdir as mkdir3, readFile as readFile8, rm as rm3, stat as stat4 } from "fs/promises";
14673
15068
  import { dirname as dirname2 } from "path";
14674
15069
  async function appendStep(path, step) {
14675
15070
  await mkdir3(dirname2(path), { recursive: true });
@@ -14706,7 +15101,7 @@ async function* reverseSteps(path) {
14706
15101
  }
14707
15102
  }
14708
15103
  async function clearJournal(path) {
14709
- await rm2(path, { force: true });
15104
+ await rm3(path, { force: true });
14710
15105
  }
14711
15106
  async function journalFacts(path) {
14712
15107
  let exists = false;
@@ -14775,10 +15170,10 @@ var reverseCommandImpls = {
14775
15170
  });
14776
15171
  },
14777
15172
  remove_file: async ({ path }) => {
14778
- await rm2(path, { force: true });
15173
+ await rm3(path, { force: true });
14779
15174
  },
14780
15175
  remove_dir: async ({ path }) => {
14781
- await rm2(path, { recursive: true, force: true });
15176
+ await rm3(path, { recursive: true, force: true });
14782
15177
  },
14783
15178
  revert_file: async ({ path, originalContent }) => {
14784
15179
  const { writeFile: writeFile7 } = await import("fs/promises");
@@ -14803,7 +15198,7 @@ var reverseCommandImpls = {
14803
15198
  await runPrivileged2(["launchctl", "unload", "-w", plistPath]).catch(() => {
14804
15199
  return;
14805
15200
  });
14806
- await rm2(plistPath, { force: true });
15201
+ await rm3(plistPath, { force: true });
14807
15202
  },
14808
15203
  noop: async () => {}
14809
15204
  };
@@ -14842,6 +15237,7 @@ init_dns();
14842
15237
  init_types();
14843
15238
 
14844
15239
  // src/features/proxy/cli.ts
15240
+ init_types();
14845
15241
  async function dispatchProxyCommand(argv) {
14846
15242
  const [sub, ...rest] = argv;
14847
15243
  if (!sub || sub === "--help" || sub === "help") {
@@ -14914,9 +15310,23 @@ async function install(argv) {
14914
15310
  }
14915
15311
  });
14916
15312
  mutations.push(...await buildDnsMutations(config));
14917
- mutations.push(portBindMutation({
14918
- binaryPath: process.argv[0] ?? "/usr/bin/env"
14919
- }));
15313
+ try {
15314
+ mutations.push(portBindMutation({
15315
+ binaryPath: process.execPath,
15316
+ allowInterpreter: resolveAllowInterpreterGrant(argv, process.env)
15317
+ }));
15318
+ } catch (err) {
15319
+ if (err instanceof ProxyError) {
15320
+ process.stderr.write(`
15321
+ ${err.message}
15322
+ `);
15323
+ if (err.hint)
15324
+ process.stderr.write(`${err.hint}
15325
+ `);
15326
+ return 1;
15327
+ }
15328
+ throw err;
15329
+ }
14920
15330
  try {
14921
15331
  const { applied } = await atomicInstall(journalPath, mutations, {
14922
15332
  onStep: (step) => process.stdout.write(` [${step.step}] ${step.action}
@@ -15056,6 +15466,9 @@ function defaultConfigPath() {
15056
15466
  function defaultJournalPath() {
15057
15467
  return join7(homedir(), ".mockstar", "install-state.json");
15058
15468
  }
15469
+ function resolveAllowInterpreterGrant(argv, env) {
15470
+ return argv.includes(ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG) || env[ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV] === "1";
15471
+ }
15059
15472
  function pickFlag(args, name) {
15060
15473
  const prefixed = args.find((a2) => a2.startsWith(`${name}=`));
15061
15474
  if (prefixed)
@@ -15085,6 +15498,13 @@ function proxyHelp() {
15085
15498
  "Subcommands:",
15086
15499
  " install Install local CA + DNS + port-443 capability; journaled for clean uninstall.",
15087
15500
  " Flags: --force, --dns-mode=<dnsmasq|hosts>, --config=<path>",
15501
+ ` ${ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG}`,
15502
+ " Opt-in escape hatch for #39: grants the network-bind capability",
15503
+ " even when running from source (bun) instead of a packaged binary.",
15504
+ " Grants EVERY program run by that interpreter the ability to bind",
15505
+ " privileged ports \u2014 only use on a single-purpose, ephemeral host",
15506
+ " (CI runner, throwaway VM/container), never on a dev machine. Env:",
15507
+ ` ${ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV}=1 (for CI steps / Dockerfiles).`,
15088
15508
  " uninstall Reverse every journaled install mutation (LIFO).",
15089
15509
  " start Run the HTTPS proxy (requires prior install).",
15090
15510
  " Flags: --config=<path>",
@@ -15102,7 +15522,7 @@ function proxyHelp() {
15102
15522
  }
15103
15523
 
15104
15524
  // src/version.ts
15105
- var MOCKSTAR_VERSION = "0.3.0";
15525
+ var MOCKSTAR_VERSION = "0.4.0";
15106
15526
 
15107
15527
  // src/cli.ts
15108
15528
  function parseArgs(argv) {