@fabioplunser/epd 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -434,7 +434,8 @@ var TOP_LEVEL_KEYS = [
434
434
  "labels",
435
435
  "drain",
436
436
  "stop_timeout",
437
- "docker_options"
437
+ "docker_options",
438
+ "cloudflare"
438
439
  ];
439
440
  function normalize(raw, configPath, root, destination) {
440
441
  checkKeys(raw, TOP_LEVEL_KEYS, "epd.yml");
@@ -664,6 +665,24 @@ function normalize(raw, configPath, root, destination) {
664
665
  const strategy = asString(raw.strategy, "epd.yml.strategy", "rolling");
665
666
  if (strategy !== "rolling" && strategy !== "parallel")
666
667
  fail("epd.yml.strategy", 'expected "rolling" or "parallel"');
668
+ let cloudflare = undefined;
669
+ if (raw.cloudflare !== undefined && raw.cloudflare !== false) {
670
+ if (raw.cloudflare !== true && (typeof raw.cloudflare !== "object" || Array.isArray(raw.cloudflare))) {
671
+ fail("epd.yml.cloudflare", "expected a mapping or boolean");
672
+ }
673
+ const cfRaw = raw.cloudflare === true ? {} : raw.cloudflare;
674
+ checkKeys(cfRaw, ["enabled", "api_token", "zone_id", "proxied", "ttl", "auto_sync", "domains"], "epd.yml.cloudflare");
675
+ const apiToken = cfRaw.api_token ? asString(cfRaw.api_token, "epd.yml.cloudflare.api_token") : process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || "";
676
+ cloudflare = {
677
+ enabled: asBool(cfRaw.enabled, "epd.yml.cloudflare.enabled", true),
678
+ apiToken,
679
+ zoneId: cfRaw.zone_id ? asString(cfRaw.zone_id, "epd.yml.cloudflare.zone_id") : process.env.CLOUDFLARE_ZONE_ID || undefined,
680
+ proxied: asBool(cfRaw.proxied, "epd.yml.cloudflare.proxied", true),
681
+ ttl: asNumber(cfRaw.ttl, "epd.yml.cloudflare.ttl", 1),
682
+ autoSync: asBool(cfRaw.auto_sync, "epd.yml.cloudflare.auto_sync", true),
683
+ domains: cfRaw.domains ? asList(cfRaw.domains, "epd.yml.cloudflare.domains") : undefined
684
+ };
685
+ }
667
686
  const cfg = {
668
687
  name,
669
688
  mode,
@@ -703,6 +722,7 @@ function normalize(raw, configPath, root, destination) {
703
722
  onFailure: hooksRaw.on_failure ? asString(hooksRaw.on_failure, "epd.yml.hooks.on_failure") : undefined
704
723
  },
705
724
  process: processCfg,
725
+ cloudflare,
706
726
  portBase: asNumber(raw.port_base, "epd.yml.port_base", 20000 + hash32(name) % 117 * 256),
707
727
  strategy,
708
728
  keepReleases: asNumber(raw.keep_releases, "epd.yml.keep_releases", 5),
@@ -1484,9 +1504,9 @@ function declFor(cfg) {
1484
1504
  extra: cfg.proxy.extra
1485
1505
  };
1486
1506
  }
1487
- async function readDecls(host2, cfg) {
1507
+ async function readDecls(host, cfg) {
1488
1508
  const dir = paths(cfg).proxyAppsDir;
1489
- const out = await host2.capture(`for f in ${shq(dir)}/*.json; do [ -f "$f" ] || continue; echo "###EPD_FILE"; cat "$f"; done`, { allowFailure: true });
1509
+ const out = await host.capture(`for f in ${shq(dir)}/*.json; do [ -f "$f" ] || continue; echo "###EPD_FILE"; cat "$f"; done`, { allowFailure: true });
1490
1510
  const decls = [];
1491
1511
  for (const chunk of out.split("###EPD_FILE")) {
1492
1512
  const t = chunk.trim();
@@ -1495,7 +1515,7 @@ async function readDecls(host2, cfg) {
1495
1515
  try {
1496
1516
  decls.push(JSON.parse(t));
1497
1517
  } catch {
1498
- log.warn(`${host2.name}: ignoring an unreadable proxy declaration`);
1518
+ log.warn(`${host.name}: ignoring an unreadable proxy declaration`);
1499
1519
  }
1500
1520
  }
1501
1521
  return decls;
@@ -1647,18 +1667,18 @@ function dynamicConfig(cfg, endpoints, accessories = []) {
1647
1667
  middlewares[key] = {
1648
1668
  redirectRegex: { regex: "^https?://[^/]+(.*)", replacement: `${route.redirect.to.replace(/\/$/, "")}$1`, permanent: route.redirect.permanent }
1649
1669
  };
1650
- const svcKey2 = `${owner.key}-${route.port}`;
1651
- ensureService(services, svcKey2, owner.urlsFor(route.port), route, owner.health);
1670
+ const svcKey = `${owner.key}-${route.port}`;
1671
+ ensureService(services, svcKey, owner.urlsFor(route.port), route, owner.health);
1652
1672
  routers[routerKey] = {
1653
1673
  rule,
1654
1674
  entryPoints: [entrypoint],
1655
1675
  middlewares: [...mws, key],
1656
- service: svcKey2,
1676
+ service: svcKey,
1657
1677
  ...route.ssl ? { tls: tlsFor(route) } : {},
1658
1678
  ...route.priority !== undefined ? { priority: route.priority } : {}
1659
1679
  };
1660
1680
  if (route.ssl && cfg.proxy.httpsRedirect) {
1661
- routers[`${routerKey}-http`] = { rule, entryPoints: ["web"], middlewares: [key], service: svcKey2 };
1681
+ routers[`${routerKey}-http`] = { rule, entryPoints: ["web"], middlewares: [key], service: svcKey };
1662
1682
  }
1663
1683
  return;
1664
1684
  }
@@ -1743,18 +1763,18 @@ function containerSpec(d, cfg, staticHash) {
1743
1763
  args.push(d.image);
1744
1764
  return args;
1745
1765
  }
1746
- async function ensureProxy(host2, cfg, opts = {}) {
1766
+ async function ensureProxy(host, cfg, opts = {}) {
1747
1767
  if (!cfg.proxy.enabled)
1748
1768
  return;
1749
1769
  const p = paths(cfg);
1750
1770
  const containerMode = cfg.mode === "docker";
1751
- await host2.writeFile(p.proxyApp, JSON.stringify(declFor(cfg), null, 2), "644");
1752
- const merged = mergeDecls(await readDecls(host2, cfg));
1771
+ await host.writeFile(p.proxyApp, JSON.stringify(declFor(cfg), null, 2), "644");
1772
+ const merged = mergeDecls(await readDecls(host, cfg));
1753
1773
  if (!Object.keys(merged.entrypoints).length)
1754
1774
  merged.entrypoints = cfg.proxy.entrypoints;
1755
1775
  const where = containerMode ? CONTAINER_PATHS : { dynamicDir: p.proxyDynamicDir, acmeFile: `${p.acmeDir}/acme.json` };
1756
1776
  const staticJson = JSON.stringify(staticConfig(merged, where), null, 2);
1757
- await host2.writeFile(p.proxyStatic, staticJson, "644");
1777
+ await host.writeFile(p.proxyStatic, staticJson, "644");
1758
1778
  if (merged.dnsEnv.length) {
1759
1779
  const lines = merged.dnsEnv.map((name) => {
1760
1780
  const value = opts.secrets?.[name];
@@ -1763,7 +1783,7 @@ async function ensureProxy(host2, cfg, opts = {}) {
1763
1783
  }
1764
1784
  return `${name}=${value}`;
1765
1785
  });
1766
- await host2.writeFile(p.proxyEnv, lines.join(`
1786
+ await host.writeFile(p.proxyEnv, lines.join(`
1767
1787
  `), "600");
1768
1788
  }
1769
1789
  if (merged.dashboard && merged.dashboardHost) {
@@ -1779,23 +1799,23 @@ async function ensureProxy(host2, cfg, opts = {}) {
1779
1799
  }
1780
1800
  }
1781
1801
  };
1782
- await host2.writeFile(`${p.proxyDynamicDir}/_dashboard.yml`, JSON.stringify(dash, null, 2), "644");
1802
+ await host.writeFile(`${p.proxyDynamicDir}/_dashboard.yml`, JSON.stringify(dash, null, 2), "644");
1783
1803
  }
1784
1804
  const specHash = hash32(staticJson + JSON.stringify(merged)).toString(36);
1785
1805
  if (containerMode)
1786
- await ensureProxyContainer(host2, cfg, merged, specHash, opts);
1806
+ await ensureProxyContainer(host, cfg, merged, specHash, opts);
1787
1807
  else
1788
- await ensureProxyProcess(host2, cfg, merged, specHash, opts);
1808
+ await ensureProxyProcess(host, cfg, merged, specHash, opts);
1789
1809
  }
1790
- async function ensureProxyContainer(host2, cfg, merged, specHash, opts) {
1810
+ async function ensureProxyContainer(host, cfg, merged, specHash, opts) {
1791
1811
  const spec = containerSpec(merged, cfg, specHash);
1792
- const state = await host2.capture(`docker inspect -f '{{.State.Running}} {{index .Config.Labels "epd.spec"}}' ${PROXY_CONTAINER} 2>/dev/null || echo "missing"`);
1812
+ const state = await host.capture(`docker inspect -f '{{.State.Running}} {{index .Config.Labels "epd.spec"}}' ${PROXY_CONTAINER} 2>/dev/null || echo "missing"`);
1793
1813
  const [running, currentHash] = state.split(/\s+/);
1794
1814
  if (!opts.force && running === "true" && currentHash === specHash) {
1795
- log.host(host2.name, "proxy is up to date");
1815
+ log.host(host.name, "proxy is up to date");
1796
1816
  return;
1797
1817
  }
1798
- await host2.exec(`docker network inspect ${shq(merged.network)} >/dev/null 2>&1 || docker network create ${shq(merged.network)} >/dev/null
1818
+ await host.exec(`docker network inspect ${shq(merged.network)} >/dev/null 2>&1 || docker network create ${shq(merged.network)} >/dev/null
1799
1819
  docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true
1800
1820
  docker pull ${shq(merged.image)} >/dev/null
1801
1821
  ${spec.map((a) => shq(a)).join(" ")} >/dev/null
@@ -1804,15 +1824,15 @@ docker inspect -f '{{.State.Running}}' ${PROXY_CONTAINER} | grep -q true || {
1804
1824
  echo "traefik failed to start:" >&2
1805
1825
  docker logs --tail 40 ${PROXY_CONTAINER} >&2 || true
1806
1826
  exit 1
1807
- }`, { label: `${host2.name}: start proxy` });
1808
- log.host(host2.name, `proxy running (${entrypointSummary(merged)})`);
1827
+ }`, { label: `${host.name}: start proxy` });
1828
+ log.host(host.name, `proxy running (${entrypointSummary(merged)})`);
1809
1829
  }
1810
1830
  var TRAEFIK_FALLBACK_VERSION = "v3.3.7";
1811
- async function ensureProxyProcess(host2, cfg, merged, specHash, opts) {
1831
+ async function ensureProxyProcess(host, cfg, merged, specHash, opts) {
1812
1832
  const p = paths(cfg);
1813
1833
  const wanted = merged.version ?? (/^traefik:(v\d+\.\d+\.\d+)$/.exec(merged.image)?.[1] ?? "");
1814
1834
  const needsPrivilegedPort = Object.values(merged.entrypoints).some((port) => port < 1024);
1815
- await host2.exec(`mkdir -p ${shq(`${p.proxyDir}/bin`)} ${shq(p.proxyLogDir)}
1835
+ await host.exec(`mkdir -p ${shq(`${p.proxyDir}/bin`)} ${shq(p.proxyLogDir)}
1816
1836
  want=${shq(wanted)}
1817
1837
  if [ -z "$want" ]; then
1818
1838
  # Piping curl straight into grep -m1 closes the pipe early, which pipefail
@@ -1845,7 +1865,7 @@ if [ "$have" != "$want" ]; then
1845
1865
  rm -rf "$tmp"
1846
1866
  fi
1847
1867
  ${needsPrivilegedPort ? `command -v setcap >/dev/null 2>&1 && setcap 'cap_net_bind_service=+ep' ${shq(p.proxyBin)} 2>/dev/null || echo "note: could not grant the traefik binary permission to bind ports below 1024" >&2` : ""}
1848
- true`, { stream: true, label: `${host2.name}: install traefik` });
1868
+ true`, { stream: true, label: `${host.name}: install traefik` });
1849
1869
  const ecosystem = {
1850
1870
  apps: [
1851
1871
  {
@@ -1865,17 +1885,17 @@ true`, { stream: true, label: `${host2.name}: install traefik` });
1865
1885
  }
1866
1886
  ]
1867
1887
  };
1868
- await host2.writeFile(p.proxyEcosystem, JSON.stringify(ecosystem, null, 2), "600");
1869
- const jlist = await host2.capture(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null || echo '[]'`, {
1888
+ await host.writeFile(p.proxyEcosystem, JSON.stringify(ecosystem, null, 2), "600");
1889
+ const jlist = await host.capture(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null || echo '[]'`, {
1870
1890
  sudo: false,
1871
1891
  allowFailure: true
1872
1892
  });
1873
- const running = await host2.test(`${pathPrelude(cfg)} pm2 describe ${PROXY_PROCESS} >/dev/null 2>&1`);
1893
+ const running = await host.test(`${pathPrelude(cfg)} pm2 describe ${PROXY_PROCESS} >/dev/null 2>&1`);
1874
1894
  if (!opts.force && running && jlist.includes(specHash)) {
1875
- log.host(host2.name, "proxy is up to date");
1895
+ log.host(host.name, "proxy is up to date");
1876
1896
  return;
1877
1897
  }
1878
- await host2.exec(`${pathPrelude(cfg)} pm2 delete ${PROXY_PROCESS} >/dev/null 2>&1 || true
1898
+ await host.exec(`${pathPrelude(cfg)} pm2 delete ${PROXY_PROCESS} >/dev/null 2>&1 || true
1879
1899
  ${pathPrelude(cfg)} pm2 start ${shq(p.proxyEcosystem)} --update-env
1880
1900
  ${pathPrelude(cfg)} pm2 save --force >/dev/null 2>&1 || true
1881
1901
  sleep 2
@@ -1883,29 +1903,29 @@ ${pathPrelude(cfg)} pm2 describe ${PROXY_PROCESS} | grep -q online || {
1883
1903
  echo "traefik failed to start:" >&2
1884
1904
  tail -n 40 ${shq(`${p.proxyLogDir}/err.log`)} >&2 2>/dev/null || true
1885
1905
  exit 1
1886
- }`, { sudo: false, label: `${host2.name}: start proxy` });
1887
- log.host(host2.name, `proxy running (${entrypointSummary(merged)})`);
1906
+ }`, { sudo: false, label: `${host.name}: start proxy` });
1907
+ log.host(host.name, `proxy running (${entrypointSummary(merged)})`);
1888
1908
  }
1889
1909
  function entrypointSummary(d) {
1890
1910
  return Object.entries(d.entrypoints).map(([name, port]) => `${name}:${port}`).join(" ");
1891
1911
  }
1892
- async function writeRoutes(host2, cfg, endpoints, accessories = []) {
1912
+ async function writeRoutes(host, cfg, endpoints, accessories = []) {
1893
1913
  if (!cfg.proxy.enabled)
1894
1914
  return;
1895
1915
  const doc = dynamicConfig(cfg, endpoints, accessories);
1896
- await host2.writeFile(paths(cfg).proxyDynamic, JSON.stringify(doc, null, 2), "644");
1897
- await host2.exec(`sleep ${Math.max(1, cfg.proxy.reloadWait)}`);
1916
+ await host.writeFile(paths(cfg).proxyDynamic, JSON.stringify(doc, null, 2), "644");
1917
+ await host.exec(`sleep ${Math.max(1, cfg.proxy.reloadWait)}`);
1898
1918
  }
1899
- async function removeRoutes(host2, cfg) {
1900
- await host2.exec(`rm -f ${shq(paths(cfg).proxyDynamic)} ${shq(paths(cfg).proxyApp)}`, { allowFailure: true });
1919
+ async function removeRoutes(host, cfg) {
1920
+ await host.exec(`rm -f ${shq(paths(cfg).proxyDynamic)} ${shq(paths(cfg).proxyApp)}`, { allowFailure: true });
1901
1921
  }
1902
- async function proxyState(host2, cfg) {
1922
+ async function proxyState(host, cfg) {
1903
1923
  if (cfg.mode === "docker") {
1904
- const out2 = await host2.capture(`docker inspect -f '{{.State.Running}}|{{.Config.Image}}|{{.State.Status}}' ${PROXY_CONTAINER} 2>/dev/null || echo 'false||absent'`, { allowFailure: true });
1905
- const [running, image, status2] = out2.split("|");
1906
- return { running: running === "true", image: image ?? "", status: status2 ?? "absent" };
1924
+ const out = await host.capture(`docker inspect -f '{{.State.Running}}|{{.Config.Image}}|{{.State.Status}}' ${PROXY_CONTAINER} 2>/dev/null || echo 'false||absent'`, { allowFailure: true });
1925
+ const [running, image, status] = out.split("|");
1926
+ return { running: running === "true", image: image ?? "", status: status ?? "absent" };
1907
1927
  }
1908
- const out = await host2.capture(`describe=$(${pathPrelude(cfg)} pm2 describe ${PROXY_PROCESS} 2>/dev/null || true)
1928
+ const out = await host.capture(`describe=$(${pathPrelude(cfg)} pm2 describe ${PROXY_PROCESS} 2>/dev/null || true)
1909
1929
  printf '%s' "$describe" | awk -F'\u2502' '/status/ {gsub(/ /,"",$3); print $3; exit}' || true
1910
1930
  version_out=$(${shq(paths(cfg).proxyBin)} version 2>/dev/null || true)
1911
1931
  printf '%s' "$version_out" | awk '/[Vv]ersion:/ {print "traefik " $2; exit}' || true`, { sudo: false, allowFailure: true });
@@ -1931,8 +1951,8 @@ class DeployLock {
1931
1951
  async acquire(what) {
1932
1952
  const dir = paths(this.cfg).lock;
1933
1953
  const info = { by: who(), at: new Date().toISOString(), what };
1934
- for (const host2 of this.hosts) {
1935
- const res = await host2.exec(`mkdir -p ${shq(paths(this.cfg).app)}
1954
+ for (const host of this.hosts) {
1955
+ const res = await host.exec(`mkdir -p ${shq(paths(this.cfg).app)}
1936
1956
  if mkdir ${shq(dir)} 2>/dev/null; then
1937
1957
  printf '%s' ${shq(JSON.stringify(info))} > ${shq(dir)}/info
1938
1958
  echo acquired
@@ -1946,27 +1966,27 @@ fi`, { allowFailure: true });
1946
1966
  try {
1947
1967
  held = JSON.parse(res.stdout || "{}");
1948
1968
  } catch {}
1949
- throw new EpdError(`${this.cfg.name} is locked on ${host2.name}`, held.by ? `Held by ${held.by} since ${held.at} (${held.what}).
1969
+ throw new EpdError(`${this.cfg.name} is locked on ${host.name}`, held.by ? `Held by ${held.by} since ${held.at} (${held.what}).
1950
1970
  If that deploy died, run: epd lock release` : "Run `epd lock release` if a previous deploy was interrupted.");
1951
1971
  }
1952
- this.held.push(host2);
1972
+ this.held.push(host);
1953
1973
  }
1954
1974
  log.debug(`lock acquired on ${this.held.length} host(s)`);
1955
1975
  }
1956
1976
  async release() {
1957
1977
  const dir = paths(this.cfg).lock;
1958
- for (const host2 of this.held.splice(0)) {
1959
- await host2.exec(`rm -rf ${shq(dir)}`, { allowFailure: true });
1978
+ for (const host of this.held.splice(0)) {
1979
+ await host.exec(`rm -rf ${shq(dir)}`, { allowFailure: true });
1960
1980
  }
1961
1981
  }
1962
1982
  static async forceRelease(cfg, hosts) {
1963
- for (const host2 of hosts)
1964
- await host2.exec(`rm -rf ${shq(paths(cfg).lock)}`, { allowFailure: true });
1983
+ for (const host of hosts)
1984
+ await host.exec(`rm -rf ${shq(paths(cfg).lock)}`, { allowFailure: true });
1965
1985
  }
1966
1986
  static async status(cfg, hosts) {
1967
1987
  const out = [];
1968
- for (const host2 of hosts) {
1969
- const raw = await host2.readFile(`${paths(cfg).lock}/info`);
1988
+ for (const host of hosts) {
1989
+ const raw = await host.readFile(`${paths(cfg).lock}/info`);
1970
1990
  let info = null;
1971
1991
  if (raw) {
1972
1992
  try {
@@ -1975,7 +1995,7 @@ If that deploy died, run: epd lock release` : "Run `epd lock release` if a previ
1975
1995
  info = { by: "unknown", at: "unknown", what: "unknown" };
1976
1996
  }
1977
1997
  }
1978
- out.push({ host: host2.name, info });
1998
+ out.push({ host: host.name, info });
1979
1999
  }
1980
2000
  return out;
1981
2001
  }
@@ -2074,34 +2094,34 @@ EPD_TARGETS
2074
2094
  done
2075
2095
  `;
2076
2096
  }
2077
- async function waitHealthy(host2, targets, health) {
2097
+ async function waitHealthy(host, targets, health) {
2078
2098
  if (!targets.length)
2079
2099
  return;
2080
- const res = await host2.exec(healthScript(targets, health), {
2100
+ const res = await host.exec(healthScript(targets, health), {
2081
2101
  allowFailure: true,
2082
- label: `${host2.name}: health check`
2102
+ label: `${host.name}: health check`
2083
2103
  });
2084
2104
  if (res.code === 0 && res.stdout.includes("EPD_HEALTHY"))
2085
2105
  return;
2086
2106
  const detail = res.stdout.replace("EPD_UNHEALTHY:", "").trim() || res.stderr;
2087
- throw new EpdError(`${host2.name}: new version did not become healthy within ${health.timeout}s`, `Still failing:${detail ? ` ${detail}` : ""}
2107
+ throw new EpdError(`${host.name}: new version did not become healthy within ${health.timeout}s`, `Still failing:${detail ? ` ${detail}` : ""}
2088
2108
  Check \`epd logs\` \u2014 the old version is still serving traffic.`);
2089
2109
  }
2090
2110
 
2091
2111
  // src/core/state.ts
2092
- async function readState(host2, cfg) {
2093
- const raw = await host2.readFile(paths(cfg).state);
2112
+ async function readState(host, cfg) {
2113
+ const raw = await host.readFile(paths(cfg).state);
2094
2114
  if (!raw)
2095
2115
  return null;
2096
2116
  try {
2097
2117
  return JSON.parse(raw);
2098
2118
  } catch {
2099
- log.warn(`${host2.name}: state file is corrupt, treating this host as fresh`);
2119
+ log.warn(`${host.name}: state file is corrupt, treating this host as fresh`);
2100
2120
  return null;
2101
2121
  }
2102
2122
  }
2103
- async function writeState(host2, cfg, state) {
2104
- await host2.writeFile(paths(cfg).state, JSON.stringify(state, null, 2), "644");
2123
+ async function writeState(host, cfg, state) {
2124
+ await host.writeFile(paths(cfg).state, JSON.stringify(state, null, 2), "644");
2105
2125
  }
2106
2126
  function emptyState(cfg) {
2107
2127
  return {
@@ -2210,7 +2230,7 @@ async function ensureBuilder() {
2210
2230
  log.info('creating buildx builder "epd"');
2211
2231
  await run(["docker", "buildx", "create", "--name", "epd", "--use", "--bootstrap"], { stream: true });
2212
2232
  }
2213
- async function loginRegistry(host2, cfg, env) {
2233
+ async function loginRegistry(host, cfg, env) {
2214
2234
  if (!cfg.registry)
2215
2235
  return;
2216
2236
  const password = env[cfg.registry.passwordEnv];
@@ -2218,25 +2238,25 @@ async function loginRegistry(host2, cfg, env) {
2218
2238
  throw new EpdError(`registry password: ${cfg.registry.passwordEnv} is not set`, "Export it, or put it in .env next to epd.yml.");
2219
2239
  }
2220
2240
  const server = cfg.registry.server ?? "";
2221
- await host2.exec(`printf '%s' ${shq(password)} | docker login ${server ? shq(server) + " " : ""}--username ${shq(cfg.registry.username)} --password-stdin >/dev/null`, { label: `${host2.name}: docker login` });
2241
+ await host.exec(`printf '%s' ${shq(password)} | docker login ${server ? shq(server) + " " : ""}--username ${shq(cfg.registry.username)} --password-stdin >/dev/null`, { label: `${host.name}: docker login` });
2222
2242
  }
2223
- async function ensureImage(host2, cfg, version) {
2243
+ async function ensureImage(host, cfg, version) {
2224
2244
  const ref = imageRef(cfg, version);
2225
- if (await host2.test(`docker image inspect ${shq(ref)} >/dev/null 2>&1`)) {
2226
- log.host(host2.name, `image ${version} already present`);
2245
+ if (await host.test(`docker image inspect ${shq(ref)} >/dev/null 2>&1`)) {
2246
+ log.host(host.name, `image ${version} already present`);
2227
2247
  return;
2228
2248
  }
2229
2249
  if (cfg.registry) {
2230
- log.host(host2.name, `pulling ${ref}`);
2231
- await host2.exec(`docker pull ${shq(ref)} >/dev/null`, { label: `${host2.name}: docker pull` });
2250
+ log.host(host.name, `pulling ${ref}`);
2251
+ await host.exec(`docker pull ${shq(ref)} >/dev/null`, { label: `${host.name}: docker pull` });
2232
2252
  } else {
2233
- log.host(host2.name, `shipping ${ref} over ssh (no registry configured)`);
2234
- await host2.pipeInto("gunzip | docker load", ["/bin/sh", "-c", `docker save ${shq(ref)} | gzip -1`]);
2253
+ log.host(host.name, `shipping ${ref} over ssh (no registry configured)`);
2254
+ await host.pipeInto("gunzip | docker load", ["/bin/sh", "-c", `docker save ${shq(ref)} | gzip -1`]);
2235
2255
  }
2236
2256
  }
2237
- async function pruneImages(host2, cfg, keep, inUse) {
2257
+ async function pruneImages(host, cfg, keep, inUse) {
2238
2258
  const keepRefs = inUse.map((v) => imageRef(cfg, v));
2239
- await host2.exec(`keep=${shq(keepRefs.join(" "))}
2259
+ await host.exec(`keep=${shq(keepRefs.join(" "))}
2240
2260
  docker images --filter "label=epd.app=${cfg.name}" --format '{{.Repository}}:{{.Tag}} {{.CreatedAt}}' 2>/dev/null \\
2241
2261
  | sort -k2 -r | tail -n +$(( ${keep} + 1 )) | awk '{print $1}' | while read -r img; do
2242
2262
  case " $keep " in *" $img "*) continue;; esac
@@ -2271,10 +2291,10 @@ function envFileContent(vars) {
2271
2291
  return Object.entries(vars).map(([k, v]) => `${k}=${v}`).join(`
2272
2292
  `);
2273
2293
  }
2274
- async function writeServiceEnv(host2, cfg, svc, env) {
2294
+ async function writeServiceEnv(host, cfg, svc, env) {
2275
2295
  const secrets = resolveSecrets(svc.secrets, env, `servers.${svc.name}`);
2276
2296
  const file = `${paths(cfg).app}/env.${svc.name}`;
2277
- await host2.writeFile(file, envFileContent({ ...svc.env, ...secrets }), "600");
2297
+ await host.writeFile(file, envFileContent({ ...svc.env, ...secrets }), "600");
2278
2298
  return file;
2279
2299
  }
2280
2300
  function dockerRunArgs(o) {
@@ -2301,7 +2321,7 @@ function dockerRunArgs(o) {
2301
2321
  args.push(...parseCommand(svc.command));
2302
2322
  return args;
2303
2323
  }
2304
- async function startSlot(host2, cfg, svc, slot, version, envFile) {
2324
+ async function startSlot(host, cfg, svc, slot, version, envFile) {
2305
2325
  const names = [];
2306
2326
  const lines = [
2307
2327
  `old=$(docker ps -a -q --filter "label=epd.app=${cfg.name}" --filter "label=epd.service=${svc.name}" --filter "label=epd.slot=${slot}")`,
@@ -2310,19 +2330,19 @@ async function startSlot(host2, cfg, svc, slot, version, envFile) {
2310
2330
  for (let i = 0;i < svc.replicas; i++) {
2311
2331
  const name = containerName(cfg.name, svc.name, slot, i);
2312
2332
  names.push(name);
2313
- const args = dockerRunArgs({ cfg, svc, slot, version, replica: i, serverHost: host2.name, envFile });
2333
+ const args = dockerRunArgs({ cfg, svc, slot, version, replica: i, serverHost: host.name, envFile });
2314
2334
  lines.push(`docker rm -f ${shq(name)} >/dev/null 2>&1 || true`);
2315
2335
  lines.push(`${args.map((a) => shq(a)).join(" ")} >/dev/null`);
2316
2336
  }
2317
- await host2.exec(lines.join(`
2318
- `), { label: `${host2.name}: start ${svc.name}/${slot}` });
2337
+ await host.exec(lines.join(`
2338
+ `), { label: `${host.name}: start ${svc.name}/${slot}` });
2319
2339
  return names;
2320
2340
  }
2321
- async function containerIps(host2, cfg, names) {
2341
+ async function containerIps(host, cfg, names) {
2322
2342
  if (!names.length)
2323
2343
  return {};
2324
2344
  const tpl = `{{ with (index .NetworkSettings.Networks ${JSON.stringify(cfg.proxy.network)}) }}{{ .IPAddress }}{{ end }}`;
2325
- const out = await host2.capture(names.map((n) => `echo "${n} $(docker inspect -f ${shq(tpl)} ${shq(n)} 2>/dev/null)"`).join(`
2345
+ const out = await host.capture(names.map((n) => `echo "${n} $(docker inspect -f ${shq(tpl)} ${shq(n)} 2>/dev/null)"`).join(`
2326
2346
  `));
2327
2347
  const map = {};
2328
2348
  for (const line of out.split(`
@@ -2333,21 +2353,21 @@ async function containerIps(host2, cfg, names) {
2333
2353
  }
2334
2354
  return map;
2335
2355
  }
2336
- async function stopSlot(host2, cfg, svc, slot, opts) {
2356
+ async function stopSlot(host, cfg, svc, slot, opts) {
2337
2357
  const teardown = `names=$(docker ps -a -q --filter "label=epd.app=${cfg.name}" --filter "label=epd.service=${svc.name}" --filter "label=epd.slot=${slot}")
2338
2358
  if [ -n "$names" ]; then
2339
2359
  sleep ${opts.drain}
2340
2360
  docker stop --timeout ${svc.stopTimeout} $names >/dev/null 2>&1 || true
2341
2361
  ${opts.remove ? "docker rm -f $names >/dev/null 2>&1 || true" : ""}
2342
2362
  fi`;
2343
- await host2.exec(opts.detach ? `nohup setsid bash -c ${shq(teardown)} >/dev/null 2>&1 < /dev/null &
2344
- disown 2>/dev/null || true` : teardown, { allowFailure: true, label: `${host2.name}: stop ${svc.name}/${slot}` });
2363
+ await host.exec(opts.detach ? `nohup setsid bash -c ${shq(teardown)} >/dev/null 2>&1 < /dev/null &
2364
+ disown 2>/dev/null || true` : teardown, { allowFailure: true, label: `${host.name}: stop ${svc.name}/${slot}` });
2345
2365
  }
2346
- async function removeApp(host2, cfg) {
2347
- await host2.exec(`ids=$(docker ps -a -q --filter "label=epd.app=${cfg.name}")
2366
+ async function removeApp(host, cfg) {
2367
+ await host.exec(`ids=$(docker ps -a -q --filter "label=epd.app=${cfg.name}")
2348
2368
  [ -n "$ids" ] && docker rm -f $ids >/dev/null 2>&1 || true`, { allowFailure: true });
2349
2369
  }
2350
- async function listContainers(host2, cfg) {
2370
+ async function listContainers(host, cfg) {
2351
2371
  const fmt = [
2352
2372
  "{{.Names}}",
2353
2373
  '{{.Label "epd.service"}}',
@@ -2359,7 +2379,7 @@ async function listContainers(host2, cfg) {
2359
2379
  "{{.Image}}",
2360
2380
  "{{.CreatedAt}}"
2361
2381
  ].join("\t");
2362
- const out = await host2.capture(`docker ps -a --filter "label=epd.app=${cfg.name}" --format ${shq(fmt)} 2>/dev/null || true`, { allowFailure: true });
2382
+ const out = await host.capture(`docker ps -a --filter "label=epd.app=${cfg.name}" --format ${shq(fmt)} 2>/dev/null || true`, { allowFailure: true });
2363
2383
  return out.split(`
2364
2384
  `).filter(Boolean).map((line) => {
2365
2385
  const [name, service, slot, version, replica, status, state, image, created] = line.split("\t");
@@ -2376,11 +2396,11 @@ async function listContainers(host2, cfg) {
2376
2396
  };
2377
2397
  });
2378
2398
  }
2379
- async function startAccessory(host2, cfg, acc, env, opts) {
2399
+ async function startAccessory(host, cfg, acc, env, opts) {
2380
2400
  const name = accessoryContainer(cfg.name, acc.name);
2381
2401
  const secrets = resolveSecrets(acc.secrets, env, `accessories.${acc.name}`);
2382
2402
  const envFile = `${paths(cfg).app}/env.acc.${acc.name}`;
2383
- await host2.writeFile(envFile, envFileContent({ ...acc.env, ...secrets }), "600");
2403
+ await host.writeFile(envFile, envFileContent({ ...acc.env, ...secrets }), "600");
2384
2404
  const args = [
2385
2405
  "docker",
2386
2406
  "run",
@@ -2411,12 +2431,12 @@ async function startAccessory(host2, cfg, acc, env, opts) {
2411
2431
  args.push(...acc.dockerOptions, acc.image);
2412
2432
  if (acc.command)
2413
2433
  args.push(...parseCommand(acc.command));
2414
- await host2.exec(`if docker inspect ${shq(name)} >/dev/null 2>&1; then
2434
+ await host.exec(`if docker inspect ${shq(name)} >/dev/null 2>&1; then
2415
2435
  ${opts.recreate ? `docker rm -f ${shq(name)} >/dev/null` : `docker start ${shq(name)} >/dev/null 2>&1 || true; exit 0`}
2416
2436
  fi
2417
2437
  docker pull ${shq(acc.image)} >/dev/null
2418
- ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host2.name}: accessory ${acc.name}` });
2419
- log.host(host2.name, `accessory ${acc.name} running`);
2438
+ ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: accessory ${acc.name}` });
2439
+ log.host(host.name, `accessory ${acc.name} running`);
2420
2440
  }
2421
2441
 
2422
2442
  // src/deploy/process.ts
@@ -2427,34 +2447,34 @@ var pm2 = (cfg, args) => `${pathPrelude(cfg)} pm2 ${args}`;
2427
2447
  function releaseDir(cfg, version) {
2428
2448
  return `${paths(cfg).releases}/${version}`;
2429
2449
  }
2430
- async function uploadSource(host2, cfg, version) {
2450
+ async function uploadSource(host, cfg, version) {
2431
2451
  const dest = releaseDir(cfg, version);
2432
2452
  const p = paths(cfg);
2433
- await host2.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
2453
+ await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
2434
2454
  if (cfg.process.source === "git") {
2435
2455
  if (!existsSync4(join5(cfg.root, ".git")))
2436
2456
  throw new EpdError('process.source is "git" but this is not a git repository');
2437
- log.host(host2.name, `uploading HEAD as ${version}`);
2438
- await host2.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
2457
+ log.host(host.name, `uploading HEAD as ${version}`);
2458
+ await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
2439
2459
  return;
2440
2460
  }
2441
- const previous = await host2.capture(`ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | head -n 1 || true`, { ...asUser, allowFailure: true });
2461
+ const previous = await host.capture(`ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | head -n 1 || true`, { ...asUser, allowFailure: true });
2442
2462
  const args = ["rsync", "-az", "--delete", "--human-readable", "--info=stats1"];
2443
2463
  for (const ex of cfg.process.exclude)
2444
2464
  args.push("--exclude", ex);
2445
2465
  if (previous)
2446
2466
  args.push("--link-dest", previous.replace(/\/$/, ""));
2447
- args.push("-e", host2.rsyncShell());
2448
- args.push(`${cfg.root.replace(/\/$/, "")}/`, `${host2.target}:${dest}/`);
2449
- await host2.exec(`mkdir -p ${shq(dest)}`, asUser);
2450
- log.host(host2.name, `uploading ${version}`);
2451
- await run(args, { cwd: cfg.root, label: `rsync \u2192 ${host2.name}` });
2467
+ args.push("-e", host.rsyncShell());
2468
+ args.push(`${cfg.root.replace(/\/$/, "")}/`, `${host.target}:${dest}/`);
2469
+ await host.exec(`mkdir -p ${shq(dest)}`, asUser);
2470
+ log.host(host.name, `uploading ${version}`);
2471
+ await run(args, { cwd: cfg.root, label: `rsync \u2192 ${host.name}` });
2452
2472
  }
2453
- async function buildRelease(host2, cfg, version, env) {
2473
+ async function buildRelease(host, cfg, version, env) {
2454
2474
  const dest = releaseDir(cfg, version);
2455
2475
  const secrets = resolveSecrets(cfg.secrets, env, "env.secret");
2456
2476
  const envFile = paths(cfg).envFile;
2457
- await host2.writeFile(envFile, Object.entries({ ...cfg.env, ...secrets }).map(([k, v]) => `${k}=${v}`).join(`
2477
+ await host.writeFile(envFile, Object.entries({ ...cfg.env, ...secrets }).map(([k, v]) => `${k}=${v}`).join(`
2458
2478
  `), "600");
2459
2479
  const steps = [`cd ${shq(dest)}`, pathPrelude(cfg), `set -a; . ${shq(envFile)}; set +a`];
2460
2480
  if (cfg.process.install)
@@ -2462,9 +2482,9 @@ async function buildRelease(host2, cfg, version, env) {
2462
2482
  if (cfg.process.build)
2463
2483
  steps.push(cfg.process.build);
2464
2484
  if (steps.length > 3) {
2465
- log.host(host2.name, "installing and building");
2466
- await host2.exec(steps.join(`
2467
- `), { ...asUser, stream: true, label: `${host2.name}: build` });
2485
+ log.host(host.name, "installing and building");
2486
+ await host.exec(steps.join(`
2487
+ `), { ...asUser, stream: true, label: `${host.name}: build` });
2468
2488
  }
2469
2489
  }
2470
2490
  function ecosystem(cfg, svc, slot, version, env) {
@@ -2502,34 +2522,34 @@ function ecosystem(cfg, svc, slot, version, env) {
2502
2522
  }
2503
2523
  return { apps };
2504
2524
  }
2505
- async function startSlot2(host2, cfg, svc, slot, version, env) {
2525
+ async function startSlot2(host, cfg, svc, slot, version, env) {
2506
2526
  const secrets = resolveSecrets(svc.secrets, env, `servers.${svc.name}`);
2507
2527
  const doc = ecosystem(cfg, svc, slot, version, { ...svc.env, ...secrets });
2508
2528
  const file = `${paths(cfg).app}/pm2.${svc.name}.${slot}.json`;
2509
- await host2.writeFile(file, JSON.stringify(doc, null, 2), "600");
2529
+ await host.writeFile(file, JSON.stringify(doc, null, 2), "600");
2510
2530
  const stale = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
2511
- await host2.exec(`for name in ${stale.map((n) => shq(n)).join(" ")}; do ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true; done
2531
+ await host.exec(`for name in ${stale.map((n) => shq(n)).join(" ")}; do ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true; done
2512
2532
  ${pm2(cfg, `start ${shq(file)} --update-env`)}
2513
- ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, label: `${host2.name}: pm2 start ${svc.name}/${slot}` });
2533
+ ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, label: `${host.name}: pm2 start ${svc.name}/${slot}` });
2514
2534
  }
2515
- async function stopSlot2(host2, cfg, svc, slot, drain, opts = {}) {
2535
+ async function stopSlot2(host, cfg, svc, slot, drain, opts = {}) {
2516
2536
  const names = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
2517
2537
  const teardown = `sleep ${drain}
2518
2538
  for name in ${names.map((n) => shq(n)).join(" ")}; do
2519
2539
  ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true
2520
2540
  done
2521
2541
  ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`;
2522
- await host2.exec(opts.detach ? `nohup setsid bash -c ${shq(teardown)} >/dev/null 2>&1 < /dev/null &
2523
- disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host2.name}: pm2 stop ${svc.name}/${slot}` });
2542
+ await host.exec(opts.detach ? `nohup setsid bash -c ${shq(teardown)} >/dev/null 2>&1 < /dev/null &
2543
+ disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host.name}: pm2 stop ${svc.name}/${slot}` });
2524
2544
  }
2525
- async function removeApp2(host2, cfg) {
2526
- await host2.exec(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null | tr ',' '\\n' | grep -o '"name":"epd-${cfg.name}-[^"]*"' | cut -d'"' -f4 | sort -u | while read -r n; do
2545
+ async function removeApp2(host, cfg) {
2546
+ await host.exec(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null | tr ',' '\\n' | grep -o '"name":"epd-${cfg.name}-[^"]*"' | cut -d'"' -f4 | sort -u | while read -r n; do
2527
2547
  ${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
2528
2548
  done
2529
2549
  ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
2530
2550
  }
2531
- async function listProcesses(host2, cfg) {
2532
- const out = await host2.capture(`${pm2(cfg, "jlist")} 2>/dev/null || echo '[]'`, { ...asUser, allowFailure: true });
2551
+ async function listProcesses(host, cfg) {
2552
+ const out = await host.capture(`${pm2(cfg, "jlist")} 2>/dev/null || echo '[]'`, { ...asUser, allowFailure: true });
2533
2553
  const jsonStart = out.indexOf("[");
2534
2554
  let parsed = [];
2535
2555
  try {
@@ -2546,19 +2566,227 @@ async function listProcesses(host2, cfg) {
2546
2566
  memory: p.monit?.memory ?? 0
2547
2567
  }));
2548
2568
  }
2549
- async function finalizeRelease(host2, cfg, version) {
2569
+ async function finalizeRelease(host, cfg, version) {
2550
2570
  const p = paths(cfg);
2551
- await host2.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
2571
+ await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
2552
2572
  ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1 )) | while read -r d; do
2553
2573
  case "$d" in *${shq(version)}*) continue;; esac
2554
2574
  rm -rf "$d"
2555
2575
  done`, { ...asUser, allowFailure: true });
2556
2576
  }
2557
2577
 
2578
+ // src/core/cloudflare.ts
2579
+ import dns from "dns/promises";
2580
+ class CloudflareClient {
2581
+ apiToken;
2582
+ baseUrl;
2583
+ constructor(apiToken, baseUrl = "https://api.cloudflare.com/client/v4") {
2584
+ this.apiToken = apiToken;
2585
+ this.baseUrl = baseUrl.replace(/\/$/, "");
2586
+ }
2587
+ async request(path, options = {}) {
2588
+ const url = `${this.baseUrl}${path}`;
2589
+ const headers = {
2590
+ Authorization: `Bearer ${this.apiToken}`,
2591
+ "Content-Type": "application/json",
2592
+ ...options.headers
2593
+ };
2594
+ const res = await fetch(url, { ...options, headers });
2595
+ const data = await res.json();
2596
+ if (!res.ok || data.success === false) {
2597
+ const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
2598
+ throw new EpdError(`Cloudflare API error: ${msg}`);
2599
+ }
2600
+ return data.result;
2601
+ }
2602
+ async listZones(name) {
2603
+ const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
2604
+ return this.request(`/zones${query}`);
2605
+ }
2606
+ async findZoneForDomain(domain, explicitZoneId) {
2607
+ if (explicitZoneId) {
2608
+ return { id: explicitZoneId, name: domain, status: "active" };
2609
+ }
2610
+ const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
2611
+ const parts = cleanDomain.split(".");
2612
+ for (let i = 0;i < parts.length - 1; i++) {
2613
+ const candidate = parts.slice(i).join(".");
2614
+ const zones = await this.listZones(candidate);
2615
+ const match = zones.find((z) => z.name.toLowerCase() === candidate);
2616
+ if (match)
2617
+ return match;
2618
+ }
2619
+ throw new EpdError(`Cloudflare zone for domain "${domain}" not found`, `Make sure the domain is registered under your Cloudflare account and your API token has Zone.Read permissions.`);
2620
+ }
2621
+ async listDnsRecords(zoneId, name, type) {
2622
+ const params = new URLSearchParams;
2623
+ params.set("per_page", "100");
2624
+ if (name)
2625
+ params.set("name", name);
2626
+ if (type)
2627
+ params.set("type", type);
2628
+ return this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
2629
+ }
2630
+ async createDnsRecord(zoneId, record) {
2631
+ return this.request(`/zones/${zoneId}/dns_records`, {
2632
+ method: "POST",
2633
+ body: JSON.stringify(record)
2634
+ });
2635
+ }
2636
+ async updateDnsRecord(zoneId, recordId, record) {
2637
+ return this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
2638
+ method: "PUT",
2639
+ body: JSON.stringify(record)
2640
+ });
2641
+ }
2642
+ }
2643
+ function isIPv4(ip) {
2644
+ const parts = ip.split(".");
2645
+ if (parts.length !== 4)
2646
+ return false;
2647
+ return parts.every((p) => {
2648
+ const n = Number(p);
2649
+ return !isNaN(n) && n >= 0 && n <= 255 && String(n) === p;
2650
+ });
2651
+ }
2652
+ function isIPv6(ip) {
2653
+ return ip.includes(":") && /^[0-9a-fA-F:]+$/.test(ip);
2654
+ }
2655
+ async function resolveHostIps(target) {
2656
+ const clean = target.trim();
2657
+ if (isIPv4(clean) || isIPv6(clean))
2658
+ return [clean];
2659
+ try {
2660
+ const lookup = await dns.lookup(clean, { all: true });
2661
+ if (lookup && lookup.length > 0) {
2662
+ return lookup.map((l) => l.address);
2663
+ }
2664
+ } catch {}
2665
+ return [clean];
2666
+ }
2667
+ function getRouteDomains(cfg) {
2668
+ if (cfg.cloudflare?.domains && cfg.cloudflare.domains.length > 0) {
2669
+ return cfg.cloudflare.domains;
2670
+ }
2671
+ const domains = new Set;
2672
+ for (const svc of cfg.services) {
2673
+ for (const route of svc.routes) {
2674
+ for (const host of route.hosts) {
2675
+ const d = (host.split(":")[0] ?? "").trim().toLowerCase();
2676
+ if (d)
2677
+ domains.add(d);
2678
+ }
2679
+ }
2680
+ }
2681
+ for (const acc of cfg.accessories) {
2682
+ for (const route of acc.routes) {
2683
+ for (const host of route.hosts) {
2684
+ const d = (host.split(":")[0] ?? "").trim().toLowerCase();
2685
+ if (d)
2686
+ domains.add(d);
2687
+ }
2688
+ }
2689
+ }
2690
+ return [...domains];
2691
+ }
2692
+ async function syncDns(cfg, opts = {}) {
2693
+ const token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
2694
+ if (!token) {
2695
+ throw new EpdError("Cloudflare API token is missing", "Set CLOUDFLARE_API_TOKEN in your environment or specify api_token in epd.yml under cloudflare.");
2696
+ }
2697
+ const client = opts.client ?? new CloudflareClient(token);
2698
+ const domains = getRouteDomains(cfg);
2699
+ if (!domains.length) {
2700
+ if (opts.log)
2701
+ log.step("Cloudflare DNS: no domain names found in routes to sync");
2702
+ return [];
2703
+ }
2704
+ const routedHosts = new Set;
2705
+ for (const svc of cfg.services) {
2706
+ if (svc.routes.length) {
2707
+ for (const h of svc.hosts)
2708
+ routedHosts.add(h);
2709
+ }
2710
+ }
2711
+ const ips = new Set;
2712
+ for (const h of routedHosts) {
2713
+ const resolved = await resolveHostIps(h);
2714
+ for (const ip of resolved) {
2715
+ if (isIPv4(ip) || isIPv6(ip))
2716
+ ips.add(ip);
2717
+ }
2718
+ }
2719
+ if (!ips.size) {
2720
+ if (opts.log)
2721
+ log.step("Cloudflare DNS: no server IP addresses resolved to sync");
2722
+ return [];
2723
+ }
2724
+ const isProxied = opts.proxied ?? cfg.cloudflare?.proxied ?? true;
2725
+ const ttl = cfg.cloudflare?.ttl ?? 1;
2726
+ const results = [];
2727
+ if (opts.log) {
2728
+ log.step(`Cloudflare: syncing ${c.bold(domains.length.toString())} domain(s) across ${c.bold(ips.size.toString())} server IP(s)`);
2729
+ }
2730
+ const zoneCache = new Map;
2731
+ for (const domain of domains) {
2732
+ let zone = zoneCache.get(domain);
2733
+ if (!zone) {
2734
+ zone = await client.findZoneForDomain(domain, cfg.cloudflare?.zoneId);
2735
+ zoneCache.set(domain, zone);
2736
+ }
2737
+ const existingRecords = await client.listDnsRecords(zone.id, domain);
2738
+ for (const ip of ips) {
2739
+ const type = isIPv6(ip) ? "AAAA" : "A";
2740
+ const existing = existingRecords.find((r) => r.name.toLowerCase() === domain.toLowerCase() && r.type === type && r.content === ip);
2741
+ if (existing) {
2742
+ if (existing.proxied !== isProxied || ttl !== 1 && existing.ttl !== ttl) {
2743
+ if (!opts.dryRun) {
2744
+ await client.updateDnsRecord(zone.id, existing.id, {
2745
+ name: domain,
2746
+ type,
2747
+ content: ip,
2748
+ proxied: isProxied,
2749
+ ttl,
2750
+ comment: `Managed by epd (${cfg.name})`
2751
+ });
2752
+ }
2753
+ results.push({ domain, ip, type, action: "updated", recordId: existing.id, proxied: isProxied });
2754
+ if (opts.log) {
2755
+ log.ok(`Cloudflare: updated ${type} ${c.bold(domain)} \u2192 ${ip} (${isProxied ? "proxied" : "DNS only"})`);
2756
+ }
2757
+ } else {
2758
+ results.push({ domain, ip, type, action: "unchanged", recordId: existing.id, proxied: isProxied });
2759
+ if (opts.log) {
2760
+ log.debug(`${type} ${domain} \u2192 ${ip} (${isProxied ? "proxied" : "DNS only"}) already in sync`);
2761
+ }
2762
+ }
2763
+ } else {
2764
+ let recordId;
2765
+ if (!opts.dryRun) {
2766
+ const created = await client.createDnsRecord(zone.id, {
2767
+ name: domain,
2768
+ type,
2769
+ content: ip,
2770
+ proxied: isProxied,
2771
+ ttl,
2772
+ comment: `Managed by epd (${cfg.name})`
2773
+ });
2774
+ recordId = created.id;
2775
+ }
2776
+ results.push({ domain, ip, type, action: "created", recordId, proxied: isProxied });
2777
+ if (opts.log) {
2778
+ log.ok(`Cloudflare: created ${type} ${c.bold(domain)} \u2192 ${ip} (${isProxied ? "proxied" : "DNS only"})${opts.dryRun ? " [dry-run]" : ""}`);
2779
+ }
2780
+ }
2781
+ }
2782
+ }
2783
+ return results;
2784
+ }
2785
+
2558
2786
  // src/deploy/deploy.ts
2559
2787
  async function deploy(loaded, opts = {}) {
2560
2788
  const { config: cfg, env } = loaded;
2561
- const started2 = Date.now();
2789
+ const started = Date.now();
2562
2790
  const services = selectServices(cfg, opts.onlyServices);
2563
2791
  const targetHosts = selectHosts(cfg, services, opts.onlyHosts);
2564
2792
  const hosts = targetHosts.map((h) => host(h, cfg.ssh));
@@ -2575,15 +2803,15 @@ async function deploy(loaded, opts = {}) {
2575
2803
  await hook(cfg, "pre_deploy", cfg.hooks.preDeploy, version);
2576
2804
  await withLock(cfg, hosts, `deploy ${version}`, opts.skipLock ?? false, async () => {
2577
2805
  log.step("Preparing servers");
2578
- await pool(hosts, 8, async (host2) => {
2579
- await verifyHost(host2, cfg);
2806
+ await pool(hosts, 8, async (host) => {
2807
+ await verifyHost(host, cfg);
2580
2808
  if (cfg.mode === "docker")
2581
- await ensureNetwork(host2, cfg);
2809
+ await ensureNetwork(host, cfg);
2582
2810
  });
2583
2811
  await deployAccessories(cfg, env, opts.recreateAccessories ?? false);
2584
2812
  if (cfg.proxy.enabled && proxyHosts(cfg).length) {
2585
2813
  log.step("Checking proxy");
2586
- await pool(proxyHosts(cfg).filter((h) => targetHosts.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host2) => ensureProxy(host2, cfg, { secrets: env }));
2814
+ await pool(proxyHosts(cfg).filter((h) => targetHosts.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: env }));
2587
2815
  }
2588
2816
  const live = new Map;
2589
2817
  for (const h of allHosts(cfg)) {
@@ -2593,61 +2821,68 @@ async function deploy(loaded, opts = {}) {
2593
2821
  m.set(svc, s.slot);
2594
2822
  live.set(h, m);
2595
2823
  }
2596
- const deployHost = async (host2) => {
2597
- await deployToHost({ cfg, env, host: host2, services, version, opts, live });
2824
+ const deployHost = async (host) => {
2825
+ await deployToHost({ cfg, env, host, services, version, opts, live });
2598
2826
  };
2599
2827
  if (cfg.strategy === "parallel") {
2600
2828
  await pool(hosts, hosts.length, deployHost);
2601
2829
  } else {
2602
- for (const host2 of hosts)
2603
- await deployHost(host2);
2830
+ for (const host of hosts)
2831
+ await deployHost(host);
2604
2832
  }
2605
2833
  if (cfg.proxy.crossHost) {
2606
2834
  log.step("Syncing routes across hosts");
2607
- await pool(proxyHosts(cfg).map((h) => host(h, cfg.ssh)), 4, async (host2) => {
2608
- await writeRoutes(host2, cfg, buildEndpoints(cfg, host2.name, live), buildAccessoryEndpoints(cfg, host2.name));
2835
+ await pool(proxyHosts(cfg).map((h) => host(h, cfg.ssh)), 4, async (host) => {
2836
+ await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
2609
2837
  });
2610
2838
  }
2611
2839
  });
2840
+ if (cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
2841
+ try {
2842
+ await syncDns(cfg, { log: true });
2843
+ } catch (e) {
2844
+ log.warn(`Cloudflare DNS sync: ${e instanceof Error ? e.message : String(e)}`);
2845
+ }
2846
+ }
2612
2847
  if (!opts.skipHooks && cfg.hooks.postDeploy)
2613
2848
  await hook(cfg, "post_deploy", cfg.hooks.postDeploy, version);
2614
- log.ok(`Deployed ${cfg.name} ${version} in ${dur(Date.now() - started2)}`);
2849
+ log.ok(`Deployed ${cfg.name} ${version} in ${dur(Date.now() - started)}`);
2615
2850
  printUrls(cfg);
2616
2851
  }
2617
2852
  async function deployToHost(d) {
2618
- const { cfg, env, host: host2, version, opts, live } = d;
2619
- const services = d.services.filter((s) => s.hosts.includes(host2.name));
2853
+ const { cfg, env, host, version, opts, live } = d;
2854
+ const services = d.services.filter((s) => s.hosts.includes(host.name));
2620
2855
  if (!services.length)
2621
2856
  return;
2622
- log.step(`${host2.name}: deploying ${services.map((s) => s.name).join(", ")}`);
2857
+ log.step(`${host.name}: deploying ${services.map((s) => s.name).join(", ")}`);
2623
2858
  if (cfg.mode === "docker") {
2624
- await loginRegistry(host2, cfg, env);
2625
- await ensureImage(host2, cfg, version);
2859
+ await loginRegistry(host, cfg, env);
2860
+ await ensureImage(host, cfg, version);
2626
2861
  } else if (!opts.reuse) {
2627
- await uploadSource(host2, cfg, version);
2628
- await buildRelease(host2, cfg, version, env);
2862
+ await uploadSource(host, cfg, version);
2863
+ await buildRelease(host, cfg, version, env);
2629
2864
  } else {
2630
2865
  const dir = releaseDir(cfg, version);
2631
- if (!await host2.test(`[ -d ${JSON.stringify(dir)} ]`)) {
2632
- throw new EpdError(`${host2.name}: release ${version} is not on this server`, "Deploy it normally first.");
2866
+ if (!await host.test(`[ -d ${JSON.stringify(dir)} ]`)) {
2867
+ throw new EpdError(`${host.name}: release ${version} is not on this server`, "Deploy it normally first.");
2633
2868
  }
2634
2869
  }
2635
- const state = await readState(host2, cfg) ?? emptyState(cfg);
2870
+ const state = await readState(host, cfg) ?? emptyState(cfg);
2636
2871
  const previous = new Map;
2637
- const started2 = [];
2872
+ const started = [];
2638
2873
  try {
2639
2874
  for (const svc of services) {
2640
2875
  const current = state.services[svc.name]?.slot;
2641
2876
  if (current)
2642
2877
  previous.set(svc.name, current);
2643
2878
  const slot = current ? otherSlot(current) : "blue";
2644
- log.host(host2.name, `${svc.name}: starting ${svc.replicas} replica(s) on ${slot}`);
2879
+ log.host(host.name, `${svc.name}: starting ${svc.replicas} replica(s) on ${slot}`);
2645
2880
  let probes = [];
2646
2881
  if (cfg.mode === "docker") {
2647
- const envFile = await writeServiceEnv(host2, cfg, svc, env);
2648
- const names = await startSlot(host2, cfg, svc, slot, version, envFile);
2649
- started2.push({ svc, slot });
2650
- const ips = usesHostPorts(cfg) ? {} : await containerIps(host2, cfg, names);
2882
+ const envFile = await writeServiceEnv(host, cfg, svc, env);
2883
+ const names = await startSlot(host, cfg, svc, slot, version, envFile);
2884
+ started.push({ svc, slot });
2885
+ const ips = usesHostPorts(cfg) ? {} : await containerIps(host, cfg, names);
2651
2886
  probes = names.map((name, i) => ({
2652
2887
  label: name,
2653
2888
  address: usesHostPorts(cfg) ? "127.0.0.1" : ips[name] ?? "",
@@ -2655,10 +2890,10 @@ async function deployToHost(d) {
2655
2890
  }));
2656
2891
  const noIp = probes.find((p) => !p.address);
2657
2892
  if (noIp)
2658
- throw new EpdError(`${host2.name}: ${noIp.label} did not get an IP on the ${cfg.proxy.network} network`, "Check `epd logs`.");
2893
+ throw new EpdError(`${host.name}: ${noIp.label} did not get an IP on the ${cfg.proxy.network} network`, "Check `epd logs`.");
2659
2894
  } else {
2660
- await startSlot2(host2, cfg, svc, slot, version, env);
2661
- started2.push({ svc, slot });
2895
+ await startSlot2(host, cfg, svc, slot, version, env);
2896
+ started.push({ svc, slot });
2662
2897
  probes = Array.from({ length: svc.replicas }, (_, i) => ({
2663
2898
  label: `${svc.name}#${i}`,
2664
2899
  address: "127.0.0.1",
@@ -2666,52 +2901,52 @@ async function deployToHost(d) {
2666
2901
  }));
2667
2902
  }
2668
2903
  if (!opts.skipHealth && svc.proxied) {
2669
- log.host(host2.name, `${svc.name}: waiting for health check${svc.health.path ? ` ${svc.health.path}` : " (tcp)"}`);
2670
- await waitHealthy(host2, probes, svc.health);
2671
- log.host(host2.name, `${svc.name}: healthy`);
2904
+ log.host(host.name, `${svc.name}: waiting for health check${svc.health.path ? ` ${svc.health.path}` : " (tcp)"}`);
2905
+ await waitHealthy(host, probes, svc.health);
2906
+ log.host(host.name, `${svc.name}: healthy`);
2672
2907
  } else if (!opts.skipHealth) {
2673
- await confirmUp(host2, cfg, svc, slot);
2908
+ await confirmUp(host, cfg, svc, slot);
2674
2909
  }
2675
- live.get(host2.name)?.set(svc.name, slot) ?? live.set(host2.name, new Map([[svc.name, slot]]));
2910
+ live.get(host.name)?.set(svc.name, slot) ?? live.set(host.name, new Map([[svc.name, slot]]));
2676
2911
  state.services[svc.name] = {
2677
2912
  slot,
2678
2913
  replicas: svc.replicas,
2679
2914
  version,
2680
- endpoints: endpointsFor(cfg, svc, slot, host2.name).map((e) => e.url)
2915
+ endpoints: endpointsFor(cfg, svc, slot, host.name).map((e) => e.url)
2681
2916
  };
2682
2917
  }
2683
2918
  const hasSvcRoutes = services.some((s) => s.routes.length);
2684
- const hasAccRoutes = cfg.accessories.some((a) => a.routes.length && (cfg.proxy.crossHost || a.host === host2.name));
2919
+ const hasAccRoutes = cfg.accessories.some((a) => a.routes.length && (cfg.proxy.crossHost || a.host === host.name));
2685
2920
  if (cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
2686
- await writeRoutes(host2, cfg, buildEndpoints(cfg, host2.name, live), buildAccessoryEndpoints(cfg, host2.name));
2687
- log.host(host2.name, "routes updated");
2921
+ await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
2922
+ log.host(host.name, "routes updated");
2688
2923
  }
2689
2924
  for (const svc of services) {
2690
2925
  const old = previous.get(svc.name);
2691
2926
  if (!old)
2692
2927
  continue;
2693
2928
  const drain = Math.max(svc.drain, cfg.proxy.reloadWait + 2);
2694
- log.host(host2.name, `${svc.name}: retiring ${old} (${drain}s drain, in the background)`);
2929
+ log.host(host.name, `${svc.name}: retiring ${old} (${drain}s drain, in the background)`);
2695
2930
  if (cfg.mode === "docker")
2696
- await stopSlot(host2, cfg, svc, old, { drain, remove: true, detach: true });
2931
+ await stopSlot(host, cfg, svc, old, { drain, remove: true, detach: true });
2697
2932
  else
2698
- await stopSlot2(host2, cfg, svc, old, drain, { detach: true });
2933
+ await stopSlot2(host, cfg, svc, old, drain, { detach: true });
2699
2934
  }
2700
- await writeState(host2, cfg, recordDeploy(state, version, process.env.USER ?? "epd", cfg.keepReleases));
2935
+ await writeState(host, cfg, recordDeploy(state, version, process.env.USER ?? "epd", cfg.keepReleases));
2701
2936
  if (cfg.mode === "docker") {
2702
- await pruneImages(host2, cfg, cfg.keepReleases, [version, ...state.history.slice(0, 2).map((h) => h.version)]);
2937
+ await pruneImages(host, cfg, cfg.keepReleases, [version, ...state.history.slice(0, 2).map((h) => h.version)]);
2703
2938
  } else {
2704
- await finalizeRelease(host2, cfg, version);
2939
+ await finalizeRelease(host, cfg, version);
2705
2940
  }
2706
- log.host(host2.name, c.green("done"));
2941
+ log.host(host.name, c.green("done"));
2707
2942
  } catch (error) {
2708
- log.error(`${host2.name}: deploy failed, rolling back this host`);
2709
- for (const { svc, slot } of started2) {
2943
+ log.error(`${host.name}: deploy failed, rolling back this host`);
2944
+ for (const { svc, slot } of started) {
2710
2945
  try {
2711
2946
  if (cfg.mode === "docker")
2712
- await stopSlot(host2, cfg, svc, slot, { drain: 0, remove: true });
2947
+ await stopSlot(host, cfg, svc, slot, { drain: 0, remove: true });
2713
2948
  else
2714
- await stopSlot2(host2, cfg, svc, slot, 0);
2949
+ await stopSlot2(host, cfg, svc, slot, 0);
2715
2950
  } catch {}
2716
2951
  }
2717
2952
  if (!d.opts.skipHooks && cfg.hooks.onFailure) {
@@ -2722,18 +2957,18 @@ async function deployToHost(d) {
2722
2957
  throw error;
2723
2958
  }
2724
2959
  }
2725
- async function confirmUp(host2, cfg, svc, slot) {
2960
+ async function confirmUp(host, cfg, svc, slot) {
2726
2961
  if (cfg.mode === "docker") {
2727
- const containers = await listContainers(host2, cfg);
2962
+ const containers = await listContainers(host, cfg);
2728
2963
  const bad = containers.filter((ct) => ct.service === svc.name && ct.slot === slot && !ct.running);
2729
2964
  if (bad.length) {
2730
- throw new EpdError(`${host2.name}: ${bad.map((b) => b.name).join(", ")} exited right after starting`, `Run: epd logs --service ${svc.name}`);
2965
+ throw new EpdError(`${host.name}: ${bad.map((b) => b.name).join(", ")} exited right after starting`, `Run: epd logs --service ${svc.name}`);
2731
2966
  }
2732
2967
  } else {
2733
- const procs = await listProcesses(host2, cfg);
2968
+ const procs = await listProcesses(host, cfg);
2734
2969
  const bad = procs.filter((p) => p.name.includes(`-${svc.name}-${slot}-`) && p.status !== "online");
2735
2970
  if (bad.length) {
2736
- throw new EpdError(`${host2.name}: ${bad.map((b) => b.name).join(", ")} is ${bad[0].status}`, `Run: epd logs --service ${svc.name}`);
2971
+ throw new EpdError(`${host.name}: ${bad.map((b) => b.name).join(", ")} is ${bad[0].status}`, `Run: epd logs --service ${svc.name}`);
2737
2972
  }
2738
2973
  }
2739
2974
  }
@@ -2874,22 +3109,29 @@ Options
2874
3109
  log.step(`Preparing ${hosts.length} host(s) for ${c.bold(cfg.name)}`);
2875
3110
  if (cfg.mode === "docker")
2876
3111
  await requireLocal("docker", "Install Docker Desktop or the docker engine to build images.");
2877
- await pool(hosts, 4, async (host2) => {
2878
- await host2.ping();
2879
- log.host(host2.name, "reachable");
3112
+ await pool(hosts, 4, async (host) => {
3113
+ await host.ping();
3114
+ log.host(host.name, "reachable");
2880
3115
  if (cfg.mode === "docker") {
2881
- await installDocker(host2);
2882
- await ensureNetwork(host2, cfg);
3116
+ await installDocker(host);
3117
+ await ensureNetwork(host, cfg);
2883
3118
  } else {
2884
- await installSystemPackages(host2);
2885
- await installProcessRuntime(host2, cfg);
3119
+ await installSystemPackages(host);
3120
+ await installProcessRuntime(host, cfg);
2886
3121
  }
2887
- await ensureDirs(host2, cfg);
2888
- await reservePorts(host2, cfg);
3122
+ await ensureDirs(host, cfg);
3123
+ await reservePorts(host, cfg);
2889
3124
  });
2890
3125
  if (cfg.proxy.enabled && proxyHosts(cfg).length) {
2891
3126
  log.step("Starting the proxy");
2892
- await pool(proxyHosts(cfg).filter((h) => names.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host2) => ensureProxy(host2, cfg, { secrets: loaded.env, force: true }));
3127
+ await pool(proxyHosts(cfg).filter((h) => names.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: loaded.env, force: true }));
3128
+ }
3129
+ if (cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
3130
+ try {
3131
+ await syncDns(cfg, { log: true });
3132
+ } catch (e) {
3133
+ log.warn(`Cloudflare DNS sync: ${e instanceof Error ? e.message : String(e)}`);
3134
+ }
2893
3135
  }
2894
3136
  log.ok("servers are ready");
2895
3137
  if (ctx.values["skip-deploy"]) {
@@ -3250,12 +3492,12 @@ Examples
3250
3492
  const known = cfg.accessories.map((a) => a.name);
3251
3493
  throw new EpdError(`no such accessory "${accName}"`, known.length ? `Known: ${known.join(", ")}` : "No accessories configured.");
3252
3494
  }
3253
- const host3 = host(acc.host, cfg.ssh);
3495
+ const host2 = host(acc.host, cfg.ssh);
3254
3496
  const container = accessoryContainer(cfg.name, acc.name);
3255
- log.info(`${host3.name}: ${container} $ ${command}`);
3256
- const code2 = await host3.interactive(`docker exec ${ctx.values.interactive ? "-it" : ""} ${shq(container)} ${cmdArgs}`);
3257
- if (code2 !== 0)
3258
- process.exitCode = code2;
3497
+ log.info(`${host2.name}: ${container} $ ${command}`);
3498
+ const code = await host2.interactive(`docker exec ${ctx.values.interactive ? "-it" : ""} ${shq(container)} ${cmdArgs}`);
3499
+ if (code !== 0)
3500
+ process.exitCode = code;
3259
3501
  return;
3260
3502
  }
3261
3503
  const host2 = await pickHost(ctx, cfg);
@@ -3270,18 +3512,18 @@ Examples
3270
3512
  const dir = `${paths(cfg).current}`;
3271
3513
  const script = `cd ${shq(dir)} && ${pathPrelude(cfg)} && set -a && . ${shq(paths(cfg).envFile)} && set +a && ${command}`;
3272
3514
  log.info(`${host2.name}: ${command}`);
3273
- const code2 = await host2.interactive(script, { sudo: false });
3274
- if (code2 !== 0)
3275
- process.exitCode = code2;
3515
+ const code = await host2.interactive(script, { sudo: false });
3516
+ if (code !== 0)
3517
+ process.exitCode = code;
3276
3518
  return;
3277
3519
  }
3278
3520
  if (ctx.values.reuse) {
3279
3521
  const slot = state.services[svc.name]?.slot;
3280
3522
  const container = `epd-${cfg.name}-${svc.name}-${slot}-0`;
3281
3523
  log.info(`${host2.name}: ${container} $ ${command}`);
3282
- const code2 = await host2.interactive(`docker exec ${ctx.values.interactive ? "-it" : ""} ${shq(container)} ${cmdArgs}`);
3283
- if (code2 !== 0)
3284
- process.exitCode = code2;
3524
+ const code = await host2.interactive(`docker exec ${ctx.values.interactive ? "-it" : ""} ${shq(container)} ${cmdArgs}`);
3525
+ if (code !== 0)
3526
+ process.exitCode = code;
3285
3527
  return;
3286
3528
  }
3287
3529
  const envFile = `${paths(cfg).app}/env.${svc.name}`;
@@ -3360,12 +3602,12 @@ Options
3360
3602
  const hosts = names.map((h) => host(h, cfg.ssh));
3361
3603
  switch (sub) {
3362
3604
  case "status": {
3363
- for (const host2 of hosts) {
3364
- const s = await proxyState(host2, cfg);
3365
- const listening = cfg.mode === "docker" ? await host2.capture(`docker port ${PROXY_CONTAINER} 2>/dev/null | sort -u || true`, { allowFailure: true }) : Object.entries(cfg.proxy.entrypoints).map(([n, p]) => `${n} -> :${p}`).join(`
3605
+ for (const host of hosts) {
3606
+ const s = await proxyState(host, cfg);
3607
+ const listening = cfg.mode === "docker" ? await host.capture(`docker port ${PROXY_CONTAINER} 2>/dev/null | sort -u || true`, { allowFailure: true }) : Object.entries(cfg.proxy.entrypoints).map(([n, p]) => `${n} -> :${p}`).join(`
3366
3608
  `);
3367
- const apps = await host2.capture(`ls -1 ${shq(paths(cfg).proxyDynamicDir)} 2>/dev/null | sed 's/\\.yml$//' || true`, { allowFailure: true });
3368
- log.plain(`${c.magenta(host2.name)} ${s.running ? c.green("running") : c.red(s.status)} ${c.gray(s.image)}`);
3609
+ const apps = await host.capture(`ls -1 ${shq(paths(cfg).proxyDynamicDir)} 2>/dev/null | sed 's/\\.yml$//' || true`, { allowFailure: true });
3610
+ log.plain(`${c.magenta(host.name)} ${s.running ? c.green("running") : c.red(s.status)} ${c.gray(s.image)}`);
3369
3611
  if (listening)
3370
3612
  log.plain(listening.split(`
3371
3613
  `).map((l) => ` ${l}`).join(`
@@ -3377,8 +3619,8 @@ Options
3377
3619
  return;
3378
3620
  }
3379
3621
  case "reboot": {
3380
- await pool(hosts, 4, async (host2) => {
3381
- await ensureProxy(host2, cfg, { force: true, secrets: loaded.env });
3622
+ await pool(hosts, 4, async (host) => {
3623
+ await ensureProxy(host, cfg, { force: true, secrets: loaded.env });
3382
3624
  });
3383
3625
  log.ok("proxy restarted");
3384
3626
  return;
@@ -3386,40 +3628,40 @@ Options
3386
3628
  case "logs": {
3387
3629
  const lines = String(ctx.values.lines ?? "100");
3388
3630
  const follow = Boolean(ctx.values.follow);
3389
- for (const host2 of hosts) {
3631
+ for (const host of hosts) {
3390
3632
  const cmd = cfg.mode === "docker" ? `docker logs ${follow ? "-f " : ""}--tail ${lines} ${PROXY_CONTAINER} 2>&1` : `${pathPrelude(cfg)} pm2 logs ${PROXY_PROCESS} --lines ${lines}${follow ? "" : " --nostream"} 2>&1`;
3391
3633
  if (follow) {
3392
- log.info(`following proxy on ${host2.name} \u2014 Ctrl-C to stop`);
3393
- await host2.interactive(cmd, { sudo: cfg.mode === "docker" ? undefined : false });
3634
+ log.info(`following proxy on ${host.name} \u2014 Ctrl-C to stop`);
3635
+ await host.interactive(cmd, { sudo: cfg.mode === "docker" ? undefined : false });
3394
3636
  } else {
3395
- const out = await host2.exec(`${cmd} || true`, { allowFailure: true, sudo: cfg.mode === "docker" ? undefined : false });
3396
- log.plain(c.magenta(host2.name));
3637
+ const out = await host.exec(`${cmd} || true`, { allowFailure: true, sudo: cfg.mode === "docker" ? undefined : false });
3638
+ log.plain(c.magenta(host.name));
3397
3639
  log.plain(out.stdout || c.gray(" no output"));
3398
3640
  }
3399
3641
  }
3400
3642
  return;
3401
3643
  }
3402
3644
  case "routes": {
3403
- for (const host2 of hosts) {
3404
- const doc = await host2.readFile(paths(cfg).proxyDynamic);
3405
- log.plain(c.magenta(host2.name));
3645
+ for (const host of hosts) {
3646
+ const doc = await host.readFile(paths(cfg).proxyDynamic);
3647
+ log.plain(c.magenta(host.name));
3406
3648
  log.plain(doc ?? c.gray(" no routes written yet"));
3407
3649
  }
3408
3650
  return;
3409
3651
  }
3410
3652
  case "remove": {
3411
- for (const host2 of hosts) {
3412
- await removeRoutes(host2, cfg);
3413
- const left = await host2.capture(`ls -1 ${shq(paths(cfg).proxyDynamicDir)}/*.yml 2>/dev/null | wc -l`, { allowFailure: true });
3653
+ for (const host of hosts) {
3654
+ await removeRoutes(host, cfg);
3655
+ const left = await host.capture(`ls -1 ${shq(paths(cfg).proxyDynamicDir)}/*.yml 2>/dev/null | wc -l`, { allowFailure: true });
3414
3656
  if (Number(left.trim()) === 0) {
3415
3657
  if (cfg.mode === "docker") {
3416
- await host2.exec(`docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true`, { allowFailure: true });
3658
+ await host.exec(`docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true`, { allowFailure: true });
3417
3659
  } else {
3418
- await host2.exec(`${pathPrelude(cfg)} pm2 delete ${PROXY_PROCESS} >/dev/null 2>&1 || true`, { allowFailure: true, sudo: false });
3660
+ await host.exec(`${pathPrelude(cfg)} pm2 delete ${PROXY_PROCESS} >/dev/null 2>&1 || true`, { allowFailure: true, sudo: false });
3419
3661
  }
3420
- log.host(host2.name, "routes removed, proxy stopped (no apps left)");
3662
+ log.host(host.name, "routes removed, proxy stopped (no apps left)");
3421
3663
  } else {
3422
- log.host(host2.name, `routes removed, proxy still serving ${left.trim()} other app(s)`);
3664
+ log.host(host.name, `routes removed, proxy still serving ${left.trim()} other app(s)`);
3423
3665
  }
3424
3666
  }
3425
3667
  return;
@@ -3560,8 +3802,8 @@ If a deploy was killed halfway, release it by hand.`,
3560
3802
  }
3561
3803
  if (sub !== "status")
3562
3804
  throw new EpdError(`unknown subcommand "${sub}"`, "Try: status, release");
3563
- for (const { host: host2, info } of await DeployLock.status(cfg, hosts)) {
3564
- log.plain(info ? `${c.magenta(host2)} ${c.yellow("locked")} by ${info.by} ${c.gray(`${info.at} \u2014 ${info.what}`)}` : `${c.magenta(host2)} ${c.green("free")}`);
3805
+ for (const { host, info } of await DeployLock.status(cfg, hosts)) {
3806
+ log.plain(info ? `${c.magenta(host)} ${c.yellow("locked")} by ${info.by} ${c.gray(`${info.at} \u2014 ${info.what}`)}` : `${c.magenta(host)} ${c.green("free")}`);
3565
3807
  }
3566
3808
  }
3567
3809
  };
@@ -3593,16 +3835,16 @@ Options
3593
3835
  return;
3594
3836
  }
3595
3837
  }
3596
- await pool(names.map((h) => host(h, cfg.ssh)), 4, async (host2) => {
3597
- await removeRoutes(host2, cfg);
3838
+ await pool(names.map((h) => host(h, cfg.ssh)), 4, async (host) => {
3839
+ await removeRoutes(host, cfg);
3598
3840
  if (cfg.mode === "docker")
3599
- await removeApp(host2, cfg);
3841
+ await removeApp(host, cfg);
3600
3842
  else
3601
- await removeApp2(host2, cfg);
3843
+ await removeApp2(host, cfg);
3602
3844
  if (!ctx.values["keep-data"]) {
3603
- await host2.exec(`rm -rf ${shq(paths(cfg).app)} ${shq(`${paths(cfg).portsDir}/${cfg.portBase}`)}`, { allowFailure: true });
3845
+ await host.exec(`rm -rf ${shq(paths(cfg).app)} ${shq(`${paths(cfg).portsDir}/${cfg.portBase}`)}`, { allowFailure: true });
3604
3846
  }
3605
- log.host(host2.name, "removed");
3847
+ log.host(host.name, "removed");
3606
3848
  });
3607
3849
  log.ok(`${cfg.name} removed from ${names.length} host(s)`);
3608
3850
  log.info(`the shared proxy is still running \u2014 ${c.cyan("epd proxy remove")} stops it if nothing else uses it`);
@@ -3736,6 +3978,110 @@ Options
3736
3978
  }
3737
3979
  };
3738
3980
 
3981
+ // src/commands/cloudflare.ts
3982
+ var cloudflare = {
3983
+ name: "cloudflare",
3984
+ aliases: ["cf"],
3985
+ summary: "Manage Cloudflare DNS records for application domains",
3986
+ options: {
3987
+ "dry-run": { type: "boolean" },
3988
+ proxied: { type: "boolean" },
3989
+ "no-proxied": { type: "boolean" }
3990
+ },
3991
+ help: () => `${c.bold("epd cloudflare")} \u2014 Cloudflare automation and DNS management
3992
+
3993
+ Commands
3994
+ epd cloudflare dns [sync] Sync domain A/AAAA records to target server IPs
3995
+ epd cloudflare dns status Show current Cloudflare DNS status for app domains
3996
+
3997
+ Options
3998
+ --dry-run Preview DNS changes without applying them
3999
+ --proxied Force proxied mode (orange cloud)
4000
+ --no-proxied Force DNS-only mode (gray cloud)
4001
+ -c, --config <file> Path to epd.yml
4002
+ -d, --destination <d> Overlay epd.<d>.yml
4003
+
4004
+ Environment
4005
+ CLOUDFLARE_API_TOKEN Cloudflare API Token with Zone.DNS edit permissions
4006
+ CLOUDFLARE_ZONE_ID Optional Zone ID override`,
4007
+ async run(ctx) {
4008
+ const loaded = ctx.load();
4009
+ const cfg = loaded.config;
4010
+ const sub = ctx.positionals[0] || "dns";
4011
+ const action = ctx.positionals[1] || (sub === "status" ? "status" : "sync");
4012
+ const token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
4013
+ if (!token) {
4014
+ throw new EpdError("Cloudflare API token is missing", `Set CLOUDFLARE_API_TOKEN in your environment or add it to epd.yml:
4015
+ ` + " cloudflare:\n api_token: ${CLOUDFLARE_API_TOKEN}");
4016
+ }
4017
+ const client = new CloudflareClient(token);
4018
+ const domains = getRouteDomains(cfg);
4019
+ if (!domains.length) {
4020
+ log.warn("No domains found in service routes. Add domains to your routes or configure cloudflare.domains in epd.yml.");
4021
+ return;
4022
+ }
4023
+ const routedHosts = new Set;
4024
+ for (const svc of cfg.services) {
4025
+ if (svc.routes.length) {
4026
+ for (const h of svc.hosts)
4027
+ routedHosts.add(h);
4028
+ }
4029
+ }
4030
+ const ips = new Set;
4031
+ for (const h of routedHosts) {
4032
+ const resolved = await resolveHostIps(h);
4033
+ for (const ip of resolved)
4034
+ ips.add(ip);
4035
+ }
4036
+ if (sub === "status" || action === "status") {
4037
+ log.step(`Checking Cloudflare DNS status for ${c.bold(cfg.name)} (${domains.length} domain(s))`);
4038
+ console.log(`
4039
+ ${c.bold("Configured Server IPs:")} ${[...ips].join(", ") || "none"}`);
4040
+ for (const domain of domains) {
4041
+ try {
4042
+ const zone = await client.findZoneForDomain(domain, cfg.cloudflare?.zoneId);
4043
+ const records = await client.listDnsRecords(zone.id, domain);
4044
+ console.log(`
4045
+ ${c.bold(domain)} (Zone: ${zone.name} [${zone.id}])`);
4046
+ if (!records.length) {
4047
+ console.log(` ${c.yellow("! No DNS records found for this domain")}`);
4048
+ } else {
4049
+ for (const r of records) {
4050
+ const matchesServer = ips.has(r.content);
4051
+ const statusTag = matchesServer ? c.green("\u2713 points to server") : c.yellow("! points elsewhere");
4052
+ const proxyTag = r.proxied ? c.cyan("[proxied (orange cloud)]") : c.gray("[DNS only]");
4053
+ console.log(` \u2022 ${r.type.padEnd(4)} ${r.content.padEnd(20)} ${proxyTag.padEnd(24)} ${statusTag}`);
4054
+ }
4055
+ }
4056
+ } catch (e) {
4057
+ console.log(`
4058
+ ${c.bold(domain)}: ${c.red(e instanceof Error ? e.message : String(e))}`);
4059
+ }
4060
+ }
4061
+ console.log("");
4062
+ return;
4063
+ }
4064
+ let proxied = undefined;
4065
+ if (ctx.values.proxied === true)
4066
+ proxied = true;
4067
+ if (ctx.values["no-proxied"] === true || ctx.values.proxied === false)
4068
+ proxied = false;
4069
+ const dryRun = Boolean(ctx.values["dry-run"]);
4070
+ if (dryRun)
4071
+ log.step("Previewing Cloudflare DNS changes (dry-run)");
4072
+ const results = await syncDns(cfg, {
4073
+ dryRun,
4074
+ log: true,
4075
+ client,
4076
+ proxied
4077
+ });
4078
+ const created = results.filter((r) => r.action === "created").length;
4079
+ const updated = results.filter((r) => r.action === "updated").length;
4080
+ const unchanged = results.filter((r) => r.action === "unchanged").length;
4081
+ log.ok(`DNS sync finished: ${created} created, ${updated} updated, ${unchanged} unchanged`);
4082
+ }
4083
+ };
4084
+
3739
4085
  // src/commands/index.ts
3740
4086
  var commands = [
3741
4087
  init,
@@ -3751,11 +4097,12 @@ var commands = [
3751
4097
  config,
3752
4098
  lock,
3753
4099
  remove,
3754
- dockerCommand
4100
+ dockerCommand,
4101
+ cloudflare
3755
4102
  ];
3756
4103
 
3757
4104
  // src/cli.ts
3758
- var VERSION = "0.1.0";
4105
+ var VERSION = "0.2.0";
3759
4106
  var USAGE = `${c.bold("epd")} \u2014 Easy Project Deployer ${c.gray(`v${VERSION}`)}
3760
4107
 
3761
4108
  ${c.bold("Usage")}