easy-devops 1.3.6 → 1.4.1

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.
Files changed (78) hide show
  1. package/README.md +1 -0
  2. package/dist/ui/assets/index-Bu7af-Kj.css +1 -0
  3. package/dist/ui/assets/index-gndgYe3K.js +532 -0
  4. package/dist/ui/assets/socket-Bv0wCEgi.js +65 -0
  5. package/dist/ui/index.html +2 -2
  6. package/install.bat +14 -7
  7. package/package.json +2 -2
  8. package/src/cli/index.js +8 -0
  9. package/src/cli/managers/domain-manager.js +37 -6
  10. package/src/cli/managers/nginx-manager.js +14 -5
  11. package/src/cli/managers/node-manager.js +19 -13
  12. package/src/cli/managers/ssl-manager.js +89 -26
  13. package/src/cli/menu.js +8 -2
  14. package/src/cli/menus/cleanup.js +4 -2
  15. package/src/cli/menus/dashboard.js +22 -15
  16. package/src/cli/menus/hub.js +402 -0
  17. package/src/cli/menus/runtime.js +12 -0
  18. package/src/cli/menus/service.js +80 -13
  19. package/src/cli/menus/settings.js +46 -12
  20. package/src/cli/menus/uninstall.js +13 -5
  21. package/src/cli/menus/update.js +24 -14
  22. package/src/cli/ui/page.js +123 -0
  23. package/src/core/cert-operations.js +34 -4
  24. package/src/core/cert-reader.js +67 -22
  25. package/src/core/cert-renewal.js +65 -9
  26. package/src/core/cert-suggest.js +120 -0
  27. package/src/core/cleanup.js +221 -1
  28. package/src/core/cloudflare-ips.js +161 -0
  29. package/src/core/daemon/ipc.js +1 -1
  30. package/src/core/daemon/lock.js +296 -9
  31. package/src/core/daemon/run.js +12 -0
  32. package/src/core/daemon/stateFile.js +128 -0
  33. package/src/core/dashboardProcess.js +134 -6
  34. package/src/core/db.js +26 -1
  35. package/src/core/deploy/apps.js +36 -62
  36. package/src/core/deploy/deployKey.js +331 -0
  37. package/src/core/deploy/domainLink.js +280 -23
  38. package/src/core/deploy/engine.js +382 -63
  39. package/src/core/deploy/ezfile.js +496 -29
  40. package/src/core/deploy/githubApi.js +100 -13
  41. package/src/core/deploy/hubCommands.js +158 -18
  42. package/src/core/deploy/status.js +28 -1
  43. package/src/core/domains-db.js +1 -0
  44. package/src/core/hub/agent.js +238 -32
  45. package/src/core/hub/deployProgress.js +411 -0
  46. package/src/core/hubConnect.js +205 -0
  47. package/src/core/hubPermissions.js +48 -10
  48. package/src/core/jobs/bus.js +1 -1
  49. package/src/core/jobs/owner.js +268 -6
  50. package/src/core/nginx-conf-generator.js +124 -19
  51. package/src/core/notifications/claim.js +26 -3
  52. package/src/core/permissions.js +277 -59
  53. package/src/core/platform.js +73 -2
  54. package/src/core/runner.js +96 -40
  55. package/src/core/service/dataDir.js +34 -9
  56. package/src/core/service/index.js +203 -24
  57. package/src/core/service/runtime.js +40 -3
  58. package/src/core/service/windowsService.js +452 -107
  59. package/src/core/service/winsw.js +44 -3
  60. package/src/core/ssl/preflight.js +548 -0
  61. package/src/core/ssl/progress.js +196 -0
  62. package/src/core/ssl-issuer.js +502 -148
  63. package/src/core/validators.js +24 -0
  64. package/src/dashboard/controllers/authController.js +12 -5
  65. package/src/dashboard/controllers/deploymentsController.js +76 -11
  66. package/src/dashboard/controllers/domainsController.js +35 -1
  67. package/src/dashboard/controllers/hubController.js +4 -3
  68. package/src/dashboard/controllers/settingsController.js +73 -68
  69. package/src/dashboard/controllers/sslController.js +135 -15
  70. package/src/dashboard/public/js/app.js +42 -7
  71. package/src/dashboard/routes/deployments.js +2 -0
  72. package/src/dashboard/routes/domains.js +1 -0
  73. package/src/dashboard/server.js +42 -7
  74. package/src/dashboard/socketManager.js +19 -25
  75. package/src/dashboard/views/partials/settings-panel.ejs +29 -10
  76. package/dist/ui/assets/index-BUpPxWmp.css +0 -1
  77. package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
  78. package/dist/ui/assets/socket-4tfdap-e.js +0 -65
@@ -54,7 +54,9 @@ import {
54
54
  issueCertificate,
55
55
  prepareDomainForHttpChallenge,
56
56
  reloadNginx,
57
+ verifyServedCertificate,
57
58
  } from './ssl-issuer.js';
59
+ import { createSslProgress, isValidOpId, newOpId } from './ssl/progress.js';
58
60
 
59
61
  /** Renew this many days before expiry unless the setting says otherwise. */
60
62
  export const DEFAULT_AUTO_RENEW_DAYS = 7;
@@ -197,6 +199,10 @@ export function failureReason(result) {
197
199
  return String(cause).split('\n')[0].trim();
198
200
  }
199
201
 
202
+ function firstLine(value) {
203
+ return String(value ?? '').split('\n')[0].trim();
204
+ }
205
+
200
206
  /**
201
207
  * Renews one certificate, keeping the names it already covers, and reloads
202
208
  * nginx when nginx was left running so the new certificate is actually served.
@@ -215,7 +221,11 @@ export function failureReason(result) {
215
221
  * @returns {Promise<Object>}
216
222
  */
217
223
  export async function renewCertificate(domainName, options = {}) {
218
- const { email = null, mode = null, unattended = false, deps = {} } = options;
224
+ const {
225
+ email = null, mode = null, unattended = false, deps = {},
226
+ opId: rawOpId = null, onEvent = null, onProgress = null,
227
+ behindCloudflare = false,
228
+ } = options;
219
229
  const {
220
230
  issue = issueCertificate,
221
231
  prepare = prepareDomainForHttpChallenge,
@@ -223,8 +233,16 @@ export async function renewCertificate(domainName, options = {}) {
223
233
  nginxStatus = getStatus,
224
234
  describe = describeCertificate,
225
235
  lookupDomain = findDomain,
236
+ verify = verifyServedCertificate,
226
237
  } = deps;
227
238
 
239
+ const opId = isValidOpId(rawOpId) ? rawOpId : newOpId();
240
+ const progress = createSslProgress({
241
+ opId, domain: domainName, onEvent, onProgress,
242
+ ...(deps.progress ?? {}),
243
+ });
244
+ const report = (stage, status, detail) => progress.report(stage, status, detail);
245
+
228
246
  const config = loadConfig();
229
247
  const info = await describe(domainName);
230
248
 
@@ -287,6 +305,11 @@ export async function renewCertificate(domainName, options = {}) {
287
305
  www: info.www,
288
306
  validationMethod: 'http',
289
307
  email: email || config.acmeEmail,
308
+ opId,
309
+ onEvent,
310
+ onProgress,
311
+ // This caller reports the nginx stages itself, so they appear exactly once.
312
+ manageNginx: false,
290
313
  ...(chosenMode ? { mode: chosenMode } : {}),
291
314
  });
292
315
 
@@ -294,14 +317,46 @@ export async function renewCertificate(domainName, options = {}) {
294
317
  // Proxy mode leaves it running with the old one in memory.
295
318
  let nginxReloaded = null;
296
319
  let reloadDetail = null;
297
- if (result?.success && result.mode === CHALLENGE_MODES.PROXY) {
298
- try {
299
- const reloaded = await reload();
300
- nginxReloaded = Boolean(reloaded?.ok);
301
- if (!nginxReloaded) reloadDetail = reloaded?.output ?? null;
302
- } catch (err) {
303
- nginxReloaded = false;
304
- reloadDetail = err.message;
320
+ let httpsVerified = null;
321
+
322
+ if (result?.success) {
323
+ if (result.mode === CHALLENGE_MODES.PROXY) {
324
+ report('nginx config test', 'running');
325
+ try {
326
+ const reloaded = await reload();
327
+ nginxReloaded = Boolean(reloaded?.ok);
328
+ if (!nginxReloaded) reloadDetail = reloaded?.output ?? null;
329
+ } catch (err) {
330
+ nginxReloaded = false;
331
+ reloadDetail = err.message;
332
+ }
333
+ const detail = nginxReloaded ? undefined : (firstLine(reloadDetail) || 'nginx did not reload');
334
+ report('nginx config test', nginxReloaded ? 'ok' : 'failed', detail);
335
+ report('nginx reload', 'running');
336
+ report('nginx reload', nginxReloaded ? 'ok' : 'failed', detail);
337
+ } else if (result.mode === 'dns-01') {
338
+ report('nginx config test', 'skipped', 'DNS-01 leaves nginx untouched');
339
+ report('nginx reload', 'skipped', 'DNS-01 leaves nginx untouched');
340
+ } else {
341
+ report('nginx config test', 'skipped', 'standalone mode restarted nginx');
342
+ report('nginx reload', 'skipped', 'standalone mode restarted nginx');
343
+ }
344
+
345
+ const proxied = Boolean(behindCloudflare || result.preflight?.proxied);
346
+ if (proxied) {
347
+ report('https verified', 'skipped', "served by Cloudflare's edge");
348
+ } else if (!result.certPath) {
349
+ report('https verified', 'skipped', 'no certificate file to compare');
350
+ } else {
351
+ report('https verified', 'running');
352
+ try {
353
+ const checked = await verify(domainName, result.certPath);
354
+ httpsVerified = Boolean(checked?.ok);
355
+ report('https verified', checked?.ok ? 'ok' : 'failed', checked?.ok ? undefined : checked?.message);
356
+ } catch (err) {
357
+ httpsVerified = false;
358
+ report('https verified', 'failed', firstLine(err.message));
359
+ }
305
360
  }
306
361
  }
307
362
 
@@ -313,6 +368,7 @@ export async function renewCertificate(domainName, options = {}) {
313
368
  configRegenerated: Boolean(result?.configRegenerated || prepared?.regenerated),
314
369
  nginxReloaded,
315
370
  reloadDetail,
371
+ httpsVerified,
316
372
  };
317
373
  }
318
374
 
@@ -0,0 +1,120 @@
1
+ /**
2
+ * core/cert-suggest.js
3
+ *
4
+ * Finds an existing certificate that can serve a domain, so a domain added
5
+ * without SSL can be pointed at it in one click instead of having the operator
6
+ * retype a path that is almost always `<sslDir>/<name>/fullchain.pem`.
7
+ *
8
+ * Matching is deliberately conservative — a wrong suggestion writes the wrong
9
+ * certificate onto a live site:
10
+ *
11
+ * 1. exact the certificate directory is named after the domain, which is
12
+ * how every certificate issued here is stored;
13
+ * 2. san one of the certificate's names is the domain itself (a cert
14
+ * issued for `example.com` that lists `api.example.com`);
15
+ * 3. wildcard a name like `*.example.com` covers `api.example.com` — but
16
+ * only one label, because `*.example.com` does not cover
17
+ * `a.b.example.com` (RFC 6125), and offering it would produce a
18
+ * site that fails certificate validation.
19
+ *
20
+ * Exact beats SAN beats wildcard; among wildcards the most specific suffix
21
+ * wins. Nothing is suggested from a certificate that could not be read.
22
+ */
23
+
24
+ import { loadConfig } from './config.js';
25
+ import { listAllCerts } from './cert-reader.js';
26
+ import { describeCertificate } from './cert-renewal.js';
27
+ import { getDefaultCertPaths } from './nginx-conf-generator.js';
28
+
29
+ const MATCH_RANK = { exact: 0, san: 1, wildcard: 2 };
30
+
31
+ /** Lowercase, trim, drop trailing dots. `*.` is meaningful and kept. */
32
+ export function normalizeForMatch(value) {
33
+ return String(value ?? '').trim().toLowerCase().replace(/\.+$/, '');
34
+ }
35
+
36
+ /** True when a certificate name like `*.example.com` covers `api.example.com`. */
37
+ export function wildcardCovers(pattern, domain) {
38
+ const p = normalizeForMatch(pattern);
39
+ const d = normalizeForMatch(domain);
40
+ if (!p.startsWith('*.') || !d) return false;
41
+
42
+ const suffix = p.slice(2);
43
+ if (!suffix || !d.endsWith(`.${suffix}`)) return false;
44
+
45
+ const label = d.slice(0, -(suffix.length + 1));
46
+ return label.length > 0 && !label.includes('.');
47
+ }
48
+
49
+ /**
50
+ * @param {string} domainName The bare domain (a leading `*.` is ignored)
51
+ * @param {Object} [opts]
52
+ * @param {string} [opts.sslDir] Certificates directory (defaults to the setting)
53
+ * @returns {Promise<{ found: false } | {
54
+ * found: true,
55
+ * match: 'exact'|'san'|'wildcard',
56
+ * certificate: {
57
+ * domain: string, names: string[], certPath: string, keyPath: string,
58
+ * expiry: string|null, daysLeft: number|null, status: string
59
+ * }
60
+ * }>}
61
+ */
62
+ export async function findCertificateForDomain(domainName, { sslDir } = {}) {
63
+ const dir = sslDir ?? loadConfig().sslDir;
64
+ const domain = normalizeForMatch(String(domainName ?? '').replace(/^\*\./, ''));
65
+ if (!domain) return { found: false };
66
+
67
+ // A folder whose certificate cannot be read has no usable paths to offer.
68
+ const certs = (await listAllCerts({ sslDir: dir })).filter((c) => c.status !== 'error');
69
+ if (certs.length === 0) return { found: false };
70
+
71
+ const candidates = [];
72
+ for (const cert of certs) {
73
+ if (normalizeForMatch(cert.domain) === domain) {
74
+ candidates.push({ match: 'exact', cert, specificity: 0 });
75
+ }
76
+ }
77
+
78
+ if (candidates.length === 0) {
79
+ for (const cert of certs) {
80
+ const info = await describeCertificate(cert.domain, { sslDir: dir });
81
+ const names = (info.names ?? []).map(normalizeForMatch);
82
+
83
+ if (names.includes(domain)) {
84
+ candidates.push({ match: 'san', cert, specificity: 0 });
85
+ continue;
86
+ }
87
+ const wildcard = names.find((n) => wildcardCovers(n, domain));
88
+ if (wildcard) {
89
+ candidates.push({ match: 'wildcard', cert, specificity: wildcard.length });
90
+ }
91
+ }
92
+ }
93
+
94
+ if (candidates.length === 0) return { found: false };
95
+
96
+ candidates.sort(
97
+ (a, b) =>
98
+ MATCH_RANK[a.match] - MATCH_RANK[b.match] ||
99
+ b.specificity - a.specificity ||
100
+ a.cert.domain.localeCompare(b.cert.domain)
101
+ );
102
+
103
+ const best = candidates[0];
104
+ const paths = getDefaultCertPaths(best.cert.domain, process.platform, dir);
105
+ const info = await describeCertificate(best.cert.domain, { sslDir: dir });
106
+
107
+ return {
108
+ found: true,
109
+ match: best.match,
110
+ certificate: {
111
+ domain: best.cert.domain,
112
+ names: info.names ?? [best.cert.domain],
113
+ certPath: paths.certPath,
114
+ keyPath: paths.keyPath,
115
+ expiry: best.cert.expiry ?? null,
116
+ daysLeft: best.cert.daysLeft ?? null,
117
+ status: best.cert.status,
118
+ },
119
+ };
120
+ }
@@ -538,6 +538,169 @@ export async function scan({
538
538
 
539
539
  // ─── Applying ────────────────────────────────────────────────────────────────
540
540
 
541
+ /**
542
+ * Normalised form of an absolute path, for comparisons only.
543
+ *
544
+ * Separators are unified so a Windows path cannot dodge a check by being
545
+ * written with forward slashes, and case is ignored on Windows where the
546
+ * filesystem is. Never used to touch the filesystem.
547
+ *
548
+ * @param {string} target
549
+ * @returns {string}
550
+ */
551
+ function normalizeForCompare(target) {
552
+ const forward = path.resolve(target).replace(/\\/g, '/');
553
+ return isWindows ? forward.toLowerCase() : forward;
554
+ }
555
+
556
+ /**
557
+ * True when `target` is one of `roots` or lives inside one.
558
+ *
559
+ * Segments, never string prefixes: `/data-evil` starts with `/data` but is not
560
+ * inside it, and a prefix check would delete it.
561
+ *
562
+ * @param {string} root Real path of the root
563
+ * @param {string} target Already a real path
564
+ * @returns {boolean}
565
+ */
566
+ function isInsideOrEqual(root, target) {
567
+ const base = normalizeForCompare(root).replace(/\/+$/, '');
568
+ const real = normalizeForCompare(target);
569
+ if (!base) return false;
570
+ return real === base || real.startsWith(`${base}/`);
571
+ }
572
+
573
+ /**
574
+ * True when `target` lives strictly INSIDE one of `roots`.
575
+ *
576
+ * Equality is refused on purpose: an item whose real path IS a root is the
577
+ * data directory, the nginx directory or the PM2 home, and `rmSync` with
578
+ * `recursive` on one of those removes everything in it — the database
579
+ * included. Only a path below a root may be deleted.
580
+ *
581
+ * @param {string[]} roots Real paths, as allowedRoots() returns them
582
+ * @param {string} target Already a real path
583
+ * @returns {boolean}
584
+ */
585
+ function isInsideAny(roots, target) {
586
+ const real = normalizeForCompare(target);
587
+
588
+ return roots.some((root) => {
589
+ const base = normalizeForCompare(root).replace(/\/+$/, '');
590
+ if (!base) return false;
591
+ return real !== base && real.startsWith(`${base}/`);
592
+ });
593
+ }
594
+
595
+ /**
596
+ * The directories `apply()` may delete inside.
597
+ *
598
+ * Exactly the places the scan reached, so an item id from anywhere else — a
599
+ * stale report, a hand-edited file, a crafted API payload — cannot become an
600
+ * arbitrary delete. Paths are resolved to their real form here so a symlinked
601
+ * root is compared the same way the item's own real path is.
602
+ *
603
+ * @param {Object} opts
604
+ * @returns {string[]}
605
+ */
606
+ function allowedRoots({ dataDir, config, deps }) {
607
+ const roots = [dataDir];
608
+
609
+ // Windows Server mode writes the service's logs under ProgramData.
610
+ if (isWindows) roots.push(path.join(programDataDir(), 'logs'));
611
+
612
+ if (typeof config?.nginxDir === 'string' && config.nginxDir.trim()) {
613
+ roots.push(config.nginxDir.trim());
614
+ }
615
+
616
+ // PM2's own log directory, for the `pm2 flush` action.
617
+ try {
618
+ const pm2Home = (deps.pm2HomeDir ?? runner.pm2HomeDir)();
619
+ if (pm2Home) roots.push(pm2Home);
620
+ } catch { /* PM2 is not installed */ }
621
+
622
+ return roots
623
+ .filter((root) => typeof root === 'string' && root.length > 0)
624
+ .map((root) => {
625
+ try {
626
+ return fs.realpathSync(root);
627
+ } catch {
628
+ // A root that does not exist cannot contain a file that does; the
629
+ // resolved form keeps the comparison honest all the same.
630
+ return path.resolve(root);
631
+ }
632
+ });
633
+ }
634
+
635
+ /**
636
+ * Whether an item is one of the `<dataDir>.backup-*` directories the scan
637
+ * offers, which sit BESIDE the data directory rather than inside it.
638
+ *
639
+ * Matched by the exact name shape the scanner produces and by an equal parent,
640
+ * never by a parent-directory prefix: a prefix would also admit everything
641
+ * else the user keeps next to the data directory.
642
+ *
643
+ * @param {string} target Already a real path
644
+ * @param {string} dataDir
645
+ * @returns {boolean}
646
+ */
647
+ function isDataDirBackupSibling(target, dataDir) {
648
+ const parent = normalizeForCompare(path.dirname(path.resolve(dataDir)));
649
+ if (normalizeForCompare(path.dirname(target)) !== parent) return false;
650
+
651
+ const prefix = `${path.basename(path.resolve(dataDir))}.backup-`;
652
+ const name = path.basename(target);
653
+ return isWindows ? name.toLowerCase().startsWith(prefix.toLowerCase()) : name.startsWith(prefix);
654
+ }
655
+
656
+ /**
657
+ * Why a path must never be removed, or null when it may be.
658
+ *
659
+ * Being inside a root is not enough. These live inside the very directories
660
+ * the scan reads, and removing any of them breaks the installation rather
661
+ * than reclaiming disk:
662
+ *
663
+ * - the SQLite database and its `-wal` / `-shm` / `.migrated` siblings —
664
+ * inside the data directory, and offered by nothing, but a crafted item id
665
+ * naming one would otherwise pass the containment check;
666
+ * - anything under the configured sslDir (certificates, private keys, the
667
+ * ACME account key), including sslDir itself. The scan never lists these;
668
+ * apply() must refuse them even if it is handed one;
669
+ * - an active nginx config: a `.conf` file anywhere, and from the nginx
670
+ * directory only `.bak` copies (which is the only thing the scan offers
671
+ * there).
672
+ *
673
+ * @param {string} real Already a real path
674
+ * @param {{ dataDir: string, config: Object }} opts
675
+ * @returns {string|null} The reason to refuse, or null
676
+ */
677
+ function protectedReason(real, { dataDir, config }) {
678
+ const name = path.basename(real);
679
+
680
+ // core/db.js keeps its database at <dataDir>/easy-devops.sqlite; the name is
681
+ // matched by prefix so -wal, -shm and .migrated are covered by the same rule.
682
+ if (normalizeForCompare(path.dirname(real)) === normalizeForCompare(dataDir)
683
+ && name.toLowerCase().startsWith('easy-devops.sqlite')) {
684
+ return 'the database and its side files are never removed';
685
+ }
686
+
687
+ const sslDir = typeof config?.sslDir === 'string' ? config.sslDir.trim() : '';
688
+ if (sslDir && isInsideOrEqual(sslDir, real)) {
689
+ return 'certificates and keys under the SSL directory are never removed';
690
+ }
691
+
692
+ if (/\.conf$/i.test(name)) {
693
+ return 'an active nginx config (.conf) is never removed; only .bak copies are';
694
+ }
695
+
696
+ const nginxDir = typeof config?.nginxDir === 'string' ? config.nginxDir.trim() : '';
697
+ if (nginxDir && isInsideOrEqual(nginxDir, real) && !/\.bak$/i.test(name)) {
698
+ return 'only .bak copies may be removed from the nginx directory';
699
+ }
700
+
701
+ return null;
702
+ }
703
+
541
704
  /**
542
705
  * Removes the given items, and nothing else.
543
706
  *
@@ -545,14 +708,41 @@ export async function scan({
545
708
  * logs are flushed rather than deleted, or that a Node version is uninstalled
546
709
  * by its manager.
547
710
  *
711
+ * Before deleting anything by path, the item's REAL path is checked against
712
+ * the directories this scan covers. Ids come from a previous scan, but they
713
+ * travel through a prompt and possibly an HTTP request, so they are re-checked
714
+ * where it matters: a path that is not STRICTLY inside one of those roots —
715
+ * including a symlink inside one that points outside, and including a root
716
+ * itself — is refused and reported, not removed. Strictly, because a root is
717
+ * the data directory, the nginx directory or the PM2 home, and removing one
718
+ * recursively takes everything in it, the database included.
719
+ *
720
+ * Inside a root, the protected set is refused as well: the database and its
721
+ * side files, anything under sslDir, and active nginx configs.
722
+ *
723
+ * The two actions that delete nothing here are unaffected: `pm2 flush` asks
724
+ * PM2, and a Node version is removed by its manager from a version number, so
725
+ * there is no path of ours to confine. The PM2 home is still one of the roots,
726
+ * because that is a directory the scan reads and a future path-based PM2
727
+ * removal must stay inside.
728
+ *
548
729
  * @param {Object} opts
549
730
  * @param {Array<Object>} opts.items From scan()
731
+ * @param {string} [opts.dataDir]
732
+ * @param {Object} [opts.config]
550
733
  * @returns {Promise<{ removed: Array<Object>, failed: Array<Object>, freedBytes: number }>}
551
734
  */
552
- export async function apply({ items = [], log = () => {}, deps = {} } = {}) {
735
+ export async function apply({
736
+ items = [],
737
+ log = () => {},
738
+ deps = {},
739
+ dataDir = getDataDir(),
740
+ config = loadConfig(),
741
+ } = {}) {
553
742
  const exec = deps.run ?? run;
554
743
  const removed = [];
555
744
  const failed = [];
745
+ const roots = allowedRoots({ dataDir, config, deps });
556
746
 
557
747
  for (const item of items) {
558
748
  // Defence in depth: an item the scan marked as keep must not be removable
@@ -583,7 +773,37 @@ export async function apply({ items = [], log = () => {}, deps = {} } = {}) {
583
773
  continue;
584
774
  }
585
775
 
776
+ // The containment check is on the REAL path: a symlink inside a root that
777
+ // points outside it must not become a delete outside it.
778
+ let real;
779
+ try {
780
+ real = fs.realpathSync(item.path);
781
+ } catch (err) {
782
+ failed.push({ ...item, reason: `could not verify the path (${err.code ?? err.message}); nothing was removed` });
783
+ continue;
784
+ }
785
+
786
+ if (!isInsideAny(roots, real) && !isDataDirBackupSibling(real, dataDir)) {
787
+ failed.push({
788
+ ...item,
789
+ reason: 'refused: the path is outside the directories this cleanup covers',
790
+ });
791
+ log(`Refused ${item.path}: outside the directories this cleanup covers`);
792
+ continue;
793
+ }
794
+
795
+ // Inside a root is necessary, not sufficient: the database, the
796
+ // certificate store and live nginx configs live there too.
797
+ const protectedBy = protectedReason(real, { dataDir, config });
798
+ if (protectedBy) {
799
+ failed.push({ ...item, reason: `refused: ${protectedBy}` });
800
+ log(`Refused ${item.path}: ${protectedBy}`);
801
+ continue;
802
+ }
803
+
586
804
  try {
805
+ // Removed by its own path, not the resolved one: a symlink is unlinked,
806
+ // never followed to its target.
587
807
  fs.rmSync(item.path, { recursive: true, force: true });
588
808
  removed.push(item);
589
809
  log(`Removed ${item.path}`);
@@ -0,0 +1,161 @@
1
+ /**
2
+ * core/cloudflare-ips.js
3
+ *
4
+ * Cloudflare's published edge ranges, in ONE refreshable file.
5
+ *
6
+ * These are the addresses a domain may trust as `set_real_ip_from` when it is
7
+ * marked `behindCloudflare`. The list is data, not logic: `scripts/refresh-
8
+ * cloudflare-ips.mjs` fetches https://www.cloudflare.com/ips-v4 and /ips-v6,
9
+ * validates every entry, and rewrites the arrays below (never run it in tests).
10
+ *
11
+ * Keeping it here rather than in the generator means a refresh touches exactly
12
+ * one file and the generator only asks whether an entry is a valid CIDR.
13
+ */
14
+
15
+ import net from 'node:net';
16
+
17
+ /** Where the list comes from. */
18
+ export const SOURCE_URLS = Object.freeze({
19
+ ipv4: 'https://www.cloudflare.com/ips-v4',
20
+ ipv6: 'https://www.cloudflare.com/ips-v6',
21
+ });
22
+
23
+ /** Date the arrays below were last refreshed. Updated by the refresh script. */
24
+ export const LAST_REFRESHED = '2025-01-01';
25
+
26
+ /* BEGIN CLOUDFLARE_IPV4 */
27
+ export const CLOUDFLARE_IPV4 = Object.freeze([
28
+ '173.245.48.0/20',
29
+ '103.21.244.0/22',
30
+ '103.22.200.0/22',
31
+ '103.31.4.0/22',
32
+ '141.101.64.0/18',
33
+ '108.162.192.0/18',
34
+ '190.93.240.0/20',
35
+ '188.114.96.0/20',
36
+ '197.234.240.0/22',
37
+ '198.41.128.0/17',
38
+ '162.158.0.0/15',
39
+ '104.16.0.0/13',
40
+ '104.24.0.0/14',
41
+ '172.64.0.0/13',
42
+ '131.0.72.0/22',
43
+ ]);
44
+ /* END CLOUDFLARE_IPV4 */
45
+
46
+ /* BEGIN CLOUDFLARE_IPV6 */
47
+ export const CLOUDFLARE_IPV6 = Object.freeze([
48
+ '2400:cb00::/32',
49
+ '2606:4700::/32',
50
+ '2803:f800::/32',
51
+ '2405:b500::/32',
52
+ '2405:8100::/32',
53
+ '2a06:98c0::/29',
54
+ '2c0f:f248::/32',
55
+ ]);
56
+ /* END CLOUDFLARE_IPV6 */
57
+
58
+ /** IPv4 + IPv6, in that order. */
59
+ export const CLOUDFLARE_RANGES = Object.freeze([...CLOUDFLARE_IPV4, ...CLOUDFLARE_IPV6]);
60
+
61
+ /**
62
+ * True when `entry` is a syntactically valid CIDR (address + in-range prefix).
63
+ * @param {unknown} entry
64
+ * @returns {boolean}
65
+ */
66
+ export function isValidCidr(entry) {
67
+ if (typeof entry !== 'string' || entry !== entry.trim()) return false;
68
+ const match = /^([^\s/]+)\/(\d{1,3})$/.exec(entry);
69
+ if (!match) return false;
70
+
71
+ const address = match[1];
72
+ const family = net.isIP(address);
73
+ if (family !== 4 && family !== 6) return false;
74
+
75
+ const prefix = Number(match[2]);
76
+ return prefix >= 0 && prefix <= (family === 4 ? 32 : 128);
77
+ }
78
+
79
+ /**
80
+ * Validates a whole list and, when given, that every entry has one family.
81
+ * @param {unknown} list
82
+ * @param {4|6} [family]
83
+ * @returns {{ ok: boolean, invalid: string[] }}
84
+ */
85
+ export function validateCidrList(list, family) {
86
+ if (!Array.isArray(list)) return { ok: false, invalid: ['(not an array)'] };
87
+
88
+ const invalid = [];
89
+ for (const entry of list) {
90
+ if (!isValidCidr(entry)) {
91
+ invalid.push(String(entry));
92
+ continue;
93
+ }
94
+ if (family) {
95
+ const address = entry.slice(0, entry.indexOf('/'));
96
+ if (net.isIP(address) !== family) invalid.push(entry);
97
+ }
98
+ }
99
+
100
+ return { ok: invalid.length === 0, invalid };
101
+ }
102
+
103
+ /**
104
+ * Throws unless both shipped lists are non-empty and entirely valid CIDRs.
105
+ * Called by the refresh script before it writes anything, and usable by tests.
106
+ */
107
+ export function assertShippedRanges() {
108
+ const v4 = validateCidrList(CLOUDFLARE_IPV4, 4);
109
+ const v6 = validateCidrList(CLOUDFLARE_IPV6, 6);
110
+ if (!CLOUDFLARE_IPV4.length || !CLOUDFLARE_IPV6.length) {
111
+ throw new Error('Cloudflare range list is empty');
112
+ }
113
+ if (!v4.ok) throw new Error(`Invalid IPv4 Cloudflare range(s): ${v4.invalid.join(', ')}`);
114
+ if (!v6.ok) throw new Error(`Invalid IPv6 Cloudflare range(s): ${v6.invalid.join(', ')}`);
115
+ }
116
+
117
+ /**
118
+ * Parses a fetch response body into a validated CIDR list for one family.
119
+ * @param {string} text
120
+ * @param {4|6} family
121
+ * @returns {string[]}
122
+ */
123
+ export function parseRangeText(text, family) {
124
+ const entries = String(text ?? '')
125
+ .split(/\s+/)
126
+ .map((line) => line.trim())
127
+ .filter(Boolean);
128
+
129
+ const { ok, invalid } = validateCidrList(entries, family);
130
+ if (entries.length === 0) throw new Error(`No IPv${family} ranges returned`);
131
+ if (!ok) throw new Error(`Invalid IPv${family} range(s): ${invalid.join(', ')}`);
132
+ return entries;
133
+ }
134
+
135
+ /**
136
+ * Fetches both published lists and validates them. No filesystem, no writes —
137
+ * the script owns that so this can be exercised with a fake fetch.
138
+ *
139
+ * @param {{ fetchImpl?: typeof fetch }} [options]
140
+ * @returns {Promise<{ ipv4: string[], ipv6: string[], refreshedAt: string }>}
141
+ */
142
+ export async function fetchCloudflareRanges({ fetchImpl = globalThis.fetch } = {}) {
143
+ if (typeof fetchImpl !== 'function') throw new Error('No fetch implementation available');
144
+
145
+ const [v4Response, v6Response] = await Promise.all([
146
+ fetchImpl(SOURCE_URLS.ipv4),
147
+ fetchImpl(SOURCE_URLS.ipv6),
148
+ ]);
149
+
150
+ for (const [label, response] of [['ips-v4', v4Response], ['ips-v6', v6Response]]) {
151
+ if (!response.ok) {
152
+ throw new Error(`Fetching ${label} failed: HTTP ${response.status}`);
153
+ }
154
+ }
155
+
156
+ const [v4Text, v6Text] = await Promise.all([v4Response.text(), v6Response.text()]);
157
+ const ipv4 = parseRangeText(v4Text, 4);
158
+ const ipv6 = parseRangeText(v6Text, 6);
159
+
160
+ return { ipv4, ipv6, refreshedAt: new Date().toISOString().slice(0, 10) };
161
+ }
@@ -30,7 +30,7 @@
30
30
  *
31
31
  * ── Why the payloads are the contract's payloads ───────────────────────────
32
32
  *
33
- * The event names and shapes are the ones in docs/api-contract.md, so the
33
+ * The event names and shapes are the ones in API-CONTRACT.md, so the
34
34
  * dashboard forwards each frame to the browser unchanged. Anything else would
35
35
  * mean two schemas describing the same data.
36
36
  */