easy-devops 1.2.0 → 1.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.
Files changed (132) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-B6zdwEnG.css +1 -0
  3. package/dist/ui/assets/index-Cy0oNmul.js +442 -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 +17 -5
  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 +93 -2
  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 +221 -65
  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/channels/discord.js +77 -0
  42. package/src/core/channels/telegram.js +120 -0
  43. package/src/core/cleanup.js +600 -0
  44. package/src/core/config.js +169 -2
  45. package/src/core/daemon/ipc.js +292 -0
  46. package/src/core/daemon/lock.js +294 -0
  47. package/src/core/daemon/run.js +241 -0
  48. package/src/core/daemon/stopRequest.js +162 -0
  49. package/src/core/db.js +44 -8
  50. package/src/core/deploy/apps.js +491 -0
  51. package/src/core/deploy/domainLink.js +200 -0
  52. package/src/core/deploy/engine.js +973 -0
  53. package/src/core/deploy/ezfile.js +361 -0
  54. package/src/core/deploy/github.js +239 -0
  55. package/src/core/deploy/githubApi.js +261 -0
  56. package/src/core/deploy/hookServer.js +325 -0
  57. package/src/core/deploy/hubCommands.js +267 -0
  58. package/src/core/deploy/launcher.js +57 -0
  59. package/src/core/deploy/status.js +91 -0
  60. package/src/core/deploy/store.js +398 -0
  61. package/src/core/domainNotifier.js +364 -0
  62. package/src/core/domains-db.js +234 -0
  63. package/src/core/events.js +222 -0
  64. package/src/core/hub/agent.js +842 -0
  65. package/src/core/hubLink.js +306 -0
  66. package/src/core/hubPermissions.js +430 -0
  67. package/src/core/installSource.js +162 -0
  68. package/src/core/jobs/bus.js +120 -0
  69. package/src/core/jobs/index.js +371 -0
  70. package/src/core/jobs/monitors.js +368 -0
  71. package/src/core/jobs/owner.js +217 -0
  72. package/src/core/jobs/revisionWatcher.js +106 -0
  73. package/src/core/nginx-apply.js +213 -0
  74. package/src/core/nginx-conf-generator.js +253 -17
  75. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  76. package/src/core/notifications/claim.js +214 -0
  77. package/src/core/notifications/dispatch.js +154 -0
  78. package/src/core/notifier.js +103 -0
  79. package/src/core/passwords.js +172 -0
  80. package/src/core/permissions.js +8 -4
  81. package/src/core/platform.js +709 -2
  82. package/src/core/probeCache.js +258 -0
  83. package/src/core/purge.js +372 -0
  84. package/src/core/runner.js +488 -0
  85. package/src/core/service/acl.js +226 -0
  86. package/src/core/service/dataDir.js +345 -0
  87. package/src/core/service/index.js +1128 -0
  88. package/src/core/service/legacy.js +218 -0
  89. package/src/core/service/runtime.js +446 -0
  90. package/src/core/service/runtimeUpdate.js +800 -0
  91. package/src/core/service/systemd.js +458 -0
  92. package/src/core/service/windowsPersonal.js +530 -0
  93. package/src/core/service/windowsService.js +576 -0
  94. package/src/core/service/winsw.js +260 -0
  95. package/src/core/setupCode.js +331 -0
  96. package/src/core/shell.js +128 -13
  97. package/src/core/ssl-issuer.js +627 -0
  98. package/src/core/updater.js +295 -0
  99. package/src/core/validators.js +99 -0
  100. package/src/dashboard/controllers/authController.js +316 -0
  101. package/src/dashboard/controllers/deploymentsController.js +479 -0
  102. package/src/dashboard/controllers/domainsController.js +403 -0
  103. package/src/dashboard/controllers/hubController.js +135 -0
  104. package/src/dashboard/controllers/nginxController.js +146 -0
  105. package/src/dashboard/controllers/processesController.js +368 -0
  106. package/src/dashboard/controllers/settingsController.js +503 -0
  107. package/src/dashboard/controllers/sslController.js +452 -0
  108. package/src/dashboard/lib/daemonBridge.js +163 -0
  109. package/src/dashboard/lib/localRequest.js +235 -0
  110. package/src/dashboard/lib/loginRateLimit.js +119 -0
  111. package/src/dashboard/lib/requireAuth.js +80 -0
  112. package/src/dashboard/public/img/icon.png +0 -0
  113. package/src/dashboard/public/img/icon_b.png +0 -0
  114. package/src/dashboard/public/js/app.js +595 -19
  115. package/src/dashboard/routes/auth.js +14 -33
  116. package/src/dashboard/routes/deployments.js +46 -0
  117. package/src/dashboard/routes/domains.js +20 -363
  118. package/src/dashboard/routes/hub.js +22 -0
  119. package/src/dashboard/routes/nginx.js +22 -146
  120. package/src/dashboard/routes/processes.js +29 -0
  121. package/src/dashboard/routes/settings.js +25 -232
  122. package/src/dashboard/routes/ssl.js +18 -276
  123. package/src/dashboard/server.js +279 -165
  124. package/src/dashboard/socketManager.js +246 -0
  125. package/src/dashboard/views/index.ejs +1 -0
  126. package/src/dashboard/views/partials/domain-form.ejs +64 -1
  127. package/src/dashboard/views/partials/login.ejs +69 -8
  128. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  129. package/src/dashboard/views/partials/settings-panel.ejs +549 -118
  130. package/src/dashboard/views/partials/sidebar.ejs +3 -1
  131. package/src/dashboard/lib/domains-db.js +0 -51
  132. /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
@@ -0,0 +1,294 @@
1
+ /**
2
+ * core/daemon/lock.js
3
+ *
4
+ * Single-instance lock for the background daemon, and the signal the dashboard
5
+ * uses to decide whether it should run the jobs itself.
6
+ *
7
+ * The lock is a JSON file in the data directory holding a pid, a start time and
8
+ * a heartbeat the owner refreshes every few seconds. Two readers care about it:
9
+ *
10
+ * - `ezz daemon` refuses to start when another daemon already holds it.
11
+ * - `ezz --dash` runs the background jobs only while NO daemon holds it, and
12
+ * hands them over in either direction when that changes.
13
+ *
14
+ * ── Why a heartbeat and not just a pid ─────────────────────────────────────
15
+ *
16
+ * A pid alone is not enough in either direction. A crashed daemon leaves its
17
+ * pid behind, and the OS will eventually hand that number to something else —
18
+ * so a live pid does not prove OUR process is alive. A heartbeat alone is not
19
+ * enough either: a daemon stopped at a breakpoint, or a machine resumed from
20
+ * sleep, has a stale heartbeat while still holding the socket.
21
+ *
22
+ * So a lock is considered dead only when BOTH say so: the heartbeat is older
23
+ * than STALE_AFTER_MS *and* the pid is not running. That errs toward leaving a
24
+ * questionable lock alone, which is the safe direction — two daemons competing
25
+ * for the hub socket is worse than none, and "none" is visible to the user
26
+ * while "two" is not.
27
+ */
28
+
29
+ import fs from 'fs';
30
+ import path from 'path';
31
+ import { getDataDir } from '../platform.js';
32
+
33
+ /** How often the owner refreshes the heartbeat. */
34
+ export const HEARTBEAT_INTERVAL_MS = 5_000;
35
+
36
+ /**
37
+ * How old a heartbeat may get before the lock is a candidate for recovery.
38
+ * Four missed beats: long enough to survive a slow disk or a GC pause, short
39
+ * enough that a real crash is recovered inside a dashboard poll interval.
40
+ */
41
+ export const STALE_AFTER_MS = 20_000;
42
+
43
+ /** Lock file name inside the data directory. */
44
+ const LOCK_FILE = 'daemon.lock';
45
+
46
+ /** @returns {string} Absolute path to the lock file. */
47
+ export function lockPath(dataDir = getDataDir()) {
48
+ return path.join(dataDir, LOCK_FILE);
49
+ }
50
+
51
+ /**
52
+ * True when a process with this pid exists.
53
+ *
54
+ * Signal 0 performs the permission and existence checks without delivering
55
+ * anything. EPERM means the process exists but belongs to another user, which
56
+ * for our purposes is "alive".
57
+ *
58
+ * @param {number} pid
59
+ * @returns {boolean}
60
+ */
61
+ export function isPidAlive(pid) {
62
+ if (!Number.isInteger(pid) || pid <= 0) return false;
63
+ try {
64
+ process.kill(pid, 0);
65
+ return true;
66
+ } catch (err) {
67
+ return err?.code === 'EPERM';
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Reads the lock without judging it.
73
+ * @returns {{ pid: number, startedAt: number, heartbeatAt: number, version: string|null, mode: string|null }|null}
74
+ */
75
+ export function readLock(dataDir = getDataDir()) {
76
+ try {
77
+ const raw = fs.readFileSync(lockPath(dataDir), 'utf8');
78
+ const parsed = JSON.parse(raw);
79
+ if (!Number.isInteger(parsed?.pid)) return null;
80
+ return {
81
+ pid: parsed.pid,
82
+ startedAt: Number(parsed.startedAt) || 0,
83
+ heartbeatAt: Number(parsed.heartbeatAt) || 0,
84
+ version: parsed.version ?? null,
85
+ mode: parsed.mode ?? null,
86
+ };
87
+ } catch {
88
+ // Missing, unreadable or truncated — all mean "no usable lock". A
89
+ // half-written file is possible if a daemon died mid-write, and treating
90
+ // that as absent is correct: nothing is holding it.
91
+ return null;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * The state of the daemon as far as anyone else can tell.
97
+ *
98
+ * @param {Object} [opts]
99
+ * @param {string} [opts.dataDir]
100
+ * @param {number} [opts.now] Injectable clock, for tests
101
+ * @returns {{ running: boolean, stale: boolean, lock: Object|null, age: number|null, reason: string }}
102
+ */
103
+ export function inspect({ dataDir = getDataDir(), now = Date.now() } = {}) {
104
+ const lock = readLock(dataDir);
105
+ if (!lock) return { running: false, stale: false, lock: null, age: null, reason: 'no lock file' };
106
+
107
+ const age = now - lock.heartbeatAt;
108
+ const alive = isPidAlive(lock.pid);
109
+ const fresh = age < STALE_AFTER_MS;
110
+
111
+ // Alive OR fresh counts as running. Both must fail before the lock is
112
+ // treated as abandoned — see the module header.
113
+ if (alive && fresh) {
114
+ return { running: true, stale: false, lock, age, reason: 'pid alive, heartbeat fresh' };
115
+ }
116
+ if (alive && !fresh) {
117
+ return { running: true, stale: false, lock, age, reason: `pid ${lock.pid} alive but heartbeat is ${Math.round(age / 1000)}s old` };
118
+ }
119
+ if (!alive && fresh) {
120
+ return { running: true, stale: false, lock, age, reason: 'heartbeat fresh but pid is gone; waiting for it to go stale' };
121
+ }
122
+
123
+ return {
124
+ running: false,
125
+ stale: true,
126
+ lock,
127
+ age,
128
+ reason: `pid ${lock.pid} is gone and the heartbeat is ${Math.round(age / 1000)}s old`,
129
+ };
130
+ }
131
+
132
+ /** Convenience: is a daemon holding this data directory right now? */
133
+ export function isDaemonRunning(opts = {}) {
134
+ return inspect(opts).running;
135
+ }
136
+
137
+ /**
138
+ * Takes the lock for this process.
139
+ *
140
+ * Recovers an abandoned lock, refuses a live one. The write is atomic — a
141
+ * temporary file renamed into place — so a reader can never see a half-written
142
+ * lock, and `wx` on the temp name means two daemons racing cannot both believe
143
+ * they created it.
144
+ *
145
+ * @param {Object} [opts]
146
+ * @param {string} [opts.dataDir]
147
+ * @param {string} [opts.version]
148
+ * @param {string} [opts.mode] Free-form label, e.g. 'daemon' or 'dashboard'
149
+ * @param {number} [opts.now]
150
+ * @returns {{ ok: true, recovered: boolean, lock: Object }
151
+ * | { ok: false, reason: string, lock: Object|null }}
152
+ */
153
+ export function acquire({
154
+ dataDir = getDataDir(),
155
+ version = null,
156
+ mode = 'daemon',
157
+ now = Date.now(),
158
+ } = {}) {
159
+ const state = inspect({ dataDir, now });
160
+
161
+ if (state.running) {
162
+ // Our own pid holding it is not a conflict: a re-acquire is idempotent so
163
+ // a restart inside one process does not deadlock itself.
164
+ if (state.lock?.pid === process.pid) {
165
+ return { ok: true, recovered: false, lock: write({ dataDir, version, mode, now }) };
166
+ }
167
+ return { ok: false, reason: state.reason, lock: state.lock };
168
+ }
169
+
170
+ return { ok: true, recovered: state.stale, lock: write({ dataDir, version, mode, now }) };
171
+ }
172
+
173
+ /**
174
+ * Refreshes the heartbeat.
175
+ *
176
+ * Returns false when the lock is gone or has been taken over, which the caller
177
+ * must treat as "I am no longer the owner" rather than ignoring: continuing to
178
+ * run jobs after losing the lock is exactly the duplicate-work case the lock
179
+ * exists to prevent.
180
+ *
181
+ * @returns {boolean} True while this process still owns the lock
182
+ */
183
+ export function heartbeat({ dataDir = getDataDir(), version = null, mode = 'daemon', now = Date.now() } = {}) {
184
+ const current = readLock(dataDir);
185
+ if (!current || current.pid !== process.pid) return false;
186
+
187
+ write({ dataDir, version, mode, now, startedAt: current.startedAt });
188
+ return true;
189
+ }
190
+
191
+ /**
192
+ * Releases the lock, but only if this process owns it.
193
+ * @returns {boolean} True when a lock was actually removed
194
+ */
195
+ export function release({ dataDir = getDataDir() } = {}) {
196
+ const current = readLock(dataDir);
197
+ if (!current || current.pid !== process.pid) return false;
198
+
199
+ try {
200
+ fs.unlinkSync(lockPath(dataDir));
201
+ return true;
202
+ } catch {
203
+ return false;
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Calls back whenever the lock file appears, changes or disappears.
209
+ *
210
+ * The dashboard polls ownership every 15 seconds, which is fine for noticing a
211
+ * daemon that went away but far too slow for one that arrived: for those
212
+ * seconds both processes ran the jobs, so both had a Hub agent connected with
213
+ * the same serverId and the Hub evicted them in turn. Watching the file closes
214
+ * that window to milliseconds.
215
+ *
216
+ * The DIRECTORY is watched rather than the file, because the file does not
217
+ * exist when there is no daemon — and that absence is exactly the state a
218
+ * watcher needs to see change. `fs.watch` on a missing path throws.
219
+ *
220
+ * Events are debounced: an atomic write is a create plus a rename, which
221
+ * surfaces as several events for one logical change.
222
+ *
223
+ * @param {Object} opts
224
+ * @param {string} [opts.dataDir]
225
+ * @param {() => void} opts.onChange
226
+ * @param {number} [opts.debounceMs]
227
+ * @returns {{ close: () => void, watching: boolean }}
228
+ */
229
+ export function watchLock({ dataDir = getDataDir(), onChange, debounceMs = 50 } = {}) {
230
+ let timer = null;
231
+ let watcher = null;
232
+
233
+ const fire = () => {
234
+ if (timer) clearTimeout(timer);
235
+ timer = setTimeout(() => {
236
+ timer = null;
237
+ try {
238
+ onChange?.();
239
+ } catch (err) {
240
+ console.error('[lock] watch handler threw:', err.message);
241
+ }
242
+ }, debounceMs);
243
+ };
244
+
245
+ try {
246
+ fs.mkdirSync(dataDir, { recursive: true });
247
+ watcher = fs.watch(dataDir, (_event, filename) => {
248
+ // A rename within the directory reports the temp name too; only the
249
+ // lock itself matters. A null filename (possible on some platforms)
250
+ // is treated as "something changed", which is the safe direction.
251
+ if (!filename || filename === LOCK_FILE) fire();
252
+ });
253
+ watcher.on('error', () => { /* the poll remains as the fallback */ });
254
+ } catch {
255
+ // No watcher is survivable: ownership is still re-checked on the poll, so
256
+ // the hand-over is slow rather than broken.
257
+ watcher = null;
258
+ }
259
+
260
+ return {
261
+ watching: watcher !== null,
262
+ close() {
263
+ if (timer) clearTimeout(timer);
264
+ timer = null;
265
+ try { watcher?.close(); } catch { /* already closed */ }
266
+ watcher = null;
267
+ },
268
+ };
269
+ }
270
+
271
+ /**
272
+ * Writes the lock atomically.
273
+ *
274
+ * `rename` is atomic on both platforms for a same-directory move, so a reader
275
+ * either sees the old file or the new one — never a partial write.
276
+ */
277
+ function write({ dataDir, version, mode, now, startedAt }) {
278
+ const payload = {
279
+ pid: process.pid,
280
+ startedAt: startedAt ?? now,
281
+ heartbeatAt: now,
282
+ version,
283
+ mode,
284
+ };
285
+
286
+ const target = lockPath(dataDir);
287
+ const temp = `${target}.${process.pid}.tmp`;
288
+
289
+ fs.mkdirSync(dataDir, { recursive: true });
290
+ fs.writeFileSync(temp, `${JSON.stringify(payload)}\n`, { encoding: 'utf8', mode: 0o600 });
291
+ fs.renameSync(temp, target);
292
+
293
+ return payload;
294
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * core/daemon/run.js
3
+ *
4
+ * `ezz daemon` — the long-running background process.
5
+ *
6
+ * Runs in the FOREGROUND and, by default, opens NO HTTP port. Both are
7
+ * deliberate:
8
+ *
9
+ * - Foreground, because every service manager this project targets (Windows
10
+ * Services via WinSW, systemd, and the Startup-folder supervisor) wants a
11
+ * process it can start, watch and stop. A process that daemonises itself is
12
+ * one the manager immediately believes has exited.
13
+ * - No port, because the daemon does monitoring, not serving. A port would
14
+ * need its own bind policy, authentication and firewall story; the
15
+ * dashboard already has all three and is started on demand. Live events
16
+ * reach it over the local IPC channel instead (core/daemon/ipc.js).
17
+ *
18
+ * The one exception is opt-in: the deploy hook (core/deploy/hookServer.js),
19
+ * which a CI job calls to trigger a deployment and which therefore has to
20
+ * be there when the dashboard is not. It is off until switched on, binds
21
+ * to loopback unless told otherwise, serves only /.ez-deploy/, and carries
22
+ * its own bind policy and per-app token — the "own story" the paragraph
23
+ * above says a port needs. It is started with the jobs, not here.
24
+ *
25
+ * What it owns while it runs: the single-instance lock, the monitors, the
26
+ * revision watcher, the hub agent, and the IPC server that feeds an open
27
+ * dashboard.
28
+ */
29
+
30
+ import { createRequire } from 'module';
31
+
32
+ import { getDataDir } from '../platform.js';
33
+ import { startJobs } from '../jobs/index.js';
34
+ import { startIpcServer } from './ipc.js';
35
+ import { inspect } from './lock.js';
36
+ import { watchForStop } from './stopRequest.js';
37
+ import { getHubAgentStatus } from '../hub/agent.js';
38
+ import { loadConfig } from '../config.js';
39
+ import { ensureCode as ensureSetupCode, describe as describeSetupCode } from '../setupCode.js';
40
+
41
+ const require = createRequire(import.meta.url);
42
+ const { version } = require('../../../package.json');
43
+
44
+ /**
45
+ * Starts the daemon and resolves when it is up.
46
+ *
47
+ * It does NOT resolve when the daemon stops — the caller keeps the process
48
+ * alive; `stop()` on the returned handle is for tests and for the signal
49
+ * handlers installed by runDaemon().
50
+ *
51
+ * @param {Object} [opts]
52
+ * @param {string} [opts.dataDir]
53
+ * @param {Object} [opts.intervals] Monitor interval overrides, for tests
54
+ * @param {boolean} [opts.hub] Start the hub agent (default true)
55
+ * @param {(line: string) => void} [opts.log]
56
+ * @returns {Promise<{ ok: true, stop: () => Promise<void>, ipcPath: string, state: () => Object }
57
+ * | { ok: false, reason: string, lock: Object|null }>}
58
+ */
59
+ export async function startDaemon({
60
+ dataDir = getDataDir(),
61
+ intervals = {},
62
+ hub = true,
63
+ log = (line) => process.stdout.write(`${line}\n`),
64
+ // Lets a test drive the stop-request path without taking its own process
65
+ // down. Production always wants the exit: it is the signal the supervisor
66
+ // reads to decide not to restart.
67
+ exitOnStop = true,
68
+ } = {}) {
69
+ const jobs = startJobs({ role: 'daemon', dataDir, version, intervals, hub });
70
+
71
+ // startJobs() returns a failure object rather than throwing when another
72
+ // daemon holds the lock: that is an ordinary outcome, not an error, and the
73
+ // caller decides how to report it.
74
+ if (jobs.ok === false) {
75
+ return { ok: false, reason: jobs.reason, lock: jobs.lock };
76
+ }
77
+
78
+ log(`Easy DevOps daemon v${version}`);
79
+ log(` data directory : ${dataDir}`);
80
+ log(` pid : ${process.pid}`);
81
+
82
+ // The lock is taken by now, which is what an open dashboard watches for. It
83
+ // stands down immediately; this waits until it actually has, so the Hub
84
+ // never sees two agents for one server. Bounded — see core/jobs/owner.js.
85
+ await jobs.ready();
86
+
87
+ let ipc = null;
88
+ try {
89
+ ipc = await startIpcServer({
90
+ dataDir,
91
+ // A dashboard that connects mid-flight has missed every event so far.
92
+ // The hello frame gives it the daemon's identity immediately, so it can
93
+ // show the "background service is running" banner without waiting for
94
+ // the next poll to come round.
95
+ hello: () => ({
96
+ version,
97
+ pid: process.pid,
98
+ startedAt: inspect({ dataDir }).lock?.startedAt ?? Date.now(),
99
+ hub: getHubAgentStatus(),
100
+ }),
101
+ });
102
+ log(` event channel : ${ipc.path}`);
103
+ } catch (err) {
104
+ // The daemon is still useful without IPC: monitoring and notifications do
105
+ // not depend on it, only the live view in an open dashboard does. Failing
106
+ // to start entirely would trade all of that for one feature.
107
+ log(` event channel : unavailable (${err.message})`);
108
+ log(' The dashboard will fall back to polling. Background work continues.');
109
+ }
110
+
111
+ // The hub agent is NOT started here: startJobs() owns it, because it must
112
+ // start and stop with job ownership rather than with this process. See the
113
+ // comment in core/jobs/index.js — two agents on one pairing would execute
114
+ // every Hub command twice.
115
+ const agent = getHubAgentStatus();
116
+ log(` hub agent : ${agent?.status ?? 'unknown'}`);
117
+
118
+ // The first-run setup code, while the dashboard still has no password.
119
+ // The daemon's stdout IS the service log (WinSW, systemd, the Startup
120
+ // supervisor all capture it), which is the second of the two places the
121
+ // code is allowed to appear - the other being a local terminal. Whichever
122
+ // of the daemon and the dashboard starts first issues it; the other says
123
+ // one is outstanding, because nothing stores the cleartext to re-print.
124
+ try {
125
+ const code = await ensureSetupCode({ config: loadConfig() });
126
+ if (code.pending) for (const line of describeSetupCode(code)) log(line);
127
+ } catch (err) {
128
+ log(` setup code : unavailable (${err.message})`);
129
+ }
130
+
131
+ log('');
132
+ log('Running. Background jobs are owned by this process.');
133
+
134
+ let stopping = null;
135
+
136
+ const handle = {
137
+ ok: true,
138
+ ipcPath: ipc?.path ?? null,
139
+ state: () => ({ ...jobs.state(), version, pid: process.pid, ipcPath: ipc?.path ?? null }),
140
+
141
+ /** Idempotent: a second signal while shutting down must not run it twice. */
142
+ stop() {
143
+ if (stopping) return stopping;
144
+ stopping = (async () => {
145
+ log('Stopping...');
146
+ stopWatch.stop();
147
+ if (ipc) {
148
+ try { await ipc.close(); } catch { /* best effort */ }
149
+ }
150
+ await jobs.stop();
151
+ log('Stopped.');
152
+ })();
153
+ return stopping;
154
+ },
155
+ };
156
+
157
+ // `ezz service stop` has no service manager to go through in Windows
158
+ // Personal mode, so it writes a request file and the daemon answers it by
159
+ // exiting with code 0. The supervisor treats 0 as "asked to stop" and does
160
+ // not restart — which is what makes a stop actually stick.
161
+ //
162
+ // The file is deliberately NOT cleared here: it is what keeps the supervisor
163
+ // from starting another daemon. The logon bootstrap and `ezz service start`
164
+ // clear it, which is what makes a stop temporary rather than permanent.
165
+ const stopWatch = watchForStop({
166
+ dataDir,
167
+ onStop(request) {
168
+ log(`Stop requested${request.reason ? ` (${request.reason})` : ''}. Exiting.`);
169
+ // Exit code 0 is the signal: the supervisor reads it as "asked to stop"
170
+ // and does not restart. A non-zero exit would be restarted.
171
+ handle.stop().then(
172
+ () => { if (exitOnStop) process.exit(0); },
173
+ () => { if (exitOnStop) process.exit(0); },
174
+ );
175
+ },
176
+ });
177
+
178
+ // Checked once immediately: a daemon started while a stop is still pending
179
+ // must not sit there running. Only reachable if something started it without
180
+ // clearing the request, which `start` and the logon bootstrap both do.
181
+ stopWatch.check();
182
+
183
+ return handle;
184
+ }
185
+
186
+ /**
187
+ * The CLI entry: starts the daemon, installs signal handlers, and keeps the
188
+ * process alive until it is told to stop.
189
+ *
190
+ * @param {Object} [opts] Passed through to startDaemon()
191
+ * @returns {Promise<number>} Process exit code
192
+ */
193
+ export async function runDaemon(opts = {}) {
194
+ const started = await startDaemon(opts);
195
+
196
+ if (!started.ok) {
197
+ process.stderr.write(
198
+ `\nAnother Easy DevOps daemon is already running.\n` +
199
+ ` ${started.reason}\n\n` +
200
+ `Only one may own the background jobs at a time.\n` +
201
+ ` ezz service status see what is running\n` +
202
+ ` ezz service restart restart the installed service\n\n`,
203
+ );
204
+ return 1;
205
+ }
206
+
207
+ let code = 0;
208
+
209
+ const shutdown = async (signal) => {
210
+ process.stdout.write(`\nReceived ${signal}.\n`);
211
+ await started.stop();
212
+ process.exit(code);
213
+ };
214
+
215
+ process.on('SIGINT', () => { shutdown('SIGINT'); });
216
+ process.on('SIGTERM', () => { shutdown('SIGTERM'); });
217
+
218
+ // Windows service managers stop a console process by closing its console,
219
+ // which Node surfaces as SIGHUP. Without this the process is killed outright
220
+ // and the lock file is left behind for the next start to recover.
221
+ process.on('SIGHUP', () => { shutdown('SIGHUP'); });
222
+
223
+ // An unexpected throw must not leave a daemon that holds the lock but runs
224
+ // nothing. Release and exit non-zero so the service manager restarts it.
225
+ process.on('uncaughtException', async (err) => {
226
+ process.stderr.write(`\n[daemon] uncaught exception: ${err.stack || err.message}\n`);
227
+ code = 1;
228
+ await started.stop();
229
+ process.exit(1);
230
+ });
231
+
232
+ process.on('unhandledRejection', (reason) => {
233
+ // Logged, not fatal: a rejected push to the Hub or a failed status read is
234
+ // not a reason to take down monitoring.
235
+ process.stderr.write(`[daemon] unhandled rejection: ${reason?.stack || reason}\n`);
236
+ });
237
+
238
+ // Nothing further to do on this stack. The monitors' intervals and the IPC
239
+ // server keep the event loop alive.
240
+ return new Promise(() => {});
241
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * core/daemon/stopRequest.js
3
+ *
4
+ * How `ezz service stop` reaches a daemon that has no service manager behind
5
+ * it — Windows Personal mode, where the daemon is started by a hidden
6
+ * Startup-folder supervisor and there is nothing to `sc stop`.
7
+ *
8
+ * ── Why a file and not the IPC channel ─────────────────────────────────────
9
+ *
10
+ * The IPC channel in core/daemon/ipc.js is deliberately **one-way**: the
11
+ * daemon sends events and accepts no commands, because it may run as a service
12
+ * account with access the dashboard user does not have. Adding a "stop"
13
+ * command would turn that channel into a control surface and undo the
14
+ * guarantee. A file in the data directory stays on the right side of that
15
+ * line: writing it needs write access to the data directory, which is the same
16
+ * permission that lets you edit the database anyway.
17
+ *
18
+ * ── The protocol ───────────────────────────────────────────────────────────
19
+ *
20
+ * 1. `ezz service stop` writes `<dataDir>/daemon.stop`.
21
+ * 2. The daemon notices within a second and exits with code **0**.
22
+ * 3. The supervisor treats exit 0 as "it was asked to stop" and does not
23
+ * restart it. It also checks for the file before each start, so a stop
24
+ * lands even while the supervisor is mid-backoff with no daemon running.
25
+ * 4. The file is NOT removed by either of them — it is what keeps the
26
+ * supervisor from restarting. It is cleared by the logon bootstrap and by
27
+ * `ezz service start`, which is exactly what makes a stop temporary:
28
+ * back at the next logon, or when the user starts it again.
29
+ *
30
+ * Only Personal mode writes this file. Server mode and Linux have real service
31
+ * managers, and `sc stop` / `systemctl stop` are authoritative there — adding
32
+ * a marker a restarted service would then obey would break "back at boot".
33
+ */
34
+
35
+ import fs from 'fs';
36
+ import path from 'path';
37
+
38
+ import { getDataDir } from '../platform.js';
39
+
40
+ /** How often the daemon checks for the request. */
41
+ export const STOP_POLL_MS = 1_000;
42
+
43
+ const STOP_FILE = 'daemon.stop';
44
+
45
+ /** @returns {string} Absolute path to the stop-request file. */
46
+ export function stopRequestPath(dataDir = getDataDir()) {
47
+ return path.join(dataDir, STOP_FILE);
48
+ }
49
+
50
+ /**
51
+ * Asks the running daemon to stop.
52
+ *
53
+ * @param {Object} [opts]
54
+ * @param {string} [opts.dataDir]
55
+ * @param {string} [opts.reason] Recorded for the log, never acted on
56
+ * @returns {{ ok: boolean, path: string, reason?: string }}
57
+ */
58
+ export function requestStop({ dataDir = getDataDir(), reason = 'ezz service stop' } = {}) {
59
+ const file = stopRequestPath(dataDir);
60
+
61
+ try {
62
+ fs.mkdirSync(dataDir, { recursive: true });
63
+ fs.writeFileSync(
64
+ file,
65
+ `${JSON.stringify({ at: new Date().toISOString(), by: process.pid, reason })}\n`,
66
+ { encoding: 'utf8', mode: 0o600 },
67
+ );
68
+ return { ok: true, path: file };
69
+ } catch (err) {
70
+ return { ok: false, path: file, reason: `could not write ${file}: ${err.message}` };
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Whether a stop has been requested and not yet cleared.
76
+ *
77
+ * @param {Object} [opts]
78
+ * @returns {{ requested: boolean, at: string|null, reason: string|null }}
79
+ */
80
+ export function readStopRequest({ dataDir = getDataDir() } = {}) {
81
+ const file = stopRequestPath(dataDir);
82
+
83
+ let raw;
84
+ try {
85
+ raw = fs.readFileSync(file, 'utf8');
86
+ } catch {
87
+ return { requested: false, at: null, reason: null };
88
+ }
89
+
90
+ // An unparseable file still counts as a request: its presence is the signal,
91
+ // and the contents are only there to explain it afterwards. Treating a
92
+ // half-written file as "no request" would make a stop silently fail.
93
+ try {
94
+ const parsed = JSON.parse(raw);
95
+ return { requested: true, at: parsed?.at ?? null, reason: parsed?.reason ?? null };
96
+ } catch {
97
+ return { requested: true, at: null, reason: null };
98
+ }
99
+ }
100
+
101
+ /** Convenience boolean. */
102
+ export function isStopRequested(opts = {}) {
103
+ return readStopRequest(opts).requested;
104
+ }
105
+
106
+ /**
107
+ * Clears the request, so the supervisor may start the daemon again.
108
+ *
109
+ * Called by the logon bootstrap and by `ezz service start` — never by the
110
+ * daemon or the supervisor, which both need the file to persist in order to
111
+ * stay stopped.
112
+ *
113
+ * @returns {boolean} True when a request was actually removed
114
+ */
115
+ export function clearStopRequest({ dataDir = getDataDir() } = {}) {
116
+ try {
117
+ fs.rmSync(stopRequestPath(dataDir), { force: true });
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Watches for a stop request and calls back once.
126
+ *
127
+ * A poll rather than `fs.watch`: the file is created by another process, and
128
+ * `fs.watch` on a directory to catch a creation is unreliable across platforms
129
+ * and network shares. A one-second `existsSync` is cheap and cannot miss the
130
+ * event.
131
+ *
132
+ * @param {Object} opts
133
+ * @param {string} [opts.dataDir]
134
+ * @param {number} [opts.intervalMs]
135
+ * @param {(request: { at: string|null, reason: string|null }) => void} opts.onStop
136
+ * @returns {{ stop: () => void, check: () => boolean }}
137
+ */
138
+ export function watchForStop({ dataDir = getDataDir(), intervalMs = STOP_POLL_MS, onStop } = {}) {
139
+ let fired = false;
140
+
141
+ const check = () => {
142
+ if (fired) return true;
143
+
144
+ const request = readStopRequest({ dataDir });
145
+ if (!request.requested) return false;
146
+
147
+ fired = true;
148
+ try {
149
+ onStop?.(request);
150
+ } catch (err) {
151
+ console.error('[daemon] stop handler threw:', err.message);
152
+ }
153
+ return true;
154
+ };
155
+
156
+ const timer = setInterval(check, intervalMs);
157
+
158
+ return {
159
+ stop() { clearInterval(timer); },
160
+ check,
161
+ };
162
+ }