supbuddy 3.0.11 → 3.0.12

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 (2) hide show
  1. package/dist/daemon/worker.cjs +442 -126
  2. package/package.json +1 -1
@@ -33,11 +33,11 @@ const require$$1$1 = require("querystring");
33
33
  const require$$2 = require("timers");
34
34
  const require$$6$2 = require("ws");
35
35
  const fs = require("fs/promises");
36
+ const net$1 = require("net");
36
37
  const tls$1 = require("tls");
37
38
  const child_process = require("child_process");
38
39
  const util$1 = require("util");
39
40
  const nodeProcess = require("node:process");
40
- const net$1 = require("net");
41
41
  const url = require("url");
42
42
  const require$$0$2 = require("buffer");
43
43
  const dgram$1 = require("dgram");
@@ -26735,7 +26735,8 @@ function buildCaddyfileContent(mappings, settings, options = {}) {
26735
26735
 
26736
26736
  # Admin API endpoint
26737
26737
  {
26738
- admin off
26738
+ # Admin API stays on even with no sites: reloads (mappings added while running) must reach localhost:2019 — 'admin off' here deadlocked the proxy (reload impossible → CA never generated).
26739
+ admin localhost:2019
26739
26740
  }
26740
26741
  `;
26741
26742
  return emptyConfig;
@@ -26776,9 +26777,6 @@ function buildCaddyfileContent(mappings, settings, options = {}) {
26776
26777
  lines.push(" # Headers for proper proxy behavior");
26777
26778
  lines.push(" header_up X-Real-IP {remote_host}");
26778
26779
  lines.push(" header_up X-Forwarded-For {remote_host}");
26779
- lines.push("");
26780
- lines.push(" # Override Origin for WebSocket/HMR to pass Next.js origin check");
26781
- lines.push(` header_up Origin http://${upstreamHostFor(mapping)}:${mapping.port}`);
26782
26780
  lines.push(" }");
26783
26781
  lines.push("");
26784
26782
  lines.push(" # Enable JSON access logging for request monitoring");
@@ -26817,7 +26815,6 @@ function buildCaddyfileContent(mappings, settings, options = {}) {
26817
26815
  lines.push(" flush_interval -1");
26818
26816
  lines.push(" header_up X-Real-IP {remote_host}");
26819
26817
  lines.push(" header_up X-Forwarded-For {remote_host}");
26820
- lines.push(` header_up Origin http://${upstreamHostFor(mapping)}:${mapping.port}`);
26821
26818
  lines.push(" }");
26822
26819
  lines.push(" log {");
26823
26820
  lines.push(" output stderr");
@@ -28536,19 +28533,48 @@ function probeCaddyTls(opts) {
28536
28533
  });
28537
28534
  });
28538
28535
  }
28539
- function decideSelfHeal(state, probeHealthy, now, cfg) {
28536
+ function probeCaddyAdmin(timeoutMs = 1e3) {
28537
+ return new Promise((resolve) => {
28538
+ const socket2 = net$1.createConnection({ host: "127.0.0.1", port: 2019 });
28539
+ const timeout = setTimeout(() => {
28540
+ socket2.destroy();
28541
+ resolve(false);
28542
+ }, timeoutMs);
28543
+ socket2.on("connect", () => {
28544
+ clearTimeout(timeout);
28545
+ socket2.end();
28546
+ resolve(true);
28547
+ });
28548
+ socket2.on("error", () => {
28549
+ clearTimeout(timeout);
28550
+ resolve(false);
28551
+ });
28552
+ });
28553
+ }
28554
+ function decideSelfHeal(state, probeHealthy, adminReachable, now, cfg) {
28540
28555
  if (probeHealthy) {
28541
- return { reload: false, state: { consecutiveFailures: 0, lastReloadAt: state.lastReloadAt } };
28556
+ return {
28557
+ action: "none",
28558
+ state: { consecutiveFailures: 0, lastReloadAt: state.lastReloadAt, reloadFailures: 0 }
28559
+ };
28542
28560
  }
28543
28561
  const failures = state.consecutiveFailures + 1;
28544
28562
  const cooledDown = state.lastReloadAt === null || now - state.lastReloadAt >= cfg.reloadCooldownMs;
28545
- const reload = failures >= cfg.failuresBeforeReload && cooledDown;
28563
+ const shouldAct = failures >= cfg.failuresBeforeReload && cooledDown;
28564
+ if (!shouldAct) {
28565
+ return {
28566
+ action: "none",
28567
+ state: {
28568
+ consecutiveFailures: failures,
28569
+ lastReloadAt: state.lastReloadAt,
28570
+ reloadFailures: state.reloadFailures
28571
+ }
28572
+ };
28573
+ }
28574
+ const action = !adminReachable || state.reloadFailures >= 2 ? "restart" : "reload";
28546
28575
  return {
28547
- reload,
28548
- state: {
28549
- consecutiveFailures: reload ? 0 : failures,
28550
- lastReloadAt: reload ? now : state.lastReloadAt
28551
- }
28576
+ action,
28577
+ state: { consecutiveFailures: 0, lastReloadAt: now, reloadFailures: state.reloadFailures }
28552
28578
  };
28553
28579
  }
28554
28580
  const DEFAULT_HEALTH_MONITOR_CONFIG = {
@@ -28569,10 +28595,10 @@ function pickProbeTarget() {
28569
28595
  return active ? { servername: active.domain, port } : null;
28570
28596
  }
28571
28597
  let monitorTimer = null;
28572
- let healState = { consecutiveFailures: 0, lastReloadAt: null };
28598
+ let healState = { consecutiveFailures: 0, lastReloadAt: null, reloadFailures: 0 };
28573
28599
  async function healthTick(cfg) {
28574
28600
  if (!isCaddyRunning()) {
28575
- healState = { consecutiveFailures: 0, lastReloadAt: healState.lastReloadAt };
28601
+ healState = { consecutiveFailures: 0, lastReloadAt: healState.lastReloadAt, reloadFailures: 0 };
28576
28602
  if (proxyExpectedRunning() && !isCaddyStartInProgress()) {
28577
28603
  void caddySupervisor.requestRestart("health-monitor");
28578
28604
  }
@@ -28587,20 +28613,35 @@ async function healthTick(cfg) {
28587
28613
  timeoutMs: cfg.probeTimeoutMs
28588
28614
  });
28589
28615
  if (probe.ok) caddySupervisor.reset();
28590
- const decision = decideSelfHeal(healState, probe.ok, Date.now(), cfg);
28616
+ const adminReachable = probe.ok ? true : await probeCaddyAdmin();
28617
+ const decision = decideSelfHeal(healState, probe.ok, adminReachable, Date.now(), cfg);
28591
28618
  healState = decision.state;
28592
- if (decision.reload) {
28619
+ if (decision.action === "restart") {
28593
28620
  console.warn(
28594
- `[CaddyHealth] TLS probe to ${target.servername}:${target.port} failing (${probe.reason}); reloading Caddy to self-heal`
28621
+ `[CaddyHealth] TLS probe to ${target.servername}:${target.port} failing (${probe.reason}) and Caddy is wedged (adminReachable=${adminReachable}, reloadFailures=${healState.reloadFailures}); restarting Caddy to self-heal`
28595
28622
  );
28596
- await reloadCaddyConfig().catch(
28597
- (err) => console.error("[CaddyHealth] self-heal reload failed:", err)
28623
+ void restartWedgedCaddy().catch(
28624
+ (err) => console.error("[CaddyHealth] wedged-Caddy restart failed:", err)
28625
+ );
28626
+ } else if (decision.action === "reload") {
28627
+ console.warn(
28628
+ `[CaddyHealth] TLS probe to ${target.servername}:${target.port} failing (${probe.reason}); reloading Caddy to self-heal`
28598
28629
  );
28630
+ await reloadCaddyConfig().then(() => {
28631
+ healState.reloadFailures = 0;
28632
+ }).catch((err) => {
28633
+ healState.reloadFailures += 1;
28634
+ console.error("[CaddyHealth] self-heal reload failed:", err);
28635
+ });
28599
28636
  }
28600
28637
  }
28638
+ async function restartWedgedCaddy() {
28639
+ await stopCaddyServer();
28640
+ await startCaddyServer();
28641
+ }
28601
28642
  function startCaddyHealthMonitor(cfg = DEFAULT_HEALTH_MONITOR_CONFIG) {
28602
28643
  if (monitorTimer) return stopCaddyHealthMonitor;
28603
- healState = { consecutiveFailures: 0, lastReloadAt: null };
28644
+ healState = { consecutiveFailures: 0, lastReloadAt: null, reloadFailures: 0 };
28604
28645
  monitorTimer = setInterval(() => {
28605
28646
  void healthTick(cfg);
28606
28647
  }, cfg.intervalMs);
@@ -28770,25 +28811,73 @@ async function checkCAInstalled() {
28770
28811
  return false;
28771
28812
  }
28772
28813
  }
28814
+ function parseKeychainSha1Fingerprints(securityOutput) {
28815
+ return [...securityOutput.matchAll(/^SHA-1 hash:\s*([0-9A-F]+)\s*$/gim)].map(
28816
+ (m) => m[1].toUpperCase()
28817
+ );
28818
+ }
28819
+ async function getCurrentCaddyRootSha1() {
28820
+ const caPath = await getCaddyCAPath();
28821
+ if (!caPath) return null;
28822
+ const pem = await fs.readFile(caPath, "utf-8");
28823
+ const { X509Certificate } = await __vitePreload(async () => {
28824
+ const { X509Certificate: X509Certificate2 } = await import("crypto");
28825
+ return { X509Certificate: X509Certificate2 };
28826
+ }, false ? __VITE_PRELOAD__ : void 0);
28827
+ return new X509Certificate(pem).fingerprint.replaceAll(":", "").toUpperCase();
28828
+ }
28829
+ function buildDarwinCaInstallCommand(caPath, staleFingerprints) {
28830
+ return [
28831
+ ...staleFingerprints.map(
28832
+ (fp) => `security delete-certificate -Z ${fp} /Library/Keychains/System.keychain`
28833
+ ),
28834
+ `security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${caPath}"`
28835
+ ].join(" && ");
28836
+ }
28773
28837
  async function installCaddyCA(elevate = defaultElevate$1) {
28774
28838
  const caPath = await getCaddyCAPath();
28775
28839
  if (!caPath) {
28776
28840
  return {
28777
28841
  success: false,
28778
- error: "Caddy CA not found. Please start the proxy first to generate the CA."
28842
+ error: "Caddy hasn't generated its local root CA yet. Add at least one mapping and start the proxy, then try again."
28779
28843
  };
28780
28844
  }
28781
28845
  const platform = process.platform;
28782
28846
  try {
28783
28847
  if (platform === "darwin") {
28784
- return {
28785
- success: true,
28786
- message: "Caddy automatically installs the CA on first run. If you see certificate warnings, restart your browser."
28787
- };
28848
+ const { execSync } = await __vitePreload(async () => {
28849
+ const { execSync: execSync2 } = await import("child_process");
28850
+ return { execSync: execSync2 };
28851
+ }, false ? __VITE_PRELOAD__ : void 0);
28852
+ let existing = [];
28853
+ try {
28854
+ const out = execSync(
28855
+ 'security find-certificate -a -c "Caddy Local Authority" -Z /Library/Keychains/System.keychain 2>&1',
28856
+ { encoding: "utf-8" }
28857
+ );
28858
+ existing = parseKeychainSha1Fingerprints(out);
28859
+ } catch {
28860
+ existing = [];
28861
+ }
28862
+ const current = await getCurrentCaddyRootSha1();
28863
+ const stale = existing.filter((fp) => fp !== current);
28864
+ if (current && existing.includes(current) && stale.length === 0) {
28865
+ return { success: true, message: "CA already trusted — nothing to do." };
28866
+ }
28867
+ const result = await elevate({
28868
+ command: buildDarwinCaInstallCommand(caPath, stale),
28869
+ prompt: "Supbuddy needs administrator access to add the local HTTPS certificate authority to your System keychain."
28870
+ });
28871
+ if (!result.success) {
28872
+ return { success: false, error: result.error || "Failed to add the CA to the System keychain" };
28873
+ }
28874
+ return { success: true, message: "Local CA added to the System keychain. Fully quit and reopen your browser to pick it up." };
28788
28875
  } else if (platform === "win32") {
28789
28876
  return {
28790
- success: true,
28791
- message: "Caddy automatically installs the CA on first run. If you see certificate warnings, restart your browser."
28877
+ success: false,
28878
+ needsManual: true,
28879
+ error: "Automatic CA install is not available on Windows yet.",
28880
+ message: `Run PowerShell as Administrator: Import-Certificate -FilePath "${caPath}" -CertStoreLocation Cert:\\LocalMachine\\Root`
28792
28881
  };
28793
28882
  } else {
28794
28883
  const result = await elevate({
@@ -28816,18 +28905,21 @@ async function uninstallCaddyCA(elevate = defaultElevate$1) {
28816
28905
  const { execSync: execSync2 } = await import("child_process");
28817
28906
  return { execSync: execSync2 };
28818
28907
  }, false ? __VITE_PRELOAD__ : void 0);
28819
- let found = false;
28908
+ let fingerprints = [];
28820
28909
  try {
28821
- const check = execSync('security find-certificate -a -c "Caddy Local Authority" 2>&1', { encoding: "utf-8" });
28822
- found = check.includes("Caddy Local Authority");
28910
+ const check = execSync(
28911
+ 'security find-certificate -a -c "Caddy Local Authority" -Z /Library/Keychains/System.keychain 2>&1',
28912
+ { encoding: "utf-8" }
28913
+ );
28914
+ fingerprints = parseKeychainSha1Fingerprints(check);
28823
28915
  } catch {
28824
- found = false;
28916
+ fingerprints = [];
28825
28917
  }
28826
- if (!found) {
28918
+ if (fingerprints.length === 0) {
28827
28919
  return { success: true, message: "Caddy Local Authority certificate not found in keychain — nothing to remove." };
28828
28920
  }
28829
28921
  const result = await elevate({
28830
- command: 'security delete-certificate -c "Caddy Local Authority" /Library/Keychains/System.keychain',
28922
+ command: fingerprints.map((fp) => `security delete-certificate -Z ${fp} /Library/Keychains/System.keychain`).join(" && "),
28831
28923
  prompt: "Supbuddy needs administrator access to remove the Caddy CA from your System keychain."
28832
28924
  });
28833
28925
  if (!result.success) {
@@ -28865,21 +28957,26 @@ async function uninstallCaddyCA(elevate = defaultElevate$1) {
28865
28957
  async function getCaddyCAInstructions() {
28866
28958
  const caPath = await getCaddyCAPath();
28867
28959
  if (!caPath) {
28868
- return `Caddy's CA has not been generated yet.
28960
+ return `Caddy's local root CA has not been generated yet.
28869
28961
 
28870
- Please start the proxy server first. Caddy will automatically:
28871
- 1. Generate a local Certificate Authority (CA)
28872
- 2. Install it in your system's trust store
28873
- 3. Generate certificates for your domains
28962
+ Caddy only mints its CA once it serves a site, so:
28963
+ 1. Add at least one enabled mapping
28964
+ 2. Start the proxy
28874
28965
 
28875
- Once started, the CA will be available at:
28966
+ Then use the "Install" button in Settings to add the CA to your system trust
28967
+ store (Caddy does not install it for you — the generated Caddyfile sets
28968
+ skip_install_trust).
28969
+
28970
+ Once generated, the CA will be available at:
28876
28971
  ${await getCaddyDataDir()}/pki/authorities/local/root.crt`;
28877
28972
  }
28878
28973
  const platform = process.platform;
28879
28974
  if (platform === "darwin") {
28880
28975
  return `Caddy Local Certificate Authority
28881
28976
 
28882
- Caddy automatically installs the CA when first started.
28977
+ Use the "Install" button in Settings to add this CA to your System keychain —
28978
+ Caddy does not install it for you (the generated Caddyfile sets
28979
+ skip_install_trust). After installing, fully quit and reopen your browser.
28883
28980
 
28884
28981
  CA Certificate Location:
28885
28982
  ${caPath}
@@ -28897,7 +28994,7 @@ If you're still seeing certificate warnings:
28897
28994
  • Search for "Caddy Local Authority"
28898
28995
  • Double-click it and check that "When using this certificate" is set to "Always Trust"
28899
28996
 
28900
- 3. **Manual Installation** (if automatic failed):
28997
+ 3. **Manual Installation** (if the Install button failed):
28901
28998
  sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${caPath}"
28902
28999
 
28903
29000
  Then restart your browser.`;
@@ -28905,16 +29002,14 @@ Then restart your browser.`;
28905
29002
  if (platform === "win32") {
28906
29003
  return `Caddy Local Certificate Authority
28907
29004
 
28908
- Caddy automatically installs the CA when first started.
29005
+ Automatic CA install is not available on Windows yet — Caddy does not install
29006
+ the CA for you (the generated Caddyfile sets skip_install_trust). Install it
29007
+ manually with the step below, then fully quit and reopen your browser.
28909
29008
 
28910
29009
  CA Certificate Location:
28911
29010
  ${caPath}
28912
29011
 
28913
- If you're still seeing certificate warnings:
28914
-
28915
- 1. **Restart your browser** (completely close and reopen)
28916
-
28917
- 2. **Manual Installation** (if automatic failed):
29012
+ Manual Installation:
28918
29013
  - Open PowerShell as Administrator
28919
29014
  - Run: Import-Certificate -FilePath "${caPath}" -CertStoreLocation Cert:\\LocalMachine\\Root
28920
29015
 
@@ -28943,11 +29038,14 @@ For Firefox (uses its own certificate store):
28943
29038
  }
28944
29039
  const caddyCaManager = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
28945
29040
  __proto__: null,
29041
+ buildDarwinCaInstallCommand,
28946
29042
  getCaddyCAInstructions,
28947
29043
  getCaddyCAPath,
28948
29044
  getCaddyCAStatus,
28949
29045
  getCaddyDataDir,
29046
+ getCurrentCaddyRootSha1,
28950
29047
  installCaddyCA,
29048
+ parseKeychainSha1Fingerprints,
28951
29049
  uninstallCaddyCA
28952
29050
  }, Symbol.toStringTag, { value: "Module" }));
28953
29051
  var define_process_env_default$7 = {};
@@ -29515,7 +29613,7 @@ async function install(opts) {
29515
29613
  if (bundleInfo.rootCount === 0) {
29516
29614
  return {
29517
29615
  success: false,
29518
- error: "Caddy hasn't generated its local root CA yet. Start the proxy at least once, then try again."
29616
+ error: "Caddy hasn't generated its local root CA yet. Add at least one mapping and start the proxy, then try again."
29519
29617
  };
29520
29618
  }
29521
29619
  const env = await readCurrentEnv();
@@ -29622,6 +29720,9 @@ async function detectTools() {
29622
29720
  anyFound: results.some((r) => r.found)
29623
29721
  };
29624
29722
  }
29723
+ function buildTrustProbeUrl(domain, httpsPort, portForwardingEnabled) {
29724
+ return portForwardingEnabled ? `https://${domain}/` : `https://${domain}:${httpsPort}/`;
29725
+ }
29625
29726
  async function testTrust(opts) {
29626
29727
  const bundlePath = getBundlePath();
29627
29728
  if (!fsSync.existsSync(bundlePath)) {
@@ -29706,30 +29807,76 @@ async function startRotationWatcher(onChange) {
29706
29807
  }
29707
29808
  }
29708
29809
  util$1.promisify(child_process.exec);
29709
- async function getPortForwardingStatus(httpPort, httpsPort) {
29810
+ async function getPortForwardingStatus(httpPort, httpsPort, opts) {
29710
29811
  try {
29711
29812
  const anchorContent = await fs.readFile("/etc/pf.anchors/virtual.localhost", "utf-8");
29712
29813
  const hasHttpForwarding = anchorContent.includes(`port 80 -> 127.0.0.1 port ${httpPort}`);
29713
29814
  const hasHttpsForwarding = anchorContent.includes(`port 443 -> 127.0.0.1 port ${httpsPort}`);
29714
29815
  if (!hasHttpForwarding || !hasHttpsForwarding) {
29715
- return { enabled: false, httpPort, httpsPort };
29816
+ return { enabled: false, httpPort, httpsPort, enforced: null };
29716
29817
  }
29717
29818
  try {
29718
29819
  const pfConf = await fs.readFile("/etc/pf.conf", "utf-8");
29719
- const hasAnchorRef = pfConf.includes("virtual.localhost");
29720
- return { enabled: hasAnchorRef, httpPort, httpsPort };
29820
+ const enabled = pfConf.includes("virtual.localhost");
29821
+ const enforced = enabled && opts?.probe ? await opts.probe() : null;
29822
+ return { enabled, httpPort, httpsPort, enforced };
29721
29823
  } catch {
29722
- return { enabled: false, httpPort, httpsPort };
29824
+ return { enabled: false, httpPort, httpsPort, enforced: null };
29723
29825
  }
29724
29826
  } catch (error) {
29725
29827
  return {
29726
29828
  enabled: false,
29727
29829
  httpPort,
29728
- httpsPort
29830
+ httpsPort,
29831
+ enforced: null
29729
29832
  };
29730
29833
  }
29731
29834
  }
29732
- function getEnablePortForwardingCommand(httpPort, httpsPort, lanSharing = false) {
29835
+ async function probe443(timeoutMs = 1e3) {
29836
+ const net2 = await __vitePreload(() => import("net"), false ? __VITE_PRELOAD__ : void 0);
29837
+ return new Promise((resolve) => {
29838
+ const socket2 = net2.createConnection({ host: "127.0.0.1", port: 443 });
29839
+ const timeout = setTimeout(() => {
29840
+ socket2.destroy();
29841
+ resolve(false);
29842
+ }, timeoutMs);
29843
+ socket2.on("connect", () => {
29844
+ clearTimeout(timeout);
29845
+ socket2.end();
29846
+ resolve(true);
29847
+ });
29848
+ socket2.on("error", () => {
29849
+ clearTimeout(timeout);
29850
+ resolve(false);
29851
+ });
29852
+ });
29853
+ }
29854
+ const PF_RDR_LINE = 'rdr-anchor "virtual.localhost" # Supbuddy port forwarding';
29855
+ const PF_LOAD_LINE = 'load anchor "virtual.localhost" from "/etc/pf.anchors/virtual.localhost" # Supbuddy port forwarding';
29856
+ function buildCorrectedPfConf(existing) {
29857
+ const stripped = existing.split("\n").filter((l) => {
29858
+ const t = l.trim();
29859
+ return !t.includes("virtual.localhost") && t !== "# Supbuddy port forwarding";
29860
+ });
29861
+ while (stripped.length > 0 && stripped[stripped.length - 1].trim() === "") stripped.pop();
29862
+ let insertAt = -1;
29863
+ for (let i2 = 0; i2 < stripped.length; i2++) {
29864
+ if (stripped[i2].trim().startsWith("rdr-anchor ")) insertAt = i2 + 1;
29865
+ }
29866
+ if (insertAt === -1) {
29867
+ const firstFilter = stripped.findIndex((l) => /^anchor\s/.test(l.trim()));
29868
+ insertAt = firstFilter === -1 ? stripped.length : firstFilter;
29869
+ }
29870
+ const out = [...stripped];
29871
+ out.splice(insertAt, 0, PF_RDR_LINE);
29872
+ out.push(PF_LOAD_LINE);
29873
+ const content = out.join("\n") + "\n";
29874
+ return { content, changed: content !== existing };
29875
+ }
29876
+ function buildValidationPfConf(content, anchorTmpPath) {
29877
+ return content.replaceAll('from "/etc/pf.anchors/virtual.localhost"', `from "${anchorTmpPath}"`);
29878
+ }
29879
+ function buildAnchorContent(httpPort, httpsPort, lanSharing = false) {
29733
29880
  let anchorContent = `# Supbuddy port forwarding rules
29734
29881
  rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port ${httpPort}
29735
29882
  rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 443 -> 127.0.0.1 port ${httpsPort}`;
@@ -29742,24 +29889,21 @@ rdr pass on en1 inet proto tcp from any to any port 80 -> 127.0.0.1 port ${httpP
29742
29889
  rdr pass on en1 inet proto tcp from any to any port 443 -> 127.0.0.1 port ${httpsPort}`;
29743
29890
  }
29744
29891
  anchorContent += "\n";
29745
- return `
29746
- # Create anchor file
29747
- mkdir -p /etc/pf.anchors
29748
- echo '${anchorContent}' > /etc/pf.anchors/virtual.localhost
29749
-
29750
- # Add anchor to pf.conf if not already there
29751
- if ! grep -q "virtual.localhost" /etc/pf.conf; then
29752
- cp /etc/pf.conf /etc/pf.conf.backup.$(date +%Y%m%d_%H%M%S)
29753
- echo "" >> /etc/pf.conf
29754
- echo "# Supbuddy port forwarding" >> /etc/pf.conf
29755
- echo "rdr-anchor \\"virtual.localhost\\"" >> /etc/pf.conf
29756
- echo "load anchor \\"virtual.localhost\\" from \\"/etc/pf.anchors/virtual.localhost\\"" >> /etc/pf.conf
29757
- fi
29758
-
29759
- # Enable pfctl and load rules
29760
- pfctl -e 2>/dev/null || true
29761
- pfctl -f /etc/pf.conf
29762
- `.trim();
29892
+ return anchorContent;
29893
+ }
29894
+ function getEnablePortForwardingCommand(_httpPort, _httpsPort, _lanSharing, _currentPfConf, tmpAnchorPath, tmpPfConfPath) {
29895
+ const cmds = [
29896
+ "mkdir -p /etc/pf.anchors",
29897
+ `cp "${tmpAnchorPath}" /etc/pf.anchors/virtual.localhost`
29898
+ ];
29899
+ if (tmpPfConfPath) {
29900
+ cmds.push(
29901
+ "{ [ -f /etc/pf.conf.supbuddy-backup ] || cp /etc/pf.conf /etc/pf.conf.supbuddy-backup; }",
29902
+ `cp "${tmpPfConfPath}" /etc/pf.conf`
29903
+ );
29904
+ }
29905
+ cmds.push("{ pfctl -e 2>/dev/null || true; }", "pfctl -f /etc/pf.conf");
29906
+ return cmds.join(" && ");
29763
29907
  }
29764
29908
  function getDisablePortForwardingCommand() {
29765
29909
  return `
@@ -43619,7 +43763,11 @@ const trustTools = {
43619
43763
  (m) => m.enabled && m.domain.endsWith("." + tld)
43620
43764
  );
43621
43765
  if (candidate) {
43622
- url2 = `https://${candidate.domain}:${store2.settings.httpsPort ?? 8443}/`;
43766
+ url2 = buildTrustProbeUrl(
43767
+ candidate.domain,
43768
+ store2.settings.httpsPort ?? 8443,
43769
+ store2.proxyState.portForwardingEnabled ?? false
43770
+ );
43623
43771
  }
43624
43772
  }
43625
43773
  if (!url2) {
@@ -44184,7 +44332,7 @@ async function detectTargets(projectPath) {
44184
44332
  jetbrains: await isDir(path.join(projectPath, ".idea"))
44185
44333
  };
44186
44334
  }
44187
- const DOCS_MARKDOWN = "# Supbuddy docs\n\n> Run multiple Supabase projects at once on one Mac, each with its own custom local domain.\n\n## Getting started\n\nThere are two ways to run Supbuddy. Use the **macOS desktop app** (steps below), or the **command-line interface**, which runs on macOS and Linux. For the CLI, install it with `npx supbuddy@latest` and jump to [Command-line interface](#command-line-interface-cli). The app and the CLI share the same state, so you can use either or both.\n\n### 1. Install\n\nDownload the latest `.dmg` from the [download page](/api/download). Drag **Supbuddy.app** into `/Applications` and launch it. Supbuddy is signed and notarized; macOS will not show a Gatekeeper warning. Requires an Apple Silicon Mac (M1/M2/M3/M4, arm64). The desktop app is macOS-only in v2, but the headless CLI runs on Linux too. See [Command-line interface](#command-line-interface-cli).\n\n### 2. Trust the local Certificate Authority\n\nOn first launch, open the app and click **Install Certificate** when prompted. Supbuddy generates a local CA (Caddy's internal PKI) at `~/Library/Application Support/Supbuddy/caddy-data/caddy/pki/authorities/local/root.crt` and installs it into your system Keychain via `sudo security add-trusted-cert`. macOS will ask for your password once. After this, every Supbuddy domain gets the green padlock automatically, with no per-domain prompts and no browser warnings.\n\nIf Supbuddy detects an AI tool that ships its own JavaScript runtime (Claude Code, Cursor, Windsurf, Continue, Codex CLI, OpenCode, etc.) it will also offer to enable **Bundled-runtime trust** in the same first-run prompt. Those tools don't read the system Keychain (they carry their own Mozilla CA bundle), so without this setup the first OAuth/MCP connection to a `*.test` URL fails with `unable to get local issuer certificate`. Enable it once and Supbuddy keeps it in sync (including across yearly Caddy CA rotation). See the **Bundled-runtime trust** section under Settings → General for details.\n\nIf you skip the prompt, you can re-trigger it any time from the **Settings → Network** tab.\n\n### 3. Add your first project\n\nClick **Add project** in the Configure tab and pick a project root folder (the one with `package.json` and/or `supabase/config.toml`). Supbuddy scans it and creates auto-mapped subdomains based on what it finds:\n\n- Supabase Kong → `api.<project>.test`\n- Supabase Studio → `studio.<project>.test`\n- Supabase Inbucket / Mailpit → `mail.<project>.test`\n- Each detected app (Next.js, Vite, etc.) → `<app-name>.<project>.test`\n\nThe default TLD is `.test`. You can change it project-wide in **Settings → General → Default TLD**.\n\n### 4. Start the proxy\n\nToggle the project on. Supbuddy starts Caddy on port 8443 (HTTPS) and starts its built-in DNS server on port 5353. If you want real ports 80/443 instead of 8080/8443, enable **port forwarding** in **Settings → Network**. Supbuddy adds a `pfctl` redirect rule (asks for sudo once).\n\n## Core concepts\n\nFour things to understand:\n\n- **Project**: a folder you registered. Holds detected *apps* (Next.js, Vite, etc.), detected *services* (Supabase stack, Docker Compose services), and a list of *mappings*.\n- **Mapping**: a domain → port pair (e.g. `api.acme.test → 54321`). Auto-generated mappings are tied to a detected service or app; you can also create manual ones.\n- **Isolation mode**: per-project. One of:\n - `thin` (lightweight, **the default for newly registered projects**): still your host Docker (no nested containers, no DinD), but Supbuddy gives each project its own **port block** and a unique Compose `project_id`, written into that project's `supabase/config.toml`. That's what lets several Supabase projects run **at once on the shared daemon**, each reached by name (`api.<project>.test`, `studio.<project>.test`). Apps bind a **per-project loopback IP** (127.0.0.2, 127.0.0.3, …) so every project's dev servers keep their canonical ports — each project gets its *own* `:3000`. Start dev servers with `supbuddy run -- <dev command>` so they bind that IP. Supbuddy owns those config.toml keys while the project is `thin` and restores them the moment you switch back to `host`.\n - `host`: everything shares `127.0.0.1` and the stock ports. Dev-server ports collide across projects, and only one host-mode Supabase project can run at a time (the standard `supabase start` constraint). Use `host` **only when the project's Supabase stack is already running on the host independently of Supbuddy** (you run `supabase start` yourself and don't want Supbuddy re-porting `config.toml`). MCP registration (`register_project`) detects that case and keeps such projects on `host` automatically; in the app's Add-project dialog, pick **Host** in the Environment section yourself.\n- **Active vs inactive**: any project can be \"active\" (proxied + reachable) or inactive. Inactive projects keep their state, so flipping them on is a few seconds. Run as many active projects as you want.\n\n## Project cards (Configure tab)\n\nEach registered project appears as a card in the Configure tab. Cards have a single-row header that's always visible and a tab-based body that expands on click.\n\n### Header\n\nReading left to right:\n\n- **Expand chevron** + **project name**: click to expand/collapse the card.\n- **Status indicator**: a single colored dot next to the project name aggregating the realtime state of every subsystem (Supabase services, Compose, scripts, AI sync, port conflicts, next.config warnings). Red = error, amber = warning, green = at least one service running, muted gray = idle, animated cyan spinner = transitioning. Hover for a tooltip that lists each subsystem's state.\n- **Tech badges**: e.g. `TurboRepo`, `Supabase` (shown when detected).\n\n**Supabase connection warning.** When a project's app `.env` is missing the\nSupabase connection vars, or they've gone stale relative to the live target\n(e.g. after switching isolation, which republishes ports), the card shows a\n`supabase env: not connected` / `supabase env: out of date` pill. Click it to\nopen Connect and push fresh values, or choose **Ignore for this project**.\n- **Env mode chip**: read-only `Host` or `Thin` label (matching the project's isolation mode). To switch modes, open the **Supabase** tab and use the **Environment** section at the top.\n- **Issues counter**: red for errors, amber for warnings. Click to open the **issues popover** (see below). Hidden when there are no issues.\n- **Warnings chip**: all project-level warnings (isolation drift, missing env vars, config issues, etc.) are consolidated into a single amber chip next to the enable toggle. Click it to see each warning item-by-item; it shows a spinner while Supbuddy re-checks the project.\n- **Enable toggle** (right edge): turn the project's proxy on/off without deleting it.\n- **⋯ actions menu** (right edge): every project-level action: **Edit project**, **Rescan**, **Re-check configs** (re-runs the connection/env drift check for this project), **Select folder**, **Export bundle**, and **Delete project**.\n\n### Issues popover\n\nClicking the issues counter opens a popover listing all current errors and warnings. Each issue shows a severity icon, title, optional detail, and a **→ open {tab}** link. Clicking the link jumps to the relevant tab and closes the popover.\n\n### Body tabs (when expanded)\n\nThe body renders a flat tab strip with 6 conditional tabs. Below ~480 px, the strip collapses to a dropdown selector. (Project-level actions, like edit, rescan, re-check configs, select folder, export, and delete, are in the header's **⋯ menu**, not a tab.)\n\n#### Apps (default tab)\n\nPer-app rows are domain-first: `domain → :port` (with hover-revealed copy/open URL buttons), then app name + tech badge, then a flex spacer pushes hover-revealed **edit** / **delete** / **access** (LAN / Tailscale state) actions and the per-mapping **toggle** to the right edge. A **Map** CTA appears on hover for unmapped apps. Manual mappings scoped to this project (not auto-generated) are listed below under their own subheader.\n\n#### Supabase (shown when Supabase is detected)\n\n**Environment section (top):** host/thin switcher. A legacy project still on the old Isolated (VM) mode shows the migration wizard here instead (see [Migrating a legacy Isolated (VM) project to Thin](#migrating-a-legacy-isolated-vm-project-to-thin)).\n\n**Action bar:** Start, Stop, Restart buttons; a first-class **Connect** button (cyan, opens the connection panel for `.env` generation / merge); and a **More** menu with **Config editor** and **Details**.\n\n**Config editor: secret extraction.** When you save a `supabase/config.toml` that contains a secret-bearing value inline (e.g. an SMTP password under `[auth.email.smtp]`, an OAuth `secret`, or any `*_key`/`auth_token`), Supbuddy prompts before writing: it lists the detected secrets and lets you pick which gitignored env file to move them to (defaulting to the project-root `.env.local`). The value is written there and replaced in `config.toml` with an `env(SUPABASE_…)` reference, so secrets never land in git. Supbuddy injects those `SUPABASE_`-prefixed values back into the `supabase start` environment so the references resolve. (Saving a config with no inline secrets writes directly, with no prompt.)\n\n**Service rows** (read-only): status dot, service name, URL. No inline actions; lifecycle is driven by the action bar.\n\n#### Compose (shown when Compose services are detected)\n\n**Action bar:** Start, Stop, Restart. **Service rows** are read-only (status dot, name, URL). Add-on services declared in `supbuddy.addons.yml` (see **Add-on Compose services**) appear here alongside the base stack and in `get_compose_status` over MCP.\n\n#### Other (shown when non-Supabase, non-Compose services are detected)\n\nRead-only service rows: status dot, name, URL.\n\n#### Scripts (shown when scripts are detected)\n\nBookmarked scripts appear in a **Quick Access** group at the top; remaining scripts appear under **Other Scripts**. Per-script row: status dot, name, uptime, bookmark star, Start/Stop/Restart buttons. A search input appears when there are more than 5 scripts.\n\n#### AI Tools\n\nWraps the project-context-sync panel: sync mode selector (Auto / Manual / Off), detected targets list with per-target **scope** (global / local), advanced options, and recent activity. See [Per-project AI context sync](#per-project-ai-context-sync) for what global vs. local means.\n\n> Project-level actions (**Edit**, **Rescan**, **Re-check configs**, **Select folder**, **Export bundle**, **Delete**) are no longer a tab. They live in the header's **⋯ actions menu**.\n\n---\n\n## Multiple Supabase projects (the main use case)\n\nThe reason Supbuddy exists. Stock Supabase CLI binds to fixed ports (54321 Kong, 54322 Postgres, 54323 Studio, 54324 Inbucket). Two projects on the same machine collide; you must `supabase stop` one before `supabase start`-ing the other.\n\nTwo ways to break that constraint, picked per project in the **Supabase** tab → **Environment** section:\n\n### Thin (lightweight, recommended)\n\nSwitch a project to **Thin**. Supbuddy assigns it a free port block (in the `55000+` range), writes those ports plus a unique Compose `project_id` into its `supabase/config.toml`, and runs `supabase start` on your **normal host Docker**, with no nested containers and nothing to pull. Several projects boot side by side this way; each is reached by name (`api.acme.test`, `studio.acme.test`, `mail.acme.test`). Switch back to **Host** and Supbuddy restores the original `config.toml` and stops just that project's stack.\n\nThis is the lightest, fastest option and the right default for most setups — which is why **newly registered projects default to Thin**. One caveat: if your `config.toml` omits a port key (e.g. `[inbucket] smtp_port`), Supbuddy can't relocate a port that isn't declared, so that one service falls back to its stock port. That is fine for a single project, but spell those keys out if two Thin projects need the same service.\n\n### Dev servers on Thin: every project keeps its own `:3000`\n\nA Thin project also gets its own **loopback IP** (127.0.0.2, 127.0.0.3, …, persisted per project). Its app dev servers bind that IP instead of `127.0.0.1`, so canonical ports never collide across projects — five Next.js apps in five projects can all run on `:3000` at once, and Supbuddy's proxy routes each `web.<project>.test` to its project's IP.\n\nStart dev servers through the launcher:\n\n```bash\nsupbuddy run -- next dev # binds -H <project loopback IP>, stays on :3000\nsupbuddy run -- vite # injects --host <ip> --strictPort\nsupbuddy run --print -- next dev # show what would run, without running it\n```\n\n`supbuddy run` reads the project's IP from the nearest `.supbuddy/meta.json` (`loopbackIp`, written when Thin is enabled), ensures the loopback alias exists, injects the right bind flag for the detected framework, and execs your command. It prints one concise line with the project's Caddy-proxied URL (e.g. `[supbuddy] → https://web.<project>.test`) — the address you should actually open. For **Next and Vite** it also hides the dev server's own `- Local:/- Network:` banner (which only echoes the raw loopback IP `127.0.0.N:<port>`, bypassing Supbuddy's HTTPS proxy): those two lines are filtered out of the piped output, every other line passes through untouched, and colours are preserved via `FORCE_COLOR` (stdin stays interactive). Other frameworks pass through with no filtering. When a project has several app mappings, it matches the one whose port equals the dev server's port (from `--port`/`-p` or the framework default), else lists them all. Make it the project's `dev` script (`\"dev\": \"supbuddy run -- next dev\"`) so nobody — humans or agents — has to remember it. **Never move an app to a nonstandard port because `127.0.0.1:3000` is busy**; that port belongs to another project's IP space.\n\n### When to stay on Host\n\nKeep a project on **Host** only when its Supabase stack runs on the host *independently of Supbuddy* — you run `supabase start` yourself on the stock ports and don't want Supbuddy rewriting `config.toml`. MCP registration (`register_project`) detects a stack like that (running containers for the project's `config.toml` `project_id`) and keeps the project on Host automatically; in the app's Add-project dialog, pick **Host** in the Environment section for such projects. Stop the stack (`supabase stop`) and switch to Thin whenever you're ready.\n\n### Running them all at once\n\nRegister as many projects as you want, and all of them can be \"active\" (proxied) at the same time. There's no limit. A Thin project's stack restarts in seconds; a Host project needs the standard `supabase start` cycle.\n\n### Migrating a legacy Isolated (VM) project to Thin\n\nIf you created a project in an older version of Supbuddy that used the now-retired **Isolated (VM)** mode, Supbuddy detects it on launch and offers a one-way, guided migration to **Thin**. The migration wizard appears in the **Supabase** tab's Environment section for any project still flagged as VM.\n\nThe migration is data-safe: Supbuddy dumps your Postgres data, starts a fresh Thin stack, restores the dump into it, and row-count-verifies the restore before tearing down the old VM container. No data loss. After migrating, the VM is gone and there's no way to switch back (but your data is intact in the Thin stack).\n\nOver MCP, three tools handle the migration bridge:\n\n- `list_pending_vm_migrations` (read): lists all projects still on the legacy VM mode awaiting migration.\n- `migrate_vm_to_thin` ( `{ project_id }` ) (write): starts the guided data-safe migration (dump, restore, verify).\n- `finish_vm_migration` ( `{ project_id }` ) (write): tears down the old VM container after migration is verified. Returns an error if called before verification passes.\n\n## Custom domains & TLDs\n\nEvery mapping resolves through Supbuddy's built-in DNS server on port 5353. By default the TLD is `.test` (an IETF-reserved TLD safe for local use). You can change the default in **Settings → General → Default TLD** to `local`, `dev`, or anything else; existing mappings are migrated to the new TLD on save.\n\nFor host resolution, Supbuddy *does not* use `/etc/hosts` for wildcards; it runs a DNS resolver. macOS's default resolver only queries port 53; Supbuddy installs a per-project resolver file under `/etc/resolver/<project-domain>` (e.g. `/etc/resolver/myapp.local`) pointing at `127.0.0.1:5353`. macOS picks the longest-suffix-matching file, so per-project entries route reliably without colliding with reserved namespaces like `.local` (which Bonjour/mDNS owns). You'll be prompted for sudo the first time this changes.\n\n### Per-project TLD\n\nBy default every project's domain uses the global TLD (Settings → Default TLD, e.g. `.test`). A single project can opt into its **own** TLD — set the suffix in the project dialog, pass `tld` to the `register_project` / `update_project` MCP tools, or use the CLI: `supbuddy project add <path> --tld=portal` when registering, or `supbuddy project set <project> --tld=portal` on an existing one (`--tld=` with an empty value clears the override). That project's base domain and all its subdomains then live on the override TLD (e.g. `cueplusplus.portal`, `web.cueplusplus.portal`) while every other project stays on the global default. The override is durable across restarts and is unaffected when you change the global TLD. Prefer `.test` or a vanity label like `.portal`; avoid `.local` (it collides with macOS mDNS/Bonjour).\n\n### LAN sharing\n\nWhen LAN sharing is enabled (Settings → Network), Supbuddy binds Caddy to `0.0.0.0` instead of `127.0.0.1` and runs an mDNS responder so other machines on your local network can reach your dev servers via `<hostname>.local`. Useful for testing on your phone or another laptop without setting up Tailscale.\n\n**`.local` TLD + LAN sharing:** macOS reserves the `.local` namespace for Bonjour/mDNS (RFC 6762), and macOS's TCP stack short-circuits self-connections to your own LAN IP via the loopback path *without consulting `pf`*, so the obvious \"redirect lo0 → my LAN IP\" trick can't fix it. Supbuddy's mDNS responder works around this by **ignoring queries that originate from this machine**, letting the OS resolver fall through to `/etc/resolver/<project-domain>` (which routes to `127.0.0.1` where Caddy listens). Other LAN devices still get answered with the LAN IP and reach you normally. The net result: `.local` works correctly both on this machine and on other LAN devices, with no manual configuration. If you previously worked around this by switching to `.test`, you can switch back.\n\nIf `studio.<project>.local` (or similar) doesn't load: open the Configure tab. A red banner will tell you whether it's a DNS, port-forwarding, or mDNS-race issue, with the specific recovery action.\n\n### Tailscale\n\nIf you have Tailscale installed and a Tailscale API key configured in Settings, Supbuddy can push split-DNS routes to your tailnet so any device on your tailnet resolves your Supbuddy domains. Optional, off by default.\n\n## Monorepo support\n\nSupbuddy auto-detects these monorepo layouts when scanning a project root:\n\n- Turborepo (presence of `turbo.json`)\n- pnpm workspaces (`pnpm-workspace.yaml`)\n- npm/yarn workspaces (`workspaces` field in root `package.json`)\n- Common folder layouts: `apps/*`, `packages/*`, `services/*`, `sites/*`\n\nEach detected app gets its own subdomain. Supabase is searched for in the project root and these subdirectories: `apps/*`, `packages/*`, `services/*`, `sites/*`, `db/`, `db/*`, `database/`, `database/*`, `packages/backend`, `packages/db`, `packages/database`.\n\n### Detected app frameworks\n\nPort detection looks for the framework dependency in `package.json` and combines that with: explicit `-p`/`--port` in the dev script, `PORT=` env in the dev script, or a config file read. If none of those resolve, the framework default is used:\n\n| Framework dependency | Default port |\n| --- | --- |\n| `next` | 3000 |\n| `vite` | 5173 |\n| `@remix-run/dev`, `@remix-run/serve` | 3000 |\n| `astro` | 4321 |\n| `nuxt`, `nuxt3` | 3000 |\n| `@sveltejs/kit` | 5173 |\n| `@angular/core` | 4200 |\n| `@nestjs/core` | 3000 |\n| `express`, `fastify`, `koa`, `hono`, `@hono/node-server`, `elysia`, `polka`, `tinyhttp` | none (must be explicit in dev script) |\n\n### Server Actions allowedOrigins audit\n\nFor Next.js apps, Supbuddy reads your `next.config.{ts,mts,js,mjs,cjs}` and extracts the hosts in `experimental.serverActions.allowedOrigins`. If a mapped subdomain is missing from that list, the project's **warnings chip** flags `next.config: N origins missing`; Server Action POSTs through Supbuddy mappings would 403 otherwise. Open the **Apps** tab (the chip's \"open apps\" jump) where the affected app shows the warning with a **Fix** button.\n\nThe Fix button opens a dialog with a paste-ready snippet and an **Apply…** button: click it to see a unified diff of the change Supbuddy will make to your `next.config`, then **Confirm & write** to apply it. Supbuddy handles the four common config shapes (existing `allowedOrigins` array, existing `serverActions` block without it, existing `experimental` block without `serverActions`, or no `experimental` at all). After write, Supbuddy rescans the project so the warning disappears immediately. Restart your dev server for the change to take effect; Next.js does not hot-reload `next.config`.\n\n### Vite allowedHosts audit\n\nFor Vite apps, Supbuddy reads your `vite.config.{ts,mts,cts,js,mjs,cjs}` and extracts `server.allowedHosts`. If a mapped host isn't covered, the **warnings chip** flags `vite: N hosts blocked`; Vite's dev server otherwise rejects proxied requests for unknown hosts with `Blocked request. This host (\"…\") is not allowed.` (403). A `.your-project.local` entry counts as covering every subdomain, so an existing wildcard suffix doesn't trigger a false warning.\n\nLike the Next.js audit, the affected app's **Fix** button on the **Apps** tab opens a dialog with a paste-ready snippet and an **Apply…** button that previews a unified diff and writes `server.allowedHosts` into your `vite.config` (handling an existing `allowedHosts` array, an existing `server` block without it, or no `server` block at all; `allowedHosts: true` is left untouched). After write, Supbuddy rescans so the warning clears. Restart your dev server for the change to take effect; Vite does not hot-reload `vite.config`.\n\n## MCP setup (AI agents)\n\nSupbuddy ships a built-in MCP server on `http://127.0.0.1:9877/mcp` with static Bearer-token auth. Five clients have one-click install; any other MCP-compatible tool can be configured manually with the same URL + token.\n\nOpen **Settings → MCP → Add client**, pick the client kind, and Supbuddy generates a token, edits the client's config file, and backs up the original (`<file>.supbuddy-backup` next to it).\n\n### Auto-install paths\n\n| Client | Config file | Transport |\n| --- | --- | --- |\n| Claude Code | `~/.claude.json` (user) or `<project>/.mcp.json` (project) | HTTP |\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | stdio shim via `npx -y @supbuddy/mcp@latest` |\n| Cursor | `~/.cursor/mcp.json` (user) or `<project>/.cursor/mcp.json` (project) | HTTP |\n| Codex CLI | `~/.codex/config.toml` (adds an `[mcp_servers.supbuddy]` block) | HTTP |\n| Windsurf | `~/.codeium/windsurf/mcp_config.json` | HTTP |\n\n### MCP tool surface\n\nThe MCP server has full read and write access:\n\n- Read tools (`list_mappings`, `list_projects`, `get_health`, `get_compose_status`, `list_pending_vm_migrations`, etc.), with env values and request bodies included.\n- `get_client_capabilities` and `request_scope_elevation` (scope discovery + user-approved grant).\n- `read_env_file`, `tail_request_logs`, `watch_audit_log`.\n- Write tools: `create_mapping`, `delete_mapping` (soft-delete), `register_project`, `update_project`, `set_supabase_config_path`, `start_proxy`, `start_supabase`, `stop_supabase`, `restart_supabase`, `switch_isolation`, `migrate_vm_to_thin`, `finish_vm_migration`, `start_compose`, `stop_compose`, `restart_compose`, `scaffold_addons`, `seed_addons`, `write_env_file`, `copy_env_var`, `write_supabase_config`.\n- Scripts tools (`list_scripts`, `start_script`, `stop_script`, `restart_script`, `bookmark_script`, `tail_script_logs`); see *Scripts MCP tools* below.\n- Extended Supabase tools: `init_supabase`, `validate_supabase_config`, `list_supabase_backups`, `restore_supabase_backup`, `cancel_supabase_start`, `force_recreate_supabase`, `restart_supabase_container`, `get_supabase_analytics`, `set_supabase_analytics`.\n- Bundle (export/import a project's full config): `export_bundle`, `import_bundle`, `validate_bundle`.\n- Supbuddy Cloud (opt-in, per-project): `cloud_sign_in`, `push_to_cloud`, `get_cloud_status`, `cloud_teardown` — push a project (with its Supabase schema + data) to a hosted cloud stack and control it. The `cloud` link (`{ projectId, stackId, pushedAt, url }`) also appears on `get_project` / `list_projects`, so any client sees which projects are in the cloud.\n- Connection / env-target workflow: `preview_connection`, `get_env_targets`, `diff_env`, `apply_env`, `write_connection`, `test_connection`, `dismiss_connection_drift`.\n- Host & network tools: bundled-runtime trust (`get_trust_status`, `install_trust`, `remove_trust`, `detect_trust_tools`, `test_trust`), Tailscale (`get_tailscale_status`, `set_tailscale_key`, `remove_tailscale_key`, `test_tailscale`), DNS (`get_dns_status`), CA (`uninstall_ca`), and port-forwarding (`get_port_forwarding_status`, `set_port_forwarding`, `reload_port_forwarding`).\n- `tail_service_logs`: streams a Compose/add-on service's container logs over SSE (like `tail_request_logs` but for container stdout/stderr).\n- `watch_supabase`: streams a project's live Supabase start/stop/restart progress over SSE: operation status, image-pull/service snapshots, and (for VM projects) raw log lines. Backs `supbuddy supabase start --follow`.\n- Multiple MCP clients can connect simultaneously. The same MCP-HTTP surface backs the headless **CLI** (see *Command-line interface* below).\n\n### Scopes: discovery & self-service elevation\n\nEach MCP client holds a set of **scopes** (`read`, `log_tail`, `mappings`, `projects`, `services`, `config`, `system`, `apply`) chosen when it's added. A tool call that needs a scope the client lacks fails with `scope_denied`, whose payload now carries a `user_message` and `details.remediation` pointing at the fix.\n\n- `get_client_capabilities` ( `{ tool? }` ) returns the calling client's `granted_scopes` and `available_scopes`. Pass a `tool` name to get `{ required_scope, required_feature, can_call, reason? }` so an agent can pre-flight a call instead of probing by hitting `scope_denied`.\n- `request_scope_elevation` ( `{ scopes: [...] }` ) asks the **user** to grant the named scopes. Supbuddy shows a blocking approval dialog; on approval the scopes are added to the client. Already-granted scopes short-circuit without a prompt.\n\nYou can also review and edit any client's scopes from the GUI: **Settings → MCP → Clients** lists each client's granted scopes inline and exposes a **Scopes** button that opens the same scope editor used when adding a client.\n\n### Registering a project via MCP\n\n`register_project` takes a `root_path` (required), an optional `label`, `auto_scan` (default `true`), and an optional `isolation` (`'thin'` or `'host'`). It registers the project the same way the GUI's \"Add project\" flow does:\n\n- Derives a base domain as `<slug>.<defaultTld>` from the label (or the folder name), e.g. `staffhub.test`.\n- Records both the project `path` and `rootPath` so the project is visible to the proxy, scans, and file tools alike.\n- Scans the folder (unless `auto_scan: false`) for apps, services, scripts, and package manager.\n- Creates per-app subdomain mappings from the discovered apps (e.g. `site.staffhub.test → :3400`), derives the host service subdomains (`api.`, `studio.`, …), and reloads Caddy.\n- **Defaults to `thin` isolation**: the project gets its own loopback IP so its dev servers keep canonical ports (`:3000`) with no cross-project collisions — run them with `supbuddy run -- <dev command>`. The one exception: if the project's Supabase stack is **already running on the host outside Supbuddy**, registration keeps it on `host` (switching would rewrite its `config.toml` ports and orphan the running stack). Pass `isolation: 'host'` to opt out explicitly, or `isolation: 'thin'` to skip the detection and force thin.\n\nThe response includes an `isolation_note` explaining which mode was chosen and why — agents should read it instead of assuming.\n\n### Switching isolation over MCP\n\n`switch_isolation` ( `{ project_id, target_mode: 'host' | 'thin', auto_start? }` ) moves an existing project between **host** and **thin** mode. To-thin writes the per-project port block and `project_id` into `supabase/config.toml` and (unless `auto_start: false`) starts Supabase; to-host restores the original `config.toml` and stops that project's stack. It runs in the background and returns `{ started: true }`; poll `get_project` (`isolation`) for the current mode.\n\nA project can also be patched with `update_project`: its `patch` accepts `name`, `enabled`, `domain`, and `isolation` (it intentionally does **not** accept `path`/`rootPath`). Note that patching `isolation` only flips the flag; use `switch_isolation` to actually provision/tear down the port assignment.\n\n### Legacy VM migration over MCP\n\nFor projects still on the retired Isolated (VM) mode, three tools handle the one-way migration to Thin:\n\n- `list_pending_vm_migrations` (read): lists all projects still on the legacy VM mode, with their current `vmState` and migration readiness.\n- `migrate_vm_to_thin` ( `{ project_id }` ) (write): starts the guided data-safe migration. It dumps Postgres data from the VM, starts a fresh Thin stack, restores the dump, and row-count-verifies before signalling completion. Returns `{ started: true }`; poll `get_project` (`migrationState`) for progress.\n- `finish_vm_migration` ( `{ project_id }` ) (write): tears down the old VM container after verification passes. Errors if called before the verify step completes.\n\n### Repointing a project's Supabase config\n\n`set_supabase_config_path` ( `{ project_id, supabase_path }` ) switches which `supabase/config.toml` a project uses, for monorepos that carry more than one (e.g. a repo-root config and an app-level one). `supabase_path` is the project-relative directory **containing** the `supabase/` folder (`\".\"` for the repo root, e.g. `\"apps/getnightowls\"`). It persists the path, re-derives `supabaseProjectId` from the new config, and re-scans services. The previous stack's Docker volume is **left intact** (not deleted), so the switch is reversible; the response reports it under `orphaned_previous_stack`.\n\n### Moving a secret between env files\n\n`copy_env_var` ( `{ source_path, source_key, target_path, target_key? }` ) relocates a single variable from one env file to another (e.g. a value put in an app's `.env.local` that the stack actually injects from the repo-root `.env.local`). The value is read and written entirely inside the worker (it **never crosses the MCP boundary** and never appears in the audit log), so an agent can move a secret without it being printed. `target_key` defaults to `source_key`.\n\n### Plan / apply for destructive tools\n\nTools that delete or mutate state (`delete_mapping`, `delete_project`, `write_env_file`, etc.) return a *plan* with a preview. The MCP client (or you, in the Activity panel) explicitly calls `apply` with the `plan_id` to execute. Plans expire after 5 minutes if not applied. Soft-deletes go to the Trash and are recoverable for 7 days.\n\n## Add-on Compose services\n\nA project can declare **extra** Docker Compose services that Supbuddy discovers, merges, runs, health-checks, and tails alongside the managed stack: a Redis cache, a worker queue, a search engine, etc. Add-on services run on the host's shared Docker daemon in both `host` and `thin` isolation, with no extra setup needed.\n\n### Declaration files & merge precedence\n\nSupbuddy looks for up to three Compose fragments in the project and merges them, later wins:\n\n1. `docker-compose.yml`: your base Compose file.\n2. `docker-compose.override.yml`: your own override, honored if present (standard Compose convention).\n3. `supbuddy.addons.yml`: Supbuddy-owned add-on fragment.\n\nAll present fragments are passed explicitly, e.g. `docker compose -f docker-compose.yml -f docker-compose.override.yml -f supbuddy.addons.yml --project-name <pinned> …`. The project name is pinned so the same set of containers is addressed every time. Add-on services join the Compose project's default network automatically; no extra network setup is needed for them to reach (or be reached by) the rest of the stack.\n\n### `supbuddy.addons.yml` format\n\nA valid Compose fragment (a standard `services:` map) plus an optional Supbuddy-only `x-supbuddy:` extension block. A plain `docker compose up` ignores `x-supbuddy:`, so the file stays usable without Supbuddy. Today `x-supbuddy` supports a one-shot **seed** step:\n\n```yaml\nservices:\n redis:\n image: redis:7-alpine\n ports: [\"6379:6379\"]\nx-supbuddy:\n seed:\n service: redis\n command: [\"redis-cli\", \"ping\"] # explicit argv, runs once after services are healthy\n runOnce: true\n```\n\nThe seed step runs **once** after the add-on services are up and healthy. It's idempotent, keyed by a signature of the seed spec, so it only re-runs if the spec changes (or you force it). It fires automatically on project start, and on demand via the `seed_addons` MCP tool.\n\n### MCP tools\n\n- `scaffold_addons` ( `{ project_id }` ): scope `config`. Creates a starter `supbuddy.addons.yml` if the project doesn't have one. Never clobbers an existing file.\n- `seed_addons` ( `{ project_id, force? }` ): scope `services`. Runs the declared `x-supbuddy.seed` step. Idempotent unless `force: true`.\n- `tail_service_logs` ( `{ project_id, service }` ): scope `log_tail`. Streams a Compose/add-on service's container logs over SSE (like `tail_request_logs`, but for container stdout/stderr).\n- `watch_supabase` ( `{ project_id }` ): scope `log_tail`. Streams a project's live Supabase start/stop/restart progress over SSE: `operation` (status + message), `progress` (image-pull/service snapshots), and `log` (raw lines, VM projects). The stream ends on a terminal status. Backs `supbuddy supabase start --follow`.\n\n### Scripts MCP tools\n\nScripts detected in a project (e.g. `dev`, `build`, `test`) are controllable over MCP:\n\n- `list_scripts` ( `{ project_id }` ): scope `read`. Returns all detected scripts with their current status and bookmark state.\n- `start_script` ( `{ project_id, script }` ): scope `services`. Starts the named script process.\n- `stop_script` ( `{ project_id, script }` ): scope `services`. Stops the named script process.\n- `restart_script` ( `{ project_id, script }` ): scope `services`. Stops then starts the named script process.\n- `bookmark_script` ( `{ project_id, script, bookmarked }` ): scope `services`. Pins (`bookmarked: true`) or unpins a script in the Quick Access group.\n- `tail_script_logs` ( `{ project_id, script }` ): scope `log_tail`. Streams the named script's stdout/stderr over SSE.\n\n### `get_compose_status` shape\n\n`get_compose_status` ( `{ project_id }` ) returns live per-service status, not just whether Compose is installed:\n\n```json\n{\n \"project_id\": \"…\",\n \"compose_installed\": true,\n \"running\": true,\n \"services\": [\n { \"name\": \"redis\", \"status\": \"running\", \"health\": \"healthy\", \"ports\": [\"6379:6379\"], \"image\": \"redis:7-alpine\", \"container_id\": \"…\", \"source\": \"addons\" }\n ]\n}\n```\n\nEach service's `source` is one of `base` | `override` | `addons`, telling you which fragment declared it.\n\n## Per-project AI context sync\n\nEach project has a **Context sync: AI tools** panel, accessible via the **AI Tools** tab in the project card, that writes a project-scoped briefing to disk so AI agents working in that repo see your live mappings, services, and isolation state without having to ask. Files written:\n\n- `.supbuddy/`: `README.md`, `mappings.md`, `services.md`, `project.md`, `mcp.md`, `do-not.md`, `docs.md`. The full live snapshot, regenerated on each sync.\n- `AGENTS.md` and `CLAUDE.md`: a small managed block prepended (or updated in place) telling the agent which project this is and pointing it at `.supbuddy/`.\n- Editor skill files when detected: `.cursor/rules/supbuddy.mdc`, `.claude/skills/supbuddy/SKILL.md`, `.codeium/windsurf/rules/supbuddy.md`, `.continue/rules/supbuddy.md`, `.github/copilot-instructions.md`, `.idea/supbuddy.md`.\n- `.gitignore` managed block, ignoring: `.supbuddy/meta.json` (volatile sync state), `*.supbuddy-backup-*` (rollback snapshots), and the per-editor skill files that are written **locally** (see scope below). The rest of `.supbuddy/` is intended to be committed; `AGENTS.md`, `CLAUDE.md`, and `.github/copilot-instructions.md` are also kept committable since you may have hand-written content there alongside Supbuddy's managed block.\n\n### Global vs. local scope\n\nThe per-editor skill files are generic Supbuddy-owned pointers (\"this is a Supbuddy project: read `.supbuddy/`, prefer the MCP tools\"). For editors that expose a **Supbuddy-owned global location**, Supbuddy writes that pointer **once, machine-wide** instead of copying it into every project, so it isn't duplicated across all your repos. Project-specific data always stays local in `.supbuddy/`.\n\n- **Claude Code** → one global skill at `~/.claude/skills/supbuddy/SKILL.md`. **Cursor** → `~/.cursor/skills/supbuddy/SKILL.md`. The global skill self-scopes: it only acts when the working directory has a `.supbuddy/` folder, and resolves the active project from that folder's `meta.json`.\n- All other targets (`windsurf`, `continue`, the `AGENTS.md`/`CLAUDE.md`/Copilot managed blocks, JetBrains) stay **local**: their \"global\" files are shared user files, so Supbuddy won't overwrite them.\n- Each target has a **scope** setting: `auto` (default: global for the Claude/Cursor skills, local for everything else), `global`, `local` (force per-project, useful if you commit the file for teammates), or `off`. A machine-global file is reference-counted across projects and removed automatically once no project uses it (on disabling sync, deleting a project, or switching that target back to local). Note: uninstalling Supbuddy (e.g. dragging it to the Trash on macOS) does **not** auto-remove these global files; delete them manually from `~/.claude/skills/supbuddy/` and `~/.cursor/skills/supbuddy/` if needed.\n- The always-loaded `CLAUDE.md`/`AGENTS.md` managed block stays local as a safety net so agents stay aware even if the on-demand global skill doesn't auto-activate.\n\nSync modes per project:\n\n- **Auto**: Supbuddy regenerates the files whenever mappings, services, or project state change.\n- **Manual only**: files are only written when you click **Sync now** (or use the tray's *Sync AI context for all projects*).\n- **Off**: nothing is written.\n\nThe collapsed header shows an at-a-glance status pill: mode (`auto` / `manual` / `off`), a colored dot for the last sync result, and a relative timestamp. Disabled targets (e.g. an editor whose folder isn't present) appear greyed out in the **Detected targets** list inside the panel.\n\n## Supbuddy Cloud\n\nPush a project — its Supabase schema **and data** — to a hosted cloud dev-stack (its own full self-hosted Supabase — Postgres, Auth, REST, Storage, Realtime, Studio behind a gateway — as an isolated graph of machines on a per-tenant private network) and control it from the app, the CLI, or MCP. **Opt-in and per-project:** nothing cloud-related appears in a project until you've signed in.\n\n- **Get started** — the top bar shows a **Get started with Supbuddy Cloud** strip; sign in (email/password) there. Once signed in it becomes **Open cloud** (opens [cloud.supbuddy.app](https://cloud.supbuddy.app) in your browser). Sign-in state + the Claude connection also live under **Settings → Cloud**.\n- **Push a project** — after signing in, each project's ⋯ menu gains **Push to cloud…**. The push ships the project's stack descriptor + a `pg_dump` of its Supabase data (fail-closed: uploaded to a private bucket via a single-use key, sha-verified, restored *inside* the stack's private network, then deleted). Your **local project stays intact** — a **☁** badge appears on its row; click it (or ⋯ → **Open in cloud**) to open the stack in the web app.\n- **CLI / MCP** — the same flow headless: `supbuddy cloud login|push|status|teardown` (password via arg or `SUPBUDDY_CLOUD_PASSWORD`), or the `push_to_cloud` / `get_cloud_status` / `cloud_teardown` / `cloud_sign_in` MCP tools. `project ls` marks pushed projects with ☁, and `get_project` / `list_projects` carry the `cloud` link. `cloud_teardown` (and the ⋯ teardown) destroy the remote stack and unlink it locally — routed through the same plan/apply gate as other destructive tools.\n- **Service breadth** — a self-hosted push provisions the **full** Supabase stack by default. Pass `push_to_cloud`'s `supabase_services: \"minimal\"` (MCP) to opt down to a lean db/auth/REST stack instead.\n- **Idle auto-stop** — a running cloud stack that reports no activity for ~30 minutes is automatically **stopped** to save cost (its data + config persist; start it again from the web app). A background reaper also reconciles any stack whose machines went missing.\n- **Web console** — [cloud.supbuddy.app](https://cloud.supbuddy.app) lists your org's stacks; open one for its per-service health, live status, and **start / stop / restart / tear down** controls, plus a **Recent activity** feed of control-plane events. **Push to cloud** in the console provisions a stack from a GitHub `owner/repo` (self-hosted or bring-your-own Supabase; full or minimal service set) — the code-only path; pushing a local project *with its data* still goes through the desktop app / CLI.\n\n## Command-line interface (CLI)\n\nEverything the desktop app can do is also driveable headlessly from a terminal, with no GUI window. The CLI runs a **daemon** (the same worker process the GUI uses: Caddy proxy, DNS, Supabase/Compose lifecycle, MCP-HTTP) and a set of commands that attach to it over the local MCP-HTTP port. This is for SSH sessions, CI, `tmux`/server boxes, and scripting.\n\nThe binary is `supbuddy`, with a short alias `sup`. Run `supbuddy help` for the full usage list.\n\nYou can install the CLI on its own, without the desktop app:\n\n```bash\nnpx supbuddy@latest # asks to install the CLI globally (supbuddy + sup)\n```\n\nThat command does nothing on its own except offer to put `supbuddy` and `sup` on your PATH. The CLI runs independently of the desktop app, so you can add the app later (or never). On a Mac the app installs the same two commands for you.\n\n### The daemon\n\n```bash\nsupbuddy daemon --detach # start the worker in the background\nsupbuddy status # daemon + proxy health\nsupbuddy stop # graceful shutdown\n```\n\n`--detach` backgrounds the daemon and prints its pid + ports. Foreground `supbuddy daemon` runs it attached (Ctrl-C shuts it down cleanly). On start the daemon writes a discovery file, `daemon.json` (mode `0600`), into the shared state dir holding its pid, the Socket.IO port, the MCP-HTTP port, and a control token; every other command reads it to find and authenticate to the daemon, so you never pass ports or tokens by hand. Only one daemon may run per state dir; a second `daemon` start is refused.\n\nThe CLI and the desktop app **share one state dir** (`~/Library/Application Support/Supbuddy/`), so they manage the same projects, mappings, and settings. They must not run two workers against it at once: if you launch the desktop app while a CLI daemon is running, the app detects it and offers to **stop the daemon and continue** or **quit**. It never forks a competing worker (which would corrupt `state.json`).\n\n### Run on login (service)\n\n```bash\nsupbuddy service install # start-on-login (launchd on macOS, systemd-user on Linux)\nsupbuddy service status\nsupbuddy service uninstall\n```\n\n### Commands\n\nAll app surfaces have a command. Names follow `supbuddy <module> <action> [args] [--flags]`. The main groups:\n\n| Group | Examples |\n| --- | --- |\n| Dev launcher | `run [--print] -- <dev command>` — on a Thin project, binds the dev server to the project's loopback IP (from `.supbuddy/meta.json`) so it keeps its canonical port (e.g. `supbuddy run -- next dev` stays on `:3000`) |\n| Health / proxy | `status`, `proxy status\\|start\\|stop\\|restart` |\n| Mappings | `map ls\\|add\\|get\\|set\\|enable\\|disable\\|rm\\|restore` |\n| Projects | `project ls\\|add\\|get\\|scan\\|set\\|enable\\|disable\\|rm\\|restore\\|env\\|refresh-context` |\n| Supabase | `supabase start\\|stop\\|restart\\|status <proj>` (add `--follow` to stream live progress), `supabase config apply <proj> <file>` |\n| Cloud | `cloud login <email> [<pw>]` (or `SUPBUDDY_CLOUD_PASSWORD`), `cloud push <proj> [--repo=owner/repo] [--force]`, `cloud status [<proj>]`, `cloud teardown <proj>` — push a project (with its Supabase data) to a hosted cloud stack; `project ls` marks pushed projects with ☁ |\n| Compose | `compose up\\|down\\|restart\\|status\\|logs <proj> [svcs]` |\n| Scripts | `scripts ls\\|start\\|stop\\|restart\\|logs\\|bookmark <proj> [script]` |\n| Isolation | `isolation switch <proj> <host\\|thin>`, `isolation pending-migrations`, `migrate start\\|finish <uuid>` |\n| Certificates | `ca status\\|install\\|uninstall` |\n| Env files | `env copy <src> <key> <target>`, `env write <path> <K=V>…` |\n| Settings | `settings get`, `settings set --json <patch>` |\n| MCP | `mcp add [<agent>]` (register Supbuddy into a coding agent: interactive, or `--write`/`--print`/`--prompt`), `mcp ls`, `mcp revoke <id>`, `mcp approvals apply\\|cancel <id>` |\n| Host / network | `connect`, `trust`, `tailscale`, `dns`, `pf` (port-forwarding) |\n| Logs | `logs requests [-f]`, `logs audit [-f]`, `logs get <id>` |\n| Account | `account`, `caps`, `addons scaffold\\|seed <proj>` |\n| Dashboard | `tui` (alias `dash`) |\n\nGlobal flags: `--json` (machine-readable output), `--yes` (skip confirmations), `--quiet`, `--url`/`--token` (attach to a specific/remote daemon instead of auto-discovery), `--state-dir` (override the shared dir), `--timeout`, and `-f`/`--follow` for streaming log commands and live `supabase start|stop|restart` progress.\n\nDestructive operations go through the same **plan → apply** gate as MCP (see *Plan / apply for destructive tools*); the CLI's control token is granted auto-apply, so they execute directly.\n\n### Live dashboard (TUI)\n\n```bash\nsupbuddy tui # or: sup dash\n```\n\n`supbuddy tui` opens a full-screen terminal dashboard that attaches to the running daemon and shows live connection/proxy status, the project list (with each project's isolation, Supabase, and Compose state), the mapping count, and a tail of recent requests. Press `r` to refresh, `q` to quit. It needs a running daemon (`supbuddy daemon --detach`); if none is found it tells you so.\n\n## Settings reference\n\nOpen Settings via the gear icon top-right or by clicking the tray icon → Open Dashboard → gear. Five tabs.\n\n### General\n\n- **Theme**: dark or light.\n- **Auto-start at login**: registers Supbuddy as a macOS login item. Default: on.\n- **Default TLD**: applied to new auto-generated mappings. Existing mappings are renamed to the new TLD on save. Default: `test`.\n- **Default isolation**: `host` or `thin` for newly added projects. Default: `thin` (per-project loopback IP; apps keep canonical ports like `:3000`). MCP registration additionally keeps a project on `host` when its Supabase stack is already running on the host outside Supbuddy.\n- **Auto-subdomain mapping**: when on, services and apps detected during a project scan get mappings created automatically. Default: on.\n- **Bundled-runtime trust**: installs Supbuddy's local root CA into a place that apps with bundled JavaScript runtimes (Claude Code, Cursor, Windsurf, Continue, Codex CLI, OpenCode, …) actually read. These apps don't consult the system Keychain (they ship their own Mozilla bundle), so without this they fail OAuth/MCP/HTTPS calls to `*.test` with `unable to get local issuer certificate`. Default: prompted on first launch when one of those tools is detected.\n - **macOS**: writes `~/Library/LaunchAgents/com.cueplusplus.supbuddy.bundled-runtime-ca-trust.plist` and calls `launchctl setenv NODE_EXTRA_CA_CERTS / SSL_CERT_FILE / REQUESTS_CA_BUNDLE` so GUI-launched apps inherit the right vars at process-start time.\n - **Linux**: writes `~/.config/environment.d/supbuddy-ca.conf` (read by systemd-aware user sessions on GNOME/KDE/Sway/etc.).\n - **Windows**: per-user `setx NODE_EXTRA_CA_CERTS / SSL_CERT_FILE / REQUESTS_CA_BUNDLE` to `HKCU\\Environment`.\n - All three env vars point at `~/Library/Application Support/Supbuddy/ca-bundle/current.crt` (or the platform-equivalent), a *cumulative* concatenated PEM Supbuddy maintains. When Caddy rotates its root (yearly today, sometimes more), Supbuddy appends the new root automatically; long-running TLS contexts holding the old root keep working until the process restarts.\n - **Test trust**: runs an in-process HTTPS request against the first available `*.test` mapping with the same env vars set, to verify end-to-end without relaunching anything.\n - **Conflict refusal**: if `NODE_EXTRA_CA_CERTS` is already set to something else (corporate proxy, Zscaler), Supbuddy refuses to overwrite and surfaces the conflicting path. You can override with the explicit prompt that pops up on Install.\n - **Quit and relaunch your AI tools** after install: the env var only takes effect for *newly-launched* processes.\n\n### Network\n\n- **HTTP port**: default 8080.\n- **HTTPS port**: default 8443.\n- **DNS port**: default 5353.\n- **Port forwarding**: when on, adds a `pfctl` rule mapping 80→HTTP port and 443→HTTPS port. Asks for sudo once.\n- **LAN sharing**: binds Caddy to `0.0.0.0` + starts mDNS responder.\n- **Tailscale**: paste a tailnet API key to enable split-DNS push.\n- **Install / Uninstall CA**: installs Caddy's root cert into your Keychain. Uninstall is not yet implemented (manual remove via Keychain Access).\n\n### Storage\n\nTrash retention (per-kind), volume sizes, image-cache controls.\n\n### MCP\n\n- **Clients**: list of connected clients. Each row has a **⋯** actions menu: install, edit scopes, set-primary, rotate token, revoke.\n- **Activity**: audit log with Apply/Cancel/Undo on plan rows.\n- **Trash**: soft-deleted mappings and projects, restorable for 7 days.\n- Settings: server `enabled`, `port` (default 9877), `audit_cap` (default 5000), `trash_ttl_days` (default 7).\n\n### AI Skills\n\nInstall Supbuddy's agent **skill at the user level** (machine-wide) so the agent sees Supbuddy in every repo without per-project setup. Each global-capable agent has a **master on/off** plus an **autosync** toggle (keeps the installed skill refreshed when Supbuddy updates it) and shows its install path + version.\n\n- **Who can install at user level**: only agents whose global file Supbuddy fully **owns** and that **self-scope** (act only when the working directory has a `.supbuddy/`): **Claude Code** (`~/.claude/skills/supbuddy/SKILL.md`) and **Cursor** (`~/.cursor/skills/supbuddy/SKILL.md`). The install is reference-counted under a synthetic `__user__` ref so it persists independent of any project and is never pruned by the boot reconcile.\n- **Master ↔ project**: the AI Skills tab is the **master** (user-level). To commit a skill into a specific repo, use that project's **AI Tools** tab and set the target to **Project** (the old `local` scope, which writes into the repo for teammates); **User** there means the master install covers it.\n- Agents whose global file holds *your own* content (Claude `CLAUDE.md`, Codex `AGENTS.md`, Copilot, Windsurf, Continue, JetBrains) are **project-level only**: a machine-wide write there could clobber your config, so they're injected per-project instead.\n\n## Tray menu\n\nThe macOS menu bar tray icon opens a menu with:\n\n- **Status: …**: current proxy state (running / idle).\n- **DNS Active (:5353)**: shown when proxy is running.\n- **LAN Sharing (\\<ip\\>)**: shown when LAN sharing is on.\n- **Tailscale (\\<ip\\>)**: shown when Tailscale is connected.\n- **Start Proxy / Stop Proxy**: opens the dashboard.\n- **Projects**: each project opens a submenu with **Apps** (click to open the mapped URL), **Supabase** services (status dot + open), and **Scripts** (your bookmarked scripts as a one-click **Start <name>** / **Stop <name>** toggle), plus **Restart Supabase**/**Restart services** and **Show in Supbuddy**.\n- **Open Dashboard**.\n- **Sync AI context for all projects**: runs the project-context sync engine for every registered project (writes `.supbuddy/`, `CLAUDE.md`, `AGENTS.md`, etc.).\n- **Show Logs**: reveals `main.log` in Finder.\n- **Check for Updates...**: manual update check (only enabled in packaged builds).\n- **Quit**.\n\n## File locations\n\nAll under `~/Library/Application Support/Supbuddy/` on macOS:\n\n- `main.log` + `main.log.1`: app logs (rotates at 2 MB).\n- `state.json`: persistent state (projects, mappings, settings, MCP clients, license).\n- `caddy-data/`: Caddy's data dir (PKI, autosaves, certs).\n- `caddy-data/caddy/pki/authorities/local/root.crt`: the local CA cert installed in your Keychain.\n- `ca-bundle/current.crt`: cumulative PEM containing every Caddy root that has ever been emitted. Used by **Bundled-runtime trust** as the target for `NODE_EXTRA_CA_CERTS` / `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE`. Real file (not a symlink) so Bun-bundled CLIs read it correctly.\n- `ca-bundle/versioned/<sha>.crt`: per-root snapshots for forensics.\n- `Caddyfile`: generated reverse-proxy config.\n- `daemon.json`: written while a headless CLI daemon is running (pid, Socket.IO + MCP-HTTP ports, control token); `0600`, removed on shutdown. Used by `supbuddy` CLI commands to discover and authenticate to the daemon, and by the desktop app to detect a running CLI daemon at launch.\n- `certs/`: legacy CA from the pre-Caddy era (unused in current builds).\n\nMCP-specific:\n\n- MCP client tokens (file-backed secret, mode `0600`): `~/Library/Application Support/Supbuddy/secrets/mcp-<client-id>.secret`\n- MCP audit log: under `~/Library/Application Support/Supbuddy/`, capped at `audit_cap` entries (default 5000).\n\n## Troubleshooting\n\n### Browser shows \"Not secure\" or certificate warning\n\nThe Caddy CA is not trusted. Open **Settings → Network → Install Certificate**. macOS will prompt for your password. After install, fully restart your browser (Cmd+Q, not just close window). Verify: *Keychain Access* → System keychain → search for \"Caddy Local Authority\".\n\n### \"unable to get local issuer certificate\" / \"self signed certificate in certificate chain\" from Claude Code, Cursor, MCP servers, or other AI tools\n\nThese tools ship their own bundled JavaScript runtime (Bun, Electron, pkg-bundled Node) and ignore the system Keychain. Open **Settings → General → Bundled-runtime trust** and click **Install**. Then *fully quit and relaunch* the AI tool; the env vars only take effect for newly-launched processes. Verify with `launchctl getenv NODE_EXTRA_CA_CERTS` (macOS); it should print `~/Library/Application Support/Supbuddy/ca-bundle/current.crt`. If install is refused with a conflict warning, you already have `NODE_EXTRA_CA_CERTS` set (often a corporate proxy / Zscaler), so Supbuddy won't silently overwrite; use the override prompt or manually concatenate the two PEMs.\n\n### \"Docker is not running. Please start Docker Desktop.\"\n\nCompose and Supabase features need Docker. Open Docker Desktop and wait until the whale icon stops animating.\n\n### \"Docker Compose is not installed\"\n\nCompose v2 ships inside Docker Desktop. If you removed Docker Desktop and are using a standalone Docker daemon (e.g. Colima, Rancher), install compose: `brew install docker-compose`.\n\n### \"Leftover host containers\" / \"isolation drift\" warning on a project\n\nSupbuddy flags **isolation drift** when a project's running containers don't match its configured isolation mode, for example a **Host** project with a stale `thin`-mode stack still running, or a **Thin** project with leftover host-mode containers. Switching isolation modes doesn't tear down the old layer, so those containers linger, waste resources, and can shadow the project's real stack. The warning appears in the **warnings chip** next to the enable toggle (click it to see each item; it shows a spinner while Supbuddy re-checks), as an entry in the issues counter, and as a notice on the **Supabase** tab listing the exact containers and any data volumes.\n\n**Guided cleanup.** Open the Supabase tab → **Clean up leftovers…** to stop and remove the leftover containers. Data volumes are kept by default; deleting them is opt-in, and when the leftover copy looks newer than the active one, it requires an explicit choice and a backup (tarred to `…/Supbuddy/backups/<project>-<timestamp>/`). If you recently migrated a VM project, any leftover VM container from before migration can also be cleaned up from this flow.\n\nIf the leftover copy's data looks **newer** than the active one, the warning turns red; don't delete its volumes without first deciding which copy to keep. The Configure tab also shows a dismissible note when Supabase stacks are running on your host that Supbuddy doesn't manage at all (e.g. a plain `supabase start`).\n\n### MCP client says \"Invalid OAuth error\" or \"JSON Parse error: Unexpected EOF\"\n\nThe MCP client is trying OAuth discovery and getting an empty 404. Either the token was lost (regenerate it in **Settings → MCP → the client's ⋯ menu → Rotate token**) or you're on a build older than the OAuth-probe fix. Update to the latest version; the server now answers OAuth discovery paths with a structured 404 instead of an empty body, and 401 responses include `WWW-Authenticate: Bearer` so the client doesn't fall back to OAuth.\n\n### MCP token disappeared after app restart\n\nFixed in recent builds. If you're on an older version, regenerate the token. Root cause was that `addMcpClient` didn't trigger state persistence; the client was held in memory only.\n\n### Server Actions return 403 in a Next.js app behind Supbuddy\n\nNext.js's CSRF guard rejects POSTs whose Origin isn't in `experimental.serverActions.allowedOrigins`. Supbuddy detects this and flags it in the warnings chip: open the **Apps** tab and hit **Fix** on the affected app for a paste-ready snippet, or **Apply…** to preview a unified diff and write the change to `next.config` directly. After applying, restart your dev server.\n\n### Vite dev server returns \"Blocked request. This host is not allowed.\" (403)\n\nVite (v5+) rejects requests whose `Host` header isn't in `server.allowedHosts`, so a Vite app reached through a Supbuddy domain 403s until the host is allowed. Supbuddy detects this and flags `vite: N hosts blocked` in the warnings chip: open the **Apps** tab and hit **Fix** on the affected app for a paste-ready snippet, or **Apply…** to preview a diff and write `server.allowedHosts` into your `vite.config` directly. **Restart the Vite dev server afterward**; Vite does not hot-reload its config. A single `.your-project.local` entry covers every subdomain.\n\n### Supabase Realtime: channel reaches `SUBSCRIBED` but no `postgres_changes` events arrive\n\nIf a channel subscribes fine (and writes succeed) but change events never fire, this is almost always **realtime warmup timing right after the stack starts** — not the Supbuddy proxy. Local Realtime can accept a channel join and report `SUBSCRIBED` before its logical-replication binding for the tenant is ready, so `INSERT`/`UPDATE`s in that brief window are silently missed. Give the stack a few seconds after the Supabase tab goes green, then re-subscribe (or reconnect the channel). This is **unrelated to the `.local` domain**: Kong routes `/realtime/v1/*` by path and rewrites the upstream `Host` to its internal realtime tenant, so reaching realtime through `https://api.<project>.local` behaves identically to the raw `localhost:54321` port — forwarding the `.local` host upstream does not change tenant resolution. The new `sb_publishable_*` / `sb_secret_*` API keys also work for local realtime (Kong maps them to the legacy JWT), so you don't need to switch key formats.\n\n### Project shows a red \"PROXY ERROR\" banner: domain resolves but won't load\n\nAfter the proxy starts, Supbuddy runs an end-to-end reachability check: it resolves a project domain through the OS resolver and tries to connect to Caddy on the HTTPS port. If the name resolves but the connection fails, the project shows a red **PROXY ERROR** banner naming the likely cause (DNS, port-forwarding, or mDNS race) plus a recovery action.\n\nThe most common case: the domain resolves to `127.0.0.1` but port 443 won't connect because the elevated `pfctl` 443→8443 redirect drifted away (typically after a restart, so Caddy is up on 8443 with nothing forwarding 443). Click **Retry**; as of v2.3.6 it re-applies the port-forwarding rule (approve the sudo prompt). On older builds, toggle the proxy off→on instead. If LAN sharing is **off**, disregard any \"LAN sharing / Bonjour\" wording in the banner; the cause is the missing forward, not mDNS.\n\n### Port already in use (8080, 8443, 5353, 9877)\n\nDefault ports: HTTP 8080, HTTPS 8443, DNS 5353, MCP 9877. Change them in **Settings → Network** / **Settings → MCP**. Find what's holding a port: `lsof -i :<port>`.\n\n### Wipe everything and start over\n\nQuit Supbuddy, then:\n\n```bash\n# Wipe app data (state, certs, Caddyfile, logs, MCP tokens under secrets/)\nrm -rf ~/Library/Application\\ Support/Supbuddy\n\n# Optional: remove the trusted CA\nsudo security delete-certificate -c \"Caddy Local Authority\" /Library/Keychains/System.keychain\n```\n\n## FAQ\n\n### Is Supbuddy free?\n\nYes. Supbuddy is free. Register as many projects and mappings as you want, with full HTTPS, full DNS, full Supabase isolation, and full read and write MCP access. There are no caps and no tiers.\n\n### Does Supbuddy send my data anywhere?\n\nNo. Caddy, the DNS server, and the MCP server all run locally on your Mac. The only outbound traffic is: Tailscale split-DNS push (only if you enabled it), auto-update checks (GitHub Releases), and Google Analytics on the marketing site (not the desktop app). The desktop app does not send telemetry.\n\n### Can I work offline?\n\nYes. The app works fully offline once the CA is trusted and projects are registered.\n\n### Linux / Windows support?\n\nThe desktop app is macOS-only in v2. The headless CLI and daemon also run on Linux, where `supbuddy service install` registers a `systemd-user` start-on-login unit (macOS uses `launchd`). Windows is not supported. A few desktop code paths (certutil, update-ca-certificates) anticipate other platforms but are not tested there.\n\n### Can I use my own TLD?\n\nYes. Set any TLD in **Settings → General → Default TLD**. Supbuddy installs `/etc/resolver/<project-domain>` files that tell macOS to query our DNS server for that project's domain. Avoid TLDs that actually resolve on the public internet (.com, .net, etc.); your browser will hit the real site for cached entries.\n\n### What happens if I delete a project?\n\nThe project moves to the Trash (visible in **Settings → MCP → Trash**) for 7 days, then is permanently deleted by the sweep timer. Restoring brings back the project record and all its mappings.\n\n### How do I uninstall Supbuddy?\n\n1. Quit the app.\n2. Drag **Supbuddy.app** from `/Applications` to the Trash.\n3. Optional cleanup: see \"Wipe everything and start over\" above.\n4. Optional: `sudo security delete-certificate -c \"Caddy Local Authority\" /Library/Keychains/System.keychain` to remove the trusted CA.\n\n### Where do I report a bug?\n\nEmail support with your version (visible at the bottom of the Settings popover) and the relevant lines from `~/Library/Application Support/Supbuddy/main.log`.\n";
44335
+ const DOCS_MARKDOWN = "# Supbuddy docs\n\n> Run multiple Supabase projects at once on one Mac, each with its own custom local domain.\n\n## Getting started\n\nThere are two ways to run Supbuddy. Use the **macOS desktop app** (steps below), or the **command-line interface**, which runs on macOS and Linux. For the CLI, install it with `npx supbuddy@latest` and jump to [Command-line interface](#command-line-interface-cli). The app and the CLI share the same state, so you can use either or both.\n\n### 1. Install\n\nDownload the latest `.dmg` from the [download page](/api/download). Drag **Supbuddy.app** into `/Applications` and launch it. Supbuddy is signed and notarized; macOS will not show a Gatekeeper warning. Requires an Apple Silicon Mac (M1/M2/M3/M4, arm64). The desktop app is macOS-only in v2, but the headless CLI runs on Linux too. See [Command-line interface](#command-line-interface-cli).\n\n### 2. Trust the local Certificate Authority\n\nCaddy mints its local CA the first time it actually serves a site, so the cert only exists once you have **at least one enabled mapping and the proxy running** — an empty proxy never generates it. With that in place, open the app and click **Install** (the first-launch prompt, or **Settings → Network** later). Supbuddy adds the CA (Caddy's internal PKI at `~/Library/Application Support/Supbuddy/caddy-data/caddy/pki/authorities/local/root.crt`) to your **System keychain** via `sudo security add-trusted-cert`; macOS asks for your password once. Caddy does **not** self-install trust (the generated Caddyfile sets `skip_install_trust`), so this button is what makes the padlock green — fully quit and reopen your browser afterward to pick it up. Every Supbuddy domain then gets HTTPS with no per-domain prompts or warnings. (On Windows the install is manual: Supbuddy shows the PowerShell `Import-Certificate … -CertStoreLocation Cert:\\LocalMachine\\Root` command to run as Administrator.)\n\nCaddy names its root by year, so each yearly rotation (or a data wipe) leaves a same-name root behind with a different key. On every Install, Supbuddy first removes any stale `Caddy Local Authority` roots whose fingerprint doesn't match the current one, then adds the current root — leftover mismatched roots otherwise make Firefox-family browsers fail with `SEC_ERROR_BAD_SIGNATURE`.\n\n**Firefox, Zen, and Brave keep their own certificate store** that Supbuddy can't reach (they don't consult the System keychain). After a CA change, either delete any stale `Caddy Local Authority` entries from the browser's own certificate manager and re-import the new root, or — on Firefox/Zen — set `security.enterprise_roots.enabled` to `true` in `about:config` so the browser reads the System keychain.\n\nIf Supbuddy detects an AI tool that ships its own JavaScript runtime (Claude Code, Cursor, Windsurf, Continue, Codex CLI, OpenCode, etc.) it will also offer to enable **Bundled-runtime trust** in the same first-run prompt. Those tools don't read the system Keychain (they carry their own Mozilla CA bundle), so without this setup the first OAuth/MCP connection to a `*.test` URL fails with `unable to get local issuer certificate`. Enable it once and Supbuddy keeps it in sync (including across yearly Caddy CA rotation). See the **Bundled-runtime trust** section under Settings → General for details.\n\nIf you skip the prompt, you can re-trigger it any time from the **Settings → Network** tab.\n\n### 3. Add your first project\n\nClick **Add project** in the Configure tab and pick a project root folder (the one with `package.json` and/or `supabase/config.toml`). Supbuddy scans it and creates auto-mapped subdomains based on what it finds:\n\n- Supabase Kong → `api.<project>.test`\n- Supabase Studio → `studio.<project>.test`\n- Supabase Inbucket / Mailpit → `mail.<project>.test`\n- Each detected app (Next.js, Vite, etc.) → `<app-name>.<project>.test`\n\nThe default TLD is `.test`. You can change it project-wide in **Settings → General → Default TLD**.\n\n### 4. Start the proxy\n\nToggle the project on. Supbuddy starts Caddy on port 8443 (HTTPS) and starts its built-in DNS server on port 5353. If you want real ports 80/443 instead of 8080/8443, enable **port forwarding** in **Settings → Network**. Supbuddy inserts a `pfctl` redirect rule into `/etc/pf.conf` (asks for sudo once) and reports whether the redirect is actually being enforced via a live 443 probe — not merely that the rule is on disk. If port forwarding is on but 443 won't connect, see [Port forwarding is on but 443 won't connect](#port-forwarding-is-on-but-443-wont-connect).\n\n> If the one-time sudo prompt is cancelled or fails, Supbuddy no longer aborts the start: Caddy still comes up and HTTPS keeps working on the high port (8443), and the proxy shows a degraded **error** state with a **Retry** so you can re-run the privileged setup. The CA is still generated in this state.\n\n## Core concepts\n\nFour things to understand:\n\n- **Project**: a folder you registered. Holds detected *apps* (Next.js, Vite, etc.), detected *services* (Supabase stack, Docker Compose services), and a list of *mappings*.\n- **Mapping**: a domain → port pair (e.g. `api.acme.test → 54321`). Auto-generated mappings are tied to a detected service or app; you can also create manual ones.\n- **Isolation mode**: per-project. One of:\n - `thin` (lightweight, **the default for newly registered projects**): still your host Docker (no nested containers, no DinD), but Supbuddy gives each project its own **port block** and a unique Compose `project_id`, written into that project's `supabase/config.toml`. That's what lets several Supabase projects run **at once on the shared daemon**, each reached by name (`api.<project>.test`, `studio.<project>.test`). Apps bind a **per-project loopback IP** (127.0.0.2, 127.0.0.3, …) so every project's dev servers keep their canonical ports — each project gets its *own* `:3000`. Start dev servers with `supbuddy run -- <dev command>` so they bind that IP. Supbuddy owns those config.toml keys while the project is `thin` and restores them the moment you switch back to `host`.\n - `host`: everything shares `127.0.0.1` and the stock ports. Dev-server ports collide across projects, and only one host-mode Supabase project can run at a time (the standard `supabase start` constraint). Use `host` **only when the project's Supabase stack is already running on the host independently of Supbuddy** (you run `supabase start` yourself and don't want Supbuddy re-porting `config.toml`). MCP registration (`register_project`) detects that case and keeps such projects on `host` automatically; in the app's Add-project dialog, pick **Host** in the Environment section yourself.\n- **Active vs inactive**: any project can be \"active\" (proxied + reachable) or inactive. Inactive projects keep their state, so flipping them on is a few seconds. Run as many active projects as you want.\n\n## Project cards (Configure tab)\n\nEach registered project appears as a card in the Configure tab. Cards have a single-row header that's always visible and a tab-based body that expands on click.\n\n### Header\n\nReading left to right:\n\n- **Expand chevron** + **project name**: click to expand/collapse the card.\n- **Status indicator**: a single colored dot next to the project name aggregating the realtime state of every subsystem (Supabase services, Compose, scripts, AI sync, port conflicts, next.config warnings). Red = error, amber = warning, green = at least one service running, muted gray = idle, animated cyan spinner = transitioning. Hover for a tooltip that lists each subsystem's state.\n- **Tech badges**: e.g. `TurboRepo`, `Supabase` (shown when detected).\n\n**Supabase connection warning.** When a project's app `.env` is missing the\nSupabase connection vars, or they've gone stale relative to the live target\n(e.g. after switching isolation, which republishes ports), the card shows a\n`supabase env: not connected` / `supabase env: out of date` pill. Click it to\nopen Connect and push fresh values, or choose **Ignore for this project**.\n- **Env mode chip**: read-only `Host` or `Thin` label (matching the project's isolation mode). To switch modes, open the **Supabase** tab and use the **Environment** section at the top.\n- **Issues counter**: red for errors, amber for warnings. Click to open the **issues popover** (see below). Hidden when there are no issues.\n- **Warnings chip**: all project-level warnings (isolation drift, missing env vars, config issues, etc.) are consolidated into a single amber chip next to the enable toggle. Click it to see each warning item-by-item; it shows a spinner while Supbuddy re-checks the project.\n- **Enable toggle** (right edge): turn the project's proxy on/off without deleting it.\n- **⋯ actions menu** (right edge): every project-level action: **Edit project**, **Rescan**, **Re-check configs** (re-runs the connection/env drift check for this project), **Select folder**, **Export bundle**, and **Delete project**.\n\n### Issues popover\n\nClicking the issues counter opens a popover listing all current errors and warnings. Each issue shows a severity icon, title, optional detail, and a **→ open {tab}** link. Clicking the link jumps to the relevant tab and closes the popover.\n\n### Body tabs (when expanded)\n\nThe body renders a flat tab strip with 6 conditional tabs. Below ~480 px, the strip collapses to a dropdown selector. (Project-level actions, like edit, rescan, re-check configs, select folder, export, and delete, are in the header's **⋯ menu**, not a tab.)\n\n#### Apps (default tab)\n\nPer-app rows are domain-first: `domain → :port` (with hover-revealed copy/open URL buttons), then app name + tech badge, then a flex spacer pushes hover-revealed **edit** / **delete** / **access** (LAN / Tailscale state) actions and the per-mapping **toggle** to the right edge. A **Map** CTA appears on hover for unmapped apps. Manual mappings scoped to this project (not auto-generated) are listed below under their own subheader.\n\n#### Supabase (shown when Supabase is detected)\n\n**Environment section (top):** host/thin switcher. A legacy project still on the old Isolated (VM) mode shows the migration wizard here instead (see [Migrating a legacy Isolated (VM) project to Thin](#migrating-a-legacy-isolated-vm-project-to-thin)).\n\n**Action bar:** Start, Stop, Restart buttons; a first-class **Connect** button (cyan, opens the connection panel for `.env` generation / merge); and a **More** menu with **Config editor** and **Details**.\n\n**Config editor: secret extraction.** When you save a `supabase/config.toml` that contains a secret-bearing value inline (e.g. an SMTP password under `[auth.email.smtp]`, an OAuth `secret`, or any `*_key`/`auth_token`), Supbuddy prompts before writing: it lists the detected secrets and lets you pick which gitignored env file to move them to (defaulting to the project-root `.env.local`). The value is written there and replaced in `config.toml` with an `env(SUPABASE_…)` reference, so secrets never land in git. Supbuddy injects those `SUPABASE_`-prefixed values back into the `supabase start` environment so the references resolve. (Saving a config with no inline secrets writes directly, with no prompt.)\n\n**Service rows** (read-only): status dot, service name, URL. No inline actions; lifecycle is driven by the action bar.\n\n#### Compose (shown when Compose services are detected)\n\n**Action bar:** Start, Stop, Restart. **Service rows** are read-only (status dot, name, URL). Add-on services declared in `supbuddy.addons.yml` (see **Add-on Compose services**) appear here alongside the base stack and in `get_compose_status` over MCP.\n\n#### Other (shown when non-Supabase, non-Compose services are detected)\n\nRead-only service rows: status dot, name, URL.\n\n#### Scripts (shown when scripts are detected)\n\nBookmarked scripts appear in a **Quick Access** group at the top; remaining scripts appear under **Other Scripts**. Per-script row: status dot, name, uptime, bookmark star, Start/Stop/Restart buttons. A search input appears when there are more than 5 scripts.\n\n#### AI Tools\n\nWraps the project-context-sync panel: sync mode selector (Auto / Manual / Off), detected targets list with per-target **scope** (global / local), advanced options, and recent activity. See [Per-project AI context sync](#per-project-ai-context-sync) for what global vs. local means.\n\n> Project-level actions (**Edit**, **Rescan**, **Re-check configs**, **Select folder**, **Export bundle**, **Delete**) are no longer a tab. They live in the header's **⋯ actions menu**.\n\n---\n\n## Multiple Supabase projects (the main use case)\n\nThe reason Supbuddy exists. Stock Supabase CLI binds to fixed ports (54321 Kong, 54322 Postgres, 54323 Studio, 54324 Inbucket). Two projects on the same machine collide; you must `supabase stop` one before `supabase start`-ing the other.\n\nTwo ways to break that constraint, picked per project in the **Supabase** tab → **Environment** section:\n\n### Thin (lightweight, recommended)\n\nSwitch a project to **Thin**. Supbuddy assigns it a free port block (in the `55000+` range), writes those ports plus a unique Compose `project_id` into its `supabase/config.toml`, and runs `supabase start` on your **normal host Docker**, with no nested containers and nothing to pull. Several projects boot side by side this way; each is reached by name (`api.acme.test`, `studio.acme.test`, `mail.acme.test`). Switch back to **Host** and Supbuddy restores the original `config.toml` and stops just that project's stack.\n\nThis is the lightest, fastest option and the right default for most setups — which is why **newly registered projects default to Thin**. One caveat: if your `config.toml` omits a port key (e.g. `[inbucket] smtp_port`), Supbuddy can't relocate a port that isn't declared, so that one service falls back to its stock port. That is fine for a single project, but spell those keys out if two Thin projects need the same service.\n\n### Dev servers on Thin: every project keeps its own `:3000`\n\nA Thin project also gets its own **loopback IP** (127.0.0.2, 127.0.0.3, …, persisted per project). Its app dev servers bind that IP instead of `127.0.0.1`, so canonical ports never collide across projects — five Next.js apps in five projects can all run on `:3000` at once, and Supbuddy's proxy routes each `web.<project>.test` to its project's IP.\n\nStart dev servers through the launcher:\n\n```bash\nsupbuddy run -- next dev # binds -H <project loopback IP>, stays on :3000\nsupbuddy run -- vite # injects --host <ip> --strictPort\nsupbuddy run --print -- next dev # show what would run, without running it\n```\n\n`supbuddy run` reads the project's IP from the nearest `.supbuddy/meta.json` (`loopbackIp`, written when Thin is enabled), ensures the loopback alias exists, injects the right bind flag for the detected framework, and execs your command. It prints one concise line with the project's Caddy-proxied URL (e.g. `[supbuddy] → https://web.<project>.test`) — the address you should actually open. For **Next and Vite** it also hides the dev server's own `- Local:/- Network:` banner (which only echoes the raw loopback IP `127.0.0.N:<port>`, bypassing Supbuddy's HTTPS proxy): those two lines are filtered out of the piped output, every other line passes through untouched, and colours are preserved via `FORCE_COLOR` (stdin stays interactive). Other frameworks pass through with no filtering. When a project has several app mappings, it matches the one whose port equals the dev server's port (from `--port`/`-p` or the framework default), else lists them all. Make it the project's `dev` script (`\"dev\": \"supbuddy run -- next dev\"`) so nobody — humans or agents — has to remember it. **Never move an app to a nonstandard port because `127.0.0.1:3000` is busy**; that port belongs to another project's IP space.\n\n### When to stay on Host\n\nKeep a project on **Host** only when its Supabase stack runs on the host *independently of Supbuddy* — you run `supabase start` yourself on the stock ports and don't want Supbuddy rewriting `config.toml`. MCP registration (`register_project`) detects a stack like that (running containers for the project's `config.toml` `project_id`) and keeps the project on Host automatically; in the app's Add-project dialog, pick **Host** in the Environment section for such projects. Stop the stack (`supabase stop`) and switch to Thin whenever you're ready.\n\n### Running them all at once\n\nRegister as many projects as you want, and all of them can be \"active\" (proxied) at the same time. There's no limit. A Thin project's stack restarts in seconds; a Host project needs the standard `supabase start` cycle.\n\n### Migrating a legacy Isolated (VM) project to Thin\n\nIf you created a project in an older version of Supbuddy that used the now-retired **Isolated (VM)** mode, Supbuddy detects it on launch and offers a one-way, guided migration to **Thin**. The migration wizard appears in the **Supabase** tab's Environment section for any project still flagged as VM.\n\nThe migration is data-safe: Supbuddy dumps your Postgres data, starts a fresh Thin stack, restores the dump into it, and row-count-verifies the restore before tearing down the old VM container. No data loss. After migrating, the VM is gone and there's no way to switch back (but your data is intact in the Thin stack).\n\nOver MCP, three tools handle the migration bridge:\n\n- `list_pending_vm_migrations` (read): lists all projects still on the legacy VM mode awaiting migration.\n- `migrate_vm_to_thin` ( `{ project_id }` ) (write): starts the guided data-safe migration (dump, restore, verify).\n- `finish_vm_migration` ( `{ project_id }` ) (write): tears down the old VM container after migration is verified. Returns an error if called before verification passes.\n\n## Custom domains & TLDs\n\nEvery mapping resolves through Supbuddy's built-in DNS server on port 5353. By default the TLD is `.test` (an IETF-reserved TLD safe for local use). You can change the default in **Settings → General → Default TLD** to `local`, `dev`, or anything else; existing mappings are migrated to the new TLD on save.\n\nFor host resolution, Supbuddy *does not* use `/etc/hosts` for wildcards; it runs a DNS resolver. macOS's default resolver only queries port 53; Supbuddy installs a per-project resolver file under `/etc/resolver/<project-domain>` (e.g. `/etc/resolver/myapp.local`) pointing at `127.0.0.1:5353`. macOS picks the longest-suffix-matching file, so per-project entries route reliably without colliding with reserved namespaces like `.local` (which Bonjour/mDNS owns). You'll be prompted for sudo the first time this changes.\n\n### Per-project TLD\n\nBy default every project's domain uses the global TLD (Settings → Default TLD, e.g. `.test`). A single project can opt into its **own** TLD — set the suffix in the project dialog, pass `tld` to the `register_project` / `update_project` MCP tools, or use the CLI: `supbuddy project add <path> --tld=portal` when registering, or `supbuddy project set <project> --tld=portal` on an existing one (`--tld=` with an empty value clears the override). That project's base domain and all its subdomains then live on the override TLD (e.g. `cueplusplus.portal`, `web.cueplusplus.portal`) while every other project stays on the global default. The override is durable across restarts and is unaffected when you change the global TLD. Prefer `.test` or a vanity label like `.portal`; avoid `.local` (it collides with macOS mDNS/Bonjour).\n\n### LAN sharing\n\nWhen LAN sharing is enabled (Settings → Network), Supbuddy binds Caddy to `0.0.0.0` instead of `127.0.0.1` and runs an mDNS responder so other machines on your local network can reach your dev servers via `<hostname>.local`. Useful for testing on your phone or another laptop without setting up Tailscale.\n\n**`.local` TLD + LAN sharing:** macOS reserves the `.local` namespace for Bonjour/mDNS (RFC 6762), and macOS's TCP stack short-circuits self-connections to your own LAN IP via the loopback path *without consulting `pf`*, so the obvious \"redirect lo0 → my LAN IP\" trick can't fix it. Supbuddy's mDNS responder works around this by **ignoring queries that originate from this machine**, letting the OS resolver fall through to `/etc/resolver/<project-domain>` (which routes to `127.0.0.1` where Caddy listens). Other LAN devices still get answered with the LAN IP and reach you normally. The net result: `.local` works correctly both on this machine and on other LAN devices, with no manual configuration. If you previously worked around this by switching to `.test`, you can switch back.\n\nIf `studio.<project>.local` (or similar) doesn't load: open the Configure tab. A red banner will tell you whether it's a DNS, port-forwarding, or mDNS-race issue, with the specific recovery action.\n\n### Tailscale\n\nIf you have Tailscale installed and a Tailscale API key configured in Settings, Supbuddy can push split-DNS routes to your tailnet so any device on your tailnet resolves your Supbuddy domains. Optional, off by default.\n\n## Monorepo support\n\nSupbuddy auto-detects these monorepo layouts when scanning a project root:\n\n- Turborepo (presence of `turbo.json`)\n- pnpm workspaces (`pnpm-workspace.yaml`)\n- npm/yarn workspaces (`workspaces` field in root `package.json`)\n- Common folder layouts: `apps/*`, `packages/*`, `services/*`, `sites/*`\n\nEach detected app gets its own subdomain. Supabase is searched for in the project root and these subdirectories: `apps/*`, `packages/*`, `services/*`, `sites/*`, `db/`, `db/*`, `database/`, `database/*`, `packages/backend`, `packages/db`, `packages/database`.\n\n### Detected app frameworks\n\nPort detection looks for the framework dependency in `package.json` and combines that with: explicit `-p`/`--port` in the dev script, `PORT=` env in the dev script, or a config file read. If none of those resolve, the framework default is used:\n\n| Framework dependency | Default port |\n| --- | --- |\n| `next` | 3000 |\n| `vite` | 5173 |\n| `@remix-run/dev`, `@remix-run/serve` | 3000 |\n| `astro` | 4321 |\n| `nuxt`, `nuxt3` | 3000 |\n| `@sveltejs/kit` | 5173 |\n| `@angular/core` | 4200 |\n| `@nestjs/core` | 3000 |\n| `express`, `fastify`, `koa`, `hono`, `@hono/node-server`, `elysia`, `polka`, `tinyhttp` | none (must be explicit in dev script) |\n\n### Server Actions allowedOrigins audit\n\nFor Next.js apps, Supbuddy reads your `next.config.{ts,mts,js,mjs,cjs}` and extracts the hosts in `experimental.serverActions.allowedOrigins`. If a mapped subdomain is missing from that list, the project's **warnings chip** flags `next.config: N origins missing`; Server Action POSTs through Supbuddy mappings would 403 otherwise. Open the **Apps** tab (the chip's \"open apps\" jump) where the affected app shows the warning with a **Fix** button.\n\nThe Fix button opens a dialog with a paste-ready snippet and an **Apply…** button: click it to see a unified diff of the change Supbuddy will make to your `next.config`, then **Confirm & write** to apply it. Supbuddy handles the four common config shapes (existing `allowedOrigins` array, existing `serverActions` block without it, existing `experimental` block without `serverActions`, or no `experimental` at all). After write, Supbuddy rescans the project so the warning disappears immediately. Restart your dev server for the change to take effect; Next.js does not hot-reload `next.config`. Over MCP the same audit is exposed as `preview_next_origins` / `apply_next_origins`.\n\n### Next.js cross-origin dev requests (allowedDevOrigins)\n\nSupbuddy proxies your dev server but **passes the browser's real `Origin` header through** (it no longer rewrites `Origin` to the upstream address). That's required so Server Actions and other origin checks see the actual page origin — but it means **Next.js 15.3+ and 16** dev servers, which validate cross-origin dev requests against `allowedDevOrigins` (defaulting to `localhost`), now treat a request arriving on a Supbuddy domain (or a Thin project's `127.0.0.N` loopback IP) as cross-origin and can reject it. Add your Supbuddy domain to `allowedDevOrigins` in `next.config`:\n\n```js\n// next.config.js\nmodule.exports = {\n allowedDevOrigins: ['web.myproject.test'],\n}\n```\n\nRestart the dev server afterward; Next.js does not hot-reload `next.config`. This is separate from `experimental.serverActions.allowedOrigins` (the Server Actions CSRF list above) — 15.3+/16 may need both.\n\n### Vite allowedHosts audit\n\nFor Vite apps, Supbuddy reads your `vite.config.{ts,mts,cts,js,mjs,cjs}` and extracts `server.allowedHosts`. If a mapped host isn't covered, the **warnings chip** flags `vite: N hosts blocked`; Vite's dev server otherwise rejects proxied requests for unknown hosts with `Blocked request. This host (\"…\") is not allowed.` (403). A `.your-project.local` entry counts as covering every subdomain, so an existing wildcard suffix doesn't trigger a false warning.\n\nLike the Next.js audit, the affected app's **Fix** button on the **Apps** tab opens a dialog with a paste-ready snippet and an **Apply…** button that previews a unified diff and writes `server.allowedHosts` into your `vite.config` (handling an existing `allowedHosts` array, an existing `server` block without it, or no `server` block at all; `allowedHosts: true` is left untouched). After write, Supbuddy rescans so the warning clears. Restart your dev server for the change to take effect; Vite does not hot-reload `vite.config`.\n\n## MCP setup (AI agents)\n\nSupbuddy ships a built-in MCP server on `http://127.0.0.1:9877/mcp` with static Bearer-token auth. Five clients have one-click install; any other MCP-compatible tool can be configured manually with the same URL + token.\n\nOpen **Settings → MCP → Add client**, pick the client kind, and Supbuddy generates a token, edits the client's config file, and backs up the original (`<file>.supbuddy-backup` next to it). If the install can't complete it surfaces an error toast rather than stalling. The same client-management surface (**Settings → MCP → Clients**: install, edit scopes, set-primary, rotate token, revoke) drives each client from the app.\n\n### Auto-install paths\n\n| Client | Config file | Transport |\n| --- | --- | --- |\n| Claude Code | `~/.claude.json` (user) or `<project>/.mcp.json` (project) | HTTP |\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | stdio shim via `npx -y @supbuddy/mcp@latest` |\n| Cursor | `~/.cursor/mcp.json` (user) or `<project>/.cursor/mcp.json` (project) | HTTP |\n| Codex CLI | `~/.codex/config.toml` (adds an `[mcp_servers.supbuddy]` block) | HTTP |\n| Windsurf | `~/.codeium/windsurf/mcp_config.json` | HTTP |\n\n### MCP tool surface\n\nThe MCP server has full read and write access:\n\n- Read tools (`list_mappings`, `list_projects`, `get_health`, `get_compose_status`, `list_pending_vm_migrations`, etc.), with env values and request bodies included.\n- `get_client_capabilities` and `request_scope_elevation` (scope discovery + user-approved grant).\n- `read_env_file`, `tail_request_logs`, `watch_audit_log`.\n- Write tools: `create_mapping`, `delete_mapping` (soft-delete), `register_project`, `update_project`, `set_supabase_config_path`, `start_proxy`, `start_supabase`, `stop_supabase`, `restart_supabase`, `switch_isolation`, `migrate_vm_to_thin`, `finish_vm_migration`, `start_compose`, `stop_compose`, `restart_compose`, `scaffold_addons`, `seed_addons`, `write_env_file`, `copy_env_var`, `write_supabase_config`.\n- Scripts tools (`list_scripts`, `start_script`, `stop_script`, `restart_script`, `bookmark_script`, `tail_script_logs`); see *Scripts MCP tools* below.\n- Extended Supabase tools: `init_supabase`, `validate_supabase_config`, `list_supabase_backups`, `restore_supabase_backup`, `cancel_supabase_start`, `force_recreate_supabase`, `restart_supabase_container`, `get_supabase_analytics`, `set_supabase_analytics`.\n- Bundle (export/import a project's full config): `export_bundle`, `import_bundle`, `validate_bundle`.\n- Supbuddy Cloud (opt-in, per-project): `cloud_sign_in`, `push_to_cloud`, `get_cloud_status`, `cloud_teardown` — push a project (with its Supabase schema + data) to a hosted cloud stack and control it. The `cloud` link (`{ projectId, stackId, pushedAt, url }`) also appears on `get_project` / `list_projects`, so any client sees which projects are in the cloud.\n- Connection / env-target workflow: `preview_connection`, `get_env_targets`, `diff_env`, `apply_env`, `write_connection`, `test_connection`, `dismiss_connection_drift`.\n- Host & network tools: bundled-runtime trust (`get_trust_status`, `install_trust`, `remove_trust`, `detect_trust_tools`, `test_trust`), Tailscale (`get_tailscale_status`, `set_tailscale_key`, `remove_tailscale_key`, `test_tailscale`), DNS (`get_dns_status`), CA (`uninstall_ca`), and port-forwarding (`get_port_forwarding_status`, `set_port_forwarding`, `reload_port_forwarding`).\n- `tail_service_logs`: streams a Compose/add-on service's container logs over SSE (like `tail_request_logs` but for container stdout/stderr).\n- `watch_supabase`: streams a project's live Supabase start/stop/restart progress over SSE: operation status, image-pull/service snapshots, and (for VM projects) raw log lines. Backs `supbuddy supabase start --follow`.\n- Multiple MCP clients can connect simultaneously. The same MCP-HTTP surface backs the headless **CLI** (see *Command-line interface* below).\n\n### Scopes: discovery & self-service elevation\n\nEach MCP client holds a set of **scopes** (`read`, `log_tail`, `mappings`, `projects`, `services`, `config`, `system`, `apply`) chosen when it's added. A tool call that needs a scope the client lacks fails with `scope_denied`, whose payload now carries a `user_message` and `details.remediation` pointing at the fix.\n\n- `get_client_capabilities` ( `{ tool? }` ) returns the calling client's `granted_scopes` and `available_scopes`. Pass a `tool` name to get `{ required_scope, required_feature, can_call, reason? }` so an agent can pre-flight a call instead of probing by hitting `scope_denied`.\n- `request_scope_elevation` ( `{ scopes: [...] }` ) asks the **user** to grant the named scopes. Supbuddy shows a blocking approval dialog; on approval the scopes are added to the client. Already-granted scopes short-circuit without a prompt.\n\nYou can also review and edit any client's scopes from the GUI: **Settings → MCP → Clients** lists each client's granted scopes inline and exposes a **Scopes** button that opens the same scope editor used when adding a client.\n\n### Registering a project via MCP\n\n`register_project` takes a `root_path` (required), an optional `label`, `auto_scan` (default `true`), and an optional `isolation` (`'thin'` or `'host'`). It registers the project the same way the GUI's \"Add project\" flow does:\n\n- Derives a base domain as `<slug>.<defaultTld>` from the label (or the folder name), e.g. `staffhub.test`.\n- Records both the project `path` and `rootPath` so the project is visible to the proxy, scans, and file tools alike.\n- Scans the folder (unless `auto_scan: false`) for apps, services, scripts, and package manager.\n- Creates per-app subdomain mappings from the discovered apps (e.g. `site.staffhub.test → :3400`), derives the host service subdomains (`api.`, `studio.`, …), and reloads Caddy.\n- **Defaults to `thin` isolation**: the project gets its own loopback IP so its dev servers keep canonical ports (`:3000`) with no cross-project collisions — run them with `supbuddy run -- <dev command>`. The one exception: if the project's Supabase stack is **already running on the host outside Supbuddy**, registration keeps it on `host` (switching would rewrite its `config.toml` ports and orphan the running stack). Pass `isolation: 'host'` to opt out explicitly, or `isolation: 'thin'` to skip the detection and force thin.\n\nThe response includes an `isolation_note` explaining which mode was chosen and why — agents should read it instead of assuming.\n\n### Switching isolation over MCP\n\n`switch_isolation` ( `{ project_id, target_mode: 'host' | 'thin', auto_start? }` ) moves an existing project between **host** and **thin** mode. To-thin writes the per-project port block and `project_id` into `supabase/config.toml` and (unless `auto_start: false`) starts Supabase; to-host restores the original `config.toml` and stops that project's stack. It runs in the background and returns `{ started: true }`; poll `get_project` (`isolation`) for the current mode.\n\nA project can also be patched with `update_project`: its `patch` accepts `name`, `enabled`, `domain`, and `isolation` (it intentionally does **not** accept `path`/`rootPath`). Note that patching `isolation` only flips the flag; use `switch_isolation` to actually provision/tear down the port assignment.\n\n### Legacy VM migration over MCP\n\nFor projects still on the retired Isolated (VM) mode, three tools handle the one-way migration to Thin:\n\n- `list_pending_vm_migrations` (read): lists all projects still on the legacy VM mode, with their current `vmState` and migration readiness.\n- `migrate_vm_to_thin` ( `{ project_id }` ) (write): starts the guided data-safe migration. It dumps Postgres data from the VM, starts a fresh Thin stack, restores the dump, and row-count-verifies before signalling completion. Returns `{ started: true }`; poll `get_project` (`migrationState`) for progress.\n- `finish_vm_migration` ( `{ project_id }` ) (write): tears down the old VM container after verification passes. Errors if called before the verify step completes.\n\n### Repointing a project's Supabase config\n\n`set_supabase_config_path` ( `{ project_id, supabase_path }` ) switches which `supabase/config.toml` a project uses, for monorepos that carry more than one (e.g. a repo-root config and an app-level one). `supabase_path` is the project-relative directory **containing** the `supabase/` folder (`\".\"` for the repo root, e.g. `\"apps/getnightowls\"`). It persists the path, re-derives `supabaseProjectId` from the new config, and re-scans services. The previous stack's Docker volume is **left intact** (not deleted), so the switch is reversible; the response reports it under `orphaned_previous_stack`.\n\n### Moving a secret between env files\n\n`copy_env_var` ( `{ source_path, source_key, target_path, target_key? }` ) relocates a single variable from one env file to another (e.g. a value put in an app's `.env.local` that the stack actually injects from the repo-root `.env.local`). The value is read and written entirely inside the worker (it **never crosses the MCP boundary** and never appears in the audit log), so an agent can move a secret without it being printed. `target_key` defaults to `source_key`.\n\n### Plan / apply for destructive tools\n\nTools that delete or mutate state (`delete_mapping`, `delete_project`, `write_env_file`, etc.) return a *plan* with a preview. The MCP client (or you, in the Activity panel) explicitly calls `apply` with the `plan_id` to execute. Plans expire after 5 minutes if not applied. Soft-deletes go to the Trash and are recoverable for 7 days.\n\n## Add-on Compose services\n\nA project can declare **extra** Docker Compose services that Supbuddy discovers, merges, runs, health-checks, and tails alongside the managed stack: a Redis cache, a worker queue, a search engine, etc. Add-on services run on the host's shared Docker daemon in both `host` and `thin` isolation, with no extra setup needed.\n\n### Declaration files & merge precedence\n\nSupbuddy looks for up to three Compose fragments in the project and merges them, later wins:\n\n1. `docker-compose.yml`: your base Compose file.\n2. `docker-compose.override.yml`: your own override, honored if present (standard Compose convention).\n3. `supbuddy.addons.yml`: Supbuddy-owned add-on fragment.\n\nAll present fragments are passed explicitly, e.g. `docker compose -f docker-compose.yml -f docker-compose.override.yml -f supbuddy.addons.yml --project-name <pinned> …`. The project name is pinned so the same set of containers is addressed every time. Add-on services join the Compose project's default network automatically; no extra network setup is needed for them to reach (or be reached by) the rest of the stack.\n\n### `supbuddy.addons.yml` format\n\nA valid Compose fragment (a standard `services:` map) plus an optional Supbuddy-only `x-supbuddy:` extension block. A plain `docker compose up` ignores `x-supbuddy:`, so the file stays usable without Supbuddy. Today `x-supbuddy` supports a one-shot **seed** step:\n\n```yaml\nservices:\n redis:\n image: redis:7-alpine\n ports: [\"6379:6379\"]\nx-supbuddy:\n seed:\n service: redis\n command: [\"redis-cli\", \"ping\"] # explicit argv, runs once after services are healthy\n runOnce: true\n```\n\nThe seed step runs **once** after the add-on services are up and healthy. It's idempotent, keyed by a signature of the seed spec, so it only re-runs if the spec changes (or you force it). It fires automatically on project start, and on demand via the `seed_addons` MCP tool.\n\n### MCP tools\n\n- `scaffold_addons` ( `{ project_id }` ): scope `config`. Creates a starter `supbuddy.addons.yml` if the project doesn't have one. Never clobbers an existing file.\n- `seed_addons` ( `{ project_id, force? }` ): scope `services`. Runs the declared `x-supbuddy.seed` step. Idempotent unless `force: true`.\n- `tail_service_logs` ( `{ project_id, service }` ): scope `log_tail`. Streams a Compose/add-on service's container logs over SSE (like `tail_request_logs`, but for container stdout/stderr).\n- `watch_supabase` ( `{ project_id }` ): scope `log_tail`. Streams a project's live Supabase start/stop/restart progress over SSE: `operation` (status + message), `progress` (image-pull/service snapshots), and `log` (raw lines, VM projects). The stream ends on a terminal status. Backs `supbuddy supabase start --follow`.\n\n### Scripts MCP tools\n\nScripts detected in a project (e.g. `dev`, `build`, `test`) are controllable over MCP:\n\n- `list_scripts` ( `{ project_id }` ): scope `read`. Returns all detected scripts with their current status and bookmark state.\n- `start_script` ( `{ project_id, script }` ): scope `services`. Starts the named script process.\n- `stop_script` ( `{ project_id, script }` ): scope `services`. Stops the named script process.\n- `restart_script` ( `{ project_id, script }` ): scope `services`. Stops then starts the named script process.\n- `bookmark_script` ( `{ project_id, script, bookmarked }` ): scope `services`. Pins (`bookmarked: true`) or unpins a script in the Quick Access group.\n- `tail_script_logs` ( `{ project_id, script }` ): scope `log_tail`. Streams the named script's stdout/stderr over SSE.\n\n### `get_compose_status` shape\n\n`get_compose_status` ( `{ project_id }` ) returns live per-service status, not just whether Compose is installed:\n\n```json\n{\n \"project_id\": \"…\",\n \"compose_installed\": true,\n \"running\": true,\n \"services\": [\n { \"name\": \"redis\", \"status\": \"running\", \"health\": \"healthy\", \"ports\": [\"6379:6379\"], \"image\": \"redis:7-alpine\", \"container_id\": \"…\", \"source\": \"addons\" }\n ]\n}\n```\n\nEach service's `source` is one of `base` | `override` | `addons`, telling you which fragment declared it.\n\n## Per-project AI context sync\n\nEach project has a **Context sync: AI tools** panel, accessible via the **AI Tools** tab in the project card, that writes a project-scoped briefing to disk so AI agents working in that repo see your live mappings, services, and isolation state without having to ask. Files written:\n\n- `.supbuddy/`: `README.md`, `mappings.md`, `services.md`, `project.md`, `mcp.md`, `do-not.md`, `docs.md`. The full live snapshot, regenerated on each sync.\n- `AGENTS.md` and `CLAUDE.md`: a small managed block prepended (or updated in place) telling the agent which project this is and pointing it at `.supbuddy/`.\n- Editor skill files when detected: `.cursor/rules/supbuddy.mdc`, `.claude/skills/supbuddy/SKILL.md`, `.codeium/windsurf/rules/supbuddy.md`, `.continue/rules/supbuddy.md`, `.github/copilot-instructions.md`, `.idea/supbuddy.md`.\n- `.gitignore` managed block, ignoring: `.supbuddy/meta.json` (volatile sync state), `*.supbuddy-backup-*` (rollback snapshots), and the per-editor skill files that are written **locally** (see scope below). The rest of `.supbuddy/` is intended to be committed; `AGENTS.md`, `CLAUDE.md`, and `.github/copilot-instructions.md` are also kept committable since you may have hand-written content there alongside Supbuddy's managed block.\n\n### Global vs. local scope\n\nThe per-editor skill files are generic Supbuddy-owned pointers (\"this is a Supbuddy project: read `.supbuddy/`, prefer the MCP tools\"). For editors that expose a **Supbuddy-owned global location**, Supbuddy writes that pointer **once, machine-wide** instead of copying it into every project, so it isn't duplicated across all your repos. Project-specific data always stays local in `.supbuddy/`.\n\n- **Claude Code** → one global skill at `~/.claude/skills/supbuddy/SKILL.md`. **Cursor** → `~/.cursor/skills/supbuddy/SKILL.md`. The global skill self-scopes: it only acts when the working directory has a `.supbuddy/` folder, and resolves the active project from that folder's `meta.json`.\n- All other targets (`windsurf`, `continue`, the `AGENTS.md`/`CLAUDE.md`/Copilot managed blocks, JetBrains) stay **local**: their \"global\" files are shared user files, so Supbuddy won't overwrite them.\n- Each target has a **scope** setting: `auto` (default: global for the Claude/Cursor skills, local for everything else), `global`, `local` (force per-project, useful if you commit the file for teammates), or `off`. A machine-global file is reference-counted across projects and removed automatically once no project uses it (on disabling sync, deleting a project, or switching that target back to local). Note: uninstalling Supbuddy (e.g. dragging it to the Trash on macOS) does **not** auto-remove these global files; delete them manually from `~/.claude/skills/supbuddy/` and `~/.cursor/skills/supbuddy/` if needed.\n- The always-loaded `CLAUDE.md`/`AGENTS.md` managed block stays local as a safety net so agents stay aware even if the on-demand global skill doesn't auto-activate.\n\nSync modes per project:\n\n- **Auto**: Supbuddy regenerates the files whenever mappings, services, or project state change.\n- **Manual only**: files are only written when you click **Sync now** (or use the tray's *Sync AI context for all projects*).\n- **Off**: nothing is written.\n\nThe collapsed header shows an at-a-glance status pill: mode (`auto` / `manual` / `off`), a colored dot for the last sync result, and a relative timestamp. Disabled targets (e.g. an editor whose folder isn't present) appear greyed out in the **Detected targets** list inside the panel.\n\n## Supbuddy Cloud\n\nPush a project — its Supabase schema **and data** — to a hosted cloud dev-stack (its own full self-hosted Supabase — Postgres, Auth, REST, Storage, Realtime, Studio behind a gateway — as an isolated graph of machines on a per-tenant private network) and control it from the app, the CLI, or MCP. **Opt-in and per-project:** nothing cloud-related appears in a project until you've signed in.\n\n- **Get started** — the top bar shows a **Get started with Supbuddy Cloud** strip; sign in (email/password) there. Once signed in it becomes **Open cloud** (opens [cloud.supbuddy.app](https://cloud.supbuddy.app) in your browser). Sign-in state + the Claude connection also live under **Settings → Cloud**.\n- **Push a project** — after signing in, each project's ⋯ menu gains **Push to cloud…**. The push ships the project's stack descriptor + a `pg_dump` of its Supabase data (fail-closed: uploaded to a private bucket via a single-use key, sha-verified, restored *inside* the stack's private network, then deleted). Your **local project stays intact** — a **☁** badge appears on its row; click it (or ⋯ → **Open in cloud**) to open the stack in the web app.\n- **CLI / MCP** — the same flow headless: `supbuddy cloud login|push|status|teardown` (password via arg or `SUPBUDDY_CLOUD_PASSWORD`), or the `push_to_cloud` / `get_cloud_status` / `cloud_teardown` / `cloud_sign_in` MCP tools. `project ls` marks pushed projects with ☁, and `get_project` / `list_projects` carry the `cloud` link. `cloud_teardown` (and the ⋯ teardown) destroy the remote stack and unlink it locally — routed through the same plan/apply gate as other destructive tools.\n- **Service breadth** — a self-hosted push provisions the **full** Supabase stack by default. Pass `push_to_cloud`'s `supabase_services: \"minimal\"` (MCP) to opt down to a lean db/auth/REST stack instead.\n- **Idle auto-stop** — a running cloud stack that reports no activity for ~30 minutes is automatically **stopped** to save cost (its data + config persist; start it again from the web app). A background reaper also reconciles any stack whose machines went missing.\n- **Web console** — [cloud.supbuddy.app](https://cloud.supbuddy.app) lists your org's stacks; open one for its per-service health, live status, and **start / stop / restart / tear down** controls, plus a **Recent activity** feed of control-plane events. **Push to cloud** in the console provisions a stack from a GitHub `owner/repo` (self-hosted or bring-your-own Supabase; full or minimal service set) — the code-only path; pushing a local project *with its data* still goes through the desktop app / CLI.\n\n## Command-line interface (CLI)\n\nEverything the desktop app can do is also driveable headlessly from a terminal, with no GUI window. The CLI runs a **daemon** (the same worker process the GUI uses: Caddy proxy, DNS, Supabase/Compose lifecycle, MCP-HTTP) and a set of commands that attach to it over the local MCP-HTTP port. This is for SSH sessions, CI, `tmux`/server boxes, and scripting.\n\nThe binary is `supbuddy`, with a short alias `sup`. Run `supbuddy help` for the full usage list.\n\nYou can install the CLI on its own, without the desktop app:\n\n```bash\nnpx supbuddy@latest # asks to install the CLI globally (supbuddy + sup)\n```\n\nThat command does nothing on its own except offer to put `supbuddy` and `sup` on your PATH. The CLI runs independently of the desktop app, so you can add the app later (or never). On a Mac the app installs the same two commands for you.\n\n### The daemon\n\n```bash\nsupbuddy daemon --detach # start the worker in the background\nsupbuddy status # daemon + proxy health\nsupbuddy stop # graceful shutdown\n```\n\n`--detach` backgrounds the daemon and prints its pid + ports. Foreground `supbuddy daemon` runs it attached (Ctrl-C shuts it down cleanly). On start the daemon writes a discovery file, `daemon.json` (mode `0600`), into the shared state dir holding its pid, the Socket.IO port, the MCP-HTTP port, and a control token; every other command reads it to find and authenticate to the daemon, so you never pass ports or tokens by hand. Only one daemon may run per state dir; a second `daemon` start is refused.\n\nThe CLI and the desktop app **share one state dir** (`~/Library/Application Support/Supbuddy/`), so they manage the same projects, mappings, and settings. They must not run two workers against it at once: if you launch the desktop app while a CLI daemon is running, the app detects it and offers to **stop the daemon and continue** or **quit**. It never forks a competing worker (which would corrupt `state.json`).\n\n### Run on login (service)\n\n```bash\nsupbuddy service install # start-on-login (launchd on macOS, systemd-user on Linux)\nsupbuddy service status\nsupbuddy service uninstall\n```\n\n### Commands\n\nAll app surfaces have a command. Names follow `supbuddy <module> <action> [args] [--flags]`. The main groups:\n\n| Group | Examples |\n| --- | --- |\n| Dev launcher | `run [--print] -- <dev command>` — on a Thin project, binds the dev server to the project's loopback IP (from `.supbuddy/meta.json`) so it keeps its canonical port (e.g. `supbuddy run -- next dev` stays on `:3000`) |\n| Health / proxy | `status`, `proxy status\\|start\\|stop\\|restart` |\n| Mappings | `map ls\\|add\\|get\\|set\\|enable\\|disable\\|rm\\|restore` |\n| Projects | `project ls\\|add\\|get\\|scan\\|set\\|enable\\|disable\\|rm\\|restore\\|env\\|refresh-context` |\n| Supabase | `supabase start\\|stop\\|restart\\|status <proj>` (add `--follow` to stream live progress), `supabase config apply <proj> <file>` |\n| Cloud | `cloud login <email> [<pw>]` (or `SUPBUDDY_CLOUD_PASSWORD`), `cloud push <proj> [--repo=owner/repo] [--force]`, `cloud status [<proj>]`, `cloud teardown <proj>` — push a project (with its Supabase data) to a hosted cloud stack; `project ls` marks pushed projects with ☁ |\n| Compose | `compose up\\|down\\|restart\\|status\\|logs <proj> [svcs]` |\n| Scripts | `scripts ls\\|start\\|stop\\|restart\\|logs\\|bookmark <proj> [script]` |\n| Isolation | `isolation switch <proj> <host\\|thin>`, `isolation pending-migrations`, `migrate start\\|finish <uuid>` |\n| Certificates | `ca status\\|install\\|uninstall` |\n| Env files | `env copy <src> <key> <target>`, `env write <path> <K=V>…` |\n| Settings | `settings get`, `settings set --json <patch>` |\n| MCP | `mcp add [<agent>]` (register Supbuddy into a coding agent: interactive, or `--write`/`--print`/`--prompt`), `mcp ls`, `mcp revoke <id>`, `mcp approvals apply\\|cancel <id>` |\n| Host / network | `connect`, `trust`, `tailscale`, `dns`, `pf` (port-forwarding) |\n| Logs | `logs requests [-f]`, `logs audit [-f]`, `logs get <id>` |\n| Account | `account`, `caps`, `addons scaffold\\|seed <proj>` |\n| Dashboard | `tui` (alias `dash`) |\n\nGlobal flags: `--json` (machine-readable output), `--yes` (skip confirmations), `--quiet`, `--url`/`--token` (attach to a specific/remote daemon instead of auto-discovery), `--state-dir` (override the shared dir), `--timeout`, and `-f`/`--follow` for streaming log commands and live `supabase start|stop|restart` progress.\n\nDestructive operations go through the same **plan → apply** gate as MCP (see *Plan / apply for destructive tools*); the CLI's control token is granted auto-apply, so they execute directly.\n\n### Live dashboard (TUI)\n\n```bash\nsupbuddy tui # or: sup dash\n```\n\n`supbuddy tui` opens a full-screen terminal dashboard that attaches to the running daemon and shows live connection/proxy status, the project list (with each project's isolation, Supabase, and Compose state), the mapping count, and a tail of recent requests. Press `r` to refresh, `q` to quit. It needs a running daemon (`supbuddy daemon --detach`); if none is found it tells you so.\n\n## Settings reference\n\nOpen Settings via the gear icon top-right or by clicking the tray icon → Open Dashboard → gear. Five tabs.\n\n### General\n\n- **Theme**: dark or light.\n- **Auto-start at login**: registers Supbuddy as a macOS login item. Default: on.\n- **Default TLD**: applied to new auto-generated mappings. Existing mappings are renamed to the new TLD on save. Default: `test`.\n- **Default isolation**: `host` or `thin` for newly added projects. Default: `thin` (per-project loopback IP; apps keep canonical ports like `:3000`). MCP registration additionally keeps a project on `host` when its Supabase stack is already running on the host outside Supbuddy.\n- **Auto-subdomain mapping**: when on, services and apps detected during a project scan get mappings created automatically. Default: on.\n- **Bundled-runtime trust**: installs Supbuddy's local root CA into a place that apps with bundled JavaScript runtimes (Claude Code, Cursor, Windsurf, Continue, Codex CLI, OpenCode, …) actually read. These apps don't consult the system Keychain (they ship their own Mozilla bundle), so without this they fail OAuth/MCP/HTTPS calls to `*.test` with `unable to get local issuer certificate`. Default: prompted on first launch when one of those tools is detected.\n - **macOS**: writes `~/Library/LaunchAgents/com.cueplusplus.supbuddy.bundled-runtime-ca-trust.plist` and calls `launchctl setenv NODE_EXTRA_CA_CERTS / SSL_CERT_FILE / REQUESTS_CA_BUNDLE` so GUI-launched apps inherit the right vars at process-start time.\n - **Linux**: writes `~/.config/environment.d/supbuddy-ca.conf` (read by systemd-aware user sessions on GNOME/KDE/Sway/etc.).\n - **Windows**: per-user `setx NODE_EXTRA_CA_CERTS / SSL_CERT_FILE / REQUESTS_CA_BUNDLE` to `HKCU\\Environment`.\n - All three env vars point at `~/Library/Application Support/Supbuddy/ca-bundle/current.crt` (or the platform-equivalent), a *cumulative* concatenated PEM Supbuddy maintains. When Caddy rotates its root (yearly today, sometimes more), Supbuddy appends the new root automatically; long-running TLS contexts holding the old root keep working until the process restarts.\n - **Test trust**: runs an in-process HTTPS request against the first available `*.test` mapping with the same env vars set, to verify end-to-end without relaunching anything. It probes the **real access path** (port 443 when port forwarding is on, otherwise the high port), matching what real clients hit, so it doesn't false-negative against a port nothing is forwarding.\n - **Conflict refusal**: if `NODE_EXTRA_CA_CERTS` is already set to something else (corporate proxy, Zscaler), Supbuddy refuses to overwrite and surfaces the conflicting path. You can override with the explicit prompt that pops up on Install.\n - **Quit and relaunch your AI tools** after install: the env var only takes effect for *newly-launched* processes.\n\n### Network\n\n- **HTTP port**: default 8080.\n- **HTTPS port**: default 8443.\n- **DNS port**: default 5353.\n- **Port forwarding**: when on, inserts a `pfctl` rule mapping 80→HTTP port and 443→HTTPS port into `/etc/pf.conf` (correct translation-section placement; self-heals a file corrupted by older versions). Asks for sudo once. Status reflects a live 443 enforcement probe, not just file presence.\n- **LAN sharing**: binds Caddy to `0.0.0.0` + starts mDNS responder.\n- **Tailscale**: paste a tailnet API key to enable split-DNS push.\n- **Install / Uninstall CA**: **Install** adds Caddy's root cert to your System keychain (removing any stale same-name roots first); **Uninstall** removes every `Caddy Local Authority` root it added. macOS asks for your password each time.\n\n### Storage\n\nTrash retention (per-kind), volume sizes, image-cache controls.\n\n### MCP\n\n- **Clients**: list of connected clients. Each row has a **⋯** actions menu: install, edit scopes, set-primary, rotate token, revoke.\n- **Activity**: audit log with Apply/Cancel/Undo on plan rows.\n- **Trash**: soft-deleted mappings and projects, restorable for 7 days.\n- Settings: server `enabled`, `port` (default 9877), `audit_cap` (default 5000), `trash_ttl_days` (default 7).\n\n### AI Skills\n\nInstall Supbuddy's agent **skill at the user level** (machine-wide) so the agent sees Supbuddy in every repo without per-project setup. Each global-capable agent has a **master on/off** plus an **autosync** toggle (keeps the installed skill refreshed when Supbuddy updates it) and shows its install path + version.\n\n- **Who can install at user level**: only agents whose global file Supbuddy fully **owns** and that **self-scope** (act only when the working directory has a `.supbuddy/`): **Claude Code** (`~/.claude/skills/supbuddy/SKILL.md`) and **Cursor** (`~/.cursor/skills/supbuddy/SKILL.md`). The install is reference-counted under a synthetic `__user__` ref so it persists independent of any project and is never pruned by the boot reconcile.\n- **Master ↔ project**: the AI Skills tab is the **master** (user-level). To commit a skill into a specific repo, use that project's **AI Tools** tab and set the target to **Project** (the old `local` scope, which writes into the repo for teammates); **User** there means the master install covers it.\n- Agents whose global file holds *your own* content (Claude `CLAUDE.md`, Codex `AGENTS.md`, Copilot, Windsurf, Continue, JetBrains) are **project-level only**: a machine-wide write there could clobber your config, so they're injected per-project instead.\n\n## Tray menu\n\nThe macOS menu bar tray icon opens a menu with:\n\n- **Status: …**: current proxy state (running / idle).\n- **DNS Active (:5353)**: shown when proxy is running.\n- **LAN Sharing (\\<ip\\>)**: shown when LAN sharing is on.\n- **Tailscale (\\<ip\\>)**: shown when Tailscale is connected.\n- **Start Proxy / Stop Proxy**: opens the dashboard.\n- **Projects**: each project opens a submenu with **Apps** (click to open the mapped URL), **Supabase** services (status dot + open), and **Scripts** (your bookmarked scripts as a one-click **Start <name>** / **Stop <name>** toggle), plus **Restart Supabase**/**Restart services** and **Show in Supbuddy**.\n- **Open Dashboard**.\n- **Sync AI context for all projects**: runs the project-context sync engine for every registered project (writes `.supbuddy/`, `CLAUDE.md`, `AGENTS.md`, etc.).\n- **Show Logs**: reveals `main.log` in Finder.\n- **Check for Updates...**: manual update check (only enabled in packaged builds).\n- **Quit**.\n\n## File locations\n\nAll under `~/Library/Application Support/Supbuddy/` on macOS:\n\n- `main.log` + `main.log.1`: app logs (rotates at 2 MB).\n- `state.json`: persistent state (projects, mappings, settings, MCP clients, license).\n- `caddy-data/`: Caddy's data dir (PKI, autosaves, certs).\n- `caddy-data/caddy/pki/authorities/local/root.crt`: the local CA cert installed in your Keychain.\n- `ca-bundle/current.crt`: cumulative PEM containing every Caddy root that has ever been emitted. Used by **Bundled-runtime trust** as the target for `NODE_EXTRA_CA_CERTS` / `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE`. Real file (not a symlink) so Bun-bundled CLIs read it correctly.\n- `ca-bundle/versioned/<sha>.crt`: per-root snapshots for forensics.\n- `Caddyfile`: generated reverse-proxy config.\n- `daemon.json`: written while a headless CLI daemon is running (pid, Socket.IO + MCP-HTTP ports, control token); `0600`, removed on shutdown. Used by `supbuddy` CLI commands to discover and authenticate to the daemon, and by the desktop app to detect a running CLI daemon at launch.\n- `certs/`: legacy CA from the pre-Caddy era (unused in current builds).\n\nMCP-specific:\n\n- MCP client tokens (file-backed secret, mode `0600`): `~/Library/Application Support/Supbuddy/secrets/mcp-<client-id>.secret`\n- MCP audit log: under `~/Library/Application Support/Supbuddy/`, capped at `audit_cap` entries (default 5000).\n\n## Troubleshooting\n\n### Browser shows \"Not secure\" or certificate warning\n\nThe Caddy CA is not trusted. Open **Settings → Network → Install Certificate**. macOS will prompt for your password. After install, fully restart your browser (Cmd+Q, not just close window). Verify: *Keychain Access* → System keychain → search for \"Caddy Local Authority\".\n\n### \"unable to get local issuer certificate\" / \"self signed certificate in certificate chain\" from Claude Code, Cursor, MCP servers, or other AI tools\n\nThese tools ship their own bundled JavaScript runtime (Bun, Electron, pkg-bundled Node) and ignore the system Keychain. Open **Settings → General → Bundled-runtime trust** and click **Install**. Then *fully quit and relaunch* the AI tool; the env vars only take effect for newly-launched processes. Verify with `launchctl getenv NODE_EXTRA_CA_CERTS` (macOS); it should print `~/Library/Application Support/Supbuddy/ca-bundle/current.crt`. If install is refused with a conflict warning, you already have `NODE_EXTRA_CA_CERTS` set (often a corporate proxy / Zscaler), so Supbuddy won't silently overwrite; use the override prompt or manually concatenate the two PEMs.\n\n### \"Docker is not running. Please start Docker Desktop.\"\n\nCompose and Supabase features need Docker. Open Docker Desktop and wait until the whale icon stops animating.\n\n### \"Docker Compose is not installed\"\n\nCompose v2 ships inside Docker Desktop. If you removed Docker Desktop and are using a standalone Docker daemon (e.g. Colima, Rancher), install compose: `brew install docker-compose`.\n\n### \"Leftover host containers\" / \"isolation drift\" warning on a project\n\nSupbuddy flags **isolation drift** when a project's running containers don't match its configured isolation mode, for example a **Host** project with a stale `thin`-mode stack still running, or a **Thin** project with leftover host-mode containers. Switching isolation modes doesn't tear down the old layer, so those containers linger, waste resources, and can shadow the project's real stack. The warning appears in the **warnings chip** next to the enable toggle (click it to see each item; it shows a spinner while Supbuddy re-checks), as an entry in the issues counter, and as a notice on the **Supabase** tab listing the exact containers and any data volumes.\n\n**Guided cleanup.** Open the Supabase tab → **Clean up leftovers…** to stop and remove the leftover containers. Data volumes are kept by default; deleting them is opt-in, and when the leftover copy looks newer than the active one, it requires an explicit choice and a backup (tarred to `…/Supbuddy/backups/<project>-<timestamp>/`). If you recently migrated a VM project, any leftover VM container from before migration can also be cleaned up from this flow.\n\nIf the leftover copy's data looks **newer** than the active one, the warning turns red; don't delete its volumes without first deciding which copy to keep. The Configure tab also shows a dismissible note when Supabase stacks are running on your host that Supbuddy doesn't manage at all (e.g. a plain `supabase start`).\n\n### MCP client says \"Invalid OAuth error\" or \"JSON Parse error: Unexpected EOF\"\n\nThe MCP client is trying OAuth discovery and getting an empty 404. Either the token was lost (regenerate it in **Settings → MCP → the client's ⋯ menu → Rotate token**) or you're on a build older than the OAuth-probe fix. Update to the latest version; the server now answers OAuth discovery paths with a structured 404 instead of an empty body, and 401 responses include `WWW-Authenticate: Bearer` so the client doesn't fall back to OAuth.\n\n### MCP token disappeared after app restart\n\nFixed in recent builds. If you're on an older version, regenerate the token. Root cause was that `addMcpClient` didn't trigger state persistence; the client was held in memory only.\n\n### Server Actions return 403 in a Next.js app behind Supbuddy\n\nNext.js's CSRF guard rejects POSTs whose Origin isn't in `experimental.serverActions.allowedOrigins`. Supbuddy detects this and flags it in the warnings chip: open the **Apps** tab and hit **Fix** on the affected app for a paste-ready snippet, or **Apply…** to preview a unified diff and write the change to `next.config` directly. After applying, restart your dev server.\n\nOn **Next.js 15.3+/16**, a proxied dev request can also be blocked (e.g. a \"Cross origin request detected\" warning) because Supbuddy now passes the real browser `Origin` through rather than rewriting it, and Next validates it against `allowedDevOrigins` (which defaults to `localhost`). Add your Supbuddy domain to `allowedDevOrigins` in `next.config` — see [Next.js cross-origin dev requests](#nextjs-cross-origin-dev-requests-alloweddevorigins). This is a separate key from the Server Actions list; 15.3+/16 may need both.\n\n### Vite dev server returns \"Blocked request. This host is not allowed.\" (403)\n\nVite (v5+) rejects requests whose `Host` header isn't in `server.allowedHosts`, so a Vite app reached through a Supbuddy domain 403s until the host is allowed. Supbuddy detects this and flags `vite: N hosts blocked` in the warnings chip: open the **Apps** tab and hit **Fix** on the affected app for a paste-ready snippet, or **Apply…** to preview a diff and write `server.allowedHosts` into your `vite.config` directly. **Restart the Vite dev server afterward**; Vite does not hot-reload its config. A single `.your-project.local` entry covers every subdomain.\n\n### Supabase Realtime: channel reaches `SUBSCRIBED` but no `postgres_changes` events arrive\n\nIf a channel subscribes fine (and writes succeed) but change events never fire, this is almost always **realtime warmup timing right after the stack starts** — not the Supbuddy proxy. Local Realtime can accept a channel join and report `SUBSCRIBED` before its logical-replication binding for the tenant is ready, so `INSERT`/`UPDATE`s in that brief window are silently missed. Give the stack a few seconds after the Supabase tab goes green, then re-subscribe (or reconnect the channel). This is **unrelated to the `.local` domain**: Kong routes `/realtime/v1/*` by path and rewrites the upstream `Host` to its internal realtime tenant, so reaching realtime through `https://api.<project>.local` behaves identically to the raw `localhost:54321` port — forwarding the `.local` host upstream does not change tenant resolution. The new `sb_publishable_*` / `sb_secret_*` API keys also work for local realtime (Kong maps them to the legacy JWT), so you don't need to switch key formats.\n\n### Project shows a red \"PROXY ERROR\" banner: domain resolves but won't load\n\nAfter the proxy starts, Supbuddy runs an end-to-end reachability check: it resolves a project domain through the OS resolver and tries to connect to Caddy on the HTTPS port. If the name resolves but the connection fails, the project shows a red **PROXY ERROR** banner naming the likely cause (DNS, port-forwarding, or mDNS race) plus a recovery action.\n\nThe most common case: the domain resolves to `127.0.0.1` but port 443 won't connect because the elevated `pfctl` 443→8443 redirect drifted away (typically after a restart, so Caddy is up on 8443 with nothing forwarding 443). Click **Retry**; as of v2.3.6 it re-applies the port-forwarding rule (approve the sudo prompt). On older builds, toggle the proxy off→on instead. If LAN sharing is **off**, disregard any \"LAN sharing / Bonjour\" wording in the banner; the cause is the missing forward, not mDNS.\n\n### Port forwarding is on but 443 won't connect\n\nSupbuddy reports port forwarding as **active** only when a live probe confirms 443 actually reaches Caddy — the rule being on disk isn't enough. If the rule is present but not being enforced (typically right after a reboot, or when an older Supbuddy version left `/etc/pf.conf` in a broken state), the status carries a `pf_not_enforcing` diagnostic instead of a false \"enabled\", and the banner tells you to **restart the proxy** to re-apply the redirect.\n\nOlder versions appended their `rdr-anchor` to the **end** of `/etc/pf.conf`, after Apple's filter anchor — which pf rejects, because translation rules must come before filtering rules. That silently invalidated the whole ruleset, so every later `pfctl -f` failed and 443 was dead. Current builds insert the anchor in the correct translation section and **self-heal** a file corrupted by the old version on the next proxy start. Supbuddy keeps a single stable backup at `/etc/pf.conf.supbuddy-backup` (older builds accumulated unbounded timestamped backups). If a restart doesn't fix it, inspect `/etc/pf.conf` and confirm the `rdr-anchor \"virtual.localhost\"` line sits before `anchor \"com.apple/*\"`.\n\n### Proxy came up but shows a degraded \"error\" state\n\nIf the one-time sudo prompt for port forwarding / DNS is cancelled or fails, Supbuddy no longer aborts the whole start. Caddy still starts and HTTPS keeps working on the high port (8443), and the CA is still generated; the proxy just shows an actionable **error** (degraded) state with a **Retry**. Click **Retry** and approve the sudo prompt to restore real-port (80/443) access and DNS. Until then, reach your apps on `https://<domain>:8443`.\n\n### Port already in use (8080, 8443, 5353, 9877)\n\nDefault ports: HTTP 8080, HTTPS 8443, DNS 5353, MCP 9877. Change them in **Settings → Network** / **Settings → MCP**. Find what's holding a port: `lsof -i :<port>`.\n\n### Wipe everything and start over\n\nQuit Supbuddy, then:\n\n```bash\n# Wipe app data (state, certs, Caddyfile, logs, MCP tokens under secrets/)\nrm -rf ~/Library/Application\\ Support/Supbuddy\n\n# Optional: remove the trusted CA\nsudo security delete-certificate -c \"Caddy Local Authority\" /Library/Keychains/System.keychain\n```\n\n## FAQ\n\n### Is Supbuddy free?\n\nYes. Supbuddy is free. Register as many projects and mappings as you want, with full HTTPS, full DNS, full Supabase isolation, and full read and write MCP access. There are no caps and no tiers.\n\n### Does Supbuddy send my data anywhere?\n\nNo. Caddy, the DNS server, and the MCP server all run locally on your Mac. The only outbound traffic is: Tailscale split-DNS push (only if you enabled it), auto-update checks (GitHub Releases), and Google Analytics on the marketing site (not the desktop app). The desktop app does not send telemetry.\n\n### Can I work offline?\n\nYes. The app works fully offline once the CA is trusted and projects are registered.\n\n### Linux / Windows support?\n\nThe desktop app is macOS-only in v2. The headless CLI and daemon also run on Linux, where `supbuddy service install` registers a `systemd-user` start-on-login unit (macOS uses `launchd`). Windows is not supported. A few desktop code paths (certutil, update-ca-certificates) anticipate other platforms but are not tested there.\n\n### Can I use my own TLD?\n\nYes. Set any TLD in **Settings → General → Default TLD**. Supbuddy installs `/etc/resolver/<project-domain>` files that tell macOS to query our DNS server for that project's domain. Avoid TLDs that actually resolve on the public internet (.com, .net, etc.); your browser will hit the real site for cached entries.\n\n### What happens if I delete a project?\n\nThe project moves to the Trash (visible in **Settings → MCP → Trash**) for 7 days, then is permanently deleted by the sweep timer. Restoring brings back the project record and all its mappings.\n\n### How do I uninstall Supbuddy?\n\n1. Quit the app.\n2. Drag **Supbuddy.app** from `/Applications` to the Trash.\n3. Optional cleanup: see \"Wipe everything and start over\" above.\n4. Optional: `sudo security delete-certificate -c \"Caddy Local Authority\" /Library/Keychains/System.keychain` to remove the trusted CA.\n\n### Where do I report a bug?\n\nEmail support with your version (visible at the bottom of the Settings popover) and the relevant lines from `~/Library/Application Support/Supbuddy/main.log`.\n";
44188
44336
  const HEADER = (filename) => `<!-- AUTO-GENERATED BY SUPBUDDY · DO NOT EDIT (file: ${filename}) -->
44189
44337
  `;
44190
44338
  function renderReadme(ctx) {
@@ -46010,6 +46158,27 @@ async function handleMcpRpc(req) {
46010
46158
  throw new Error(`Unknown MCP RPC op: ${req.op}`);
46011
46159
  }
46012
46160
  }
46161
+ const MCP_CHANNEL_OPS = {
46162
+ "mcp:get-server-state": "get_server_state",
46163
+ "mcp:set-server-running": "set_server_running",
46164
+ "mcp:list-clients": "list_clients",
46165
+ "mcp:create-client": "create_client",
46166
+ "mcp:update-client": "update_client",
46167
+ "mcp:rotate-token": "rotate_token",
46168
+ "mcp:revoke-client": "revoke_client",
46169
+ "mcp:set-primary": "set_primary",
46170
+ "mcp:list-audit": "list_audit",
46171
+ "mcp:list-trash": "list_trash",
46172
+ "mcp:restore": "restore",
46173
+ "mcp:apply-plan": "apply_plan",
46174
+ "mcp:cancel-plan": "cancel_plan"
46175
+ };
46176
+ function mcpChannelToRpcRequest(channel, data) {
46177
+ const op = MCP_CHANNEL_OPS[channel];
46178
+ if (!op) return null;
46179
+ if (channel === "mcp:set-server-running") return { op, enabled: !!data };
46180
+ return { op, ...typeof data === "object" && data !== null ? data : {} };
46181
+ }
46013
46182
  var packet = { exports: {} };
46014
46183
  function BufferReader$1(buffer, offset) {
46015
46184
  this.buffer = buffer;
@@ -48498,17 +48667,24 @@ async function probeOsResolverLoaded(timeoutMs = 1500) {
48498
48667
  return { loaded: false, domain: target, error: e.code || e.message };
48499
48668
  }
48500
48669
  }
48670
+ function classifyPortFallback(primaryPort, primaryOk, fallbackOk) {
48671
+ if (primaryOk) return "ok";
48672
+ if (primaryPort === 443 && fallbackOk) return "pf_not_enforcing";
48673
+ return "unreachable";
48674
+ }
48501
48675
  function resolveReachabilityHint(rawHint, lanSharing) {
48502
48676
  if (rawHint === "mdns_hijack" && !lanSharing) return "resolved_but_unreachable";
48503
48677
  return rawHint;
48504
48678
  }
48505
- async function probeProxyReachability(ownLanIps, timeoutMs = 1500, maxSamples = 8) {
48506
- const store2 = useStore.getState();
48507
- const port = store2.proxyState.portForwardingEnabled ? 443 : store2.settings.httpsPort;
48679
+ function sampleProbeDomains(mappings, getProject, maxSamples) {
48508
48680
  const seenApex = /* @__PURE__ */ new Set();
48509
48681
  const samples = [];
48510
- for (const m of store2.mappings) {
48682
+ for (const m of mappings) {
48511
48683
  if (!m.enabled) continue;
48684
+ if (m.projectId !== null) {
48685
+ const p = getProject(m.projectId);
48686
+ if (!p || p.enabled !== true) continue;
48687
+ }
48512
48688
  const parts = m.domain.split(".").filter(Boolean);
48513
48689
  const apex = parts.length >= 3 ? parts.slice(1).join(".") : parts.join(".");
48514
48690
  if (seenApex.has(apex)) continue;
@@ -48516,6 +48692,12 @@ async function probeProxyReachability(ownLanIps, timeoutMs = 1500, maxSamples =
48516
48692
  samples.push({ domain: m.domain, apex });
48517
48693
  if (samples.length >= maxSamples) break;
48518
48694
  }
48695
+ return samples;
48696
+ }
48697
+ async function probeProxyReachability(ownLanIps, timeoutMs = 1500, maxSamples = 8) {
48698
+ const store2 = useStore.getState();
48699
+ const port = store2.proxyState.portForwardingEnabled ? 443 : store2.settings.httpsPort;
48700
+ const samples = sampleProbeDomains(store2.mappings, store2.getProject, maxSamples);
48519
48701
  if (samples.length === 0) {
48520
48702
  return { ok: true, resolved: [], reachable: [] };
48521
48703
  }
@@ -48529,7 +48711,15 @@ async function probeProxyReachability(ownLanIps, timeoutMs = 1500, maxSamples =
48529
48711
  firstFailure = result;
48530
48712
  }
48531
48713
  }
48532
- if (firstFailure) return firstFailure;
48714
+ if (firstFailure) {
48715
+ if (port === 443 && firstFailure.domain && firstFailure.resolved.length > 0) {
48716
+ const fallback = await probeOneDomain(firstFailure.domain, store2.settings.httpsPort, ownLanIps, timeoutMs);
48717
+ if (classifyPortFallback(port, firstFailure.ok, fallback.ok) === "pf_not_enforcing") {
48718
+ return { ...firstFailure, hint: "pf_not_enforcing" };
48719
+ }
48720
+ }
48721
+ return firstFailure;
48722
+ }
48533
48723
  return lastSuccess ?? { ok: true, resolved: [], reachable: [] };
48534
48724
  }
48535
48725
  async function probeOneDomain(domain, port, ownLanIps, timeoutMs) {
@@ -48608,11 +48798,13 @@ const dnsPlatform = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineP
48608
48798
  auditResolverState,
48609
48799
  buildPlatformDnsCleanupCommand,
48610
48800
  buildPlatformDnsCommand,
48801
+ classifyPortFallback,
48611
48802
  getManagedDomainSuffixes,
48612
48803
  probeLocalDnsServer,
48613
48804
  probeOsResolverLoaded,
48614
48805
  probeProxyReachability,
48615
- resolveReachabilityHint
48806
+ resolveReachabilityHint,
48807
+ sampleProbeDomains
48616
48808
  }, Symbol.toStringTag, { value: "Module" }));
48617
48809
  function buildPfAnchor(input) {
48618
48810
  const { httpPort, httpsPort, lanSharing, lanInterfaces } = input;
@@ -49649,23 +49841,7 @@ async function applyProjectActivation(projectId, opts) {
49649
49841
  globalThis.applyProjectActivation = applyProjectActivation;
49650
49842
  globalThis.reapplyDnsResolversIfDrifted = reapplyDnsResolversIfDrifted;
49651
49843
  async function testPortForwarding(_httpsPort) {
49652
- const net2 = await __vitePreload(() => import("net"), false ? __VITE_PRELOAD__ : void 0);
49653
- return new Promise((resolve) => {
49654
- const socket2 = net2.createConnection({ host: "127.0.0.1", port: 443 });
49655
- const timeout = setTimeout(() => {
49656
- socket2.destroy();
49657
- resolve(false);
49658
- }, 1e3);
49659
- socket2.on("connect", () => {
49660
- clearTimeout(timeout);
49661
- socket2.end();
49662
- resolve(true);
49663
- });
49664
- socket2.on("error", () => {
49665
- clearTimeout(timeout);
49666
- resolve(false);
49667
- });
49668
- });
49844
+ return probe443();
49669
49845
  }
49670
49846
  const migrationCancellation = /* @__PURE__ */ new Map();
49671
49847
  const activeSupabaseStarts = /* @__PURE__ */ new Map();
@@ -49860,6 +50036,22 @@ async function maybeAutoStartProxyForGui() {
49860
50036
  } catch (e) {
49861
50037
  console.error("[Proxy] GUI auto-start failed:", e);
49862
50038
  }
50039
+ const afterFirst = useStore.getState().proxyState;
50040
+ if (afterFirst.needsPrivilegedRepair && /TTY|ASKPASS/i.test(afterFirst.error || "")) {
50041
+ console.warn(
50042
+ "[Proxy] auto-start hit the host-bridge owner race (TTY/ASKPASS) — retrying privileged setup once in 2s"
50043
+ );
50044
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
50045
+ try {
50046
+ await handleStartProxy();
50047
+ const afterRetry = useStore.getState().proxyState;
50048
+ console.log(
50049
+ afterRetry.needsPrivilegedRepair ? "[Proxy] auto-start retry still degraded — privileged setup failed again (manual Retry remains available)" : "[Proxy] auto-start retry recovered — privileged setup applied"
50050
+ );
50051
+ } catch (e) {
50052
+ console.error("[Proxy] auto-start retry failed:", e);
50053
+ }
50054
+ }
49863
50055
  }
49864
50056
  async function handleStartProxy() {
49865
50057
  const alreadyRunning = isCaddyRunning();
@@ -49882,7 +50074,7 @@ async function handleStartProxy() {
49882
50074
  }
49883
50075
  try {
49884
50076
  const { httpPort, httpsPort } = store2.settings;
49885
- const pfStatus = await getPortForwardingStatus(httpPort, httpsPort);
50077
+ const pfStatus = await getPortForwardingStatus(httpPort, httpsPort, isCaddyRunning() ? { probe: probe443 } : void 0);
49886
50078
  store2.setPortForwardingEnabled(pfStatus.enabled);
49887
50079
  console.log(`[Proxy] Port forwarding status: ${pfStatus.enabled ? "enabled" : "disabled"}`);
49888
50080
  const sudoCommands = [];
@@ -49895,24 +50087,42 @@ async function handleStartProxy() {
49895
50087
  lanSharing,
49896
50088
  lanInterfaces: lanSharing ? getLanInterfaces() : []
49897
50089
  });
49898
- const tmpAnchor = path.join(os$1.tmpdir(), `supbuddy-pf-anchor-${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
50090
+ const tmpSuffix = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
50091
+ const tmpAnchor = path.join(os$1.tmpdir(), `supbuddy-pf-anchor-${tmpSuffix}`);
49899
50092
  fsSync.writeFileSync(tmpAnchor, anchorRules);
49900
50093
  tmpFilesToClean.push(tmpAnchor);
50094
+ let currentPfConf = "";
50095
+ try {
50096
+ currentPfConf = fsSync.readFileSync("/etc/pf.conf", "utf-8");
50097
+ } catch {
50098
+ currentPfConf = "";
50099
+ }
50100
+ const { content: correctedPfConf, changed: pfConfChanged } = buildCorrectedPfConf(currentPfConf);
50101
+ const tmpValidation = path.join(os$1.tmpdir(), `supbuddy-pf-validate-${tmpSuffix}`);
50102
+ fsSync.writeFileSync(tmpValidation, buildValidationPfConf(correctedPfConf, tmpAnchor));
50103
+ tmpFilesToClean.push(tmpValidation);
49901
50104
  try {
49902
- child_process.execSync(`pfctl -nf "${tmpAnchor}"`, { stdio: "pipe" });
50105
+ child_process.execSync(`pfctl -nf "${tmpValidation}"`, { stdio: "pipe" });
49903
50106
  } catch (validationErr) {
49904
50107
  const stderr = (validationErr?.stderr?.toString() ?? "").trim();
49905
50108
  const ranButRejected = validationErr?.status != null && /syntax error|error:/i.test(stderr);
49906
50109
  if (ranButRejected) {
49907
50110
  throw new Error(
49908
- `Generated pf anchor failed validation, refusing to install (would disable port forwarding): ${stderr}`
50111
+ `Generated pf ruleset failed validation, refusing to install (would disable port forwarding): ${stderr}`
49909
50112
  );
49910
50113
  }
49911
- console.warn("[Proxy] pf anchor pre-validation could not run (continuing):", validationErr?.message);
50114
+ console.warn("[Proxy] pf pre-validation could not run (continuing):", validationErr?.message);
49912
50115
  }
49913
50116
  sudoCommands.push(`cp "${tmpAnchor}" /etc/pf.anchors/virtual.localhost`);
49914
- sudoCommands.push("pfctl -e 2>/dev/null || true");
49915
- sudoCommands.push("pfctl -f /etc/pf.conf 2>&1 || true");
50117
+ if (pfConfChanged) {
50118
+ const tmpPfConf = path.join(os$1.tmpdir(), `supbuddy-pf-conf-${tmpSuffix}`);
50119
+ fsSync.writeFileSync(tmpPfConf, correctedPfConf);
50120
+ tmpFilesToClean.push(tmpPfConf);
50121
+ sudoCommands.push("{ [ -f /etc/pf.conf.supbuddy-backup ] || cp /etc/pf.conf /etc/pf.conf.supbuddy-backup; }");
50122
+ sudoCommands.push(`cp "${tmpPfConf}" /etc/pf.conf`);
50123
+ }
50124
+ sudoCommands.push("{ pfctl -e 2>/dev/null || true; }");
50125
+ sudoCommands.push("pfctl -f /etc/pf.conf");
49916
50126
  }
49917
50127
  const thinIps = thinAliasIps(store2.projects);
49918
50128
  if (thinIps.length > 0) {
@@ -49937,6 +50147,7 @@ async function handleStartProxy() {
49937
50147
  sudoCommands.push(dnsCmd.command);
49938
50148
  tmpFilesToClean.push(...dnsCmd.tmpFiles);
49939
50149
  }
50150
+ let privilegedFailure = null;
49940
50151
  if (sudoCommands.length > 0 && process.send) {
49941
50152
  const batchedCommand = sudoCommands.join(" && ");
49942
50153
  console.log(`[Proxy] Executing batched sudo (${sudoCommands.length} operations)...`);
@@ -49963,16 +50174,16 @@ async function handleStartProxy() {
49963
50174
  process.on("message", handler);
49964
50175
  });
49965
50176
  if (!sudoResult.success) {
49966
- const reason = sudoResult.error || "unknown error";
49967
- console.error(`[Proxy] sudo setup failed: ${reason}`);
49968
- throw new Error(`Privileged setup failed: ${reason}. Port forwarding and DNS resolution may be incomplete.`);
49969
- }
49970
- console.log("[Proxy] sudo setup result: success");
49971
- const resolverAudit = await auditResolverState().catch(() => null);
49972
- if (resolverAudit && resolverAudit.in_sync === false && resolverAudit.missing.length > 0) {
49973
- throw new Error(
49974
- `DNS resolver files missing after privileged setup: ${resolverAudit.missing.join(", ")}. The OS resolver can't route these project domains — re-run the proxy setup.`
50177
+ privilegedFailure = sudoResult.error || "unknown error";
50178
+ console.error(
50179
+ `[Proxy] privileged setup failed (continuing degraded Caddy still starts): ${privilegedFailure}`
49975
50180
  );
50181
+ } else {
50182
+ console.log("[Proxy] sudo setup result: success");
50183
+ const resolverAudit = await auditResolverState().catch(() => null);
50184
+ if (resolverAudit && resolverAudit.in_sync === false && resolverAudit.missing.length > 0) {
50185
+ privilegedFailure = `DNS resolver files missing after privileged setup: ${resolverAudit.missing.join(", ")}`;
50186
+ }
49976
50187
  }
49977
50188
  }
49978
50189
  if (!alreadyRunning) {
@@ -49980,7 +50191,15 @@ async function handleStartProxy() {
49980
50191
  } else {
49981
50192
  store2.setProxyStatus("running");
49982
50193
  }
49983
- store2.setProxyFields({ networkingDegraded: false, needsPrivilegedRepair: false });
50194
+ if (privilegedFailure) {
50195
+ store2.setProxyFields({ networkingDegraded: true, needsPrivilegedRepair: true });
50196
+ store2.setProxyStatus(
50197
+ "error",
50198
+ `Privileged setup failed: ${privilegedFailure}. HTTPS still works on port ${store2.settings.httpsPort}; port 443 and .${store2.settings.defaultTld || "test"} DNS may be unavailable — click Retry to re-run the privileged setup.`
50199
+ );
50200
+ } else {
50201
+ store2.setProxyFields({ networkingDegraded: false, needsPrivilegedRepair: false });
50202
+ }
49984
50203
  refreshBundledRuntimeBundleAfterCaddy().catch(
49985
50204
  (err) => console.warn("[Worker] bundled-runtime bundle refresh failed:", err.message)
49986
50205
  );
@@ -50059,12 +50278,13 @@ async function checkProxyReachabilityAndSurface() {
50059
50278
  mdns_hijack: `Browser DNS for ${result.domain} returns ${result.resolved.join(", ")} (your own LAN IP) but Caddy isn't reachable on port ${result.port}. This usually means LAN sharing is publishing the name via Bonjour and pf rules need a re-apply — toggle the proxy off/on, or disable LAN sharing.`,
50060
50279
  foreign_owner: `Another device on your LAN is responding for ${result.domain} (${result.resolved.join(", ")}) — Bonjour/mDNS race for the .local namespace. Switch this project's TLD to .test in Settings, or take the other device offline.`,
50061
50280
  no_resolution: `The OS resolver couldn't resolve ${result.domain}. The resolver files and DNS server on :${store2.dnsState.port} may be fine — on macOS Sonoma+ the OS often just hasn't loaded /etc/resolver yet. Click RETRY (or restart the proxy) to rewrite the resolver files and reload the OS DNS cache. If it persists, run get_health → dns.resolver to check for missing files.`,
50062
- resolved_but_unreachable: `${result.domain} resolves to ${result.resolved.join(", ")} but TCP connect to port ${result.port} fails. Likely a port-forwarding rule is missing for that IP — toggle the proxy off/on.`
50281
+ resolved_but_unreachable: `${result.domain} resolves to ${result.resolved.join(", ")} but TCP connect to port ${result.port} fails. Likely a port-forwarding rule is missing for that IP — toggle the proxy off/on.`,
50282
+ pf_not_enforcing: `${result.domain} resolves correctly and Caddy is serving on port ${store2.settings.httpsPort}, but the pf 443→${store2.settings.httpsPort} redirect is not active — /etc/pf.conf likely failed to load. Restart the proxy to re-apply it (the app now self-heals the pf.conf ordering).`
50063
50283
  };
50064
50284
  const effectiveHint = resolveReachabilityHint2(result.hint, store2.settings.lanSharing);
50065
50285
  const message = effectiveHint ? hintMessage[effectiveHint] : `${result.domain} is not reachable on port ${result.port}.`;
50066
50286
  console.warn("[Proxy] reachability probe failed:", message, result);
50067
- const pfRepairable = effectiveHint === "resolved_but_unreachable" || effectiveHint === "mdns_hijack";
50287
+ const pfRepairable = effectiveHint === "resolved_but_unreachable" || effectiveHint === "mdns_hijack" || effectiveHint === "pf_not_enforcing";
50068
50288
  if (pfRepairable) store2.setProxyFields({ needsPrivilegedRepair: true });
50069
50289
  store2.setProxyStatus("error", message);
50070
50290
  }
@@ -50436,7 +50656,11 @@ process.on("message", async (message) => {
50436
50656
  }
50437
50657
  case "port-forwarding:status": {
50438
50658
  const { httpPort = 8080, httpsPort = 8443 } = message.data ?? {};
50439
- const status = await getPortForwardingStatus(httpPort, httpsPort);
50659
+ const status = await getPortForwardingStatus(
50660
+ httpPort,
50661
+ httpsPort,
50662
+ isCaddyRunning() ? { probe: probe443 } : void 0
50663
+ );
50440
50664
  useStore.getState().setPortForwardingEnabled(status.enabled);
50441
50665
  process.send({ type: "port-forwarding:status:response", data: status });
50442
50666
  break;
@@ -50450,14 +50674,56 @@ process.on("message", async (message) => {
50450
50674
  process.send({ type: "port-forwarding:enable:response", data: { success: true } });
50451
50675
  break;
50452
50676
  }
50677
+ const effLanSharing = lanSharing ?? store2.settings.lanSharing;
50678
+ let currentPfConf = "";
50679
+ try {
50680
+ currentPfConf = fsSync.readFileSync("/etc/pf.conf", "utf-8");
50681
+ } catch {
50682
+ currentPfConf = "";
50683
+ }
50684
+ const { content: correctedPfConf, changed: pfConfChanged } = buildCorrectedPfConf(currentPfConf);
50685
+ const tmpSuffix = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
50686
+ const tmpAnchor = path.join(os$1.tmpdir(), `supbuddy-pf-anchor-${tmpSuffix}`);
50687
+ fsSync.writeFileSync(tmpAnchor, buildAnchorContent(httpPort, httpsPort, effLanSharing));
50688
+ const tmpFiles = [tmpAnchor];
50689
+ let tmpPfConf = null;
50690
+ if (pfConfChanged) {
50691
+ tmpPfConf = path.join(os$1.tmpdir(), `supbuddy-pf-conf-${tmpSuffix}`);
50692
+ fsSync.writeFileSync(tmpPfConf, correctedPfConf);
50693
+ tmpFiles.push(tmpPfConf);
50694
+ }
50695
+ const tmpValidation = path.join(os$1.tmpdir(), `supbuddy-pf-validate-${tmpSuffix}`);
50696
+ fsSync.writeFileSync(tmpValidation, buildValidationPfConf(correctedPfConf, tmpAnchor));
50697
+ tmpFiles.push(tmpValidation);
50698
+ try {
50699
+ child_process.execSync(`pfctl -nf "${tmpValidation}"`, { stdio: "pipe" });
50700
+ } catch (validationErr) {
50701
+ const stderr = (validationErr?.stderr?.toString() ?? "").trim();
50702
+ const ranButRejected = validationErr?.status != null && /syntax error|error:/i.test(stderr);
50703
+ if (ranButRejected) {
50704
+ process.send({
50705
+ type: "port-forwarding:enable:response",
50706
+ data: {
50707
+ success: false,
50708
+ error: `Generated pf ruleset failed validation, refusing to install: ${stderr}`
50709
+ }
50710
+ });
50711
+ break;
50712
+ }
50713
+ console.warn("[PortForwarding] pf pre-validation could not run (continuing):", validationErr?.message);
50714
+ }
50453
50715
  const command = getEnablePortForwardingCommand(
50454
50716
  httpPort,
50455
50717
  httpsPort,
50456
- lanSharing ?? store2.settings.lanSharing
50718
+ effLanSharing,
50719
+ currentPfConf,
50720
+ tmpAnchor,
50721
+ tmpPfConf
50457
50722
  );
50458
50723
  const result = await requestPrivilegedBatch(
50459
50724
  command,
50460
- "Supbuddy needs administrator access to set up port forwarding (ports 80/443)."
50725
+ "Supbuddy needs administrator access to set up port forwarding (ports 80/443).",
50726
+ tmpFiles
50461
50727
  );
50462
50728
  if (result.success) store2.setPortForwardingEnabled(true);
50463
50729
  process.send({
@@ -51221,6 +51487,16 @@ process.on("message", async (message) => {
51221
51487
  process.send({ type: "ca:instructions:response", data: instructions });
51222
51488
  break;
51223
51489
  }
51490
+ case "ca:install": {
51491
+ const result = await installCaddyCA();
51492
+ process.send({ type: "ca:install:response", data: result });
51493
+ break;
51494
+ }
51495
+ case "ca:uninstall": {
51496
+ const result = await uninstallCaddyCA();
51497
+ process.send({ type: "ca:uninstall:response", data: result });
51498
+ break;
51499
+ }
51224
51500
  case "brt:status": {
51225
51501
  try {
51226
51502
  const store2 = useStore.getState();
@@ -51302,7 +51578,11 @@ process.on("message", async (message) => {
51302
51578
  (m) => m.enabled && m.domain.endsWith("." + tld)
51303
51579
  );
51304
51580
  if (candidate) {
51305
- url2 = `https://${candidate.domain}:${store2.settings.httpsPort}/`;
51581
+ url2 = buildTrustProbeUrl(
51582
+ candidate.domain,
51583
+ store2.settings.httpsPort,
51584
+ store2.proxyState.portForwardingEnabled ?? false
51585
+ );
51306
51586
  }
51307
51587
  }
51308
51588
  if (!url2) {
@@ -52092,11 +52372,36 @@ process.on("message", async (message) => {
52092
52372
  process.send({ type: "dns:status:response", _rid: message._rid, data: store2.dnsState });
52093
52373
  break;
52094
52374
  }
52095
- case "system:unmanaged-supabase": {
52375
+ case "system:unmanagedSupabase": {
52096
52376
  const store2 = useStore.getState();
52097
52377
  const known = store2.projects.map((p) => p.supabaseProjectId).filter((id) => typeof id === "string" && id.length > 0);
52098
52378
  const stacks = await detectUnmanagedSupabaseStacks(known);
52099
- process.send({ type: "system:unmanaged-supabase:response", _rid: message._rid, data: stacks });
52379
+ process.send({ type: "system:unmanagedSupabase:response", _rid: message._rid, data: stacks });
52380
+ break;
52381
+ }
52382
+ case "project-context:get-settings": {
52383
+ const data = await handleProjectContextRpc({ op: "get_settings", project_id: message.data.project_id });
52384
+ process.send({ type: "project-context:get-settings:response", _rid: message._rid, data });
52385
+ break;
52386
+ }
52387
+ case "project-context:update-settings": {
52388
+ const data = await handleProjectContextRpc({ op: "update_settings", project_id: message.data.project_id, patch: message.data.patch });
52389
+ process.send({ type: "project-context:update-settings:response", _rid: message._rid, data });
52390
+ break;
52391
+ }
52392
+ case "project-context:sync-now": {
52393
+ const data = await handleProjectContextRpc({ op: "sync_now", project_id: message.data.project_id });
52394
+ process.send({ type: "project-context:sync-now:response", _rid: message._rid, data });
52395
+ break;
52396
+ }
52397
+ case "project-context:refresh-detection": {
52398
+ const data = await handleProjectContextRpc({ op: "refresh_detection", project_id: message.data.project_id });
52399
+ process.send({ type: "project-context:refresh-detection:response", _rid: message._rid, data });
52400
+ break;
52401
+ }
52402
+ case "project-context:sync-all-now": {
52403
+ const data = await handleProjectContextRpc({ op: "sync_all_now" });
52404
+ process.send({ type: "project-context:sync-all-now:response", _rid: message._rid, data });
52100
52405
  break;
52101
52406
  }
52102
52407
  case "tailscale:status": {
@@ -52306,8 +52611,19 @@ process.on("message", async (message) => {
52306
52611
  }
52307
52612
  break;
52308
52613
  }
52309
- default:
52614
+ default: {
52615
+ const rpcReq = mcpChannelToRpcRequest(message.type, message.data);
52616
+ if (rpcReq) {
52617
+ try {
52618
+ const data = await handleMcpRpc(rpcReq);
52619
+ process.send({ type: `${message.type}:response`, _rid: message._rid, data });
52620
+ } catch (error) {
52621
+ process.send({ type: `${message.type}:response`, _rid: message._rid, error: error.message });
52622
+ }
52623
+ break;
52624
+ }
52310
52625
  console.warn("Unknown message type:", message.type);
52626
+ }
52311
52627
  }
52312
52628
  } catch (error) {
52313
52629
  console.error("Error handling message:", error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "supbuddy",
3
- "version": "3.0.11",
3
+ "version": "3.0.12",
4
4
  "description": "Run multiple Supabase projects at once on custom local domains with HTTPS. A headless CLI and daemon (proxy, DNS, Supabase/Compose lifecycle, MCP) for macOS and Linux.",
5
5
  "keywords": [
6
6
  "supabase",