easy-devops 1.4.0 → 1.4.2

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.
@@ -0,0 +1,128 @@
1
+ /**
2
+ * core/daemon/stateFile.js
3
+ *
4
+ * The daemon's public state, written to a file in the data directory.
5
+ *
6
+ * ── Why a file when there is an IPC channel ────────────────────────────────
7
+ *
8
+ * In Windows Server mode the daemon runs as `NT SERVICE\EasyDevOps`, and the
9
+ * named pipe it creates carries that account's default security: an
10
+ * Administrator's CLI cannot open it. Node has no API to put a different ACL
11
+ * on a pipe, and a native module for it would be a new dependency for one
12
+ * read. So `ezz hub status` and `ezz hub connect` said "not reported by the
13
+ * background service yet" while the Hub showed the agent connected.
14
+ *
15
+ * The data directory is already shared on purpose — the service account
16
+ * modifies it, Administrators own ProgramData, the installing user reads it —
17
+ * so the daemon also writes what a CLI needs to read there. The IPC channel is
18
+ * unchanged and stays one-way; this file is a second, read-only window, not a
19
+ * way to send anything to the daemon.
20
+ *
21
+ * ── What it holds ──────────────────────────────────────────────────────────
22
+ *
23
+ * Only what `getHubAgentStatus()` returns — linked, connected, status,
24
+ * lastError, attempts — plus the daemon's pid, version and the time of the
25
+ * write. No secret, no Hub URL, no server id: those are in the database,
26
+ * readable by the same people, and never needed here.
27
+ *
28
+ * ── Staleness ──────────────────────────────────────────────────────────────
29
+ *
30
+ * A file outlives its writer. A reader trusts it only when its pid is the pid
31
+ * holding the live daemon lock (pid + heartbeat, core/daemon/lock.js), so a
32
+ * leftover from a crashed or stopped daemon is never reported as current.
33
+ */
34
+
35
+ import fs from 'fs';
36
+ import path from 'path';
37
+
38
+ import { inspect as inspectLock } from './lock.js';
39
+
40
+ export const STATE_FILE_NAME = 'daemon-state.json';
41
+
42
+ /** @param {string} dataDir */
43
+ export function stateFilePath(dataDir) {
44
+ return path.join(dataDir, STATE_FILE_NAME);
45
+ }
46
+
47
+ /**
48
+ * Writes the state atomically: a temporary file, then a rename, so a reader
49
+ * never sees half a JSON document. Never throws — the daemon's work must not
50
+ * depend on a status file.
51
+ *
52
+ * @param {Object} opts
53
+ * @param {string} opts.dataDir
54
+ * @param {number} opts.pid
55
+ * @param {string} [opts.version]
56
+ * @param {Object|null} opts.hub getHubAgentStatus()
57
+ * @returns {boolean} whether it was written
58
+ */
59
+ export function writeDaemonState({ dataDir, pid, version = null, hub }) {
60
+ const file = stateFilePath(dataDir);
61
+ const body = `${JSON.stringify({
62
+ pid,
63
+ version,
64
+ updatedAt: new Date().toISOString(),
65
+ hub: hub
66
+ ? {
67
+ linked: Boolean(hub.linked),
68
+ connected: Boolean(hub.connected),
69
+ status: hub.status ?? null,
70
+ lastError: hub.lastError ?? null,
71
+ attempts: Number.isFinite(hub.attempts) ? hub.attempts : 0,
72
+ }
73
+ : null,
74
+ })}\n`;
75
+
76
+ const temp = `${file}.${pid}.tmp`;
77
+ try {
78
+ fs.writeFileSync(temp, body, 'utf8');
79
+ try {
80
+ fs.renameSync(temp, file);
81
+ } catch {
82
+ // Windows refuses a rename over a file a reader has open at that
83
+ // instant. A direct write is still whole for a document this small.
84
+ fs.writeFileSync(file, body, 'utf8');
85
+ fs.rmSync(temp, { force: true });
86
+ }
87
+ return true;
88
+ } catch {
89
+ try { fs.rmSync(temp, { force: true }); } catch { /* nothing to clean */ }
90
+ return false;
91
+ }
92
+ }
93
+
94
+ /** Removes the file on a clean stop. Best effort. */
95
+ export function removeDaemonState({ dataDir, pid }) {
96
+ try {
97
+ const current = readDaemonStateFile({ dataDir });
98
+ // Only our own: a daemon that already replaced us must keep its file.
99
+ if (!current || current.pid === pid) fs.rmSync(stateFilePath(dataDir), { force: true });
100
+ } catch { /* best effort */ }
101
+ }
102
+
103
+ /** The raw file, or null. */
104
+ export function readDaemonStateFile({ dataDir }) {
105
+ try {
106
+ return JSON.parse(fs.readFileSync(stateFilePath(dataDir), 'utf8'));
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The agent state as last written by the RUNNING daemon, or null.
114
+ *
115
+ * @param {Object} opts
116
+ * @param {string} opts.dataDir
117
+ * @param {Function} [opts.inspect] Injected for tests
118
+ * @returns {Object|null} the `hub` object, with `source: 'state-file'`
119
+ */
120
+ export function readAgentStateFromFile({ dataDir, inspect = inspectLock } = {}) {
121
+ const state = readDaemonStateFile({ dataDir });
122
+ if (!state?.hub) return null;
123
+
124
+ const lock = inspect({ dataDir });
125
+ if (!lock.running || lock.lock?.pid !== state.pid) return null;
126
+
127
+ return { ...state.hub, updatedAt: state.updatedAt ?? null, source: 'state-file' };
128
+ }
package/src/core/db.js CHANGED
@@ -12,6 +12,11 @@ const DATA_DIR = getDataDir();
12
12
 
13
13
  const DB_PATH = path.join(DATA_DIR, 'easy-devops.sqlite');
14
14
 
15
+ // The file the open connection uses. It equals DB_PATH for the life of almost
16
+ // every process; only reopenDb() moves it, after the Windows Server-mode
17
+ // migration has changed what getDataDir() answers.
18
+ let dbPath = DB_PATH;
19
+
15
20
  // ─── One-time migration from old package-relative location ───────────────────
16
21
  const OLD_DATA_DIR = path.join(__dirname, '..', '..', 'data');
17
22
  const OLD_DB_PATH = path.join(OLD_DATA_DIR, 'easy-devops.sqlite');
@@ -70,7 +75,7 @@ let db;
70
75
  * per call site without every future caller having to remember.
71
76
  */
72
77
  function createDbConnection() {
73
- return new GoodDB(new SQLiteDriver({ path: DB_PATH }), {
78
+ return new GoodDB(new SQLiteDriver({ path: dbPath }), {
74
79
  nested: "..",
75
80
  nestedIsEnabled: true,
76
81
  cache: {
@@ -117,3 +122,23 @@ export function initDb() {
117
122
  db = createDbConnection();
118
123
  }
119
124
  }
125
+
126
+ /**
127
+ * Closes the connection and opens the database in the CURRENT data directory.
128
+ *
129
+ * For the one place where the data directory changes within a process: the
130
+ * Windows Server-mode switch during `ezz service install`. Without it, the
131
+ * installing process kept writing to the per-user database it opened at
132
+ * startup — a file every later process ignores — and Windows refused to
133
+ * rename that directory to its backup name because this handle held it open.
134
+ *
135
+ * @returns {string} The database file now in use
136
+ */
137
+ export function reopenDb() {
138
+ closeDb();
139
+ const dir = getDataDir();
140
+ fs.mkdirSync(dir, { recursive: true });
141
+ dbPath = path.join(dir, 'easy-devops.sqlite');
142
+ db = createDbConnection();
143
+ return dbPath;
144
+ }
@@ -8,6 +8,11 @@ import { loadConfig } from './config.js';
8
8
  import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk } from './platform.js';
9
9
  import { saveDomainNotifConfig } from './domainNotifier.js';
10
10
  import { bumpHubRevision } from './hubLink.js';
11
+ import { missingCertFiles, CERT_MISSING_HINT } from './cert-usage.js';
12
+ import {
13
+ validateDomainName, validatePort, validateUpstreamType,
14
+ validateMaxBodySize, validateBehindCloudflare,
15
+ } from './validators.js';
11
16
 
12
17
  // Re-export DOMAIN_DEFAULTS for consumers
13
18
  export { DOMAIN_DEFAULTS, migrateDomain };
@@ -71,6 +76,48 @@ export function createDomain(partial) {
71
76
  // Called by hubAgent when the hub dispatches a hub:manageDomain event.
72
77
  // Payload shape: { action: 'create'|'update'|'delete'|'toggle'|'reload', name?, domain? }
73
78
 
79
+ /**
80
+ * The checks the dashboard's domain controller runs, applied to a Hub payload.
81
+ * On update only the fields present are checked, as the dashboard does.
82
+ *
83
+ * @param {Object} input The payload's `domain`
84
+ * @param {{ creating: boolean, existing?: Object }} options
85
+ * @returns {string|null} The first problem, or null
86
+ */
87
+ function hubDomainInputError(input, { creating, existing = null }) {
88
+ if (creating) {
89
+ const nameError = validateDomainName(input.name);
90
+ if (nameError) return nameError;
91
+ }
92
+
93
+ const backendIsUrl = /^https?:\/\//i.test(input.backendHost ?? existing?.backendHost ?? '');
94
+ if ((creating || input.port !== undefined) && !backendIsUrl) {
95
+ const portError = validatePort(input.port);
96
+ if (portError) return portError;
97
+ }
98
+ if (input.upstreamType !== undefined) {
99
+ const upstreamError = validateUpstreamType(input.upstreamType);
100
+ if (upstreamError) return upstreamError;
101
+ }
102
+ if (input.performance?.maxBodySize !== undefined) {
103
+ const sizeError = validateMaxBodySize(input.performance.maxBodySize);
104
+ if (sizeError) return sizeError;
105
+ }
106
+ if (input.behindCloudflare !== undefined) {
107
+ const cloudflareError = validateBehindCloudflare(input.behindCloudflare);
108
+ if (cloudflareError) return cloudflareError;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * The dashboard's 422 `cert_missing`, as a Hub refusal: the resolved paths
115
+ * and the hint travel to the Hub as the command's data.
116
+ */
117
+ function certMissingResult({ certPath, keyPath }) {
118
+ return { ok: false, code: 'cert_missing', certPath, keyPath, hint: CERT_MISSING_HINT, error: CERT_MISSING_HINT };
119
+ }
120
+
74
121
  export async function handleHubDomainCommand(payload) {
75
122
  const { action, name, domain, deleteCert } = payload ?? {};
76
123
  const { nginxDir } = loadConfig();
@@ -79,6 +126,10 @@ export async function handleHubDomainCommand(payload) {
79
126
 
80
127
  case 'create': {
81
128
  if (!domain?.name) return { ok: false, error: 'domain.name is required' };
129
+ // The same checks the dashboard runs. The name becomes a config file
130
+ // name, so it must be a plain hostname before anything is written.
131
+ const invalid = hubDomainInputError(domain, { creating: true });
132
+ if (invalid) return { ok: false, error: invalid };
82
133
  if (findDomain(domain.name)) return { ok: false, error: `Domain ${domain.name} already exists` };
83
134
 
84
135
  const newDomain = createDomain({
@@ -96,6 +147,11 @@ export async function handleHubDomainCommand(payload) {
96
147
  advanced: { ...DOMAIN_DEFAULTS.advanced, ...domain.advanced },
97
148
  });
98
149
 
150
+ // Same refusal as the dashboard: never point nginx at certificate files
151
+ // that are not on disk. The Hub offers Create certificate on this code.
152
+ const missingNew = await missingCertFiles(newDomain);
153
+ if (missingNew) return certMissingResult(missingNew);
154
+
99
155
  // Shared core apply (same path as the CLI and the dashboard API).
100
156
  const created = await writeConfWithTest(newDomain);
101
157
  if (!created.ok) {
@@ -120,7 +176,12 @@ export async function handleHubDomainCommand(payload) {
120
176
  const existing = targetName ? findDomain(targetName) : null;
121
177
  if (!existing) return { ok: false, error: `Domain ${targetName} not found` };
122
178
 
123
- const updates = domain ?? {};
179
+ // Fields the agent owns are never taken from the Hub: the config path is
180
+ // derived from the name, and enabling is hub:manageDomain toggle, which
181
+ // has its own permission.
182
+ const { configFile: _cf, enabled: _en, createdAt: _ca, ...updates } = domain ?? {};
183
+ const invalid = hubDomainInputError(updates, { creating: false, existing });
184
+ if (invalid) return { ok: false, error: invalid };
124
185
  const updatedDomain = {
125
186
  ...existing,
126
187
  ...updates,
@@ -132,6 +193,11 @@ export async function handleHubDomainCommand(payload) {
132
193
  updatedAt: new Date().toISOString(),
133
194
  };
134
195
 
196
+ // Same refusal as the dashboard: never point nginx at certificate files
197
+ // that are not on disk. The Hub offers Create certificate on this code.
198
+ const missingUpdated = await missingCertFiles(updatedDomain);
199
+ if (missingUpdated) return certMissingResult(missingUpdated);
200
+
135
201
  // Shared core apply — restores the previous config exactly if it fails,
136
202
  // so the .bak dance is no longer needed here.
137
203
  const updatedResult = await writeConfWithTest(updatedDomain);
@@ -426,6 +426,24 @@ export function createCommandProgress(requestId) {
426
426
  };
427
427
  }
428
428
 
429
+ /**
430
+ * An Error carrying a handler's own { ok: false, ... } result as `data`, so a
431
+ * refusal reaches the Hub with its details (the failed stage, the domains that
432
+ * still use a certificate) instead of only a message. Handlers build that
433
+ * result from fields meant for the Hub; nothing secret goes in it.
434
+ *
435
+ * @param {Object} result
436
+ * @param {string} fallback
437
+ */
438
+ function refusalError(result, fallback) {
439
+ const message = typeof result?.error === 'string'
440
+ ? result.error
441
+ : (result?.error?.cause || fallback);
442
+ const err = new Error(message);
443
+ err.data = result;
444
+ return err;
445
+ }
446
+
429
447
  /** Emits the acknowledgement the Hub and its browser clients wait for. */
430
448
  function sendResult(requestId, ok, { error = null, data = null } = {}, ack = null) {
431
449
  if (!requestId) return;
@@ -488,7 +506,9 @@ async function runCommand(command, payload, fn, ack = null) {
488
506
  } catch (err) {
489
507
  console.error('[hubAgent]', command, 'failed:', err.message);
490
508
  logCommandTiming(command, startedAt, false);
491
- sendResult(requestId, false, { error: err.message }, ack);
509
+ // A handler may attach a structured refusal (refusalError above) so the
510
+ // Hub can show it as well as the message.
511
+ sendResult(requestId, false, { error: err.message, data: err.data ?? null }, ack);
492
512
  }
493
513
  }
494
514
 
@@ -627,7 +647,7 @@ async function handleManageDomain(payload, ack) {
627
647
  return runCommand('hub:manageDomain', payload, async (p) => {
628
648
  const { handleHubDomainCommand } = await import('../domains-db.js');
629
649
  const result = await handleHubDomainCommand(p);
630
- if (result && result.ok === false) throw new Error(result.error || 'domain command failed');
650
+ if (result && result.ok === false) throw refusalError(result, 'domain command failed');
631
651
 
632
652
  // Re-sync to the hub and refresh any open local dashboard tab.
633
653
  pushDomainHealth();
@@ -643,7 +663,7 @@ async function handleManageSSL(payload, ack) {
643
663
  const result = await handleHubSslCommand(p, {
644
664
  onProgress: createCommandProgress(p?.requestId),
645
665
  });
646
- if (result && result.ok === false) throw new Error(result.error || 'ssl command failed');
666
+ if (result && result.ok === false) throw refusalError(result, 'ssl command failed');
647
667
 
648
668
  pushCertExpiry();
649
669
  pushDomainConfigs();
@@ -306,6 +306,31 @@ export function windowsProductNameCmd() {
306
306
  return "(Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion').ProductName";
307
307
  }
308
308
 
309
+ /**
310
+ * Command that prints `True` only when this process runs ELEVATED.
311
+ *
312
+ * Membership of Administrators is not enough: with UAC on, an administrator's
313
+ * normal terminal carries a filtered token, and IsInRole(Administrator) is
314
+ * false there until "Run as administrator". That is exactly the question —
315
+ * a filtered token is what makes Windows raise a UAC prompt for the wrapper.
316
+ * @returns {string}
317
+ */
318
+ export function windowsElevationCheckCmd() {
319
+ return '([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent())'
320
+ + '.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)';
321
+ }
322
+
323
+ /**
324
+ * The Service Control Manager's command-line tool, always with its extension.
325
+ *
326
+ * Commands run through PowerShell on Windows, and there `sc` is the built-in
327
+ * alias for Set-Content: `sc query EasyDevOps` silently wrote a file named
328
+ * `query` containing "EasyDevOps" into the current directory and "succeeded".
329
+ * 1.4.0 shipped that, which is why status read "unknown" and stop/start did
330
+ * nothing. `sc.exe` names the real program in PowerShell and cmd alike.
331
+ */
332
+ export const WINDOWS_SC = 'sc.exe';
333
+
309
334
  /**
310
335
  * Address the daemon listens on for local event delivery to a dashboard.
311
336
  *
@@ -146,18 +146,23 @@ export function backupPathFor(dir, now = new Date()) {
146
146
  * @param {string} opts.to
147
147
  * @param {boolean} [opts.keepBackup] Leave the backup in place (default true)
148
148
  * @param {(line: string) => void} [opts.log]
149
- * @returns {{ ok: true, moved: boolean, backup: string|null, reason?: string }
149
+ * `originalAt` always says where the original data is afterwards: the backup
150
+ * path when the rename worked, or `from` itself when it could not be renamed
151
+ * (Windows refuses to rename a directory while a file in it is open). It is
152
+ * null only when there was no original, or it was removed on request.
153
+ *
154
+ * @returns {{ ok: true, moved: boolean, backup: string|null, originalAt: string|null, reason?: string }
150
155
  * | { ok: false, reason: string }}
151
156
  */
152
157
  export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
153
158
  if (!fs.existsSync(from)) {
154
159
  // Nothing to move is a success: a fresh install has no per-user data, and
155
160
  // the service simply starts with an empty ProgramData directory.
156
- return { ok: true, moved: false, backup: null, reason: `${from} does not exist` };
161
+ return { ok: true, moved: false, backup: null, originalAt: null, reason: `${from} does not exist` };
157
162
  }
158
163
 
159
164
  if (path.resolve(from).toLowerCase() === path.resolve(to).toLowerCase()) {
160
- return { ok: true, moved: false, backup: null, reason: 'source and destination are the same' };
165
+ return { ok: true, moved: false, backup: null, originalAt: from, reason: 'source and destination are the same' };
161
166
  }
162
167
 
163
168
  const busy = assertNotInUse(from);
@@ -203,10 +208,12 @@ export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
203
208
  // The copy is good and verified, so the data is safe in two places. Not
204
209
  // being able to rename the original is worth reporting but not worth
205
210
  // undoing a verified migration over.
211
+ log(`Original left in place at ${from} (it could not be renamed: ${err.code ?? err.message})`);
206
212
  return {
207
213
  ok: true,
208
214
  moved: true,
209
215
  backup: null,
216
+ originalAt: from,
210
217
  reason: `the data was copied and verified, but the original could not be renamed: ${err.message}. `
211
218
  + `It is still at ${from} — remove it by hand once you are satisfied.`,
212
219
  };
@@ -216,13 +223,30 @@ export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
216
223
  try {
217
224
  fs.rmSync(backup, { recursive: true, force: true });
218
225
  log('Backup removed as requested.');
219
- return { ok: true, moved: true, backup: null };
226
+ return { ok: true, moved: true, backup: null, originalAt: null };
220
227
  } catch (err) {
221
- return { ok: true, moved: true, backup, reason: `the backup could not be removed: ${err.message}` };
228
+ return { ok: true, moved: true, backup, originalAt: backup, reason: `the backup could not be removed: ${err.message}` };
222
229
  }
223
230
  }
224
231
 
225
- return { ok: true, moved: true, backup };
232
+ return { ok: true, moved: true, backup, originalAt: backup };
233
+ }
234
+
235
+ /**
236
+ * One line saying where the user's original data is after a migration.
237
+ *
238
+ * Exists because 1.4.0 printed `backup at null`: the rename to a backup name
239
+ * fails on Windows while the database inside is open, the original then stays
240
+ * where it was, and `backup` is null for exactly that reason. The data was
241
+ * never lost — the message just did not say where it was.
242
+ *
243
+ * @param {{ backup?: string|null, originalAt?: string|null }} result
244
+ * @returns {string}
245
+ */
246
+ export function describeOriginal(result) {
247
+ if (result?.backup) return `the original is kept as a backup at ${result.backup}`;
248
+ if (result?.originalAt) return `the original was left in place at ${result.originalAt}; remove it by hand once you are satisfied`;
249
+ return 'there was no earlier data to keep';
226
250
  }
227
251
 
228
252
  /**
@@ -235,7 +259,8 @@ export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
235
259
  *
236
260
  * @param {Object} [opts]
237
261
  * @param {(line: string) => void} [opts.log]
238
- * @returns {{ ok: boolean, dataDir: string, migrated: boolean, backup: string|null, reason?: string }}
262
+ * @returns {{ ok: boolean, dataDir: string, migrated: boolean, backup: string|null, originalAt?: string|null,
263
+ * reason?: string }}
239
264
  */
240
265
  export function enableServerMode({ log = () => {} } = {}) {
241
266
  if (!isWindows) {
@@ -289,7 +314,7 @@ export function enableServerMode({ log = () => {} } = {}) {
289
314
  resetDataDirCache();
290
315
  log(`Server mode enabled. Data directory: ${target}`);
291
316
 
292
- return { ok: true, dataDir: target, migrated: moved.moved, backup: moved.backup, reason: moved.reason };
317
+ return { ok: true, dataDir: target, migrated: moved.moved, backup: moved.backup, originalAt: moved.originalAt, reason: moved.reason };
293
318
  }
294
319
 
295
320
  /**
@@ -341,5 +366,5 @@ export function disableServerMode({ log = () => {} } = {}) {
341
366
  }
342
367
 
343
368
  log(`Server mode disabled. Data directory: ${target}`);
344
- return { ok: true, dataDir: target, moved: moved.moved, backup: moved.backup, reason: moved.reason };
369
+ return { ok: true, dataDir: target, moved: moved.moved, backup: moved.backup, originalAt: moved.originalAt, reason: moved.reason };
345
370
  }