easy-devops 1.4.2 → 1.4.3

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.
@@ -56,6 +56,7 @@ import * as windowsPersonal from './windowsPersonal.js';
56
56
  import * as legacy from './legacy.js';
57
57
  import { enableServerMode, disableServerMode, describeOriginal } from './dataDir.js';
58
58
  import { linkRuntime, inspectRuntime, runtimeNodePath } from './runtime.js';
59
+ import { resolveOperator } from './operator.js';
59
60
 
60
61
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
61
62
 
@@ -477,10 +478,16 @@ async function installWindowsServer({ entry, root, log, legacyResult, deps = {}
477
478
 
478
479
  const config = loadConfig();
479
480
 
481
+ // Who may start and stop the service afterwards without elevation: the
482
+ // account that asked for the install (operator.js). Resolved here, in the
483
+ // elevated process, from Windows itself or from the relaunch that started it.
484
+ const operator = await (deps.resolveOperator ?? resolveOperator)({});
485
+
480
486
  const installed = await ws.install({
481
487
  dataDir,
482
488
  appRoot: root,
483
489
  config,
490
+ operator,
484
491
  log,
485
492
  ...(deps.windowsServiceOpts ?? {}),
486
493
  });
@@ -497,6 +504,7 @@ async function installWindowsServer({ entry, root, log, legacyResult, deps = {}
497
504
  entry: installed.runtime?.entry ?? entry,
498
505
  dataDir,
499
506
  granted: installed.granted ?? [],
507
+ operator: installed.operator ?? null,
500
508
  });
501
509
  }
502
510
 
@@ -668,9 +676,14 @@ export async function uninstall({
668
676
  if (!removed.ok) return { ok: false, ...result, reason: removed.reason };
669
677
  } else if (mech.mode === MODES.SERVER) {
670
678
  const config = loadConfig();
679
+ const operator = (dbGet(STATE_KEY) ?? {}).operator ?? null;
671
680
  const removed = await (deps.windowsService ?? windowsService).uninstall({
672
681
  dataDir: getDataDir(),
673
682
  config,
683
+ // The start/stop right goes with the service. The data directory grant
684
+ // is removed only when the data leaves ProgramData: while the CLI keeps
685
+ // using it there, removing it would bring back the read-only database.
686
+ operator: keepServerDataLocation ? null : operator,
674
687
  log,
675
688
  ...(deps.windowsServiceOpts ?? {}),
676
689
  });
@@ -685,6 +698,12 @@ export async function uninstall({
685
698
  + 'the dashboard keep reading it. Run `ezz service uninstall` again and choose to move it '
686
699
  + 'back if you change your mind.',
687
700
  );
701
+ if (operator?.dataDir) {
702
+ result.notes.push(
703
+ `${operator.name ?? 'Your account'} keeps write access to ${programDataDir()} so the CLI can still use it; `
704
+ + 'it is removed when the data is moved back or purged.',
705
+ );
706
+ }
688
707
  result.dataDir = programDataDir();
689
708
  } else {
690
709
  log('Moving the data back to %APPDATA%…');
@@ -722,7 +741,12 @@ export async function uninstall({
722
741
  }
723
742
 
724
743
  const existing = dbGet(STATE_KEY) ?? {};
725
- dbSet(STATE_KEY, { ...existing, mode: null, mechanism: null, uninstalledAt: new Date().toISOString() });
744
+ const keptOperator = mech.mode === MODES.SERVER && keepServerDataLocation && existing.operator?.dataDir
745
+ ? { ...existing.operator, serviceControl: false }
746
+ : null;
747
+ dbSet(STATE_KEY, {
748
+ ...existing, mode: null, mechanism: null, operator: keptOperator, uninstalledAt: new Date().toISOString(),
749
+ });
726
750
 
727
751
  return { ok: true, ...result };
728
752
  }
@@ -925,7 +949,7 @@ export async function restart({ log = () => {}, deps = {} } = {}) {
925
949
  if (!result.ok) return { ok: false, reason: result.reason };
926
950
  } else {
927
951
  const result = await (deps.windowsService ?? windowsService).restart(deps.windowsServiceOpts ?? {});
928
- if (!result.ok) return { ok: false, reason: result.reason };
952
+ if (!result.ok) return { ok: false, reason: result.reason, needsElevation: result.needsElevation ?? false };
929
953
  }
930
954
 
931
955
  // A restart also ends a deliberate stop: the service is running again, so
@@ -1049,6 +1073,7 @@ export async function status({ cache = false, coldWaitMs, deps = {} } = {}) {
1049
1073
  dataDir,
1050
1074
  config,
1051
1075
  granted: recorded.granted ?? [],
1076
+ operatorSid: recorded.operator?.sid ?? null,
1052
1077
  ...(deps.windowsServiceOpts ?? {}),
1053
1078
  });
1054
1079
  }
@@ -1088,6 +1113,36 @@ export async function status({ cache = false, coldWaitMs, deps = {} } = {}) {
1088
1113
  if (isWindows && mech.mode === MODES.SERVER && out.service.acl && !out.service.acl.ok) {
1089
1114
  out.warnings.push(out.service.acl.reason);
1090
1115
  }
1116
+
1117
+ // Who may start and stop it without elevation. The record says who it was
1118
+ // granted to; the service's DACL (read by the probe) says whether it still is.
1119
+ if (isWindows && mech.mode === MODES.SERVER) {
1120
+ const op = recorded.operator ?? null;
1121
+ const control = out.service.operatorControl ?? null;
1122
+ out.operator = op
1123
+ ? {
1124
+ name: op.name ?? null,
1125
+ sid: op.sid,
1126
+ serviceControl: control ? control.granted : Boolean(op.serviceControl),
1127
+ dataDir: Boolean(op.dataDir),
1128
+ grantedAt: op.grantedAt ?? null,
1129
+ verified: Boolean(control),
1130
+ }
1131
+ : null;
1132
+
1133
+ if (out.service.installed && (!op || !op.dataDir || (control && !control.granted))) {
1134
+ out.warnings.push(
1135
+ 'Starting and stopping the service, and writing its data, need an Administrator terminal for your '
1136
+ + 'account. Run `ezz service repair` once from an Administrator PowerShell to allow it without elevation.',
1137
+ );
1138
+ }
1139
+ if (control?.excessive) {
1140
+ out.warnings.push(
1141
+ `The service permissions give ${op?.name ?? op?.sid} more than start, stop and query. `
1142
+ + 'Run `ezz service repair` from an Administrator PowerShell to reset them.',
1143
+ );
1144
+ }
1145
+ }
1091
1146
  if (isWindows && mech.mode !== MODES.SERVER) {
1092
1147
  out.warnings.push(...(out.service.warnings ?? []));
1093
1148
  }
@@ -1247,6 +1302,8 @@ export async function repair({ log = () => {}, deps = {} } = {}) {
1247
1302
  dataDir,
1248
1303
  appRoot: appRoot(),
1249
1304
  config: loadConfig(),
1305
+ // Repair is how an install from before 1.4.3 gets these rights.
1306
+ operator: await (deps.resolveOperator ?? resolveOperator)({}),
1250
1307
  log,
1251
1308
  // Repair restores the previous runtime if the daemon does not come up,
1252
1309
  // and "came up" means its heartbeat — not the service manager's word.
@@ -1259,7 +1316,12 @@ export async function repair({ log = () => {}, deps = {} } = {}) {
1259
1316
  });
1260
1317
  if (result.ok) {
1261
1318
  const existing = dbGet(STATE_KEY) ?? {};
1262
- dbSet(STATE_KEY, { ...existing, granted: result.granted ?? existing.granted ?? [], repairedAt: new Date().toISOString() });
1319
+ dbSet(STATE_KEY, {
1320
+ ...existing,
1321
+ granted: result.granted ?? existing.granted ?? [],
1322
+ operator: result.operator ?? existing.operator ?? null,
1323
+ repairedAt: new Date().toISOString(),
1324
+ });
1263
1325
  }
1264
1326
  return { ...result, mechanism: 'winsw' };
1265
1327
  }
@@ -0,0 +1,401 @@
1
+ /**
2
+ * core/service/operator.js
3
+ *
4
+ * Windows Server mode: what the INSTALLING USER may do without elevation.
5
+ *
6
+ * Server mode needs an Administrator terminal for anything that replaces the
7
+ * service's files. It should not need one to start or stop the service, or to
8
+ * run `ezz hub status` against the shared database. So install and repair give
9
+ * exactly one account — the one that installed it, by SID — two things:
10
+ *
11
+ * 1. On the service's own DACL: start, stop and query (`CC LC LO RP WP`).
12
+ * Not change its configuration (DC), not delete it (SD), not rewrite its
13
+ * permissions (WD) or take ownership (WO). Those stay with Administrators.
14
+ * 2. Modify on the data directory, so the CLI can write the database a
15
+ * service account also writes. Without it every write from a normal
16
+ * terminal failed with "SqliteError: attempt to write a readonly database".
17
+ *
18
+ * ── Why never Users or Everyone ────────────────────────────────────────────
19
+ *
20
+ * The grant is for a person, not for whoever logs on to the server. Only an
21
+ * account SID is accepted (S-1-5-21-…, a local or domain user; S-1-12-1-…, an
22
+ * Entra ID user); well-known groups are refused by shape, so no code path can
23
+ * be talked into granting Users (S-1-5-32-545) or Everyone (S-1-1-0).
24
+ *
25
+ * ── Why the runtime and the wrapper are protected ──────────────────────────
26
+ *
27
+ * Both live INSIDE the data directory (`runtime\`, `bin\`), so the data grant
28
+ * would otherwise be inherited by them — and replacing node.exe or
29
+ * EasyDevOps.exe would run that user's code as NT SERVICE\EasyDevOps. Those two
30
+ * folders stop inheriting and get an explicit list instead: SYSTEM and
31
+ * Administrators full control, Users and the service account read & execute.
32
+ * A deny entry would have been shorter and wrong: the same SID is in the
33
+ * user's ELEVATED token too, so it would also lock out `ezz update`.
34
+ *
35
+ * Every command here goes through shell.js and is injectable, so tests drive a
36
+ * stub and assert the exact commands rather than touching real ACLs.
37
+ */
38
+
39
+ import fs from 'fs';
40
+
41
+ import { run as shellRun } from '../shell.js';
42
+ import { WINDOWS_SC, windowsCurrentUserCmd } from '../platform.js';
43
+ import { SERVICE_ID, SERVICE_ACCOUNT } from './winsw.js';
44
+
45
+ /** Set by the relaunch, so the elevated copy grants the user who asked — see cli/elevation.js. */
46
+ export const OPERATOR_SID_ENV = 'EZ_OPERATOR_SID';
47
+
48
+ /** Start, stop, query status, query config, interrogate. Nothing that changes the service. */
49
+ export const OPERATOR_SERVICE_RIGHTS = 'CCLCLORPWP';
50
+
51
+ /** Rights an operator ACE must never carry: change config, delete, write DAC, write owner, all access. */
52
+ const FORBIDDEN_RIGHTS = ['DC', 'SD', 'WD', 'WO', 'GA', 'GW', 'FA'];
53
+
54
+ /**
55
+ * Whether `sid` names one account (a user), not a group or a well-known SID.
56
+ *
57
+ * @param {unknown} sid
58
+ * @returns {boolean}
59
+ */
60
+ export function isAccountSid(sid) {
61
+ return typeof sid === 'string'
62
+ && (/^S-1-5-21-\d{1,10}-\d{1,10}-\d{1,10}-\d{1,10}$/.test(sid)
63
+ || /^S-1-12-1-\d{1,10}-\d{1,10}-\d{1,10}-\d{1,10}$/.test(sid));
64
+ }
65
+
66
+ /**
67
+ * The account this process runs as.
68
+ *
69
+ * @returns {Promise<{ sid: string, name: string|null }|null>}
70
+ */
71
+ export async function currentUser({ run = shellRun } = {}) {
72
+ const result = await run(windowsCurrentUserCmd(), { timeout: 20_000 });
73
+ const line = `${result?.stdout ?? ''}`.trim().split(/\r?\n/).pop() ?? '';
74
+ const [sid, name] = line.split('|');
75
+ if (!isAccountSid(sid?.trim())) return null;
76
+ return { sid: sid.trim(), name: name?.trim() || null };
77
+ }
78
+
79
+ /**
80
+ * Who the operator grants are for.
81
+ *
82
+ * The relaunch passes the SID of the user who asked for it; that is who
83
+ * installed the service even when the elevated window runs under a different
84
+ * administrator account. Otherwise it is this process's own account — the
85
+ * usual case, where the same person ran PowerShell "as administrator".
86
+ *
87
+ * @returns {Promise<{ sid: string, name: string|null, via: 'relaunch'|'current' }|null>}
88
+ */
89
+ export async function resolveOperator({ run = shellRun, env = process.env } = {}) {
90
+ const me = await currentUser({ run });
91
+ const passed = env?.[OPERATOR_SID_ENV];
92
+ if (isAccountSid(passed)) {
93
+ return { sid: passed, name: me?.sid === passed ? me.name : null, via: 'relaunch' };
94
+ }
95
+ return me ? { ...me, via: 'current' } : null;
96
+ }
97
+
98
+ // ─── The service DACL ────────────────────────────────────────────────────────
99
+
100
+ /**
101
+ * Splits an SDDL string into its DACL and the rest.
102
+ *
103
+ * @param {string} sddl
104
+ * @returns {{ head: string, aces: string[], tail: string }|null}
105
+ */
106
+ function splitDacl(sddl) {
107
+ const match = /^(.*?D:[A-Z]*)((?:\([^()]*\))*)(.*)$/s.exec(sddl);
108
+ if (!match) return null;
109
+ const aces = match[2].match(/\([^()]*\)/g) ?? [];
110
+ return { head: match[1], aces, tail: match[3] };
111
+ }
112
+
113
+ /** The trustee field of one ACE, `(type;flags;rights;object;inherit;trustee)`. */
114
+ function aceTrustee(ace) {
115
+ return ace.slice(1, -1).split(';')[5] ?? '';
116
+ }
117
+
118
+ /**
119
+ * The SDDL with exactly one operator ACE for `sid`, appended to the DACL.
120
+ *
121
+ * Any earlier ACE for the same SID is removed first, so a repair cannot stack
122
+ * grants. Allow ACEs go after the existing ones, which keeps the DACL in
123
+ * canonical order (explicit denies first).
124
+ *
125
+ * @param {string} sddl
126
+ * @param {string} sid
127
+ * @returns {string}
128
+ */
129
+ export function withOperatorAce(sddl, sid) {
130
+ if (!isAccountSid(sid)) throw new Error(`not an account SID: ${sid}`);
131
+ const parts = splitDacl(sddl);
132
+ if (!parts) throw new Error('the service security descriptor has no DACL');
133
+ const kept = parts.aces.filter((ace) => aceTrustee(ace).toUpperCase() !== sid.toUpperCase());
134
+ return `${parts.head}${kept.join('')}(A;;${OPERATOR_SERVICE_RIGHTS};;;${sid})${parts.tail}`;
135
+ }
136
+
137
+ /**
138
+ * Whether the SDDL lets `sid` start and stop the service, and nothing more.
139
+ *
140
+ * @returns {{ granted: boolean, excessive: boolean }}
141
+ */
142
+ export function operatorAceState(sddl, sid) {
143
+ const parts = splitDacl(sddl ?? '');
144
+ if (!parts || !isAccountSid(sid)) return { granted: false, excessive: false };
145
+ const mine = parts.aces.filter((ace) => aceTrustee(ace).toUpperCase() === sid.toUpperCase()
146
+ && ace.startsWith('(A;'));
147
+ const fields = mine.map((ace) => ace.slice(1, -1).split(';')[2] ?? '');
148
+ // SDDL service rights are two-letter codes. A hex mask (0x…) cannot be read
149
+ // that way, so it counts as granting too much rather than as fine.
150
+ const hex = fields.some((field) => /^0x/i.test(field));
151
+ const codes = fields.flatMap((field) => (/^0x/i.test(field) ? [] : field.match(/[A-Z]{2}/g) ?? []));
152
+ return {
153
+ granted: ['RP', 'WP', 'LC'].every((code) => codes.includes(code)),
154
+ excessive: hex || FORBIDDEN_RIGHTS.some((code) => codes.includes(code)),
155
+ };
156
+ }
157
+
158
+ /** `sc.exe sdshow`, the DACL line only. */
159
+ export async function readServiceSddl({ run = shellRun } = {}) {
160
+ const result = await run(`${WINDOWS_SC} sdshow ${SERVICE_ID}`, { timeout: 20_000 });
161
+ const line = `${result?.stdout ?? ''}`.split(/\r?\n/).map((l) => l.trim()).find((l) => l.startsWith('D:'));
162
+ return line ?? null;
163
+ }
164
+
165
+ /**
166
+ * Lets `sid` start, stop and query the service. Needs elevation.
167
+ *
168
+ * @returns {Promise<{ ok: boolean, reason?: string }>}
169
+ */
170
+ export async function grantServiceControl({ sid, run = shellRun } = {}) {
171
+ if (!isAccountSid(sid)) return { ok: false, reason: 'no user account to grant it to' };
172
+
173
+ const current = await readServiceSddl({ run });
174
+ if (!current) return { ok: false, reason: `could not read the ${SERVICE_ID} service permissions` };
175
+
176
+ let next;
177
+ try {
178
+ next = withOperatorAce(current, sid);
179
+ } catch (err) {
180
+ return { ok: false, reason: err.message };
181
+ }
182
+ // The value is passed to a shell. SDDL is letters, digits and `:;()-`;
183
+ // anything else means it was not read correctly, and it is not sent.
184
+ if (!/^[A-Za-z0-9:;()-]+$/.test(next)) {
185
+ return { ok: false, reason: 'the service permissions contained unexpected characters; nothing was changed' };
186
+ }
187
+
188
+ const result = await run(`${WINDOWS_SC} sdset ${SERVICE_ID} "${next}"`, { timeout: 20_000 });
189
+ if (!result.success) {
190
+ return { ok: false, reason: `${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 300) || 'sc.exe sdset failed' };
191
+ }
192
+
193
+ const after = operatorAceState(await readServiceSddl({ run }), sid);
194
+ return after.granted && !after.excessive
195
+ ? { ok: true }
196
+ : { ok: false, reason: 'the permission was written but does not read back as expected' };
197
+ }
198
+
199
+ // ─── The data directory ──────────────────────────────────────────────────────
200
+
201
+ /** Well-known SIDs, so the commands do not depend on the display language. */
202
+ const SID_SYSTEM = '*S-1-5-18';
203
+ const SID_ADMINISTRATORS = '*S-1-5-32-544';
204
+ const SID_USERS = '*S-1-5-32-545';
205
+
206
+ /**
207
+ * Modify on the data directory, inherited by what it contains.
208
+ *
209
+ * No `/T`: the grant reaches existing files and folders by inheritance, which
210
+ * is exactly what lets the protected folders below opt out of it. `/T` would
211
+ * write it onto every child explicitly, protected or not.
212
+ */
213
+ export function buildDataDirGrantCommand(dataDir, sid) {
214
+ return `icacls "${safePath(dataDir)}" /grant "*${accountSid(sid)}:(OI)(CI)M" /C /Q`;
215
+ }
216
+
217
+ /** Removes every allow entry for the SID under the data directory. */
218
+ export function buildDataDirRevokeCommand(dataDir, sid) {
219
+ return `icacls "${safePath(dataDir)}" /remove:g "*${accountSid(sid)}" /T /C /Q`;
220
+ }
221
+
222
+ /**
223
+ * A path that can sit inside double quotes in a shell command. Windows paths
224
+ * cannot contain `"`, so one that does was not a path; refused rather than
225
+ * escaped. The data directory can come from EASY_DEVOPS_DATA_DIR.
226
+ */
227
+ function safePath(dir) {
228
+ const value = String(dir ?? '');
229
+ if (!value || /["\r\n`$]/.test(value)) throw new Error(`refusing an unusual path: ${JSON.stringify(value)}`);
230
+ return value;
231
+ }
232
+
233
+ /** The SID, or a throw: nothing but an account SID is ever written into a grant. */
234
+ function accountSid(sid) {
235
+ if (!isAccountSid(sid)) throw new Error(`not an account SID: ${sid}`);
236
+ return sid;
237
+ }
238
+
239
+ /**
240
+ * The commands that make one folder administrator-only to change.
241
+ *
242
+ * Inheritance off, then an explicit list replacing whatever was there, then
243
+ * any leftover entry for the operator removed (a grant from before this
244
+ * protection existed was applied with `/T`).
245
+ */
246
+ export function buildProtectCommands(dir, sid = null, { serviceAccount = true } = {}) {
247
+ const target = safePath(dir);
248
+ // Before the service is registered its account does not exist yet, and
249
+ // icacls refuses an unknown name; install protects again once it does.
250
+ const service = serviceAccount ? ` "${SERVICE_ACCOUNT}:(OI)(CI)RX"` : '';
251
+ const commands = [
252
+ // Administrators own it, so no other account holds the owner's implicit
253
+ // right to rewrite its permissions.
254
+ `icacls "${target}" /setowner "${SID_ADMINISTRATORS}" /T /C /Q`,
255
+ `icacls "${target}" /inheritance:r /grant:r "${SID_SYSTEM}:(OI)(CI)F" "${SID_ADMINISTRATORS}:(OI)(CI)F" `
256
+ + `"${SID_USERS}:(OI)(CI)RX"${service} /T /C /Q`,
257
+ ];
258
+ if (isAccountSid(sid)) commands.push(`icacls "${target}" /remove:g "*${sid}" /T /C /Q`);
259
+ return commands;
260
+ }
261
+
262
+ /**
263
+ * Makes the runtime and wrapper folders administrator-only to change.
264
+ *
265
+ * Runs on install and on every repair: a repair replaces the runtime folder
266
+ * with a fresh copy, and a fresh folder inherits again.
267
+ *
268
+ * @param {Object} opts
269
+ * @param {string[]} opts.dirs
270
+ * @param {string|null} [opts.sid]
271
+ * @returns {Promise<{ ok: boolean, protected: string[], failed: Array<{ path: string, reason: string }> }>}
272
+ */
273
+ export async function protectServiceFiles({ dirs, sid = null, serviceAccount = true, run = shellRun, log = () => {} } = {}) {
274
+ const done = [];
275
+ const failed = [];
276
+ for (const dir of dirs) {
277
+ if (!dir || !fs.existsSync(dir)) continue;
278
+ let error = null;
279
+ let commands = [];
280
+ try {
281
+ commands = buildProtectCommands(dir, sid, { serviceAccount });
282
+ } catch (err) {
283
+ error = err.message;
284
+ }
285
+ for (const command of commands) {
286
+ const result = await run(command, { timeout: 120_000 });
287
+ if (!result.success) {
288
+ error = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 300) || 'icacls failed';
289
+ break;
290
+ }
291
+ }
292
+ if (error) {
293
+ failed.push({ path: dir, reason: error });
294
+ log(` ${dir}: could not be protected`);
295
+ } else {
296
+ done.push(dir);
297
+ log(` ${dir}: administrators only (read & execute for the service and users)`);
298
+ }
299
+ }
300
+ return { ok: failed.length === 0, protected: done, failed };
301
+ }
302
+
303
+ /**
304
+ * Everything the operator gets, applied in the order that keeps it safe:
305
+ * protect the service's files first, then grant the data directory.
306
+ *
307
+ * @param {Object} opts
308
+ * @param {{ sid: string, name: string|null }|null} opts.operator
309
+ * @param {string} opts.dataDir
310
+ * @param {string[]} opts.protectedDirs The runtime and wrapper folders
311
+ * @returns {Promise<Object>} the record to keep under `service-state.operator`
312
+ */
313
+ export async function grantOperator({ operator, dataDir, protectedDirs, run = shellRun, log = () => {} } = {}) {
314
+ const protection = await protectServiceFiles({ dirs: protectedDirs, sid: operator?.sid ?? null, run, log });
315
+
316
+ if (!operator || !isAccountSid(operator.sid)) {
317
+ return {
318
+ record: null,
319
+ protection,
320
+ notes: ['could not tell which account ran the install, so nobody was allowed to start or stop the service '
321
+ + 'without elevation'],
322
+ };
323
+ }
324
+
325
+ const notes = [];
326
+ const control = await grantServiceControl({ sid: operator.sid, run });
327
+ if (control.ok) log(` ${operator.name ?? operator.sid}: may start, stop and restart the service`);
328
+ else notes.push(`start/stop without elevation was not granted: ${control.reason}`);
329
+
330
+ // Only once the service's own files are protected: the data grant is
331
+ // inherited, and until then it would have reached them.
332
+ let dataAccess = false;
333
+ if (protection.ok) {
334
+ const result = await runSafely(() => buildDataDirGrantCommand(dataDir, operator.sid), run, 60_000);
335
+ dataAccess = result.success;
336
+ if (dataAccess) log(` ${operator.name ?? operator.sid}: may use the data directory without elevation`);
337
+ else notes.push(`data directory access was not granted: ${`${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 200)}`);
338
+ } else {
339
+ // Fail closed. A grant from an earlier install or repair would otherwise
340
+ // still be inherited by a runtime folder that could not be protected.
341
+ await runSafely(() => buildDataDirRevokeCommand(dataDir, operator.sid), run, 120_000);
342
+ notes.push('the runtime folder could not be protected, so the data directory is not shared with your account; '
343
+ + 'run `ezz service repair` as administrator again');
344
+ }
345
+
346
+ return {
347
+ record: {
348
+ sid: operator.sid,
349
+ name: operator.name ?? null,
350
+ serviceControl: control.ok,
351
+ dataDir: dataAccess,
352
+ grantedAt: new Date().toISOString(),
353
+ },
354
+ protection,
355
+ notes,
356
+ };
357
+ }
358
+
359
+ /**
360
+ * Removes the operator's data directory grant. The service DACL entry needs no
361
+ * removal: it belongs to the service and is deleted with it.
362
+ */
363
+ export async function revokeOperator({ operator, dataDir, run = shellRun, log = () => {} } = {}) {
364
+ if (!operator || !isAccountSid(operator.sid) || !dataDir || !fs.existsSync(dataDir)) return { ok: true };
365
+ const result = await runSafely(() => buildDataDirRevokeCommand(dataDir, operator.sid), run, 120_000);
366
+ if (result.success) log(` ${operator.name ?? operator.sid}: data directory access removed`);
367
+ return result.success
368
+ ? { ok: true }
369
+ : { ok: false, reason: `${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 300) };
370
+ }
371
+
372
+ /** Builds a command and runs it; a refused build is a failed result, never a throw. */
373
+ async function runSafely(build, run, timeout) {
374
+ let command;
375
+ try {
376
+ command = build();
377
+ } catch (err) {
378
+ return { success: false, stdout: '', stderr: err.message };
379
+ }
380
+ return run(command, { timeout });
381
+ }
382
+
383
+ /**
384
+ * Creates a folder the service will run code from and protects it while it is
385
+ * still empty.
386
+ *
387
+ * A fresh folder inside the data directory inherits the installing user's
388
+ * Modify grant, so copying first and protecting afterwards would leave a window
389
+ * in which a file could be placed or replaced before the service starts on it.
390
+ *
391
+ * @returns {Promise<{ ok: boolean, reason?: string }>}
392
+ */
393
+ export async function prepareProtectedDir({ dir, sid = null, serviceAccount = true, run = shellRun, log = () => {} } = {}) {
394
+ try {
395
+ fs.mkdirSync(dir, { recursive: true });
396
+ } catch (err) {
397
+ return { ok: false, reason: `could not create ${dir}: ${err.message}` };
398
+ }
399
+ const result = await protectServiceFiles({ dirs: [dir], sid, serviceAccount, run, log });
400
+ return result.ok ? { ok: true } : { ok: false, reason: result.failed[0]?.reason ?? `could not protect ${dir}` };
401
+ }
@@ -48,7 +48,7 @@ import { run } from '../shell.js';
48
48
  import { isWindows, getDataDir, quoteExe } from '../platform.js';
49
49
  import { detectInstallSource } from '../installSource.js';
50
50
  import * as windowsPersonal from './windowsPersonal.js';
51
- import { canWriteProgramData } from './windowsService.js';
51
+ import { canWriteProgramData, isElevated } from './windowsService.js';
52
52
  import {
53
53
  runtimeDir,
54
54
  runtimeNodePath,
@@ -683,6 +683,24 @@ export async function update({
683
683
  const mech = deps.mechanism ?? resolveMechanism();
684
684
  const service = deps.service ?? (await import('./index.js'));
685
685
 
686
+ // 0. Windows Server mode: the runtime folder is administrator-only on
687
+ // purpose. Asked of Windows before anything is installed or stopped — the
688
+ // write probe alone is not enough once the installing user may write the
689
+ // data directory around it.
690
+ if (isWindows && mech.mode === MODES.SERVER) {
691
+ const elevated = await (deps.isElevated ?? isElevated)({});
692
+ if (elevated === false) {
693
+ return {
694
+ ok: false,
695
+ step: 'elevation',
696
+ needsElevation: true,
697
+ untouched: true,
698
+ reason: 'Moving the service to another Node version replaces node.exe in an administrator-only folder. '
699
+ + 'Run `ezz runtime update` from PowerShell opened with "Run as administrator". No password is needed.',
700
+ };
701
+ }
702
+ }
703
+
686
704
  // 1. The target has to be installable and allowed.
687
705
  if (!target?.version) return { ok: false, step: 'target', reason: 'no target version was chosen' };
688
706
  if (!meetsMinimum(target.version)) {