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,452 @@
1
+ import { listAllCerts } from '../../core/cert-reader.js';
2
+ import { issueCert } from '../../cli/managers/ssl-manager.js';
3
+ import {
4
+ renewCertificate,
5
+ describeRenewal,
6
+ describeCertificate,
7
+ getAutoRenewSettings,
8
+ getAutoRenewState,
9
+ autoRenewPlan,
10
+ } from '../../core/cert-renewal.js';
11
+ import { describeIssuance, prepareDomainForHttpChallenge } from '../../core/ssl-issuer.js';
12
+ import { findDomain, getDomains } from '../../core/domains-db.js';
13
+ import { loadConfig } from '../../core/config.js';
14
+ import { promises as dns } from 'dns';
15
+
16
+ // In-memory DNS challenge state
17
+ // Keyed by domain name. Entries are cleaned up when the ACME process exits
18
+ // or when cancelled. Entries older than 10 minutes are forcibly removed.
19
+ const pendingDnsChallenges = new Map();
20
+
21
+ const dnsSweepTimer = setInterval(() => {
22
+ const now = Date.now();
23
+ for (const [domain, state] of pendingDnsChallenges) {
24
+ if (now - state.createdAt > 10 * 60 * 1000) {
25
+ state.confirmDeferred.reject(new Error('DNS challenge timed out after 10 minutes'));
26
+ pendingDnsChallenges.delete(domain);
27
+ }
28
+ }
29
+ }, 60000);
30
+
31
+ /**
32
+ * Stops the DNS-challenge sweep and rejects anything still pending.
33
+ *
34
+ * Called by the dashboard's shutdown(): this interval is created at module
35
+ * load and would otherwise keep the event loop alive, so `ezz --dash` would
36
+ * never exit on Ctrl+C. Safe to call more than once.
37
+ */
38
+ export function stopSslController() {
39
+ clearInterval(dnsSweepTimer);
40
+
41
+ for (const [domain, state] of pendingDnsChallenges) {
42
+ try {
43
+ state.confirmDeferred.reject(new Error('Dashboard is shutting down'));
44
+ } catch { /* already settled */ }
45
+ pendingDnsChallenges.delete(domain);
46
+ }
47
+ }
48
+
49
+ class SslController {
50
+ async create(req, res, next) {
51
+ try {
52
+ const { domain, www = false, validationMethod = 'http', email = null } = req.body ?? {};
53
+
54
+ if (!domain || typeof domain !== 'string' || !domain.trim()) {
55
+ return res.status(400).json({ error: 'domain is required' });
56
+ }
57
+
58
+ const domainKey = domain.trim();
59
+ const config = loadConfig();
60
+ const acmeEmail = email || config.acmeEmail;
61
+
62
+ if (validationMethod === 'dns') {
63
+ // Two-phase flow: spawn ACME process, wait for TXT record, respond 202, pause until confirm.
64
+ let confirmResolve, confirmReject;
65
+ const confirmPromise = new Promise((resolve, reject) => {
66
+ confirmResolve = resolve;
67
+ confirmReject = reject;
68
+ });
69
+
70
+ let resultResolve;
71
+ const resultPromise = new Promise((resolve) => { resultResolve = resolve; });
72
+
73
+ // Track whether a response has already been sent (202 from onDnsChallenge)
74
+ let responseSent = false;
75
+
76
+ const onDnsChallenge = async (txtName, txtValue) => {
77
+ responseSent = true;
78
+ pendingDnsChallenges.set(domainKey, {
79
+ domain: domainKey,
80
+ txtName,
81
+ txtValue,
82
+ confirmDeferred: { resolve: confirmResolve, reject: confirmReject },
83
+ resultPromise,
84
+ createdAt: Date.now(),
85
+ });
86
+
87
+ res.status(202).json({
88
+ status: 'waiting_dns',
89
+ domain: domainKey,
90
+ txtName,
91
+ txtValue,
92
+ hint: 'Add a DNS TXT record with the name and value above, then call POST /api/ssl/create-confirm',
93
+ });
94
+
95
+ // Pause until user calls /create-confirm (resolves) or /create-cancel (rejects)
96
+ await confirmPromise;
97
+ };
98
+
99
+ // Run issueCert in the background — it will call onDnsChallenge which sends 202 and pauses.
100
+ issueCert(domainKey, { www: !!www, validationMethod: 'dns', email: acmeEmail, onDnsChallenge })
101
+ .then(result => {
102
+ resultResolve(result);
103
+ pendingDnsChallenges.delete(domainKey);
104
+ if (!responseSent) {
105
+ responseSent = true;
106
+ if (result.success) {
107
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
108
+ }
109
+ const { step } = result.error ?? {};
110
+ if (step === 'email configuration') {
111
+ return res.status(400).json({ error: 'email_required', hint: 'Configure acmeEmail in settings or provide email parameter.' });
112
+ }
113
+ return res.status(500).json({ success: false, error: result.error });
114
+ }
115
+ })
116
+ .catch(err => {
117
+ const errResult = {
118
+ success: false,
119
+ certPath: null,
120
+ keyPath: null,
121
+ error: {
122
+ step: 'certificate issuance',
123
+ cause: err.message,
124
+ consequence: 'Unexpected error during DNS certificate issuance.',
125
+ nginxRunning: true,
126
+ configSaved: false,
127
+ },
128
+ };
129
+ resultResolve(errResult);
130
+ pendingDnsChallenges.delete(domainKey);
131
+ if (!responseSent) {
132
+ responseSent = true;
133
+ return res.status(500).json({ success: false, error: errResult.error });
134
+ }
135
+ });
136
+
137
+ // The response is sent either by onDnsChallenge (202) or by the .then()/.catch() above.
138
+ return;
139
+ }
140
+
141
+ // HTTP validation path (synchronous — responds when complete).
142
+ //
143
+ // Flow 2: make sure nginx can answer the challenge first. For a domain
144
+ // that is already configured this regenerates a stale config; for a new
145
+ // one it writes a temporary HTTP-only config. Either way nginx is only
146
+ // reloaded, never stopped.
147
+ const existing = findDomain(domainKey);
148
+ let prepared = null;
149
+ if (existing) {
150
+ prepared = await prepareDomainForHttpChallenge(existing);
151
+ if (!prepared.ok) {
152
+ return res.status(500).json({
153
+ error: 'challenge_setup_failed',
154
+ detail: prepared.error,
155
+ hint: 'nginx could not be prepared to answer the ACME challenge. Check the nginx config and try again.',
156
+ });
157
+ }
158
+ }
159
+
160
+ const result = await issueCert(domainKey, { www: !!www, validationMethod: 'http', email: acmeEmail });
161
+
162
+ if (result.success) {
163
+ // Tell the UI how the challenge ran: proxy (nginx stayed up), or a
164
+ // standalone fallback with how long nginx was stopped.
165
+ return res.json({
166
+ success: true,
167
+ certPath: result.certPath,
168
+ keyPath: result.keyPath,
169
+ mode: result.mode,
170
+ fellBack: result.fellBack,
171
+ nginxDownMs: result.nginxDownMs,
172
+ staging: result.staging,
173
+ summary: describeIssuance(result),
174
+ });
175
+ }
176
+
177
+ const { step } = result.error;
178
+ if (step === 'email configuration') {
179
+ return res.status(400).json({
180
+ error: 'email_required',
181
+ hint: 'Configure acmeEmail in settings or provide email parameter.',
182
+ });
183
+ }
184
+ if (step === 'port 80 check') {
185
+ return res.status(409).json({
186
+ error: 'port_busy',
187
+ detail: result.error.cause,
188
+ hint: 'Stop the process using port 80 and try again.',
189
+ });
190
+ }
191
+ return res.status(500).json({ success: false, error: result.error });
192
+ } catch (error) {
193
+ next(error);
194
+ }
195
+ }
196
+
197
+ async createConfirm(req, res, next) {
198
+ try {
199
+ const { domain } = req.body ?? {};
200
+ const domainKey = domain?.trim();
201
+ const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
202
+
203
+ if (!state) {
204
+ return res.status(404).json({
205
+ error: 'no_pending_challenge',
206
+ hint: 'No DNS challenge is pending for this domain. Start a new certificate issuance.',
207
+ });
208
+ }
209
+
210
+ try {
211
+ const records = await dns.resolveTxt(`_acme-challenge.${domainKey}`);
212
+ const flatRecords = records.flat();
213
+
214
+ const found = flatRecords.includes(state.txtValue);
215
+ if (!found) {
216
+ return res.status(400).json({
217
+ error: 'dns_not_propagated',
218
+ hint: 'The expected TXT record value was not found. Make sure you added the correct TXT record and wait a few minutes for DNS propagation.',
219
+ expected: state.txtValue,
220
+ found: flatRecords,
221
+ });
222
+ }
223
+ } catch (err) {
224
+ return res.status(400).json({
225
+ error: 'dns_lookup_failed',
226
+ hint: 'Failed to lookup the expected TXT record. Make sure you added the correct TXT record.',
227
+ detail: err.message,
228
+ });
229
+ }
230
+ // Signal issueCert() to continue with the ACME process
231
+ await state.confirmDeferred.resolve();
232
+
233
+ // Wait for the ACME process to complete
234
+ const result = await state.resultPromise;
235
+ pendingDnsChallenges.delete(domainKey);
236
+
237
+ if (result.success) {
238
+ // Tell the UI how the challenge ran: proxy (nginx stayed up), or a
239
+ // standalone fallback with how long nginx was stopped.
240
+ return res.json({
241
+ success: true,
242
+ certPath: result.certPath,
243
+ keyPath: result.keyPath,
244
+ mode: result.mode,
245
+ fellBack: result.fellBack,
246
+ nginxDownMs: result.nginxDownMs,
247
+ staging: result.staging,
248
+ summary: describeIssuance(result),
249
+ });
250
+ }
251
+ return res.status(500).json({ success: false, error: result.error });
252
+ } catch (error) {
253
+ next(error);
254
+ }
255
+ }
256
+
257
+ async createCancel(req, res, next) {
258
+ try {
259
+ const { domain } = req.body ?? {};
260
+ const domainKey = domain?.trim();
261
+ const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
262
+
263
+ if (!state) {
264
+ return res.status(404).json({
265
+ error: 'no_pending_challenge',
266
+ hint: 'No DNS challenge is pending for this domain.',
267
+ });
268
+ }
269
+
270
+ // Reject the deferred — issueCert() will return a failure result
271
+ state.confirmDeferred.reject(new Error('cancelled by user'));
272
+ pendingDnsChallenges.delete(domainKey);
273
+
274
+ return res.json({ cancelled: true });
275
+ } catch (error) {
276
+ next(error);
277
+ }
278
+ }
279
+
280
+ async list(req, res, next) {
281
+ try {
282
+ const certs = await listAllCerts();
283
+
284
+ // Additive: what the background job intends for each certificate, so the
285
+ // UI can show "auto-renews" / "manual renewal" instead of leaving the
286
+ // operator to guess. Computed by the same function the job uses.
287
+ const config = loadConfig();
288
+ const settings = getAutoRenewSettings(config);
289
+ const domains = getDomains();
290
+ const state = getAutoRenewState();
291
+
292
+ const withPlan = await Promise.all(certs.map(async (cert) => {
293
+ let plan = 'off';
294
+ try {
295
+ const info = await describeCertificate(cert.domain);
296
+ plan = autoRenewPlan({ certDomain: cert.domain, info, settings, domains, sslDir: config.sslDir });
297
+ } catch { /* unreadable certificate: report it as not handled */ }
298
+
299
+ const last = state[cert.domain] ?? null;
300
+ return {
301
+ ...cert,
302
+ autoRenew: plan,
303
+ autoRenewDays: settings.days,
304
+ lastAutoRenew: last
305
+ ? {
306
+ at: last.lastAttemptAt ?? null,
307
+ result: last.lastResult ?? null,
308
+ error: last.lastError ?? null,
309
+ }
310
+ : null,
311
+ };
312
+ }));
313
+
314
+ res.json(withPlan);
315
+ } catch (error) {
316
+ next(error);
317
+ }
318
+ }
319
+
320
+ async renew(req, res, next) {
321
+ try {
322
+ const domain = req.params.domain;
323
+ const config = loadConfig();
324
+
325
+ if (!config.acmeEmail) {
326
+ return res.status(400).json({
327
+ error: 'email_required',
328
+ hint: 'Configure acmeEmail in settings first.',
329
+ });
330
+ }
331
+
332
+ const certs = await listAllCerts();
333
+ const found = certs.find(cert => cert.domain === domain);
334
+ if (!found) {
335
+ return res.status(404).json({ error: `Domain '${domain}' not found` });
336
+ }
337
+
338
+ // renewCertificate() is the one renewal path (core/cert-renewal.js): it
339
+ // regenerates a config that predates the ACME challenge location, keeps
340
+ // the names the certificate already covers, and reloads nginx so the new
341
+ // certificate is the one being served.
342
+ const result = await renewCertificate(domain, { email: config.acmeEmail });
343
+
344
+ if (result.success) {
345
+ // Tell the UI how the challenge ran: proxy (nginx stayed up), or a
346
+ // standalone fallback with how long nginx was stopped.
347
+ return res.json({
348
+ success: true,
349
+ certPath: result.certPath,
350
+ keyPath: result.keyPath,
351
+ mode: result.mode,
352
+ fellBack: result.fellBack,
353
+ nginxDownMs: result.nginxDownMs,
354
+ staging: result.staging,
355
+ nginxReloaded: result.nginxReloaded,
356
+ summary: describeRenewal(result),
357
+ });
358
+ }
359
+
360
+ if (result.skipped === 'manual') {
361
+ return res.status(409).json({
362
+ error: 'manual_renewal_required',
363
+ detail: result.error.cause,
364
+ hint: 'Create the certificate again from the SSL page using the DNS method.',
365
+ });
366
+ }
367
+
368
+ const { step } = result.error;
369
+ if (step === 'challenge setup') {
370
+ return res.status(500).json({
371
+ error: 'challenge_setup_failed',
372
+ detail: result.error.cause,
373
+ hint: 'nginx could not be prepared to answer the ACME challenge.',
374
+ });
375
+ }
376
+ if (step === 'port 80 check') {
377
+ return res.status(409).json({
378
+ error: 'port_busy',
379
+ detail: result.error.cause,
380
+ hint: 'Stop the process using port 80 and try again.',
381
+ });
382
+ }
383
+ return res.status(500).json({ success: false, error: result.error });
384
+ } catch (error) {
385
+ next(error);
386
+ }
387
+ }
388
+
389
+ async renewAll(req, res, next) {
390
+ try {
391
+ const config = loadConfig();
392
+
393
+ if (!config.acmeEmail) {
394
+ return res.status(400).json({
395
+ error: 'email_required',
396
+ hint: 'Configure acmeEmail in settings first.',
397
+ });
398
+ }
399
+
400
+ const certs = await listAllCerts();
401
+ const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
402
+ const results = [];
403
+
404
+ for (const cert of expiring) {
405
+ const result = await renewCertificate(cert.domain, { email: config.acmeEmail });
406
+
407
+ if (!result.success && result.error?.step === 'challenge setup') {
408
+ results.push({
409
+ domain: cert.domain,
410
+ success: false,
411
+ certPath: null,
412
+ keyPath: null,
413
+ error: 'challenge_setup_failed',
414
+ detail: result.error.cause,
415
+ });
416
+ continue;
417
+ }
418
+
419
+ if (result.skipped === 'manual') {
420
+ results.push({
421
+ domain: cert.domain,
422
+ success: false,
423
+ certPath: null,
424
+ keyPath: null,
425
+ error: 'manual_renewal_required',
426
+ detail: result.error.cause,
427
+ });
428
+ continue;
429
+ }
430
+
431
+ results.push({
432
+ domain: cert.domain,
433
+ success: result.success,
434
+ certPath: result.certPath,
435
+ keyPath: result.keyPath,
436
+ mode: result.mode,
437
+ fellBack: result.fellBack,
438
+ nginxDownMs: result.nginxDownMs,
439
+ configRegenerated: Boolean(result.configRegenerated),
440
+ nginxReloaded: result.nginxReloaded,
441
+ summary: describeRenewal(result),
442
+ });
443
+ }
444
+
445
+ res.json(results);
446
+ } catch (error) {
447
+ next(error);
448
+ }
449
+ }
450
+ }
451
+
452
+ export default SslController;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * dashboard/lib/daemonBridge.js
3
+ *
4
+ * The dashboard's end of the daemon's event channel.
5
+ *
6
+ * It connects to the daemon's IPC socket and REPUBLISHES every frame onto this
7
+ * process's job bus. That one decision is what keeps the rest of the dashboard
8
+ * simple: dashboard/socketManager.js subscribes to the bus and nothing else,
9
+ * so it does not care whether an event came from monitors running here or from
10
+ * a daemon in another process. There is exactly one path to the browser.
11
+ *
12
+ * The two cases never overlap. When a daemon is running, core/jobs/index.js
13
+ * stops this process's monitors, so the only events on the bus are the ones
14
+ * arriving over IPC. When no daemon is running, there is nothing to connect to
15
+ * and the bus carries local events only.
16
+ *
17
+ * It also answers "is the service running?" for the banner — from the lock
18
+ * file, not from whether the socket happens to be connected. A daemon that is
19
+ * up but whose IPC failed to bind is still running the jobs, and telling the
20
+ * user to install a service they already have would be worse than saying
21
+ * nothing.
22
+ */
23
+
24
+ import { connectToDaemon } from '../../core/daemon/ipc.js';
25
+ import { publish } from '../../core/jobs/bus.js';
26
+ import { inspect, watchLock } from '../../core/daemon/lock.js';
27
+ import { getDataDir } from '../../core/platform.js';
28
+ import { backgroundServiceState, invalidateProbes } from '../../core/service/index.js';
29
+
30
+ let bridge = null;
31
+ let hello = null;
32
+ let lockWatch = null;
33
+ let lastAnnounced = null;
34
+
35
+ /**
36
+ * Starts the bridge. Safe to call when no daemon exists: the client retries
37
+ * quietly with backoff and connects if one appears later.
38
+ *
39
+ * @param {Object} [opts]
40
+ * @param {string} [opts.dataDir]
41
+ * @returns {{ stop: () => void, status: () => DaemonStatus }}
42
+ *
43
+ * @typedef {Object} DaemonStatus
44
+ * @property {boolean} running A daemon holds the lock
45
+ * @property {boolean} connected We have a live event channel to it
46
+ * @property {number|null} pid
47
+ * @property {string|null} version
48
+ * @property {number|null} startedAt
49
+ */
50
+ export function startDaemonBridge({ dataDir = getDataDir() } = {}) {
51
+ stopDaemonBridge();
52
+
53
+ bridge = connectToDaemon({
54
+ dataDir,
55
+ onEvent(event, payload) {
56
+ if (event === 'daemon:hello') {
57
+ // Identity, not an event the browser needs: the banner reads it from
58
+ // status() instead.
59
+ hello = payload;
60
+ announce(dataDir);
61
+ return;
62
+ }
63
+ publish(event, payload);
64
+ },
65
+ onStatus(connected, detail) {
66
+ if (connected) {
67
+ console.log('[daemonBridge] connected to the background service');
68
+ } else {
69
+ hello = null;
70
+ // A daemon that stopped is not the same as one we cannot reach, and
71
+ // saying "no event channel" for both was misleading during an ordinary
72
+ // restart. The lock tells us which this is.
73
+ const stillThere = inspect({ dataDir }).running;
74
+ console.log(stillThere
75
+ ? `[daemonBridge] lost the event channel to the running service (${detail ?? 'disconnected'}) — retrying`
76
+ : '[daemonBridge] the background service is not running');
77
+ }
78
+ announce(dataDir);
79
+ },
80
+ });
81
+
82
+ // The lock is the authority on whether a daemon exists, and it changes the
83
+ // instant one starts. Watching it does two things the backoff cannot:
84
+ // reconnect the event channel immediately instead of waiting out a delay
85
+ // computed from earlier failures, and tell the browser about the new state
86
+ // at once.
87
+ lockWatch = watchLock({
88
+ dataDir,
89
+ onChange() {
90
+ if (inspect({ dataDir }).running) bridge?.reconnectNow();
91
+ announce(dataDir);
92
+ },
93
+ });
94
+
95
+ announce(dataDir);
96
+
97
+ return { stop: stopDaemonBridge, status: daemonStatus, announce: () => announce(dataDir) };
98
+ }
99
+
100
+ /**
101
+ * Publishes the background-service state to the browser, when it changes.
102
+ *
103
+ * Only on a real change: this is called from a lock watcher and from every
104
+ * connect and disconnect, and a browser that re-rendered on each of those
105
+ * would flicker during an ordinary restart.
106
+ */
107
+ function announce(dataDir) {
108
+ try {
109
+ const next = daemonStatus({ dataDir });
110
+ const signature = JSON.stringify(next);
111
+ if (signature === lastAnnounced) return;
112
+ lastAnnounced = signature;
113
+
114
+ // The service state changed, so the cached probes in GET /api/service no
115
+ // longer describe it. Dropped here rather than only on a TTL, because this
116
+ // fires the moment a daemon appears or goes away - including when a change
117
+ // was made by `ezz service start` in another process, which nothing in
118
+ // THIS process would otherwise know about.
119
+ invalidateProbes();
120
+
121
+ publish('service:changed', next);
122
+ } catch (err) {
123
+ console.error('[daemonBridge] could not publish the service state:', err.message);
124
+ }
125
+ }
126
+
127
+ /** Stops the bridge if one is running. Idempotent. */
128
+ export function stopDaemonBridge() {
129
+ if (bridge) {
130
+ bridge.close();
131
+ bridge = null;
132
+ }
133
+ lockWatch?.close();
134
+ lockWatch = null;
135
+ hello = null;
136
+ lastAnnounced = null;
137
+ }
138
+
139
+ /**
140
+ * What the dashboard should tell the user about the background service.
141
+ *
142
+ * `running` comes from the lock file — the authority on whether a daemon
143
+ * exists. `connected` is about this process's event channel to it, which is a
144
+ * separate question and only affects how fresh the live view is.
145
+ *
146
+ * @param {Object} [opts]
147
+ * @returns {DaemonStatus}
148
+ */
149
+ export function daemonStatus({ dataDir = getDataDir() } = {}) {
150
+ // Everything about the service itself comes from core, so the HTTP response
151
+ // and the `service:changed` socket event carry the identical shape and the
152
+ // UI has one type to render. Only `connected` is the bridge's own business —
153
+ // it describes THIS process's event channel, not the service.
154
+ const state = backgroundServiceState({ dataDir });
155
+
156
+ return {
157
+ ...state,
158
+ connected: Boolean(bridge?.connected()),
159
+ // The hello frame is the daemon's own word for its version; the lock is a
160
+ // fallback for a daemon whose IPC never came up.
161
+ version: hello?.version ?? state.version,
162
+ };
163
+ }