@fabioplunser/epd 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +2105 -654
- package/docs/.vitepress/config.mts +49 -16
- package/docs/.vitepress/theme/DeployAnimation.vue +1259 -0
- package/docs/.vitepress/theme/index.ts +10 -0
- package/docs/.vitepress/theme/style.css +109 -0
- package/docs/ci-cd.md +8 -0
- package/docs/getting-started.md +244 -0
- package/docs/guide/accessories.md +103 -0
- package/docs/guide/architecture.md +94 -0
- package/docs/guide/blue-green.md +93 -0
- package/docs/guide/deployment-modes.md +135 -0
- package/docs/guide/getting-started.md +244 -0
- package/docs/guide/high-availability.md +89 -0
- package/docs/guide/installation.md +127 -0
- package/docs/guide/multi-site.md +101 -0
- package/docs/guide/routing.md +129 -0
- package/docs/guide/secrets.md +109 -0
- package/docs/guide/troubleshooting.md +109 -0
- package/docs/guide.md +172 -535
- package/docs/hetzner-dns.md +8 -0
- package/docs/index.md +20 -25
- package/docs/public/CNAME +1 -0
- package/docs/public/favicon.svg +52 -0
- package/docs/reference/cli.md +299 -0
- package/docs/reference/config.md +177 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
+
var __require = import.meta.require;
|
|
3
|
+
|
|
2
4
|
// src/cli.ts
|
|
3
5
|
import { parseArgs } from "util";
|
|
4
6
|
|
|
@@ -849,8 +851,8 @@ function validateCrossReferences(cfg) {
|
|
|
849
851
|
}
|
|
850
852
|
|
|
851
853
|
// src/commands/init.ts
|
|
852
|
-
import { existsSync as
|
|
853
|
-
import { basename, join as
|
|
854
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
855
|
+
import { basename, join as join3 } from "path";
|
|
854
856
|
|
|
855
857
|
// src/util/prompt.ts
|
|
856
858
|
var isTTY = process.stdin.isTTY && process.stdout.isTTY;
|
|
@@ -869,6 +871,19 @@ async function ask(question, dflt) {
|
|
|
869
871
|
const answer = (await readLine()).trim();
|
|
870
872
|
return answer || dflt || "";
|
|
871
873
|
}
|
|
874
|
+
async function askSecret(question) {
|
|
875
|
+
if (!isTTY)
|
|
876
|
+
return "";
|
|
877
|
+
process.stdout.write(`${c.cyan("?")} ${question} `);
|
|
878
|
+
const answer = (await readLine()).trim();
|
|
879
|
+
return answer;
|
|
880
|
+
}
|
|
881
|
+
async function pressEnter(message) {
|
|
882
|
+
if (!isTTY)
|
|
883
|
+
return;
|
|
884
|
+
process.stdout.write(`${c.cyan("\u21B5")} ${message} ${c.gray("[Press Enter]")} `);
|
|
885
|
+
await readLine();
|
|
886
|
+
}
|
|
872
887
|
async function confirm(question, dflt = false) {
|
|
873
888
|
if (!isTTY)
|
|
874
889
|
return dflt;
|
|
@@ -887,239 +902,937 @@ async function choose(question, options, dflt) {
|
|
|
887
902
|
return options[idx]?.value ?? dflt;
|
|
888
903
|
}
|
|
889
904
|
|
|
890
|
-
// src/
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
905
|
+
// src/util/auth.ts
|
|
906
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync, chmodSync } from "fs";
|
|
907
|
+
import { homedir as homedir2 } from "os";
|
|
908
|
+
import { join as join2 } from "path";
|
|
909
|
+
import { spawn } from "child_process";
|
|
910
|
+
function openBrowser(url) {
|
|
911
|
+
try {
|
|
912
|
+
const platform = process.platform;
|
|
913
|
+
if (platform === "darwin") {
|
|
914
|
+
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
915
|
+
return true;
|
|
916
|
+
} else if (platform === "win32") {
|
|
917
|
+
spawn("cmd", ["/c", "start", '""', url], { detached: true, stdio: "ignore" }).unref();
|
|
918
|
+
return true;
|
|
919
|
+
} else {
|
|
920
|
+
spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
921
|
+
return true;
|
|
922
|
+
}
|
|
923
|
+
} catch {
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
function getGlobalAuthPath() {
|
|
928
|
+
const xdgDir = join2(homedir2(), ".config", "epd");
|
|
929
|
+
const fallbackDir = join2(homedir2(), ".epd");
|
|
930
|
+
if (existsSync2(join2(xdgDir, "auth.json")))
|
|
931
|
+
return join2(xdgDir, "auth.json");
|
|
932
|
+
if (existsSync2(join2(fallbackDir, "auth.json")))
|
|
933
|
+
return join2(fallbackDir, "auth.json");
|
|
934
|
+
return join2(xdgDir, "auth.json");
|
|
935
|
+
}
|
|
936
|
+
function getGlobalAuth() {
|
|
937
|
+
const path = getGlobalAuthPath();
|
|
938
|
+
if (!existsSync2(path))
|
|
939
|
+
return {};
|
|
940
|
+
try {
|
|
941
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
942
|
+
} catch {
|
|
943
|
+
return {};
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function saveGlobalAuth(updater) {
|
|
947
|
+
const dir = join2(homedir2(), ".config", "epd");
|
|
948
|
+
if (!existsSync2(dir)) {
|
|
949
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
950
|
+
}
|
|
951
|
+
const file = join2(dir, "auth.json");
|
|
952
|
+
const current = getGlobalAuth();
|
|
953
|
+
const next = updater(current);
|
|
954
|
+
writeFileSync(file, JSON.stringify(next, null, 2) + `
|
|
955
|
+
`, { mode: 384 });
|
|
956
|
+
try {
|
|
957
|
+
chmodSync(file, 384);
|
|
958
|
+
} catch {}
|
|
959
|
+
}
|
|
960
|
+
function saveProjectEnv(entries, root = process.cwd()) {
|
|
961
|
+
const envPath = join2(root, ".env");
|
|
962
|
+
let content = existsSync2(envPath) ? readFileSync2(envPath, "utf8") : "";
|
|
963
|
+
for (const [key, val] of Object.entries(entries)) {
|
|
964
|
+
const regex = new RegExp(`^${key}=.*$`, "m");
|
|
965
|
+
const line = `${key}=${val}`;
|
|
966
|
+
if (regex.test(content)) {
|
|
967
|
+
content = content.replace(regex, line);
|
|
968
|
+
} else {
|
|
969
|
+
if (content.length && !content.endsWith(`
|
|
970
|
+
`))
|
|
971
|
+
content += `
|
|
972
|
+
`;
|
|
973
|
+
content += `${line}
|
|
974
|
+
`;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
writeFileSync(envPath, content, "utf8");
|
|
978
|
+
}
|
|
979
|
+
function getCloudflareToken(root = process.cwd()) {
|
|
980
|
+
if (process.env.CLOUDFLARE_API_TOKEN)
|
|
981
|
+
return process.env.CLOUDFLARE_API_TOKEN;
|
|
982
|
+
if (process.env.CF_DNS_API_TOKEN)
|
|
983
|
+
return process.env.CF_DNS_API_TOKEN;
|
|
984
|
+
const envPath = join2(root, ".env");
|
|
985
|
+
if (existsSync2(envPath)) {
|
|
897
986
|
try {
|
|
898
|
-
|
|
987
|
+
const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
|
|
988
|
+
if (parsed.CLOUDFLARE_API_TOKEN)
|
|
989
|
+
return parsed.CLOUDFLARE_API_TOKEN;
|
|
990
|
+
if (parsed.CF_DNS_API_TOKEN)
|
|
991
|
+
return parsed.CF_DNS_API_TOKEN;
|
|
899
992
|
} catch {}
|
|
900
|
-
const bun = existsSync2(join2(root, "bun.lockb")) || existsSync2(join2(root, "bun.lock"));
|
|
901
|
-
const scripts = pkg.scripts ?? {};
|
|
902
|
-
const runner = bun ? "bun" : "npm";
|
|
903
|
-
return {
|
|
904
|
-
name: (pkg.name ?? name).replace(/^@[^/]+\//, "").replace(/[^a-z0-9_-]/gi, "-"),
|
|
905
|
-
runtime: bun ? "bun" : "node",
|
|
906
|
-
port: 3000,
|
|
907
|
-
install: bun ? "bun install --frozen-lockfile" : "npm ci --omit=dev",
|
|
908
|
-
build: scripts.build ? `${runner} run build` : undefined,
|
|
909
|
-
start: scripts.start ? `${runner} run start` : bun ? "bun run index.ts" : "node index.js",
|
|
910
|
-
hasDockerfile
|
|
911
|
-
};
|
|
912
993
|
}
|
|
913
|
-
|
|
914
|
-
|
|
994
|
+
const global = getGlobalAuth();
|
|
995
|
+
return global.cloudflare?.apiToken;
|
|
996
|
+
}
|
|
997
|
+
function getCloudflareTokenSource(root = process.cwd()) {
|
|
998
|
+
if (process.env.CLOUDFLARE_API_TOKEN)
|
|
999
|
+
return "environment variable (CLOUDFLARE_API_TOKEN)";
|
|
1000
|
+
if (process.env.CF_DNS_API_TOKEN)
|
|
1001
|
+
return "environment variable (CF_DNS_API_TOKEN)";
|
|
1002
|
+
const envPath = join2(root, ".env");
|
|
1003
|
+
if (existsSync2(envPath)) {
|
|
1004
|
+
try {
|
|
1005
|
+
const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
|
|
1006
|
+
if (parsed.CLOUDFLARE_API_TOKEN || parsed.CF_DNS_API_TOKEN)
|
|
1007
|
+
return ".env file";
|
|
1008
|
+
} catch {}
|
|
915
1009
|
}
|
|
916
|
-
|
|
917
|
-
|
|
1010
|
+
const global = getGlobalAuth();
|
|
1011
|
+
if (global.cloudflare?.apiToken)
|
|
1012
|
+
return "~/.config/epd/auth.json (global)";
|
|
1013
|
+
return "none";
|
|
1014
|
+
}
|
|
1015
|
+
function getHetznerToken(root = process.cwd()) {
|
|
1016
|
+
if (process.env.HETZNER_API_TOKEN)
|
|
1017
|
+
return process.env.HETZNER_API_TOKEN;
|
|
1018
|
+
if (process.env.HCLOUD_TOKEN)
|
|
1019
|
+
return process.env.HCLOUD_TOKEN;
|
|
1020
|
+
const envPath = join2(root, ".env");
|
|
1021
|
+
if (existsSync2(envPath)) {
|
|
1022
|
+
try {
|
|
1023
|
+
const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
|
|
1024
|
+
if (parsed.HETZNER_API_TOKEN)
|
|
1025
|
+
return parsed.HETZNER_API_TOKEN;
|
|
1026
|
+
if (parsed.HCLOUD_TOKEN)
|
|
1027
|
+
return parsed.HCLOUD_TOKEN;
|
|
1028
|
+
} catch {}
|
|
918
1029
|
}
|
|
919
|
-
|
|
920
|
-
|
|
1030
|
+
const global = getGlobalAuth();
|
|
1031
|
+
return global.hetzner?.apiToken;
|
|
1032
|
+
}
|
|
1033
|
+
function getHetznerTokenSource(root = process.cwd()) {
|
|
1034
|
+
if (process.env.HETZNER_API_TOKEN)
|
|
1035
|
+
return "environment variable (HETZNER_API_TOKEN)";
|
|
1036
|
+
if (process.env.HCLOUD_TOKEN)
|
|
1037
|
+
return "environment variable (HCLOUD_TOKEN)";
|
|
1038
|
+
const envPath = join2(root, ".env");
|
|
1039
|
+
if (existsSync2(envPath)) {
|
|
1040
|
+
try {
|
|
1041
|
+
const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
|
|
1042
|
+
if (parsed.HETZNER_API_TOKEN || parsed.HCLOUD_TOKEN)
|
|
1043
|
+
return ".env file";
|
|
1044
|
+
} catch {}
|
|
921
1045
|
}
|
|
922
|
-
|
|
1046
|
+
const global = getGlobalAuth();
|
|
1047
|
+
if (global.hetzner?.apiToken)
|
|
1048
|
+
return "~/.config/epd/auth.json (global)";
|
|
1049
|
+
return "none";
|
|
923
1050
|
}
|
|
924
|
-
function
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
# password: \${GITHUB_TOKEN}
|
|
942
|
-
`;
|
|
943
|
-
const processBlock = o.mode === "process" ? `
|
|
944
|
-
# No Docker: each replica is started with pm2 and gets a unique $PORT.
|
|
945
|
-
process:
|
|
946
|
-
${o.detected.install ? `install: ${o.detected.install}` : "# install: bun install --frozen-lockfile"}
|
|
947
|
-
${o.detected.build ? `build: ${o.detected.build}` : "# build: bun run build"}
|
|
948
|
-
start: ${o.detected.start ?? "bun run start"}
|
|
949
|
-
# Files that never need to reach the server.
|
|
950
|
-
exclude: [".git", "node_modules", ".env", "dist", "*.log"]
|
|
951
|
-
` : "";
|
|
952
|
-
return `# ${o.name} \u2014 deployed with epd (https://github.com/you/epd)
|
|
953
|
-
#
|
|
954
|
-
# epd setup prepare the servers and deploy for the first time
|
|
955
|
-
# epd deploy build and deploy the current commit
|
|
956
|
-
# epd status see what is running where
|
|
957
|
-
# epd rollback go back to the previous version
|
|
958
|
-
#
|
|
959
|
-
name: ${o.name}
|
|
960
|
-
|
|
961
|
-
# "docker" builds an image from your Dockerfile. "process" uploads the project
|
|
962
|
-
# and runs it with pm2 \u2014 no Docker on the server at all.
|
|
963
|
-
mode: ${o.mode}
|
|
964
|
-
${o.mode === "docker" ? `
|
|
965
|
-
# Image name. Tagged with the git sha of every deploy.
|
|
966
|
-
image: ${o.image ?? o.name}
|
|
967
|
-
${registry}` : ""}${processBlock}
|
|
968
|
-
# One entry per group of processes. Add more (worker, cron, \u2026) as you need them.
|
|
969
|
-
servers:
|
|
970
|
-
web:
|
|
971
|
-
hosts: ${list(o.hosts)}
|
|
972
|
-
# Replicas per host. Traefik load balances across all of them, and across
|
|
973
|
-
# every host when proxy.cross_host is on.
|
|
974
|
-
replicas: ${o.replicas}
|
|
975
|
-
port: ${o.port}
|
|
976
|
-
domains: ${list(o.domains)}
|
|
977
|
-
# Routes give you finer control \u2014 several sites, paths and ports per app:
|
|
978
|
-
#
|
|
979
|
-
# routes:
|
|
980
|
-
# - host: ${o.domains[0] ?? "example.com"}
|
|
981
|
-
# - host: api.${o.domains[0] ?? "example.com"}
|
|
982
|
-
# port: 8080
|
|
983
|
-
# - host: ${o.domains[0] ?? "example.com"}
|
|
984
|
-
# path: /admin
|
|
985
|
-
# port: 4000
|
|
986
|
-
# basic_auth: ["admin:$apr1$..."]
|
|
987
|
-
|
|
988
|
-
# worker:
|
|
989
|
-
# hosts: ${list(o.hosts.slice(0, 1))}
|
|
990
|
-
# command: bun run worker.ts
|
|
991
|
-
|
|
992
|
-
# Traefik runs once per server and is shared by every epd app on it, so you can
|
|
993
|
-
# host as many sites on one machine as you like.
|
|
994
|
-
proxy:
|
|
995
|
-
ssl: true
|
|
996
|
-
email: ${o.email || "you@example.com"}
|
|
997
|
-
# Route to replicas on *other* servers too, so one machine can serve while
|
|
998
|
-
# another is down. Needs the app port reachable between servers.
|
|
999
|
-
cross_host: false
|
|
1000
|
-
# private_ips: { "203.0.113.10": "10.0.0.10" }
|
|
1001
|
-
|
|
1002
|
-
# Zero-downtime health check for the new version before traffic moves to it.
|
|
1003
|
-
healthcheck:
|
|
1004
|
-
path: /
|
|
1005
|
-
timeout: 60
|
|
1006
|
-
|
|
1007
|
-
env:
|
|
1008
|
-
clear:
|
|
1009
|
-
NODE_ENV: production
|
|
1010
|
-
# Read from your shell or .env at deploy time and written to the server
|
|
1011
|
-
# as a 0600 file. Never committed.
|
|
1012
|
-
secret:
|
|
1013
|
-
# - DATABASE_URL
|
|
1014
|
-
|
|
1015
|
-
# Long-lived containers epd starts but never rebuilds, like a database.
|
|
1016
|
-
# accessories:
|
|
1017
|
-
# db:
|
|
1018
|
-
# image: postgres:17
|
|
1019
|
-
# host: ${o.hosts[0] ?? "203.0.113.10"}
|
|
1020
|
-
# env:
|
|
1021
|
-
# clear:
|
|
1022
|
-
# POSTGRES_DB: ${o.name}
|
|
1023
|
-
# secret:
|
|
1024
|
-
# - POSTGRES_PASSWORD
|
|
1025
|
-
# volumes:
|
|
1026
|
-
# - /var/lib/epd/volumes/${o.name}-db:/var/lib/postgresql/data
|
|
1027
|
-
|
|
1028
|
-
# hooks:
|
|
1029
|
-
# pre_deploy: ./bin/run-tests
|
|
1030
|
-
# post_deploy: ./bin/notify-slack
|
|
1031
|
-
|
|
1032
|
-
# Host ports epd reserves on each server (only used in process mode or with
|
|
1033
|
-
# cross_host). Change it if two apps ever collide.
|
|
1034
|
-
port_base: ${portBase}
|
|
1035
|
-
`;
|
|
1051
|
+
async function verifyCloudflareToken(token) {
|
|
1052
|
+
try {
|
|
1053
|
+
const res = await fetch("https://api.cloudflare.com/client/v4/user/tokens/verify", {
|
|
1054
|
+
headers: {
|
|
1055
|
+
Authorization: `Bearer ${token}`,
|
|
1056
|
+
"Content-Type": "application/json"
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
const data = await res.json();
|
|
1060
|
+
if (res.ok && data.success && data.result?.status === "active") {
|
|
1061
|
+
return { valid: true, status: data.result.status };
|
|
1062
|
+
}
|
|
1063
|
+
const err = data.errors?.[0]?.message || `HTTP ${res.status}`;
|
|
1064
|
+
return { valid: false, error: err };
|
|
1065
|
+
} catch (err) {
|
|
1066
|
+
return { valid: false, error: err.message };
|
|
1067
|
+
}
|
|
1036
1068
|
}
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
COPY . .
|
|
1049
|
-
RUN bun run build || true
|
|
1050
|
-
|
|
1051
|
-
FROM base AS run
|
|
1052
|
-
ENV NODE_ENV=production
|
|
1053
|
-
COPY --from=build /app ./
|
|
1054
|
-
EXPOSE 3000
|
|
1055
|
-
CMD ["bun", "run", "start"]
|
|
1056
|
-
`,
|
|
1057
|
-
node: `# syntax=docker/dockerfile:1
|
|
1058
|
-
FROM node:22-slim AS base
|
|
1059
|
-
WORKDIR /app
|
|
1060
|
-
|
|
1061
|
-
FROM base AS deps
|
|
1062
|
-
COPY package*.json ./
|
|
1063
|
-
RUN npm ci
|
|
1064
|
-
|
|
1065
|
-
FROM base AS build
|
|
1066
|
-
COPY --from=deps /app/node_modules ./node_modules
|
|
1067
|
-
COPY . .
|
|
1068
|
-
RUN npm run build --if-present
|
|
1069
|
-
|
|
1070
|
-
FROM base AS run
|
|
1071
|
-
ENV NODE_ENV=production
|
|
1072
|
-
COPY --from=build /app ./
|
|
1073
|
-
RUN npm prune --omit=dev
|
|
1074
|
-
EXPOSE 3000
|
|
1075
|
-
CMD ["npm", "run", "start"]
|
|
1076
|
-
`
|
|
1077
|
-
};
|
|
1078
|
-
var init = {
|
|
1079
|
-
name: "init",
|
|
1080
|
-
summary: "Create an epd.yml for this project",
|
|
1081
|
-
options: {
|
|
1082
|
-
name: { type: "string" },
|
|
1083
|
-
mode: { type: "string" },
|
|
1084
|
-
host: { type: "string", multiple: true },
|
|
1085
|
-
domain: { type: "string", multiple: true },
|
|
1086
|
-
port: { type: "string" },
|
|
1087
|
-
email: { type: "string" },
|
|
1088
|
-
replicas: { type: "string" },
|
|
1089
|
-
force: { type: "boolean" },
|
|
1090
|
-
dockerfile: { type: "boolean" },
|
|
1091
|
-
ci: { type: "boolean" }
|
|
1092
|
-
},
|
|
1093
|
-
help: () => `${c.bold("epd init")} \u2014 create an epd.yml for this project
|
|
1094
|
-
|
|
1095
|
-
Options
|
|
1096
|
-
--name <name> App name (default: the directory name)
|
|
1097
|
-
--mode <docker|process>
|
|
1098
|
-
--host <ip> Server to deploy to (repeatable)
|
|
1099
|
-
--domain <domain> Domain to serve (repeatable)
|
|
1100
|
-
--port <port> Port your app listens on
|
|
1101
|
-
--email <email> Contact address for Let's Encrypt
|
|
1102
|
-
--replicas <n> Replicas per host (default 1)
|
|
1103
|
-
--dockerfile Also write a starter Dockerfile
|
|
1104
|
-
--ci Also generate a GitHub Actions deploy workflow (.github/workflows/deploy.yml)
|
|
1105
|
-
--force Overwrite an existing epd.yml`,
|
|
1106
|
-
async run(ctx) {
|
|
1107
|
-
const root = process.cwd();
|
|
1108
|
-
const target = join2(root, "epd.yml");
|
|
1109
|
-
if (existsSync2(target) && !ctx.values.force) {
|
|
1110
|
-
throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
|
|
1069
|
+
async function verifyHetznerToken(token) {
|
|
1070
|
+
try {
|
|
1071
|
+
const res = await fetch("https://api.hetzner.cloud/v1/servers", {
|
|
1072
|
+
headers: {
|
|
1073
|
+
Authorization: `Bearer ${token}`,
|
|
1074
|
+
"Content-Type": "application/json"
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
const data = await res.json();
|
|
1078
|
+
if (res.ok && Array.isArray(data.servers)) {
|
|
1079
|
+
return { valid: true };
|
|
1111
1080
|
}
|
|
1112
|
-
const
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1081
|
+
const err = data.error?.message || `HTTP ${res.status}`;
|
|
1082
|
+
return { valid: false, error: err };
|
|
1083
|
+
} catch (err) {
|
|
1084
|
+
return { valid: false, error: err.message };
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
async function linkCloudflareInteractive(root = process.cwd()) {
|
|
1088
|
+
const url = "https://dash.cloudflare.com/profile/api-tokens";
|
|
1089
|
+
console.log(`
|
|
1090
|
+
${c.bold("Linking Cloudflare to EPD")}`);
|
|
1091
|
+
console.log(`Cloudflare manages DNS records and SSL certificates automatically for your domains.
|
|
1092
|
+
`);
|
|
1093
|
+
await pressEnter("Press Enter to open Cloudflare token creation in your browser...");
|
|
1094
|
+
const opened = openBrowser(url);
|
|
1095
|
+
if (opened) {
|
|
1096
|
+
log.info(`Opened ${c.cyan(url)} in browser.`);
|
|
1097
|
+
} else {
|
|
1098
|
+
log.info(`Open this URL in your browser: ${c.cyan(url)}`);
|
|
1099
|
+
}
|
|
1100
|
+
console.log(c.gray(' 1. In Cloudflare, select "Create Token" \u2192 use the "Edit zone DNS" template.'));
|
|
1101
|
+
console.log(c.gray(` 2. Complete token creation, copy the token, and paste it below.
|
|
1102
|
+
`));
|
|
1103
|
+
for (;; ) {
|
|
1104
|
+
const token = await askSecret("Paste Cloudflare API Token (or press Enter to skip):");
|
|
1105
|
+
if (!token) {
|
|
1106
|
+
log.info("Cloudflare linking skipped.");
|
|
1107
|
+
return null;
|
|
1108
|
+
}
|
|
1109
|
+
log.step("Verifying Cloudflare API token...");
|
|
1110
|
+
const check = await verifyCloudflareToken(token);
|
|
1111
|
+
if (check.valid) {
|
|
1112
|
+
log.ok(`Cloudflare API token verified (${c.green("status: active")})`);
|
|
1113
|
+
const where = await choose("Where would you like to save this Cloudflare token?", [
|
|
1114
|
+
{ value: "global", label: "Globally in ~/.config/epd/auth.json (recommended \u2014 all projects)" },
|
|
1115
|
+
{ value: "project", label: "This project only (.env)" },
|
|
1116
|
+
{ value: "both", label: "Both globally and in this project's .env" }
|
|
1117
|
+
], "global");
|
|
1118
|
+
if (where === "global" || where === "both") {
|
|
1119
|
+
saveGlobalAuth((curr) => ({
|
|
1120
|
+
...curr,
|
|
1121
|
+
cloudflare: { apiToken: token, verifiedAt: new Date().toISOString() }
|
|
1122
|
+
}));
|
|
1123
|
+
log.ok(`Saved Cloudflare token globally in ${c.bold("~/.config/epd/auth.json")}`);
|
|
1124
|
+
}
|
|
1125
|
+
if (where === "project" || where === "both") {
|
|
1126
|
+
saveProjectEnv({ CLOUDFLARE_API_TOKEN: token }, root);
|
|
1127
|
+
log.ok(`Saved CLOUDFLARE_API_TOKEN in ${c.bold(".env")}`);
|
|
1128
|
+
}
|
|
1129
|
+
return token;
|
|
1130
|
+
} else {
|
|
1131
|
+
log.warn(`Token verification failed: ${check.error}`);
|
|
1132
|
+
console.log(c.gray(`Make sure the token has "Zone.DNS:Edit" and "Zone:Read" permissions.
|
|
1133
|
+
`));
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
async function linkHetznerInteractive(root = process.cwd()) {
|
|
1138
|
+
const url = "https://console.hetzner.cloud/";
|
|
1139
|
+
console.log(`
|
|
1140
|
+
${c.bold("Linking Hetzner Cloud to EPD")}`);
|
|
1141
|
+
console.log(`Hetzner Cloud lets EPD list, provision, and deploy directly to your cloud servers.
|
|
1142
|
+
`);
|
|
1143
|
+
await pressEnter("Press Enter to open Hetzner Cloud Console in your browser...");
|
|
1144
|
+
const opened = openBrowser(url);
|
|
1145
|
+
if (opened) {
|
|
1146
|
+
log.info(`Opened ${c.cyan(url)} in browser.`);
|
|
1147
|
+
} else {
|
|
1148
|
+
log.info(`Open this URL in your browser: ${c.cyan(url)}`);
|
|
1149
|
+
}
|
|
1150
|
+
console.log(c.gray(' 1. In Hetzner Cloud, select your project \u2192 "Security" \u2192 "API Tokens".'));
|
|
1151
|
+
console.log(c.gray(' 2. Generate an API token with "Read & Write" permissions.'));
|
|
1152
|
+
console.log(c.gray(` 3. Copy the token and paste it below.
|
|
1153
|
+
`));
|
|
1154
|
+
for (;; ) {
|
|
1155
|
+
const token = await askSecret("Paste Hetzner Cloud API Token (or press Enter to skip):");
|
|
1156
|
+
if (!token) {
|
|
1157
|
+
log.info("Hetzner linking skipped.");
|
|
1158
|
+
return null;
|
|
1159
|
+
}
|
|
1160
|
+
log.step("Verifying Hetzner Cloud API token...");
|
|
1161
|
+
const check = await verifyHetznerToken(token);
|
|
1162
|
+
if (check.valid) {
|
|
1163
|
+
log.ok(`Hetzner Cloud API token verified`);
|
|
1164
|
+
const where = await choose("Where would you like to save this Hetzner token?", [
|
|
1165
|
+
{ value: "global", label: "Globally in ~/.config/epd/auth.json (recommended \u2014 all projects)" },
|
|
1166
|
+
{ value: "project", label: "This project only (.env)" },
|
|
1167
|
+
{ value: "both", label: "Both globally and in this project's .env" }
|
|
1168
|
+
], "global");
|
|
1169
|
+
if (where === "global" || where === "both") {
|
|
1170
|
+
saveGlobalAuth((curr) => ({
|
|
1171
|
+
...curr,
|
|
1172
|
+
hetzner: { apiToken: token, verifiedAt: new Date().toISOString() }
|
|
1173
|
+
}));
|
|
1174
|
+
log.ok(`Saved Hetzner token globally in ${c.bold("~/.config/epd/auth.json")}`);
|
|
1175
|
+
}
|
|
1176
|
+
if (where === "project" || where === "both") {
|
|
1177
|
+
saveProjectEnv({ HETZNER_API_TOKEN: token }, root);
|
|
1178
|
+
log.ok(`Saved HETZNER_API_TOKEN in ${c.bold(".env")}`);
|
|
1179
|
+
}
|
|
1180
|
+
return token;
|
|
1181
|
+
} else {
|
|
1182
|
+
log.warn(`Token verification failed: ${check.error}`);
|
|
1183
|
+
console.log(c.gray(`Make sure the token is active with Read & Write permissions.
|
|
1184
|
+
`));
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// src/hetzner/api.ts
|
|
1190
|
+
class HetznerCloudClient {
|
|
1191
|
+
apiToken;
|
|
1192
|
+
baseUrl;
|
|
1193
|
+
constructor(apiToken, baseUrl = "https://api.hetzner.cloud/v1") {
|
|
1194
|
+
this.apiToken = apiToken;
|
|
1195
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
1196
|
+
}
|
|
1197
|
+
async request(path, options = {}) {
|
|
1198
|
+
const url = `${this.baseUrl}${path}`;
|
|
1199
|
+
const headers = {
|
|
1200
|
+
Authorization: `Bearer ${this.apiToken}`,
|
|
1201
|
+
"Content-Type": "application/json",
|
|
1202
|
+
...options.headers
|
|
1203
|
+
};
|
|
1204
|
+
const res = await fetch(url, { ...options, headers });
|
|
1205
|
+
let data;
|
|
1206
|
+
try {
|
|
1207
|
+
data = await res.json();
|
|
1208
|
+
} catch {
|
|
1209
|
+
data = null;
|
|
1210
|
+
}
|
|
1211
|
+
if (!res.ok) {
|
|
1212
|
+
const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
|
|
1213
|
+
throw new EpdError(`Hetzner Cloud API error: ${msg}`);
|
|
1214
|
+
}
|
|
1215
|
+
return data;
|
|
1216
|
+
}
|
|
1217
|
+
mapServer(s) {
|
|
1218
|
+
return {
|
|
1219
|
+
id: s.id,
|
|
1220
|
+
name: s.name,
|
|
1221
|
+
status: s.status,
|
|
1222
|
+
created: s.created,
|
|
1223
|
+
publicNet: {
|
|
1224
|
+
ipv4: {
|
|
1225
|
+
ip: s.public_net?.ipv4?.ip ?? "",
|
|
1226
|
+
blocked: Boolean(s.public_net?.ipv4?.blocked),
|
|
1227
|
+
dnsPtr: s.public_net?.ipv4?.dns_ptr
|
|
1228
|
+
},
|
|
1229
|
+
ipv6: s.public_net?.ipv6 ? {
|
|
1230
|
+
ip: s.public_net.ipv6.ip ?? "",
|
|
1231
|
+
blocked: Boolean(s.public_net.ipv6.blocked)
|
|
1232
|
+
} : undefined
|
|
1233
|
+
},
|
|
1234
|
+
serverType: {
|
|
1235
|
+
id: s.server_type?.id ?? 0,
|
|
1236
|
+
name: s.server_type?.name ?? "",
|
|
1237
|
+
description: s.server_type?.description ?? "",
|
|
1238
|
+
cores: s.server_type?.cores ?? 0,
|
|
1239
|
+
memory: s.server_type?.memory ?? 0,
|
|
1240
|
+
disk: s.server_type?.disk ?? 0,
|
|
1241
|
+
cpuType: s.server_type?.cpu_type ?? "shared",
|
|
1242
|
+
architecture: s.server_type?.architecture ?? "x86"
|
|
1243
|
+
},
|
|
1244
|
+
datacenter: {
|
|
1245
|
+
id: s.datacenter?.id ?? 0,
|
|
1246
|
+
name: s.datacenter?.name ?? "",
|
|
1247
|
+
description: s.datacenter?.description ?? "",
|
|
1248
|
+
location: {
|
|
1249
|
+
id: s.datacenter?.location?.id ?? 0,
|
|
1250
|
+
name: s.datacenter?.location?.name ?? "",
|
|
1251
|
+
description: s.datacenter?.location?.description ?? "",
|
|
1252
|
+
country: s.datacenter?.location?.country ?? "",
|
|
1253
|
+
city: s.datacenter?.location?.city ?? ""
|
|
1254
|
+
}
|
|
1255
|
+
},
|
|
1256
|
+
image: s.image ? {
|
|
1257
|
+
id: s.image.id,
|
|
1258
|
+
name: s.image.name ?? "",
|
|
1259
|
+
osFlavor: s.image.os_flavor ?? "",
|
|
1260
|
+
description: s.image.description ?? ""
|
|
1261
|
+
} : undefined,
|
|
1262
|
+
labels: s.labels ?? {}
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
async listServers(opts = {}) {
|
|
1266
|
+
const params = new URLSearchParams;
|
|
1267
|
+
if (opts.name)
|
|
1268
|
+
params.set("name", opts.name);
|
|
1269
|
+
if (opts.labelSelector)
|
|
1270
|
+
params.set("label_selector", opts.labelSelector);
|
|
1271
|
+
params.set("per_page", "50");
|
|
1272
|
+
const query = params.toString() ? `?${params.toString()}` : "";
|
|
1273
|
+
const res = await this.request(`/servers${query}`);
|
|
1274
|
+
return (res.servers ?? []).map((s) => this.mapServer(s));
|
|
1275
|
+
}
|
|
1276
|
+
async getServer(idOrName) {
|
|
1277
|
+
if (typeof idOrName === "number" || /^\d+$/.test(String(idOrName))) {
|
|
1278
|
+
try {
|
|
1279
|
+
const res = await this.request(`/servers/${idOrName}`);
|
|
1280
|
+
return this.mapServer(res.server);
|
|
1281
|
+
} catch (e) {
|
|
1282
|
+
if (e instanceof EpdError && e.message.includes("404"))
|
|
1283
|
+
return null;
|
|
1284
|
+
throw e;
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
const servers = await this.listServers({ name: String(idOrName) });
|
|
1288
|
+
return servers.find((s) => s.name === String(idOrName)) ?? null;
|
|
1289
|
+
}
|
|
1290
|
+
async createServer(opts) {
|
|
1291
|
+
const body = {
|
|
1292
|
+
name: opts.name,
|
|
1293
|
+
server_type: opts.serverType ?? "cx22",
|
|
1294
|
+
image: opts.image ?? "ubuntu-24.04",
|
|
1295
|
+
start_after_create: opts.startAfterCreate ?? true
|
|
1296
|
+
};
|
|
1297
|
+
if (opts.location)
|
|
1298
|
+
body.location = opts.location;
|
|
1299
|
+
if (opts.datacenter)
|
|
1300
|
+
body.datacenter = opts.datacenter;
|
|
1301
|
+
if (opts.sshKeys?.length)
|
|
1302
|
+
body.ssh_keys = opts.sshKeys;
|
|
1303
|
+
if (opts.labels)
|
|
1304
|
+
body.labels = opts.labels;
|
|
1305
|
+
if (opts.userData)
|
|
1306
|
+
body.user_data = opts.userData;
|
|
1307
|
+
const res = await this.request("/servers", {
|
|
1308
|
+
method: "POST",
|
|
1309
|
+
body: JSON.stringify(body)
|
|
1310
|
+
});
|
|
1311
|
+
return {
|
|
1312
|
+
server: this.mapServer(res.server),
|
|
1313
|
+
action: res.action,
|
|
1314
|
+
rootPassword: res.root_password
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
async deleteServer(id) {
|
|
1318
|
+
await this.request(`/servers/${id}`, {
|
|
1319
|
+
method: "DELETE"
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
async listServerTypes() {
|
|
1323
|
+
const res = await this.request("/server_types");
|
|
1324
|
+
return (res.server_types ?? []).map((st) => ({
|
|
1325
|
+
id: st.id,
|
|
1326
|
+
name: st.name,
|
|
1327
|
+
description: st.description,
|
|
1328
|
+
cores: st.cores,
|
|
1329
|
+
memory: st.memory,
|
|
1330
|
+
disk: st.disk,
|
|
1331
|
+
cpuType: st.cpu_type,
|
|
1332
|
+
architecture: st.architecture,
|
|
1333
|
+
prices: (st.prices ?? []).map((p) => ({
|
|
1334
|
+
location: p.location,
|
|
1335
|
+
priceHourly: { net: p.price_hourly?.net ?? "", gross: p.price_hourly?.gross ?? "" },
|
|
1336
|
+
priceMonthly: { net: p.price_monthly?.net ?? "", gross: p.price_monthly?.gross ?? "" }
|
|
1337
|
+
}))
|
|
1338
|
+
}));
|
|
1339
|
+
}
|
|
1340
|
+
async listLocations() {
|
|
1341
|
+
const res = await this.request("/locations");
|
|
1342
|
+
return (res.locations ?? []).map((l) => ({
|
|
1343
|
+
id: l.id,
|
|
1344
|
+
name: l.name,
|
|
1345
|
+
description: l.description,
|
|
1346
|
+
country: l.country,
|
|
1347
|
+
city: l.city,
|
|
1348
|
+
networkZone: l.network_zone
|
|
1349
|
+
}));
|
|
1350
|
+
}
|
|
1351
|
+
async listSshKeys() {
|
|
1352
|
+
const res = await this.request("/ssh_keys");
|
|
1353
|
+
return (res.ssh_keys ?? []).map((k) => ({
|
|
1354
|
+
id: k.id,
|
|
1355
|
+
name: k.name,
|
|
1356
|
+
fingerprint: k.fingerprint,
|
|
1357
|
+
publicKey: k.public_key
|
|
1358
|
+
}));
|
|
1359
|
+
}
|
|
1360
|
+
async getAction(id) {
|
|
1361
|
+
const res = await this.request(`/actions/${id}`);
|
|
1362
|
+
return res.action;
|
|
1363
|
+
}
|
|
1364
|
+
async waitForAction(actionId, timeoutMs = 120000) {
|
|
1365
|
+
const deadline = Date.now() + timeoutMs;
|
|
1366
|
+
while (Date.now() < deadline) {
|
|
1367
|
+
const action = await this.getAction(actionId);
|
|
1368
|
+
if (action.status === "success")
|
|
1369
|
+
return;
|
|
1370
|
+
if (action.status === "error") {
|
|
1371
|
+
throw new EpdError(`Hetzner action failed: ${action.error?.message || "Unknown error"}`);
|
|
1372
|
+
}
|
|
1373
|
+
await sleep(1500);
|
|
1374
|
+
}
|
|
1375
|
+
throw new EpdError(`Hetzner action ${actionId} timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
1376
|
+
}
|
|
1377
|
+
async waitForServerRunning(serverId, timeoutMs = 120000) {
|
|
1378
|
+
const deadline = Date.now() + timeoutMs;
|
|
1379
|
+
while (Date.now() < deadline) {
|
|
1380
|
+
const server = await this.getServer(serverId);
|
|
1381
|
+
if (server && server.status === "running" && server.publicNet.ipv4.ip) {
|
|
1382
|
+
return server;
|
|
1383
|
+
}
|
|
1384
|
+
await sleep(2000);
|
|
1385
|
+
}
|
|
1386
|
+
throw new EpdError(`Timed out waiting for Hetzner server ${serverId} to become running`);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
// src/dns/cloudflare.ts
|
|
1391
|
+
class CloudflareClient {
|
|
1392
|
+
name = "cloudflare";
|
|
1393
|
+
apiToken;
|
|
1394
|
+
baseUrl;
|
|
1395
|
+
constructor(apiToken, baseUrl = "https://api.cloudflare.com/client/v4") {
|
|
1396
|
+
this.apiToken = apiToken;
|
|
1397
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
1398
|
+
}
|
|
1399
|
+
async request(path, options = {}) {
|
|
1400
|
+
const url = `${this.baseUrl}${path}`;
|
|
1401
|
+
const headers = {
|
|
1402
|
+
Authorization: `Bearer ${this.apiToken}`,
|
|
1403
|
+
"Content-Type": "application/json",
|
|
1404
|
+
...options.headers
|
|
1405
|
+
};
|
|
1406
|
+
const res = await fetch(url, { ...options, headers });
|
|
1407
|
+
const data = await res.json();
|
|
1408
|
+
if (!res.ok || data.success === false) {
|
|
1409
|
+
const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
|
|
1410
|
+
throw new EpdError(`Cloudflare API error: ${msg}`);
|
|
1411
|
+
}
|
|
1412
|
+
return data.result;
|
|
1413
|
+
}
|
|
1414
|
+
async listZones(name) {
|
|
1415
|
+
const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
|
|
1416
|
+
return this.request(`/zones${query}`);
|
|
1417
|
+
}
|
|
1418
|
+
async findZoneForDomain(domain, explicitZoneId) {
|
|
1419
|
+
if (explicitZoneId) {
|
|
1420
|
+
return { id: explicitZoneId, name: domain };
|
|
1421
|
+
}
|
|
1422
|
+
const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
|
|
1423
|
+
const parts = cleanDomain.split(".");
|
|
1424
|
+
for (let i = 0;i < parts.length - 1; i++) {
|
|
1425
|
+
const candidate = parts.slice(i).join(".");
|
|
1426
|
+
const zones = await this.listZones(candidate);
|
|
1427
|
+
const match = zones.find((z) => z.name.toLowerCase() === candidate);
|
|
1428
|
+
if (match)
|
|
1429
|
+
return { id: match.id, name: match.name };
|
|
1430
|
+
}
|
|
1431
|
+
throw new EpdError(`Cloudflare zone for domain "${domain}" not found`, `Make sure the domain is registered under your Cloudflare account and your API token has Zone.Read permissions.`);
|
|
1432
|
+
}
|
|
1433
|
+
async listDnsRecords(zoneId, name, type) {
|
|
1434
|
+
const params = new URLSearchParams;
|
|
1435
|
+
params.set("per_page", "100");
|
|
1436
|
+
if (name)
|
|
1437
|
+
params.set("name", name);
|
|
1438
|
+
if (type)
|
|
1439
|
+
params.set("type", type);
|
|
1440
|
+
const raw = await this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
|
|
1441
|
+
return raw.map((r) => ({
|
|
1442
|
+
id: String(r.id),
|
|
1443
|
+
zoneId: String(r.zone_id ?? zoneId),
|
|
1444
|
+
name: r.name,
|
|
1445
|
+
type: r.type,
|
|
1446
|
+
content: r.content,
|
|
1447
|
+
proxied: Boolean(r.proxied),
|
|
1448
|
+
ttl: Number(r.ttl ?? 1)
|
|
1449
|
+
}));
|
|
1450
|
+
}
|
|
1451
|
+
async createDnsRecord(zoneId, record) {
|
|
1452
|
+
const res = await this.request(`/zones/${zoneId}/dns_records`, {
|
|
1453
|
+
method: "POST",
|
|
1454
|
+
body: JSON.stringify({
|
|
1455
|
+
name: record.name,
|
|
1456
|
+
type: record.type,
|
|
1457
|
+
content: record.content,
|
|
1458
|
+
proxied: Boolean(record.proxied),
|
|
1459
|
+
ttl: record.ttl,
|
|
1460
|
+
comment: record.comment
|
|
1461
|
+
})
|
|
1462
|
+
});
|
|
1463
|
+
return {
|
|
1464
|
+
id: String(res.id),
|
|
1465
|
+
zoneId: String(res.zone_id ?? zoneId),
|
|
1466
|
+
name: res.name,
|
|
1467
|
+
type: res.type,
|
|
1468
|
+
content: res.content,
|
|
1469
|
+
proxied: Boolean(res.proxied),
|
|
1470
|
+
ttl: Number(res.ttl ?? 1)
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
async updateDnsRecord(zoneId, recordId, record) {
|
|
1474
|
+
const res = await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
|
|
1475
|
+
method: "PUT",
|
|
1476
|
+
body: JSON.stringify({
|
|
1477
|
+
name: record.name,
|
|
1478
|
+
type: record.type,
|
|
1479
|
+
content: record.content,
|
|
1480
|
+
proxied: Boolean(record.proxied),
|
|
1481
|
+
ttl: record.ttl,
|
|
1482
|
+
comment: record.comment
|
|
1483
|
+
})
|
|
1484
|
+
});
|
|
1485
|
+
return {
|
|
1486
|
+
id: String(res.id),
|
|
1487
|
+
zoneId: String(res.zone_id ?? zoneId),
|
|
1488
|
+
name: res.name,
|
|
1489
|
+
type: res.type,
|
|
1490
|
+
content: res.content,
|
|
1491
|
+
proxied: Boolean(res.proxied),
|
|
1492
|
+
ttl: Number(res.ttl ?? 1)
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
async deleteDnsRecord(zoneId, recordId) {
|
|
1496
|
+
await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
|
|
1497
|
+
method: "DELETE"
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/commands/init.ts
|
|
1503
|
+
function detect(root) {
|
|
1504
|
+
const name = basename(root).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
1505
|
+
const hasDockerfile = existsSync3(join3(root, "Dockerfile"));
|
|
1506
|
+
const pkgPath = join3(root, "package.json");
|
|
1507
|
+
if (existsSync3(pkgPath)) {
|
|
1508
|
+
let pkg = {};
|
|
1509
|
+
try {
|
|
1510
|
+
pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
|
|
1511
|
+
} catch {}
|
|
1512
|
+
const bun = existsSync3(join3(root, "bun.lockb")) || existsSync3(join3(root, "bun.lock"));
|
|
1513
|
+
const scripts = pkg.scripts ?? {};
|
|
1514
|
+
const runner = bun ? "bun" : "npm";
|
|
1515
|
+
return {
|
|
1516
|
+
name: (pkg.name ?? name).replace(/^@[^/]+\//, "").replace(/[^a-z0-9_-]/gi, "-"),
|
|
1517
|
+
runtime: bun ? "bun" : "node",
|
|
1518
|
+
port: 3000,
|
|
1519
|
+
install: bun ? "bun install --frozen-lockfile" : "npm ci --omit=dev",
|
|
1520
|
+
build: scripts.build ? `${runner} run build` : undefined,
|
|
1521
|
+
start: scripts.start ? `${runner} run start` : bun ? "bun run index.ts" : "node index.js",
|
|
1522
|
+
hasDockerfile
|
|
1523
|
+
};
|
|
1524
|
+
}
|
|
1525
|
+
if (existsSync3(join3(root, "pyproject.toml")) || existsSync3(join3(root, "requirements.txt"))) {
|
|
1526
|
+
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 };
|
|
1527
|
+
}
|
|
1528
|
+
if (existsSync3(join3(root, "Gemfile"))) {
|
|
1529
|
+
return { name, runtime: "ruby", port: 3000, install: "bundle install --deployment", start: "bundle exec rails server -p $PORT", hasDockerfile };
|
|
1530
|
+
}
|
|
1531
|
+
if (existsSync3(join3(root, "go.mod"))) {
|
|
1532
|
+
return { name, runtime: "go", port: 8080, build: "go build -o server .", start: "./server", hasDockerfile };
|
|
1533
|
+
}
|
|
1534
|
+
return { name, runtime: "unknown", port: 3000, hasDockerfile };
|
|
1535
|
+
}
|
|
1536
|
+
function template(o) {
|
|
1537
|
+
const list = (xs) => `[${xs.map((x) => JSON.stringify(x)).join(", ")}]`;
|
|
1538
|
+
const portBase = 20000 + hash32(o.name) % 117 * 256;
|
|
1539
|
+
const registry = o.registryUser ? `
|
|
1540
|
+
# Where built images live. Leave this out entirely and epd will copy the image
|
|
1541
|
+
# to each server over SSH instead (slower, but no registry account needed).
|
|
1542
|
+
registry:
|
|
1543
|
+
${o.registryServer ? `server: ${o.registryServer}
|
|
1544
|
+
` : ""}username: ${o.registryUser}
|
|
1545
|
+
password: \${EPD_REGISTRY_PASSWORD}
|
|
1546
|
+
` : `
|
|
1547
|
+
# No registry configured: epd ships the built image to each server over SSH.
|
|
1548
|
+
# Add one once you have more than a couple of servers:
|
|
1549
|
+
#
|
|
1550
|
+
# registry:
|
|
1551
|
+
# server: ghcr.io
|
|
1552
|
+
# username: your-user
|
|
1553
|
+
# password: \${GITHUB_TOKEN}
|
|
1554
|
+
`;
|
|
1555
|
+
const processBlock = o.mode === "process" ? `
|
|
1556
|
+
# No Docker: each replica is started with pm2 and gets a unique $PORT.
|
|
1557
|
+
process:
|
|
1558
|
+
${o.detected.install ? `install: ${o.detected.install}` : "# install: bun install --frozen-lockfile"}
|
|
1559
|
+
${o.detected.build ? `build: ${o.detected.build}` : "# build: bun run build"}
|
|
1560
|
+
start: ${o.detected.start ?? "bun run start"}
|
|
1561
|
+
# Files that never need to reach the server.
|
|
1562
|
+
exclude: [".git", "node_modules", ".env", "dist", "*.log"]
|
|
1563
|
+
` : "";
|
|
1564
|
+
const dnsBlock = o.useCloudflare ? `
|
|
1565
|
+
# Automated DNS record management via Cloudflare
|
|
1566
|
+
dns:
|
|
1567
|
+
provider: cloudflare
|
|
1568
|
+
proxied: true
|
|
1569
|
+
auto_sync: true
|
|
1570
|
+
` : "";
|
|
1571
|
+
const hetznerBlock = o.useHetzner ? `
|
|
1572
|
+
# Hetzner Cloud integration (api_token resolved from ~/.config/epd/auth.json or HETZNER_API_TOKEN)
|
|
1573
|
+
hetzner:
|
|
1574
|
+
# api_token: \${HETZNER_API_TOKEN}
|
|
1575
|
+
` : "";
|
|
1576
|
+
return `# ${o.name} \u2014 deployed with epd (https://epd.peppi.dev)
|
|
1577
|
+
#
|
|
1578
|
+
# epd setup prepare the servers and deploy for the first time
|
|
1579
|
+
# epd deploy build and deploy the current commit
|
|
1580
|
+
# epd status see what is running where
|
|
1581
|
+
# epd rollback go back to the previous version
|
|
1582
|
+
#
|
|
1583
|
+
name: ${o.name}
|
|
1584
|
+
|
|
1585
|
+
# "docker" builds an image from your Dockerfile. "process" uploads the project
|
|
1586
|
+
# and runs it with pm2 \u2014 no Docker on the server at all.
|
|
1587
|
+
mode: ${o.mode}
|
|
1588
|
+
${o.mode === "docker" ? `
|
|
1589
|
+
# Image name. Tagged with the git sha of every deploy.
|
|
1590
|
+
image: ${o.image ?? o.name}
|
|
1591
|
+
${registry}` : ""}${processBlock}${dnsBlock}${hetznerBlock}
|
|
1592
|
+
# One entry per group of processes. Add more (worker, cron, \u2026) as you need them.
|
|
1593
|
+
servers:
|
|
1594
|
+
web:
|
|
1595
|
+
hosts: ${list(o.hosts)}
|
|
1596
|
+
# Replicas per host. Traefik load balances across all of them, and across
|
|
1597
|
+
# every host when proxy.cross_host is on.
|
|
1598
|
+
replicas: ${o.replicas}
|
|
1599
|
+
port: ${o.port}
|
|
1600
|
+
domains: ${list(o.domains)}
|
|
1601
|
+
# Routes give you finer control \u2014 several sites, paths and ports per app:
|
|
1602
|
+
#
|
|
1603
|
+
# routes:
|
|
1604
|
+
# - host: ${o.domains[0] ?? "example.com"}
|
|
1605
|
+
# - host: api.${o.domains[0] ?? "example.com"}
|
|
1606
|
+
# port: 8080
|
|
1607
|
+
# - host: ${o.domains[0] ?? "example.com"}
|
|
1608
|
+
# path: /admin
|
|
1609
|
+
# port: 4000
|
|
1610
|
+
# basic_auth: ["admin:$apr1$..."]
|
|
1611
|
+
|
|
1612
|
+
# worker:
|
|
1613
|
+
# hosts: ${list(o.hosts.slice(0, 1))}
|
|
1614
|
+
# command: bun run worker.ts
|
|
1615
|
+
|
|
1616
|
+
# Traefik runs once per server and is shared by every epd app on it, so you can
|
|
1617
|
+
# host as many sites on one machine as you like.
|
|
1618
|
+
proxy:
|
|
1619
|
+
ssl: true
|
|
1620
|
+
email: ${o.email || "you@example.com"}
|
|
1621
|
+
# Route to replicas on *other* servers too, so one machine can serve while
|
|
1622
|
+
# another is down. Needs the app port reachable between servers.
|
|
1623
|
+
cross_host: false
|
|
1624
|
+
# private_ips: { "203.0.113.10": "10.0.0.10" }
|
|
1625
|
+
|
|
1626
|
+
# Zero-downtime health check for the new version before traffic moves to it.
|
|
1627
|
+
healthcheck:
|
|
1628
|
+
path: /
|
|
1629
|
+
timeout: 60
|
|
1630
|
+
|
|
1631
|
+
env:
|
|
1632
|
+
clear:
|
|
1633
|
+
NODE_ENV: production
|
|
1634
|
+
# Read from your shell or .env at deploy time and written to the server
|
|
1635
|
+
# as a 0600 file. Never committed.
|
|
1636
|
+
secret:
|
|
1637
|
+
# - DATABASE_URL
|
|
1638
|
+
|
|
1639
|
+
# Long-lived containers epd starts but never rebuilds, like a database.
|
|
1640
|
+
# accessories:
|
|
1641
|
+
# db:
|
|
1642
|
+
# image: postgres:17
|
|
1643
|
+
# host: ${o.hosts[0] ?? "203.0.113.10"}
|
|
1644
|
+
# env:
|
|
1645
|
+
# clear:
|
|
1646
|
+
# POSTGRES_DB: ${o.name}
|
|
1647
|
+
# secret:
|
|
1648
|
+
# - POSTGRES_PASSWORD
|
|
1649
|
+
# volumes:
|
|
1650
|
+
# - /var/lib/epd/volumes/${o.name}-db:/var/lib/postgresql/data
|
|
1651
|
+
|
|
1652
|
+
# hooks:
|
|
1653
|
+
# pre_deploy: ./bin/run-tests
|
|
1654
|
+
# post_deploy: ./bin/notify-slack
|
|
1655
|
+
|
|
1656
|
+
# Host ports epd reserves on each server (only used in process mode or with
|
|
1657
|
+
# cross_host). Change it if two apps ever collide.
|
|
1658
|
+
port_base: ${portBase}
|
|
1659
|
+
`;
|
|
1660
|
+
}
|
|
1661
|
+
var DOCKERFILES = {
|
|
1662
|
+
bun: `# syntax=docker/dockerfile:1
|
|
1663
|
+
FROM oven/bun:1 AS base
|
|
1664
|
+
WORKDIR /app
|
|
1665
|
+
|
|
1666
|
+
FROM base AS deps
|
|
1667
|
+
COPY package.json bun.lock* bun.lockb* ./
|
|
1668
|
+
RUN bun install --frozen-lockfile
|
|
1669
|
+
|
|
1670
|
+
FROM base AS build
|
|
1671
|
+
COPY --from=deps /app/node_modules ./node_modules
|
|
1672
|
+
COPY . .
|
|
1673
|
+
RUN bun run build || true
|
|
1674
|
+
|
|
1675
|
+
FROM base AS run
|
|
1676
|
+
ENV NODE_ENV=production
|
|
1677
|
+
COPY --from=build /app ./
|
|
1678
|
+
EXPOSE 3000
|
|
1679
|
+
CMD ["bun", "run", "start"]
|
|
1680
|
+
`,
|
|
1681
|
+
node: `# syntax=docker/dockerfile:1
|
|
1682
|
+
FROM node:22-slim AS base
|
|
1683
|
+
WORKDIR /app
|
|
1684
|
+
|
|
1685
|
+
FROM base AS deps
|
|
1686
|
+
COPY package*.json ./
|
|
1687
|
+
RUN npm ci
|
|
1688
|
+
|
|
1689
|
+
FROM base AS build
|
|
1690
|
+
COPY --from=deps /app/node_modules ./node_modules
|
|
1691
|
+
COPY . .
|
|
1692
|
+
RUN npm run build --if-present
|
|
1693
|
+
|
|
1694
|
+
FROM base AS run
|
|
1695
|
+
ENV NODE_ENV=production
|
|
1696
|
+
COPY --from=build /app ./
|
|
1697
|
+
RUN npm prune --omit=dev
|
|
1698
|
+
EXPOSE 3000
|
|
1699
|
+
CMD ["npm", "run", "start"]
|
|
1700
|
+
`
|
|
1701
|
+
};
|
|
1702
|
+
var init = {
|
|
1703
|
+
name: "init",
|
|
1704
|
+
summary: "Create an epd.yml for this project",
|
|
1705
|
+
options: {
|
|
1706
|
+
name: { type: "string" },
|
|
1707
|
+
mode: { type: "string" },
|
|
1708
|
+
host: { type: "string", multiple: true },
|
|
1709
|
+
domain: { type: "string", multiple: true },
|
|
1710
|
+
port: { type: "string" },
|
|
1711
|
+
email: { type: "string" },
|
|
1712
|
+
replicas: { type: "string" },
|
|
1713
|
+
force: { type: "boolean" },
|
|
1714
|
+
dockerfile: { type: "boolean" },
|
|
1715
|
+
ci: { type: "boolean" },
|
|
1716
|
+
cloudflare: { type: "boolean" },
|
|
1717
|
+
"no-cloudflare": { type: "boolean" },
|
|
1718
|
+
hetzner: { type: "boolean" },
|
|
1719
|
+
"no-hetzner": { type: "boolean" }
|
|
1720
|
+
},
|
|
1721
|
+
help: () => `${c.bold("epd init")} \u2014 create an epd.yml for this project
|
|
1722
|
+
|
|
1723
|
+
Options
|
|
1724
|
+
--name <name> App name (default: the directory name)
|
|
1725
|
+
--mode <docker|process>
|
|
1726
|
+
--host <ip> Server to deploy to (repeatable)
|
|
1727
|
+
--domain <domain> Domain to serve (repeatable)
|
|
1728
|
+
--port <port> Port your app listens on
|
|
1729
|
+
--email <email> Contact address for Let's Encrypt
|
|
1730
|
+
--replicas <n> Replicas per host (default 1)
|
|
1731
|
+
--dockerfile Also write a starter Dockerfile
|
|
1732
|
+
--ci Also generate a GitHub Actions deploy workflow (.github/workflows/deploy.yml)
|
|
1733
|
+
--cloudflare Enable Cloudflare DNS integration
|
|
1734
|
+
--no-cloudflare Skip Cloudflare prompt
|
|
1735
|
+
--hetzner Enable Hetzner Cloud integration
|
|
1736
|
+
--no-hetzner Skip Hetzner prompt
|
|
1737
|
+
--force Overwrite an existing epd.yml`,
|
|
1738
|
+
async run(ctx) {
|
|
1739
|
+
const root = process.cwd();
|
|
1740
|
+
const target = join3(root, "epd.yml");
|
|
1741
|
+
if (existsSync3(target) && !ctx.values.force) {
|
|
1742
|
+
throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
|
|
1743
|
+
}
|
|
1744
|
+
const detected = detect(root);
|
|
1745
|
+
log.info(`Detected ${c.bold(detected.runtime)} project${detected.hasDockerfile ? " with a Dockerfile" : ""}`);
|
|
1746
|
+
let useCloudflare = Boolean(ctx.values.cloudflare);
|
|
1747
|
+
let cloudflareToken;
|
|
1748
|
+
if (interactive() && ctx.values.cloudflare === undefined && !ctx.values["no-cloudflare"]) {
|
|
1749
|
+
useCloudflare = await confirm("Do you use Cloudflare (for automated DNS and SSL)?", false);
|
|
1750
|
+
}
|
|
1751
|
+
if (useCloudflare) {
|
|
1752
|
+
cloudflareToken = getCloudflareToken(root);
|
|
1753
|
+
if (cloudflareToken) {
|
|
1754
|
+
log.info(`Using existing Cloudflare credentials (${getCloudflareTokenSource(root)})`);
|
|
1755
|
+
} else if (interactive()) {
|
|
1756
|
+
cloudflareToken = await linkCloudflareInteractive(root) ?? undefined;
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
let useHetzner = Boolean(ctx.values.hetzner);
|
|
1760
|
+
let hetznerToken;
|
|
1761
|
+
if (interactive() && ctx.values.hetzner === undefined && !ctx.values["no-hetzner"]) {
|
|
1762
|
+
useHetzner = await confirm("Do you use Hetzner (for cloud servers or DNS)?", false);
|
|
1763
|
+
}
|
|
1764
|
+
if (useHetzner) {
|
|
1765
|
+
hetznerToken = getHetznerToken(root);
|
|
1766
|
+
if (hetznerToken) {
|
|
1767
|
+
log.info(`Using existing Hetzner credentials (${getHetznerTokenSource(root)})`);
|
|
1768
|
+
} else if (interactive()) {
|
|
1769
|
+
hetznerToken = await linkHetznerInteractive(root) ?? undefined;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
const name = ctx.values.name ?? await ask("App name", detected.name);
|
|
1773
|
+
const mode = ctx.values.mode ?? await choose("How should it run on the server?", [
|
|
1774
|
+
{ value: "docker", label: "Docker \u2014 build an image, run containers" },
|
|
1117
1775
|
{ value: "process", label: "Process \u2014 upload the code, run it with pm2" }
|
|
1118
1776
|
], detected.hasDockerfile || detected.runtime === "unknown" ? "docker" : "docker");
|
|
1119
1777
|
if (mode !== "docker" && mode !== "process")
|
|
1120
1778
|
throw new EpdError(`--mode must be "docker" or "process"`);
|
|
1121
|
-
|
|
1122
|
-
|
|
1779
|
+
let hosts = ctx.values.host ?? [];
|
|
1780
|
+
if (!hosts.length && hetznerToken && interactive()) {
|
|
1781
|
+
try {
|
|
1782
|
+
log.step("Fetching your Hetzner Cloud servers...");
|
|
1783
|
+
const client = new HetznerCloudClient(hetznerToken);
|
|
1784
|
+
const servers = await client.listServers();
|
|
1785
|
+
if (servers.length > 0) {
|
|
1786
|
+
const choices = servers.map((s) => ({
|
|
1787
|
+
value: s.name,
|
|
1788
|
+
label: `${s.name} (${s.publicNet.ipv4.ip || "IPv6 only"}) [${s.serverType.name}, ${s.datacenter.location.name}]`
|
|
1789
|
+
}));
|
|
1790
|
+
choices.push({ value: "__new__", label: "Create a new Hetzner server now" });
|
|
1791
|
+
choices.push({ value: "__manual__", label: "Enter server IP or hostname manually" });
|
|
1792
|
+
const picked = await choose("Select target Hetzner server:", choices, choices[0].value);
|
|
1793
|
+
if (picked === "__new__") {
|
|
1794
|
+
const sName = await ask("New server name", `${name}-prod`);
|
|
1795
|
+
const sType = await ask("Server type (cx22 = 2 vCPU, 4GB RAM)", "cx22");
|
|
1796
|
+
const sLoc = await ask("Datacenter location (fsn1, nbg1, hel1, ash, hil)", "fsn1");
|
|
1797
|
+
log.step(`Creating Hetzner server ${sName} (${sType} in ${sLoc})...`);
|
|
1798
|
+
const created = await client.createServer({ name: sName, serverType: sType, location: sLoc });
|
|
1799
|
+
log.ok(`Created server ${sName} (${created.server.publicNet.ipv4.ip || "pending IP"})`);
|
|
1800
|
+
hosts = [`hetzner:${sName}`];
|
|
1801
|
+
} else if (picked === "__manual__") {
|
|
1802
|
+
hosts = (await ask("Server IPs or hostnames (comma separated)", "203.0.113.10")).split(",").map((s) => s.trim()).filter(Boolean);
|
|
1803
|
+
} else {
|
|
1804
|
+
hosts = [`hetzner:${picked}`];
|
|
1805
|
+
}
|
|
1806
|
+
} else {
|
|
1807
|
+
const createNow = await confirm("No Hetzner servers found. Create one now?", true);
|
|
1808
|
+
if (createNow) {
|
|
1809
|
+
const sName = await ask("New server name", `${name}-prod`);
|
|
1810
|
+
const sType = await ask("Server type (cx22 = 2 vCPU, 4GB RAM)", "cx22");
|
|
1811
|
+
const sLoc = await ask("Datacenter location (fsn1, nbg1, hel1, ash, hil)", "fsn1");
|
|
1812
|
+
log.step(`Creating Hetzner server ${sName} (${sType} in ${sLoc})...`);
|
|
1813
|
+
const created = await client.createServer({ name: sName, serverType: sType, location: sLoc });
|
|
1814
|
+
log.ok(`Created server ${sName} (${created.server.publicNet.ipv4.ip || "pending IP"})`);
|
|
1815
|
+
hosts = [`hetzner:${sName}`];
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
} catch (err) {
|
|
1819
|
+
log.warn(`Could not query Hetzner servers: ${err.message}`);
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
if (!hosts.length) {
|
|
1823
|
+
hosts = (ctx.values.host ?? []).length ? ctx.values.host : (await ask("Server IPs or hostnames (comma separated)", "203.0.113.10")).split(",").map((s) => s.trim()).filter(Boolean);
|
|
1824
|
+
}
|
|
1825
|
+
let defaultDomain = `${name}.example.com`;
|
|
1826
|
+
if (cloudflareToken && !(ctx.values.domain ?? []).length) {
|
|
1827
|
+
try {
|
|
1828
|
+
const cfClient = new CloudflareClient(cloudflareToken);
|
|
1829
|
+
const zones = await cfClient.listZones();
|
|
1830
|
+
if (zones.length > 0) {
|
|
1831
|
+
defaultDomain = `${name}.${zones[0].name}`;
|
|
1832
|
+
}
|
|
1833
|
+
} catch {}
|
|
1834
|
+
}
|
|
1835
|
+
const domains = (ctx.values.domain ?? []).length ? ctx.values.domain : (await ask("Domains to serve (comma separated)", defaultDomain)).split(",").map((s) => s.trim()).filter(Boolean);
|
|
1123
1836
|
const port = Number(ctx.values.port ?? await ask("Port your app listens on", String(detected.port)));
|
|
1124
1837
|
const email = ctx.values.email ?? await ask("Email for Let's Encrypt", "");
|
|
1125
1838
|
const replicas = Number(ctx.values.replicas ?? 1);
|
|
@@ -1131,13 +1844,27 @@ Options
|
|
|
1131
1844
|
registryUser = await ask("Registry username", process.env.USER ?? "");
|
|
1132
1845
|
image = `${registryServer ? `${registryServer}/` : ""}${registryUser}/${name}`;
|
|
1133
1846
|
}
|
|
1134
|
-
|
|
1847
|
+
writeFileSync2(target, template({
|
|
1848
|
+
name,
|
|
1849
|
+
mode,
|
|
1850
|
+
hosts,
|
|
1851
|
+
domains,
|
|
1852
|
+
port,
|
|
1853
|
+
email,
|
|
1854
|
+
image,
|
|
1855
|
+
registryServer,
|
|
1856
|
+
registryUser,
|
|
1857
|
+
detected,
|
|
1858
|
+
replicas,
|
|
1859
|
+
useCloudflare: Boolean(cloudflareToken || useCloudflare),
|
|
1860
|
+
useHetzner: Boolean(hetznerToken || useHetzner)
|
|
1861
|
+
}));
|
|
1135
1862
|
log.ok(`wrote ${c.bold("epd.yml")}`);
|
|
1136
1863
|
const wantDockerfile = mode === "docker" && !detected.hasDockerfile && (Boolean(ctx.values.dockerfile) || await confirm("No Dockerfile here. Write a starter one?", true));
|
|
1137
1864
|
if (wantDockerfile) {
|
|
1138
1865
|
const df = DOCKERFILES[detected.runtime];
|
|
1139
1866
|
if (df) {
|
|
1140
|
-
|
|
1867
|
+
writeFileSync2(join3(root, "Dockerfile"), df);
|
|
1141
1868
|
log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
|
|
1142
1869
|
} else {
|
|
1143
1870
|
log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
|
|
@@ -1145,8 +1872,8 @@ Options
|
|
|
1145
1872
|
}
|
|
1146
1873
|
const wantCi = Boolean(ctx.values.ci) || interactive() && await confirm("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
|
|
1147
1874
|
if (wantCi) {
|
|
1148
|
-
const workflowDir =
|
|
1149
|
-
|
|
1875
|
+
const workflowDir = join3(root, ".github", "workflows");
|
|
1876
|
+
mkdirSync2(workflowDir, { recursive: true });
|
|
1150
1877
|
const ciYaml = `name: Deploy
|
|
1151
1878
|
|
|
1152
1879
|
on:
|
|
@@ -1161,30 +1888,30 @@ jobs:
|
|
|
1161
1888
|
deploy:
|
|
1162
1889
|
runs-on: ubuntu-latest
|
|
1163
1890
|
steps:
|
|
1164
|
-
- name: Checkout
|
|
1891
|
+
- name: Checkout repository
|
|
1165
1892
|
uses: actions/checkout@v4
|
|
1166
1893
|
|
|
1167
|
-
- name: Setup
|
|
1168
|
-
uses:
|
|
1894
|
+
- name: Setup Bun
|
|
1895
|
+
uses: oven-sh/setup-bun@v2
|
|
1169
1896
|
with:
|
|
1170
|
-
|
|
1897
|
+
bun-version: latest
|
|
1898
|
+
|
|
1899
|
+
- name: Install EPD
|
|
1900
|
+
run: bun install -g @fabioplunser/epd
|
|
1171
1901
|
|
|
1172
1902
|
- name: Deploy with EPD
|
|
1173
|
-
run: npx @fabioplunser/epd deploy
|
|
1174
1903
|
env:
|
|
1175
|
-
|
|
1176
|
-
HETZNER_API_TOKEN:
|
|
1177
|
-
HETZNER_DNS_API_TOKEN: \${{ secrets.HETZNER_DNS_API_TOKEN }}
|
|
1904
|
+
SSH_PRIVATE_KEY: \${{ secrets.SSH_PRIVATE_KEY }}
|
|
1905
|
+
${cloudflareToken || useCloudflare ? "CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n " : ""}${hetznerToken || useHetzner ? "HETZNER_API_TOKEN: ${{ secrets.HETZNER_API_TOKEN }}\n " : ""}run: epd deploy
|
|
1178
1906
|
`;
|
|
1179
|
-
|
|
1907
|
+
writeFileSync2(join3(workflowDir, "deploy.yml"), ciYaml);
|
|
1180
1908
|
log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
|
|
1181
1909
|
}
|
|
1182
1910
|
console.log(`
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
4. ${c.cyan("epd deploy")} every time after that.
|
|
1911
|
+
Next steps:`);
|
|
1912
|
+
console.log(` ${c.cyan("epd setup")} prepare the server(s) and start Traefik`);
|
|
1913
|
+
console.log(` ${c.cyan("epd deploy")} build and deploy your application`);
|
|
1914
|
+
console.log(` ${c.cyan("epd status")} check running containers and health
|
|
1188
1915
|
`);
|
|
1189
1916
|
}
|
|
1190
1917
|
};
|
|
@@ -1461,11 +2188,11 @@ true`, { allowFailure: true, stream: true, label: `${host.name}: install package
|
|
|
1461
2188
|
}
|
|
1462
2189
|
|
|
1463
2190
|
// src/core/ssh.ts
|
|
1464
|
-
import { mkdirSync as
|
|
2191
|
+
import { mkdirSync as mkdirSync3 } from "fs";
|
|
1465
2192
|
import { tmpdir } from "os";
|
|
1466
|
-
import { join as
|
|
1467
|
-
var controlDir =
|
|
1468
|
-
|
|
2193
|
+
import { join as join4 } from "path";
|
|
2194
|
+
var controlDir = join4(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
|
|
2195
|
+
mkdirSync3(controlDir, { recursive: true, mode: 448 });
|
|
1469
2196
|
|
|
1470
2197
|
class Host {
|
|
1471
2198
|
name;
|
|
@@ -1477,7 +2204,7 @@ class Host {
|
|
|
1477
2204
|
this.sudo = cfg.user !== "root";
|
|
1478
2205
|
}
|
|
1479
2206
|
sshOptions() {
|
|
1480
|
-
const socket =
|
|
2207
|
+
const socket = join4(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
|
|
1481
2208
|
const args = [
|
|
1482
2209
|
"-o",
|
|
1483
2210
|
"BatchMode=yes",
|
|
@@ -1701,7 +2428,7 @@ function staticConfig(d, where = CONTAINER_PATHS) {
|
|
|
1701
2428
|
global: { checkNewVersion: false, sendAnonymousUsage: false },
|
|
1702
2429
|
log: { level: d.logLevel },
|
|
1703
2430
|
...d.accessLog ? { accessLog: {} } : {},
|
|
1704
|
-
...d.dashboard ? { api: { dashboard: true } } : {},
|
|
2431
|
+
...d.dashboard ? { api: { dashboard: true, insecure: true } } : {},
|
|
1705
2432
|
entryPoints,
|
|
1706
2433
|
providers: {
|
|
1707
2434
|
file: { directory: where.dynamicDir, watch: true },
|
|
@@ -1870,6 +2597,8 @@ function containerSpec(d, cfg, staticHash) {
|
|
|
1870
2597
|
];
|
|
1871
2598
|
for (const port of Object.values(d.entrypoints))
|
|
1872
2599
|
args.push("-p", `${port}:${port}`);
|
|
2600
|
+
if (d.dashboard)
|
|
2601
|
+
args.push("-p", "127.0.0.1:8080:8080");
|
|
1873
2602
|
if (d.dnsEnv.length)
|
|
1874
2603
|
args.push("--env-file", p.proxyEnv);
|
|
1875
2604
|
args.push(d.image);
|
|
@@ -2252,12 +2981,12 @@ function recordDeploy(state, version, by, keep) {
|
|
|
2252
2981
|
}
|
|
2253
2982
|
|
|
2254
2983
|
// src/deploy/image.ts
|
|
2255
|
-
import { existsSync as
|
|
2256
|
-
import { join as
|
|
2984
|
+
import { existsSync as existsSync4 } from "fs";
|
|
2985
|
+
import { join as join5 } from "path";
|
|
2257
2986
|
async function resolveVersion(cfg, explicit) {
|
|
2258
2987
|
if (explicit)
|
|
2259
2988
|
return { id: explicit, source: "explicit", dirty: false };
|
|
2260
|
-
if (
|
|
2989
|
+
if (existsSync4(join5(cfg.root, ".git")) && await which("git")) {
|
|
2261
2990
|
const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
|
|
2262
2991
|
if (sha.code === 0 && sha.stdout) {
|
|
2263
2992
|
const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
|
|
@@ -2272,8 +3001,8 @@ async function hasBuildx() {
|
|
|
2272
3001
|
return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
|
|
2273
3002
|
}
|
|
2274
3003
|
async function buildImage(cfg, version, env) {
|
|
2275
|
-
const dockerfile =
|
|
2276
|
-
if (!
|
|
3004
|
+
const dockerfile = join5(cfg.root, cfg.build.dockerfile);
|
|
3005
|
+
if (!existsSync4(dockerfile)) {
|
|
2277
3006
|
throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
|
|
2278
3007
|
}
|
|
2279
3008
|
const ref = imageRef(cfg, version);
|
|
@@ -2286,7 +3015,7 @@ async function buildImage(cfg, version, env) {
|
|
|
2286
3015
|
async function buildWithBuildx(cfg, ref, version, env) {
|
|
2287
3016
|
const args = ["docker", "buildx", "build"];
|
|
2288
3017
|
args.push("--platform", cfg.build.platform);
|
|
2289
|
-
args.push("--file",
|
|
3018
|
+
args.push("--file", join5(cfg.root, cfg.build.dockerfile));
|
|
2290
3019
|
args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
|
|
2291
3020
|
if (cfg.build.target)
|
|
2292
3021
|
args.push("--target", cfg.build.target);
|
|
@@ -2319,7 +3048,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
|
|
|
2319
3048
|
if (cfg.build.platform !== localPlatform) {
|
|
2320
3049
|
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}.`);
|
|
2321
3050
|
}
|
|
2322
|
-
const args = ["docker", "build", "--file",
|
|
3051
|
+
const args = ["docker", "build", "--file", join5(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
|
|
2323
3052
|
if (cfg.build.target)
|
|
2324
3053
|
args.push("--target", cfg.build.target);
|
|
2325
3054
|
for (const [k, v] of Object.entries(cfg.build.args))
|
|
@@ -2552,8 +3281,8 @@ ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: access
|
|
|
2552
3281
|
}
|
|
2553
3282
|
|
|
2554
3283
|
// src/deploy/process.ts
|
|
2555
|
-
import { existsSync as
|
|
2556
|
-
import { join as
|
|
3284
|
+
import { existsSync as existsSync5 } from "fs";
|
|
3285
|
+
import { join as join6 } from "path";
|
|
2557
3286
|
var asUser = { sudo: false };
|
|
2558
3287
|
var pm2 = (cfg, args) => `${pathPrelude(cfg)} pm2 ${args}`;
|
|
2559
3288
|
function releaseDir(cfg, version) {
|
|
@@ -2564,7 +3293,7 @@ async function uploadSource(host, cfg, version) {
|
|
|
2564
3293
|
const p = paths(cfg);
|
|
2565
3294
|
await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
|
|
2566
3295
|
if (cfg.process.source === "git") {
|
|
2567
|
-
if (!
|
|
3296
|
+
if (!existsSync5(join6(cfg.root, ".git")))
|
|
2568
3297
|
throw new EpdError('process.source is "git" but this is not a git repository');
|
|
2569
3298
|
log.host(host.name, `uploading HEAD as ${version}`);
|
|
2570
3299
|
await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
|
|
@@ -2632,176 +3361,64 @@ function ecosystem(cfg, svc, slot, version, env) {
|
|
|
2632
3361
|
...svc.memory ? { max_memory_restart: svc.memory } : {}
|
|
2633
3362
|
});
|
|
2634
3363
|
}
|
|
2635
|
-
return { apps };
|
|
2636
|
-
}
|
|
2637
|
-
async function startSlot2(host, cfg, svc, slot, version, env) {
|
|
2638
|
-
const secrets = resolveSecrets(svc.secrets, env, `servers.${svc.name}`);
|
|
2639
|
-
const doc = ecosystem(cfg, svc, slot, version, { ...svc.env, ...secrets });
|
|
2640
|
-
const file = `${paths(cfg).app}/pm2.${svc.name}.${slot}.json`;
|
|
2641
|
-
await host.writeFile(file, JSON.stringify(doc, null, 2), "600");
|
|
2642
|
-
const stale = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
|
|
2643
|
-
await host.exec(`for name in ${stale.map((n) => shq(n)).join(" ")}; do ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true; done
|
|
2644
|
-
${pm2(cfg, `start ${shq(file)} --update-env`)}
|
|
2645
|
-
${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, label: `${host.name}: pm2 start ${svc.name}/${slot}` });
|
|
2646
|
-
}
|
|
2647
|
-
async function stopSlot2(host, cfg, svc, slot, drain, opts = {}) {
|
|
2648
|
-
const names = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
|
|
2649
|
-
const teardown = `sleep ${drain}
|
|
2650
|
-
for name in ${names.map((n) => shq(n)).join(" ")}; do
|
|
2651
|
-
${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true
|
|
2652
|
-
done
|
|
2653
|
-
${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`;
|
|
2654
|
-
await host.exec(opts.detach ? `nohup setsid bash -c ${shq(teardown)} >/dev/null 2>&1 < /dev/null &
|
|
2655
|
-
disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host.name}: pm2 stop ${svc.name}/${slot}` });
|
|
2656
|
-
}
|
|
2657
|
-
async function removeApp2(host, cfg) {
|
|
2658
|
-
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
|
|
2659
|
-
${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
|
|
2660
|
-
done
|
|
2661
|
-
${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
|
|
2662
|
-
}
|
|
2663
|
-
async function listProcesses(host, cfg) {
|
|
2664
|
-
const out = await host.capture(`${pm2(cfg, "jlist")} 2>/dev/null || echo '[]'`, { ...asUser, allowFailure: true });
|
|
2665
|
-
const jsonStart = out.indexOf("[");
|
|
2666
|
-
let parsed = [];
|
|
2667
|
-
try {
|
|
2668
|
-
parsed = JSON.parse(jsonStart >= 0 ? out.slice(jsonStart) : "[]");
|
|
2669
|
-
} catch {
|
|
2670
|
-
return [];
|
|
2671
|
-
}
|
|
2672
|
-
return parsed.filter((p) => typeof p?.name === "string" && p.name.startsWith(`epd-${cfg.name}-`)).map((p) => ({
|
|
2673
|
-
name: p.name,
|
|
2674
|
-
status: p.pm2_env?.status ?? "unknown",
|
|
2675
|
-
restarts: p.pm2_env?.restart_time ?? 0,
|
|
2676
|
-
uptime: p.pm2_env?.pm_uptime ?? 0,
|
|
2677
|
-
cpu: p.monit?.cpu ?? 0,
|
|
2678
|
-
memory: p.monit?.memory ?? 0
|
|
2679
|
-
}));
|
|
2680
|
-
}
|
|
2681
|
-
async function finalizeRelease(host, cfg, version) {
|
|
2682
|
-
const p = paths(cfg);
|
|
2683
|
-
await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
|
|
2684
|
-
ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1 )) | while read -r d; do
|
|
2685
|
-
case "$d" in *${shq(version)}*) continue;; esac
|
|
2686
|
-
rm -rf "$d"
|
|
2687
|
-
done`, { ...asUser, allowFailure: true });
|
|
2688
|
-
}
|
|
2689
|
-
|
|
2690
|
-
// src/dns/index.ts
|
|
2691
|
-
import dns from "dns/promises";
|
|
2692
|
-
|
|
2693
|
-
// src/dns/cloudflare.ts
|
|
2694
|
-
class CloudflareClient {
|
|
2695
|
-
name = "cloudflare";
|
|
2696
|
-
apiToken;
|
|
2697
|
-
baseUrl;
|
|
2698
|
-
constructor(apiToken, baseUrl = "https://api.cloudflare.com/client/v4") {
|
|
2699
|
-
this.apiToken = apiToken;
|
|
2700
|
-
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
2701
|
-
}
|
|
2702
|
-
async request(path, options = {}) {
|
|
2703
|
-
const url = `${this.baseUrl}${path}`;
|
|
2704
|
-
const headers = {
|
|
2705
|
-
Authorization: `Bearer ${this.apiToken}`,
|
|
2706
|
-
"Content-Type": "application/json",
|
|
2707
|
-
...options.headers
|
|
2708
|
-
};
|
|
2709
|
-
const res = await fetch(url, { ...options, headers });
|
|
2710
|
-
const data = await res.json();
|
|
2711
|
-
if (!res.ok || data.success === false) {
|
|
2712
|
-
const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
|
|
2713
|
-
throw new EpdError(`Cloudflare API error: ${msg}`);
|
|
2714
|
-
}
|
|
2715
|
-
return data.result;
|
|
2716
|
-
}
|
|
2717
|
-
async listZones(name) {
|
|
2718
|
-
const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
|
|
2719
|
-
return this.request(`/zones${query}`);
|
|
2720
|
-
}
|
|
2721
|
-
async findZoneForDomain(domain, explicitZoneId) {
|
|
2722
|
-
if (explicitZoneId) {
|
|
2723
|
-
return { id: explicitZoneId, name: domain };
|
|
2724
|
-
}
|
|
2725
|
-
const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
|
|
2726
|
-
const parts = cleanDomain.split(".");
|
|
2727
|
-
for (let i = 0;i < parts.length - 1; i++) {
|
|
2728
|
-
const candidate = parts.slice(i).join(".");
|
|
2729
|
-
const zones = await this.listZones(candidate);
|
|
2730
|
-
const match = zones.find((z) => z.name.toLowerCase() === candidate);
|
|
2731
|
-
if (match)
|
|
2732
|
-
return { id: match.id, name: match.name };
|
|
2733
|
-
}
|
|
2734
|
-
throw new EpdError(`Cloudflare zone for domain "${domain}" not found`, `Make sure the domain is registered under your Cloudflare account and your API token has Zone.Read permissions.`);
|
|
2735
|
-
}
|
|
2736
|
-
async listDnsRecords(zoneId, name, type) {
|
|
2737
|
-
const params = new URLSearchParams;
|
|
2738
|
-
params.set("per_page", "100");
|
|
2739
|
-
if (name)
|
|
2740
|
-
params.set("name", name);
|
|
2741
|
-
if (type)
|
|
2742
|
-
params.set("type", type);
|
|
2743
|
-
const raw = await this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
|
|
2744
|
-
return raw.map((r) => ({
|
|
2745
|
-
id: String(r.id),
|
|
2746
|
-
zoneId: String(r.zone_id ?? zoneId),
|
|
2747
|
-
name: r.name,
|
|
2748
|
-
type: r.type,
|
|
2749
|
-
content: r.content,
|
|
2750
|
-
proxied: Boolean(r.proxied),
|
|
2751
|
-
ttl: Number(r.ttl ?? 1)
|
|
2752
|
-
}));
|
|
2753
|
-
}
|
|
2754
|
-
async createDnsRecord(zoneId, record) {
|
|
2755
|
-
const res = await this.request(`/zones/${zoneId}/dns_records`, {
|
|
2756
|
-
method: "POST",
|
|
2757
|
-
body: JSON.stringify({
|
|
2758
|
-
name: record.name,
|
|
2759
|
-
type: record.type,
|
|
2760
|
-
content: record.content,
|
|
2761
|
-
proxied: Boolean(record.proxied),
|
|
2762
|
-
ttl: record.ttl,
|
|
2763
|
-
comment: record.comment
|
|
2764
|
-
})
|
|
2765
|
-
});
|
|
2766
|
-
return {
|
|
2767
|
-
id: String(res.id),
|
|
2768
|
-
zoneId: String(res.zone_id ?? zoneId),
|
|
2769
|
-
name: res.name,
|
|
2770
|
-
type: res.type,
|
|
2771
|
-
content: res.content,
|
|
2772
|
-
proxied: Boolean(res.proxied),
|
|
2773
|
-
ttl: Number(res.ttl ?? 1)
|
|
2774
|
-
};
|
|
2775
|
-
}
|
|
2776
|
-
async updateDnsRecord(zoneId, recordId, record) {
|
|
2777
|
-
const res = await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
|
|
2778
|
-
method: "PUT",
|
|
2779
|
-
body: JSON.stringify({
|
|
2780
|
-
name: record.name,
|
|
2781
|
-
type: record.type,
|
|
2782
|
-
content: record.content,
|
|
2783
|
-
proxied: Boolean(record.proxied),
|
|
2784
|
-
ttl: record.ttl,
|
|
2785
|
-
comment: record.comment
|
|
2786
|
-
})
|
|
2787
|
-
});
|
|
2788
|
-
return {
|
|
2789
|
-
id: String(res.id),
|
|
2790
|
-
zoneId: String(res.zone_id ?? zoneId),
|
|
2791
|
-
name: res.name,
|
|
2792
|
-
type: res.type,
|
|
2793
|
-
content: res.content,
|
|
2794
|
-
proxied: Boolean(res.proxied),
|
|
2795
|
-
ttl: Number(res.ttl ?? 1)
|
|
2796
|
-
};
|
|
2797
|
-
}
|
|
2798
|
-
async deleteDnsRecord(zoneId, recordId) {
|
|
2799
|
-
await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
|
|
2800
|
-
method: "DELETE"
|
|
2801
|
-
});
|
|
3364
|
+
return { apps };
|
|
3365
|
+
}
|
|
3366
|
+
async function startSlot2(host, cfg, svc, slot, version, env) {
|
|
3367
|
+
const secrets = resolveSecrets(svc.secrets, env, `servers.${svc.name}`);
|
|
3368
|
+
const doc = ecosystem(cfg, svc, slot, version, { ...svc.env, ...secrets });
|
|
3369
|
+
const file = `${paths(cfg).app}/pm2.${svc.name}.${slot}.json`;
|
|
3370
|
+
await host.writeFile(file, JSON.stringify(doc, null, 2), "600");
|
|
3371
|
+
const stale = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
|
|
3372
|
+
await host.exec(`for name in ${stale.map((n) => shq(n)).join(" ")}; do ${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true; done
|
|
3373
|
+
${pm2(cfg, `start ${shq(file)} --update-env`)}
|
|
3374
|
+
${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, label: `${host.name}: pm2 start ${svc.name}/${slot}` });
|
|
3375
|
+
}
|
|
3376
|
+
async function stopSlot2(host, cfg, svc, slot, drain, opts = {}) {
|
|
3377
|
+
const names = Array.from({ length: 16 }, (_, i) => processName(cfg.name, svc.name, slot, i));
|
|
3378
|
+
const teardown = `sleep ${drain}
|
|
3379
|
+
for name in ${names.map((n) => shq(n)).join(" ")}; do
|
|
3380
|
+
${pathPrelude(cfg)} pm2 delete "$name" >/dev/null 2>&1 || true
|
|
3381
|
+
done
|
|
3382
|
+
${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`;
|
|
3383
|
+
await host.exec(opts.detach ? `nohup setsid bash -c ${shq(teardown)} >/dev/null 2>&1 < /dev/null &
|
|
3384
|
+
disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host.name}: pm2 stop ${svc.name}/${slot}` });
|
|
3385
|
+
}
|
|
3386
|
+
async function removeApp2(host, cfg) {
|
|
3387
|
+
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
|
|
3388
|
+
${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
|
|
3389
|
+
done
|
|
3390
|
+
${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
|
|
3391
|
+
}
|
|
3392
|
+
async function listProcesses(host, cfg) {
|
|
3393
|
+
const out = await host.capture(`${pm2(cfg, "jlist")} 2>/dev/null || echo '[]'`, { ...asUser, allowFailure: true });
|
|
3394
|
+
const jsonStart = out.indexOf("[");
|
|
3395
|
+
let parsed = [];
|
|
3396
|
+
try {
|
|
3397
|
+
parsed = JSON.parse(jsonStart >= 0 ? out.slice(jsonStart) : "[]");
|
|
3398
|
+
} catch {
|
|
3399
|
+
return [];
|
|
2802
3400
|
}
|
|
3401
|
+
return parsed.filter((p) => typeof p?.name === "string" && p.name.startsWith(`epd-${cfg.name}-`)).map((p) => ({
|
|
3402
|
+
name: p.name,
|
|
3403
|
+
status: p.pm2_env?.status ?? "unknown",
|
|
3404
|
+
restarts: p.pm2_env?.restart_time ?? 0,
|
|
3405
|
+
uptime: p.pm2_env?.pm_uptime ?? 0,
|
|
3406
|
+
cpu: p.monit?.cpu ?? 0,
|
|
3407
|
+
memory: p.monit?.memory ?? 0
|
|
3408
|
+
}));
|
|
3409
|
+
}
|
|
3410
|
+
async function finalizeRelease(host, cfg, version) {
|
|
3411
|
+
const p = paths(cfg);
|
|
3412
|
+
await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
|
|
3413
|
+
ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1 )) | while read -r d; do
|
|
3414
|
+
case "$d" in *${shq(version)}*) continue;; esac
|
|
3415
|
+
rm -rf "$d"
|
|
3416
|
+
done`, { ...asUser, allowFailure: true });
|
|
2803
3417
|
}
|
|
2804
3418
|
|
|
3419
|
+
// src/dns/index.ts
|
|
3420
|
+
import dns from "dns/promises";
|
|
3421
|
+
|
|
2805
3422
|
// src/dns/hetzner.ts
|
|
2806
3423
|
class HetznerDnsClient {
|
|
2807
3424
|
name = "hetzner";
|
|
@@ -3149,207 +3766,6 @@ async function syncDns(cfg, opts = {}) {
|
|
|
3149
3766
|
}
|
|
3150
3767
|
return results;
|
|
3151
3768
|
}
|
|
3152
|
-
// src/hetzner/api.ts
|
|
3153
|
-
class HetznerCloudClient {
|
|
3154
|
-
apiToken;
|
|
3155
|
-
baseUrl;
|
|
3156
|
-
constructor(apiToken, baseUrl = "https://api.hetzner.cloud/v1") {
|
|
3157
|
-
this.apiToken = apiToken;
|
|
3158
|
-
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
3159
|
-
}
|
|
3160
|
-
async request(path, options = {}) {
|
|
3161
|
-
const url = `${this.baseUrl}${path}`;
|
|
3162
|
-
const headers = {
|
|
3163
|
-
Authorization: `Bearer ${this.apiToken}`,
|
|
3164
|
-
"Content-Type": "application/json",
|
|
3165
|
-
...options.headers
|
|
3166
|
-
};
|
|
3167
|
-
const res = await fetch(url, { ...options, headers });
|
|
3168
|
-
let data;
|
|
3169
|
-
try {
|
|
3170
|
-
data = await res.json();
|
|
3171
|
-
} catch {
|
|
3172
|
-
data = null;
|
|
3173
|
-
}
|
|
3174
|
-
if (!res.ok) {
|
|
3175
|
-
const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
|
|
3176
|
-
throw new EpdError(`Hetzner Cloud API error: ${msg}`);
|
|
3177
|
-
}
|
|
3178
|
-
return data;
|
|
3179
|
-
}
|
|
3180
|
-
mapServer(s) {
|
|
3181
|
-
return {
|
|
3182
|
-
id: s.id,
|
|
3183
|
-
name: s.name,
|
|
3184
|
-
status: s.status,
|
|
3185
|
-
created: s.created,
|
|
3186
|
-
publicNet: {
|
|
3187
|
-
ipv4: {
|
|
3188
|
-
ip: s.public_net?.ipv4?.ip ?? "",
|
|
3189
|
-
blocked: Boolean(s.public_net?.ipv4?.blocked),
|
|
3190
|
-
dnsPtr: s.public_net?.ipv4?.dns_ptr
|
|
3191
|
-
},
|
|
3192
|
-
ipv6: s.public_net?.ipv6 ? {
|
|
3193
|
-
ip: s.public_net.ipv6.ip ?? "",
|
|
3194
|
-
blocked: Boolean(s.public_net.ipv6.blocked)
|
|
3195
|
-
} : undefined
|
|
3196
|
-
},
|
|
3197
|
-
serverType: {
|
|
3198
|
-
id: s.server_type?.id ?? 0,
|
|
3199
|
-
name: s.server_type?.name ?? "",
|
|
3200
|
-
description: s.server_type?.description ?? "",
|
|
3201
|
-
cores: s.server_type?.cores ?? 0,
|
|
3202
|
-
memory: s.server_type?.memory ?? 0,
|
|
3203
|
-
disk: s.server_type?.disk ?? 0,
|
|
3204
|
-
cpuType: s.server_type?.cpu_type ?? "shared",
|
|
3205
|
-
architecture: s.server_type?.architecture ?? "x86"
|
|
3206
|
-
},
|
|
3207
|
-
datacenter: {
|
|
3208
|
-
id: s.datacenter?.id ?? 0,
|
|
3209
|
-
name: s.datacenter?.name ?? "",
|
|
3210
|
-
description: s.datacenter?.description ?? "",
|
|
3211
|
-
location: {
|
|
3212
|
-
id: s.datacenter?.location?.id ?? 0,
|
|
3213
|
-
name: s.datacenter?.location?.name ?? "",
|
|
3214
|
-
description: s.datacenter?.location?.description ?? "",
|
|
3215
|
-
country: s.datacenter?.location?.country ?? "",
|
|
3216
|
-
city: s.datacenter?.location?.city ?? ""
|
|
3217
|
-
}
|
|
3218
|
-
},
|
|
3219
|
-
image: s.image ? {
|
|
3220
|
-
id: s.image.id,
|
|
3221
|
-
name: s.image.name ?? "",
|
|
3222
|
-
osFlavor: s.image.os_flavor ?? "",
|
|
3223
|
-
description: s.image.description ?? ""
|
|
3224
|
-
} : undefined,
|
|
3225
|
-
labels: s.labels ?? {}
|
|
3226
|
-
};
|
|
3227
|
-
}
|
|
3228
|
-
async listServers(opts = {}) {
|
|
3229
|
-
const params = new URLSearchParams;
|
|
3230
|
-
if (opts.name)
|
|
3231
|
-
params.set("name", opts.name);
|
|
3232
|
-
if (opts.labelSelector)
|
|
3233
|
-
params.set("label_selector", opts.labelSelector);
|
|
3234
|
-
params.set("per_page", "50");
|
|
3235
|
-
const query = params.toString() ? `?${params.toString()}` : "";
|
|
3236
|
-
const res = await this.request(`/servers${query}`);
|
|
3237
|
-
return (res.servers ?? []).map((s) => this.mapServer(s));
|
|
3238
|
-
}
|
|
3239
|
-
async getServer(idOrName) {
|
|
3240
|
-
if (typeof idOrName === "number" || /^\d+$/.test(String(idOrName))) {
|
|
3241
|
-
try {
|
|
3242
|
-
const res = await this.request(`/servers/${idOrName}`);
|
|
3243
|
-
return this.mapServer(res.server);
|
|
3244
|
-
} catch (e) {
|
|
3245
|
-
if (e instanceof EpdError && e.message.includes("404"))
|
|
3246
|
-
return null;
|
|
3247
|
-
throw e;
|
|
3248
|
-
}
|
|
3249
|
-
}
|
|
3250
|
-
const servers = await this.listServers({ name: String(idOrName) });
|
|
3251
|
-
return servers.find((s) => s.name === String(idOrName)) ?? null;
|
|
3252
|
-
}
|
|
3253
|
-
async createServer(opts) {
|
|
3254
|
-
const body = {
|
|
3255
|
-
name: opts.name,
|
|
3256
|
-
server_type: opts.serverType ?? "cx22",
|
|
3257
|
-
image: opts.image ?? "ubuntu-24.04",
|
|
3258
|
-
start_after_create: opts.startAfterCreate ?? true
|
|
3259
|
-
};
|
|
3260
|
-
if (opts.location)
|
|
3261
|
-
body.location = opts.location;
|
|
3262
|
-
if (opts.datacenter)
|
|
3263
|
-
body.datacenter = opts.datacenter;
|
|
3264
|
-
if (opts.sshKeys?.length)
|
|
3265
|
-
body.ssh_keys = opts.sshKeys;
|
|
3266
|
-
if (opts.labels)
|
|
3267
|
-
body.labels = opts.labels;
|
|
3268
|
-
if (opts.userData)
|
|
3269
|
-
body.user_data = opts.userData;
|
|
3270
|
-
const res = await this.request("/servers", {
|
|
3271
|
-
method: "POST",
|
|
3272
|
-
body: JSON.stringify(body)
|
|
3273
|
-
});
|
|
3274
|
-
return {
|
|
3275
|
-
server: this.mapServer(res.server),
|
|
3276
|
-
action: res.action,
|
|
3277
|
-
rootPassword: res.root_password
|
|
3278
|
-
};
|
|
3279
|
-
}
|
|
3280
|
-
async deleteServer(id) {
|
|
3281
|
-
await this.request(`/servers/${id}`, {
|
|
3282
|
-
method: "DELETE"
|
|
3283
|
-
});
|
|
3284
|
-
}
|
|
3285
|
-
async listServerTypes() {
|
|
3286
|
-
const res = await this.request("/server_types");
|
|
3287
|
-
return (res.server_types ?? []).map((st) => ({
|
|
3288
|
-
id: st.id,
|
|
3289
|
-
name: st.name,
|
|
3290
|
-
description: st.description,
|
|
3291
|
-
cores: st.cores,
|
|
3292
|
-
memory: st.memory,
|
|
3293
|
-
disk: st.disk,
|
|
3294
|
-
cpuType: st.cpu_type,
|
|
3295
|
-
architecture: st.architecture,
|
|
3296
|
-
prices: (st.prices ?? []).map((p) => ({
|
|
3297
|
-
location: p.location,
|
|
3298
|
-
priceHourly: { net: p.price_hourly?.net ?? "", gross: p.price_hourly?.gross ?? "" },
|
|
3299
|
-
priceMonthly: { net: p.price_monthly?.net ?? "", gross: p.price_monthly?.gross ?? "" }
|
|
3300
|
-
}))
|
|
3301
|
-
}));
|
|
3302
|
-
}
|
|
3303
|
-
async listLocations() {
|
|
3304
|
-
const res = await this.request("/locations");
|
|
3305
|
-
return (res.locations ?? []).map((l) => ({
|
|
3306
|
-
id: l.id,
|
|
3307
|
-
name: l.name,
|
|
3308
|
-
description: l.description,
|
|
3309
|
-
country: l.country,
|
|
3310
|
-
city: l.city,
|
|
3311
|
-
networkZone: l.network_zone
|
|
3312
|
-
}));
|
|
3313
|
-
}
|
|
3314
|
-
async listSshKeys() {
|
|
3315
|
-
const res = await this.request("/ssh_keys");
|
|
3316
|
-
return (res.ssh_keys ?? []).map((k) => ({
|
|
3317
|
-
id: k.id,
|
|
3318
|
-
name: k.name,
|
|
3319
|
-
fingerprint: k.fingerprint,
|
|
3320
|
-
publicKey: k.public_key
|
|
3321
|
-
}));
|
|
3322
|
-
}
|
|
3323
|
-
async getAction(id) {
|
|
3324
|
-
const res = await this.request(`/actions/${id}`);
|
|
3325
|
-
return res.action;
|
|
3326
|
-
}
|
|
3327
|
-
async waitForAction(actionId, timeoutMs = 120000) {
|
|
3328
|
-
const deadline = Date.now() + timeoutMs;
|
|
3329
|
-
while (Date.now() < deadline) {
|
|
3330
|
-
const action = await this.getAction(actionId);
|
|
3331
|
-
if (action.status === "success")
|
|
3332
|
-
return;
|
|
3333
|
-
if (action.status === "error") {
|
|
3334
|
-
throw new EpdError(`Hetzner action failed: ${action.error?.message || "Unknown error"}`);
|
|
3335
|
-
}
|
|
3336
|
-
await sleep(1500);
|
|
3337
|
-
}
|
|
3338
|
-
throw new EpdError(`Hetzner action ${actionId} timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
3339
|
-
}
|
|
3340
|
-
async waitForServerRunning(serverId, timeoutMs = 120000) {
|
|
3341
|
-
const deadline = Date.now() + timeoutMs;
|
|
3342
|
-
while (Date.now() < deadline) {
|
|
3343
|
-
const server = await this.getServer(serverId);
|
|
3344
|
-
if (server && server.status === "running" && server.publicNet.ipv4.ip) {
|
|
3345
|
-
return server;
|
|
3346
|
-
}
|
|
3347
|
-
await sleep(2000);
|
|
3348
|
-
}
|
|
3349
|
-
throw new EpdError(`Timed out waiting for Hetzner server ${serverId} to become running`);
|
|
3350
|
-
}
|
|
3351
|
-
}
|
|
3352
|
-
|
|
3353
3769
|
// src/hetzner/resolve.ts
|
|
3354
3770
|
async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
|
|
3355
3771
|
let needsHetzner = Boolean(cfg.hetzner);
|
|
@@ -3367,7 +3783,7 @@ async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
|
|
|
3367
3783
|
}
|
|
3368
3784
|
if (!needsHetzner)
|
|
3369
3785
|
return;
|
|
3370
|
-
const token = cfg.hetzner?.apiToken || env.HETZNER_API_TOKEN || env.HCLOUD_TOKEN || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN;
|
|
3786
|
+
const token = cfg.hetzner?.apiToken || env.HETZNER_API_TOKEN || env.HCLOUD_TOKEN || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN || getHetznerToken();
|
|
3371
3787
|
if (!token && !clientOverride) {
|
|
3372
3788
|
throw new EpdError("Hetzner Cloud API token is missing", "Set HETZNER_API_TOKEN or HCLOUD_TOKEN in your environment or configure hetzner.api_token in epd.yml.");
|
|
3373
3789
|
}
|
|
@@ -3765,6 +4181,30 @@ Options
|
|
|
3765
4181
|
async run(ctx) {
|
|
3766
4182
|
const loaded = ctx.load();
|
|
3767
4183
|
const cfg = loaded.config;
|
|
4184
|
+
const needsHetzner = Boolean(cfg.hetzner) || cfg.services.some((s) => s.hosts.some((h) => h.startsWith("hetzner:")));
|
|
4185
|
+
if (needsHetzner && !cfg.hetzner?.apiToken && !getHetznerToken() && interactive()) {
|
|
4186
|
+
log.warn("Hetzner Cloud integration requires an API token.");
|
|
4187
|
+
const link = await confirm("Would you like to link Hetzner Cloud now?", true);
|
|
4188
|
+
if (link) {
|
|
4189
|
+
const token = await linkHetznerInteractive();
|
|
4190
|
+
if (token && cfg.hetzner)
|
|
4191
|
+
cfg.hetzner.apiToken = token;
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
const needsCloudflare = cfg.dns?.provider === "cloudflare" || Boolean(cfg.cloudflare);
|
|
4195
|
+
if (needsCloudflare && !cfg.dns?.apiToken && !cfg.cloudflare?.apiToken && !getCloudflareToken() && interactive()) {
|
|
4196
|
+
log.warn("Cloudflare DNS integration requires an API token.");
|
|
4197
|
+
const link = await confirm("Would you like to link Cloudflare now?", true);
|
|
4198
|
+
if (link) {
|
|
4199
|
+
const token = await linkCloudflareInteractive();
|
|
4200
|
+
if (token) {
|
|
4201
|
+
if (cfg.dns)
|
|
4202
|
+
cfg.dns.apiToken = token;
|
|
4203
|
+
if (cfg.cloudflare)
|
|
4204
|
+
cfg.cloudflare.apiToken = token;
|
|
4205
|
+
}
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
3768
4208
|
await resolveDynamicHosts(cfg, loaded.env);
|
|
3769
4209
|
const only = ctx.values.host;
|
|
3770
4210
|
const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
|
|
@@ -4240,7 +4680,7 @@ Options
|
|
|
4240
4680
|
var proxy = {
|
|
4241
4681
|
name: "proxy",
|
|
4242
4682
|
summary: "Inspect or restart the shared Traefik proxy",
|
|
4243
|
-
options: { host: { type: "string" }, lines: { type: "string", short: "n" }, follow: { type: "boolean", short: "f" } },
|
|
4683
|
+
options: { host: { type: "string" }, lines: { type: "string", short: "n" }, follow: { type: "boolean", short: "f" }, port: { type: "string", short: "p" } },
|
|
4244
4684
|
help: () => `${c.bold("epd proxy <status|reboot|logs|routes|remove>")}
|
|
4245
4685
|
|
|
4246
4686
|
One Traefik container per server, shared by every epd app on it. Rebooting it
|
|
@@ -4249,13 +4689,15 @@ briefly interrupts *all* sites on that server; the apps themselves keep running.
|
|
|
4249
4689
|
status Is it up, on which image, with which entrypoints
|
|
4250
4690
|
reboot Recreate it from the current configuration
|
|
4251
4691
|
logs Traefik's own logs (certificates, routing errors)
|
|
4252
|
-
routes
|
|
4253
|
-
|
|
4692
|
+
routes The route file epd wrote for this app
|
|
4693
|
+
dashboard Open a secure SSH tunnel to the Traefik web UI & launch browser
|
|
4694
|
+
remove Remove this app's routes and stop the proxy if nothing else needs it
|
|
4254
4695
|
|
|
4255
4696
|
Options
|
|
4256
4697
|
--host <ip> Only this host
|
|
4257
4698
|
-n, --lines <n> Log lines (default 100)
|
|
4258
|
-
-f, --follow Stream logs
|
|
4699
|
+
-f, --follow Stream logs
|
|
4700
|
+
-p, --port <port> Local dashboard port (default 8080)`,
|
|
4259
4701
|
async run(ctx) {
|
|
4260
4702
|
const loaded = ctx.load();
|
|
4261
4703
|
const cfg = loaded.config;
|
|
@@ -4315,6 +4757,30 @@ Options
|
|
|
4315
4757
|
}
|
|
4316
4758
|
return;
|
|
4317
4759
|
}
|
|
4760
|
+
case "dashboard": {
|
|
4761
|
+
const targetHost = hosts[0];
|
|
4762
|
+
if (!targetHost)
|
|
4763
|
+
throw new EpdError("No proxy hosts available");
|
|
4764
|
+
const localPort = Number(ctx.values.port) || 8080;
|
|
4765
|
+
const dashboardUrl = `http://localhost:${localPort}/dashboard/`;
|
|
4766
|
+
log.step(`Connecting to Traefik dashboard on ${c.bold(targetHost.name)}...`);
|
|
4767
|
+
const s = await proxyState(targetHost, cfg);
|
|
4768
|
+
if (!s.running) {
|
|
4769
|
+
throw new EpdError(`Proxy on ${targetHost.name} is not running. Run ${c.cyan("epd proxy reboot")} first.`);
|
|
4770
|
+
}
|
|
4771
|
+
log.info(`Forwarding local port ${c.bold(String(localPort))} -> 127.0.0.1:8080 on ${targetHost.name}`);
|
|
4772
|
+
log.ok(`Dashboard URL: ${c.cyan(dashboardUrl)}`);
|
|
4773
|
+
log.info(`Press Ctrl-C to close the dashboard tunnel.`);
|
|
4774
|
+
await openBrowser(dashboardUrl);
|
|
4775
|
+
const args = [...targetHost.sshOptions(), "-N", "-L", `${localPort}:127.0.0.1:8080`, targetHost.target];
|
|
4776
|
+
const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...args], { stdout: "inherit", stderr: "inherit" }) : __require("child_process").spawn("ssh", args, { stdio: "inherit" });
|
|
4777
|
+
if (proc.exited) {
|
|
4778
|
+
await proc.exited;
|
|
4779
|
+
} else {
|
|
4780
|
+
await new Promise((resolve) => proc.on("close", resolve));
|
|
4781
|
+
}
|
|
4782
|
+
return;
|
|
4783
|
+
}
|
|
4318
4784
|
case "remove": {
|
|
4319
4785
|
for (const host of hosts) {
|
|
4320
4786
|
await removeRoutes(host, cfg);
|
|
@@ -4677,10 +5143,16 @@ Environment
|
|
|
4677
5143
|
const cfg = loaded.config;
|
|
4678
5144
|
const sub = ctx.positionals[0] || "dns";
|
|
4679
5145
|
const action = ctx.positionals[1] || (sub === "status" ? "status" : "sync");
|
|
4680
|
-
|
|
5146
|
+
let token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || getCloudflareToken();
|
|
5147
|
+
if (!token && interactive()) {
|
|
5148
|
+
log.info("No Cloudflare API token found.");
|
|
5149
|
+
const link = await confirm("Would you like to link your Cloudflare account now?", true);
|
|
5150
|
+
if (link) {
|
|
5151
|
+
token = await linkCloudflareInteractive() ?? undefined;
|
|
5152
|
+
}
|
|
5153
|
+
}
|
|
4681
5154
|
if (!token) {
|
|
4682
|
-
throw new EpdError("Cloudflare API token is missing", `
|
|
4683
|
-
` + " cloudflare:\n api_token: ${CLOUDFLARE_API_TOKEN}");
|
|
5155
|
+
throw new EpdError("Cloudflare API token is missing", "Run `epd auth cloudflare`, set CLOUDFLARE_API_TOKEN in your environment, or configure `cloudflare.api_token` in epd.yml.");
|
|
4684
5156
|
}
|
|
4685
5157
|
const client = new CloudflareClient(token);
|
|
4686
5158
|
const domains = getRouteDomains(cfg);
|
|
@@ -4786,9 +5258,16 @@ Environment
|
|
|
4786
5258
|
const providerName = ctx.values.provider || cfg.dns?.provider || (cfg.cloudflare ? "cloudflare" : undefined) || (process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN ? "cloudflare" : undefined) || (process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN ? "hetzner" : undefined) || "cloudflare";
|
|
4787
5259
|
let provider;
|
|
4788
5260
|
if (providerName === "cloudflare") {
|
|
4789
|
-
|
|
5261
|
+
let token = cfg.dns?.apiToken || cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || getCloudflareToken();
|
|
5262
|
+
if (!token && interactive()) {
|
|
5263
|
+
log.info("No Cloudflare API token found.");
|
|
5264
|
+
const link = await confirm("Would you like to link your Cloudflare account now?", true);
|
|
5265
|
+
if (link) {
|
|
5266
|
+
token = await linkCloudflareInteractive() ?? undefined;
|
|
5267
|
+
}
|
|
5268
|
+
}
|
|
4790
5269
|
if (!token) {
|
|
4791
|
-
throw new EpdError("Cloudflare API token is missing", "
|
|
5270
|
+
throw new EpdError("Cloudflare API token is missing", "Run `epd auth cloudflare`, set CLOUDFLARE_API_TOKEN in environment, or add it to epd.yml under dns or cloudflare.");
|
|
4792
5271
|
}
|
|
4793
5272
|
provider = new CloudflareClient(token);
|
|
4794
5273
|
} else if (providerName === "hetzner") {
|
|
@@ -4909,9 +5388,16 @@ Environment
|
|
|
4909
5388
|
token = loaded.config.hetzner?.apiToken || loaded.env.HETZNER_API_TOKEN || loaded.env.HCLOUD_TOKEN;
|
|
4910
5389
|
projectName = loaded.config.name;
|
|
4911
5390
|
} catch {}
|
|
4912
|
-
token = token || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN;
|
|
5391
|
+
token = token || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN || getHetznerToken();
|
|
5392
|
+
if (!token && interactive()) {
|
|
5393
|
+
log.info("No Hetzner Cloud API token found.");
|
|
5394
|
+
const link = await confirm("Would you like to link your Hetzner Cloud account now?", true);
|
|
5395
|
+
if (link) {
|
|
5396
|
+
token = await linkHetznerInteractive() ?? undefined;
|
|
5397
|
+
}
|
|
5398
|
+
}
|
|
4913
5399
|
if (!token) {
|
|
4914
|
-
throw new EpdError("Hetzner Cloud API token is missing", "
|
|
5400
|
+
throw new EpdError("Hetzner Cloud API token is missing", "Run `epd auth hetzner`, set HETZNER_API_TOKEN in your environment, or configure `hetzner.api_token` in epd.yml.");
|
|
4915
5401
|
}
|
|
4916
5402
|
const client = new HetznerCloudClient(token);
|
|
4917
5403
|
const sub = ctx.positionals[0] || "list";
|
|
@@ -4981,11 +5467,14 @@ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
|
|
|
4981
5467
|
labels.app = projectName;
|
|
4982
5468
|
const userLabels = ctx.values.label ?? [];
|
|
4983
5469
|
for (const l of userLabels) {
|
|
4984
|
-
const
|
|
4985
|
-
if (
|
|
4986
|
-
labels[
|
|
5470
|
+
const eq = l.indexOf("=");
|
|
5471
|
+
if (eq !== -1) {
|
|
5472
|
+
labels[l.slice(0, eq).trim()] = l.slice(eq + 1).trim();
|
|
5473
|
+
} else {
|
|
5474
|
+
labels[l.trim()] = "true";
|
|
5475
|
+
}
|
|
4987
5476
|
}
|
|
4988
|
-
let sshKeys
|
|
5477
|
+
let sshKeys;
|
|
4989
5478
|
const explicitKey = ctx.values["ssh-key"];
|
|
4990
5479
|
if (explicitKey) {
|
|
4991
5480
|
sshKeys = [explicitKey];
|
|
@@ -5050,8 +5539,8 @@ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
|
|
|
5050
5539
|
if (!server) {
|
|
5051
5540
|
throw new EpdError(`Hetzner server "${target}" not found.`);
|
|
5052
5541
|
}
|
|
5053
|
-
const
|
|
5054
|
-
if (!
|
|
5542
|
+
const confirmDel = Boolean(ctx.values.yes);
|
|
5543
|
+
if (!confirmDel) {
|
|
5055
5544
|
process.stdout.write(`Are you sure you want to permanently delete server ${c.bold(server.name)} (${server.publicNet.ipv4.ip || server.id})? [y/N]: `);
|
|
5056
5545
|
for await (const line of console) {
|
|
5057
5546
|
if (!line.trim().toLowerCase().startsWith("y")) {
|
|
@@ -5116,9 +5605,9 @@ ${c.bold("HETZNER DATACENTER LOCATIONS")}
|
|
|
5116
5605
|
};
|
|
5117
5606
|
|
|
5118
5607
|
// src/core/update.ts
|
|
5119
|
-
import { chmodSync, existsSync as
|
|
5120
|
-
import { homedir as
|
|
5121
|
-
import { dirname as dirname2, join as
|
|
5608
|
+
import { chmodSync as chmodSync2, existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync, writeFileSync as writeFileSync3 } from "fs";
|
|
5609
|
+
import { homedir as homedir3 } from "os";
|
|
5610
|
+
import { dirname as dirname2, join as join7 } from "path";
|
|
5122
5611
|
function parseSemver(v) {
|
|
5123
5612
|
const clean = v.replace(/^v/, "").trim();
|
|
5124
5613
|
const parts = clean.split("-")[0].split(".").map((n) => Number(n) || 0);
|
|
@@ -5138,13 +5627,13 @@ function isNewer(current, latest) {
|
|
|
5138
5627
|
return lPatch > cPatch;
|
|
5139
5628
|
}
|
|
5140
5629
|
function getCachePath() {
|
|
5141
|
-
return
|
|
5630
|
+
return join7(homedir3(), ".epd", "update-check.json");
|
|
5142
5631
|
}
|
|
5143
5632
|
function readCache() {
|
|
5144
5633
|
try {
|
|
5145
5634
|
const p = getCachePath();
|
|
5146
|
-
if (
|
|
5147
|
-
return JSON.parse(
|
|
5635
|
+
if (existsSync6(p)) {
|
|
5636
|
+
return JSON.parse(readFileSync4(p, "utf8"));
|
|
5148
5637
|
}
|
|
5149
5638
|
} catch {}
|
|
5150
5639
|
return null;
|
|
@@ -5152,9 +5641,9 @@ function readCache() {
|
|
|
5152
5641
|
function writeCache(latestVersion) {
|
|
5153
5642
|
try {
|
|
5154
5643
|
const p = getCachePath();
|
|
5155
|
-
|
|
5644
|
+
mkdirSync4(dirname2(p), { recursive: true });
|
|
5156
5645
|
const data = { lastChecked: Date.now(), latestVersion };
|
|
5157
|
-
|
|
5646
|
+
writeFileSync3(p, JSON.stringify(data));
|
|
5158
5647
|
} catch {}
|
|
5159
5648
|
}
|
|
5160
5649
|
async function fetchLatestNpmVersion() {
|
|
@@ -5221,8 +5710,8 @@ async function performUpdate(targetVersion) {
|
|
|
5221
5710
|
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
|
5222
5711
|
const buf = await res.arrayBuffer();
|
|
5223
5712
|
const tmpPath = `${execPath}.tmp.${Date.now()}`;
|
|
5224
|
-
|
|
5225
|
-
|
|
5713
|
+
writeFileSync3(tmpPath, Buffer.from(buf));
|
|
5714
|
+
chmodSync2(tmpPath, 493);
|
|
5226
5715
|
renameSync(tmpPath, execPath);
|
|
5227
5716
|
return true;
|
|
5228
5717
|
}
|
|
@@ -5277,7 +5766,7 @@ async function promptAutoUpdate(currentVersion) {
|
|
|
5277
5766
|
}
|
|
5278
5767
|
|
|
5279
5768
|
// src/version.ts
|
|
5280
|
-
var VERSION = "0.
|
|
5769
|
+
var VERSION = "0.5.0";
|
|
5281
5770
|
|
|
5282
5771
|
// src/commands/update.ts
|
|
5283
5772
|
var update = {
|
|
@@ -5318,6 +5807,962 @@ Options
|
|
|
5318
5807
|
}
|
|
5319
5808
|
};
|
|
5320
5809
|
|
|
5810
|
+
// src/commands/auth.ts
|
|
5811
|
+
var auth = {
|
|
5812
|
+
name: "auth",
|
|
5813
|
+
aliases: ["login"],
|
|
5814
|
+
summary: "Manage Cloudflare and Hetzner API authentication and linked accounts",
|
|
5815
|
+
options: {
|
|
5816
|
+
global: { type: "boolean" }
|
|
5817
|
+
},
|
|
5818
|
+
help: () => `${c.bold("epd auth")} \u2014 manage linked cloud accounts and API tokens
|
|
5819
|
+
|
|
5820
|
+
Commands
|
|
5821
|
+
epd auth Show status of linked Cloudflare and Hetzner accounts
|
|
5822
|
+
epd auth cloudflare Link or re-authenticate Cloudflare (DNS & SSL)
|
|
5823
|
+
epd auth hetzner Link or re-authenticate Hetzner Cloud (Servers & DNS)
|
|
5824
|
+
epd auth logout Remove globally saved authentication credentials
|
|
5825
|
+
|
|
5826
|
+
Saved credentials are stored with 0600 permissions in ~/.config/epd/auth.json`,
|
|
5827
|
+
async run(ctx) {
|
|
5828
|
+
const sub = ctx.positionals[0] || "status";
|
|
5829
|
+
const root = process.cwd();
|
|
5830
|
+
if (sub === "cloudflare" || sub === "cf") {
|
|
5831
|
+
await linkCloudflareInteractive(root);
|
|
5832
|
+
return;
|
|
5833
|
+
}
|
|
5834
|
+
if (sub === "hetzner" || sub === "hcloud") {
|
|
5835
|
+
await linkHetznerInteractive(root);
|
|
5836
|
+
return;
|
|
5837
|
+
}
|
|
5838
|
+
if (sub === "logout") {
|
|
5839
|
+
const confirmed = await confirm("Remove all credentials from ~/.config/epd/auth.json?", true);
|
|
5840
|
+
if (confirmed) {
|
|
5841
|
+
saveGlobalAuth(() => ({}));
|
|
5842
|
+
log.ok("Cleared globally stored credentials in ~/.config/epd/auth.json");
|
|
5843
|
+
}
|
|
5844
|
+
return;
|
|
5845
|
+
}
|
|
5846
|
+
if (sub === "status") {
|
|
5847
|
+
console.log(`
|
|
5848
|
+
${c.bold("EPD Authentication Status")}
|
|
5849
|
+
`);
|
|
5850
|
+
const cfToken = getCloudflareToken(root);
|
|
5851
|
+
const cfSource = getCloudflareTokenSource(root);
|
|
5852
|
+
const hToken = getHetznerToken(root);
|
|
5853
|
+
const hSource = getHetznerTokenSource(root);
|
|
5854
|
+
const authPath = getGlobalAuthPath();
|
|
5855
|
+
console.log(` Global storage: ${c.cyan(authPath)}`);
|
|
5856
|
+
console.log(` Cloudflare: ${cfToken ? `${c.green("Linked")} via ${cfSource}` : c.gray("Not linked")}`);
|
|
5857
|
+
console.log(` Hetzner Cloud: ${hToken ? `${c.green("Linked")} via ${hSource}` : c.gray("Not linked")}`);
|
|
5858
|
+
console.log(`
|
|
5859
|
+
Run ${c.cyan("epd auth cloudflare")} or ${c.cyan("epd auth hetzner")} to link an account.
|
|
5860
|
+
`);
|
|
5861
|
+
return;
|
|
5862
|
+
}
|
|
5863
|
+
log.warn(`Unknown auth subcommand: ${sub}`);
|
|
5864
|
+
console.log(auth.help());
|
|
5865
|
+
}
|
|
5866
|
+
};
|
|
5867
|
+
|
|
5868
|
+
// src/commands/maintenance.ts
|
|
5869
|
+
function extractDomains(cfg) {
|
|
5870
|
+
const domains = new Set;
|
|
5871
|
+
for (const svc of cfg.services) {
|
|
5872
|
+
for (const r of svc.routes) {
|
|
5873
|
+
for (const h of r.hosts)
|
|
5874
|
+
domains.add(h);
|
|
5875
|
+
}
|
|
5876
|
+
}
|
|
5877
|
+
return Array.from(domains);
|
|
5878
|
+
}
|
|
5879
|
+
function maintenanceHtml(title, message, retrySeconds, appName) {
|
|
5880
|
+
return `<!DOCTYPE html>
|
|
5881
|
+
<html lang="en">
|
|
5882
|
+
<head>
|
|
5883
|
+
<meta charset="UTF-8">
|
|
5884
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
5885
|
+
<title>${title} \u2014 ${appName}</title>
|
|
5886
|
+
<style>
|
|
5887
|
+
:root {
|
|
5888
|
+
--bg: #0b0f19;
|
|
5889
|
+
--card: #151c2e;
|
|
5890
|
+
--border: #232d48;
|
|
5891
|
+
--text: #f8fafc;
|
|
5892
|
+
--subtext: #94a3b8;
|
|
5893
|
+
--brand: #38bdf8;
|
|
5894
|
+
--accent: #6366f1;
|
|
5895
|
+
}
|
|
5896
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
5897
|
+
body {
|
|
5898
|
+
background-color: var(--bg);
|
|
5899
|
+
color: var(--text);
|
|
5900
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
5901
|
+
min-height: 100vh;
|
|
5902
|
+
display: flex;
|
|
5903
|
+
align-items: center;
|
|
5904
|
+
justify-content: center;
|
|
5905
|
+
padding: 1.5rem;
|
|
5906
|
+
}
|
|
5907
|
+
.card {
|
|
5908
|
+
background: var(--card);
|
|
5909
|
+
border: 1px solid var(--border);
|
|
5910
|
+
border-radius: 1.25rem;
|
|
5911
|
+
max-width: 32rem;
|
|
5912
|
+
width: 100%;
|
|
5913
|
+
padding: 2.5rem 2rem;
|
|
5914
|
+
text-align: center;
|
|
5915
|
+
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
|
|
5916
|
+
position: relative;
|
|
5917
|
+
overflow: hidden;
|
|
5918
|
+
}
|
|
5919
|
+
.card::before {
|
|
5920
|
+
content: "";
|
|
5921
|
+
position: absolute;
|
|
5922
|
+
top: 0; left: 0; right: 0;
|
|
5923
|
+
height: 4px;
|
|
5924
|
+
background: linear-gradient(90deg, var(--brand), var(--accent));
|
|
5925
|
+
}
|
|
5926
|
+
.icon-box {
|
|
5927
|
+
width: 4.5rem;
|
|
5928
|
+
height: 4.5rem;
|
|
5929
|
+
background: rgba(56, 189, 248, 0.1);
|
|
5930
|
+
border: 1px solid rgba(56, 189, 248, 0.2);
|
|
5931
|
+
border-radius: 1rem;
|
|
5932
|
+
display: inline-flex;
|
|
5933
|
+
align-items: center;
|
|
5934
|
+
justify-content: center;
|
|
5935
|
+
font-size: 2.25rem;
|
|
5936
|
+
margin-bottom: 1.5rem;
|
|
5937
|
+
animation: pulse 3s infinite ease-in-out;
|
|
5938
|
+
}
|
|
5939
|
+
@keyframes pulse {
|
|
5940
|
+
0%, 100% { transform: scale(1); opacity: 1; }
|
|
5941
|
+
50% { transform: scale(1.05); opacity: 0.85; }
|
|
5942
|
+
}
|
|
5943
|
+
h1 {
|
|
5944
|
+
font-size: 1.5rem;
|
|
5945
|
+
font-weight: 700;
|
|
5946
|
+
letter-spacing: -0.025em;
|
|
5947
|
+
margin-bottom: 0.75rem;
|
|
5948
|
+
}
|
|
5949
|
+
p {
|
|
5950
|
+
color: var(--subtext);
|
|
5951
|
+
font-size: 1rem;
|
|
5952
|
+
line-height: 1.6;
|
|
5953
|
+
margin-bottom: 1.75rem;
|
|
5954
|
+
}
|
|
5955
|
+
.badge {
|
|
5956
|
+
display: inline-flex;
|
|
5957
|
+
align-items: center;
|
|
5958
|
+
gap: 0.5rem;
|
|
5959
|
+
padding: 0.35rem 0.85rem;
|
|
5960
|
+
background: rgba(245, 158, 11, 0.1);
|
|
5961
|
+
border: 1px solid rgba(245, 158, 11, 0.3);
|
|
5962
|
+
border-radius: 9999px;
|
|
5963
|
+
color: #f59e0b;
|
|
5964
|
+
font-size: 0.825rem;
|
|
5965
|
+
font-weight: 600;
|
|
5966
|
+
margin-bottom: 1.5rem;
|
|
5967
|
+
}
|
|
5968
|
+
.dot {
|
|
5969
|
+
width: 0.5rem;
|
|
5970
|
+
height: 0.5rem;
|
|
5971
|
+
border-radius: 9999px;
|
|
5972
|
+
background: #f59e0b;
|
|
5973
|
+
animation: blink 1.5s infinite;
|
|
5974
|
+
}
|
|
5975
|
+
@keyframes blink {
|
|
5976
|
+
0%, 100% { opacity: 1; }
|
|
5977
|
+
50% { opacity: 0.3; }
|
|
5978
|
+
}
|
|
5979
|
+
.countdown {
|
|
5980
|
+
font-size: 0.875rem;
|
|
5981
|
+
color: var(--subtext);
|
|
5982
|
+
border-top: 1px solid var(--border);
|
|
5983
|
+
padding-top: 1.25rem;
|
|
5984
|
+
}
|
|
5985
|
+
</style>
|
|
5986
|
+
</head>
|
|
5987
|
+
<body>
|
|
5988
|
+
<div class="card">
|
|
5989
|
+
<div class="icon-box">\u26A1</div>
|
|
5990
|
+
<div class="badge"><span class="dot"></span> Maintenance Mode Active</div>
|
|
5991
|
+
<h1>${title}</h1>
|
|
5992
|
+
<p>${message}</p>
|
|
5993
|
+
<div class="countdown">
|
|
5994
|
+
Auto-refreshing in <span id="timer" style="font-weight: 600; color: var(--brand);">${retrySeconds}</span>s...
|
|
5995
|
+
</div>
|
|
5996
|
+
</div>
|
|
5997
|
+
<script>
|
|
5998
|
+
let remaining = ${retrySeconds};
|
|
5999
|
+
const timer = document.getElementById('timer');
|
|
6000
|
+
setInterval(() => {
|
|
6001
|
+
remaining--;
|
|
6002
|
+
if (remaining <= 0) {
|
|
6003
|
+
window.location.reload();
|
|
6004
|
+
} else if (timer) {
|
|
6005
|
+
timer.textContent = remaining;
|
|
6006
|
+
}
|
|
6007
|
+
}, 1000);
|
|
6008
|
+
</script>
|
|
6009
|
+
</body>
|
|
6010
|
+
</html>`;
|
|
6011
|
+
}
|
|
6012
|
+
function maintenanceYaml(appName, domains, port) {
|
|
6013
|
+
if (!domains.length)
|
|
6014
|
+
domains = ["localhost"];
|
|
6015
|
+
const hostRule = domains.map((d) => `Host(\`${d}\`)`).join(" || ");
|
|
6016
|
+
return `http:
|
|
6017
|
+
routers:
|
|
6018
|
+
${appName}-maint-http:
|
|
6019
|
+
rule: "${hostRule}"
|
|
6020
|
+
entryPoints: ["web"]
|
|
6021
|
+
service: "${appName}-maint-svc"
|
|
6022
|
+
priority: 2000000000
|
|
6023
|
+
${appName}-maint-https:
|
|
6024
|
+
rule: "${hostRule}"
|
|
6025
|
+
entryPoints: ["websecure"]
|
|
6026
|
+
service: "${appName}-maint-svc"
|
|
6027
|
+
priority: 2000000000
|
|
6028
|
+
tls: {}
|
|
6029
|
+
services:
|
|
6030
|
+
${appName}-maint-svc:
|
|
6031
|
+
loadBalancer:
|
|
6032
|
+
servers:
|
|
6033
|
+
- url: "http://127.0.0.1:${port}"
|
|
6034
|
+
`;
|
|
6035
|
+
}
|
|
6036
|
+
var maintenance = {
|
|
6037
|
+
name: "maintenance",
|
|
6038
|
+
summary: "Toggle or inspect zero-downtime maintenance mode for this application",
|
|
6039
|
+
options: {
|
|
6040
|
+
message: { type: "string", short: "m" },
|
|
6041
|
+
title: { type: "string" },
|
|
6042
|
+
retry: { type: "string" },
|
|
6043
|
+
status: { type: "string" },
|
|
6044
|
+
host: { type: "string" }
|
|
6045
|
+
},
|
|
6046
|
+
help: () => `${c.bold("epd maintenance <on|off|status>")} \u2014 manage maintenance mode
|
|
6047
|
+
|
|
6048
|
+
Presents a responsive 503 Maintenance page to all public visitors via Traefik
|
|
6049
|
+
without stopping your backend applications or dropping SSL.
|
|
6050
|
+
|
|
6051
|
+
Commands
|
|
6052
|
+
on Enable maintenance mode and route all traffic to the maintenance page
|
|
6053
|
+
off Disable maintenance mode and resume live blue/green routing
|
|
6054
|
+
status Check if maintenance mode is currently active
|
|
6055
|
+
|
|
6056
|
+
Options
|
|
6057
|
+
-m, --message <text> Custom maintenance message
|
|
6058
|
+
--title <text> Custom page title (default: Maintenance in Progress)
|
|
6059
|
+
--retry <sec> Retry-After header and auto-refresh timer (default: 30)
|
|
6060
|
+
--status <code> HTTP response status code (default: 503)
|
|
6061
|
+
--host <ip> Run only on a specific host`,
|
|
6062
|
+
async run(ctx) {
|
|
6063
|
+
const loaded = ctx.load();
|
|
6064
|
+
const cfg = loaded.config;
|
|
6065
|
+
const action = ctx.positionals[0] ?? "status";
|
|
6066
|
+
let hostNames = allHosts(cfg);
|
|
6067
|
+
if (ctx.values.host)
|
|
6068
|
+
hostNames = hostNames.filter((h) => h === ctx.values.host);
|
|
6069
|
+
if (!hostNames.length)
|
|
6070
|
+
throw new EpdError("No hosts found in configuration");
|
|
6071
|
+
const hosts = hostNames.map((h) => host(h, cfg.ssh));
|
|
6072
|
+
const p = paths(cfg);
|
|
6073
|
+
const maintPort = (cfg.portBase || 31776) + 999;
|
|
6074
|
+
const domains = extractDomains(cfg);
|
|
6075
|
+
const maintDir = `${p.root}/maintenance/${cfg.name}`;
|
|
6076
|
+
const traefikDynamicFile = `${p.proxyDynamicDir}/${cfg.name}-maintenance.yml`;
|
|
6077
|
+
switch (action) {
|
|
6078
|
+
case "status": {
|
|
6079
|
+
for (const host of hosts) {
|
|
6080
|
+
const isActive = await host.test(`[ -f ${shq(traefikDynamicFile)} ]`);
|
|
6081
|
+
if (isActive) {
|
|
6082
|
+
log.plain(`${c.magenta(host.name)}: ${c.yellow(c.bold("MAINTENANCE ACTIVE"))} (routes overriding live app)`);
|
|
6083
|
+
} else {
|
|
6084
|
+
log.plain(`${c.magenta(host.name)}: ${c.green("Live")} (normal blue/green routing)`);
|
|
6085
|
+
}
|
|
6086
|
+
}
|
|
6087
|
+
return;
|
|
6088
|
+
}
|
|
6089
|
+
case "on": {
|
|
6090
|
+
const title = ctx.values.title || "Maintenance in Progress";
|
|
6091
|
+
const message = ctx.values.message || "We are currently performing scheduled maintenance. We will be back shortly.";
|
|
6092
|
+
const retrySec = Number(ctx.values.retry) || 30;
|
|
6093
|
+
const statusCode = Number(ctx.values.status) || 503;
|
|
6094
|
+
const html = maintenanceHtml(title, message, retrySec, cfg.name);
|
|
6095
|
+
const yml = maintenanceYaml(cfg.name, domains, maintPort);
|
|
6096
|
+
log.step(`Enabling maintenance mode on ${hosts.length} host(s)...`);
|
|
6097
|
+
await pool(hosts, 4, async (host) => {
|
|
6098
|
+
await host.exec(`mkdir -p ${shq(maintDir)} ${shq(p.proxyDynamicDir)}`);
|
|
6099
|
+
await host.writeFile(`${maintDir}/index.html`, html, "644");
|
|
6100
|
+
const pyServer = `import http.server, socketserver
|
|
6101
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
6102
|
+
def do_GET(self):
|
|
6103
|
+
self.send_response(${statusCode})
|
|
6104
|
+
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
|
6105
|
+
self.send_header('Retry-After', '${retrySec}')
|
|
6106
|
+
self.end_headers()
|
|
6107
|
+
try:
|
|
6108
|
+
with open('${maintDir}/index.html', 'rb') as f:
|
|
6109
|
+
self.wfile.write(f.read())
|
|
6110
|
+
except Exception:
|
|
6111
|
+
self.wfile.write(b"<h1>Maintenance in Progress</h1>")
|
|
6112
|
+
def do_HEAD(self):
|
|
6113
|
+
self.send_response(${statusCode})
|
|
6114
|
+
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
|
6115
|
+
self.send_header('Retry-After', '${retrySec}')
|
|
6116
|
+
self.end_headers()
|
|
6117
|
+
def log_message(self, format, *args):
|
|
6118
|
+
pass
|
|
6119
|
+
|
|
6120
|
+
socketserver.TCPServer.allow_reuse_address = True
|
|
6121
|
+
with socketserver.TCPServer(('127.0.0.1', ${maintPort}), Handler) as httpd:
|
|
6122
|
+
httpd.serve_forever()
|
|
6123
|
+
`;
|
|
6124
|
+
await host.writeFile(`${maintDir}/server.py`, pyServer, "755");
|
|
6125
|
+
await host.exec(`[ -f ${shq(maintDir)}/pid ] && kill $(cat ${shq(maintDir)}/pid) 2>/dev/null || true`);
|
|
6126
|
+
await host.exec(`docker rm -f epd-${cfg.name}-maint 2>/dev/null || true`);
|
|
6127
|
+
const hasPython = await host.test("command -v python3 >/dev/null 2>&1");
|
|
6128
|
+
if (hasPython) {
|
|
6129
|
+
await host.exec(`nohup python3 ${shq(maintDir)}/server.py >/dev/null 2>&1 & echo $! > ${shq(maintDir)}/pid`);
|
|
6130
|
+
} else {
|
|
6131
|
+
await host.exec(`docker run -d --name epd-${cfg.name}-maint --restart unless-stopped -p 127.0.0.1:${maintPort}:80 -v ${shq(maintDir)}:/usr/share/nginx/html:ro nginx:alpine >/dev/null 2>&1 || true`);
|
|
6132
|
+
}
|
|
6133
|
+
await host.writeFile(traefikDynamicFile, yml, "644");
|
|
6134
|
+
log.host(host.name, `maintenance mode enabled (${c.yellow(`HTTP ${statusCode}`)})`);
|
|
6135
|
+
});
|
|
6136
|
+
log.ok(`Maintenance mode active across all hosts for: ${domains.join(", ") || cfg.name}`);
|
|
6137
|
+
log.info(`Run ${c.cyan("epd maintenance off")} when ready to resume live traffic.`);
|
|
6138
|
+
return;
|
|
6139
|
+
}
|
|
6140
|
+
case "off": {
|
|
6141
|
+
log.step(`Disabling maintenance mode on ${hosts.length} host(s)...`);
|
|
6142
|
+
await pool(hosts, 4, async (host) => {
|
|
6143
|
+
await host.exec(`rm -f ${shq(traefikDynamicFile)}`);
|
|
6144
|
+
await host.exec(`[ -f ${shq(maintDir)}/pid ] && kill $(cat ${shq(maintDir)}/pid) 2>/dev/null || true`);
|
|
6145
|
+
await host.exec(`docker rm -f epd-${cfg.name}-maint 2>/dev/null || true`);
|
|
6146
|
+
await host.exec(`rm -rf ${shq(maintDir)}`);
|
|
6147
|
+
log.host(host.name, "maintenance mode disabled");
|
|
6148
|
+
});
|
|
6149
|
+
log.ok(`Maintenance mode disabled. Live traffic restored!`);
|
|
6150
|
+
return;
|
|
6151
|
+
}
|
|
6152
|
+
default:
|
|
6153
|
+
throw new EpdError(`Unknown action "${action}". Available: on, off, status`);
|
|
6154
|
+
}
|
|
6155
|
+
}
|
|
6156
|
+
};
|
|
6157
|
+
|
|
6158
|
+
// src/commands/ssl.ts
|
|
6159
|
+
import { X509Certificate } from "crypto";
|
|
6160
|
+
function parseAcmeCert(entry) {
|
|
6161
|
+
try {
|
|
6162
|
+
if (!entry.certificate)
|
|
6163
|
+
return null;
|
|
6164
|
+
const pem = Buffer.from(entry.certificate, "base64").toString("utf8");
|
|
6165
|
+
const cert = new X509Certificate(pem);
|
|
6166
|
+
const validTo = new Date(cert.validTo);
|
|
6167
|
+
const validFrom = new Date(cert.validFrom);
|
|
6168
|
+
const msRemaining = validTo.getTime() - Date.now();
|
|
6169
|
+
const daysRemaining = Math.floor(msRemaining / (1000 * 60 * 60 * 24));
|
|
6170
|
+
let status = "active";
|
|
6171
|
+
if (daysRemaining <= 0)
|
|
6172
|
+
status = "expired";
|
|
6173
|
+
else if (daysRemaining <= 14)
|
|
6174
|
+
status = "expiring_soon";
|
|
6175
|
+
const sans = cert.subjectAltName ? cert.subjectAltName.split(", ").map((s) => s.replace(/^DNS:/, "")) : [];
|
|
6176
|
+
const issuerMatch = cert.issuer.match(/O=([^,\n]+)/) || cert.issuer.match(/CN=([^,\n]+)/);
|
|
6177
|
+
const issuer = issuerMatch ? issuerMatch[1] : cert.issuer;
|
|
6178
|
+
const mainDomain = entry.domain?.main || cert.subject.replace(/^CN=/, "");
|
|
6179
|
+
return {
|
|
6180
|
+
mainDomain,
|
|
6181
|
+
sans: sans.filter((s) => s !== mainDomain),
|
|
6182
|
+
issuer: issuer || "Let's Encrypt",
|
|
6183
|
+
validFrom: validFrom.toISOString().split("T")[0] ?? "",
|
|
6184
|
+
validTo: validTo.toISOString().split("T")[0] ?? "",
|
|
6185
|
+
daysRemaining,
|
|
6186
|
+
status
|
|
6187
|
+
};
|
|
6188
|
+
} catch {
|
|
6189
|
+
return null;
|
|
6190
|
+
}
|
|
6191
|
+
}
|
|
6192
|
+
var ssl = {
|
|
6193
|
+
name: "ssl",
|
|
6194
|
+
aliases: ["certs"],
|
|
6195
|
+
summary: "Inspect and verify Let's Encrypt SSL/TLS certificates",
|
|
6196
|
+
options: {
|
|
6197
|
+
host: { type: "string" },
|
|
6198
|
+
json: { type: "boolean" }
|
|
6199
|
+
},
|
|
6200
|
+
help: () => `${c.bold("epd ssl [status]")} \u2014 inspect SSL certificates managed by Traefik
|
|
6201
|
+
|
|
6202
|
+
Displays certificates stored in /var/lib/epd/proxy/acme/acme.json, including
|
|
6203
|
+
domains, SANs, issuers, expiration dates, and days remaining.
|
|
6204
|
+
|
|
6205
|
+
Options
|
|
6206
|
+
--host <ip> Only inspect this host
|
|
6207
|
+
--json Output certificate metadata as JSON`,
|
|
6208
|
+
async run(ctx) {
|
|
6209
|
+
const loaded = ctx.load();
|
|
6210
|
+
const cfg = loaded.config;
|
|
6211
|
+
let names = proxyHosts(cfg);
|
|
6212
|
+
if (ctx.values.host)
|
|
6213
|
+
names = names.filter((h) => h === ctx.values.host);
|
|
6214
|
+
if (!names.length)
|
|
6215
|
+
throw new EpdError("No proxy hosts found in configuration");
|
|
6216
|
+
const hosts = names.map((h) => host(h, cfg.ssh));
|
|
6217
|
+
const p = paths(cfg);
|
|
6218
|
+
const acmeFilePath = `${p.acmeDir}/acme.json`;
|
|
6219
|
+
const allResults = {};
|
|
6220
|
+
for (const host of hosts) {
|
|
6221
|
+
log.step(`Checking SSL certificates on ${c.bold(host.name)}...`);
|
|
6222
|
+
const exists = await host.test(`[ -f ${shq(acmeFilePath)} ]`);
|
|
6223
|
+
if (!exists) {
|
|
6224
|
+
log.warn(`No acme.json found on ${host.name} yet. Traefik generates certificates upon the first incoming HTTPS request.`);
|
|
6225
|
+
allResults[host.name] = [];
|
|
6226
|
+
continue;
|
|
6227
|
+
}
|
|
6228
|
+
const rawJson = await host.capture(`cat ${shq(acmeFilePath)} 2>/dev/null || echo "{}"`, { allowFailure: true });
|
|
6229
|
+
let data = {};
|
|
6230
|
+
try {
|
|
6231
|
+
data = JSON.parse(rawJson);
|
|
6232
|
+
} catch {
|
|
6233
|
+
log.warn(`Failed to parse acme.json on ${host.name}.`);
|
|
6234
|
+
allResults[host.name] = [];
|
|
6235
|
+
continue;
|
|
6236
|
+
}
|
|
6237
|
+
const certs = [];
|
|
6238
|
+
for (const resolverKey of Object.keys(data)) {
|
|
6239
|
+
const resolverObj = data[resolverKey];
|
|
6240
|
+
const certList = Array.isArray(resolverObj?.Certificates) ? resolverObj.Certificates : [];
|
|
6241
|
+
for (const entry of certList) {
|
|
6242
|
+
const parsed = parseAcmeCert(entry);
|
|
6243
|
+
if (parsed)
|
|
6244
|
+
certs.push(parsed);
|
|
6245
|
+
}
|
|
6246
|
+
}
|
|
6247
|
+
allResults[host.name] = certs;
|
|
6248
|
+
if (ctx.values.json)
|
|
6249
|
+
continue;
|
|
6250
|
+
if (!certs.length) {
|
|
6251
|
+
log.info(`No certificates found in ${acmeFilePath} on ${host.name}.`);
|
|
6252
|
+
continue;
|
|
6253
|
+
}
|
|
6254
|
+
console.log("");
|
|
6255
|
+
console.log(` ${c.bold("Host:")} ${c.magenta(host.name)}`);
|
|
6256
|
+
console.log(` ${c.bold("SSL Resolver:")} Let's Encrypt (${cfg.proxy.email || "no contact email"})`);
|
|
6257
|
+
console.log("");
|
|
6258
|
+
const rows = [
|
|
6259
|
+
["Domain", "SANs", "Issuer", "Expires", "Status"]
|
|
6260
|
+
];
|
|
6261
|
+
for (const cert of certs) {
|
|
6262
|
+
let statusStr = "";
|
|
6263
|
+
if (cert.status === "active") {
|
|
6264
|
+
statusStr = c.green(`Active (${cert.daysRemaining}d left)`);
|
|
6265
|
+
} else if (cert.status === "expiring_soon") {
|
|
6266
|
+
statusStr = c.yellow(`Expiring soon (${cert.daysRemaining}d left)`);
|
|
6267
|
+
} else {
|
|
6268
|
+
statusStr = c.red(`EXPIRED`);
|
|
6269
|
+
}
|
|
6270
|
+
rows.push([
|
|
6271
|
+
c.bold(cert.mainDomain),
|
|
6272
|
+
cert.sans.length ? cert.sans.join(", ") : c.gray("\u2014"),
|
|
6273
|
+
cert.issuer,
|
|
6274
|
+
cert.validTo,
|
|
6275
|
+
statusStr
|
|
6276
|
+
]);
|
|
6277
|
+
}
|
|
6278
|
+
const colWidths = [0, 0, 0, 0, 0];
|
|
6279
|
+
for (const row of rows) {
|
|
6280
|
+
for (let i = 0;i < row.length; i++) {
|
|
6281
|
+
const rawLen = row[i].replace(/\x1B\[\d+m/g, "").length;
|
|
6282
|
+
colWidths[i] = Math.max(colWidths[i], rawLen);
|
|
6283
|
+
}
|
|
6284
|
+
}
|
|
6285
|
+
for (let r = 0;r < rows.length; r++) {
|
|
6286
|
+
const row = rows[r];
|
|
6287
|
+
const line = row.map((val, idx) => {
|
|
6288
|
+
const rawLen = val.replace(/\x1B\[\d+m/g, "").length;
|
|
6289
|
+
const pad = " ".repeat(Math.max(0, colWidths[idx] - rawLen));
|
|
6290
|
+
return val + pad;
|
|
6291
|
+
}).join(" ");
|
|
6292
|
+
if (r === 0) {
|
|
6293
|
+
console.log(` ${c.gray(line)}`);
|
|
6294
|
+
console.log(` ${c.gray("-".repeat(line.length))}`);
|
|
6295
|
+
} else {
|
|
6296
|
+
console.log(` ${line}`);
|
|
6297
|
+
}
|
|
6298
|
+
}
|
|
6299
|
+
console.log("");
|
|
6300
|
+
}
|
|
6301
|
+
if (ctx.values.json) {
|
|
6302
|
+
console.log(JSON.stringify(allResults, null, 2));
|
|
6303
|
+
}
|
|
6304
|
+
}
|
|
6305
|
+
};
|
|
6306
|
+
|
|
6307
|
+
// src/commands/top.ts
|
|
6308
|
+
async function collectHostStats(host, cfg) {
|
|
6309
|
+
const isDocker = cfg.mode === "docker";
|
|
6310
|
+
const script = `
|
|
6311
|
+
echo "===UPTIME==="
|
|
6312
|
+
uptime || true
|
|
6313
|
+
echo "===MEM==="
|
|
6314
|
+
free -m 2>/dev/null | awk '/Mem:/ {printf "%dM / %dM (%.1f%%)", $3, $2, ($3/$2)*100}' || true
|
|
6315
|
+
echo ""
|
|
6316
|
+
echo "===DISK==="
|
|
6317
|
+
df -h /var/lib/epd 2>/dev/null | awk 'NR==2 {printf "%s / %s (%s)", $3, $2, $5}' || df -h / 2>/dev/null | awk 'NR==2 {printf "%s / %s (%s)", $3, $2, $5}' || true
|
|
6318
|
+
echo ""
|
|
6319
|
+
echo "===CONTAINERS==="
|
|
6320
|
+
${isDocker ? "docker stats --no-stream --format '{{json .}}' 2>/dev/null || true" : "pm2 jlist 2>/dev/null || true"}
|
|
6321
|
+
`;
|
|
6322
|
+
const output = await host.capture(script, { allowFailure: true });
|
|
6323
|
+
const uptimeMatch = output.match(/===UPTIME===\s*([\s\S]*?)===MEM===/);
|
|
6324
|
+
const memMatch = output.match(/===MEM===\s*([\s\S]*?)===DISK===/);
|
|
6325
|
+
const diskMatch = output.match(/===DISK===\s*([\s\S]*?)===CONTAINERS===/);
|
|
6326
|
+
const containersRaw = output.split("===CONTAINERS===")[1] || "";
|
|
6327
|
+
const uptimeStr = (uptimeMatch?.[1] ?? "").trim();
|
|
6328
|
+
const ramStr = (memMatch?.[1] ?? "").trim();
|
|
6329
|
+
const diskStr = (diskMatch?.[1] ?? "").trim();
|
|
6330
|
+
let loadAvg = "";
|
|
6331
|
+
const loadMatch = uptimeStr.match(/load average[s]?:\s*([^\n]+)/i);
|
|
6332
|
+
if (loadMatch)
|
|
6333
|
+
loadAvg = loadMatch[1].trim();
|
|
6334
|
+
const containers = [];
|
|
6335
|
+
if (isDocker) {
|
|
6336
|
+
for (const line of containersRaw.split(`
|
|
6337
|
+
`)) {
|
|
6338
|
+
const trimmed = line.trim();
|
|
6339
|
+
if (!trimmed.startsWith("{"))
|
|
6340
|
+
continue;
|
|
6341
|
+
try {
|
|
6342
|
+
const item = JSON.parse(trimmed);
|
|
6343
|
+
if (item.Name && (item.Name.includes("epd") || item.Name.includes(cfg.name))) {
|
|
6344
|
+
containers.push(item);
|
|
6345
|
+
} else if (item.Name) {
|
|
6346
|
+
containers.push(item);
|
|
6347
|
+
}
|
|
6348
|
+
} catch {}
|
|
6349
|
+
}
|
|
6350
|
+
} else {
|
|
6351
|
+
try {
|
|
6352
|
+
const pm2List = JSON.parse(containersRaw);
|
|
6353
|
+
if (Array.isArray(pm2List)) {
|
|
6354
|
+
for (const proc of pm2List) {
|
|
6355
|
+
const memMb = proc.monit?.memory ? (proc.monit.memory / (1024 * 1024)).toFixed(1) + "MiB" : "0MiB";
|
|
6356
|
+
const cpu = proc.monit?.cpu ? `${proc.monit.cpu}%` : "0%";
|
|
6357
|
+
containers.push({
|
|
6358
|
+
Name: proc.name || "process",
|
|
6359
|
+
CPUPerc: cpu,
|
|
6360
|
+
MemUsage: memMb,
|
|
6361
|
+
MemPerc: "\u2014",
|
|
6362
|
+
NetIO: "\u2014",
|
|
6363
|
+
BlockIO: "\u2014",
|
|
6364
|
+
PIDs: String(proc.pid || "\u2014")
|
|
6365
|
+
});
|
|
6366
|
+
}
|
|
6367
|
+
}
|
|
6368
|
+
} catch {}
|
|
6369
|
+
}
|
|
6370
|
+
return {
|
|
6371
|
+
hostName: host.name,
|
|
6372
|
+
uptime: uptimeStr,
|
|
6373
|
+
loadAvg,
|
|
6374
|
+
ramSummary: ramStr || "unknown",
|
|
6375
|
+
diskSummary: diskStr || "unknown",
|
|
6376
|
+
containers
|
|
6377
|
+
};
|
|
6378
|
+
}
|
|
6379
|
+
function renderDashboard(statsList) {
|
|
6380
|
+
for (const stats of statsList) {
|
|
6381
|
+
console.log(c.bold(`
|
|
6382
|
+
\u2500\u2500 Host: ${c.magenta(stats.hostName)} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`));
|
|
6383
|
+
console.log(` ${c.gray("Load:")} ${stats.loadAvg || "\u2014"} \u2502 ${c.gray("RAM:")} ${stats.ramSummary} \u2502 ${c.gray("Disk (/var/lib/epd):")} ${stats.diskSummary}`);
|
|
6384
|
+
console.log("");
|
|
6385
|
+
if (!stats.containers.length) {
|
|
6386
|
+
console.log(` ${c.gray("No running containers or processes found.")}
|
|
6387
|
+
`);
|
|
6388
|
+
continue;
|
|
6389
|
+
}
|
|
6390
|
+
const rows = [
|
|
6391
|
+
["Container / Service", "CPU %", "Mem Usage / Limit", "Mem %", "Net I/O", "PIDs"]
|
|
6392
|
+
];
|
|
6393
|
+
for (const cItem of stats.containers) {
|
|
6394
|
+
let cpuFormatted = cItem.CPUPerc;
|
|
6395
|
+
const cpuNum = parseFloat(cItem.CPUPerc);
|
|
6396
|
+
if (cpuNum > 80)
|
|
6397
|
+
cpuFormatted = c.red(cItem.CPUPerc);
|
|
6398
|
+
else if (cpuNum > 40)
|
|
6399
|
+
cpuFormatted = c.yellow(cItem.CPUPerc);
|
|
6400
|
+
else
|
|
6401
|
+
cpuFormatted = c.green(cItem.CPUPerc);
|
|
6402
|
+
rows.push([
|
|
6403
|
+
c.bold(cItem.Name),
|
|
6404
|
+
cpuFormatted,
|
|
6405
|
+
cItem.MemUsage,
|
|
6406
|
+
cItem.MemPerc,
|
|
6407
|
+
cItem.NetIO,
|
|
6408
|
+
cItem.PIDs
|
|
6409
|
+
]);
|
|
6410
|
+
}
|
|
6411
|
+
const colWidths = [0, 0, 0, 0, 0, 0];
|
|
6412
|
+
for (const row of rows) {
|
|
6413
|
+
for (let i = 0;i < row.length; i++) {
|
|
6414
|
+
const rawLen = row[i].replace(/\x1B\[\d+m/g, "").length;
|
|
6415
|
+
colWidths[i] = Math.max(colWidths[i], rawLen);
|
|
6416
|
+
}
|
|
6417
|
+
}
|
|
6418
|
+
for (let r = 0;r < rows.length; r++) {
|
|
6419
|
+
const row = rows[r];
|
|
6420
|
+
const line = row.map((val, idx) => {
|
|
6421
|
+
const rawLen = val.replace(/\x1B\[\d+m/g, "").length;
|
|
6422
|
+
const pad = " ".repeat(Math.max(0, colWidths[idx] - rawLen));
|
|
6423
|
+
return val + pad;
|
|
6424
|
+
}).join(" ");
|
|
6425
|
+
if (r === 0) {
|
|
6426
|
+
console.log(` ${c.gray(line)}`);
|
|
6427
|
+
console.log(` ${c.gray("-".repeat(line.length))}`);
|
|
6428
|
+
} else {
|
|
6429
|
+
console.log(` ${line}`);
|
|
6430
|
+
}
|
|
6431
|
+
}
|
|
6432
|
+
console.log("");
|
|
6433
|
+
}
|
|
6434
|
+
}
|
|
6435
|
+
var top = {
|
|
6436
|
+
name: "top",
|
|
6437
|
+
aliases: ["stats"],
|
|
6438
|
+
summary: "Live multi-server CPU, memory, container and disk resource monitor",
|
|
6439
|
+
options: {
|
|
6440
|
+
host: { type: "string" },
|
|
6441
|
+
watch: { type: "boolean", short: "w" },
|
|
6442
|
+
once: { type: "boolean" }
|
|
6443
|
+
},
|
|
6444
|
+
help: () => `${c.bold("epd top")} \u2014 real-time server and container metrics monitor (aliased as epd stats)
|
|
6445
|
+
|
|
6446
|
+
Aggregates CPU %, memory consumption, network I/O, disk space, and load averages
|
|
6447
|
+
across all servers running this application.
|
|
6448
|
+
|
|
6449
|
+
Options
|
|
6450
|
+
--host <ip> Monitor only this specific host
|
|
6451
|
+
-w, --watch Stream metrics continuously (refreshes every 2s)
|
|
6452
|
+
--once Print a single snapshot and exit`,
|
|
6453
|
+
async run(ctx) {
|
|
6454
|
+
const loaded = ctx.load();
|
|
6455
|
+
const cfg = loaded.config;
|
|
6456
|
+
let hostNames = allHosts(cfg);
|
|
6457
|
+
if (ctx.values.host)
|
|
6458
|
+
hostNames = hostNames.filter((h) => h === ctx.values.host);
|
|
6459
|
+
if (!hostNames.length)
|
|
6460
|
+
throw new EpdError("No hosts found in configuration");
|
|
6461
|
+
const hosts = hostNames.map((h) => host(h, cfg.ssh));
|
|
6462
|
+
const shouldWatch = Boolean(ctx.values.watch) || interactive() && !ctx.values.once;
|
|
6463
|
+
const refresh = async () => {
|
|
6464
|
+
const statsList = await Promise.all(hosts.map((h) => collectHostStats(h, cfg)));
|
|
6465
|
+
if (shouldWatch)
|
|
6466
|
+
process.stdout.write("\x1Bc");
|
|
6467
|
+
renderDashboard(statsList);
|
|
6468
|
+
if (shouldWatch) {
|
|
6469
|
+
console.log(c.gray(` Streaming live metrics (2s interval). Press Ctrl-C to exit.`));
|
|
6470
|
+
}
|
|
6471
|
+
};
|
|
6472
|
+
await refresh();
|
|
6473
|
+
if (shouldWatch) {
|
|
6474
|
+
return new Promise((resolve) => {
|
|
6475
|
+
const interval = setInterval(async () => {
|
|
6476
|
+
try {
|
|
6477
|
+
await refresh();
|
|
6478
|
+
} catch {
|
|
6479
|
+
clearInterval(interval);
|
|
6480
|
+
resolve();
|
|
6481
|
+
}
|
|
6482
|
+
}, 2000);
|
|
6483
|
+
process.on("SIGINT", () => {
|
|
6484
|
+
clearInterval(interval);
|
|
6485
|
+
console.log("");
|
|
6486
|
+
resolve();
|
|
6487
|
+
});
|
|
6488
|
+
});
|
|
6489
|
+
}
|
|
6490
|
+
}
|
|
6491
|
+
};
|
|
6492
|
+
|
|
6493
|
+
// src/commands/backup.ts
|
|
6494
|
+
import { createWriteStream, mkdirSync as mkdirSync5, statSync } from "fs";
|
|
6495
|
+
import { dirname as dirname3, join as join8, resolve as resolve2 } from "path";
|
|
6496
|
+
function detectAccessoryType(decl, cfg) {
|
|
6497
|
+
const name = decl.name;
|
|
6498
|
+
const img = (decl.image || "").toLowerCase();
|
|
6499
|
+
const hostName = decl.host || cfg.services[0]?.hosts[0] || "localhost";
|
|
6500
|
+
const containerName = accessoryContainer(cfg.name, name);
|
|
6501
|
+
const env = { ...decl.env };
|
|
6502
|
+
if (img.includes("postgres") || img.includes("postgis") || img.includes("timescale")) {
|
|
6503
|
+
return {
|
|
6504
|
+
name,
|
|
6505
|
+
decl,
|
|
6506
|
+
hostName,
|
|
6507
|
+
type: "postgres",
|
|
6508
|
+
containerName,
|
|
6509
|
+
dbUser: env.POSTGRES_USER || "postgres",
|
|
6510
|
+
dbName: env.POSTGRES_DB || cfg.name
|
|
6511
|
+
};
|
|
6512
|
+
}
|
|
6513
|
+
if (img.includes("mysql") || img.includes("mariadb")) {
|
|
6514
|
+
return {
|
|
6515
|
+
name,
|
|
6516
|
+
decl,
|
|
6517
|
+
hostName,
|
|
6518
|
+
type: "mysql",
|
|
6519
|
+
containerName,
|
|
6520
|
+
dbUser: env.MYSQL_USER || "root",
|
|
6521
|
+
dbPass: env.MYSQL_ROOT_PASSWORD || env.MYSQL_PASSWORD,
|
|
6522
|
+
dbName: env.MYSQL_DATABASE || cfg.name
|
|
6523
|
+
};
|
|
6524
|
+
}
|
|
6525
|
+
if (img.includes("mongo")) {
|
|
6526
|
+
return {
|
|
6527
|
+
name,
|
|
6528
|
+
decl,
|
|
6529
|
+
hostName,
|
|
6530
|
+
type: "mongo",
|
|
6531
|
+
containerName,
|
|
6532
|
+
dbName: cfg.name
|
|
6533
|
+
};
|
|
6534
|
+
}
|
|
6535
|
+
let volumeDir;
|
|
6536
|
+
for (const v of decl.volumes) {
|
|
6537
|
+
const hostSide = v.split(":")[0];
|
|
6538
|
+
if (hostSide && hostSide.startsWith("/")) {
|
|
6539
|
+
volumeDir = hostSide;
|
|
6540
|
+
break;
|
|
6541
|
+
}
|
|
6542
|
+
}
|
|
6543
|
+
return {
|
|
6544
|
+
name,
|
|
6545
|
+
decl,
|
|
6546
|
+
hostName,
|
|
6547
|
+
type: "volume",
|
|
6548
|
+
containerName,
|
|
6549
|
+
volumeDir
|
|
6550
|
+
};
|
|
6551
|
+
}
|
|
6552
|
+
var backup = {
|
|
6553
|
+
name: "backup",
|
|
6554
|
+
summary: "Back up databases and accessory volumes to compressed local archives",
|
|
6555
|
+
options: {
|
|
6556
|
+
output: { type: "string", short: "o" },
|
|
6557
|
+
host: { type: "string" }
|
|
6558
|
+
},
|
|
6559
|
+
help: () => `${c.bold("epd backup [accessory]")} \u2014 create compressed database or volume backups
|
|
6560
|
+
|
|
6561
|
+
Automatically inspects the accessory image (PostgreSQL, MySQL, MariaDB, Mongo, or generic volumes)
|
|
6562
|
+
and streams a compressed snapshot directly to your local ./backups directory.
|
|
6563
|
+
|
|
6564
|
+
Options
|
|
6565
|
+
-o, --output <path> Custom output path or destination directory
|
|
6566
|
+
--host <ip> Host running the accessory`,
|
|
6567
|
+
async run(ctx) {
|
|
6568
|
+
const loaded = ctx.load();
|
|
6569
|
+
const cfg = loaded.config;
|
|
6570
|
+
const requestedName = ctx.positionals[0];
|
|
6571
|
+
const accessories = cfg.accessories;
|
|
6572
|
+
if (!accessories.length) {
|
|
6573
|
+
throw new EpdError(`No accessories configured in epd.yml under "accessories:".`);
|
|
6574
|
+
}
|
|
6575
|
+
let targets = [];
|
|
6576
|
+
if (requestedName) {
|
|
6577
|
+
const found = accessories.find((a) => a.name === requestedName);
|
|
6578
|
+
if (!found) {
|
|
6579
|
+
throw new EpdError(`Accessory "${requestedName}" not found. Configured: ${accessories.map((a) => a.name).join(", ")}`);
|
|
6580
|
+
}
|
|
6581
|
+
targets = [detectAccessoryType(found, cfg)];
|
|
6582
|
+
} else {
|
|
6583
|
+
targets = accessories.map((a) => detectAccessoryType(a, cfg));
|
|
6584
|
+
}
|
|
6585
|
+
const outBaseDir = resolve2(process.cwd(), "backups");
|
|
6586
|
+
mkdirSync5(outBaseDir, { recursive: true });
|
|
6587
|
+
for (const target of targets) {
|
|
6588
|
+
const host2 = host(target.hostName, cfg.ssh);
|
|
6589
|
+
const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${target.containerName}$`)} | grep -q .`);
|
|
6590
|
+
if (!isRunning) {
|
|
6591
|
+
log.warn(`Container ${c.bold(target.containerName)} is not currently running on ${host2.name}. Skipping.`);
|
|
6592
|
+
continue;
|
|
6593
|
+
}
|
|
6594
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
|
|
6595
|
+
const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
|
|
6596
|
+
const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
|
|
6597
|
+
const localFile = ctx.values.output ? resolve2(String(ctx.values.output)) : join8(outBaseDir, filename);
|
|
6598
|
+
mkdirSync5(dirname3(localFile), { recursive: true });
|
|
6599
|
+
let dumpCmd = "";
|
|
6600
|
+
if (target.type === "postgres") {
|
|
6601
|
+
dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
|
|
6602
|
+
} else if (target.type === "mysql") {
|
|
6603
|
+
const passFlag = target.dbPass ? `-p${shq(target.dbPass)}` : "";
|
|
6604
|
+
dumpCmd = `docker exec ${shq(target.containerName)} mysqldump -u ${shq(target.dbUser)} ${passFlag} ${shq(target.dbName)} | gzip -9`;
|
|
6605
|
+
} else if (target.type === "mongo") {
|
|
6606
|
+
dumpCmd = `docker exec ${shq(target.containerName)} mongodump --archive --gzip`;
|
|
6607
|
+
} else {
|
|
6608
|
+
if (!target.volumeDir) {
|
|
6609
|
+
log.warn(`No host volume path found for accessory "${target.name}". Skipping.`);
|
|
6610
|
+
continue;
|
|
6611
|
+
}
|
|
6612
|
+
dumpCmd = `tar -czf - -C ${shq(target.volumeDir)} .`;
|
|
6613
|
+
}
|
|
6614
|
+
log.step(`Streaming ${c.bold(target.type)} backup of ${c.magenta(target.name)} from ${host2.name}...`);
|
|
6615
|
+
const t0 = Date.now();
|
|
6616
|
+
const sshArgs = [...host2.sshOptions(), host2.target, dumpCmd];
|
|
6617
|
+
const writeStream = createWriteStream(localFile);
|
|
6618
|
+
await new Promise((res, rej) => {
|
|
6619
|
+
const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...sshArgs], { stdout: "pipe", stderr: "pipe" }) : __require("child_process").spawn("ssh", sshArgs, { stdio: ["ignore", "pipe", "pipe"] });
|
|
6620
|
+
const stream = proc.stdout;
|
|
6621
|
+
stream.pipe(writeStream);
|
|
6622
|
+
writeStream.on("finish", () => res());
|
|
6623
|
+
writeStream.on("error", rej);
|
|
6624
|
+
if (proc.exited) {
|
|
6625
|
+
proc.exited.then((code) => {
|
|
6626
|
+
if (code !== 0)
|
|
6627
|
+
rej(new EpdError(`SSH backup process exited with code ${code}`));
|
|
6628
|
+
});
|
|
6629
|
+
} else {
|
|
6630
|
+
proc.on("close", (code) => {
|
|
6631
|
+
if (code !== 0)
|
|
6632
|
+
rej(new EpdError(`SSH backup process exited with code ${code}`));
|
|
6633
|
+
});
|
|
6634
|
+
}
|
|
6635
|
+
});
|
|
6636
|
+
const stats = statSync(localFile);
|
|
6637
|
+
const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
|
|
6638
|
+
const elapsed = dur(Date.now() - t0);
|
|
6639
|
+
log.ok(`Backed up ${c.bold(target.name)} \u2192 ${c.cyan(localFile)} (${sizeMb} MB in ${elapsed})`);
|
|
6640
|
+
}
|
|
6641
|
+
}
|
|
6642
|
+
};
|
|
6643
|
+
|
|
6644
|
+
// src/commands/restore.ts
|
|
6645
|
+
import { createReadStream, existsSync as existsSync7 } from "fs";
|
|
6646
|
+
import { basename as basename2, resolve as resolve3 } from "path";
|
|
6647
|
+
var restore = {
|
|
6648
|
+
name: "restore",
|
|
6649
|
+
summary: "Restore a database or volume backup into a running accessory",
|
|
6650
|
+
options: {
|
|
6651
|
+
accessory: { type: "string", short: "a" },
|
|
6652
|
+
yes: { type: "boolean", short: "y" }
|
|
6653
|
+
},
|
|
6654
|
+
help: () => `${c.bold("epd restore <backup-file>")} \u2014 restore a database or volume backup
|
|
6655
|
+
|
|
6656
|
+
Pipes a local .sql.gz or .tar.gz archive directly into a live accessory container.
|
|
6657
|
+
|
|
6658
|
+
Options
|
|
6659
|
+
-a, --accessory <name> Target accessory name (default: auto-detected from filename)
|
|
6660
|
+
-y, --yes Skip confirmation prompt`,
|
|
6661
|
+
async run(ctx) {
|
|
6662
|
+
const backupPath = ctx.positionals[0];
|
|
6663
|
+
if (!backupPath)
|
|
6664
|
+
throw new EpdError("Please provide a path to the backup file to restore.");
|
|
6665
|
+
const absPath = resolve3(backupPath);
|
|
6666
|
+
if (!existsSync7(absPath))
|
|
6667
|
+
throw new EpdError(`Backup file not found: ${absPath}`);
|
|
6668
|
+
const loaded = ctx.load();
|
|
6669
|
+
const cfg = loaded.config;
|
|
6670
|
+
const fileBase = basename2(absPath);
|
|
6671
|
+
const accessories = cfg.accessories;
|
|
6672
|
+
if (!accessories.length)
|
|
6673
|
+
throw new EpdError("No accessories configured in epd.yml.");
|
|
6674
|
+
let targetAccessoryName = ctx.values.accessory;
|
|
6675
|
+
if (!targetAccessoryName) {
|
|
6676
|
+
for (const a of accessories) {
|
|
6677
|
+
if (fileBase.includes(a.name)) {
|
|
6678
|
+
targetAccessoryName = a.name;
|
|
6679
|
+
break;
|
|
6680
|
+
}
|
|
6681
|
+
}
|
|
6682
|
+
}
|
|
6683
|
+
if (!targetAccessoryName && accessories.length === 1) {
|
|
6684
|
+
targetAccessoryName = accessories[0].name;
|
|
6685
|
+
}
|
|
6686
|
+
if (!targetAccessoryName) {
|
|
6687
|
+
throw new EpdError(`Could not auto-detect target accessory from filename "${fileBase}". Specify with --accessory <name>.`);
|
|
6688
|
+
}
|
|
6689
|
+
const decl = accessories.find((a) => a.name === targetAccessoryName);
|
|
6690
|
+
if (!decl) {
|
|
6691
|
+
throw new EpdError(`Accessory "${targetAccessoryName}" not found in configuration.`);
|
|
6692
|
+
}
|
|
6693
|
+
const hostName = decl.host || cfg.services[0]?.hosts[0] || "localhost";
|
|
6694
|
+
const host2 = host(hostName, cfg.ssh);
|
|
6695
|
+
const containerName = accessoryContainer(cfg.name, targetAccessoryName);
|
|
6696
|
+
const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${containerName}$`)} | grep -q .`);
|
|
6697
|
+
if (!isRunning) {
|
|
6698
|
+
throw new EpdError(`Accessory container ${containerName} is not running on ${host2.name}.`);
|
|
6699
|
+
}
|
|
6700
|
+
if (!ctx.values.yes) {
|
|
6701
|
+
log.warn(`Restoring will overwrite existing data in accessory ${c.bold(targetAccessoryName)} on ${c.magenta(host2.name)}!`);
|
|
6702
|
+
const ok = await confirm(`Are you sure you want to restore ${c.bold(fileBase)}?`, false);
|
|
6703
|
+
if (!ok) {
|
|
6704
|
+
log.info("Restore aborted.");
|
|
6705
|
+
return;
|
|
6706
|
+
}
|
|
6707
|
+
}
|
|
6708
|
+
const img = (decl.image || "").toLowerCase();
|
|
6709
|
+
const env = { ...decl.env };
|
|
6710
|
+
let restoreCmd = "";
|
|
6711
|
+
if (img.includes("postgres") || img.includes("postgis") || img.includes("timescale")) {
|
|
6712
|
+
const user = env.POSTGRES_USER || "postgres";
|
|
6713
|
+
const db = env.POSTGRES_DB || cfg.name;
|
|
6714
|
+
restoreCmd = `gunzip -c | docker exec -i ${shq(containerName)} psql -U ${shq(user)} ${shq(db)}`;
|
|
6715
|
+
} else if (img.includes("mysql") || img.includes("mariadb")) {
|
|
6716
|
+
const user = env.MYSQL_USER || "root";
|
|
6717
|
+
const pass = env.MYSQL_ROOT_PASSWORD || env.MYSQL_PASSWORD;
|
|
6718
|
+
const passFlag = pass ? `-p${shq(pass)}` : "";
|
|
6719
|
+
const db = env.MYSQL_DATABASE || cfg.name;
|
|
6720
|
+
restoreCmd = `gunzip -c | docker exec -i ${shq(containerName)} mysql -u ${shq(user)} ${passFlag} ${shq(db)}`;
|
|
6721
|
+
} else if (img.includes("mongo")) {
|
|
6722
|
+
restoreCmd = `docker exec -i ${shq(containerName)} mongorestore --archive --gzip`;
|
|
6723
|
+
} else {
|
|
6724
|
+
let volumeDir;
|
|
6725
|
+
for (const v of decl.volumes) {
|
|
6726
|
+
const hostSide = v.split(":")[0];
|
|
6727
|
+
if (hostSide && hostSide.startsWith("/")) {
|
|
6728
|
+
volumeDir = hostSide;
|
|
6729
|
+
break;
|
|
6730
|
+
}
|
|
6731
|
+
}
|
|
6732
|
+
if (!volumeDir)
|
|
6733
|
+
throw new EpdError(`No host volume path configured for accessory "${targetAccessoryName}".`);
|
|
6734
|
+
restoreCmd = `tar -xzf - -C ${shq(volumeDir)}`;
|
|
6735
|
+
}
|
|
6736
|
+
log.step(`Streaming restore into ${c.bold(targetAccessoryName)} on ${host2.name}...`);
|
|
6737
|
+
const t0 = Date.now();
|
|
6738
|
+
const sshArgs = [...host2.sshOptions(), host2.target, restoreCmd];
|
|
6739
|
+
const readStream = createReadStream(absPath);
|
|
6740
|
+
await new Promise((res, rej) => {
|
|
6741
|
+
const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...sshArgs], { stdin: "pipe", stdout: "inherit", stderr: "inherit" }) : __require("child_process").spawn("ssh", sshArgs, { stdio: ["pipe", "inherit", "inherit"] });
|
|
6742
|
+
const stdinStream = proc.stdin;
|
|
6743
|
+
readStream.pipe(stdinStream);
|
|
6744
|
+
readStream.on("error", rej);
|
|
6745
|
+
if (proc.exited) {
|
|
6746
|
+
proc.exited.then((code) => {
|
|
6747
|
+
if (code !== 0)
|
|
6748
|
+
rej(new EpdError(`Restore command exited with code ${code}`));
|
|
6749
|
+
else
|
|
6750
|
+
res();
|
|
6751
|
+
});
|
|
6752
|
+
} else {
|
|
6753
|
+
proc.on("close", (code) => {
|
|
6754
|
+
if (code !== 0)
|
|
6755
|
+
rej(new EpdError(`Restore command exited with code ${code}`));
|
|
6756
|
+
else
|
|
6757
|
+
res();
|
|
6758
|
+
});
|
|
6759
|
+
}
|
|
6760
|
+
});
|
|
6761
|
+
const elapsed = dur(Date.now() - t0);
|
|
6762
|
+
log.ok(`Successfully restored ${c.bold(fileBase)} into ${c.bold(targetAccessoryName)} (${elapsed})!`);
|
|
6763
|
+
}
|
|
6764
|
+
};
|
|
6765
|
+
|
|
5321
6766
|
// src/commands/index.ts
|
|
5322
6767
|
var commands = [
|
|
5323
6768
|
init,
|
|
@@ -5337,7 +6782,13 @@ var commands = [
|
|
|
5337
6782
|
cloudflare,
|
|
5338
6783
|
dns3,
|
|
5339
6784
|
hetzner,
|
|
5340
|
-
update
|
|
6785
|
+
update,
|
|
6786
|
+
auth,
|
|
6787
|
+
maintenance,
|
|
6788
|
+
ssl,
|
|
6789
|
+
top,
|
|
6790
|
+
backup,
|
|
6791
|
+
restore
|
|
5341
6792
|
];
|
|
5342
6793
|
|
|
5343
6794
|
// src/cli.ts
|