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
@@ -3,13 +3,95 @@ import { dbGet, dbSet } from './db.js';
3
3
 
4
4
  const platform = os.platform();
5
5
 
6
+ /** Accept connections from anywhere. What every install did before v1.3. */
7
+ export const BIND_ALL = '0.0.0.0';
8
+ /** Accept connections from this machine only. */
9
+ export const BIND_LOOPBACK = '127.0.0.1';
10
+ /** IPv6 loopback, accepted wherever BIND_LOOPBACK is. */
11
+ export const BIND_LOOPBACK_V6 = '::1';
12
+
13
+ /**
14
+ * How the dashboard authenticates.
15
+ *
16
+ * password — a password is required (the default)
17
+ * none — no login at all, allowed ONLY on a loopback-bound dashboard
18
+ *
19
+ * "none" is a deliberate, narrow option for a single-user machine where the
20
+ * dashboard is not reachable from the network. It is not a way to run an
21
+ * exposed dashboard without a password: see isNoAuthAllowed().
22
+ */
23
+ export const AUTH_MODES = Object.freeze({
24
+ PASSWORD: 'password',
25
+ NONE: 'none',
26
+ });
27
+
28
+ /**
29
+ * Which dashboard UI the server serves at `/`.
30
+ *
31
+ * new — the built React app in dist/ui. THE default.
32
+ * classic — the EJS + Vue page in src/dashboard/views. A temporary fallback,
33
+ * for an operator who hits a regression in the new UI and needs a
34
+ * working dashboard immediately.
35
+ *
36
+ * `--classic-ui` overrides this for one run; the setting is what a background
37
+ * service reads. A missing dist/ui build falls back to classic with the build
38
+ * command printed, so the dashboard always starts. See dashboard/server.js.
39
+ */
40
+ export const UI_MODES = Object.freeze({
41
+ CLASSIC: 'classic',
42
+ NEW: 'new',
43
+ });
44
+
45
+ /**
46
+ * True when a bind address only accepts connections from this machine.
47
+ * @param {string} addr
48
+ * @returns {boolean}
49
+ */
50
+ export function isLoopbackBind(addr) {
51
+ return addr === BIND_LOOPBACK || addr === BIND_LOOPBACK_V6;
52
+ }
53
+
54
+ /**
55
+ * True when "no password" is permissible for this configuration.
56
+ *
57
+ * The single rule that makes the option safe: with no login, the only thing
58
+ * standing between the dashboard and the network is the listener itself, so
59
+ * the listener must not be on the network.
60
+ *
61
+ * @param {{ dashboardBindAddress?: string }} config
62
+ * @returns {boolean}
63
+ */
64
+ export function isNoAuthAllowed(config) {
65
+ return isLoopbackBind(config?.dashboardBindAddress);
66
+ }
67
+
6
68
  const DEFAULTS = {
7
69
  linux: {
8
70
  nginxDir: '/etc/nginx',
9
71
  sslDir: '/etc/easy-devops/ssl',
10
72
  dashboardPort: 6443,
11
73
  dashboardPassword: '',
74
+ dashboardPasswordHash: '',
75
+ dashboardAuth: AUTH_MODES.PASSWORD,
76
+ // A Linux box is usually a server with a public address, and the
77
+ // dashboard can now run 24/7, so a new install listens on loopback only
78
+ // until the user decides otherwise.
79
+ dashboardBindAddress: BIND_LOOPBACK,
80
+ dashboardUi: UI_MODES.NEW,
81
+ dashboardUiMigrated: true,
12
82
  acmeEmail: '',
83
+ acmeChallengePort: 8089,
84
+ sslChallengeMode: 'auto',
85
+ acmeStaging: false,
86
+ // Renew HTTP-01 certificates in the background once they are this close
87
+ // to expiry. See core/cert-renewal.js.
88
+ sslAutoRenew: true,
89
+ sslAutoRenewDays: 7,
90
+ // The deploy hook: a small listener GitHub Actions can call to trigger a
91
+ // deployment. Off until the user turns it on. See core/deploy/hookServer.js.
92
+ deployHook: { enabled: false, port: 6445, bind: BIND_LOOPBACK, domain: null },
93
+ // Folder NEW deployed apps are created in. null = <data dir>/ez_deploys.
94
+ deployDir: null,
13
95
  os: 'linux',
14
96
  },
15
97
  win32: {
@@ -17,19 +99,88 @@ const DEFAULTS = {
17
99
  sslDir: 'C:\\easy-devops\\ssl',
18
100
  dashboardPort: 6443,
19
101
  dashboardPassword: '',
102
+ dashboardPasswordHash: '',
103
+ dashboardAuth: AUTH_MODES.PASSWORD,
104
+ // Windows installs are typically a workstation behind a firewall, and
105
+ // binding to loopback there would break the common "reach it from my
106
+ // laptop" setup without warning.
107
+ dashboardBindAddress: BIND_ALL,
108
+ dashboardUi: UI_MODES.NEW,
109
+ dashboardUiMigrated: true,
20
110
  acmeEmail: '',
111
+ acmeChallengePort: 8089,
112
+ sslChallengeMode: 'auto',
113
+ acmeStaging: false,
114
+ sslAutoRenew: true,
115
+ sslAutoRenewDays: 7,
116
+ // The deploy hook: a small listener GitHub Actions can call to trigger a
117
+ // deployment. Off until the user turns it on. See core/deploy/hookServer.js.
118
+ deployHook: { enabled: false, port: 6445, bind: BIND_LOOPBACK, domain: null },
119
+ // Folder NEW deployed apps are created in. null = <data dir>/ez_deploys.
120
+ deployDir: null,
21
121
  os: 'win32',
22
122
  },
23
123
  };
24
124
 
25
125
  const defaultConfig = DEFAULTS[platform] ?? DEFAULTS.linux;
26
126
 
127
+ /** True when either form of a password is stored. */
128
+ function hasStoredPassword(config) {
129
+ return Boolean(config?.dashboardPasswordHash || config?.dashboardPassword);
130
+ }
131
+
27
132
  export function loadConfig() {
28
133
  const stored = dbGet('config');
134
+
29
135
  if (stored) {
30
- // Merge with defaults to ensure new fields have default values
31
- return { ...defaultConfig, ...stored };
136
+ const merged = { ...defaultConfig, ...stored };
137
+ let migrated = false;
138
+
139
+ // An EXISTING install predates the bind setting, and was therefore
140
+ // listening on every interface. Merging the new default would silently
141
+ // move it to loopback on upgrade and cut off anyone reaching the
142
+ // dashboard over the network — so the old behaviour is preserved and
143
+ // written down explicitly, leaving the choice to the user.
144
+ if (stored.dashboardBindAddress === undefined) {
145
+ merged.dashboardBindAddress = BIND_ALL;
146
+ migrated = true;
147
+ }
148
+
149
+ // An EXISTING install predates the auth setting too. An empty password
150
+ // used to mean "no login", and for a loopback-bound dashboard that is a
151
+ // legitimate choice, so it is preserved as an explicit 'none'. With a
152
+ // bind that is reachable from the network it is not: those installs get
153
+ // 'password' and are asked to set one, because the old behaviour there
154
+ // was an exposed dashboard anyone could open.
155
+ if (stored.dashboardAuth === undefined) {
156
+ merged.dashboardAuth =
157
+ !hasStoredPassword(stored) && isLoopbackBind(merged.dashboardBindAddress)
158
+ ? AUTH_MODES.NONE
159
+ : AUTH_MODES.PASSWORD;
160
+ migrated = true;
161
+ }
162
+
163
+ // The React dashboard became the default. An existing install has
164
+ // `classic` written down — not because anyone chose it, but because it was
165
+ // the default and `--new-ui` was the only way to see the other one. So a
166
+ // stored `classic` is moved to `new` exactly ONCE, recorded by
167
+ // `dashboardUiMigrated`, and a later deliberate `classic` is then left
168
+ // alone for ever. Without the marker, every load would undo the choice of
169
+ // an operator who really does want the old page.
170
+ if (merged.dashboardUi === UI_MODES.CLASSIC && !merged.dashboardUiMigrated) {
171
+ merged.dashboardUi = UI_MODES.NEW;
172
+ merged.dashboardUiMigrated = true;
173
+ migrated = true;
174
+ } else if (!merged.dashboardUiMigrated) {
175
+ merged.dashboardUiMigrated = true;
176
+ migrated = true;
177
+ }
178
+
179
+ if (migrated) saveConfig(merged);
180
+ return merged;
32
181
  }
182
+
183
+ // Fresh install: the platform defaults above apply.
33
184
  const config = { ...defaultConfig };
34
185
  saveConfig(config);
35
186
  return config;
@@ -38,3 +189,19 @@ export function loadConfig() {
38
189
  export function saveConfig(config) {
39
190
  dbSet('config', config);
40
191
  }
192
+
193
+ /**
194
+ * The auth mode actually in force, which is not always the stored one.
195
+ *
196
+ * 'none' is only honoured while the dashboard is bound to loopback. If the
197
+ * two ever disagree — a hand-edited database, a restored backup — the safe
198
+ * reading wins and a password is required. The API refuses to create that
199
+ * combination, so this is a backstop rather than a normal path.
200
+ *
201
+ * @param {Object} config
202
+ * @returns {'password'|'none'}
203
+ */
204
+ export function effectiveAuthMode(config) {
205
+ if (config?.dashboardAuth !== AUTH_MODES.NONE) return AUTH_MODES.PASSWORD;
206
+ return isNoAuthAllowed(config) ? AUTH_MODES.NONE : AUTH_MODES.PASSWORD;
207
+ }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * core/daemon/ipc.js
3
+ *
4
+ * How live events get from the daemon to an open dashboard in another process.
5
+ *
6
+ * A named pipe on Windows, a Unix socket in the data directory elsewhere (see
7
+ * `daemonIpcPath()` in core/platform.js). Deliberately NOT an HTTP port: the
8
+ * daemon must not open one — a port is reachable from the network stack and
9
+ * would need its own authentication, binding policy and firewall story, all to
10
+ * carry events that are already available to anyone who can read the data
11
+ * directory.
12
+ *
13
+ * ── The protocol, and why it is one-way ────────────────────────────────────
14
+ *
15
+ * Newline-delimited JSON, server to client only:
16
+ *
17
+ * {"event":"nginx:status","payload":{...}}
18
+ *
19
+ * The server accepts NO commands. Nothing a client writes can make the daemon
20
+ * do anything — the read side is drained and ignored. This is a security
21
+ * decision, not laziness: the daemon may run as a Windows service account with
22
+ * access the dashboard user does not have, and a named pipe's default ACL is
23
+ * more permissive than people expect. A channel that cannot be asked to do
24
+ * anything cannot be used to escalate.
25
+ *
26
+ * So what about the other direction? Changes made in the dashboard or the CLI
27
+ * reach the daemon through the database: the revision counter in
28
+ * core/jobs/revisionWatcher.js, which every process already polls. Slower than
29
+ * a message, and entirely sufficient for "something changed, re-read it".
30
+ *
31
+ * ── Why the payloads are the contract's payloads ───────────────────────────
32
+ *
33
+ * The event names and shapes are the ones in docs/api-contract.md, so the
34
+ * dashboard forwards each frame to the browser unchanged. Anything else would
35
+ * mean two schemas describing the same data.
36
+ */
37
+
38
+ import net from 'net';
39
+ import fs from 'fs';
40
+
41
+ import { daemonIpcPath, getDataDir, isWindows } from '../platform.js';
42
+ import { JOB_EVENTS, subscribeAll } from '../jobs/bus.js';
43
+
44
+ /** Reconnect backoff for a client that cannot reach the daemon. */
45
+ const RECONNECT_MIN_MS = 1_000;
46
+ const RECONNECT_MAX_MS = 15_000;
47
+
48
+ /** A single frame may not exceed this, to bound a client's buffer. */
49
+ const MAX_FRAME_BYTES = 1024 * 1024;
50
+
51
+ /**
52
+ * Starts the daemon's event server and forwards every bus event to it.
53
+ *
54
+ * @param {Object} [opts]
55
+ * @param {string} [opts.dataDir]
56
+ * @param {() => Object} [opts.hello] Builds the state frame a new client gets
57
+ * @returns {Promise<{ close: () => Promise<void>, path: string, clients: () => number }>}
58
+ */
59
+ export async function startIpcServer({ dataDir = getDataDir(), hello = null } = {}) {
60
+ const socketPath = daemonIpcPath(dataDir);
61
+
62
+ // A Unix socket file left behind by a crash makes bind() fail with EADDRINUSE
63
+ // even though nothing is listening. Removing it is safe here because the
64
+ // daemon lock has already established that we are the only daemon — without
65
+ // that guarantee this would be how two daemons steal the socket from each
66
+ // other. Windows named pipes need no equivalent: the name disappears with
67
+ // the process that created it.
68
+ if (!isWindows) {
69
+ try {
70
+ fs.unlinkSync(socketPath);
71
+ } catch (err) {
72
+ if (err.code !== 'ENOENT') throw err;
73
+ }
74
+ }
75
+
76
+ /** @type {Set<net.Socket>} */
77
+ const clients = new Set();
78
+
79
+ const server = net.createServer((socket) => {
80
+ clients.add(socket);
81
+
82
+ // Never buffer indefinitely for a client that has stopped reading: a
83
+ // wedged dashboard tab must not grow the daemon's memory without bound.
84
+ socket.setNoDelay(true);
85
+
86
+ // The read side carries nothing we act on. It is still drained, because an
87
+ // un-read stream applies backpressure that would eventually stall the
88
+ // client's writes and look like a hang.
89
+ socket.resume();
90
+
91
+ socket.on('error', () => { /* a client that vanishes is normal */ });
92
+ socket.on('close', () => clients.delete(socket));
93
+
94
+ if (hello) {
95
+ try {
96
+ writeFrame(socket, 'daemon:hello', hello());
97
+ } catch { /* client went away between connect and hello */ }
98
+ }
99
+ });
100
+
101
+ server.on('error', (err) => {
102
+ console.error('[ipc] server error:', err.message);
103
+ });
104
+
105
+ await new Promise((resolve, reject) => {
106
+ server.once('error', reject);
107
+ server.listen(socketPath, () => {
108
+ server.removeListener('error', reject);
109
+ resolve();
110
+ });
111
+ });
112
+
113
+ // Owner-only. The socket inherits the data directory's permissions, but the
114
+ // directory may be group-readable on a shared machine and the socket should
115
+ // not widen that. Not applicable to a Windows named pipe.
116
+ if (!isWindows) {
117
+ try {
118
+ fs.chmodSync(socketPath, 0o600);
119
+ } catch { /* best effort: a failure here does not justify no IPC at all */ }
120
+ }
121
+
122
+ const unsubscribe = subscribeAll((event, payload) => {
123
+ for (const socket of clients) {
124
+ try {
125
+ writeFrame(socket, event, payload);
126
+ } catch {
127
+ clients.delete(socket);
128
+ }
129
+ }
130
+ });
131
+
132
+ return {
133
+ path: socketPath,
134
+ clients: () => clients.size,
135
+ async close() {
136
+ unsubscribe();
137
+ for (const socket of clients) socket.destroy();
138
+ clients.clear();
139
+
140
+ await new Promise((resolve) => {
141
+ const done = setTimeout(resolve, 2_000);
142
+ server.close(() => { clearTimeout(done); resolve(); });
143
+ });
144
+
145
+ if (!isWindows) {
146
+ try { fs.unlinkSync(socketPath); } catch { /* already gone */ }
147
+ }
148
+ },
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Connects to a running daemon and calls back for every event it sends.
154
+ *
155
+ * Reconnects for ever with capped backoff, because the daemon legitimately
156
+ * comes and goes (a service restart, an upgrade) and a dashboard that gave up
157
+ * after one failure would silently stop showing live data.
158
+ *
159
+ * @param {Object} opts
160
+ * @param {(event: string, payload: *) => void} opts.onEvent
161
+ * @param {(connected: boolean, detail?: string) => void} [opts.onStatus]
162
+ * @param {string} [opts.dataDir]
163
+ * @returns {{ close: () => void, connected: () => boolean, path: string }}
164
+ */
165
+ export function connectToDaemon({ onEvent, onStatus = null, dataDir = getDataDir() } = {}) {
166
+ const socketPath = daemonIpcPath(dataDir);
167
+
168
+ let socket = null;
169
+ let closed = false;
170
+ let connected = false;
171
+ let delay = RECONNECT_MIN_MS;
172
+ let retryTimer = null;
173
+
174
+ const setStatus = (value, detail) => {
175
+ if (connected === value) return;
176
+ connected = value;
177
+ if (onStatus) {
178
+ try { onStatus(value, detail); } catch { /* listener's problem */ }
179
+ }
180
+ };
181
+
182
+ const scheduleRetry = () => {
183
+ if (closed || retryTimer) return;
184
+ retryTimer = setTimeout(() => { retryTimer = null; open(); }, delay);
185
+ // Exponential up to the cap: a daemon that is not installed at all must
186
+ // not mean a connection attempt every second for the life of the process.
187
+ delay = Math.min(delay * 2, RECONNECT_MAX_MS);
188
+ };
189
+
190
+ function open() {
191
+ if (closed) return;
192
+
193
+ let buffer = '';
194
+ socket = net.createConnection(socketPath);
195
+
196
+ socket.on('connect', () => {
197
+ delay = RECONNECT_MIN_MS;
198
+ setStatus(true);
199
+ });
200
+
201
+ socket.on('data', (chunk) => {
202
+ buffer += chunk;
203
+
204
+ if (buffer.length > MAX_FRAME_BYTES) {
205
+ // A frame this large means the stream is out of sync or the peer is
206
+ // not what we think it is. Dropping the connection re-syncs on a frame
207
+ // boundary; keeping it would grow memory with no way back.
208
+ console.error('[ipc] frame too large - reconnecting');
209
+ buffer = '';
210
+ socket.destroy();
211
+ return;
212
+ }
213
+
214
+ const lines = buffer.split('\n');
215
+ buffer = lines.pop();
216
+
217
+ for (const line of lines) {
218
+ if (!line.trim()) continue;
219
+
220
+ let frame;
221
+ try {
222
+ frame = JSON.parse(line);
223
+ } catch {
224
+ continue; // a malformed frame is skipped, not fatal
225
+ }
226
+
227
+ // Only names the contract knows. An unexpected name is ignored rather
228
+ // than forwarded: the dashboard passes these straight to the browser,
229
+ // so this is the boundary where that list is enforced.
230
+ if (frame?.event === 'daemon:hello' || JOB_EVENTS.includes(frame?.event)) {
231
+ try {
232
+ onEvent(frame.event, frame.payload);
233
+ } catch (err) {
234
+ console.error('[ipc] event handler threw:', err.message);
235
+ }
236
+ }
237
+ }
238
+ });
239
+
240
+ const drop = (detail) => {
241
+ setStatus(false, detail);
242
+ socket?.destroy();
243
+ socket = null;
244
+ scheduleRetry();
245
+ };
246
+
247
+ socket.on('error', (err) => drop(err.code || err.message));
248
+ socket.on('close', () => drop('closed'));
249
+ }
250
+
251
+ open();
252
+
253
+ return {
254
+ path: socketPath,
255
+ connected: () => connected,
256
+
257
+ /**
258
+ * Connects right now, discarding any pending backoff.
259
+ *
260
+ * The backoff only resets on a successful connect, so after a daemon has
261
+ * been up and down a few times the next attempt can be fifteen seconds
262
+ * away. That is correct for "the service is not installed" and wrong for
263
+ * "a new daemon just appeared": the dashboard then logged
264
+ * "no event channel (closed)", missed the new daemon, and its ownership
265
+ * poll took the jobs back. The caller watches the daemon lock and calls
266
+ * this the moment one appears.
267
+ */
268
+ reconnectNow() {
269
+ if (closed || connected) return;
270
+ if (retryTimer) {
271
+ clearTimeout(retryTimer);
272
+ retryTimer = null;
273
+ }
274
+ delay = RECONNECT_MIN_MS;
275
+ open();
276
+ },
277
+
278
+ close() {
279
+ closed = true;
280
+ if (retryTimer) clearTimeout(retryTimer);
281
+ retryTimer = null;
282
+ socket?.destroy();
283
+ socket = null;
284
+ connected = false;
285
+ },
286
+ };
287
+ }
288
+
289
+ /** One newline-delimited JSON frame. */
290
+ function writeFrame(socket, event, payload) {
291
+ socket.write(`${JSON.stringify({ event, payload })}\n`);
292
+ }