@fabioplunser/epd 0.1.1 → 0.3.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
@@ -72,6 +72,7 @@ import { dirname, join, resolve } from "path";
72
72
  import { homedir } from "os";
73
73
 
74
74
  // src/util/misc.ts
75
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
75
76
  function hash32(s) {
76
77
  let h = 2166136261;
77
78
  for (let i = 0;i < s.length; i++) {
@@ -434,7 +435,10 @@ var TOP_LEVEL_KEYS = [
434
435
  "labels",
435
436
  "drain",
436
437
  "stop_timeout",
437
- "docker_options"
438
+ "docker_options",
439
+ "cloudflare",
440
+ "dns",
441
+ "hetzner"
438
442
  ];
439
443
  function normalize(raw, configPath, root, destination) {
440
444
  checkKeys(raw, TOP_LEVEL_KEYS, "epd.yml");
@@ -566,10 +570,26 @@ function normalize(raw, configPath, root, destination) {
566
570
  "cpus",
567
571
  "memory",
568
572
  "drain",
569
- "stop_timeout"
573
+ "stop_timeout",
574
+ "hetzner"
570
575
  ], p);
576
+ let svcHetzner = undefined;
577
+ if (o.hetzner !== undefined) {
578
+ if (typeof o.hetzner === "string") {
579
+ svcHetzner = { server: asString(o.hetzner, `${p}.hetzner`) };
580
+ } else if (typeof o.hetzner === "object" && !Array.isArray(o.hetzner)) {
581
+ const hz = o.hetzner;
582
+ checkKeys(hz, ["server", "label_selector"], `${p}.hetzner`);
583
+ svcHetzner = {
584
+ server: hz.server ? asString(hz.server, `${p}.hetzner.server`) : undefined,
585
+ labelSelector: hz.label_selector ? asString(hz.label_selector, `${p}.hetzner.label_selector`) : undefined
586
+ };
587
+ } else {
588
+ fail(`${p}.hetzner`, "expected a server name string or a mapping");
589
+ }
590
+ }
571
591
  const hosts = [...asList(o.host, `${p}.host`), ...asList(o.hosts, `${p}.hosts`)];
572
- if (!hosts.length)
592
+ if (!hosts.length && !svcHetzner)
573
593
  fail(`${p}.hosts`, "at least one host is required");
574
594
  const port = asNumber(o.port, `${p}.port`, asNumber(raw.port, "epd.yml.port", 3000));
575
595
  const routes = [];
@@ -583,6 +603,7 @@ function normalize(raw, configPath, root, destination) {
583
603
  return {
584
604
  name: svcName,
585
605
  hosts,
606
+ hetzner: svcHetzner,
586
607
  replicas: asNumber(o.replicas, `${p}.replicas`, 1),
587
608
  port,
588
609
  command: o.command === undefined ? undefined : asString(o.command, `${p}.command`),
@@ -664,6 +685,76 @@ function normalize(raw, configPath, root, destination) {
664
685
  const strategy = asString(raw.strategy, "epd.yml.strategy", "rolling");
665
686
  if (strategy !== "rolling" && strategy !== "parallel")
666
687
  fail("epd.yml.strategy", 'expected "rolling" or "parallel"');
688
+ let cloudflare = undefined;
689
+ if (raw.cloudflare !== undefined && raw.cloudflare !== false) {
690
+ if (raw.cloudflare !== true && (typeof raw.cloudflare !== "object" || Array.isArray(raw.cloudflare))) {
691
+ fail("epd.yml.cloudflare", "expected a mapping or boolean");
692
+ }
693
+ const cfRaw = raw.cloudflare === true ? {} : raw.cloudflare;
694
+ checkKeys(cfRaw, ["enabled", "api_token", "zone_id", "proxied", "ttl", "auto_sync", "domains"], "epd.yml.cloudflare");
695
+ const apiToken = cfRaw.api_token ? asString(cfRaw.api_token, "epd.yml.cloudflare.api_token") : process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || "";
696
+ cloudflare = {
697
+ enabled: asBool(cfRaw.enabled, "epd.yml.cloudflare.enabled", true),
698
+ apiToken,
699
+ zoneId: cfRaw.zone_id ? asString(cfRaw.zone_id, "epd.yml.cloudflare.zone_id") : process.env.CLOUDFLARE_ZONE_ID || undefined,
700
+ proxied: asBool(cfRaw.proxied, "epd.yml.cloudflare.proxied", true),
701
+ ttl: asNumber(cfRaw.ttl, "epd.yml.cloudflare.ttl", 1),
702
+ autoSync: asBool(cfRaw.auto_sync, "epd.yml.cloudflare.auto_sync", true),
703
+ domains: cfRaw.domains ? asList(cfRaw.domains, "epd.yml.cloudflare.domains") : undefined
704
+ };
705
+ }
706
+ let dnsConfig = undefined;
707
+ if (raw.dns !== undefined && raw.dns !== false) {
708
+ if (raw.dns !== true && (typeof raw.dns !== "object" || Array.isArray(raw.dns))) {
709
+ fail("epd.yml.dns", "expected a mapping or boolean");
710
+ }
711
+ const dRaw = raw.dns === true ? {} : raw.dns;
712
+ checkKeys(dRaw, ["provider", "enabled", "api_token", "zone_id", "proxied", "ttl", "auto_sync", "domains"], "epd.yml.dns");
713
+ const provider = asString(dRaw.provider, "epd.yml.dns.provider", "cloudflare");
714
+ if (provider !== "cloudflare" && provider !== "hetzner") {
715
+ fail("epd.yml.dns.provider", 'expected "cloudflare" or "hetzner"');
716
+ }
717
+ const defaultToken = provider === "cloudflare" ? process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN || "" : process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN || "";
718
+ const apiToken = dRaw.api_token ? asString(dRaw.api_token, "epd.yml.dns.api_token") : defaultToken;
719
+ dnsConfig = {
720
+ provider,
721
+ enabled: asBool(dRaw.enabled, "epd.yml.dns.enabled", true),
722
+ apiToken,
723
+ zoneId: dRaw.zone_id ? asString(dRaw.zone_id, "epd.yml.dns.zone_id") : undefined,
724
+ proxied: asBool(dRaw.proxied, "epd.yml.dns.proxied", provider === "cloudflare"),
725
+ ttl: asNumber(dRaw.ttl, "epd.yml.dns.ttl", provider === "hetzner" ? 300 : 1),
726
+ autoSync: asBool(dRaw.auto_sync, "epd.yml.dns.auto_sync", true),
727
+ domains: dRaw.domains ? asList(dRaw.domains, "epd.yml.dns.domains") : undefined
728
+ };
729
+ } else if (cloudflare) {
730
+ dnsConfig = {
731
+ provider: "cloudflare",
732
+ enabled: cloudflare.enabled,
733
+ apiToken: cloudflare.apiToken,
734
+ zoneId: cloudflare.zoneId,
735
+ proxied: cloudflare.proxied,
736
+ ttl: cloudflare.ttl,
737
+ autoSync: cloudflare.autoSync,
738
+ domains: cloudflare.domains
739
+ };
740
+ }
741
+ let hetznerConfig = undefined;
742
+ if (raw.hetzner !== undefined && raw.hetzner !== false) {
743
+ if (typeof raw.hetzner !== "object" || Array.isArray(raw.hetzner)) {
744
+ fail("epd.yml.hetzner", "expected a mapping");
745
+ }
746
+ const hzRaw = raw.hetzner;
747
+ checkKeys(hzRaw, ["api_token", "server_type", "location", "image", "ssh_key", "label_selector"], "epd.yml.hetzner");
748
+ const apiToken = hzRaw.api_token ? asString(hzRaw.api_token, "epd.yml.hetzner.api_token") : process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN || "";
749
+ hetznerConfig = {
750
+ apiToken,
751
+ serverType: hzRaw.server_type ? asString(hzRaw.server_type, "epd.yml.hetzner.server_type") : undefined,
752
+ location: hzRaw.location ? asString(hzRaw.location, "epd.yml.hetzner.location") : undefined,
753
+ image: hzRaw.image ? asString(hzRaw.image, "epd.yml.hetzner.image") : undefined,
754
+ sshKey: hzRaw.ssh_key ? asString(hzRaw.ssh_key, "epd.yml.hetzner.ssh_key") : undefined,
755
+ labelSelector: hzRaw.label_selector ? asString(hzRaw.label_selector, "epd.yml.hetzner.label_selector") : undefined
756
+ };
757
+ }
667
758
  const cfg = {
668
759
  name,
669
760
  mode,
@@ -703,6 +794,9 @@ function normalize(raw, configPath, root, destination) {
703
794
  onFailure: hooksRaw.on_failure ? asString(hooksRaw.on_failure, "epd.yml.hooks.on_failure") : undefined
704
795
  },
705
796
  process: processCfg,
797
+ dns: dnsConfig,
798
+ cloudflare,
799
+ hetzner: hetznerConfig,
706
800
  portBase: asNumber(raw.port_base, "epd.yml.port_base", 20000 + hash32(name) % 117 * 256),
707
801
  strategy,
708
802
  keepReleases: asNumber(raw.keep_releases, "epd.yml.keep_releases", 5),
@@ -2555,9 +2649,767 @@ ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1
2555
2649
  done`, { ...asUser, allowFailure: true });
2556
2650
  }
2557
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
+ });
2764
+ }
2765
+ }
2766
+
2767
+ // src/dns/hetzner.ts
2768
+ class HetznerDnsClient {
2769
+ name = "hetzner";
2770
+ apiToken;
2771
+ baseUrl;
2772
+ zoneCache = new Map;
2773
+ constructor(apiToken, baseUrl = "https://dns.hetzner.com/api/v1") {
2774
+ this.apiToken = apiToken;
2775
+ this.baseUrl = baseUrl.replace(/\/$/, "");
2776
+ }
2777
+ async request(path, options = {}) {
2778
+ const url = `${this.baseUrl}${path}`;
2779
+ const headers = {
2780
+ "Auth-API-Token": this.apiToken,
2781
+ "Content-Type": "application/json",
2782
+ ...options.headers
2783
+ };
2784
+ const res = await fetch(url, { ...options, headers });
2785
+ let data;
2786
+ try {
2787
+ data = await res.json();
2788
+ } catch {
2789
+ data = null;
2790
+ }
2791
+ if (!res.ok) {
2792
+ const msg = data?.error?.message || data?.message || `HTTP ${res.status} ${res.statusText}`;
2793
+ throw new EpdError(`Hetzner DNS API error: ${msg}`);
2794
+ }
2795
+ return data;
2796
+ }
2797
+ async listZones(name) {
2798
+ const query = name ? `?name=${encodeURIComponent(name)}` : "";
2799
+ const res = await this.request(`/zones${query}`);
2800
+ return (res.zones ?? []).map((z) => ({ id: z.id, name: z.name }));
2801
+ }
2802
+ async findZoneForDomain(domain, explicitZoneId) {
2803
+ if (explicitZoneId) {
2804
+ const cached = this.zoneCache.get(explicitZoneId);
2805
+ if (cached)
2806
+ return cached;
2807
+ const zones = await this.listZones();
2808
+ const match = zones.find((z) => z.id === explicitZoneId);
2809
+ const zone = match ?? { id: explicitZoneId, name: domain };
2810
+ this.zoneCache.set(explicitZoneId, zone);
2811
+ return zone;
2812
+ }
2813
+ const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
2814
+ const parts = cleanDomain.split(".");
2815
+ for (let i = 0;i < parts.length - 1; i++) {
2816
+ const candidate = parts.slice(i).join(".");
2817
+ const zones = await this.listZones(candidate);
2818
+ const match = zones.find((z) => z.name.toLowerCase() === candidate);
2819
+ if (match) {
2820
+ this.zoneCache.set(match.id, match);
2821
+ return match;
2822
+ }
2823
+ }
2824
+ throw new EpdError(`Hetzner DNS zone for domain "${domain}" not found`, `Ensure the zone is added in Hetzner DNS Console (https://dns.hetzner.com) and your Auth-API-Token has permission to manage it.`);
2825
+ }
2826
+ toHetznerName(fqdn, zoneName) {
2827
+ const cleanFqdn = fqdn.replace(/^\*\./, "").toLowerCase();
2828
+ const cleanZone = zoneName.toLowerCase();
2829
+ if (cleanFqdn === cleanZone)
2830
+ return "@";
2831
+ if (cleanFqdn.endsWith("." + cleanZone)) {
2832
+ return cleanFqdn.slice(0, -(cleanZone.length + 1));
2833
+ }
2834
+ return cleanFqdn;
2835
+ }
2836
+ toFqdnName(hetznerName, zoneName) {
2837
+ if (hetznerName === "@" || hetznerName === "")
2838
+ return zoneName;
2839
+ return `${hetznerName}.${zoneName}`;
2840
+ }
2841
+ async listDnsRecords(zoneId, name, type) {
2842
+ let zone = this.zoneCache.get(zoneId);
2843
+ if (!zone) {
2844
+ const zones = await this.listZones();
2845
+ zone = zones.find((z) => z.id === zoneId);
2846
+ if (zone)
2847
+ this.zoneCache.set(zoneId, zone);
2848
+ }
2849
+ const zoneName = zone?.name ?? "";
2850
+ const res = await this.request(`/records?zone_id=${encodeURIComponent(zoneId)}`);
2851
+ const records = res.records ?? [];
2852
+ let mapped = records.map((r) => ({
2853
+ id: r.id,
2854
+ zoneId: r.zone_id,
2855
+ name: zoneName ? this.toFqdnName(r.name, zoneName) : r.name,
2856
+ type: r.type,
2857
+ content: r.value,
2858
+ proxied: false,
2859
+ ttl: r.ttl
2860
+ }));
2861
+ if (name) {
2862
+ const targetName = name.toLowerCase();
2863
+ mapped = mapped.filter((r) => r.name.toLowerCase() === targetName);
2864
+ }
2865
+ if (type) {
2866
+ mapped = mapped.filter((r) => r.type === type);
2867
+ }
2868
+ return mapped;
2869
+ }
2870
+ async createDnsRecord(zoneId, record) {
2871
+ let zone = this.zoneCache.get(zoneId);
2872
+ if (!zone) {
2873
+ const zones = await this.listZones();
2874
+ zone = zones.find((z) => z.id === zoneId);
2875
+ if (zone)
2876
+ this.zoneCache.set(zoneId, zone);
2877
+ }
2878
+ const zoneName = zone?.name ?? "";
2879
+ const hetznerName = zoneName ? this.toHetznerName(record.name, zoneName) : record.name;
2880
+ const ttl = record.ttl <= 1 ? 300 : record.ttl;
2881
+ const res = await this.request("/records", {
2882
+ method: "POST",
2883
+ body: JSON.stringify({
2884
+ zone_id: zoneId,
2885
+ type: record.type,
2886
+ name: hetznerName,
2887
+ value: record.content,
2888
+ ttl
2889
+ })
2890
+ });
2891
+ const created = res.record;
2892
+ return {
2893
+ id: created.id,
2894
+ zoneId: created.zone_id,
2895
+ name: zoneName ? this.toFqdnName(created.name, zoneName) : record.name,
2896
+ type: created.type,
2897
+ content: created.value,
2898
+ proxied: false,
2899
+ ttl: created.ttl
2900
+ };
2901
+ }
2902
+ async updateDnsRecord(zoneId, recordId, record) {
2903
+ let zone = this.zoneCache.get(zoneId);
2904
+ if (!zone) {
2905
+ const zones = await this.listZones();
2906
+ zone = zones.find((z) => z.id === zoneId);
2907
+ if (zone)
2908
+ this.zoneCache.set(zoneId, zone);
2909
+ }
2910
+ const zoneName = zone?.name ?? "";
2911
+ const hetznerName = zoneName ? this.toHetznerName(record.name, zoneName) : record.name;
2912
+ const ttl = record.ttl <= 1 ? 300 : record.ttl;
2913
+ const res = await this.request(`/records/${recordId}`, {
2914
+ method: "PUT",
2915
+ body: JSON.stringify({
2916
+ zone_id: zoneId,
2917
+ type: record.type,
2918
+ name: hetznerName,
2919
+ value: record.content,
2920
+ ttl
2921
+ })
2922
+ });
2923
+ const updated = res.record;
2924
+ return {
2925
+ id: updated.id,
2926
+ zoneId: updated.zone_id,
2927
+ name: zoneName ? this.toFqdnName(updated.name, zoneName) : record.name,
2928
+ type: updated.type,
2929
+ content: updated.value,
2930
+ proxied: false,
2931
+ ttl: updated.ttl
2932
+ };
2933
+ }
2934
+ async deleteDnsRecord(zoneId, recordId) {
2935
+ await this.request(`/records/${recordId}`, {
2936
+ method: "DELETE"
2937
+ });
2938
+ }
2939
+ }
2940
+
2941
+ // src/dns/index.ts
2942
+ function isIPv4(ip) {
2943
+ const parts = ip.split(".");
2944
+ if (parts.length !== 4)
2945
+ return false;
2946
+ return parts.every((p) => {
2947
+ const n = Number(p);
2948
+ return !isNaN(n) && n >= 0 && n <= 255 && String(n) === p;
2949
+ });
2950
+ }
2951
+ function isIPv6(ip) {
2952
+ return ip.includes(":") && /^[0-9a-fA-F:]+$/.test(ip);
2953
+ }
2954
+ async function resolveHostIps(target) {
2955
+ const clean = target.trim();
2956
+ if (isIPv4(clean) || isIPv6(clean))
2957
+ return [clean];
2958
+ try {
2959
+ const lookup = await dns.lookup(clean, { all: true });
2960
+ if (lookup && lookup.length > 0) {
2961
+ return lookup.map((l) => l.address);
2962
+ }
2963
+ } catch {}
2964
+ return [clean];
2965
+ }
2966
+ function getRouteDomains(cfg) {
2967
+ if (cfg.dns?.domains && cfg.dns.domains.length > 0) {
2968
+ return cfg.dns.domains;
2969
+ }
2970
+ if (cfg.cloudflare?.domains && cfg.cloudflare.domains.length > 0) {
2971
+ return cfg.cloudflare.domains;
2972
+ }
2973
+ const domains = new Set;
2974
+ for (const svc of cfg.services) {
2975
+ for (const route of svc.routes) {
2976
+ for (const host of route.hosts) {
2977
+ const d = (host.split(":")[0] ?? "").trim().toLowerCase();
2978
+ if (d)
2979
+ domains.add(d);
2980
+ }
2981
+ }
2982
+ }
2983
+ for (const acc of cfg.accessories) {
2984
+ for (const route of acc.routes) {
2985
+ for (const host of route.hosts) {
2986
+ const d = (host.split(":")[0] ?? "").trim().toLowerCase();
2987
+ if (d)
2988
+ domains.add(d);
2989
+ }
2990
+ }
2991
+ }
2992
+ return [...domains];
2993
+ }
2994
+ function createDnsProvider(config) {
2995
+ switch (config.provider) {
2996
+ case "cloudflare":
2997
+ return new CloudflareClient(config.apiToken);
2998
+ case "hetzner":
2999
+ return new HetznerDnsClient(config.apiToken);
3000
+ default:
3001
+ throw new EpdError(`Unsupported DNS provider: ${String(config.provider)}`, "Supported providers: cloudflare, hetzner");
3002
+ }
3003
+ }
3004
+ async function syncDns(cfg, opts = {}) {
3005
+ let provider;
3006
+ if (opts.provider) {
3007
+ provider = opts.provider;
3008
+ } else if (opts.client) {
3009
+ provider = opts.client;
3010
+ } else if (cfg.dns?.enabled && cfg.dns.apiToken) {
3011
+ provider = createDnsProvider(cfg.dns);
3012
+ } else if (cfg.cloudflare) {
3013
+ const token = cfg.cloudflare.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
3014
+ if (!token) {
3015
+ 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
+ }
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
+ };
3241
+ }
3242
+ async deleteServer(id) {
3243
+ await this.request(`/servers/${id}`, {
3244
+ method: "DELETE"
3245
+ });
3246
+ }
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
+ }));
3264
+ }
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
+ }));
3275
+ }
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
+ }));
3284
+ }
3285
+ async getAction(id) {
3286
+ const res = await this.request(`/actions/${id}`);
3287
+ return res.action;
3288
+ }
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);
3299
+ }
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;
3308
+ }
3309
+ await sleep(2000);
3310
+ }
3311
+ throw new EpdError(`Timed out waiting for Hetzner server ${serverId} to become running`);
3312
+ }
3313
+ }
3314
+
3315
+ // src/hetzner/resolve.ts
3316
+ async function resolveDynamicHosts(cfg, env = {}, clientOverride) {
3317
+ let needsHetzner = Boolean(cfg.hetzner);
3318
+ for (const s of cfg.services) {
3319
+ if (s.hetzner)
3320
+ needsHetzner = true;
3321
+ for (const h of s.hosts) {
3322
+ if (h.startsWith("hetzner:"))
3323
+ needsHetzner = true;
3324
+ }
3325
+ }
3326
+ for (const a of cfg.accessories) {
3327
+ if (a.host.startsWith("hetzner:"))
3328
+ needsHetzner = true;
3329
+ }
3330
+ if (!needsHetzner)
3331
+ return;
3332
+ const token = cfg.hetzner?.apiToken || env.HETZNER_API_TOKEN || env.HCLOUD_TOKEN || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN;
3333
+ if (!token && !clientOverride) {
3334
+ 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
+ }
3336
+ const client = clientOverride ?? new HetznerCloudClient(token);
3337
+ const serverCache = new Map;
3338
+ const resolveServerIp = async (target) => {
3339
+ const cached = serverCache.get(target);
3340
+ if (cached)
3341
+ return cached;
3342
+ const server = await client.getServer(target);
3343
+ if (!server) {
3344
+ throw new EpdError(`Hetzner server "${target}" not found in your Hetzner Cloud project`);
3345
+ }
3346
+ const ip = server.publicNet.ipv4.ip;
3347
+ if (!ip) {
3348
+ throw new EpdError(`Hetzner server "${target}" does not have a public IPv4 address`);
3349
+ }
3350
+ serverCache.set(target, ip);
3351
+ return ip;
3352
+ };
3353
+ const resolveLabelSelector = async (selector) => {
3354
+ const servers = await client.listServers({ labelSelector: selector });
3355
+ if (!servers.length) {
3356
+ throw new EpdError(`No Hetzner servers matched label selector "${selector}"`);
3357
+ }
3358
+ const ips = [];
3359
+ for (const s of servers) {
3360
+ if (s.publicNet.ipv4.ip) {
3361
+ serverCache.set(s.name, s.publicNet.ipv4.ip);
3362
+ ips.push(s.publicNet.ipv4.ip);
3363
+ }
3364
+ }
3365
+ if (!ips.length) {
3366
+ throw new EpdError(`Matched Hetzner servers for "${selector}" have no public IPv4 addresses`);
3367
+ }
3368
+ return ips;
3369
+ };
3370
+ for (const s of cfg.services) {
3371
+ const newHosts = [];
3372
+ if (s.hetzner) {
3373
+ if (s.hetzner.server) {
3374
+ const ip = await resolveServerIp(s.hetzner.server);
3375
+ newHosts.push(ip);
3376
+ }
3377
+ if (s.hetzner.labelSelector) {
3378
+ const ips = await resolveLabelSelector(s.hetzner.labelSelector);
3379
+ newHosts.push(...ips);
3380
+ }
3381
+ }
3382
+ for (const h of s.hosts) {
3383
+ if (h.startsWith("hetzner:")) {
3384
+ const rest = h.slice("hetzner:".length);
3385
+ if (rest.startsWith("label:")) {
3386
+ const selector = rest.slice("label:".length);
3387
+ const ips = await resolveLabelSelector(selector);
3388
+ newHosts.push(...ips);
3389
+ } else {
3390
+ const nameOrId = rest.startsWith("name:") ? rest.slice("name:".length) : rest;
3391
+ const ip = await resolveServerIp(nameOrId);
3392
+ newHosts.push(ip);
3393
+ }
3394
+ } else {
3395
+ newHosts.push(h);
3396
+ }
3397
+ }
3398
+ s.hosts = [...new Set(newHosts)];
3399
+ }
3400
+ for (const a of cfg.accessories) {
3401
+ if (a.host.startsWith("hetzner:")) {
3402
+ const rest = a.host.slice("hetzner:".length);
3403
+ const nameOrId = rest.startsWith("name:") ? rest.slice("name:".length) : rest;
3404
+ a.host = await resolveServerIp(nameOrId);
3405
+ }
3406
+ }
3407
+ }
3408
+
2558
3409
  // src/deploy/deploy.ts
2559
3410
  async function deploy(loaded, opts = {}) {
2560
3411
  const { config: cfg, env } = loaded;
3412
+ await resolveDynamicHosts(cfg, env);
2561
3413
  const started = Date.now();
2562
3414
  const services = selectServices(cfg, opts.onlyServices);
2563
3415
  const targetHosts = selectHosts(cfg, services, opts.onlyHosts);
@@ -2609,6 +3461,13 @@ async function deploy(loaded, opts = {}) {
2609
3461
  });
2610
3462
  }
2611
3463
  });
3464
+ if (cfg.dns?.enabled && cfg.dns.autoSync || cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
3465
+ try {
3466
+ await syncDns(cfg, { log: true });
3467
+ } catch (e) {
3468
+ log.warn(`DNS sync: ${e instanceof Error ? e.message : String(e)}`);
3469
+ }
3470
+ }
2612
3471
  if (!opts.skipHooks && cfg.hooks.postDeploy)
2613
3472
  await hook(cfg, "post_deploy", cfg.hooks.postDeploy, version);
2614
3473
  log.ok(`Deployed ${cfg.name} ${version} in ${dur(Date.now() - started)}`);
@@ -2868,6 +3727,7 @@ Options
2868
3727
  async run(ctx) {
2869
3728
  const loaded = ctx.load();
2870
3729
  const cfg = loaded.config;
3730
+ await resolveDynamicHosts(cfg, loaded.env);
2871
3731
  const only = ctx.values.host;
2872
3732
  const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
2873
3733
  const hosts = names.map((h) => host(h, cfg.ssh));
@@ -2891,6 +3751,13 @@ Options
2891
3751
  log.step("Starting the proxy");
2892
3752
  await pool(proxyHosts(cfg).filter((h) => names.includes(h)).map((h) => host(h, cfg.ssh)), 4, (host) => ensureProxy(host, cfg, { secrets: loaded.env, force: true }));
2893
3753
  }
3754
+ if (cfg.dns?.enabled && cfg.dns.autoSync || cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
3755
+ try {
3756
+ await syncDns(cfg, { log: true });
3757
+ } catch (e) {
3758
+ log.warn(`DNS sync: ${e instanceof Error ? e.message : String(e)}`);
3759
+ }
3760
+ }
2894
3761
  log.ok("servers are ready");
2895
3762
  if (ctx.values["skip-deploy"]) {
2896
3763
  log.info(`run ${c.cyan("epd deploy")} when you are ready`);
@@ -3044,7 +3911,8 @@ each server answers on.
3044
3911
  Options
3045
3912
  --json Machine readable output`,
3046
3913
  async run(ctx) {
3047
- const { config: cfg } = ctx.load();
3914
+ const { config: cfg, env } = ctx.load();
3915
+ await resolveDynamicHosts(cfg, env);
3048
3916
  const names = allHosts(cfg);
3049
3917
  const proxied = new Set(proxyHosts(cfg));
3050
3918
  const report = await pool(names, 8, async (name) => {
@@ -3139,7 +4007,8 @@ Options
3139
4007
  --grep <text> Only lines containing this
3140
4008
  --since <time> docker --since value, e.g. 10m`,
3141
4009
  async run(ctx) {
3142
- const { config: cfg } = ctx.load();
4010
+ const { config: cfg, env } = ctx.load();
4011
+ await resolveDynamicHosts(cfg, env);
3143
4012
  const lines = String(ctx.values.lines ?? "100");
3144
4013
  const service = ctx.values.service;
3145
4014
  const accessory = ctx.values.accessory;
@@ -3238,7 +4107,8 @@ Examples
3238
4107
  epd exec --reuse -i -- sh
3239
4108
  epd exec --accessory db -i -- psql -U blog`,
3240
4109
  async run(ctx) {
3241
- const { config: cfg } = ctx.load();
4110
+ const { config: cfg, env } = ctx.load();
4111
+ await resolveDynamicHosts(cfg, env);
3242
4112
  const command = ctx.positionals.join(" ").trim();
3243
4113
  if (!command)
3244
4114
  throw new EpdError("nothing to run", "epd exec -- <command>");
@@ -3550,7 +4420,8 @@ var lock = {
3550
4420
  epd takes a lock on every server while deploying so two deploys cannot overlap.
3551
4421
  If a deploy was killed halfway, release it by hand.`,
3552
4422
  async run(ctx) {
3553
- const { config: cfg } = ctx.load();
4423
+ const { config: cfg, env } = ctx.load();
4424
+ await resolveDynamicHosts(cfg, env);
3554
4425
  const hosts = allHosts(cfg).map((h) => host(h, cfg.ssh));
3555
4426
  const sub = ctx.positionals[0] ?? "status";
3556
4427
  if (sub === "release") {
@@ -3581,7 +4452,8 @@ Options
3581
4452
  --keep-data Leave ${"{remote_root}"}/apps/<app> in place (releases, env files)
3582
4453
  --host <ip> Only this host`,
3583
4454
  async run(ctx) {
3584
- const { config: cfg } = ctx.load();
4455
+ const { config: cfg, env } = ctx.load();
4456
+ await resolveDynamicHosts(cfg, env);
3585
4457
  const only = ctx.values.host;
3586
4458
  const names = allHosts(cfg).filter((h) => !only?.length || only.includes(h));
3587
4459
  if (!ctx.values.yes) {
@@ -3736,6 +4608,475 @@ Options
3736
4608
  }
3737
4609
  };
3738
4610
 
4611
+ // src/commands/cloudflare.ts
4612
+ var cloudflare = {
4613
+ name: "cloudflare",
4614
+ aliases: ["cf"],
4615
+ summary: "Manage Cloudflare DNS records for application domains",
4616
+ options: {
4617
+ "dry-run": { type: "boolean" },
4618
+ proxied: { type: "boolean" },
4619
+ "no-proxied": { type: "boolean" }
4620
+ },
4621
+ help: () => `${c.bold("epd cloudflare")} \u2014 Cloudflare automation and DNS management
4622
+
4623
+ Commands
4624
+ epd cloudflare dns [sync] Sync domain A/AAAA records to target server IPs
4625
+ epd cloudflare dns status Show current Cloudflare DNS status for app domains
4626
+
4627
+ Options
4628
+ --dry-run Preview DNS changes without applying them
4629
+ --proxied Force proxied mode (orange cloud)
4630
+ --no-proxied Force DNS-only mode (gray cloud)
4631
+ -c, --config <file> Path to epd.yml
4632
+ -d, --destination <d> Overlay epd.<d>.yml
4633
+
4634
+ Environment
4635
+ CLOUDFLARE_API_TOKEN Cloudflare API Token with Zone.DNS edit permissions
4636
+ CLOUDFLARE_ZONE_ID Optional Zone ID override`,
4637
+ async run(ctx) {
4638
+ const loaded = ctx.load();
4639
+ const cfg = loaded.config;
4640
+ const sub = ctx.positionals[0] || "dns";
4641
+ 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;
4643
+ 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}");
4646
+ }
4647
+ const client = new CloudflareClient(token);
4648
+ const domains = getRouteDomains(cfg);
4649
+ if (!domains.length) {
4650
+ log.warn("No domains found in service routes. Add domains to your routes or configure cloudflare.domains in epd.yml.");
4651
+ return;
4652
+ }
4653
+ const routedHosts = new Set;
4654
+ for (const svc of cfg.services) {
4655
+ if (svc.routes.length) {
4656
+ for (const h of svc.hosts)
4657
+ routedHosts.add(h);
4658
+ }
4659
+ }
4660
+ const ips = new Set;
4661
+ for (const h of routedHosts) {
4662
+ const resolved = await resolveHostIps(h);
4663
+ for (const ip of resolved)
4664
+ ips.add(ip);
4665
+ }
4666
+ if (sub === "status" || action === "status") {
4667
+ log.step(`Checking Cloudflare DNS status for ${c.bold(cfg.name)} (${domains.length} domain(s))`);
4668
+ console.log(`
4669
+ ${c.bold("Configured Server IPs:")} ${[...ips].join(", ") || "none"}`);
4670
+ for (const domain of domains) {
4671
+ try {
4672
+ const zone = await client.findZoneForDomain(domain, cfg.cloudflare?.zoneId);
4673
+ const records = await client.listDnsRecords(zone.id, domain);
4674
+ console.log(`
4675
+ ${c.bold(domain)} (Zone: ${zone.name} [${zone.id}])`);
4676
+ if (!records.length) {
4677
+ console.log(` ${c.yellow("! No DNS records found for this domain")}`);
4678
+ } else {
4679
+ for (const r of records) {
4680
+ const matchesServer = ips.has(r.content);
4681
+ const statusTag = matchesServer ? c.green("\u2713 points to server") : c.yellow("! points elsewhere");
4682
+ const proxyTag = r.proxied ? c.cyan("[proxied (orange cloud)]") : c.gray("[DNS only]");
4683
+ console.log(` \u2022 ${r.type.padEnd(4)} ${r.content.padEnd(20)} ${proxyTag.padEnd(24)} ${statusTag}`);
4684
+ }
4685
+ }
4686
+ } catch (e) {
4687
+ console.log(`
4688
+ ${c.bold(domain)}: ${c.red(e instanceof Error ? e.message : String(e))}`);
4689
+ }
4690
+ }
4691
+ console.log("");
4692
+ return;
4693
+ }
4694
+ let proxied = undefined;
4695
+ if (ctx.values.proxied === true)
4696
+ proxied = true;
4697
+ if (ctx.values["no-proxied"] === true || ctx.values.proxied === false)
4698
+ proxied = false;
4699
+ const dryRun = Boolean(ctx.values["dry-run"]);
4700
+ if (dryRun)
4701
+ log.step("Previewing Cloudflare DNS changes (dry-run)");
4702
+ const results = await syncDns(cfg, {
4703
+ dryRun,
4704
+ log: true,
4705
+ client,
4706
+ proxied
4707
+ });
4708
+ const created = results.filter((r) => r.action === "created").length;
4709
+ const updated = results.filter((r) => r.action === "updated").length;
4710
+ const unchanged = results.filter((r) => r.action === "unchanged").length;
4711
+ log.ok(`DNS sync finished: ${created} created, ${updated} updated, ${unchanged} unchanged`);
4712
+ }
4713
+ };
4714
+
4715
+ // src/commands/dns.ts
4716
+ var dns3 = {
4717
+ name: "dns",
4718
+ summary: "Manage DNS records across Cloudflare, Hetzner, or custom providers",
4719
+ options: {
4720
+ "dry-run": { type: "boolean" },
4721
+ proxied: { type: "boolean" },
4722
+ "no-proxied": { type: "boolean" },
4723
+ provider: { type: "string" }
4724
+ },
4725
+ help: () => `${c.bold("epd dns")} \u2014 Unified DNS management (Cloudflare & Hetzner DNS)
4726
+
4727
+ Commands
4728
+ epd dns [sync] Sync domain A/AAAA records to target server IPs
4729
+ epd dns status Show current DNS status for app domains
4730
+
4731
+ Options
4732
+ --dry-run Preview DNS changes without applying them
4733
+ --proxied Force proxied mode (Cloudflare only)
4734
+ --no-proxied Force DNS-only mode
4735
+ --provider <cloudflare|hetzner> Override DNS provider
4736
+ -c, --config <file> Path to epd.yml
4737
+ -d, --destination <d> Overlay epd.<d>.yml
4738
+
4739
+ Environment
4740
+ CLOUDFLARE_API_TOKEN Cloudflare API Token
4741
+ HETZNER_DNS_API_TOKEN Hetzner DNS API Token (Auth-API-Token)`,
4742
+ async run(ctx) {
4743
+ const loaded = ctx.load();
4744
+ const cfg = loaded.config;
4745
+ await resolveDynamicHosts(cfg, loaded.env);
4746
+ const sub = ctx.positionals[0] || "sync";
4747
+ const action = ctx.positionals[1] || (sub === "status" ? "status" : "sync");
4748
+ 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
+ let provider;
4750
+ if (providerName === "cloudflare") {
4751
+ const token = cfg.dns?.apiToken || cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
4752
+ 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.");
4754
+ }
4755
+ provider = new CloudflareClient(token);
4756
+ } else if (providerName === "hetzner") {
4757
+ const token = cfg.dns?.apiToken || process.env.HETZNER_DNS_API_TOKEN || process.env.HETZNER_DNS_TOKEN;
4758
+ if (!token) {
4759
+ throw new EpdError("Hetzner DNS API token is missing", "Set HETZNER_DNS_API_TOKEN in environment or add it to epd.yml under dns.api_token.");
4760
+ }
4761
+ provider = new HetznerDnsClient(token);
4762
+ } else {
4763
+ throw new EpdError(`Unknown DNS provider: ${providerName}`, "Supported providers: cloudflare, hetzner");
4764
+ }
4765
+ const domains = getRouteDomains(cfg);
4766
+ if (!domains.length) {
4767
+ log.warn("No domains found in service routes. Add domains to your routes or configure dns.domains in epd.yml.");
4768
+ return;
4769
+ }
4770
+ const routedHosts = new Set;
4771
+ for (const svc of cfg.services) {
4772
+ if (svc.routes.length) {
4773
+ for (const h of svc.hosts)
4774
+ routedHosts.add(h);
4775
+ }
4776
+ }
4777
+ const ips = new Set;
4778
+ for (const h of routedHosts) {
4779
+ const resolved = await resolveHostIps(h);
4780
+ for (const ip of resolved)
4781
+ ips.add(ip);
4782
+ }
4783
+ if (sub === "status" || action === "status") {
4784
+ log.step(`Checking ${c.bold(provider.name)} DNS status for ${c.bold(cfg.name)} (${domains.length} domain(s))`);
4785
+ console.log(`
4786
+ ${c.bold("Configured Server IPs:")} ${[...ips].join(", ") || "none"}`);
4787
+ const explicitZoneId = cfg.dns?.zoneId ?? cfg.cloudflare?.zoneId;
4788
+ for (const domain of domains) {
4789
+ try {
4790
+ const zone = await provider.findZoneForDomain(domain, explicitZoneId);
4791
+ const records = await provider.listDnsRecords(zone.id, domain);
4792
+ console.log(`
4793
+ ${c.bold(domain)} (Zone: ${zone.name} [${zone.id}])`);
4794
+ if (!records.length) {
4795
+ console.log(` ${c.yellow("! No DNS records found for this domain")}`);
4796
+ } else {
4797
+ for (const r of records) {
4798
+ const matchesServer = ips.has(r.content);
4799
+ const statusTag = matchesServer ? c.green("\u2713 points to server") : c.yellow("! points elsewhere");
4800
+ const proxyTag = r.proxied ? c.cyan("[proxied (CDN)]") : c.gray("[DNS only]");
4801
+ console.log(` \u2022 ${r.type.padEnd(4)} ${r.content.padEnd(20)} ${proxyTag.padEnd(18)} ${statusTag}`);
4802
+ }
4803
+ }
4804
+ } catch (e) {
4805
+ console.log(`
4806
+ ${c.bold(domain)}: ${c.red(e instanceof Error ? e.message : String(e))}`);
4807
+ }
4808
+ }
4809
+ console.log("");
4810
+ return;
4811
+ }
4812
+ let proxied = undefined;
4813
+ if (ctx.values.proxied === true)
4814
+ proxied = true;
4815
+ if (ctx.values["no-proxied"] === true || ctx.values.proxied === false)
4816
+ proxied = false;
4817
+ const dryRun = Boolean(ctx.values["dry-run"]);
4818
+ if (dryRun)
4819
+ log.step(`Previewing ${provider.name} DNS changes (dry-run)`);
4820
+ const results = await syncDns(cfg, {
4821
+ dryRun,
4822
+ log: true,
4823
+ provider,
4824
+ proxied
4825
+ });
4826
+ const created = results.filter((r) => r.action === "created").length;
4827
+ const updated = results.filter((r) => r.action === "updated").length;
4828
+ const unchanged = results.filter((r) => r.action === "unchanged").length;
4829
+ log.ok(`DNS sync finished: ${created} created, ${updated} updated, ${unchanged} unchanged`);
4830
+ }
4831
+ };
4832
+
4833
+ // src/commands/hetzner.ts
4834
+ var hetzner = {
4835
+ name: "hetzner",
4836
+ aliases: ["hcloud"],
4837
+ summary: "Manage Hetzner Cloud servers and deploy targets",
4838
+ options: {
4839
+ type: { type: "string" },
4840
+ location: { type: "string" },
4841
+ image: { type: "string" },
4842
+ "ssh-key": { type: "string" },
4843
+ label: { type: "string", multiple: true },
4844
+ setup: { type: "boolean" },
4845
+ yes: { type: "boolean", short: "y" }
4846
+ },
4847
+ help: () => `${c.bold("epd hetzner")} \u2014 Hetzner Cloud server management and provisioning
4848
+
4849
+ Commands
4850
+ epd hetzner list List all servers in your Hetzner Cloud project
4851
+ epd hetzner create <name> Create and provision a new server
4852
+ epd hetzner delete <name|id> Delete a cloud server
4853
+ epd hetzner types List available server types and pricing
4854
+ epd hetzner locations List available datacenter locations
4855
+
4856
+ Create options
4857
+ --type <type> Server type (default: cx22)
4858
+ --location <loc> Location: fsn1 (Falkenstein), nbg1, hel1, ash, hil (default: fsn1)
4859
+ --image <os> OS image (default: ubuntu-24.04)
4860
+ --ssh-key <name|id> Hetzner SSH key name or ID to attach
4861
+ --label <k=v> Labels to attach to the server (repeatable)
4862
+ --setup Automatically run "epd setup" once the server is ready
4863
+
4864
+ Environment
4865
+ HETZNER_API_TOKEN / HCLOUD_TOKEN Hetzner Cloud API token (Read/Write)`,
4866
+ async run(ctx) {
4867
+ let token;
4868
+ let projectName;
4869
+ try {
4870
+ const loaded = ctx.load();
4871
+ token = loaded.config.hetzner?.apiToken || loaded.env.HETZNER_API_TOKEN || loaded.env.HCLOUD_TOKEN;
4872
+ projectName = loaded.config.name;
4873
+ } catch {}
4874
+ token = token || process.env.HETZNER_API_TOKEN || process.env.HCLOUD_TOKEN;
4875
+ 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.");
4877
+ }
4878
+ const client = new HetznerCloudClient(token);
4879
+ const sub = ctx.positionals[0] || "list";
4880
+ if (sub === "list" || sub === "ls") {
4881
+ log.step("Fetching Hetzner Cloud servers...");
4882
+ const servers = await client.listServers();
4883
+ if (!servers.length) {
4884
+ log.info("No servers found in this Hetzner Cloud project.");
4885
+ console.log(`
4886
+ Run ${c.cyan("epd hetzner create <name>")} to spin up a new server.
4887
+ `);
4888
+ return;
4889
+ }
4890
+ console.log(`
4891
+ ${c.bold("HETZNER CLOUD SERVERS")} (${servers.length})
4892
+ `);
4893
+ const headers = ["ID", "NAME", "STATUS", "IPV4", "TYPE", "DATACENTER", "LABELS"];
4894
+ const rows = servers.map((s) => {
4895
+ let statusStr = s.status;
4896
+ if (s.status === "running")
4897
+ statusStr = c.green(s.status);
4898
+ else if (s.status === "initializing" || s.status === "starting")
4899
+ statusStr = c.yellow(s.status);
4900
+ else
4901
+ statusStr = c.gray(s.status);
4902
+ const labelsStr = Object.entries(s.labels).map(([k, v]) => `${k}=${v}`).join(",");
4903
+ return [
4904
+ String(s.id),
4905
+ s.name,
4906
+ statusStr,
4907
+ s.publicNet.ipv4.ip || c.gray("none"),
4908
+ s.serverType.name,
4909
+ s.datacenter.name,
4910
+ labelsStr ? c.gray(labelsStr) : "-"
4911
+ ];
4912
+ });
4913
+ const colWidths = headers.map((h, i) => {
4914
+ const rowMax = rows.reduce((max, r) => Math.max(max, (r[i] || "").replace(/\x1b\[[0-9;]*m/g, "").length), 0);
4915
+ return Math.max(h.length, rowMax);
4916
+ });
4917
+ const headerLine = headers.map((h, i) => c.bold(h.padEnd(colWidths[i]))).join(" ");
4918
+ console.log(headerLine);
4919
+ console.log(c.gray("\u2014".repeat(headerLine.length)));
4920
+ for (const r of rows) {
4921
+ const line = r.map((cell, i) => {
4922
+ const rawLen = cell.replace(/\x1b\[[0-9;]*m/g, "").length;
4923
+ const pad = " ".repeat(Math.max(0, colWidths[i] - rawLen));
4924
+ return cell + pad;
4925
+ }).join(" ");
4926
+ console.log(line);
4927
+ }
4928
+ console.log("");
4929
+ return;
4930
+ }
4931
+ if (sub === "create") {
4932
+ const serverName = ctx.positionals[1];
4933
+ if (!serverName) {
4934
+ throw new EpdError("Server name is required", "Usage: epd hetzner create <name> [--type cx22] [--location fsn1] [--image ubuntu-24.04]");
4935
+ }
4936
+ const serverType = ctx.values.type || "cx22";
4937
+ const location = ctx.values.location || "fsn1";
4938
+ const image = ctx.values.image || "ubuntu-24.04";
4939
+ const labels = {
4940
+ managed_by: "epd"
4941
+ };
4942
+ if (projectName)
4943
+ labels.app = projectName;
4944
+ const userLabels = ctx.values.label ?? [];
4945
+ for (const l of userLabels) {
4946
+ const [k, v] = l.split("=");
4947
+ if (k && v !== undefined)
4948
+ labels[k] = v;
4949
+ }
4950
+ let sshKeys = undefined;
4951
+ const explicitKey = ctx.values["ssh-key"];
4952
+ if (explicitKey) {
4953
+ sshKeys = [explicitKey];
4954
+ } else {
4955
+ try {
4956
+ const keys = await client.listSshKeys();
4957
+ if (keys.length > 0) {
4958
+ sshKeys = keys.map((k) => k.id);
4959
+ log.info(`Attaching ${keys.length} Hetzner project SSH key(s): ${keys.map((k) => k.name).join(", ")}`);
4960
+ }
4961
+ } catch {}
4962
+ }
4963
+ log.step(`Creating Hetzner server ${c.bold(serverName)} (${serverType}, ${location}, ${image})...`);
4964
+ const res = await client.createServer({
4965
+ name: serverName,
4966
+ serverType,
4967
+ location,
4968
+ image,
4969
+ sshKeys,
4970
+ labels
4971
+ });
4972
+ log.step(`Waiting for server ${c.bold(serverName)} to become active...`);
4973
+ const readyServer = await client.waitForServerRunning(res.server.id);
4974
+ const ip = readyServer.publicNet.ipv4.ip;
4975
+ log.ok(`Server created successfully!`);
4976
+ console.log(`
4977
+ ${c.bold("Name:")} ${readyServer.name}`);
4978
+ console.log(` ${c.bold("ID:")} ${readyServer.id}`);
4979
+ console.log(` ${c.bold("Public IPv4:")} ${c.green(c.bold(ip))}`);
4980
+ if (readyServer.publicNet.ipv6?.ip) {
4981
+ console.log(` ${c.bold("Public IPv6:")} ${readyServer.publicNet.ipv6.ip}`);
4982
+ }
4983
+ console.log(` ${c.bold("Location:")} ${readyServer.datacenter.location.city} (${readyServer.datacenter.name})`);
4984
+ if (res.rootPassword) {
4985
+ console.log(` ${c.bold("Root Password:")} ${c.yellow(res.rootPassword)}`);
4986
+ }
4987
+ console.log("");
4988
+ if (ctx.values.setup) {
4989
+ log.step(`Running "epd setup" on newly created server ${ip}...`);
4990
+ await setup.run({
4991
+ ...ctx,
4992
+ values: {
4993
+ ...ctx.values,
4994
+ host: [ip]
4995
+ }
4996
+ });
4997
+ } else {
4998
+ log.info(`To deploy to this server, add its IP to your epd.yml:`);
4999
+ console.log(` ${c.cyan(`servers: [${ip}]`)} or ${c.cyan(`servers: [hetzner:${readyServer.name}]`)}
5000
+ `);
5001
+ log.info(`Then run: ${c.cyan(`epd setup --host ${ip}`)}
5002
+ `);
5003
+ }
5004
+ return;
5005
+ }
5006
+ if (sub === "delete" || sub === "rm") {
5007
+ const target = ctx.positionals[1];
5008
+ if (!target) {
5009
+ throw new EpdError("Server name or ID is required", "Usage: epd hetzner delete <name|id>");
5010
+ }
5011
+ const server = await client.getServer(target);
5012
+ if (!server) {
5013
+ throw new EpdError(`Hetzner server "${target}" not found.`);
5014
+ }
5015
+ const confirm = Boolean(ctx.values.yes);
5016
+ if (!confirm) {
5017
+ 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
+ for await (const line of console) {
5019
+ if (!line.trim().toLowerCase().startsWith("y")) {
5020
+ log.info("Aborted.");
5021
+ return;
5022
+ }
5023
+ break;
5024
+ }
5025
+ }
5026
+ log.step(`Deleting server ${c.bold(server.name)} [ID: ${server.id}]...`);
5027
+ await client.deleteServer(server.id);
5028
+ log.ok(`Server ${server.name} deleted.`);
5029
+ return;
5030
+ }
5031
+ if (sub === "types") {
5032
+ log.step("Fetching available Hetzner server types...");
5033
+ const types = await client.listServerTypes();
5034
+ console.log(`
5035
+ ${c.bold("AVAILABLE HETZNER SERVER TYPES")}
5036
+ `);
5037
+ const headers = ["NAME", "VCPU", "RAM (GB)", "DISK (GB)", "ARCH", "EUR/MO"];
5038
+ const rows = types.map((t) => {
5039
+ const price = t.prices?.[0]?.priceMonthly?.net ? `\u20AC${Number(t.prices[0].priceMonthly.net).toFixed(2)}` : "-";
5040
+ return [t.name, String(t.cores), String(t.memory), `${t.disk} GB`, t.architecture, price];
5041
+ });
5042
+ const colWidths = headers.map((h, i) => {
5043
+ const rowMax = rows.reduce((max, r) => Math.max(max, (r[i] || "").length), 0);
5044
+ return Math.max(h.length, rowMax);
5045
+ });
5046
+ const headerLine = headers.map((h, i) => c.bold(h.padEnd(colWidths[i]))).join(" ");
5047
+ console.log(headerLine);
5048
+ console.log(c.gray("\u2014".repeat(headerLine.length)));
5049
+ for (const r of rows) {
5050
+ console.log(r.map((cell, i) => cell.padEnd(colWidths[i])).join(" "));
5051
+ }
5052
+ console.log("");
5053
+ return;
5054
+ }
5055
+ if (sub === "locations") {
5056
+ log.step("Fetching Hetzner locations...");
5057
+ const locations = await client.listLocations();
5058
+ console.log(`
5059
+ ${c.bold("HETZNER DATACENTER LOCATIONS")}
5060
+ `);
5061
+ const headers = ["CODE", "CITY", "COUNTRY", "ZONE"];
5062
+ const rows = locations.map((l) => [l.name, l.city, l.country, l.networkZone]);
5063
+ const colWidths = headers.map((h, i) => {
5064
+ const rowMax = rows.reduce((max, r) => Math.max(max, (r[i] || "").length), 0);
5065
+ return Math.max(h.length, rowMax);
5066
+ });
5067
+ const headerLine = headers.map((h, i) => c.bold(h.padEnd(colWidths[i]))).join(" ");
5068
+ console.log(headerLine);
5069
+ console.log(c.gray("\u2014".repeat(headerLine.length)));
5070
+ for (const r of rows) {
5071
+ console.log(r.map((cell, i) => cell.padEnd(colWidths[i])).join(" "));
5072
+ }
5073
+ console.log("");
5074
+ return;
5075
+ }
5076
+ throw new EpdError(`Unknown hetzner subcommand "${sub}"`, "Available subcommands: list, create, delete, types, locations");
5077
+ }
5078
+ };
5079
+
3739
5080
  // src/commands/index.ts
3740
5081
  var commands = [
3741
5082
  init,
@@ -3751,11 +5092,14 @@ var commands = [
3751
5092
  config,
3752
5093
  lock,
3753
5094
  remove,
3754
- dockerCommand
5095
+ dockerCommand,
5096
+ cloudflare,
5097
+ dns3,
5098
+ hetzner
3755
5099
  ];
3756
5100
 
3757
5101
  // src/cli.ts
3758
- var VERSION = "0.1.1";
5102
+ var VERSION = "0.3.0";
3759
5103
  var USAGE = `${c.bold("epd")} \u2014 Easy Project Deployer ${c.gray(`v${VERSION}`)}
3760
5104
 
3761
5105
  ${c.bold("Usage")}