@fabioplunser/epd 0.5.14 → 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) {
@@ -270,7 +410,7 @@ function loadEnvironment(root, destination) {
270
410
  return env;
271
411
  }
272
412
  function interpolateText(text, env, file) {
273
- const substitute = (value) => value.replace(/\$(\$?)\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_m, escape, name, dflt) => {
413
+ return text.replace(/\$(\$?)\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_m, escape, name, dflt) => {
274
414
  if (escape)
275
415
  return `\${${name}${dflt !== undefined ? `:-${dflt}` : ""}}`;
276
416
  const v = env[name];
@@ -280,81 +420,16 @@ function interpolateText(text, env, file) {
280
420
  return dflt;
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
- let quote = null;
284
- let flowDepth = 0;
285
- let blockIndent = null;
286
- let blockContentIndent = null;
423
+ }
424
+ function bareRegistryPassword(text) {
425
+ let inRegistry = false;
287
426
  return text.split(`
288
427
  `).map((line) => {
289
- const indent = line.match(/^ */)[0].length;
290
- if (blockIndent !== null) {
291
- if (!line.trim() || indent > blockIndent) {
292
- blockContentIndent ??= line.trim() ? indent : null;
293
- if (blockContentIndent === null || indent >= blockContentIndent)
294
- return substitute(line);
295
- }
296
- blockIndent = blockContentIndent = null;
297
- }
298
- let comment = line.length;
299
- let scalarStart = quote === null;
300
- for (let i = 0;i < line.length; i++) {
301
- const char = line[i];
302
- if (quote) {
303
- if (quote === '"' && char === "\\") {
304
- i++;
305
- continue;
306
- }
307
- if (char === quote) {
308
- if (quote === "'" && line[i + 1] === "'") {
309
- i++;
310
- continue;
311
- }
312
- quote = null;
313
- }
314
- continue;
315
- }
316
- if (char === "#" && (i === 0 || /\s/.test(line[i - 1]))) {
317
- comment = i;
318
- break;
319
- }
320
- if (char === "$" && /^\$\$?\{/.test(line.slice(i))) {
321
- const end = line.indexOf("}", i);
322
- if (end !== -1) {
323
- i = end;
324
- scalarStart = false;
325
- continue;
326
- }
327
- }
328
- if (scalarStart && (char === "'" || char === '"')) {
329
- quote = char;
330
- scalarStart = false;
331
- continue;
332
- }
333
- if (/\s/.test(char))
334
- continue;
335
- if (scalarStart && (char === "&" || char === "!")) {
336
- while (i + 1 < line.length && !/\s/.test(line[i + 1]))
337
- i++;
338
- continue;
339
- }
340
- if (scalarStart && (char === "[" || char === "{")) {
341
- flowDepth++;
342
- } else if (flowDepth && (char === "]" || char === "}")) {
343
- flowDepth--;
344
- scalarStart = false;
345
- } else if (flowDepth && (char === "," || char === ":") || (char === ":" || char === "-" || char === "?") && /\s/.test(line[i + 1] || " ")) {
346
- scalarStart = true;
347
- } else {
348
- scalarStart = false;
349
- }
350
- }
351
- const content = line.slice(0, comment);
352
- if (!quote && /(?:^|:\s+|-\s+)[|>](?:[1-9][+-]?|[+-][1-9]?)?\s*$/.test(content)) {
353
- blockIndent = indent;
354
- const explicitIndent = content.match(/[|>][+-]?([1-9])/);
355
- blockContentIndent = explicitIndent ? indent + Number(explicitIndent[1]) : null;
356
- }
357
- return substitute(content) + line.slice(comment);
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");
358
433
  }).join(`
359
434
  `);
360
435
  }
@@ -373,15 +448,24 @@ function deepMerge(base, overlay) {
373
448
  function fail(path, msg, hint) {
374
449
  throw new EpdError(`${path}: ${msg}`, hint);
375
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
+ }
376
456
  function takeHostUser(entry, path, users) {
457
+ if (entry.startsWith("hetzner:"))
458
+ return entry;
377
459
  const at = entry.lastIndexOf("@");
378
460
  if (at < 0)
379
- return entry;
461
+ return check(entry, path, sshHostProblem, 'Write a host name or IP address, e.g. "10.0.0.1".');
380
462
  const user = entry.slice(0, at);
381
463
  const host = entry.slice(at + 1);
382
464
  if (!user || !host) {
383
465
  fail(path, `"${entry}" is not a valid host`, 'Write it as "user@host", e.g. "deploy@10.0.0.1".');
384
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".');
385
469
  const seen = users[host];
386
470
  if (seen && seen !== user) {
387
471
  fail(path, `host ${host} is listed as both ${seen}@${host} and ${user}@${host}`, "Use one ssh user per host.");
@@ -454,6 +538,14 @@ function asDict(v, path) {
454
538
  }
455
539
  fail(path, "expected a mapping");
456
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
+ }
457
549
  function checkKeys(obj, allowed, path) {
458
550
  for (const k of Object.keys(obj)) {
459
551
  if (!allowed.includes(k)) {
@@ -476,12 +568,118 @@ function levenshtein2(a, b) {
476
568
  function expandHome(p) {
477
569
  return p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
478
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
+ }
479
673
  function parseRoute(raw, path, defaults) {
480
674
  if (typeof raw === "string") {
481
675
  const s = raw.trim();
482
676
  const slash = s.indexOf("/");
483
677
  const host = slash === -1 ? s : s.slice(0, slash);
484
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);
485
683
  return {
486
684
  hosts: host === "*" || host === "" ? [] : [host],
487
685
  path: p && p !== "/" ? p : undefined,
@@ -517,12 +715,13 @@ function parseRoute(raw, path, defaults) {
517
715
  ...asList(o.host ?? o.domain, `${path}.host`),
518
716
  ...asList(o.hosts ?? o.domains, `${path}.hosts`)
519
717
  ].filter((h) => h !== "*");
718
+ checkEach(hosts, `${path}.host`, routeHostProblem, HOST_HINT);
520
719
  const redirectTo = o.redirect ? asString(o.redirect, `${path}.redirect`) : undefined;
521
720
  return {
522
721
  hosts,
523
- 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,
524
723
  stripPath: asBool(o.strip_path, `${path}.strip_path`, false),
525
- port: asNumber(o.port, `${path}.port`, defaults.port),
724
+ port: asPort(o.port, `${path}.port`, defaults.port),
526
725
  entrypoint: o.entrypoint ? asString(o.entrypoint, `${path}.entrypoint`) : undefined,
527
726
  ssl: asBool(o.ssl, `${path}.ssl`, defaults.ssl && hosts.length > 0),
528
727
  redirect: redirectTo ? { to: redirectTo, permanent: asBool(o.permanent, `${path}.permanent`, true) } : undefined,
@@ -538,14 +737,14 @@ function parseHealth(raw, path, dflt) {
538
737
  if (raw === false)
539
738
  return { ...dflt, path: null };
540
739
  if (typeof raw === "string")
541
- return { ...dflt, path: raw };
740
+ return { ...dflt, path: check(raw, path, urlPathProblem, PATH_HINT) };
542
741
  if (typeof raw !== "object")
543
742
  fail(path, "expected a mapping, a path string, or false");
544
743
  const o = raw;
545
744
  checkKeys(o, ["path", "port", "status", "timeout", "interval", "delay", "host"], path);
546
745
  return {
547
- path: o.path === false || o.path === null ? null : asString(o.path, `${path}.path`, dflt.path ?? "/"),
548
- 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,
549
748
  status: asString(o.status, `${path}.status`, dflt.status),
550
749
  timeout: asNumber(o.timeout, `${path}.timeout`, dflt.timeout),
551
750
  interval: asNumber(o.interval, `${path}.interval`, dflt.interval),
@@ -562,6 +761,7 @@ function loadConfig(opts = {}) {
562
761
  const destination = opts.destination;
563
762
  const env = loadEnvironment(root, destination);
564
763
  let raw = parseYaml(configPath, env);
764
+ let overlay;
565
765
  if (destination) {
566
766
  const overlays = [
567
767
  join(root, `epd.${destination}.yml`),
@@ -571,12 +771,56 @@ function loadConfig(opts = {}) {
571
771
  if (!overlays.length) {
572
772
  throw new EpdError(`no config found for destination "${destination}"`, `Create ${join(root, `epd.${destination}.yml`)} with the values that differ.`);
573
773
  }
574
- 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]);
781
+ }
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];
575
817
  }
576
- return { config: normalize(raw, configPath, root, destination), env, raw };
818
+ return true;
577
819
  }
578
820
  function parseYaml(file, env) {
579
- 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) {
580
824
  let parsed;
581
825
  try {
582
826
  parsed = Bun.YAML.parse(text);
@@ -592,13 +836,12 @@ function parseYaml(file, env) {
592
836
  function normalize(raw, configPath, root, destination) {
593
837
  checkKeys(raw, TOP_LEVEL_KEYS, "epd.yml");
594
838
  const name = asString(raw.name, "epd.yml.name");
595
- if (!/^[a-z0-9][a-z0-9_-]*$/i.test(name)) {
596
- fail("epd.yml.name", "must be alphanumeric with dashes or underscores", `Got ${JSON.stringify(name)}.`);
597
- }
839
+ if (!isValidName(name))
840
+ fail("epd.yml.name", nameProblem, nameHint(name));
598
841
  const mode = asString(raw.mode, "epd.yml.mode", "docker");
599
842
  if (mode !== "docker" && mode !== "process")
600
843
  fail("epd.yml.mode", `expected "docker" or "process", got ${JSON.stringify(mode)}`);
601
- 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");
602
845
  checkKeys(proxyRaw, [
603
846
  "enabled",
604
847
  "image",
@@ -628,23 +871,23 @@ function normalize(raw, configPath, root, destination) {
628
871
  ...ssl ? { websecure: 443 } : {}
629
872
  };
630
873
  for (const [k, v] of Object.entries(asDict(proxyRaw.entrypoints, "epd.yml.proxy.entrypoints"))) {
631
- entrypoints[k] = asNumber(v, `epd.yml.proxy.entrypoints.${k}`);
874
+ entrypoints[k] = asPort(v, `epd.yml.proxy.entrypoints.${k}`);
632
875
  }
633
876
  const proxy = {
634
877
  enabled: asBool(proxyRaw.enabled, "epd.yml.proxy.enabled", true),
635
- 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),
636
879
  version: proxyRaw.version ? asString(proxyRaw.version, "epd.yml.proxy.version") : undefined,
637
880
  network: asString(proxyRaw.network, "epd.yml.proxy.network", "epd"),
638
881
  ssl,
639
882
  email: proxyRaw.email ? asString(proxyRaw.email, "epd.yml.proxy.email") : undefined,
640
883
  challenge: asString(proxyRaw.challenge, "epd.yml.proxy.challenge", "http"),
641
884
  dnsProvider: proxyRaw.dns_provider ? asString(proxyRaw.dns_provider, "epd.yml.proxy.dns_provider") : undefined,
642
- 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),
643
886
  acmeServer: proxyRaw.acme_server ? asString(proxyRaw.acme_server, "epd.yml.proxy.acme_server") : undefined,
644
887
  entrypoints,
645
888
  httpsRedirect: asBool(proxyRaw.https_redirect, "epd.yml.proxy.https_redirect", ssl),
646
889
  dashboard: asBool(proxyRaw.dashboard, "epd.yml.proxy.dashboard", false),
647
- 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,
648
891
  logLevel: asString(proxyRaw.log_level, "epd.yml.proxy.log_level", "INFO"),
649
892
  accessLog: asBool(proxyRaw.access_log, "epd.yml.proxy.access_log", false),
650
893
  crossHost: asBool(proxyRaw.cross_host, "epd.yml.proxy.cross_host", false),
@@ -659,9 +902,9 @@ function normalize(raw, configPath, root, destination) {
659
902
  if (proxy.challenge === "dns" && !proxy.dnsProvider) {
660
903
  fail("epd.yml.proxy.dns_provider", 'is required when challenge is "dns"', "For example: dns_provider: cloudflare");
661
904
  }
662
- const globalEnv = raw.env;
663
- const envClear = asDict(globalEnv?.clear ?? (globalEnv && !("clear" in globalEnv) && !("secret" in globalEnv) ? globalEnv : {}), "epd.yml.env");
664
- 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;
665
908
  const defaultHealth = {
666
909
  path: "/",
667
910
  status: "200-399",
@@ -693,6 +936,8 @@ function normalize(raw, configPath, root, destination) {
693
936
  }
694
937
  const services = Object.entries(servicesRaw).map(([svcName, rawSvc]) => {
695
938
  const p = `epd.yml.servers.${svcName}`;
939
+ if (!isValidName(svcName))
940
+ fail(p, nameProblem, nameHint(svcName));
696
941
  let o;
697
942
  if (Array.isArray(rawSvc))
698
943
  o = { hosts: rawSvc };
@@ -745,27 +990,26 @@ function normalize(raw, configPath, root, destination) {
745
990
  ];
746
991
  if (!hosts.length && !svcHetzner)
747
992
  fail(`${p}.hosts`, "at least one host is required");
748
- const port = asNumber(o.port, `${p}.port`, asNumber(raw.port, "epd.yml.port", 3000));
749
- 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;
750
995
  const routes = [];
751
996
  for (const d of [...asList(o.domain, `${p}.domain`), ...asList(o.domains, `${p}.domains`)]) {
752
997
  routes.push(parseRoute(d, `${p}.domains`, { port, ssl: proxy.ssl }));
753
998
  }
754
999
  const rawRoutes = o.routes === undefined ? [] : Array.isArray(o.routes) ? o.routes : [o.routes];
755
1000
  rawRoutes.forEach((r, i) => routes.push(parseRoute(r, `${p}.routes[${i}]`, { port, ssl: proxy.ssl })));
756
- const svcEnvRaw = o.env;
757
- const svcEnv = asDict(svcEnvRaw?.clear ?? (svcEnvRaw && !("clear" in svcEnvRaw) && !("secret" in svcEnvRaw) ? svcEnvRaw : {}), `${p}.env`);
1001
+ const svcEnv = parseEnvBlock(o.env, `${p}.env`);
758
1002
  return {
759
1003
  name: svcName,
760
1004
  hosts,
761
1005
  hetzner: svcHetzner,
762
- replicas: asNumber(o.replicas, `${p}.replicas`, 1),
1006
+ replicas: asInt(o.replicas, `${p}.replicas`, 1, 1, 256),
763
1007
  port,
764
1008
  hostPort,
765
1009
  command: o.command === undefined ? undefined : asString(o.command, `${p}.command`),
766
1010
  routes,
767
- env: { ...envClear, ...svcEnv },
768
- secrets: [...envSecret, ...asList(svcEnvRaw?.secret, `${p}.env.secret`)],
1011
+ env: { ...envClear, ...svcEnv.clear },
1012
+ secrets: [...envSecret, ...svcEnv.secret],
769
1013
  volumes: [...asList(raw.volumes, "epd.yml.volumes"), ...asList(o.volumes, `${p}.volumes`)],
770
1014
  labels: { ...asDict(raw.labels, "epd.yml.labels"), ...asDict(o.labels, `${p}.labels`) },
771
1015
  health: parseHealth(o.healthcheck ?? o.health, `${p}.healthcheck`, { ...rootHealth, port: rootHealth.port ?? port }),
@@ -777,12 +1021,14 @@ function normalize(raw, configPath, root, destination) {
777
1021
  stopTimeout: asNumber(o.stop_timeout, `${p}.stop_timeout`, asNumber(raw.stop_timeout, "epd.yml.stop_timeout", 30))
778
1022
  };
779
1023
  });
780
- const accessories = Object.entries(raw.accessories ?? {}).map(([accName, rawAcc]) => {
1024
+ const accessories = Object.entries(asMap(raw.accessories, "epd.yml.accessories")).map(([accName, rawAcc]) => {
781
1025
  const p = `epd.yml.accessories.${accName}`;
782
- const o = rawAcc ?? {};
1026
+ if (!isValidName(accName))
1027
+ fail(p, nameProblem, nameHint(accName));
1028
+ const o = asMap(rawAcc, p);
783
1029
  checkKeys(o, ["image", "host", "env", "volumes", "ports", "command", "docker_options", "routes", "domain", "domains", "port"], p);
784
- const accPort = o.port !== undefined ? asNumber(o.port, `${p}.port`) : undefined;
785
- const accEnvRaw = o.env;
1030
+ const accPort = o.port !== undefined ? asPort(o.port, `${p}.port`) : undefined;
1031
+ const accEnv = parseEnvBlock(o.env, `${p}.env`);
786
1032
  const routes = [];
787
1033
  for (const d of [...asList(o.domain, `${p}.domain`), ...asList(o.domains, `${p}.domains`)]) {
788
1034
  routes.push(parseRoute(d, `${p}.domains`, { port: accPort ?? 80, ssl: proxy.ssl }));
@@ -791,10 +1037,10 @@ function normalize(raw, configPath, root, destination) {
791
1037
  rawRoutes.forEach((r, i) => routes.push(parseRoute(r, `${p}.routes[${i}]`, { port: accPort ?? 80, ssl: proxy.ssl })));
792
1038
  return {
793
1039
  name: accName,
794
- image: asString(o.image, `${p}.image`),
1040
+ image: check(asString(o.image, `${p}.image`), `${p}.image`, imageProblem, IMAGE_HINT),
795
1041
  host: takeHostUser(asString(o.host, `${p}.host`), `${p}.host`, hostUsers),
796
- env: asDict(accEnvRaw?.clear ?? (accEnvRaw && !("clear" in accEnvRaw) && !("secret" in accEnvRaw) ? accEnvRaw : {}), `${p}.env`),
797
- secrets: asList(accEnvRaw?.secret, `${p}.env.secret`),
1042
+ env: accEnv.clear,
1043
+ secrets: accEnv.secret,
798
1044
  volumes: asList(o.volumes, `${p}.volumes`),
799
1045
  ports: asList(o.ports, `${p}.ports`),
800
1046
  command: o.command === undefined ? undefined : asString(o.command, `${p}.command`),
@@ -803,24 +1049,30 @@ function normalize(raw, configPath, root, destination) {
803
1049
  port: accPort
804
1050
  };
805
1051
  });
806
- const regRaw = raw.registry;
1052
+ const regRaw = raw.registry ? asMap(raw.registry, "epd.yml.registry") : undefined;
807
1053
  let registry;
808
1054
  if (regRaw) {
809
1055
  checkKeys(regRaw, ["server", "username", "password"], "epd.yml.registry");
810
1056
  const pw = regRaw.password;
811
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
+ }
812
1064
  registry = {
813
1065
  server: regRaw.server ? asString(regRaw.server, "epd.yml.registry.server") : undefined,
814
1066
  username: asString(regRaw.username, "epd.yml.registry.username"),
815
1067
  passwordEnv
816
1068
  };
817
1069
  }
818
- const image = asString(raw.image, "epd.yml.image", registry ? `${registry.server ? registry.server + "/" : ""}${registry.username}/${name}` : name).toLowerCase();
819
- 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");
820
1072
  checkKeys(buildRaw, ["dockerfile", "context", "platform", "target", "args", "secrets", "cache", "remote"], "epd.yml.build");
821
- const sshRaw = raw.ssh ?? {};
1073
+ const sshRaw = asMap(raw.ssh, "epd.yml.ssh");
822
1074
  checkKeys(sshRaw, ["user", "port", "key", "options", "proxy_jump", "control_persist", "sudo_password"], "epd.yml.ssh");
823
- const procRaw = raw.process ?? {};
1075
+ const procRaw = asMap(raw.process, "epd.yml.process");
824
1076
  checkKeys(procRaw, ["exclude", "install", "build", "start", "path", "path_prepend", "source"], "epd.yml.process");
825
1077
  const processCfg = {
826
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"],
@@ -831,12 +1083,15 @@ function normalize(raw, configPath, root, destination) {
831
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"],
832
1084
  source: asString(procRaw.source, "epd.yml.process.source", "rsync")
833
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
+ }
834
1089
  if (mode === "process" && !processCfg.start) {
835
1090
  fail("epd.yml.process.start", "is required in process mode", `For example:
836
1091
  process:
837
1092
  start: bun run start`);
838
1093
  }
839
- const hooksRaw = raw.hooks ?? {};
1094
+ const hooksRaw = asMap(raw.hooks, "epd.yml.hooks");
840
1095
  checkKeys(hooksRaw, ["pre_build", "pre_deploy", "post_deploy", "on_failure"], "epd.yml.hooks");
841
1096
  const strategy = asString(raw.strategy, "epd.yml.strategy", "rolling");
842
1097
  if (strategy !== "rolling" && strategy !== "parallel")
@@ -856,7 +1111,7 @@ function normalize(raw, configPath, root, destination) {
856
1111
  proxied: asBool(cfRaw.proxied, "epd.yml.cloudflare.proxied", true),
857
1112
  ttl: asNumber(cfRaw.ttl, "epd.yml.cloudflare.ttl", 1),
858
1113
  autoSync: asBool(cfRaw.auto_sync, "epd.yml.cloudflare.auto_sync", true),
859
- 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
860
1115
  };
861
1116
  }
862
1117
  let dnsConfig = undefined;
@@ -880,7 +1135,7 @@ function normalize(raw, configPath, root, destination) {
880
1135
  proxied: asBool(dRaw.proxied, "epd.yml.dns.proxied", provider === "cloudflare"),
881
1136
  ttl: asNumber(dRaw.ttl, "epd.yml.dns.ttl", provider === "hetzner" ? 300 : 1),
882
1137
  autoSync: asBool(dRaw.auto_sync, "epd.yml.dns.auto_sync", true),
883
- 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
884
1139
  };
885
1140
  } else if (cloudflare) {
886
1141
  dnsConfig = {
@@ -924,15 +1179,15 @@ function normalize(raw, configPath, root, destination) {
924
1179
  context: asString(buildRaw.context, "epd.yml.build.context", "."),
925
1180
  platform: asString(buildRaw.platform, "epd.yml.build.platform", "linux/amd64"),
926
1181
  target: buildRaw.target ? asString(buildRaw.target, "epd.yml.build.target") : undefined,
927
- args: asDict(buildRaw.args, "epd.yml.build.args"),
928
- 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")),
929
1184
  cache: asBool(buildRaw.cache, "epd.yml.build.cache", true),
930
1185
  remote: asBool(buildRaw.remote, "epd.yml.build.remote", false)
931
1186
  },
932
1187
  ssh: {
933
- 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),
934
1189
  hostUsers,
935
- port: asNumber(sshRaw.port, "epd.yml.ssh.port", 22),
1190
+ port: asPort(sshRaw.port, "epd.yml.ssh.port", 22),
936
1191
  key: sshRaw.key ? expandHome(asString(sshRaw.key, "epd.yml.ssh.key")) : undefined,
937
1192
  options: asList(sshRaw.options, "epd.yml.ssh.options"),
938
1193
  proxyJump: sshRaw.proxy_jump ? asString(sshRaw.proxy_jump, "epd.yml.ssh.proxy_jump") : undefined,
@@ -955,10 +1210,10 @@ function normalize(raw, configPath, root, destination) {
955
1210
  dns: dnsConfig,
956
1211
  cloudflare,
957
1212
  hetzner: hetznerConfig,
958
- 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),
959
1214
  strategy,
960
- keepReleases: asNumber(raw.keep_releases, "epd.yml.keep_releases", 5),
961
- 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".')
962
1217
  };
963
1218
  validateCrossReferences(cfg);
964
1219
  return cfg;
@@ -987,6 +1242,13 @@ function validateCrossReferences(cfg) {
987
1242
  }
988
1243
  }
989
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
+ }
990
1252
  if (cfg.mode === "process" || cfg.proxy.crossHost) {
991
1253
  for (const svc of cfg.services) {
992
1254
  for (const route of svc.routes) {
@@ -999,11 +1261,20 @@ function validateCrossReferences(cfg) {
999
1261
  }
1000
1262
  if (cfg.mode === "docker" && !cfg.registry && cfg.services.some((s) => s.hosts.length > 1)) {}
1001
1263
  }
1002
- 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;
1003
1265
  var init_load = __esm(() => {
1004
1266
  init_log();
1005
1267
  init_misc();
1268
+ init_names();
1006
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_]*$/;
1007
1278
  TOP_LEVEL_KEYS = [
1008
1279
  "name",
1009
1280
  "mode",
@@ -1044,6 +1315,8 @@ var init_load = __esm(() => {
1044
1315
  });
1045
1316
 
1046
1317
  // src/util/proc.ts
1318
+ import { existsSync as existsSync2 } from "fs";
1319
+ import { dirname as dirname2, join as join2 } from "path";
1047
1320
  async function run(cmd, opts = {}) {
1048
1321
  const label = opts.label ?? cmd.join(" ");
1049
1322
  log.debug(`local: ${cmd.join(" ")}`);
@@ -1082,18 +1355,39 @@ async function teeStderr(stream) {
1082
1355
  reader.releaseLock();
1083
1356
  }
1084
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
+ }
1085
1380
  async function runShell(script, opts = {}) {
1086
- return run(["/bin/sh", "-c", script], { ...opts, label: opts.label ?? script });
1381
+ return run([localShell(), "-c", script], { ...opts, label: opts.label ?? script });
1087
1382
  }
1088
1383
  async function which(bin) {
1089
- const r = await run(["/bin/sh", "-c", `command -v ${bin}`], { allowFailure: true });
1090
- return r.code === 0 && r.stdout ? r.stdout.split(`
1091
- `)[0].trim() : null;
1384
+ return Bun.which(bin);
1092
1385
  }
1093
1386
  async function requireLocal(bin, hint) {
1094
1387
  if (!await which(bin))
1095
1388
  throw new EpdError(`\`${bin}\` was not found on this machine`, hint);
1096
1389
  }
1390
+ var windowsBash;
1097
1391
  var init_proc = __esm(() => {
1098
1392
  init_log();
1099
1393
  });
@@ -1123,11 +1417,11 @@ function proxyHosts(cfg) {
1123
1417
  }
1124
1418
 
1125
1419
  // src/commands/action.ts
1126
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
1127
- 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";
1128
1422
  function detectGitBranch(root) {
1129
1423
  try {
1130
- const head = readFileSync2(join2(root, ".git", "HEAD"), "utf8").trim();
1424
+ const head = readFileSync2(join3(root, ".git", "HEAD"), "utf8").trim();
1131
1425
  if (head.startsWith("ref: refs/heads/")) {
1132
1426
  return head.replace("ref: refs/heads/", "");
1133
1427
  }
@@ -1345,9 +1639,9 @@ Aliases
1345
1639
  event = "push";
1346
1640
  }
1347
1641
  const destination = ctx.loadOptions.destination;
1348
- 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");
1349
1643
  const targetFile = ctx.values.file || defaultFile;
1350
- if (existsSync2(targetFile) && !ctx.values.force) {
1644
+ if (existsSync3(targetFile) && !ctx.values.force) {
1351
1645
  const ok = interactive() && await confirm(`${targetFile} already exists. Overwrite?`, false);
1352
1646
  if (!ok) {
1353
1647
  log.info(`Aborted. Use ${c.cyan("--force")} to overwrite.`);
@@ -1361,7 +1655,7 @@ Aliases
1361
1655
  destination,
1362
1656
  cfg
1363
1657
  });
1364
- mkdirSync(dirname2(targetFile), { recursive: true });
1658
+ mkdirSync(dirname3(targetFile), { recursive: true });
1365
1659
  writeFileSync(targetFile, yaml);
1366
1660
  log.ok(`wrote ${c.bold(targetFile)}`);
1367
1661
  console.log(`
@@ -1393,10 +1687,111 @@ Next steps:`);
1393
1687
  };
1394
1688
  });
1395
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
+
1396
1791
  // src/util/auth.ts
1397
- 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";
1398
1793
  import { homedir as homedir2 } from "os";
1399
- import { join as join3 } from "path";
1794
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join4 } from "path";
1400
1795
  import { spawn } from "child_process";
1401
1796
  function openBrowser(url) {
1402
1797
  try {
@@ -1415,38 +1810,80 @@ function openBrowser(url) {
1415
1810
  return false;
1416
1811
  }
1417
1812
  }
1813
+ function userHome() {
1814
+ return process.env.HOME || homedir2();
1815
+ }
1418
1816
  function getGlobalAuthPath() {
1419
- const xdgDir = join3(homedir2(), ".config", "epd");
1420
- const fallbackDir = join3(homedir2(), ".epd");
1421
- if (existsSync3(join3(xdgDir, "auth.json")))
1422
- return join3(xdgDir, "auth.json");
1423
- if (existsSync3(join3(fallbackDir, "auth.json")))
1424
- return join3(fallbackDir, "auth.json");
1425
- 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.");
1426
1827
  }
1427
1828
  function getGlobalAuth() {
1428
1829
  const path = getGlobalAuthPath();
1429
- if (!existsSync3(path))
1830
+ if (!existsSync4(path))
1430
1831
  return {};
1832
+ let raw;
1431
1833
  try {
1432
- return JSON.parse(readFileSync3(path, "utf8"));
1834
+ raw = readFileSync3(path, "utf8");
1835
+ } catch (err) {
1836
+ throw new EpdError(`cannot read ${path}`, err?.message);
1837
+ }
1838
+ let parsed;
1839
+ try {
1840
+ parsed = JSON.parse(raw);
1433
1841
  } catch {
1434
- return {};
1842
+ throw corruptAuthError(path);
1843
+ }
1844
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1845
+ throw corruptAuthError(path);
1846
+ return parsed;
1847
+ }
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;
1435
1866
  }
1436
1867
  }
1437
1868
  function saveGlobalAuth(updater) {
1438
- const dir = join3(homedir2(), ".config", "epd");
1439
- if (!existsSync3(dir)) {
1440
- mkdirSync2(dir, { recursive: true, mode: 448 });
1441
- }
1442
- const file = join3(dir, "auth.json");
1869
+ const dir = join4(userHome(), ".config", "epd");
1870
+ ensurePrivateDir(dir);
1443
1871
  const current = getGlobalAuth();
1444
1872
  const next = updater(current);
1445
- writeFileSync2(file, JSON.stringify(next, null, 2) + `
1446
- `, { 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");
1447
1882
  try {
1448
- chmodSync(file, 384);
1449
- } catch {}
1883
+ rmSync(legacy, { force: true });
1884
+ } catch (err) {
1885
+ throw new EpdError(`could not remove the old credential file ${legacy}`, err?.message);
1886
+ }
1450
1887
  }
1451
1888
  function isLinkDeclined(provider, root = process.cwd()) {
1452
1889
  return (getGlobalAuth().declined?.[provider] ?? []).includes(root);
@@ -1467,14 +1904,28 @@ function clearLinkDecline(provider, root = process.cwd()) {
1467
1904
  declined: { ...auth.declined, [provider]: (auth.declined?.[provider] ?? []).filter((r) => r !== root) }
1468
1905
  }));
1469
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
+ }
1470
1919
  function saveProjectEnv(entries, root = process.cwd()) {
1471
- const envPath = join3(root, ".env");
1472
- 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") : "";
1473
1923
  for (const [key, val] of Object.entries(entries)) {
1924
+ registerSecret(val);
1474
1925
  const regex = new RegExp(`^${key}=.*$`, "m");
1475
1926
  const line = `${key}=${val}`;
1476
1927
  if (regex.test(content)) {
1477
- content = content.replace(regex, line);
1928
+ content = content.replace(regex, () => line);
1478
1929
  } else {
1479
1930
  if (content.length && !content.endsWith(`
1480
1931
  `))
@@ -1484,33 +1935,37 @@ function saveProjectEnv(entries, root = process.cwd()) {
1484
1935
  `;
1485
1936
  }
1486
1937
  }
1487
- 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;
1488
1943
  }
1489
1944
  function getCloudflareToken(root = process.cwd()) {
1490
1945
  if (process.env.CLOUDFLARE_API_TOKEN)
1491
- return process.env.CLOUDFLARE_API_TOKEN;
1946
+ return secret(process.env.CLOUDFLARE_API_TOKEN);
1492
1947
  if (process.env.CF_DNS_API_TOKEN)
1493
- return process.env.CF_DNS_API_TOKEN;
1494
- const envPath = join3(root, ".env");
1495
- if (existsSync3(envPath)) {
1948
+ return secret(process.env.CF_DNS_API_TOKEN);
1949
+ const envPath = join4(root, ".env");
1950
+ if (existsSync4(envPath)) {
1496
1951
  try {
1497
1952
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1498
1953
  if (parsed.CLOUDFLARE_API_TOKEN)
1499
- return parsed.CLOUDFLARE_API_TOKEN;
1954
+ return secret(parsed.CLOUDFLARE_API_TOKEN);
1500
1955
  if (parsed.CF_DNS_API_TOKEN)
1501
- return parsed.CF_DNS_API_TOKEN;
1956
+ return secret(parsed.CF_DNS_API_TOKEN);
1502
1957
  } catch {}
1503
1958
  }
1504
1959
  const global = getGlobalAuth();
1505
- return global.cloudflare?.apiToken;
1960
+ return secret(global.cloudflare?.apiToken);
1506
1961
  }
1507
1962
  function getCloudflareTokenSource(root = process.cwd()) {
1508
1963
  if (process.env.CLOUDFLARE_API_TOKEN)
1509
1964
  return "environment variable (CLOUDFLARE_API_TOKEN)";
1510
1965
  if (process.env.CF_DNS_API_TOKEN)
1511
1966
  return "environment variable (CF_DNS_API_TOKEN)";
1512
- const envPath = join3(root, ".env");
1513
- if (existsSync3(envPath)) {
1967
+ const envPath = join4(root, ".env");
1968
+ if (existsSync4(envPath)) {
1514
1969
  try {
1515
1970
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1516
1971
  if (parsed.CLOUDFLARE_API_TOKEN || parsed.CF_DNS_API_TOKEN)
@@ -1524,29 +1979,29 @@ function getCloudflareTokenSource(root = process.cwd()) {
1524
1979
  }
1525
1980
  function getHetznerToken(root = process.cwd()) {
1526
1981
  if (process.env.HETZNER_API_TOKEN)
1527
- return process.env.HETZNER_API_TOKEN;
1982
+ return secret(process.env.HETZNER_API_TOKEN);
1528
1983
  if (process.env.HCLOUD_TOKEN)
1529
- return process.env.HCLOUD_TOKEN;
1530
- const envPath = join3(root, ".env");
1531
- if (existsSync3(envPath)) {
1984
+ return secret(process.env.HCLOUD_TOKEN);
1985
+ const envPath = join4(root, ".env");
1986
+ if (existsSync4(envPath)) {
1532
1987
  try {
1533
1988
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1534
1989
  if (parsed.HETZNER_API_TOKEN)
1535
- return parsed.HETZNER_API_TOKEN;
1990
+ return secret(parsed.HETZNER_API_TOKEN);
1536
1991
  if (parsed.HCLOUD_TOKEN)
1537
- return parsed.HCLOUD_TOKEN;
1992
+ return secret(parsed.HCLOUD_TOKEN);
1538
1993
  } catch {}
1539
1994
  }
1540
1995
  const global = getGlobalAuth();
1541
- return global.hetzner?.apiToken;
1996
+ return secret(global.hetzner?.apiToken);
1542
1997
  }
1543
1998
  function getHetznerTokenSource(root = process.cwd()) {
1544
1999
  if (process.env.HETZNER_API_TOKEN)
1545
2000
  return "environment variable (HETZNER_API_TOKEN)";
1546
2001
  if (process.env.HCLOUD_TOKEN)
1547
2002
  return "environment variable (HCLOUD_TOKEN)";
1548
- const envPath = join3(root, ".env");
1549
- if (existsSync3(envPath)) {
2003
+ const envPath = join4(root, ".env");
2004
+ if (existsSync4(envPath)) {
1550
2005
  try {
1551
2006
  const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1552
2007
  if (parsed.HETZNER_API_TOKEN || parsed.HCLOUD_TOKEN)
@@ -1560,38 +2015,28 @@ function getHetznerTokenSource(root = process.cwd()) {
1560
2015
  }
1561
2016
  async function verifyCloudflareToken(token) {
1562
2017
  try {
1563
- const res = await fetch("https://api.cloudflare.com/client/v4/user/tokens/verify", {
1564
- headers: {
1565
- Authorization: `Bearer ${token}`,
1566
- "Content-Type": "application/json"
1567
- }
1568
- });
1569
- const data = await res.json();
1570
- 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") {
1571
2021
  return { valid: true, status: data.result.status };
1572
2022
  }
1573
- const err = data.errors?.[0]?.message || `HTTP ${res.status}`;
1574
- return { valid: false, error: err };
2023
+ const err = firstString(data?.errors?.[0]?.message) || statusLabel(res);
2024
+ return { valid: false, error: redactSecret(err, token) };
1575
2025
  } catch (err) {
1576
- return { valid: false, error: err.message };
2026
+ return { valid: false, error: redactSecret(err?.message ?? "network error", token) };
1577
2027
  }
1578
2028
  }
1579
2029
  async function verifyHetznerToken(token) {
1580
2030
  try {
1581
- const res = await fetch("https://api.hetzner.cloud/v1/servers", {
1582
- headers: {
1583
- Authorization: `Bearer ${token}`,
1584
- "Content-Type": "application/json"
1585
- }
1586
- });
1587
- const data = await res.json();
1588
- 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)) {
1589
2034
  return { valid: true };
1590
2035
  }
1591
- const err = data.error?.message || `HTTP ${res.status}`;
1592
- return { valid: false, error: err };
2036
+ const err = firstString(data?.error?.message) || statusLabel(res);
2037
+ return { valid: false, error: redactSecret(err, token) };
1593
2038
  } catch (err) {
1594
- return { valid: false, error: err.message };
2039
+ return { valid: false, error: redactSecret(err?.message ?? "network error", token) };
1595
2040
  }
1596
2041
  }
1597
2042
  async function linkCloudflareInteractive(root = process.cwd()) {
@@ -1613,6 +2058,7 @@ ${c.bold("Linking Cloudflare to EPD")}`);
1613
2058
  `));
1614
2059
  for (;; ) {
1615
2060
  const token = await askSecret("Paste Cloudflare API Token (or press Enter to skip):");
2061
+ registerSecret(token);
1616
2062
  if (!token) {
1617
2063
  log.info("Cloudflare linking skipped.");
1618
2064
  return null;
@@ -1665,6 +2111,7 @@ ${c.bold("Linking Hetzner Cloud to EPD")}`);
1665
2111
  `));
1666
2112
  for (;; ) {
1667
2113
  const token = await askSecret("Paste Hetzner Cloud API Token (or press Enter to skip):");
2114
+ registerSecret(token);
1668
2115
  if (!token) {
1669
2116
  log.info("Hetzner linking skipped.");
1670
2117
  return null;
@@ -1701,6 +2148,7 @@ var init_auth = __esm(() => {
1701
2148
  init_log();
1702
2149
  init_prompt();
1703
2150
  init_load();
2151
+ init_http();
1704
2152
  });
1705
2153
 
1706
2154
  // src/hetzner/api.ts
@@ -1718,16 +2166,14 @@ class HetznerCloudClient {
1718
2166
  "Content-Type": "application/json",
1719
2167
  ...options.headers
1720
2168
  };
1721
- const res = await fetch(url, { ...options, headers });
1722
- let data;
1723
- try {
1724
- data = await res.json();
1725
- } catch {
1726
- data = null;
1727
- }
2169
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
2170
+ const { data, isJson, empty } = await readJsonBody(res);
1728
2171
  if (!res.ok) {
1729
- const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
1730
- 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.");
1731
2177
  }
1732
2178
  return data;
1733
2179
  }
@@ -1788,15 +2234,15 @@ class HetznerCloudClient {
1788
2234
  params.set("per_page", "50");
1789
2235
  const query = params.toString() ? `?${params.toString()}` : "";
1790
2236
  const res = await this.request(`/servers${query}`);
1791
- return (res.servers ?? []).map((s) => this.mapServer(s));
2237
+ return (res?.servers ?? []).map((s) => this.mapServer(s));
1792
2238
  }
1793
2239
  async getServer(idOrName) {
1794
2240
  if (typeof idOrName === "number" || /^\d+$/.test(String(idOrName))) {
1795
2241
  try {
1796
2242
  const res = await this.request(`/servers/${idOrName}`);
1797
- return this.mapServer(res.server);
2243
+ return res?.server ? this.mapServer(res.server) : null;
1798
2244
  } catch (e) {
1799
- if (e instanceof EpdError && e.message.includes("404"))
2245
+ if (e instanceof HttpApiError && e.status === 404)
1800
2246
  return null;
1801
2247
  throw e;
1802
2248
  }
@@ -1825,10 +2271,12 @@ class HetznerCloudClient {
1825
2271
  method: "POST",
1826
2272
  body: JSON.stringify(body)
1827
2273
  });
2274
+ if (!res?.server)
2275
+ throw new EpdError("Hetzner Cloud API returned no server", "Try again later.");
1828
2276
  return {
1829
2277
  server: this.mapServer(res.server),
1830
- action: res.action,
1831
- rootPassword: res.root_password
2278
+ action: res?.action,
2279
+ rootPassword: res?.root_password
1832
2280
  };
1833
2281
  }
1834
2282
  async deleteServer(id) {
@@ -1838,7 +2286,7 @@ class HetznerCloudClient {
1838
2286
  }
1839
2287
  async listServerTypes() {
1840
2288
  const res = await this.request("/server_types");
1841
- return (res.server_types ?? []).map((st) => ({
2289
+ return (res?.server_types ?? []).map((st) => ({
1842
2290
  id: st.id,
1843
2291
  name: st.name,
1844
2292
  description: st.description,
@@ -1856,7 +2304,7 @@ class HetznerCloudClient {
1856
2304
  }
1857
2305
  async listLocations() {
1858
2306
  const res = await this.request("/locations");
1859
- return (res.locations ?? []).map((l) => ({
2307
+ return (res?.locations ?? []).map((l) => ({
1860
2308
  id: l.id,
1861
2309
  name: l.name,
1862
2310
  description: l.description,
@@ -1867,7 +2315,7 @@ class HetznerCloudClient {
1867
2315
  }
1868
2316
  async listSshKeys() {
1869
2317
  const res = await this.request("/ssh_keys");
1870
- return (res.ssh_keys ?? []).map((k) => ({
2318
+ return (res?.ssh_keys ?? []).map((k) => ({
1871
2319
  id: k.id,
1872
2320
  name: k.name,
1873
2321
  fingerprint: k.fingerprint,
@@ -1876,7 +2324,7 @@ class HetznerCloudClient {
1876
2324
  }
1877
2325
  async getAction(id) {
1878
2326
  const res = await this.request(`/actions/${id}`);
1879
- return res.action;
2327
+ return res?.action;
1880
2328
  }
1881
2329
  async waitForAction(actionId, timeoutMs = 120000) {
1882
2330
  const deadline = Date.now() + timeoutMs;
@@ -1906,6 +2354,7 @@ class HetznerCloudClient {
1906
2354
  var init_api = __esm(() => {
1907
2355
  init_log();
1908
2356
  init_misc();
2357
+ init_http();
1909
2358
  });
1910
2359
 
1911
2360
  // src/dns/cloudflare.ts
@@ -1924,17 +2373,20 @@ class CloudflareClient {
1924
2373
  "Content-Type": "application/json",
1925
2374
  ...options.headers
1926
2375
  };
1927
- const res = await fetch(url, { ...options, headers });
1928
- const data = await res.json();
1929
- if (!res.ok || data.success === false) {
1930
- const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
1931
- 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);
1932
2381
  }
1933
- 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;
1934
2386
  }
1935
2387
  async listZones(name) {
1936
2388
  const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
1937
- return this.request(`/zones${query}`);
2389
+ return await this.request(`/zones${query}`) ?? [];
1938
2390
  }
1939
2391
  async findZoneForDomain(domain, explicitZoneId) {
1940
2392
  if (explicitZoneId) {
@@ -1959,7 +2411,7 @@ class CloudflareClient {
1959
2411
  if (type)
1960
2412
  params.set("type", type);
1961
2413
  const raw = await this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
1962
- return raw.map((r) => ({
2414
+ return (raw ?? []).map((r) => ({
1963
2415
  id: String(r.id),
1964
2416
  zoneId: String(r.zone_id ?? zoneId),
1965
2417
  name: r.name,
@@ -1981,10 +2433,12 @@ class CloudflareClient {
1981
2433
  comment: record.comment
1982
2434
  })
1983
2435
  });
2436
+ if (!res?.id)
2437
+ throw new Error("Cloudflare API returned no DNS record");
1984
2438
  return {
1985
2439
  id: String(res.id),
1986
- zoneId: String(res.zone_id ?? zoneId),
1987
- name: res.name,
2440
+ zoneId: String(res?.zone_id ?? zoneId),
2441
+ name: res?.name,
1988
2442
  type: res.type,
1989
2443
  content: res.content,
1990
2444
  proxied: Boolean(res.proxied),
@@ -2003,10 +2457,12 @@ class CloudflareClient {
2003
2457
  comment: record.comment
2004
2458
  })
2005
2459
  });
2460
+ if (!res?.id)
2461
+ throw new Error("Cloudflare API returned no DNS record");
2006
2462
  return {
2007
2463
  id: String(res.id),
2008
- zoneId: String(res.zone_id ?? zoneId),
2009
- name: res.name,
2464
+ zoneId: String(res?.zone_id ?? zoneId),
2465
+ name: res?.name,
2010
2466
  type: res.type,
2011
2467
  content: res.content,
2012
2468
  proxied: Boolean(res.proxied),
@@ -2021,21 +2477,22 @@ class CloudflareClient {
2021
2477
  }
2022
2478
  var init_cloudflare = __esm(() => {
2023
2479
  init_log();
2480
+ init_http();
2024
2481
  });
2025
2482
 
2026
2483
  // src/commands/init.ts
2027
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
2028
- 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";
2029
2486
  function detect(root) {
2030
2487
  const name = basename(root).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
2031
- const hasDockerfile = existsSync4(join4(root, "Dockerfile"));
2032
- const pkgPath = join4(root, "package.json");
2033
- if (existsSync4(pkgPath)) {
2488
+ const hasDockerfile = existsSync5(join5(root, "Dockerfile"));
2489
+ const pkgPath = join5(root, "package.json");
2490
+ if (existsSync5(pkgPath)) {
2034
2491
  let pkg = {};
2035
2492
  try {
2036
2493
  pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
2037
2494
  } catch {}
2038
- 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"));
2039
2496
  const scripts = pkg.scripts ?? {};
2040
2497
  const runner = bun ? "bun" : "npm";
2041
2498
  return {
@@ -2048,13 +2505,13 @@ function detect(root) {
2048
2505
  hasDockerfile
2049
2506
  };
2050
2507
  }
2051
- if (existsSync4(join4(root, "pyproject.toml")) || existsSync4(join4(root, "requirements.txt"))) {
2508
+ if (existsSync5(join5(root, "pyproject.toml")) || existsSync5(join5(root, "requirements.txt"))) {
2052
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 };
2053
2510
  }
2054
- if (existsSync4(join4(root, "Gemfile"))) {
2511
+ if (existsSync5(join5(root, "Gemfile"))) {
2055
2512
  return { name, runtime: "ruby", port: 3000, install: "bundle install --deployment", start: "bundle exec rails server -p $PORT", hasDockerfile };
2056
2513
  }
2057
- if (existsSync4(join4(root, "go.mod"))) {
2514
+ if (existsSync5(join5(root, "go.mod"))) {
2058
2515
  return { name, runtime: "go", port: 8080, build: "go build -o server .", start: "./server", hasDockerfile };
2059
2516
  }
2060
2517
  return { name, runtime: "unknown", port: 3000, hasDockerfile };
@@ -2284,8 +2741,8 @@ Options
2284
2741
  --force Overwrite an existing epd.yml`,
2285
2742
  async run(ctx) {
2286
2743
  const root = process.cwd();
2287
- const target = join4(root, "epd.yml");
2288
- if (existsSync4(target) && !ctx.values.force) {
2744
+ const target = join5(root, "epd.yml");
2745
+ if (existsSync5(target) && !ctx.values.force) {
2289
2746
  throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
2290
2747
  }
2291
2748
  const detected = detect(root);
@@ -2413,7 +2870,7 @@ Options
2413
2870
  if (wantDockerfile) {
2414
2871
  const df = DOCKERFILES[detected.runtime];
2415
2872
  if (df) {
2416
- writeFileSync3(join4(root, "Dockerfile"), df);
2873
+ writeFileSync3(join5(root, "Dockerfile"), df);
2417
2874
  log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
2418
2875
  } else {
2419
2876
  log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
@@ -2421,10 +2878,10 @@ Options
2421
2878
  }
2422
2879
  const wantCi = Boolean(ctx.values.ci) || interactive() && await confirm("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
2423
2880
  if (wantCi) {
2424
- const workflowDir = join4(root, ".github", "workflows");
2881
+ const workflowDir = join5(root, ".github", "workflows");
2425
2882
  mkdirSync3(workflowDir, { recursive: true });
2426
2883
  const { yaml } = buildWorkflowYaml({ root });
2427
- writeFileSync3(join4(workflowDir, "deploy.yml"), yaml);
2884
+ writeFileSync3(join5(workflowDir, "deploy.yml"), yaml);
2428
2885
  log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
2429
2886
  }
2430
2887
  console.log(`
@@ -2437,104 +2894,6 @@ Next steps:`);
2437
2894
  };
2438
2895
  });
2439
2896
 
2440
- // src/core/names.ts
2441
- function paths(cfg) {
2442
- const root = cfg.remoteRoot;
2443
- const app = `${root}/apps/${cfg.name}`;
2444
- return {
2445
- root,
2446
- app,
2447
- envFile: `${app}/env`,
2448
- state: `${app}/state.json`,
2449
- lock: `${app}/lock`,
2450
- releases: `${app}/releases`,
2451
- current: `${app}/current`,
2452
- shared: `${app}/shared`,
2453
- proxyDir: `${root}/proxy`,
2454
- proxyStatic: `${root}/proxy/traefik.yml`,
2455
- proxyDynamicDir: `${root}/proxy/dynamic`,
2456
- proxyAppsDir: `${root}/proxy/apps`,
2457
- proxyApp: `${root}/proxy/apps/${cfg.name}.json`,
2458
- proxyEnv: `${root}/proxy/env`,
2459
- proxyDynamic: `${root}/proxy/dynamic/${cfg.name}.yml`,
2460
- acmeDir: `${root}/proxy/acme`,
2461
- portsDir: `${root}/ports`,
2462
- proxyBin: `${root}/proxy/bin/traefik`,
2463
- proxyEcosystem: `${root}/proxy/pm2.json`,
2464
- proxyLogDir: `${root}/proxy/log`
2465
- };
2466
- }
2467
- function serviceIndex(cfg, svc) {
2468
- const names = cfg.services.map((s) => s.name).sort();
2469
- const idx = names.indexOf(svc.name);
2470
- if (idx >= MAX_SERVICES) {
2471
- throw new EpdError(`too many servers: epd reserves ports for ${MAX_SERVICES} per app`, "Split the extra ones into their own epd.yml.");
2472
- }
2473
- return idx;
2474
- }
2475
- function hostPort(cfg, svc, slot, replica) {
2476
- if (replica >= MAX_REPLICAS) {
2477
- throw new EpdError(`${svc.name}: at most ${MAX_REPLICAS} replicas per server are supported`, "Add more servers instead, or run several epd apps.");
2478
- }
2479
- const s = SLOTS.indexOf(slot);
2480
- if (svc.hostPort !== undefined) {
2481
- return svc.hostPort + s * MAX_REPLICAS + replica;
2482
- }
2483
- const j = serviceIndex(cfg, svc);
2484
- return cfg.portBase + j * PORTS_PER_SERVICE + s * MAX_REPLICAS + replica;
2485
- }
2486
- function portBlock(cfg) {
2487
- return { from: cfg.portBase, to: cfg.portBase + MAX_SERVICES * PORTS_PER_SERVICE - 1 };
2488
- }
2489
- function usesHostPorts(cfg) {
2490
- return cfg.mode === "process" || cfg.proxy.crossHost || !cfg.proxy.enabled;
2491
- }
2492
- function privateAddress(cfg, host) {
2493
- return cfg.proxy.privateIps[host] ?? host;
2494
- }
2495
- function bindAddress(cfg, host) {
2496
- return cfg.proxy.privateIps[host] ?? (cfg.proxy.enabled ? "0.0.0.0" : "127.0.0.1");
2497
- }
2498
- function endpointsFor(cfg, svc, slot, serverHost, containerIp) {
2499
- const out = [];
2500
- for (let i = 0;i < svc.replicas; i++) {
2501
- if (cfg.mode === "process") {
2502
- const port = hostPort(cfg, svc, slot, i);
2503
- out.push({
2504
- url: `http://127.0.0.1:${port}`,
2505
- probeHost: "127.0.0.1",
2506
- probePort: port,
2507
- id: processName(cfg.name, svc.name, slot, i),
2508
- replica: i
2509
- });
2510
- } else if (cfg.proxy.crossHost) {
2511
- const port = hostPort(cfg, svc, slot, i);
2512
- out.push({
2513
- url: `http://${privateAddress(cfg, serverHost)}:${port}`,
2514
- probeHost: "127.0.0.1",
2515
- probePort: port,
2516
- id: containerName(cfg.name, svc.name, slot, i),
2517
- replica: i
2518
- });
2519
- } else {
2520
- const id = containerName(cfg.name, svc.name, slot, i);
2521
- out.push({
2522
- url: `http://${id}:${svc.port}`,
2523
- probeHost: containerIp?.(id) ?? id,
2524
- probePort: svc.port,
2525
- id,
2526
- replica: i
2527
- });
2528
- }
2529
- }
2530
- return out;
2531
- }
2532
- 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";
2533
- var init_names = __esm(() => {
2534
- init_log();
2535
- SLOTS = ["blue", "green"];
2536
- });
2537
-
2538
2897
  // src/core/bootstrap.ts
2539
2898
  async function ensureDirs(host, cfg) {
2540
2899
  const p = paths(cfg);
@@ -2566,14 +2925,16 @@ async function installDocker(host) {
2566
2925
  systemctl enable --now docker 2>/dev/null || true
2567
2926
  else
2568
2927
  export DEBIAN_FRONTEND=noninteractive
2928
+ script=$(mktemp)
2929
+ trap 'rm -f "$script"' EXIT
2569
2930
  if command -v curl >/dev/null 2>&1; then
2570
- curl -fsSL https://get.docker.com -o /tmp/epd-get-docker.sh
2931
+ curl -fsSL https://get.docker.com -o "$script"
2571
2932
  else
2572
2933
  (apt-get update -qq && apt-get install -y -qq curl) >/dev/null 2>&1 || true
2573
- curl -fsSL https://get.docker.com -o /tmp/epd-get-docker.sh
2934
+ curl -fsSL https://get.docker.com -o "$script"
2574
2935
  fi
2575
- sh /tmp/epd-get-docker.sh
2576
- rm -f /tmp/epd-get-docker.sh
2936
+ sh "$script"
2937
+ rm -f "$script"
2577
2938
  systemctl enable --now docker 2>/dev/null || true
2578
2939
  fi
2579
2940
  docker info >/dev/null`, { stream: true });
@@ -2603,8 +2964,15 @@ async function verifyHost(host, cfg) {
2603
2964
  await reservePorts(host, cfg);
2604
2965
  }
2605
2966
  function pathPrelude(cfg) {
2606
- const extra = cfg.process.pathPrepend.join(":");
2607
- 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("")}`;
2608
2976
  }
2609
2977
  async function installProcessRuntime(host, cfg) {
2610
2978
  log.host(host.name, "preparing process-mode runtime\u2026");
@@ -2653,10 +3021,52 @@ var init_bootstrap = __esm(() => {
2653
3021
  });
2654
3022
 
2655
3023
  // src/core/ssh.ts
2656
- 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";
2657
3025
  import { tmpdir } from "os";
2658
- 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
+ }
2659
3068
  function setSudoPassword(key, pw) {
3069
+ registerSecret(pw);
2660
3070
  sudoPasswords.set(key, pw);
2661
3071
  }
2662
3072
  function needsSudoPassword(res) {
@@ -2673,7 +3083,7 @@ async function askSudoPassword(key, target) {
2673
3083
  const pw = await askPassword(`sudo password for ${target}:`);
2674
3084
  if (!pw)
2675
3085
  return;
2676
- sudoPasswords.set(key, pw);
3086
+ setSudoPassword(key, pw);
2677
3087
  return pw;
2678
3088
  });
2679
3089
  promptQueue = asked.catch(() => {
@@ -2697,7 +3107,7 @@ class Host {
2697
3107
  this.sudo = this.user !== "root";
2698
3108
  const preset = cfg.sudoPassword || process.env.EPD_SUDO_PASSWORD;
2699
3109
  if (preset && !sudoPasswords.has(this.sudoKey))
2700
- sudoPasswords.set(this.sudoKey, preset);
3110
+ setSudoPassword(this.sudoKey, preset);
2701
3111
  }
2702
3112
  get sudoKey() {
2703
3113
  return `${this.user}@${this.name}:${this.cfg.port}`;
@@ -2706,20 +3116,20 @@ class Host {
2706
3116
  return [
2707
3117
  "SSH authentication succeeded. SSH keys do not grant sudo privileges.",
2708
3118
  `Give ${this.user} passwordless sudo on ${this.name}:`,
2709
- ` echo '${this.user} ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/epd && sudo chmod 440 /etc/sudoers.d/epd`,
3119
+ ` ${sudoersCommand(this.user)}`,
2710
3120
  "or set EPD_SUDO_PASSWORD (ssh.sudo_password in epd.yml), or deploy as root with ssh.user: root."
2711
3121
  ].join(`
2712
3122
  `);
2713
3123
  }
2714
3124
  sshOptions() {
2715
- 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`);
2716
3126
  const args = [
2717
3127
  "-o",
2718
3128
  "BatchMode=yes",
2719
3129
  "-o",
2720
3130
  "StrictHostKeyChecking=accept-new",
2721
3131
  "-o",
2722
- "ConnectTimeout=10",
3132
+ `ConnectTimeout=${SSH_CONNECT_TIMEOUT_S}`,
2723
3133
  "-o",
2724
3134
  "ServerAliveInterval=15",
2725
3135
  "-o",
@@ -2737,13 +3147,15 @@ class Host {
2737
3147
  if (rawEnvKey) {
2738
3148
  if (rawEnvKey.includes("-----BEGIN") || rawEnvKey.includes(`
2739
3149
  `)) {
2740
- keyPath = join5(controlDir, "ci_id_rsa");
3150
+ keyPath = join6(controlDir, `ci_id_rsa.${process.pid}`);
3151
+ trackScratch(keyPath);
2741
3152
  try {
3153
+ rmSync2(keyPath, { force: true });
2742
3154
  writeFileSync4(keyPath, rawEnvKey.trim() + `
2743
- `, { mode: 384 });
3155
+ `, { mode: 384, flag: "wx" });
2744
3156
  chmodSync2(keyPath, 384);
2745
3157
  } catch {}
2746
- } else if (existsSync5(rawEnvKey)) {
3158
+ } else if (existsSync6(rawEnvKey)) {
2747
3159
  keyPath = rawEnvKey;
2748
3160
  }
2749
3161
  }
@@ -2764,8 +3176,11 @@ class Host {
2764
3176
  }
2765
3177
  async exec(script, opts = {}) {
2766
3178
  const prelude = ["set -euo pipefail"];
2767
- 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)}`);
2768
3182
  prelude.push(`export ${k}=${shq(v)}`);
3183
+ }
2769
3184
  const body = `${prelude.join(`
2770
3185
  `)}
2771
3186
  ${script}
@@ -2827,14 +3242,15 @@ ${body}` : body,
2827
3242
  return await proc.exited;
2828
3243
  }
2829
3244
  async writeFile(path, content, mode = "644") {
2830
- const marker = `EPD_EOF_${hash32(path + content.length).toString(36)}`;
2831
- 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)}
2832
3248
  umask 077
2833
- cat > ${shq(path)}.tmp <<'${marker}'
2834
- ${content}
2835
- ${marker}
2836
- chmod ${mode} ${shq(path)}.tmp
2837
- 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}` });
2838
3254
  }
2839
3255
  async readFile(path) {
2840
3256
  const res = await this.exec(`cat ${shq(path)} 2>/dev/null || true`, { allowFailure: true });
@@ -2847,7 +3263,7 @@ mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
2847
3263
  const local = localCommand.map((a) => shq(a)).join(" ");
2848
3264
  const source = password ? `{ printf '%s\\n' "$EPD_SUDO_PW"; ${local}; }` : local;
2849
3265
  const script = `set -euo pipefail; ${source} | ${sshArgs.map((a) => shq(a)).join(" ")}`;
2850
- await run(["bash", "-c", script], {
3266
+ await run([localShell("bash"), "-c", script], {
2851
3267
  stream: true,
2852
3268
  label: `pipe \u2192 ${this.name}`,
2853
3269
  env: password ? { EPD_SUDO_PW: password } : undefined
@@ -2857,7 +3273,9 @@ mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
2857
3273
  const res = await this.exec("echo epd-ok", { allowFailure: true, sudo: false });
2858
3274
  if (res.code !== 0 || !res.stdout.includes("epd-ok")) {
2859
3275
  const isPublickey = res.stderr.includes("Permission denied (publickey)");
2860
- 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.";
2861
3279
  throw new EpdError(`cannot reach ${this.target}:${this.cfg.port}`, res.stderr ? `${res.stderr}
2862
3280
  ${hint}` : hint);
2863
3281
  }
@@ -2876,23 +3294,28 @@ function host(name, cfg) {
2876
3294
  }
2877
3295
  return h;
2878
3296
  }
2879
- var controlDir, sudoPasswords, promptQueue, cache;
3297
+ var SSH_CONNECT_TIMEOUT_S = 10, scratchPaths, cleanupHooked = false, controlDir, sudoPasswords, promptQueue, cache;
2880
3298
  var init_ssh = __esm(() => {
2881
3299
  init_log();
2882
3300
  init_misc();
2883
3301
  init_proc();
2884
3302
  init_prompt();
2885
- controlDir = join5(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2886
- mkdirSync4(controlDir, { recursive: true, mode: 448 });
3303
+ scratchPaths = new Set;
3304
+ controlDir = controlDirectory();
2887
3305
  sudoPasswords = new Map;
2888
3306
  promptQueue = Promise.resolve();
2889
3307
  cache = new Map;
2890
3308
  });
2891
3309
 
2892
3310
  // src/core/ssh-setup.ts
2893
- 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";
2894
3312
  import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
2895
- 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
+ }
2896
3319
  async function prepareSsh(host, canInstallKey = interactive()) {
2897
3320
  const probe = () => run([
2898
3321
  "ssh",
@@ -2928,13 +3351,9 @@ chmod 600 "$HOME/.ssh/authorized_keys"
2928
3351
  grep -qxF -- ${shq(key)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shq(key)} >> "$HOME/.ssh/authorized_keys"`;
2929
3352
  let installedCode = 1;
2930
3353
  if (password) {
2931
- 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`);
2932
3355
  try {
2933
- writeFileSync5(askpassScript, `#!/bin/sh
2934
- cat << 'EPDEOF'
2935
- ${password}
2936
- EPDEOF
2937
- `, { mode: 448 });
3356
+ writeFileSync5(askpassScript, askpassBody(password), { mode: 448 });
2938
3357
  const res = await run([
2939
3358
  "ssh",
2940
3359
  "-o",
@@ -2963,8 +3382,8 @@ EPDEOF
2963
3382
  setSudoPassword(host.sudoKey, password);
2964
3383
  }
2965
3384
  } finally {
2966
- if (existsSync6(askpassScript))
2967
- unlinkSync(askpassScript);
3385
+ if (existsSync7(askpassScript))
3386
+ unlinkSync2(askpassScript);
2968
3387
  }
2969
3388
  }
2970
3389
  if (installedCode !== 0) {
@@ -3005,9 +3424,9 @@ async function publicKeyFor(host) {
3005
3424
  const identityIndex = options.indexOf("-i");
3006
3425
  const identity = identityIndex >= 0 ? options[identityIndex + 1] : undefined;
3007
3426
  if (identity) {
3008
- if (existsSync6(`${identity}.pub`))
3427
+ if (existsSync7(`${identity}.pub`))
3009
3428
  return validateKey(readFileSync5(`${identity}.pub`, "utf8"));
3010
- if (!existsSync6(identity))
3429
+ if (!existsSync7(identity))
3011
3430
  throw new EpdError(`SSH identity does not exist: ${identity}`);
3012
3431
  const proc = Bun.spawn(["ssh-keygen", "-y", "-f", identity], {
3013
3432
  stdin: "inherit",
@@ -3026,14 +3445,14 @@ async function publicKeyFor(host) {
3026
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");
3027
3446
  return validateKey(keys[Number(selected)]);
3028
3447
  }
3029
- const sshDir = join6(homedir3(), ".ssh");
3448
+ const sshDir = join7(homedir3(), ".ssh");
3030
3449
  for (const name of ["id_ed25519", "gh_deploy", "id_ecdsa", "id_rsa"]) {
3031
- const path = join6(sshDir, `${name}.pub`);
3032
- if (existsSync6(path))
3450
+ const path = join7(sshDir, `${name}.pub`);
3451
+ if (existsSync7(path))
3033
3452
  return validateKey(readFileSync5(path, "utf8"));
3034
3453
  }
3035
- const keyPath = join6(sshDir, "id_ed25519");
3036
- if (existsSync6(keyPath)) {
3454
+ const keyPath = join7(sshDir, "id_ed25519");
3455
+ if (existsSync7(keyPath)) {
3037
3456
  throw new EpdError(`Missing public key for ${keyPath}`, "Load it with ssh-add, or set ssh.key to its path, then retry.");
3038
3457
  }
3039
3458
  mkdirSync5(sshDir, { recursive: true, mode: 448 });
@@ -3064,7 +3483,7 @@ var init_ssh_setup = __esm(() => {
3064
3483
  });
3065
3484
 
3066
3485
  // src/proxy/detect.ts
3067
- 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";
3068
3487
  import { basename as basename2, resolve as resolve2 } from "path";
3069
3488
  async function detectExistingProxy(host, checkPorts = [80, 443]) {
3070
3489
  const portsSet = new Set(checkPorts);
@@ -3278,7 +3697,7 @@ http:
3278
3697
  }
3279
3698
  function updateLocalConfigDisableProxy(configPath = "epd.yml") {
3280
3699
  const configFile = resolve2(configPath);
3281
- if (!existsSync7(configFile))
3700
+ if (!existsSync8(configFile))
3282
3701
  return;
3283
3702
  try {
3284
3703
  const raw = readFileSync6(configFile, "utf8");
@@ -3350,7 +3769,7 @@ ${c.gray(snippet)}`);
3350
3769
  const install = await confirm(`Install configuration to ${confPath} on ${host.name}?`, true);
3351
3770
  if (install) {
3352
3771
  await host.writeFile(confPath, snippet);
3353
- 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` });
3354
3773
  log.ok(`${host.name}: installed Nginx configuration and reloaded Nginx`);
3355
3774
  }
3356
3775
  } else if (detected.type === "apache") {
@@ -3380,7 +3799,7 @@ ${c.gray(snippet)}`);
3380
3799
  log.plain(`
3381
3800
  ${c.yellow("!")} Unrecognized reverse proxy detected (${detected.details}).`);
3382
3801
  const customConfig = await ask("Provide path to your custom proxy configuration file to deploy (or leave empty to configure manually):");
3383
- if (customConfig && existsSync7(customConfig)) {
3802
+ if (customConfig && existsSync8(customConfig)) {
3384
3803
  const content = readFileSync6(customConfig, "utf8");
3385
3804
  const defaultRemote = `/etc/proxy/${basename2(customConfig)}`;
3386
3805
  const remotePath = await ask(`Remote destination path on ${host.name}:`, defaultRemote);
@@ -3450,7 +3869,7 @@ import /etc/caddy/conf.d/*
3450
3869
  if (!hasBothPorts) {
3451
3870
  const snippet = generateNginxConfig(cfg, "127.0.0.1");
3452
3871
  await host.writeFile(confPath, snippet);
3453
- 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 });
3454
3873
  log.host(host.name, `installed/updated Nginx configuration for ${domains.join(", ")} with blue/green upstreams`);
3455
3874
  }
3456
3875
  }
@@ -3843,17 +4262,7 @@ async function ensureProxy(host, cfg, opts = {}) {
3843
4262
  const where = containerMode ? CONTAINER_PATHS : { dynamicDir: p.proxyDynamicDir, acmeFile: `${p.acmeDir}/acme.json` };
3844
4263
  const staticJson = JSON.stringify(staticConfig(merged, where), null, 2);
3845
4264
  await host.writeFile(p.proxyStatic, staticJson, "644");
3846
- if (merged.dnsEnv.length) {
3847
- const lines = merged.dnsEnv.map((name) => {
3848
- const value = opts.secrets?.[name];
3849
- if (value === undefined) {
3850
- 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.");
3851
- }
3852
- return `${name}=${value}`;
3853
- });
3854
- await host.writeFile(p.proxyEnv, lines.join(`
3855
- `), "600");
3856
- }
4265
+ const dnsEnv = merged.dnsEnv.length ? dnsEnvContent(merged.dnsEnv, opts.secrets) : undefined;
3857
4266
  if (merged.dashboard && merged.dashboardHost) {
3858
4267
  const dash = {
3859
4268
  http: {
@@ -3871,11 +4280,29 @@ async function ensureProxy(host, cfg, opts = {}) {
3871
4280
  }
3872
4281
  const specHash = hash32(staticJson + JSON.stringify(merged)).toString(36);
3873
4282
  if (containerMode)
3874
- await ensureProxyContainer(host, cfg, merged, specHash, opts);
4283
+ await ensureProxyContainer(host, cfg, merged, specHash, opts, dnsEnv);
3875
4284
  else
3876
4285
  await ensureProxyProcess(host, cfg, merged, specHash, opts);
3877
4286
  }
3878
- 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);
3879
4306
  const spec = containerSpec(merged, cfg, specHash);
3880
4307
  const state = await host.capture(`docker inspect -f '{{.State.Running}} {{index .Config.Labels "epd.spec"}}' ${PROXY_CONTAINER} 2>/dev/null || echo "missing"`);
3881
4308
  const [running, currentHash] = state.split(/\s+/);
@@ -3883,7 +4310,10 @@ async function ensureProxyContainer(host, cfg, merged, specHash, opts) {
3883
4310
  log.host(host.name, "proxy is up to date");
3884
4311
  return;
3885
4312
  }
3886
- 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
3887
4317
  docker pull ${shq(merged.image)} >/dev/null
3888
4318
  docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true
3889
4319
  ${spec.map((a) => shq(a)).join(" ")} >/dev/null
@@ -3952,7 +4382,6 @@ true`, { stream: true, label: `${host.name}: install traefik` });
3952
4382
  }
3953
4383
  ]
3954
4384
  };
3955
- await host.writeFile(p.proxyEcosystem, JSON.stringify(ecosystem, null, 2), "600");
3956
4385
  const jlist = await host.capture(`${pathPrelude(cfg)} pm2 jlist 2>/dev/null || echo '[]'`, {
3957
4386
  sudo: false,
3958
4387
  allowFailure: true
@@ -3962,7 +4391,9 @@ true`, { stream: true, label: `${host.name}: install traefik` });
3962
4391
  log.host(host.name, "proxy is up to date");
3963
4392
  return;
3964
4393
  }
3965
- 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
3966
4397
  ${pathPrelude(cfg)} pm2 start ${shq(p.proxyEcosystem)} --update-env
3967
4398
  ${pathPrelude(cfg)} pm2 save --force >/dev/null 2>&1 || true
3968
4399
  sleep 2
@@ -3983,6 +4414,24 @@ async function writeRoutes(host, cfg, endpoints, accessories = []) {
3983
4414
  await host.writeFile(paths(cfg).proxyDynamic, JSON.stringify(doc, null, 2), "644");
3984
4415
  await host.exec(`sleep ${Math.max(1, cfg.proxy.reloadWait)}`);
3985
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
+ }
3986
4435
  async function removeRoutes(host, cfg) {
3987
4436
  await host.exec(`rm -f ${shq(paths(cfg).proxyDynamic)} ${shq(paths(cfg).proxyApp)}`, { allowFailure: true });
3988
4437
  }
@@ -4012,56 +4461,168 @@ var init_traefik = __esm(() => {
4012
4461
  });
4013
4462
 
4014
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
+ }
4015
4500
  function who() {
4016
- 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
+ `));
4017
4531
  }
4018
4532
 
4019
4533
  class DeployLock {
4020
4534
  cfg;
4021
4535
  hosts;
4022
4536
  held = [];
4537
+ pending = [];
4538
+ infoJson = "";
4023
4539
  constructor(cfg, hosts) {
4024
4540
  this.cfg = cfg;
4025
4541
  this.hosts = hosts;
4026
4542
  }
4027
4543
  async acquire(what) {
4028
4544
  const dir = paths(this.cfg).lock;
4029
- const info = { by: who(), at: new Date().toISOString(), what };
4030
- for (const host of this.hosts) {
4031
- 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)}
4032
4551
  if mkdir ${shq(dir)} 2>/dev/null; then
4033
- 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
4034
4556
  echo acquired
4035
4557
  else
4036
4558
  cat ${shq(dir)}/info 2>/dev/null || echo '{}'
4037
4559
  exit 9
4038
4560
  fi`, { allowFailure: true });
4039
- if (res.code === 9) {
4040
- await this.release();
4041
- let held = {};
4042
- try {
4043
- held = JSON.parse(res.stdout || "{}");
4044
- } catch {}
4045
- throw new EpdError(`${this.cfg.name} is locked on ${host.name}`, held.by ? `Held by ${held.by} since ${held.at} (${held.what}).
4046
- If that deploy died, run: epd lock release` : "Run `epd lock release` if a previous deploy was interrupted.");
4047
- }
4048
- if (res.code !== 0) {
4049
- await this.release();
4050
- 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);
4051
4582
  }
4052
- this.held.push(host);
4583
+ if (this.held.length === 0)
4584
+ untrackLock(this);
4585
+ } catch (err) {
4586
+ await this.release();
4587
+ throw err;
4053
4588
  }
4054
4589
  log.debug(`lock acquired on ${this.held.length} host(s)`);
4055
4590
  }
4056
4591
  async release() {
4057
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
+ }
4058
4604
  for (const host of this.held.splice(0)) {
4059
- 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
+ }
4060
4611
  }
4612
+ untrackLock(this);
4061
4613
  }
4062
4614
  static async forceRelease(cfg, hosts) {
4063
- for (const host of hosts)
4064
- 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
+ }
4065
4626
  }
4066
4627
  static async status(cfg, hosts) {
4067
4628
  const out = [];
@@ -4091,10 +4652,21 @@ async function withLock(cfg, hosts, what, skip, fn) {
4091
4652
  await lock.release();
4092
4653
  }
4093
4654
  }
4655
+ var STALE_AFTER_MS, activeLocks, SIGNALS, SIGNAL_EXIT, SIGNAL_RELEASE_MS, releasingOnSignal = false, signalHandlers;
4094
4656
  var init_lock = __esm(() => {
4095
4657
  init_log();
4096
4658
  init_misc();
4097
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
+ };
4098
4670
  });
4099
4671
 
4100
4672
  // src/core/probe.ts
@@ -4113,6 +4685,11 @@ function statusCondition(spec) {
4113
4685
  return tests.join(" || ");
4114
4686
  }
4115
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
+ }
4116
4693
  const list = targets.map((t) => `${t.label} ${t.address} ${t.port}`).join(`
4117
4694
  `);
4118
4695
  const tcpOnly = health.path === null;
@@ -4198,16 +4775,39 @@ var init_probe = __esm(() => {
4198
4775
  });
4199
4776
 
4200
4777
  // src/core/state.ts
4201
- async function readState(host, cfg) {
4202
- const raw = await host.readFile(paths(cfg).state);
4203
- 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)
4204
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;
4205
4803
  try {
4206
- return JSON.parse(raw);
4804
+ parsed = JSON.parse(raw);
4207
4805
  } catch {
4208
- log.warn(`${host.name}: state file is corrupt, treating this host as fresh`);
4209
- return null;
4806
+ throw corrupt("not valid JSON (possibly from an interrupted write)");
4210
4807
  }
4808
+ if (!isAppState(parsed))
4809
+ throw corrupt("missing required fields");
4810
+ return parsed;
4211
4811
  }
4212
4812
  async function writeState(host, cfg, state) {
4213
4813
  await host.writeFile(paths(cfg).state, JSON.stringify(state, null, 2), "644");
@@ -4227,18 +4827,21 @@ function recordDeploy(state, version, by, keep) {
4227
4827
  const history = [{ version, at: new Date().toISOString(), by }, ...state.history.filter((h) => h.version !== version)];
4228
4828
  return { ...state, version, updatedAt: new Date().toISOString(), history: history.slice(0, Math.max(keep, 2) * 2) };
4229
4829
  }
4830
+ var PRESENT = "EPD_STATE_PRESENT", PRESENT_LINE;
4230
4831
  var init_state = __esm(() => {
4231
4832
  init_names();
4232
4833
  init_log();
4834
+ init_misc();
4835
+ PRESENT_LINE = new RegExp(`^${PRESENT}\\r?$`, "m");
4233
4836
  });
4234
4837
 
4235
4838
  // src/deploy/image.ts
4236
- import { existsSync as existsSync8 } from "fs";
4237
- import { join as join7 } from "path";
4839
+ import { existsSync as existsSync9 } from "fs";
4840
+ import { join as join8 } from "path";
4238
4841
  async function resolveVersion(cfg, explicit) {
4239
4842
  if (explicit)
4240
4843
  return { id: explicit, source: "explicit", dirty: false };
4241
- if (existsSync8(join7(cfg.root, ".git")) && await which("git")) {
4844
+ if (existsSync9(join8(cfg.root, ".git")) && await which("git")) {
4242
4845
  const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
4243
4846
  if (sha.code === 0 && sha.stdout) {
4244
4847
  const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
@@ -4252,8 +4855,8 @@ async function hasBuildx() {
4252
4855
  return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
4253
4856
  }
4254
4857
  async function buildImage(cfg, version, env) {
4255
- const dockerfile = join7(cfg.root, cfg.build.dockerfile);
4256
- if (!existsSync8(dockerfile)) {
4858
+ const dockerfile = join8(cfg.root, cfg.build.dockerfile);
4859
+ if (!existsSync9(dockerfile)) {
4257
4860
  throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
4258
4861
  }
4259
4862
  const ref = imageRef(cfg, version);
@@ -4266,7 +4869,7 @@ async function buildImage(cfg, version, env) {
4266
4869
  async function buildWithBuildx(cfg, ref, version, env) {
4267
4870
  const args = ["docker", "buildx", "build"];
4268
4871
  args.push("--platform", cfg.build.platform);
4269
- args.push("--file", join7(cfg.root, cfg.build.dockerfile));
4872
+ args.push("--file", join8(cfg.root, cfg.build.dockerfile));
4270
4873
  args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
4271
4874
  if (cfg.build.target)
4272
4875
  args.push("--target", cfg.build.target);
@@ -4299,7 +4902,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
4299
4902
  if (cfg.build.platform !== localPlatform) {
4300
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}.`);
4301
4904
  }
4302
- 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`];
4303
4906
  if (cfg.build.target)
4304
4907
  args.push("--target", cfg.build.target);
4305
4908
  for (const [k, v] of Object.entries(cfg.build.args))
@@ -4322,13 +4925,18 @@ async function ensureBuilder() {
4322
4925
  log.info('creating buildx builder "epd"');
4323
4926
  await run(["docker", "buildx", "create", "--name", "epd", "--use", "--bootstrap"], { stream: true });
4324
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
+ }
4325
4935
  async function loginRegistry(host, cfg, env) {
4326
4936
  if (!cfg.registry)
4327
4937
  return;
4938
+ checkRegistryPassword(cfg, env);
4328
4939
  const password = env[cfg.registry.passwordEnv];
4329
- if (!password) {
4330
- throw new EpdError(`registry password: ${cfg.registry.passwordEnv} is not set`, "Export it, or put it in .env next to epd.yml.");
4331
- }
4332
4940
  const server = cfg.registry.server ?? "";
4333
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` });
4334
4942
  }
@@ -4343,19 +4951,19 @@ async function ensureImage(host, cfg, version) {
4343
4951
  await host.exec(`docker pull ${shq(ref)} >/dev/null`, { label: `${host.name}: docker pull` });
4344
4952
  } else {
4345
4953
  log.host(host.name, `shipping ${ref} over ssh (no registry configured)`);
4346
- 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`]);
4347
4955
  }
4348
4956
  }
4349
4957
  async function pruneImages(host, cfg, keep, inUse) {
4350
4958
  const keepRefs = inUse.map((v) => imageRef(cfg, v));
4351
4959
  await host.exec(`keep=${shq(keepRefs.join(" "))}
4352
- 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 \\
4353
4961
  | sort -k2 -r | tail -n +$(( ${keep} + 1 )) | awk '{print $1}' | while read -r img; do
4354
4962
  case " $keep " in *" $img "*) continue;; esac
4355
4963
  case "$img" in *:latest|*:buildcache) continue;; esac
4356
4964
  docker rmi "$img" >/dev/null 2>&1 || true
4357
4965
  done
4358
- 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 });
4359
4967
  }
4360
4968
  var imageRef = (cfg, version) => `${cfg.image}:${version}`;
4361
4969
  var init_image = __esm(() => {
@@ -4389,10 +4997,13 @@ function envFileContent(vars) {
4389
4997
  return Object.entries(vars).map(([k, v]) => `${k}=${v}`).join(`
4390
4998
  `);
4391
4999
  }
4392
- async function writeServiceEnv(host, cfg, svc, env) {
5000
+ function serviceEnvContent(svc, env) {
4393
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) {
4394
5005
  const file = `${paths(cfg).app}/env.${svc.name}`;
4395
- await host.writeFile(file, envFileContent({ ...svc.env, ...secrets }), "600");
5006
+ await host.writeFile(file, serviceEnvContent(svc, env), "600");
4396
5007
  return file;
4397
5008
  }
4398
5009
  function dockerRunArgs(o) {
@@ -4422,7 +5033,8 @@ function dockerRunArgs(o) {
4422
5033
  async function startSlot(host, cfg, svc, slot, version, envFile) {
4423
5034
  const names = [];
4424
5035
  const lines = [
4425
- `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}`)})`,
4426
5038
  `[ -n "$old" ] && docker rm -f $old >/dev/null 2>&1 || true`
4427
5039
  ];
4428
5040
  for (let i = 0;i < svc.replicas; i++) {
@@ -4452,7 +5064,7 @@ async function containerIps(host, cfg, names) {
4452
5064
  return map;
4453
5065
  }
4454
5066
  async function stopSlot(host, cfg, svc, slot, opts) {
4455
- 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}`)})
4456
5068
  if [ -n "$names" ]; then
4457
5069
  sleep ${opts.drain}
4458
5070
  docker stop --timeout ${svc.stopTimeout} $names >/dev/null 2>&1 || true
@@ -4462,7 +5074,7 @@ fi`;
4462
5074
  disown 2>/dev/null || true` : teardown, { allowFailure: true, label: `${host.name}: stop ${svc.name}/${slot}` });
4463
5075
  }
4464
5076
  async function removeApp(host, cfg) {
4465
- 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}`)})
4466
5078
  [ -n "$ids" ] && docker rm -f $ids >/dev/null 2>&1 || true`, { allowFailure: true });
4467
5079
  }
4468
5080
  async function listContainers(host, cfg) {
@@ -4477,7 +5089,7 @@ async function listContainers(host, cfg) {
4477
5089
  "{{.Image}}",
4478
5090
  "{{.CreatedAt}}"
4479
5091
  ].join("\t");
4480
- 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 });
4481
5093
  return out.split(`
4482
5094
  `).filter(Boolean).map((line) => {
4483
5095
  const [name, service, slot, version, replica, status, state, image, created] = line.split("\t");
@@ -4529,13 +5141,17 @@ async function startAccessory(host, cfg, acc, env, opts) {
4529
5141
  args.push(...acc.dockerOptions, acc.image);
4530
5142
  if (acc.command)
4531
5143
  args.push(...parseCommand(acc.command));
4532
- 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
4533
5146
  ${opts.recreate ? `docker rm -f ${shq(name)} >/dev/null` : `docker start ${shq(name)} >/dev/null 2>&1 || true; exit 0`}
4534
5147
  fi
4535
5148
  docker pull ${shq(acc.image)} >/dev/null
4536
5149
  ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: accessory ${acc.name}` });
4537
5150
  log.host(host.name, `accessory ${acc.name} running`);
4538
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
+ }
4539
5155
  var init_docker = __esm(() => {
4540
5156
  init_log();
4541
5157
  init_misc();
@@ -4544,8 +5160,8 @@ var init_docker = __esm(() => {
4544
5160
  });
4545
5161
 
4546
5162
  // src/deploy/process.ts
4547
- import { existsSync as existsSync9 } from "fs";
4548
- import { join as join8 } from "path";
5163
+ import { existsSync as existsSync10 } from "fs";
5164
+ import { join as join9 } from "path";
4549
5165
  function releaseDir(cfg, version) {
4550
5166
  return `${paths(cfg).releases}/${version}`;
4551
5167
  }
@@ -4554,7 +5170,7 @@ async function uploadSource(host, cfg, version) {
4554
5170
  const p = paths(cfg);
4555
5171
  await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
4556
5172
  if (cfg.process.source === "git") {
4557
- if (!existsSync9(join8(cfg.root, ".git")))
5173
+ if (!existsSync10(join9(cfg.root, ".git")))
4558
5174
  throw new EpdError('process.source is "git" but this is not a git repository');
4559
5175
  log.host(host.name, `uploading HEAD as ${version}`);
4560
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`]);
@@ -4572,22 +5188,29 @@ async function uploadSource(host, cfg, version) {
4572
5188
  log.host(host.name, `uploading ${version}`);
4573
5189
  await run(args, { cwd: cfg.root, label: `rsync \u2192 ${host.name}` });
4574
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
+ }
4575
5196
  async function buildRelease(host, cfg, version, env) {
4576
5197
  const dest = releaseDir(cfg, version);
4577
- 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;
4578
5202
  const envFile = paths(cfg).envFile;
4579
- await host.writeFile(envFile, Object.entries({ ...cfg.env, ...secrets }).map(([k, v]) => `${k}=${v}`).join(`
4580
- `), "600");
4581
- const steps = [`cd ${shq(dest)}`, pathPrelude(cfg), `set -a; . ${shq(envFile)}; set +a`];
4582
- if (cfg.process.install)
4583
- steps.push(cfg.process.install);
4584
- if (cfg.process.build)
4585
- steps.push(cfg.process.build);
4586
- if (steps.length > 3) {
4587
- log.host(host.name, "installing and building");
4588
- 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(`
4589
5213
  `), { ...asUser, stream: true, label: `${host.name}: build` });
4590
- }
4591
5214
  }
4592
5215
  function ecosystem(cfg, svc, slot, version, env) {
4593
5216
  const dir = releaseDir(cfg, version);
@@ -4630,7 +5253,8 @@ async function startSlot2(host, cfg, svc, slot, version, env) {
4630
5253
  const file = `${paths(cfg).app}/pm2.${svc.name}.${slot}.json`;
4631
5254
  await host.writeFile(file, JSON.stringify(doc, null, 2), "600");
4632
5255
  const stale = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
4633
- 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
4634
5258
  ${pm2(cfg, `start ${shq(file)} --update-env`)}
4635
5259
  ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, label: `${host.name}: pm2 start ${svc.name}/${slot}` });
4636
5260
  }
@@ -4645,7 +5269,7 @@ ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`;
4645
5269
  disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host.name}: pm2 stop ${svc.name}/${slot}` });
4646
5270
  }
4647
5271
  async function removeApp2(host, cfg) {
4648
- 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
4649
5273
  ${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
4650
5274
  done
4651
5275
  ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
@@ -4668,6 +5292,10 @@ async function listProcesses(host, cfg) {
4668
5292
  memory: p.monit?.memory ?? 0
4669
5293
  }));
4670
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
+ }
4671
5299
  async function finalizeRelease(host, cfg, version) {
4672
5300
  const p = paths(cfg);
4673
5301
  await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
@@ -4704,23 +5332,21 @@ class HetznerDnsClient {
4704
5332
  "Content-Type": "application/json",
4705
5333
  ...options.headers
4706
5334
  };
4707
- const res = await fetch(url, { ...options, headers });
4708
- let data;
4709
- try {
4710
- data = await res.json();
4711
- } catch {
4712
- data = null;
4713
- }
5335
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
5336
+ const { data, isJson, empty } = await readJsonBody(res);
4714
5337
  if (!res.ok) {
4715
- const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
4716
- 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.");
4717
5343
  }
4718
5344
  return data;
4719
5345
  }
4720
5346
  async listZones(name) {
4721
5347
  const query = name ? `?name=${encodeURIComponent(name)}` : "";
4722
5348
  const res = await this.request(`/zones${query}`);
4723
- return (res.zones ?? []).map((z) => ({ id: z.id, name: z.name }));
5349
+ return (res?.zones ?? []).map((z) => ({ id: z.id, name: z.name }));
4724
5350
  }
4725
5351
  async findZoneForDomain(domain, explicitZoneId) {
4726
5352
  if (explicitZoneId) {
@@ -4771,7 +5397,7 @@ class HetznerDnsClient {
4771
5397
  }
4772
5398
  const zoneName = zone?.name ?? "";
4773
5399
  const res = await this.request(`/records?zone_id=${encodeURIComponent(zoneId)}`);
4774
- const records = res.records ?? [];
5400
+ const records = res?.records ?? [];
4775
5401
  let mapped = records.map((r) => ({
4776
5402
  id: r.id,
4777
5403
  zoneId: r.zone_id,
@@ -4811,7 +5437,9 @@ class HetznerDnsClient {
4811
5437
  ttl
4812
5438
  })
4813
5439
  });
4814
- 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.");
4815
5443
  return {
4816
5444
  id: created.id,
4817
5445
  zoneId: created.zone_id,
@@ -4843,7 +5471,9 @@ class HetznerDnsClient {
4843
5471
  ttl
4844
5472
  })
4845
5473
  });
4846
- 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.");
4847
5477
  return {
4848
5478
  id: updated.id,
4849
5479
  zoneId: updated.zone_id,
@@ -4862,6 +5492,7 @@ class HetznerDnsClient {
4862
5492
  }
4863
5493
  var init_hetzner = __esm(() => {
4864
5494
  init_log();
5495
+ init_http();
4865
5496
  });
4866
5497
  // src/dns/index.ts
4867
5498
  import dns from "dns/promises";
@@ -4874,12 +5505,12 @@ function isIPv4(ip) {
4874
5505
  return !isNaN(n) && n >= 0 && n <= 255 && String(n) === p;
4875
5506
  });
4876
5507
  }
4877
- function isIPv6(ip) {
5508
+ function isIPv62(ip) {
4878
5509
  return ip.includes(":") && /^[0-9a-fA-F:]+$/.test(ip);
4879
5510
  }
4880
5511
  async function resolveHostIps(target) {
4881
5512
  const clean = target.trim();
4882
- if (isIPv4(clean) || isIPv6(clean))
5513
+ if (isIPv4(clean) || isIPv62(clean))
4883
5514
  return [clean];
4884
5515
  try {
4885
5516
  const lookup = await dns.lookup(clean, { all: true });
@@ -4889,6 +5520,11 @@ async function resolveHostIps(target) {
4889
5520
  } catch {}
4890
5521
  return [clean];
4891
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
+ }
4892
5528
  function getRouteDomains(cfg) {
4893
5529
  if (cfg.dns?.domains && cfg.dns.domains.length > 0) {
4894
5530
  return cfg.dns.domains;
@@ -4900,7 +5536,7 @@ function getRouteDomains(cfg) {
4900
5536
  for (const svc of cfg.services) {
4901
5537
  for (const route of svc.routes) {
4902
5538
  for (const host of route.hosts) {
4903
- const d = (host.split(":")[0] ?? "").trim().toLowerCase();
5539
+ const d = routeHostName(host);
4904
5540
  if (d)
4905
5541
  domains.add(d);
4906
5542
  }
@@ -4909,7 +5545,7 @@ function getRouteDomains(cfg) {
4909
5545
  for (const acc of cfg.accessories) {
4910
5546
  for (const route of acc.routes) {
4911
5547
  for (const host of route.hosts) {
4912
- const d = (host.split(":")[0] ?? "").trim().toLowerCase();
5548
+ const d = routeHostName(host);
4913
5549
  if (d)
4914
5550
  domains.add(d);
4915
5551
  }
@@ -4967,7 +5603,7 @@ async function syncDns(cfg, opts = {}) {
4967
5603
  for (const h of routedHosts) {
4968
5604
  const resolved = await resolveHostIps(h);
4969
5605
  for (const ip of resolved) {
4970
- if (isIPv4(ip) || isIPv6(ip))
5606
+ if (isIPv4(ip) || isIPv62(ip))
4971
5607
  ips.add(ip);
4972
5608
  }
4973
5609
  }
@@ -4992,7 +5628,7 @@ async function syncDns(cfg, opts = {}) {
4992
5628
  }
4993
5629
  const existingRecords = await provider.listDnsRecords(zone.id, domain);
4994
5630
  for (const ip of ips) {
4995
- const type = isIPv6(ip) ? "AAAA" : "A";
5631
+ const type = isIPv62(ip) ? "AAAA" : "A";
4996
5632
  const existing = existingRecords.find((r) => r.name.toLowerCase() === domain.toLowerCase() && r.type === type && r.content === ip);
4997
5633
  if (existing) {
4998
5634
  const needsProxyUpdate = provider.name === "cloudflare" && existing.proxied !== isProxied;
@@ -5155,6 +5791,8 @@ var init_resolve = __esm(() => {
5155
5791
  // src/deploy/deploy.ts
5156
5792
  async function deploy(loaded, opts = {}) {
5157
5793
  const { config: cfg, env } = loaded;
5794
+ if (!opts.dryRun && cfg.mode === "docker")
5795
+ checkRegistryPassword(cfg, env);
5158
5796
  await resolveDynamicHosts(cfg, env);
5159
5797
  const started = Date.now();
5160
5798
  const services = selectServices(cfg, opts.onlyServices);
@@ -5232,7 +5870,7 @@ ${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made
5232
5870
  }
5233
5871
  if (!opts.skipHooks && cfg.hooks.preDeploy)
5234
5872
  await hook(cfg, "pre_deploy", cfg.hooks.preDeploy, version);
5235
- 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 () => {
5236
5874
  log.step("Preparing servers");
5237
5875
  await pool(hosts, 8, async (host) => {
5238
5876
  await verifyHost(host, cfg);
@@ -5244,30 +5882,7 @@ ${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made
5244
5882
  log.step("Checking proxy");
5245
5883
  await pool(proxyHosts(cfg).filter((h) => targetHosts.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: env }));
5246
5884
  }
5247
- const live = new Map;
5248
- for (const h of allHosts(cfg)) {
5249
- const state = await readState(host(h, cfg.ssh), cfg);
5250
- const m = new Map;
5251
- for (const [svc, s] of Object.entries(state?.services ?? {}))
5252
- m.set(svc, s.slot);
5253
- live.set(h, m);
5254
- }
5255
- const deployHost = async (host) => {
5256
- await deployToHost({ cfg, env, host, services, version, opts, live });
5257
- };
5258
- if (cfg.strategy === "parallel") {
5259
- await pool(hosts, hosts.length, deployHost);
5260
- } else {
5261
- for (const host of hosts)
5262
- await deployHost(host);
5263
- }
5264
- if (cfg.proxy.crossHost) {
5265
- log.step("Syncing routes across hosts");
5266
- await pool(proxyHosts(cfg).map((h) => host(h, cfg.ssh)), 4, async (host) => {
5267
- await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
5268
- });
5269
- }
5270
- });
5885
+ }));
5271
5886
  if (cfg.dns?.enabled && cfg.dns.autoSync || cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
5272
5887
  try {
5273
5888
  await syncDns(cfg, { log: true });
@@ -5280,41 +5895,278 @@ ${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made
5280
5895
  log.ok(`Deployed ${cfg.name} ${version} in ${dur(Date.now() - started)}`);
5281
5896
  printUrls(cfg);
5282
5897
  }
5283
- async function deployToHost(d) {
5284
- const { cfg, env, host, version, opts, live } = d;
5285
- const services = d.services.filter((s) => s.hosts.includes(host.name));
5286
- if (!services.length)
5287
- return;
5288
- log.step(`${host.name}: deploying ${services.map((s) => s.name).join(", ")}`);
5289
- if (cfg.mode === "docker") {
5290
- await loginRegistry(host, cfg, env);
5291
- await ensureImage(host, cfg, version);
5292
- } else if (!opts.reuse) {
5293
- await uploadSource(host, cfg, version);
5294
- 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));
5295
6088
  } else {
5296
- const dir = releaseDir(cfg, version);
5297
- if (!await host.test(`[ -d ${JSON.stringify(dir)} ]`)) {
5298
- 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;
5299
6093
  }
5300
6094
  }
5301
- const state = await readState(host, cfg) ?? emptyState(cfg);
5302
- const previous = new Map;
5303
- const started = [];
5304
- try {
5305
- for (const svc of services) {
5306
- const current = state.services[svc.name]?.slot;
5307
- if (current)
5308
- previous.set(svc.name, current);
5309
- const slot = current ? otherSlot(current) : "blue";
5310
- log.host(host.name, `${svc.name}: starting ${svc.replicas} replica(s) on ${slot}`);
5311
- 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) {
5312
6165
  if (cfg.mode === "docker") {
5313
6166
  const envFile = await writeServiceEnv(host, cfg, svc, env);
5314
6167
  const names = await startSlot(host, cfg, svc, slot, version, envFile);
5315
- started.push({ svc, slot });
5316
6168
  const ips = usesHostPorts(cfg) ? {} : await containerIps(host, cfg, names);
5317
- probes = names.map((name, i) => ({
6169
+ const probes = names.map((name, i) => ({
5318
6170
  label: name,
5319
6171
  address: usesHostPorts(cfg) ? "127.0.0.1" : ips[name] ?? "",
5320
6172
  port: usesHostPorts(cfg) ? hostPort(cfg, svc, slot, i) : svc.health.port ?? svc.port
@@ -5322,73 +6174,45 @@ async function deployToHost(d) {
5322
6174
  const noIp = probes.find((p) => !p.address);
5323
6175
  if (noIp)
5324
6176
  throw new EpdError(`${host.name}: ${noIp.label} did not get an IP on the ${cfg.proxy.network} network`, "Check `epd logs`.");
5325
- } else {
5326
- await startSlot2(host, cfg, svc, slot, version, env);
5327
- started.push({ svc, slot });
5328
- probes = Array.from({ length: svc.replicas }, (_, i) => ({
5329
- label: `${svc.name}#${i}`,
5330
- address: "127.0.0.1",
5331
- port: hostPort(cfg, svc, slot, i)
5332
- }));
6177
+ return probes;
5333
6178
  }
5334
- 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) {
5335
6188
  log.host(host.name, `${svc.name}: waiting for health check${svc.health.path ? ` ${svc.health.path}` : " (tcp)"}`);
5336
6189
  await waitHealthy(host, probes, svc.health);
5337
6190
  log.host(host.name, `${svc.name}: healthy`);
5338
- } else if (!opts.skipHealth) {
6191
+ } else {
5339
6192
  await confirmUp(host, cfg, svc, slot);
5340
6193
  }
5341
- live.get(host.name)?.set(svc.name, slot) ?? live.set(host.name, new Map([[svc.name, slot]]));
5342
- state.services[svc.name] = {
5343
- slot,
5344
- replicas: svc.replicas,
5345
- version,
5346
- endpoints: endpointsFor(cfg, svc, slot, host.name).map((e) => e.url)
5347
- };
5348
- }
5349
- const hasSvcRoutes = services.some((s) => s.routes.length);
5350
- const hasAccRoutes = cfg.accessories.some((a) => a.routes.length && (cfg.proxy.crossHost || a.host === host.name));
5351
- if (cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
5352
- await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
5353
- log.host(host.name, "routes updated");
5354
- } else if (!cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
5355
- await syncExternalProxy(host, cfg);
5356
- }
5357
- for (const svc of services) {
5358
- const old = previous.get(svc.name);
5359
- if (!old)
5360
- continue;
5361
- const drain = Math.max(svc.drain, cfg.proxy.reloadWait + 2);
5362
- log.host(host.name, `${svc.name}: retiring ${old} (${drain}s drain, in the background)`);
5363
- if (cfg.mode === "docker")
5364
- await stopSlot(host, cfg, svc, old, { drain, remove: true, detach: true });
5365
- else
5366
- await stopSlot2(host, cfg, svc, old, drain, { detach: true });
5367
- }
5368
- await writeState(host, cfg, recordDeploy(state, version, process.env.USER ?? "epd", cfg.keepReleases));
5369
- if (cfg.mode === "docker") {
5370
- await pruneImages(host, cfg, cfg.keepReleases, [version, ...state.history.slice(0, 2).map((h) => h.version)]);
5371
- } else {
5372
- await finalizeRelease(host, cfg, version);
5373
- }
5374
- log.host(host.name, c.green("done"));
5375
- } catch (error) {
5376
- log.error(`${host.name}: deploy failed, rolling back this host`);
5377
- for (const { svc, slot } of started) {
5378
- try {
5379
- if (cfg.mode === "docker")
5380
- await stopSlot(host, cfg, svc, slot, { drain: 0, remove: true });
5381
- else
5382
- await stopSlot2(host, cfg, svc, slot, 0);
5383
- } catch {}
5384
- }
5385
- if (!d.opts.skipHooks && cfg.hooks.onFailure) {
5386
- await hook(cfg, "on_failure", cfg.hooks.onFailure, version).catch(() => {
5387
- return;
5388
- });
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
+ }
5389
6214
  }
5390
- throw error;
5391
- }
6215
+ };
5392
6216
  }
5393
6217
  async function confirmUp(host, cfg, svc, slot) {
5394
6218
  if (cfg.mode === "docker") {
@@ -5459,11 +6283,15 @@ async function deployAccessories(cfg, env, recreate) {
5459
6283
  if (cfg.mode === "process" && !await hasDocker(host2)) {
5460
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.");
5461
6285
  }
5462
- await ensureDirs(host2, cfg);
5463
- await ensureNetwork(host2, cfg);
5464
- await startAccessory(host2, cfg, acc, env, { recreate });
6286
+ await deployAccessory(host2, cfg, acc, env, recreate);
5465
6287
  }
5466
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
+ }
5467
6295
  function selectServices(cfg, only) {
5468
6296
  if (!only?.length)
5469
6297
  return cfg.services;
@@ -5516,6 +6344,7 @@ function printUrls(cfg) {
5516
6344
  for (const u of urls)
5517
6345
  log.info(c.cyan(u));
5518
6346
  }
6347
+ var errMsg = (e) => e instanceof Error ? e.message : String(e);
5519
6348
  var init_deploy = __esm(() => {
5520
6349
  init_log();
5521
6350
  init_misc();
@@ -5549,6 +6378,7 @@ var init_setup = __esm(() => {
5549
6378
  init_traefik();
5550
6379
  init_detect();
5551
6380
  init_deploy();
6381
+ init_image();
5552
6382
  init_cloudflare2();
5553
6383
  init_resolve();
5554
6384
  setup = {
@@ -5599,6 +6429,8 @@ Options
5599
6429
  log.info(`not asking again \u2014 run ${c.cyan("epd auth cloudflare")} to link it later`);
5600
6430
  }
5601
6431
  }
6432
+ if (cfg.mode === "docker")
6433
+ checkRegistryPassword(cfg, loaded.env);
5602
6434
  await resolveDynamicHosts(cfg, loaded.env);
5603
6435
  const only = ctx.values.host;
5604
6436
  const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
@@ -5731,6 +6563,7 @@ var rollback;
5731
6563
  var init_rollback = __esm(() => {
5732
6564
  init_log();
5733
6565
  init_deploy();
6566
+ init_image();
5734
6567
  init_state();
5735
6568
  init_ssh();
5736
6569
  rollback = {
@@ -5758,6 +6591,8 @@ Options
5758
6591
  const first = hosts[0];
5759
6592
  if (!first)
5760
6593
  throw new EpdError("no hosts configured");
6594
+ if (cfg.mode === "docker" && !ctx.values.list)
6595
+ checkRegistryPassword(cfg, loaded.env);
5761
6596
  const state = await readState(first, cfg);
5762
6597
  if (!state?.history.length) {
5763
6598
  throw new EpdError(`${cfg.name} has no deploy history on ${first.name}`, "Deploy it at least twice before rolling back.");
@@ -5929,6 +6764,8 @@ Options
5929
6764
  const { config: cfg, env } = ctx.load();
5930
6765
  await resolveDynamicHosts(cfg, env);
5931
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)}`);
5932
6769
  const service = ctx.values.service;
5933
6770
  const accessory = ctx.values.accessory;
5934
6771
  const grep = ctx.values.grep;
@@ -5953,9 +6790,9 @@ Options
5953
6790
  names = [names[0]];
5954
6791
  }
5955
6792
  const filter = [
5956
- `--filter "label=epd.app=${cfg.name}"`,
5957
- service ? `--filter "label=epd.service=${service}"` : "",
5958
- 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}`)}` : ""
5959
6796
  ].filter(Boolean).join(" ");
5960
6797
  for (const name of names) {
5961
6798
  const host2 = host(name, cfg.ssh);
@@ -5992,6 +6829,7 @@ wait`;
5992
6829
  });
5993
6830
 
5994
6831
  // src/commands/exec.ts
6832
+ import { randomBytes } from "crypto";
5995
6833
  async function pickHost(ctx, cfg) {
5996
6834
  const names = allHosts(cfg);
5997
6835
  const chosen = ctx.values.host ?? names[0];
@@ -5999,6 +6837,40 @@ async function pickHost(ctx, cfg) {
5999
6837
  throw new EpdError(`no such host "${chosen}"`, `Known: ${names.join(", ")}`);
6000
6838
  return host(chosen, cfg.ssh);
6001
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
+ }
6002
6874
  var exec, shell;
6003
6875
  var init_exec = __esm(() => {
6004
6876
  init_log();
@@ -6007,6 +6879,8 @@ var init_exec = __esm(() => {
6007
6879
  init_names();
6008
6880
  init_state();
6009
6881
  init_ssh();
6882
+ init_docker();
6883
+ init_process();
6010
6884
  init_image();
6011
6885
  init_resolve();
6012
6886
  exec = {
@@ -6067,10 +6941,8 @@ Examples
6067
6941
  if (!version)
6068
6942
  throw new EpdError(`${cfg.name} is not deployed on ${host2.name}`);
6069
6943
  if (cfg.mode === "process") {
6070
- const dir = `${paths(cfg).current}`;
6071
- const script = `cd ${shq(dir)} && ${pathPrelude(cfg)} && set -a && . ${shq(paths(cfg).envFile)} && set +a && ${command}`;
6072
6944
  log.info(`${host2.name}: ${command}`);
6073
- const code = await host2.interactive(script, { sudo: false });
6945
+ const code = await runInProcessApp(host2, cfg, env, command);
6074
6946
  if (code !== 0)
6075
6947
  process.exitCode = code;
6076
6948
  return;
@@ -6084,24 +6956,11 @@ Examples
6084
6956
  process.exitCode = code;
6085
6957
  return;
6086
6958
  }
6087
- const envFile = `${paths(cfg).app}/env.${svc.name}`;
6088
- const args = [
6089
- "docker",
6090
- "run",
6091
- "--rm",
6092
- ctx.values.interactive ? "-it" : "",
6093
- "--network",
6094
- cfg.proxy.network,
6095
- "--env-file",
6096
- envFile,
6097
- "--env",
6098
- `PORT=${svc.port}`,
6099
- "--label",
6100
- `epd.app=${cfg.name}`,
6101
- imageRef(cfg, version)
6102
- ].filter(Boolean);
6103
6959
  log.info(`${host2.name}: ${command} ${c.gray(`(new container from ${version})`)}`);
6104
- 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
+ });
6105
6964
  if (code !== 0)
6106
6965
  process.exitCode = code;
6107
6966
  }
@@ -6197,6 +7056,8 @@ Options
6197
7056
  }
6198
7057
  case "logs": {
6199
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)}`);
6200
7061
  const follow = Boolean(ctx.values.follow);
6201
7062
  for (const host of hosts) {
6202
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`;
@@ -6399,7 +7260,8 @@ var init_lock2 = __esm(() => {
6399
7260
  help: () => `${c.bold("epd lock <status|release>")}
6400
7261
 
6401
7262
  epd takes a lock on every server while deploying so two deploys cannot overlap.
6402
- 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.`,
6403
7265
  async run(ctx) {
6404
7266
  const { config: cfg, env } = ctx.load();
6405
7267
  await resolveDynamicHosts(cfg, env);
@@ -6413,7 +7275,14 @@ If a deploy was killed halfway, release it by hand.`,
6413
7275
  if (sub !== "status")
6414
7276
  throw new EpdError(`unknown subcommand "${sub}"`, "Try: status, release");
6415
7277
  for (const { host, info } of await DeployLock.status(cfg, hosts)) {
6416
- 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`)}`);
6417
7286
  }
6418
7287
  }
6419
7288
  };
@@ -6477,6 +7346,16 @@ Options
6477
7346
  });
6478
7347
 
6479
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
+ }
6480
7359
  function pretty(args) {
6481
7360
  const out = [];
6482
7361
  let line = "";
@@ -6526,6 +7405,9 @@ Options
6526
7405
  const replicas = ctx.values.replica !== undefined ? [Number(ctx.values.replica)] : Array.from({ length: svc.replicas }, (_, i) => i);
6527
7406
  log.plain(`${c.bold(`# ${svc.name}`)} ${c.gray(`on ${serverHost}, slot ${slot}, version ${version}`)}`);
6528
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
+ `));
6529
7411
  for (const i of replicas) {
6530
7412
  const args = dockerRunArgs({
6531
7413
  cfg,
@@ -6534,11 +7416,13 @@ Options
6534
7416
  version,
6535
7417
  replica: i,
6536
7418
  serverHost,
6537
- envFile: `${paths(cfg).app}/env.${svc.name}`
7419
+ envFile
6538
7420
  });
6539
7421
  log.plain(pretty(args));
6540
7422
  log.plain("");
6541
7423
  }
7424
+ log.plain(`rm -f -- ${shq(envFile)}`);
7425
+ log.plain("");
6542
7426
  } else {
6543
7427
  const command = svc.command ?? cfg.process.start;
6544
7428
  const argv = parseCommand(command);
@@ -6555,6 +7439,9 @@ Options
6555
7439
  if (cfg.accessories.length) {
6556
7440
  for (const acc of cfg.accessories) {
6557
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
+ `));
6558
7445
  const accArgs = [
6559
7446
  "docker",
6560
7447
  "run",
@@ -6572,7 +7459,7 @@ Options
6572
7459
  "--label",
6573
7460
  "epd.managed=true",
6574
7461
  "--env-file",
6575
- `${paths(cfg).app}/env.acc.${acc.name}`,
7462
+ envFile,
6576
7463
  "--log-opt",
6577
7464
  "max-size=10m",
6578
7465
  "--log-opt",
@@ -6585,6 +7472,8 @@ Options
6585
7472
  ];
6586
7473
  log.plain(pretty(accArgs));
6587
7474
  log.plain("");
7475
+ log.plain(`rm -f -- ${shq(envFile)}`);
7476
+ log.plain("");
6588
7477
  }
6589
7478
  }
6590
7479
  log.plain(`${c.bold("# proxy")} ${c.gray("(one per server, shared by every epd app on it)")}`);
@@ -7141,16 +8030,14 @@ class SevallaClient {
7141
8030
  "Content-Type": "application/json",
7142
8031
  ...options.headers
7143
8032
  };
7144
- const res = await fetch(url, { ...options, headers });
7145
- let data;
7146
- try {
7147
- data = await res.json();
7148
- } catch {
7149
- data = null;
7150
- }
8033
+ const res = await fetchWithRetry(url, { ...options, headers }, { timeoutMs: 30000 });
8034
+ const { data, isJson, empty } = await readJsonBody(res);
7151
8035
  if (!res.ok) {
7152
- const msg = data?.message || data?.error?.message || `HTTP ${res.status} ${res.statusText}`;
7153
- 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.");
7154
8041
  }
7155
8042
  return data;
7156
8043
  }
@@ -7202,7 +8089,7 @@ class SevallaClient {
7202
8089
  ];
7203
8090
  }
7204
8091
  const res = await this.request("/applications");
7205
- const list = res.applications || res.data || [];
8092
+ const list = res?.applications || res?.data || [];
7206
8093
  return list.map((a) => ({
7207
8094
  id: a.id,
7208
8095
  name: a.name || a.display_name,
@@ -7236,12 +8123,12 @@ class SevallaClient {
7236
8123
  body: JSON.stringify(opts)
7237
8124
  });
7238
8125
  return {
7239
- id: res.id || res.deployment_id,
8126
+ id: res?.id || res?.deployment_id,
7240
8127
  applicationId: id,
7241
- status: res.status || "deploying",
7242
- commitHash: res.commit_hash,
7243
- commitMessage: res.commit_message,
7244
- 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()
7245
8132
  };
7246
8133
  }
7247
8134
  async listDatabases() {
@@ -7266,7 +8153,7 @@ class SevallaClient {
7266
8153
  ];
7267
8154
  }
7268
8155
  const res = await this.request("/databases");
7269
- const list = res.databases || res.data || [];
8156
+ const list = res?.databases || res?.data || [];
7270
8157
  return list.map((d) => ({
7271
8158
  id: d.id,
7272
8159
  name: d.name,
@@ -7307,15 +8194,15 @@ class SevallaClient {
7307
8194
  body: JSON.stringify(opts)
7308
8195
  });
7309
8196
  return {
7310
- id: res.id,
7311
- name: res.name || opts.name,
7312
- displayName: res.display_name || opts.name,
7313
- type: res.type || opts.type,
7314
- version: res.version || opts.version || "16",
7315
- status: res.status || "creating",
7316
- internalHost: res.internal_host,
7317
- externalHost: res.external_host,
7318
- 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,
7319
8206
  dbName: res.db_name || opts.name,
7320
8207
  dbUser: res.db_user || "admin",
7321
8208
  region: res.region || opts.region,
@@ -7325,6 +8212,7 @@ class SevallaClient {
7325
8212
  }
7326
8213
  var init_api2 = __esm(() => {
7327
8214
  init_log();
8215
+ init_http();
7328
8216
  });
7329
8217
 
7330
8218
  // src/commands/sevalla.ts
@@ -7375,6 +8263,7 @@ Environment
7375
8263
  token = loaded.config.sevalla?.apiToken || loaded.env.SEVALLA_API_TOKEN;
7376
8264
  } catch {}
7377
8265
  token = token || process.env.SEVALLA_API_TOKEN;
8266
+ registerSecret(token);
7378
8267
  const sub = ctx.positionals[0] || "apps";
7379
8268
  if (sub === "auth") {
7380
8269
  log.step("Link your Sevalla Cloud account");
@@ -7482,9 +8371,79 @@ ${c.bold("SEVALLA MANAGED DATABASES")} (${dbs.length})
7482
8371
  });
7483
8372
 
7484
8373
  // src/core/update.ts
7485
- 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";
7486
8376
  import { homedir as homedir4 } from "os";
7487
- 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
+ }
7488
8447
  function isCompiledExecutable(execPath, isBun) {
7489
8448
  return isBun && !["bun", "bun.exe"].includes(basename3(execPath).toLowerCase());
7490
8449
  }
@@ -7510,12 +8469,12 @@ function isNewer(current, latest) {
7510
8469
  return lPatch > cPatch;
7511
8470
  }
7512
8471
  function getCachePath() {
7513
- return join9(homedir4(), ".epd", "update-check.json");
8472
+ return join10(homedir4(), ".epd", "update-check.json");
7514
8473
  }
7515
8474
  function readCache() {
7516
8475
  try {
7517
8476
  const p = getCachePath();
7518
- if (existsSync10(p)) {
8477
+ if (existsSync11(p)) {
7519
8478
  return JSON.parse(readFileSync7(p, "utf8"));
7520
8479
  }
7521
8480
  } catch {}
@@ -7524,7 +8483,7 @@ function readCache() {
7524
8483
  function writeCache(latestVersion) {
7525
8484
  try {
7526
8485
  const p = getCachePath();
7527
- mkdirSync6(dirname3(p), { recursive: true });
8486
+ mkdirSync6(dirname5(p), { recursive: true });
7528
8487
  const data = { lastChecked: Date.now(), latestVersion };
7529
8488
  writeFileSync7(p, JSON.stringify(data));
7530
8489
  } catch {}
@@ -7567,56 +8526,46 @@ async function checkForUpdate(currentVersion, options = {}) {
7567
8526
  return { hasUpdate: false, latestVersion: currentVersion };
7568
8527
  }
7569
8528
  async function performUpdate(targetVersion) {
8529
+ if (targetVersion && !isValidVersion(targetVersion)) {
8530
+ return { ok: false, reason: "failed", message: `Refusing to install invalid version "${targetVersion}".` };
8531
+ }
7570
8532
  const isBun = typeof process.isBun !== "undefined";
7571
8533
  const execPath = process.execPath || "";
7572
8534
  const isCompiledBinary = isCompiledExecutable(execPath, isBun);
7573
- if (isCompiledBinary) {
8535
+ const binaryName = isCompiledBinary ? binaryNameFor(process.platform, process.arch) : null;
8536
+ if (binaryName) {
7574
8537
  try {
7575
- const platform = process.platform;
7576
- const arch = process.arch;
7577
- let binaryName = "";
7578
- if (platform === "linux" && arch === "x64")
7579
- binaryName = "epd-linux-x64";
7580
- else if (platform === "linux" && arch === "arm64")
7581
- binaryName = "epd-linux-arm64";
7582
- else if (platform === "darwin" && arch === "x64")
7583
- binaryName = "epd-darwin-x64";
7584
- else if (platform === "darwin" && arch === "arm64")
7585
- binaryName = "epd-darwin-arm64";
7586
- else if (platform === "win32" && arch === "x64")
7587
- binaryName = "epd-windows-x64.exe";
7588
- if (binaryName) {
7589
- log.step(`Downloading ${binaryName} from GitHub Releases...`);
7590
- const release = targetVersion ? `download/v${targetVersion}` : "latest/download";
7591
- const url = `https://github.com/FabioPlunser/epd/releases/${release}/${binaryName}`;
7592
- const res = await fetch(url);
7593
- if (!res.ok)
7594
- throw new Error(`HTTP ${res.status} ${res.statusText}`);
7595
- const buf = await res.arrayBuffer();
7596
- const tmpPath = `${execPath}.tmp.${Date.now()}`;
7597
- writeFileSync7(tmpPath, Buffer.from(buf));
7598
- chmodSync3(tmpPath, 493);
7599
- renameSync(tmpPath, execPath);
7600
- return true;
7601
- }
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 };
7602
8545
  } catch (e) {
8546
+ if (e instanceof IntegrityError) {
8547
+ return { ok: false, reason: "integrity", message: e.message };
8548
+ }
7603
8549
  log.debug(`Binary self-update failed, falling back to package manager: ${e}`);
7604
8550
  }
7605
8551
  }
7606
8552
  const isBunGlobal = (process.argv[1] || "").includes(".bun");
7607
8553
  const pkgMgr = isBunGlobal ? "bun" : "npm";
7608
- const pkgSpec = targetVersion ? `@fabioplunser/epd@${targetVersion}` : "@fabioplunser/epd@latest";
7609
- 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";
7610
8561
  try {
7611
- log.step(`Updating via ${manager}...`);
7612
- const res = await run(packageUpdateCommand(manager, pkgSpec), { stream: true, allowFailure: true });
7613
- if (res.code === 0)
7614
- return true;
7615
- } catch (error) {
7616
- 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}.` };
7617
8567
  }
7618
8568
  }
7619
- return false;
7620
8569
  }
7621
8570
  async function promptAutoUpdate(currentVersion) {
7622
8571
  if (!interactive() || process.env.CI || process.env.EPD_NO_UPDATE_CHECK === "1" || process.env.EPD_NO_UPDATE_CHECK === "true") {
@@ -7633,26 +8582,38 @@ async function promptAutoUpdate(currentVersion) {
7633
8582
  return false;
7634
8583
  }
7635
8584
  log.step(`Updating epd to v${latestVersion}...`);
7636
- const success = await performUpdate(latestVersion);
7637
- if (success) {
8585
+ const outcome = await performUpdate(latestVersion);
8586
+ if (outcome.ok) {
7638
8587
  log.ok(`Successfully updated epd to ${c.bold(`v${latestVersion}`)}!`);
7639
8588
  console.log("");
7640
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.`);
7641
8593
  } else {
7642
8594
  log.warn(`Auto-update failed. You can update manually with:
7643
8595
  ${c.cyan(`npm install -g @fabioplunser/epd@latest`)}
7644
8596
  `);
7645
- return false;
7646
8597
  }
8598
+ return false;
7647
8599
  }
8600
+ var RELEASE_REPO = "FabioPlunser/epd", CHECKSUM_ASSET = "checksums.sha256", IntegrityError, VERSION_RE;
7648
8601
  var init_update = __esm(() => {
8602
+ init_http();
7649
8603
  init_log();
7650
8604
  init_prompt();
7651
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.-]+)?$/;
7652
8613
  });
7653
8614
 
7654
8615
  // package.json
7655
- var version = "0.5.14";
8616
+ var version = "0.5.15";
7656
8617
  var init_package = () => {};
7657
8618
 
7658
8619
  // src/version.ts
@@ -7695,11 +8656,14 @@ Options
7695
8656
  return;
7696
8657
  }
7697
8658
  log.step(`Upgrading epd to v${latestVersion}...`);
7698
- const success = await performUpdate(latestVersion);
7699
- if (success) {
8659
+ const outcome = await performUpdate(latestVersion);
8660
+ if (outcome.ok) {
7700
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.`);
7701
8664
  } else {
7702
- log.error(`Update failed. You can update manually with:`);
8665
+ log.error(`Update failed. ${outcome.message}`);
8666
+ log.error(`You can update manually with:`);
7703
8667
  console.log(` ${c.cyan("npm install -g @fabioplunser/epd@latest")}
7704
8668
  `);
7705
8669
  }
@@ -7743,8 +8707,8 @@ Saved credentials are stored with 0600 permissions in ~/.config/epd/auth.json`,
7743
8707
  if (sub === "logout") {
7744
8708
  const confirmed = await confirm("Remove all credentials from ~/.config/epd/auth.json?", true);
7745
8709
  if (confirmed) {
7746
- saveGlobalAuth(() => ({}));
7747
- 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)");
7748
8712
  }
7749
8713
  return;
7750
8714
  }
@@ -8421,8 +9385,8 @@ Options
8421
9385
  });
8422
9386
 
8423
9387
  // src/commands/backup.ts
8424
- import { createWriteStream, mkdirSync as mkdirSync7, statSync } from "fs";
8425
- 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";
8426
9390
  function detectAccessoryType(decl, cfg) {
8427
9391
  const name = decl.name;
8428
9392
  const img = (decl.image || "").toLowerCase();
@@ -8530,8 +9494,8 @@ Options
8530
9494
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
8531
9495
  const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
8532
9496
  const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
8533
- const localFile = ctx.values.output ? resolve3(String(ctx.values.output)) : join10(outBaseDir, filename);
8534
- 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 });
8535
9499
  let dumpCmd = "";
8536
9500
  if (target.type === "postgres") {
8537
9501
  dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
@@ -8569,7 +9533,7 @@ Options
8569
9533
  });
8570
9534
  }
8571
9535
  });
8572
- const stats = statSync(localFile);
9536
+ const stats = statSync2(localFile);
8573
9537
  const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
8574
9538
  const elapsed = dur(Date.now() - t0);
8575
9539
  log.ok(`Backed up ${c.bold(target.name)} \u2192 ${c.cyan(localFile)} (${sizeMb} MB in ${elapsed})`);
@@ -8579,7 +9543,7 @@ Options
8579
9543
  });
8580
9544
 
8581
9545
  // src/commands/restore.ts
8582
- import { createReadStream, existsSync as existsSync11 } from "fs";
9546
+ import { createReadStream, existsSync as existsSync12 } from "fs";
8583
9547
  import { basename as basename4, resolve as resolve4 } from "path";
8584
9548
  var restore;
8585
9549
  var init_restore = __esm(() => {
@@ -8607,7 +9571,7 @@ Options
8607
9571
  if (!backupPath)
8608
9572
  throw new EpdError("Please provide a path to the backup file to restore.");
8609
9573
  const absPath = resolve4(backupPath);
8610
- if (!existsSync11(absPath))
9574
+ if (!existsSync12(absPath))
8611
9575
  throw new EpdError(`Backup file not found: ${absPath}`);
8612
9576
  const loaded = ctx.load();
8613
9577
  const cfg = loaded.config;
@@ -8709,9 +9673,9 @@ Options
8709
9673
  });
8710
9674
 
8711
9675
  // src/commands/doctor.ts
8712
- import { existsSync as existsSync12, readdirSync, statSync as statSync2 } from "fs";
9676
+ import { existsSync as existsSync13, readdirSync, statSync as statSync3 } from "fs";
8713
9677
  import { homedir as homedir5 } from "os";
8714
- import { join as join11 } from "path";
9678
+ import { join as join12 } from "path";
8715
9679
  function printResults(results, prefix = " ") {
8716
9680
  for (const r of results) {
8717
9681
  const symbol = r.status === "ok" ? c.green("\u2713") : r.status === "warn" ? c.yellow("!") : c.red("\u2717");
@@ -8726,6 +9690,7 @@ var init_doctor = __esm(() => {
8726
9690
  init_log();
8727
9691
  init_proc();
8728
9692
  init_ssh();
9693
+ init_misc();
8729
9694
  init_names();
8730
9695
  init_resolve();
8731
9696
  doctor = {
@@ -8825,21 +9790,21 @@ Options
8825
9790
  hint: "Install OpenSSH client via your package manager."
8826
9791
  });
8827
9792
  }
8828
- const sshDir = join11(homedir5(), ".ssh");
9793
+ const sshDir = join12(homedir5(), ".ssh");
8829
9794
  if (process.env.SSH_PRIVATE_KEY || process.env.EPD_SSH_KEY) {
8830
9795
  results.push({
8831
9796
  name: "SSH Key (Environment)",
8832
9797
  status: "ok",
8833
9798
  message: "SSH_PRIVATE_KEY is set in the environment (ideal for CI)"
8834
9799
  });
8835
- } else if (existsSync12(sshDir)) {
9800
+ } else if (existsSync13(sshDir)) {
8836
9801
  const keys = readdirSync(sshDir).filter((f) => ["id_ed25519", "id_rsa", "gh_deploy"].includes(f));
8837
9802
  if (keys.length > 0) {
8838
9803
  const keyIssues = [];
8839
9804
  for (const k of keys) {
8840
- const p = join11(sshDir, k);
9805
+ const p = join12(sshDir, k);
8841
9806
  try {
8842
- const st = statSync2(p);
9807
+ const st = statSync3(p);
8843
9808
  const mode = st.mode & 511;
8844
9809
  if (mode !== 384 && mode !== 256) {
8845
9810
  keyIssues.push(`${k} has insecure permissions (${mode.toString(8)} instead of 600)`);
@@ -9000,7 +9965,7 @@ ${c.bold("Remote Servers")}`);
9000
9965
  status: "warn",
9001
9966
  message: `${h.user} requires a password for sudo`,
9002
9967
  hint: `Grant passwordless sudo on ${hostname}:
9003
- echo "${h.user} ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/epd && sudo chmod 440 /etc/sudoers.d/epd`
9968
+ ${sudoersCommand(h.user)}`
9004
9969
  });
9005
9970
  }
9006
9971
  }
@@ -9041,7 +10006,7 @@ ${c.bold("Remote Servers")}`);
9041
10006
  }
9042
10007
  }
9043
10008
  const lockPath = paths(cfg).lock;
9044
- 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 });
9045
10010
  if (lockCheck.stdout.trim() === "locked") {
9046
10011
  results.push({
9047
10012
  name: "Deploy Lock",
@@ -9479,14 +10444,14 @@ try {
9479
10444
  process.exitCode = await main(process.argv.slice(2));
9480
10445
  } catch (error) {
9481
10446
  if (error instanceof EpdError) {
9482
- log.error(error.message);
10447
+ log.error(redact(error.message));
9483
10448
  if (error.hint)
9484
10449
  console.error(`
9485
- ${c.gray(error.hint)}`);
10450
+ ${c.gray(redact(error.hint))}`);
9486
10451
  } else {
9487
10452
  log.error(error instanceof Error ? error.message : String(error));
9488
10453
  if (process.env.EPD_DEBUG && error instanceof Error)
9489
- console.error(error.stack);
10454
+ console.error(redact(error.stack ?? ""));
9490
10455
  }
9491
10456
  process.exitCode = 1;
9492
10457
  }