@dhaneshpurohit/mockstar 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/cli.js +786 -178
  3. package/dist/core/config/schema.d.ts +486 -320
  4. package/dist/core/config/schema.d.ts.map +1 -1
  5. package/dist/core/http/body-cap.d.ts +37 -0
  6. package/dist/core/http/body-cap.d.ts.map +1 -0
  7. package/dist/core/http/rate-limit.d.ts +55 -0
  8. package/dist/core/http/rate-limit.d.ts.map +1 -0
  9. package/dist/core/matching/discriminators.d.ts +25 -0
  10. package/dist/core/matching/discriminators.d.ts.map +1 -1
  11. package/dist/core/matching/index.d.ts +3 -1
  12. package/dist/core/matching/index.d.ts.map +1 -1
  13. package/dist/features/openapi/converter.d.ts.map +1 -1
  14. package/dist/features/pass-through.d.ts +7 -0
  15. package/dist/features/pass-through.d.ts.map +1 -1
  16. package/dist/features/proxy/cli.d.ts +11 -0
  17. package/dist/features/proxy/cli.d.ts.map +1 -1
  18. package/dist/features/proxy/dns.d.ts +21 -3
  19. package/dist/features/proxy/dns.d.ts.map +1 -1
  20. package/dist/features/proxy/index.d.ts +1 -1
  21. package/dist/features/proxy/index.d.ts.map +1 -1
  22. package/dist/features/proxy/port-bind.d.ts +18 -1
  23. package/dist/features/proxy/port-bind.d.ts.map +1 -1
  24. package/dist/features/proxy/sni-gate.d.ts +4 -3
  25. package/dist/features/proxy/sni-gate.d.ts.map +1 -1
  26. package/dist/features/url-validator.d.ts +48 -0
  27. package/dist/features/url-validator.d.ts.map +1 -1
  28. package/dist/features/webhooks/dispatcher.d.ts.map +1 -1
  29. package/dist/features/webhooks/event-registry.d.ts +7 -0
  30. package/dist/features/webhooks/event-registry.d.ts.map +1 -1
  31. package/dist/features/webhooks/index.d.ts +3 -1
  32. package/dist/features/webhooks/index.d.ts.map +1 -1
  33. package/dist/features/webhooks/journal.d.ts +23 -0
  34. package/dist/features/webhooks/journal.d.ts.map +1 -1
  35. package/dist/features/webhooks/queue.d.ts +18 -0
  36. package/dist/features/webhooks/queue.d.ts.map +1 -1
  37. package/dist/features/webhooks/scheme.d.ts +46 -0
  38. package/dist/features/webhooks/scheme.d.ts.map +1 -0
  39. package/dist/features/webhooks/signing.d.ts +24 -13
  40. package/dist/features/webhooks/signing.d.ts.map +1 -1
  41. package/dist/features/webhooks/types.d.ts +32 -5
  42. package/dist/features/webhooks/types.d.ts.map +1 -1
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +628 -133
  46. package/dist/server.d.ts +17 -0
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/version.d.ts +1 -1
  49. package/package.json +2 -1
package/dist/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
  }
@@ -1060,9 +1131,13 @@ function compileOne(spec) {
1060
1131
  jitterRatio: spec.retry.jitterRatio
1061
1132
  },
1062
1133
  signing: spec.signing ? {
1134
+ mode: spec.signing.mode,
1063
1135
  enabled: spec.signing.enabled,
1064
1136
  algorithm: spec.signing.algorithm,
1065
1137
  secretRef: spec.signing.secretRef,
1138
+ signedPayload: spec.signing.signedPayload,
1139
+ signatureTemplate: spec.signing.signatureTemplate,
1140
+ digestEncoding: spec.signing.digestEncoding,
1066
1141
  signatureHeader: spec.signing.signatureHeader,
1067
1142
  timestampHeader: spec.signing.timestampHeader,
1068
1143
  replayWindowMs: spec.signing.replayWindowMs
@@ -2592,20 +2667,64 @@ JSONPath.prototype.safeVm = {
2592
2667
  JSONPath.prototype.vm = vm;
2593
2668
 
2594
2669
  // src/core/matching/discriminators.ts
2595
- 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) {
2596
2715
  if (pred.query) {
2597
- for (const [field, expected] of Object.entries(pred.query)) {
2716
+ for (const [field, expected] of pred.query) {
2598
2717
  const got = req.query.get(field);
2599
- if (!stringMatchOk(expected, got)) {
2600
- return { kind: "query", field, expected: describe(expected), got };
2718
+ if (!compiledMatchOk(expected, got)) {
2719
+ return { kind: "query", field, expected: describeCompiled(expected), got };
2601
2720
  }
2602
2721
  }
2603
2722
  }
2604
2723
  if (pred.headers) {
2605
- for (const [field, expected] of Object.entries(pred.headers)) {
2724
+ for (const [field, expected] of pred.headers) {
2606
2725
  const got = req.headers.get(field.toLowerCase());
2607
- if (!stringMatchOk(expected, got)) {
2608
- return { kind: "headers", field, expected: describe(expected), got };
2726
+ if (!compiledMatchOk(expected, got)) {
2727
+ return { kind: "headers", field, expected: describeCompiled(expected), got };
2609
2728
  }
2610
2729
  }
2611
2730
  }
@@ -2630,34 +2749,6 @@ function evaluateDiscriminators(pred, req) {
2630
2749
  }
2631
2750
  return null;
2632
2751
  }
2633
- function stringMatchOk(spec, got) {
2634
- if (typeof spec === "string")
2635
- return got === spec;
2636
- if ("equals" in spec)
2637
- return got === spec.equals;
2638
- if (got === undefined)
2639
- return false;
2640
- if ("regex" in spec)
2641
- return new RegExp(spec.regex).test(got);
2642
- if ("startsWith" in spec)
2643
- return got.startsWith(spec.startsWith);
2644
- if ("contains" in spec)
2645
- return got.includes(spec.contains);
2646
- return false;
2647
- }
2648
- function describe(spec) {
2649
- if (typeof spec === "string")
2650
- return `=${spec}`;
2651
- if ("equals" in spec)
2652
- return `=${spec.equals}`;
2653
- if ("regex" in spec)
2654
- return `~/${spec.regex}/`;
2655
- if ("startsWith" in spec)
2656
- return `^${spec.startsWith}`;
2657
- if ("contains" in spec)
2658
- return `*${spec.contains}*`;
2659
- return "?";
2660
- }
2661
2752
  function deepEquals(a, b) {
2662
2753
  if (a === b)
2663
2754
  return true;
@@ -2769,7 +2860,7 @@ function buildMatchIndex(entries) {
2769
2860
  const byMethod = new Map;
2770
2861
  const wildcardMethodRoot = createNode();
2771
2862
  entries.forEach((e, i) => {
2772
- const indexed = { entry: e, order: i };
2863
+ const indexed = { entry: e, order: i, compiled: compilePredicate(e.match) };
2773
2864
  if (e.match.method === "*") {
2774
2865
  insertPattern(wildcardMethodRoot, e.match.path, indexed);
2775
2866
  return;
@@ -2803,7 +2894,7 @@ function buildMatchIndex(entries) {
2803
2894
  match(method, path, req) {
2804
2895
  const hits = orderCandidates(candidates(method, path));
2805
2896
  for (const hit of hits) {
2806
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2897
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2807
2898
  if (!failure) {
2808
2899
  return { entry: hit.value.entry, params: hit.params };
2809
2900
  }
@@ -2816,7 +2907,7 @@ function buildMatchIndex(entries) {
2816
2907
  for (const hit of hits) {
2817
2908
  if (out.length >= limit)
2818
2909
  break;
2819
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2910
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2820
2911
  if (failure)
2821
2912
  out.push({ entry: hit.value.entry, params: hit.params, failure });
2822
2913
  }
@@ -2826,7 +2917,7 @@ function buildMatchIndex(entries) {
2826
2917
  }
2827
2918
 
2828
2919
  // src/core/scenarios/evaluator.ts
2829
- function compileMatcher(spec) {
2920
+ function compileMatcher2(spec) {
2830
2921
  if (typeof spec === "string")
2831
2922
  return { kind: "exact", value: spec };
2832
2923
  if ("equals" in spec)
@@ -2837,15 +2928,15 @@ function compileMatcher(spec) {
2837
2928
  return { kind: "startsWith", value: spec.startsWith };
2838
2929
  return { kind: "contains", value: spec.contains };
2839
2930
  }
2840
- function compileDim(record) {
2841
- 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)]));
2842
2933
  }
2843
- function compilePredicate(pred) {
2934
+ function compilePredicate2(pred) {
2844
2935
  return {
2845
- ...pred.params && { params: compileDim(pred.params) },
2846
- ...pred.query && { query: compileDim(pred.query) },
2847
- ...pred.headers && { headers: compileDim(pred.headers) },
2848
- ...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) }
2849
2940
  };
2850
2941
  }
2851
2942
  function compileResponse(resp) {
@@ -2874,7 +2965,7 @@ function compileResponse(resp) {
2874
2965
  function compileScenarioRules(rules) {
2875
2966
  return rules.map((rule) => ({
2876
2967
  id: rule.id,
2877
- predicate: compilePredicate(rule.when),
2968
+ predicate: compilePredicate2(rule.when),
2878
2969
  response: compileResponse(rule.response)
2879
2970
  }));
2880
2971
  }
@@ -6926,15 +7017,65 @@ var coerce = {
6926
7017
  date: (arg) => ZodDate.create({ ...arg, coerce: true })
6927
7018
  };
6928
7019
  var NEVER = INVALID;
7020
+ // src/features/webhooks/scheme.ts
7021
+ var DEFAULT_SIGNED_PAYLOAD = "{timestamp}.{body}";
7022
+ var DEFAULT_SIGNATURE_TEMPLATE = "{algorithm}={signature}";
7023
+ var SIGNED_PAYLOAD_PLACEHOLDERS = ["body", "timestamp", "timestampSeconds"];
7024
+ var SIGNATURE_TEMPLATE_PLACEHOLDERS = [
7025
+ "signature",
7026
+ "algorithm",
7027
+ "timestamp",
7028
+ "timestampSeconds"
7029
+ ];
7030
+ var PLACEHOLDER_RE = /\{([A-Za-z][A-Za-z0-9]*)\}/g;
7031
+ var UNKNOWN_PLACEHOLDER_SCAN_RE = /\{[^{}]*\}/g;
7032
+ function unknownPlaceholders(template, allowed) {
7033
+ const seen = new Set;
7034
+ const out = [];
7035
+ for (const match of template.matchAll(UNKNOWN_PLACEHOLDER_SCAN_RE)) {
7036
+ const name = match[0].slice(1, -1);
7037
+ if (name === "")
7038
+ continue;
7039
+ if (allowed.includes(name) || seen.has(name))
7040
+ continue;
7041
+ seen.add(name);
7042
+ out.push(name);
7043
+ }
7044
+ return out;
7045
+ }
7046
+ function hasUnbalancedPlaceholder(template) {
7047
+ const residue = template.replace(UNKNOWN_PLACEHOLDER_SCAN_RE, "");
7048
+ return /\{[A-Za-z]/.test(residue);
7049
+ }
7050
+ function substitute(template, values) {
7051
+ return template.replace(PLACEHOLDER_RE, (match, name) => Object.hasOwn(values, name) ? values[name] : match);
7052
+ }
7053
+ function renderSignedPayload(template, v) {
7054
+ return substitute(template, {
7055
+ body: v.body,
7056
+ timestamp: String(v.timestampMs),
7057
+ timestampSeconds: String(Math.floor(v.timestampMs / 1000))
7058
+ });
7059
+ }
7060
+ function renderSignatureHeader(template, v) {
7061
+ return substitute(template, {
7062
+ signature: v.signature,
7063
+ algorithm: v.algorithm,
7064
+ timestamp: String(v.timestampMs),
7065
+ timestampSeconds: String(Math.floor(v.timestampMs / 1000))
7066
+ });
7067
+ }
7068
+ function timestampUnitFor(scheme) {
7069
+ const combined = `${scheme.signedPayload} ${scheme.signatureTemplate}`;
7070
+ if (combined.includes("{timestamp}"))
7071
+ return "ms";
7072
+ if (combined.includes("{timestampSeconds}"))
7073
+ return "s";
7074
+ return null;
7075
+ }
7076
+
6929
7077
  // src/core/config/schema.ts
6930
7078
  var MatchMethod = exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "*"]);
6931
- var StringMatch = exports_external.union([
6932
- exports_external.string(),
6933
- exports_external.object({ equals: exports_external.string() }).strict(),
6934
- exports_external.object({ regex: exports_external.string() }).strict(),
6935
- exports_external.object({ startsWith: exports_external.string() }).strict(),
6936
- exports_external.object({ contains: exports_external.string() }).strict()
6937
- ]);
6938
7079
  function isUnsafeRegex(pattern) {
6939
7080
  return /\([^)]*[*+{][^)]*\)[*+{]/.test(pattern) || /\([^)]*\|[^)]*\)[*+{]/.test(pattern);
6940
7081
  }
@@ -6942,7 +7083,7 @@ var StringMatchWithRegexGuard = exports_external.union([
6942
7083
  exports_external.string(),
6943
7084
  exports_external.object({ equals: exports_external.string() }).strict(),
6944
7085
  exports_external.object({ regex: exports_external.string() }).strict().refine((v) => !isUnsafeRegex(v.regex), (v) => ({
6945
- 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`
6946
7087
  })),
6947
7088
  exports_external.object({ startsWith: exports_external.string() }).strict(),
6948
7089
  exports_external.object({ contains: exports_external.string() }).strict()
@@ -6955,8 +7096,8 @@ var BodyMatch = exports_external.object({
6955
7096
  var MatchPredicate = exports_external.object({
6956
7097
  method: MatchMethod.default("*"),
6957
7098
  path: exports_external.string().min(1),
6958
- query: exports_external.record(StringMatch).optional(),
6959
- headers: exports_external.record(StringMatch).optional(),
7099
+ query: exports_external.record(StringMatchWithRegexGuard).optional(),
7100
+ headers: exports_external.record(StringMatchWithRegexGuard).optional(),
6960
7101
  body: BodyMatch.optional(),
6961
7102
  priority: exports_external.number().int().default(0)
6962
7103
  }).strict();
@@ -7007,16 +7148,105 @@ var ScenarioRule = exports_external.object({
7007
7148
  response: ScenarioResponse
7008
7149
  }).strict();
7009
7150
  var SECRET_REF_RE = /^(\{\{\s*env\.[A-Z_][A-Z0-9_]*\s*\}\}|file:.+)$/;
7010
- var WebhookSigning = exports_external.object({
7151
+ var HmacSigning = exports_external.object({
7152
+ mode: exports_external.literal("hmac").default("hmac"),
7011
7153
  enabled: exports_external.boolean().default(false),
7012
7154
  algorithm: exports_external.literal("sha256").default("sha256"),
7013
7155
  secretRef: exports_external.string().regex(SECRET_REF_RE, {
7014
7156
  message: "webhook signing.secretRef must be `{{ env.NAME }}` or `file:/path`; inline secrets rejected (S3)"
7015
7157
  }),
7158
+ signedPayload: exports_external.string().min(1).default(DEFAULT_SIGNED_PAYLOAD),
7159
+ signatureTemplate: exports_external.string().min(1).default(DEFAULT_SIGNATURE_TEMPLATE),
7160
+ digestEncoding: exports_external.enum(["hex", "base64"]).default("hex"),
7016
7161
  signatureHeader: exports_external.string().min(1).default("x-mockstar-signature"),
7017
- timestampHeader: exports_external.string().min(1).default("x-mockstar-timestamp"),
7162
+ timestampHeader: exports_external.string().min(1).nullable().default("x-mockstar-timestamp"),
7018
7163
  replayWindowMs: exports_external.number().int().positive().default(300000)
7019
7164
  }).strict();
7165
+ var WebhookSigning = exports_external.preprocess((raw) => raw !== null && typeof raw === "object" && !Array.isArray(raw) && !("mode" in raw) ? { ...raw, mode: "hmac" } : raw, exports_external.discriminatedUnion("mode", [HmacSigning])).superRefine((v, ctx) => {
7166
+ if (typeof v.signedPayload !== "string" || typeof v.signatureTemplate !== "string")
7167
+ return;
7168
+ const fmt = (names) => names.map((n) => `{${n}}`).join(", ");
7169
+ const signedPayloadHasDoubleBrace = v.signedPayload.includes("{{");
7170
+ if (signedPayloadHasDoubleBrace) {
7171
+ ctx.addIssue({
7172
+ code: exports_external.ZodIssueCode.custom,
7173
+ path: ["signedPayload"],
7174
+ message: "signedPayload uses single-brace placeholders (e.g. {body}), not the {{ }} request-template syntax \u2014 did you mean {body} instead of {{ body }}?"
7175
+ });
7176
+ }
7177
+ const signatureTemplateHasDoubleBrace = v.signatureTemplate.includes("{{");
7178
+ if (signatureTemplateHasDoubleBrace) {
7179
+ ctx.addIssue({
7180
+ code: exports_external.ZodIssueCode.custom,
7181
+ path: ["signatureTemplate"],
7182
+ message: "signatureTemplate uses single-brace placeholders (e.g. {signature}), not the {{ }} request-template syntax \u2014 did you mean {signature} instead of {{ signature }}?"
7183
+ });
7184
+ }
7185
+ const signedPayloadHasTemplateLiteral = v.signedPayload.includes("${");
7186
+ if (signedPayloadHasTemplateLiteral) {
7187
+ ctx.addIssue({
7188
+ code: exports_external.ZodIssueCode.custom,
7189
+ path: ["signedPayload"],
7190
+ message: "signedPayload uses single-brace placeholders (e.g. {body}), not JS template-literal syntax \u2014 did you mean {body} instead of ${body}?"
7191
+ });
7192
+ }
7193
+ const signatureTemplateHasTemplateLiteral = v.signatureTemplate.includes("${");
7194
+ if (signatureTemplateHasTemplateLiteral) {
7195
+ ctx.addIssue({
7196
+ code: exports_external.ZodIssueCode.custom,
7197
+ path: ["signatureTemplate"],
7198
+ message: "signatureTemplate uses single-brace placeholders (e.g. {signature}), not JS template-literal syntax \u2014 did you mean {signature} instead of ${signature}?"
7199
+ });
7200
+ }
7201
+ if (!signedPayloadHasDoubleBrace && !signedPayloadHasTemplateLiteral) {
7202
+ const badPayload = unknownPlaceholders(v.signedPayload, SIGNED_PAYLOAD_PLACEHOLDERS);
7203
+ if (badPayload.length > 0) {
7204
+ ctx.addIssue({
7205
+ code: exports_external.ZodIssueCode.custom,
7206
+ path: ["signedPayload"],
7207
+ message: `unknown placeholder(s) ${fmt(badPayload)} \u2014 allowed: ${fmt(SIGNED_PAYLOAD_PLACEHOLDERS)}`
7208
+ });
7209
+ }
7210
+ if (!v.signedPayload.includes("{body}")) {
7211
+ ctx.addIssue({
7212
+ code: exports_external.ZodIssueCode.custom,
7213
+ path: ["signedPayload"],
7214
+ message: "signedPayload must contain {body} \u2014 otherwise the signature covers no request content"
7215
+ });
7216
+ }
7217
+ if (hasUnbalancedPlaceholder(v.signedPayload)) {
7218
+ ctx.addIssue({
7219
+ code: exports_external.ZodIssueCode.custom,
7220
+ path: ["signedPayload"],
7221
+ message: "signedPayload has an unmatched { that looks like an unterminated placeholder \u2014 check for a missing closing brace"
7222
+ });
7223
+ }
7224
+ }
7225
+ if (!signatureTemplateHasDoubleBrace && !signatureTemplateHasTemplateLiteral) {
7226
+ const badTemplate = unknownPlaceholders(v.signatureTemplate, SIGNATURE_TEMPLATE_PLACEHOLDERS);
7227
+ if (badTemplate.length > 0) {
7228
+ ctx.addIssue({
7229
+ code: exports_external.ZodIssueCode.custom,
7230
+ path: ["signatureTemplate"],
7231
+ message: `unknown placeholder(s) ${fmt(badTemplate)} \u2014 allowed: ${fmt(SIGNATURE_TEMPLATE_PLACEHOLDERS)}`
7232
+ });
7233
+ }
7234
+ if (!v.signatureTemplate.includes("{signature}")) {
7235
+ ctx.addIssue({
7236
+ code: exports_external.ZodIssueCode.custom,
7237
+ path: ["signatureTemplate"],
7238
+ message: "signatureTemplate must contain {signature} \u2014 otherwise the signature header carries no digest"
7239
+ });
7240
+ }
7241
+ if (hasUnbalancedPlaceholder(v.signatureTemplate)) {
7242
+ ctx.addIssue({
7243
+ code: exports_external.ZodIssueCode.custom,
7244
+ path: ["signatureTemplate"],
7245
+ message: "signatureTemplate has an unmatched { that looks like an unterminated placeholder \u2014 check for a missing closing brace"
7246
+ });
7247
+ }
7248
+ }
7249
+ });
7020
7250
  var WebhookRetry = exports_external.object({
7021
7251
  attempts: exports_external.number().int().min(1).max(20).default(6),
7022
7252
  backoff: exports_external.array(exports_external.number().int().nonnegative()).default([1000, 2000, 4000, 8000, 16000]),
@@ -7077,7 +7307,7 @@ var MocksFile = exports_external.object({
7077
7307
  var TenantLimits = exports_external.object({
7078
7308
  maxBodyBytes: exports_external.number().int().positive().default(1048576),
7079
7309
  maxResponseBytes: exports_external.number().int().positive().default(1048576),
7080
- requestsPerSecond: exports_external.number().int().positive().default(1000),
7310
+ requestsPerSecond: exports_external.number().int().positive().default(1e4),
7081
7311
  journalSize: exports_external.number().int().positive().default(1000)
7082
7312
  }).strict();
7083
7313
  var TenantConfig = exports_external.object({
@@ -9021,6 +9251,77 @@ function installProcessHandlers(opts) {
9021
9251
  process.off("uncaughtException", excHandler);
9022
9252
  };
9023
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
+
9024
9325
  // src/core/journal/ring-buffer.ts
9025
9326
  class RingBuffer {
9026
9327
  capacity;
@@ -11502,7 +11803,7 @@ function adminRouter(deps) {
11502
11803
  entryId,
11503
11804
  id: spec.id,
11504
11805
  method: spec.method,
11505
- signing: spec.signing ? { enabled: spec.signing.enabled, algorithm: spec.signing.algorithm } : null,
11806
+ signing: spec.signing ? { mode: spec.signing.mode, enabled: spec.signing.enabled, algorithm: spec.signing.algorithm } : null,
11506
11807
  retry: { attempts: spec.retry.attempts },
11507
11808
  circuit: spec.circuit,
11508
11809
  timeoutMs: spec.timeoutMs,
@@ -11611,7 +11912,11 @@ var PRIVATE_IPV4_RANGES = [
11611
11912
  [127, 0, 0, 8],
11612
11913
  [169, 254, 0, 16],
11613
11914
  [100, 64, 0, 10],
11614
- [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]
11615
11920
  ];
11616
11921
  function validateUpstreamUrl(raw2, opts = {}) {
11617
11922
  const allowedSchemes = opts.allowedSchemes ?? ["https"];
@@ -11674,12 +11979,49 @@ async function validateUpstreamUrlResolved(raw2, opts = {}) {
11674
11979
  });
11675
11980
  return parsed;
11676
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
+ }
11677
12019
  function isPrivateHost(hostname) {
11678
12020
  const stripped = hostname.replace(/^\[/, "").replace(/\]$/, "");
11679
12021
  const lowered = stripped.toLowerCase();
11680
12022
  if (lowered === "localhost" || lowered === "ip6-localhost" || lowered === "ip6-loopback")
11681
12023
  return true;
11682
- if (lowered === "::1" || lowered.startsWith("fe80:") || lowered.startsWith("fc") || lowered.startsWith("fd")) {
12024
+ if (isIpLiteral(stripped) && isPrivateIpv6(lowered)) {
11683
12025
  return true;
11684
12026
  }
11685
12027
  const ipv4MappedDotted = lowered.match(/^::ffff:([0-9.]+)$/);
@@ -11700,6 +12042,75 @@ function isPrivateHost(hostname) {
11700
12042
  }
11701
12043
  return false;
11702
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
+ }
11703
12114
  function isPrivateIpv4(ip) {
11704
12115
  const parts = ip.split(".").map((p3) => Number.parseInt(p3, 10));
11705
12116
  if (parts.length !== 4 || parts.some((p3) => Number.isNaN(p3) || p3 < 0 || p3 > 255))
@@ -11711,16 +12122,13 @@ function isPrivateIpv4(ip) {
11711
12122
  }
11712
12123
  return false;
11713
12124
  }
11714
- function matchesIpv4(a2, _b, _c, _d, ra2, _rb, _rc, mask) {
11715
- if (mask === 8)
11716
- return a2 === ra2;
11717
- if (mask === 16)
11718
- return a2 === ra2 && _b === _rb;
11719
- if (mask === 12)
11720
- return a2 === ra2 && (_b & 240) === (_rb & 240);
11721
- if (mask === 10)
11722
- return a2 === ra2 && (_b & 192) === (_rb & 192);
11723
- 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;
11724
12132
  }
11725
12133
 
11726
12134
  // src/features/pass-through.ts
@@ -11729,12 +12137,13 @@ async function renderPassThrough(entry, ctx, opts) {
11729
12137
  throw new Error(`renderPassThrough called for non-passthrough entry '${entry.id}'`);
11730
12138
  }
11731
12139
  const spec = entry.response;
12140
+ const validationOpts = {
12141
+ allowedSchemes: ["https", "http"],
12142
+ allowPrivateUpstreams: opts.allowPrivateUpstreams
12143
+ };
11732
12144
  let upstreamUrl;
11733
12145
  try {
11734
- upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, {
11735
- allowedSchemes: ["https", "http"],
11736
- allowPrivateUpstreams: opts.allowPrivateUpstreams
11737
- });
12146
+ upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, validationOpts);
11738
12147
  } catch (err) {
11739
12148
  opts.logger.error({
11740
12149
  event: "passthrough_url_rejected",
@@ -11761,14 +12170,16 @@ async function renderPassThrough(entry, ctx, opts) {
11761
12170
  const controller = new AbortController;
11762
12171
  const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
11763
12172
  timer.unref?.();
12173
+ const bodyCap = ctx.req.method === "GET" || ctx.req.method === "HEAD" ? null : capRequestBodyStream(ctx, opts.maxBodyBytes);
11764
12174
  const started = performance.now();
11765
12175
  try {
11766
- const upstreamRes = await fetch(targetUrl, {
12176
+ const requestBody = bodyCap ? await ctx.req.raw.arrayBuffer() : null;
12177
+ const { response: upstreamRes } = await fetchWithRedirectGuard(targetUrl, {
11767
12178
  method: ctx.req.method,
11768
12179
  headers,
11769
- body: ctx.req.method === "GET" || ctx.req.method === "HEAD" ? undefined : await ctx.req.raw.arrayBuffer(),
12180
+ body: requestBody,
11770
12181
  signal: controller.signal
11771
- });
12182
+ }, validationOpts);
11772
12183
  clearTimeout(timer);
11773
12184
  return new Response(upstreamRes.body, {
11774
12185
  status: upstreamRes.status,
@@ -11776,7 +12187,23 @@ async function renderPassThrough(entry, ctx, opts) {
11776
12187
  });
11777
12188
  } catch (err) {
11778
12189
  clearTimeout(timer);
12190
+ if (bodyCap?.tooLarge()) {
12191
+ return bodyTooLargeResponse(opts.maxBodyBytes);
12192
+ }
11779
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
+ }
11780
12207
  const aborted = err instanceof DOMException && err.name === "AbortError";
11781
12208
  opts.logger.error({
11782
12209
  event: "passthrough_upstream_error",
@@ -12262,12 +12689,39 @@ class BoundedRetryQueue {
12262
12689
  #cap;
12263
12690
  #onDropped;
12264
12691
  #onSizeChange;
12692
+ #timers = new Map;
12693
+ #stopped = false;
12265
12694
  constructor(opts = {}) {
12266
12695
  this.#pq = new PQueue({ concurrency: opts.concurrency ?? DEFAULT_CONCURRENCY });
12267
12696
  this.#cap = opts.cap ?? DEFAULT_CAP;
12268
12697
  this.#onDropped = opts.onDropped;
12269
12698
  this.#onSizeChange = opts.onSizeChange;
12270
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
+ }
12271
12725
  #fireSizeChange() {
12272
12726
  if (!this.#onSizeChange)
12273
12727
  return;
@@ -12286,7 +12740,14 @@ class BoundedRetryQueue {
12286
12740
  inflight() {
12287
12741
  return this.#pq.pending;
12288
12742
  }
12743
+ liveTimerCount() {
12744
+ return this.#timers.size;
12745
+ }
12289
12746
  enqueue(req) {
12747
+ if (this.#stopped) {
12748
+ this.#dropDelivery(req);
12749
+ return;
12750
+ }
12290
12751
  while (this.size() >= this.#cap) {
12291
12752
  const oldest = this.#waiting.shift();
12292
12753
  if (oldest) {
@@ -12319,7 +12780,17 @@ class BoundedRetryQueue {
12319
12780
  if (attempt > 1) {
12320
12781
  const baseMs = req.retry.backoff[attempt - 2] ?? 0;
12321
12782
  const delayMs = applyJitter(baseMs, req.retry.jitterRatio);
12322
- 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
+ }
12323
12794
  }
12324
12795
  const gate = req.circuitGate();
12325
12796
  if (gate === "open") {
@@ -12361,7 +12832,7 @@ class BoundedRetryQueue {
12361
12832
  lastError = errorToString(err);
12362
12833
  req.onAttempt({
12363
12834
  attempt,
12364
- outcome: attempt === req.retry.attempts ? "failed" : "success",
12835
+ outcome: attempt === req.retry.attempts ? "failed" : "retrying",
12365
12836
  durationUs: 0,
12366
12837
  error: lastError
12367
12838
  });
@@ -12399,11 +12870,6 @@ function applyJitter(baseMs, ratio) {
12399
12870
  const delta = baseMs * ratio;
12400
12871
  return Math.max(0, Math.round(baseMs - delta + Math.random() * 2 * delta));
12401
12872
  }
12402
- function sleep(ms) {
12403
- if (ms <= 0)
12404
- return Promise.resolve();
12405
- return new Promise((resolve4) => setTimeout(resolve4, ms));
12406
- }
12407
12873
  function errorToString(err) {
12408
12874
  if (err instanceof Error)
12409
12875
  return `${err.name}: ${err.message}`;
@@ -12523,6 +12989,13 @@ class DeliveryEventRegistry {
12523
12989
  this.#completed.delete(id);
12524
12990
  }
12525
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
+ }
12526
12999
  pendingCount() {
12527
13000
  return this.#pending.size;
12528
13001
  }
@@ -12532,6 +13005,25 @@ class DeliveryEventRegistry {
12532
13005
  }
12533
13006
  // src/features/webhooks/journal.ts
12534
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
+
12535
13027
  class WebhookJournalRegistry {
12536
13028
  #buffers = new Map;
12537
13029
  #capacityFor;
@@ -12541,11 +13033,12 @@ class WebhookJournalRegistry {
12541
13033
  this.#journalFile = opts.journalFile;
12542
13034
  }
12543
13035
  record(entry) {
12544
- const buf = this.#bufferFor(entry.tenant);
12545
- buf.push(entry);
13036
+ const redacted = redactEntry(entry);
13037
+ const buf = this.#bufferFor(redacted.tenant);
13038
+ buf.push(redacted);
12546
13039
  if (this.#journalFile) {
12547
13040
  try {
12548
- appendFileSync(this.#journalFile, `${JSON.stringify(entry)}
13041
+ appendFileSync(this.#journalFile, `${JSON.stringify(redacted)}
12549
13042
  `);
12550
13043
  } catch (err) {
12551
13044
  console.warn(`[mockstar] webhook journal file write failed: ${err.message ?? err}`);
@@ -12578,9 +13071,33 @@ class WebhookJournalRegistry {
12578
13071
  }
12579
13072
  // src/features/webhooks/signing.ts
12580
13073
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
12581
- function signPayload(rawBody, secret, timestampMs) {
12582
- const stringToSign = `${timestampMs}.${rawBody}`;
12583
- return createHmac("sha256", secret).update(stringToSign, "utf8").digest("hex");
13074
+ var LEGACY_SCHEME = Object.freeze({
13075
+ signedPayload: DEFAULT_SIGNED_PAYLOAD,
13076
+ signatureTemplate: DEFAULT_SIGNATURE_TEMPLATE,
13077
+ digestEncoding: "hex",
13078
+ algorithm: "sha256"
13079
+ });
13080
+ function signPayload(rawBody, secret, timestampMs, scheme = LEGACY_SCHEME) {
13081
+ const stringToSign = renderSignedPayload(scheme.signedPayload, { body: rawBody, timestampMs });
13082
+ return createHmac(scheme.algorithm, secret).update(stringToSign, "utf8").digest(scheme.digestEncoding);
13083
+ }
13084
+ function verifySignature(rawBody, secret, timestampMs, signature, scheme = LEGACY_SCHEME) {
13085
+ try {
13086
+ const expected = signPayload(rawBody, secret, timestampMs, scheme);
13087
+ if (expected.length !== signature.length)
13088
+ return false;
13089
+ const a2 = Buffer.from(expected, scheme.digestEncoding);
13090
+ const b2 = Buffer.from(signature, scheme.digestEncoding);
13091
+ if (a2.length !== b2.length || a2.length === 0)
13092
+ return false;
13093
+ return timingSafeEqual2(a2, b2);
13094
+ } catch {
13095
+ return false;
13096
+ }
13097
+ }
13098
+ function withinReplayWindow(timestampMs, windowMs, nowMs = Date.now(), futureSkewMs = 60000) {
13099
+ const delta = nowMs - timestampMs;
13100
+ return delta <= windowMs && delta >= -futureSkewMs;
12584
13101
  }
12585
13102
  function resolveSecret(secretRef) {
12586
13103
  const envMatch = secretRef.match(/^\{\{\s*env\.([A-Z_][A-Z0-9_]*)\s*\}\}$/);
@@ -12645,14 +13162,13 @@ function dispatchWebhooks(deps, input) {
12645
13162
  }
12646
13163
  async function performAttempt(spec, input, _deps) {
12647
13164
  const attemptStart = performance.now();
12648
- let urlString;
12649
13165
  const headerUrl = _deps.allowWebhookUrlHeader && spec.acceptHeaderOverride ? input.requestHeaders.get("x-mockstar-webhook-url") : undefined;
12650
- urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12651
- const allowedSchemes = spec.allowHttp ? ["http", "https"] : ["https"];
12652
- await validateUpstreamUrlResolved(urlString, {
12653
- allowedSchemes,
13166
+ const urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
13167
+ const validationOpts = {
13168
+ allowedSchemes: spec.allowHttp ? ["http", "https"] : ["https"],
12654
13169
  allowPrivateUpstreams: spec.allowPrivateNetworks
12655
- });
13170
+ };
13171
+ const validatedUrl = await validateUpstreamUrlResolved(urlString, validationOpts);
12656
13172
  const renderedHeaders = new Headers;
12657
13173
  for (const [key, tmpl] of spec.headers) {
12658
13174
  renderedHeaders.set(key, tmpl.render(input.templateContext));
@@ -12661,23 +13177,43 @@ async function performAttempt(spec, input, _deps) {
12661
13177
  if (spec.signing?.enabled) {
12662
13178
  const secret = resolveSecret(spec.signing.secretRef);
12663
13179
  const timestampMs = Date.now();
12664
- const signature = signPayload(rawBody, secret, timestampMs);
12665
- renderedHeaders.set(spec.signing.signatureHeader, `${spec.signing.algorithm}=${signature}`);
12666
- renderedHeaders.set(spec.signing.timestampHeader, String(timestampMs));
13180
+ const scheme = {
13181
+ signedPayload: spec.signing.signedPayload,
13182
+ signatureTemplate: spec.signing.signatureTemplate,
13183
+ digestEncoding: spec.signing.digestEncoding,
13184
+ algorithm: spec.signing.algorithm
13185
+ };
13186
+ const signature = signPayload(rawBody, secret, timestampMs, scheme);
13187
+ renderedHeaders.set(spec.signing.signatureHeader, renderSignatureHeader(scheme.signatureTemplate, {
13188
+ signature,
13189
+ algorithm: scheme.algorithm,
13190
+ timestampMs
13191
+ }));
13192
+ const unit = timestampUnitFor(scheme);
13193
+ if (unit !== null && spec.signing.timestampHeader !== null) {
13194
+ const value = unit === "s" ? Math.floor(timestampMs / 1000) : timestampMs;
13195
+ renderedHeaders.set(spec.signing.timestampHeader, String(value));
13196
+ }
12667
13197
  }
12668
13198
  if (!renderedHeaders.has("x-mockstar-delivery-id")) {
12669
13199
  renderedHeaders.set("x-mockstar-delivery-id", input.triggerRequestId);
12670
13200
  }
12671
13201
  const signal = AbortSignal.timeout(spec.timeoutMs);
12672
13202
  let response;
13203
+ let finalUrl;
12673
13204
  try {
12674
- response = await fetch(urlString, {
13205
+ const result = await fetchWithRedirectGuard(validatedUrl, {
12675
13206
  method: spec.method,
12676
13207
  headers: renderedHeaders,
12677
- body: spec.method === "GET" || spec.method === "DELETE" ? undefined : rawBody,
13208
+ body: spec.method === "GET" || spec.method === "DELETE" ? null : rawBody,
12678
13209
  signal
12679
- });
13210
+ }, validationOpts);
13211
+ response = result.response;
13212
+ finalUrl = result.finalUrl;
12680
13213
  } catch (err) {
13214
+ if (err instanceof UrlValidationError) {
13215
+ throw new Error(`webhook delivery redirect rejected: ${err.message}`);
13216
+ }
12681
13217
  throw new Error(`webhook delivery network error: ${err.message ?? err}`);
12682
13218
  }
12683
13219
  if (!isSuccessStatus(response.status, spec.expectResponse)) {
@@ -12692,7 +13228,7 @@ async function performAttempt(spec, input, _deps) {
12692
13228
  return {
12693
13229
  httpStatus: response.status,
12694
13230
  durationUs: Math.round((performance.now() - attemptStart) * 1000),
12695
- resolvedUrl: urlString
13231
+ resolvedUrl: finalUrl.href
12696
13232
  };
12697
13233
  }
12698
13234
  function isSuccessStatus(status, expect) {
@@ -12743,6 +13279,8 @@ function makeDeliveryId() {
12743
13279
  return crypto.randomUUID();
12744
13280
  }
12745
13281
  // src/server.ts
13282
+ var UNKNOWN_TENANT_BUCKET = ":unknown:";
13283
+ var DEFAULT_REQUESTS_PER_SECOND = 1e4;
12746
13284
  function createServer(opts) {
12747
13285
  const logger = opts.logger ?? createLogger({ deterministic: opts.deterministic });
12748
13286
  const metrics = new Metrics;
@@ -12750,6 +13288,7 @@ function createServer(opts) {
12750
13288
  const snap = opts.holder.get().tenants.get(tenant);
12751
13289
  return snap?.limits.journalSize ?? 1000;
12752
13290
  });
13291
+ const rateLimiter = new TenantRateLimiter({ now: opts.rateLimiterNow });
12753
13292
  const webhookJournal = new WebhookJournalRegistry((tenant) => {
12754
13293
  const snap = opts.holder.get().tenants.get(tenant);
12755
13294
  return snap?.limits.journalSize ?? 1000;
@@ -12860,6 +13399,7 @@ function createServer(opts) {
12860
13399
  clock,
12861
13400
  journal,
12862
13401
  metrics,
13402
+ rateLimiter,
12863
13403
  handlerTimeoutMs,
12864
13404
  genRequestId,
12865
13405
  webhookJournal,
@@ -12868,15 +13408,22 @@ function createServer(opts) {
12868
13408
  circuitFor,
12869
13409
  allowWebhookUrlHeader
12870
13410
  }));
13411
+ const stopWebhooks = () => {
13412
+ for (const q3 of webhookQueues.values())
13413
+ q3.stop();
13414
+ webhookEvents.stop();
13415
+ };
12871
13416
  return {
12872
13417
  hono: app,
12873
13418
  journal,
12874
13419
  metrics,
13420
+ rateLimiter,
12875
13421
  ready,
12876
13422
  uninstallCrashHandlers,
12877
13423
  webhookJournal,
12878
13424
  webhookEvents,
12879
- replayWebhook
13425
+ replayWebhook,
13426
+ stopWebhooks
12880
13427
  };
12881
13428
  }
12882
13429
  async function dispatch(ctx, deps) {
@@ -12888,28 +13435,35 @@ async function dispatch(ctx, deps) {
12888
13435
  const startedUs = performance.now() * 1000;
12889
13436
  const matchPath = effectivePath(ctx);
12890
13437
  const method = ctx.req.method;
13438
+ const observedTenant = tenantSnap ? tenant : UNKNOWN_TENANT_BUCKET;
12891
13439
  let response;
12892
13440
  let matchedMockId = null;
12893
13441
  let scenarioId;
12894
13442
  let scenarioMissReason;
12895
13443
  let webhookTrigger;
12896
13444
  try {
12897
- 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) {
12898
13450
  response = notFoundUnknownTenant(tenant, method, matchPath);
12899
13451
  } else {
12900
13452
  const contentLength = Number.parseInt(ctx.req.header("content-length") ?? "0", 10);
12901
13453
  if (contentLength > tenantSnap.limits.maxBodyBytes) {
12902
- response = new Response(JSON.stringify({ error: "body_too_large", limit: tenantSnap.limits.maxBodyBytes }), {
12903
- status: 413,
12904
- headers: { "content-type": "application/json" }
12905
- });
13454
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
12906
13455
  } else {
12907
- const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps);
12908
- response = result.response;
12909
- matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
12910
- scenarioId = result.scenarioId;
12911
- scenarioMissReason = result.scenarioMissReason;
12912
- 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
+ }
12913
13467
  }
12914
13468
  }
12915
13469
  } catch (err) {
@@ -12930,7 +13484,7 @@ async function dispatch(ctx, deps) {
12930
13484
  const durationUs = Math.round(performance.now() * 1000 - startedUs);
12931
13485
  const entry = {
12932
13486
  timestamp: Date.now(),
12933
- tenant,
13487
+ tenant: observedTenant,
12934
13488
  requestId,
12935
13489
  method,
12936
13490
  path: matchPath,
@@ -12942,15 +13496,15 @@ async function dispatch(ctx, deps) {
12942
13496
  };
12943
13497
  deps.journal.record(entry);
12944
13498
  deps.metrics.incCounter("mockstar_requests_total", {
12945
- tenant,
13499
+ tenant: observedTenant,
12946
13500
  method,
12947
13501
  status: String(response.status),
12948
13502
  matched: matchedMockId ? "1" : "0"
12949
13503
  });
12950
- deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant }, durationUs);
13504
+ deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant: observedTenant }, durationUs);
12951
13505
  deps.logger.info({
12952
13506
  event: "request",
12953
- tenant,
13507
+ tenant: observedTenant,
12954
13508
  method,
12955
13509
  path: matchPath,
12956
13510
  status: response.status,
@@ -12999,9 +13553,8 @@ async function dispatch(ctx, deps) {
12999
13553
  });
13000
13554
  return response;
13001
13555
  }
13002
- async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps) {
13556
+ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, body) {
13003
13557
  const url = new URL(ctx.req.url);
13004
- const body = await safeParseBody(ctx);
13005
13558
  const req = {
13006
13559
  query: new Map(Array.from(url.searchParams)),
13007
13560
  headers: new Map(Array.from(ctx.req.raw.headers).map(([k2, v3]) => [k2.toLowerCase(), v3])),
@@ -13113,7 +13666,8 @@ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap,
13113
13666
  case "passthrough":
13114
13667
  response = await renderPassThrough(hit.entry, ctx, {
13115
13668
  allowPrivateUpstreams: tenantSnap.allowPrivateUpstreams,
13116
- logger: deps.logger
13669
+ logger: deps.logger,
13670
+ maxBodyBytes: tenantSnap.limits.maxBodyBytes
13117
13671
  });
13118
13672
  break;
13119
13673
  }
@@ -13131,20 +13685,27 @@ function notFoundUnknownTenant(tenant, method, path) {
13131
13685
  headers: { "content-type": "application/json" }
13132
13686
  });
13133
13687
  }
13134
- async function safeParseBody(ctx) {
13688
+ async function safeParseBody(ctx, maxBodyBytes) {
13135
13689
  const method = ctx.req.method;
13136
13690
  if (method === "GET" || method === "HEAD")
13137
- return null;
13691
+ return { ok: true, body: null };
13138
13692
  const contentType = ctx.req.header("content-type") ?? "";
13139
13693
  if (!contentType.includes("json"))
13140
- return null;
13694
+ return { ok: true, body: null };
13695
+ const { tooLarge } = capRequestBodyStream(ctx, maxBodyBytes);
13141
13696
  try {
13142
13697
  const text = await ctx.req.text();
13143
13698
  if (text.length === 0)
13144
- return null;
13145
- return JSON.parse(text);
13146
- } catch {
13147
- 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;
13148
13709
  }
13149
13710
  }
13150
13711
  function createRequestIdGenerator(deterministic) {
@@ -13196,6 +13757,7 @@ async function launch(opts) {
13196
13757
  holder,
13197
13758
  async stop() {
13198
13759
  watcher?.stop();
13760
+ server.stopWebhooks();
13199
13761
  server.uninstallCrashHandlers();
13200
13762
  }
13201
13763
  };
@@ -13712,10 +14274,10 @@ function convertOpenApi(doc, opts = {}) {
13712
14274
  if (!doc || typeof doc !== "object") {
13713
14275
  throw new OpenApiImportError("OpenAPI document root must be an object");
13714
14276
  }
13715
- const refs = findRefs(doc);
13716
- for (const ref of refs) {
14277
+ const refs = findRefs(doc, "$");
14278
+ for (const { ref, path } of refs) {
13717
14279
  if (!ref.startsWith("#")) {
13718
- 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 });
13719
14281
  }
13720
14282
  }
13721
14283
  const openapi = doc;
@@ -13762,18 +14324,39 @@ function convertOpenApi(doc, opts = {}) {
13762
14324
  }
13763
14325
  return entries;
13764
14326
  }
13765
- function findRefs(value, acc = []) {
14327
+ function findRefs(value, path, acc = []) {
13766
14328
  if (value === null || typeof value !== "object")
13767
14329
  return acc;
13768
14330
  if (Array.isArray(value)) {
13769
- for (const v3 of value)
13770
- findRefs(v3, acc);
14331
+ value.forEach((v3, i2) => findRefs(v3, `${path}[${i2}]`, acc));
13771
14332
  return acc;
13772
14333
  }
13773
- for (const [k2, v3] of Object.entries(value)) {
13774
- if (k2 === "$ref" && typeof v3 === "string")
13775
- acc.push(v3);
13776
- 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);
13777
14360
  }
13778
14361
  return acc;
13779
14362
  }
@@ -13781,7 +14364,7 @@ function pickExemplar(op, doc) {
13781
14364
  const responses = op.responses ?? {};
13782
14365
  const preferred = ["200", "201", "202", "204", "default"];
13783
14366
  for (const code of preferred) {
13784
- const res = responses[code];
14367
+ const res = responses[code] ?? (code === "default" ? undefined : responses[`${code[0]}XX`]);
13785
14368
  if (!res)
13786
14369
  continue;
13787
14370
  const status = code === "default" ? 200 : Number.parseInt(code, 10);
@@ -14481,7 +15064,7 @@ init_port_bind();
14481
15064
  // src/features/proxy/install-journal.ts
14482
15065
  init_types();
14483
15066
  import { createHash } from "crypto";
14484
- 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";
14485
15068
  import { dirname as dirname2 } from "path";
14486
15069
  async function appendStep(path, step) {
14487
15070
  await mkdir3(dirname2(path), { recursive: true });
@@ -14518,7 +15101,7 @@ async function* reverseSteps(path) {
14518
15101
  }
14519
15102
  }
14520
15103
  async function clearJournal(path) {
14521
- await rm2(path, { force: true });
15104
+ await rm3(path, { force: true });
14522
15105
  }
14523
15106
  async function journalFacts(path) {
14524
15107
  let exists = false;
@@ -14587,10 +15170,10 @@ var reverseCommandImpls = {
14587
15170
  });
14588
15171
  },
14589
15172
  remove_file: async ({ path }) => {
14590
- await rm2(path, { force: true });
15173
+ await rm3(path, { force: true });
14591
15174
  },
14592
15175
  remove_dir: async ({ path }) => {
14593
- await rm2(path, { recursive: true, force: true });
15176
+ await rm3(path, { recursive: true, force: true });
14594
15177
  },
14595
15178
  revert_file: async ({ path, originalContent }) => {
14596
15179
  const { writeFile: writeFile7 } = await import("fs/promises");
@@ -14615,7 +15198,7 @@ var reverseCommandImpls = {
14615
15198
  await runPrivileged2(["launchctl", "unload", "-w", plistPath]).catch(() => {
14616
15199
  return;
14617
15200
  });
14618
- await rm2(plistPath, { force: true });
15201
+ await rm3(plistPath, { force: true });
14619
15202
  },
14620
15203
  noop: async () => {}
14621
15204
  };
@@ -14654,6 +15237,7 @@ init_dns();
14654
15237
  init_types();
14655
15238
 
14656
15239
  // src/features/proxy/cli.ts
15240
+ init_types();
14657
15241
  async function dispatchProxyCommand(argv) {
14658
15242
  const [sub, ...rest] = argv;
14659
15243
  if (!sub || sub === "--help" || sub === "help") {
@@ -14726,9 +15310,23 @@ async function install(argv) {
14726
15310
  }
14727
15311
  });
14728
15312
  mutations.push(...await buildDnsMutations(config));
14729
- mutations.push(portBindMutation({
14730
- binaryPath: process.argv[0] ?? "/usr/bin/env"
14731
- }));
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
+ }
14732
15330
  try {
14733
15331
  const { applied } = await atomicInstall(journalPath, mutations, {
14734
15332
  onStep: (step) => process.stdout.write(` [${step.step}] ${step.action}
@@ -14868,6 +15466,9 @@ function defaultConfigPath() {
14868
15466
  function defaultJournalPath() {
14869
15467
  return join7(homedir(), ".mockstar", "install-state.json");
14870
15468
  }
15469
+ function resolveAllowInterpreterGrant(argv, env) {
15470
+ return argv.includes(ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG) || env[ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV] === "1";
15471
+ }
14871
15472
  function pickFlag(args, name) {
14872
15473
  const prefixed = args.find((a2) => a2.startsWith(`${name}=`));
14873
15474
  if (prefixed)
@@ -14897,6 +15498,13 @@ function proxyHelp() {
14897
15498
  "Subcommands:",
14898
15499
  " install Install local CA + DNS + port-443 capability; journaled for clean uninstall.",
14899
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).`,
14900
15508
  " uninstall Reverse every journaled install mutation (LIFO).",
14901
15509
  " start Run the HTTPS proxy (requires prior install).",
14902
15510
  " Flags: --config=<path>",
@@ -14914,7 +15522,7 @@ function proxyHelp() {
14914
15522
  }
14915
15523
 
14916
15524
  // src/version.ts
14917
- var MOCKSTAR_VERSION = "0.2.2";
15525
+ var MOCKSTAR_VERSION = "0.4.0";
14918
15526
 
14919
15527
  // src/cli.ts
14920
15528
  function parseArgs(argv) {