easy-devops 1.2.1 → 1.3.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 (126) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-CMRzkIKj.css +1 -0
  3. package/dist/ui/assets/index-DEouL3IK.js +452 -0
  4. package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
  5. package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
  6. package/dist/ui/brand/apple-touch-icon.png +0 -0
  7. package/dist/ui/brand/favicon-16.png +0 -0
  8. package/dist/ui/brand/favicon-32.png +0 -0
  9. package/dist/ui/brand/favicon-light-16.png +0 -0
  10. package/dist/ui/brand/favicon-light-32.png +0 -0
  11. package/dist/ui/brand/favicon.ico +0 -0
  12. package/dist/ui/brand/icon-192.png +0 -0
  13. package/dist/ui/brand/icon-48.png +0 -0
  14. package/dist/ui/brand/icon-512.png +0 -0
  15. package/dist/ui/brand/icon-64-light.png +0 -0
  16. package/dist/ui/brand/icon-64.png +0 -0
  17. package/dist/ui/brand/logo-dark.png +0 -0
  18. package/dist/ui/brand/logo-light.png +0 -0
  19. package/dist/ui/brand/mark-dark.png +0 -0
  20. package/dist/ui/brand/mark-light.png +0 -0
  21. package/dist/ui/index.html +71 -0
  22. package/install.ps1 +188 -1
  23. package/install.sh +254 -29
  24. package/package.json +15 -4
  25. package/src/cli/dash.js +110 -0
  26. package/src/cli/index.js +237 -106
  27. package/src/cli/managers/domain-manager.js +60 -40
  28. package/src/cli/managers/ssl-manager.js +47 -330
  29. package/src/cli/menu.js +156 -0
  30. package/src/cli/menus/cleanup.js +205 -0
  31. package/src/cli/menus/dashboard.js +92 -1
  32. package/src/cli/menus/runtime.js +236 -0
  33. package/src/cli/menus/service.js +764 -0
  34. package/src/cli/menus/settings.js +176 -8
  35. package/src/cli/menus/uninstall.js +167 -0
  36. package/src/cli/menus/update.js +222 -47
  37. package/src/core/acme-challenge.js +273 -0
  38. package/src/core/cert-operations.js +189 -0
  39. package/src/{dashboard/lib → core}/cert-reader.js +2 -2
  40. package/src/core/cert-renewal.js +494 -0
  41. package/src/core/cleanup.js +600 -0
  42. package/src/core/config.js +169 -2
  43. package/src/core/daemon/ipc.js +292 -0
  44. package/src/core/daemon/lock.js +294 -0
  45. package/src/core/daemon/run.js +241 -0
  46. package/src/core/daemon/stopRequest.js +162 -0
  47. package/src/core/db.js +37 -8
  48. package/src/core/deploy/apps.js +491 -0
  49. package/src/core/deploy/domainLink.js +200 -0
  50. package/src/core/deploy/engine.js +973 -0
  51. package/src/core/deploy/ezfile.js +361 -0
  52. package/src/core/deploy/github.js +239 -0
  53. package/src/core/deploy/githubApi.js +261 -0
  54. package/src/core/deploy/hookServer.js +325 -0
  55. package/src/core/deploy/hubCommands.js +267 -0
  56. package/src/core/deploy/launcher.js +57 -0
  57. package/src/core/deploy/status.js +91 -0
  58. package/src/core/deploy/store.js +398 -0
  59. package/src/core/domainNotifier.js +94 -28
  60. package/src/core/domains-db.js +234 -0
  61. package/src/core/events.js +94 -2
  62. package/src/core/hub/agent.js +842 -0
  63. package/src/core/hubLink.js +306 -0
  64. package/src/core/hubPermissions.js +430 -0
  65. package/src/core/installSource.js +162 -0
  66. package/src/core/jobs/bus.js +120 -0
  67. package/src/core/jobs/index.js +371 -0
  68. package/src/core/jobs/monitors.js +368 -0
  69. package/src/core/jobs/owner.js +217 -0
  70. package/src/core/jobs/revisionWatcher.js +106 -0
  71. package/src/core/nginx-apply.js +213 -0
  72. package/src/core/nginx-conf-generator.js +253 -17
  73. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  74. package/src/core/notifications/claim.js +214 -0
  75. package/src/core/notifications/dispatch.js +154 -0
  76. package/src/core/notifier.js +31 -1
  77. package/src/core/passwords.js +172 -0
  78. package/src/core/permissions.js +8 -4
  79. package/src/core/platform.js +709 -2
  80. package/src/core/probeCache.js +258 -0
  81. package/src/core/purge.js +372 -0
  82. package/src/core/runner.js +488 -0
  83. package/src/core/service/acl.js +226 -0
  84. package/src/core/service/dataDir.js +345 -0
  85. package/src/core/service/index.js +1128 -0
  86. package/src/core/service/legacy.js +218 -0
  87. package/src/core/service/runtime.js +446 -0
  88. package/src/core/service/runtimeUpdate.js +800 -0
  89. package/src/core/service/systemd.js +458 -0
  90. package/src/core/service/windowsPersonal.js +530 -0
  91. package/src/core/service/windowsService.js +576 -0
  92. package/src/core/service/winsw.js +260 -0
  93. package/src/core/setupCode.js +331 -0
  94. package/src/core/shell.js +70 -7
  95. package/src/core/ssl-issuer.js +627 -0
  96. package/src/core/updater.js +295 -0
  97. package/src/core/validators.js +99 -0
  98. package/src/dashboard/controllers/authController.js +302 -15
  99. package/src/dashboard/controllers/deploymentsController.js +479 -0
  100. package/src/dashboard/controllers/domainsController.js +80 -61
  101. package/src/dashboard/controllers/hubController.js +135 -0
  102. package/src/dashboard/controllers/nginxController.js +21 -3
  103. package/src/dashboard/controllers/processesController.js +368 -0
  104. package/src/dashboard/controllers/settingsController.js +180 -12
  105. package/src/dashboard/controllers/sslController.js +288 -10
  106. package/src/dashboard/lib/daemonBridge.js +163 -0
  107. package/src/dashboard/lib/localRequest.js +235 -0
  108. package/src/dashboard/lib/loginRateLimit.js +119 -0
  109. package/src/dashboard/lib/requireAuth.js +80 -0
  110. package/src/dashboard/public/js/app.js +489 -19
  111. package/src/dashboard/routes/auth.js +10 -10
  112. package/src/dashboard/routes/deployments.js +46 -0
  113. package/src/dashboard/routes/domains.js +9 -0
  114. package/src/dashboard/routes/hub.js +22 -0
  115. package/src/dashboard/routes/nginx.js +9 -0
  116. package/src/dashboard/routes/processes.js +29 -0
  117. package/src/dashboard/routes/settings.js +9 -0
  118. package/src/dashboard/routes/ssl.js +10 -0
  119. package/src/dashboard/server.js +288 -21
  120. package/src/dashboard/socketManager.js +171 -207
  121. package/src/dashboard/views/index.ejs +1 -0
  122. package/src/dashboard/views/partials/login.ejs +68 -7
  123. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  124. package/src/dashboard/views/partials/settings-panel.ejs +287 -0
  125. package/src/dashboard/views/partials/sidebar.ejs +2 -0
  126. package/src/dashboard/lib/domains-db.js +0 -51
@@ -0,0 +1,258 @@
1
+ /**
2
+ * core/probeCache.js
3
+ *
4
+ * Cache for probes that cost a subprocess, with refresh in the background.
5
+ *
6
+ * ── Why this exists, with numbers ──────────────────────────────────────────
7
+ *
8
+ * `GET /api/service` took about twenty seconds on a Windows machine. Nothing
9
+ * in it was slow by itself; it was the spawn count. Measured on that machine:
10
+ *
11
+ * one bare `run()` through PowerShell ~0.9 - 1.4 s
12
+ * `where.exe pm2` ~2.0 s
13
+ * `pm2 --version` ~4.0 s
14
+ * `schtasks /Query` ~1.7 s
15
+ *
16
+ * and the endpoint made about six of them, in sequence: the service manager's
17
+ * status, the pinned runtime's `--version`, the legacy PM2 scan (which detects
18
+ * PM2 and lists its apps), and PM2 detection again for the Processes panel.
19
+ * Five spawns run one after another cost ~6 s; the same five together cost
20
+ * ~1.7 s. So there are two separate wins, and this module is the bigger one.
21
+ *
22
+ * ── The contract ───────────────────────────────────────────────────────────
23
+ *
24
+ * A caller asks for a key and gets an answer immediately whenever one exists,
25
+ * even a stale one, and a refresh is started in the background. Only a COLD
26
+ * key — nothing cached at all — can make a caller wait, and then only up to
27
+ * the timeout it passes.
28
+ *
29
+ * Serving a stale answer is the right default here because of what these
30
+ * probes describe: whether PM2 is installed, which Node the service is pinned
31
+ * to, whether a Task Scheduler leftover exists. Those change when the user
32
+ * runs a command, never on their own — and every command that changes one
33
+ * calls `invalidate()`. The things that DO change on their own, the daemon
34
+ * lock and the heartbeat, are read fresh on every request and never come from
35
+ * here; they cost microseconds.
36
+ *
37
+ * ── Single-flight ──────────────────────────────────────────────────────────
38
+ *
39
+ * Two requests arriving together must not both spawn `where.exe pm2`. A key
40
+ * has at most one producer in flight, and everyone waiting on that key gets
41
+ * its result. Without this, an open dashboard polling every fifteen seconds
42
+ * with two tabs would double the spawn count rather than halve it.
43
+ */
44
+
45
+ /**
46
+ * @typedef {Object} Entry
47
+ * @property {*} value
48
+ * @property {number} at When the value was produced
49
+ * @property {number} ttlMs
50
+ * @property {Promise|null} inFlight
51
+ * @property {string|null} error The last failure, if the value is stale
52
+ */
53
+
54
+ /** @type {Map<string, Entry>} */
55
+ const entries = new Map();
56
+
57
+ /** Counters, for tests and for a status line. Not a metrics system. */
58
+ const counters = { hits: 0, stale: 0, misses: 0, refreshes: 0, failures: 0 };
59
+
60
+ /** Default lifetime. Overridden per key by every real caller. */
61
+ export const DEFAULT_TTL_MS = 30_000;
62
+
63
+ /**
64
+ * How long a cold caller may wait before being answered with "pending".
65
+ *
66
+ * Chosen so the FIRST request after a dashboard starts still returns inside a
67
+ * couple of seconds even when every probe is cold and slow. The dashboard also
68
+ * warms the cache at startup, so in practice this deadline is rarely reached.
69
+ */
70
+ export const DEFAULT_COLD_WAIT_MS = 1_500;
71
+
72
+ /**
73
+ * Reads a key, refreshing it in the background when it is past its TTL.
74
+ *
75
+ * @param {string} key
76
+ * @param {() => Promise<*>} producer Does the expensive work
77
+ * @param {Object} [opts]
78
+ * @param {number} [opts.ttlMs]
79
+ * @param {number} [opts.coldWaitMs] Max wait when nothing is cached
80
+ * @param {number} [opts.now]
81
+ * @returns {Promise<{ value: *, ageMs: number|null, fresh: boolean, pending: boolean, refreshing: boolean, error: string|null }>}
82
+ */
83
+ export async function probe(key, producer, {
84
+ ttlMs = DEFAULT_TTL_MS,
85
+ coldWaitMs = DEFAULT_COLD_WAIT_MS,
86
+ now = Date.now(),
87
+ } = {}) {
88
+ const entry = entries.get(key);
89
+
90
+ // ── Fresh ────────────────────────────────────────────────────────────────
91
+ if (entry && entry.at !== null && now - entry.at < ttlMs) {
92
+ counters.hits += 1;
93
+ return {
94
+ value: entry.value,
95
+ ageMs: now - entry.at,
96
+ fresh: true,
97
+ pending: false,
98
+ refreshing: Boolean(entry.inFlight),
99
+ error: entry.error,
100
+ };
101
+ }
102
+
103
+ // ── Stale: answer now, refresh behind ────────────────────────────────────
104
+ if (entry && entry.at !== null) {
105
+ counters.stale += 1;
106
+ startRefresh(key, producer, ttlMs);
107
+ return {
108
+ value: entry.value,
109
+ ageMs: now - entry.at,
110
+ fresh: false,
111
+ pending: false,
112
+ refreshing: true,
113
+ error: entry.error,
114
+ };
115
+ }
116
+
117
+ // ── Cold: wait, but not for ever ─────────────────────────────────────────
118
+ counters.misses += 1;
119
+ const refresh = startRefresh(key, producer, ttlMs);
120
+
121
+ const raced = await Promise.race([
122
+ refresh.then(() => 'done', () => 'failed'),
123
+ new Promise((resolve) => {
124
+ const timer = setTimeout(() => resolve('timeout'), coldWaitMs);
125
+ // Never hold the event loop open for a deadline nobody is waiting on:
126
+ // this is what stops `ezz --dash` hanging on Ctrl+C.
127
+ timer.unref?.();
128
+ }),
129
+ ]);
130
+
131
+ const settled = entries.get(key);
132
+
133
+ if (raced === 'done' && settled?.at !== null) {
134
+ return {
135
+ value: settled.value,
136
+ ageMs: Date.now() - settled.at,
137
+ fresh: true,
138
+ pending: false,
139
+ refreshing: false,
140
+ error: settled.error,
141
+ };
142
+ }
143
+
144
+ // Either it is still running, or it failed with nothing cached to fall back
145
+ // on. Both are "no answer yet", and the caller decides what to render.
146
+ return {
147
+ value: null,
148
+ ageMs: null,
149
+ fresh: false,
150
+ pending: true,
151
+ refreshing: Boolean(settled?.inFlight),
152
+ error: settled?.error ?? null,
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Starts a refresh unless one is already running for this key.
158
+ *
159
+ * @returns {Promise<*>} The in-flight promise, so a cold caller can await it
160
+ */
161
+ function startRefresh(key, producer, ttlMs) {
162
+ const existing = entries.get(key);
163
+ if (existing?.inFlight) return existing.inFlight;
164
+
165
+ const entry = existing ?? { value: null, at: null, ttlMs, inFlight: null, error: null };
166
+ entry.ttlMs = ttlMs;
167
+ entries.set(key, entry);
168
+
169
+ counters.refreshes += 1;
170
+
171
+ entry.inFlight = (async () => {
172
+ try {
173
+ const value = await producer();
174
+ entry.value = value;
175
+ entry.at = Date.now();
176
+ entry.error = null;
177
+ return value;
178
+ } catch (err) {
179
+ counters.failures += 1;
180
+ entry.error = err?.message ?? String(err);
181
+ // A failed refresh does NOT discard the previous value. A probe that
182
+ // fails once - a tool busy, a transient permission error - must not turn
183
+ // a working status display into an empty one.
184
+ throw err;
185
+ } finally {
186
+ entry.inFlight = null;
187
+ }
188
+ })();
189
+
190
+ // The rejection is handled by whoever awaits it; this keeps a background
191
+ // refresh from becoming an unhandled rejection that takes the daemon down.
192
+ entry.inFlight.catch(() => {});
193
+
194
+ return entry.inFlight;
195
+ }
196
+
197
+ /**
198
+ * Drops cached values so the next read re-probes.
199
+ *
200
+ * Called by every operation that changes what the probes describe: install,
201
+ * uninstall, start, stop, restart, repair, a runtime update, and the
202
+ * dashboard's `service:changed`. Without that, a user who had just started the
203
+ * service would be shown "not running" for the rest of the TTL — which is the
204
+ * failure mode that makes caching feel broken.
205
+ *
206
+ * @param {string} [prefix] Only keys starting with this; everything when omitted
207
+ * @returns {number} How many keys were dropped
208
+ */
209
+ export function invalidate(prefix) {
210
+ let dropped = 0;
211
+ for (const key of [...entries.keys()]) {
212
+ if (prefix !== undefined && !key.startsWith(prefix)) continue;
213
+ const entry = entries.get(key);
214
+ // An in-flight producer is left to finish, but its result is no longer
215
+ // wanted: clearing `at` makes the next read treat the key as cold.
216
+ if (entry) {
217
+ entry.value = null;
218
+ entry.at = null;
219
+ entry.error = null;
220
+ }
221
+ entries.delete(key);
222
+ dropped += 1;
223
+ }
224
+ return dropped;
225
+ }
226
+
227
+ /** The cached value without producing or refreshing anything. For tests. */
228
+ export function peek(key, { now = Date.now() } = {}) {
229
+ const entry = entries.get(key);
230
+ if (!entry || entry.at === null) return { cached: false, value: null, ageMs: null };
231
+ return { cached: true, value: entry.value, ageMs: now - entry.at, refreshing: Boolean(entry.inFlight) };
232
+ }
233
+
234
+ /** Hit/miss counters. Reset by `resetStats()`; for tests and diagnostics. */
235
+ export function stats() {
236
+ return { ...counters, keys: entries.size };
237
+ }
238
+
239
+ /** Zeroes the counters, leaving the cached values alone. */
240
+ export function resetStats() {
241
+ for (const key of Object.keys(counters)) counters[key] = 0;
242
+ }
243
+
244
+ /**
245
+ * Waits for every in-flight refresh to settle.
246
+ *
247
+ * For tests and for a deliberate warm-up, so a caller can say "fill the cache,
248
+ * then measure a warm call" without sleeping for an arbitrary length of time.
249
+ *
250
+ * @returns {Promise<void>}
251
+ */
252
+ export async function settle() {
253
+ for (let round = 0; round < 10; round += 1) {
254
+ const pending = [...entries.values()].map((e) => e.inFlight).filter(Boolean);
255
+ if (pending.length === 0) return;
256
+ await Promise.allSettled(pending);
257
+ }
258
+ }
@@ -0,0 +1,372 @@
1
+ /**
2
+ * core/purge.js
3
+ *
4
+ * `ezz uninstall --purge` — remove Easy DevOps itself: the service, the pinned
5
+ * runtime and the data directory.
6
+ *
7
+ * ── The backup comes first, and it is not optional ─────────────────────────
8
+ *
9
+ * The data directory holds the only copy of things that cannot be regenerated:
10
+ * the domain list, the notification channels, the Hub pairing, the dashboard
11
+ * password hash and the session secret. A purge that removed it and then
12
+ * failed, or that the user regretted an hour later, would be unrecoverable.
13
+ *
14
+ * So the order is: export, verify the export, print where it is, and only then
15
+ * remove anything. If the export fails, nothing is removed at all — that is
16
+ * the one failure that aborts the whole operation rather than being reported
17
+ * and worked around.
18
+ *
19
+ * The backup is a plain directory copy, not an archive. No new dependency can
20
+ * be added (and none is needed): a directory is restorable with the file
21
+ * manager the user already has, needs no tool to inspect, and cannot be
22
+ * half-written in a way that looks complete. It goes OUTSIDE the data
23
+ * directory, in the user's home by default, because the data directory is what
24
+ * is about to be deleted.
25
+ *
26
+ * ── What is kept, deliberately ─────────────────────────────────────────────
27
+ *
28
+ * nginx itself, the sites it serves, and the certificates. Easy DevOps
29
+ * configures nginx; it does not own it. Removing a working web server because
30
+ * its configuration tool was uninstalled would take sites offline, and that is
31
+ * never what "uninstall the tool" means. Certificates are the one part the
32
+ * caller may choose to remove, because they are private keys — the default is
33
+ * to keep them, and the caller has to ask for anything else.
34
+ */
35
+
36
+ import fs from 'fs';
37
+ import os from 'os';
38
+ import path from 'path';
39
+ import { createRequire } from 'module';
40
+
41
+ import { getDataDir, isWindows, programDataDir } from './platform.js';
42
+ import { loadConfig } from './config.js';
43
+ import { closeDb, initDb } from './db.js';
44
+ import { runtimeDir, runtimeNodePath, inspectLink } from './service/runtime.js';
45
+ import { detectInstallSource } from './installSource.js';
46
+ import { PACKAGE } from './updater.js';
47
+
48
+ const require = createRequire(import.meta.url);
49
+
50
+ /** `easy-devops-backup-2026-11-15T05-40-12`. */
51
+ export function backupName(now = new Date()) {
52
+ const stamp = now.toISOString().replace(/[:.]/g, '-').replace(/Z$/, '').slice(0, 19);
53
+ return `easy-devops-backup-${stamp}`;
54
+ }
55
+
56
+ /** Where a backup goes unless the caller says otherwise: the user's home. */
57
+ export function defaultBackupDir() {
58
+ return os.homedir();
59
+ }
60
+
61
+ /**
62
+ * Copies the data directory somewhere safe and describes what is in it.
63
+ *
64
+ * The SQLite handle is closed first and reopened after: on Windows an open
65
+ * database file cannot be copied reliably, and a copy taken mid-write is worse
66
+ * than no copy because it looks like one.
67
+ *
68
+ * @param {Object} [opts]
69
+ * @returns {{ ok: boolean, path?: string, bytes?: number, reason?: string }}
70
+ */
71
+ export function exportBackup({
72
+ dataDir = getDataDir(),
73
+ into = defaultBackupDir(),
74
+ now = new Date(),
75
+ log = () => {},
76
+ } = {}) {
77
+ const dest = path.join(into, backupName(now));
78
+
79
+ if (!fs.existsSync(dataDir)) {
80
+ return { ok: false, reason: `there is no data directory at ${dataDir}` };
81
+ }
82
+
83
+ // Refusing rather than merging into something that already exists: a second
84
+ // purge in the same second is unlikely, but overwriting a backup is exactly
85
+ // the kind of thing that is only noticed when it is needed.
86
+ if (fs.existsSync(dest)) {
87
+ return { ok: false, reason: `${dest} already exists` };
88
+ }
89
+
90
+ const config = safeConfig();
91
+
92
+ closeDb();
93
+ try {
94
+ fs.mkdirSync(dest, { recursive: true });
95
+ fs.cpSync(dataDir, path.join(dest, 'data'), { recursive: true });
96
+ } catch (err) {
97
+ return { ok: false, reason: `could not copy ${dataDir}: ${err.message}` };
98
+ } finally {
99
+ initDb();
100
+ }
101
+
102
+ // Verified, not assumed: the database is the file that matters, and a copy
103
+ // that silently skipped it would be discovered only on a restore.
104
+ const dbName = 'easy-devops.sqlite';
105
+ const copiedDb = path.join(dest, 'data', dbName);
106
+ if (fs.existsSync(path.join(dataDir, dbName)) && !fs.existsSync(copiedDb)) {
107
+ return { ok: false, reason: `the backup is missing ${dbName}; nothing was removed` };
108
+ }
109
+
110
+ try {
111
+ fs.writeFileSync(path.join(dest, 'MANIFEST.txt'), manifest({ dataDir, config, now }), 'utf8');
112
+ } catch (err) {
113
+ log(`could not write the manifest: ${err.message}`);
114
+ }
115
+
116
+ log(`Backup written to ${dest}`);
117
+ return { ok: true, path: dest, bytes: dirSize(dest) };
118
+ }
119
+
120
+ /** Config without the secrets a backup note has no business repeating. */
121
+ function safeConfig() {
122
+ const config = loadConfig();
123
+ return {
124
+ dashboardPort: config.dashboardPort,
125
+ dashboardBindAddress: config.dashboardBindAddress,
126
+ dashboardAuth: config.dashboardAuth,
127
+ dashboardUi: config.dashboardUi,
128
+ nginxDir: config.nginxDir,
129
+ sslDir: config.sslDir,
130
+ acmeEmail: config.acmeEmail,
131
+ };
132
+ }
133
+
134
+ function manifest({ dataDir, config, now }) {
135
+ const version = String(require('../../package.json').version);
136
+
137
+ return [
138
+ 'Easy DevOps backup',
139
+ '==================',
140
+ '',
141
+ `taken : ${now.toISOString()}`,
142
+ `version : ${version}`,
143
+ `platform : ${process.platform}`,
144
+ `data dir : ${dataDir}`,
145
+ '',
146
+ 'What is here',
147
+ '------------',
148
+ 'data/ a copy of the whole Easy DevOps data directory, including',
149
+ ' easy-devops.sqlite - the domains, notification channels, Hub',
150
+ ' pairing, dashboard password hash and session secret.',
151
+ '',
152
+ 'What is NOT here',
153
+ '----------------',
154
+ `nginx configuration (${config.nginxDir ?? 'not configured'}) and the`,
155
+ `certificates (${config.sslDir ?? 'not configured'}) were left in place on`,
156
+ 'the machine, not copied. nginx and your sites keep running.',
157
+ '',
158
+ 'Restoring',
159
+ '---------',
160
+ `1. Reinstall Easy DevOps: npm install -g ${PACKAGE}`,
161
+ '2. Copy data/ back over the new data directory, with nothing running:',
162
+ ` ${dataDir}`,
163
+ '3. ezz service install',
164
+ '',
165
+ 'The settings in the database point at the nginx and certificate paths',
166
+ 'above, so a restore onto the same machine needs no reconfiguration.',
167
+ '',
168
+ ].join('\n');
169
+ }
170
+
171
+ function dirSize(target) {
172
+ let total = 0;
173
+ let stat;
174
+ try {
175
+ stat = fs.statSync(target);
176
+ } catch {
177
+ return 0;
178
+ }
179
+ if (!stat.isDirectory()) return stat.size;
180
+ let entries = [];
181
+ try {
182
+ entries = fs.readdirSync(target);
183
+ } catch {
184
+ return 0;
185
+ }
186
+ for (const entry of entries) total += dirSize(path.join(target, entry));
187
+ return total;
188
+ }
189
+
190
+ /**
191
+ * What a purge would remove and what it would keep, without doing anything.
192
+ *
193
+ * Printed before the confirmation, so the answer to "what exactly is about to
194
+ * happen" is the same list the code then walks.
195
+ *
196
+ * @param {Object} [opts]
197
+ * @returns {{ removes: Array<{ what: string, path: string }>, keeps: Array<{ what: string, path: string }> }}
198
+ */
199
+ export function plan({ dataDir = getDataDir(), certificates = 'keep', config = loadConfig() } = {}) {
200
+ const removes = [{ what: 'the background service', path: '(service manager entry)' }];
201
+
202
+ const runtime = isWindows ? runtimeDir(dataDir) : path.dirname(runtimeNodePath(dataDir));
203
+ if (fs.existsSync(runtime)) {
204
+ removes.push({ what: 'the pinned runtime', path: runtime });
205
+ }
206
+
207
+ removes.push({ what: 'the data directory', path: dataDir });
208
+
209
+ if (isWindows && fs.existsSync(programDataDir()) && path.resolve(programDataDir()) !== path.resolve(dataDir)) {
210
+ removes.push({ what: 'the machine-wide data directory', path: programDataDir() });
211
+ }
212
+
213
+ const keeps = [
214
+ { what: 'nginx and its configuration', path: config.nginxDir ?? '(not configured)' },
215
+ { what: 'your sites', path: '(served by nginx, untouched)' },
216
+ ];
217
+
218
+ if (certificates === 'remove') {
219
+ removes.push({ what: 'the certificates', path: config.sslDir ?? '(not configured)' });
220
+ } else {
221
+ keeps.push({ what: 'the certificates and keys', path: config.sslDir ?? '(not configured)' });
222
+ }
223
+
224
+ return { removes, keeps };
225
+ }
226
+
227
+ /**
228
+ * Removes Easy DevOps.
229
+ *
230
+ * @param {Object} opts
231
+ * @param {'keep'|'remove'} [opts.certificates] Default 'keep'
232
+ * @param {string} [opts.backupDir]
233
+ * @param {(line: string) => void} [opts.log]
234
+ * @returns {Promise<Object>}
235
+ */
236
+ export async function purge({
237
+ dataDir = getDataDir(),
238
+ certificates = 'keep',
239
+ backupDir = defaultBackupDir(),
240
+ log = () => {},
241
+ deps = {},
242
+ } = {}) {
243
+ const service = deps.service ?? (await import('./service/index.js'));
244
+ const config = deps.config ?? loadConfig();
245
+ const source = (deps.detectInstallSource ?? detectInstallSource)();
246
+
247
+ // 1. The backup. Nothing is removed if this fails.
248
+ log('Exporting a backup of the data directory...');
249
+ const backup = (deps.exportBackup ?? exportBackup)({ dataDir, into: backupDir, log });
250
+ if (!backup.ok) {
251
+ return {
252
+ ok: false,
253
+ step: 'backup',
254
+ reason: backup.reason,
255
+ untouched: true,
256
+ hint: 'Nothing was removed. Fix the backup location, or pass --backup-dir, and try again.',
257
+ };
258
+ }
259
+
260
+ const removed = [];
261
+ const failed = [];
262
+
263
+ // 2. The service. Attempted before the files it points at are deleted, so
264
+ // the service manager is not left with an entry for a missing binary.
265
+ log('Removing the background service...');
266
+ let uninstalled = { ok: true, notes: ['no service was installed'] };
267
+ try {
268
+ uninstalled = await service.uninstall({ keepServerDataLocation: true, removeLegacy: true, log });
269
+ } catch (err) {
270
+ uninstalled = { ok: false, reason: err.message };
271
+ }
272
+
273
+ if (uninstalled.ok) {
274
+ removed.push({ what: 'the background service', detail: uninstalled.mechanism ?? 'none' });
275
+ } else {
276
+ failed.push({
277
+ what: 'the background service',
278
+ reason: uninstalled.reason,
279
+ needsElevation: uninstalled.needsElevation ?? false,
280
+ });
281
+ }
282
+
283
+ // 3. The pinned runtime. On Linux this is a symlink and its TARGET is a real
284
+ // Node installation that must not be touched: only the link goes.
285
+ const runtimeTarget = isWindows ? runtimeDir(dataDir) : null;
286
+ if (!isWindows) {
287
+ const link = inspectLink(dataDir);
288
+ if (link.exists) {
289
+ try {
290
+ fs.rmSync(link.link, { force: true });
291
+ removed.push({ what: 'the runtime link', detail: `${link.link} (its target was left alone)` });
292
+ } catch (err) {
293
+ failed.push({ what: 'the runtime link', reason: err.message });
294
+ }
295
+ }
296
+ } else if (runtimeTarget && fs.existsSync(runtimeTarget)) {
297
+ try {
298
+ fs.rmSync(runtimeTarget, { recursive: true, force: true });
299
+ removed.push({ what: 'the pinned runtime', detail: runtimeTarget });
300
+ } catch (err) {
301
+ failed.push({
302
+ what: 'the pinned runtime',
303
+ reason: `${err.message} (removing it under ProgramData needs an Administrator terminal)`,
304
+ });
305
+ }
306
+ }
307
+
308
+ // 4. The certificates, only if asked.
309
+ if (certificates === 'remove' && config.sslDir) {
310
+ if (fs.existsSync(config.sslDir)) {
311
+ try {
312
+ fs.rmSync(config.sslDir, { recursive: true, force: true });
313
+ removed.push({ what: 'the certificates', detail: config.sslDir });
314
+ } catch (err) {
315
+ failed.push({ what: 'the certificates', reason: err.message });
316
+ }
317
+ }
318
+ }
319
+
320
+ // 5. The data directory, last: every step above reads from it.
321
+ //
322
+ // The database handle is closed first (on Windows an open file cannot be
323
+ // removed) and deliberately NOT reopened afterwards: initDb() would recreate
324
+ // the directory that was just deleted, which is the one thing a purge must
325
+ // not do. It IS reopened when the removal failed, so a failed purge leaves a
326
+ // working process rather than one that throws on its next read.
327
+ log('Removing the data directory...');
328
+ closeDb();
329
+ let databaseClosed = true;
330
+ try {
331
+ fs.rmSync(dataDir, { recursive: true, force: true });
332
+ removed.push({ what: 'the data directory', detail: dataDir });
333
+ } catch (err) {
334
+ failed.push({ what: 'the data directory', reason: err.message });
335
+ initDb();
336
+ databaseClosed = false;
337
+ }
338
+
339
+ // The machine-wide directory in Server mode, which is a second location.
340
+ if (isWindows) {
341
+ const machine = programDataDir();
342
+ if (fs.existsSync(machine) && path.resolve(machine) !== path.resolve(dataDir)) {
343
+ try {
344
+ fs.rmSync(machine, { recursive: true, force: true });
345
+ removed.push({ what: 'the machine-wide data directory', detail: machine });
346
+ } catch (err) {
347
+ failed.push({
348
+ what: 'the machine-wide data directory',
349
+ reason: `${err.message} (needs an Administrator terminal)`,
350
+ });
351
+ }
352
+ }
353
+ }
354
+
355
+ return {
356
+ ok: failed.length === 0,
357
+ step: 'done',
358
+ backup,
359
+ removed,
360
+ failed,
361
+ // The caller is expected to exit after this: the data directory is gone
362
+ // and nothing in this process can read or write settings any more.
363
+ databaseClosed,
364
+ kept: plan({ dataDir, certificates, config }).keeps,
365
+ // The package itself cannot remove the package: npm would be deleting the
366
+ // files it is running from. So the last step is the user's.
367
+ finalCommand: source.kind === 'clone'
368
+ ? `rm -rf ${source.root} # this clone; nothing was installed globally`
369
+ : `npm uninstall -g ${PACKAGE}`,
370
+ installSource: source,
371
+ };
372
+ }