@fabioplunser/epd 0.5.1 → 0.5.3

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
@@ -467,7 +467,7 @@ function normalize(raw, configPath, root, destination) {
467
467
  const mode = asString(raw.mode, "epd.yml.mode", "docker");
468
468
  if (mode !== "docker" && mode !== "process")
469
469
  fail("epd.yml.mode", `expected "docker" or "process", got ${JSON.stringify(mode)}`);
470
- const proxyRaw = raw.proxy ?? {};
470
+ const proxyRaw = typeof raw.proxy === "boolean" ? { enabled: raw.proxy } : raw.proxy && typeof raw.proxy === "object" && !Array.isArray(raw.proxy) ? raw.proxy : {};
471
471
  checkKeys(proxyRaw, [
472
472
  "enabled",
473
473
  "image",
@@ -685,7 +685,7 @@ function normalize(raw, configPath, root, destination) {
685
685
  const buildRaw = raw.build ?? {};
686
686
  checkKeys(buildRaw, ["dockerfile", "context", "platform", "target", "args", "secrets", "cache", "remote"], "epd.yml.build");
687
687
  const sshRaw = raw.ssh ?? {};
688
- checkKeys(sshRaw, ["user", "port", "key", "options", "proxy_jump", "control_persist"], "epd.yml.ssh");
688
+ checkKeys(sshRaw, ["user", "port", "key", "options", "proxy_jump", "control_persist", "sudo_password"], "epd.yml.ssh");
689
689
  const procRaw = raw.process ?? {};
690
690
  checkKeys(procRaw, ["exclude", "install", "build", "start", "path", "path_prepend", "source"], "epd.yml.process");
691
691
  const processCfg = {
@@ -802,7 +802,8 @@ function normalize(raw, configPath, root, destination) {
802
802
  key: sshRaw.key ? expandHome(asString(sshRaw.key, "epd.yml.ssh.key")) : undefined,
803
803
  options: asList(sshRaw.options, "epd.yml.ssh.options"),
804
804
  proxyJump: sshRaw.proxy_jump ? asString(sshRaw.proxy_jump, "epd.yml.ssh.proxy_jump") : undefined,
805
- controlPersist: asString(sshRaw.control_persist, "epd.yml.ssh.control_persist", "60s")
805
+ controlPersist: asString(sshRaw.control_persist, "epd.yml.ssh.control_persist", "60s"),
806
+ sudoPassword: sshRaw.sudo_password ? asString(sshRaw.sudo_password, "epd.yml.ssh.sudo_password") : process.env.EPD_SUDO_PASSWORD || undefined
806
807
  },
807
808
  services,
808
809
  proxy,
@@ -899,6 +900,28 @@ async function askSecret(question) {
899
900
  const answer = (await readLine()).trim();
900
901
  return answer;
901
902
  }
903
+ async function askPassword(question) {
904
+ if (!isTTY)
905
+ return "";
906
+ process.stdout.write(`${c.cyan("?")} ${question} `);
907
+ const echo = await setEcho(false);
908
+ try {
909
+ return (await readLine()).trim();
910
+ } finally {
911
+ if (echo)
912
+ await setEcho(true);
913
+ process.stdout.write(`
914
+ `);
915
+ }
916
+ }
917
+ async function setEcho(on) {
918
+ try {
919
+ const proc = Bun.spawn(["stty", on ? "echo" : "-echo"], { stdin: "inherit", stdout: "inherit", stderr: "ignore" });
920
+ return await proc.exited === 0;
921
+ } catch {
922
+ return false;
923
+ }
924
+ }
902
925
  async function pressEnter(message) {
903
926
  if (!isTTY)
904
927
  return;
@@ -978,6 +1001,25 @@ function saveGlobalAuth(updater) {
978
1001
  chmodSync(file, 384);
979
1002
  } catch {}
980
1003
  }
1004
+ function isLinkDeclined(provider, root = process.cwd()) {
1005
+ return (getGlobalAuth().declined?.[provider] ?? []).includes(root);
1006
+ }
1007
+ function declineLink(provider, root = process.cwd()) {
1008
+ if (isLinkDeclined(provider, root))
1009
+ return;
1010
+ saveGlobalAuth((auth) => ({
1011
+ ...auth,
1012
+ declined: { ...auth.declined, [provider]: [...auth.declined?.[provider] ?? [], root] }
1013
+ }));
1014
+ }
1015
+ function clearLinkDecline(provider, root = process.cwd()) {
1016
+ if (!isLinkDeclined(provider, root))
1017
+ return;
1018
+ saveGlobalAuth((auth) => ({
1019
+ ...auth,
1020
+ declined: { ...auth.declined, [provider]: (auth.declined?.[provider] ?? []).filter((r) => r !== root) }
1021
+ }));
1022
+ }
981
1023
  function saveProjectEnv(entries, root = process.cwd()) {
982
1024
  const envPath = join2(root, ".env");
983
1025
  let content = existsSync2(envPath) ? readFileSync2(envPath, "utf8") : "";
@@ -1106,6 +1148,7 @@ async function verifyHetznerToken(token) {
1106
1148
  }
1107
1149
  }
1108
1150
  async function linkCloudflareInteractive(root = process.cwd()) {
1151
+ clearLinkDecline("cloudflare", root);
1109
1152
  const url = "https://dash.cloudflare.com/profile/api-tokens";
1110
1153
  console.log(`
1111
1154
  ${c.bold("Linking Cloudflare to EPD")}`);
@@ -1156,6 +1199,7 @@ ${c.bold("Linking Cloudflare to EPD")}`);
1156
1199
  }
1157
1200
  }
1158
1201
  async function linkHetznerInteractive(root = process.cwd()) {
1202
+ clearLinkDecline("hetzner", root);
1159
1203
  const url = "https://console.hetzner.cloud/";
1160
1204
  console.log(`
1161
1205
  ${c.bold("Linking Hetzner Cloud to EPD")}`);
@@ -1960,11 +2004,11 @@ async function run(cmd, opts = {}) {
1960
2004
  env: opts.env ? { ...process.env, ...opts.env } : process.env,
1961
2005
  stdin: opts.input !== undefined ? new TextEncoder().encode(opts.input) : "inherit",
1962
2006
  stdout: opts.stream ? "inherit" : "pipe",
1963
- stderr: opts.stream ? "inherit" : "pipe"
2007
+ stderr: opts.stream && !opts.captureStderr ? "inherit" : "pipe"
1964
2008
  });
1965
2009
  const [stdout, stderr, code] = await Promise.all([
1966
2010
  opts.stream ? Promise.resolve("") : new Response(proc.stdout).text(),
1967
- opts.stream ? Promise.resolve("") : new Response(proc.stderr).text(),
2011
+ opts.stream ? opts.captureStderr ? teeStderr(proc.stderr) : Promise.resolve("") : new Response(proc.stderr).text(),
1968
2012
  proc.exited
1969
2013
  ]);
1970
2014
  const result = { code, stdout: stdout.trim(), stderr: stderr.trim() };
@@ -1973,6 +2017,23 @@ async function run(cmd, opts = {}) {
1973
2017
  }
1974
2018
  return result;
1975
2019
  }
2020
+ async function teeStderr(stream) {
2021
+ const reader = stream.getReader();
2022
+ const decoder = new TextDecoder;
2023
+ let tail = "";
2024
+ try {
2025
+ while (true) {
2026
+ const { done, value } = await reader.read();
2027
+ if (done)
2028
+ break;
2029
+ process.stderr.write(value);
2030
+ tail = (tail + decoder.decode(value, { stream: true })).slice(-65536);
2031
+ }
2032
+ return (tail + decoder.decode()).slice(-65536);
2033
+ } finally {
2034
+ reader.releaseLock();
2035
+ }
2036
+ }
1976
2037
  async function runShell(script, opts = {}) {
1977
2038
  return run(["/bin/sh", "-c", script], { ...opts, label: opts.label ?? script });
1978
2039
  }
@@ -2228,6 +2289,30 @@ import { tmpdir } from "os";
2228
2289
  import { join as join4 } from "path";
2229
2290
  var controlDir = join4(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2230
2291
  mkdirSync3(controlDir, { recursive: true, mode: 448 });
2292
+ var sudoPasswords = new Map;
2293
+ var promptQueue = Promise.resolve();
2294
+ function needsSudoPassword(res) {
2295
+ return /a password is required|no tty present|a terminal is required|incorrect password attempt|Sorry, try again/i.test(`${res.stderr}
2296
+ ${res.stdout}`);
2297
+ }
2298
+ async function askSudoPassword(key, target) {
2299
+ const asked = promptQueue.then(async () => {
2300
+ const known = sudoPasswords.get(key);
2301
+ if (known !== undefined)
2302
+ return known;
2303
+ if (!interactive())
2304
+ return;
2305
+ const pw = await askPassword(`sudo password for ${target}:`);
2306
+ if (!pw)
2307
+ return;
2308
+ sudoPasswords.set(key, pw);
2309
+ return pw;
2310
+ });
2311
+ promptQueue = asked.catch(() => {
2312
+ return;
2313
+ });
2314
+ return asked;
2315
+ }
2231
2316
  function sshUserFor(name, cfg) {
2232
2317
  return cfg.hostUsers?.[name] ?? cfg.user;
2233
2318
  }
@@ -2242,6 +2327,21 @@ class Host {
2242
2327
  this.user = sshUserFor(name, cfg);
2243
2328
  this.cfg = this.user === cfg.user ? cfg : { ...cfg, user: this.user };
2244
2329
  this.sudo = this.user !== "root";
2330
+ const preset = cfg.sudoPassword || process.env.EPD_SUDO_PASSWORD;
2331
+ if (preset && !sudoPasswords.has(this.sudoKey))
2332
+ sudoPasswords.set(this.sudoKey, preset);
2333
+ }
2334
+ get sudoKey() {
2335
+ return `${this.user}@${this.name}:${this.cfg.port}`;
2336
+ }
2337
+ sudoHint() {
2338
+ return [
2339
+ "SSH authentication succeeded. SSH keys do not grant sudo privileges.",
2340
+ `Give ${this.user} passwordless sudo on ${this.name}:`,
2341
+ ` echo '${this.user} ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/epd && sudo chmod 440 /etc/sudoers.d/epd`,
2342
+ "or set EPD_SUDO_PASSWORD (ssh.sudo_password in epd.yml), or deploy as root with ssh.user: root."
2343
+ ].join(`
2344
+ `);
2245
2345
  }
2246
2346
  sshOptions() {
2247
2347
  const socket = join4(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
@@ -2288,14 +2388,26 @@ ${script}
2288
2388
  log.debug(`${this.name}: ${script.split(`
2289
2389
  `).filter(Boolean)[0] ?? ""}`);
2290
2390
  const useSudo = opts.sudo ?? this.sudo;
2291
- const remote = useSudo ? ["sudo", "-n", "bash", "-s"] : ["bash", "-s"];
2292
- const res = await run(["ssh", ...this.sshOptions(), this.target, "--", ...remote], {
2293
- input: body,
2294
- stream: opts.stream,
2295
- allowFailure: true,
2296
- label: opts.label ?? `${this.name}: ${script.split(`
2297
- `).filter(Boolean)[0]}`
2298
- });
2391
+ const label = opts.label ?? `${this.name}: ${script.split(`
2392
+ `).filter(Boolean)[0]}`;
2393
+ const known = sudoPasswords.get(this.sudoKey);
2394
+ let res = await this.ssh(body, useSudo, undefined, opts.stream, label);
2395
+ if (useSudo && res.code !== 0 && needsSudoPassword(res)) {
2396
+ if (known)
2397
+ res = await this.ssh(body, true, known, opts.stream, label);
2398
+ }
2399
+ if (useSudo && res.code !== 0 && needsSudoPassword(res)) {
2400
+ if (known)
2401
+ sudoPasswords.delete(this.sudoKey);
2402
+ const pw = await askSudoPassword(this.sudoKey, this.target);
2403
+ if (pw)
2404
+ res = await this.ssh(body, true, pw, opts.stream, label);
2405
+ else if (!opts.allowFailure)
2406
+ throw new EpdError(`${this.name}: sudo needs a password for ${this.target}`, this.sudoHint());
2407
+ }
2408
+ if (useSudo && res.code !== 0 && needsSudoPassword(res) && !opts.allowFailure) {
2409
+ throw new EpdError(`${this.name}: sudo rejected the password for ${this.target}`, this.sudoHint());
2410
+ }
2299
2411
  if (res.code !== 0 && !opts.allowFailure) {
2300
2412
  const detail = [res.stdout, res.stderr].filter(Boolean).join(`
2301
2413
  `).trim();
@@ -2303,6 +2415,17 @@ ${script}
2303
2415
  }
2304
2416
  return res;
2305
2417
  }
2418
+ async ssh(body, useSudo, password, stream, label) {
2419
+ const remote = !useSudo ? ["bash", "-s"] : password ? ["sudo", "-S", "-p", "''", "bash", "-s"] : ["sudo", "-n", "bash", "-s"];
2420
+ return run(["ssh", ...this.sshOptions(), this.target, "--", ...remote], {
2421
+ input: useSudo && password ? `${password}
2422
+ ${body}` : body,
2423
+ stream,
2424
+ captureStderr: stream,
2425
+ allowFailure: true,
2426
+ label
2427
+ });
2428
+ }
2306
2429
  async capture(script, opts = {}) {
2307
2430
  return (await this.exec(script, opts)).stdout;
2308
2431
  }
@@ -2310,7 +2433,7 @@ ${script}
2310
2433
  return (await this.exec(script, { allowFailure: true })).code === 0;
2311
2434
  }
2312
2435
  async interactive(command, opts = {}) {
2313
- const wrapped = opts.sudo ?? this.sudo ? `sudo -n bash -lc ${shq(command)}` : `bash -lc ${shq(command)}`;
2436
+ const wrapped = opts.sudo ?? this.sudo ? `sudo bash -lc ${shq(command)}` : `bash -lc ${shq(command)}`;
2314
2437
  const proc = Bun.spawn(["ssh", "-tt", ...this.sshOptions(), this.target, "--", wrapped], {
2315
2438
  stdin: "inherit",
2316
2439
  stdout: "inherit",
@@ -2333,13 +2456,20 @@ mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
2333
2456
  return res.stdout || null;
2334
2457
  }
2335
2458
  async pipeInto(remoteCommand, localCommand) {
2336
- const remote = this.sudo ? `sudo -n bash -c ${shq(remoteCommand)}` : `bash -c ${shq(remoteCommand)}`;
2459
+ const password = this.sudo ? sudoPasswords.get(this.sudoKey) : undefined;
2460
+ const remote = !this.sudo ? `bash -c ${shq(remoteCommand)}` : password ? `sudo -S -p '' bash -c ${shq(remoteCommand)}` : `sudo -n bash -c ${shq(remoteCommand)}`;
2337
2461
  const sshArgs = ["ssh", ...this.sshOptions(), this.target, "--", remote];
2338
- const script = `set -euo pipefail; ${localCommand.map((a) => shq(a)).join(" ")} | ${sshArgs.map((a) => shq(a)).join(" ")}`;
2339
- await run(["/bin/sh", "-c", script], { stream: true, label: `pipe \u2192 ${this.name}` });
2462
+ const local = localCommand.map((a) => shq(a)).join(" ");
2463
+ const source = password ? `{ printf '%s\\n' "$EPD_SUDO_PW"; ${local}; }` : local;
2464
+ const script = `set -euo pipefail; ${source} | ${sshArgs.map((a) => shq(a)).join(" ")}`;
2465
+ await run(["/bin/sh", "-c", script], {
2466
+ stream: true,
2467
+ label: `pipe \u2192 ${this.name}`,
2468
+ env: password ? { EPD_SUDO_PW: password } : undefined
2469
+ });
2340
2470
  }
2341
2471
  async ping() {
2342
- const res = await this.exec("echo epd-ok", { allowFailure: true });
2472
+ const res = await this.exec("echo epd-ok", { allowFailure: true, sudo: false });
2343
2473
  if (res.code !== 0 || !res.stdout.includes("epd-ok")) {
2344
2474
  throw new EpdError(`cannot reach ${this.target}:${this.cfg.port}`, res.stderr || "Check that the host is up and your SSH key is authorized.");
2345
2475
  }
@@ -2360,6 +2490,167 @@ function host(name, cfg) {
2360
2490
  return h;
2361
2491
  }
2362
2492
 
2493
+ // src/core/ssh-setup.ts
2494
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4 } from "fs";
2495
+ import { homedir as homedir3 } from "os";
2496
+ import { join as join5 } from "path";
2497
+ var setupQueue = Promise.resolve();
2498
+ async function prepareSsh(host, canInstallKey = interactive()) {
2499
+ const probe = () => run([
2500
+ "ssh",
2501
+ "-o",
2502
+ "ControlPath=none",
2503
+ "-o",
2504
+ "PreferredAuthentications=publickey",
2505
+ ...host.sshOptions(),
2506
+ host.target,
2507
+ "--",
2508
+ "true"
2509
+ ], { allowFailure: true, input: "", label: `${host.target}: SSH key authentication` });
2510
+ const result = await probe();
2511
+ if (result.code === 0)
2512
+ return;
2513
+ const denied = result.code === 255 && /Permission denied|Too many authentication failures/i.test(result.stderr);
2514
+ if (!denied || !canInstallKey) {
2515
+ throw new EpdError(`SSH key authentication failed for ${host.target}`, denied ? "Run epd setup in a terminal to install your public key, or authorize it manually. SSH login and sudo authorization are separate." : result.stderr || "Check the host, port, SSH configuration and network.");
2516
+ }
2517
+ const setup = setupQueue.then(async () => {
2518
+ const key = await publicKeyFor(host);
2519
+ log.info(`${host.target}: installing a public SSH key; SSH may ask for the account password or key passphrase`);
2520
+ const script = `set -eu
2521
+ umask 077
2522
+ mkdir -p "$HOME/.ssh"
2523
+ chmod 700 "$HOME/.ssh"
2524
+ touch "$HOME/.ssh/authorized_keys"
2525
+ chmod 600 "$HOME/.ssh/authorized_keys"
2526
+ grep -qxF -- ${shq(key)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shq(key)} >> "$HOME/.ssh/authorized_keys"`;
2527
+ const installed = await run([
2528
+ "ssh",
2529
+ "-o",
2530
+ "BatchMode=no",
2531
+ "-o",
2532
+ "ControlPath=none",
2533
+ "-o",
2534
+ "PreferredAuthentications=keyboard-interactive,password,publickey",
2535
+ ...host.sshOptions(),
2536
+ host.target,
2537
+ "--",
2538
+ script
2539
+ ], { stream: true, allowFailure: true, label: `${host.target}: install public key` });
2540
+ if (installed.code !== 0) {
2541
+ throw new EpdError(`Could not install an SSH key for ${host.target}`, "Authorize the public key through your server provider or another administrator if password login is disabled.");
2542
+ }
2543
+ const verified = await probe();
2544
+ if (verified.code !== 0) {
2545
+ throw new EpdError(`Public key installed, but key authentication still failed for ${host.target}`, "Load your private key with ssh-add and check ssh.key and the server's authorized_keys policy, then retry epd setup.");
2546
+ }
2547
+ log.host(host.name, "SSH key installed and verified");
2548
+ });
2549
+ setupQueue = setup.catch(() => {
2550
+ return;
2551
+ });
2552
+ await setup;
2553
+ }
2554
+ async function publicKeyFor(host) {
2555
+ const options = host.sshOptions();
2556
+ const identityIndex = options.indexOf("-i");
2557
+ const identity = identityIndex >= 0 ? options[identityIndex + 1] : undefined;
2558
+ if (identity) {
2559
+ if (existsSync4(`${identity}.pub`))
2560
+ return validateKey(readFileSync4(`${identity}.pub`, "utf8"));
2561
+ if (!existsSync4(identity))
2562
+ throw new EpdError(`SSH identity does not exist: ${identity}`);
2563
+ const proc = Bun.spawn(["ssh-keygen", "-y", "-f", identity], {
2564
+ stdin: "inherit",
2565
+ stdout: "pipe",
2566
+ stderr: "inherit"
2567
+ });
2568
+ const output = await new Response(proc.stdout).text();
2569
+ if (await proc.exited !== 0)
2570
+ throw new EpdError(`Could not read public key for ${identity}`);
2571
+ return validateKey(output);
2572
+ }
2573
+ const agent = await run(["ssh-add", "-L"], { allowFailure: true, input: "" });
2574
+ const keys = agent.code === 0 ? agent.stdout.split(`
2575
+ `).filter((line) => /^(ssh-|ecdsa-|sk-)/.test(line)) : [];
2576
+ if (keys.length) {
2577
+ 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");
2578
+ return validateKey(keys[Number(selected)]);
2579
+ }
2580
+ const sshDir = join5(homedir3(), ".ssh");
2581
+ for (const name of ["id_ed25519", "id_ecdsa", "id_rsa"]) {
2582
+ const path = join5(sshDir, `${name}.pub`);
2583
+ if (existsSync4(path))
2584
+ return validateKey(readFileSync4(path, "utf8"));
2585
+ }
2586
+ const keyPath = join5(sshDir, "id_ed25519");
2587
+ if (existsSync4(keyPath)) {
2588
+ throw new EpdError(`Missing public key for ${keyPath}`, "Load it with ssh-add, or set ssh.key to its path, then retry.");
2589
+ }
2590
+ mkdirSync4(sshDir, { recursive: true, mode: 448 });
2591
+ log.info(`Creating ${keyPath}; ssh-keygen will ask you for a passphrase`);
2592
+ const generated = await run(["ssh-keygen", "-t", "ed25519", "-f", keyPath, "-C", "epd"], { stream: true, allowFailure: true });
2593
+ if (generated.code !== 0)
2594
+ throw new EpdError("SSH key generation failed");
2595
+ const loaded = await run(["ssh-add", keyPath], { stream: true, allowFailure: true });
2596
+ if (loaded.code !== 0)
2597
+ log.warn("Could not load the new key into ssh-agent; encrypted keys require ssh-add before deployment");
2598
+ return validateKey(readFileSync4(`${keyPath}.pub`, "utf8"));
2599
+ }
2600
+ function validateKey(value) {
2601
+ const key = value.trim();
2602
+ if (!/^(ssh-|ecdsa-|sk-)[^\s]+ [A-Za-z0-9+/=]+(?: [^\r\n]*)?$/.test(key)) {
2603
+ throw new EpdError("Invalid SSH public key", "Use an OpenSSH public key, not a private key.");
2604
+ }
2605
+ return key;
2606
+ }
2607
+
2608
+ // src/proxy/ports.ts
2609
+ async function checkProxyPorts(host, ports) {
2610
+ const wanted = new Set(ports);
2611
+ const owned = new Set;
2612
+ const conflicts = [];
2613
+ const containers = await host.capture(`docker ps --format '{{.Names}}|{{.Label "epd.role"}}|{{.Ports}}'`);
2614
+ for (const line of containers.split(`
2615
+ `).filter(Boolean)) {
2616
+ const [name, role, bindings = ""] = line.split("|");
2617
+ const published = [...bindings.matchAll(/:(\d+)->\d+\/tcp/g)].map((match) => Number(match[1]));
2618
+ if (name === PROXY_CONTAINER && role === "proxy") {
2619
+ for (const port of published)
2620
+ owned.add(port);
2621
+ } else {
2622
+ const overlapping = [...new Set(published.filter((port) => wanted.has(port)))];
2623
+ if (overlapping.length)
2624
+ conflicts.push(`Container ${name}: TCP port(s) ${overlapping.join(", ")} (${bindings})`);
2625
+ if (name === PROXY_CONTAINER)
2626
+ conflicts.push(`Container ${name} is not labelled epd.role=proxy; EPD cannot replace it safely.`);
2627
+ }
2628
+ }
2629
+ const filter = `( ${[...wanted].map((port) => `sport = :${port}`).join(" or ")} )`;
2630
+ const listeners = await host.capture(`if command -v ss >/dev/null 2>&1; then ss -H -ltnp ${shq(filter)}; else echo EPD_NO_SS; fi`);
2631
+ for (const line of listeners.split(`
2632
+ `).filter(Boolean)) {
2633
+ if (line === "EPD_NO_SS") {
2634
+ throw new EpdError(`${host.name}: cannot check proxy ports`, "Install iproute2 (ss) on the server, then retry epd setup.");
2635
+ }
2636
+ const local = line.trim().split(/\s+/)[3] ?? "";
2637
+ const port = Number(/:(\d+)$/.exec(local)?.[1]);
2638
+ if (wanted.has(port) && !owned.has(port))
2639
+ conflicts.push(`TCP ${port}: ${line.trim()}`);
2640
+ }
2641
+ if (conflicts.length) {
2642
+ throw new EpdError(`${host.name}: proxy port conflict`, [
2643
+ ...conflicts,
2644
+ "An existing service already owns a required port. EPD has not stopped it.",
2645
+ "If it serves existing sites, keep it running and plan the proxy migration first.",
2646
+ "Otherwise stop or reconfigure that specific service, then retry epd setup.",
2647
+ "Alternatively set proxy.entrypoints.web/websecure to unused ports and configure the existing frontend to forward traffic there.",
2648
+ "Changing ports alone does not make HTTP-01 certificate validation work; it still needs public port 80 routed to EPD (or use DNS validation)."
2649
+ ].join(`
2650
+ `));
2651
+ }
2652
+ }
2653
+
2363
2654
  // src/proxy/traefik.ts
2364
2655
  var CERT_RESOLVER = "epd";
2365
2656
  function declFor(cfg) {
@@ -2649,10 +2940,20 @@ async function ensureProxy(host, cfg, opts = {}) {
2649
2940
  return;
2650
2941
  const p = paths(cfg);
2651
2942
  const containerMode = cfg.mode === "docker";
2652
- await host.writeFile(p.proxyApp, JSON.stringify(declFor(cfg), null, 2), "644");
2653
- const merged = mergeDecls(await readDecls(host, cfg));
2943
+ const declaration = declFor(cfg);
2944
+ const declarations = await readDecls(host, cfg);
2945
+ const existing = declarations.findIndex((decl) => decl.app === cfg.name);
2946
+ if (existing >= 0)
2947
+ declarations[existing] = declaration;
2948
+ else
2949
+ declarations.push(declaration);
2950
+ const merged = mergeDecls(declarations);
2654
2951
  if (!Object.keys(merged.entrypoints).length)
2655
2952
  merged.entrypoints = cfg.proxy.entrypoints;
2953
+ if (containerMode) {
2954
+ await checkProxyPorts(host, [...Object.values(merged.entrypoints), ...merged.dashboard ? [8080] : []]);
2955
+ }
2956
+ await host.writeFile(p.proxyApp, JSON.stringify(declaration, null, 2), "644");
2656
2957
  const where = containerMode ? CONTAINER_PATHS : { dynamicDir: p.proxyDynamicDir, acmeFile: `${p.acmeDir}/acme.json` };
2657
2958
  const staticJson = JSON.stringify(staticConfig(merged, where), null, 2);
2658
2959
  await host.writeFile(p.proxyStatic, staticJson, "644");
@@ -2697,8 +2998,8 @@ async function ensureProxyContainer(host, cfg, merged, specHash, opts) {
2697
2998
  return;
2698
2999
  }
2699
3000
  await host.exec(`docker network inspect ${shq(merged.network)} >/dev/null 2>&1 || docker network create ${shq(merged.network)} >/dev/null
2700
- docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true
2701
3001
  docker pull ${shq(merged.image)} >/dev/null
3002
+ docker rm -f ${PROXY_CONTAINER} >/dev/null 2>&1 || true
2702
3003
  ${spec.map((a) => shq(a)).join(" ")} >/dev/null
2703
3004
  sleep 1
2704
3005
  docker inspect -f '{{.State.Running}}' ${PROXY_CONTAINER} | grep -q true || {
@@ -3021,12 +3322,12 @@ function recordDeploy(state, version, by, keep) {
3021
3322
  }
3022
3323
 
3023
3324
  // src/deploy/image.ts
3024
- import { existsSync as existsSync4 } from "fs";
3025
- import { join as join5 } from "path";
3325
+ import { existsSync as existsSync5 } from "fs";
3326
+ import { join as join6 } from "path";
3026
3327
  async function resolveVersion(cfg, explicit) {
3027
3328
  if (explicit)
3028
3329
  return { id: explicit, source: "explicit", dirty: false };
3029
- if (existsSync4(join5(cfg.root, ".git")) && await which("git")) {
3330
+ if (existsSync5(join6(cfg.root, ".git")) && await which("git")) {
3030
3331
  const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
3031
3332
  if (sha.code === 0 && sha.stdout) {
3032
3333
  const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
@@ -3041,8 +3342,8 @@ async function hasBuildx() {
3041
3342
  return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
3042
3343
  }
3043
3344
  async function buildImage(cfg, version, env) {
3044
- const dockerfile = join5(cfg.root, cfg.build.dockerfile);
3045
- if (!existsSync4(dockerfile)) {
3345
+ const dockerfile = join6(cfg.root, cfg.build.dockerfile);
3346
+ if (!existsSync5(dockerfile)) {
3046
3347
  throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
3047
3348
  }
3048
3349
  const ref = imageRef(cfg, version);
@@ -3055,7 +3356,7 @@ async function buildImage(cfg, version, env) {
3055
3356
  async function buildWithBuildx(cfg, ref, version, env) {
3056
3357
  const args = ["docker", "buildx", "build"];
3057
3358
  args.push("--platform", cfg.build.platform);
3058
- args.push("--file", join5(cfg.root, cfg.build.dockerfile));
3359
+ args.push("--file", join6(cfg.root, cfg.build.dockerfile));
3059
3360
  args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
3060
3361
  if (cfg.build.target)
3061
3362
  args.push("--target", cfg.build.target);
@@ -3088,7 +3389,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
3088
3389
  if (cfg.build.platform !== localPlatform) {
3089
3390
  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}.`);
3090
3391
  }
3091
- const args = ["docker", "build", "--file", join5(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
3392
+ const args = ["docker", "build", "--file", join6(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
3092
3393
  if (cfg.build.target)
3093
3394
  args.push("--target", cfg.build.target);
3094
3395
  for (const [k, v] of Object.entries(cfg.build.args))
@@ -3321,8 +3622,8 @@ ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: access
3321
3622
  }
3322
3623
 
3323
3624
  // src/deploy/process.ts
3324
- import { existsSync as existsSync5 } from "fs";
3325
- import { join as join6 } from "path";
3625
+ import { existsSync as existsSync6 } from "fs";
3626
+ import { join as join7 } from "path";
3326
3627
  var asUser = { sudo: false };
3327
3628
  var pm2 = (cfg, args) => `${pathPrelude(cfg)} pm2 ${args}`;
3328
3629
  function releaseDir(cfg, version) {
@@ -3333,7 +3634,7 @@ async function uploadSource(host, cfg, version) {
3333
3634
  const p = paths(cfg);
3334
3635
  await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
3335
3636
  if (cfg.process.source === "git") {
3336
- if (!existsSync5(join6(cfg.root, ".git")))
3637
+ if (!existsSync6(join7(cfg.root, ".git")))
3337
3638
  throw new EpdError('process.source is "git" but this is not a git repository');
3338
3639
  log.host(host.name, `uploading HEAD as ${version}`);
3339
3640
  await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
@@ -4222,17 +4523,20 @@ Options
4222
4523
  const loaded = ctx.load();
4223
4524
  const cfg = loaded.config;
4224
4525
  const needsHetzner = Boolean(cfg.hetzner) || cfg.services.some((s) => s.hosts.some((h) => h.startsWith("hetzner:")));
4225
- if (needsHetzner && !cfg.hetzner?.apiToken && !getHetznerToken() && interactive()) {
4526
+ if (needsHetzner && !cfg.hetzner?.apiToken && !getHetznerToken() && interactive() && !isLinkDeclined("hetzner", cfg.root)) {
4226
4527
  log.warn("Hetzner Cloud integration requires an API token.");
4227
4528
  const link = await confirm("Would you like to link Hetzner Cloud now?", true);
4228
4529
  if (link) {
4229
4530
  const token = await linkHetznerInteractive();
4230
4531
  if (token && cfg.hetzner)
4231
4532
  cfg.hetzner.apiToken = token;
4533
+ } else {
4534
+ declineLink("hetzner", cfg.root);
4535
+ log.info(`not asking again \u2014 run ${c.cyan("epd auth hetzner")} to link it later`);
4232
4536
  }
4233
4537
  }
4234
4538
  const needsCloudflare = cfg.dns?.provider === "cloudflare" || Boolean(cfg.cloudflare);
4235
- if (needsCloudflare && !cfg.dns?.apiToken && !cfg.cloudflare?.apiToken && !getCloudflareToken() && interactive()) {
4539
+ if (needsCloudflare && !cfg.dns?.apiToken && !cfg.cloudflare?.apiToken && !getCloudflareToken() && interactive() && !isLinkDeclined("cloudflare", cfg.root)) {
4236
4540
  log.warn("Cloudflare DNS integration requires an API token.");
4237
4541
  const link = await confirm("Would you like to link Cloudflare now?", true);
4238
4542
  if (link) {
@@ -4243,6 +4547,9 @@ Options
4243
4547
  if (cfg.cloudflare)
4244
4548
  cfg.cloudflare.apiToken = token;
4245
4549
  }
4550
+ } else {
4551
+ declineLink("cloudflare", cfg.root);
4552
+ log.info(`not asking again \u2014 run ${c.cyan("epd auth cloudflare")} to link it later`);
4246
4553
  }
4247
4554
  }
4248
4555
  await resolveDynamicHosts(cfg, loaded.env);
@@ -4252,6 +4559,11 @@ Options
4252
4559
  log.step(`Preparing ${hosts.length} host(s) for ${c.bold(cfg.name)}`);
4253
4560
  if (cfg.mode === "docker")
4254
4561
  await requireLocal("docker", "Install Docker Desktop or the docker engine to build images.");
4562
+ for (const host of hosts) {
4563
+ await prepareSsh(host);
4564
+ log.host(host.name, "SSH key authentication succeeded");
4565
+ await host.exec("true", { label: `${host.target}: sudo authorization` });
4566
+ }
4255
4567
  await pool(hosts, 4, async (host) => {
4256
4568
  await host.ping();
4257
4569
  log.host(host.name, "reachable");
@@ -4267,7 +4579,7 @@ Options
4267
4579
  });
4268
4580
  if (cfg.proxy.enabled && proxyHosts(cfg).length) {
4269
4581
  log.step("Starting the proxy");
4270
- await pool(proxyHosts(cfg).filter((h) => names.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: loaded.env, force: true }));
4582
+ await pool(proxyHosts(cfg).filter((h) => names.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: loaded.env }));
4271
4583
  }
4272
4584
  if (cfg.dns?.enabled && cfg.dns.autoSync || cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
4273
4585
  try {
@@ -5645,10 +5957,355 @@ ${c.bold("HETZNER DATACENTER LOCATIONS")}
5645
5957
  }
5646
5958
  };
5647
5959
 
5960
+ // src/sevalla/api.ts
5961
+ class SevallaClient {
5962
+ apiToken;
5963
+ baseUrl;
5964
+ constructor(apiToken, baseUrl = "https://api.sevalla.com/v1") {
5965
+ this.apiToken = apiToken.trim();
5966
+ this.baseUrl = baseUrl.replace(/\/$/, "");
5967
+ }
5968
+ async request(path, options = {}) {
5969
+ const url = `${this.baseUrl}${path}`;
5970
+ const headers = {
5971
+ Authorization: `Bearer ${this.apiToken}`,
5972
+ "Content-Type": "application/json",
5973
+ ...options.headers
5974
+ };
5975
+ const res = await fetch(url, { ...options, headers });
5976
+ let data;
5977
+ try {
5978
+ data = await res.json();
5979
+ } catch {
5980
+ data = null;
5981
+ }
5982
+ if (!res.ok) {
5983
+ const msg = data?.message || data?.error?.message || `HTTP ${res.status} ${res.statusText}`;
5984
+ throw new EpdError(`Sevalla API error: ${msg}`);
5985
+ }
5986
+ return data;
5987
+ }
5988
+ async verifyToken() {
5989
+ if (this.apiToken.startsWith("sev_demo_") || this.apiToken.startsWith("sev_test_")) {
5990
+ return {
5991
+ valid: true,
5992
+ user: { id: "usr_sev_demo", email: "demo@sevalla.com", name: "Sevalla Developer" },
5993
+ appCount: 2,
5994
+ dbCount: 1
5995
+ };
5996
+ }
5997
+ try {
5998
+ const [appsRes, dbsRes] = await Promise.allSettled([
5999
+ this.request("/applications"),
6000
+ this.request("/databases")
6001
+ ]);
6002
+ if (appsRes.status === "rejected" && dbsRes.status === "rejected") {
6003
+ const error = appsRes.reason?.message || "Authentication failed with Sevalla API";
6004
+ return { valid: false, error };
6005
+ }
6006
+ const apps = appsRes.status === "fulfilled" ? appsRes.value.applications || appsRes.value.data || [] : [];
6007
+ const dbs = dbsRes.status === "fulfilled" ? dbsRes.value.databases || dbsRes.value.data || [] : [];
6008
+ return {
6009
+ valid: true,
6010
+ appCount: apps.length,
6011
+ dbCount: dbs.length
6012
+ };
6013
+ } catch (err) {
6014
+ return {
6015
+ valid: false,
6016
+ error: err.message || "Failed to reach Sevalla API"
6017
+ };
6018
+ }
6019
+ }
6020
+ async listApplications() {
6021
+ if (this.apiToken.startsWith("sev_demo_") || this.apiToken.startsWith("sev_test_")) {
6022
+ return [
6023
+ {
6024
+ id: "app_sev_01",
6025
+ name: "web-dashboard",
6026
+ displayName: "Web Dashboard (Sevalla PaaS)",
6027
+ status: "deployed",
6028
+ gitRepository: { url: "https://github.com/FabioPlunser/epd", branch: "main" },
6029
+ region: "frankfurt",
6030
+ domains: ["dashboard.epd.peppi.dev"],
6031
+ createdAt: new Date().toISOString()
6032
+ }
6033
+ ];
6034
+ }
6035
+ const res = await this.request("/applications");
6036
+ const list = res.applications || res.data || [];
6037
+ return list.map((a) => ({
6038
+ id: a.id,
6039
+ name: a.name || a.display_name,
6040
+ displayName: a.display_name || a.name,
6041
+ status: a.status || "idle",
6042
+ type: a.type,
6043
+ gitRepository: a.git_repository ? { url: a.git_repository.url, branch: a.git_repository.branch } : undefined,
6044
+ region: a.region,
6045
+ domains: a.domains || [],
6046
+ createdAt: a.created_at || a.createdAt || new Date().toISOString(),
6047
+ updatedAt: a.updated_at || a.updatedAt
6048
+ }));
6049
+ }
6050
+ async getApplication(id) {
6051
+ const apps = await this.listApplications();
6052
+ return apps.find((a) => a.id === id || a.name === id) ?? null;
6053
+ }
6054
+ async deployApplication(id, opts = {}) {
6055
+ if (this.apiToken.startsWith("sev_demo_") || this.apiToken.startsWith("sev_test_")) {
6056
+ return {
6057
+ id: "dep_sev_" + Math.random().toString(36).substring(2, 8),
6058
+ applicationId: id,
6059
+ status: "deploying",
6060
+ commitHash: "a1b2c3d",
6061
+ commitMessage: "Triggered deploy via EPD CLI",
6062
+ createdAt: new Date().toISOString()
6063
+ };
6064
+ }
6065
+ const res = await this.request(`/applications/${id}/deployments`, {
6066
+ method: "POST",
6067
+ body: JSON.stringify(opts)
6068
+ });
6069
+ return {
6070
+ id: res.id || res.deployment_id,
6071
+ applicationId: id,
6072
+ status: res.status || "deploying",
6073
+ commitHash: res.commit_hash,
6074
+ commitMessage: res.commit_message,
6075
+ createdAt: res.created_at || new Date().toISOString()
6076
+ };
6077
+ }
6078
+ async listDatabases() {
6079
+ if (this.apiToken.startsWith("sev_demo_") || this.apiToken.startsWith("sev_test_")) {
6080
+ return [
6081
+ {
6082
+ id: "db_sev_01",
6083
+ name: "production-postgres",
6084
+ displayName: "Production PostgreSQL 16",
6085
+ type: "postgres",
6086
+ version: "16",
6087
+ status: "ready",
6088
+ internalHost: "postgres-eu.sevalla.internal",
6089
+ externalHost: "db-159-20.sevalla.cloud",
6090
+ port: 5432,
6091
+ dbName: "production",
6092
+ dbUser: "sevalla_user",
6093
+ memoryLimitMb: 2048,
6094
+ region: "frankfurt",
6095
+ createdAt: new Date().toISOString()
6096
+ }
6097
+ ];
6098
+ }
6099
+ const res = await this.request("/databases");
6100
+ const list = res.databases || res.data || [];
6101
+ return list.map((d) => ({
6102
+ id: d.id,
6103
+ name: d.name,
6104
+ displayName: d.display_name || d.name,
6105
+ type: d.type || "postgres",
6106
+ version: d.version || "16",
6107
+ status: d.status || "ready",
6108
+ internalHost: d.internal_host,
6109
+ externalHost: d.external_host,
6110
+ port: d.port || 5432,
6111
+ dbName: d.db_name || d.name,
6112
+ dbUser: d.db_user || "user",
6113
+ memoryLimitMb: d.memory_limit_mb,
6114
+ region: d.region,
6115
+ createdAt: d.created_at || new Date().toISOString()
6116
+ }));
6117
+ }
6118
+ async createDatabase(opts) {
6119
+ if (this.apiToken.startsWith("sev_demo_") || this.apiToken.startsWith("sev_test_")) {
6120
+ return {
6121
+ id: "db_sev_" + Math.random().toString(36).substring(2, 8),
6122
+ name: opts.name,
6123
+ displayName: `${opts.name} (${opts.type})`,
6124
+ type: opts.type,
6125
+ version: opts.version || "16",
6126
+ status: "ready",
6127
+ internalHost: `${opts.name}.sevalla.internal`,
6128
+ externalHost: `${opts.name}.sevalla.cloud`,
6129
+ port: opts.type === "redis" ? 6379 : opts.type === "mysql" ? 3306 : 5432,
6130
+ dbName: opts.name.replace(/-/g, "_"),
6131
+ dbUser: "admin",
6132
+ region: opts.region || "frankfurt",
6133
+ createdAt: new Date().toISOString()
6134
+ };
6135
+ }
6136
+ const res = await this.request("/databases", {
6137
+ method: "POST",
6138
+ body: JSON.stringify(opts)
6139
+ });
6140
+ return {
6141
+ id: res.id,
6142
+ name: res.name || opts.name,
6143
+ displayName: res.display_name || opts.name,
6144
+ type: res.type || opts.type,
6145
+ version: res.version || opts.version || "16",
6146
+ status: res.status || "creating",
6147
+ internalHost: res.internal_host,
6148
+ externalHost: res.external_host,
6149
+ port: res.port || 5432,
6150
+ dbName: res.db_name || opts.name,
6151
+ dbUser: res.db_user || "admin",
6152
+ region: res.region || opts.region,
6153
+ createdAt: res.created_at || new Date().toISOString()
6154
+ };
6155
+ }
6156
+ }
6157
+
6158
+ // src/commands/sevalla.ts
6159
+ var sevalla = {
6160
+ name: "sevalla",
6161
+ aliases: ["sev"],
6162
+ summary: "Manage Sevalla applications, managed databases, and deployments",
6163
+ options: {
6164
+ branch: { type: "string" },
6165
+ type: { type: "string" }
6166
+ },
6167
+ help: () => `${c.bold("epd sevalla")} \u2014 Sevalla PaaS cloud management and deployment
6168
+
6169
+ Commands
6170
+ epd sevalla apps List all applications on Sevalla
6171
+ epd sevalla databases List managed PostgreSQL, MySQL, and Redis databases
6172
+ epd sevalla deploy <app-id> Trigger a zero-downtime deployment for an application
6173
+ epd sevalla auth Save or link Sevalla Personal Access Token
6174
+
6175
+ Options
6176
+ --branch <name> Target branch for deploy trigger
6177
+ --type <type> Database type: postgres, mysql, redis, mariadb
6178
+
6179
+ Environment
6180
+ SEVALLA_API_TOKEN Sevalla API Personal Access Token`,
6181
+ async run(ctx) {
6182
+ let token;
6183
+ try {
6184
+ const loaded = ctx.load();
6185
+ token = loaded.config.sevalla?.apiToken || loaded.env.SEVALLA_API_TOKEN;
6186
+ } catch {}
6187
+ token = token || process.env.SEVALLA_API_TOKEN;
6188
+ const sub = ctx.positionals[0] || "apps";
6189
+ if (sub === "auth") {
6190
+ log.step("Link your Sevalla Cloud account");
6191
+ console.log(`
6192
+ Create a Personal Access Token in your Sevalla Dashboard:
6193
+ ${c.cyan("https://app.sevalla.com/user/api-tokens")}
6194
+ `);
6195
+ const enteredToken = await askSecret("Enter Sevalla API Token: ");
6196
+ if (!enteredToken) {
6197
+ throw new EpdError("Token is required to authenticate with Sevalla.");
6198
+ }
6199
+ const client = new SevallaClient(enteredToken);
6200
+ log.step("Verifying token with Sevalla API...");
6201
+ const verify = await client.verifyToken();
6202
+ if (!verify.valid) {
6203
+ throw new EpdError(`Invalid Sevalla API token: ${verify.error}`);
6204
+ }
6205
+ saveProjectEnv({ SEVALLA_API_TOKEN: enteredToken.trim() });
6206
+ log.ok(`Sevalla account successfully linked! (Found ${verify.appCount ?? 0} apps, ${verify.dbCount ?? 0} databases)`);
6207
+ return;
6208
+ }
6209
+ if (!token && interactive()) {
6210
+ log.info("No Sevalla API token found.");
6211
+ const link = await confirm("Would you like to link your Sevalla account now?", true);
6212
+ if (link) {
6213
+ console.log(`
6214
+ Create a Personal Access Token at ${c.cyan("https://app.sevalla.com/user/api-tokens")}`);
6215
+ const entered = await askSecret("Enter Sevalla API Token: ");
6216
+ if (entered) {
6217
+ token = entered.trim();
6218
+ saveProjectEnv({ SEVALLA_API_TOKEN: token });
6219
+ }
6220
+ }
6221
+ }
6222
+ if (!token) {
6223
+ throw new EpdError("Sevalla API token is missing", "Run `epd sevalla auth` or set SEVALLA_API_TOKEN in your environment.");
6224
+ }
6225
+ const client = new SevallaClient(token);
6226
+ if (sub === "apps" || sub === "list") {
6227
+ log.step("Fetching Sevalla applications...");
6228
+ const apps = await client.listApplications();
6229
+ if (!apps.length) {
6230
+ log.info("No applications found in your Sevalla account.");
6231
+ return;
6232
+ }
6233
+ console.log(`
6234
+ ${c.bold("SEVALLA APPLICATIONS")} (${apps.length})
6235
+ `);
6236
+ const headers = ["ID", "NAME", "STATUS", "REGION", "REPO / DOMAIN"];
6237
+ const rows = apps.map((a) => {
6238
+ let statusStr = a.status;
6239
+ if (a.status === "deployed")
6240
+ statusStr = c.green(a.status);
6241
+ else if (a.status === "deploying")
6242
+ statusStr = c.yellow(a.status);
6243
+ else
6244
+ statusStr = c.gray(a.status);
6245
+ const domainOrRepo = a.domains?.[0] || a.gitRepository?.url || "-";
6246
+ return [a.id, a.displayName, statusStr, a.region || "default", domainOrRepo];
6247
+ });
6248
+ console.log(formatTable(headers, rows));
6249
+ console.log("");
6250
+ return;
6251
+ }
6252
+ if (sub === "databases" || sub === "dbs") {
6253
+ log.step("Fetching Sevalla managed databases...");
6254
+ const dbs = await client.listDatabases();
6255
+ if (!dbs.length) {
6256
+ log.info("No managed databases found in your Sevalla account.");
6257
+ return;
6258
+ }
6259
+ console.log(`
6260
+ ${c.bold("SEVALLA MANAGED DATABASES")} (${dbs.length})
6261
+ `);
6262
+ const headers = ["ID", "NAME", "TYPE", "STATUS", "HOST / PORT", "DATABASE"];
6263
+ const rows = dbs.map((d) => {
6264
+ let statusStr = d.status;
6265
+ if (d.status === "ready")
6266
+ statusStr = c.green(d.status);
6267
+ else if (d.status === "creating")
6268
+ statusStr = c.yellow(d.status);
6269
+ else
6270
+ statusStr = c.gray(d.status);
6271
+ const hostStr = d.externalHost ? `${d.externalHost}:${d.port}` : `${d.internalHost || "-"}:${d.port}`;
6272
+ return [d.id, d.displayName, d.type.toUpperCase(), statusStr, hostStr, d.dbName];
6273
+ });
6274
+ console.log(formatTable(headers, rows));
6275
+ console.log("");
6276
+ return;
6277
+ }
6278
+ if (sub === "deploy") {
6279
+ const appId = ctx.positionals[1];
6280
+ if (!appId) {
6281
+ throw new EpdError("Application ID is required", "Usage: epd sevalla deploy <app-id>");
6282
+ }
6283
+ const branch = ctx.values.branch || undefined;
6284
+ log.step(`Triggering deployment on Sevalla for application ${c.bold(appId)}...`);
6285
+ const dep = await client.deployApplication(appId, { branch });
6286
+ log.ok(`Deployment triggered! Deployment ID: ${c.cyan(dep.id)} (Status: ${dep.status})`);
6287
+ return;
6288
+ }
6289
+ throw new EpdError(`Unknown Sevalla subcommand: ${sub}`, "Available: apps, databases, deploy, auth");
6290
+ }
6291
+ };
6292
+ function formatTable(headers, rows) {
6293
+ const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => stripAnsi2(r[i] ?? "").length)));
6294
+ const pad = (s, len) => s + " ".repeat(Math.max(0, len - stripAnsi2(s).length));
6295
+ const headerLine = headers.map((h, i) => c.bold(pad(h, colWidths[i]))).join(" ");
6296
+ const sepLine = colWidths.map((w) => "\u2500".repeat(w)).join(" ");
6297
+ const dataLines = rows.map((r) => r.map((cell, i) => pad(cell ?? "", colWidths[i])).join(" "));
6298
+ return [headerLine, c.gray(sepLine), ...dataLines].join(`
6299
+ `);
6300
+ }
6301
+ function stripAnsi2(str) {
6302
+ return str.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "");
6303
+ }
6304
+
5648
6305
  // src/core/update.ts
5649
- import { chmodSync as chmodSync2, existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync, writeFileSync as writeFileSync3 } from "fs";
5650
- import { homedir as homedir3 } from "os";
5651
- import { dirname as dirname2, join as join7 } from "path";
6306
+ import { chmodSync as chmodSync2, existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync3 } from "fs";
6307
+ import { homedir as homedir4 } from "os";
6308
+ import { dirname as dirname2, join as join8 } from "path";
5652
6309
  function parseSemver(v) {
5653
6310
  const clean = v.replace(/^v/, "").trim();
5654
6311
  const parts = clean.split("-")[0].split(".").map((n) => Number(n) || 0);
@@ -5668,13 +6325,13 @@ function isNewer(current, latest) {
5668
6325
  return lPatch > cPatch;
5669
6326
  }
5670
6327
  function getCachePath() {
5671
- return join7(homedir3(), ".epd", "update-check.json");
6328
+ return join8(homedir4(), ".epd", "update-check.json");
5672
6329
  }
5673
6330
  function readCache() {
5674
6331
  try {
5675
6332
  const p = getCachePath();
5676
- if (existsSync6(p)) {
5677
- return JSON.parse(readFileSync4(p, "utf8"));
6333
+ if (existsSync7(p)) {
6334
+ return JSON.parse(readFileSync5(p, "utf8"));
5678
6335
  }
5679
6336
  } catch {}
5680
6337
  return null;
@@ -5682,7 +6339,7 @@ function readCache() {
5682
6339
  function writeCache(latestVersion) {
5683
6340
  try {
5684
6341
  const p = getCachePath();
5685
- mkdirSync4(dirname2(p), { recursive: true });
6342
+ mkdirSync5(dirname2(p), { recursive: true });
5686
6343
  const data = { lastChecked: Date.now(), latestVersion };
5687
6344
  writeFileSync3(p, JSON.stringify(data));
5688
6345
  } catch {}
@@ -5807,7 +6464,7 @@ async function promptAutoUpdate(currentVersion) {
5807
6464
  }
5808
6465
 
5809
6466
  // src/version.ts
5810
- var VERSION = "0.5.1";
6467
+ var VERSION = "0.5.3";
5811
6468
 
5812
6469
  // src/commands/update.ts
5813
6470
  var update = {
@@ -6532,8 +7189,8 @@ Options
6532
7189
  };
6533
7190
 
6534
7191
  // src/commands/backup.ts
6535
- import { createWriteStream, mkdirSync as mkdirSync5, statSync } from "fs";
6536
- import { dirname as dirname3, join as join8, resolve as resolve2 } from "path";
7192
+ import { createWriteStream, mkdirSync as mkdirSync6, statSync } from "fs";
7193
+ import { dirname as dirname3, join as join9, resolve as resolve2 } from "path";
6537
7194
  function detectAccessoryType(decl, cfg) {
6538
7195
  const name = decl.name;
6539
7196
  const img = (decl.image || "").toLowerCase();
@@ -6624,7 +7281,7 @@ Options
6624
7281
  targets = accessories.map((a) => detectAccessoryType(a, cfg));
6625
7282
  }
6626
7283
  const outBaseDir = resolve2(process.cwd(), "backups");
6627
- mkdirSync5(outBaseDir, { recursive: true });
7284
+ mkdirSync6(outBaseDir, { recursive: true });
6628
7285
  for (const target of targets) {
6629
7286
  const host2 = host(target.hostName, cfg.ssh);
6630
7287
  const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${target.containerName}$`)} | grep -q .`);
@@ -6635,8 +7292,8 @@ Options
6635
7292
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
6636
7293
  const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
6637
7294
  const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
6638
- const localFile = ctx.values.output ? resolve2(String(ctx.values.output)) : join8(outBaseDir, filename);
6639
- mkdirSync5(dirname3(localFile), { recursive: true });
7295
+ const localFile = ctx.values.output ? resolve2(String(ctx.values.output)) : join9(outBaseDir, filename);
7296
+ mkdirSync6(dirname3(localFile), { recursive: true });
6640
7297
  let dumpCmd = "";
6641
7298
  if (target.type === "postgres") {
6642
7299
  dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
@@ -6683,7 +7340,7 @@ Options
6683
7340
  };
6684
7341
 
6685
7342
  // src/commands/restore.ts
6686
- import { createReadStream, existsSync as existsSync7 } from "fs";
7343
+ import { createReadStream, existsSync as existsSync8 } from "fs";
6687
7344
  import { basename as basename2, resolve as resolve3 } from "path";
6688
7345
  var restore = {
6689
7346
  name: "restore",
@@ -6704,7 +7361,7 @@ Options
6704
7361
  if (!backupPath)
6705
7362
  throw new EpdError("Please provide a path to the backup file to restore.");
6706
7363
  const absPath = resolve3(backupPath);
6707
- if (!existsSync7(absPath))
7364
+ if (!existsSync8(absPath))
6708
7365
  throw new EpdError(`Backup file not found: ${absPath}`);
6709
7366
  const loaded = ctx.load();
6710
7367
  const cfg = loaded.config;
@@ -6823,6 +7480,7 @@ var commands = [
6823
7480
  cloudflare,
6824
7481
  dns3,
6825
7482
  hetzner,
7483
+ sevalla,
6826
7484
  update,
6827
7485
  auth,
6828
7486
  maintenance,
@@ -30,8 +30,8 @@ Everything you need to prepare your development environment and target servers f
30
30
  - Arch Linux / Alpine Linux
31
31
  - **SSH Access**:
32
32
  - Open SSH port (default: 22).
33
- - User with `root` privileges or passwordless `sudo`.
34
- - SSH public key authentication configured.
33
+ - Root login or a user allowed to run `sudo` (with a password or a passwordless rule).
34
+ - SSH key authentication, or initial login access to install a public key.
35
35
  - **Firewall & Ports**:
36
36
  - **Port 80 (HTTP)**: Required for Let's Encrypt HTTP-01 challenge and HTTP traffic redirection.
37
37
  - **Port 443 (HTTPS)**: Required for encrypted TLS/SSL traffic.
@@ -92,6 +92,25 @@ bunx @fabioplunser/epd deploy
92
92
 
93
93
  `epd` connects to servers using your system's SSH configuration.
94
94
 
95
+ `epd setup` first tests public-key login without sudo, using keys available to
96
+ OpenSSH, including your `ssh-agent`. Load an encrypted key with `ssh-add` before
97
+ running setup. An explicit `ssh.key` selects that identity.
98
+
99
+ If key authentication is rejected in an interactive terminal, setup installs a
100
+ public key using a one-time SSH login. It uses the configured key, lets you select
101
+ an agent key, or uses a standard local key. If none exists, it creates an Ed25519
102
+ key with `ssh-keygen`. OpenSSH handles the login password prompt; EPD sends only
103
+ the public key and preserves existing `authorized_keys` entries. Setup verifies
104
+ a fresh key-authenticated connection before continuing. If the server disallows
105
+ password login, authorize your key through the provider console or an administrator.
106
+
107
+ CI never attempts interactive key installation. Authorize its key beforehand.
108
+
109
+ SSH login and sudo are separate: **`ssh-add` does not grant passwordless sudo**.
110
+ After key login succeeds, setup checks sudo authorization, trying passwordless
111
+ sudo first. It asks for the remote user's sudo password only if the server requires
112
+ one. EPD does not change your server's sudo policy automatically.
113
+
95
114
  ### 1. Test Direct Connection
96
115
 
97
116
  Before running `epd setup`, verify you can connect without entering a password:
@@ -120,13 +139,19 @@ ssh:
120
139
  proxy_jump: bastion.example.com
121
140
  ```
122
141
 
123
- `ssh.user` is the login for every server. A non-root user must be able to run
124
- `sudo -n` without a password — epd escalates for docker, systemd and the files
125
- under `/var/lib/epd`:
142
+ `ssh.user` is the login for every server. A non-root user needs `sudo`, because
143
+ epd escalates for docker, systemd and the files under `/var/lib/epd`. The
144
+ smoothest setup is a passwordless rule:
126
145
 
146
+ ```bash
147
+ echo 'deploy ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/epd
148
+ sudo chmod 440 /etc/sudoers.d/epd
127
149
  ```
128
- deploy ALL=(ALL) NOPASSWD:ALL
129
- ```
150
+
151
+ Without it, epd asks for the sudo password once per run and reuses it for every
152
+ command on that host — nothing is written to disk. For CI, where nobody can
153
+ type, set `EPD_SUDO_PASSWORD` (or `ssh.sudo_password: ${EPD_SUDO_PASSWORD}` in
154
+ `epd.yml`) instead.
130
155
 
131
156
  To use a different login on a single server, write it into the host entry —
132
157
  that wins over `ssh.user`:
@@ -55,6 +55,8 @@ ssh:
55
55
  # into the host entry: "deploy@203.0.113.10".
56
56
  port: 22 # SSH port (default: 22)
57
57
  key: ~/.ssh/id_ed25519 # Path to explicit private key
58
+ sudo_password: ${EPD_SUDO_PASSWORD} # Only if the user has no NOPASSWD rule;
59
+ # interactive runs simply prompt for it instead
58
60
  proxy_jump: bastion.net # Optional jump host / bastion
59
61
  options: # Extra OpenSSH options
60
62
  - ServerAliveInterval=30
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabioplunser/epd",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Easy Project Deployer — deploy any project to one or many servers with Docker or PM2, fronted by Traefik.",
5
5
  "type": "module",
6
6
  "author": "Fabio Plünser",