@fabioplunser/epd 0.5.13 → 0.5.15

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
@@ -16,11 +16,24 @@ var __require = import.meta.require;
16
16
  function setVerbose(v) {
17
17
  verbose = v;
18
18
  }
19
+ function registerSecret(value) {
20
+ if (value && value.length >= 4)
21
+ knownSecrets.add(value);
22
+ }
23
+ function redact(text) {
24
+ let out = text;
25
+ for (const secret of [...knownSecrets].sort((a, b) => b.length - a.length)) {
26
+ out = out.split(secret).join(REDACTED);
27
+ }
28
+ for (const [re, replacement] of SECRET_PATTERNS)
29
+ out = out.replace(re, replacement);
30
+ return out;
31
+ }
19
32
  function stamp() {
20
33
  const s = ((Date.now() - started) / 1000).toFixed(1).padStart(5, " ");
21
34
  return c.gray(`${s}s`);
22
35
  }
23
- var useColor, wrap = (code) => (s) => useColor ? `\x1B[${code}m${s}\x1B[0m` : s, c, verbose = false, started, log, EpdError;
36
+ var useColor, wrap = (code) => (s) => useColor ? `\x1B[${code}m${s}\x1B[0m` : s, c, verbose = false, knownSecrets, REDACTED = "[REDACTED]", SECRET_PATTERNS, started, log, EpdError;
24
37
  var init_log = __esm(() => {
25
38
  useColor = process.stdout.isTTY && process.env.NO_COLOR === undefined;
26
39
  c = {
@@ -34,33 +47,45 @@ var init_log = __esm(() => {
34
47
  cyan: wrap("36"),
35
48
  gray: wrap("90")
36
49
  };
50
+ knownSecrets = new Set;
51
+ SECRET_PATTERNS = [
52
+ [/(-----BEGIN [A-Z ]*PRIVATE KEY-----)[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----)/g, `$1${REDACTED}$2`],
53
+ [/(\bBearer\s+)[A-Za-z0-9._~+/=-]+/gi, `$1${REDACTED}`],
54
+ [/\b(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, REDACTED],
55
+ [/("(?:apiToken|api_token|password|passwd|secret|token)"\s*:\s*")[^"]*"/gi, `$1${REDACTED}"`],
56
+ [/(?<![.\w])((?:password|passwd|secret|token|api_token)\s*[:=]\s*)\S+/gi, `$1${REDACTED}`],
57
+ [/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Za-z0-9_]*=)\S+/g, `$1${REDACTED}`]
58
+ ];
37
59
  started = Date.now();
38
60
  log = {
39
61
  step(msg) {
40
- console.log(`${stamp()} ${c.blue("\u203A")} ${c.bold(msg)}`);
62
+ console.log(`${stamp()} ${c.blue("\u203A")} ${c.bold(redact(msg))}`);
41
63
  },
42
64
  info(msg) {
43
- console.log(`${stamp()} ${msg}`);
65
+ console.log(`${stamp()} ${redact(msg)}`);
44
66
  },
45
67
  ok(msg) {
46
- console.log(`${stamp()} ${c.green("\u2713")} ${msg}`);
68
+ console.log(`${stamp()} ${c.green("\u2713")} ${redact(msg)}`);
47
69
  },
48
70
  warn(msg) {
49
- console.log(`${stamp()} ${c.yellow("!")} ${msg}`);
71
+ console.log(`${stamp()} ${c.yellow("!")} ${redact(msg)}`);
50
72
  },
51
73
  error(msg) {
52
- console.error(`${stamp()} ${c.red("\u2717")} ${msg}`);
74
+ console.error(`${stamp()} ${c.red("\u2717")} ${redact(msg)}`);
53
75
  },
54
76
  debug(msg) {
55
77
  if (verbose)
56
- console.log(`${stamp()} ${c.gray("\xB7")} ${c.gray(msg)}`);
78
+ console.log(`${stamp()} ${c.gray("\xB7")} ${c.gray(redact(msg))}`);
57
79
  },
58
80
  plain(msg) {
81
+ console.log(redact(msg));
82
+ },
83
+ template(msg) {
59
84
  console.log(msg);
60
85
  },
61
86
  host(host, msg) {
62
87
  const p = c.magenta(host.padEnd(15).slice(0, 15));
63
- for (const line of msg.split(`
88
+ for (const line of redact(msg).split(`
64
89
  `))
65
90
  if (line.length)
66
91
  console.log(`${stamp()} ${p} ${line}`);
@@ -69,9 +94,9 @@ var init_log = __esm(() => {
69
94
  EpdError = class EpdError extends Error {
70
95
  hint;
71
96
  constructor(message, hint) {
72
- super(message);
73
- this.hint = hint;
97
+ super(redact(message));
74
98
  this.name = "EpdError";
99
+ this.hint = hint === undefined ? undefined : redact(hint);
75
100
  }
76
101
  };
77
102
  });
@@ -88,6 +113,21 @@ function hash32(s) {
88
113
  function shq(s) {
89
114
  return `'${String(s).replaceAll("'", `'\\''`)}'`;
90
115
  }
116
+ async function retry(fn, opts) {
117
+ let last;
118
+ for (let i = 1;i <= opts.attempts; i++) {
119
+ try {
120
+ return await fn(i);
121
+ } catch (e) {
122
+ last = e;
123
+ if (i < opts.attempts) {
124
+ opts.onRetry?.(e, i);
125
+ await sleep(opts.delayMs);
126
+ }
127
+ }
128
+ }
129
+ throw last;
130
+ }
91
131
  async function pool(items, limit, fn) {
92
132
  const out = new Array(items.length);
93
133
  let next = 0;
@@ -203,8 +243,108 @@ var init_prompt = __esm(() => {
203
243
  init_log();
204
244
  });
205
245
 
246
+ // src/core/names.ts
247
+ function paths(cfg) {
248
+ const root = cfg.remoteRoot;
249
+ const app = `${root}/apps/${cfg.name}`;
250
+ return {
251
+ root,
252
+ app,
253
+ envFile: `${app}/env`,
254
+ state: `${app}/state.json`,
255
+ lock: `${app}/lock`,
256
+ releases: `${app}/releases`,
257
+ current: `${app}/current`,
258
+ shared: `${app}/shared`,
259
+ proxyDir: `${root}/proxy`,
260
+ proxyStatic: `${root}/proxy/traefik.yml`,
261
+ proxyDynamicDir: `${root}/proxy/dynamic`,
262
+ proxyAppsDir: `${root}/proxy/apps`,
263
+ proxyApp: `${root}/proxy/apps/${cfg.name}.json`,
264
+ proxyEnv: `${root}/proxy/env`,
265
+ proxyDynamic: `${root}/proxy/dynamic/${cfg.name}.yml`,
266
+ acmeDir: `${root}/proxy/acme`,
267
+ portsDir: `${root}/ports`,
268
+ proxyBin: `${root}/proxy/bin/traefik`,
269
+ proxyEcosystem: `${root}/proxy/pm2.json`,
270
+ proxyLogDir: `${root}/proxy/log`
271
+ };
272
+ }
273
+ function serviceIndex(cfg, svc) {
274
+ const names = cfg.services.map((s) => s.name).sort();
275
+ const idx = names.indexOf(svc.name);
276
+ if (idx >= MAX_SERVICES) {
277
+ throw new EpdError(`too many servers: epd reserves ports for ${MAX_SERVICES} per app`, "Split the extra ones into their own epd.yml.");
278
+ }
279
+ return idx;
280
+ }
281
+ function hostPort(cfg, svc, slot, replica) {
282
+ if (replica >= MAX_REPLICAS) {
283
+ throw new EpdError(`${svc.name}: at most ${MAX_REPLICAS} replicas per server are supported`, "Add more servers instead, or run several epd apps.");
284
+ }
285
+ const s = SLOTS.indexOf(slot);
286
+ if (svc.hostPort !== undefined) {
287
+ return svc.hostPort + s * MAX_REPLICAS + replica;
288
+ }
289
+ const j = serviceIndex(cfg, svc);
290
+ return cfg.portBase + j * PORTS_PER_SERVICE + s * MAX_REPLICAS + replica;
291
+ }
292
+ function portBlock(cfg) {
293
+ return { from: cfg.portBase, to: cfg.portBase + MAX_SERVICES * PORTS_PER_SERVICE - 1 };
294
+ }
295
+ function usesHostPorts(cfg) {
296
+ return cfg.mode === "process" || cfg.proxy.crossHost || !cfg.proxy.enabled;
297
+ }
298
+ function privateAddress(cfg, host) {
299
+ return cfg.proxy.privateIps[host] ?? host;
300
+ }
301
+ function bindAddress(cfg, host) {
302
+ return cfg.proxy.privateIps[host] ?? (cfg.proxy.enabled ? "0.0.0.0" : "127.0.0.1");
303
+ }
304
+ function endpointsFor(cfg, svc, slot, serverHost, containerIp) {
305
+ const out = [];
306
+ for (let i = 0;i < svc.replicas; i++) {
307
+ if (cfg.mode === "process") {
308
+ const port = hostPort(cfg, svc, slot, i);
309
+ out.push({
310
+ url: `http://127.0.0.1:${port}`,
311
+ probeHost: "127.0.0.1",
312
+ probePort: port,
313
+ id: processName(cfg.name, svc.name, slot, i),
314
+ replica: i
315
+ });
316
+ } else if (cfg.proxy.crossHost) {
317
+ const port = hostPort(cfg, svc, slot, i);
318
+ out.push({
319
+ url: `http://${privateAddress(cfg, serverHost)}:${port}`,
320
+ probeHost: "127.0.0.1",
321
+ probePort: port,
322
+ id: containerName(cfg.name, svc.name, slot, i),
323
+ replica: i
324
+ });
325
+ } else {
326
+ const id = containerName(cfg.name, svc.name, slot, i);
327
+ out.push({
328
+ url: `http://${id}:${svc.port}`,
329
+ probeHost: containerIp?.(id) ?? id,
330
+ probePort: svc.port,
331
+ id,
332
+ replica: i
333
+ });
334
+ }
335
+ }
336
+ return out;
337
+ }
338
+ var SLOTS, otherSlot = (s) => s === "blue" ? "green" : "blue", MAX_REPLICAS = 16, PORTS_PER_SERVICE = 32, MAX_SERVICES = 8, MAX_NAME_LENGTH = 63, NAME_PATTERN, isValidName = (name) => name.length <= MAX_NAME_LENGTH && NAME_PATTERN.test(name), containerName = (app, svc, slot, i) => `epd-${app}-${svc}-${slot}-${i}`, accessoryContainer = (app, name) => `epd-${app}-acc-${name}`, processName = (app, svc, slot, i) => `epd-${app}-${svc}-${slot}-${i}`, PROXY_CONTAINER = "epd-proxy", PROXY_PROCESS = "epd-proxy";
339
+ var init_names = __esm(() => {
340
+ init_log();
341
+ SLOTS = ["blue", "green"];
342
+ NAME_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
343
+ });
344
+
206
345
  // src/config/load.ts
207
346
  import { existsSync, readFileSync } from "fs";
347
+ import { isIPv6 } from "net";
208
348
  import { dirname, join, resolve } from "path";
209
349
  import { homedir } from "os";
210
350
  function findConfigFile(startDir) {
@@ -281,6 +421,18 @@ function interpolateText(text, env, file) {
281
421
  throw new EpdError(`${file}: environment variable \${${name}} is not set`, `Export it, add it to .env, or write \${${name}:-fallback}.`);
282
422
  });
283
423
  }
424
+ function bareRegistryPassword(text) {
425
+ let inRegistry = false;
426
+ return text.split(`
427
+ `).map((line) => {
428
+ if (/^[^\s#]/.test(line))
429
+ inRegistry = /^registry\s*:/.test(line);
430
+ if (!inRegistry || !/\bpassword\s*:|^\s*-\s/.test(line))
431
+ return line;
432
+ return line.replace(/(?<!\$)\$\{([^}]*)\}/g, "$1");
433
+ }).join(`
434
+ `);
435
+ }
284
436
  function deepMerge(base, overlay) {
285
437
  const out = Array.isArray(base) ? [...base] : { ...base };
286
438
  for (const [k, v] of Object.entries(overlay)) {
@@ -296,15 +448,24 @@ function deepMerge(base, overlay) {
296
448
  function fail(path, msg, hint) {
297
449
  throw new EpdError(`${path}: ${msg}`, hint);
298
450
  }
451
+ function nameHint(name) {
452
+ const lower = name.toLowerCase();
453
+ const suggestion = lower !== name && isValidName(lower) ? `Use "${lower}" instead. ` : "";
454
+ return `Got ${JSON.stringify(name)}. ${suggestion}` + "Container and state names derive from this name, so renaming it starts new containers and leaves the old ones running.";
455
+ }
299
456
  function takeHostUser(entry, path, users) {
457
+ if (entry.startsWith("hetzner:"))
458
+ return entry;
300
459
  const at = entry.lastIndexOf("@");
301
460
  if (at < 0)
302
- return entry;
461
+ return check(entry, path, sshHostProblem, 'Write a host name or IP address, e.g. "10.0.0.1".');
303
462
  const user = entry.slice(0, at);
304
463
  const host = entry.slice(at + 1);
305
464
  if (!user || !host) {
306
465
  fail(path, `"${entry}" is not a valid host`, 'Write it as "user@host", e.g. "deploy@10.0.0.1".');
307
466
  }
467
+ check(user, path, sshUserProblem, 'Write the login before the "@", e.g. "deploy@10.0.0.1".');
468
+ check(host, path, sshHostProblem, 'Write a host name or IP address, e.g. "10.0.0.1".');
308
469
  const seen = users[host];
309
470
  if (seen && seen !== user) {
310
471
  fail(path, `host ${host} is listed as both ${seen}@${host} and ${user}@${host}`, "Use one ssh user per host.");
@@ -377,6 +538,14 @@ function asDict(v, path) {
377
538
  }
378
539
  fail(path, "expected a mapping");
379
540
  }
541
+ function asMap(v, path) {
542
+ if (v === undefined || v === null)
543
+ return {};
544
+ if (typeof v !== "object" || Array.isArray(v)) {
545
+ fail(path, `expected a mapping, got ${Array.isArray(v) ? "a list" : typeof v}`);
546
+ }
547
+ return v;
548
+ }
380
549
  function checkKeys(obj, allowed, path) {
381
550
  for (const k of Object.keys(obj)) {
382
551
  if (!allowed.includes(k)) {
@@ -399,12 +568,118 @@ function levenshtein2(a, b) {
399
568
  function expandHome(p) {
400
569
  return p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
401
570
  }
571
+ function hostnameProblem(h) {
572
+ const port = HOST_PORT.exec(h);
573
+ const name = port ? h.slice(0, port.index) : h;
574
+ if (port && (Number(port[1]) < 1 || Number(port[1]) > 65535))
575
+ return "has an invalid port";
576
+ const wild = name.startsWith("*.") ? name.slice(2) : name;
577
+ const body = wild.endsWith(".") ? wild.slice(0, -1) : wild;
578
+ const ok = body.length > 0 && body.length <= 253 && body.split(".").every((label) => HOST_LABEL.test(label));
579
+ return ok ? null : "is not a valid hostname";
580
+ }
581
+ function routeHostProblem(h) {
582
+ const m = BRACKETED_IPV6.exec(h);
583
+ if (!m)
584
+ return hostnameProblem(h);
585
+ if (!isIPv6(m[1]))
586
+ return "is not a valid IPv6 address";
587
+ if (m[2] !== undefined && (Number(m[2]) < 1 || Number(m[2]) > 65535))
588
+ return "has an invalid port";
589
+ return null;
590
+ }
591
+ function urlPathProblem(p) {
592
+ if (!p.startsWith("/"))
593
+ return "must start with /";
594
+ if (/[\s`'"\\\x00-\x1f\x7f]/.test(p))
595
+ return "must not contain spaces, quotes, backticks, backslashes or control characters";
596
+ if (p.split("/").includes(".."))
597
+ return 'must not contain ".." segments';
598
+ return null;
599
+ }
600
+ function asInt(v, path, dflt, min, max) {
601
+ if (v === undefined || v === null) {
602
+ if (dflt !== undefined)
603
+ return dflt;
604
+ fail(path, "is required");
605
+ }
606
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\s*\d+\s*$/.test(v) ? Number(v) : NaN;
607
+ if (!Number.isInteger(n) || n < min || n > max) {
608
+ fail(path, `must be a whole number from ${min} to ${max}, got ${JSON.stringify(v)}`);
609
+ }
610
+ return n;
611
+ }
612
+ function absolutePathProblem(p) {
613
+ if (!p.startsWith("/"))
614
+ return "must be an absolute path";
615
+ if (/[\x00-\x1f\x7f]/.test(p))
616
+ return "must not contain newlines or control characters";
617
+ if (p.split("/").includes(".."))
618
+ return 'must not contain ".." segments';
619
+ return null;
620
+ }
621
+ function check(value, path, problem, hint) {
622
+ const why = problem(value);
623
+ if (why)
624
+ fail(path, `${JSON.stringify(value)} ${why}`, hint);
625
+ return value;
626
+ }
627
+ function checkEach(values, path, problem, hint) {
628
+ values.forEach((v, i) => check(v, `${path}[${i}]`, problem, hint));
629
+ return values;
630
+ }
631
+ function imageProblem(ref) {
632
+ return ref.length <= 255 && IMAGE_REF.test(ref) ? null : "is not a valid image reference";
633
+ }
634
+ function sshHostProblem(h) {
635
+ return SSH_HOST.test(h) ? null : "is not a valid host name or address";
636
+ }
637
+ function sshUserProblem(u) {
638
+ return SSH_USER.test(u) ? null : "is not a valid ssh login name";
639
+ }
640
+ function envNameProblem(n) {
641
+ return ENV_NAME.test(n) ? null : "is not a valid environment variable name";
642
+ }
643
+ function checkEnvMap(env, path) {
644
+ for (const [k, v] of Object.entries(env)) {
645
+ check(k, path, envNameProblem, ENV_NAME_HINT);
646
+ if (/[\r\n\0]/.test(v))
647
+ fail(`${path}.${k}`, "value must not contain newlines", "Each variable is one line in the env file.");
648
+ }
649
+ return env;
650
+ }
651
+ function checkBuildSecrets(secrets) {
652
+ for (const [id, envName] of Object.entries(secrets)) {
653
+ check(envName, `epd.yml.build.secrets.${id}`, envNameProblem, ENV_NAME_HINT);
654
+ }
655
+ return secrets;
656
+ }
657
+ function parseEnvBlock(v, path) {
658
+ if (Array.isArray(v))
659
+ return { clear: checkEnvMap(asDict(v, path), path), secret: [] };
660
+ const m = asMap(v, path);
661
+ const bare = !("clear" in m) && !("secret" in m);
662
+ const clearPath = bare ? path : `${path}.clear`;
663
+ return {
664
+ clear: checkEnvMap(asDict(m.clear ?? (bare ? m : {}), clearPath), clearPath),
665
+ secret: checkEach(asList(m.secret, `${path}.secret`), `${path}.secret`, envNameProblem, ENV_NAME_HINT)
666
+ };
667
+ }
668
+ function looksLikeToken(v) {
669
+ if (/^(gh[pousr]_|github_pat_|glpat-)/.test(v))
670
+ return true;
671
+ return v.length > 30 && /^[A-Za-z0-9]+$/.test(v) && /[a-z]/.test(v) && /[A-Z]/.test(v) && /[0-9]/.test(v);
672
+ }
402
673
  function parseRoute(raw, path, defaults) {
403
674
  if (typeof raw === "string") {
404
675
  const s = raw.trim();
405
676
  const slash = s.indexOf("/");
406
677
  const host = slash === -1 ? s : s.slice(0, slash);
407
678
  const p = slash === -1 ? undefined : s.slice(slash);
679
+ if (host !== "*" && host !== "")
680
+ check(host, path, routeHostProblem, HOST_HINT);
681
+ if (p && p !== "/")
682
+ check(p, path, urlPathProblem, PATH_HINT);
408
683
  return {
409
684
  hosts: host === "*" || host === "" ? [] : [host],
410
685
  path: p && p !== "/" ? p : undefined,
@@ -440,12 +715,13 @@ function parseRoute(raw, path, defaults) {
440
715
  ...asList(o.host ?? o.domain, `${path}.host`),
441
716
  ...asList(o.hosts ?? o.domains, `${path}.hosts`)
442
717
  ].filter((h) => h !== "*");
718
+ checkEach(hosts, `${path}.host`, routeHostProblem, HOST_HINT);
443
719
  const redirectTo = o.redirect ? asString(o.redirect, `${path}.redirect`) : undefined;
444
720
  return {
445
721
  hosts,
446
- path: o.path ? asString(o.path, `${path}.path`) : undefined,
722
+ path: o.path ? check(asString(o.path, `${path}.path`), `${path}.path`, urlPathProblem, PATH_HINT) : undefined,
447
723
  stripPath: asBool(o.strip_path, `${path}.strip_path`, false),
448
- port: asNumber(o.port, `${path}.port`, defaults.port),
724
+ port: asPort(o.port, `${path}.port`, defaults.port),
449
725
  entrypoint: o.entrypoint ? asString(o.entrypoint, `${path}.entrypoint`) : undefined,
450
726
  ssl: asBool(o.ssl, `${path}.ssl`, defaults.ssl && hosts.length > 0),
451
727
  redirect: redirectTo ? { to: redirectTo, permanent: asBool(o.permanent, `${path}.permanent`, true) } : undefined,
@@ -461,14 +737,14 @@ function parseHealth(raw, path, dflt) {
461
737
  if (raw === false)
462
738
  return { ...dflt, path: null };
463
739
  if (typeof raw === "string")
464
- return { ...dflt, path: raw };
740
+ return { ...dflt, path: check(raw, path, urlPathProblem, PATH_HINT) };
465
741
  if (typeof raw !== "object")
466
742
  fail(path, "expected a mapping, a path string, or false");
467
743
  const o = raw;
468
744
  checkKeys(o, ["path", "port", "status", "timeout", "interval", "delay", "host"], path);
469
745
  return {
470
- path: o.path === false || o.path === null ? null : asString(o.path, `${path}.path`, dflt.path ?? "/"),
471
- port: o.port !== undefined ? asNumber(o.port, `${path}.port`) : dflt.port,
746
+ path: o.path === false || o.path === null ? null : check(asString(o.path, `${path}.path`, dflt.path ?? "/"), `${path}.path`, urlPathProblem, PATH_HINT),
747
+ port: o.port !== undefined ? asPort(o.port, `${path}.port`) : dflt.port,
472
748
  status: asString(o.status, `${path}.status`, dflt.status),
473
749
  timeout: asNumber(o.timeout, `${path}.timeout`, dflt.timeout),
474
750
  interval: asNumber(o.interval, `${path}.interval`, dflt.interval),
@@ -485,6 +761,7 @@ function loadConfig(opts = {}) {
485
761
  const destination = opts.destination;
486
762
  const env = loadEnvironment(root, destination);
487
763
  let raw = parseYaml(configPath, env);
764
+ let overlay;
488
765
  if (destination) {
489
766
  const overlays = [
490
767
  join(root, `epd.${destination}.yml`),
@@ -494,12 +771,56 @@ function loadConfig(opts = {}) {
494
771
  if (!overlays.length) {
495
772
  throw new EpdError(`no config found for destination "${destination}"`, `Create ${join(root, `epd.${destination}.yml`)} with the values that differ.`);
496
773
  }
497
- raw = deepMerge(raw, parseYaml(overlays[0], env));
774
+ overlay = { file: overlays[0], raw: parseYaml(overlays[0], env) };
775
+ raw = deepMerge(raw, overlay.raw);
776
+ }
777
+ const config = locate({ base: configPath, overlay }, () => normalize(raw, configPath, root, destination));
778
+ const registryPassword = config.registry ? [config.registry.passwordEnv] : [];
779
+ for (const name of [...registryPassword, ...config.secrets, ...config.services.flatMap((s) => s.secrets), ...config.accessories.flatMap((a) => a.secrets), ...Object.values(config.build?.secrets ?? {})]) {
780
+ registerSecret(env[name]);
498
781
  }
499
- return { config: normalize(raw, configPath, root, destination), env, raw };
782
+ return { config, env, raw };
783
+ }
784
+ function locate(files, build) {
785
+ try {
786
+ return build();
787
+ } catch (e) {
788
+ if (e instanceof EpdError && e.message.startsWith("epd.yml")) {
789
+ const rest = e.message.slice("epd.yml".length).replace(/^\./, "");
790
+ const sep = rest.indexOf(": ");
791
+ const keyPath = sep === -1 ? rest : rest.slice(0, sep);
792
+ const fromOverlay = !!files.overlay && !!keyPath && definesKey(files.overlay.raw, keyPath);
793
+ const file = fromOverlay ? files.overlay.file : files.base;
794
+ throw new EpdError(rest ? `${file}: ${rest}` : file, e.hint);
795
+ }
796
+ throw e;
797
+ }
798
+ }
799
+ function definesKey(raw, keyPath) {
800
+ const tokens = keyPath.replace(/\[(\d+)\]/g, ".$1").split(".");
801
+ const candidates = [tokens];
802
+ if (tokens[0] === "servers") {
803
+ candidates.push(["services", ...tokens.slice(1)]);
804
+ if (tokens[1] === "web")
805
+ candidates.push(tokens.slice(2));
806
+ }
807
+ return candidates.some((c) => c.length > 0 && walk(raw, c));
808
+ }
809
+ function walk(raw, tokens) {
810
+ let cur = raw;
811
+ for (const t of tokens) {
812
+ if (Array.isArray(cur))
813
+ return true;
814
+ if (!cur || typeof cur !== "object" || !(t in cur))
815
+ return false;
816
+ cur = cur[t];
817
+ }
818
+ return true;
500
819
  }
501
820
  function parseYaml(file, env) {
502
- const text = interpolateText(readFileSync(file, "utf8"), env, file);
821
+ return parseMapping(interpolateText(bareRegistryPassword(readFileSync(file, "utf8")), env, file), file);
822
+ }
823
+ function parseMapping(text, file) {
503
824
  let parsed;
504
825
  try {
505
826
  parsed = Bun.YAML.parse(text);
@@ -515,13 +836,12 @@ function parseYaml(file, env) {
515
836
  function normalize(raw, configPath, root, destination) {
516
837
  checkKeys(raw, TOP_LEVEL_KEYS, "epd.yml");
517
838
  const name = asString(raw.name, "epd.yml.name");
518
- if (!/^[a-z0-9][a-z0-9_-]*$/i.test(name)) {
519
- fail("epd.yml.name", "must be alphanumeric with dashes or underscores", `Got ${JSON.stringify(name)}.`);
520
- }
839
+ if (!isValidName(name))
840
+ fail("epd.yml.name", nameProblem, nameHint(name));
521
841
  const mode = asString(raw.mode, "epd.yml.mode", "docker");
522
842
  if (mode !== "docker" && mode !== "process")
523
843
  fail("epd.yml.mode", `expected "docker" or "process", got ${JSON.stringify(mode)}`);
524
- const proxyRaw = typeof raw.proxy === "boolean" ? { enabled: raw.proxy } : raw.proxy && typeof raw.proxy === "object" && !Array.isArray(raw.proxy) ? raw.proxy : {};
844
+ const proxyRaw = typeof raw.proxy === "boolean" ? { enabled: raw.proxy } : asMap(raw.proxy, "epd.yml.proxy");
525
845
  checkKeys(proxyRaw, [
526
846
  "enabled",
527
847
  "image",
@@ -551,23 +871,23 @@ function normalize(raw, configPath, root, destination) {
551
871
  ...ssl ? { websecure: 443 } : {}
552
872
  };
553
873
  for (const [k, v] of Object.entries(asDict(proxyRaw.entrypoints, "epd.yml.proxy.entrypoints"))) {
554
- entrypoints[k] = asNumber(v, `epd.yml.proxy.entrypoints.${k}`);
874
+ entrypoints[k] = asPort(v, `epd.yml.proxy.entrypoints.${k}`);
555
875
  }
556
876
  const proxy = {
557
877
  enabled: asBool(proxyRaw.enabled, "epd.yml.proxy.enabled", true),
558
- image: asString(proxyRaw.image, "epd.yml.proxy.image", "traefik:v3.3"),
878
+ image: check(asString(proxyRaw.image, "epd.yml.proxy.image", "traefik:v3.3"), "epd.yml.proxy.image", imageProblem, IMAGE_HINT),
559
879
  version: proxyRaw.version ? asString(proxyRaw.version, "epd.yml.proxy.version") : undefined,
560
880
  network: asString(proxyRaw.network, "epd.yml.proxy.network", "epd"),
561
881
  ssl,
562
882
  email: proxyRaw.email ? asString(proxyRaw.email, "epd.yml.proxy.email") : undefined,
563
883
  challenge: asString(proxyRaw.challenge, "epd.yml.proxy.challenge", "http"),
564
884
  dnsProvider: proxyRaw.dns_provider ? asString(proxyRaw.dns_provider, "epd.yml.proxy.dns_provider") : undefined,
565
- dnsEnv: asList(proxyRaw.dns_env, "epd.yml.proxy.dns_env"),
885
+ dnsEnv: checkEach(asList(proxyRaw.dns_env, "epd.yml.proxy.dns_env"), "epd.yml.proxy.dns_env", envNameProblem, ENV_NAME_HINT),
566
886
  acmeServer: proxyRaw.acme_server ? asString(proxyRaw.acme_server, "epd.yml.proxy.acme_server") : undefined,
567
887
  entrypoints,
568
888
  httpsRedirect: asBool(proxyRaw.https_redirect, "epd.yml.proxy.https_redirect", ssl),
569
889
  dashboard: asBool(proxyRaw.dashboard, "epd.yml.proxy.dashboard", false),
570
- dashboardHost: proxyRaw.dashboard_host ? asString(proxyRaw.dashboard_host, "epd.yml.proxy.dashboard_host") : undefined,
890
+ dashboardHost: proxyRaw.dashboard_host ? check(asString(proxyRaw.dashboard_host, "epd.yml.proxy.dashboard_host"), "epd.yml.proxy.dashboard_host", routeHostProblem, HOST_HINT) : undefined,
571
891
  logLevel: asString(proxyRaw.log_level, "epd.yml.proxy.log_level", "INFO"),
572
892
  accessLog: asBool(proxyRaw.access_log, "epd.yml.proxy.access_log", false),
573
893
  crossHost: asBool(proxyRaw.cross_host, "epd.yml.proxy.cross_host", false),
@@ -582,9 +902,9 @@ function normalize(raw, configPath, root, destination) {
582
902
  if (proxy.challenge === "dns" && !proxy.dnsProvider) {
583
903
  fail("epd.yml.proxy.dns_provider", 'is required when challenge is "dns"', "For example: dns_provider: cloudflare");
584
904
  }
585
- const globalEnv = raw.env;
586
- const envClear = asDict(globalEnv?.clear ?? (globalEnv && !("clear" in globalEnv) && !("secret" in globalEnv) ? globalEnv : {}), "epd.yml.env");
587
- const envSecret = asList(globalEnv?.secret, "epd.yml.env.secret");
905
+ const globalEnv = parseEnvBlock(raw.env, "epd.yml.env");
906
+ const envClear = globalEnv.clear;
907
+ const envSecret = globalEnv.secret;
588
908
  const defaultHealth = {
589
909
  path: "/",
590
910
  status: "200-399",
@@ -616,6 +936,8 @@ function normalize(raw, configPath, root, destination) {
616
936
  }
617
937
  const services = Object.entries(servicesRaw).map(([svcName, rawSvc]) => {
618
938
  const p = `epd.yml.servers.${svcName}`;
939
+ if (!isValidName(svcName))
940
+ fail(p, nameProblem, nameHint(svcName));
619
941
  let o;
620
942
  if (Array.isArray(rawSvc))
621
943
  o = { hosts: rawSvc };
@@ -668,27 +990,26 @@ function normalize(raw, configPath, root, destination) {
668
990
  ];
669
991
  if (!hosts.length && !svcHetzner)
670
992
  fail(`${p}.hosts`, "at least one host is required");
671
- const port = asNumber(o.port, `${p}.port`, asNumber(raw.port, "epd.yml.port", 3000));
672
- const hostPort = o.host_port !== undefined ? asNumber(o.host_port, `${p}.host_port`) : undefined;
993
+ const port = asPort(o.port, `${p}.port`, asPort(raw.port, "epd.yml.port", 3000));
994
+ const hostPort = o.host_port !== undefined ? asInt(o.host_port, `${p}.host_port`, undefined, 1, 65535 - (2 * MAX_REPLICAS - 1)) : undefined;
673
995
  const routes = [];
674
996
  for (const d of [...asList(o.domain, `${p}.domain`), ...asList(o.domains, `${p}.domains`)]) {
675
997
  routes.push(parseRoute(d, `${p}.domains`, { port, ssl: proxy.ssl }));
676
998
  }
677
999
  const rawRoutes = o.routes === undefined ? [] : Array.isArray(o.routes) ? o.routes : [o.routes];
678
1000
  rawRoutes.forEach((r, i) => routes.push(parseRoute(r, `${p}.routes[${i}]`, { port, ssl: proxy.ssl })));
679
- const svcEnvRaw = o.env;
680
- const svcEnv = asDict(svcEnvRaw?.clear ?? (svcEnvRaw && !("clear" in svcEnvRaw) && !("secret" in svcEnvRaw) ? svcEnvRaw : {}), `${p}.env`);
1001
+ const svcEnv = parseEnvBlock(o.env, `${p}.env`);
681
1002
  return {
682
1003
  name: svcName,
683
1004
  hosts,
684
1005
  hetzner: svcHetzner,
685
- replicas: asNumber(o.replicas, `${p}.replicas`, 1),
1006
+ replicas: asInt(o.replicas, `${p}.replicas`, 1, 1, 256),
686
1007
  port,
687
1008
  hostPort,
688
1009
  command: o.command === undefined ? undefined : asString(o.command, `${p}.command`),
689
1010
  routes,
690
- env: { ...envClear, ...svcEnv },
691
- secrets: [...envSecret, ...asList(svcEnvRaw?.secret, `${p}.env.secret`)],
1011
+ env: { ...envClear, ...svcEnv.clear },
1012
+ secrets: [...envSecret, ...svcEnv.secret],
692
1013
  volumes: [...asList(raw.volumes, "epd.yml.volumes"), ...asList(o.volumes, `${p}.volumes`)],
693
1014
  labels: { ...asDict(raw.labels, "epd.yml.labels"), ...asDict(o.labels, `${p}.labels`) },
694
1015
  health: parseHealth(o.healthcheck ?? o.health, `${p}.healthcheck`, { ...rootHealth, port: rootHealth.port ?? port }),
@@ -700,12 +1021,14 @@ function normalize(raw, configPath, root, destination) {
700
1021
  stopTimeout: asNumber(o.stop_timeout, `${p}.stop_timeout`, asNumber(raw.stop_timeout, "epd.yml.stop_timeout", 30))
701
1022
  };
702
1023
  });
703
- const accessories = Object.entries(raw.accessories ?? {}).map(([accName, rawAcc]) => {
1024
+ const accessories = Object.entries(asMap(raw.accessories, "epd.yml.accessories")).map(([accName, rawAcc]) => {
704
1025
  const p = `epd.yml.accessories.${accName}`;
705
- const o = rawAcc ?? {};
1026
+ if (!isValidName(accName))
1027
+ fail(p, nameProblem, nameHint(accName));
1028
+ const o = asMap(rawAcc, p);
706
1029
  checkKeys(o, ["image", "host", "env", "volumes", "ports", "command", "docker_options", "routes", "domain", "domains", "port"], p);
707
- const accPort = o.port !== undefined ? asNumber(o.port, `${p}.port`) : undefined;
708
- const accEnvRaw = o.env;
1030
+ const accPort = o.port !== undefined ? asPort(o.port, `${p}.port`) : undefined;
1031
+ const accEnv = parseEnvBlock(o.env, `${p}.env`);
709
1032
  const routes = [];
710
1033
  for (const d of [...asList(o.domain, `${p}.domain`), ...asList(o.domains, `${p}.domains`)]) {
711
1034
  routes.push(parseRoute(d, `${p}.domains`, { port: accPort ?? 80, ssl: proxy.ssl }));
@@ -714,10 +1037,10 @@ function normalize(raw, configPath, root, destination) {
714
1037
  rawRoutes.forEach((r, i) => routes.push(parseRoute(r, `${p}.routes[${i}]`, { port: accPort ?? 80, ssl: proxy.ssl })));
715
1038
  return {
716
1039
  name: accName,
717
- image: asString(o.image, `${p}.image`),
1040
+ image: check(asString(o.image, `${p}.image`), `${p}.image`, imageProblem, IMAGE_HINT),
718
1041
  host: takeHostUser(asString(o.host, `${p}.host`), `${p}.host`, hostUsers),
719
- env: asDict(accEnvRaw?.clear ?? (accEnvRaw && !("clear" in accEnvRaw) && !("secret" in accEnvRaw) ? accEnvRaw : {}), `${p}.env`),
720
- secrets: asList(accEnvRaw?.secret, `${p}.env.secret`),
1042
+ env: accEnv.clear,
1043
+ secrets: accEnv.secret,
721
1044
  volumes: asList(o.volumes, `${p}.volumes`),
722
1045
  ports: asList(o.ports, `${p}.ports`),
723
1046
  command: o.command === undefined ? undefined : asString(o.command, `${p}.command`),
@@ -726,24 +1049,30 @@ function normalize(raw, configPath, root, destination) {
726
1049
  port: accPort
727
1050
  };
728
1051
  });
729
- const regRaw = raw.registry;
1052
+ const regRaw = raw.registry ? asMap(raw.registry, "epd.yml.registry") : undefined;
730
1053
  let registry;
731
1054
  if (regRaw) {
732
1055
  checkKeys(regRaw, ["server", "username", "password"], "epd.yml.registry");
733
1056
  const pw = regRaw.password;
734
1057
  const passwordEnv = Array.isArray(pw) ? asString(pw[0], "epd.yml.registry.password[0]") : asString(pw, "epd.yml.registry.password");
1058
+ if (looksLikeToken(passwordEnv)) {
1059
+ fail("epd.yml.registry.password", "looks like a literal token, not the name of an environment variable", "Put the token in an environment variable (in .env or your CI secrets) and write its name, for example GITHUB_TOKEN.");
1060
+ }
1061
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(passwordEnv)) {
1062
+ fail("epd.yml.registry.password", "must be the upper-case name of an environment variable", "Put the token in an environment variable and write its name, for example GITHUB_TOKEN.");
1063
+ }
735
1064
  registry = {
736
1065
  server: regRaw.server ? asString(regRaw.server, "epd.yml.registry.server") : undefined,
737
1066
  username: asString(regRaw.username, "epd.yml.registry.username"),
738
1067
  passwordEnv
739
1068
  };
740
1069
  }
741
- const image = asString(raw.image, "epd.yml.image", registry ? `${registry.server ? registry.server + "/" : ""}${registry.username}/${name}` : name).toLowerCase();
742
- const buildRaw = raw.build ?? {};
1070
+ const image = check(asString(raw.image, "epd.yml.image", registry ? `${registry.server ? registry.server + "/" : ""}${registry.username}/${name}` : name).toLowerCase(), "epd.yml.image", imageProblem, IMAGE_HINT);
1071
+ const buildRaw = asMap(raw.build, "epd.yml.build");
743
1072
  checkKeys(buildRaw, ["dockerfile", "context", "platform", "target", "args", "secrets", "cache", "remote"], "epd.yml.build");
744
- const sshRaw = raw.ssh ?? {};
1073
+ const sshRaw = asMap(raw.ssh, "epd.yml.ssh");
745
1074
  checkKeys(sshRaw, ["user", "port", "key", "options", "proxy_jump", "control_persist", "sudo_password"], "epd.yml.ssh");
746
- const procRaw = raw.process ?? {};
1075
+ const procRaw = asMap(raw.process, "epd.yml.process");
747
1076
  checkKeys(procRaw, ["exclude", "install", "build", "start", "path", "path_prepend", "source"], "epd.yml.process");
748
1077
  const processCfg = {
749
1078
  exclude: asList(procRaw.exclude, "epd.yml.process.exclude").length ? asList(procRaw.exclude, "epd.yml.process.exclude") : [".git", "node_modules", ".env", ".env.*", "dist", ".next/cache", "tmp", "*.log"],
@@ -754,12 +1083,15 @@ function normalize(raw, configPath, root, destination) {
754
1083
  pathPrepend: asList(procRaw.path_prepend, "epd.yml.process.path_prepend").length ? asList(procRaw.path_prepend, "epd.yml.process.path_prepend") : ["$HOME/.bun/bin", "$HOME/.local/bin", "/usr/local/bin"],
755
1084
  source: asString(procRaw.source, "epd.yml.process.source", "rsync")
756
1085
  };
1086
+ if (processCfg.source !== "rsync" && processCfg.source !== "git") {
1087
+ fail("epd.yml.process.source", `expected "rsync" or "git", got ${JSON.stringify(processCfg.source)}`);
1088
+ }
757
1089
  if (mode === "process" && !processCfg.start) {
758
1090
  fail("epd.yml.process.start", "is required in process mode", `For example:
759
1091
  process:
760
1092
  start: bun run start`);
761
1093
  }
762
- const hooksRaw = raw.hooks ?? {};
1094
+ const hooksRaw = asMap(raw.hooks, "epd.yml.hooks");
763
1095
  checkKeys(hooksRaw, ["pre_build", "pre_deploy", "post_deploy", "on_failure"], "epd.yml.hooks");
764
1096
  const strategy = asString(raw.strategy, "epd.yml.strategy", "rolling");
765
1097
  if (strategy !== "rolling" && strategy !== "parallel")
@@ -779,7 +1111,7 @@ function normalize(raw, configPath, root, destination) {
779
1111
  proxied: asBool(cfRaw.proxied, "epd.yml.cloudflare.proxied", true),
780
1112
  ttl: asNumber(cfRaw.ttl, "epd.yml.cloudflare.ttl", 1),
781
1113
  autoSync: asBool(cfRaw.auto_sync, "epd.yml.cloudflare.auto_sync", true),
782
- domains: cfRaw.domains ? asList(cfRaw.domains, "epd.yml.cloudflare.domains") : undefined
1114
+ domains: cfRaw.domains ? checkEach(asList(cfRaw.domains, "epd.yml.cloudflare.domains"), "epd.yml.cloudflare.domains", hostnameProblem, HOST_HINT) : undefined
783
1115
  };
784
1116
  }
785
1117
  let dnsConfig = undefined;
@@ -803,7 +1135,7 @@ function normalize(raw, configPath, root, destination) {
803
1135
  proxied: asBool(dRaw.proxied, "epd.yml.dns.proxied", provider === "cloudflare"),
804
1136
  ttl: asNumber(dRaw.ttl, "epd.yml.dns.ttl", provider === "hetzner" ? 300 : 1),
805
1137
  autoSync: asBool(dRaw.auto_sync, "epd.yml.dns.auto_sync", true),
806
- domains: dRaw.domains ? asList(dRaw.domains, "epd.yml.dns.domains") : undefined
1138
+ domains: dRaw.domains ? checkEach(asList(dRaw.domains, "epd.yml.dns.domains"), "epd.yml.dns.domains", hostnameProblem, HOST_HINT) : undefined
807
1139
  };
808
1140
  } else if (cloudflare) {
809
1141
  dnsConfig = {
@@ -847,15 +1179,15 @@ function normalize(raw, configPath, root, destination) {
847
1179
  context: asString(buildRaw.context, "epd.yml.build.context", "."),
848
1180
  platform: asString(buildRaw.platform, "epd.yml.build.platform", "linux/amd64"),
849
1181
  target: buildRaw.target ? asString(buildRaw.target, "epd.yml.build.target") : undefined,
850
- args: asDict(buildRaw.args, "epd.yml.build.args"),
851
- secrets: asDict(buildRaw.secrets, "epd.yml.build.secrets"),
1182
+ args: checkEnvMap(asDict(buildRaw.args, "epd.yml.build.args"), "epd.yml.build.args"),
1183
+ secrets: checkBuildSecrets(asDict(buildRaw.secrets, "epd.yml.build.secrets")),
852
1184
  cache: asBool(buildRaw.cache, "epd.yml.build.cache", true),
853
1185
  remote: asBool(buildRaw.remote, "epd.yml.build.remote", false)
854
1186
  },
855
1187
  ssh: {
856
- user: asString(sshRaw.user, "epd.yml.ssh.user", "root"),
1188
+ user: check(asString(sshRaw.user, "epd.yml.ssh.user", "root"), "epd.yml.ssh.user", sshUserProblem),
857
1189
  hostUsers,
858
- port: asNumber(sshRaw.port, "epd.yml.ssh.port", 22),
1190
+ port: asPort(sshRaw.port, "epd.yml.ssh.port", 22),
859
1191
  key: sshRaw.key ? expandHome(asString(sshRaw.key, "epd.yml.ssh.key")) : undefined,
860
1192
  options: asList(sshRaw.options, "epd.yml.ssh.options"),
861
1193
  proxyJump: sshRaw.proxy_jump ? asString(sshRaw.proxy_jump, "epd.yml.ssh.proxy_jump") : undefined,
@@ -878,10 +1210,10 @@ function normalize(raw, configPath, root, destination) {
878
1210
  dns: dnsConfig,
879
1211
  cloudflare,
880
1212
  hetzner: hetznerConfig,
881
- portBase: asNumber(raw.port_base, "epd.yml.port_base", 20000 + hash32(name) % 117 * 256),
1213
+ portBase: asInt(raw.port_base, "epd.yml.port_base", 20000 + hash32(name) % 117 * 256, 1, 65535 - MAX_SERVICES * PORTS_PER_SERVICE + 1),
882
1214
  strategy,
883
- keepReleases: asNumber(raw.keep_releases, "epd.yml.keep_releases", 5),
884
- remoteRoot: asString(raw.remote_root, "epd.yml.remote_root", "/var/lib/epd")
1215
+ keepReleases: asInt(raw.keep_releases, "epd.yml.keep_releases", 5, 1, 1000),
1216
+ remoteRoot: check(asString(raw.remote_root, "epd.yml.remote_root", "/var/lib/epd"), "epd.yml.remote_root", absolutePathProblem, 'Write an absolute path such as "/var/lib/epd".')
885
1217
  };
886
1218
  validateCrossReferences(cfg);
887
1219
  return cfg;
@@ -910,6 +1242,13 @@ function validateCrossReferences(cfg) {
910
1242
  }
911
1243
  }
912
1244
  }
1245
+ if (usesHostPorts(cfg)) {
1246
+ for (const svc of cfg.services) {
1247
+ if (svc.replicas > MAX_REPLICAS) {
1248
+ fail(`epd.yml.servers.${svc.name}.replicas`, `is ${svc.replicas}, but at most ${MAX_REPLICAS} replicas per server are supported when ports are published`, "Add more servers instead, or run several epd apps.");
1249
+ }
1250
+ }
1251
+ }
913
1252
  if (cfg.mode === "process" || cfg.proxy.crossHost) {
914
1253
  for (const svc of cfg.services) {
915
1254
  for (const route of svc.routes) {
@@ -922,11 +1261,20 @@ function validateCrossReferences(cfg) {
922
1261
  }
923
1262
  if (cfg.mode === "docker" && !cfg.registry && cfg.services.some((s) => s.hosts.length > 1)) {}
924
1263
  }
925
- var CONFIG_NAMES, TOP_LEVEL_KEYS;
1264
+ var CONFIG_NAMES, nameProblem, HOST_LABEL, HOST_HINT = 'Use a DNS name such as "example.com", "*.example.com" or an IP address.', PATH_HINT = 'Write a path such as "/health" or "/api".', HOST_PORT, BRACKETED_IPV6, asPort = (v, path, dflt) => asInt(v, path, dflt, 1, 65535), IMAGE_REF, IMAGE_HINT = 'Write an image such as "ghcr.io/acme/api:1.2" or "postgres:17". The repository name must be lower case.', SSH_HOST, SSH_USER, ENV_NAME, ENV_NAME_HINT = "Use letters, digits and underscores, starting with a letter or underscore.", TOP_LEVEL_KEYS;
926
1265
  var init_load = __esm(() => {
927
1266
  init_log();
928
1267
  init_misc();
1268
+ init_names();
929
1269
  CONFIG_NAMES = ["epd.yml", "epd.yaml", ".epd.yml", "config/epd.yml"];
1270
+ nameProblem = `must be ${MAX_NAME_LENGTH} characters or fewer: lowercase letters, digits, dashes or underscores, starting with a letter or digit`;
1271
+ HOST_LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/i;
1272
+ HOST_PORT = /:(\d{1,5})$/;
1273
+ BRACKETED_IPV6 = /^\[([0-9a-fA-F:.]+)\](?::(\d{1,5}))?$/;
1274
+ IMAGE_REF = /^(?:[A-Za-z0-9.-]+(?::\d+)?\/)?(?:[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*\/)*[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$/;
1275
+ SSH_HOST = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
1276
+ SSH_USER = /^[A-Za-z_][A-Za-z0-9._-]*$/;
1277
+ ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
930
1278
  TOP_LEVEL_KEYS = [
931
1279
  "name",
932
1280
  "mode",
@@ -967,6 +1315,8 @@ var init_load = __esm(() => {
967
1315
  });
968
1316
 
969
1317
  // src/util/proc.ts
1318
+ import { existsSync as existsSync2 } from "fs";
1319
+ import { dirname as dirname2, join as join2 } from "path";
970
1320
  async function run(cmd, opts = {}) {
971
1321
  const label = opts.label ?? cmd.join(" ");
972
1322
  log.debug(`local: ${cmd.join(" ")}`);
@@ -1005,18 +1355,39 @@ async function teeStderr(stream) {
1005
1355
  reader.releaseLock();
1006
1356
  }
1007
1357
  }
1358
+ function localShell(kind = "sh") {
1359
+ if (process.platform !== "win32")
1360
+ return kind === "sh" ? "/bin/sh" : "bash";
1361
+ if (windowsBash)
1362
+ return windowsBash;
1363
+ const candidates = [];
1364
+ const git = Bun.which("git");
1365
+ if (git)
1366
+ candidates.push(join2(dirname2(git), "..", "bin", "bash.exe"), join2(dirname2(git), "..", "usr", "bin", "bash.exe"));
1367
+ for (const root of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && join2(process.env.LOCALAPPDATA, "Programs")]) {
1368
+ if (root)
1369
+ candidates.push(join2(root, "Git", "bin", "bash.exe"));
1370
+ }
1371
+ const onPath = Bun.which("bash");
1372
+ if (onPath && !/\\system32\\/i.test(onPath))
1373
+ candidates.push(onPath);
1374
+ const found = candidates.find((c) => existsSync2(c));
1375
+ if (!found) {
1376
+ throw new EpdError("no POSIX shell found on this machine", "On Windows epd runs shell steps through Git Bash. Install Git for Windows (https://git-scm.com/download/win) and open a new terminal.");
1377
+ }
1378
+ return windowsBash = found;
1379
+ }
1008
1380
  async function runShell(script, opts = {}) {
1009
- return run(["/bin/sh", "-c", script], { ...opts, label: opts.label ?? script });
1381
+ return run([localShell(), "-c", script], { ...opts, label: opts.label ?? script });
1010
1382
  }
1011
1383
  async function which(bin) {
1012
- const r = await run(["/bin/sh", "-c", `command -v ${bin}`], { allowFailure: true });
1013
- return r.code === 0 && r.stdout ? r.stdout.split(`
1014
- `)[0].trim() : null;
1384
+ return Bun.which(bin);
1015
1385
  }
1016
1386
  async function requireLocal(bin, hint) {
1017
1387
  if (!await which(bin))
1018
1388
  throw new EpdError(`\`${bin}\` was not found on this machine`, hint);
1019
1389
  }
1390
+ var windowsBash;
1020
1391
  var init_proc = __esm(() => {
1021
1392
  init_log();
1022
1393
  });
@@ -1046,11 +1417,11 @@ function proxyHosts(cfg) {
1046
1417
  }
1047
1418
 
1048
1419
  // src/commands/action.ts
1049
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
1050
- import { dirname as dirname2, join as join2 } from "path";
1420
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
1421
+ import { dirname as dirname3, join as join3 } from "path";
1051
1422
  function detectGitBranch(root) {
1052
1423
  try {
1053
- const head = readFileSync2(join2(root, ".git", "HEAD"), "utf8").trim();
1424
+ const head = readFileSync2(join3(root, ".git", "HEAD"), "utf8").trim();
1054
1425
  if (head.startsWith("ref: refs/heads/")) {
1055
1426
  return head.replace("ref: refs/heads/", "");
1056
1427
  }
@@ -1268,9 +1639,9 @@ Aliases
1268
1639
  event = "push";
1269
1640
  }
1270
1641
  const destination = ctx.loadOptions.destination;
1271
- const defaultFile = join2(root, ".github", "workflows", destination ? `deploy-${destination}.yml` : "deploy.yml");
1642
+ const defaultFile = join3(root, ".github", "workflows", destination ? `deploy-${destination}.yml` : "deploy.yml");
1272
1643
  const targetFile = ctx.values.file || defaultFile;
1273
- if (existsSync2(targetFile) && !ctx.values.force) {
1644
+ if (existsSync3(targetFile) && !ctx.values.force) {
1274
1645
  const ok = interactive() && await confirm(`${targetFile} already exists. Overwrite?`, false);
1275
1646
  if (!ok) {
1276
1647
  log.info(`Aborted. Use ${c.cyan("--force")} to overwrite.`);
@@ -1284,7 +1655,7 @@ Aliases
1284
1655
  destination,
1285
1656
  cfg
1286
1657
  });
1287
- mkdirSync(dirname2(targetFile), { recursive: true });
1658
+ mkdirSync(dirname3(targetFile), { recursive: true });
1288
1659
  writeFileSync(targetFile, yaml);
1289
1660
  log.ok(`wrote ${c.bold(targetFile)}`);
1290
1661
  console.log(`
@@ -1316,10 +1687,111 @@ Next steps:`);
1316
1687
  };
1317
1688
  });
1318
1689
 
1690
+ // src/util/http.ts
1691
+ function backoffFor(attempt, base) {
1692
+ return base * 2 ** attempt;
1693
+ }
1694
+ function retryAfterMs(res) {
1695
+ const raw = res.headers.get("retry-after");
1696
+ if (!raw)
1697
+ return null;
1698
+ const seconds = Number(raw);
1699
+ if (!Number.isFinite(seconds) || seconds < 0)
1700
+ return null;
1701
+ return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);
1702
+ }
1703
+ function redactSecret(text, secret) {
1704
+ if (!secret)
1705
+ return text;
1706
+ return text.split(secret).join("[REDACTED]");
1707
+ }
1708
+ function describeUrl(url) {
1709
+ try {
1710
+ const u = new URL(url);
1711
+ return `${u.host}${u.pathname}`;
1712
+ } catch {
1713
+ return "API";
1714
+ }
1715
+ }
1716
+ async function fetchWithRetry(url, init = {}, opts = {}) {
1717
+ const method = (init.method ?? "GET").toUpperCase();
1718
+ const idempotentRead = method === "GET" || method === "HEAD";
1719
+ const retries = idempotentRead ? opts.retries ?? 2 : 0;
1720
+ const timeoutMs = opts.timeoutMs ?? 30000;
1721
+ const backoffMs = opts.backoffMs ?? 500;
1722
+ for (let attempt = 0;; attempt++) {
1723
+ const canRetry = attempt < retries;
1724
+ let res;
1725
+ try {
1726
+ res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
1727
+ requestMethods.set(res, method);
1728
+ } catch (err) {
1729
+ if (canRetry) {
1730
+ await sleep(backoffFor(attempt, backoffMs));
1731
+ continue;
1732
+ }
1733
+ const where = describeUrl(url);
1734
+ if (err?.name === "TimeoutError" || err?.name === "AbortError") {
1735
+ const after = timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)}s` : `${timeoutMs}ms`;
1736
+ throw new EpdError(`Request to ${where} timed out after ${after}`, "Check your network connection and try again.");
1737
+ }
1738
+ throw new EpdError(`Could not reach ${where}: ${err?.message ?? "network error"}`, "Check your network connection and try again.");
1739
+ }
1740
+ if (canRetry && (res.status === 429 || res.status >= 500)) {
1741
+ const wait = retryAfterMs(res) ?? backoffFor(attempt, backoffMs);
1742
+ await res.body?.cancel().catch(() => {});
1743
+ await sleep(wait);
1744
+ continue;
1745
+ }
1746
+ return res;
1747
+ }
1748
+ }
1749
+ async function readJsonBody(res) {
1750
+ let text = "";
1751
+ try {
1752
+ text = await res.text();
1753
+ } catch {
1754
+ return { data: null, isJson: false, empty: false };
1755
+ }
1756
+ if (!text.trim()) {
1757
+ const emptyOk = res.status === 204 || requestMethods.get(res) === "DELETE";
1758
+ return { data: null, isJson: false, empty: emptyOk };
1759
+ }
1760
+ try {
1761
+ return { data: JSON.parse(text), isJson: true, empty: false };
1762
+ } catch {
1763
+ return { data: null, isJson: false, empty: false };
1764
+ }
1765
+ }
1766
+ function firstString(...values) {
1767
+ for (const v of values) {
1768
+ if (typeof v === "string" && v.trim())
1769
+ return v.trim();
1770
+ }
1771
+ return "";
1772
+ }
1773
+ function statusLabel(res) {
1774
+ return `HTTP ${[res.status, res.statusText].filter(Boolean).join(" ")}`;
1775
+ }
1776
+ var HttpApiError, MAX_RETRY_AFTER_MS = 1e4, requestMethods;
1777
+ var init_http = __esm(() => {
1778
+ init_log();
1779
+ init_misc();
1780
+ HttpApiError = class HttpApiError extends EpdError {
1781
+ status;
1782
+ constructor(message, status, hint) {
1783
+ super(message, hint);
1784
+ this.status = status;
1785
+ this.name = "HttpApiError";
1786
+ }
1787
+ };
1788
+ requestMethods = new WeakMap;
1789
+ });
1790
+
1319
1791
  // src/util/auth.ts
1320
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2, chmodSync } from "fs";
1792
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, readlinkSync, realpathSync, statSync, writeFileSync as writeFileSync2, chmodSync, renameSync, rmSync, unlinkSync } from "fs";
1321
1793
  import { homedir as homedir2 } from "os";
1322
- import { join as join3 } from "path";
1794
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join4 } from "path";
1323
1795
  import { spawn } from "child_process";
1324
1796
  function openBrowser(url) {
1325
1797
  try {
@@ -1338,38 +1810,80 @@ function openBrowser(url) {
1338
1810
  return false;
1339
1811
  }
1340
1812
  }
1813
+ function userHome() {
1814
+ return process.env.HOME || homedir2();
1815
+ }
1341
1816
  function getGlobalAuthPath() {
1342
- const xdgDir = join3(homedir2(), ".config", "epd");
1343
- const fallbackDir = join3(homedir2(), ".epd");
1344
- if (existsSync3(join3(xdgDir, "auth.json")))
1345
- return join3(xdgDir, "auth.json");
1346
- if (existsSync3(join3(fallbackDir, "auth.json")))
1347
- return join3(fallbackDir, "auth.json");
1348
- return join3(xdgDir, "auth.json");
1817
+ const xdgDir = join4(userHome(), ".config", "epd");
1818
+ const fallbackDir = join4(userHome(), ".epd");
1819
+ if (existsSync4(join4(xdgDir, "auth.json")))
1820
+ return join4(xdgDir, "auth.json");
1821
+ if (existsSync4(join4(fallbackDir, "auth.json")))
1822
+ return join4(fallbackDir, "auth.json");
1823
+ return join4(xdgDir, "auth.json");
1824
+ }
1825
+ function corruptAuthError(path) {
1826
+ return new EpdError(`${path} is not valid JSON`, "It may have been half-written or edited by hand. Fix it, or delete it and run `epd auth cloudflare` / `epd auth hetzner` again.");
1349
1827
  }
1350
1828
  function getGlobalAuth() {
1351
1829
  const path = getGlobalAuthPath();
1352
- if (!existsSync3(path))
1830
+ if (!existsSync4(path))
1353
1831
  return {};
1832
+ let raw;
1833
+ try {
1834
+ raw = readFileSync3(path, "utf8");
1835
+ } catch (err) {
1836
+ throw new EpdError(`cannot read ${path}`, err?.message);
1837
+ }
1838
+ let parsed;
1354
1839
  try {
1355
- return JSON.parse(readFileSync3(path, "utf8"));
1840
+ parsed = JSON.parse(raw);
1356
1841
  } catch {
1357
- return {};
1842
+ throw corruptAuthError(path);
1358
1843
  }
1844
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1845
+ throw corruptAuthError(path);
1846
+ return parsed;
1359
1847
  }
1360
- function saveGlobalAuth(updater) {
1361
- const dir = join3(homedir2(), ".config", "epd");
1362
- if (!existsSync3(dir)) {
1363
- mkdirSync2(dir, { recursive: true, mode: 448 });
1848
+ function ensurePrivateDir(dir) {
1849
+ mkdirSync2(dir, { recursive: true, mode: 448 });
1850
+ try {
1851
+ chmodSync(dir, 448);
1852
+ } catch {}
1853
+ }
1854
+ function writeSecretFile(file, content, mode = 384) {
1855
+ const tmp = `${file}.${process.pid}.tmp`;
1856
+ try {
1857
+ rmSync(tmp, { force: true });
1858
+ writeFileSync2(tmp, content, { mode: 384, flag: "wx" });
1859
+ chmodSync(tmp, mode);
1860
+ renameSync(tmp, file);
1861
+ } catch (err) {
1862
+ try {
1863
+ unlinkSync(tmp);
1864
+ } catch {}
1865
+ throw err;
1364
1866
  }
1365
- const file = join3(dir, "auth.json");
1867
+ }
1868
+ function saveGlobalAuth(updater) {
1869
+ const dir = join4(userHome(), ".config", "epd");
1870
+ ensurePrivateDir(dir);
1366
1871
  const current = getGlobalAuth();
1367
1872
  const next = updater(current);
1368
- writeFileSync2(file, JSON.stringify(next, null, 2) + `
1369
- `, { mode: 384 });
1873
+ writeSecretFile(join4(dir, "auth.json"), JSON.stringify(next, null, 2) + `
1874
+ `);
1875
+ }
1876
+ function clearGlobalAuth() {
1877
+ const dir = join4(userHome(), ".config", "epd");
1878
+ ensurePrivateDir(dir);
1879
+ writeSecretFile(join4(dir, "auth.json"), `{}
1880
+ `);
1881
+ const legacy = join4(userHome(), ".epd", "auth.json");
1370
1882
  try {
1371
- chmodSync(file, 384);
1372
- } catch {}
1883
+ rmSync(legacy, { force: true });
1884
+ } catch (err) {
1885
+ throw new EpdError(`could not remove the old credential file ${legacy}`, err?.message);
1886
+ }
1373
1887
  }
1374
1888
  function isLinkDeclined(provider, root = process.cwd()) {
1375
1889
  return (getGlobalAuth().declined?.[provider] ?? []).includes(root);
@@ -1390,14 +1904,28 @@ function clearLinkDecline(provider, root = process.cwd()) {
1390
1904
  declined: { ...auth.declined, [provider]: (auth.declined?.[provider] ?? []).filter((r) => r !== root) }
1391
1905
  }));
1392
1906
  }
1907
+ function writeTarget(path) {
1908
+ try {
1909
+ return realpathSync(path);
1910
+ } catch {
1911
+ try {
1912
+ const link = readlinkSync(path);
1913
+ return isAbsolute2(link) ? link : join4(dirname4(path), link);
1914
+ } catch {
1915
+ return path;
1916
+ }
1917
+ }
1918
+ }
1393
1919
  function saveProjectEnv(entries, root = process.cwd()) {
1394
- const envPath = join3(root, ".env");
1395
- let content = existsSync3(envPath) ? readFileSync3(envPath, "utf8") : "";
1920
+ const envPath = writeTarget(join4(root, ".env"));
1921
+ const exists = existsSync4(envPath);
1922
+ let content = exists ? readFileSync3(envPath, "utf8") : "";
1396
1923
  for (const [key, val] of Object.entries(entries)) {
1924
+ registerSecret(val);
1397
1925
  const regex = new RegExp(`^${key}=.*$`, "m");
1398
1926
  const line = `${key}=${val}`;
1399
1927
  if (regex.test(content)) {
1400
- content = content.replace(regex, line);
1928
+ content = content.replace(regex, () => line);
1401
1929
  } else {
1402
1930
  if (content.length && !content.endsWith(`
1403
1931
  `))
@@ -1407,33 +1935,37 @@ function saveProjectEnv(entries, root = process.cwd()) {
1407
1935
  `;
1408
1936
  }
1409
1937
  }
1410
- writeFileSync2(envPath, content, "utf8");
1938
+ writeSecretFile(envPath, content, exists ? statSync(envPath).mode & 511 : 384);
1939
+ }
1940
+ function secret(value) {
1941
+ registerSecret(value);
1942
+ return value;
1411
1943
  }
1412
1944
  function getCloudflareToken(root = process.cwd()) {
1413
1945
  if (process.env.CLOUDFLARE_API_TOKEN)
1414
- return process.env.CLOUDFLARE_API_TOKEN;
1946
+ return secret(process.env.CLOUDFLARE_API_TOKEN);
1415
1947
  if (process.env.CF_DNS_API_TOKEN)
1416
- return process.env.CF_DNS_API_TOKEN;
1417
- const envPath = join3(root, ".env");
1418
- if (existsSync3(envPath)) {
1948
+ return secret(process.env.CF_DNS_API_TOKEN);
1949
+ const envPath = join4(root, ".env");
1950
+ if (existsSync4(envPath)) {
1419
1951
  try {
1420
1952
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1421
1953
  if (parsed.CLOUDFLARE_API_TOKEN)
1422
- return parsed.CLOUDFLARE_API_TOKEN;
1954
+ return secret(parsed.CLOUDFLARE_API_TOKEN);
1423
1955
  if (parsed.CF_DNS_API_TOKEN)
1424
- return parsed.CF_DNS_API_TOKEN;
1956
+ return secret(parsed.CF_DNS_API_TOKEN);
1425
1957
  } catch {}
1426
1958
  }
1427
1959
  const global = getGlobalAuth();
1428
- return global.cloudflare?.apiToken;
1960
+ return secret(global.cloudflare?.apiToken);
1429
1961
  }
1430
1962
  function getCloudflareTokenSource(root = process.cwd()) {
1431
1963
  if (process.env.CLOUDFLARE_API_TOKEN)
1432
1964
  return "environment variable (CLOUDFLARE_API_TOKEN)";
1433
1965
  if (process.env.CF_DNS_API_TOKEN)
1434
1966
  return "environment variable (CF_DNS_API_TOKEN)";
1435
- const envPath = join3(root, ".env");
1436
- if (existsSync3(envPath)) {
1967
+ const envPath = join4(root, ".env");
1968
+ if (existsSync4(envPath)) {
1437
1969
  try {
1438
1970
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1439
1971
  if (parsed.CLOUDFLARE_API_TOKEN || parsed.CF_DNS_API_TOKEN)
@@ -1447,29 +1979,29 @@ function getCloudflareTokenSource(root = process.cwd()) {
1447
1979
  }
1448
1980
  function getHetznerToken(root = process.cwd()) {
1449
1981
  if (process.env.HETZNER_API_TOKEN)
1450
- return process.env.HETZNER_API_TOKEN;
1982
+ return secret(process.env.HETZNER_API_TOKEN);
1451
1983
  if (process.env.HCLOUD_TOKEN)
1452
- return process.env.HCLOUD_TOKEN;
1453
- const envPath = join3(root, ".env");
1454
- if (existsSync3(envPath)) {
1984
+ return secret(process.env.HCLOUD_TOKEN);
1985
+ const envPath = join4(root, ".env");
1986
+ if (existsSync4(envPath)) {
1455
1987
  try {
1456
1988
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1457
1989
  if (parsed.HETZNER_API_TOKEN)
1458
- return parsed.HETZNER_API_TOKEN;
1990
+ return secret(parsed.HETZNER_API_TOKEN);
1459
1991
  if (parsed.HCLOUD_TOKEN)
1460
- return parsed.HCLOUD_TOKEN;
1992
+ return secret(parsed.HCLOUD_TOKEN);
1461
1993
  } catch {}
1462
1994
  }
1463
1995
  const global = getGlobalAuth();
1464
- return global.hetzner?.apiToken;
1996
+ return secret(global.hetzner?.apiToken);
1465
1997
  }
1466
1998
  function getHetznerTokenSource(root = process.cwd()) {
1467
1999
  if (process.env.HETZNER_API_TOKEN)
1468
2000
  return "environment variable (HETZNER_API_TOKEN)";
1469
2001
  if (process.env.HCLOUD_TOKEN)
1470
2002
  return "environment variable (HCLOUD_TOKEN)";
1471
- const envPath = join3(root, ".env");
1472
- if (existsSync3(envPath)) {
2003
+ const envPath = join4(root, ".env");
2004
+ if (existsSync4(envPath)) {
1473
2005
  try {
1474
2006
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1475
2007
  if (parsed.HETZNER_API_TOKEN || parsed.HCLOUD_TOKEN)
@@ -1483,38 +2015,28 @@ function getHetznerTokenSource(root = process.cwd()) {
1483
2015
  }
1484
2016
  async function verifyCloudflareToken(token) {
1485
2017
  try {
1486
- const res = await fetch("https://api.cloudflare.com/client/v4/user/tokens/verify", {
1487
- headers: {
1488
- Authorization: `Bearer ${token}`,
1489
- "Content-Type": "application/json"
1490
- }
1491
- });
1492
- const data = await res.json();
1493
- if (res.ok && data.success && data.result?.status === "active") {
2018
+ const res = await fetchWithRetry("https://api.cloudflare.com/client/v4/user/tokens/verify", { headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" } }, { timeoutMs: 15000 });
2019
+ const { data, isJson } = await readJsonBody(res);
2020
+ if (res.ok && isJson && data?.success && data.result?.status === "active") {
1494
2021
  return { valid: true, status: data.result.status };
1495
2022
  }
1496
- const err = data.errors?.[0]?.message || `HTTP ${res.status}`;
1497
- return { valid: false, error: err };
2023
+ const err = firstString(data?.errors?.[0]?.message) || statusLabel(res);
2024
+ return { valid: false, error: redactSecret(err, token) };
1498
2025
  } catch (err) {
1499
- return { valid: false, error: err.message };
2026
+ return { valid: false, error: redactSecret(err?.message ?? "network error", token) };
1500
2027
  }
1501
2028
  }
1502
2029
  async function verifyHetznerToken(token) {
1503
2030
  try {
1504
- const res = await fetch("https://api.hetzner.cloud/v1/servers", {
1505
- headers: {
1506
- Authorization: `Bearer ${token}`,
1507
- "Content-Type": "application/json"
1508
- }
1509
- });
1510
- const data = await res.json();
1511
- if (res.ok && Array.isArray(data.servers)) {
2031
+ const res = await fetchWithRetry("https://api.hetzner.cloud/v1/servers", { headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" } }, { timeoutMs: 15000 });
2032
+ const { data, isJson } = await readJsonBody(res);
2033
+ if (res.ok && isJson && Array.isArray(data?.servers)) {
1512
2034
  return { valid: true };
1513
2035
  }
1514
- const err = data.error?.message || `HTTP ${res.status}`;
1515
- return { valid: false, error: err };
2036
+ const err = firstString(data?.error?.message) || statusLabel(res);
2037
+ return { valid: false, error: redactSecret(err, token) };
1516
2038
  } catch (err) {
1517
- return { valid: false, error: err.message };
2039
+ return { valid: false, error: redactSecret(err?.message ?? "network error", token) };
1518
2040
  }
1519
2041
  }
1520
2042
  async function linkCloudflareInteractive(root = process.cwd()) {
@@ -1536,6 +2058,7 @@ ${c.bold("Linking Cloudflare to EPD")}`);
1536
2058
  `));
1537
2059
  for (;; ) {
1538
2060
  const token = await askSecret("Paste Cloudflare API Token (or press Enter to skip):");
2061
+ registerSecret(token);
1539
2062
  if (!token) {
1540
2063
  log.info("Cloudflare linking skipped.");
1541
2064
  return null;
@@ -1588,6 +2111,7 @@ ${c.bold("Linking Hetzner Cloud to EPD")}`);
1588
2111
  `));
1589
2112
  for (;; ) {
1590
2113
  const token = await askSecret("Paste Hetzner Cloud API Token (or press Enter to skip):");
2114
+ registerSecret(token);
1591
2115
  if (!token) {
1592
2116
  log.info("Hetzner linking skipped.");
1593
2117
  return null;
@@ -1624,6 +2148,7 @@ var init_auth = __esm(() => {
1624
2148
  init_log();
1625
2149
  init_prompt();
1626
2150
  init_load();
2151
+ init_http();
1627
2152
  });
1628
2153
 
1629
2154
  // src/hetzner/api.ts
@@ -1641,16 +2166,14 @@ class HetznerCloudClient {
1641
2166
  "Content-Type": "application/json",
1642
2167
  ...options.headers
1643
2168
  };
1644
- const res = await fetch(url, { ...options, headers });
1645
- let data;
1646
- try {
1647
- data = await res.json();
1648
- } catch {
1649
- data = null;
1650
- }
2169
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
2170
+ const { data, isJson, empty } = await readJsonBody(res);
1651
2171
  if (!res.ok) {
1652
- const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
1653
- throw new EpdError(`Hetzner Cloud API error: ${msg}`);
2172
+ const msg = firstString(data?.error?.message, data?.message) || statusLabel(res);
2173
+ throw new HttpApiError(redactSecret(`Hetzner Cloud API error: ${msg}`, this.apiToken), res.status);
2174
+ }
2175
+ if (!isJson && !empty) {
2176
+ throw new EpdError(`Hetzner Cloud API returned a non-JSON response (${statusLabel(res)})`, "The API may be unavailable or a proxy may be intercepting the request. Try again later.");
1654
2177
  }
1655
2178
  return data;
1656
2179
  }
@@ -1711,15 +2234,15 @@ class HetznerCloudClient {
1711
2234
  params.set("per_page", "50");
1712
2235
  const query = params.toString() ? `?${params.toString()}` : "";
1713
2236
  const res = await this.request(`/servers${query}`);
1714
- return (res.servers ?? []).map((s) => this.mapServer(s));
2237
+ return (res?.servers ?? []).map((s) => this.mapServer(s));
1715
2238
  }
1716
2239
  async getServer(idOrName) {
1717
2240
  if (typeof idOrName === "number" || /^\d+$/.test(String(idOrName))) {
1718
2241
  try {
1719
2242
  const res = await this.request(`/servers/${idOrName}`);
1720
- return this.mapServer(res.server);
2243
+ return res?.server ? this.mapServer(res.server) : null;
1721
2244
  } catch (e) {
1722
- if (e instanceof EpdError && e.message.includes("404"))
2245
+ if (e instanceof HttpApiError && e.status === 404)
1723
2246
  return null;
1724
2247
  throw e;
1725
2248
  }
@@ -1748,10 +2271,12 @@ class HetznerCloudClient {
1748
2271
  method: "POST",
1749
2272
  body: JSON.stringify(body)
1750
2273
  });
2274
+ if (!res?.server)
2275
+ throw new EpdError("Hetzner Cloud API returned no server", "Try again later.");
1751
2276
  return {
1752
2277
  server: this.mapServer(res.server),
1753
- action: res.action,
1754
- rootPassword: res.root_password
2278
+ action: res?.action,
2279
+ rootPassword: res?.root_password
1755
2280
  };
1756
2281
  }
1757
2282
  async deleteServer(id) {
@@ -1761,7 +2286,7 @@ class HetznerCloudClient {
1761
2286
  }
1762
2287
  async listServerTypes() {
1763
2288
  const res = await this.request("/server_types");
1764
- return (res.server_types ?? []).map((st) => ({
2289
+ return (res?.server_types ?? []).map((st) => ({
1765
2290
  id: st.id,
1766
2291
  name: st.name,
1767
2292
  description: st.description,
@@ -1779,7 +2304,7 @@ class HetznerCloudClient {
1779
2304
  }
1780
2305
  async listLocations() {
1781
2306
  const res = await this.request("/locations");
1782
- return (res.locations ?? []).map((l) => ({
2307
+ return (res?.locations ?? []).map((l) => ({
1783
2308
  id: l.id,
1784
2309
  name: l.name,
1785
2310
  description: l.description,
@@ -1790,7 +2315,7 @@ class HetznerCloudClient {
1790
2315
  }
1791
2316
  async listSshKeys() {
1792
2317
  const res = await this.request("/ssh_keys");
1793
- return (res.ssh_keys ?? []).map((k) => ({
2318
+ return (res?.ssh_keys ?? []).map((k) => ({
1794
2319
  id: k.id,
1795
2320
  name: k.name,
1796
2321
  fingerprint: k.fingerprint,
@@ -1799,7 +2324,7 @@ class HetznerCloudClient {
1799
2324
  }
1800
2325
  async getAction(id) {
1801
2326
  const res = await this.request(`/actions/${id}`);
1802
- return res.action;
2327
+ return res?.action;
1803
2328
  }
1804
2329
  async waitForAction(actionId, timeoutMs = 120000) {
1805
2330
  const deadline = Date.now() + timeoutMs;
@@ -1829,6 +2354,7 @@ class HetznerCloudClient {
1829
2354
  var init_api = __esm(() => {
1830
2355
  init_log();
1831
2356
  init_misc();
2357
+ init_http();
1832
2358
  });
1833
2359
 
1834
2360
  // src/dns/cloudflare.ts
@@ -1847,17 +2373,20 @@ class CloudflareClient {
1847
2373
  "Content-Type": "application/json",
1848
2374
  ...options.headers
1849
2375
  };
1850
- const res = await fetch(url, { ...options, headers });
1851
- const data = await res.json();
1852
- if (!res.ok || data.success === false) {
1853
- const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
1854
- throw new EpdError(`Cloudflare API error: ${msg}`);
2376
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
2377
+ const { data, isJson, empty } = await readJsonBody(res);
2378
+ if (!res.ok || isJson && data?.success === false) {
2379
+ const msg = firstString(data?.errors?.[0]?.message) || statusLabel(res);
2380
+ throw new HttpApiError(redactSecret(`Cloudflare API error: ${msg}`, this.apiToken), res.status);
1855
2381
  }
1856
- return data.result;
2382
+ if (!isJson && !empty) {
2383
+ throw new EpdError(`Cloudflare API returned a non-JSON response (${statusLabel(res)})`, "The API may be unavailable or a proxy may be intercepting the request. Try again later.");
2384
+ }
2385
+ return data?.result;
1857
2386
  }
1858
2387
  async listZones(name) {
1859
2388
  const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
1860
- return this.request(`/zones${query}`);
2389
+ return await this.request(`/zones${query}`) ?? [];
1861
2390
  }
1862
2391
  async findZoneForDomain(domain, explicitZoneId) {
1863
2392
  if (explicitZoneId) {
@@ -1882,7 +2411,7 @@ class CloudflareClient {
1882
2411
  if (type)
1883
2412
  params.set("type", type);
1884
2413
  const raw = await this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
1885
- return raw.map((r) => ({
2414
+ return (raw ?? []).map((r) => ({
1886
2415
  id: String(r.id),
1887
2416
  zoneId: String(r.zone_id ?? zoneId),
1888
2417
  name: r.name,
@@ -1904,10 +2433,12 @@ class CloudflareClient {
1904
2433
  comment: record.comment
1905
2434
  })
1906
2435
  });
2436
+ if (!res?.id)
2437
+ throw new Error("Cloudflare API returned no DNS record");
1907
2438
  return {
1908
2439
  id: String(res.id),
1909
- zoneId: String(res.zone_id ?? zoneId),
1910
- name: res.name,
2440
+ zoneId: String(res?.zone_id ?? zoneId),
2441
+ name: res?.name,
1911
2442
  type: res.type,
1912
2443
  content: res.content,
1913
2444
  proxied: Boolean(res.proxied),
@@ -1926,10 +2457,12 @@ class CloudflareClient {
1926
2457
  comment: record.comment
1927
2458
  })
1928
2459
  });
2460
+ if (!res?.id)
2461
+ throw new Error("Cloudflare API returned no DNS record");
1929
2462
  return {
1930
2463
  id: String(res.id),
1931
- zoneId: String(res.zone_id ?? zoneId),
1932
- name: res.name,
2464
+ zoneId: String(res?.zone_id ?? zoneId),
2465
+ name: res?.name,
1933
2466
  type: res.type,
1934
2467
  content: res.content,
1935
2468
  proxied: Boolean(res.proxied),
@@ -1944,21 +2477,22 @@ class CloudflareClient {
1944
2477
  }
1945
2478
  var init_cloudflare = __esm(() => {
1946
2479
  init_log();
2480
+ init_http();
1947
2481
  });
1948
2482
 
1949
2483
  // src/commands/init.ts
1950
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
1951
- import { basename, join as join4 } from "path";
2484
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
2485
+ import { basename, join as join5 } from "path";
1952
2486
  function detect(root) {
1953
2487
  const name = basename(root).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
1954
- const hasDockerfile = existsSync4(join4(root, "Dockerfile"));
1955
- const pkgPath = join4(root, "package.json");
1956
- if (existsSync4(pkgPath)) {
2488
+ const hasDockerfile = existsSync5(join5(root, "Dockerfile"));
2489
+ const pkgPath = join5(root, "package.json");
2490
+ if (existsSync5(pkgPath)) {
1957
2491
  let pkg = {};
1958
2492
  try {
1959
2493
  pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
1960
2494
  } catch {}
1961
- const bun = existsSync4(join4(root, "bun.lockb")) || existsSync4(join4(root, "bun.lock"));
2495
+ const bun = existsSync5(join5(root, "bun.lockb")) || existsSync5(join5(root, "bun.lock"));
1962
2496
  const scripts = pkg.scripts ?? {};
1963
2497
  const runner = bun ? "bun" : "npm";
1964
2498
  return {
@@ -1971,13 +2505,13 @@ function detect(root) {
1971
2505
  hasDockerfile
1972
2506
  };
1973
2507
  }
1974
- if (existsSync4(join4(root, "pyproject.toml")) || existsSync4(join4(root, "requirements.txt"))) {
2508
+ if (existsSync5(join5(root, "pyproject.toml")) || existsSync5(join5(root, "requirements.txt"))) {
1975
2509
  return { name, runtime: "python", port: 8000, install: "pip install -r requirements.txt", start: "python -m uvicorn main:app --host 127.0.0.1 --port $PORT", hasDockerfile };
1976
2510
  }
1977
- if (existsSync4(join4(root, "Gemfile"))) {
2511
+ if (existsSync5(join5(root, "Gemfile"))) {
1978
2512
  return { name, runtime: "ruby", port: 3000, install: "bundle install --deployment", start: "bundle exec rails server -p $PORT", hasDockerfile };
1979
2513
  }
1980
- if (existsSync4(join4(root, "go.mod"))) {
2514
+ if (existsSync5(join5(root, "go.mod"))) {
1981
2515
  return { name, runtime: "go", port: 8080, build: "go build -o server .", start: "./server", hasDockerfile };
1982
2516
  }
1983
2517
  return { name, runtime: "unknown", port: 3000, hasDockerfile };
@@ -2207,8 +2741,8 @@ Options
2207
2741
  --force Overwrite an existing epd.yml`,
2208
2742
  async run(ctx) {
2209
2743
  const root = process.cwd();
2210
- const target = join4(root, "epd.yml");
2211
- if (existsSync4(target) && !ctx.values.force) {
2744
+ const target = join5(root, "epd.yml");
2745
+ if (existsSync5(target) && !ctx.values.force) {
2212
2746
  throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
2213
2747
  }
2214
2748
  const detected = detect(root);
@@ -2336,7 +2870,7 @@ Options
2336
2870
  if (wantDockerfile) {
2337
2871
  const df = DOCKERFILES[detected.runtime];
2338
2872
  if (df) {
2339
- writeFileSync3(join4(root, "Dockerfile"), df);
2873
+ writeFileSync3(join5(root, "Dockerfile"), df);
2340
2874
  log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
2341
2875
  } else {
2342
2876
  log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
@@ -2344,10 +2878,10 @@ Options
2344
2878
  }
2345
2879
  const wantCi = Boolean(ctx.values.ci) || interactive() && await confirm("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
2346
2880
  if (wantCi) {
2347
- const workflowDir = join4(root, ".github", "workflows");
2881
+ const workflowDir = join5(root, ".github", "workflows");
2348
2882
  mkdirSync3(workflowDir, { recursive: true });
2349
2883
  const { yaml } = buildWorkflowYaml({ root });
2350
- writeFileSync3(join4(workflowDir, "deploy.yml"), yaml);
2884
+ writeFileSync3(join5(workflowDir, "deploy.yml"), yaml);
2351
2885
  log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
2352
2886
  }
2353
2887
  console.log(`
@@ -2360,104 +2894,6 @@ Next steps:`);
2360
2894
  };
2361
2895
  });
2362
2896
 
2363
- // src/core/names.ts
2364
- function paths(cfg) {
2365
- const root = cfg.remoteRoot;
2366
- const app = `${root}/apps/${cfg.name}`;
2367
- return {
2368
- root,
2369
- app,
2370
- envFile: `${app}/env`,
2371
- state: `${app}/state.json`,
2372
- lock: `${app}/lock`,
2373
- releases: `${app}/releases`,
2374
- current: `${app}/current`,
2375
- shared: `${app}/shared`,
2376
- proxyDir: `${root}/proxy`,
2377
- proxyStatic: `${root}/proxy/traefik.yml`,
2378
- proxyDynamicDir: `${root}/proxy/dynamic`,
2379
- proxyAppsDir: `${root}/proxy/apps`,
2380
- proxyApp: `${root}/proxy/apps/${cfg.name}.json`,
2381
- proxyEnv: `${root}/proxy/env`,
2382
- proxyDynamic: `${root}/proxy/dynamic/${cfg.name}.yml`,
2383
- acmeDir: `${root}/proxy/acme`,
2384
- portsDir: `${root}/ports`,
2385
- proxyBin: `${root}/proxy/bin/traefik`,
2386
- proxyEcosystem: `${root}/proxy/pm2.json`,
2387
- proxyLogDir: `${root}/proxy/log`
2388
- };
2389
- }
2390
- function serviceIndex(cfg, svc) {
2391
- const names = cfg.services.map((s) => s.name).sort();
2392
- const idx = names.indexOf(svc.name);
2393
- if (idx >= MAX_SERVICES) {
2394
- throw new EpdError(`too many servers: epd reserves ports for ${MAX_SERVICES} per app`, "Split the extra ones into their own epd.yml.");
2395
- }
2396
- return idx;
2397
- }
2398
- function hostPort(cfg, svc, slot, replica) {
2399
- if (replica >= MAX_REPLICAS) {
2400
- throw new EpdError(`${svc.name}: at most ${MAX_REPLICAS} replicas per server are supported`, "Add more servers instead, or run several epd apps.");
2401
- }
2402
- const s = SLOTS.indexOf(slot);
2403
- if (svc.hostPort !== undefined) {
2404
- return svc.hostPort + s * MAX_REPLICAS + replica;
2405
- }
2406
- const j = serviceIndex(cfg, svc);
2407
- return cfg.portBase + j * PORTS_PER_SERVICE + s * MAX_REPLICAS + replica;
2408
- }
2409
- function portBlock(cfg) {
2410
- return { from: cfg.portBase, to: cfg.portBase + MAX_SERVICES * PORTS_PER_SERVICE - 1 };
2411
- }
2412
- function usesHostPorts(cfg) {
2413
- return cfg.mode === "process" || cfg.proxy.crossHost || !cfg.proxy.enabled;
2414
- }
2415
- function privateAddress(cfg, host) {
2416
- return cfg.proxy.privateIps[host] ?? host;
2417
- }
2418
- function bindAddress(cfg, host) {
2419
- return cfg.proxy.privateIps[host] ?? (cfg.proxy.enabled ? "0.0.0.0" : "127.0.0.1");
2420
- }
2421
- function endpointsFor(cfg, svc, slot, serverHost, containerIp) {
2422
- const out = [];
2423
- for (let i = 0;i < svc.replicas; i++) {
2424
- if (cfg.mode === "process") {
2425
- const port = hostPort(cfg, svc, slot, i);
2426
- out.push({
2427
- url: `http://127.0.0.1:${port}`,
2428
- probeHost: "127.0.0.1",
2429
- probePort: port,
2430
- id: processName(cfg.name, svc.name, slot, i),
2431
- replica: i
2432
- });
2433
- } else if (cfg.proxy.crossHost) {
2434
- const port = hostPort(cfg, svc, slot, i);
2435
- out.push({
2436
- url: `http://${privateAddress(cfg, serverHost)}:${port}`,
2437
- probeHost: "127.0.0.1",
2438
- probePort: port,
2439
- id: containerName(cfg.name, svc.name, slot, i),
2440
- replica: i
2441
- });
2442
- } else {
2443
- const id = containerName(cfg.name, svc.name, slot, i);
2444
- out.push({
2445
- url: `http://${id}:${svc.port}`,
2446
- probeHost: containerIp?.(id) ?? id,
2447
- probePort: svc.port,
2448
- id,
2449
- replica: i
2450
- });
2451
- }
2452
- }
2453
- return out;
2454
- }
2455
- var SLOTS, otherSlot = (s) => s === "blue" ? "green" : "blue", MAX_REPLICAS = 16, PORTS_PER_SERVICE = 32, MAX_SERVICES = 8, containerName = (app, svc, slot, i) => `epd-${app}-${svc}-${slot}-${i}`, accessoryContainer = (app, name) => `epd-${app}-acc-${name}`, processName = (app, svc, slot, i) => `epd-${app}-${svc}-${slot}-${i}`, PROXY_CONTAINER = "epd-proxy", PROXY_PROCESS = "epd-proxy";
2456
- var init_names = __esm(() => {
2457
- init_log();
2458
- SLOTS = ["blue", "green"];
2459
- });
2460
-
2461
2897
  // src/core/bootstrap.ts
2462
2898
  async function ensureDirs(host, cfg) {
2463
2899
  const p = paths(cfg);
@@ -2489,14 +2925,16 @@ async function installDocker(host) {
2489
2925
  systemctl enable --now docker 2>/dev/null || true
2490
2926
  else
2491
2927
  export DEBIAN_FRONTEND=noninteractive
2928
+ script=$(mktemp)
2929
+ trap 'rm -f "$script"' EXIT
2492
2930
  if command -v curl >/dev/null 2>&1; then
2493
- curl -fsSL https://get.docker.com -o /tmp/epd-get-docker.sh
2931
+ curl -fsSL https://get.docker.com -o "$script"
2494
2932
  else
2495
2933
  (apt-get update -qq && apt-get install -y -qq curl) >/dev/null 2>&1 || true
2496
- curl -fsSL https://get.docker.com -o /tmp/epd-get-docker.sh
2934
+ curl -fsSL https://get.docker.com -o "$script"
2497
2935
  fi
2498
- sh /tmp/epd-get-docker.sh
2499
- rm -f /tmp/epd-get-docker.sh
2936
+ sh "$script"
2937
+ rm -f "$script"
2500
2938
  systemctl enable --now docker 2>/dev/null || true
2501
2939
  fi
2502
2940
  docker info >/dev/null`, { stream: true });
@@ -2526,8 +2964,15 @@ async function verifyHost(host, cfg) {
2526
2964
  await reservePorts(host, cfg);
2527
2965
  }
2528
2966
  function pathPrelude(cfg) {
2529
- const extra = cfg.process.pathPrepend.join(":");
2530
- return `PATH="${extra}:$PATH"`;
2967
+ const dirs = cfg.process.pathPrepend.map((d) => {
2968
+ const ref = /^(?:\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*))/.exec(d);
2969
+ if (!ref)
2970
+ return shq(`${d}:`);
2971
+ const name = ref[1] ?? ref[2];
2972
+ const rest = d.slice(ref[0].length);
2973
+ return "${" + name + ':+"$' + name + '"' + shq(`${rest}:`) + "}";
2974
+ });
2975
+ return `PATH=${[...dirs, '"$PATH"'].join("")}`;
2531
2976
  }
2532
2977
  async function installProcessRuntime(host, cfg) {
2533
2978
  log.host(host.name, "preparing process-mode runtime\u2026");
@@ -2576,10 +3021,52 @@ var init_bootstrap = __esm(() => {
2576
3021
  });
2577
3022
 
2578
3023
  // src/core/ssh.ts
2579
- import { chmodSync as chmodSync2, existsSync as existsSync5, mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from "fs";
3024
+ import { chmodSync as chmodSync2, existsSync as existsSync6, lstatSync, mkdirSync as mkdirSync4, mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
2580
3025
  import { tmpdir } from "os";
2581
- import { join as join5 } from "path";
3026
+ import { join as join6 } from "path";
3027
+ function controlDirectory(base = tmpdir()) {
3028
+ const uid = process.getuid?.();
3029
+ const preferred = join6(base, `epd-${uid ?? 0}`);
3030
+ try {
3031
+ mkdirSync4(preferred, { recursive: true, mode: 448 });
3032
+ const st = lstatSync(preferred);
3033
+ if (st.isDirectory() && (uid === undefined || st.uid === uid) && (st.mode & 63) === 0)
3034
+ return preferred;
3035
+ } catch {}
3036
+ const fresh = mkdtempSync(join6(base, "epd-ctl-"));
3037
+ trackScratch(fresh);
3038
+ return fresh;
3039
+ }
3040
+ function trackScratch(path) {
3041
+ scratchPaths.add(path);
3042
+ if (cleanupHooked)
3043
+ return;
3044
+ cleanupHooked = true;
3045
+ process.on("exit", removeScratchPaths);
3046
+ for (const sig of ["SIGINT", "SIGTERM"]) {
3047
+ const onSignal = () => {
3048
+ if (process.listenerCount(sig) > 1)
3049
+ return;
3050
+ removeScratchPaths();
3051
+ process.removeListener(sig, onSignal);
3052
+ process.kill(process.pid, sig);
3053
+ };
3054
+ process.on(sig, onSignal);
3055
+ }
3056
+ }
3057
+ function removeScratchPaths() {
3058
+ for (const path of scratchPaths) {
3059
+ try {
3060
+ rmSync2(path, { recursive: true, force: true });
3061
+ } catch {}
3062
+ }
3063
+ scratchPaths.clear();
3064
+ }
3065
+ function sudoersCommand(user) {
3066
+ return `echo ${shq(`${user} ALL=(ALL) NOPASSWD:ALL`)} | sudo tee /etc/sudoers.d/epd && sudo chmod 440 /etc/sudoers.d/epd`;
3067
+ }
2582
3068
  function setSudoPassword(key, pw) {
3069
+ registerSecret(pw);
2583
3070
  sudoPasswords.set(key, pw);
2584
3071
  }
2585
3072
  function needsSudoPassword(res) {
@@ -2596,7 +3083,7 @@ async function askSudoPassword(key, target) {
2596
3083
  const pw = await askPassword(`sudo password for ${target}:`);
2597
3084
  if (!pw)
2598
3085
  return;
2599
- sudoPasswords.set(key, pw);
3086
+ setSudoPassword(key, pw);
2600
3087
  return pw;
2601
3088
  });
2602
3089
  promptQueue = asked.catch(() => {
@@ -2620,7 +3107,7 @@ class Host {
2620
3107
  this.sudo = this.user !== "root";
2621
3108
  const preset = cfg.sudoPassword || process.env.EPD_SUDO_PASSWORD;
2622
3109
  if (preset && !sudoPasswords.has(this.sudoKey))
2623
- sudoPasswords.set(this.sudoKey, preset);
3110
+ setSudoPassword(this.sudoKey, preset);
2624
3111
  }
2625
3112
  get sudoKey() {
2626
3113
  return `${this.user}@${this.name}:${this.cfg.port}`;
@@ -2629,20 +3116,20 @@ class Host {
2629
3116
  return [
2630
3117
  "SSH authentication succeeded. SSH keys do not grant sudo privileges.",
2631
3118
  `Give ${this.user} passwordless sudo on ${this.name}:`,
2632
- ` echo '${this.user} ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/epd && sudo chmod 440 /etc/sudoers.d/epd`,
3119
+ ` ${sudoersCommand(this.user)}`,
2633
3120
  "or set EPD_SUDO_PASSWORD (ssh.sudo_password in epd.yml), or deploy as root with ssh.user: root."
2634
3121
  ].join(`
2635
3122
  `);
2636
3123
  }
2637
3124
  sshOptions() {
2638
- const socket = join5(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
3125
+ const socket = join6(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
2639
3126
  const args = [
2640
3127
  "-o",
2641
3128
  "BatchMode=yes",
2642
3129
  "-o",
2643
3130
  "StrictHostKeyChecking=accept-new",
2644
3131
  "-o",
2645
- "ConnectTimeout=10",
3132
+ `ConnectTimeout=${SSH_CONNECT_TIMEOUT_S}`,
2646
3133
  "-o",
2647
3134
  "ServerAliveInterval=15",
2648
3135
  "-o",
@@ -2660,13 +3147,15 @@ class Host {
2660
3147
  if (rawEnvKey) {
2661
3148
  if (rawEnvKey.includes("-----BEGIN") || rawEnvKey.includes(`
2662
3149
  `)) {
2663
- keyPath = join5(controlDir, "ci_id_rsa");
3150
+ keyPath = join6(controlDir, `ci_id_rsa.${process.pid}`);
3151
+ trackScratch(keyPath);
2664
3152
  try {
3153
+ rmSync2(keyPath, { force: true });
2665
3154
  writeFileSync4(keyPath, rawEnvKey.trim() + `
2666
- `, { mode: 384 });
3155
+ `, { mode: 384, flag: "wx" });
2667
3156
  chmodSync2(keyPath, 384);
2668
3157
  } catch {}
2669
- } else if (existsSync5(rawEnvKey)) {
3158
+ } else if (existsSync6(rawEnvKey)) {
2670
3159
  keyPath = rawEnvKey;
2671
3160
  }
2672
3161
  }
@@ -2687,8 +3176,11 @@ class Host {
2687
3176
  }
2688
3177
  async exec(script, opts = {}) {
2689
3178
  const prelude = ["set -euo pipefail"];
2690
- for (const [k, v] of Object.entries(opts.env ?? {}))
3179
+ for (const [k, v] of Object.entries(opts.env ?? {})) {
3180
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
3181
+ throw new EpdError(`invalid environment variable name ${JSON.stringify(k)}`);
2691
3182
  prelude.push(`export ${k}=${shq(v)}`);
3183
+ }
2692
3184
  const body = `${prelude.join(`
2693
3185
  `)}
2694
3186
  ${script}
@@ -2750,14 +3242,15 @@ ${body}` : body,
2750
3242
  return await proc.exited;
2751
3243
  }
2752
3244
  async writeFile(path, content, mode = "644") {
2753
- const marker = `EPD_EOF_${hash32(path + content.length).toString(36)}`;
2754
- await this.exec(`mkdir -p ${shq(dirnameOf(path))}
3245
+ const dir = dirnameOf(path);
3246
+ const encoded = Buffer.from(content, "utf8").toString("base64");
3247
+ await this.exec(`mkdir -p ${shq(dir)}
2755
3248
  umask 077
2756
- cat > ${shq(path)}.tmp <<'${marker}'
2757
- ${content}
2758
- ${marker}
2759
- chmod ${mode} ${shq(path)}.tmp
2760
- mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
3249
+ tmp=$(mktemp ${shq(`${dir}/.epd-XXXXXXXX`)})
3250
+ trap 'rm -f "$tmp"' EXIT
3251
+ printf '%s' ${shq(encoded)} | base64 -d > "$tmp"
3252
+ chmod ${shq(mode)} "$tmp"
3253
+ mv -f "$tmp" ${shq(path)}`, { label: `${this.name}: write ${path}` });
2761
3254
  }
2762
3255
  async readFile(path) {
2763
3256
  const res = await this.exec(`cat ${shq(path)} 2>/dev/null || true`, { allowFailure: true });
@@ -2770,7 +3263,7 @@ mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
2770
3263
  const local = localCommand.map((a) => shq(a)).join(" ");
2771
3264
  const source = password ? `{ printf '%s\\n' "$EPD_SUDO_PW"; ${local}; }` : local;
2772
3265
  const script = `set -euo pipefail; ${source} | ${sshArgs.map((a) => shq(a)).join(" ")}`;
2773
- await run(["bash", "-c", script], {
3266
+ await run([localShell("bash"), "-c", script], {
2774
3267
  stream: true,
2775
3268
  label: `pipe \u2192 ${this.name}`,
2776
3269
  env: password ? { EPD_SUDO_PW: password } : undefined
@@ -2780,7 +3273,9 @@ mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
2780
3273
  const res = await this.exec("echo epd-ok", { allowFailure: true, sudo: false });
2781
3274
  if (res.code !== 0 || !res.stdout.includes("epd-ok")) {
2782
3275
  const isPublickey = res.stderr.includes("Permission denied (publickey)");
2783
- const hint = isPublickey ? "SSH key authentication failed. Ensure the SSH key is in ~/.ssh/authorized_keys on the server and has NO passphrase (passphrases cannot be entered in non-interactive CI)." : res.stderr || "Check that the host is up and your SSH key is authorized.";
3276
+ const hostKeyChanged = /REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed/.test(res.stderr);
3277
+ const knownHost = this.cfg.port === 22 ? this.name : `[${this.name}]:${this.cfg.port}`;
3278
+ const hint = hostKeyChanged ? `The server's host key does not match ~/.ssh/known_hosts. If the server was rebuilt, remove its old entry with \`ssh-keygen -R ${shq(knownHost)}\` and retry. epd keeps host key checking on; it does not disable it.` : isPublickey ? "SSH key authentication failed. Ensure the SSH key is in ~/.ssh/authorized_keys on the server and has NO passphrase (passphrases cannot be entered in non-interactive CI)." : res.stderr || "Check that the host is up and your SSH key is authorized.";
2784
3279
  throw new EpdError(`cannot reach ${this.target}:${this.cfg.port}`, res.stderr ? `${res.stderr}
2785
3280
  ${hint}` : hint);
2786
3281
  }
@@ -2799,23 +3294,28 @@ function host(name, cfg) {
2799
3294
  }
2800
3295
  return h;
2801
3296
  }
2802
- var controlDir, sudoPasswords, promptQueue, cache;
3297
+ var SSH_CONNECT_TIMEOUT_S = 10, scratchPaths, cleanupHooked = false, controlDir, sudoPasswords, promptQueue, cache;
2803
3298
  var init_ssh = __esm(() => {
2804
3299
  init_log();
2805
3300
  init_misc();
2806
3301
  init_proc();
2807
3302
  init_prompt();
2808
- controlDir = join5(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2809
- mkdirSync4(controlDir, { recursive: true, mode: 448 });
3303
+ scratchPaths = new Set;
3304
+ controlDir = controlDirectory();
2810
3305
  sudoPasswords = new Map;
2811
3306
  promptQueue = Promise.resolve();
2812
3307
  cache = new Map;
2813
3308
  });
2814
3309
 
2815
3310
  // src/core/ssh-setup.ts
2816
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync5, unlinkSync, writeFileSync as writeFileSync5 } from "fs";
3311
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync5, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "fs";
2817
3312
  import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
2818
- import { join as join6 } from "path";
3313
+ import { join as join7 } from "path";
3314
+ function askpassBody(password) {
3315
+ return `#!/bin/sh
3316
+ printf '%s\\n' ${shq(password)}
3317
+ `;
3318
+ }
2819
3319
  async function prepareSsh(host, canInstallKey = interactive()) {
2820
3320
  const probe = () => run([
2821
3321
  "ssh",
@@ -2851,13 +3351,9 @@ chmod 600 "$HOME/.ssh/authorized_keys"
2851
3351
  grep -qxF -- ${shq(key)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shq(key)} >> "$HOME/.ssh/authorized_keys"`;
2852
3352
  let installedCode = 1;
2853
3353
  if (password) {
2854
- const askpassScript = join6(tmpdir2(), `epd-askpass-${Date.now()}-${Math.random().toString(36).slice(2)}.sh`);
3354
+ const askpassScript = join7(tmpdir2(), `epd-askpass-${Date.now()}-${Math.random().toString(36).slice(2)}.sh`);
2855
3355
  try {
2856
- writeFileSync5(askpassScript, `#!/bin/sh
2857
- cat << 'EPDEOF'
2858
- ${password}
2859
- EPDEOF
2860
- `, { mode: 448 });
3356
+ writeFileSync5(askpassScript, askpassBody(password), { mode: 448 });
2861
3357
  const res = await run([
2862
3358
  "ssh",
2863
3359
  "-o",
@@ -2886,8 +3382,8 @@ EPDEOF
2886
3382
  setSudoPassword(host.sudoKey, password);
2887
3383
  }
2888
3384
  } finally {
2889
- if (existsSync6(askpassScript))
2890
- unlinkSync(askpassScript);
3385
+ if (existsSync7(askpassScript))
3386
+ unlinkSync2(askpassScript);
2891
3387
  }
2892
3388
  }
2893
3389
  if (installedCode !== 0) {
@@ -2928,9 +3424,9 @@ async function publicKeyFor(host) {
2928
3424
  const identityIndex = options.indexOf("-i");
2929
3425
  const identity = identityIndex >= 0 ? options[identityIndex + 1] : undefined;
2930
3426
  if (identity) {
2931
- if (existsSync6(`${identity}.pub`))
3427
+ if (existsSync7(`${identity}.pub`))
2932
3428
  return validateKey(readFileSync5(`${identity}.pub`, "utf8"));
2933
- if (!existsSync6(identity))
3429
+ if (!existsSync7(identity))
2934
3430
  throw new EpdError(`SSH identity does not exist: ${identity}`);
2935
3431
  const proc = Bun.spawn(["ssh-keygen", "-y", "-f", identity], {
2936
3432
  stdin: "inherit",
@@ -2949,14 +3445,14 @@ async function publicKeyFor(host) {
2949
3445
  const selected = keys.length === 1 ? "0" : await choose("Which SSH agent key should EPD authorize?", keys.map((key, index) => ({ value: String(index), label: key.split(/\s+/).slice(2).join(" ") || `Agent key ${index + 1}` })), "0");
2950
3446
  return validateKey(keys[Number(selected)]);
2951
3447
  }
2952
- const sshDir = join6(homedir3(), ".ssh");
3448
+ const sshDir = join7(homedir3(), ".ssh");
2953
3449
  for (const name of ["id_ed25519", "gh_deploy", "id_ecdsa", "id_rsa"]) {
2954
- const path = join6(sshDir, `${name}.pub`);
2955
- if (existsSync6(path))
3450
+ const path = join7(sshDir, `${name}.pub`);
3451
+ if (existsSync7(path))
2956
3452
  return validateKey(readFileSync5(path, "utf8"));
2957
3453
  }
2958
- const keyPath = join6(sshDir, "id_ed25519");
2959
- if (existsSync6(keyPath)) {
3454
+ const keyPath = join7(sshDir, "id_ed25519");
3455
+ if (existsSync7(keyPath)) {
2960
3456
  throw new EpdError(`Missing public key for ${keyPath}`, "Load it with ssh-add, or set ssh.key to its path, then retry.");
2961
3457
  }
2962
3458
  mkdirSync5(sshDir, { recursive: true, mode: 448 });
@@ -2987,7 +3483,7 @@ var init_ssh_setup = __esm(() => {
2987
3483
  });
2988
3484
 
2989
3485
  // src/proxy/detect.ts
2990
- import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
3486
+ import { existsSync as existsSync8, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
2991
3487
  import { basename as basename2, resolve as resolve2 } from "path";
2992
3488
  async function detectExistingProxy(host, checkPorts = [80, 443]) {
2993
3489
  const portsSet = new Set(checkPorts);
@@ -3201,7 +3697,7 @@ http:
3201
3697
  }
3202
3698
  function updateLocalConfigDisableProxy(configPath = "epd.yml") {
3203
3699
  const configFile = resolve2(configPath);
3204
- if (!existsSync7(configFile))
3700
+ if (!existsSync8(configFile))
3205
3701
  return;
3206
3702
  try {
3207
3703
  const raw = readFileSync6(configFile, "utf8");
@@ -3273,7 +3769,7 @@ ${c.gray(snippet)}`);
3273
3769
  const install = await confirm(`Install configuration to ${confPath} on ${host.name}?`, true);
3274
3770
  if (install) {
3275
3771
  await host.writeFile(confPath, snippet);
3276
- await host.exec(`ln -sf ${shq(confPath)} /etc/nginx/sites-enabled/${cfg.name}.conf && nginx -t && systemctl reload nginx`, { allowFailure: true, label: `${host.name}: enable and reload nginx` });
3772
+ await host.exec(`ln -sf ${shq(confPath)} ${shq(`/etc/nginx/sites-enabled/${cfg.name}.conf`)} && nginx -t && systemctl reload nginx`, { allowFailure: true, label: `${host.name}: enable and reload nginx` });
3277
3773
  log.ok(`${host.name}: installed Nginx configuration and reloaded Nginx`);
3278
3774
  }
3279
3775
  } else if (detected.type === "apache") {
@@ -3303,7 +3799,7 @@ ${c.gray(snippet)}`);
3303
3799
  log.plain(`
3304
3800
  ${c.yellow("!")} Unrecognized reverse proxy detected (${detected.details}).`);
3305
3801
  const customConfig = await ask("Provide path to your custom proxy configuration file to deploy (or leave empty to configure manually):");
3306
- if (customConfig && existsSync7(customConfig)) {
3802
+ if (customConfig && existsSync8(customConfig)) {
3307
3803
  const content = readFileSync6(customConfig, "utf8");
3308
3804
  const defaultRemote = `/etc/proxy/${basename2(customConfig)}`;
3309
3805
  const remotePath = await ask(`Remote destination path on ${host.name}:`, defaultRemote);
@@ -3373,7 +3869,7 @@ import /etc/caddy/conf.d/*
3373
3869
  if (!hasBothPorts) {
3374
3870
  const snippet = generateNginxConfig(cfg, "127.0.0.1");
3375
3871
  await host.writeFile(confPath, snippet);
3376
- await host.exec(`ln -sf ${shq(confPath)} /etc/nginx/sites-enabled/${cfg.name}.conf && nginx -t && systemctl reload nginx || true`, { allowFailure: true });
3872
+ await host.exec(`ln -sf ${shq(confPath)} ${shq(`/etc/nginx/sites-enabled/${cfg.name}.conf`)} && nginx -t && systemctl reload nginx || true`, { allowFailure: true });
3377
3873
  log.host(host.name, `installed/updated Nginx configuration for ${domains.join(", ")} with blue/green upstreams`);
3378
3874
  }
3379
3875
  }
@@ -3766,17 +4262,7 @@ async function ensureProxy(host, cfg, opts = {}) {
3766
4262
  const where = containerMode ? CONTAINER_PATHS : { dynamicDir: p.proxyDynamicDir, acmeFile: `${p.acmeDir}/acme.json` };
3767
4263
  const staticJson = JSON.stringify(staticConfig(merged, where), null, 2);
3768
4264
  await host.writeFile(p.proxyStatic, staticJson, "644");
3769
- if (merged.dnsEnv.length) {
3770
- const lines = merged.dnsEnv.map((name) => {
3771
- const value = opts.secrets?.[name];
3772
- if (value === undefined) {
3773
- throw new EpdError(`proxy.dns_env: ${name} is not set locally`, "Export it or add it to .env \u2014 traefik needs it to answer the DNS challenge.");
3774
- }
3775
- return `${name}=${value}`;
3776
- });
3777
- await host.writeFile(p.proxyEnv, lines.join(`
3778
- `), "600");
3779
- }
4265
+ const dnsEnv = merged.dnsEnv.length ? dnsEnvContent(merged.dnsEnv, opts.secrets) : undefined;
3780
4266
  if (merged.dashboard && merged.dashboardHost) {
3781
4267
  const dash = {
3782
4268
  http: {
@@ -3794,11 +4280,29 @@ async function ensureProxy(host, cfg, opts = {}) {
3794
4280
  }
3795
4281
  const specHash = hash32(staticJson + JSON.stringify(merged)).toString(36);
3796
4282
  if (containerMode)
3797
- await ensureProxyContainer(host, cfg, merged, specHash, opts);
4283
+ await ensureProxyContainer(host, cfg, merged, specHash, opts, dnsEnv);
3798
4284
  else
3799
4285
  await ensureProxyProcess(host, cfg, merged, specHash, opts);
3800
4286
  }
3801
- async function ensureProxyContainer(host, cfg, merged, specHash, opts) {
4287
+ function dnsEnvContent(names, secrets) {
4288
+ const lines = names.map((name) => {
4289
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
4290
+ throw new EpdError(`proxy.dns_env: ${JSON.stringify(name)} is not a valid variable name`, "Use names such as CF_DNS_API_TOKEN.");
4291
+ }
4292
+ const value = secrets?.[name];
4293
+ if (value !== undefined && /[\r\n]/.test(value)) {
4294
+ throw new EpdError(`proxy.dns_env: ${name} contains a line break`, "Set it to a single-line value.");
4295
+ }
4296
+ if (value === undefined) {
4297
+ throw new EpdError(`proxy.dns_env: ${name} is not set locally`, "Export it or add it to .env \u2014 traefik needs it to answer the DNS challenge.");
4298
+ }
4299
+ return `${name}=${value}`;
4300
+ });
4301
+ return lines.join(`
4302
+ `);
4303
+ }
4304
+ async function ensureProxyContainer(host, cfg, merged, specHash, opts, dnsEnv) {
4305
+ const p = paths(cfg);
3802
4306
  const spec = containerSpec(merged, cfg, specHash);
3803
4307
  const state = await host.capture(`docker inspect -f '{{.State.Running}} {{index .Config.Labels "epd.spec"}}' ${PROXY_CONTAINER} 2>/dev/null || echo "missing"`);
3804
4308
  const [running, currentHash] = state.split(/\s+/);
@@ -3806,7 +4310,10 @@ async function ensureProxyContainer(host, cfg, merged, specHash, opts) {
3806
4310
  log.host(host.name, "proxy is up to date");
3807
4311
  return;
3808
4312
  }
3809
- await host.exec(`docker network inspect ${shq(merged.network)} >/dev/null 2>&1 || docker network create ${shq(merged.network)} >/dev/null
4313
+ if (dnsEnv !== undefined)
4314
+ await host.writeFile(p.proxyEnv, dnsEnv, "600");
4315
+ await host.exec(`${dnsEnv !== undefined ? `trap ${shq(`rm -f -- ${shq(p.proxyEnv)}`)} EXIT
4316
+ ` : ""}docker network inspect ${shq(merged.network)} >/dev/null 2>&1 || docker network create ${shq(merged.network)} >/dev/null
3810
4317
  docker pull ${shq(merged.image)} >/dev/null
3811
4318
  docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true
3812
4319
  ${spec.map((a) => shq(a)).join(" ")} >/dev/null
@@ -3875,7 +4382,6 @@ true`, { stream: true, label: `${host.name}: install traefik` });
3875
4382
  }
3876
4383
  ]
3877
4384
  };
3878
- await host.writeFile(p.proxyEcosystem, JSON.stringify(ecosystem, null, 2), "600");
3879
4385
  const jlist = await host.capture(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null || echo '[]'`, {
3880
4386
  sudo: false,
3881
4387
  allowFailure: true
@@ -3885,7 +4391,9 @@ true`, { stream: true, label: `${host.name}: install traefik` });
3885
4391
  log.host(host.name, "proxy is up to date");
3886
4392
  return;
3887
4393
  }
3888
- await host.exec(`${pathPrelude(cfg)} pm2 delete ${PROXY_PROCESS} >/dev/null 2>&1 || true
4394
+ await host.writeFile(p.proxyEcosystem, JSON.stringify(ecosystem, null, 2), "600");
4395
+ await host.exec(`trap ${shq(`rm -f -- ${shq(p.proxyEcosystem)}`)} EXIT
4396
+ ${pathPrelude(cfg)} pm2 delete ${PROXY_PROCESS} >/dev/null 2>&1 || true
3889
4397
  ${pathPrelude(cfg)} pm2 start ${shq(p.proxyEcosystem)} --update-env
3890
4398
  ${pathPrelude(cfg)} pm2 save --force >/dev/null 2>&1 || true
3891
4399
  sleep 2
@@ -3906,6 +4414,24 @@ async function writeRoutes(host, cfg, endpoints, accessories = []) {
3906
4414
  await host.writeFile(paths(cfg).proxyDynamic, JSON.stringify(doc, null, 2), "644");
3907
4415
  await host.exec(`sleep ${Math.max(1, cfg.proxy.reloadWait)}`);
3908
4416
  }
4417
+ async function readRouteUrls(host, cfg) {
4418
+ const raw = await host.readFile(paths(cfg).proxyDynamic);
4419
+ if (!raw)
4420
+ return null;
4421
+ try {
4422
+ const doc = JSON.parse(raw);
4423
+ const urls = [];
4424
+ for (const svc of Object.values(doc.http?.services ?? {})) {
4425
+ for (const server of svc.loadBalancer?.servers ?? []) {
4426
+ if (typeof server.url === "string")
4427
+ urls.push(server.url);
4428
+ }
4429
+ }
4430
+ return urls;
4431
+ } catch {
4432
+ return null;
4433
+ }
4434
+ }
3909
4435
  async function removeRoutes(host, cfg) {
3910
4436
  await host.exec(`rm -f ${shq(paths(cfg).proxyDynamic)} ${shq(paths(cfg).proxyApp)}`, { allowFailure: true });
3911
4437
  }
@@ -3935,56 +4461,168 @@ var init_traefik = __esm(() => {
3935
4461
  });
3936
4462
 
3937
4463
  // src/core/lock.ts
4464
+ import { hostname } from "os";
4465
+ function trackLock(lock) {
4466
+ if (activeLocks.size === 0)
4467
+ for (const sig of SIGNALS)
4468
+ process.on(sig, signalHandlers[sig]);
4469
+ activeLocks.add(lock);
4470
+ }
4471
+ function untrackLock(lock) {
4472
+ if (!activeLocks.delete(lock) || activeLocks.size > 0)
4473
+ return;
4474
+ for (const sig of SIGNALS)
4475
+ process.off(sig, signalHandlers[sig]);
4476
+ }
4477
+ async function releaseOnSignal(sig, exit = (code) => process.exit(code), budgetMs = SIGNAL_RELEASE_MS) {
4478
+ if (releasingOnSignal) {
4479
+ log.warn(`${sig}: exiting now. The deploy lock may be left: run \`epd lock release\` to clear it.`);
4480
+ exit(SIGNAL_EXIT[sig]);
4481
+ return;
4482
+ }
4483
+ releasingOnSignal = true;
4484
+ log.warn(`${sig}: releasing the deploy lock before exit. Press Ctrl-C again to exit at once; the lock may then be left, and \`epd lock release\` clears it.`);
4485
+ let timer;
4486
+ const budget = new Promise((resolve) => {
4487
+ timer = setTimeout(() => {
4488
+ log.warn("timed out releasing the deploy lock. Run `epd lock release` once the server is reachable.");
4489
+ resolve();
4490
+ }, budgetMs);
4491
+ });
4492
+ try {
4493
+ await Promise.race([Promise.all([...activeLocks].map((lock) => lock.release())), budget]);
4494
+ } finally {
4495
+ clearTimeout(timer);
4496
+ releasingOnSignal = false;
4497
+ }
4498
+ exit(SIGNAL_EXIT[sig]);
4499
+ }
3938
4500
  function who() {
3939
- return `${process.env.USER ?? process.env.LOGNAME ?? "someone"}@${process.env.HOSTNAME ?? "local"}`;
4501
+ return `${process.env.USER ?? process.env.LOGNAME ?? "someone"}@${hostname()}`;
4502
+ }
4503
+ function processAlive(pid) {
4504
+ try {
4505
+ process.kill(pid, 0);
4506
+ return true;
4507
+ } catch (err) {
4508
+ return err?.code === "EPERM";
4509
+ }
4510
+ }
4511
+ function staleReason(info, now = Date.now()) {
4512
+ if (info.host === hostname() && typeof info.pid === "number") {
4513
+ return processAlive(info.pid) ? null : `the deploy process on this machine (pid ${info.pid}) is no longer running`;
4514
+ }
4515
+ const at = Date.parse(info.at ?? "");
4516
+ if (Number.isFinite(at) && now - at > STALE_AFTER_MS) {
4517
+ return `it has been held for more than ${Math.round(STALE_AFTER_MS / 3600000)} hours`;
4518
+ }
4519
+ return null;
4520
+ }
4521
+ function lockedError(app, hostName, held) {
4522
+ const lines = [
4523
+ held.by ? `Held by ${held.by}${held.host ? ` on ${held.host}` : ""} since ${held.at} (${held.what}).` : "Held by a deploy that did not record who it is."
4524
+ ];
4525
+ const stale = staleReason(held);
4526
+ if (stale)
4527
+ lines.push(`This looks stale: ${stale}.`);
4528
+ lines.push("Check with `epd lock status`. If no deploy is running, clear the lock with `epd lock release`.");
4529
+ return new EpdError(`${app} is locked on ${hostName}`, lines.join(`
4530
+ `));
3940
4531
  }
3941
4532
 
3942
4533
  class DeployLock {
3943
4534
  cfg;
3944
4535
  hosts;
3945
4536
  held = [];
4537
+ pending = [];
4538
+ infoJson = "";
3946
4539
  constructor(cfg, hosts) {
3947
4540
  this.cfg = cfg;
3948
4541
  this.hosts = hosts;
3949
4542
  }
3950
4543
  async acquire(what) {
3951
4544
  const dir = paths(this.cfg).lock;
3952
- const info = { by: who(), at: new Date().toISOString(), what };
3953
- for (const host of this.hosts) {
3954
- const res = await host.exec(`mkdir -p ${shq(paths(this.cfg).app)}
4545
+ const info = { by: who(), at: new Date().toISOString(), what, host: hostname(), pid: process.pid };
4546
+ this.infoJson = JSON.stringify(info);
4547
+ trackLock(this);
4548
+ try {
4549
+ for (const host of this.hosts) {
4550
+ const sent = host.exec(`mkdir -p ${shq(paths(this.cfg).app)}
3955
4551
  if mkdir ${shq(dir)} 2>/dev/null; then
3956
- printf '%s' ${shq(JSON.stringify(info))} > ${shq(dir)}/info
4552
+ if ! printf '%s' ${shq(this.infoJson)} > ${shq(dir)}/info; then
4553
+ rm -rf ${shq(dir)}
4554
+ exit 1
4555
+ fi
3957
4556
  echo acquired
3958
4557
  else
3959
4558
  cat ${shq(dir)}/info 2>/dev/null || echo '{}'
3960
4559
  exit 9
3961
4560
  fi`, { allowFailure: true });
3962
- if (res.code === 9) {
3963
- await this.release();
3964
- let held = {};
3965
- try {
3966
- held = JSON.parse(res.stdout || "{}");
3967
- } catch {}
3968
- throw new EpdError(`${this.cfg.name} is locked on ${host.name}`, held.by ? `Held by ${held.by} since ${held.at} (${held.what}).
3969
- If that deploy died, run: epd lock release` : "Run `epd lock release` if a previous deploy was interrupted.");
3970
- }
3971
- if (res.code !== 0) {
3972
- await this.release();
3973
- throw new EpdError(`failed to acquire deploy lock on ${host.name}`, res.stderr || res.stdout || undefined);
4561
+ const entry = { host, sent: sent.catch(() => {
4562
+ return;
4563
+ }) };
4564
+ this.pending.push(entry);
4565
+ const res = await sent;
4566
+ const taken = !this.pending.includes(entry);
4567
+ if (!taken && res.code !== 255)
4568
+ this.pending.splice(this.pending.indexOf(entry), 1);
4569
+ if (res.code === 9) {
4570
+ let held = {};
4571
+ try {
4572
+ held = JSON.parse(res.stdout || "{}");
4573
+ } catch {}
4574
+ throw lockedError(this.cfg.name, host.name, held);
4575
+ }
4576
+ if (taken)
4577
+ throw new EpdError(`interrupted while taking the deploy lock on ${host.name}`);
4578
+ if (res.code !== 0) {
4579
+ throw new EpdError(`failed to acquire deploy lock on ${host.name}`, res.stderr || res.stdout || undefined);
4580
+ }
4581
+ this.held.push(host);
3974
4582
  }
3975
- this.held.push(host);
4583
+ if (this.held.length === 0)
4584
+ untrackLock(this);
4585
+ } catch (err) {
4586
+ await this.release();
4587
+ throw err;
3976
4588
  }
3977
4589
  log.debug(`lock acquired on ${this.held.length} host(s)`);
3978
4590
  }
3979
4591
  async release() {
3980
4592
  const dir = paths(this.cfg).lock;
4593
+ for (const { host, sent } of this.pending.splice(0)) {
4594
+ await sent;
4595
+ try {
4596
+ const res = await host.exec(`if [ "$(cat ${shq(`${dir}/info`)} 2>/dev/null)" = ${shq(this.infoJson)} ]; then rm -rf ${shq(dir)}; fi`, { allowFailure: true });
4597
+ if (res.code === 255)
4598
+ log.warn(`the deploy lock on ${host.name} may have been taken; \`epd lock release\` clears it`);
4599
+ } catch (err) {
4600
+ log.warn(`could not release the deploy lock on ${host.name}: ${err?.message ?? err}`);
4601
+ log.warn("run `epd lock release` once the server is reachable");
4602
+ }
4603
+ }
3981
4604
  for (const host of this.held.splice(0)) {
3982
- await host.exec(`rm -rf ${shq(dir)}`, { allowFailure: true });
4605
+ try {
4606
+ await host.exec(`rm -rf ${shq(dir)}`, { allowFailure: true });
4607
+ } catch (err) {
4608
+ log.warn(`could not release the deploy lock on ${host.name}: ${err?.message ?? err}`);
4609
+ log.warn("run `epd lock release` once the server is reachable");
4610
+ }
3983
4611
  }
4612
+ untrackLock(this);
3984
4613
  }
3985
4614
  static async forceRelease(cfg, hosts) {
3986
- for (const host of hosts)
3987
- await host.exec(`rm -rf ${shq(paths(cfg).lock)}`);
4615
+ const failed = [];
4616
+ for (const host of hosts) {
4617
+ try {
4618
+ await host.exec(`rm -rf ${shq(paths(cfg).lock)}`);
4619
+ } catch {
4620
+ failed.push(host.name);
4621
+ }
4622
+ }
4623
+ if (failed.length) {
4624
+ throw new EpdError(`could not release the lock on ${failed.join(", ")}`, "Check that those servers are reachable, then run `epd lock release` again.");
4625
+ }
3988
4626
  }
3989
4627
  static async status(cfg, hosts) {
3990
4628
  const out = [];
@@ -4014,10 +4652,21 @@ async function withLock(cfg, hosts, what, skip, fn) {
4014
4652
  await lock.release();
4015
4653
  }
4016
4654
  }
4655
+ var STALE_AFTER_MS, activeLocks, SIGNALS, SIGNAL_EXIT, SIGNAL_RELEASE_MS, releasingOnSignal = false, signalHandlers;
4017
4656
  var init_lock = __esm(() => {
4018
4657
  init_log();
4019
4658
  init_misc();
4020
4659
  init_names();
4660
+ init_ssh();
4661
+ STALE_AFTER_MS = 6 * 60 * 60 * 1000;
4662
+ activeLocks = new Set;
4663
+ SIGNALS = ["SIGINT", "SIGTERM"];
4664
+ SIGNAL_EXIT = { SIGINT: 130, SIGTERM: 143 };
4665
+ SIGNAL_RELEASE_MS = 2 * SSH_CONNECT_TIMEOUT_S * 1000 + 5000;
4666
+ signalHandlers = {
4667
+ SIGINT: () => void releaseOnSignal("SIGINT"),
4668
+ SIGTERM: () => void releaseOnSignal("SIGTERM")
4669
+ };
4021
4670
  });
4022
4671
 
4023
4672
  // src/core/probe.ts
@@ -4036,6 +4685,11 @@ function statusCondition(spec) {
4036
4685
  return tests.join(" || ");
4037
4686
  }
4038
4687
  function healthScript(targets, health) {
4688
+ for (const t of targets) {
4689
+ if (!/^\S+$/.test(t.label) || !/^\S+$/.test(t.address) || !Number.isInteger(t.port)) {
4690
+ throw new EpdError(`health target ${JSON.stringify(t.label)} has an invalid name, address or port`, "Use a service name without spaces.");
4691
+ }
4692
+ }
4039
4693
  const list = targets.map((t) => `${t.label} ${t.address} ${t.port}`).join(`
4040
4694
  `);
4041
4695
  const tcpOnly = health.path === null;
@@ -4121,16 +4775,39 @@ var init_probe = __esm(() => {
4121
4775
  });
4122
4776
 
4123
4777
  // src/core/state.ts
4124
- async function readState(host, cfg) {
4125
- const raw = await host.readFile(paths(cfg).state);
4126
- if (!raw)
4778
+ function isAppState(v) {
4779
+ if (!v || typeof v !== "object")
4780
+ return false;
4781
+ const s = v;
4782
+ return typeof s.app === "string" && typeof s.version === "string" && typeof s.updatedAt === "string" && !!s.services && typeof s.services === "object" && !Array.isArray(s.services) && Array.isArray(s.history);
4783
+ }
4784
+ async function readState(host, cfg, opts = {}) {
4785
+ const file = paths(cfg).state;
4786
+ const res = await host.exec(`if [ -e ${shq(file)} ]; then echo ${PRESENT}; cat ${shq(file)}; fi`, { allowFailure: true });
4787
+ if (res.code !== 0) {
4788
+ const failure = res.code === 255 ? new EpdError(`${host.name}: unreachable, so its state is unknown`, res.stderr || "Check that the host is up and reachable over SSH, then re-run.") : new EpdError(`${host.name}: could not read state file ${file} (exit ${res.code})`, res.stderr || undefined);
4789
+ if (!opts.skipUnreachable)
4790
+ throw failure;
4791
+ log.warn(`${failure.message}; skipping it`);
4792
+ opts.onSkip?.();
4793
+ return null;
4794
+ }
4795
+ const marker = PRESENT_LINE.exec(res.stdout);
4796
+ if (!marker)
4127
4797
  return null;
4798
+ const raw = res.stdout.slice(marker.index + marker[0].length).replace(/^\r?\n/, "");
4799
+ const corrupt = (why) => new EpdError(`${host.name}: state file ${file} is ${why}`, "epd will not guess. Starting fresh forgets the live slots, so the next deploy may switch routes away from running replicas. Inspect the routes on that host first, then restore the previous state file from a backup.");
4800
+ if (!raw.trim())
4801
+ throw corrupt("empty (possibly from an interrupted write)");
4802
+ let parsed;
4128
4803
  try {
4129
- return JSON.parse(raw);
4804
+ parsed = JSON.parse(raw);
4130
4805
  } catch {
4131
- log.warn(`${host.name}: state file is corrupt, treating this host as fresh`);
4132
- return null;
4806
+ throw corrupt("not valid JSON (possibly from an interrupted write)");
4133
4807
  }
4808
+ if (!isAppState(parsed))
4809
+ throw corrupt("missing required fields");
4810
+ return parsed;
4134
4811
  }
4135
4812
  async function writeState(host, cfg, state) {
4136
4813
  await host.writeFile(paths(cfg).state, JSON.stringify(state, null, 2), "644");
@@ -4150,18 +4827,21 @@ function recordDeploy(state, version, by, keep) {
4150
4827
  const history = [{ version, at: new Date().toISOString(), by }, ...state.history.filter((h) => h.version !== version)];
4151
4828
  return { ...state, version, updatedAt: new Date().toISOString(), history: history.slice(0, Math.max(keep, 2) * 2) };
4152
4829
  }
4830
+ var PRESENT = "EPD_STATE_PRESENT", PRESENT_LINE;
4153
4831
  var init_state = __esm(() => {
4154
4832
  init_names();
4155
4833
  init_log();
4834
+ init_misc();
4835
+ PRESENT_LINE = new RegExp(`^${PRESENT}\\r?$`, "m");
4156
4836
  });
4157
4837
 
4158
4838
  // src/deploy/image.ts
4159
- import { existsSync as existsSync8 } from "fs";
4160
- import { join as join7 } from "path";
4839
+ import { existsSync as existsSync9 } from "fs";
4840
+ import { join as join8 } from "path";
4161
4841
  async function resolveVersion(cfg, explicit) {
4162
4842
  if (explicit)
4163
4843
  return { id: explicit, source: "explicit", dirty: false };
4164
- if (existsSync8(join7(cfg.root, ".git")) && await which("git")) {
4844
+ if (existsSync9(join8(cfg.root, ".git")) && await which("git")) {
4165
4845
  const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
4166
4846
  if (sha.code === 0 && sha.stdout) {
4167
4847
  const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
@@ -4175,8 +4855,8 @@ async function hasBuildx() {
4175
4855
  return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
4176
4856
  }
4177
4857
  async function buildImage(cfg, version, env) {
4178
- const dockerfile = join7(cfg.root, cfg.build.dockerfile);
4179
- if (!existsSync8(dockerfile)) {
4858
+ const dockerfile = join8(cfg.root, cfg.build.dockerfile);
4859
+ if (!existsSync9(dockerfile)) {
4180
4860
  throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
4181
4861
  }
4182
4862
  const ref = imageRef(cfg, version);
@@ -4189,7 +4869,7 @@ async function buildImage(cfg, version, env) {
4189
4869
  async function buildWithBuildx(cfg, ref, version, env) {
4190
4870
  const args = ["docker", "buildx", "build"];
4191
4871
  args.push("--platform", cfg.build.platform);
4192
- args.push("--file", join7(cfg.root, cfg.build.dockerfile));
4872
+ args.push("--file", join8(cfg.root, cfg.build.dockerfile));
4193
4873
  args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
4194
4874
  if (cfg.build.target)
4195
4875
  args.push("--target", cfg.build.target);
@@ -4222,7 +4902,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
4222
4902
  if (cfg.build.platform !== localPlatform) {
4223
4903
  log.warn(`buildx is not installed, so the image is built for ${localPlatform} rather than ${cfg.build.platform}. ` + `Install buildx to cross-build, or set build.platform: ${localPlatform}.`);
4224
4904
  }
4225
- const args = ["docker", "build", "--file", join7(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
4905
+ const args = ["docker", "build", "--file", join8(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
4226
4906
  if (cfg.build.target)
4227
4907
  args.push("--target", cfg.build.target);
4228
4908
  for (const [k, v] of Object.entries(cfg.build.args))
@@ -4245,13 +4925,18 @@ async function ensureBuilder() {
4245
4925
  log.info('creating buildx builder "epd"');
4246
4926
  await run(["docker", "buildx", "create", "--name", "epd", "--use", "--bootstrap"], { stream: true });
4247
4927
  }
4928
+ function checkRegistryPassword(cfg, env) {
4929
+ if (!cfg.registry)
4930
+ return;
4931
+ if (!env[cfg.registry.passwordEnv]) {
4932
+ throw new EpdError(`registry password is not set: ${cfg.registry.passwordEnv}`, "Export it, or put it in .env next to epd.yml.");
4933
+ }
4934
+ }
4248
4935
  async function loginRegistry(host, cfg, env) {
4249
4936
  if (!cfg.registry)
4250
4937
  return;
4938
+ checkRegistryPassword(cfg, env);
4251
4939
  const password = env[cfg.registry.passwordEnv];
4252
- if (!password) {
4253
- throw new EpdError(`registry password: ${cfg.registry.passwordEnv} is not set`, "Export it, or put it in .env next to epd.yml.");
4254
- }
4255
4940
  const server = cfg.registry.server ?? "";
4256
4941
  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` });
4257
4942
  }
@@ -4266,19 +4951,19 @@ async function ensureImage(host, cfg, version) {
4266
4951
  await host.exec(`docker pull ${shq(ref)} >/dev/null`, { label: `${host.name}: docker pull` });
4267
4952
  } else {
4268
4953
  log.host(host.name, `shipping ${ref} over ssh (no registry configured)`);
4269
- await host.pipeInto("gunzip | docker load", ["bash", "-c", `docker save ${shq(ref)} | gzip -1`]);
4954
+ await host.pipeInto("gunzip | docker load", [localShell("bash"), "-c", `docker save ${shq(ref)} | gzip -1`]);
4270
4955
  }
4271
4956
  }
4272
4957
  async function pruneImages(host, cfg, keep, inUse) {
4273
4958
  const keepRefs = inUse.map((v) => imageRef(cfg, v));
4274
4959
  await host.exec(`keep=${shq(keepRefs.join(" "))}
4275
- docker images --filter "label=epd.app=${cfg.name}" --format '{{.Repository}}:{{.Tag}} {{.CreatedAt}}' 2>/dev/null \\
4960
+ docker images --filter ${shq(`label=epd.app=${cfg.name}`)} --format '{{.Repository}}:{{.Tag}} {{.CreatedAt}}' 2>/dev/null \\
4276
4961
  | sort -k2 -r | tail -n +$(( ${keep} + 1 )) | awk '{print $1}' | while read -r img; do
4277
4962
  case " $keep " in *" $img "*) continue;; esac
4278
4963
  case "$img" in *:latest|*:buildcache) continue;; esac
4279
4964
  docker rmi "$img" >/dev/null 2>&1 || true
4280
4965
  done
4281
- docker image prune -f --filter "label=epd.app=${cfg.name}" >/dev/null 2>&1 || true`, { allowFailure: true });
4966
+ docker image prune -f --filter ${shq(`label=epd.app=${cfg.name}`)} >/dev/null 2>&1 || true`, { allowFailure: true });
4282
4967
  }
4283
4968
  var imageRef = (cfg, version) => `${cfg.image}:${version}`;
4284
4969
  var init_image = __esm(() => {
@@ -4312,10 +4997,13 @@ function envFileContent(vars) {
4312
4997
  return Object.entries(vars).map(([k, v]) => `${k}=${v}`).join(`
4313
4998
  `);
4314
4999
  }
4315
- async function writeServiceEnv(host, cfg, svc, env) {
5000
+ function serviceEnvContent(svc, env) {
4316
5001
  const secrets = resolveSecrets(svc.secrets, env, `servers.${svc.name}`);
5002
+ return envFileContent({ ...svc.env, ...secrets });
5003
+ }
5004
+ async function writeServiceEnv(host, cfg, svc, env) {
4317
5005
  const file = `${paths(cfg).app}/env.${svc.name}`;
4318
- await host.writeFile(file, envFileContent({ ...svc.env, ...secrets }), "600");
5006
+ await host.writeFile(file, serviceEnvContent(svc, env), "600");
4319
5007
  return file;
4320
5008
  }
4321
5009
  function dockerRunArgs(o) {
@@ -4345,7 +5033,8 @@ function dockerRunArgs(o) {
4345
5033
  async function startSlot(host, cfg, svc, slot, version, envFile) {
4346
5034
  const names = [];
4347
5035
  const lines = [
4348
- `old=$(docker ps -a -q --filter "label=epd.app=${cfg.name}" --filter "label=epd.service=${svc.name}" --filter "label=epd.slot=${slot}")`,
5036
+ `trap ${shq(`rm -f -- ${shq(envFile)}`)} EXIT`,
5037
+ `old=$(docker ps -a -q --filter ${shq(`label=epd.app=${cfg.name}`)} --filter ${shq(`label=epd.service=${svc.name}`)} --filter ${shq(`label=epd.slot=${slot}`)})`,
4349
5038
  `[ -n "$old" ] && docker rm -f $old >/dev/null 2>&1 || true`
4350
5039
  ];
4351
5040
  for (let i = 0;i < svc.replicas; i++) {
@@ -4375,7 +5064,7 @@ async function containerIps(host, cfg, names) {
4375
5064
  return map;
4376
5065
  }
4377
5066
  async function stopSlot(host, cfg, svc, slot, opts) {
4378
- const teardown = `names=$(docker ps -a -q --filter "label=epd.app=${cfg.name}" --filter "label=epd.service=${svc.name}" --filter "label=epd.slot=${slot}")
5067
+ const teardown = `names=$(docker ps -a -q --filter ${shq(`label=epd.app=${cfg.name}`)} --filter ${shq(`label=epd.service=${svc.name}`)} --filter ${shq(`label=epd.slot=${slot}`)})
4379
5068
  if [ -n "$names" ]; then
4380
5069
  sleep ${opts.drain}
4381
5070
  docker stop --timeout ${svc.stopTimeout} $names >/dev/null 2>&1 || true
@@ -4385,7 +5074,7 @@ fi`;
4385
5074
  disown 2>/dev/null || true` : teardown, { allowFailure: true, label: `${host.name}: stop ${svc.name}/${slot}` });
4386
5075
  }
4387
5076
  async function removeApp(host, cfg) {
4388
- await host.exec(`ids=$(docker ps -a -q --filter "label=epd.app=${cfg.name}")
5077
+ await host.exec(`ids=$(docker ps -a -q --filter ${shq(`label=epd.app=${cfg.name}`)})
4389
5078
  [ -n "$ids" ] && docker rm -f $ids >/dev/null 2>&1 || true`, { allowFailure: true });
4390
5079
  }
4391
5080
  async function listContainers(host, cfg) {
@@ -4400,7 +5089,7 @@ async function listContainers(host, cfg) {
4400
5089
  "{{.Image}}",
4401
5090
  "{{.CreatedAt}}"
4402
5091
  ].join("\t");
4403
- const out = await host.capture(`docker ps -a --filter "label=epd.app=${cfg.name}" --format ${shq(fmt)} 2>/dev/null || true`, { allowFailure: true });
5092
+ const out = await host.capture(`docker ps -a --filter ${shq(`label=epd.app=${cfg.name}`)} --format ${shq(fmt)} 2>/dev/null || true`, { allowFailure: true });
4404
5093
  return out.split(`
4405
5094
  `).filter(Boolean).map((line) => {
4406
5095
  const [name, service, slot, version, replica, status, state, image, created] = line.split("\t");
@@ -4452,13 +5141,17 @@ async function startAccessory(host, cfg, acc, env, opts) {
4452
5141
  args.push(...acc.dockerOptions, acc.image);
4453
5142
  if (acc.command)
4454
5143
  args.push(...parseCommand(acc.command));
4455
- await host.exec(`if docker inspect ${shq(name)} >/dev/null 2>&1; then
5144
+ await host.exec(`trap ${shq(`rm -f -- ${shq(envFile)}`)} EXIT
5145
+ if docker inspect ${shq(name)} >/dev/null 2>&1; then
4456
5146
  ${opts.recreate ? `docker rm -f ${shq(name)} >/dev/null` : `docker start ${shq(name)} >/dev/null 2>&1 || true; exit 0`}
4457
5147
  fi
4458
5148
  docker pull ${shq(acc.image)} >/dev/null
4459
5149
  ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: accessory ${acc.name}` });
4460
5150
  log.host(host.name, `accessory ${acc.name} running`);
4461
5151
  }
5152
+ async function removeLegacyEnvFiles(host, cfg) {
5153
+ await host.exec(`rm -f -- ${shq(paths(cfg).app)}/env.*`, { allowFailure: true, label: `${host.name}: remove old env files` });
5154
+ }
4462
5155
  var init_docker = __esm(() => {
4463
5156
  init_log();
4464
5157
  init_misc();
@@ -4467,8 +5160,8 @@ var init_docker = __esm(() => {
4467
5160
  });
4468
5161
 
4469
5162
  // src/deploy/process.ts
4470
- import { existsSync as existsSync9 } from "fs";
4471
- import { join as join8 } from "path";
5163
+ import { existsSync as existsSync10 } from "fs";
5164
+ import { join as join9 } from "path";
4472
5165
  function releaseDir(cfg, version) {
4473
5166
  return `${paths(cfg).releases}/${version}`;
4474
5167
  }
@@ -4477,7 +5170,7 @@ async function uploadSource(host, cfg, version) {
4477
5170
  const p = paths(cfg);
4478
5171
  await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
4479
5172
  if (cfg.process.source === "git") {
4480
- if (!existsSync9(join8(cfg.root, ".git")))
5173
+ if (!existsSync10(join9(cfg.root, ".git")))
4481
5174
  throw new EpdError('process.source is "git" but this is not a git repository');
4482
5175
  log.host(host.name, `uploading HEAD as ${version}`);
4483
5176
  await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
@@ -4495,22 +5188,29 @@ async function uploadSource(host, cfg, version) {
4495
5188
  log.host(host.name, `uploading ${version}`);
4496
5189
  await run(args, { cwd: cfg.root, label: `rsync \u2192 ${host.name}` });
4497
5190
  }
5191
+ function processEnvContent(cfg, env) {
5192
+ const secrets = resolveSecrets(cfg.secrets, env, "env.secret");
5193
+ return Object.entries({ ...cfg.env, ...secrets }).map(([k, v]) => `${k}=${shq(v)}`).join(`
5194
+ `);
5195
+ }
4498
5196
  async function buildRelease(host, cfg, version, env) {
4499
5197
  const dest = releaseDir(cfg, version);
4500
- const secrets = resolveSecrets(cfg.secrets, env, "env.secret");
5198
+ const content = processEnvContent(cfg, env);
5199
+ const commands = [cfg.process.install, cfg.process.build].filter((c) => Boolean(c));
5200
+ if (!commands.length)
5201
+ return;
4501
5202
  const envFile = paths(cfg).envFile;
4502
- await host.writeFile(envFile, Object.entries({ ...cfg.env, ...secrets }).map(([k, v]) => `${k}=${v}`).join(`
4503
- `), "600");
4504
- const steps = [`cd ${shq(dest)}`, pathPrelude(cfg), `set -a; . ${shq(envFile)}; set +a`];
4505
- if (cfg.process.install)
4506
- steps.push(cfg.process.install);
4507
- if (cfg.process.build)
4508
- steps.push(cfg.process.build);
4509
- if (steps.length > 3) {
4510
- log.host(host.name, "installing and building");
4511
- await host.exec(steps.join(`
5203
+ await host.writeFile(envFile, content, "600");
5204
+ const steps = [
5205
+ `trap ${shq(`rm -f -- ${shq(envFile)}`)} EXIT`,
5206
+ `cd ${shq(dest)}`,
5207
+ pathPrelude(cfg),
5208
+ `set -a; . ${shq(envFile)}; set +a`,
5209
+ ...commands
5210
+ ];
5211
+ log.host(host.name, "installing and building");
5212
+ await host.exec(steps.join(`
4512
5213
  `), { ...asUser, stream: true, label: `${host.name}: build` });
4513
- }
4514
5214
  }
4515
5215
  function ecosystem(cfg, svc, slot, version, env) {
4516
5216
  const dir = releaseDir(cfg, version);
@@ -4553,7 +5253,8 @@ async function startSlot2(host, cfg, svc, slot, version, env) {
4553
5253
  const file = `${paths(cfg).app}/pm2.${svc.name}.${slot}.json`;
4554
5254
  await host.writeFile(file, JSON.stringify(doc, null, 2), "600");
4555
5255
  const stale = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
4556
- await host.exec(`for name in ${stale.map((n) => shq(n)).join(" ")}; do ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true; done
5256
+ await host.exec(`trap ${shq(`rm -f -- ${shq(file)}`)} EXIT
5257
+ for name in ${stale.map((n) => shq(n)).join(" ")}; do ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true; done
4557
5258
  ${pm2(cfg, `start ${shq(file)} --update-env`)}
4558
5259
  ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, label: `${host.name}: pm2 start ${svc.name}/${slot}` });
4559
5260
  }
@@ -4568,7 +5269,7 @@ ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`;
4568
5269
  disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host.name}: pm2 stop ${svc.name}/${slot}` });
4569
5270
  }
4570
5271
  async function removeApp2(host, cfg) {
4571
- 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
5272
+ await host.exec(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null | tr ',' '\\n' | grep -o ${shq(`"name":"epd-${cfg.name}-[^"]*"`)} | cut -d'"' -f4 | sort -u | while read -r n; do
4572
5273
  ${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
4573
5274
  done
4574
5275
  ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
@@ -4591,6 +5292,10 @@ async function listProcesses(host, cfg) {
4591
5292
  memory: p.monit?.memory ?? 0
4592
5293
  }));
4593
5294
  }
5295
+ async function removeLegacyEcosystemFiles(host, cfg) {
5296
+ const app = paths(cfg).app;
5297
+ await host.exec(`rm -f -- ${shq(app)}/pm2.*.json ${shq(app)}/env`, { ...asUser, allowFailure: true });
5298
+ }
4594
5299
  async function finalizeRelease(host, cfg, version) {
4595
5300
  const p = paths(cfg);
4596
5301
  await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
@@ -4627,23 +5332,21 @@ class HetznerDnsClient {
4627
5332
  "Content-Type": "application/json",
4628
5333
  ...options.headers
4629
5334
  };
4630
- const res = await fetch(url, { ...options, headers });
4631
- let data;
4632
- try {
4633
- data = await res.json();
4634
- } catch {
4635
- data = null;
4636
- }
5335
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
5336
+ const { data, isJson, empty } = await readJsonBody(res);
4637
5337
  if (!res.ok) {
4638
- const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
4639
- throw new EpdError(`Hetzner DNS API error: ${msg}`);
5338
+ const msg = firstString(data?.error?.message, data?.message) || statusLabel(res);
5339
+ throw new HttpApiError(redactSecret(`Hetzner DNS API error: ${msg}`, this.apiToken), res.status);
5340
+ }
5341
+ if (!isJson && !empty) {
5342
+ throw new EpdError(`Hetzner DNS API returned a non-JSON response (${statusLabel(res)})`, "The API may be unavailable or a proxy may be intercepting the request. Try again later.");
4640
5343
  }
4641
5344
  return data;
4642
5345
  }
4643
5346
  async listZones(name) {
4644
5347
  const query = name ? `?name=${encodeURIComponent(name)}` : "";
4645
5348
  const res = await this.request(`/zones${query}`);
4646
- return (res.zones ?? []).map((z) => ({ id: z.id, name: z.name }));
5349
+ return (res?.zones ?? []).map((z) => ({ id: z.id, name: z.name }));
4647
5350
  }
4648
5351
  async findZoneForDomain(domain, explicitZoneId) {
4649
5352
  if (explicitZoneId) {
@@ -4694,7 +5397,7 @@ class HetznerDnsClient {
4694
5397
  }
4695
5398
  const zoneName = zone?.name ?? "";
4696
5399
  const res = await this.request(`/records?zone_id=${encodeURIComponent(zoneId)}`);
4697
- const records = res.records ?? [];
5400
+ const records = res?.records ?? [];
4698
5401
  let mapped = records.map((r) => ({
4699
5402
  id: r.id,
4700
5403
  zoneId: r.zone_id,
@@ -4734,7 +5437,9 @@ class HetznerDnsClient {
4734
5437
  ttl
4735
5438
  })
4736
5439
  });
4737
- const created = res.record;
5440
+ const created = res?.record;
5441
+ if (!created)
5442
+ throw new EpdError("Hetzner DNS API returned no record", "Try again later.");
4738
5443
  return {
4739
5444
  id: created.id,
4740
5445
  zoneId: created.zone_id,
@@ -4766,7 +5471,9 @@ class HetznerDnsClient {
4766
5471
  ttl
4767
5472
  })
4768
5473
  });
4769
- const updated = res.record;
5474
+ const updated = res?.record;
5475
+ if (!updated)
5476
+ throw new EpdError("Hetzner DNS API returned no record", "Try again later.");
4770
5477
  return {
4771
5478
  id: updated.id,
4772
5479
  zoneId: updated.zone_id,
@@ -4785,6 +5492,7 @@ class HetznerDnsClient {
4785
5492
  }
4786
5493
  var init_hetzner = __esm(() => {
4787
5494
  init_log();
5495
+ init_http();
4788
5496
  });
4789
5497
  // src/dns/index.ts
4790
5498
  import dns from "dns/promises";
@@ -4797,12 +5505,12 @@ function isIPv4(ip) {
4797
5505
  return !isNaN(n) && n >= 0 && n <= 255 && String(n) === p;
4798
5506
  });
4799
5507
  }
4800
- function isIPv6(ip) {
5508
+ function isIPv62(ip) {
4801
5509
  return ip.includes(":") && /^[0-9a-fA-F:]+$/.test(ip);
4802
5510
  }
4803
5511
  async function resolveHostIps(target) {
4804
5512
  const clean = target.trim();
4805
- if (isIPv4(clean) || isIPv6(clean))
5513
+ if (isIPv4(clean) || isIPv62(clean))
4806
5514
  return [clean];
4807
5515
  try {
4808
5516
  const lookup = await dns.lookup(clean, { all: true });
@@ -4812,6 +5520,11 @@ async function resolveHostIps(target) {
4812
5520
  } catch {}
4813
5521
  return [clean];
4814
5522
  }
5523
+ function routeHostName(host) {
5524
+ if (host.startsWith("["))
5525
+ return host.slice(1, host.indexOf("]")).trim().toLowerCase();
5526
+ return (host.split(":")[0] ?? "").trim().toLowerCase();
5527
+ }
4815
5528
  function getRouteDomains(cfg) {
4816
5529
  if (cfg.dns?.domains && cfg.dns.domains.length > 0) {
4817
5530
  return cfg.dns.domains;
@@ -4823,7 +5536,7 @@ function getRouteDomains(cfg) {
4823
5536
  for (const svc of cfg.services) {
4824
5537
  for (const route of svc.routes) {
4825
5538
  for (const host of route.hosts) {
4826
- const d = (host.split(":")[0] ?? "").trim().toLowerCase();
5539
+ const d = routeHostName(host);
4827
5540
  if (d)
4828
5541
  domains.add(d);
4829
5542
  }
@@ -4832,7 +5545,7 @@ function getRouteDomains(cfg) {
4832
5545
  for (const acc of cfg.accessories) {
4833
5546
  for (const route of acc.routes) {
4834
5547
  for (const host of route.hosts) {
4835
- const d = (host.split(":")[0] ?? "").trim().toLowerCase();
5548
+ const d = routeHostName(host);
4836
5549
  if (d)
4837
5550
  domains.add(d);
4838
5551
  }
@@ -4890,7 +5603,7 @@ async function syncDns(cfg, opts = {}) {
4890
5603
  for (const h of routedHosts) {
4891
5604
  const resolved = await resolveHostIps(h);
4892
5605
  for (const ip of resolved) {
4893
- if (isIPv4(ip) || isIPv6(ip))
5606
+ if (isIPv4(ip) || isIPv62(ip))
4894
5607
  ips.add(ip);
4895
5608
  }
4896
5609
  }
@@ -4915,7 +5628,7 @@ async function syncDns(cfg, opts = {}) {
4915
5628
  }
4916
5629
  const existingRecords = await provider.listDnsRecords(zone.id, domain);
4917
5630
  for (const ip of ips) {
4918
- const type = isIPv6(ip) ? "AAAA" : "A";
5631
+ const type = isIPv62(ip) ? "AAAA" : "A";
4919
5632
  const existing = existingRecords.find((r) => r.name.toLowerCase() === domain.toLowerCase() && r.type === type && r.content === ip);
4920
5633
  if (existing) {
4921
5634
  const needsProxyUpdate = provider.name === "cloudflare" && existing.proxied !== isProxied;
@@ -5078,6 +5791,8 @@ var init_resolve = __esm(() => {
5078
5791
  // src/deploy/deploy.ts
5079
5792
  async function deploy(loaded, opts = {}) {
5080
5793
  const { config: cfg, env } = loaded;
5794
+ if (!opts.dryRun && cfg.mode === "docker")
5795
+ checkRegistryPassword(cfg, env);
5081
5796
  await resolveDynamicHosts(cfg, env);
5082
5797
  const started = Date.now();
5083
5798
  const services = selectServices(cfg, opts.onlyServices);
@@ -5155,7 +5870,7 @@ ${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made
5155
5870
  }
5156
5871
  if (!opts.skipHooks && cfg.hooks.preDeploy)
5157
5872
  await hook(cfg, "pre_deploy", cfg.hooks.preDeploy, version);
5158
- await withLock(cfg, hosts, `deploy ${version}`, opts.skipLock ?? false, async () => {
5873
+ await withLock(cfg, hosts, `deploy ${version}`, opts.skipLock ?? false, () => deployLocked(cfg, hosts, services, version, opts, liveEffects(cfg, env), async () => {
5159
5874
  log.step("Preparing servers");
5160
5875
  await pool(hosts, 8, async (host) => {
5161
5876
  await verifyHost(host, cfg);
@@ -5167,30 +5882,7 @@ ${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made
5167
5882
  log.step("Checking proxy");
5168
5883
  await pool(proxyHosts(cfg).filter((h) => targetHosts.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: env }));
5169
5884
  }
5170
- const live = new Map;
5171
- for (const h of allHosts(cfg)) {
5172
- const state = await readState(host(h, cfg.ssh), cfg);
5173
- const m = new Map;
5174
- for (const [svc, s] of Object.entries(state?.services ?? {}))
5175
- m.set(svc, s.slot);
5176
- live.set(h, m);
5177
- }
5178
- const deployHost = async (host) => {
5179
- await deployToHost({ cfg, env, host, services, version, opts, live });
5180
- };
5181
- if (cfg.strategy === "parallel") {
5182
- await pool(hosts, hosts.length, deployHost);
5183
- } else {
5184
- for (const host of hosts)
5185
- await deployHost(host);
5186
- }
5187
- if (cfg.proxy.crossHost) {
5188
- log.step("Syncing routes across hosts");
5189
- await pool(proxyHosts(cfg).map((h) => host(h, cfg.ssh)), 4, async (host) => {
5190
- await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
5191
- });
5192
- }
5193
- });
5885
+ }));
5194
5886
  if (cfg.dns?.enabled && cfg.dns.autoSync || cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
5195
5887
  try {
5196
5888
  await syncDns(cfg, { log: true });
@@ -5203,41 +5895,278 @@ ${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made
5203
5895
  log.ok(`Deployed ${cfg.name} ${version} in ${dur(Date.now() - started)}`);
5204
5896
  printUrls(cfg);
5205
5897
  }
5206
- async function deployToHost(d) {
5207
- const { cfg, env, host, version, opts, live } = d;
5208
- const services = d.services.filter((s) => s.hosts.includes(host.name));
5209
- if (!services.length)
5210
- return;
5211
- log.step(`${host.name}: deploying ${services.map((s) => s.name).join(", ")}`);
5212
- if (cfg.mode === "docker") {
5213
- await loginRegistry(host, cfg, env);
5214
- await ensureImage(host, cfg, version);
5215
- } else if (!opts.reuse) {
5216
- await uploadSource(host, cfg, version);
5217
- await buildRelease(host, cfg, version, env);
5898
+ async function deployLocked(cfg, hosts, services, version, opts, fx, prep) {
5899
+ const snapshot = await snapshotLive(cfg, fx, true);
5900
+ if (cfg.proxy.crossHost && snapshot.skipped.length) {
5901
+ throw new EpdError(`could not read the state of ${snapshot.skipped.join(", ")}, so cross-host routes cannot be synced`, "With proxy.cross_host, every server's replicas must be in the routes. Check the connection to the listed hosts and re-run `epd deploy`. Nothing was changed.");
5902
+ }
5903
+ await prep();
5904
+ await rolloutWithFailureHook(cfg, version, opts.skipHooks ?? false, () => rollout(cfg, hosts, services, version, opts, fx, snapshot));
5905
+ }
5906
+ async function rolloutWithFailureHook(cfg, version, skipHooks, roll) {
5907
+ try {
5908
+ await roll();
5909
+ } catch (error) {
5910
+ if (!skipHooks && cfg.hooks.onFailure) {
5911
+ await hook(cfg, "on_failure", cfg.hooks.onFailure, version).catch(() => {
5912
+ return;
5913
+ });
5914
+ }
5915
+ throw error;
5916
+ }
5917
+ }
5918
+ async function snapshotLive(cfg, fx, skipUnreachable) {
5919
+ const before = new Map;
5920
+ const skipped = [];
5921
+ for (const name of allHosts(cfg)) {
5922
+ const opts = skipUnreachable ? { skipUnreachable, onSkip: () => skipped.push(name) } : undefined;
5923
+ const state = await fx.readState(host(name, cfg.ssh), opts);
5924
+ const slots = new Map;
5925
+ for (const [svc, s] of Object.entries(state?.services ?? {}))
5926
+ slots.set(svc, s.slot);
5927
+ before.set(name, slots);
5928
+ }
5929
+ return { before, skipped };
5930
+ }
5931
+ function ownUpstreams(cfg, svc, slot, host) {
5932
+ const ports = new Set([svc.port, ...svc.routes.map((r) => r.port)]);
5933
+ return [...ports].flatMap((port) => urlsForPort(cfg, svc, slot, host, port));
5934
+ }
5935
+ function routeGeneration(cfg, host, own, fresh, previous, fileUrls) {
5936
+ if (!fileUrls)
5937
+ return null;
5938
+ const inFile = new Set(fileUrls);
5939
+ const references = (slots) => own.some((svc) => {
5940
+ const slot = slots.get(svc.name);
5941
+ return slot !== undefined && svc.routes.length > 0 && ownUpstreams(cfg, svc, slot, host).some((u) => inFile.has(u));
5942
+ });
5943
+ const refNew = references(fresh);
5944
+ const refOld = references(previous);
5945
+ if (refNew === refOld)
5946
+ return null;
5947
+ return refNew ? "new" : "old";
5948
+ }
5949
+ async function rollout(cfg, hosts, services, version, opts, fx, snapshot) {
5950
+ const { before, skipped } = snapshot ?? await snapshotLive(cfg, fx, false);
5951
+ const live = new Map;
5952
+ for (const [name, slots] of before)
5953
+ live.set(name, new Map(slots));
5954
+ const setLive = (host, svc, slot) => {
5955
+ const slots = live.get(host) ?? new Map;
5956
+ if (slot)
5957
+ slots.set(svc, slot);
5958
+ else
5959
+ slots.delete(svc);
5960
+ live.set(host, slots);
5961
+ };
5962
+ const routeHost = (host, view) => cfg.proxy.enabled ? fx.writeRoutes(host, buildEndpoints(cfg, host.name, view), buildAccessoryEndpoints(cfg, host.name)) : fx.syncExternal(host);
5963
+ const restoreRoutes = async (host) => {
5964
+ if (!cfg.proxy.enabled)
5965
+ return true;
5966
+ try {
5967
+ await routeHost(host, before);
5968
+ return true;
5969
+ } catch (error) {
5970
+ log.error(`${host.name}: restoring the old routes failed: ${errMsg(error)}`);
5971
+ return false;
5972
+ }
5973
+ };
5974
+ const stopNew = async (host, started) => {
5975
+ for (const { svc, slot } of started)
5976
+ await fx.stop(host, svc, slot, { drain: 0 }).catch(() => {
5977
+ return;
5978
+ });
5979
+ };
5980
+ const units = [];
5981
+ const errors = [];
5982
+ let warnings = 0;
5983
+ const deployHost = async (host) => {
5984
+ const own = services.filter((s) => s.hosts.includes(host.name));
5985
+ if (!own.length)
5986
+ return;
5987
+ if (skipped.includes(host.name)) {
5988
+ throw new EpdError(`${host.name}: unreachable, so its state is unknown`, "Check ssh access to the host, then deploy again.");
5989
+ }
5990
+ log.step(`${host.name}: deploying ${own.map((s) => s.name).join(", ")}`);
5991
+ const prior = await fx.readState(host) ?? emptyState(cfg);
5992
+ const unit = { host, services: own, prior, previous: new Map, committed: false, persisted: false };
5993
+ units.push(unit);
5994
+ const started = [];
5995
+ const slots = new Map;
5996
+ const records = {};
5997
+ try {
5998
+ await fx.prepare(host, version, opts.reuse ?? false);
5999
+ for (const svc of own) {
6000
+ const current = prior.services[svc.name]?.slot;
6001
+ if (current)
6002
+ unit.previous.set(svc.name, current);
6003
+ const slot = current ? otherSlot(current) : "blue";
6004
+ log.host(host.name, `${svc.name}: starting ${svc.replicas} replica(s) on ${slot}`);
6005
+ started.push({ svc, slot });
6006
+ const probes = await fx.start(host, svc, slot, version);
6007
+ if (!opts.skipHealth)
6008
+ await fx.check(host, svc, slot, probes);
6009
+ slots.set(svc.name, slot);
6010
+ records[svc.name] = {
6011
+ slot,
6012
+ replicas: svc.replicas,
6013
+ version,
6014
+ endpoints: endpointsFor(cfg, svc, slot, host.name).map((e) => e.url)
6015
+ };
6016
+ }
6017
+ } catch (error) {
6018
+ log.error(`${host.name}: deploy failed before any route changed; stopping the new slot, the old one keeps serving`);
6019
+ await stopNew(host, started);
6020
+ throw error;
6021
+ }
6022
+ for (const [name, slot] of slots)
6023
+ setLive(host.name, name, slot);
6024
+ const hasRoutes = own.some((s) => s.routes.length > 0) || cfg.accessories.some((a) => a.routes.length > 0 && (cfg.proxy.crossHost || a.host === host.name));
6025
+ if (hasRoutes) {
6026
+ try {
6027
+ await routeHost(host, live);
6028
+ log.host(host.name, "routes updated");
6029
+ } catch (error) {
6030
+ if (await restoreRoutes(host)) {
6031
+ for (const name of slots.keys())
6032
+ setLive(host.name, name, before.get(host.name)?.get(name));
6033
+ log.error(`${host.name}: route switch failed; old routes restored, new slot stopped`);
6034
+ await stopNew(host, started);
6035
+ throw error;
6036
+ }
6037
+ let generation = null;
6038
+ try {
6039
+ generation = routeGeneration(cfg, host.name, own, slots, unit.previous, await fx.readRoutes(host));
6040
+ } catch {
6041
+ generation = null;
6042
+ }
6043
+ if (generation === "old") {
6044
+ for (const name of slots.keys())
6045
+ setLive(host.name, name, before.get(host.name)?.get(name));
6046
+ log.error(`${host.name}: route switch failed and the proxy routes to the old slot; stopping the new slot`);
6047
+ await stopNew(host, started);
6048
+ throw error;
6049
+ }
6050
+ if (generation === "new") {
6051
+ unit.routeError = error;
6052
+ log.error(`${host.name}: route switch failed and the old routes could not be restored; the proxy routes to the new slot, keeping it`);
6053
+ } else {
6054
+ for (const name of slots.keys())
6055
+ setLive(host.name, name, before.get(host.name)?.get(name));
6056
+ unit.committed = true;
6057
+ unit.unconfirmed = true;
6058
+ throw new EpdError(`${host.name}: the route switch failed and the old routes could not be restored, and the proxy's routes cannot be confirmed`, `Inspect ${paths(cfg).proxyDynamic} on ${host.target} before doing anything else. Both slots are still running and the saved state is unchanged. Re-run \`epd deploy\` only after you know which slot that file routes to.`);
6059
+ }
6060
+ }
6061
+ }
6062
+ unit.committed = true;
6063
+ const next = recordDeploy({ ...prior, services: { ...prior.services, ...records } }, version, process.env.USER ?? "epd", cfg.keepReleases);
6064
+ try {
6065
+ await retry(() => fx.writeState(host, next), {
6066
+ attempts: 3,
6067
+ delayMs: 1000,
6068
+ onRetry: (e, n) => log.warn(`${host.name}: state write failed, retrying (${n}/3): ${errMsg(e)}`)
6069
+ });
6070
+ } catch (error) {
6071
+ const describe = (m) => [...m].map(([svc, slot]) => `${svc} on ${slot}`).join(", ") || "nothing";
6072
+ throw new EpdError(`${host.name}: ${version} is serving, but its state could not be saved: ${errMsg(error)}`, `The routes point at ${describe(slots)}, but the saved state still names ${describe(unit.previous)} as live. ` + `Re-running \`epd deploy\` will restart ${describe(slots)}, the slot serving traffic now, before it records the state, so expect a brief interruption. ` + `Fix the write error on ${host.target} (state file: ${paths(cfg).state}), then run \`epd deploy\` again.`);
6073
+ }
6074
+ unit.persisted = true;
6075
+ if (unit.routeError)
6076
+ throw unit.routeError;
6077
+ log.host(host.name, c.green("done"));
6078
+ };
6079
+ const run = async (host) => {
6080
+ try {
6081
+ await deployHost(host);
6082
+ } catch (error) {
6083
+ errors.push(error);
6084
+ }
6085
+ };
6086
+ if (cfg.strategy === "parallel") {
6087
+ await Promise.all(hosts.map(run));
5218
6088
  } else {
5219
- const dir = releaseDir(cfg, version);
5220
- if (!await host.test(`[ -d ${JSON.stringify(dir)} ]`)) {
5221
- throw new EpdError(`${host.name}: release ${version} is not on this server`, "Deploy it normally first.");
6089
+ for (const host of hosts) {
6090
+ await run(host);
6091
+ if (errors.length)
6092
+ break;
5222
6093
  }
5223
6094
  }
5224
- const state = await readState(host, cfg) ?? emptyState(cfg);
5225
- const previous = new Map;
5226
- const started = [];
5227
- try {
5228
- for (const svc of services) {
5229
- const current = state.services[svc.name]?.slot;
5230
- if (current)
5231
- previous.set(svc.name, current);
5232
- const slot = current ? otherSlot(current) : "blue";
5233
- log.host(host.name, `${svc.name}: starting ${svc.replicas} replica(s) on ${slot}`);
5234
- let probes = [];
6095
+ let synced = true;
6096
+ const unconfirmed = new Set(units.filter((u) => u.unconfirmed).map((u) => u.host.name));
6097
+ if (cfg.proxy.crossHost && units.some((u) => u.committed && !u.unconfirmed)) {
6098
+ log.step("Syncing routes across hosts");
6099
+ try {
6100
+ await pool(proxyHosts(cfg).filter((h) => !unconfirmed.has(h)).map((h) => host(h, cfg.ssh)), 4, (proxy) => routeHost(proxy, live));
6101
+ } catch (error) {
6102
+ synced = false;
6103
+ errors.push(error);
6104
+ }
6105
+ }
6106
+ if (cfg.proxy.crossHost && unconfirmed.size)
6107
+ synced = false;
6108
+ for (const unit of units) {
6109
+ if (!unit.persisted || unit.routeError || !synced)
6110
+ continue;
6111
+ for (const svc of unit.services) {
6112
+ const old = unit.previous.get(svc.name);
6113
+ if (!old)
6114
+ continue;
6115
+ const drain = Math.max(svc.drain, cfg.proxy.reloadWait + 2);
6116
+ log.host(unit.host.name, `${svc.name}: retiring ${old} (${drain}s drain, in the background)`);
6117
+ try {
6118
+ await fx.stop(unit.host, svc, old, { drain, detach: true });
6119
+ } catch (error) {
6120
+ warnings++;
6121
+ log.warn(`${unit.host.name}: could not retire ${svc.name}/${old}, it keeps running: ${errMsg(error)}`);
6122
+ }
6123
+ }
6124
+ }
6125
+ for (const unit of units) {
6126
+ if (!unit.persisted)
6127
+ continue;
6128
+ try {
6129
+ await fx.cleanup(unit.host, version, unit.prior);
6130
+ } catch (error) {
6131
+ warnings++;
6132
+ log.warn(`${unit.host.name}: cleanup failed (non-fatal): ${errMsg(error)}`);
6133
+ }
6134
+ }
6135
+ if (errors.length) {
6136
+ const switched = units.filter((u) => u.committed && !u.unconfirmed).map((u) => u.host.name);
6137
+ if (switched.length)
6138
+ log.warn(`${version} was switched on: ${switched.join(", ")}`);
6139
+ for (const extra of errors.slice(1))
6140
+ log.error(errMsg(extra));
6141
+ throw errors[0];
6142
+ }
6143
+ if (warnings) {
6144
+ log.warn(`${version} is live; ${warnings} non-fatal cleanup warning(s) above`);
6145
+ }
6146
+ }
6147
+ function liveEffects(cfg, env) {
6148
+ return {
6149
+ async prepare(host, version, reuse) {
6150
+ if (cfg.mode === "docker") {
6151
+ await loginRegistry(host, cfg, env);
6152
+ await ensureImage(host, cfg, version);
6153
+ } else if (!reuse) {
6154
+ await uploadSource(host, cfg, version);
6155
+ await buildRelease(host, cfg, version, env);
6156
+ } else {
6157
+ const dir = releaseDir(cfg, version);
6158
+ if (!await host.test(`[ -d ${shq(dir)} ]`)) {
6159
+ throw new EpdError(`${host.name}: release ${version} is not on this server`, "Deploy it normally first.");
6160
+ }
6161
+ }
6162
+ },
6163
+ readState: (host, opts) => readState(host, cfg, opts),
6164
+ async start(host, svc, slot, version) {
5235
6165
  if (cfg.mode === "docker") {
5236
6166
  const envFile = await writeServiceEnv(host, cfg, svc, env);
5237
6167
  const names = await startSlot(host, cfg, svc, slot, version, envFile);
5238
- started.push({ svc, slot });
5239
6168
  const ips = usesHostPorts(cfg) ? {} : await containerIps(host, cfg, names);
5240
- probes = names.map((name, i) => ({
6169
+ const probes = names.map((name, i) => ({
5241
6170
  label: name,
5242
6171
  address: usesHostPorts(cfg) ? "127.0.0.1" : ips[name] ?? "",
5243
6172
  port: usesHostPorts(cfg) ? hostPort(cfg, svc, slot, i) : svc.health.port ?? svc.port
@@ -5245,73 +6174,45 @@ async function deployToHost(d) {
5245
6174
  const noIp = probes.find((p) => !p.address);
5246
6175
  if (noIp)
5247
6176
  throw new EpdError(`${host.name}: ${noIp.label} did not get an IP on the ${cfg.proxy.network} network`, "Check `epd logs`.");
5248
- } else {
5249
- await startSlot2(host, cfg, svc, slot, version, env);
5250
- started.push({ svc, slot });
5251
- probes = Array.from({ length: svc.replicas }, (_, i) => ({
5252
- label: `${svc.name}#${i}`,
5253
- address: "127.0.0.1",
5254
- port: hostPort(cfg, svc, slot, i)
5255
- }));
6177
+ return probes;
5256
6178
  }
5257
- if (!opts.skipHealth && svc.proxied) {
6179
+ await startSlot2(host, cfg, svc, slot, version, env);
6180
+ return Array.from({ length: svc.replicas }, (_, i) => ({
6181
+ label: `${svc.name}#${i}`,
6182
+ address: "127.0.0.1",
6183
+ port: hostPort(cfg, svc, slot, i)
6184
+ }));
6185
+ },
6186
+ async check(host, svc, slot, probes) {
6187
+ if (svc.proxied) {
5258
6188
  log.host(host.name, `${svc.name}: waiting for health check${svc.health.path ? ` ${svc.health.path}` : " (tcp)"}`);
5259
6189
  await waitHealthy(host, probes, svc.health);
5260
6190
  log.host(host.name, `${svc.name}: healthy`);
5261
- } else if (!opts.skipHealth) {
6191
+ } else {
5262
6192
  await confirmUp(host, cfg, svc, slot);
5263
6193
  }
5264
- live.get(host.name)?.set(svc.name, slot) ?? live.set(host.name, new Map([[svc.name, slot]]));
5265
- state.services[svc.name] = {
5266
- slot,
5267
- replicas: svc.replicas,
5268
- version,
5269
- endpoints: endpointsFor(cfg, svc, slot, host.name).map((e) => e.url)
5270
- };
5271
- }
5272
- const hasSvcRoutes = services.some((s) => s.routes.length);
5273
- const hasAccRoutes = cfg.accessories.some((a) => a.routes.length && (cfg.proxy.crossHost || a.host === host.name));
5274
- if (cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
5275
- await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
5276
- log.host(host.name, "routes updated");
5277
- } else if (!cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
5278
- await syncExternalProxy(host, cfg);
5279
- }
5280
- for (const svc of services) {
5281
- const old = previous.get(svc.name);
5282
- if (!old)
5283
- continue;
5284
- const drain = Math.max(svc.drain, cfg.proxy.reloadWait + 2);
5285
- log.host(host.name, `${svc.name}: retiring ${old} (${drain}s drain, in the background)`);
5286
- if (cfg.mode === "docker")
5287
- await stopSlot(host, cfg, svc, old, { drain, remove: true, detach: true });
5288
- else
5289
- await stopSlot2(host, cfg, svc, old, drain, { detach: true });
5290
- }
5291
- await writeState(host, cfg, recordDeploy(state, version, process.env.USER ?? "epd", cfg.keepReleases));
5292
- if (cfg.mode === "docker") {
5293
- await pruneImages(host, cfg, cfg.keepReleases, [version, ...state.history.slice(0, 2).map((h) => h.version)]);
5294
- } else {
5295
- await finalizeRelease(host, cfg, version);
5296
- }
5297
- log.host(host.name, c.green("done"));
5298
- } catch (error) {
5299
- log.error(`${host.name}: deploy failed, rolling back this host`);
5300
- for (const { svc, slot } of started) {
5301
- try {
5302
- if (cfg.mode === "docker")
5303
- await stopSlot(host, cfg, svc, slot, { drain: 0, remove: true });
5304
- else
5305
- await stopSlot2(host, cfg, svc, slot, 0);
5306
- } catch {}
5307
- }
5308
- if (!d.opts.skipHooks && cfg.hooks.onFailure) {
5309
- await hook(cfg, "on_failure", cfg.hooks.onFailure, version).catch(() => {
5310
- return;
5311
- });
6194
+ },
6195
+ writeRoutes: (host, endpoints, accessories) => writeRoutes(host, cfg, endpoints, accessories),
6196
+ readRoutes: (host) => readRouteUrls(host, cfg),
6197
+ syncExternal: (host) => syncExternalProxy(host, cfg),
6198
+ async stop(host, svc, slot, o) {
6199
+ if (cfg.mode === "docker") {
6200
+ await stopSlot(host, cfg, svc, slot, { drain: o.drain, remove: true, detach: o.detach });
6201
+ } else {
6202
+ await stopSlot2(host, cfg, svc, slot, o.drain, { detach: o.detach });
6203
+ }
6204
+ },
6205
+ writeState: (host, state) => writeState(host, cfg, state),
6206
+ async cleanup(host, version, previous) {
6207
+ if (cfg.mode === "docker") {
6208
+ await removeLegacyEnvFiles(host, cfg);
6209
+ await pruneImages(host, cfg, cfg.keepReleases, [version, ...previous.history.slice(0, 2).map((h) => h.version)]);
6210
+ } else {
6211
+ await removeLegacyEcosystemFiles(host, cfg);
6212
+ await finalizeRelease(host, cfg, version);
6213
+ }
5312
6214
  }
5313
- throw error;
5314
- }
6215
+ };
5315
6216
  }
5316
6217
  async function confirmUp(host, cfg, svc, slot) {
5317
6218
  if (cfg.mode === "docker") {
@@ -5382,11 +6283,15 @@ async function deployAccessories(cfg, env, recreate) {
5382
6283
  if (cfg.mode === "process" && !await hasDocker(host2)) {
5383
6284
  throw new EpdError(`accessories.${acc.name} needs docker on ${acc.host}`, "Accessories always run as containers. Install docker there, or run this dependency yourself.");
5384
6285
  }
5385
- await ensureDirs(host2, cfg);
5386
- await ensureNetwork(host2, cfg);
5387
- await startAccessory(host2, cfg, acc, env, { recreate });
6286
+ await deployAccessory(host2, cfg, acc, env, recreate);
5388
6287
  }
5389
6288
  }
6289
+ async function deployAccessory(host, cfg, acc, env, recreate) {
6290
+ await ensureDirs(host, cfg);
6291
+ await ensureNetwork(host, cfg);
6292
+ await startAccessory(host, cfg, acc, env, { recreate });
6293
+ await removeLegacyEnvFiles(host, cfg);
6294
+ }
5390
6295
  function selectServices(cfg, only) {
5391
6296
  if (!only?.length)
5392
6297
  return cfg.services;
@@ -5439,6 +6344,7 @@ function printUrls(cfg) {
5439
6344
  for (const u of urls)
5440
6345
  log.info(c.cyan(u));
5441
6346
  }
6347
+ var errMsg = (e) => e instanceof Error ? e.message : String(e);
5442
6348
  var init_deploy = __esm(() => {
5443
6349
  init_log();
5444
6350
  init_misc();
@@ -5472,6 +6378,7 @@ var init_setup = __esm(() => {
5472
6378
  init_traefik();
5473
6379
  init_detect();
5474
6380
  init_deploy();
6381
+ init_image();
5475
6382
  init_cloudflare2();
5476
6383
  init_resolve();
5477
6384
  setup = {
@@ -5522,6 +6429,8 @@ Options
5522
6429
  log.info(`not asking again \u2014 run ${c.cyan("epd auth cloudflare")} to link it later`);
5523
6430
  }
5524
6431
  }
6432
+ if (cfg.mode === "docker")
6433
+ checkRegistryPassword(cfg, loaded.env);
5525
6434
  await resolveDynamicHosts(cfg, loaded.env);
5526
6435
  const only = ctx.values.host;
5527
6436
  const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
@@ -5654,6 +6563,7 @@ var rollback;
5654
6563
  var init_rollback = __esm(() => {
5655
6564
  init_log();
5656
6565
  init_deploy();
6566
+ init_image();
5657
6567
  init_state();
5658
6568
  init_ssh();
5659
6569
  rollback = {
@@ -5681,6 +6591,8 @@ Options
5681
6591
  const first = hosts[0];
5682
6592
  if (!first)
5683
6593
  throw new EpdError("no hosts configured");
6594
+ if (cfg.mode === "docker" && !ctx.values.list)
6595
+ checkRegistryPassword(cfg, loaded.env);
5684
6596
  const state = await readState(first, cfg);
5685
6597
  if (!state?.history.length) {
5686
6598
  throw new EpdError(`${cfg.name} has no deploy history on ${first.name}`, "Deploy it at least twice before rolling back.");
@@ -5852,6 +6764,8 @@ Options
5852
6764
  const { config: cfg, env } = ctx.load();
5853
6765
  await resolveDynamicHosts(cfg, env);
5854
6766
  const lines = String(ctx.values.lines ?? "100");
6767
+ if (!/^\d+$/.test(lines))
6768
+ throw new EpdError(`--lines must be a number, got ${JSON.stringify(lines)}`);
5855
6769
  const service = ctx.values.service;
5856
6770
  const accessory = ctx.values.accessory;
5857
6771
  const grep = ctx.values.grep;
@@ -5876,9 +6790,9 @@ Options
5876
6790
  names = [names[0]];
5877
6791
  }
5878
6792
  const filter = [
5879
- `--filter "label=epd.app=${cfg.name}"`,
5880
- service ? `--filter "label=epd.service=${service}"` : "",
5881
- accessory ? `--filter "label=epd.accessory=${accessory}"` : ""
6793
+ `--filter ${shq(`label=epd.app=${cfg.name}`)}`,
6794
+ service ? `--filter ${shq(`label=epd.service=${service}`)}` : "",
6795
+ accessory ? `--filter ${shq(`label=epd.accessory=${accessory}`)}` : ""
5882
6796
  ].filter(Boolean).join(" ");
5883
6797
  for (const name of names) {
5884
6798
  const host2 = host(name, cfg.ssh);
@@ -5915,6 +6829,7 @@ wait`;
5915
6829
  });
5916
6830
 
5917
6831
  // src/commands/exec.ts
6832
+ import { randomBytes } from "crypto";
5918
6833
  async function pickHost(ctx, cfg) {
5919
6834
  const names = allHosts(cfg);
5920
6835
  const chosen = ctx.values.host ?? names[0];
@@ -5922,6 +6837,40 @@ async function pickHost(ctx, cfg) {
5922
6837
  throw new EpdError(`no such host "${chosen}"`, `Known: ${names.join(", ")}`);
5923
6838
  return host(chosen, cfg.ssh);
5924
6839
  }
6840
+ function oneOffEnvFile(cfg) {
6841
+ return `${paths(cfg).app}/exec-env.${randomBytes(8).toString("hex")}`;
6842
+ }
6843
+ async function withEnvFile(host, file, content, script, opts = {}) {
6844
+ await host.writeFile(file, content, "600");
6845
+ return host.interactive(`trap ${shq(`rm -f -- ${shq(file)}`)} EXIT
6846
+ ${script}`, opts);
6847
+ }
6848
+ async function runInProcessApp(host, cfg, env, command) {
6849
+ const file = oneOffEnvFile(cfg);
6850
+ const script = `cd ${shq(paths(cfg).current)} && ${pathPrelude(cfg)} && set -a && . ${shq(file)} && set +a && ${command}`;
6851
+ return withEnvFile(host, file, processEnvContent(cfg, env), script, { sudo: false });
6852
+ }
6853
+ async function runInNewContainer(host, cfg, env, svc, version, o) {
6854
+ const content = serviceEnvContent(svc, env);
6855
+ const file = oneOffEnvFile(cfg);
6856
+ const args = [
6857
+ "docker",
6858
+ "run",
6859
+ "--rm",
6860
+ o.interactive ? "-it" : "",
6861
+ "--network",
6862
+ cfg.proxy.network,
6863
+ "--env-file",
6864
+ file,
6865
+ "--env",
6866
+ `PORT=${svc.port}`,
6867
+ "--label",
6868
+ `epd.app=${cfg.name}`,
6869
+ imageRef(cfg, version)
6870
+ ].filter(Boolean);
6871
+ const script = [...args, ...o.argv].map((a) => shq(a)).join(" ");
6872
+ return withEnvFile(host, file, content, script);
6873
+ }
5925
6874
  var exec, shell;
5926
6875
  var init_exec = __esm(() => {
5927
6876
  init_log();
@@ -5930,6 +6879,8 @@ var init_exec = __esm(() => {
5930
6879
  init_names();
5931
6880
  init_state();
5932
6881
  init_ssh();
6882
+ init_docker();
6883
+ init_process();
5933
6884
  init_image();
5934
6885
  init_resolve();
5935
6886
  exec = {
@@ -5990,10 +6941,8 @@ Examples
5990
6941
  if (!version)
5991
6942
  throw new EpdError(`${cfg.name} is not deployed on ${host2.name}`);
5992
6943
  if (cfg.mode === "process") {
5993
- const dir = `${paths(cfg).current}`;
5994
- const script = `cd ${shq(dir)} && ${pathPrelude(cfg)} && set -a && . ${shq(paths(cfg).envFile)} && set +a && ${command}`;
5995
6944
  log.info(`${host2.name}: ${command}`);
5996
- const code = await host2.interactive(script, { sudo: false });
6945
+ const code = await runInProcessApp(host2, cfg, env, command);
5997
6946
  if (code !== 0)
5998
6947
  process.exitCode = code;
5999
6948
  return;
@@ -6007,24 +6956,11 @@ Examples
6007
6956
  process.exitCode = code;
6008
6957
  return;
6009
6958
  }
6010
- const envFile = `${paths(cfg).app}/env.${svc.name}`;
6011
- const args = [
6012
- "docker",
6013
- "run",
6014
- "--rm",
6015
- ctx.values.interactive ? "-it" : "",
6016
- "--network",
6017
- cfg.proxy.network,
6018
- "--env-file",
6019
- envFile,
6020
- "--env",
6021
- `PORT=${svc.port}`,
6022
- "--label",
6023
- `epd.app=${cfg.name}`,
6024
- imageRef(cfg, version)
6025
- ].filter(Boolean);
6026
6959
  log.info(`${host2.name}: ${command} ${c.gray(`(new container from ${version})`)}`);
6027
- const code = await host2.interactive(`${args.map((a) => shq(a)).join(" ")} ${cmdArgs}`);
6960
+ const code = await runInNewContainer(host2, cfg, env, svc, version, {
6961
+ argv: ctx.positionals,
6962
+ interactive: Boolean(ctx.values.interactive)
6963
+ });
6028
6964
  if (code !== 0)
6029
6965
  process.exitCode = code;
6030
6966
  }
@@ -6120,6 +7056,8 @@ Options
6120
7056
  }
6121
7057
  case "logs": {
6122
7058
  const lines = String(ctx.values.lines ?? "100");
7059
+ if (!/^\d+$/.test(lines))
7060
+ throw new EpdError(`--lines must be a number, got ${JSON.stringify(lines)}`);
6123
7061
  const follow = Boolean(ctx.values.follow);
6124
7062
  for (const host of hosts) {
6125
7063
  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`;
@@ -6322,7 +7260,8 @@ var init_lock2 = __esm(() => {
6322
7260
  help: () => `${c.bold("epd lock <status|release>")}
6323
7261
 
6324
7262
  epd takes a lock on every server while deploying so two deploys cannot overlap.
6325
- If a deploy was killed halfway, release it by hand.`,
7263
+ If a deploy was killed halfway, release it by hand with \`epd lock release\`.
7264
+ \`epd lock status\` shows who holds each server's lock and flags locks that look stale.`,
6326
7265
  async run(ctx) {
6327
7266
  const { config: cfg, env } = ctx.load();
6328
7267
  await resolveDynamicHosts(cfg, env);
@@ -6336,7 +7275,14 @@ If a deploy was killed halfway, release it by hand.`,
6336
7275
  if (sub !== "status")
6337
7276
  throw new EpdError(`unknown subcommand "${sub}"`, "Try: status, release");
6338
7277
  for (const { host, info } of await DeployLock.status(cfg, hosts)) {
6339
- 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")}`);
7278
+ if (!info) {
7279
+ log.plain(`${c.magenta(host)} ${c.green("free")}`);
7280
+ continue;
7281
+ }
7282
+ const stale = staleReason(info);
7283
+ log.plain(`${c.magenta(host)} ${c.yellow("locked")} by ${info.by} ${c.gray(`${info.at} \u2014 ${info.what}`)}`);
7284
+ if (stale)
7285
+ log.plain(` ${c.gray(`probably stale: ${stale}. Clear it with: epd lock release`)}`);
6340
7286
  }
6341
7287
  }
6342
7288
  };
@@ -6400,6 +7346,16 @@ Options
6400
7346
  });
6401
7347
 
6402
7348
  // src/commands/dockerCommand.ts
7349
+ function envFileLines(file, clear, secrets) {
7350
+ return [
7351
+ `# env file: create it first, filling in the secrets; delete it after the run`,
7352
+ "umask 077",
7353
+ `cat > ${shq(file)} <<'EOF'`,
7354
+ ...Object.entries(clear).map(([k, v]) => `${k}=${redact(v)}`),
7355
+ ...secrets.map((k) => `${k}=<secret>`),
7356
+ "EOF"
7357
+ ];
7358
+ }
6403
7359
  function pretty(args) {
6404
7360
  const out = [];
6405
7361
  let line = "";
@@ -6449,6 +7405,9 @@ Options
6449
7405
  const replicas = ctx.values.replica !== undefined ? [Number(ctx.values.replica)] : Array.from({ length: svc.replicas }, (_, i) => i);
6450
7406
  log.plain(`${c.bold(`# ${svc.name}`)} ${c.gray(`on ${serverHost}, slot ${slot}, version ${version}`)}`);
6451
7407
  if (cfg.mode === "docker") {
7408
+ const envFile = `${paths(cfg).app}/env.${svc.name}`;
7409
+ log.template(envFileLines(envFile, svc.env, svc.secrets).join(`
7410
+ `));
6452
7411
  for (const i of replicas) {
6453
7412
  const args = dockerRunArgs({
6454
7413
  cfg,
@@ -6457,11 +7416,13 @@ Options
6457
7416
  version,
6458
7417
  replica: i,
6459
7418
  serverHost,
6460
- envFile: `${paths(cfg).app}/env.${svc.name}`
7419
+ envFile
6461
7420
  });
6462
7421
  log.plain(pretty(args));
6463
7422
  log.plain("");
6464
7423
  }
7424
+ log.plain(`rm -f -- ${shq(envFile)}`);
7425
+ log.plain("");
6465
7426
  } else {
6466
7427
  const command = svc.command ?? cfg.process.start;
6467
7428
  const argv = parseCommand(command);
@@ -6478,6 +7439,9 @@ Options
6478
7439
  if (cfg.accessories.length) {
6479
7440
  for (const acc of cfg.accessories) {
6480
7441
  log.plain(`${c.bold(`# accessory: ${acc.name}`)} ${c.gray(`on ${acc.host}`)}`);
7442
+ const envFile = `${paths(cfg).app}/env.acc.${acc.name}`;
7443
+ log.template(envFileLines(envFile, acc.env, acc.secrets).join(`
7444
+ `));
6481
7445
  const accArgs = [
6482
7446
  "docker",
6483
7447
  "run",
@@ -6495,7 +7459,7 @@ Options
6495
7459
  "--label",
6496
7460
  "epd.managed=true",
6497
7461
  "--env-file",
6498
- `${paths(cfg).app}/env.acc.${acc.name}`,
7462
+ envFile,
6499
7463
  "--log-opt",
6500
7464
  "max-size=10m",
6501
7465
  "--log-opt",
@@ -6508,6 +7472,8 @@ Options
6508
7472
  ];
6509
7473
  log.plain(pretty(accArgs));
6510
7474
  log.plain("");
7475
+ log.plain(`rm -f -- ${shq(envFile)}`);
7476
+ log.plain("");
6511
7477
  }
6512
7478
  }
6513
7479
  log.plain(`${c.bold("# proxy")} ${c.gray("(one per server, shared by every epd app on it)")}`);
@@ -7064,16 +8030,14 @@ class SevallaClient {
7064
8030
  "Content-Type": "application/json",
7065
8031
  ...options.headers
7066
8032
  };
7067
- const res = await fetch(url, { ...options, headers });
7068
- let data;
7069
- try {
7070
- data = await res.json();
7071
- } catch {
7072
- data = null;
7073
- }
8033
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
8034
+ const { data, isJson, empty } = await readJsonBody(res);
7074
8035
  if (!res.ok) {
7075
- const msg = data?.message || data?.error?.message || `HTTP ${res.status} ${res.statusText}`;
7076
- throw new EpdError(`Sevalla API error: ${msg}`);
8036
+ const msg = firstString(data?.message, data?.error?.message) || statusLabel(res);
8037
+ throw new HttpApiError(redactSecret(`Sevalla API error: ${msg}`, this.apiToken), res.status);
8038
+ }
8039
+ if (!isJson && !empty) {
8040
+ throw new EpdError(`Sevalla API returned a non-JSON response (${statusLabel(res)})`, "The API may be unavailable or a proxy may be intercepting the request. Try again later.");
7077
8041
  }
7078
8042
  return data;
7079
8043
  }
@@ -7125,7 +8089,7 @@ class SevallaClient {
7125
8089
  ];
7126
8090
  }
7127
8091
  const res = await this.request("/applications");
7128
- const list = res.applications || res.data || [];
8092
+ const list = res?.applications || res?.data || [];
7129
8093
  return list.map((a) => ({
7130
8094
  id: a.id,
7131
8095
  name: a.name || a.display_name,
@@ -7159,12 +8123,12 @@ class SevallaClient {
7159
8123
  body: JSON.stringify(opts)
7160
8124
  });
7161
8125
  return {
7162
- id: res.id || res.deployment_id,
8126
+ id: res?.id || res?.deployment_id,
7163
8127
  applicationId: id,
7164
- status: res.status || "deploying",
7165
- commitHash: res.commit_hash,
7166
- commitMessage: res.commit_message,
7167
- createdAt: res.created_at || new Date().toISOString()
8128
+ status: res?.status || "deploying",
8129
+ commitHash: res?.commit_hash,
8130
+ commitMessage: res?.commit_message,
8131
+ createdAt: res?.created_at || new Date().toISOString()
7168
8132
  };
7169
8133
  }
7170
8134
  async listDatabases() {
@@ -7189,7 +8153,7 @@ class SevallaClient {
7189
8153
  ];
7190
8154
  }
7191
8155
  const res = await this.request("/databases");
7192
- const list = res.databases || res.data || [];
8156
+ const list = res?.databases || res?.data || [];
7193
8157
  return list.map((d) => ({
7194
8158
  id: d.id,
7195
8159
  name: d.name,
@@ -7230,15 +8194,15 @@ class SevallaClient {
7230
8194
  body: JSON.stringify(opts)
7231
8195
  });
7232
8196
  return {
7233
- id: res.id,
7234
- name: res.name || opts.name,
7235
- displayName: res.display_name || opts.name,
7236
- type: res.type || opts.type,
7237
- version: res.version || opts.version || "16",
7238
- status: res.status || "creating",
7239
- internalHost: res.internal_host,
7240
- externalHost: res.external_host,
7241
- port: res.port || 5432,
8197
+ id: res?.id,
8198
+ name: res?.name || opts.name,
8199
+ displayName: res?.display_name || opts.name,
8200
+ type: res?.type || opts.type,
8201
+ version: res?.version || opts.version || "16",
8202
+ status: res?.status || "creating",
8203
+ internalHost: res?.internal_host,
8204
+ externalHost: res?.external_host,
8205
+ port: res?.port || 5432,
7242
8206
  dbName: res.db_name || opts.name,
7243
8207
  dbUser: res.db_user || "admin",
7244
8208
  region: res.region || opts.region,
@@ -7248,6 +8212,7 @@ class SevallaClient {
7248
8212
  }
7249
8213
  var init_api2 = __esm(() => {
7250
8214
  init_log();
8215
+ init_http();
7251
8216
  });
7252
8217
 
7253
8218
  // src/commands/sevalla.ts
@@ -7298,6 +8263,7 @@ Environment
7298
8263
  token = loaded.config.sevalla?.apiToken || loaded.env.SEVALLA_API_TOKEN;
7299
8264
  } catch {}
7300
8265
  token = token || process.env.SEVALLA_API_TOKEN;
8266
+ registerSecret(token);
7301
8267
  const sub = ctx.positionals[0] || "apps";
7302
8268
  if (sub === "auth") {
7303
8269
  log.step("Link your Sevalla Cloud account");
@@ -7405,9 +8371,79 @@ ${c.bold("SEVALLA MANAGED DATABASES")} (${dbs.length})
7405
8371
  });
7406
8372
 
7407
8373
  // src/core/update.ts
7408
- import { chmodSync as chmodSync3, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync, writeFileSync as writeFileSync7 } from "fs";
8374
+ import { createHash } from "crypto";
8375
+ import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "fs";
7409
8376
  import { homedir as homedir4 } from "os";
7410
- import { basename as basename3, dirname as dirname3, join as join9 } from "path";
8377
+ import { basename as basename3, dirname as dirname5, join as join10 } from "path";
8378
+ function isValidVersion(version) {
8379
+ return VERSION_RE.test(version);
8380
+ }
8381
+ function binaryNameFor(platform, arch) {
8382
+ if (platform === "linux" && arch === "x64")
8383
+ return "epd-linux-x64";
8384
+ if (platform === "linux" && arch === "arm64")
8385
+ return "epd-linux-arm64";
8386
+ if (platform === "darwin" && arch === "x64")
8387
+ return "epd-darwin-x64";
8388
+ if (platform === "darwin" && arch === "arm64")
8389
+ return "epd-darwin-arm64";
8390
+ if (platform === "win32" && arch === "x64")
8391
+ return "epd-windows-x64.exe";
8392
+ return null;
8393
+ }
8394
+ function releaseDownloadBase(version) {
8395
+ const v = version?.trim().replace(/^v/, "");
8396
+ return v ? `https://github.com/${RELEASE_REPO}/releases/download/v${v}` : `https://github.com/${RELEASE_REPO}/releases/latest/download`;
8397
+ }
8398
+ function parseChecksums(text) {
8399
+ const out = new Map;
8400
+ for (const line of text.split(/\r?\n/)) {
8401
+ const m = /^([0-9a-fA-F]{64})\s+\*?(\S+)\s*$/.exec(line);
8402
+ if (m)
8403
+ out.set(m[2], m[1].toLowerCase());
8404
+ }
8405
+ return out;
8406
+ }
8407
+ function verifyBinaryChecksum(name, data, checksumsText) {
8408
+ const expected = parseChecksums(checksumsText).get(name);
8409
+ if (!expected) {
8410
+ throw new IntegrityError(`No SHA-256 checksum is published for ${name}. Refusing to install an unverified binary.`);
8411
+ }
8412
+ const actual = createHash("sha256").update(data).digest("hex");
8413
+ if (actual !== expected) {
8414
+ throw new IntegrityError(`SHA-256 mismatch for ${name} (expected ${expected}, got ${actual}). Refusing to install the download.`);
8415
+ }
8416
+ }
8417
+ function assertHttps(url) {
8418
+ if (new URL(url).protocol !== "https:")
8419
+ throw new Error(`Refusing non-HTTPS download: ${url}`);
8420
+ }
8421
+ async function downloadBytes(url, timeoutMs) {
8422
+ assertHttps(url);
8423
+ const res = await fetchWithRetry(url, {}, { timeoutMs, retries: 2 });
8424
+ const name = url.split("/").pop();
8425
+ if (res.status === 404 && name === CHECKSUM_ASSET) {
8426
+ throw new IntegrityError(`${CHECKSUM_ASSET} is not published for this release. Refusing to install an unverified binary.`);
8427
+ }
8428
+ if (!res.ok)
8429
+ throw new Error(`${statusLabel(res)} downloading ${name}`);
8430
+ if (res.url)
8431
+ assertHttps(res.url);
8432
+ return new Uint8Array(await res.arrayBuffer());
8433
+ }
8434
+ function replaceExecutable(path, data) {
8435
+ const tmpPath = `${path}.tmp.${process.pid}.${Date.now()}`;
8436
+ try {
8437
+ writeFileSync7(tmpPath, data);
8438
+ chmodSync3(tmpPath, 493);
8439
+ renameSync2(tmpPath, path);
8440
+ } catch (e) {
8441
+ try {
8442
+ unlinkSync3(tmpPath);
8443
+ } catch {}
8444
+ throw e;
8445
+ }
8446
+ }
7411
8447
  function isCompiledExecutable(execPath, isBun) {
7412
8448
  return isBun && !["bun", "bun.exe"].includes(basename3(execPath).toLowerCase());
7413
8449
  }
@@ -7433,12 +8469,12 @@ function isNewer(current, latest) {
7433
8469
  return lPatch > cPatch;
7434
8470
  }
7435
8471
  function getCachePath() {
7436
- return join9(homedir4(), ".epd", "update-check.json");
8472
+ return join10(homedir4(), ".epd", "update-check.json");
7437
8473
  }
7438
8474
  function readCache() {
7439
8475
  try {
7440
8476
  const p = getCachePath();
7441
- if (existsSync10(p)) {
8477
+ if (existsSync11(p)) {
7442
8478
  return JSON.parse(readFileSync7(p, "utf8"));
7443
8479
  }
7444
8480
  } catch {}
@@ -7447,7 +8483,7 @@ function readCache() {
7447
8483
  function writeCache(latestVersion) {
7448
8484
  try {
7449
8485
  const p = getCachePath();
7450
- mkdirSync6(dirname3(p), { recursive: true });
8486
+ mkdirSync6(dirname5(p), { recursive: true });
7451
8487
  const data = { lastChecked: Date.now(), latestVersion };
7452
8488
  writeFileSync7(p, JSON.stringify(data));
7453
8489
  } catch {}
@@ -7490,56 +8526,46 @@ async function checkForUpdate(currentVersion, options = {}) {
7490
8526
  return { hasUpdate: false, latestVersion: currentVersion };
7491
8527
  }
7492
8528
  async function performUpdate(targetVersion) {
8529
+ if (targetVersion && !isValidVersion(targetVersion)) {
8530
+ return { ok: false, reason: "failed", message: `Refusing to install invalid version "${targetVersion}".` };
8531
+ }
7493
8532
  const isBun = typeof process.isBun !== "undefined";
7494
8533
  const execPath = process.execPath || "";
7495
8534
  const isCompiledBinary = isCompiledExecutable(execPath, isBun);
7496
- if (isCompiledBinary) {
8535
+ const binaryName = isCompiledBinary ? binaryNameFor(process.platform, process.arch) : null;
8536
+ if (binaryName) {
7497
8537
  try {
7498
- const platform = process.platform;
7499
- const arch = process.arch;
7500
- let binaryName = "";
7501
- if (platform === "linux" && arch === "x64")
7502
- binaryName = "epd-linux-x64";
7503
- else if (platform === "linux" && arch === "arm64")
7504
- binaryName = "epd-linux-arm64";
7505
- else if (platform === "darwin" && arch === "x64")
7506
- binaryName = "epd-darwin-x64";
7507
- else if (platform === "darwin" && arch === "arm64")
7508
- binaryName = "epd-darwin-arm64";
7509
- else if (platform === "win32" && arch === "x64")
7510
- binaryName = "epd-windows-x64.exe";
7511
- if (binaryName) {
7512
- log.step(`Downloading ${binaryName} from GitHub Releases...`);
7513
- const release = targetVersion ? `download/v${targetVersion}` : "latest/download";
7514
- const url = `https://github.com/FabioPlunser/epd/releases/${release}/${binaryName}`;
7515
- const res = await fetch(url);
7516
- if (!res.ok)
7517
- throw new Error(`HTTP ${res.status} ${res.statusText}`);
7518
- const buf = await res.arrayBuffer();
7519
- const tmpPath = `${execPath}.tmp.${Date.now()}`;
7520
- writeFileSync7(tmpPath, Buffer.from(buf));
7521
- chmodSync3(tmpPath, 493);
7522
- renameSync(tmpPath, execPath);
7523
- return true;
7524
- }
8538
+ const base = releaseDownloadBase(targetVersion);
8539
+ log.step(`Downloading ${binaryName} from GitHub Releases...`);
8540
+ const checksums = new TextDecoder().decode(await downloadBytes(`${base}/${CHECKSUM_ASSET}`, 15000));
8541
+ const data = await downloadBytes(`${base}/${binaryName}`, 300000);
8542
+ verifyBinaryChecksum(binaryName, data, checksums);
8543
+ replaceExecutable(execPath, data);
8544
+ return { ok: true };
7525
8545
  } catch (e) {
8546
+ if (e instanceof IntegrityError) {
8547
+ return { ok: false, reason: "integrity", message: e.message };
8548
+ }
7526
8549
  log.debug(`Binary self-update failed, falling back to package manager: ${e}`);
7527
8550
  }
7528
8551
  }
7529
8552
  const isBunGlobal = (process.argv[1] || "").includes(".bun");
7530
8553
  const pkgMgr = isBunGlobal ? "bun" : "npm";
7531
- const pkgSpec = targetVersion ? `@fabioplunser/epd@${targetVersion}` : "@fabioplunser/epd@latest";
7532
- for (const manager of [pkgMgr, pkgMgr === "bun" ? "npm" : "bun"]) {
8554
+ const pkgSpec = targetVersion ? `@fabioplunser/epd@${targetVersion.replace(/^v/, "")}` : "@fabioplunser/epd@latest";
8555
+ try {
8556
+ log.step(`Updating via ${pkgMgr}...`);
8557
+ const res = await run(packageUpdateCommand(pkgMgr, pkgSpec), { stream: true, allowFailure: true });
8558
+ return res.code === 0 ? { ok: true } : { ok: false, reason: "failed", message: `${pkgMgr} install exited with code ${res.code}.` };
8559
+ } catch {
8560
+ const fallback = pkgMgr === "bun" ? "npm" : "bun";
7533
8561
  try {
7534
- log.step(`Updating via ${manager}...`);
7535
- const res = await run(packageUpdateCommand(manager, pkgSpec), { stream: true, allowFailure: true });
7536
- if (res.code === 0)
7537
- return true;
7538
- } catch (error) {
7539
- log.debug(`${manager} update failed: ${error}`);
8562
+ log.step(`Trying ${fallback}...`);
8563
+ const res = await run(packageUpdateCommand(fallback, pkgSpec), { stream: true, allowFailure: true });
8564
+ return res.code === 0 ? { ok: true } : { ok: false, reason: "failed", message: `${fallback} install exited with code ${res.code}.` };
8565
+ } catch {
8566
+ return { ok: false, reason: "failed", message: `Neither bun nor npm could install ${pkgSpec}.` };
7540
8567
  }
7541
8568
  }
7542
- return false;
7543
8569
  }
7544
8570
  async function promptAutoUpdate(currentVersion) {
7545
8571
  if (!interactive() || process.env.CI || process.env.EPD_NO_UPDATE_CHECK === "1" || process.env.EPD_NO_UPDATE_CHECK === "true") {
@@ -7556,26 +8582,38 @@ async function promptAutoUpdate(currentVersion) {
7556
8582
  return false;
7557
8583
  }
7558
8584
  log.step(`Updating epd to v${latestVersion}...`);
7559
- const success = await performUpdate(latestVersion);
7560
- if (success) {
8585
+ const outcome = await performUpdate(latestVersion);
8586
+ if (outcome.ok) {
7561
8587
  log.ok(`Successfully updated epd to ${c.bold(`v${latestVersion}`)}!`);
7562
8588
  console.log("");
7563
8589
  return true;
8590
+ }
8591
+ if (outcome.reason === "integrity") {
8592
+ log.error(`Auto-update rejected for integrity reasons: ${outcome.message} The installed epd binary was not changed.`);
7564
8593
  } else {
7565
8594
  log.warn(`Auto-update failed. You can update manually with:
7566
8595
  ${c.cyan(`npm install -g @fabioplunser/epd@latest`)}
7567
8596
  `);
7568
- return false;
7569
8597
  }
8598
+ return false;
7570
8599
  }
8600
+ var RELEASE_REPO = "FabioPlunser/epd", CHECKSUM_ASSET = "checksums.sha256", IntegrityError, VERSION_RE;
7571
8601
  var init_update = __esm(() => {
8602
+ init_http();
7572
8603
  init_log();
7573
8604
  init_prompt();
7574
8605
  init_proc();
8606
+ IntegrityError = class IntegrityError extends Error {
8607
+ constructor(message) {
8608
+ super(message);
8609
+ this.name = "IntegrityError";
8610
+ }
8611
+ };
8612
+ VERSION_RE = /^v?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
7575
8613
  });
7576
8614
 
7577
8615
  // package.json
7578
- var version = "0.5.13";
8616
+ var version = "0.5.15";
7579
8617
  var init_package = () => {};
7580
8618
 
7581
8619
  // src/version.ts
@@ -7618,11 +8656,14 @@ Options
7618
8656
  return;
7619
8657
  }
7620
8658
  log.step(`Upgrading epd to v${latestVersion}...`);
7621
- const success = await performUpdate(latestVersion);
7622
- if (success) {
8659
+ const outcome = await performUpdate(latestVersion);
8660
+ if (outcome.ok) {
7623
8661
  log.ok(`epd updated successfully to ${c.bold(`v${latestVersion}`)}!`);
8662
+ } else if (outcome.reason === "integrity") {
8663
+ log.error(`Update rejected: the download failed integrity verification. ${outcome.message} The installed epd binary was not changed.`);
7624
8664
  } else {
7625
- log.error(`Update failed. You can update manually with:`);
8665
+ log.error(`Update failed. ${outcome.message}`);
8666
+ log.error(`You can update manually with:`);
7626
8667
  console.log(` ${c.cyan("npm install -g @fabioplunser/epd@latest")}
7627
8668
  `);
7628
8669
  }
@@ -7666,8 +8707,8 @@ Saved credentials are stored with 0600 permissions in ~/.config/epd/auth.json`,
7666
8707
  if (sub === "logout") {
7667
8708
  const confirmed = await confirm("Remove all credentials from ~/.config/epd/auth.json?", true);
7668
8709
  if (confirmed) {
7669
- saveGlobalAuth(() => ({}));
7670
- log.ok("Cleared globally stored credentials in ~/.config/epd/auth.json");
8710
+ clearGlobalAuth();
8711
+ log.ok("Cleared globally stored credentials in ~/.config/epd/auth.json (and the legacy ~/.epd/auth.json)");
7671
8712
  }
7672
8713
  return;
7673
8714
  }
@@ -8344,8 +9385,8 @@ Options
8344
9385
  });
8345
9386
 
8346
9387
  // src/commands/backup.ts
8347
- import { createWriteStream, mkdirSync as mkdirSync7, statSync } from "fs";
8348
- import { dirname as dirname4, join as join10, resolve as resolve3 } from "path";
9388
+ import { createWriteStream, mkdirSync as mkdirSync7, statSync as statSync2 } from "fs";
9389
+ import { dirname as dirname6, join as join11, resolve as resolve3 } from "path";
8349
9390
  function detectAccessoryType(decl, cfg) {
8350
9391
  const name = decl.name;
8351
9392
  const img = (decl.image || "").toLowerCase();
@@ -8453,8 +9494,8 @@ Options
8453
9494
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
8454
9495
  const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
8455
9496
  const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
8456
- const localFile = ctx.values.output ? resolve3(String(ctx.values.output)) : join10(outBaseDir, filename);
8457
- mkdirSync7(dirname4(localFile), { recursive: true });
9497
+ const localFile = ctx.values.output ? resolve3(String(ctx.values.output)) : join11(outBaseDir, filename);
9498
+ mkdirSync7(dirname6(localFile), { recursive: true });
8458
9499
  let dumpCmd = "";
8459
9500
  if (target.type === "postgres") {
8460
9501
  dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
@@ -8492,7 +9533,7 @@ Options
8492
9533
  });
8493
9534
  }
8494
9535
  });
8495
- const stats = statSync(localFile);
9536
+ const stats = statSync2(localFile);
8496
9537
  const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
8497
9538
  const elapsed = dur(Date.now() - t0);
8498
9539
  log.ok(`Backed up ${c.bold(target.name)} \u2192 ${c.cyan(localFile)} (${sizeMb} MB in ${elapsed})`);
@@ -8502,7 +9543,7 @@ Options
8502
9543
  });
8503
9544
 
8504
9545
  // src/commands/restore.ts
8505
- import { createReadStream, existsSync as existsSync11 } from "fs";
9546
+ import { createReadStream, existsSync as existsSync12 } from "fs";
8506
9547
  import { basename as basename4, resolve as resolve4 } from "path";
8507
9548
  var restore;
8508
9549
  var init_restore = __esm(() => {
@@ -8530,7 +9571,7 @@ Options
8530
9571
  if (!backupPath)
8531
9572
  throw new EpdError("Please provide a path to the backup file to restore.");
8532
9573
  const absPath = resolve4(backupPath);
8533
- if (!existsSync11(absPath))
9574
+ if (!existsSync12(absPath))
8534
9575
  throw new EpdError(`Backup file not found: ${absPath}`);
8535
9576
  const loaded = ctx.load();
8536
9577
  const cfg = loaded.config;
@@ -8632,9 +9673,9 @@ Options
8632
9673
  });
8633
9674
 
8634
9675
  // src/commands/doctor.ts
8635
- import { existsSync as existsSync12, readdirSync, statSync as statSync2 } from "fs";
9676
+ import { existsSync as existsSync13, readdirSync, statSync as statSync3 } from "fs";
8636
9677
  import { homedir as homedir5 } from "os";
8637
- import { join as join11 } from "path";
9678
+ import { join as join12 } from "path";
8638
9679
  function printResults(results, prefix = " ") {
8639
9680
  for (const r of results) {
8640
9681
  const symbol = r.status === "ok" ? c.green("\u2713") : r.status === "warn" ? c.yellow("!") : c.red("\u2717");
@@ -8649,6 +9690,7 @@ var init_doctor = __esm(() => {
8649
9690
  init_log();
8650
9691
  init_proc();
8651
9692
  init_ssh();
9693
+ init_misc();
8652
9694
  init_names();
8653
9695
  init_resolve();
8654
9696
  doctor = {
@@ -8748,21 +9790,21 @@ Options
8748
9790
  hint: "Install OpenSSH client via your package manager."
8749
9791
  });
8750
9792
  }
8751
- const sshDir = join11(homedir5(), ".ssh");
9793
+ const sshDir = join12(homedir5(), ".ssh");
8752
9794
  if (process.env.SSH_PRIVATE_KEY || process.env.EPD_SSH_KEY) {
8753
9795
  results.push({
8754
9796
  name: "SSH Key (Environment)",
8755
9797
  status: "ok",
8756
9798
  message: "SSH_PRIVATE_KEY is set in the environment (ideal for CI)"
8757
9799
  });
8758
- } else if (existsSync12(sshDir)) {
9800
+ } else if (existsSync13(sshDir)) {
8759
9801
  const keys = readdirSync(sshDir).filter((f) => ["id_ed25519", "id_rsa", "gh_deploy"].includes(f));
8760
9802
  if (keys.length > 0) {
8761
9803
  const keyIssues = [];
8762
9804
  for (const k of keys) {
8763
- const p = join11(sshDir, k);
9805
+ const p = join12(sshDir, k);
8764
9806
  try {
8765
- const st = statSync2(p);
9807
+ const st = statSync3(p);
8766
9808
  const mode = st.mode & 511;
8767
9809
  if (mode !== 384 && mode !== 256) {
8768
9810
  keyIssues.push(`${k} has insecure permissions (${mode.toString(8)} instead of 600)`);
@@ -8923,7 +9965,7 @@ ${c.bold("Remote Servers")}`);
8923
9965
  status: "warn",
8924
9966
  message: `${h.user} requires a password for sudo`,
8925
9967
  hint: `Grant passwordless sudo on ${hostname}:
8926
- echo "${h.user} ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/epd && sudo chmod 440 /etc/sudoers.d/epd`
9968
+ ${sudoersCommand(h.user)}`
8927
9969
  });
8928
9970
  }
8929
9971
  }
@@ -8964,7 +10006,7 @@ ${c.bold("Remote Servers")}`);
8964
10006
  }
8965
10007
  }
8966
10008
  const lockPath = paths(cfg).lock;
8967
- const lockCheck = await h.exec(`[ -d "${lockPath}" ] && echo locked || echo free`, { allowFailure: true });
10009
+ const lockCheck = await h.exec(`[ -d ${shq(lockPath)} ] && echo locked || echo free`, { allowFailure: true });
8968
10010
  if (lockCheck.stdout.trim() === "locked") {
8969
10011
  results.push({
8970
10012
  name: "Deploy Lock",
@@ -9402,14 +10444,14 @@ try {
9402
10444
  process.exitCode = await main(process.argv.slice(2));
9403
10445
  } catch (error) {
9404
10446
  if (error instanceof EpdError) {
9405
- log.error(error.message);
10447
+ log.error(redact(error.message));
9406
10448
  if (error.hint)
9407
10449
  console.error(`
9408
- ${c.gray(error.hint)}`);
10450
+ ${c.gray(redact(error.hint))}`);
9409
10451
  } else {
9410
10452
  log.error(error instanceof Error ? error.message : String(error));
9411
10453
  if (process.env.EPD_DEBUG && error instanceof Error)
9412
- console.error(error.stack);
10454
+ console.error(redact(error.stack ?? ""));
9413
10455
  }
9414
10456
  process.exitCode = 1;
9415
10457
  }