@fabioplunser/epd 0.4.0 → 0.5.1

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/README.md CHANGED
@@ -139,14 +139,15 @@ build:
139
139
  npm_token: NPM_TOKEN
140
140
 
141
141
  ssh:
142
- user: root
142
+ user: root # default login; a non-root user needs passwordless sudo
143
143
  port: 22
144
144
  key: ~/.ssh/id_ed25519
145
145
  proxy_jump: bastion.example.com
146
146
 
147
147
  servers:
148
148
  web:
149
- hosts: [203.0.113.10, 203.0.113.11]
149
+ # "user@host" overrides ssh.user for that one server.
150
+ hosts: [203.0.113.10, deploy@203.0.113.11]
150
151
  replicas: 2 # per host, load balanced by the proxy
151
152
  port: 3000 # the port your app listens on
152
153
  domains: [example.com, www.example.com]
package/dist/cli.js CHANGED
@@ -1,4 +1,6 @@
1
1
  // @bun
2
+ var __require = import.meta.require;
3
+
2
4
  // src/cli.ts
3
5
  import { parseArgs } from "util";
4
6
 
@@ -203,6 +205,22 @@ function deepMerge(base, overlay) {
203
205
  function fail(path, msg, hint) {
204
206
  throw new EpdError(`${path}: ${msg}`, hint);
205
207
  }
208
+ function takeHostUser(entry, path, users) {
209
+ const at = entry.lastIndexOf("@");
210
+ if (at < 0)
211
+ return entry;
212
+ const user = entry.slice(0, at);
213
+ const host = entry.slice(at + 1);
214
+ if (!user || !host) {
215
+ fail(path, `"${entry}" is not a valid host`, 'Write it as "user@host", e.g. "deploy@10.0.0.1".');
216
+ }
217
+ const seen = users[host];
218
+ if (seen && seen !== user) {
219
+ fail(path, `host ${host} is listed as both ${seen}@${host} and ${user}@${host}`, "Use one ssh user per host.");
220
+ }
221
+ users[host] = user;
222
+ return host;
223
+ }
206
224
  function asString(v, path, dflt) {
207
225
  if (v === undefined || v === null) {
208
226
  if (dflt !== undefined)
@@ -521,6 +539,7 @@ function normalize(raw, configPath, root, destination) {
521
539
  delay: 1
522
540
  };
523
541
  const rootHealth = parseHealth(raw.healthcheck ?? raw.health, "epd.yml.healthcheck", defaultHealth);
542
+ const hostUsers = {};
524
543
  let servicesRaw = raw.services ?? raw.servers;
525
544
  const inlineKeys = ["hosts", "host", "replicas", "port", "domain", "domains", "routes", "command", "labels", "volumes", "drain", "stop_timeout", "docker_options"];
526
545
  const hasInline = inlineKeys.some((k) => raw[k] !== undefined);
@@ -588,7 +607,10 @@ function normalize(raw, configPath, root, destination) {
588
607
  fail(`${p}.hetzner`, "expected a server name string or a mapping");
589
608
  }
590
609
  }
591
- const hosts = [...asList(o.host, `${p}.host`), ...asList(o.hosts, `${p}.hosts`)];
610
+ const hosts = [
611
+ ...asList(o.host, `${p}.host`).map((h) => takeHostUser(h, `${p}.host`, hostUsers)),
612
+ ...asList(o.hosts, `${p}.hosts`).map((h) => takeHostUser(h, `${p}.hosts`, hostUsers))
613
+ ];
592
614
  if (!hosts.length && !svcHetzner)
593
615
  fail(`${p}.hosts`, "at least one host is required");
594
616
  const port = asNumber(o.port, `${p}.port`, asNumber(raw.port, "epd.yml.port", 3000));
@@ -636,7 +658,7 @@ function normalize(raw, configPath, root, destination) {
636
658
  return {
637
659
  name: accName,
638
660
  image: asString(o.image, `${p}.image`),
639
- host: asString(o.host, `${p}.host`),
661
+ host: takeHostUser(asString(o.host, `${p}.host`), `${p}.host`, hostUsers),
640
662
  env: asDict(accEnvRaw?.clear ?? (accEnvRaw && !("clear" in accEnvRaw) && !("secret" in accEnvRaw) ? accEnvRaw : {}), `${p}.env`),
641
663
  secrets: asList(accEnvRaw?.secret, `${p}.env.secret`),
642
664
  volumes: asList(o.volumes, `${p}.volumes`),
@@ -775,6 +797,7 @@ function normalize(raw, configPath, root, destination) {
775
797
  },
776
798
  ssh: {
777
799
  user: asString(sshRaw.user, "epd.yml.ssh.user", "root"),
800
+ hostUsers,
778
801
  port: asNumber(sshRaw.port, "epd.yml.ssh.port", 22),
779
802
  key: sshRaw.key ? expandHome(asString(sshRaw.key, "epd.yml.ssh.key")) : undefined,
780
803
  options: asList(sshRaw.options, "epd.yml.ssh.options"),
@@ -1566,6 +1589,15 @@ dns:
1566
1589
  proxied: true
1567
1590
  auto_sync: true
1568
1591
  ` : "";
1592
+ const sshBlock = `
1593
+ # How epd reaches your servers: plain ssh with your own key, no agent installed.
1594
+ # A non-root user needs passwordless sudo (epd escalates with "sudo -n").
1595
+ ssh:
1596
+ user: ${o.sshUser}
1597
+ # port: 22
1598
+ # key: ~/.ssh/id_ed25519
1599
+ # proxy_jump: bastion.example.com
1600
+ `;
1569
1601
  const hetznerBlock = o.useHetzner ? `
1570
1602
  # Hetzner Cloud integration (api_token resolved from ~/.config/epd/auth.json or HETZNER_API_TOKEN)
1571
1603
  hetzner:
@@ -1586,8 +1618,9 @@ mode: ${o.mode}
1586
1618
  ${o.mode === "docker" ? `
1587
1619
  # Image name. Tagged with the git sha of every deploy.
1588
1620
  image: ${o.image ?? o.name}
1589
- ${registry}` : ""}${processBlock}${dnsBlock}${hetznerBlock}
1621
+ ${registry}` : ""}${processBlock}${sshBlock}${dnsBlock}${hetznerBlock}
1590
1622
  # One entry per group of processes. Add more (worker, cron, \u2026) as you need them.
1623
+ # A host may carry its own login \u2014 "deploy@203.0.113.10" overrides ssh.user.
1591
1624
  servers:
1592
1625
  web:
1593
1626
  hosts: ${list(o.hosts)}
@@ -1707,6 +1740,7 @@ var init = {
1707
1740
  domain: { type: "string", multiple: true },
1708
1741
  port: { type: "string" },
1709
1742
  email: { type: "string" },
1743
+ "ssh-user": { type: "string" },
1710
1744
  replicas: { type: "string" },
1711
1745
  force: { type: "boolean" },
1712
1746
  dockerfile: { type: "boolean" },
@@ -1725,6 +1759,7 @@ Options
1725
1759
  --domain <domain> Domain to serve (repeatable)
1726
1760
  --port <port> Port your app listens on
1727
1761
  --email <email> Contact address for Let's Encrypt
1762
+ --ssh-user <user> SSH login for the servers (default root)
1728
1763
  --replicas <n> Replicas per host (default 1)
1729
1764
  --dockerfile Also write a starter Dockerfile
1730
1765
  --ci Also generate a GitHub Actions deploy workflow (.github/workflows/deploy.yml)
@@ -1833,6 +1868,7 @@ Options
1833
1868
  const domains = (ctx.values.domain ?? []).length ? ctx.values.domain : (await ask("Domains to serve (comma separated)", defaultDomain)).split(",").map((s) => s.trim()).filter(Boolean);
1834
1869
  const port = Number(ctx.values.port ?? await ask("Port your app listens on", String(detected.port)));
1835
1870
  const email = ctx.values.email ?? await ask("Email for Let's Encrypt", "");
1871
+ const sshUser = ctx.values["ssh-user"] ?? await ask("SSH user for the server(s)", "root");
1836
1872
  const replicas = Number(ctx.values.replicas ?? 1);
1837
1873
  let registryUser;
1838
1874
  let registryServer;
@@ -1845,6 +1881,7 @@ Options
1845
1881
  writeFileSync2(target, template({
1846
1882
  name,
1847
1883
  mode,
1884
+ sshUser: sshUser || "root",
1848
1885
  hosts,
1849
1886
  domains,
1850
1887
  port,
@@ -2191,15 +2228,20 @@ import { tmpdir } from "os";
2191
2228
  import { join as join4 } from "path";
2192
2229
  var controlDir = join4(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2193
2230
  mkdirSync3(controlDir, { recursive: true, mode: 448 });
2231
+ function sshUserFor(name, cfg) {
2232
+ return cfg.hostUsers?.[name] ?? cfg.user;
2233
+ }
2194
2234
 
2195
2235
  class Host {
2196
2236
  name;
2237
+ user;
2197
2238
  cfg;
2198
2239
  sudo;
2199
2240
  constructor(name, cfg) {
2200
2241
  this.name = name;
2201
- this.cfg = cfg;
2202
- this.sudo = cfg.user !== "root";
2242
+ this.user = sshUserFor(name, cfg);
2243
+ this.cfg = this.user === cfg.user ? cfg : { ...cfg, user: this.user };
2244
+ this.sudo = this.user !== "root";
2203
2245
  }
2204
2246
  sshOptions() {
2205
2247
  const socket = join4(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
@@ -2309,7 +2351,7 @@ function dirnameOf(p) {
2309
2351
  }
2310
2352
  var cache = new Map;
2311
2353
  function host(name, cfg) {
2312
- const key = `${cfg.user}@${name}:${cfg.port}`;
2354
+ const key = `${sshUserFor(name, cfg)}@${name}:${cfg.port}`;
2313
2355
  let h = cache.get(key);
2314
2356
  if (!h) {
2315
2357
  h = new Host(name, cfg);
@@ -2426,7 +2468,7 @@ function staticConfig(d, where = CONTAINER_PATHS) {
2426
2468
  global: { checkNewVersion: false, sendAnonymousUsage: false },
2427
2469
  log: { level: d.logLevel },
2428
2470
  ...d.accessLog ? { accessLog: {} } : {},
2429
- ...d.dashboard ? { api: { dashboard: true } } : {},
2471
+ ...d.dashboard ? { api: { dashboard: true, insecure: true } } : {},
2430
2472
  entryPoints,
2431
2473
  providers: {
2432
2474
  file: { directory: where.dynamicDir, watch: true },
@@ -2595,6 +2637,8 @@ function containerSpec(d, cfg, staticHash) {
2595
2637
  ];
2596
2638
  for (const port of Object.values(d.entrypoints))
2597
2639
  args.push("-p", `${port}:${port}`);
2640
+ if (d.dashboard)
2641
+ args.push("-p", "127.0.0.1:8080:8080");
2598
2642
  if (d.dnsEnv.length)
2599
2643
  args.push("--env-file", p.proxyEnv);
2600
2644
  args.push(d.image);
@@ -4676,7 +4720,7 @@ Options
4676
4720
  var proxy = {
4677
4721
  name: "proxy",
4678
4722
  summary: "Inspect or restart the shared Traefik proxy",
4679
- options: { host: { type: "string" }, lines: { type: "string", short: "n" }, follow: { type: "boolean", short: "f" } },
4723
+ options: { host: { type: "string" }, lines: { type: "string", short: "n" }, follow: { type: "boolean", short: "f" }, port: { type: "string", short: "p" } },
4680
4724
  help: () => `${c.bold("epd proxy <status|reboot|logs|routes|remove>")}
4681
4725
 
4682
4726
  One Traefik container per server, shared by every epd app on it. Rebooting it
@@ -4685,13 +4729,15 @@ briefly interrupts *all* sites on that server; the apps themselves keep running.
4685
4729
  status Is it up, on which image, with which entrypoints
4686
4730
  reboot Recreate it from the current configuration
4687
4731
  logs Traefik's own logs (certificates, routing errors)
4688
- routes The route file epd wrote for this app
4689
- remove Remove this app's routes and stop the proxy if nothing else needs it
4732
+ routes The route file epd wrote for this app
4733
+ dashboard Open a secure SSH tunnel to the Traefik web UI & launch browser
4734
+ remove Remove this app's routes and stop the proxy if nothing else needs it
4690
4735
 
4691
4736
  Options
4692
4737
  --host <ip> Only this host
4693
4738
  -n, --lines <n> Log lines (default 100)
4694
- -f, --follow Stream logs`,
4739
+ -f, --follow Stream logs
4740
+ -p, --port <port> Local dashboard port (default 8080)`,
4695
4741
  async run(ctx) {
4696
4742
  const loaded = ctx.load();
4697
4743
  const cfg = loaded.config;
@@ -4751,6 +4797,30 @@ Options
4751
4797
  }
4752
4798
  return;
4753
4799
  }
4800
+ case "dashboard": {
4801
+ const targetHost = hosts[0];
4802
+ if (!targetHost)
4803
+ throw new EpdError("No proxy hosts available");
4804
+ const localPort = Number(ctx.values.port) || 8080;
4805
+ const dashboardUrl = `http://localhost:${localPort}/dashboard/`;
4806
+ log.step(`Connecting to Traefik dashboard on ${c.bold(targetHost.name)}...`);
4807
+ const s = await proxyState(targetHost, cfg);
4808
+ if (!s.running) {
4809
+ throw new EpdError(`Proxy on ${targetHost.name} is not running. Run ${c.cyan("epd proxy reboot")} first.`);
4810
+ }
4811
+ log.info(`Forwarding local port ${c.bold(String(localPort))} -> 127.0.0.1:8080 on ${targetHost.name}`);
4812
+ log.ok(`Dashboard URL: ${c.cyan(dashboardUrl)}`);
4813
+ log.info(`Press Ctrl-C to close the dashboard tunnel.`);
4814
+ await openBrowser(dashboardUrl);
4815
+ const args = [...targetHost.sshOptions(), "-N", "-L", `${localPort}:127.0.0.1:8080`, targetHost.target];
4816
+ const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...args], { stdout: "inherit", stderr: "inherit" }) : __require("child_process").spawn("ssh", args, { stdio: "inherit" });
4817
+ if (proc.exited) {
4818
+ await proc.exited;
4819
+ } else {
4820
+ await new Promise((resolve) => proc.on("close", resolve));
4821
+ }
4822
+ return;
4823
+ }
4754
4824
  case "remove": {
4755
4825
  for (const host of hosts) {
4756
4826
  await removeRoutes(host, cfg);
@@ -4833,7 +4903,8 @@ Options
4833
4903
  else
4834
4904
  log.plain(` start ${cfg.process.start}`);
4835
4905
  log.plain(` hosts ${allHosts(cfg).join(", ")}`);
4836
- log.plain(` ssh ${cfg.ssh.user}@\u2026:${cfg.ssh.port}`);
4906
+ const sshOverrides = Object.entries(cfg.ssh.hostUsers).filter(([, u]) => u !== cfg.ssh.user).map(([h, u]) => `${u}@${h}`);
4907
+ log.plain(` ssh ${cfg.ssh.user}@\u2026:${cfg.ssh.port}${sshOverrides.length ? c.gray(` (${sshOverrides.join(", ")})`) : ""}`);
4837
4908
  log.plain(` strategy ${cfg.strategy}`);
4838
4909
  if (usesHostPorts(cfg)) {
4839
4910
  const b = portBlock(cfg);
@@ -5736,7 +5807,7 @@ async function promptAutoUpdate(currentVersion) {
5736
5807
  }
5737
5808
 
5738
5809
  // src/version.ts
5739
- var VERSION = "0.4.0";
5810
+ var VERSION = "0.5.1";
5740
5811
 
5741
5812
  // src/commands/update.ts
5742
5813
  var update = {
@@ -5835,6 +5906,904 @@ Run ${c.cyan("epd auth cloudflare")} or ${c.cyan("epd auth hetzner")} to link an
5835
5906
  }
5836
5907
  };
5837
5908
 
5909
+ // src/commands/maintenance.ts
5910
+ function extractDomains(cfg) {
5911
+ const domains = new Set;
5912
+ for (const svc of cfg.services) {
5913
+ for (const r of svc.routes) {
5914
+ for (const h of r.hosts)
5915
+ domains.add(h);
5916
+ }
5917
+ }
5918
+ return Array.from(domains);
5919
+ }
5920
+ function maintenanceHtml(title, message, retrySeconds, appName) {
5921
+ return `<!DOCTYPE html>
5922
+ <html lang="en">
5923
+ <head>
5924
+ <meta charset="UTF-8">
5925
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
5926
+ <title>${title} \u2014 ${appName}</title>
5927
+ <style>
5928
+ :root {
5929
+ --bg: #0b0f19;
5930
+ --card: #151c2e;
5931
+ --border: #232d48;
5932
+ --text: #f8fafc;
5933
+ --subtext: #94a3b8;
5934
+ --brand: #38bdf8;
5935
+ --accent: #6366f1;
5936
+ }
5937
+ * { box-sizing: border-box; margin: 0; padding: 0; }
5938
+ body {
5939
+ background-color: var(--bg);
5940
+ color: var(--text);
5941
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
5942
+ min-height: 100vh;
5943
+ display: flex;
5944
+ align-items: center;
5945
+ justify-content: center;
5946
+ padding: 1.5rem;
5947
+ }
5948
+ .card {
5949
+ background: var(--card);
5950
+ border: 1px solid var(--border);
5951
+ border-radius: 1.25rem;
5952
+ max-width: 32rem;
5953
+ width: 100%;
5954
+ padding: 2.5rem 2rem;
5955
+ text-align: center;
5956
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
5957
+ position: relative;
5958
+ overflow: hidden;
5959
+ }
5960
+ .card::before {
5961
+ content: "";
5962
+ position: absolute;
5963
+ top: 0; left: 0; right: 0;
5964
+ height: 4px;
5965
+ background: linear-gradient(90deg, var(--brand), var(--accent));
5966
+ }
5967
+ .icon-box {
5968
+ width: 4.5rem;
5969
+ height: 4.5rem;
5970
+ background: rgba(56, 189, 248, 0.1);
5971
+ border: 1px solid rgba(56, 189, 248, 0.2);
5972
+ border-radius: 1rem;
5973
+ display: inline-flex;
5974
+ align-items: center;
5975
+ justify-content: center;
5976
+ font-size: 2.25rem;
5977
+ margin-bottom: 1.5rem;
5978
+ animation: pulse 3s infinite ease-in-out;
5979
+ }
5980
+ @keyframes pulse {
5981
+ 0%, 100% { transform: scale(1); opacity: 1; }
5982
+ 50% { transform: scale(1.05); opacity: 0.85; }
5983
+ }
5984
+ h1 {
5985
+ font-size: 1.5rem;
5986
+ font-weight: 700;
5987
+ letter-spacing: -0.025em;
5988
+ margin-bottom: 0.75rem;
5989
+ }
5990
+ p {
5991
+ color: var(--subtext);
5992
+ font-size: 1rem;
5993
+ line-height: 1.6;
5994
+ margin-bottom: 1.75rem;
5995
+ }
5996
+ .badge {
5997
+ display: inline-flex;
5998
+ align-items: center;
5999
+ gap: 0.5rem;
6000
+ padding: 0.35rem 0.85rem;
6001
+ background: rgba(245, 158, 11, 0.1);
6002
+ border: 1px solid rgba(245, 158, 11, 0.3);
6003
+ border-radius: 9999px;
6004
+ color: #f59e0b;
6005
+ font-size: 0.825rem;
6006
+ font-weight: 600;
6007
+ margin-bottom: 1.5rem;
6008
+ }
6009
+ .dot {
6010
+ width: 0.5rem;
6011
+ height: 0.5rem;
6012
+ border-radius: 9999px;
6013
+ background: #f59e0b;
6014
+ animation: blink 1.5s infinite;
6015
+ }
6016
+ @keyframes blink {
6017
+ 0%, 100% { opacity: 1; }
6018
+ 50% { opacity: 0.3; }
6019
+ }
6020
+ .countdown {
6021
+ font-size: 0.875rem;
6022
+ color: var(--subtext);
6023
+ border-top: 1px solid var(--border);
6024
+ padding-top: 1.25rem;
6025
+ }
6026
+ </style>
6027
+ </head>
6028
+ <body>
6029
+ <div class="card">
6030
+ <div class="icon-box">\u26A1</div>
6031
+ <div class="badge"><span class="dot"></span> Maintenance Mode Active</div>
6032
+ <h1>${title}</h1>
6033
+ <p>${message}</p>
6034
+ <div class="countdown">
6035
+ Auto-refreshing in <span id="timer" style="font-weight: 600; color: var(--brand);">${retrySeconds}</span>s...
6036
+ </div>
6037
+ </div>
6038
+ <script>
6039
+ let remaining = ${retrySeconds};
6040
+ const timer = document.getElementById('timer');
6041
+ setInterval(() => {
6042
+ remaining--;
6043
+ if (remaining <= 0) {
6044
+ window.location.reload();
6045
+ } else if (timer) {
6046
+ timer.textContent = remaining;
6047
+ }
6048
+ }, 1000);
6049
+ </script>
6050
+ </body>
6051
+ </html>`;
6052
+ }
6053
+ function maintenanceYaml(appName, domains, port) {
6054
+ if (!domains.length)
6055
+ domains = ["localhost"];
6056
+ const hostRule = domains.map((d) => `Host(\`${d}\`)`).join(" || ");
6057
+ return `http:
6058
+ routers:
6059
+ ${appName}-maint-http:
6060
+ rule: "${hostRule}"
6061
+ entryPoints: ["web"]
6062
+ service: "${appName}-maint-svc"
6063
+ priority: 2000000000
6064
+ ${appName}-maint-https:
6065
+ rule: "${hostRule}"
6066
+ entryPoints: ["websecure"]
6067
+ service: "${appName}-maint-svc"
6068
+ priority: 2000000000
6069
+ tls: {}
6070
+ services:
6071
+ ${appName}-maint-svc:
6072
+ loadBalancer:
6073
+ servers:
6074
+ - url: "http://127.0.0.1:${port}"
6075
+ `;
6076
+ }
6077
+ var maintenance = {
6078
+ name: "maintenance",
6079
+ summary: "Toggle or inspect zero-downtime maintenance mode for this application",
6080
+ options: {
6081
+ message: { type: "string", short: "m" },
6082
+ title: { type: "string" },
6083
+ retry: { type: "string" },
6084
+ status: { type: "string" },
6085
+ host: { type: "string" }
6086
+ },
6087
+ help: () => `${c.bold("epd maintenance <on|off|status>")} \u2014 manage maintenance mode
6088
+
6089
+ Presents a responsive 503 Maintenance page to all public visitors via Traefik
6090
+ without stopping your backend applications or dropping SSL.
6091
+
6092
+ Commands
6093
+ on Enable maintenance mode and route all traffic to the maintenance page
6094
+ off Disable maintenance mode and resume live blue/green routing
6095
+ status Check if maintenance mode is currently active
6096
+
6097
+ Options
6098
+ -m, --message <text> Custom maintenance message
6099
+ --title <text> Custom page title (default: Maintenance in Progress)
6100
+ --retry <sec> Retry-After header and auto-refresh timer (default: 30)
6101
+ --status <code> HTTP response status code (default: 503)
6102
+ --host <ip> Run only on a specific host`,
6103
+ async run(ctx) {
6104
+ const loaded = ctx.load();
6105
+ const cfg = loaded.config;
6106
+ const action = ctx.positionals[0] ?? "status";
6107
+ let hostNames = allHosts(cfg);
6108
+ if (ctx.values.host)
6109
+ hostNames = hostNames.filter((h) => h === ctx.values.host);
6110
+ if (!hostNames.length)
6111
+ throw new EpdError("No hosts found in configuration");
6112
+ const hosts = hostNames.map((h) => host(h, cfg.ssh));
6113
+ const p = paths(cfg);
6114
+ const maintPort = (cfg.portBase || 31776) + 999;
6115
+ const domains = extractDomains(cfg);
6116
+ const maintDir = `${p.root}/maintenance/${cfg.name}`;
6117
+ const traefikDynamicFile = `${p.proxyDynamicDir}/${cfg.name}-maintenance.yml`;
6118
+ switch (action) {
6119
+ case "status": {
6120
+ for (const host of hosts) {
6121
+ const isActive = await host.test(`[ -f ${shq(traefikDynamicFile)} ]`);
6122
+ if (isActive) {
6123
+ log.plain(`${c.magenta(host.name)}: ${c.yellow(c.bold("MAINTENANCE ACTIVE"))} (routes overriding live app)`);
6124
+ } else {
6125
+ log.plain(`${c.magenta(host.name)}: ${c.green("Live")} (normal blue/green routing)`);
6126
+ }
6127
+ }
6128
+ return;
6129
+ }
6130
+ case "on": {
6131
+ const title = ctx.values.title || "Maintenance in Progress";
6132
+ const message = ctx.values.message || "We are currently performing scheduled maintenance. We will be back shortly.";
6133
+ const retrySec = Number(ctx.values.retry) || 30;
6134
+ const statusCode = Number(ctx.values.status) || 503;
6135
+ const html = maintenanceHtml(title, message, retrySec, cfg.name);
6136
+ const yml = maintenanceYaml(cfg.name, domains, maintPort);
6137
+ log.step(`Enabling maintenance mode on ${hosts.length} host(s)...`);
6138
+ await pool(hosts, 4, async (host) => {
6139
+ await host.exec(`mkdir -p ${shq(maintDir)} ${shq(p.proxyDynamicDir)}`);
6140
+ await host.writeFile(`${maintDir}/index.html`, html, "644");
6141
+ const pyServer = `import http.server, socketserver
6142
+ class Handler(http.server.BaseHTTPRequestHandler):
6143
+ def do_GET(self):
6144
+ self.send_response(${statusCode})
6145
+ self.send_header('Content-Type', 'text/html; charset=utf-8')
6146
+ self.send_header('Retry-After', '${retrySec}')
6147
+ self.end_headers()
6148
+ try:
6149
+ with open('${maintDir}/index.html', 'rb') as f:
6150
+ self.wfile.write(f.read())
6151
+ except Exception:
6152
+ self.wfile.write(b"<h1>Maintenance in Progress</h1>")
6153
+ def do_HEAD(self):
6154
+ self.send_response(${statusCode})
6155
+ self.send_header('Content-Type', 'text/html; charset=utf-8')
6156
+ self.send_header('Retry-After', '${retrySec}')
6157
+ self.end_headers()
6158
+ def log_message(self, format, *args):
6159
+ pass
6160
+
6161
+ socketserver.TCPServer.allow_reuse_address = True
6162
+ with socketserver.TCPServer(('127.0.0.1', ${maintPort}), Handler) as httpd:
6163
+ httpd.serve_forever()
6164
+ `;
6165
+ await host.writeFile(`${maintDir}/server.py`, pyServer, "755");
6166
+ await host.exec(`[ -f ${shq(maintDir)}/pid ] && kill $(cat ${shq(maintDir)}/pid) 2>/dev/null || true`);
6167
+ await host.exec(`docker rm -f epd-${cfg.name}-maint 2>/dev/null || true`);
6168
+ const hasPython = await host.test("command -v python3 >/dev/null 2>&1");
6169
+ if (hasPython) {
6170
+ await host.exec(`nohup python3 ${shq(maintDir)}/server.py >/dev/null 2>&1 & echo $! > ${shq(maintDir)}/pid`);
6171
+ } else {
6172
+ await host.exec(`docker run -d --name epd-${cfg.name}-maint --restart unless-stopped -p 127.0.0.1:${maintPort}:80 -v ${shq(maintDir)}:/usr/share/nginx/html:ro nginx:alpine >/dev/null 2>&1 || true`);
6173
+ }
6174
+ await host.writeFile(traefikDynamicFile, yml, "644");
6175
+ log.host(host.name, `maintenance mode enabled (${c.yellow(`HTTP ${statusCode}`)})`);
6176
+ });
6177
+ log.ok(`Maintenance mode active across all hosts for: ${domains.join(", ") || cfg.name}`);
6178
+ log.info(`Run ${c.cyan("epd maintenance off")} when ready to resume live traffic.`);
6179
+ return;
6180
+ }
6181
+ case "off": {
6182
+ log.step(`Disabling maintenance mode on ${hosts.length} host(s)...`);
6183
+ await pool(hosts, 4, async (host) => {
6184
+ await host.exec(`rm -f ${shq(traefikDynamicFile)}`);
6185
+ await host.exec(`[ -f ${shq(maintDir)}/pid ] && kill $(cat ${shq(maintDir)}/pid) 2>/dev/null || true`);
6186
+ await host.exec(`docker rm -f epd-${cfg.name}-maint 2>/dev/null || true`);
6187
+ await host.exec(`rm -rf ${shq(maintDir)}`);
6188
+ log.host(host.name, "maintenance mode disabled");
6189
+ });
6190
+ log.ok(`Maintenance mode disabled. Live traffic restored!`);
6191
+ return;
6192
+ }
6193
+ default:
6194
+ throw new EpdError(`Unknown action "${action}". Available: on, off, status`);
6195
+ }
6196
+ }
6197
+ };
6198
+
6199
+ // src/commands/ssl.ts
6200
+ import { X509Certificate } from "crypto";
6201
+ function parseAcmeCert(entry) {
6202
+ try {
6203
+ if (!entry.certificate)
6204
+ return null;
6205
+ const pem = Buffer.from(entry.certificate, "base64").toString("utf8");
6206
+ const cert = new X509Certificate(pem);
6207
+ const validTo = new Date(cert.validTo);
6208
+ const validFrom = new Date(cert.validFrom);
6209
+ const msRemaining = validTo.getTime() - Date.now();
6210
+ const daysRemaining = Math.floor(msRemaining / (1000 * 60 * 60 * 24));
6211
+ let status = "active";
6212
+ if (daysRemaining <= 0)
6213
+ status = "expired";
6214
+ else if (daysRemaining <= 14)
6215
+ status = "expiring_soon";
6216
+ const sans = cert.subjectAltName ? cert.subjectAltName.split(", ").map((s) => s.replace(/^DNS:/, "")) : [];
6217
+ const issuerMatch = cert.issuer.match(/O=([^,\n]+)/) || cert.issuer.match(/CN=([^,\n]+)/);
6218
+ const issuer = issuerMatch ? issuerMatch[1] : cert.issuer;
6219
+ const mainDomain = entry.domain?.main || cert.subject.replace(/^CN=/, "");
6220
+ return {
6221
+ mainDomain,
6222
+ sans: sans.filter((s) => s !== mainDomain),
6223
+ issuer: issuer || "Let's Encrypt",
6224
+ validFrom: validFrom.toISOString().split("T")[0] ?? "",
6225
+ validTo: validTo.toISOString().split("T")[0] ?? "",
6226
+ daysRemaining,
6227
+ status
6228
+ };
6229
+ } catch {
6230
+ return null;
6231
+ }
6232
+ }
6233
+ var ssl = {
6234
+ name: "ssl",
6235
+ aliases: ["certs"],
6236
+ summary: "Inspect and verify Let's Encrypt SSL/TLS certificates",
6237
+ options: {
6238
+ host: { type: "string" },
6239
+ json: { type: "boolean" }
6240
+ },
6241
+ help: () => `${c.bold("epd ssl [status]")} \u2014 inspect SSL certificates managed by Traefik
6242
+
6243
+ Displays certificates stored in /var/lib/epd/proxy/acme/acme.json, including
6244
+ domains, SANs, issuers, expiration dates, and days remaining.
6245
+
6246
+ Options
6247
+ --host <ip> Only inspect this host
6248
+ --json Output certificate metadata as JSON`,
6249
+ async run(ctx) {
6250
+ const loaded = ctx.load();
6251
+ const cfg = loaded.config;
6252
+ let names = proxyHosts(cfg);
6253
+ if (ctx.values.host)
6254
+ names = names.filter((h) => h === ctx.values.host);
6255
+ if (!names.length)
6256
+ throw new EpdError("No proxy hosts found in configuration");
6257
+ const hosts = names.map((h) => host(h, cfg.ssh));
6258
+ const p = paths(cfg);
6259
+ const acmeFilePath = `${p.acmeDir}/acme.json`;
6260
+ const allResults = {};
6261
+ for (const host of hosts) {
6262
+ log.step(`Checking SSL certificates on ${c.bold(host.name)}...`);
6263
+ const exists = await host.test(`[ -f ${shq(acmeFilePath)} ]`);
6264
+ if (!exists) {
6265
+ log.warn(`No acme.json found on ${host.name} yet. Traefik generates certificates upon the first incoming HTTPS request.`);
6266
+ allResults[host.name] = [];
6267
+ continue;
6268
+ }
6269
+ const rawJson = await host.capture(`cat ${shq(acmeFilePath)} 2>/dev/null || echo "{}"`, { allowFailure: true });
6270
+ let data = {};
6271
+ try {
6272
+ data = JSON.parse(rawJson);
6273
+ } catch {
6274
+ log.warn(`Failed to parse acme.json on ${host.name}.`);
6275
+ allResults[host.name] = [];
6276
+ continue;
6277
+ }
6278
+ const certs = [];
6279
+ for (const resolverKey of Object.keys(data)) {
6280
+ const resolverObj = data[resolverKey];
6281
+ const certList = Array.isArray(resolverObj?.Certificates) ? resolverObj.Certificates : [];
6282
+ for (const entry of certList) {
6283
+ const parsed = parseAcmeCert(entry);
6284
+ if (parsed)
6285
+ certs.push(parsed);
6286
+ }
6287
+ }
6288
+ allResults[host.name] = certs;
6289
+ if (ctx.values.json)
6290
+ continue;
6291
+ if (!certs.length) {
6292
+ log.info(`No certificates found in ${acmeFilePath} on ${host.name}.`);
6293
+ continue;
6294
+ }
6295
+ console.log("");
6296
+ console.log(` ${c.bold("Host:")} ${c.magenta(host.name)}`);
6297
+ console.log(` ${c.bold("SSL Resolver:")} Let's Encrypt (${cfg.proxy.email || "no contact email"})`);
6298
+ console.log("");
6299
+ const rows = [
6300
+ ["Domain", "SANs", "Issuer", "Expires", "Status"]
6301
+ ];
6302
+ for (const cert of certs) {
6303
+ let statusStr = "";
6304
+ if (cert.status === "active") {
6305
+ statusStr = c.green(`Active (${cert.daysRemaining}d left)`);
6306
+ } else if (cert.status === "expiring_soon") {
6307
+ statusStr = c.yellow(`Expiring soon (${cert.daysRemaining}d left)`);
6308
+ } else {
6309
+ statusStr = c.red(`EXPIRED`);
6310
+ }
6311
+ rows.push([
6312
+ c.bold(cert.mainDomain),
6313
+ cert.sans.length ? cert.sans.join(", ") : c.gray("\u2014"),
6314
+ cert.issuer,
6315
+ cert.validTo,
6316
+ statusStr
6317
+ ]);
6318
+ }
6319
+ const colWidths = [0, 0, 0, 0, 0];
6320
+ for (const row of rows) {
6321
+ for (let i = 0;i < row.length; i++) {
6322
+ const rawLen = row[i].replace(/\x1B\[\d+m/g, "").length;
6323
+ colWidths[i] = Math.max(colWidths[i], rawLen);
6324
+ }
6325
+ }
6326
+ for (let r = 0;r < rows.length; r++) {
6327
+ const row = rows[r];
6328
+ const line = row.map((val, idx) => {
6329
+ const rawLen = val.replace(/\x1B\[\d+m/g, "").length;
6330
+ const pad = " ".repeat(Math.max(0, colWidths[idx] - rawLen));
6331
+ return val + pad;
6332
+ }).join(" ");
6333
+ if (r === 0) {
6334
+ console.log(` ${c.gray(line)}`);
6335
+ console.log(` ${c.gray("-".repeat(line.length))}`);
6336
+ } else {
6337
+ console.log(` ${line}`);
6338
+ }
6339
+ }
6340
+ console.log("");
6341
+ }
6342
+ if (ctx.values.json) {
6343
+ console.log(JSON.stringify(allResults, null, 2));
6344
+ }
6345
+ }
6346
+ };
6347
+
6348
+ // src/commands/top.ts
6349
+ async function collectHostStats(host, cfg) {
6350
+ const isDocker = cfg.mode === "docker";
6351
+ const script = `
6352
+ echo "===UPTIME==="
6353
+ uptime || true
6354
+ echo "===MEM==="
6355
+ free -m 2>/dev/null | awk '/Mem:/ {printf "%dM / %dM (%.1f%%)", $3, $2, ($3/$2)*100}' || true
6356
+ echo ""
6357
+ echo "===DISK==="
6358
+ df -h /var/lib/epd 2>/dev/null | awk 'NR==2 {printf "%s / %s (%s)", $3, $2, $5}' || df -h / 2>/dev/null | awk 'NR==2 {printf "%s / %s (%s)", $3, $2, $5}' || true
6359
+ echo ""
6360
+ echo "===CONTAINERS==="
6361
+ ${isDocker ? "docker stats --no-stream --format '{{json .}}' 2>/dev/null || true" : "pm2 jlist 2>/dev/null || true"}
6362
+ `;
6363
+ const output = await host.capture(script, { allowFailure: true });
6364
+ const uptimeMatch = output.match(/===UPTIME===\s*([\s\S]*?)===MEM===/);
6365
+ const memMatch = output.match(/===MEM===\s*([\s\S]*?)===DISK===/);
6366
+ const diskMatch = output.match(/===DISK===\s*([\s\S]*?)===CONTAINERS===/);
6367
+ const containersRaw = output.split("===CONTAINERS===")[1] || "";
6368
+ const uptimeStr = (uptimeMatch?.[1] ?? "").trim();
6369
+ const ramStr = (memMatch?.[1] ?? "").trim();
6370
+ const diskStr = (diskMatch?.[1] ?? "").trim();
6371
+ let loadAvg = "";
6372
+ const loadMatch = uptimeStr.match(/load average[s]?:\s*([^\n]+)/i);
6373
+ if (loadMatch)
6374
+ loadAvg = loadMatch[1].trim();
6375
+ const containers = [];
6376
+ if (isDocker) {
6377
+ for (const line of containersRaw.split(`
6378
+ `)) {
6379
+ const trimmed = line.trim();
6380
+ if (!trimmed.startsWith("{"))
6381
+ continue;
6382
+ try {
6383
+ const item = JSON.parse(trimmed);
6384
+ if (item.Name && (item.Name.includes("epd") || item.Name.includes(cfg.name))) {
6385
+ containers.push(item);
6386
+ } else if (item.Name) {
6387
+ containers.push(item);
6388
+ }
6389
+ } catch {}
6390
+ }
6391
+ } else {
6392
+ try {
6393
+ const pm2List = JSON.parse(containersRaw);
6394
+ if (Array.isArray(pm2List)) {
6395
+ for (const proc of pm2List) {
6396
+ const memMb = proc.monit?.memory ? (proc.monit.memory / (1024 * 1024)).toFixed(1) + "MiB" : "0MiB";
6397
+ const cpu = proc.monit?.cpu ? `${proc.monit.cpu}%` : "0%";
6398
+ containers.push({
6399
+ Name: proc.name || "process",
6400
+ CPUPerc: cpu,
6401
+ MemUsage: memMb,
6402
+ MemPerc: "\u2014",
6403
+ NetIO: "\u2014",
6404
+ BlockIO: "\u2014",
6405
+ PIDs: String(proc.pid || "\u2014")
6406
+ });
6407
+ }
6408
+ }
6409
+ } catch {}
6410
+ }
6411
+ return {
6412
+ hostName: host.name,
6413
+ uptime: uptimeStr,
6414
+ loadAvg,
6415
+ ramSummary: ramStr || "unknown",
6416
+ diskSummary: diskStr || "unknown",
6417
+ containers
6418
+ };
6419
+ }
6420
+ function renderDashboard(statsList) {
6421
+ for (const stats of statsList) {
6422
+ console.log(c.bold(`
6423
+ \u2500\u2500 Host: ${c.magenta(stats.hostName)} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`));
6424
+ console.log(` ${c.gray("Load:")} ${stats.loadAvg || "\u2014"} \u2502 ${c.gray("RAM:")} ${stats.ramSummary} \u2502 ${c.gray("Disk (/var/lib/epd):")} ${stats.diskSummary}`);
6425
+ console.log("");
6426
+ if (!stats.containers.length) {
6427
+ console.log(` ${c.gray("No running containers or processes found.")}
6428
+ `);
6429
+ continue;
6430
+ }
6431
+ const rows = [
6432
+ ["Container / Service", "CPU %", "Mem Usage / Limit", "Mem %", "Net I/O", "PIDs"]
6433
+ ];
6434
+ for (const cItem of stats.containers) {
6435
+ let cpuFormatted = cItem.CPUPerc;
6436
+ const cpuNum = parseFloat(cItem.CPUPerc);
6437
+ if (cpuNum > 80)
6438
+ cpuFormatted = c.red(cItem.CPUPerc);
6439
+ else if (cpuNum > 40)
6440
+ cpuFormatted = c.yellow(cItem.CPUPerc);
6441
+ else
6442
+ cpuFormatted = c.green(cItem.CPUPerc);
6443
+ rows.push([
6444
+ c.bold(cItem.Name),
6445
+ cpuFormatted,
6446
+ cItem.MemUsage,
6447
+ cItem.MemPerc,
6448
+ cItem.NetIO,
6449
+ cItem.PIDs
6450
+ ]);
6451
+ }
6452
+ const colWidths = [0, 0, 0, 0, 0, 0];
6453
+ for (const row of rows) {
6454
+ for (let i = 0;i < row.length; i++) {
6455
+ const rawLen = row[i].replace(/\x1B\[\d+m/g, "").length;
6456
+ colWidths[i] = Math.max(colWidths[i], rawLen);
6457
+ }
6458
+ }
6459
+ for (let r = 0;r < rows.length; r++) {
6460
+ const row = rows[r];
6461
+ const line = row.map((val, idx) => {
6462
+ const rawLen = val.replace(/\x1B\[\d+m/g, "").length;
6463
+ const pad = " ".repeat(Math.max(0, colWidths[idx] - rawLen));
6464
+ return val + pad;
6465
+ }).join(" ");
6466
+ if (r === 0) {
6467
+ console.log(` ${c.gray(line)}`);
6468
+ console.log(` ${c.gray("-".repeat(line.length))}`);
6469
+ } else {
6470
+ console.log(` ${line}`);
6471
+ }
6472
+ }
6473
+ console.log("");
6474
+ }
6475
+ }
6476
+ var top = {
6477
+ name: "top",
6478
+ aliases: ["stats"],
6479
+ summary: "Live multi-server CPU, memory, container and disk resource monitor",
6480
+ options: {
6481
+ host: { type: "string" },
6482
+ watch: { type: "boolean", short: "w" },
6483
+ once: { type: "boolean" }
6484
+ },
6485
+ help: () => `${c.bold("epd top")} \u2014 real-time server and container metrics monitor (aliased as epd stats)
6486
+
6487
+ Aggregates CPU %, memory consumption, network I/O, disk space, and load averages
6488
+ across all servers running this application.
6489
+
6490
+ Options
6491
+ --host <ip> Monitor only this specific host
6492
+ -w, --watch Stream metrics continuously (refreshes every 2s)
6493
+ --once Print a single snapshot and exit`,
6494
+ async run(ctx) {
6495
+ const loaded = ctx.load();
6496
+ const cfg = loaded.config;
6497
+ let hostNames = allHosts(cfg);
6498
+ if (ctx.values.host)
6499
+ hostNames = hostNames.filter((h) => h === ctx.values.host);
6500
+ if (!hostNames.length)
6501
+ throw new EpdError("No hosts found in configuration");
6502
+ const hosts = hostNames.map((h) => host(h, cfg.ssh));
6503
+ const shouldWatch = Boolean(ctx.values.watch) || interactive() && !ctx.values.once;
6504
+ const refresh = async () => {
6505
+ const statsList = await Promise.all(hosts.map((h) => collectHostStats(h, cfg)));
6506
+ if (shouldWatch)
6507
+ process.stdout.write("\x1Bc");
6508
+ renderDashboard(statsList);
6509
+ if (shouldWatch) {
6510
+ console.log(c.gray(` Streaming live metrics (2s interval). Press Ctrl-C to exit.`));
6511
+ }
6512
+ };
6513
+ await refresh();
6514
+ if (shouldWatch) {
6515
+ return new Promise((resolve) => {
6516
+ const interval = setInterval(async () => {
6517
+ try {
6518
+ await refresh();
6519
+ } catch {
6520
+ clearInterval(interval);
6521
+ resolve();
6522
+ }
6523
+ }, 2000);
6524
+ process.on("SIGINT", () => {
6525
+ clearInterval(interval);
6526
+ console.log("");
6527
+ resolve();
6528
+ });
6529
+ });
6530
+ }
6531
+ }
6532
+ };
6533
+
6534
+ // src/commands/backup.ts
6535
+ import { createWriteStream, mkdirSync as mkdirSync5, statSync } from "fs";
6536
+ import { dirname as dirname3, join as join8, resolve as resolve2 } from "path";
6537
+ function detectAccessoryType(decl, cfg) {
6538
+ const name = decl.name;
6539
+ const img = (decl.image || "").toLowerCase();
6540
+ const hostName = decl.host || cfg.services[0]?.hosts[0] || "localhost";
6541
+ const containerName = accessoryContainer(cfg.name, name);
6542
+ const env = { ...decl.env };
6543
+ if (img.includes("postgres") || img.includes("postgis") || img.includes("timescale")) {
6544
+ return {
6545
+ name,
6546
+ decl,
6547
+ hostName,
6548
+ type: "postgres",
6549
+ containerName,
6550
+ dbUser: env.POSTGRES_USER || "postgres",
6551
+ dbName: env.POSTGRES_DB || cfg.name
6552
+ };
6553
+ }
6554
+ if (img.includes("mysql") || img.includes("mariadb")) {
6555
+ return {
6556
+ name,
6557
+ decl,
6558
+ hostName,
6559
+ type: "mysql",
6560
+ containerName,
6561
+ dbUser: env.MYSQL_USER || "root",
6562
+ dbPass: env.MYSQL_ROOT_PASSWORD || env.MYSQL_PASSWORD,
6563
+ dbName: env.MYSQL_DATABASE || cfg.name
6564
+ };
6565
+ }
6566
+ if (img.includes("mongo")) {
6567
+ return {
6568
+ name,
6569
+ decl,
6570
+ hostName,
6571
+ type: "mongo",
6572
+ containerName,
6573
+ dbName: cfg.name
6574
+ };
6575
+ }
6576
+ let volumeDir;
6577
+ for (const v of decl.volumes) {
6578
+ const hostSide = v.split(":")[0];
6579
+ if (hostSide && hostSide.startsWith("/")) {
6580
+ volumeDir = hostSide;
6581
+ break;
6582
+ }
6583
+ }
6584
+ return {
6585
+ name,
6586
+ decl,
6587
+ hostName,
6588
+ type: "volume",
6589
+ containerName,
6590
+ volumeDir
6591
+ };
6592
+ }
6593
+ var backup = {
6594
+ name: "backup",
6595
+ summary: "Back up databases and accessory volumes to compressed local archives",
6596
+ options: {
6597
+ output: { type: "string", short: "o" },
6598
+ host: { type: "string" }
6599
+ },
6600
+ help: () => `${c.bold("epd backup [accessory]")} \u2014 create compressed database or volume backups
6601
+
6602
+ Automatically inspects the accessory image (PostgreSQL, MySQL, MariaDB, Mongo, or generic volumes)
6603
+ and streams a compressed snapshot directly to your local ./backups directory.
6604
+
6605
+ Options
6606
+ -o, --output <path> Custom output path or destination directory
6607
+ --host <ip> Host running the accessory`,
6608
+ async run(ctx) {
6609
+ const loaded = ctx.load();
6610
+ const cfg = loaded.config;
6611
+ const requestedName = ctx.positionals[0];
6612
+ const accessories = cfg.accessories;
6613
+ if (!accessories.length) {
6614
+ throw new EpdError(`No accessories configured in epd.yml under "accessories:".`);
6615
+ }
6616
+ let targets = [];
6617
+ if (requestedName) {
6618
+ const found = accessories.find((a) => a.name === requestedName);
6619
+ if (!found) {
6620
+ throw new EpdError(`Accessory "${requestedName}" not found. Configured: ${accessories.map((a) => a.name).join(", ")}`);
6621
+ }
6622
+ targets = [detectAccessoryType(found, cfg)];
6623
+ } else {
6624
+ targets = accessories.map((a) => detectAccessoryType(a, cfg));
6625
+ }
6626
+ const outBaseDir = resolve2(process.cwd(), "backups");
6627
+ mkdirSync5(outBaseDir, { recursive: true });
6628
+ for (const target of targets) {
6629
+ const host2 = host(target.hostName, cfg.ssh);
6630
+ const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${target.containerName}$`)} | grep -q .`);
6631
+ if (!isRunning) {
6632
+ log.warn(`Container ${c.bold(target.containerName)} is not currently running on ${host2.name}. Skipping.`);
6633
+ continue;
6634
+ }
6635
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
6636
+ const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
6637
+ const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
6638
+ const localFile = ctx.values.output ? resolve2(String(ctx.values.output)) : join8(outBaseDir, filename);
6639
+ mkdirSync5(dirname3(localFile), { recursive: true });
6640
+ let dumpCmd = "";
6641
+ if (target.type === "postgres") {
6642
+ dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
6643
+ } else if (target.type === "mysql") {
6644
+ const passFlag = target.dbPass ? `-p${shq(target.dbPass)}` : "";
6645
+ dumpCmd = `docker exec ${shq(target.containerName)} mysqldump -u ${shq(target.dbUser)} ${passFlag} ${shq(target.dbName)} | gzip -9`;
6646
+ } else if (target.type === "mongo") {
6647
+ dumpCmd = `docker exec ${shq(target.containerName)} mongodump --archive --gzip`;
6648
+ } else {
6649
+ if (!target.volumeDir) {
6650
+ log.warn(`No host volume path found for accessory "${target.name}". Skipping.`);
6651
+ continue;
6652
+ }
6653
+ dumpCmd = `tar -czf - -C ${shq(target.volumeDir)} .`;
6654
+ }
6655
+ log.step(`Streaming ${c.bold(target.type)} backup of ${c.magenta(target.name)} from ${host2.name}...`);
6656
+ const t0 = Date.now();
6657
+ const sshArgs = [...host2.sshOptions(), host2.target, dumpCmd];
6658
+ const writeStream = createWriteStream(localFile);
6659
+ await new Promise((res, rej) => {
6660
+ const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...sshArgs], { stdout: "pipe", stderr: "pipe" }) : __require("child_process").spawn("ssh", sshArgs, { stdio: ["ignore", "pipe", "pipe"] });
6661
+ const stream = proc.stdout;
6662
+ stream.pipe(writeStream);
6663
+ writeStream.on("finish", () => res());
6664
+ writeStream.on("error", rej);
6665
+ if (proc.exited) {
6666
+ proc.exited.then((code) => {
6667
+ if (code !== 0)
6668
+ rej(new EpdError(`SSH backup process exited with code ${code}`));
6669
+ });
6670
+ } else {
6671
+ proc.on("close", (code) => {
6672
+ if (code !== 0)
6673
+ rej(new EpdError(`SSH backup process exited with code ${code}`));
6674
+ });
6675
+ }
6676
+ });
6677
+ const stats = statSync(localFile);
6678
+ const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
6679
+ const elapsed = dur(Date.now() - t0);
6680
+ log.ok(`Backed up ${c.bold(target.name)} \u2192 ${c.cyan(localFile)} (${sizeMb} MB in ${elapsed})`);
6681
+ }
6682
+ }
6683
+ };
6684
+
6685
+ // src/commands/restore.ts
6686
+ import { createReadStream, existsSync as existsSync7 } from "fs";
6687
+ import { basename as basename2, resolve as resolve3 } from "path";
6688
+ var restore = {
6689
+ name: "restore",
6690
+ summary: "Restore a database or volume backup into a running accessory",
6691
+ options: {
6692
+ accessory: { type: "string", short: "a" },
6693
+ yes: { type: "boolean", short: "y" }
6694
+ },
6695
+ help: () => `${c.bold("epd restore <backup-file>")} \u2014 restore a database or volume backup
6696
+
6697
+ Pipes a local .sql.gz or .tar.gz archive directly into a live accessory container.
6698
+
6699
+ Options
6700
+ -a, --accessory <name> Target accessory name (default: auto-detected from filename)
6701
+ -y, --yes Skip confirmation prompt`,
6702
+ async run(ctx) {
6703
+ const backupPath = ctx.positionals[0];
6704
+ if (!backupPath)
6705
+ throw new EpdError("Please provide a path to the backup file to restore.");
6706
+ const absPath = resolve3(backupPath);
6707
+ if (!existsSync7(absPath))
6708
+ throw new EpdError(`Backup file not found: ${absPath}`);
6709
+ const loaded = ctx.load();
6710
+ const cfg = loaded.config;
6711
+ const fileBase = basename2(absPath);
6712
+ const accessories = cfg.accessories;
6713
+ if (!accessories.length)
6714
+ throw new EpdError("No accessories configured in epd.yml.");
6715
+ let targetAccessoryName = ctx.values.accessory;
6716
+ if (!targetAccessoryName) {
6717
+ for (const a of accessories) {
6718
+ if (fileBase.includes(a.name)) {
6719
+ targetAccessoryName = a.name;
6720
+ break;
6721
+ }
6722
+ }
6723
+ }
6724
+ if (!targetAccessoryName && accessories.length === 1) {
6725
+ targetAccessoryName = accessories[0].name;
6726
+ }
6727
+ if (!targetAccessoryName) {
6728
+ throw new EpdError(`Could not auto-detect target accessory from filename "${fileBase}". Specify with --accessory <name>.`);
6729
+ }
6730
+ const decl = accessories.find((a) => a.name === targetAccessoryName);
6731
+ if (!decl) {
6732
+ throw new EpdError(`Accessory "${targetAccessoryName}" not found in configuration.`);
6733
+ }
6734
+ const hostName = decl.host || cfg.services[0]?.hosts[0] || "localhost";
6735
+ const host2 = host(hostName, cfg.ssh);
6736
+ const containerName = accessoryContainer(cfg.name, targetAccessoryName);
6737
+ const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${containerName}$`)} | grep -q .`);
6738
+ if (!isRunning) {
6739
+ throw new EpdError(`Accessory container ${containerName} is not running on ${host2.name}.`);
6740
+ }
6741
+ if (!ctx.values.yes) {
6742
+ log.warn(`Restoring will overwrite existing data in accessory ${c.bold(targetAccessoryName)} on ${c.magenta(host2.name)}!`);
6743
+ const ok = await confirm(`Are you sure you want to restore ${c.bold(fileBase)}?`, false);
6744
+ if (!ok) {
6745
+ log.info("Restore aborted.");
6746
+ return;
6747
+ }
6748
+ }
6749
+ const img = (decl.image || "").toLowerCase();
6750
+ const env = { ...decl.env };
6751
+ let restoreCmd = "";
6752
+ if (img.includes("postgres") || img.includes("postgis") || img.includes("timescale")) {
6753
+ const user = env.POSTGRES_USER || "postgres";
6754
+ const db = env.POSTGRES_DB || cfg.name;
6755
+ restoreCmd = `gunzip -c | docker exec -i ${shq(containerName)} psql -U ${shq(user)} ${shq(db)}`;
6756
+ } else if (img.includes("mysql") || img.includes("mariadb")) {
6757
+ const user = env.MYSQL_USER || "root";
6758
+ const pass = env.MYSQL_ROOT_PASSWORD || env.MYSQL_PASSWORD;
6759
+ const passFlag = pass ? `-p${shq(pass)}` : "";
6760
+ const db = env.MYSQL_DATABASE || cfg.name;
6761
+ restoreCmd = `gunzip -c | docker exec -i ${shq(containerName)} mysql -u ${shq(user)} ${passFlag} ${shq(db)}`;
6762
+ } else if (img.includes("mongo")) {
6763
+ restoreCmd = `docker exec -i ${shq(containerName)} mongorestore --archive --gzip`;
6764
+ } else {
6765
+ let volumeDir;
6766
+ for (const v of decl.volumes) {
6767
+ const hostSide = v.split(":")[0];
6768
+ if (hostSide && hostSide.startsWith("/")) {
6769
+ volumeDir = hostSide;
6770
+ break;
6771
+ }
6772
+ }
6773
+ if (!volumeDir)
6774
+ throw new EpdError(`No host volume path configured for accessory "${targetAccessoryName}".`);
6775
+ restoreCmd = `tar -xzf - -C ${shq(volumeDir)}`;
6776
+ }
6777
+ log.step(`Streaming restore into ${c.bold(targetAccessoryName)} on ${host2.name}...`);
6778
+ const t0 = Date.now();
6779
+ const sshArgs = [...host2.sshOptions(), host2.target, restoreCmd];
6780
+ const readStream = createReadStream(absPath);
6781
+ await new Promise((res, rej) => {
6782
+ const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...sshArgs], { stdin: "pipe", stdout: "inherit", stderr: "inherit" }) : __require("child_process").spawn("ssh", sshArgs, { stdio: ["pipe", "inherit", "inherit"] });
6783
+ const stdinStream = proc.stdin;
6784
+ readStream.pipe(stdinStream);
6785
+ readStream.on("error", rej);
6786
+ if (proc.exited) {
6787
+ proc.exited.then((code) => {
6788
+ if (code !== 0)
6789
+ rej(new EpdError(`Restore command exited with code ${code}`));
6790
+ else
6791
+ res();
6792
+ });
6793
+ } else {
6794
+ proc.on("close", (code) => {
6795
+ if (code !== 0)
6796
+ rej(new EpdError(`Restore command exited with code ${code}`));
6797
+ else
6798
+ res();
6799
+ });
6800
+ }
6801
+ });
6802
+ const elapsed = dur(Date.now() - t0);
6803
+ log.ok(`Successfully restored ${c.bold(fileBase)} into ${c.bold(targetAccessoryName)} (${elapsed})!`);
6804
+ }
6805
+ };
6806
+
5838
6807
  // src/commands/index.ts
5839
6808
  var commands = [
5840
6809
  init,
@@ -5855,7 +6824,12 @@ var commands = [
5855
6824
  dns3,
5856
6825
  hetzner,
5857
6826
  update,
5858
- auth
6827
+ auth,
6828
+ maintenance,
6829
+ ssl,
6830
+ top,
6831
+ backup,
6832
+ restore
5859
6833
  ];
5860
6834
 
5861
6835
  // src/cli.ts
@@ -26,7 +26,7 @@ export default defineConfig({
26
26
  ],
27
27
  },
28
28
  {
29
- text: "v0.4.0",
29
+ text: "v0.5.0",
30
30
  items: [
31
31
  { text: "Releases & Changelog", link: "https://github.com/FabioPlunser/epd/releases" },
32
32
  { text: "NPM Package", link: "https://www.npmjs.com/package/@fabioplunser/epd" },
@@ -120,6 +120,23 @@ ssh:
120
120
  proxy_jump: bastion.example.com
121
121
  ```
122
122
 
123
+ `ssh.user` is the login for every server. A non-root user must be able to run
124
+ `sudo -n` without a password — epd escalates for docker, systemd and the files
125
+ under `/var/lib/epd`:
126
+
127
+ ```
128
+ deploy ALL=(ALL) NOPASSWD:ALL
129
+ ```
130
+
131
+ To use a different login on a single server, write it into the host entry —
132
+ that wins over `ssh.user`:
133
+
134
+ ```yaml
135
+ servers:
136
+ web:
137
+ hosts: ["deploy@203.0.113.10", "ubuntu@203.0.113.11"]
138
+ ```
139
+
123
140
  ---
124
141
 
125
142
  ## Next Step
@@ -184,6 +184,7 @@ epd proxy status # View Traefik container status
184
184
  epd proxy logs -f # Tail live Traefik access & error logs
185
185
  epd proxy routes # View rendered dynamic routing configuration
186
186
  epd proxy reboot # Restart Traefik proxy
187
+ epd proxy dashboard # Open secure SSH tunnel to Traefik web UI & launch browser
187
188
  ```
188
189
 
189
190
  ---
@@ -236,3 +237,63 @@ epd remove
236
237
  epd remove -y # Non-interactive confirmation
237
238
  epd remove --keep-data # Leave persistent volume data on disk
238
239
  ```
240
+
241
+ ---
242
+
243
+ ## `epd maintenance`
244
+
245
+ Toggle or inspect zero-downtime maintenance mode for this application. Injects an instant Traefik routing override that presents a responsive 503 Maintenance page to all public visitors without stopping backend containers or dropping TLS certificates.
246
+
247
+ ```bash
248
+ epd maintenance status # Check if maintenance mode is active
249
+ epd maintenance on # Enable maintenance mode
250
+ epd maintenance on -m "Migrating database. Back at 15:00 UTC."
251
+ epd maintenance off # Disable maintenance mode and restore traffic
252
+ ```
253
+
254
+ ---
255
+
256
+ ## `epd ssl`
257
+
258
+ Inspect and verify Let's Encrypt SSL/TLS certificates managed by Traefik across your servers (aliased as `epd certs`).
259
+
260
+ ```bash
261
+ epd ssl # Display table of domains, SANs, issuers, and days remaining
262
+ epd ssl --json # Output certificate metadata as JSON
263
+ epd ssl --host 203.0.113.10 # Query a specific host
264
+ ```
265
+
266
+ ---
267
+
268
+ ## `epd top`
269
+
270
+ Real-time multi-server metrics monitor (aliased as `epd stats`). Displays CPU %, memory consumption, container processes, network I/O, disk usage, and host load averages across all servers.
271
+
272
+ ```bash
273
+ epd top # Launch interactive streaming metrics dashboard (2s refresh)
274
+ epd top --once # Print a single metrics snapshot and exit
275
+ epd top --host 203.0.113.10 # Monitor a specific server
276
+ ```
277
+
278
+ ---
279
+
280
+ ## `epd backup`
281
+
282
+ Create compressed database and volume backups from running accessories (PostgreSQL, MySQL, MariaDB, MongoDB, or generic persistent volumes).
283
+
284
+ ```bash
285
+ epd backup # Back up all configured accessories
286
+ epd backup db # Back up a specific database accessory
287
+ epd backup db -o ./my-backup.sql.gz # Custom local output file path
288
+ ```
289
+
290
+ ---
291
+
292
+ ## `epd restore`
293
+
294
+ Restore a database or volume snapshot into a live running accessory.
295
+
296
+ ```bash
297
+ epd restore ./backups/myapp-db-2026-09-07.sql.gz
298
+ epd restore ./backups/myapp-db.sql.gz --accessory db -y # Skip confirmation prompt
299
+ ```
@@ -50,6 +50,9 @@ process:
50
50
  # ==============================================================================
51
51
  ssh:
52
52
  user: root # SSH username (default: root)
53
+ # Any non-root user needs passwordless sudo.
54
+ # Override it per server by writing the login
55
+ # into the host entry: "deploy@203.0.113.10".
53
56
  port: 22 # SSH port (default: 22)
54
57
  key: ~/.ssh/id_ed25519 # Path to explicit private key
55
58
  proxy_jump: bastion.net # Optional jump host / bastion
@@ -63,6 +66,7 @@ servers:
63
66
  web:
64
67
  hosts: # Target servers (IPs or Hetzner selectors)
65
68
  - 203.0.113.10
69
+ - deploy@203.0.113.11 # Per-host ssh login, overrides ssh.user
66
70
  - hetzner:prod-web-1 # Dynamic Hetzner query by server name
67
71
  - hetzner:label:app=web # Dynamic Hetzner query by label selector
68
72
  replicas: 2 # Number of container replicas per host
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@fabioplunser/epd",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Easy Project Deployer — deploy any project to one or many servers with Docker or PM2, fronted by Traefik.",
5
5
  "type": "module",
6
6
  "author": "Fabio Plünser",
7
7
  "license": "MIT",
8
- "homepage": "https://github.com/FabioPlunser/epd#readme",
8
+ "homepage": "https://epd.peppi.dev",
9
9
  "repository": {
10
10
  "type": "git",
11
11
  "url": "https://github.com/FabioPlunser/epd"
@@ -33,6 +33,9 @@
33
33
  "LICENSE",
34
34
  "docs"
35
35
  ],
36
+ "workspaces": [
37
+ "apps/*"
38
+ ],
36
39
  "publishConfig": {
37
40
  "access": "public"
38
41
  },
@@ -44,6 +47,8 @@
44
47
  "build:binaries": "bun run scripts/build-all.ts",
45
48
  "typecheck": "tsc --noEmit",
46
49
  "test": "bun test",
50
+ "web:dev": "cd apps/web && bun run dev",
51
+ "web:build": "cd apps/web && bun run build",
47
52
  "docs:dev": "vitepress dev docs",
48
53
  "docs:build": "vitepress build docs",
49
54
  "docs:preview": "vitepress preview docs",
@@ -53,7 +58,7 @@
53
58
  "bun": ">=1.1.0"
54
59
  },
55
60
  "devDependencies": {
56
- "@types/bun": "latest",
61
+ "@types/bun": "^1.4.1",
57
62
  "typescript": "^5.6.0",
58
63
  "vitepress": "^1.6.4"
59
64
  }