@kelceyp/caw 1.0.35 → 1.0.36

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 (3) hide show
  1. package/README.md +19 -3
  2. package/dist/caw.js +1808 -16
  3. package/package.json +1 -1
package/dist/caw.js CHANGED
@@ -10488,6 +10488,106 @@ function createCommand(name) {
10488
10488
  }
10489
10489
  // node_modules/@kelceyp/clibuilder/dist/builders/CommandGroup.js
10490
10490
  init_CLIError();
10491
+ class CommandGroupBuilder {
10492
+ _name;
10493
+ _summary;
10494
+ _description;
10495
+ _children = [];
10496
+ _parent;
10497
+ _defaultChild;
10498
+ constructor(name, parent) {
10499
+ const nameError = validateName(name, "group");
10500
+ if (nameError) {
10501
+ throw new ConfigurationError(nameError);
10502
+ }
10503
+ this._name = name;
10504
+ this._parent = parent;
10505
+ }
10506
+ summary(summary) {
10507
+ if (!summary || typeof summary !== "string" || summary.trim() === "") {
10508
+ throw new TypeError("Summary must be a non-empty string");
10509
+ }
10510
+ this._summary = summary;
10511
+ return this;
10512
+ }
10513
+ description(description) {
10514
+ if (!description || typeof description !== "string" || description.trim() === "") {
10515
+ throw new TypeError("Description must be a non-empty string");
10516
+ }
10517
+ this._description = description;
10518
+ return this;
10519
+ }
10520
+ command(command) {
10521
+ if (!command || command.type !== "command") {
10522
+ throw new TypeError("command() requires a Command object. Use build() on CommandBuilder first.");
10523
+ }
10524
+ this._children.push(command);
10525
+ return this;
10526
+ }
10527
+ group(group) {
10528
+ if (!group || group.type !== "group") {
10529
+ throw new ConfigurationError("group() requires a CommandGroup object. Use build() on CommandGroupBuilder first.");
10530
+ }
10531
+ this._children.push(group);
10532
+ return this;
10533
+ }
10534
+ commandGroup(name) {
10535
+ if (!name || typeof name !== "string") {
10536
+ throw new TypeError("Command group name must be a non-empty string");
10537
+ }
10538
+ return new CommandGroupBuilder(name, this);
10539
+ }
10540
+ defaultChild(name) {
10541
+ if (!name || typeof name !== "string" || name.trim() === "") {
10542
+ throw new TypeError("defaultChild name must be a non-empty string");
10543
+ }
10544
+ this._defaultChild = name;
10545
+ return this;
10546
+ }
10547
+ build() {
10548
+ if (this._children.length === 0) {
10549
+ throw new ConfigurationError(`CommandGroup "${this._name}" must have at least one command or command group. Add children with .command() or .commandGroup()`);
10550
+ }
10551
+ const childNames = new Set;
10552
+ for (const child of this._children) {
10553
+ if (childNames.has(child.name)) {
10554
+ throw new ConfigurationError(`CommandGroup "${this._name}" has duplicate child name "${child.name}"`);
10555
+ }
10556
+ childNames.add(child.name);
10557
+ if (child.type === "command" && child.aliases) {
10558
+ const aliases = child.aliases || [];
10559
+ for (const alias of aliases) {
10560
+ if (childNames.has(alias)) {
10561
+ throw new ConfigurationError(`CommandGroup "${this._name}" has duplicate child name/alias "${alias}"`);
10562
+ }
10563
+ childNames.add(alias);
10564
+ }
10565
+ }
10566
+ }
10567
+ if (this._defaultChild) {
10568
+ if (!childNames.has(this._defaultChild)) {
10569
+ const availableChildren = Array.from(childNames).join(", ");
10570
+ throw new ConfigurationError(`CommandGroup "${this._name}" has invalid defaultChild "${this._defaultChild}". ` + `Available children: ${availableChildren}`);
10571
+ }
10572
+ }
10573
+ const group = {
10574
+ type: "group",
10575
+ name: this._name,
10576
+ summary: this._summary,
10577
+ description: this._description,
10578
+ children: this._children,
10579
+ defaultChild: this._defaultChild
10580
+ };
10581
+ if (this._parent) {
10582
+ this._parent._children.push(group);
10583
+ return this._parent;
10584
+ }
10585
+ return group;
10586
+ }
10587
+ }
10588
+ function createCommandGroup(name) {
10589
+ return new CommandGroupBuilder(name);
10590
+ }
10491
10591
  // node_modules/@kelceyp/clibuilder/dist/types/RuntimeBindings.js
10492
10592
  var globalHandlerRegistry = new Map;
10493
10593
  // src/guards.js
@@ -10842,6 +10942,9 @@ function hasPendingConfig(envDir) {
10842
10942
  function readPendingConfig(envDir) {
10843
10943
  return readJsonFile(pendingPath(envDir));
10844
10944
  }
10945
+ function writePendingConfig(envDir, data) {
10946
+ atomicWrite(pendingPath(envDir), data);
10947
+ }
10845
10948
  function deletePendingConfig(envDir) {
10846
10949
  fs4.unlinkSync(pendingPath(envDir));
10847
10950
  }
@@ -11689,6 +11792,23 @@ function buildEnvNodeArgs(envDir) {
11689
11792
  const envFilePath = path8.join(envDir, ".env");
11690
11793
  return [`--env-file=${envFilePath}`];
11691
11794
  }
11795
+ function buildServerEnvVars(activeConfig, envDir) {
11796
+ if (typeof envDir !== "string" || envDir.length === 0) {
11797
+ throw new Error("buildServerEnvVars: envDir is required (server main.js exits when CAW_ENV_DIR is unset)");
11798
+ }
11799
+ const envVars = {
11800
+ CAW_PORT: String(activeConfig.port),
11801
+ CAW_ENV_DIR: envDir
11802
+ };
11803
+ if (typeof activeConfig.installId === "string" && activeConfig.installId.length > 0 && typeof activeConfig.installSalt === "string" && activeConfig.installSalt.length > 0) {
11804
+ envVars.CAW_INSTALL_ID = String(activeConfig.installId);
11805
+ envVars.CAW_INSTALL_SALT = String(activeConfig.installSalt);
11806
+ }
11807
+ if (typeof activeConfig.analyticsEnabled === "boolean") {
11808
+ envVars.CAW_ANALYTICS_ENABLED = activeConfig.analyticsEnabled ? "true" : "false";
11809
+ }
11810
+ return envVars;
11811
+ }
11692
11812
  function sleepSync(ms) {
11693
11813
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
11694
11814
  }
@@ -11912,17 +12032,7 @@ How would you like to proceed?`,
11912
12032
  }
11913
12033
  console.log(`Found environment file: ${envCheck.path}`);
11914
12034
  rotateLogIfNeeded(envDir);
11915
- const envVars = {
11916
- CAW_PORT: String(activeConfig.port),
11917
- CAW_ENV_DIR: envDir
11918
- };
11919
- if (typeof activeConfig.installId === "string" && activeConfig.installId.length > 0 && typeof activeConfig.installSalt === "string" && activeConfig.installSalt.length > 0) {
11920
- envVars.CAW_INSTALL_ID = String(activeConfig.installId);
11921
- envVars.CAW_INSTALL_SALT = String(activeConfig.installSalt);
11922
- }
11923
- if (typeof activeConfig.analyticsEnabled === "boolean") {
11924
- envVars.CAW_ANALYTICS_ENABLED = activeConfig.analyticsEnabled ? "true" : "false";
11925
- }
12035
+ const envVars = buildServerEnvVars(activeConfig, envDir);
11926
12036
  const nodeArgs = buildEnvNodeArgs(envDir);
11927
12037
  const pm2 = createProcessManager(activeConfig, envDir);
11928
12038
  const id = pm2.start(serverInfo.mainJsPath, envVars, nodeArgs);
@@ -12620,10 +12730,7 @@ How would you like to proceed?`,
12620
12730
  }
12621
12731
  console.log(`Found environment file: ${envCheck.path}`);
12622
12732
  rotateLogIfNeeded(envDir);
12623
- const envVars = {
12624
- CAW_PORT: String(activeConfig.port),
12625
- CAW_ENV_DIR: envDir
12626
- };
12733
+ const envVars = buildServerEnvVars(activeConfig, envDir);
12627
12734
  const nodeArgs = buildEnvNodeArgs(envDir);
12628
12735
  const pm2 = createProcessManager(activeConfig, envDir);
12629
12736
  const id = pm2.start(serverInfo.mainJsPath, envVars, nodeArgs);
@@ -12640,6 +12747,1691 @@ How would you like to proceed?`,
12640
12747
  };
12641
12748
  var restart_default = Object.freeze({ create: create7 });
12642
12749
 
12750
+ // src/commands/caddy.js
12751
+ import fs15 from "node:fs";
12752
+ import path15 from "node:path";
12753
+ import os8 from "node:os";
12754
+ import http from "node:http";
12755
+ import https from "node:https";
12756
+ import crypto3 from "node:crypto";
12757
+ import { execFile, spawn as spawn3 } from "node:child_process";
12758
+ var PRODUCTION_SEAMS = Object.freeze({ execFile, spawn: spawn3, httpRequest: productionHttpRequest });
12759
+ var DEFAULT_ENV_DIR = "~/.caw/";
12760
+ var DEFAULT_LABEL = "com.caw.caddy";
12761
+ var DEFAULT_LISTEN_HTTP = 80;
12762
+ var DEFAULT_LISTEN_HTTPS = 443;
12763
+ var DEFAULT_ADMIN_ADDRESS = "127.0.0.1:2019";
12764
+ var DEFAULT_KEYCHAIN_PATH = "/Library/Keychains/System.keychain";
12765
+ var DEFAULT_USR_LOCAL_CADDY = "/usr/local/bin/caddy";
12766
+ var DEFAULT_HOMEBREW_CADDY = "/opt/homebrew/bin/caddy";
12767
+ var DEFAULT_SUDO_PATH = "/usr/bin/sudo";
12768
+ function buildKeychainFindCertArgv(keychainPath) {
12769
+ if (typeof keychainPath !== "string" || keychainPath.length === 0) {
12770
+ throw new TypeError("buildKeychainFindCertArgv: keychainPath is required");
12771
+ }
12772
+ return [
12773
+ "find-certificate",
12774
+ "-a",
12775
+ "-c",
12776
+ "Caddy Local Authority",
12777
+ "-Z",
12778
+ keychainPath
12779
+ ];
12780
+ }
12781
+ function generateCaddyfile({ domain, port, adminAddress, listenHttp, listenHttps }) {
12782
+ requireNonEmptyString("domain", domain);
12783
+ requirePresent("port", port);
12784
+ requireNonEmptyString("adminAddress", adminAddress);
12785
+ requirePresent("listenHttp", listenHttp);
12786
+ requirePresent("listenHttps", listenHttps);
12787
+ return "# caw-managed v1 — generated by `caw caddy setup`; edits will be overwritten\n" + `{
12788
+ ` + ` admin ${adminAddress}
12789
+ ` + ` http_port ${listenHttp}
12790
+ ` + `}
12791
+ ` + `
12792
+ ` + `${domain}:${listenHttps} {
12793
+ ` + ` reverse_proxy localhost:${port}
12794
+ ` + `}
12795
+ `;
12796
+ }
12797
+ function generatePlist({ label, caddyBinaryPath, caddyfilePath, stdoutLogPath, stderrLogPath }) {
12798
+ requireNonEmptyString("label", label);
12799
+ requireNonEmptyString("caddyBinaryPath", caddyBinaryPath);
12800
+ requireNonEmptyString("caddyfilePath", caddyfilePath);
12801
+ requireNonEmptyString("stdoutLogPath", stdoutLogPath);
12802
+ requireNonEmptyString("stderrLogPath", stderrLogPath);
12803
+ return `<?xml version="1.0" encoding="UTF-8"?>
12804
+ ` + `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
12805
+ ` + `<plist version="1.0">
12806
+ ` + `<dict>
12807
+ ` + ` <key>Label</key>
12808
+ ` + ` <string>${escapeXml(label)}</string>
12809
+ ` + ` <key>ProgramArguments</key>
12810
+ ` + ` <array>
12811
+ ` + ` <string>${escapeXml(caddyBinaryPath)}</string>
12812
+ ` + ` <string>run</string>
12813
+ ` + ` <string>--config</string>
12814
+ ` + ` <string>${escapeXml(caddyfilePath)}</string>
12815
+ ` + ` </array>
12816
+ ` + ` <key>RunAtLoad</key>
12817
+ ` + ` <true/>
12818
+ ` + ` <key>KeepAlive</key>
12819
+ ` + ` <true/>
12820
+ ` + ` <key>StandardOutPath</key>
12821
+ ` + ` <string>${escapeXml(stdoutLogPath)}</string>
12822
+ ` + ` <key>StandardErrorPath</key>
12823
+ ` + ` <string>${escapeXml(stderrLogPath)}</string>
12824
+ ` + `</dict>
12825
+ ` + `</plist>
12826
+ `;
12827
+ }
12828
+ async function readKeychainFingerprints({ execFile: execFileSeam, keychainPath = DEFAULT_KEYCHAIN_PATH } = {}) {
12829
+ if (typeof execFileSeam !== "function") {
12830
+ throw new TypeError("readKeychainFingerprints: execFile seam is required");
12831
+ }
12832
+ const argv = buildKeychainFindCertArgv(keychainPath);
12833
+ const stdout = await execFileAsync(execFileSeam, "security", argv);
12834
+ return parseSha256Fingerprints(stdout);
12835
+ }
12836
+ function parseSha256Fingerprints(stdout) {
12837
+ const set = new Set;
12838
+ if (typeof stdout !== "string" || stdout.length === 0)
12839
+ return set;
12840
+ const re = /SHA-256\s+hash:\s+([0-9a-fA-F]{64})/g;
12841
+ let m;
12842
+ while ((m = re.exec(stdout)) !== null) {
12843
+ set.add(m[1].toUpperCase());
12844
+ }
12845
+ return set;
12846
+ }
12847
+ function execFileAsync(execFileSeam, cmd, args) {
12848
+ return new Promise((resolve2, reject) => {
12849
+ execFileSeam(cmd, args, (err, stdout) => {
12850
+ if (err) {
12851
+ if (typeof stdout === "string")
12852
+ err.stdout = stdout;
12853
+ reject(err);
12854
+ } else {
12855
+ resolve2(typeof stdout === "string" ? stdout : String(stdout ?? ""));
12856
+ }
12857
+ });
12858
+ });
12859
+ }
12860
+ function requireNonEmptyString(name, v) {
12861
+ if (typeof v !== "string" || v.length === 0) {
12862
+ throw new TypeError(`${name} must be a non-empty string`);
12863
+ }
12864
+ }
12865
+ function requirePresent(name, v) {
12866
+ if (v === undefined || v === null || v === "") {
12867
+ throw new TypeError(`${name} is required`);
12868
+ }
12869
+ }
12870
+ function escapeXml(s) {
12871
+ return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
12872
+ }
12873
+ var CAW_MANAGED_MARKER_RE = /^# caw-managed v\d+\b/m;
12874
+ function hasCawManagedMarker(text) {
12875
+ return typeof text === "string" && CAW_MANAGED_MARKER_RE.test(text);
12876
+ }
12877
+ function parseLaunchctlPrint(stdout) {
12878
+ if (typeof stdout !== "string" || stdout.length === 0)
12879
+ return null;
12880
+ const programMatch = stdout.match(/^\s*program\s*=\s*(\S.*?)\s*$/m);
12881
+ const argsBlock = stdout.match(/arguments\s*=\s*\{([\s\S]*?)^\s*\}/m);
12882
+ let args = null;
12883
+ if (argsBlock) {
12884
+ args = [];
12885
+ const argLine = /^\s*"([^"]*)"\s*$/gm;
12886
+ let m;
12887
+ while ((m = argLine.exec(argsBlock[1])) !== null) {
12888
+ args.push(m[1]);
12889
+ }
12890
+ }
12891
+ let configPath2 = null;
12892
+ if (args) {
12893
+ const idx = args.indexOf("--config");
12894
+ if (idx >= 0 && idx + 1 < args.length)
12895
+ configPath2 = args[idx + 1];
12896
+ }
12897
+ return {
12898
+ program: programMatch ? programMatch[1] : null,
12899
+ args,
12900
+ configPath: configPath2
12901
+ };
12902
+ }
12903
+ function classifyPlistOwnership({ parsed, expected, readCaddyfile }) {
12904
+ if (parsed === null)
12905
+ return "absent";
12906
+ const { program, args, configPath: configPath2 } = parsed;
12907
+ if (!program || !Array.isArray(args) || !configPath2)
12908
+ return "foreign";
12909
+ if (program !== expected.program)
12910
+ return "foreign";
12911
+ if (args.length !== expected.args.length)
12912
+ return "foreign";
12913
+ for (let i = 0;i < args.length; i++) {
12914
+ if (args[i] !== expected.args[i])
12915
+ return "foreign";
12916
+ }
12917
+ if (configPath2 !== expected.configPath)
12918
+ return "foreign";
12919
+ let caddyfileText;
12920
+ try {
12921
+ caddyfileText = readCaddyfile(configPath2);
12922
+ } catch {
12923
+ return "foreign";
12924
+ }
12925
+ const admin = extractAdminDirective(caddyfileText);
12926
+ if (admin !== expected.adminAddress)
12927
+ return "foreign";
12928
+ return "ours";
12929
+ }
12930
+ function extractAdminDirective(text) {
12931
+ if (typeof text !== "string")
12932
+ return null;
12933
+ const m = text.match(/^\s*admin\s+(\S+)\s*$/m);
12934
+ return m ? m[1] : null;
12935
+ }
12936
+ function parseLsofListeners(stdout) {
12937
+ if (typeof stdout !== "string" || stdout.length === 0)
12938
+ return [];
12939
+ const listeners = [];
12940
+ const lines = stdout.split(`
12941
+ `);
12942
+ for (const line of lines) {
12943
+ if (!line || line.startsWith("COMMAND"))
12944
+ continue;
12945
+ const parts = line.trim().split(/\s+/);
12946
+ if (parts.length < 2)
12947
+ continue;
12948
+ const command = parts[0];
12949
+ const pid = parts[1];
12950
+ if (!/^\d+$/.test(pid))
12951
+ continue;
12952
+ listeners.push({ command, pid });
12953
+ }
12954
+ return listeners;
12955
+ }
12956
+ function classifyLegacyCaddyfileJson({ adapted, domain, port, listenHttps, expectedAdminAddress, expectedHttpPort }) {
12957
+ if (adapted === null || typeof adapted !== "object") {
12958
+ return { adopts: false, observed: "adapted JSON is not an object" };
12959
+ }
12960
+ if (adapted.admin !== undefined && adapted.admin !== null) {
12961
+ const listens = extractAdminListens(adapted.admin);
12962
+ if (listens && listens.length > 0 && !listens.includes(expectedAdminAddress)) {
12963
+ return { adopts: false, observed: `admin listen [${listens.join(",")}] != ${expectedAdminAddress}` };
12964
+ }
12965
+ }
12966
+ const httpApp = adapted.apps?.http;
12967
+ if (!httpApp || typeof httpApp !== "object") {
12968
+ return { adopts: false, observed: "apps.http is missing" };
12969
+ }
12970
+ if (httpApp.http_port !== undefined && httpApp.http_port !== null) {
12971
+ if (Number(httpApp.http_port) !== Number(expectedHttpPort)) {
12972
+ return { adopts: false, observed: `apps.http.http_port ${httpApp.http_port} != ${expectedHttpPort}` };
12973
+ }
12974
+ }
12975
+ const servers = httpApp.servers;
12976
+ if (!servers || typeof servers !== "object") {
12977
+ return { adopts: false, observed: "apps.http.servers is missing" };
12978
+ }
12979
+ const serverKeys = Object.keys(servers);
12980
+ if (serverKeys.length !== 1) {
12981
+ return { adopts: false, observed: `apps.http.servers has ${serverKeys.length} entries` };
12982
+ }
12983
+ const server = servers[serverKeys[0]];
12984
+ if (!server || typeof server !== "object") {
12985
+ return { adopts: false, observed: "server entry is not an object" };
12986
+ }
12987
+ if (Array.isArray(server.listen) && server.listen.length > 0) {
12988
+ const target = `:${listenHttps}`;
12989
+ if (!server.listen.includes(target)) {
12990
+ return { adopts: false, observed: `server.listen [${server.listen.join(",")}] != [${target}]` };
12991
+ }
12992
+ }
12993
+ const routes = server.routes;
12994
+ if (!Array.isArray(routes) || routes.length !== 1) {
12995
+ return { adopts: false, observed: `server has ${Array.isArray(routes) ? routes.length : 0} routes` };
12996
+ }
12997
+ const route = routes[0];
12998
+ if (!matchesHostOnly(route.match, domain)) {
12999
+ return { adopts: false, observed: `route.match != host ${domain}` };
13000
+ }
13001
+ const rp = unwrapSubrouteToReverseProxy(route.handle);
13002
+ if (!rp) {
13003
+ return { adopts: false, observed: "route handler is not a single reverse_proxy" };
13004
+ }
13005
+ const upstreams = rp.upstreams;
13006
+ if (!Array.isArray(upstreams) || upstreams.length !== 1) {
13007
+ return { adopts: false, observed: `reverse_proxy has ${Array.isArray(upstreams) ? upstreams.length : 0} upstreams` };
13008
+ }
13009
+ const dial = upstreams[0]?.dial;
13010
+ if (dial !== `localhost:${port}`) {
13011
+ return { adopts: false, observed: `reverse_proxy upstream ${dial} != localhost:${port}` };
13012
+ }
13013
+ return { adopts: true };
13014
+ }
13015
+ function extractAdminListens(adminNode) {
13016
+ if (adminNode === null || adminNode === undefined)
13017
+ return null;
13018
+ if (typeof adminNode === "string")
13019
+ return [adminNode];
13020
+ if (typeof adminNode !== "object")
13021
+ return null;
13022
+ if (Array.isArray(adminNode.listen))
13023
+ return adminNode.listen;
13024
+ if (typeof adminNode.listen === "string")
13025
+ return [adminNode.listen];
13026
+ return [];
13027
+ }
13028
+ function matchesHostOnly(matchArr, domain) {
13029
+ if (!Array.isArray(matchArr) || matchArr.length !== 1)
13030
+ return false;
13031
+ const m = matchArr[0];
13032
+ if (!m || typeof m !== "object")
13033
+ return false;
13034
+ const keys = Object.keys(m);
13035
+ if (keys.length !== 1 || keys[0] !== "host")
13036
+ return false;
13037
+ return Array.isArray(m.host) && m.host.length === 1 && m.host[0] === domain;
13038
+ }
13039
+ function unwrapSubrouteToReverseProxy(handleArr) {
13040
+ if (!Array.isArray(handleArr) || handleArr.length !== 1)
13041
+ return null;
13042
+ const h = handleArr[0];
13043
+ if (!h || typeof h !== "object")
13044
+ return null;
13045
+ if (h.handler === "reverse_proxy")
13046
+ return h;
13047
+ if (h.handler === "subroute") {
13048
+ if (!Array.isArray(h.routes) || h.routes.length !== 1)
13049
+ return null;
13050
+ return unwrapSubrouteToReverseProxy(h.routes[0].handle);
13051
+ }
13052
+ return null;
13053
+ }
13054
+ function safeCaddyVersion(execFileSeam, binaryPath) {
13055
+ return new Promise((resolve2) => {
13056
+ try {
13057
+ execFileSeam(binaryPath, ["version"], (err, stdout) => {
13058
+ if (err)
13059
+ resolve2(null);
13060
+ else
13061
+ resolve2(String(stdout ?? "").trim());
13062
+ });
13063
+ } catch {
13064
+ resolve2(null);
13065
+ }
13066
+ });
13067
+ }
13068
+ function launchctlLabelForPid(execFileSeam, uid, pid) {
13069
+ return new Promise((resolve2) => {
13070
+ try {
13071
+ execFileSeam("launchctl", ["print", `gui/${uid}`], (err, stdout) => {
13072
+ if (err || typeof stdout !== "string") {
13073
+ resolve2(null);
13074
+ return;
13075
+ }
13076
+ const labelRe = new RegExp(`^\\s*(\\S+)\\s*=\\s*\\{[\\s\\S]*?pid\\s*=\\s*${pid}\\b`, "m");
13077
+ const m = stdout.match(labelRe);
13078
+ resolve2(m ? m[1] : null);
13079
+ });
13080
+ } catch {
13081
+ resolve2(null);
13082
+ }
13083
+ });
13084
+ }
13085
+ async function classifyPhase1({ options, deps }) {
13086
+ const {
13087
+ _execFile,
13088
+ fs: fsDep = fs15,
13089
+ hasTty,
13090
+ uid,
13091
+ homeDir,
13092
+ readConfig: readConfig2 = readConfigWithDefaults,
13093
+ generators,
13094
+ paths = {}
13095
+ } = deps;
13096
+ const sudoPath = paths.sudo ?? DEFAULT_SUDO_PATH;
13097
+ const usrLocalCaddy = paths.usrLocalCaddy ?? DEFAULT_USR_LOCAL_CADDY;
13098
+ const homebrewCaddy = paths.homebrewCaddy ?? DEFAULT_HOMEBREW_CADDY;
13099
+ const caddyfilePath = paths.caddyfile ?? path15.join(homeDir, ".caw", "Caddyfile");
13100
+ const plistPath = paths.plist ?? path15.join(homeDir, "Library", "LaunchAgents", `${options.label}.plist`);
13101
+ const stdoutLogPath = paths.stdoutLog ?? path15.join(homeDir, ".caw", "caddy.out.log");
13102
+ const stderrLogPath = paths.stderrLog ?? path15.join(homeDir, ".caw", "caddy.err.log");
13103
+ let whichStdout = "";
13104
+ try {
13105
+ whichStdout = (await execFileAsync(_execFile, "which", ["caddy"])).trim();
13106
+ } catch {
13107
+ whichStdout = "";
13108
+ }
13109
+ if (!whichStdout) {
13110
+ return { tag: "binary-unresolvable", exitCode: 1, message: "Install Caddy first: brew install caddy" };
13111
+ }
13112
+ const caddyBinaryPath = whichStdout;
13113
+ let versionSkewWarning = null;
13114
+ const otherPath = caddyBinaryPath === usrLocalCaddy ? homebrewCaddy : caddyBinaryPath === homebrewCaddy ? usrLocalCaddy : null;
13115
+ if (otherPath && fsDep.existsSync(otherPath) && fsDep.existsSync(caddyBinaryPath)) {
13116
+ const [selfVer, otherVer] = await Promise.all([
13117
+ safeCaddyVersion(_execFile, caddyBinaryPath),
13118
+ safeCaddyVersion(_execFile, otherPath)
13119
+ ]);
13120
+ if (selfVer && otherVer && selfVer !== otherVer) {
13121
+ versionSkewWarning = `Two Caddy binaries with mismatched versions; resolved to ${caddyBinaryPath} (${selfVer}), other at ${otherPath} reports ${otherVer}`;
13122
+ }
13123
+ }
13124
+ if (!fsDep.existsSync(sudoPath)) {
13125
+ return { tag: "sudo-absent", exitCode: 1, message: "/usr/bin/sudo not found; cannot proceed" };
13126
+ }
13127
+ let fingerprints;
13128
+ try {
13129
+ fingerprints = await generators.readKeychainFingerprints();
13130
+ } catch {
13131
+ fingerprints = new Set;
13132
+ }
13133
+ let ttyTrustDecision;
13134
+ if (fingerprints.size > 0) {
13135
+ ttyTrustDecision = "trust-already-present";
13136
+ } else if (hasTty) {
13137
+ ttyTrustDecision = "tty-available";
13138
+ } else {
13139
+ return { tag: "no-tty-trust-needed", exitCode: 1, message: "Trust needed but no TTY; re-run in a terminal or pass --skip-trust (which does not succeed)" };
13140
+ }
13141
+ let activeConfig;
13142
+ try {
13143
+ activeConfig = readConfig2(options.envDir);
13144
+ } catch (e) {
13145
+ return { tag: "envdir-malformed", exitCode: 1, message: e.message };
13146
+ }
13147
+ const domain = activeConfig?.caddy?.domain;
13148
+ const upstreamPort = activeConfig?.port;
13149
+ if (!domain || upstreamPort === undefined || upstreamPort === null) {
13150
+ return { tag: "envdir-malformed", exitCode: 1, message: `envDir ${options.envDir} config is missing caddy.domain or port` };
13151
+ }
13152
+ let printOut = null;
13153
+ try {
13154
+ printOut = await execFileAsync(_execFile, "launchctl", ["print", `gui/${uid}/${options.label}`]);
13155
+ } catch (e) {
13156
+ printOut = null;
13157
+ }
13158
+ const parsedPrint = parseLaunchctlPrint(printOut);
13159
+ const readCaddyfileText = (p) => fsDep.readFileSync(p, "utf8");
13160
+ const ownership = parsedPrint ? classifyPlistOwnership({
13161
+ parsed: parsedPrint,
13162
+ expected: {
13163
+ program: caddyBinaryPath,
13164
+ args: [caddyBinaryPath, "run", "--config", caddyfilePath],
13165
+ configPath: caddyfilePath,
13166
+ adminAddress: options.adminAddress
13167
+ },
13168
+ readCaddyfile: readCaddyfileText
13169
+ }) : "absent";
13170
+ if (ownership === "foreign") {
13171
+ return {
13172
+ tag: "plist-foreign",
13173
+ exitCode: 1,
13174
+ message: `A LaunchAgent under ${options.label} exists but is not ours; run \`launchctl bootout gui/$UID/${options.label}\` first`
13175
+ };
13176
+ }
13177
+ const listenHttps = options.listenHttps;
13178
+ let lsofStdout = "";
13179
+ try {
13180
+ lsofStdout = await execFileAsync(_execFile, "lsof", ["-nP", `-iTCP:${listenHttps}`, "-sTCP:LISTEN"]);
13181
+ } catch (e) {
13182
+ lsofStdout = e?.stdout ?? "";
13183
+ }
13184
+ const listeners = parseLsofListeners(lsofStdout);
13185
+ let portState;
13186
+ if (listeners.length === 0) {
13187
+ if (options.label !== DEFAULT_LABEL && listenHttps !== DEFAULT_LISTEN_HTTPS) {
13188
+ portState = "scratch-passes";
13189
+ } else {
13190
+ portState = "port-free";
13191
+ }
13192
+ } else {
13193
+ const first = listeners[0];
13194
+ const isCaddy = /caddy/i.test(first.command);
13195
+ if (isCaddy) {
13196
+ if (ownership === "ours") {
13197
+ portState = "held-by-ours";
13198
+ } else {
13199
+ const otherLabel = await launchctlLabelForPid(_execFile, uid, first.pid);
13200
+ const labelText = otherLabel || "<other-label>";
13201
+ return {
13202
+ tag: "port-held-by-foreign-caddy",
13203
+ exitCode: 1,
13204
+ message: `Port ${listenHttps} is held by Caddy loaded under ${labelText}; run \`launchctl bootout gui/$UID/${labelText}\` or \`brew services stop caddy\` first`
13205
+ };
13206
+ }
13207
+ } else if (first.command && first.command !== "-") {
13208
+ return {
13209
+ tag: "port-held-by-foreign-non-caddy",
13210
+ exitCode: 1,
13211
+ message: `Port ${listenHttps} is held by ${first.command} (pid ${first.pid}); stop it first`
13212
+ };
13213
+ } else {
13214
+ return {
13215
+ tag: "port-busy-owner-not-determinable",
13216
+ exitCode: 1,
13217
+ message: `Port ${listenHttps} is busy but ownership is not determinable as an unprivileged user; run \`sudo lsof -iTCP:${listenHttps} -sTCP:LISTEN\` to identify`
13218
+ };
13219
+ }
13220
+ }
13221
+ let caddyfileState = "absent";
13222
+ if (fsDep.existsSync(caddyfilePath)) {
13223
+ let text;
13224
+ try {
13225
+ text = fsDep.readFileSync(caddyfilePath, "utf8");
13226
+ } catch (e) {
13227
+ return { tag: "caddyfile-foreign", exitCode: 1, message: `~/.caw/Caddyfile is present and its shape does not match; observed: unreadable (${e.message})` };
13228
+ }
13229
+ if (hasCawManagedMarker(text)) {
13230
+ caddyfileState = "ours-marker";
13231
+ } else {
13232
+ let adaptedStdout;
13233
+ try {
13234
+ adaptedStdout = await execFileAsync(_execFile, caddyBinaryPath, ["adapt", "--config", caddyfilePath]);
13235
+ } catch (e) {
13236
+ return {
13237
+ tag: "caddy-adapt-unavailable",
13238
+ exitCode: 1,
13239
+ message: "`caddy adapt` failed on ~/.caw/Caddyfile; adoption cannot be decided"
13240
+ };
13241
+ }
13242
+ let adapted;
13243
+ try {
13244
+ adapted = JSON.parse(adaptedStdout);
13245
+ } catch {
13246
+ return {
13247
+ tag: "caddy-adapt-unavailable",
13248
+ exitCode: 1,
13249
+ message: "`caddy adapt` failed on ~/.caw/Caddyfile; adoption cannot be decided"
13250
+ };
13251
+ }
13252
+ const verdict = classifyLegacyCaddyfileJson({
13253
+ adapted,
13254
+ domain,
13255
+ port: upstreamPort,
13256
+ listenHttps,
13257
+ expectedAdminAddress: options.adminAddress,
13258
+ expectedHttpPort: options.listenHttp
13259
+ });
13260
+ if (!verdict.adopts) {
13261
+ return {
13262
+ tag: "caddyfile-foreign",
13263
+ exitCode: 1,
13264
+ message: `~/.caw/Caddyfile is present and its shape does not match; observed: ${verdict.observed}`
13265
+ };
13266
+ }
13267
+ caddyfileState = "adopts";
13268
+ }
13269
+ }
13270
+ const continueTag = portState === "held-by-ours" ? "port-held-by-ours" : portState === "scratch-passes" ? "scratch-labelled-run-passes" : "port-free";
13271
+ return {
13272
+ tag: continueTag,
13273
+ exitCode: 0,
13274
+ warning: versionSkewWarning,
13275
+ caddyBinaryPath,
13276
+ ttyTrustDecision,
13277
+ portState,
13278
+ plistState: ownership,
13279
+ caddyfileState,
13280
+ activeConfig: { port: upstreamPort, domain },
13281
+ paths: { caddyfile: caddyfilePath, plist: plistPath, stdoutLog: stdoutLogPath, stderrLog: stderrLogPath }
13282
+ };
13283
+ }
13284
+ function renderPlanPreview({ classification, options, generators }) {
13285
+ const lines = [];
13286
+ lines.push("Phase 1 (Validate) — plan preview (no mutation)");
13287
+ lines.push(` Binary: ${classification.caddyBinaryPath}`);
13288
+ if (classification.warning) {
13289
+ lines.push(` Warning: ${classification.warning}`);
13290
+ }
13291
+ lines.push(` Trust: ${classification.ttyTrustDecision}`);
13292
+ lines.push(` Port state: ${classification.portState}`);
13293
+ lines.push(` Plist state: ${classification.plistState}`);
13294
+ lines.push(` Caddyfile: ${classification.caddyfileState}`);
13295
+ lines.push("");
13296
+ lines.push("Phase 2 would write:");
13297
+ lines.push(` Caddyfile at ${classification.paths.caddyfile}`);
13298
+ const caddyfileText = generators.caddyfile({
13299
+ domain: classification.activeConfig.domain,
13300
+ port: classification.activeConfig.port,
13301
+ adminAddress: options.adminAddress,
13302
+ listenHttp: options.listenHttp,
13303
+ listenHttps: options.listenHttps
13304
+ });
13305
+ lines.push(caddyfileText.replace(/\n$/, "").split(`
13306
+ `).map((l) => ` ${l}`).join(`
13307
+ `));
13308
+ lines.push("");
13309
+ lines.push(` Plist at ${classification.paths.plist}`);
13310
+ lines.push(` Label: ${options.label}`);
13311
+ lines.push(" ProgramArguments:");
13312
+ lines.push(` ${classification.caddyBinaryPath}`);
13313
+ lines.push(" run");
13314
+ lines.push(" --config");
13315
+ lines.push(` ${classification.paths.caddyfile}`);
13316
+ lines.push(` Admin endpoint: ${options.adminAddress}`);
13317
+ return lines.join(`
13318
+ `);
13319
+ }
13320
+ function renderContinueSummary({ classification }) {
13321
+ const lines = [];
13322
+ lines.push(`Phase 1 (Validate) continues: ${classification.tag}`);
13323
+ if (classification.warning)
13324
+ lines.push(`Warning: ${classification.warning}`);
13325
+ lines.push(` Binary: ${classification.caddyBinaryPath}`);
13326
+ lines.push(` Trust: ${classification.ttyTrustDecision}`);
13327
+ lines.push(` Port state: ${classification.portState}`);
13328
+ lines.push(` Plist state: ${classification.plistState}`);
13329
+ lines.push(` Caddyfile: ${classification.caddyfileState}`);
13330
+ return lines.join(`
13331
+ `);
13332
+ }
13333
+ function productionHttpRequest(url, { method = "GET", ca, timeoutMs, family } = {}) {
13334
+ const parsed = new URL(url);
13335
+ const isHttps = parsed.protocol === "https:";
13336
+ const lib = isHttps ? https : http;
13337
+ const requestOpts = {
13338
+ method,
13339
+ hostname: parsed.hostname,
13340
+ port: parsed.port || (isHttps ? 443 : 80),
13341
+ path: parsed.pathname + parsed.search
13342
+ };
13343
+ if (isHttps && ca)
13344
+ requestOpts.ca = ca;
13345
+ if (family)
13346
+ requestOpts.family = family;
13347
+ if (timeoutMs)
13348
+ requestOpts.signal = AbortSignal.timeout(timeoutMs);
13349
+ return new Promise((resolve2, reject) => {
13350
+ const req = lib.request(requestOpts, (res) => {
13351
+ const chunks = [];
13352
+ res.on("data", (c) => chunks.push(c));
13353
+ res.on("end", () => resolve2({
13354
+ status: res.statusCode,
13355
+ headers: res.headers,
13356
+ body: Buffer.concat(chunks).toString("utf8")
13357
+ }));
13358
+ res.on("error", reject);
13359
+ });
13360
+ req.on("error", reject);
13361
+ req.end();
13362
+ });
13363
+ }
13364
+ function sha256HexOfPem(pem) {
13365
+ if (typeof pem !== "string" || pem.length === 0)
13366
+ return null;
13367
+ const match = pem.match(/-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/);
13368
+ if (!match)
13369
+ return null;
13370
+ const b64 = match[1].replace(/\s+/g, "");
13371
+ if (b64.length === 0)
13372
+ return null;
13373
+ let der;
13374
+ try {
13375
+ der = Buffer.from(b64, "base64");
13376
+ } catch {
13377
+ return null;
13378
+ }
13379
+ return crypto3.createHash("sha256").update(der).digest("hex").toUpperCase();
13380
+ }
13381
+ function atomicWriteWithBackup({ fs: fsDep, path: filePath, content }) {
13382
+ let priorContent = null;
13383
+ let hadPrior = false;
13384
+ try {
13385
+ priorContent = fsDep.readFileSync(filePath, "utf8");
13386
+ hadPrior = true;
13387
+ } catch (e) {
13388
+ if (e.code !== "ENOENT")
13389
+ throw e;
13390
+ }
13391
+ if (hadPrior && priorContent === content) {
13392
+ return { wrote: false, hadPrior: true, priorContent };
13393
+ }
13394
+ const tmpPath = `${filePath}.tmp`;
13395
+ fsDep.writeFileSync(tmpPath, content);
13396
+ if (hadPrior) {
13397
+ fsDep.renameSync(filePath, `${filePath}.bak`);
13398
+ }
13399
+ fsDep.renameSync(tmpPath, filePath);
13400
+ return { wrote: true, hadPrior, priorContent };
13401
+ }
13402
+ function sleep(ms) {
13403
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
13404
+ }
13405
+ function tailFile(fsDep, filePath, maxLines) {
13406
+ try {
13407
+ const text = fsDep.readFileSync(filePath, "utf8");
13408
+ const lines = text.split(`
13409
+ `);
13410
+ return lines.slice(-maxLines).join(`
13411
+ `);
13412
+ } catch {
13413
+ return "";
13414
+ }
13415
+ }
13416
+ async function pollAdminForRoot({ httpRequest, adminBaseUrl, attempts, intervalMs, timeoutMs }) {
13417
+ let lastErr;
13418
+ for (let i = 0;i < attempts; i++) {
13419
+ try {
13420
+ const resp = await httpRequest(`${adminBaseUrl}/pki/ca/local`, {
13421
+ method: "GET",
13422
+ timeoutMs
13423
+ });
13424
+ if (resp.status < 200 || resp.status >= 300) {
13425
+ lastErr = new Error(`admin /pki/ca/local returned HTTP ${resp.status}`);
13426
+ } else {
13427
+ let parsed;
13428
+ try {
13429
+ parsed = JSON.parse(resp.body);
13430
+ } catch (e) {
13431
+ lastErr = new Error(`admin /pki/ca/local returned non-JSON: ${e.message}`);
13432
+ continue;
13433
+ }
13434
+ const pem = parsed?.root_certificate;
13435
+ if (typeof pem !== "string" || pem.length === 0) {
13436
+ lastErr = new Error("admin /pki/ca/local response has no root_certificate PEM");
13437
+ continue;
13438
+ }
13439
+ const fingerprint = sha256HexOfPem(pem);
13440
+ if (!fingerprint) {
13441
+ lastErr = new Error("root_certificate PEM did not yield a SHA-256 fingerprint");
13442
+ continue;
13443
+ }
13444
+ return { pem, fingerprint };
13445
+ }
13446
+ } catch (e) {
13447
+ lastErr = e;
13448
+ }
13449
+ if (i < attempts - 1 && intervalMs > 0)
13450
+ await sleep(intervalMs);
13451
+ }
13452
+ throw lastErr ?? new Error("admin poll exhausted with no attempts");
13453
+ }
13454
+ function extractAdminPort(adminAddress) {
13455
+ const m = String(adminAddress).match(/^([^:]+):(\d+)$/);
13456
+ if (!m)
13457
+ throw new Error(`admin-address must be host:port, got ${adminAddress}`);
13458
+ return { host: m[1], port: Number(m[2]) };
13459
+ }
13460
+ function buildAdminBaseUrl(adminAddress) {
13461
+ const { port } = extractAdminPort(adminAddress);
13462
+ return `http://127.0.0.1:${port}`;
13463
+ }
13464
+ function spawnAwaitExit(spawnSeam, command, args, opts = {}) {
13465
+ return new Promise((resolve2, reject) => {
13466
+ let child;
13467
+ try {
13468
+ child = spawnSeam(command, args, opts);
13469
+ } catch (e) {
13470
+ reject(e);
13471
+ return;
13472
+ }
13473
+ let stdoutBuf = "";
13474
+ let stderrBuf = "";
13475
+ if (child?.stdout && typeof child.stdout.on === "function") {
13476
+ child.stdout.on("data", (chunk) => {
13477
+ stdoutBuf += String(chunk);
13478
+ });
13479
+ }
13480
+ if (child?.stderr && typeof child.stderr.on === "function") {
13481
+ child.stderr.on("data", (chunk) => {
13482
+ stderrBuf += String(chunk);
13483
+ });
13484
+ }
13485
+ let settled = false;
13486
+ const settle = (fn, ...args2) => {
13487
+ if (settled)
13488
+ return;
13489
+ settled = true;
13490
+ fn(...args2);
13491
+ };
13492
+ child.on("error", (e) => settle(reject, e));
13493
+ child.on("exit", (code, signal) => {
13494
+ if (code === 0) {
13495
+ settle(resolve2, { stdout: stdoutBuf, stderr: stderrBuf });
13496
+ } else {
13497
+ const err = new Error(`${command} exited with code ${code}${signal ? ` (signal ${signal})` : ""}`);
13498
+ err.code = code;
13499
+ err.stdout = stdoutBuf;
13500
+ err.stderr = stderrBuf;
13501
+ settle(reject, err);
13502
+ }
13503
+ });
13504
+ });
13505
+ }
13506
+ function emitWriteProvenance(writeInfo, filePath, stderr) {
13507
+ if (!writeInfo.wrote)
13508
+ return;
13509
+ if (writeInfo.hadPrior) {
13510
+ stderr(`wrote ${filePath} (backed up prior to ${filePath}.bak)`);
13511
+ } else {
13512
+ stderr(`wrote ${filePath}`);
13513
+ }
13514
+ }
13515
+ async function phase2Provision({ classification, options, deps, seams, generators, phase2Events }) {
13516
+ const branch = classification.tag === "port-held-by-ours" ? "reload" : "bootstrap";
13517
+ const caddyfilePath = classification.paths.caddyfile;
13518
+ const plistPath = classification.paths.plist;
13519
+ const label = options.label;
13520
+ const adminBaseUrl = buildAdminBaseUrl(options.adminAddress);
13521
+ const adminPollAttempts = deps.adminPollAttempts ?? 30;
13522
+ const adminPollIntervalMs = deps.adminPollIntervalMs ?? 200;
13523
+ const adminPollTimeoutMs = deps.adminPollTimeoutMs ?? 2000;
13524
+ const events = phase2Events ?? [];
13525
+ const logEvent = (msg, extra) => events.push({ ts: nowIso(deps), msg, ...extra || {} });
13526
+ const rollbackCtx = {
13527
+ branch,
13528
+ label,
13529
+ adminBaseUrl,
13530
+ caddyfilePath,
13531
+ plistPath,
13532
+ caddyBinaryPath: classification.caddyBinaryPath,
13533
+ priorCaPem: null,
13534
+ priorCaFingerprint: null,
13535
+ writes: { caddyfile: null, plist: null },
13536
+ envDir: path15.dirname(classification.paths.stderrLog),
13537
+ stderrLogPath: classification.paths.stderrLog,
13538
+ uid: deps.uid,
13539
+ domain: classification.activeConfig.domain,
13540
+ events
13541
+ };
13542
+ const caddyfileContent = generators.caddyfile({
13543
+ domain: classification.activeConfig.domain,
13544
+ port: classification.activeConfig.port,
13545
+ adminAddress: options.adminAddress,
13546
+ listenHttp: options.listenHttp,
13547
+ listenHttps: options.listenHttps
13548
+ });
13549
+ if (branch === "reload") {
13550
+ try {
13551
+ const snap = await pollAdminForRoot({
13552
+ httpRequest: seams._httpRequest,
13553
+ adminBaseUrl,
13554
+ attempts: 1,
13555
+ intervalMs: 0,
13556
+ timeoutMs: adminPollTimeoutMs
13557
+ });
13558
+ rollbackCtx.priorCaPem = snap.pem;
13559
+ rollbackCtx.priorCaFingerprint = snap.fingerprint;
13560
+ logEvent(`captured prior-CA fingerprint ${snap.fingerprint}`);
13561
+ } catch (e) {
13562
+ logEvent(`pre-reload admin snapshot failed: ${e.message}`);
13563
+ }
13564
+ }
13565
+ try {
13566
+ rollbackCtx.writes.caddyfile = atomicWriteWithBackup({
13567
+ fs: deps.fs,
13568
+ path: caddyfilePath,
13569
+ content: caddyfileContent
13570
+ });
13571
+ emitWriteProvenance(rollbackCtx.writes.caddyfile, caddyfilePath, deps.stderr);
13572
+ } catch (e) {
13573
+ logEvent(`atomic write of Caddyfile failed: ${e.message}`);
13574
+ return { failed: true, trigger: "phase2-write-failure", error: e, rollbackCtx };
13575
+ }
13576
+ if (branch === "bootstrap") {
13577
+ const plistContent = generators.plist({
13578
+ label: options.label,
13579
+ caddyBinaryPath: classification.caddyBinaryPath,
13580
+ caddyfilePath,
13581
+ stdoutLogPath: classification.paths.stdoutLog,
13582
+ stderrLogPath: classification.paths.stderrLog
13583
+ });
13584
+ try {
13585
+ rollbackCtx.writes.plist = atomicWriteWithBackup({
13586
+ fs: deps.fs,
13587
+ path: plistPath,
13588
+ content: plistContent
13589
+ });
13590
+ emitWriteProvenance(rollbackCtx.writes.plist, plistPath, deps.stderr);
13591
+ } catch (e) {
13592
+ logEvent(`atomic write of plist failed: ${e.message}`);
13593
+ return { failed: true, trigger: "phase2-write-failure", error: e, rollbackCtx };
13594
+ }
13595
+ }
13596
+ if (branch === "reload") {
13597
+ if (rollbackCtx.writes.caddyfile.wrote) {
13598
+ try {
13599
+ await execFileAsync(seams._execFile, classification.caddyBinaryPath, [
13600
+ "reload",
13601
+ "--config",
13602
+ caddyfilePath,
13603
+ "--address",
13604
+ adminBaseUrl
13605
+ ]);
13606
+ deps.stderr(`reloaded ${label} against ${caddyfilePath} via caddy reload`);
13607
+ logEvent(`caddy reload ok`);
13608
+ } catch (e) {
13609
+ logEvent(`caddy reload failed: ${e.message}`);
13610
+ return { failed: true, trigger: "phase2-reload-failed", error: e, rollbackCtx };
13611
+ }
13612
+ }
13613
+ } else {
13614
+ try {
13615
+ await execFileAsync(seams._execFile, "launchctl", [
13616
+ "bootstrap",
13617
+ `gui/${deps.uid}`,
13618
+ plistPath
13619
+ ]);
13620
+ deps.stderr(`bootstrapped ${label} via launchctl`);
13621
+ logEvent(`launchctl bootstrap ok`);
13622
+ } catch (e) {
13623
+ logEvent(`launchctl bootstrap failed: ${e.message}`);
13624
+ return { failed: true, trigger: "phase2-bootstrap-failed", error: e, rollbackCtx };
13625
+ }
13626
+ }
13627
+ let currentSnap;
13628
+ try {
13629
+ currentSnap = await pollAdminForRoot({
13630
+ httpRequest: seams._httpRequest,
13631
+ adminBaseUrl,
13632
+ attempts: adminPollAttempts,
13633
+ intervalMs: adminPollIntervalMs,
13634
+ timeoutMs: adminPollTimeoutMs
13635
+ });
13636
+ logEvent(`admin poll succeeded; fingerprint ${currentSnap.fingerprint}`);
13637
+ } catch (e) {
13638
+ const tail = tailFile(deps.fs, classification.paths.stderrLog, 40);
13639
+ const combined = new Error(`admin poll exhausted at ${adminBaseUrl}/pki/ca/local after ${adminPollAttempts} attempts: ${e.message}` + (tail ? `
13640
+ --- ${classification.paths.stderrLog} tail ---
13641
+ ${tail}` : `
13642
+ (no caddy.err.log tail available)`));
13643
+ combined.cause = e;
13644
+ logEvent(`admin poll exhausted: ${e.message}`);
13645
+ return { failed: true, trigger: "phase2-admin-poll-exhausted", error: combined, rollbackCtx };
13646
+ }
13647
+ let fingerprints;
13648
+ try {
13649
+ fingerprints = await generators.readKeychainFingerprints();
13650
+ } catch (e) {
13651
+ logEvent(`keychain read failed post-provision: ${e.message}`);
13652
+ fingerprints = new Set;
13653
+ }
13654
+ const matched = fingerprints.has(currentSnap.fingerprint);
13655
+ return {
13656
+ failed: false,
13657
+ rollbackCtx,
13658
+ servedPem: currentSnap.pem,
13659
+ servedFingerprint: currentSnap.fingerprint,
13660
+ keychainFingerprints: fingerprints,
13661
+ matched
13662
+ };
13663
+ }
13664
+ async function phase3Trust({ options, deps, seams, generators, phase2Result }) {
13665
+ const rollbackCtx = phase2Result.rollbackCtx;
13666
+ const adminBaseUrl = rollbackCtx.adminBaseUrl;
13667
+ const caddyBinaryPath = rollbackCtx.caddyBinaryPath;
13668
+ const servedFingerprint = phase2Result.servedFingerprint;
13669
+ if (phase2Result.matched) {
13670
+ return { status: "trusted-fast-path", servedFingerprint };
13671
+ }
13672
+ if (options.skipTrust) {
13673
+ return {
13674
+ status: "skip-trust-exit-5",
13675
+ servedFingerprint,
13676
+ keychainFingerprints: phase2Result.keychainFingerprints
13677
+ };
13678
+ }
13679
+ try {
13680
+ await spawnAwaitExit(seams._spawn, DEFAULT_SUDO_PATH, ["-v"], { stdio: "inherit" });
13681
+ } catch (e) {
13682
+ return { status: "sudo-v-failed", error: e };
13683
+ }
13684
+ let trustErr = null;
13685
+ try {
13686
+ await spawnAwaitExit(seams._spawn, DEFAULT_SUDO_PATH, [
13687
+ caddyBinaryPath,
13688
+ "trust",
13689
+ "--address",
13690
+ adminBaseUrl
13691
+ ]);
13692
+ } catch (e) {
13693
+ trustErr = e;
13694
+ }
13695
+ let post;
13696
+ try {
13697
+ post = await generators.readKeychainFingerprints();
13698
+ } catch {
13699
+ post = new Set;
13700
+ }
13701
+ if (post.has(servedFingerprint)) {
13702
+ deps.stderr(`trusted local CA fingerprint ${servedFingerprint} to System keychain`);
13703
+ return { status: "trusted-newly", servedFingerprint };
13704
+ }
13705
+ return {
13706
+ status: "trust-failed-exit-5",
13707
+ servedFingerprint,
13708
+ keychainFingerprints: post,
13709
+ trustErr
13710
+ };
13711
+ }
13712
+ async function performRollback({ rollbackCtx, trigger, error, deps, seams }) {
13713
+ const events = rollbackCtx.events;
13714
+ const logEvent = (msg, extra) => events.push({ ts: nowIso(deps), msg, ...extra || {} });
13715
+ logEvent(`rollback triggered: ${trigger}: ${error?.message ?? "(no error message)"}`);
13716
+ for (const which of ["caddyfile", "plist"]) {
13717
+ const filePath = which === "caddyfile" ? rollbackCtx.caddyfilePath : rollbackCtx.plistPath;
13718
+ const writeInfo = rollbackCtx.writes[which];
13719
+ if (!writeInfo || !writeInfo.wrote)
13720
+ continue;
13721
+ if (writeInfo.hadPrior) {
13722
+ try {
13723
+ deps.fs.renameSync(`${filePath}.bak`, filePath);
13724
+ deps.stderr(`restored ${filePath} from ${filePath}.bak`);
13725
+ logEvent(`restored ${filePath} from ${filePath}.bak`);
13726
+ } catch (e) {
13727
+ logEvent(`restore failed for ${filePath}: ${e.message}`);
13728
+ }
13729
+ } else {
13730
+ try {
13731
+ deps.fs.unlinkSync(filePath);
13732
+ logEvent(`deleted freshly-written ${filePath} (no prior file)`);
13733
+ } catch (e) {
13734
+ logEvent(`delete failed for ${filePath}: ${e.message}`);
13735
+ }
13736
+ }
13737
+ }
13738
+ const adminBaseUrl = rollbackCtx.adminBaseUrl;
13739
+ if (rollbackCtx.branch === "reload") {
13740
+ try {
13741
+ const r = await execFileAsync(seams._execFile, rollbackCtx.caddyBinaryPath, [
13742
+ "reload",
13743
+ "--config",
13744
+ rollbackCtx.caddyfilePath,
13745
+ "--address",
13746
+ adminBaseUrl
13747
+ ]);
13748
+ deps.stderr(`reloaded prior config via caddy reload`);
13749
+ logEvent(`caddy reload (rollback) ok`, { stdout: r });
13750
+ } catch (e) {
13751
+ logEvent(`caddy reload (rollback) failed: ${e.message}`, { stderr: e.stderr });
13752
+ }
13753
+ } else {
13754
+ try {
13755
+ const r = await execFileAsync(seams._execFile, "launchctl", [
13756
+ "bootout",
13757
+ `gui/${rollbackCtx.uid}/${rollbackCtx.label}`
13758
+ ]);
13759
+ deps.stderr(`booted out ${rollbackCtx.label} via launchctl`);
13760
+ logEvent(`launchctl bootout ok`, { stdout: r });
13761
+ } catch (e) {
13762
+ logEvent(`launchctl bootout failed: ${e.message}`, { stderr: e.stderr });
13763
+ }
13764
+ }
13765
+ const adminPollAttempts = deps.adminPollAttempts ?? 30;
13766
+ const adminPollIntervalMs = deps.adminPollIntervalMs ?? 200;
13767
+ const adminPollTimeoutMs = deps.adminPollTimeoutMs ?? 2000;
13768
+ const httpsProbeTimeoutMs = deps.httpsProbeTimeoutMs ?? 2000;
13769
+ let verifyResult;
13770
+ if (rollbackCtx.branch === "reload") {
13771
+ let adminOk = false;
13772
+ let httpsOk = false;
13773
+ try {
13774
+ const snap = await pollAdminForRoot({
13775
+ httpRequest: seams._httpRequest,
13776
+ adminBaseUrl,
13777
+ attempts: adminPollAttempts,
13778
+ intervalMs: adminPollIntervalMs,
13779
+ timeoutMs: adminPollTimeoutMs
13780
+ });
13781
+ adminOk = rollbackCtx.priorCaFingerprint !== null && snap.fingerprint === rollbackCtx.priorCaFingerprint;
13782
+ logEvent(`rollback admin re-poll fingerprint ${snap.fingerprint} — match=${adminOk}`);
13783
+ } catch (e) {
13784
+ logEvent(`rollback admin re-poll failed: ${e.message}`);
13785
+ }
13786
+ if (rollbackCtx.priorCaPem) {
13787
+ try {
13788
+ const resp = await seams._httpRequest(`https://${rollbackCtx.domain}/health`, {
13789
+ method: "GET",
13790
+ ca: rollbackCtx.priorCaPem,
13791
+ timeoutMs: httpsProbeTimeoutMs
13792
+ });
13793
+ httpsOk = resp.status >= 200 && resp.status < 300;
13794
+ logEvent(`rollback https /health status ${resp.status} — ok=${httpsOk}`);
13795
+ } catch (e) {
13796
+ logEvent(`rollback https /health failed: ${e.message}`);
13797
+ }
13798
+ } else {
13799
+ logEvent(`rollback https /health skipped: no prior CA PEM captured`);
13800
+ }
13801
+ verifyResult = adminOk && httpsOk ? "confirmed" : "unconfirmed";
13802
+ if (verifyResult === "unconfirmed") {
13803
+ deps.stderr(`Rollback unconfirmed. Run manually: ` + `${rollbackCtx.caddyBinaryPath} reload --config ${rollbackCtx.caddyfilePath} --address ${adminBaseUrl}`);
13804
+ }
13805
+ } else {
13806
+ let unreachable = false;
13807
+ try {
13808
+ await seams._httpRequest(`${adminBaseUrl}/pki/ca/local`, {
13809
+ method: "GET",
13810
+ timeoutMs: adminPollTimeoutMs
13811
+ });
13812
+ logEvent(`admin endpoint still answering after bootout — rollback unconfirmed`);
13813
+ } catch (e) {
13814
+ const codeOrMsg = String(e?.code || e?.message || "");
13815
+ unreachable = /ECONNREFUSED|ECONNRESET|EAI_AGAIN|ENOTFOUND|EPIPE/.test(codeOrMsg);
13816
+ logEvent(`admin endpoint unreachable check: ${codeOrMsg} — unreachable=${unreachable}`);
13817
+ }
13818
+ verifyResult = unreachable ? "confirmed" : "unconfirmed";
13819
+ if (verifyResult === "unconfirmed") {
13820
+ deps.stderr(`Rollback unconfirmed. Run manually: launchctl bootout gui/${rollbackCtx.uid}/${rollbackCtx.label}`);
13821
+ }
13822
+ }
13823
+ const stamp = nowIso(deps).replace(/[:.]/g, "-");
13824
+ const logPath = path15.join(rollbackCtx.envDir, `caw-caddy-setup-${stamp}.log`);
13825
+ const logBody = renderRollbackLog({ rollbackCtx, trigger, error, events, verifyResult });
13826
+ try {
13827
+ deps.fs.writeFileSync(logPath, logBody);
13828
+ deps.stderr(`rollback diagnostic log: ${logPath}`);
13829
+ } catch (e) {
13830
+ deps.stderr(`WARNING: failed to write rollback log at ${logPath}: ${e.message}`);
13831
+ }
13832
+ return verifyResult === "confirmed" ? 2 : 3;
13833
+ }
13834
+ function nowIso(deps) {
13835
+ const nowFn = deps?.now ?? (() => new Date);
13836
+ const d = nowFn();
13837
+ return d.toISOString();
13838
+ }
13839
+ function renderRollbackLog({ rollbackCtx, trigger, error, events, verifyResult }) {
13840
+ const lines = [];
13841
+ lines.push(`# caw caddy setup — rollback diagnostic`);
13842
+ lines.push(`# trigger: ${trigger}`);
13843
+ lines.push(`# error: ${error?.message ?? "(none)"}`);
13844
+ if (error?.stack) {
13845
+ lines.push(`# stack:`);
13846
+ for (const s of String(error.stack).split(`
13847
+ `))
13848
+ lines.push(`# ${s}`);
13849
+ }
13850
+ lines.push(`# branch: ${rollbackCtx.branch}`);
13851
+ lines.push(`# label: ${rollbackCtx.label}`);
13852
+ lines.push(`# caddyfile: ${rollbackCtx.caddyfilePath}`);
13853
+ lines.push(`# plist: ${rollbackCtx.plistPath}`);
13854
+ lines.push(`# admin: ${rollbackCtx.adminBaseUrl}`);
13855
+ lines.push(`# domain: ${rollbackCtx.domain}`);
13856
+ lines.push(`# prior-CA fingerprint: ${rollbackCtx.priorCaFingerprint ?? "(none)"}`);
13857
+ lines.push(`# verify result: ${verifyResult}`);
13858
+ lines.push("");
13859
+ for (const ev of events) {
13860
+ lines.push(`[${ev.ts}] ${ev.msg}`);
13861
+ if (ev.stdout)
13862
+ lines.push(` stdout: ${String(ev.stdout).replace(/\n/g, `
13863
+ `)}`);
13864
+ if (ev.stderr)
13865
+ lines.push(` stderr: ${String(ev.stderr).replace(/\n/g, `
13866
+ `)}`);
13867
+ }
13868
+ return lines.join(`
13869
+ `) + `
13870
+ `;
13871
+ }
13872
+ function resolveEnvDir7(rawEnvDir, homeDir) {
13873
+ if (typeof rawEnvDir !== "string" || rawEnvDir.length === 0) {
13874
+ throw new TypeError("resolveEnvDir: rawEnvDir must be a non-empty string");
13875
+ }
13876
+ if (rawEnvDir.startsWith("~")) {
13877
+ if (typeof homeDir !== "string" || homeDir.length === 0) {
13878
+ throw new TypeError("resolveEnvDir: homeDir is required when rawEnvDir starts with ~");
13879
+ }
13880
+ return path15.resolve(path15.join(homeDir, rawEnvDir.slice(1)));
13881
+ }
13882
+ return path15.resolve(rawEnvDir);
13883
+ }
13884
+ function isPhase4Idempotent({ resolvedEnvDir, resolvedDomain, deps }) {
13885
+ const readCfg = deps.readConfig ?? readConfig;
13886
+ let activeConfig;
13887
+ try {
13888
+ activeConfig = readCfg(resolvedEnvDir);
13889
+ } catch {
13890
+ return false;
13891
+ }
13892
+ if (!activeConfig || typeof activeConfig !== "object")
13893
+ return false;
13894
+ if (activeConfig.caddy?.enabled !== true)
13895
+ return false;
13896
+ if (activeConfig.caddy?.domain !== resolvedDomain)
13897
+ return false;
13898
+ const hasPending = deps.hasPendingConfig ?? hasPendingConfig;
13899
+ if (!hasPending(resolvedEnvDir))
13900
+ return true;
13901
+ let pending;
13902
+ try {
13903
+ const readPending = deps.readPendingConfig ?? readPendingConfig;
13904
+ pending = readPending(resolvedEnvDir);
13905
+ } catch {
13906
+ return false;
13907
+ }
13908
+ if (!pending || typeof pending !== "object")
13909
+ return true;
13910
+ for (const k of Object.keys(pending)) {
13911
+ if (k === "caddy" || k.startsWith("caddy."))
13912
+ return false;
13913
+ }
13914
+ return true;
13915
+ }
13916
+ function reconcilePending(resolvedEnvDir, deps, logEvent) {
13917
+ const hasPending = deps.hasPendingConfig ?? hasPendingConfig;
13918
+ if (!hasPending(resolvedEnvDir))
13919
+ return { touched: false };
13920
+ const readPending = deps.readPendingConfig ?? readPendingConfig;
13921
+ const writePending = deps.writePendingConfig ?? writePendingConfig;
13922
+ const deletePending = deps.deletePendingConfig ?? deletePendingConfig;
13923
+ let pending;
13924
+ try {
13925
+ pending = readPending(resolvedEnvDir);
13926
+ } catch (e) {
13927
+ logEvent(`readPendingConfig failed: ${e.message}`);
13928
+ return { touched: false, error: e };
13929
+ }
13930
+ if (!pending || typeof pending !== "object") {
13931
+ return { touched: false };
13932
+ }
13933
+ const filtered = {};
13934
+ let removed = 0;
13935
+ for (const [k, v] of Object.entries(pending)) {
13936
+ if (k === "caddy" || k.startsWith("caddy.")) {
13937
+ removed++;
13938
+ continue;
13939
+ }
13940
+ filtered[k] = v;
13941
+ }
13942
+ if (removed === 0) {
13943
+ return { touched: false };
13944
+ }
13945
+ if (Object.keys(filtered).length === 0) {
13946
+ try {
13947
+ deletePending(resolvedEnvDir);
13948
+ logEvent("pending config deleted (only caddy.* keys were present)");
13949
+ return { touched: true, deleted: true, removedCount: removed };
13950
+ } catch (e) {
13951
+ logEvent(`deletePendingConfig failed: ${e.message}`);
13952
+ return { touched: false, error: e };
13953
+ }
13954
+ }
13955
+ try {
13956
+ writePending(resolvedEnvDir, filtered);
13957
+ logEvent(`pending config rewritten (removed ${removed} caddy.* key(s))`);
13958
+ return { touched: true, deleted: false, removedCount: removed };
13959
+ } catch (e) {
13960
+ logEvent(`writePendingConfig failed: ${e.message}`);
13961
+ return { touched: false, error: e };
13962
+ }
13963
+ }
13964
+ async function respawnServer(activeConfig, resolvedEnvDir, deps, logEvent) {
13965
+ const bootstrapFn = deps.bootstrap ?? bootstrap;
13966
+ const validateEnvFileFn = deps.validateEnvFile ?? validateEnvFile;
13967
+ const buildEnvNodeArgsFn = deps.buildEnvNodeArgs ?? buildEnvNodeArgs;
13968
+ const buildServerEnvVarsFn = deps.buildServerEnvVars ?? buildServerEnvVars;
13969
+ const rotateLogFn = deps.rotateLogIfNeeded ?? rotateLogIfNeeded;
13970
+ const resolveBinaryFn = deps.resolveServerBinary ?? resolve;
13971
+ const createPmFn = deps.createProcessManager ?? createProcessManager;
13972
+ const pollHealthFn = deps.pollHealth ?? pollHealth;
13973
+ try {
13974
+ bootstrapFn(resolvedEnvDir);
13975
+ } catch (e) {
13976
+ logEvent(`bootstrap failed: ${e.message}`);
13977
+ return { healthy: false, error: e };
13978
+ }
13979
+ const envCheck = validateEnvFileFn(resolvedEnvDir);
13980
+ if (!envCheck?.ok) {
13981
+ const err = new Error(envCheck?.message ?? "validateEnvFile: unknown failure");
13982
+ logEvent(`validateEnvFile failed: ${err.message}`);
13983
+ return { healthy: false, error: err };
13984
+ }
13985
+ const serverInfo = resolveBinaryFn();
13986
+ if (!serverInfo) {
13987
+ const err = new Error("caw-server not resolvable (install it with `npm install -g @kelceyp/caw-server@^1`)");
13988
+ logEvent("resolveServerBinary returned null");
13989
+ return { healthy: false, error: err };
13990
+ }
13991
+ try {
13992
+ rotateLogFn(resolvedEnvDir);
13993
+ } catch (e) {
13994
+ logEvent(`rotateLogIfNeeded warning: ${e.message}`);
13995
+ }
13996
+ const envVars = buildServerEnvVarsFn(activeConfig, resolvedEnvDir);
13997
+ const nodeArgs = buildEnvNodeArgsFn(resolvedEnvDir);
13998
+ const pm = createPmFn(activeConfig, resolvedEnvDir);
13999
+ let pmId;
14000
+ try {
14001
+ pmId = pm.start(serverInfo.mainJsPath, envVars, nodeArgs);
14002
+ } catch (e) {
14003
+ logEvent(`pm.start failed: ${e.message}`);
14004
+ return { healthy: false, error: e, envVars, nodeArgs };
14005
+ }
14006
+ logEvent(`server spawned (${pm.mode ?? "pid"}: ${pmId})`);
14007
+ const healthy = await pollHealthFn(activeConfig.port);
14008
+ if (!healthy) {
14009
+ return {
14010
+ healthy: false,
14011
+ error: new Error(`server did not become healthy on port ${activeConfig.port} within pollHealth window`),
14012
+ envVars,
14013
+ nodeArgs,
14014
+ pmId
14015
+ };
14016
+ }
14017
+ return { healthy: true, envVars, nodeArgs, pmId };
14018
+ }
14019
+ async function phase4Cutover({ classification, options, resolvedEnvDir, resolvedDomain, deps, events }) {
14020
+ const evts = events ?? [];
14021
+ const logEvent = (msg, extra) => evts.push({ ts: nowIso(deps), msg, ...extra || {} });
14022
+ if (isPhase4Idempotent({ resolvedEnvDir, resolvedDomain, deps })) {
14023
+ logEvent("phase 4 idempotency: active caddy.enabled=true, domain matches, pending clean");
14024
+ return { status: "skipped-idempotent", resolvedDomain, events: evts };
14025
+ }
14026
+ const readCfg = deps.readConfig ?? readConfig;
14027
+ let priorActiveConfig;
14028
+ try {
14029
+ priorActiveConfig = readCfg(resolvedEnvDir);
14030
+ } catch (e) {
14031
+ logEvent(`read prior active config failed: ${e.message}`);
14032
+ return { status: "read-config-failed", error: e, events: evts };
14033
+ }
14034
+ const executeStopFn = deps.executeStop ?? executeStop;
14035
+ const createPmFn = deps.createProcessManager ?? createProcessManager;
14036
+ const priorConfigMerged = { ...DEFAULTS, ...priorActiveConfig };
14037
+ const pmForStop = createPmFn(priorConfigMerged, resolvedEnvDir);
14038
+ let stopResult;
14039
+ try {
14040
+ stopResult = await executeStopFn(pmForStop, priorConfigMerged, true, async () => true, resolvedEnvDir);
14041
+ } catch (e) {
14042
+ logEvent(`executeStop threw: ${e.message}`);
14043
+ return { status: "stop-failed", error: e, priorActiveConfig, events: evts };
14044
+ }
14045
+ const stopOk = stopResult?.stopped === true || stopResult?.wasRunning === false;
14046
+ if (!stopOk) {
14047
+ const reason = stopResult?.error ?? "stop-declined-or-unkillable";
14048
+ const err = new Error(`executeStop failed (${reason})`);
14049
+ logEvent(`executeStop reported failure: ${reason}`);
14050
+ return { status: "stop-failed", error: err, priorActiveConfig, stopResult, events: evts };
14051
+ }
14052
+ logEvent(`executeStop ok (wasRunning=${stopResult?.wasRunning === true}, stopped=${stopResult?.stopped === true})`);
14053
+ const pendingResult = reconcilePending(resolvedEnvDir, deps, logEvent);
14054
+ const writeConfigFn = deps.writeConfig ?? writeConfig;
14055
+ const nextActiveConfig = {
14056
+ ...priorActiveConfig,
14057
+ caddy: { enabled: true, domain: resolvedDomain }
14058
+ };
14059
+ try {
14060
+ writeConfigFn(resolvedEnvDir, nextActiveConfig);
14061
+ logEvent(`active config updated: caddy.enabled=true caddy.domain=${resolvedDomain}`);
14062
+ } catch (e) {
14063
+ logEvent(`writeConfig failed: ${e.message}`);
14064
+ return { status: "active-write-failed", error: e, priorActiveConfig, pendingResult, events: evts };
14065
+ }
14066
+ const nextConfigMerged = { ...DEFAULTS, ...nextActiveConfig };
14067
+ const respawnResult = await respawnServer(nextConfigMerged, resolvedEnvDir, deps, logEvent);
14068
+ if (respawnResult.healthy) {
14069
+ logEvent(`pollHealth green on new active config; cutover complete`);
14070
+ return {
14071
+ status: "cutover-ok",
14072
+ priorActiveConfig,
14073
+ newActiveConfig: nextActiveConfig,
14074
+ respawnResult,
14075
+ pendingResult,
14076
+ events: evts
14077
+ };
14078
+ }
14079
+ logEvent(`pollHealth failed on new active config; attempting reverse restart on prior config`);
14080
+ try {
14081
+ writeConfigFn(resolvedEnvDir, priorActiveConfig);
14082
+ logEvent("restored prior active config on disk for recovery");
14083
+ } catch (e) {
14084
+ logEvent(`restore prior config write failed: ${e.message}`);
14085
+ }
14086
+ const priorMerged = { ...DEFAULTS, ...priorActiveConfig };
14087
+ const recoveryResult = await respawnServer(priorMerged, resolvedEnvDir, deps, logEvent);
14088
+ if (recoveryResult.healthy) {
14089
+ logEvent(`reverse restart pollHealth green; machine restored to prior config`);
14090
+ return {
14091
+ status: "recovered",
14092
+ priorActiveConfig,
14093
+ newActiveConfig: nextActiveConfig,
14094
+ originalError: respawnResult.error,
14095
+ recoveryResult,
14096
+ pendingResult,
14097
+ events: evts
14098
+ };
14099
+ }
14100
+ return {
14101
+ status: "recovery-failed",
14102
+ priorActiveConfig,
14103
+ newActiveConfig: nextActiveConfig,
14104
+ originalError: respawnResult.error,
14105
+ recoveryError: recoveryResult.error,
14106
+ recoveryResult,
14107
+ pendingResult,
14108
+ events: evts
14109
+ };
14110
+ }
14111
+ function renderRecoveryLog({ resolvedEnvDir, resolvedDomain, phase4Result, serverLogPath }) {
14112
+ const lines = [];
14113
+ lines.push("# caw caddy setup — recovery diagnostic");
14114
+ lines.push(`# outcome: ${phase4Result.status}`);
14115
+ lines.push(`# envDir: ${resolvedEnvDir}`);
14116
+ lines.push(`# domain: ${resolvedDomain}`);
14117
+ lines.push(`# server log: ${serverLogPath}`);
14118
+ lines.push(`# original cutover error: ${phase4Result.originalError?.message ?? "(none)"}`);
14119
+ if (phase4Result.originalError?.stack) {
14120
+ lines.push("# original stack:");
14121
+ for (const s of String(phase4Result.originalError.stack).split(`
14122
+ `))
14123
+ lines.push(`# ${s}`);
14124
+ }
14125
+ if (phase4Result.recoveryError) {
14126
+ lines.push(`# recovery error: ${phase4Result.recoveryError.message}`);
14127
+ if (phase4Result.recoveryError.stack) {
14128
+ lines.push("# recovery stack:");
14129
+ for (const s of String(phase4Result.recoveryError.stack).split(`
14130
+ `))
14131
+ lines.push(`# ${s}`);
14132
+ }
14133
+ }
14134
+ lines.push("");
14135
+ for (const ev of phase4Result.events ?? []) {
14136
+ lines.push(`[${ev.ts}] ${ev.msg}`);
14137
+ if (ev.stdout)
14138
+ lines.push(` stdout: ${String(ev.stdout).replace(/\n/g, `
14139
+ `)}`);
14140
+ if (ev.stderr)
14141
+ lines.push(` stderr: ${String(ev.stderr).replace(/\n/g, `
14142
+ `)}`);
14143
+ }
14144
+ return lines.join(`
14145
+ `) + `
14146
+ `;
14147
+ }
14148
+ function writeRecoveryDiagnostic({ resolvedEnvDir, resolvedDomain, phase4Result, serverLogPath, deps }) {
14149
+ const stamp = nowIso(deps).replace(/[:.]/g, "-");
14150
+ const logPath = path15.join(resolvedEnvDir, `caw-caddy-setup-${stamp}.log`);
14151
+ const body = renderRecoveryLog({ resolvedEnvDir, resolvedDomain, phase4Result, serverLogPath });
14152
+ const fsDep = deps.fs ?? fs15;
14153
+ try {
14154
+ fsDep.writeFileSync(logPath, body);
14155
+ return { logPath, error: null };
14156
+ } catch (e) {
14157
+ return { logPath, error: e };
14158
+ }
14159
+ }
14160
+ function createSetupHandler(deps = {}) {
14161
+ const runPreflight = deps.runPreflight ?? runInstallPreflight;
14162
+ const onPreflightFailure = deps.onPreflightFailure ?? emitPreflightFailure;
14163
+ const _execFile = deps.execFile ?? PRODUCTION_SEAMS.execFile;
14164
+ const _spawn = deps.spawn ?? PRODUCTION_SEAMS.spawn;
14165
+ const _httpRequest = deps.httpRequest ?? PRODUCTION_SEAMS.httpRequest;
14166
+ const keychainPath = deps.keychainPath ?? DEFAULT_KEYCHAIN_PATH;
14167
+ const generators = Object.freeze({
14168
+ caddyfile: deps.generateCaddyfile ?? generateCaddyfile,
14169
+ plist: deps.generatePlist ?? generatePlist,
14170
+ readKeychainFingerprints: deps.readKeychainFingerprints ?? ((overrides = {}) => readKeychainFingerprints({
14171
+ execFile: _execFile,
14172
+ keychainPath,
14173
+ ...overrides
14174
+ }))
14175
+ });
14176
+ return async function setupHandler(ctx) {
14177
+ const preflight = runPreflight({ requireNotRoot: true });
14178
+ if (!preflight.ok) {
14179
+ onPreflightFailure(preflight);
14180
+ return { preflight };
14181
+ }
14182
+ const params = ctx?.params ?? {};
14183
+ const options = Object.freeze({
14184
+ envDir: params["env-dir"],
14185
+ skipTrust: params["skip-trust"],
14186
+ dryRun: params["dry-run"],
14187
+ label: params.label,
14188
+ listenHttp: params["listen-http"],
14189
+ listenHttps: params["listen-https"],
14190
+ adminAddress: params["admin-address"]
14191
+ });
14192
+ const phase1Deps = {
14193
+ _execFile,
14194
+ fs: deps.fs ?? fs15,
14195
+ hasTty: deps.hasTty ?? Boolean(process.stdin?.isTTY),
14196
+ uid: deps.uid ?? (process.getuid ? process.getuid() : 0),
14197
+ homeDir: deps.homeDir ?? os8.homedir(),
14198
+ readConfig: deps.readConfig ?? readConfigWithDefaults,
14199
+ generators,
14200
+ paths: deps.paths ?? {}
14201
+ };
14202
+ const out = deps.stdout ?? ((s) => console.log(s));
14203
+ const err = deps.stderr ?? ((s) => console.error(s));
14204
+ const exit = deps.exit ?? ((code) => process.exit(code));
14205
+ out("→ Phase 1: Validate");
14206
+ const classification = await classifyPhase1({ options, deps: phase1Deps });
14207
+ if (classification.exitCode === 1) {
14208
+ out(`← Phase 1: Validate (aborted)`);
14209
+ err(classification.message);
14210
+ exit(1);
14211
+ return { preflight, options, classification };
14212
+ }
14213
+ out(`← Phase 1: Validate (pass)`);
14214
+ const seams = Object.freeze({ _execFile, _spawn, _httpRequest });
14215
+ if (options.dryRun) {
14216
+ out(renderPlanPreview({ classification, options, generators }));
14217
+ exit(0);
14218
+ return { preflight, options, classification, seams, keychainPath, generators };
14219
+ }
14220
+ out(renderContinueSummary({ classification }));
14221
+ out("→ Phase 2: Provision");
14222
+ const phase2Deps = {
14223
+ fs: deps.fs ?? fs15,
14224
+ stderr: err,
14225
+ uid: phase1Deps.uid,
14226
+ adminPollAttempts: deps.adminPollAttempts,
14227
+ adminPollIntervalMs: deps.adminPollIntervalMs,
14228
+ adminPollTimeoutMs: deps.adminPollTimeoutMs,
14229
+ now: deps.now
14230
+ };
14231
+ const phase2Result = await phase2Provision({
14232
+ classification,
14233
+ options,
14234
+ deps: phase2Deps,
14235
+ seams,
14236
+ generators
14237
+ });
14238
+ if (phase2Result.failed) {
14239
+ out(`← Phase 2: Provision (rolled-back)`);
14240
+ const rollbackDeps = {
14241
+ ...phase2Deps,
14242
+ httpsProbeTimeoutMs: deps.httpsProbeTimeoutMs
14243
+ };
14244
+ const rollbackExit = await performRollback({
14245
+ rollbackCtx: phase2Result.rollbackCtx,
14246
+ trigger: phase2Result.trigger,
14247
+ error: phase2Result.error,
14248
+ deps: rollbackDeps,
14249
+ seams
14250
+ });
14251
+ err(phase2Result.error.message);
14252
+ exit(rollbackExit);
14253
+ return { preflight, options, classification, seams, keychainPath, generators, phase2Result, rollbackExit };
14254
+ }
14255
+ out(`← Phase 2: Provision (provisioned)`);
14256
+ out("→ Phase 3: Trust");
14257
+ const phase3Result = await phase3Trust({
14258
+ options,
14259
+ deps: { stderr: err },
14260
+ seams,
14261
+ generators,
14262
+ phase2Result
14263
+ });
14264
+ const resolvedEnvDir = resolveEnvDir7(options.envDir, phase1Deps.homeDir);
14265
+ const resolvedDomain = classification.activeConfig.domain;
14266
+ const phase4Deps = {
14267
+ fs: deps.fs ?? fs15,
14268
+ now: deps.now,
14269
+ readConfig: deps.readConfigRaw ?? readConfig,
14270
+ writeConfig: deps.writeConfig ?? writeConfig,
14271
+ hasPendingConfig: deps.hasPendingConfig ?? hasPendingConfig,
14272
+ readPendingConfig: deps.readPendingConfig ?? readPendingConfig,
14273
+ writePendingConfig: deps.writePendingConfig ?? writePendingConfig,
14274
+ deletePendingConfig: deps.deletePendingConfig ?? deletePendingConfig,
14275
+ createProcessManager: deps.createProcessManager ?? createProcessManager,
14276
+ executeStop: deps.executeStop ?? executeStop,
14277
+ resolveServerBinary: deps.resolveServerBinary ?? resolve,
14278
+ bootstrap: deps.bootstrap ?? bootstrap,
14279
+ validateEnvFile: deps.validateEnvFile ?? validateEnvFile,
14280
+ buildEnvNodeArgs: deps.buildEnvNodeArgs ?? buildEnvNodeArgs,
14281
+ buildServerEnvVars: deps.buildServerEnvVars ?? buildServerEnvVars,
14282
+ pollHealth: deps.pollHealth ?? pollHealth,
14283
+ rotateLogIfNeeded: deps.rotateLogIfNeeded ?? rotateLogIfNeeded
14284
+ };
14285
+ switch (phase3Result.status) {
14286
+ case "trusted-fast-path":
14287
+ out(`← Phase 3: Trust (already-trusted)`);
14288
+ out(`Benign window: https://${resolvedDomain} works now while ` + `\`caw status\` still shows Caddy disabled until the active-config write in Phase 4; ` + `the exit-0 completion line below closes this window.`);
14289
+ return await runPhase4({
14290
+ preflight,
14291
+ options,
14292
+ classification,
14293
+ seams,
14294
+ keychainPath,
14295
+ generators,
14296
+ phase2Result,
14297
+ phase3Result,
14298
+ resolvedEnvDir,
14299
+ resolvedDomain,
14300
+ phase4Deps,
14301
+ out,
14302
+ err,
14303
+ exit,
14304
+ deps
14305
+ });
14306
+ case "trusted-newly":
14307
+ out(`← Phase 3: Trust (trusted)`);
14308
+ out(`Benign window: https://${resolvedDomain} works now while ` + `\`caw status\` still shows Caddy disabled until the active-config write in Phase 4; ` + `the exit-0 completion line below closes this window.`);
14309
+ return await runPhase4({
14310
+ preflight,
14311
+ options,
14312
+ classification,
14313
+ seams,
14314
+ keychainPath,
14315
+ generators,
14316
+ phase2Result,
14317
+ phase3Result,
14318
+ resolvedEnvDir,
14319
+ resolvedDomain,
14320
+ phase4Deps,
14321
+ out,
14322
+ err,
14323
+ exit,
14324
+ deps
14325
+ });
14326
+ case "skip-trust-exit-5": {
14327
+ out(`← Phase 3: Trust (aborted)`);
14328
+ const fps = [...phase3Result.keychainFingerprints];
14329
+ err(`--skip-trust set and served fingerprint ${phase3Result.servedFingerprint} was not in the System keychain — ` + `machine is provisioned-but-untrusted; browsers will hit a certificate interstitial. ` + `Re-run without --skip-trust, or run manually: ` + `sudo ${classification.caddyBinaryPath} trust --address ${phase2Result.rollbackCtx.adminBaseUrl}` + ` (keychain currently has: [${fps.join(", ") || "none"}])`);
14330
+ exit(5);
14331
+ return { preflight, options, classification, seams, keychainPath, generators, phase2Result, phase3Result };
14332
+ }
14333
+ case "trust-failed-exit-5": {
14334
+ out(`← Phase 3: Trust (aborted)`);
14335
+ const fps = [...phase3Result.keychainFingerprints];
14336
+ const trustStderr = phase3Result.trustErr?.stderr ? `
14337
+ --- sudo caddy trust stderr ---
14338
+ ${phase3Result.trustErr.stderr}` : "";
14339
+ err(`Phase 3 (Trust) failed post-compare (M6). ` + `Served fingerprint: ${phase3Result.servedFingerprint}. ` + `Keychain fingerprints: [${fps.join(", ") || "none"}]. ` + `sudo caddy trust ${phase3Result.trustErr ? `exited: ${phase3Result.trustErr.message}` : "exited 0"}. ` + `Re-run manually: sudo ${classification.caddyBinaryPath} trust --address ${phase2Result.rollbackCtx.adminBaseUrl}` + trustStderr);
14340
+ exit(5);
14341
+ return { preflight, options, classification, seams, keychainPath, generators, phase2Result, phase3Result };
14342
+ }
14343
+ case "sudo-v-failed": {
14344
+ out(`← Phase 3: Trust (rolled-back)`);
14345
+ const rollbackDeps = {
14346
+ ...phase2Deps,
14347
+ httpsProbeTimeoutMs: deps.httpsProbeTimeoutMs
14348
+ };
14349
+ const rollbackExit = await performRollback({
14350
+ rollbackCtx: phase2Result.rollbackCtx,
14351
+ trigger: "phase3-sudo-v-failed",
14352
+ error: phase3Result.error,
14353
+ deps: rollbackDeps,
14354
+ seams
14355
+ });
14356
+ err(`Phase 3 (Trust) — sudo -v aborted: ${phase3Result.error?.message ?? "(no error)"}`);
14357
+ exit(rollbackExit);
14358
+ return { preflight, options, classification, seams, keychainPath, generators, phase2Result, phase3Result, rollbackExit };
14359
+ }
14360
+ default:
14361
+ out(`← Phase 3: Trust (aborted)`);
14362
+ err(`Phase 3 returned unrecognised status: ${phase3Result.status}`);
14363
+ exit(1);
14364
+ return { preflight, options, classification, seams, keychainPath, generators, phase2Result, phase3Result };
14365
+ }
14366
+ };
14367
+ }
14368
+ async function runPhase4({ preflight, options, classification, seams, keychainPath, generators, phase2Result, phase3Result, resolvedEnvDir, resolvedDomain, phase4Deps, out, err, exit, deps }) {
14369
+ out("→ Phase 4: Cutover");
14370
+ const phase4Result = await phase4Cutover({
14371
+ classification,
14372
+ options,
14373
+ resolvedEnvDir,
14374
+ resolvedDomain,
14375
+ deps: phase4Deps
14376
+ });
14377
+ const returnBase = { preflight, options, classification, seams, keychainPath, generators, phase2Result, phase3Result, phase4Result, resolvedEnvDir, resolvedDomain };
14378
+ switch (phase4Result.status) {
14379
+ case "skipped-idempotent":
14380
+ out(`← Phase 4: Cutover (skipped-idempotent)`);
14381
+ out(`Caddy setup is already in effect (nothing to cut over); no restart performed.`);
14382
+ exit(0);
14383
+ return returnBase;
14384
+ case "cutover-ok":
14385
+ out(`← Phase 4: Cutover (cutover-ok)`);
14386
+ out(`caw caddy setup complete: machine provisioned and healthy on ` + `https://${resolvedDomain} (upstream port ${phase4Result.newActiveConfig.port ?? classification.activeConfig.port}). ` + `Browser can reach CAW over HTTPS.`);
14387
+ exit(0);
14388
+ return returnBase;
14389
+ case "stop-failed":
14390
+ out(`← Phase 4: Cutover (aborted)`);
14391
+ err(`Phase 4 (Cutover) aborted before any mutation: executeStop failed ` + `(${phase4Result.error?.message ?? "(no message)"}). CAW is still up on the prior config; ` + `no pending reconcile and no active-config write attempted.`);
14392
+ exit(1);
14393
+ return returnBase;
14394
+ case "read-config-failed":
14395
+ case "active-write-failed":
14396
+ out(`← Phase 4: Cutover (aborted)`);
14397
+ err(`Phase 4 (Cutover) failed: ${phase4Result.error?.message ?? "(no message)"}. ` + `Re-run \`caw caddy setup\` after resolving the underlying issue.`);
14398
+ exit(1);
14399
+ return returnBase;
14400
+ case "recovered": {
14401
+ out(`← Phase 4: Cutover (recovered)`);
14402
+ const serverLogPath = path15.join(resolvedEnvDir, "server.log");
14403
+ const diag = writeRecoveryDiagnostic({ resolvedEnvDir, resolvedDomain, phase4Result, serverLogPath, deps: phase4Deps });
14404
+ err(`Phase 4 (Cutover) failed on new config: ${phase4Result.originalError?.message ?? "(no message)"}. ` + `Reverse restart on prior config is /health-green — machine is on the PRIOR config. ` + `Recovery diagnostic: ${diag.logPath}${diag.error ? ` (write warning: ${diag.error.message})` : ""}`);
14405
+ exit(1);
14406
+ return returnBase;
14407
+ }
14408
+ case "recovery-failed": {
14409
+ out(`← Phase 4: Cutover (recovery-failed)`);
14410
+ const serverLogPath = path15.join(resolvedEnvDir, "server.log");
14411
+ const diag = writeRecoveryDiagnostic({ resolvedEnvDir, resolvedDomain, phase4Result, serverLogPath, deps: phase4Deps });
14412
+ err(`Phase 4 (Cutover) failed on new config: ${phase4Result.originalError?.message ?? "(no message)"}
14413
+ ` + `Reverse restart on prior config ALSO failed: ${phase4Result.recoveryError?.message ?? "(no message)"}
14414
+ ` + `Server log: ${serverLogPath}
14415
+ ` + `Run manually to bring CAW back up: caw start --env-dir ${resolvedEnvDir}
14416
+ ` + `Recovery diagnostic: ${diag.logPath}${diag.error ? ` (write warning: ${diag.error.message})` : ""}`);
14417
+ exit(4);
14418
+ return returnBase;
14419
+ }
14420
+ default:
14421
+ out(`← Phase 4: Cutover (aborted)`);
14422
+ err(`Phase 4 returned unrecognised status: ${phase4Result.status}`);
14423
+ exit(1);
14424
+ return returnBase;
14425
+ }
14426
+ }
14427
+ function createSetupCommand(deps = {}) {
14428
+ const handler = createSetupHandler(deps);
14429
+ return createCommand("setup").summary("Configure Caddy to reverse-proxy HTTPS to the CAW server").param((p) => p.name("env-dir").type("string").flag("env-dir").default(DEFAULT_ENV_DIR)).param((p) => p.name("skip-trust").type("boolean").flag("skip-trust").default(false)).param((p) => p.name("dry-run").type("boolean").flag("dry-run").default(false)).param((p) => p.name("label").type("string").flag("label").default(DEFAULT_LABEL)).param((p) => p.name("listen-http").type("number").flag("listen-http").default(DEFAULT_LISTEN_HTTP)).param((p) => p.name("listen-https").type("number").flag("listen-https").default(DEFAULT_LISTEN_HTTPS)).param((p) => p.name("admin-address").type("string").flag("admin-address").default(DEFAULT_ADMIN_ADDRESS)).run(handler).onError({ exitCode: 1 }).build();
14430
+ }
14431
+ var setupCommand = createSetupCommand();
14432
+ var caddyGroup = createCommandGroup("caddy").summary("Manage Caddy HTTPS reverse-proxy for CAW").command(setupCommand).build();
14433
+ var caddy_default = caddyGroup;
14434
+
12643
14435
  // src/main.js
12644
14436
  var [major] = process.versions.node.split(".").map(Number);
12645
14437
  if (major < 24) {
@@ -12666,5 +14458,5 @@ var serverInfo = resolve();
12666
14458
  var serverVersion = serverInfo ? serverInfo.version : "not installed";
12667
14459
  var versionString = `Launcher: ${LAUNCHER_VERSION}
12668
14460
  Server: ${serverVersion}`;
12669
- var app = create().name("caw").version(versionString).command(start_default.create()).command(stop_default.create()).command(status_default.create()).command(logs_default.create()).command(upgrade_default.create()).command(restart_default.create());
14461
+ var app = create().name("caw").version(versionString).command(start_default.create()).command(stop_default.create()).command(status_default.create()).command(logs_default.create()).command(upgrade_default.create()).command(restart_default.create()).group(caddy_default);
12670
14462
  await app.run(process.argv.slice(2));