@fabioplunser/epd 0.3.1 → 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, mkdirSync, 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:
@@ -1088,7 +1710,11 @@ var init = {
1088
1710
  replicas: { type: "string" },
1089
1711
  force: { type: "boolean" },
1090
1712
  dockerfile: { type: "boolean" },
1091
- ci: { type: "boolean" }
1713
+ ci: { type: "boolean" },
1714
+ cloudflare: { type: "boolean" },
1715
+ "no-cloudflare": { type: "boolean" },
1716
+ hetzner: { type: "boolean" },
1717
+ "no-hetzner": { type: "boolean" }
1092
1718
  },
1093
1719
  help: () => `${c.bold("epd init")} \u2014 create an epd.yml for this project
1094
1720
 
@@ -1102,15 +1728,45 @@ Options
1102
1728
  --replicas <n> Replicas per host (default 1)
1103
1729
  --dockerfile Also write a starter Dockerfile
1104
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
1105
1735
  --force Overwrite an existing epd.yml`,
1106
1736
  async run(ctx) {
1107
1737
  const root = process.cwd();
1108
- const target = join2(root, "epd.yml");
1109
- if (existsSync2(target) && !ctx.values.force) {
1738
+ const target = join3(root, "epd.yml");
1739
+ if (existsSync3(target) && !ctx.values.force) {
1110
1740
  throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
1111
1741
  }
1112
1742
  const detected = detect(root);
1113
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
+ }
1114
1770
  const name = ctx.values.name ?? await ask("App name", detected.name);
1115
1771
  const mode = ctx.values.mode ?? await choose("How should it run on the server?", [
1116
1772
  { value: "docker", label: "Docker \u2014 build an image, run containers" },
@@ -1118,8 +1774,63 @@ Options
1118
1774
  ], detected.hasDockerfile || detected.runtime === "unknown" ? "docker" : "docker");
1119
1775
  if (mode !== "docker" && mode !== "process")
1120
1776
  throw new EpdError(`--mode must be "docker" or "process"`);
1121
- 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);
1122
- 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);
1123
1834
  const port = Number(ctx.values.port ?? await ask("Port your app listens on", String(detected.port)));
1124
1835
  const email = ctx.values.email ?? await ask("Email for Let's Encrypt", "");
1125
1836
  const replicas = Number(ctx.values.replicas ?? 1);
@@ -1131,13 +1842,27 @@ Options
1131
1842
  registryUser = await ask("Registry username", process.env.USER ?? "");
1132
1843
  image = `${registryServer ? `${registryServer}/` : ""}${registryUser}/${name}`;
1133
1844
  }
1134
- 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
+ }));
1135
1860
  log.ok(`wrote ${c.bold("epd.yml")}`);
1136
1861
  const wantDockerfile = mode === "docker" && !detected.hasDockerfile && (Boolean(ctx.values.dockerfile) || await confirm("No Dockerfile here. Write a starter one?", true));
1137
1862
  if (wantDockerfile) {
1138
1863
  const df = DOCKERFILES[detected.runtime];
1139
1864
  if (df) {
1140
- writeFileSync(join2(root, "Dockerfile"), df);
1865
+ writeFileSync2(join3(root, "Dockerfile"), df);
1141
1866
  log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
1142
1867
  } else {
1143
1868
  log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
@@ -1145,8 +1870,8 @@ Options
1145
1870
  }
1146
1871
  const wantCi = Boolean(ctx.values.ci) || interactive() && await confirm("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
1147
1872
  if (wantCi) {
1148
- const workflowDir = join2(root, ".github", "workflows");
1149
- mkdirSync(workflowDir, { recursive: true });
1873
+ const workflowDir = join3(root, ".github", "workflows");
1874
+ mkdirSync2(workflowDir, { recursive: true });
1150
1875
  const ciYaml = `name: Deploy
1151
1876
 
1152
1877
  on:
@@ -1161,30 +1886,30 @@ jobs:
1161
1886
  deploy:
1162
1887
  runs-on: ubuntu-latest
1163
1888
  steps:
1164
- - name: Checkout code
1889
+ - name: Checkout repository
1165
1890
  uses: actions/checkout@v4
1166
1891
 
1167
- - name: Setup SSH Agent
1168
- uses: webfactory/ssh-agent@v0.9.0
1892
+ - name: Setup Bun
1893
+ uses: oven-sh/setup-bun@v2
1169
1894
  with:
1170
- ssh-private-key: \${{ secrets.SSH_PRIVATE_KEY }}
1895
+ bun-version: latest
1896
+
1897
+ - name: Install EPD
1898
+ run: bun install -g @fabioplunser/epd
1171
1899
 
1172
1900
  - name: Deploy with EPD
1173
- run: npx @fabioplunser/epd deploy
1174
1901
  env:
1175
- CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
1176
- HETZNER_API_TOKEN: \${{ secrets.HETZNER_API_TOKEN }}
1177
- HETZNER_DNS_API_TOKEN: \${{ secrets.HETZNER_DNS_API_TOKEN }}
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
1178
1904
  `;
1179
- writeFileSync(join2(workflowDir, "deploy.yml"), ciYaml);
1905
+ writeFileSync2(join3(workflowDir, "deploy.yml"), ciYaml);
1180
1906
  log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
1181
1907
  }
1182
1908
  console.log(`
1183
- ${c.bold("Next")}
1184
- 1. Edit ${c.cyan("epd.yml")} \u2014 servers, domains, env.
1185
- 2. Point your domains' A records at ${hosts.join(", ")}.
1186
- 3. ${c.cyan("epd setup")} installs what the servers need and deploys.
1187
- 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
1188
1913
  `);
1189
1914
  }
1190
1915
  };
@@ -1461,11 +2186,11 @@ true`, { allowFailure: true, stream: true, label: `${host.name}: install package
1461
2186
  }
1462
2187
 
1463
2188
  // src/core/ssh.ts
1464
- import { mkdirSync as mkdirSync2 } from "fs";
2189
+ import { mkdirSync as mkdirSync3 } from "fs";
1465
2190
  import { tmpdir } from "os";
1466
- import { join as join3 } from "path";
1467
- var controlDir = join3(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
1468
- mkdirSync2(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 });
1469
2194
 
1470
2195
  class Host {
1471
2196
  name;
@@ -1477,7 +2202,7 @@ class Host {
1477
2202
  this.sudo = cfg.user !== "root";
1478
2203
  }
1479
2204
  sshOptions() {
1480
- 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`);
1481
2206
  const args = [
1482
2207
  "-o",
1483
2208
  "BatchMode=yes",
@@ -2252,12 +2977,12 @@ function recordDeploy(state, version, by, keep) {
2252
2977
  }
2253
2978
 
2254
2979
  // src/deploy/image.ts
2255
- import { existsSync as existsSync3 } from "fs";
2256
- import { join as join4 } from "path";
2980
+ import { existsSync as existsSync4 } from "fs";
2981
+ import { join as join5 } from "path";
2257
2982
  async function resolveVersion(cfg, explicit) {
2258
2983
  if (explicit)
2259
2984
  return { id: explicit, source: "explicit", dirty: false };
2260
- if (existsSync3(join4(cfg.root, ".git")) && await which("git")) {
2985
+ if (existsSync4(join5(cfg.root, ".git")) && await which("git")) {
2261
2986
  const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
2262
2987
  if (sha.code === 0 && sha.stdout) {
2263
2988
  const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
@@ -2272,8 +2997,8 @@ async function hasBuildx() {
2272
2997
  return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
2273
2998
  }
2274
2999
  async function buildImage(cfg, version, env) {
2275
- const dockerfile = join4(cfg.root, cfg.build.dockerfile);
2276
- if (!existsSync3(dockerfile)) {
3000
+ const dockerfile = join5(cfg.root, cfg.build.dockerfile);
3001
+ if (!existsSync4(dockerfile)) {
2277
3002
  throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
2278
3003
  }
2279
3004
  const ref = imageRef(cfg, version);
@@ -2286,7 +3011,7 @@ async function buildImage(cfg, version, env) {
2286
3011
  async function buildWithBuildx(cfg, ref, version, env) {
2287
3012
  const args = ["docker", "buildx", "build"];
2288
3013
  args.push("--platform", cfg.build.platform);
2289
- args.push("--file", join4(cfg.root, cfg.build.dockerfile));
3014
+ args.push("--file", join5(cfg.root, cfg.build.dockerfile));
2290
3015
  args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
2291
3016
  if (cfg.build.target)
2292
3017
  args.push("--target", cfg.build.target);
@@ -2319,7 +3044,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
2319
3044
  if (cfg.build.platform !== localPlatform) {
2320
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}.`);
2321
3046
  }
2322
- 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`];
2323
3048
  if (cfg.build.target)
2324
3049
  args.push("--target", cfg.build.target);
2325
3050
  for (const [k, v] of Object.entries(cfg.build.args))
@@ -2552,8 +3277,8 @@ ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: access
2552
3277
  }
2553
3278
 
2554
3279
  // src/deploy/process.ts
2555
- import { existsSync as existsSync4 } from "fs";
2556
- import { join as join5 } from "path";
3280
+ import { existsSync as existsSync5 } from "fs";
3281
+ import { join as join6 } from "path";
2557
3282
  var asUser = { sudo: false };
2558
3283
  var pm2 = (cfg, args) => `${pathPrelude(cfg)} pm2 ${args}`;
2559
3284
  function releaseDir(cfg, version) {
@@ -2564,7 +3289,7 @@ async function uploadSource(host, cfg, version) {
2564
3289
  const p = paths(cfg);
2565
3290
  await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
2566
3291
  if (cfg.process.source === "git") {
2567
- if (!existsSync4(join5(cfg.root, ".git")))
3292
+ if (!existsSync5(join6(cfg.root, ".git")))
2568
3293
  throw new EpdError('process.source is "git" but this is not a git repository');
2569
3294
  log.host(host.name, `uploading HEAD as ${version}`);
2570
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`]);
@@ -2670,138 +3395,26 @@ async function listProcesses(host, cfg) {
2670
3395
  return [];
2671
3396
  }
2672
3397
  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
- });
2802
- }
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 });
2803
3413
  }
2804
3414
 
3415
+ // src/dns/index.ts
3416
+ import dns from "dns/promises";
3417
+
2805
3418
  // src/dns/hetzner.ts
2806
3419
  class HetznerDnsClient {
2807
3420
  name = "hetzner";
@@ -3149,207 +3762,6 @@ async function syncDns(cfg, opts = {}) {
3149
3762
  }
3150
3763
  return results;
3151
3764
  }
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
3765
  // src/hetzner/resolve.ts
3354
3766
  async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
3355
3767
  let needsHetzner = Boolean(cfg.hetzner);
@@ -3367,7 +3779,7 @@ async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
3367
3779
  }
3368
3780
  if (!needsHetzner)
3369
3781
  return;
3370
- 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();
3371
3783
  if (!token && !clientOverride) {
3372
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.");
3373
3785
  }
@@ -3765,6 +4177,30 @@ Options
3765
4177
  async run(ctx) {
3766
4178
  const loaded = ctx.load();
3767
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
+ }
3768
4204
  await resolveDynamicHosts(cfg, loaded.env);
3769
4205
  const only = ctx.values.host;
3770
4206
  const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
@@ -4677,10 +5113,16 @@ Environment
4677
5113
  const cfg = loaded.config;
4678
5114
  const sub = ctx.positionals[0] || "dns";
4679
5115
  const action = ctx.positionals[1] || (sub === "status" ? "status" : "sync");
4680
- 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
+ }
4681
5124
  if (!token) {
4682
- throw new EpdError("Cloudflare API token is missing", `Set CLOUDFLARE_API_TOKEN in your environment or add it to epd.yml:
4683
- ` + " 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.");
4684
5126
  }
4685
5127
  const client = new CloudflareClient(token);
4686
5128
  const domains = getRouteDomains(cfg);
@@ -4786,9 +5228,16 @@ Environment
4786
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";
4787
5229
  let provider;
4788
5230
  if (providerName === "cloudflare") {
4789
- 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
+ }
4790
5239
  if (!token) {
4791
- 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.");
4792
5241
  }
4793
5242
  provider = new CloudflareClient(token);
4794
5243
  } else if (providerName === "hetzner") {
@@ -4909,9 +5358,16 @@ Environment
4909
5358
  token = loaded.config.hetzner?.apiToken || loaded.env.HETZNER_API_TOKEN || loaded.env.HCLOUD_TOKEN;
4910
5359
  projectName = loaded.config.name;
4911
5360
  } catch {}
4912
- 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
+ }
4913
5369
  if (!token) {
4914
- 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.");
4915
5371
  }
4916
5372
  const client = new HetznerCloudClient(token);
4917
5373
  const sub = ctx.positionals[0] || "list";
@@ -4981,11 +5437,14 @@ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
4981
5437
  labels.app = projectName;
4982
5438
  const userLabels = ctx.values.label ?? [];
4983
5439
  for (const l of userLabels) {
4984
- const [k, v] = l.split("=");
4985
- if (k && v !== undefined)
4986
- 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
+ }
4987
5446
  }
4988
- let sshKeys = undefined;
5447
+ let sshKeys;
4989
5448
  const explicitKey = ctx.values["ssh-key"];
4990
5449
  if (explicitKey) {
4991
5450
  sshKeys = [explicitKey];
@@ -5050,8 +5509,8 @@ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
5050
5509
  if (!server) {
5051
5510
  throw new EpdError(`Hetzner server "${target}" not found.`);
5052
5511
  }
5053
- const confirm = Boolean(ctx.values.yes);
5054
- if (!confirm) {
5512
+ const confirmDel = Boolean(ctx.values.yes);
5513
+ if (!confirmDel) {
5055
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]: `);
5056
5515
  for await (const line of console) {
5057
5516
  if (!line.trim().toLowerCase().startsWith("y")) {
@@ -5116,9 +5575,9 @@ ${c.bold("HETZNER DATACENTER LOCATIONS")}
5116
5575
  };
5117
5576
 
5118
5577
  // src/core/update.ts
5119
- import { chmodSync, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync, writeFileSync as writeFileSync2 } from "fs";
5120
- import { homedir as homedir2 } from "os";
5121
- import { dirname as dirname2, join as join6 } from "path";
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";
5122
5581
  function parseSemver(v) {
5123
5582
  const clean = v.replace(/^v/, "").trim();
5124
5583
  const parts = clean.split("-")[0].split(".").map((n) => Number(n) || 0);
@@ -5138,13 +5597,13 @@ function isNewer(current, latest) {
5138
5597
  return lPatch > cPatch;
5139
5598
  }
5140
5599
  function getCachePath() {
5141
- return join6(homedir2(), ".epd", "update-check.json");
5600
+ return join7(homedir3(), ".epd", "update-check.json");
5142
5601
  }
5143
5602
  function readCache() {
5144
5603
  try {
5145
5604
  const p = getCachePath();
5146
- if (existsSync5(p)) {
5147
- return JSON.parse(readFileSync3(p, "utf8"));
5605
+ if (existsSync6(p)) {
5606
+ return JSON.parse(readFileSync4(p, "utf8"));
5148
5607
  }
5149
5608
  } catch {}
5150
5609
  return null;
@@ -5152,9 +5611,9 @@ function readCache() {
5152
5611
  function writeCache(latestVersion) {
5153
5612
  try {
5154
5613
  const p = getCachePath();
5155
- mkdirSync3(dirname2(p), { recursive: true });
5614
+ mkdirSync4(dirname2(p), { recursive: true });
5156
5615
  const data = { lastChecked: Date.now(), latestVersion };
5157
- writeFileSync2(p, JSON.stringify(data));
5616
+ writeFileSync3(p, JSON.stringify(data));
5158
5617
  } catch {}
5159
5618
  }
5160
5619
  async function fetchLatestNpmVersion() {
@@ -5221,8 +5680,8 @@ async function performUpdate(targetVersion) {
5221
5680
  throw new Error(`HTTP ${res.status} ${res.statusText}`);
5222
5681
  const buf = await res.arrayBuffer();
5223
5682
  const tmpPath = `${execPath}.tmp.${Date.now()}`;
5224
- writeFileSync2(tmpPath, Buffer.from(buf));
5225
- chmodSync(tmpPath, 493);
5683
+ writeFileSync3(tmpPath, Buffer.from(buf));
5684
+ chmodSync2(tmpPath, 493);
5226
5685
  renameSync(tmpPath, execPath);
5227
5686
  return true;
5228
5687
  }
@@ -5277,7 +5736,7 @@ async function promptAutoUpdate(currentVersion) {
5277
5736
  }
5278
5737
 
5279
5738
  // src/version.ts
5280
- var VERSION = "0.3.1";
5739
+ var VERSION = "0.4.0";
5281
5740
 
5282
5741
  // src/commands/update.ts
5283
5742
  var update = {
@@ -5318,6 +5777,64 @@ Options
5318
5777
  }
5319
5778
  };
5320
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
+
5321
5838
  // src/commands/index.ts
5322
5839
  var commands = [
5323
5840
  init,
@@ -5337,7 +5854,8 @@ var commands = [
5337
5854
  cloudflare,
5338
5855
  dns3,
5339
5856
  hetzner,
5340
- update
5857
+ update,
5858
+ auth
5341
5859
  ];
5342
5860
 
5343
5861
  // src/cli.ts