@fabioplunser/epd 0.3.0 → 0.4.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/dist/cli.js CHANGED
@@ -849,8 +849,8 @@ function validateCrossReferences(cfg) {
849
849
  }
850
850
 
851
851
  // src/commands/init.ts
852
- import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
853
- import { basename, join as join2 } from "path";
852
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
853
+ import { basename, join as join3 } from "path";
854
854
 
855
855
  // src/util/prompt.ts
856
856
  var isTTY = process.stdin.isTTY && process.stdout.isTTY;
@@ -869,6 +869,19 @@ async function ask(question, dflt) {
869
869
  const answer = (await readLine()).trim();
870
870
  return answer || dflt || "";
871
871
  }
872
+ async function askSecret(question) {
873
+ if (!isTTY)
874
+ return "";
875
+ process.stdout.write(`${c.cyan("?")} ${question} `);
876
+ const answer = (await readLine()).trim();
877
+ return answer;
878
+ }
879
+ async function pressEnter(message) {
880
+ if (!isTTY)
881
+ return;
882
+ process.stdout.write(`${c.cyan("\u21B5")} ${message} ${c.gray("[Press Enter]")} `);
883
+ await readLine();
884
+ }
872
885
  async function confirm(question, dflt = false) {
873
886
  if (!isTTY)
874
887
  return dflt;
@@ -887,17 +900,614 @@ async function choose(question, options, dflt) {
887
900
  return options[idx]?.value ?? dflt;
888
901
  }
889
902
 
903
+ // src/util/auth.ts
904
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync, chmodSync } from "fs";
905
+ import { homedir as homedir2 } from "os";
906
+ import { join as join2 } from "path";
907
+ import { spawn } from "child_process";
908
+ function openBrowser(url) {
909
+ try {
910
+ const platform = process.platform;
911
+ if (platform === "darwin") {
912
+ spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
913
+ return true;
914
+ } else if (platform === "win32") {
915
+ spawn("cmd", ["/c", "start", '""', url], { detached: true, stdio: "ignore" }).unref();
916
+ return true;
917
+ } else {
918
+ spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
919
+ return true;
920
+ }
921
+ } catch {
922
+ return false;
923
+ }
924
+ }
925
+ function getGlobalAuthPath() {
926
+ const xdgDir = join2(homedir2(), ".config", "epd");
927
+ const fallbackDir = join2(homedir2(), ".epd");
928
+ if (existsSync2(join2(xdgDir, "auth.json")))
929
+ return join2(xdgDir, "auth.json");
930
+ if (existsSync2(join2(fallbackDir, "auth.json")))
931
+ return join2(fallbackDir, "auth.json");
932
+ return join2(xdgDir, "auth.json");
933
+ }
934
+ function getGlobalAuth() {
935
+ const path = getGlobalAuthPath();
936
+ if (!existsSync2(path))
937
+ return {};
938
+ try {
939
+ return JSON.parse(readFileSync2(path, "utf8"));
940
+ } catch {
941
+ return {};
942
+ }
943
+ }
944
+ function saveGlobalAuth(updater) {
945
+ const dir = join2(homedir2(), ".config", "epd");
946
+ if (!existsSync2(dir)) {
947
+ mkdirSync(dir, { recursive: true, mode: 448 });
948
+ }
949
+ const file = join2(dir, "auth.json");
950
+ const current = getGlobalAuth();
951
+ const next = updater(current);
952
+ writeFileSync(file, JSON.stringify(next, null, 2) + `
953
+ `, { mode: 384 });
954
+ try {
955
+ chmodSync(file, 384);
956
+ } catch {}
957
+ }
958
+ function saveProjectEnv(entries, root = process.cwd()) {
959
+ const envPath = join2(root, ".env");
960
+ let content = existsSync2(envPath) ? readFileSync2(envPath, "utf8") : "";
961
+ for (const [key, val] of Object.entries(entries)) {
962
+ const regex = new RegExp(`^${key}=.*$`, "m");
963
+ const line = `${key}=${val}`;
964
+ if (regex.test(content)) {
965
+ content = content.replace(regex, line);
966
+ } else {
967
+ if (content.length && !content.endsWith(`
968
+ `))
969
+ content += `
970
+ `;
971
+ content += `${line}
972
+ `;
973
+ }
974
+ }
975
+ writeFileSync(envPath, content, "utf8");
976
+ }
977
+ function getCloudflareToken(root = process.cwd()) {
978
+ if (process.env.CLOUDFLARE_API_TOKEN)
979
+ return process.env.CLOUDFLARE_API_TOKEN;
980
+ if (process.env.CF_DNS_API_TOKEN)
981
+ return process.env.CF_DNS_API_TOKEN;
982
+ const envPath = join2(root, ".env");
983
+ if (existsSync2(envPath)) {
984
+ try {
985
+ const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
986
+ if (parsed.CLOUDFLARE_API_TOKEN)
987
+ return parsed.CLOUDFLARE_API_TOKEN;
988
+ if (parsed.CF_DNS_API_TOKEN)
989
+ return parsed.CF_DNS_API_TOKEN;
990
+ } catch {}
991
+ }
992
+ const global = getGlobalAuth();
993
+ return global.cloudflare?.apiToken;
994
+ }
995
+ function getCloudflareTokenSource(root = process.cwd()) {
996
+ if (process.env.CLOUDFLARE_API_TOKEN)
997
+ return "environment variable (CLOUDFLARE_API_TOKEN)";
998
+ if (process.env.CF_DNS_API_TOKEN)
999
+ return "environment variable (CF_DNS_API_TOKEN)";
1000
+ const envPath = join2(root, ".env");
1001
+ if (existsSync2(envPath)) {
1002
+ try {
1003
+ const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1004
+ if (parsed.CLOUDFLARE_API_TOKEN || parsed.CF_DNS_API_TOKEN)
1005
+ return ".env file";
1006
+ } catch {}
1007
+ }
1008
+ const global = getGlobalAuth();
1009
+ if (global.cloudflare?.apiToken)
1010
+ return "~/.config/epd/auth.json (global)";
1011
+ return "none";
1012
+ }
1013
+ function getHetznerToken(root = process.cwd()) {
1014
+ if (process.env.HETZNER_API_TOKEN)
1015
+ return process.env.HETZNER_API_TOKEN;
1016
+ if (process.env.HCLOUD_TOKEN)
1017
+ return process.env.HCLOUD_TOKEN;
1018
+ const envPath = join2(root, ".env");
1019
+ if (existsSync2(envPath)) {
1020
+ try {
1021
+ const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1022
+ if (parsed.HETZNER_API_TOKEN)
1023
+ return parsed.HETZNER_API_TOKEN;
1024
+ if (parsed.HCLOUD_TOKEN)
1025
+ return parsed.HCLOUD_TOKEN;
1026
+ } catch {}
1027
+ }
1028
+ const global = getGlobalAuth();
1029
+ return global.hetzner?.apiToken;
1030
+ }
1031
+ function getHetznerTokenSource(root = process.cwd()) {
1032
+ if (process.env.HETZNER_API_TOKEN)
1033
+ return "environment variable (HETZNER_API_TOKEN)";
1034
+ if (process.env.HCLOUD_TOKEN)
1035
+ return "environment variable (HCLOUD_TOKEN)";
1036
+ const envPath = join2(root, ".env");
1037
+ if (existsSync2(envPath)) {
1038
+ try {
1039
+ const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1040
+ if (parsed.HETZNER_API_TOKEN || parsed.HCLOUD_TOKEN)
1041
+ return ".env file";
1042
+ } catch {}
1043
+ }
1044
+ const global = getGlobalAuth();
1045
+ if (global.hetzner?.apiToken)
1046
+ return "~/.config/epd/auth.json (global)";
1047
+ return "none";
1048
+ }
1049
+ async function verifyCloudflareToken(token) {
1050
+ try {
1051
+ const res = await fetch("https://api.cloudflare.com/client/v4/user/tokens/verify", {
1052
+ headers: {
1053
+ Authorization: `Bearer ${token}`,
1054
+ "Content-Type": "application/json"
1055
+ }
1056
+ });
1057
+ const data = await res.json();
1058
+ if (res.ok && data.success && data.result?.status === "active") {
1059
+ return { valid: true, status: data.result.status };
1060
+ }
1061
+ const err = data.errors?.[0]?.message || `HTTP ${res.status}`;
1062
+ return { valid: false, error: err };
1063
+ } catch (err) {
1064
+ return { valid: false, error: err.message };
1065
+ }
1066
+ }
1067
+ async function verifyHetznerToken(token) {
1068
+ try {
1069
+ const res = await fetch("https://api.hetzner.cloud/v1/servers", {
1070
+ headers: {
1071
+ Authorization: `Bearer ${token}`,
1072
+ "Content-Type": "application/json"
1073
+ }
1074
+ });
1075
+ const data = await res.json();
1076
+ if (res.ok && Array.isArray(data.servers)) {
1077
+ return { valid: true };
1078
+ }
1079
+ const err = data.error?.message || `HTTP ${res.status}`;
1080
+ return { valid: false, error: err };
1081
+ } catch (err) {
1082
+ return { valid: false, error: err.message };
1083
+ }
1084
+ }
1085
+ async function linkCloudflareInteractive(root = process.cwd()) {
1086
+ const url = "https://dash.cloudflare.com/profile/api-tokens";
1087
+ console.log(`
1088
+ ${c.bold("Linking Cloudflare to EPD")}`);
1089
+ console.log(`Cloudflare manages DNS records and SSL certificates automatically for your domains.
1090
+ `);
1091
+ await pressEnter("Press Enter to open Cloudflare token creation in your browser...");
1092
+ const opened = openBrowser(url);
1093
+ if (opened) {
1094
+ log.info(`Opened ${c.cyan(url)} in browser.`);
1095
+ } else {
1096
+ log.info(`Open this URL in your browser: ${c.cyan(url)}`);
1097
+ }
1098
+ console.log(c.gray(' 1. In Cloudflare, select "Create Token" \u2192 use the "Edit zone DNS" template.'));
1099
+ console.log(c.gray(` 2. Complete token creation, copy the token, and paste it below.
1100
+ `));
1101
+ for (;; ) {
1102
+ const token = await askSecret("Paste Cloudflare API Token (or press Enter to skip):");
1103
+ if (!token) {
1104
+ log.info("Cloudflare linking skipped.");
1105
+ return null;
1106
+ }
1107
+ log.step("Verifying Cloudflare API token...");
1108
+ const check = await verifyCloudflareToken(token);
1109
+ if (check.valid) {
1110
+ log.ok(`Cloudflare API token verified (${c.green("status: active")})`);
1111
+ const where = await choose("Where would you like to save this Cloudflare token?", [
1112
+ { value: "global", label: "Globally in ~/.config/epd/auth.json (recommended \u2014 all projects)" },
1113
+ { value: "project", label: "This project only (.env)" },
1114
+ { value: "both", label: "Both globally and in this project's .env" }
1115
+ ], "global");
1116
+ if (where === "global" || where === "both") {
1117
+ saveGlobalAuth((curr) => ({
1118
+ ...curr,
1119
+ cloudflare: { apiToken: token, verifiedAt: new Date().toISOString() }
1120
+ }));
1121
+ log.ok(`Saved Cloudflare token globally in ${c.bold("~/.config/epd/auth.json")}`);
1122
+ }
1123
+ if (where === "project" || where === "both") {
1124
+ saveProjectEnv({ CLOUDFLARE_API_TOKEN: token }, root);
1125
+ log.ok(`Saved CLOUDFLARE_API_TOKEN in ${c.bold(".env")}`);
1126
+ }
1127
+ return token;
1128
+ } else {
1129
+ log.warn(`Token verification failed: ${check.error}`);
1130
+ console.log(c.gray(`Make sure the token has "Zone.DNS:Edit" and "Zone:Read" permissions.
1131
+ `));
1132
+ }
1133
+ }
1134
+ }
1135
+ async function linkHetznerInteractive(root = process.cwd()) {
1136
+ const url = "https://console.hetzner.cloud/";
1137
+ console.log(`
1138
+ ${c.bold("Linking Hetzner Cloud to EPD")}`);
1139
+ console.log(`Hetzner Cloud lets EPD list, provision, and deploy directly to your cloud servers.
1140
+ `);
1141
+ await pressEnter("Press Enter to open Hetzner Cloud Console in your browser...");
1142
+ const opened = openBrowser(url);
1143
+ if (opened) {
1144
+ log.info(`Opened ${c.cyan(url)} in browser.`);
1145
+ } else {
1146
+ log.info(`Open this URL in your browser: ${c.cyan(url)}`);
1147
+ }
1148
+ console.log(c.gray(' 1. In Hetzner Cloud, select your project \u2192 "Security" \u2192 "API Tokens".'));
1149
+ console.log(c.gray(' 2. Generate an API token with "Read & Write" permissions.'));
1150
+ console.log(c.gray(` 3. Copy the token and paste it below.
1151
+ `));
1152
+ for (;; ) {
1153
+ const token = await askSecret("Paste Hetzner Cloud API Token (or press Enter to skip):");
1154
+ if (!token) {
1155
+ log.info("Hetzner linking skipped.");
1156
+ return null;
1157
+ }
1158
+ log.step("Verifying Hetzner Cloud API token...");
1159
+ const check = await verifyHetznerToken(token);
1160
+ if (check.valid) {
1161
+ log.ok(`Hetzner Cloud API token verified`);
1162
+ const where = await choose("Where would you like to save this Hetzner token?", [
1163
+ { value: "global", label: "Globally in ~/.config/epd/auth.json (recommended \u2014 all projects)" },
1164
+ { value: "project", label: "This project only (.env)" },
1165
+ { value: "both", label: "Both globally and in this project's .env" }
1166
+ ], "global");
1167
+ if (where === "global" || where === "both") {
1168
+ saveGlobalAuth((curr) => ({
1169
+ ...curr,
1170
+ hetzner: { apiToken: token, verifiedAt: new Date().toISOString() }
1171
+ }));
1172
+ log.ok(`Saved Hetzner token globally in ${c.bold("~/.config/epd/auth.json")}`);
1173
+ }
1174
+ if (where === "project" || where === "both") {
1175
+ saveProjectEnv({ HETZNER_API_TOKEN: token }, root);
1176
+ log.ok(`Saved HETZNER_API_TOKEN in ${c.bold(".env")}`);
1177
+ }
1178
+ return token;
1179
+ } else {
1180
+ log.warn(`Token verification failed: ${check.error}`);
1181
+ console.log(c.gray(`Make sure the token is active with Read & Write permissions.
1182
+ `));
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ // src/hetzner/api.ts
1188
+ class HetznerCloudClient {
1189
+ apiToken;
1190
+ baseUrl;
1191
+ constructor(apiToken, baseUrl = "https://api.hetzner.cloud/v1") {
1192
+ this.apiToken = apiToken;
1193
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1194
+ }
1195
+ async request(path, options = {}) {
1196
+ const url = `${this.baseUrl}${path}`;
1197
+ const headers = {
1198
+ Authorization: `Bearer ${this.apiToken}`,
1199
+ "Content-Type": "application/json",
1200
+ ...options.headers
1201
+ };
1202
+ const res = await fetch(url, { ...options, headers });
1203
+ let data;
1204
+ try {
1205
+ data = await res.json();
1206
+ } catch {
1207
+ data = null;
1208
+ }
1209
+ if (!res.ok) {
1210
+ const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
1211
+ throw new EpdError(`Hetzner Cloud API error: ${msg}`);
1212
+ }
1213
+ return data;
1214
+ }
1215
+ mapServer(s) {
1216
+ return {
1217
+ id: s.id,
1218
+ name: s.name,
1219
+ status: s.status,
1220
+ created: s.created,
1221
+ publicNet: {
1222
+ ipv4: {
1223
+ ip: s.public_net?.ipv4?.ip ?? "",
1224
+ blocked: Boolean(s.public_net?.ipv4?.blocked),
1225
+ dnsPtr: s.public_net?.ipv4?.dns_ptr
1226
+ },
1227
+ ipv6: s.public_net?.ipv6 ? {
1228
+ ip: s.public_net.ipv6.ip ?? "",
1229
+ blocked: Boolean(s.public_net.ipv6.blocked)
1230
+ } : undefined
1231
+ },
1232
+ serverType: {
1233
+ id: s.server_type?.id ?? 0,
1234
+ name: s.server_type?.name ?? "",
1235
+ description: s.server_type?.description ?? "",
1236
+ cores: s.server_type?.cores ?? 0,
1237
+ memory: s.server_type?.memory ?? 0,
1238
+ disk: s.server_type?.disk ?? 0,
1239
+ cpuType: s.server_type?.cpu_type ?? "shared",
1240
+ architecture: s.server_type?.architecture ?? "x86"
1241
+ },
1242
+ datacenter: {
1243
+ id: s.datacenter?.id ?? 0,
1244
+ name: s.datacenter?.name ?? "",
1245
+ description: s.datacenter?.description ?? "",
1246
+ location: {
1247
+ id: s.datacenter?.location?.id ?? 0,
1248
+ name: s.datacenter?.location?.name ?? "",
1249
+ description: s.datacenter?.location?.description ?? "",
1250
+ country: s.datacenter?.location?.country ?? "",
1251
+ city: s.datacenter?.location?.city ?? ""
1252
+ }
1253
+ },
1254
+ image: s.image ? {
1255
+ id: s.image.id,
1256
+ name: s.image.name ?? "",
1257
+ osFlavor: s.image.os_flavor ?? "",
1258
+ description: s.image.description ?? ""
1259
+ } : undefined,
1260
+ labels: s.labels ?? {}
1261
+ };
1262
+ }
1263
+ async listServers(opts = {}) {
1264
+ const params = new URLSearchParams;
1265
+ if (opts.name)
1266
+ params.set("name", opts.name);
1267
+ if (opts.labelSelector)
1268
+ params.set("label_selector", opts.labelSelector);
1269
+ params.set("per_page", "50");
1270
+ const query = params.toString() ? `?${params.toString()}` : "";
1271
+ const res = await this.request(`/servers${query}`);
1272
+ return (res.servers ?? []).map((s) => this.mapServer(s));
1273
+ }
1274
+ async getServer(idOrName) {
1275
+ if (typeof idOrName === "number" || /^\d+$/.test(String(idOrName))) {
1276
+ try {
1277
+ const res = await this.request(`/servers/${idOrName}`);
1278
+ return this.mapServer(res.server);
1279
+ } catch (e) {
1280
+ if (e instanceof EpdError && e.message.includes("404"))
1281
+ return null;
1282
+ throw e;
1283
+ }
1284
+ }
1285
+ const servers = await this.listServers({ name: String(idOrName) });
1286
+ return servers.find((s) => s.name === String(idOrName)) ?? null;
1287
+ }
1288
+ async createServer(opts) {
1289
+ const body = {
1290
+ name: opts.name,
1291
+ server_type: opts.serverType ?? "cx22",
1292
+ image: opts.image ?? "ubuntu-24.04",
1293
+ start_after_create: opts.startAfterCreate ?? true
1294
+ };
1295
+ if (opts.location)
1296
+ body.location = opts.location;
1297
+ if (opts.datacenter)
1298
+ body.datacenter = opts.datacenter;
1299
+ if (opts.sshKeys?.length)
1300
+ body.ssh_keys = opts.sshKeys;
1301
+ if (opts.labels)
1302
+ body.labels = opts.labels;
1303
+ if (opts.userData)
1304
+ body.user_data = opts.userData;
1305
+ const res = await this.request("/servers", {
1306
+ method: "POST",
1307
+ body: JSON.stringify(body)
1308
+ });
1309
+ return {
1310
+ server: this.mapServer(res.server),
1311
+ action: res.action,
1312
+ rootPassword: res.root_password
1313
+ };
1314
+ }
1315
+ async deleteServer(id) {
1316
+ await this.request(`/servers/${id}`, {
1317
+ method: "DELETE"
1318
+ });
1319
+ }
1320
+ async listServerTypes() {
1321
+ const res = await this.request("/server_types");
1322
+ return (res.server_types ?? []).map((st) => ({
1323
+ id: st.id,
1324
+ name: st.name,
1325
+ description: st.description,
1326
+ cores: st.cores,
1327
+ memory: st.memory,
1328
+ disk: st.disk,
1329
+ cpuType: st.cpu_type,
1330
+ architecture: st.architecture,
1331
+ prices: (st.prices ?? []).map((p) => ({
1332
+ location: p.location,
1333
+ priceHourly: { net: p.price_hourly?.net ?? "", gross: p.price_hourly?.gross ?? "" },
1334
+ priceMonthly: { net: p.price_monthly?.net ?? "", gross: p.price_monthly?.gross ?? "" }
1335
+ }))
1336
+ }));
1337
+ }
1338
+ async listLocations() {
1339
+ const res = await this.request("/locations");
1340
+ return (res.locations ?? []).map((l) => ({
1341
+ id: l.id,
1342
+ name: l.name,
1343
+ description: l.description,
1344
+ country: l.country,
1345
+ city: l.city,
1346
+ networkZone: l.network_zone
1347
+ }));
1348
+ }
1349
+ async listSshKeys() {
1350
+ const res = await this.request("/ssh_keys");
1351
+ return (res.ssh_keys ?? []).map((k) => ({
1352
+ id: k.id,
1353
+ name: k.name,
1354
+ fingerprint: k.fingerprint,
1355
+ publicKey: k.public_key
1356
+ }));
1357
+ }
1358
+ async getAction(id) {
1359
+ const res = await this.request(`/actions/${id}`);
1360
+ return res.action;
1361
+ }
1362
+ async waitForAction(actionId, timeoutMs = 120000) {
1363
+ const deadline = Date.now() + timeoutMs;
1364
+ while (Date.now() < deadline) {
1365
+ const action = await this.getAction(actionId);
1366
+ if (action.status === "success")
1367
+ return;
1368
+ if (action.status === "error") {
1369
+ throw new EpdError(`Hetzner action failed: ${action.error?.message || "Unknown error"}`);
1370
+ }
1371
+ await sleep(1500);
1372
+ }
1373
+ throw new EpdError(`Hetzner action ${actionId} timed out after ${Math.round(timeoutMs / 1000)}s`);
1374
+ }
1375
+ async waitForServerRunning(serverId, timeoutMs = 120000) {
1376
+ const deadline = Date.now() + timeoutMs;
1377
+ while (Date.now() < deadline) {
1378
+ const server = await this.getServer(serverId);
1379
+ if (server && server.status === "running" && server.publicNet.ipv4.ip) {
1380
+ return server;
1381
+ }
1382
+ await sleep(2000);
1383
+ }
1384
+ throw new EpdError(`Timed out waiting for Hetzner server ${serverId} to become running`);
1385
+ }
1386
+ }
1387
+
1388
+ // src/dns/cloudflare.ts
1389
+ class CloudflareClient {
1390
+ name = "cloudflare";
1391
+ apiToken;
1392
+ baseUrl;
1393
+ constructor(apiToken, baseUrl = "https://api.cloudflare.com/client/v4") {
1394
+ this.apiToken = apiToken;
1395
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1396
+ }
1397
+ async request(path, options = {}) {
1398
+ const url = `${this.baseUrl}${path}`;
1399
+ const headers = {
1400
+ Authorization: `Bearer ${this.apiToken}`,
1401
+ "Content-Type": "application/json",
1402
+ ...options.headers
1403
+ };
1404
+ const res = await fetch(url, { ...options, headers });
1405
+ const data = await res.json();
1406
+ if (!res.ok || data.success === false) {
1407
+ const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
1408
+ throw new EpdError(`Cloudflare API error: ${msg}`);
1409
+ }
1410
+ return data.result;
1411
+ }
1412
+ async listZones(name) {
1413
+ const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
1414
+ return this.request(`/zones${query}`);
1415
+ }
1416
+ async findZoneForDomain(domain, explicitZoneId) {
1417
+ if (explicitZoneId) {
1418
+ return { id: explicitZoneId, name: domain };
1419
+ }
1420
+ const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
1421
+ const parts = cleanDomain.split(".");
1422
+ for (let i = 0;i < parts.length - 1; i++) {
1423
+ const candidate = parts.slice(i).join(".");
1424
+ const zones = await this.listZones(candidate);
1425
+ const match = zones.find((z) => z.name.toLowerCase() === candidate);
1426
+ if (match)
1427
+ return { id: match.id, name: match.name };
1428
+ }
1429
+ 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.`);
1430
+ }
1431
+ async listDnsRecords(zoneId, name, type) {
1432
+ const params = new URLSearchParams;
1433
+ params.set("per_page", "100");
1434
+ if (name)
1435
+ params.set("name", name);
1436
+ if (type)
1437
+ params.set("type", type);
1438
+ const raw = await this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
1439
+ return raw.map((r) => ({
1440
+ id: String(r.id),
1441
+ zoneId: String(r.zone_id ?? zoneId),
1442
+ name: r.name,
1443
+ type: r.type,
1444
+ content: r.content,
1445
+ proxied: Boolean(r.proxied),
1446
+ ttl: Number(r.ttl ?? 1)
1447
+ }));
1448
+ }
1449
+ async createDnsRecord(zoneId, record) {
1450
+ const res = await this.request(`/zones/${zoneId}/dns_records`, {
1451
+ method: "POST",
1452
+ body: JSON.stringify({
1453
+ name: record.name,
1454
+ type: record.type,
1455
+ content: record.content,
1456
+ proxied: Boolean(record.proxied),
1457
+ ttl: record.ttl,
1458
+ comment: record.comment
1459
+ })
1460
+ });
1461
+ return {
1462
+ id: String(res.id),
1463
+ zoneId: String(res.zone_id ?? zoneId),
1464
+ name: res.name,
1465
+ type: res.type,
1466
+ content: res.content,
1467
+ proxied: Boolean(res.proxied),
1468
+ ttl: Number(res.ttl ?? 1)
1469
+ };
1470
+ }
1471
+ async updateDnsRecord(zoneId, recordId, record) {
1472
+ const res = await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
1473
+ method: "PUT",
1474
+ body: JSON.stringify({
1475
+ name: record.name,
1476
+ type: record.type,
1477
+ content: record.content,
1478
+ proxied: Boolean(record.proxied),
1479
+ ttl: record.ttl,
1480
+ comment: record.comment
1481
+ })
1482
+ });
1483
+ return {
1484
+ id: String(res.id),
1485
+ zoneId: String(res.zone_id ?? zoneId),
1486
+ name: res.name,
1487
+ type: res.type,
1488
+ content: res.content,
1489
+ proxied: Boolean(res.proxied),
1490
+ ttl: Number(res.ttl ?? 1)
1491
+ };
1492
+ }
1493
+ async deleteDnsRecord(zoneId, recordId) {
1494
+ await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
1495
+ method: "DELETE"
1496
+ });
1497
+ }
1498
+ }
1499
+
890
1500
  // src/commands/init.ts
891
1501
  function detect(root) {
892
1502
  const name = basename(root).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
893
- const hasDockerfile = existsSync2(join2(root, "Dockerfile"));
894
- const pkgPath = join2(root, "package.json");
895
- if (existsSync2(pkgPath)) {
1503
+ const hasDockerfile = existsSync3(join3(root, "Dockerfile"));
1504
+ const pkgPath = join3(root, "package.json");
1505
+ if (existsSync3(pkgPath)) {
896
1506
  let pkg = {};
897
1507
  try {
898
- pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
1508
+ pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
899
1509
  } catch {}
900
- const bun = existsSync2(join2(root, "bun.lockb")) || existsSync2(join2(root, "bun.lock"));
1510
+ const bun = existsSync3(join3(root, "bun.lockb")) || existsSync3(join3(root, "bun.lock"));
901
1511
  const scripts = pkg.scripts ?? {};
902
1512
  const runner = bun ? "bun" : "npm";
903
1513
  return {
@@ -910,13 +1520,13 @@ function detect(root) {
910
1520
  hasDockerfile
911
1521
  };
912
1522
  }
913
- if (existsSync2(join2(root, "pyproject.toml")) || existsSync2(join2(root, "requirements.txt"))) {
1523
+ if (existsSync3(join3(root, "pyproject.toml")) || existsSync3(join3(root, "requirements.txt"))) {
914
1524
  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 };
915
1525
  }
916
- if (existsSync2(join2(root, "Gemfile"))) {
1526
+ if (existsSync3(join3(root, "Gemfile"))) {
917
1527
  return { name, runtime: "ruby", port: 3000, install: "bundle install --deployment", start: "bundle exec rails server -p $PORT", hasDockerfile };
918
1528
  }
919
- if (existsSync2(join2(root, "go.mod"))) {
1529
+ if (existsSync3(join3(root, "go.mod"))) {
920
1530
  return { name, runtime: "go", port: 8080, build: "go build -o server .", start: "./server", hasDockerfile };
921
1531
  }
922
1532
  return { name, runtime: "unknown", port: 3000, hasDockerfile };
@@ -949,7 +1559,19 @@ process:
949
1559
  # Files that never need to reach the server.
950
1560
  exclude: [".git", "node_modules", ".env", "dist", "*.log"]
951
1561
  ` : "";
952
- return `# ${o.name} \u2014 deployed with epd (https://github.com/you/epd)
1562
+ const dnsBlock = o.useCloudflare ? `
1563
+ # Automated DNS record management via Cloudflare
1564
+ dns:
1565
+ provider: cloudflare
1566
+ proxied: true
1567
+ auto_sync: true
1568
+ ` : "";
1569
+ const hetznerBlock = o.useHetzner ? `
1570
+ # Hetzner Cloud integration (api_token resolved from ~/.config/epd/auth.json or HETZNER_API_TOKEN)
1571
+ hetzner:
1572
+ # api_token: \${HETZNER_API_TOKEN}
1573
+ ` : "";
1574
+ return `# ${o.name} \u2014 deployed with epd (https://epd.peppi.dev)
953
1575
  #
954
1576
  # epd setup prepare the servers and deploy for the first time
955
1577
  # epd deploy build and deploy the current commit
@@ -964,7 +1586,7 @@ mode: ${o.mode}
964
1586
  ${o.mode === "docker" ? `
965
1587
  # Image name. Tagged with the git sha of every deploy.
966
1588
  image: ${o.image ?? o.name}
967
- ${registry}` : ""}${processBlock}
1589
+ ${registry}` : ""}${processBlock}${dnsBlock}${hetznerBlock}
968
1590
  # One entry per group of processes. Add more (worker, cron, \u2026) as you need them.
969
1591
  servers:
970
1592
  web:
@@ -1087,7 +1709,12 @@ var init = {
1087
1709
  email: { type: "string" },
1088
1710
  replicas: { type: "string" },
1089
1711
  force: { type: "boolean" },
1090
- dockerfile: { type: "boolean" }
1712
+ dockerfile: { type: "boolean" },
1713
+ ci: { type: "boolean" },
1714
+ cloudflare: { type: "boolean" },
1715
+ "no-cloudflare": { type: "boolean" },
1716
+ hetzner: { type: "boolean" },
1717
+ "no-hetzner": { type: "boolean" }
1091
1718
  },
1092
1719
  help: () => `${c.bold("epd init")} \u2014 create an epd.yml for this project
1093
1720
 
@@ -1100,15 +1727,46 @@ Options
1100
1727
  --email <email> Contact address for Let's Encrypt
1101
1728
  --replicas <n> Replicas per host (default 1)
1102
1729
  --dockerfile Also write a starter Dockerfile
1730
+ --ci Also generate a GitHub Actions deploy workflow (.github/workflows/deploy.yml)
1731
+ --cloudflare Enable Cloudflare DNS integration
1732
+ --no-cloudflare Skip Cloudflare prompt
1733
+ --hetzner Enable Hetzner Cloud integration
1734
+ --no-hetzner Skip Hetzner prompt
1103
1735
  --force Overwrite an existing epd.yml`,
1104
1736
  async run(ctx) {
1105
1737
  const root = process.cwd();
1106
- const target = join2(root, "epd.yml");
1107
- if (existsSync2(target) && !ctx.values.force) {
1738
+ const target = join3(root, "epd.yml");
1739
+ if (existsSync3(target) && !ctx.values.force) {
1108
1740
  throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
1109
1741
  }
1110
1742
  const detected = detect(root);
1111
1743
  log.info(`Detected ${c.bold(detected.runtime)} project${detected.hasDockerfile ? " with a Dockerfile" : ""}`);
1744
+ let useCloudflare = Boolean(ctx.values.cloudflare);
1745
+ let cloudflareToken;
1746
+ if (interactive() && ctx.values.cloudflare === undefined && !ctx.values["no-cloudflare"]) {
1747
+ useCloudflare = await confirm("Do you use Cloudflare (for automated DNS and SSL)?", false);
1748
+ }
1749
+ if (useCloudflare) {
1750
+ cloudflareToken = getCloudflareToken(root);
1751
+ if (cloudflareToken) {
1752
+ log.info(`Using existing Cloudflare credentials (${getCloudflareTokenSource(root)})`);
1753
+ } else if (interactive()) {
1754
+ cloudflareToken = await linkCloudflareInteractive(root) ?? undefined;
1755
+ }
1756
+ }
1757
+ let useHetzner = Boolean(ctx.values.hetzner);
1758
+ let hetznerToken;
1759
+ if (interactive() && ctx.values.hetzner === undefined && !ctx.values["no-hetzner"]) {
1760
+ useHetzner = await confirm("Do you use Hetzner (for cloud servers or DNS)?", false);
1761
+ }
1762
+ if (useHetzner) {
1763
+ hetznerToken = getHetznerToken(root);
1764
+ if (hetznerToken) {
1765
+ log.info(`Using existing Hetzner credentials (${getHetznerTokenSource(root)})`);
1766
+ } else if (interactive()) {
1767
+ hetznerToken = await linkHetznerInteractive(root) ?? undefined;
1768
+ }
1769
+ }
1112
1770
  const name = ctx.values.name ?? await ask("App name", detected.name);
1113
1771
  const mode = ctx.values.mode ?? await choose("How should it run on the server?", [
1114
1772
  { value: "docker", label: "Docker \u2014 build an image, run containers" },
@@ -1116,8 +1774,63 @@ Options
1116
1774
  ], detected.hasDockerfile || detected.runtime === "unknown" ? "docker" : "docker");
1117
1775
  if (mode !== "docker" && mode !== "process")
1118
1776
  throw new EpdError(`--mode must be "docker" or "process"`);
1119
- const 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);
1120
- const domains = (ctx.values.domain ?? []).length ? ctx.values.domain : (await ask("Domains to serve (comma separated)", `${name}.example.com`)).split(",").map((s) => s.trim()).filter(Boolean);
1777
+ let hosts = ctx.values.host ?? [];
1778
+ if (!hosts.length && hetznerToken && interactive()) {
1779
+ try {
1780
+ log.step("Fetching your Hetzner Cloud servers...");
1781
+ const client = new HetznerCloudClient(hetznerToken);
1782
+ const servers = await client.listServers();
1783
+ if (servers.length > 0) {
1784
+ const choices = servers.map((s) => ({
1785
+ value: s.name,
1786
+ label: `${s.name} (${s.publicNet.ipv4.ip || "IPv6 only"}) [${s.serverType.name}, ${s.datacenter.location.name}]`
1787
+ }));
1788
+ choices.push({ value: "__new__", label: "Create a new Hetzner server now" });
1789
+ choices.push({ value: "__manual__", label: "Enter server IP or hostname manually" });
1790
+ const picked = await choose("Select target Hetzner server:", choices, choices[0].value);
1791
+ if (picked === "__new__") {
1792
+ const sName = await ask("New server name", `${name}-prod`);
1793
+ const sType = await ask("Server type (cx22 = 2 vCPU, 4GB RAM)", "cx22");
1794
+ const sLoc = await ask("Datacenter location (fsn1, nbg1, hel1, ash, hil)", "fsn1");
1795
+ log.step(`Creating Hetzner server ${sName} (${sType} in ${sLoc})...`);
1796
+ const created = await client.createServer({ name: sName, serverType: sType, location: sLoc });
1797
+ log.ok(`Created server ${sName} (${created.server.publicNet.ipv4.ip || "pending IP"})`);
1798
+ hosts = [`hetzner:${sName}`];
1799
+ } else if (picked === "__manual__") {
1800
+ hosts = (await ask("Server IPs or hostnames (comma separated)", "203.0.113.10")).split(",").map((s) => s.trim()).filter(Boolean);
1801
+ } else {
1802
+ hosts = [`hetzner:${picked}`];
1803
+ }
1804
+ } else {
1805
+ const createNow = await confirm("No Hetzner servers found. Create one now?", true);
1806
+ if (createNow) {
1807
+ const sName = await ask("New server name", `${name}-prod`);
1808
+ const sType = await ask("Server type (cx22 = 2 vCPU, 4GB RAM)", "cx22");
1809
+ const sLoc = await ask("Datacenter location (fsn1, nbg1, hel1, ash, hil)", "fsn1");
1810
+ log.step(`Creating Hetzner server ${sName} (${sType} in ${sLoc})...`);
1811
+ const created = await client.createServer({ name: sName, serverType: sType, location: sLoc });
1812
+ log.ok(`Created server ${sName} (${created.server.publicNet.ipv4.ip || "pending IP"})`);
1813
+ hosts = [`hetzner:${sName}`];
1814
+ }
1815
+ }
1816
+ } catch (err) {
1817
+ log.warn(`Could not query Hetzner servers: ${err.message}`);
1818
+ }
1819
+ }
1820
+ if (!hosts.length) {
1821
+ 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);
1822
+ }
1823
+ let defaultDomain = `${name}.example.com`;
1824
+ if (cloudflareToken && !(ctx.values.domain ?? []).length) {
1825
+ try {
1826
+ const cfClient = new CloudflareClient(cloudflareToken);
1827
+ const zones = await cfClient.listZones();
1828
+ if (zones.length > 0) {
1829
+ defaultDomain = `${name}.${zones[0].name}`;
1830
+ }
1831
+ } catch {}
1832
+ }
1833
+ const domains = (ctx.values.domain ?? []).length ? ctx.values.domain : (await ask("Domains to serve (comma separated)", defaultDomain)).split(",").map((s) => s.trim()).filter(Boolean);
1121
1834
  const port = Number(ctx.values.port ?? await ask("Port your app listens on", String(detected.port)));
1122
1835
  const email = ctx.values.email ?? await ask("Email for Let's Encrypt", "");
1123
1836
  const replicas = Number(ctx.values.replicas ?? 1);
@@ -1129,24 +1842,74 @@ Options
1129
1842
  registryUser = await ask("Registry username", process.env.USER ?? "");
1130
1843
  image = `${registryServer ? `${registryServer}/` : ""}${registryUser}/${name}`;
1131
1844
  }
1132
- writeFileSync(target, template({ name, mode, hosts, domains, port, email, image, registryServer, registryUser, detected, replicas }));
1845
+ writeFileSync2(target, template({
1846
+ name,
1847
+ mode,
1848
+ hosts,
1849
+ domains,
1850
+ port,
1851
+ email,
1852
+ image,
1853
+ registryServer,
1854
+ registryUser,
1855
+ detected,
1856
+ replicas,
1857
+ useCloudflare: Boolean(cloudflareToken || useCloudflare),
1858
+ useHetzner: Boolean(hetznerToken || useHetzner)
1859
+ }));
1133
1860
  log.ok(`wrote ${c.bold("epd.yml")}`);
1134
1861
  const wantDockerfile = mode === "docker" && !detected.hasDockerfile && (Boolean(ctx.values.dockerfile) || await confirm("No Dockerfile here. Write a starter one?", true));
1135
1862
  if (wantDockerfile) {
1136
1863
  const df = DOCKERFILES[detected.runtime];
1137
1864
  if (df) {
1138
- writeFileSync(join2(root, "Dockerfile"), df);
1865
+ writeFileSync2(join3(root, "Dockerfile"), df);
1139
1866
  log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
1140
1867
  } else {
1141
1868
  log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
1142
1869
  }
1143
1870
  }
1871
+ const wantCi = Boolean(ctx.values.ci) || interactive() && await confirm("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
1872
+ if (wantCi) {
1873
+ const workflowDir = join3(root, ".github", "workflows");
1874
+ mkdirSync2(workflowDir, { recursive: true });
1875
+ const ciYaml = `name: Deploy
1876
+
1877
+ on:
1878
+ push:
1879
+ branches: [main]
1880
+
1881
+ concurrency:
1882
+ group: deploy-\${{ github.ref }}
1883
+ cancel-in-progress: false
1884
+
1885
+ jobs:
1886
+ deploy:
1887
+ runs-on: ubuntu-latest
1888
+ steps:
1889
+ - name: Checkout repository
1890
+ uses: actions/checkout@v4
1891
+
1892
+ - name: Setup Bun
1893
+ uses: oven-sh/setup-bun@v2
1894
+ with:
1895
+ bun-version: latest
1896
+
1897
+ - name: Install EPD
1898
+ run: bun install -g @fabioplunser/epd
1899
+
1900
+ - name: Deploy with EPD
1901
+ env:
1902
+ SSH_PRIVATE_KEY: \${{ secrets.SSH_PRIVATE_KEY }}
1903
+ ${cloudflareToken || useCloudflare ? "CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n " : ""}${hetznerToken || useHetzner ? "HETZNER_API_TOKEN: ${{ secrets.HETZNER_API_TOKEN }}\n " : ""}run: epd deploy
1904
+ `;
1905
+ writeFileSync2(join3(workflowDir, "deploy.yml"), ciYaml);
1906
+ log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
1907
+ }
1144
1908
  console.log(`
1145
- ${c.bold("Next")}
1146
- 1. Edit ${c.cyan("epd.yml")} \u2014 servers, domains, env.
1147
- 2. Point your domains' A records at ${hosts.join(", ")}.
1148
- 3. ${c.cyan("epd setup")} installs what the servers need and deploys.
1149
- 4. ${c.cyan("epd deploy")} every time after that.
1909
+ Next steps:`);
1910
+ console.log(` ${c.cyan("epd setup")} prepare the server(s) and start Traefik`);
1911
+ console.log(` ${c.cyan("epd deploy")} build and deploy your application`);
1912
+ console.log(` ${c.cyan("epd status")} check running containers and health
1150
1913
  `);
1151
1914
  }
1152
1915
  };
@@ -1423,11 +2186,11 @@ true`, { allowFailure: true, stream: true, label: `${host.name}: install package
1423
2186
  }
1424
2187
 
1425
2188
  // src/core/ssh.ts
1426
- import { mkdirSync } from "fs";
2189
+ import { mkdirSync as mkdirSync3 } from "fs";
1427
2190
  import { tmpdir } from "os";
1428
- import { join as join3 } from "path";
1429
- var controlDir = join3(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
1430
- mkdirSync(controlDir, { recursive: true, mode: 448 });
2191
+ import { join as join4 } from "path";
2192
+ var controlDir = join4(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2193
+ mkdirSync3(controlDir, { recursive: true, mode: 448 });
1431
2194
 
1432
2195
  class Host {
1433
2196
  name;
@@ -1439,7 +2202,7 @@ class Host {
1439
2202
  this.sudo = cfg.user !== "root";
1440
2203
  }
1441
2204
  sshOptions() {
1442
- const socket = join3(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
2205
+ const socket = join4(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
1443
2206
  const args = [
1444
2207
  "-o",
1445
2208
  "BatchMode=yes",
@@ -2214,12 +2977,12 @@ function recordDeploy(state, version, by, keep) {
2214
2977
  }
2215
2978
 
2216
2979
  // src/deploy/image.ts
2217
- import { existsSync as existsSync3 } from "fs";
2218
- import { join as join4 } from "path";
2980
+ import { existsSync as existsSync4 } from "fs";
2981
+ import { join as join5 } from "path";
2219
2982
  async function resolveVersion(cfg, explicit) {
2220
2983
  if (explicit)
2221
2984
  return { id: explicit, source: "explicit", dirty: false };
2222
- if (existsSync3(join4(cfg.root, ".git")) && await which("git")) {
2985
+ if (existsSync4(join5(cfg.root, ".git")) && await which("git")) {
2223
2986
  const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
2224
2987
  if (sha.code === 0 && sha.stdout) {
2225
2988
  const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
@@ -2234,8 +2997,8 @@ async function hasBuildx() {
2234
2997
  return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
2235
2998
  }
2236
2999
  async function buildImage(cfg, version, env) {
2237
- const dockerfile = join4(cfg.root, cfg.build.dockerfile);
2238
- if (!existsSync3(dockerfile)) {
3000
+ const dockerfile = join5(cfg.root, cfg.build.dockerfile);
3001
+ if (!existsSync4(dockerfile)) {
2239
3002
  throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
2240
3003
  }
2241
3004
  const ref = imageRef(cfg, version);
@@ -2248,7 +3011,7 @@ async function buildImage(cfg, version, env) {
2248
3011
  async function buildWithBuildx(cfg, ref, version, env) {
2249
3012
  const args = ["docker", "buildx", "build"];
2250
3013
  args.push("--platform", cfg.build.platform);
2251
- args.push("--file", join4(cfg.root, cfg.build.dockerfile));
3014
+ args.push("--file", join5(cfg.root, cfg.build.dockerfile));
2252
3015
  args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
2253
3016
  if (cfg.build.target)
2254
3017
  args.push("--target", cfg.build.target);
@@ -2281,7 +3044,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
2281
3044
  if (cfg.build.platform !== localPlatform) {
2282
3045
  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}.`);
2283
3046
  }
2284
- const args = ["docker", "build", "--file", join4(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
3047
+ const args = ["docker", "build", "--file", join5(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
2285
3048
  if (cfg.build.target)
2286
3049
  args.push("--target", cfg.build.target);
2287
3050
  for (const [k, v] of Object.entries(cfg.build.args))
@@ -2514,8 +3277,8 @@ ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: access
2514
3277
  }
2515
3278
 
2516
3279
  // src/deploy/process.ts
2517
- import { existsSync as existsSync4 } from "fs";
2518
- import { join as join5 } from "path";
3280
+ import { existsSync as existsSync5 } from "fs";
3281
+ import { join as join6 } from "path";
2519
3282
  var asUser = { sudo: false };
2520
3283
  var pm2 = (cfg, args) => `${pathPrelude(cfg)} pm2 ${args}`;
2521
3284
  function releaseDir(cfg, version) {
@@ -2526,7 +3289,7 @@ async function uploadSource(host, cfg, version) {
2526
3289
  const p = paths(cfg);
2527
3290
  await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
2528
3291
  if (cfg.process.source === "git") {
2529
- if (!existsSync4(join5(cfg.root, ".git")))
3292
+ if (!existsSync5(join6(cfg.root, ".git")))
2530
3293
  throw new EpdError('process.source is "git" but this is not a git repository');
2531
3294
  log.host(host.name, `uploading HEAD as ${version}`);
2532
3295
  await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
@@ -2617,153 +3380,41 @@ ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`;
2617
3380
  disown 2>/dev/null || true` : teardown, { ...asUser, allowFailure: true, label: `${host.name}: pm2 stop ${svc.name}/${slot}` });
2618
3381
  }
2619
3382
  async function removeApp2(host, cfg) {
2620
- 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
2621
- ${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
2622
- done
2623
- ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
2624
- }
2625
- async function listProcesses(host, cfg) {
2626
- const out = await host.capture(`${pm2(cfg, "jlist")} 2>/dev/null || echo '[]'`, { ...asUser, allowFailure: true });
2627
- const jsonStart = out.indexOf("[");
2628
- let parsed = [];
2629
- try {
2630
- parsed = JSON.parse(jsonStart >= 0 ? out.slice(jsonStart) : "[]");
2631
- } catch {
2632
- return [];
2633
- }
2634
- return parsed.filter((p) => typeof p?.name === "string" && p.name.startsWith(`epd-${cfg.name}-`)).map((p) => ({
2635
- name: p.name,
2636
- status: p.pm2_env?.status ?? "unknown",
2637
- restarts: p.pm2_env?.restart_time ?? 0,
2638
- uptime: p.pm2_env?.pm_uptime ?? 0,
2639
- cpu: p.monit?.cpu ?? 0,
2640
- memory: p.monit?.memory ?? 0
2641
- }));
2642
- }
2643
- async function finalizeRelease(host, cfg, version) {
2644
- const p = paths(cfg);
2645
- await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
2646
- ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1 )) | while read -r d; do
2647
- case "$d" in *${shq(version)}*) continue;; esac
2648
- rm -rf "$d"
2649
- done`, { ...asUser, allowFailure: true });
2650
- }
2651
-
2652
- // src/dns/index.ts
2653
- import dns from "dns/promises";
2654
-
2655
- // src/dns/cloudflare.ts
2656
- class CloudflareClient {
2657
- name = "cloudflare";
2658
- apiToken;
2659
- baseUrl;
2660
- constructor(apiToken, baseUrl = "https://api.cloudflare.com/client/v4") {
2661
- this.apiToken = apiToken;
2662
- this.baseUrl = baseUrl.replace(/\/$/, "");
2663
- }
2664
- async request(path, options = {}) {
2665
- const url = `${this.baseUrl}${path}`;
2666
- const headers = {
2667
- Authorization: `Bearer ${this.apiToken}`,
2668
- "Content-Type": "application/json",
2669
- ...options.headers
2670
- };
2671
- const res = await fetch(url, { ...options, headers });
2672
- const data = await res.json();
2673
- if (!res.ok || data.success === false) {
2674
- const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
2675
- throw new EpdError(`Cloudflare API error: ${msg}`);
2676
- }
2677
- return data.result;
2678
- }
2679
- async listZones(name) {
2680
- const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
2681
- return this.request(`/zones${query}`);
2682
- }
2683
- async findZoneForDomain(domain, explicitZoneId) {
2684
- if (explicitZoneId) {
2685
- return { id: explicitZoneId, name: domain };
2686
- }
2687
- const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
2688
- const parts = cleanDomain.split(".");
2689
- for (let i = 0;i < parts.length - 1; i++) {
2690
- const candidate = parts.slice(i).join(".");
2691
- const zones = await this.listZones(candidate);
2692
- const match = zones.find((z) => z.name.toLowerCase() === candidate);
2693
- if (match)
2694
- return { id: match.id, name: match.name };
2695
- }
2696
- 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.`);
2697
- }
2698
- async listDnsRecords(zoneId, name, type) {
2699
- const params = new URLSearchParams;
2700
- params.set("per_page", "100");
2701
- if (name)
2702
- params.set("name", name);
2703
- if (type)
2704
- params.set("type", type);
2705
- const raw = await this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
2706
- return raw.map((r) => ({
2707
- id: String(r.id),
2708
- zoneId: String(r.zone_id ?? zoneId),
2709
- name: r.name,
2710
- type: r.type,
2711
- content: r.content,
2712
- proxied: Boolean(r.proxied),
2713
- ttl: Number(r.ttl ?? 1)
2714
- }));
2715
- }
2716
- async createDnsRecord(zoneId, record) {
2717
- const res = await this.request(`/zones/${zoneId}/dns_records`, {
2718
- method: "POST",
2719
- body: JSON.stringify({
2720
- name: record.name,
2721
- type: record.type,
2722
- content: record.content,
2723
- proxied: Boolean(record.proxied),
2724
- ttl: record.ttl,
2725
- comment: record.comment
2726
- })
2727
- });
2728
- return {
2729
- id: String(res.id),
2730
- zoneId: String(res.zone_id ?? zoneId),
2731
- name: res.name,
2732
- type: res.type,
2733
- content: res.content,
2734
- proxied: Boolean(res.proxied),
2735
- ttl: Number(res.ttl ?? 1)
2736
- };
2737
- }
2738
- async updateDnsRecord(zoneId, recordId, record) {
2739
- const res = await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
2740
- method: "PUT",
2741
- body: JSON.stringify({
2742
- name: record.name,
2743
- type: record.type,
2744
- content: record.content,
2745
- proxied: Boolean(record.proxied),
2746
- ttl: record.ttl,
2747
- comment: record.comment
2748
- })
2749
- });
2750
- return {
2751
- id: String(res.id),
2752
- zoneId: String(res.zone_id ?? zoneId),
2753
- name: res.name,
2754
- type: res.type,
2755
- content: res.content,
2756
- proxied: Boolean(res.proxied),
2757
- ttl: Number(res.ttl ?? 1)
2758
- };
2759
- }
2760
- async deleteDnsRecord(zoneId, recordId) {
2761
- await this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
2762
- method: "DELETE"
2763
- });
3383
+ 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
3384
+ ${pathPrelude(cfg)} pm2 delete "$n" >/dev/null 2>&1 || true
3385
+ done
3386
+ ${pm2(cfg, "save --force")} >/dev/null 2>&1 || true`, { ...asUser, allowFailure: true });
3387
+ }
3388
+ async function listProcesses(host, cfg) {
3389
+ const out = await host.capture(`${pm2(cfg, "jlist")} 2>/dev/null || echo '[]'`, { ...asUser, allowFailure: true });
3390
+ const jsonStart = out.indexOf("[");
3391
+ let parsed = [];
3392
+ try {
3393
+ parsed = JSON.parse(jsonStart >= 0 ? out.slice(jsonStart) : "[]");
3394
+ } catch {
3395
+ return [];
2764
3396
  }
3397
+ return parsed.filter((p) => typeof p?.name === "string" && p.name.startsWith(`epd-${cfg.name}-`)).map((p) => ({
3398
+ name: p.name,
3399
+ status: p.pm2_env?.status ?? "unknown",
3400
+ restarts: p.pm2_env?.restart_time ?? 0,
3401
+ uptime: p.pm2_env?.pm_uptime ?? 0,
3402
+ cpu: p.monit?.cpu ?? 0,
3403
+ memory: p.monit?.memory ?? 0
3404
+ }));
3405
+ }
3406
+ async function finalizeRelease(host, cfg, version) {
3407
+ const p = paths(cfg);
3408
+ await host.exec(`ln -sfn ${shq(releaseDir(cfg, version))} ${shq(p.current)}.tmp && mv -Tf ${shq(p.current)}.tmp ${shq(p.current)}
3409
+ ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1 )) | while read -r d; do
3410
+ case "$d" in *${shq(version)}*) continue;; esac
3411
+ rm -rf "$d"
3412
+ done`, { ...asUser, allowFailure: true });
2765
3413
  }
2766
3414
 
3415
+ // src/dns/index.ts
3416
+ import dns from "dns/promises";
3417
+
2767
3418
  // src/dns/hetzner.ts
2768
3419
  class HetznerDnsClient {
2769
3420
  name = "hetzner";
@@ -3014,304 +3665,103 @@ async function syncDns(cfg, opts = {}) {
3014
3665
  if (!token) {
3015
3666
  throw new EpdError("Cloudflare API token is missing", "Set CLOUDFLARE_API_TOKEN in your environment or specify api_token in epd.yml under cloudflare.");
3016
3667
  }
3017
- provider = new CloudflareClient(token);
3018
- } else if (process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN) {
3019
- const token = process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN;
3020
- provider = new HetznerDnsClient(token);
3021
- } else {
3022
- throw new EpdError("No DNS provider configured", "Configure `dns:` or `cloudflare:` in epd.yml, or set CLOUDFLARE_API_TOKEN / HETZNER_DNS_API_TOKEN in environment.");
3023
- }
3024
- const domains = getRouteDomains(cfg);
3025
- if (!domains.length) {
3026
- if (opts.log)
3027
- log.step(`${provider.name} DNS: no domain names found in routes to sync`);
3028
- return [];
3029
- }
3030
- const routedHosts = new Set;
3031
- for (const svc of cfg.services) {
3032
- if (svc.routes.length) {
3033
- for (const h of svc.hosts)
3034
- routedHosts.add(h);
3035
- }
3036
- }
3037
- const ips = new Set;
3038
- for (const h of routedHosts) {
3039
- const resolved = await resolveHostIps(h);
3040
- for (const ip of resolved) {
3041
- if (isIPv4(ip) || isIPv6(ip))
3042
- ips.add(ip);
3043
- }
3044
- }
3045
- if (!ips.size) {
3046
- if (opts.log)
3047
- log.step(`${provider.name} DNS: no server IP addresses resolved to sync`);
3048
- return [];
3049
- }
3050
- const isProxied = opts.proxied ?? cfg.dns?.proxied ?? cfg.cloudflare?.proxied ?? true;
3051
- const ttl = cfg.dns?.ttl ?? cfg.cloudflare?.ttl ?? (provider.name === "hetzner" ? 300 : 1);
3052
- const explicitZoneId = cfg.dns?.zoneId ?? cfg.cloudflare?.zoneId;
3053
- const results = [];
3054
- if (opts.log) {
3055
- log.step(`${provider.name} DNS: syncing ${c.bold(domains.length.toString())} domain(s) across ${c.bold(ips.size.toString())} server IP(s)`);
3056
- }
3057
- const zoneCache = new Map;
3058
- for (const domain of domains) {
3059
- let zone = zoneCache.get(domain);
3060
- if (!zone) {
3061
- zone = await provider.findZoneForDomain(domain, explicitZoneId);
3062
- zoneCache.set(domain, zone);
3063
- }
3064
- const existingRecords = await provider.listDnsRecords(zone.id, domain);
3065
- for (const ip of ips) {
3066
- const type = isIPv6(ip) ? "AAAA" : "A";
3067
- const existing = existingRecords.find((r) => r.name.toLowerCase() === domain.toLowerCase() && r.type === type && r.content === ip);
3068
- if (existing) {
3069
- const needsProxyUpdate = provider.name === "cloudflare" && existing.proxied !== isProxied;
3070
- const needsTtlUpdate = ttl !== 1 && existing.ttl !== ttl;
3071
- if (needsProxyUpdate || needsTtlUpdate) {
3072
- if (!opts.dryRun) {
3073
- await provider.updateDnsRecord(zone.id, existing.id, {
3074
- name: domain,
3075
- type,
3076
- content: ip,
3077
- proxied: isProxied,
3078
- ttl,
3079
- comment: `Managed by epd (${cfg.name})`
3080
- });
3081
- }
3082
- results.push({ provider: provider.name, domain, ip, type, action: "updated", recordId: existing.id, proxied: isProxied });
3083
- if (opts.log) {
3084
- log.ok(`${provider.name}: updated ${type} ${c.bold(domain)} \u2192 ${ip}${provider.name === "cloudflare" ? ` (${isProxied ? "proxied" : "DNS only"})` : ""}`);
3085
- }
3086
- } else {
3087
- results.push({ provider: provider.name, domain, ip, type, action: "unchanged", recordId: existing.id, proxied: isProxied });
3088
- if (opts.log) {
3089
- log.debug(`${type} ${domain} \u2192 ${ip} already in sync`);
3090
- }
3091
- }
3092
- } else {
3093
- let recordId;
3094
- if (!opts.dryRun) {
3095
- const created = await provider.createDnsRecord(zone.id, {
3096
- name: domain,
3097
- type,
3098
- content: ip,
3099
- proxied: isProxied,
3100
- ttl,
3101
- comment: `Managed by epd (${cfg.name})`
3102
- });
3103
- recordId = created.id;
3104
- }
3105
- results.push({ provider: provider.name, domain, ip, type, action: "created", recordId, proxied: isProxied });
3106
- if (opts.log) {
3107
- log.ok(`${provider.name}: created ${type} ${c.bold(domain)} \u2192 ${ip}${provider.name === "cloudflare" ? ` (${isProxied ? "proxied" : "DNS only"})` : ""}${opts.dryRun ? " [dry-run]" : ""}`);
3108
- }
3109
- }
3110
- }
3111
- }
3112
- return results;
3113
- }
3114
- // src/hetzner/api.ts
3115
- class HetznerCloudClient {
3116
- apiToken;
3117
- baseUrl;
3118
- constructor(apiToken, baseUrl = "https://api.hetzner.cloud/v1") {
3119
- this.apiToken = apiToken;
3120
- this.baseUrl = baseUrl.replace(/\/$/, "");
3121
- }
3122
- async request(path, options = {}) {
3123
- const url = `${this.baseUrl}${path}`;
3124
- const headers = {
3125
- Authorization: `Bearer ${this.apiToken}`,
3126
- "Content-Type": "application/json",
3127
- ...options.headers
3128
- };
3129
- const res = await fetch(url, { ...options, headers });
3130
- let data;
3131
- try {
3132
- data = await res.json();
3133
- } catch {
3134
- data = null;
3135
- }
3136
- if (!res.ok) {
3137
- const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
3138
- throw new EpdError(`Hetzner Cloud API error: ${msg}`);
3139
- }
3140
- return data;
3141
- }
3142
- mapServer(s) {
3143
- return {
3144
- id: s.id,
3145
- name: s.name,
3146
- status: s.status,
3147
- created: s.created,
3148
- publicNet: {
3149
- ipv4: {
3150
- ip: s.public_net?.ipv4?.ip ?? "",
3151
- blocked: Boolean(s.public_net?.ipv4?.blocked),
3152
- dnsPtr: s.public_net?.ipv4?.dns_ptr
3153
- },
3154
- ipv6: s.public_net?.ipv6 ? {
3155
- ip: s.public_net.ipv6.ip ?? "",
3156
- blocked: Boolean(s.public_net.ipv6.blocked)
3157
- } : undefined
3158
- },
3159
- serverType: {
3160
- id: s.server_type?.id ?? 0,
3161
- name: s.server_type?.name ?? "",
3162
- description: s.server_type?.description ?? "",
3163
- cores: s.server_type?.cores ?? 0,
3164
- memory: s.server_type?.memory ?? 0,
3165
- disk: s.server_type?.disk ?? 0,
3166
- cpuType: s.server_type?.cpu_type ?? "shared",
3167
- architecture: s.server_type?.architecture ?? "x86"
3168
- },
3169
- datacenter: {
3170
- id: s.datacenter?.id ?? 0,
3171
- name: s.datacenter?.name ?? "",
3172
- description: s.datacenter?.description ?? "",
3173
- location: {
3174
- id: s.datacenter?.location?.id ?? 0,
3175
- name: s.datacenter?.location?.name ?? "",
3176
- description: s.datacenter?.location?.description ?? "",
3177
- country: s.datacenter?.location?.country ?? "",
3178
- city: s.datacenter?.location?.city ?? ""
3179
- }
3180
- },
3181
- image: s.image ? {
3182
- id: s.image.id,
3183
- name: s.image.name ?? "",
3184
- osFlavor: s.image.os_flavor ?? "",
3185
- description: s.image.description ?? ""
3186
- } : undefined,
3187
- labels: s.labels ?? {}
3188
- };
3189
- }
3190
- async listServers(opts = {}) {
3191
- const params = new URLSearchParams;
3192
- if (opts.name)
3193
- params.set("name", opts.name);
3194
- if (opts.labelSelector)
3195
- params.set("label_selector", opts.labelSelector);
3196
- params.set("per_page", "50");
3197
- const query = params.toString() ? `?${params.toString()}` : "";
3198
- const res = await this.request(`/servers${query}`);
3199
- return (res.servers ?? []).map((s) => this.mapServer(s));
3200
- }
3201
- async getServer(idOrName) {
3202
- if (typeof idOrName === "number" || /^\d+$/.test(String(idOrName))) {
3203
- try {
3204
- const res = await this.request(`/servers/${idOrName}`);
3205
- return this.mapServer(res.server);
3206
- } catch (e) {
3207
- if (e instanceof EpdError && e.message.includes("404"))
3208
- return null;
3209
- throw e;
3210
- }
3211
- }
3212
- const servers = await this.listServers({ name: String(idOrName) });
3213
- return servers.find((s) => s.name === String(idOrName)) ?? null;
3214
- }
3215
- async createServer(opts) {
3216
- const body = {
3217
- name: opts.name,
3218
- server_type: opts.serverType ?? "cx22",
3219
- image: opts.image ?? "ubuntu-24.04",
3220
- start_after_create: opts.startAfterCreate ?? true
3221
- };
3222
- if (opts.location)
3223
- body.location = opts.location;
3224
- if (opts.datacenter)
3225
- body.datacenter = opts.datacenter;
3226
- if (opts.sshKeys?.length)
3227
- body.ssh_keys = opts.sshKeys;
3228
- if (opts.labels)
3229
- body.labels = opts.labels;
3230
- if (opts.userData)
3231
- body.user_data = opts.userData;
3232
- const res = await this.request("/servers", {
3233
- method: "POST",
3234
- body: JSON.stringify(body)
3235
- });
3236
- return {
3237
- server: this.mapServer(res.server),
3238
- action: res.action,
3239
- rootPassword: res.root_password
3240
- };
3668
+ provider = new CloudflareClient(token);
3669
+ } else if (process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN) {
3670
+ const token = process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN;
3671
+ provider = new HetznerDnsClient(token);
3672
+ } else {
3673
+ throw new EpdError("No DNS provider configured", "Configure `dns:` or `cloudflare:` in epd.yml, or set CLOUDFLARE_API_TOKEN / HETZNER_DNS_API_TOKEN in environment.");
3241
3674
  }
3242
- async deleteServer(id) {
3243
- await this.request(`/servers/${id}`, {
3244
- method: "DELETE"
3245
- });
3675
+ const domains = getRouteDomains(cfg);
3676
+ if (!domains.length) {
3677
+ if (opts.log)
3678
+ log.step(`${provider.name} DNS: no domain names found in routes to sync`);
3679
+ return [];
3246
3680
  }
3247
- async listServerTypes() {
3248
- const res = await this.request("/server_types");
3249
- return (res.server_types ?? []).map((st) => ({
3250
- id: st.id,
3251
- name: st.name,
3252
- description: st.description,
3253
- cores: st.cores,
3254
- memory: st.memory,
3255
- disk: st.disk,
3256
- cpuType: st.cpu_type,
3257
- architecture: st.architecture,
3258
- prices: (st.prices ?? []).map((p) => ({
3259
- location: p.location,
3260
- priceHourly: { net: p.price_hourly?.net ?? "", gross: p.price_hourly?.gross ?? "" },
3261
- priceMonthly: { net: p.price_monthly?.net ?? "", gross: p.price_monthly?.gross ?? "" }
3262
- }))
3263
- }));
3681
+ const routedHosts = new Set;
3682
+ for (const svc of cfg.services) {
3683
+ if (svc.routes.length) {
3684
+ for (const h of svc.hosts)
3685
+ routedHosts.add(h);
3686
+ }
3264
3687
  }
3265
- async listLocations() {
3266
- const res = await this.request("/locations");
3267
- return (res.locations ?? []).map((l) => ({
3268
- id: l.id,
3269
- name: l.name,
3270
- description: l.description,
3271
- country: l.country,
3272
- city: l.city,
3273
- networkZone: l.network_zone
3274
- }));
3688
+ const ips = new Set;
3689
+ for (const h of routedHosts) {
3690
+ const resolved = await resolveHostIps(h);
3691
+ for (const ip of resolved) {
3692
+ if (isIPv4(ip) || isIPv6(ip))
3693
+ ips.add(ip);
3694
+ }
3275
3695
  }
3276
- async listSshKeys() {
3277
- const res = await this.request("/ssh_keys");
3278
- return (res.ssh_keys ?? []).map((k) => ({
3279
- id: k.id,
3280
- name: k.name,
3281
- fingerprint: k.fingerprint,
3282
- publicKey: k.public_key
3283
- }));
3696
+ if (!ips.size) {
3697
+ if (opts.log)
3698
+ log.step(`${provider.name} DNS: no server IP addresses resolved to sync`);
3699
+ return [];
3284
3700
  }
3285
- async getAction(id) {
3286
- const res = await this.request(`/actions/${id}`);
3287
- return res.action;
3701
+ const isProxied = opts.proxied ?? cfg.dns?.proxied ?? cfg.cloudflare?.proxied ?? true;
3702
+ const ttl = cfg.dns?.ttl ?? cfg.cloudflare?.ttl ?? (provider.name === "hetzner" ? 300 : 1);
3703
+ const explicitZoneId = cfg.dns?.zoneId ?? cfg.cloudflare?.zoneId;
3704
+ const results = [];
3705
+ if (opts.log) {
3706
+ log.step(`${provider.name} DNS: syncing ${c.bold(domains.length.toString())} domain(s) across ${c.bold(ips.size.toString())} server IP(s)`);
3288
3707
  }
3289
- async waitForAction(actionId, timeoutMs = 120000) {
3290
- const deadline = Date.now() + timeoutMs;
3291
- while (Date.now() < deadline) {
3292
- const action = await this.getAction(actionId);
3293
- if (action.status === "success")
3294
- return;
3295
- if (action.status === "error") {
3296
- throw new EpdError(`Hetzner action failed: ${action.error?.message || "Unknown error"}`);
3297
- }
3298
- await sleep(1500);
3708
+ const zoneCache = new Map;
3709
+ for (const domain of domains) {
3710
+ let zone = zoneCache.get(domain);
3711
+ if (!zone) {
3712
+ zone = await provider.findZoneForDomain(domain, explicitZoneId);
3713
+ zoneCache.set(domain, zone);
3299
3714
  }
3300
- throw new EpdError(`Hetzner action ${actionId} timed out after ${Math.round(timeoutMs / 1000)}s`);
3301
- }
3302
- async waitForServerRunning(serverId, timeoutMs = 120000) {
3303
- const deadline = Date.now() + timeoutMs;
3304
- while (Date.now() < deadline) {
3305
- const server = await this.getServer(serverId);
3306
- if (server && server.status === "running" && server.publicNet.ipv4.ip) {
3307
- return server;
3715
+ const existingRecords = await provider.listDnsRecords(zone.id, domain);
3716
+ for (const ip of ips) {
3717
+ const type = isIPv6(ip) ? "AAAA" : "A";
3718
+ const existing = existingRecords.find((r) => r.name.toLowerCase() === domain.toLowerCase() && r.type === type && r.content === ip);
3719
+ if (existing) {
3720
+ const needsProxyUpdate = provider.name === "cloudflare" && existing.proxied !== isProxied;
3721
+ const needsTtlUpdate = ttl !== 1 && existing.ttl !== ttl;
3722
+ if (needsProxyUpdate || needsTtlUpdate) {
3723
+ if (!opts.dryRun) {
3724
+ await provider.updateDnsRecord(zone.id, existing.id, {
3725
+ name: domain,
3726
+ type,
3727
+ content: ip,
3728
+ proxied: isProxied,
3729
+ ttl,
3730
+ comment: `Managed by epd (${cfg.name})`
3731
+ });
3732
+ }
3733
+ results.push({ provider: provider.name, domain, ip, type, action: "updated", recordId: existing.id, proxied: isProxied });
3734
+ if (opts.log) {
3735
+ log.ok(`${provider.name}: updated ${type} ${c.bold(domain)} \u2192 ${ip}${provider.name === "cloudflare" ? ` (${isProxied ? "proxied" : "DNS only"})` : ""}`);
3736
+ }
3737
+ } else {
3738
+ results.push({ provider: provider.name, domain, ip, type, action: "unchanged", recordId: existing.id, proxied: isProxied });
3739
+ if (opts.log) {
3740
+ log.debug(`${type} ${domain} \u2192 ${ip} already in sync`);
3741
+ }
3742
+ }
3743
+ } else {
3744
+ let recordId;
3745
+ if (!opts.dryRun) {
3746
+ const created = await provider.createDnsRecord(zone.id, {
3747
+ name: domain,
3748
+ type,
3749
+ content: ip,
3750
+ proxied: isProxied,
3751
+ ttl,
3752
+ comment: `Managed by epd (${cfg.name})`
3753
+ });
3754
+ recordId = created.id;
3755
+ }
3756
+ results.push({ provider: provider.name, domain, ip, type, action: "created", recordId, proxied: isProxied });
3757
+ if (opts.log) {
3758
+ log.ok(`${provider.name}: created ${type} ${c.bold(domain)} \u2192 ${ip}${provider.name === "cloudflare" ? ` (${isProxied ? "proxied" : "DNS only"})` : ""}${opts.dryRun ? " [dry-run]" : ""}`);
3759
+ }
3308
3760
  }
3309
- await sleep(2000);
3310
3761
  }
3311
- throw new EpdError(`Timed out waiting for Hetzner server ${serverId} to become running`);
3312
3762
  }
3763
+ return results;
3313
3764
  }
3314
-
3315
3765
  // src/hetzner/resolve.ts
3316
3766
  async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
3317
3767
  let needsHetzner = Boolean(cfg.hetzner);
@@ -3329,7 +3779,7 @@ async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
3329
3779
  }
3330
3780
  if (!needsHetzner)
3331
3781
  return;
3332
- const token = cfg.hetzner?.apiToken || env.HETZNER_API_TOKEN || env.HCLOUD_TOKEN || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN;
3782
+ const token = cfg.hetzner?.apiToken || env.HETZNER_API_TOKEN || env.HCLOUD_TOKEN || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN || getHetznerToken();
3333
3783
  if (!token && !clientOverride) {
3334
3784
  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.");
3335
3785
  }
@@ -3727,6 +4177,30 @@ Options
3727
4177
  async run(ctx) {
3728
4178
  const loaded = ctx.load();
3729
4179
  const cfg = loaded.config;
4180
+ const needsHetzner = Boolean(cfg.hetzner) || cfg.services.some((s) => s.hosts.some((h) => h.startsWith("hetzner:")));
4181
+ if (needsHetzner && !cfg.hetzner?.apiToken && !getHetznerToken() && interactive()) {
4182
+ log.warn("Hetzner Cloud integration requires an API token.");
4183
+ const link = await confirm("Would you like to link Hetzner Cloud now?", true);
4184
+ if (link) {
4185
+ const token = await linkHetznerInteractive();
4186
+ if (token && cfg.hetzner)
4187
+ cfg.hetzner.apiToken = token;
4188
+ }
4189
+ }
4190
+ const needsCloudflare = cfg.dns?.provider === "cloudflare" || Boolean(cfg.cloudflare);
4191
+ if (needsCloudflare && !cfg.dns?.apiToken && !cfg.cloudflare?.apiToken && !getCloudflareToken() && interactive()) {
4192
+ log.warn("Cloudflare DNS integration requires an API token.");
4193
+ const link = await confirm("Would you like to link Cloudflare now?", true);
4194
+ if (link) {
4195
+ const token = await linkCloudflareInteractive();
4196
+ if (token) {
4197
+ if (cfg.dns)
4198
+ cfg.dns.apiToken = token;
4199
+ if (cfg.cloudflare)
4200
+ cfg.cloudflare.apiToken = token;
4201
+ }
4202
+ }
4203
+ }
3730
4204
  await resolveDynamicHosts(cfg, loaded.env);
3731
4205
  const only = ctx.values.host;
3732
4206
  const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
@@ -4639,10 +5113,16 @@ Environment
4639
5113
  const cfg = loaded.config;
4640
5114
  const sub = ctx.positionals[0] || "dns";
4641
5115
  const action = ctx.positionals[1] || (sub === "status" ? "status" : "sync");
4642
- const token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
5116
+ let token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || getCloudflareToken();
5117
+ if (!token && interactive()) {
5118
+ log.info("No Cloudflare API token found.");
5119
+ const link = await confirm("Would you like to link your Cloudflare account now?", true);
5120
+ if (link) {
5121
+ token = await linkCloudflareInteractive() ?? undefined;
5122
+ }
5123
+ }
4643
5124
  if (!token) {
4644
- throw new EpdError("Cloudflare API token is missing", `Set CLOUDFLARE_API_TOKEN in your environment or add it to epd.yml:
4645
- ` + " cloudflare:\n api_token: ${CLOUDFLARE_API_TOKEN}");
5125
+ 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.");
4646
5126
  }
4647
5127
  const client = new CloudflareClient(token);
4648
5128
  const domains = getRouteDomains(cfg);
@@ -4748,9 +5228,16 @@ Environment
4748
5228
  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";
4749
5229
  let provider;
4750
5230
  if (providerName === "cloudflare") {
4751
- const token = cfg.dns?.apiToken || cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
5231
+ let token = cfg.dns?.apiToken || cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || getCloudflareToken();
5232
+ if (!token && interactive()) {
5233
+ log.info("No Cloudflare API token found.");
5234
+ const link = await confirm("Would you like to link your Cloudflare account now?", true);
5235
+ if (link) {
5236
+ token = await linkCloudflareInteractive() ?? undefined;
5237
+ }
5238
+ }
4752
5239
  if (!token) {
4753
- throw new EpdError("Cloudflare API token is missing", "Set CLOUDFLARE_API_TOKEN in environment or add it to epd.yml under dns or cloudflare.");
5240
+ 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.");
4754
5241
  }
4755
5242
  provider = new CloudflareClient(token);
4756
5243
  } else if (providerName === "hetzner") {
@@ -4871,9 +5358,16 @@ Environment
4871
5358
  token = loaded.config.hetzner?.apiToken || loaded.env.HETZNER_API_TOKEN || loaded.env.HCLOUD_TOKEN;
4872
5359
  projectName = loaded.config.name;
4873
5360
  } catch {}
4874
- token = token || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN;
5361
+ token = token || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN || getHetznerToken();
5362
+ if (!token && interactive()) {
5363
+ log.info("No Hetzner Cloud API token found.");
5364
+ const link = await confirm("Would you like to link your Hetzner Cloud account now?", true);
5365
+ if (link) {
5366
+ token = await linkHetznerInteractive() ?? undefined;
5367
+ }
5368
+ }
4875
5369
  if (!token) {
4876
- 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.");
5370
+ 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.");
4877
5371
  }
4878
5372
  const client = new HetznerCloudClient(token);
4879
5373
  const sub = ctx.positionals[0] || "list";
@@ -4943,11 +5437,14 @@ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
4943
5437
  labels.app = projectName;
4944
5438
  const userLabels = ctx.values.label ?? [];
4945
5439
  for (const l of userLabels) {
4946
- const [k, v] = l.split("=");
4947
- if (k && v !== undefined)
4948
- labels[k] = v;
5440
+ const eq = l.indexOf("=");
5441
+ if (eq !== -1) {
5442
+ labels[l.slice(0, eq).trim()] = l.slice(eq + 1).trim();
5443
+ } else {
5444
+ labels[l.trim()] = "true";
5445
+ }
4949
5446
  }
4950
- let sshKeys = undefined;
5447
+ let sshKeys;
4951
5448
  const explicitKey = ctx.values["ssh-key"];
4952
5449
  if (explicitKey) {
4953
5450
  sshKeys = [explicitKey];
@@ -5012,8 +5509,8 @@ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
5012
5509
  if (!server) {
5013
5510
  throw new EpdError(`Hetzner server "${target}" not found.`);
5014
5511
  }
5015
- const confirm = Boolean(ctx.values.yes);
5016
- if (!confirm) {
5512
+ const confirmDel = Boolean(ctx.values.yes);
5513
+ if (!confirmDel) {
5017
5514
  process.stdout.write(`Are you sure you want to permanently delete server ${c.bold(server.name)} (${server.publicNet.ipv4.ip || server.id})? [y/N]: `);
5018
5515
  for await (const line of console) {
5019
5516
  if (!line.trim().toLowerCase().startsWith("y")) {
@@ -5077,6 +5574,267 @@ ${c.bold("HETZNER DATACENTER LOCATIONS")}
5077
5574
  }
5078
5575
  };
5079
5576
 
5577
+ // src/core/update.ts
5578
+ import { chmodSync as chmodSync2, existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync, writeFileSync as writeFileSync3 } from "fs";
5579
+ import { homedir as homedir3 } from "os";
5580
+ import { dirname as dirname2, join as join7 } from "path";
5581
+ function parseSemver(v) {
5582
+ const clean = v.replace(/^v/, "").trim();
5583
+ const parts = clean.split("-")[0].split(".").map((n) => Number(n) || 0);
5584
+ return [parts[0] || 0, parts[1] || 0, parts[2] || 0];
5585
+ }
5586
+ function isNewer(current, latest) {
5587
+ const [cMaj, cMin, cPatch] = parseSemver(current);
5588
+ const [lMaj, lMin, lPatch] = parseSemver(latest);
5589
+ if (lMaj > cMaj)
5590
+ return true;
5591
+ if (lMaj < cMaj)
5592
+ return false;
5593
+ if (lMin > cMin)
5594
+ return true;
5595
+ if (lMin < cMin)
5596
+ return false;
5597
+ return lPatch > cPatch;
5598
+ }
5599
+ function getCachePath() {
5600
+ return join7(homedir3(), ".epd", "update-check.json");
5601
+ }
5602
+ function readCache() {
5603
+ try {
5604
+ const p = getCachePath();
5605
+ if (existsSync6(p)) {
5606
+ return JSON.parse(readFileSync4(p, "utf8"));
5607
+ }
5608
+ } catch {}
5609
+ return null;
5610
+ }
5611
+ function writeCache(latestVersion) {
5612
+ try {
5613
+ const p = getCachePath();
5614
+ mkdirSync4(dirname2(p), { recursive: true });
5615
+ const data = { lastChecked: Date.now(), latestVersion };
5616
+ writeFileSync3(p, JSON.stringify(data));
5617
+ } catch {}
5618
+ }
5619
+ async function fetchLatestNpmVersion() {
5620
+ try {
5621
+ const res = await fetch("https://registry.npmjs.org/@fabioplunser/epd/latest", {
5622
+ headers: { Accept: "application/json" },
5623
+ signal: AbortSignal.timeout(2500)
5624
+ });
5625
+ if (!res.ok)
5626
+ return null;
5627
+ const data = await res.json();
5628
+ return typeof data?.version === "string" ? data.version : null;
5629
+ } catch {
5630
+ return null;
5631
+ }
5632
+ }
5633
+ async function checkForUpdate(currentVersion, options = {}) {
5634
+ const cache = readCache();
5635
+ const cacheTtlMs = 4 * 60 * 60 * 1000;
5636
+ if (!options.force && cache && Date.now() - cache.lastChecked < cacheTtlMs) {
5637
+ const hasUpdate = isNewer(currentVersion, cache.latestVersion);
5638
+ return { hasUpdate, latestVersion: cache.latestVersion };
5639
+ }
5640
+ const remote = await fetchLatestNpmVersion();
5641
+ if (remote) {
5642
+ writeCache(remote);
5643
+ return {
5644
+ hasUpdate: isNewer(currentVersion, remote),
5645
+ latestVersion: remote
5646
+ };
5647
+ }
5648
+ if (cache) {
5649
+ return {
5650
+ hasUpdate: isNewer(currentVersion, cache.latestVersion),
5651
+ latestVersion: cache.latestVersion
5652
+ };
5653
+ }
5654
+ return { hasUpdate: false, latestVersion: currentVersion };
5655
+ }
5656
+ async function performUpdate(targetVersion) {
5657
+ const isBun = typeof process.isBun !== "undefined";
5658
+ const execPath = process.execPath || "";
5659
+ const isCompiledBinary = isBun && !execPath.endsWith("bun");
5660
+ if (isCompiledBinary) {
5661
+ try {
5662
+ const platform = process.platform;
5663
+ const arch = process.arch;
5664
+ let binaryName = "";
5665
+ if (platform === "linux" && arch === "x64")
5666
+ binaryName = "epd-linux-x64";
5667
+ else if (platform === "linux" && arch === "arm64")
5668
+ binaryName = "epd-linux-arm64";
5669
+ else if (platform === "darwin" && arch === "x64")
5670
+ binaryName = "epd-darwin-x64";
5671
+ else if (platform === "darwin" && arch === "arm64")
5672
+ binaryName = "epd-darwin-arm64";
5673
+ else if (platform === "win32" && arch === "x64")
5674
+ binaryName = "epd-windows-x64.exe";
5675
+ if (binaryName) {
5676
+ log.step(`Downloading ${binaryName} from GitHub Releases...`);
5677
+ const url = `https://github.com/FabioPlunser/epd/releases/latest/download/${binaryName}`;
5678
+ const res = await fetch(url);
5679
+ if (!res.ok)
5680
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
5681
+ const buf = await res.arrayBuffer();
5682
+ const tmpPath = `${execPath}.tmp.${Date.now()}`;
5683
+ writeFileSync3(tmpPath, Buffer.from(buf));
5684
+ chmodSync2(tmpPath, 493);
5685
+ renameSync(tmpPath, execPath);
5686
+ return true;
5687
+ }
5688
+ } catch (e) {
5689
+ log.debug(`Binary self-update failed, falling back to package manager: ${e}`);
5690
+ }
5691
+ }
5692
+ const isBunGlobal = (process.argv[1] || "").includes(".bun");
5693
+ const pkgMgr = isBunGlobal ? "bun" : "npm";
5694
+ const pkgSpec = targetVersion ? `@fabioplunser/epd@${targetVersion}` : "@fabioplunser/epd@latest";
5695
+ try {
5696
+ log.step(`Updating via ${pkgMgr}...`);
5697
+ const res = await runShell(`${pkgMgr} install -g ${pkgSpec}`, { stream: true, allowFailure: true });
5698
+ return res.code === 0;
5699
+ } catch {
5700
+ const fallback = pkgMgr === "bun" ? "npm" : "bun";
5701
+ try {
5702
+ log.step(`Trying ${fallback}...`);
5703
+ const res = await runShell(`${fallback} install -g ${pkgSpec}`, { stream: true, allowFailure: true });
5704
+ return res.code === 0;
5705
+ } catch {
5706
+ return false;
5707
+ }
5708
+ }
5709
+ }
5710
+ async function promptAutoUpdate(currentVersion) {
5711
+ if (!interactive() || process.env.CI || process.env.EPD_NO_UPDATE_CHECK === "1" || process.env.EPD_NO_UPDATE_CHECK === "true") {
5712
+ return false;
5713
+ }
5714
+ const { hasUpdate, latestVersion } = await checkForUpdate(currentVersion);
5715
+ if (!hasUpdate)
5716
+ return false;
5717
+ console.log("");
5718
+ log.info(`A new version of ${c.bold("epd")} is available: ${c.yellow(currentVersion)} \u2192 ${c.green(c.bold(latestVersion))}`);
5719
+ const shouldUpdate = await confirm("Would you like to update now?", false);
5720
+ if (!shouldUpdate) {
5721
+ console.log("");
5722
+ return false;
5723
+ }
5724
+ log.step(`Updating epd to v${latestVersion}...`);
5725
+ const success = await performUpdate(latestVersion);
5726
+ if (success) {
5727
+ log.ok(`Successfully updated epd to ${c.bold(`v${latestVersion}`)}!`);
5728
+ console.log("");
5729
+ return true;
5730
+ } else {
5731
+ log.warn(`Auto-update failed. You can update manually with:
5732
+ ${c.cyan(`npm install -g @fabioplunser/epd@latest`)}
5733
+ `);
5734
+ return false;
5735
+ }
5736
+ }
5737
+
5738
+ // src/version.ts
5739
+ var VERSION = "0.4.0";
5740
+
5741
+ // src/commands/update.ts
5742
+ var update = {
5743
+ name: "update",
5744
+ aliases: ["upgrade"],
5745
+ summary: "Check for updates and upgrade epd to the latest version",
5746
+ options: {
5747
+ check: { type: "boolean" },
5748
+ yes: { type: "boolean", short: "y" }
5749
+ },
5750
+ help: () => `${c.bold("epd update")} \u2014 update epd to the latest release
5751
+
5752
+ Options
5753
+ --check Check for updates without installing
5754
+ -y, --yes Install update without prompting`,
5755
+ async run(ctx) {
5756
+ const currentVersion = VERSION;
5757
+ log.step(`Checking for epd updates (current: v${currentVersion})...`);
5758
+ const { hasUpdate, latestVersion } = await checkForUpdate(currentVersion, { force: true });
5759
+ if (!hasUpdate) {
5760
+ log.ok(`epd is up to date (${c.green(`v${currentVersion}`)}).`);
5761
+ return;
5762
+ }
5763
+ log.info(`A newer version is available: ${c.yellow(`v${currentVersion}`)} \u2192 ${c.green(c.bold(`v${latestVersion}`))}`);
5764
+ if (ctx.values.check) {
5765
+ log.info(`Run ${c.cyan("epd update")} to upgrade.`);
5766
+ return;
5767
+ }
5768
+ log.step(`Upgrading epd to v${latestVersion}...`);
5769
+ const success = await performUpdate(latestVersion);
5770
+ if (success) {
5771
+ log.ok(`epd updated successfully to ${c.bold(`v${latestVersion}`)}!`);
5772
+ } else {
5773
+ log.error(`Update failed. You can update manually with:`);
5774
+ console.log(` ${c.cyan("npm install -g @fabioplunser/epd@latest")}
5775
+ `);
5776
+ }
5777
+ }
5778
+ };
5779
+
5780
+ // src/commands/auth.ts
5781
+ var auth = {
5782
+ name: "auth",
5783
+ aliases: ["login"],
5784
+ summary: "Manage Cloudflare and Hetzner API authentication and linked accounts",
5785
+ options: {
5786
+ global: { type: "boolean" }
5787
+ },
5788
+ help: () => `${c.bold("epd auth")} \u2014 manage linked cloud accounts and API tokens
5789
+
5790
+ Commands
5791
+ epd auth Show status of linked Cloudflare and Hetzner accounts
5792
+ epd auth cloudflare Link or re-authenticate Cloudflare (DNS & SSL)
5793
+ epd auth hetzner Link or re-authenticate Hetzner Cloud (Servers & DNS)
5794
+ epd auth logout Remove globally saved authentication credentials
5795
+
5796
+ Saved credentials are stored with 0600 permissions in ~/.config/epd/auth.json`,
5797
+ async run(ctx) {
5798
+ const sub = ctx.positionals[0] || "status";
5799
+ const root = process.cwd();
5800
+ if (sub === "cloudflare" || sub === "cf") {
5801
+ await linkCloudflareInteractive(root);
5802
+ return;
5803
+ }
5804
+ if (sub === "hetzner" || sub === "hcloud") {
5805
+ await linkHetznerInteractive(root);
5806
+ return;
5807
+ }
5808
+ if (sub === "logout") {
5809
+ const confirmed = await confirm("Remove all credentials from ~/.config/epd/auth.json?", true);
5810
+ if (confirmed) {
5811
+ saveGlobalAuth(() => ({}));
5812
+ log.ok("Cleared globally stored credentials in ~/.config/epd/auth.json");
5813
+ }
5814
+ return;
5815
+ }
5816
+ if (sub === "status") {
5817
+ console.log(`
5818
+ ${c.bold("EPD Authentication Status")}
5819
+ `);
5820
+ const cfToken = getCloudflareToken(root);
5821
+ const cfSource = getCloudflareTokenSource(root);
5822
+ const hToken = getHetznerToken(root);
5823
+ const hSource = getHetznerTokenSource(root);
5824
+ const authPath = getGlobalAuthPath();
5825
+ console.log(` Global storage: ${c.cyan(authPath)}`);
5826
+ console.log(` Cloudflare: ${cfToken ? `${c.green("Linked")} via ${cfSource}` : c.gray("Not linked")}`);
5827
+ console.log(` Hetzner Cloud: ${hToken ? `${c.green("Linked")} via ${hSource}` : c.gray("Not linked")}`);
5828
+ console.log(`
5829
+ Run ${c.cyan("epd auth cloudflare")} or ${c.cyan("epd auth hetzner")} to link an account.
5830
+ `);
5831
+ return;
5832
+ }
5833
+ log.warn(`Unknown auth subcommand: ${sub}`);
5834
+ console.log(auth.help());
5835
+ }
5836
+ };
5837
+
5080
5838
  // src/commands/index.ts
5081
5839
  var commands = [
5082
5840
  init,
@@ -5095,11 +5853,12 @@ var commands = [
5095
5853
  dockerCommand,
5096
5854
  cloudflare,
5097
5855
  dns3,
5098
- hetzner
5856
+ hetzner,
5857
+ update,
5858
+ auth
5099
5859
  ];
5100
5860
 
5101
5861
  // src/cli.ts
5102
- var VERSION = "0.3.0";
5103
5862
  var USAGE = `${c.bold("epd")} \u2014 Easy Project Deployer ${c.gray(`v${VERSION}`)}
5104
5863
 
5105
5864
  ${c.bold("Usage")}
@@ -5179,6 +5938,9 @@ ${command.help()}`);
5179
5938
  loadOptions,
5180
5939
  load: () => loadConfig(loadOptions)
5181
5940
  };
5941
+ if (command.name !== "update") {
5942
+ await promptAutoUpdate(VERSION);
5943
+ }
5182
5944
  await command.run(ctx);
5183
5945
  return 0;
5184
5946
  }