@fabioplunser/epd 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -328,6 +328,27 @@ proxy:
328
328
 
329
329
  The listed variables are read from your environment and passed to Traefik.
330
330
 
331
+ ### Cloudflare DNS Automation
332
+
333
+ `epd` can automatically manage Cloudflare DNS `A` and `AAAA` records for your application domains, pointing them to all configured servers with Cloudflare CDN/proxy (orange cloud) or DNS-only (gray cloud):
334
+
335
+ ```yaml
336
+ cloudflare:
337
+ api_token: ${CLOUDFLARE_API_TOKEN}
338
+ # zone_id is optional; auto-discovered from your domain name
339
+ proxied: true # default: true (orange cloud CDN/DDoS)
340
+ ttl: 1 # 1 = Auto
341
+ auto_sync: true # sync on setup and deploy
342
+ ```
343
+
344
+ You can also inspect or sync DNS manually with the CLI:
345
+ ```bash
346
+ epd cloudflare dns status # Compare current Cloudflare DNS vs server IPs
347
+ epd cloudflare dns sync # Sync A/AAAA records to Cloudflare
348
+ epd cloudflare dns sync --dry-run
349
+ epd cloudflare dns sync --no-proxied # DNS-only (gray cloud)
350
+ ```
351
+
331
352
  ---
332
353
 
333
354
  ## Without Docker: process mode
@@ -384,6 +405,7 @@ they need Docker on their host.
384
405
  | `epd config` | The resolved configuration; `--traefik` for the proxy files |
385
406
  | `epd docker-command` | Print the exact `docker run` (or pm2) commands epd uses (including accessories) |
386
407
  | `epd lock status\|release` | The deploy lock |
408
+ | `epd cloudflare dns [sync\|status]` | Cloudflare DNS record management and auto-sync |
387
409
  | `epd remove` | Stop this app and delete its files from the servers |
388
410
 
389
411
  Global flags: `-c/--config`, `-d/--destination`, `-v/--verbose`.
package/dist/cli.js CHANGED
@@ -434,7 +434,8 @@ var TOP_LEVEL_KEYS = [
434
434
  "labels",
435
435
  "drain",
436
436
  "stop_timeout",
437
- "docker_options"
437
+ "docker_options",
438
+ "cloudflare"
438
439
  ];
439
440
  function normalize(raw, configPath, root, destination) {
440
441
  checkKeys(raw, TOP_LEVEL_KEYS, "epd.yml");
@@ -664,6 +665,24 @@ function normalize(raw, configPath, root, destination) {
664
665
  const strategy = asString(raw.strategy, "epd.yml.strategy", "rolling");
665
666
  if (strategy !== "rolling" && strategy !== "parallel")
666
667
  fail("epd.yml.strategy", 'expected "rolling" or "parallel"');
668
+ let cloudflare = undefined;
669
+ if (raw.cloudflare !== undefined && raw.cloudflare !== false) {
670
+ if (raw.cloudflare !== true && (typeof raw.cloudflare !== "object" || Array.isArray(raw.cloudflare))) {
671
+ fail("epd.yml.cloudflare", "expected a mapping or boolean");
672
+ }
673
+ const cfRaw = raw.cloudflare === true ? {} : raw.cloudflare;
674
+ checkKeys(cfRaw, ["enabled", "api_token", "zone_id", "proxied", "ttl", "auto_sync", "domains"], "epd.yml.cloudflare");
675
+ 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 || "";
676
+ cloudflare = {
677
+ enabled: asBool(cfRaw.enabled, "epd.yml.cloudflare.enabled", true),
678
+ apiToken,
679
+ zoneId: cfRaw.zone_id ? asString(cfRaw.zone_id, "epd.yml.cloudflare.zone_id") : process.env.CLOUDFLARE_ZONE_ID || undefined,
680
+ proxied: asBool(cfRaw.proxied, "epd.yml.cloudflare.proxied", true),
681
+ ttl: asNumber(cfRaw.ttl, "epd.yml.cloudflare.ttl", 1),
682
+ autoSync: asBool(cfRaw.auto_sync, "epd.yml.cloudflare.auto_sync", true),
683
+ domains: cfRaw.domains ? asList(cfRaw.domains, "epd.yml.cloudflare.domains") : undefined
684
+ };
685
+ }
667
686
  const cfg = {
668
687
  name,
669
688
  mode,
@@ -703,6 +722,7 @@ function normalize(raw, configPath, root, destination) {
703
722
  onFailure: hooksRaw.on_failure ? asString(hooksRaw.on_failure, "epd.yml.hooks.on_failure") : undefined
704
723
  },
705
724
  process: processCfg,
725
+ cloudflare,
706
726
  portBase: asNumber(raw.port_base, "epd.yml.port_base", 20000 + hash32(name) % 117 * 256),
707
727
  strategy,
708
728
  keepReleases: asNumber(raw.keep_releases, "epd.yml.keep_releases", 5),
@@ -2555,6 +2575,214 @@ ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | tail -n +$(( ${cfg.keepReleases} + 1
2555
2575
  done`, { ...asUser, allowFailure: true });
2556
2576
  }
2557
2577
 
2578
+ // src/core/cloudflare.ts
2579
+ import dns from "dns/promises";
2580
+ class CloudflareClient {
2581
+ apiToken;
2582
+ baseUrl;
2583
+ constructor(apiToken, baseUrl = "https://api.cloudflare.com/client/v4") {
2584
+ this.apiToken = apiToken;
2585
+ this.baseUrl = baseUrl.replace(/\/$/, "");
2586
+ }
2587
+ async request(path, options = {}) {
2588
+ const url = `${this.baseUrl}${path}`;
2589
+ const headers = {
2590
+ Authorization: `Bearer ${this.apiToken}`,
2591
+ "Content-Type": "application/json",
2592
+ ...options.headers
2593
+ };
2594
+ const res = await fetch(url, { ...options, headers });
2595
+ const data = await res.json();
2596
+ if (!res.ok || data.success === false) {
2597
+ const msg = data.errors?.[0]?.message || `HTTP ${res.status} ${res.statusText}`;
2598
+ throw new EpdError(`Cloudflare API error: ${msg}`);
2599
+ }
2600
+ return data.result;
2601
+ }
2602
+ async listZones(name) {
2603
+ const query = name ? `?name=${encodeURIComponent(name)}&status=active` : "?status=active";
2604
+ return this.request(`/zones${query}`);
2605
+ }
2606
+ async findZoneForDomain(domain, explicitZoneId) {
2607
+ if (explicitZoneId) {
2608
+ return { id: explicitZoneId, name: domain, status: "active" };
2609
+ }
2610
+ const cleanDomain = domain.replace(/^\*\./, "").toLowerCase();
2611
+ const parts = cleanDomain.split(".");
2612
+ for (let i = 0;i < parts.length - 1; i++) {
2613
+ const candidate = parts.slice(i).join(".");
2614
+ const zones = await this.listZones(candidate);
2615
+ const match = zones.find((z) => z.name.toLowerCase() === candidate);
2616
+ if (match)
2617
+ return match;
2618
+ }
2619
+ 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.`);
2620
+ }
2621
+ async listDnsRecords(zoneId, name, type) {
2622
+ const params = new URLSearchParams;
2623
+ params.set("per_page", "100");
2624
+ if (name)
2625
+ params.set("name", name);
2626
+ if (type)
2627
+ params.set("type", type);
2628
+ return this.request(`/zones/${zoneId}/dns_records?${params.toString()}`);
2629
+ }
2630
+ async createDnsRecord(zoneId, record) {
2631
+ return this.request(`/zones/${zoneId}/dns_records`, {
2632
+ method: "POST",
2633
+ body: JSON.stringify(record)
2634
+ });
2635
+ }
2636
+ async updateDnsRecord(zoneId, recordId, record) {
2637
+ return this.request(`/zones/${zoneId}/dns_records/${recordId}`, {
2638
+ method: "PUT",
2639
+ body: JSON.stringify(record)
2640
+ });
2641
+ }
2642
+ }
2643
+ function isIPv4(ip) {
2644
+ const parts = ip.split(".");
2645
+ if (parts.length !== 4)
2646
+ return false;
2647
+ return parts.every((p) => {
2648
+ const n = Number(p);
2649
+ return !isNaN(n) && n >= 0 && n <= 255 && String(n) === p;
2650
+ });
2651
+ }
2652
+ function isIPv6(ip) {
2653
+ return ip.includes(":") && /^[0-9a-fA-F:]+$/.test(ip);
2654
+ }
2655
+ async function resolveHostIps(target) {
2656
+ const clean = target.trim();
2657
+ if (isIPv4(clean) || isIPv6(clean))
2658
+ return [clean];
2659
+ try {
2660
+ const lookup = await dns.lookup(clean, { all: true });
2661
+ if (lookup && lookup.length > 0) {
2662
+ return lookup.map((l) => l.address);
2663
+ }
2664
+ } catch {}
2665
+ return [clean];
2666
+ }
2667
+ function getRouteDomains(cfg) {
2668
+ if (cfg.cloudflare?.domains && cfg.cloudflare.domains.length > 0) {
2669
+ return cfg.cloudflare.domains;
2670
+ }
2671
+ const domains = new Set;
2672
+ for (const svc of cfg.services) {
2673
+ for (const route of svc.routes) {
2674
+ for (const host of route.hosts) {
2675
+ const d = (host.split(":")[0] ?? "").trim().toLowerCase();
2676
+ if (d)
2677
+ domains.add(d);
2678
+ }
2679
+ }
2680
+ }
2681
+ for (const acc of cfg.accessories) {
2682
+ for (const route of acc.routes) {
2683
+ for (const host of route.hosts) {
2684
+ const d = (host.split(":")[0] ?? "").trim().toLowerCase();
2685
+ if (d)
2686
+ domains.add(d);
2687
+ }
2688
+ }
2689
+ }
2690
+ return [...domains];
2691
+ }
2692
+ async function syncDns(cfg, opts = {}) {
2693
+ const token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
2694
+ if (!token) {
2695
+ throw new EpdError("Cloudflare API token is missing", "Set CLOUDFLARE_API_TOKEN in your environment or specify api_token in epd.yml under cloudflare.");
2696
+ }
2697
+ const client = opts.client ?? new CloudflareClient(token);
2698
+ const domains = getRouteDomains(cfg);
2699
+ if (!domains.length) {
2700
+ if (opts.log)
2701
+ log.step("Cloudflare DNS: no domain names found in routes to sync");
2702
+ return [];
2703
+ }
2704
+ const routedHosts = new Set;
2705
+ for (const svc of cfg.services) {
2706
+ if (svc.routes.length) {
2707
+ for (const h of svc.hosts)
2708
+ routedHosts.add(h);
2709
+ }
2710
+ }
2711
+ const ips = new Set;
2712
+ for (const h of routedHosts) {
2713
+ const resolved = await resolveHostIps(h);
2714
+ for (const ip of resolved) {
2715
+ if (isIPv4(ip) || isIPv6(ip))
2716
+ ips.add(ip);
2717
+ }
2718
+ }
2719
+ if (!ips.size) {
2720
+ if (opts.log)
2721
+ log.step("Cloudflare DNS: no server IP addresses resolved to sync");
2722
+ return [];
2723
+ }
2724
+ const isProxied = opts.proxied ?? cfg.cloudflare?.proxied ?? true;
2725
+ const ttl = cfg.cloudflare?.ttl ?? 1;
2726
+ const results = [];
2727
+ if (opts.log) {
2728
+ log.step(`Cloudflare: syncing ${c.bold(domains.length.toString())} domain(s) across ${c.bold(ips.size.toString())} server IP(s)`);
2729
+ }
2730
+ const zoneCache = new Map;
2731
+ for (const domain of domains) {
2732
+ let zone = zoneCache.get(domain);
2733
+ if (!zone) {
2734
+ zone = await client.findZoneForDomain(domain, cfg.cloudflare?.zoneId);
2735
+ zoneCache.set(domain, zone);
2736
+ }
2737
+ const existingRecords = await client.listDnsRecords(zone.id, domain);
2738
+ for (const ip of ips) {
2739
+ const type = isIPv6(ip) ? "AAAA" : "A";
2740
+ const existing = existingRecords.find((r) => r.name.toLowerCase() === domain.toLowerCase() && r.type === type && r.content === ip);
2741
+ if (existing) {
2742
+ if (existing.proxied !== isProxied || ttl !== 1 && existing.ttl !== ttl) {
2743
+ if (!opts.dryRun) {
2744
+ await client.updateDnsRecord(zone.id, existing.id, {
2745
+ name: domain,
2746
+ type,
2747
+ content: ip,
2748
+ proxied: isProxied,
2749
+ ttl,
2750
+ comment: `Managed by epd (${cfg.name})`
2751
+ });
2752
+ }
2753
+ results.push({ domain, ip, type, action: "updated", recordId: existing.id, proxied: isProxied });
2754
+ if (opts.log) {
2755
+ log.ok(`Cloudflare: updated ${type} ${c.bold(domain)} \u2192 ${ip} (${isProxied ? "proxied" : "DNS only"})`);
2756
+ }
2757
+ } else {
2758
+ results.push({ domain, ip, type, action: "unchanged", recordId: existing.id, proxied: isProxied });
2759
+ if (opts.log) {
2760
+ log.debug(`${type} ${domain} \u2192 ${ip} (${isProxied ? "proxied" : "DNS only"}) already in sync`);
2761
+ }
2762
+ }
2763
+ } else {
2764
+ let recordId;
2765
+ if (!opts.dryRun) {
2766
+ const created = await client.createDnsRecord(zone.id, {
2767
+ name: domain,
2768
+ type,
2769
+ content: ip,
2770
+ proxied: isProxied,
2771
+ ttl,
2772
+ comment: `Managed by epd (${cfg.name})`
2773
+ });
2774
+ recordId = created.id;
2775
+ }
2776
+ results.push({ domain, ip, type, action: "created", recordId, proxied: isProxied });
2777
+ if (opts.log) {
2778
+ log.ok(`Cloudflare: created ${type} ${c.bold(domain)} \u2192 ${ip} (${isProxied ? "proxied" : "DNS only"})${opts.dryRun ? " [dry-run]" : ""}`);
2779
+ }
2780
+ }
2781
+ }
2782
+ }
2783
+ return results;
2784
+ }
2785
+
2558
2786
  // src/deploy/deploy.ts
2559
2787
  async function deploy(loaded, opts = {}) {
2560
2788
  const { config: cfg, env } = loaded;
@@ -2609,6 +2837,13 @@ async function deploy(loaded, opts = {}) {
2609
2837
  });
2610
2838
  }
2611
2839
  });
2840
+ if (cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
2841
+ try {
2842
+ await syncDns(cfg, { log: true });
2843
+ } catch (e) {
2844
+ log.warn(`Cloudflare DNS sync: ${e instanceof Error ? e.message : String(e)}`);
2845
+ }
2846
+ }
2612
2847
  if (!opts.skipHooks && cfg.hooks.postDeploy)
2613
2848
  await hook(cfg, "post_deploy", cfg.hooks.postDeploy, version);
2614
2849
  log.ok(`Deployed ${cfg.name} ${version} in ${dur(Date.now() - started)}`);
@@ -2891,6 +3126,13 @@ Options
2891
3126
  log.step("Starting the proxy");
2892
3127
  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
3128
  }
3129
+ if (cfg.cloudflare?.enabled && cfg.cloudflare.autoSync) {
3130
+ try {
3131
+ await syncDns(cfg, { log: true });
3132
+ } catch (e) {
3133
+ log.warn(`Cloudflare DNS sync: ${e instanceof Error ? e.message : String(e)}`);
3134
+ }
3135
+ }
2894
3136
  log.ok("servers are ready");
2895
3137
  if (ctx.values["skip-deploy"]) {
2896
3138
  log.info(`run ${c.cyan("epd deploy")} when you are ready`);
@@ -3736,6 +3978,110 @@ Options
3736
3978
  }
3737
3979
  };
3738
3980
 
3981
+ // src/commands/cloudflare.ts
3982
+ var cloudflare = {
3983
+ name: "cloudflare",
3984
+ aliases: ["cf"],
3985
+ summary: "Manage Cloudflare DNS records for application domains",
3986
+ options: {
3987
+ "dry-run": { type: "boolean" },
3988
+ proxied: { type: "boolean" },
3989
+ "no-proxied": { type: "boolean" }
3990
+ },
3991
+ help: () => `${c.bold("epd cloudflare")} \u2014 Cloudflare automation and DNS management
3992
+
3993
+ Commands
3994
+ epd cloudflare dns [sync] Sync domain A/AAAA records to target server IPs
3995
+ epd cloudflare dns status Show current Cloudflare DNS status for app domains
3996
+
3997
+ Options
3998
+ --dry-run Preview DNS changes without applying them
3999
+ --proxied Force proxied mode (orange cloud)
4000
+ --no-proxied Force DNS-only mode (gray cloud)
4001
+ -c, --config <file> Path to epd.yml
4002
+ -d, --destination <d> Overlay epd.<d>.yml
4003
+
4004
+ Environment
4005
+ CLOUDFLARE_API_TOKEN Cloudflare API Token with Zone.DNS edit permissions
4006
+ CLOUDFLARE_ZONE_ID Optional Zone ID override`,
4007
+ async run(ctx) {
4008
+ const loaded = ctx.load();
4009
+ const cfg = loaded.config;
4010
+ const sub = ctx.positionals[0] || "dns";
4011
+ const action = ctx.positionals[1] || (sub === "status" ? "status" : "sync");
4012
+ const token = cfg.cloudflare?.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_DNS_API_TOKEN;
4013
+ if (!token) {
4014
+ throw new EpdError("Cloudflare API token is missing", `Set CLOUDFLARE_API_TOKEN in your environment or add it to epd.yml:
4015
+ ` + " cloudflare:\n api_token: ${CLOUDFLARE_API_TOKEN}");
4016
+ }
4017
+ const client = new CloudflareClient(token);
4018
+ const domains = getRouteDomains(cfg);
4019
+ if (!domains.length) {
4020
+ log.warn("No domains found in service routes. Add domains to your routes or configure cloudflare.domains in epd.yml.");
4021
+ return;
4022
+ }
4023
+ const routedHosts = new Set;
4024
+ for (const svc of cfg.services) {
4025
+ if (svc.routes.length) {
4026
+ for (const h of svc.hosts)
4027
+ routedHosts.add(h);
4028
+ }
4029
+ }
4030
+ const ips = new Set;
4031
+ for (const h of routedHosts) {
4032
+ const resolved = await resolveHostIps(h);
4033
+ for (const ip of resolved)
4034
+ ips.add(ip);
4035
+ }
4036
+ if (sub === "status" || action === "status") {
4037
+ log.step(`Checking Cloudflare DNS status for ${c.bold(cfg.name)} (${domains.length} domain(s))`);
4038
+ console.log(`
4039
+ ${c.bold("Configured Server IPs:")} ${[...ips].join(", ") || "none"}`);
4040
+ for (const domain of domains) {
4041
+ try {
4042
+ const zone = await client.findZoneForDomain(domain, cfg.cloudflare?.zoneId);
4043
+ const records = await client.listDnsRecords(zone.id, domain);
4044
+ console.log(`
4045
+ ${c.bold(domain)} (Zone: ${zone.name} [${zone.id}])`);
4046
+ if (!records.length) {
4047
+ console.log(` ${c.yellow("! No DNS records found for this domain")}`);
4048
+ } else {
4049
+ for (const r of records) {
4050
+ const matchesServer = ips.has(r.content);
4051
+ const statusTag = matchesServer ? c.green("\u2713 points to server") : c.yellow("! points elsewhere");
4052
+ const proxyTag = r.proxied ? c.cyan("[proxied (orange cloud)]") : c.gray("[DNS only]");
4053
+ console.log(` \u2022 ${r.type.padEnd(4)} ${r.content.padEnd(20)} ${proxyTag.padEnd(24)} ${statusTag}`);
4054
+ }
4055
+ }
4056
+ } catch (e) {
4057
+ console.log(`
4058
+ ${c.bold(domain)}: ${c.red(e instanceof Error ? e.message : String(e))}`);
4059
+ }
4060
+ }
4061
+ console.log("");
4062
+ return;
4063
+ }
4064
+ let proxied = undefined;
4065
+ if (ctx.values.proxied === true)
4066
+ proxied = true;
4067
+ if (ctx.values["no-proxied"] === true || ctx.values.proxied === false)
4068
+ proxied = false;
4069
+ const dryRun = Boolean(ctx.values["dry-run"]);
4070
+ if (dryRun)
4071
+ log.step("Previewing Cloudflare DNS changes (dry-run)");
4072
+ const results = await syncDns(cfg, {
4073
+ dryRun,
4074
+ log: true,
4075
+ client,
4076
+ proxied
4077
+ });
4078
+ const created = results.filter((r) => r.action === "created").length;
4079
+ const updated = results.filter((r) => r.action === "updated").length;
4080
+ const unchanged = results.filter((r) => r.action === "unchanged").length;
4081
+ log.ok(`DNS sync finished: ${created} created, ${updated} updated, ${unchanged} unchanged`);
4082
+ }
4083
+ };
4084
+
3739
4085
  // src/commands/index.ts
3740
4086
  var commands = [
3741
4087
  init,
@@ -3751,11 +4097,12 @@ var commands = [
3751
4097
  config,
3752
4098
  lock,
3753
4099
  remove,
3754
- dockerCommand
4100
+ dockerCommand,
4101
+ cloudflare
3755
4102
  ];
3756
4103
 
3757
4104
  // src/cli.ts
3758
- var VERSION = "0.1.1";
4105
+ var VERSION = "0.2.0";
3759
4106
  var USAGE = `${c.bold("epd")} \u2014 Easy Project Deployer ${c.gray(`v${VERSION}`)}
3760
4107
 
3761
4108
  ${c.bold("Usage")}
package/docs/guide.md CHANGED
@@ -328,6 +328,30 @@ proxy:
328
328
  dns_env: [CF_DNS_API_TOKEN]
329
329
  ```
330
330
 
331
+ ### Cloudflare Automations & DNS Auto-Sync
332
+ `epd` can automatically keep Cloudflare DNS records in sync with your servers on every deploy and setup:
333
+
334
+ ```yaml
335
+ cloudflare:
336
+ api_token: ${CLOUDFLARE_API_TOKEN}
337
+ # zone_id is optional; auto-detected from domain if omitted
338
+ proxied: true # default: true (orange cloud CDN/DDoS), or false (gray cloud / DNS-only)
339
+ ttl: 1 # default: 1 (auto)
340
+ auto_sync: true # default: true (auto sync on deploy and setup)
341
+ # domains: [custom.com] # optional; defaults to all domains in routes
342
+ ```
343
+
344
+ CLI commands:
345
+ ```bash
346
+ # Check status vs servers without modifying
347
+ epd cloudflare dns status
348
+
349
+ # Synchronize DNS records
350
+ epd cloudflare dns sync
351
+ epd cloudflare dns sync --dry-run
352
+ epd cloudflare dns sync --no-proxied
353
+ ```
354
+
331
355
  ---
332
356
 
333
357
  ## 9. Secrets & Environment Management
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabioplunser/epd",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Easy Project Deployer — deploy any project to one or many servers with Docker or PM2, fronted by Traefik.",
5
5
  "type": "module",
6
6
  "author": "Fabio Plünser",