@indigoai-us/hq-cli 5.345.215-beta.0 → 5.345.215
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.
- package/CHANGELOG.md +65 -1
- package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
- package/dist/command-catalog.generated.d.ts +46 -6
- package/dist/command-catalog.generated.js +53 -6
- package/dist/commands/bot.js +64 -6
- package/dist/commands/capacity.d.ts +4 -1
- package/dist/commands/capacity.js +46 -10
- package/dist/commands/cloud.js +1 -1
- package/dist/commands/core-delegate-w1b.js +15 -1
- package/dist/commands/core-policy.js +67 -8
- package/dist/commands/daemon.js +5 -0
- package/dist/commands/files-browse.d.ts +11 -4
- package/dist/commands/files-browse.js +21 -4
- package/dist/commands/files.d.ts +1 -1
- package/dist/commands/files.js +25 -11
- package/dist/commands/integrations-auth-rules.d.ts +27 -0
- package/dist/commands/integrations-auth-rules.js +79 -0
- package/dist/commands/integrations-import.js +124 -12
- package/dist/commands/lanes.js +2 -2
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +60 -35
- package/dist/commands/sync-held.js +5 -2
- package/dist/lazy-commands.js +3 -5
- package/dist/lib/bot/fleet-cron.d.ts +8 -0
- package/dist/lib/bot/fleet-cron.js +35 -3
- package/dist/lib/bot/fleet-daemon.d.ts +46 -0
- package/dist/lib/bot/fleet-daemon.js +99 -1
- package/dist/lib/bot/probe.js +7 -1
- package/dist/lib/bot/run.js +20 -1
- package/dist/lib/bot/runtime/codex.js +1 -1
- package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
- package/dist/lib/bot/runtime/grok-acp.js +6 -3
- package/dist/lib/bot/runtime/index.js +19 -9
- package/dist/lib/bot/runtime/messages-stream.js +2 -2
- package/dist/lib/bot/runtime/types.d.ts +15 -0
- package/dist/lib/bot/runtime/types.js +9 -0
- package/dist/lib/bot/runtime-failure.d.ts +23 -0
- package/dist/lib/bot/runtime-failure.js +43 -1
- package/dist/lib/capacity/accounts.d.ts +8 -0
- package/dist/lib/capacity/accounts.js +19 -0
- package/dist/lib/capacity/available.d.ts +154 -0
- package/dist/lib/capacity/available.js +905 -0
- package/dist/lib/capacity/codex-availability.d.ts +14 -1
- package/dist/lib/capacity/codex-availability.js +26 -1
- package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
- package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
- package/dist/lib/capacity/collectors/codex.js +10 -7
- package/dist/lib/capacity/ledger.d.ts +37 -1
- package/dist/lib/capacity/ledger.js +207 -30
- package/dist/lib/capacity/project.d.ts +26 -0
- package/dist/lib/capacity/project.js +137 -8
- package/dist/lib/capacity/refusal-rows.d.ts +31 -0
- package/dist/lib/capacity/refusal-rows.js +61 -0
- package/dist/lib/capacity/refusal.d.ts +53 -2
- package/dist/lib/capacity/refusal.js +284 -65
- package/dist/lib/capacity/route.js +46 -11
- package/dist/lib/capacity/widget.d.ts +12 -1
- package/dist/lib/capacity/widget.js +91 -3
- package/dist/lib/daemon/resolver.d.ts +2 -0
- package/dist/lib/daemon/resolver.js +3 -0
- package/dist/lib/daemon/run.d.ts +9 -0
- package/dist/lib/daemon/run.js +54 -1
- package/dist/lib/daemon/server.d.ts +2 -0
- package/dist/lib/daemon/server.js +10 -1
- package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
- package/dist/lib/daemon/tcc-eperm.js +310 -0
- package/dist/lib/delivery/admission.d.ts +86 -0
- package/dist/lib/delivery/admission.js +148 -0
- package/dist/lib/delivery/artifacts.d.ts +7 -1
- package/dist/lib/delivery/artifacts.js +29 -10
- package/dist/lib/delivery/attempt-id.d.ts +13 -0
- package/dist/lib/delivery/attempt-id.js +16 -0
- package/dist/lib/delivery/disposable-target.d.ts +42 -0
- package/dist/lib/delivery/disposable-target.js +111 -0
- package/dist/lib/delivery/effects.d.ts +136 -0
- package/dist/lib/delivery/effects.js +541 -0
- package/dist/lib/delivery/enrollment.d.ts +21 -17
- package/dist/lib/delivery/enrollment.js +83 -5
- package/dist/lib/delivery/escalations.d.ts +51 -0
- package/dist/lib/delivery/escalations.js +60 -0
- package/dist/lib/delivery/lease.d.ts +80 -0
- package/dist/lib/delivery/lease.js +134 -0
- package/dist/lib/delivery/migrations.d.ts +120 -4
- package/dist/lib/delivery/migrations.js +215 -15
- package/dist/lib/delivery/mqtt.d.ts +2 -0
- package/dist/lib/delivery/mqtt.js +7 -0
- package/dist/lib/delivery/reconciler.d.ts +65 -1
- package/dist/lib/delivery/reconciler.js +224 -13
- package/dist/lib/delivery/rpc/client.d.ts +22 -0
- package/dist/lib/delivery/rpc/client.js +159 -0
- package/dist/lib/delivery/rpc/port.d.ts +40 -0
- package/dist/lib/delivery/rpc/port.js +16 -0
- package/dist/lib/delivery/rpc/server.d.ts +30 -0
- package/dist/lib/delivery/rpc/server.js +205 -0
- package/dist/lib/delivery/rpc/wire.d.ts +85 -0
- package/dist/lib/delivery/rpc/wire.js +143 -0
- package/dist/lib/delivery/store.d.ts +2 -0
- package/dist/lib/delivery/store.js +4 -0
- package/dist/lib/delivery/windows-service-install.d.ts +262 -0
- package/dist/lib/delivery/windows-service-install.js +892 -0
- package/dist/lib/delivery/workers/macos.d.ts +16 -1
- package/dist/lib/delivery/workers/macos.js +54 -12
- package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
- package/dist/lib/delivery/workers/windows-service-live.js +711 -0
- package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
- package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
- package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
- package/dist/lib/delivery/workers/windows-service.js +584 -0
- package/dist/lib/delivery/workers/windows.d.ts +32 -22
- package/dist/lib/delivery/workers/windows.js +50 -64
- package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
- package/dist/lib/hot-channels/adapters/meetings.js +36 -3
- package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
- package/dist/lib/hot-channels/signals-pass.js +71 -2
- package/dist/lib/hot-channels/signals-redo.js +10 -2
- package/dist/lib/lanes/watcher.js +35 -0
- package/dist/lib/signals/steps/extract.js +40 -4
- package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
- package/dist/utils/catalog-runtime-paths.d.ts +34 -0
- package/dist/utils/catalog-runtime-paths.js +53 -0
- package/dist/utils/files-browse-acl.js +1 -1
- package/package.json +7 -7
- package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
- package/dist/lib/delivery/workers/windows-boundary.js +0 -693
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live checks for the installed US-006 pilot service (proposal 040 gates
|
|
3
|
+
* N1, N2 and N3). Bundled to us006-live.mjs by
|
|
4
|
+
* scripts/windows/build-us006-service.mjs and run by an Administrator on the
|
|
5
|
+
* test host:
|
|
6
|
+
* node us006-live.mjs n1 identity of a job run through the service
|
|
7
|
+
* node us006-live.mjs n2 tree cancel, job ACL probe, limits, service stop, runner kill
|
|
8
|
+
* node us006-live.mjs n3 after rollback: nothing of the pilot is left
|
|
9
|
+
*
|
|
10
|
+
* Every job goes through the same SpoolTransport the CLI uses, so it runs
|
|
11
|
+
* as the service account inside a Job Object. The checks start and stop only
|
|
12
|
+
* the pilot service, and end only one process: the runner node.exe named by
|
|
13
|
+
* the heartbeat, after its image name and account are confirmed. Each check
|
|
14
|
+
* ends with one line "N<x> PASS" or "N<x> FAIL: <reason>" and exit code 0 or 1.
|
|
15
|
+
*/
|
|
16
|
+
import { spawnSync } from "node:child_process";
|
|
17
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { dirname, join } from "node:path";
|
|
19
|
+
import { profileFolderCheck, validateNames } from "../windows-service-install.js";
|
|
20
|
+
import { manifestDigest, PILOT040, serviceSidFor, spoolPaths, SpoolTransport } from "./windows-service.js";
|
|
21
|
+
export const realLiveHost = {
|
|
22
|
+
run(file, args) {
|
|
23
|
+
const r = spawnSync(file, args, { encoding: "utf8", windowsHide: true, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
|
|
24
|
+
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Review C4: Windows creates the service profile at the first start. If ServiceProfiles\<service> (any type) or
|
|
29
|
+
* ProfileList\<SID> exists before that, it was left by an earlier run or planted, and must be cleared by rollback
|
|
30
|
+
* first. "Never started" is the absence of config\first-start.json, which only Administrators can write. The marker
|
|
31
|
+
* is written only after the post-start check passes (checkAfterFirstStart). Returns the refusal, or null.
|
|
32
|
+
*/
|
|
33
|
+
export function checkBeforeFirstStart(o) {
|
|
34
|
+
const marker = join(o.root, "config", "first-start.json");
|
|
35
|
+
if (existsSync(marker))
|
|
36
|
+
return null;
|
|
37
|
+
const folder = o.serviceProfilesDir ? join(o.serviceProfilesDir, o.service) : `${o.systemRoot ?? "C:\\Windows"}\\ServiceProfiles\\${o.service}`;
|
|
38
|
+
const key = `HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${serviceSidFor(o.service)}`;
|
|
39
|
+
let present = true;
|
|
40
|
+
try {
|
|
41
|
+
lstatSync(folder);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
present = false;
|
|
45
|
+
}
|
|
46
|
+
const why = (what) => `refused before the service's first start: ${what} exists; a previous service profile must be cleared by rollback first`;
|
|
47
|
+
if (present)
|
|
48
|
+
return why(folder);
|
|
49
|
+
const r = o.host.run(tools(o.systemRoot).reg, ["query", key]);
|
|
50
|
+
if (r.status === 0)
|
|
51
|
+
return why(key);
|
|
52
|
+
if (r.status !== 1)
|
|
53
|
+
return `refused before the service's first start: reg.exe query exit ${r.status}; cannot tell whether a previous service profile exists`;
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
const POST_START_MAX_WAIT_MS = 10_000;
|
|
57
|
+
/**
|
|
58
|
+
* Review R8: right after the first start, the profile Windows created must pass the same folder checks rollback
|
|
59
|
+
* uses (profileFolderCheck: exact path, no link, owner SYSTEM/Administrators/service SID, protected DACL, no other
|
|
60
|
+
* writer, explicit allow ACE for the service SID, ProfileList path matches). Windows may create it lazily, so it is
|
|
61
|
+
* polled for at most 10 s; still absent is a failure. On any failure the service is stopped and no marker is
|
|
62
|
+
* written, so the next run repeats the pre-start check (and refuses, because the folder now exists). On success
|
|
63
|
+
* config\first-start.json is written. Returns the failure, or null.
|
|
64
|
+
*/
|
|
65
|
+
export async function checkAfterFirstStart(o) {
|
|
66
|
+
const t = tools(o.systemRoot);
|
|
67
|
+
const profilesDir = o.serviceProfilesDir ?? `${o.systemRoot ?? "C:\\Windows"}\\ServiceProfiles`;
|
|
68
|
+
const folder = o.serviceProfilesDir ? join(profilesDir, o.service) : `${profilesDir}\\${o.service}`;
|
|
69
|
+
const sid = serviceSidFor(o.service);
|
|
70
|
+
const key = `HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}`;
|
|
71
|
+
const waitMs = Math.min(o.postStartWaitMs ?? POST_START_MAX_WAIT_MS, POST_START_MAX_WAIT_MS);
|
|
72
|
+
const pause = o.sleepMs ?? sleep;
|
|
73
|
+
const exists = () => {
|
|
74
|
+
try {
|
|
75
|
+
lstatSync(folder);
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const fail = (why) => {
|
|
83
|
+
const r = o.host.run(t.sc, ["stop", o.service]);
|
|
84
|
+
o.out(` sc.exe stop ${o.service} (post-start profile check failed): exit ${r.status}`);
|
|
85
|
+
return `post-start profile check failed: ${why}; the service was stopped`;
|
|
86
|
+
};
|
|
87
|
+
for (let waited = 0; !exists() && waited < waitMs; waited += 250)
|
|
88
|
+
await pause(250);
|
|
89
|
+
if (!exists())
|
|
90
|
+
return fail(`${folder} did not appear within ${waitMs / 1000} s after the first start`);
|
|
91
|
+
const verdict = profileFolderCheck({ run: (file, args) => o.host.run(file, args), sleep: () => { } }, { kind: "remove-service-profile-folder", label: "post-start profile check", path: folder, profilesDir, service: o.service, sid, key, reg: t.reg, systemRoot: o.serviceProfilesDir ? dirname(profilesDir) : (o.systemRoot ?? "C:\\Windows") });
|
|
92
|
+
if (verdict.state === "refuse")
|
|
93
|
+
return fail(verdict.reason.replace(/^left in place; /, ""));
|
|
94
|
+
if (verdict.state === "absent")
|
|
95
|
+
return fail(`${folder} disappeared during the check`);
|
|
96
|
+
writeFileSync(join(o.root, "config", "first-start.json"), JSON.stringify({ service: o.service, checkedAt: new Date().toISOString(), folder, key, postStart: verdict.detail }) + "\n");
|
|
97
|
+
o.out(` post-start profile check: ${verdict.detail}`);
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
function tools(systemRoot = "C:\\Windows") {
|
|
101
|
+
const s32 = `${systemRoot}\\System32`;
|
|
102
|
+
return {
|
|
103
|
+
sc: `${s32}\\sc.exe`,
|
|
104
|
+
reg: `${s32}\\reg.exe`,
|
|
105
|
+
tasklist: `${s32}\\tasklist.exe`,
|
|
106
|
+
taskkill: `${s32}\\taskkill.exe`,
|
|
107
|
+
schtasks: `${s32}\\schtasks.exe`,
|
|
108
|
+
whoami: `${s32}\\whoami.exe`,
|
|
109
|
+
powershell: `${s32}\\WindowsPowerShell\\v1.0\\powershell.exe`,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** The image names these checks start, directly or through the service. Nothing else may be ended on their account. */
|
|
113
|
+
export const LIVE_PROCESS_NAMES = ["node.exe", "hqjob.exe", "whoami.exe", `${PILOT040.service}.exe`, "sc.exe", "reg.exe", "tasklist.exe", "taskkill.exe", "schtasks.exe", "powershell.exe"];
|
|
114
|
+
/**
|
|
115
|
+
* Privileges Windows leaves in a service token whatever the service's
|
|
116
|
+
* required-privileges list says. The installer trims the service to
|
|
117
|
+
* SeChangeNotifyPrivilege, which is also the one privilege the service
|
|
118
|
+
* manager never removes, so that is the whole list. Anything else in a job's
|
|
119
|
+
* token means the trim did not take effect.
|
|
120
|
+
*/
|
|
121
|
+
export const ALWAYS_GRANTED_PRIVILEGES = ["SeChangeNotifyPrivilege"];
|
|
122
|
+
const hasSid = (text, sid) => new RegExp(`(^|[^0-9A-Za-z-])${sid}(?![0-9-])`, "m").test(text);
|
|
123
|
+
/**
|
|
124
|
+
* Judge "whoami /all" output by SID, which does not depend on the display
|
|
125
|
+
* language: the user is the service's virtual account, the token carries the
|
|
126
|
+
* SERVICE logon group, and it carries neither Administrators (in any form,
|
|
127
|
+
* deny-only included) nor an interactive or remote-interactive logon.
|
|
128
|
+
*/
|
|
129
|
+
export function evaluateWhoami(text, service) {
|
|
130
|
+
const sid = serviceSidFor(service);
|
|
131
|
+
const reasons = [];
|
|
132
|
+
const userLine = new RegExp(`^nt service\\\\${service}\\s+${sid}\\s*$`, "im");
|
|
133
|
+
if (!userLine.test(text))
|
|
134
|
+
reasons.push(`user is not NT SERVICE\\${service} (${sid})`);
|
|
135
|
+
if (hasSid(text, "S-1-5-32-544"))
|
|
136
|
+
reasons.push("token carries BUILTIN\\Administrators (S-1-5-32-544)");
|
|
137
|
+
if (hasSid(text, "S-1-5-18"))
|
|
138
|
+
reasons.push("token carries LocalSystem (S-1-5-18)");
|
|
139
|
+
if (hasSid(text, "S-1-5-4"))
|
|
140
|
+
reasons.push("token carries NT AUTHORITY\\INTERACTIVE (S-1-5-4)");
|
|
141
|
+
if (hasSid(text, "S-1-5-14"))
|
|
142
|
+
reasons.push("token carries REMOTE INTERACTIVE LOGON (S-1-5-14)");
|
|
143
|
+
if (!hasSid(text, "S-1-5-6"))
|
|
144
|
+
reasons.push("token lacks NT AUTHORITY\\SERVICE (S-1-5-6)");
|
|
145
|
+
const privileges = [...text.matchAll(/^(Se[A-Za-z]+Privilege)\s/gm)].map((m) => m[1]);
|
|
146
|
+
const extraPrivileges = privileges.filter((p) => !ALWAYS_GRANTED_PRIVILEGES.includes(p));
|
|
147
|
+
if (extraPrivileges.length > 0)
|
|
148
|
+
reasons.push(`token holds privileges beyond ${ALWAYS_GRANTED_PRIVILEGES.join(", ")}: ${extraPrivileges.join(", ")}`);
|
|
149
|
+
return { pass: reasons.length === 0, reasons, privileges, extraPrivileges };
|
|
150
|
+
}
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
// Jobs through the installed service
|
|
153
|
+
/** The node script the N2 jobs run: argv is mode pidDir token role; every process writes <role>.pid. */
|
|
154
|
+
export const LIVE_FIXTURE_SOURCE = String.raw `
|
|
155
|
+
import { spawn } from "node:child_process";
|
|
156
|
+
import { writeFileSync } from "node:fs";
|
|
157
|
+
import { join } from "node:path";
|
|
158
|
+
const [mode, pidDir, token, role] = process.argv.slice(2);
|
|
159
|
+
const self = process.argv[1];
|
|
160
|
+
writeFileSync(join(pidDir, role + ".pid"), String(process.pid));
|
|
161
|
+
const forever = () => setInterval(() => {}, 1000);
|
|
162
|
+
const child = (m, r, opts = {}) => {
|
|
163
|
+
const c = spawn(process.execPath, [self, m, pidDir, token, r], { stdio: "ignore", windowsHide: true, ...opts });
|
|
164
|
+
c.on("error", () => {});
|
|
165
|
+
return c;
|
|
166
|
+
};
|
|
167
|
+
switch (mode) {
|
|
168
|
+
case "tree":
|
|
169
|
+
if (role === "root") child("tree", "child");
|
|
170
|
+
else if (role === "child") child("tree", "grandchild");
|
|
171
|
+
else if (role === "grandchild") child("sleep", "detached", { detached: true }).unref();
|
|
172
|
+
forever();
|
|
173
|
+
break;
|
|
174
|
+
case "sleep":
|
|
175
|
+
forever();
|
|
176
|
+
break;
|
|
177
|
+
case "mem": {
|
|
178
|
+
child("sleep", "child");
|
|
179
|
+
const hold = [];
|
|
180
|
+
setInterval(() => { for (let i = 0; i < 4; i++) hold.push(Buffer.alloc(16 << 20, 1)); }, 20);
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
case "procs":
|
|
184
|
+
for (let i = 0; i < 12; i++) child("sleep", "p" + i);
|
|
185
|
+
forever();
|
|
186
|
+
break;
|
|
187
|
+
case "cpu":
|
|
188
|
+
child("sleep", "child");
|
|
189
|
+
for (;;) {}
|
|
190
|
+
}
|
|
191
|
+
`;
|
|
192
|
+
const MB = 1024 * 1024;
|
|
193
|
+
const DEFAULT_LIMITS = { memoryBytes: 512 * MB, maxProcesses: 16, cpuTimeMs: 120_000 };
|
|
194
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
195
|
+
function transportFor(o) {
|
|
196
|
+
return new SpoolTransport({ root: o.root, service: o.service, manifestDigest: manifestDigest(join(o.root, "config", "manifest.json")) });
|
|
197
|
+
}
|
|
198
|
+
function runnerUp(o) {
|
|
199
|
+
try {
|
|
200
|
+
return transportFor(o).check();
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/** Start the pilot service if its runner is not answering, and wait for a fresh heartbeat. */
|
|
207
|
+
async function ensureRunning(o) {
|
|
208
|
+
const firstStart = !existsSync(join(o.root, "config", "first-start.json"));
|
|
209
|
+
let hb = runnerUp(o);
|
|
210
|
+
if (hb) {
|
|
211
|
+
// Running without the marker: started outside these checks, so the post-start check still applies.
|
|
212
|
+
if (firstStart) {
|
|
213
|
+
const failed = await checkAfterFirstStart(o);
|
|
214
|
+
if (failed)
|
|
215
|
+
throw new Error(failed);
|
|
216
|
+
}
|
|
217
|
+
return hb;
|
|
218
|
+
}
|
|
219
|
+
if (firstStart) {
|
|
220
|
+
const refused = checkBeforeFirstStart(o);
|
|
221
|
+
if (refused)
|
|
222
|
+
throw new Error(refused);
|
|
223
|
+
}
|
|
224
|
+
const r = o.host.run(tools(o.systemRoot).sc, ["start", o.service]);
|
|
225
|
+
o.out(` sc.exe start ${o.service}: exit ${r.status}`);
|
|
226
|
+
if (firstStart) {
|
|
227
|
+
const failed = await checkAfterFirstStart(o);
|
|
228
|
+
if (failed)
|
|
229
|
+
throw new Error(failed);
|
|
230
|
+
}
|
|
231
|
+
for (let i = 0; i < 150 && !hb; i++) {
|
|
232
|
+
await sleep(200);
|
|
233
|
+
hb = runnerUp(o);
|
|
234
|
+
}
|
|
235
|
+
if (!hb)
|
|
236
|
+
throw new Error(`the runner of ${o.service} did not report a fresh heartbeat within 30 s`);
|
|
237
|
+
return hb;
|
|
238
|
+
}
|
|
239
|
+
async function waitStopped(o) {
|
|
240
|
+
for (let i = 0; i < 150; i++) {
|
|
241
|
+
const r = o.host.run(tools(o.systemRoot).sc, ["query", o.service]);
|
|
242
|
+
if (r.status === 1060 || /STATE\s*:\s*1\s+STOPPED/.test(r.stdout))
|
|
243
|
+
return true;
|
|
244
|
+
await sleep(200);
|
|
245
|
+
}
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
function pidAlive(pid) {
|
|
249
|
+
try {
|
|
250
|
+
process.kill(pid, 0);
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
catch (err) {
|
|
254
|
+
return err.code === "EPERM";
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function defaultListed(o) {
|
|
258
|
+
const r = o.host.run(tools(o.systemRoot).tasklist, ["/FO", "CSV", "/NH"]);
|
|
259
|
+
if (r.status !== 0)
|
|
260
|
+
throw new Error(`tasklist exit ${r.status}`);
|
|
261
|
+
const pids = new Set();
|
|
262
|
+
for (const line of r.stdout.split(/\r?\n/)) {
|
|
263
|
+
const m = /^"[^"]*","(\d+)"/.exec(line);
|
|
264
|
+
if (m)
|
|
265
|
+
pids.add(Number(m[1]));
|
|
266
|
+
}
|
|
267
|
+
return pids;
|
|
268
|
+
}
|
|
269
|
+
function defaultTokenPids(o, token) {
|
|
270
|
+
const t = tools(o.systemRoot);
|
|
271
|
+
// The query's own powershell.exe carries the token; it is excluded by image name.
|
|
272
|
+
const r = o.host.run(t.powershell, ["-NoProfile", "-NonInteractive", "-Command", `Get-CimInstance Win32_Process -Filter "CommandLine like '%${token}%' and Name <> 'powershell.exe'" | ForEach-Object { $_.ProcessId }`]);
|
|
273
|
+
if (r.status !== 0)
|
|
274
|
+
throw new Error(`Win32_Process query exit ${r.status}`);
|
|
275
|
+
return r.stdout
|
|
276
|
+
.split(/\r?\n/)
|
|
277
|
+
.map((l) => Number(l.trim()))
|
|
278
|
+
.filter((n) => Number.isInteger(n) && n > 0);
|
|
279
|
+
}
|
|
280
|
+
function survivors(o, pids, token) {
|
|
281
|
+
const listed = (o.listedPids ?? (() => defaultListed(o)))();
|
|
282
|
+
return { byPid: pids.filter(pidAlive), byListing: pids.filter((p) => listed.has(p)), byToken: (o.tokenPids ?? ((t) => defaultTokenPids(o, t)))(token) };
|
|
283
|
+
}
|
|
284
|
+
function readPids(pidDir) {
|
|
285
|
+
const m = new Map();
|
|
286
|
+
if (!existsSync(pidDir))
|
|
287
|
+
return m;
|
|
288
|
+
for (const f of readdirSync(pidDir)) {
|
|
289
|
+
if (!f.endsWith(".pid"))
|
|
290
|
+
continue;
|
|
291
|
+
const text = readFileSync(join(pidDir, f), "utf8").trim();
|
|
292
|
+
if (text)
|
|
293
|
+
m.set(f.slice(0, -4), Number(text));
|
|
294
|
+
}
|
|
295
|
+
return m;
|
|
296
|
+
}
|
|
297
|
+
async function waitRoles(pidDir, roles, ms = 20_000) {
|
|
298
|
+
const end = Date.now() + ms;
|
|
299
|
+
for (;;) {
|
|
300
|
+
const pids = readPids(pidDir);
|
|
301
|
+
if (roles.every((r) => pids.has(r)))
|
|
302
|
+
return pids;
|
|
303
|
+
if (Date.now() > end)
|
|
304
|
+
throw new Error(`fixture roles not up after ${ms} ms: have ${[...pids.keys()].join(",") || "none"}, want ${roles.join(",")}`);
|
|
305
|
+
await sleep(50);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/** Each run of the checks works in its own directory under runs, which the service account may write. */
|
|
309
|
+
function sessionDir(o) {
|
|
310
|
+
const dir = join(o.root, "runs", `live-${new Date().toISOString().replace(/[^0-9]/g, "").slice(0, 14)}-${process.pid}`);
|
|
311
|
+
mkdirSync(dir, { recursive: true });
|
|
312
|
+
writeFileSync(join(dir, "tree.mjs"), LIVE_FIXTURE_SOURCE);
|
|
313
|
+
return dir;
|
|
314
|
+
}
|
|
315
|
+
function submit(o, dir, name, command, limits = DEFAULT_LIMITS) {
|
|
316
|
+
const cwd = join(dir, name);
|
|
317
|
+
const pidDir = join(cwd, "pids");
|
|
318
|
+
mkdirSync(pidDir, { recursive: true });
|
|
319
|
+
const token = `hqnd-us006-live-${name}-${process.pid}-${Date.now()}`;
|
|
320
|
+
const logPath = join(cwd, "job.log");
|
|
321
|
+
const systemRoot = o.systemRoot ?? "C:\\Windows";
|
|
322
|
+
const proc = transportFor(o).submit({ ...command(pidDir, token), cwd, env: { SystemRoot: systemRoot }, logPath, limits }, { tenantId: "tenant-live-check", runId: `live-${process.pid}`, jobId: name });
|
|
323
|
+
return { proc, pidDir, token, logPath };
|
|
324
|
+
}
|
|
325
|
+
const fixtureCommand = (o, dir, mode) => (pidDir, token) => ({ file: o.node ?? join(o.root, "runtime", "node.exe"), args: [join(dir, "tree.mjs"), mode, pidDir, token, "root"] });
|
|
326
|
+
async function outcomeOf(o, job) {
|
|
327
|
+
const ms = o.outcomeTimeoutMs ?? 90_000;
|
|
328
|
+
let timer;
|
|
329
|
+
const timeout = new Promise((r) => (timer = setTimeout(() => r("timeout"), ms)));
|
|
330
|
+
const got = await Promise.race([job.proc.done, timeout]);
|
|
331
|
+
clearTimeout(timer);
|
|
332
|
+
if (got === "timeout")
|
|
333
|
+
job.proc.cancel();
|
|
334
|
+
return got;
|
|
335
|
+
}
|
|
336
|
+
/** Survivors after a terminal outcome. Windows may take a moment to drop a terminated process from its table; the wait is bounded and reported. */
|
|
337
|
+
async function settle(o, pids, token) {
|
|
338
|
+
const t0 = Date.now();
|
|
339
|
+
let left = survivors(o, pids, token);
|
|
340
|
+
while (left.byPid.length + left.byListing.length + left.byToken.length > 0 && Date.now() - t0 < 5_000) {
|
|
341
|
+
await sleep(250);
|
|
342
|
+
left = survivors(o, pids, token);
|
|
343
|
+
}
|
|
344
|
+
return { left, ms: Date.now() - t0 };
|
|
345
|
+
}
|
|
346
|
+
function verdict(name, outcome, want, wantText, pids, s) {
|
|
347
|
+
const problems = [];
|
|
348
|
+
if (outcome === "timeout")
|
|
349
|
+
problems.push("no terminal outcome in time");
|
|
350
|
+
else if (!want(outcome))
|
|
351
|
+
problems.push(`outcome ${JSON.stringify(outcome)}, expected ${wantText}`);
|
|
352
|
+
if (pids.length === 0)
|
|
353
|
+
problems.push("no fixture process was observed");
|
|
354
|
+
if (s.left.byPid.length > 0)
|
|
355
|
+
problems.push(`alive by PID: ${s.left.byPid.join(",")}`);
|
|
356
|
+
if (s.left.byListing.length > 0)
|
|
357
|
+
problems.push(`in tasklist: ${s.left.byListing.join(",")}`);
|
|
358
|
+
if (s.left.byToken.length > 0)
|
|
359
|
+
problems.push(`in the command-line listing: ${s.left.byToken.join(",")}`);
|
|
360
|
+
const seen = `outcome ${outcome === "timeout" ? "timeout" : JSON.stringify(outcome)}; fixture pids ${pids.join(",") || "none"}; survivors by PID ${s.left.byPid.length}, tasklist ${s.left.byListing.length}, command line ${s.left.byToken.length} (checked for ${s.ms} ms)`;
|
|
361
|
+
return { name, pass: problems.length === 0, detail: problems.length === 0 ? seen : `${problems.join("; ")} | ${seen}` };
|
|
362
|
+
}
|
|
363
|
+
const TREE_ROLES = ["root", "child", "grandchild", "detached"];
|
|
364
|
+
/** Cancel a four-process tree, one of them detached, through the service. */
|
|
365
|
+
export async function cancelCase(o, dir) {
|
|
366
|
+
await ensureRunning(o);
|
|
367
|
+
const job = submit(o, dir, "cancel", fixtureCommand(o, dir, "tree"));
|
|
368
|
+
const pids = [...(await waitRoles(job.pidDir, TREE_ROLES)).values()];
|
|
369
|
+
const before = pids.filter(pidAlive);
|
|
370
|
+
if (before.length !== pids.length)
|
|
371
|
+
return { name: "cancel", pass: false, detail: `the tree was not fully alive before cancel: ${before.length} of ${pids.length}` };
|
|
372
|
+
job.proc.cancel();
|
|
373
|
+
const outcome = await outcomeOf(o, job);
|
|
374
|
+
return verdict("cancel", outcome, (x) => x.reason === "cancelled", "cancelled", pids, await settle(o, pids, job.token));
|
|
375
|
+
}
|
|
376
|
+
async function limitCase(o, dir, name, mode, limit, limits) {
|
|
377
|
+
await ensureRunning(o);
|
|
378
|
+
const job = submit(o, dir, name, fixtureCommand(o, dir, mode), limits);
|
|
379
|
+
const outcome = await outcomeOf(o, job);
|
|
380
|
+
const pids = [...readPids(job.pidDir).values()];
|
|
381
|
+
return verdict(name, outcome, (x) => x.reason === "limit" && x.limit === limit, `limit ${limit}`, pids, await settle(o, pids, job.token));
|
|
382
|
+
}
|
|
383
|
+
/** Stop the service while a tree runs. */
|
|
384
|
+
async function stopCase(o, dir) {
|
|
385
|
+
await ensureRunning(o);
|
|
386
|
+
const job = submit(o, dir, "service-stop", fixtureCommand(o, dir, "tree"));
|
|
387
|
+
const pids = [...(await waitRoles(job.pidDir, TREE_ROLES)).values()];
|
|
388
|
+
const helper = job.proc.supervisorPid;
|
|
389
|
+
const r = o.host.run(tools(o.systemRoot).sc, ["stop", o.service]);
|
|
390
|
+
o.out(` sc.exe stop ${o.service}: exit ${r.status}`);
|
|
391
|
+
const outcome = await outcomeOf(o, job);
|
|
392
|
+
if (!(await waitStopped(o)))
|
|
393
|
+
return { name: "service-stop", pass: false, detail: "the service did not reach STOPPED within 30 s" };
|
|
394
|
+
const all = helper && helper > 0 ? [...pids, helper] : pids;
|
|
395
|
+
return verdict("service-stop", outcome, (x) => x.reason === "cancelled" || x.reason === "supervisor_lost", "cancelled or supervisor_lost", all, await settle(o, all, job.token));
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* True when the text is exactly one "tasklist /V /FO CSV /NH" row for a
|
|
399
|
+
* node.exe with this pid whose User Name column is the service account. Only
|
|
400
|
+
* that column is compared: the window title is set by the process itself.
|
|
401
|
+
*/
|
|
402
|
+
export function isRunnerRow(text, pid, service) {
|
|
403
|
+
const rows = text.split(/\r?\n/).filter((l) => l.trim() !== "");
|
|
404
|
+
if (rows.length !== 1)
|
|
405
|
+
return false;
|
|
406
|
+
const cols = [...rows[0].matchAll(/"([^"]*)"(?:,|$)/g)].map((m) => m[1]);
|
|
407
|
+
if (cols.length < 7)
|
|
408
|
+
return false;
|
|
409
|
+
return cols[0].toLowerCase() === "node.exe" && cols[1] === String(pid) && cols[6].toLowerCase() === `nt service\\${service}`.toLowerCase();
|
|
410
|
+
}
|
|
411
|
+
/** End the runner process itself while a tree runs. Only a node.exe owned by the service account is ended. */
|
|
412
|
+
async function killCase(o, dir) {
|
|
413
|
+
const t = tools(o.systemRoot);
|
|
414
|
+
const hb = await ensureRunning(o);
|
|
415
|
+
const job = submit(o, dir, "runner-kill", fixtureCommand(o, dir, "tree"));
|
|
416
|
+
const pids = [...(await waitRoles(job.pidDir, TREE_ROLES)).values()];
|
|
417
|
+
const helper = job.proc.supervisorPid;
|
|
418
|
+
const row = o.host.run(t.tasklist, ["/V", "/FO", "CSV", "/NH", "/FI", `PID eq ${hb.pid}`]).stdout.trim();
|
|
419
|
+
if (!isRunnerRow(row, hb.pid, o.service)) {
|
|
420
|
+
job.proc.cancel();
|
|
421
|
+
await outcomeOf(o, job);
|
|
422
|
+
return { name: "runner-kill", pass: false, detail: `pid ${hb.pid} from the heartbeat is not a node.exe of NT SERVICE\\${o.service}; nothing was ended (tasklist: ${row || "no row"})` };
|
|
423
|
+
}
|
|
424
|
+
const k = o.host.run(t.taskkill, ["/F", "/PID", String(hb.pid)]);
|
|
425
|
+
o.out(` taskkill.exe /F /PID ${hb.pid} (runner node.exe): exit ${k.status}`);
|
|
426
|
+
const outcome = await outcomeOf(o, job);
|
|
427
|
+
const all = helper && helper > 0 ? [...pids, helper, hb.pid] : [...pids, hb.pid];
|
|
428
|
+
const s = await settle(o, all, job.token);
|
|
429
|
+
const stop = o.host.run(t.sc, ["stop", o.service]);
|
|
430
|
+
o.out(` sc.exe stop ${o.service} (after the kill; 1062 not started is fine): exit ${stop.status}`);
|
|
431
|
+
if (!(await waitStopped(o)))
|
|
432
|
+
return { name: "runner-kill", pass: false, detail: "the service did not reach STOPPED within 30 s after its runner was ended" };
|
|
433
|
+
return verdict("runner-kill", outcome, (x) => x.reason === "supervisor_lost", "supervisor_lost", all, s);
|
|
434
|
+
}
|
|
435
|
+
// ---------------------------------------------------------------------------
|
|
436
|
+
// N2 acl-probe: what the job identity can write and read
|
|
437
|
+
/**
|
|
438
|
+
* Runs as the job. argv: root decoyQueueEntry decoyStateFile tag. It tries
|
|
439
|
+
* each access once and prints one JSON line. A write that is allowed is
|
|
440
|
+
* undone at once; the two open-for-write probes change no bytes.
|
|
441
|
+
*/
|
|
442
|
+
export const ACL_PROBE_SOURCE = String.raw `
|
|
443
|
+
import { appendFileSync, closeSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
444
|
+
import { join } from "node:path";
|
|
445
|
+
const [root, decoyQueue, decoyState, tag] = process.argv.slice(2);
|
|
446
|
+
const rows = [];
|
|
447
|
+
const attempt = (op, fn) => {
|
|
448
|
+
try {
|
|
449
|
+
fn();
|
|
450
|
+
rows.push({ op, result: "allowed", code: "" });
|
|
451
|
+
} catch (err) {
|
|
452
|
+
const code = String((err && err.code) || err);
|
|
453
|
+
rows.push({ op, result: code === "EPERM" || code === "EACCES" ? "denied" : "error", code });
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
const create = (dir) => () => {
|
|
457
|
+
const f = join(root, dir, "acl-probe-" + tag + ".tmp");
|
|
458
|
+
writeFileSync(f, "probe", { flag: "wx" });
|
|
459
|
+
rmSync(f, { force: true });
|
|
460
|
+
};
|
|
461
|
+
attempt("bin-create", create("bin"));
|
|
462
|
+
attempt("queue-create", create("queue"));
|
|
463
|
+
attempt("queue-entry-write", () => closeSync(openSync(decoyQueue, "r+")));
|
|
464
|
+
attempt("queue-entry-read", () => void readFileSync(decoyQueue));
|
|
465
|
+
attempt("manifest-write", () => closeSync(openSync(join(root, "config", "manifest.json"), "r+")));
|
|
466
|
+
attempt("state-write", () => appendFileSync(decoyState, "written by the job\n"));
|
|
467
|
+
console.log(JSON.stringify({ probe: rows }));
|
|
468
|
+
`;
|
|
469
|
+
/** The probe line from a job log, or nothing. */
|
|
470
|
+
export function parseAclProbe(log) {
|
|
471
|
+
for (const line of log.split(/\r?\n/)) {
|
|
472
|
+
if (!line.startsWith('{"probe":'))
|
|
473
|
+
continue;
|
|
474
|
+
try {
|
|
475
|
+
const rows = JSON.parse(line).probe;
|
|
476
|
+
if (Array.isArray(rows))
|
|
477
|
+
return rows;
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
// Not the probe line.
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return [];
|
|
484
|
+
}
|
|
485
|
+
/** Writes the installer's ACL must refuse to the job. Each can fail closed, so each is pass or fail. */
|
|
486
|
+
const ACL_MUST_DENY = {
|
|
487
|
+
"bin-create": "create a file in bin\\",
|
|
488
|
+
"queue-create": "create a file in queue\\",
|
|
489
|
+
"queue-entry-write": "open another job's queue entry for writing",
|
|
490
|
+
"manifest-write": "open config\\manifest.json for writing",
|
|
491
|
+
};
|
|
492
|
+
/**
|
|
493
|
+
* Accesses the job has because it shares the runner's identity (review 040
|
|
494
|
+
* CRITICAL 1, accepted by the owner: Windows results are untrusted). They
|
|
495
|
+
* cannot fail closed in this design, so they are reported as observed and
|
|
496
|
+
* never counted as a pass.
|
|
497
|
+
*/
|
|
498
|
+
const ACL_INFORMATIONAL = {
|
|
499
|
+
"queue-entry-read": "read another job's queue entry",
|
|
500
|
+
"state-write": "write a file in state\\, where results are recorded",
|
|
501
|
+
};
|
|
502
|
+
export function evaluateAclProbe(rows) {
|
|
503
|
+
const lines = [];
|
|
504
|
+
let pass = true;
|
|
505
|
+
const seen = (op) => rows.find((r) => r.op === op);
|
|
506
|
+
for (const [op, what] of Object.entries(ACL_MUST_DENY)) {
|
|
507
|
+
const r = seen(op);
|
|
508
|
+
if (r?.result === "denied")
|
|
509
|
+
lines.push(`N2 acl-probe ${op}: denied (${r.code}) when the job tried to ${what}; expected denied: OK`);
|
|
510
|
+
else {
|
|
511
|
+
pass = false;
|
|
512
|
+
const saw = !r ? "NOT OBSERVED" : r.result === "allowed" ? "ALLOWED" : `ERROR ${r.code}`;
|
|
513
|
+
lines.push(`N2 acl-probe ${op}: ${saw} when the job tried to ${what}; expected denied: FAIL`);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
for (const [op, what] of Object.entries(ACL_INFORMATIONAL)) {
|
|
517
|
+
const r = seen(op);
|
|
518
|
+
const saw = !r ? "not observed" : r.result === "allowed" ? "allowed" : r.result === "denied" ? `denied (${r.code})` : `error ${r.code}`;
|
|
519
|
+
lines.push(`N2 acl-probe INFO ${op}: ${saw} when the job tried to ${what}; expected to succeed because the job has the shared runner identity (review C1, accepted limitation; not a pass)`);
|
|
520
|
+
}
|
|
521
|
+
return { pass, lines };
|
|
522
|
+
}
|
|
523
|
+
/** Run the probe as a job through the service, against decoys this check creates and removes. */
|
|
524
|
+
async function aclCase(o, dir) {
|
|
525
|
+
await ensureRunning(o);
|
|
526
|
+
const tag = String(process.pid);
|
|
527
|
+
const decoyQueue = join(o.root, "queue", `acl-probe-${tag}.decoy`);
|
|
528
|
+
const decoyState = join(o.root, "state", `acl-probe-${tag}.events.decoy`);
|
|
529
|
+
const leftovers = [decoyQueue, decoyState, join(o.root, "bin", `acl-probe-${tag}.tmp`), join(o.root, "queue", `acl-probe-${tag}.tmp`)];
|
|
530
|
+
const manifestBefore = readFileSync(join(o.root, "config", "manifest.json"));
|
|
531
|
+
try {
|
|
532
|
+
// Neither decoy ends in .json or .events, so the runner ignores both.
|
|
533
|
+
writeFileSync(decoyQueue, "decoy standing in for another job's queue entry\n");
|
|
534
|
+
writeFileSync(decoyState, "");
|
|
535
|
+
writeFileSync(join(dir, "acl-probe.mjs"), ACL_PROBE_SOURCE);
|
|
536
|
+
const job = submit(o, dir, "acl-probe", () => ({ file: o.node ?? join(o.root, "runtime", "node.exe"), args: [join(dir, "acl-probe.mjs"), o.root, decoyQueue, decoyState, tag] }));
|
|
537
|
+
const outcome = await outcomeOf(o, job);
|
|
538
|
+
const rows = parseAclProbe(existsSync(job.logPath) ? readFileSync(job.logPath, "utf8") : "");
|
|
539
|
+
const v = evaluateAclProbe(rows);
|
|
540
|
+
for (const l of v.lines)
|
|
541
|
+
o.out(l);
|
|
542
|
+
const problems = [];
|
|
543
|
+
if (outcome === "timeout" || outcome.reason !== "exited" || outcome.exitCode !== 0)
|
|
544
|
+
problems.push(`the probe job did not exit 0: ${JSON.stringify(outcome)}`);
|
|
545
|
+
if (!v.pass)
|
|
546
|
+
problems.push("a protected write was allowed or not observed");
|
|
547
|
+
if (!readFileSync(join(o.root, "config", "manifest.json")).equals(manifestBefore))
|
|
548
|
+
problems.push("config\\manifest.json changed");
|
|
549
|
+
return { name: "acl-probe", pass: problems.length === 0, detail: problems.length === 0 ? "the job was denied every write to bin, queue and the manifest; see the INFO lines for what the shared identity still allows" : problems.join("; ") };
|
|
550
|
+
}
|
|
551
|
+
finally {
|
|
552
|
+
for (const f of leftovers)
|
|
553
|
+
rmSync(f, { force: true });
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
export async function n1(o) {
|
|
557
|
+
await ensureRunning(o);
|
|
558
|
+
const dir = sessionDir(o);
|
|
559
|
+
const job = submit(o, dir, "whoami", () => ({ file: tools(o.systemRoot).whoami, args: ["/all"] }));
|
|
560
|
+
const outcome = await outcomeOf(o, job);
|
|
561
|
+
const text = existsSync(job.logPath) ? readFileSync(job.logPath, "utf8") : "";
|
|
562
|
+
o.out(`--- whoami /all, as written by the job to ${job.logPath} ---`);
|
|
563
|
+
for (const line of text.split(/\r?\n/))
|
|
564
|
+
o.out(line);
|
|
565
|
+
o.out("--- end ---");
|
|
566
|
+
const v = evaluateWhoami(text, o.service);
|
|
567
|
+
if (outcome === "timeout" || outcome.reason !== "exited" || outcome.exitCode !== 0)
|
|
568
|
+
v.reasons.unshift(`the whoami job did not exit 0: ${JSON.stringify(outcome)}`);
|
|
569
|
+
o.out(`expected user: NT SERVICE\\${o.service} ${serviceSidFor(o.service)}`);
|
|
570
|
+
o.out(`privileges in the job token: ${v.privileges.join(", ") || "none listed"}`);
|
|
571
|
+
o.out(`privileges Windows always leaves in a service token (allowed): ${ALWAYS_GRANTED_PRIVILEGES.join(", ")}`);
|
|
572
|
+
o.out(v.extraPrivileges.length === 0 ? "N1 PRIVILEGES OK: nothing beyond the allowed list" : `N1 PRIVILEGES FAIL: not in the allowed list: ${v.extraPrivileges.join(", ")}`);
|
|
573
|
+
o.out(v.reasons.length === 0 ? "N1 PASS" : `N1 FAIL: ${v.reasons.join("; ")}`);
|
|
574
|
+
return v.reasons.length === 0;
|
|
575
|
+
}
|
|
576
|
+
export async function n2(o) {
|
|
577
|
+
const dir = sessionDir(o);
|
|
578
|
+
const cases = [
|
|
579
|
+
() => cancelCase(o, dir),
|
|
580
|
+
() => aclCase(o, dir),
|
|
581
|
+
() => limitCase(o, dir, "limit-memory", "mem", "memory", { memoryBytes: 256 * MB, maxProcesses: 16, cpuTimeMs: 120_000 }),
|
|
582
|
+
() => limitCase(o, dir, "limit-processes", "procs", "processes", { memoryBytes: 1024 * MB, maxProcesses: 6, cpuTimeMs: 120_000 }),
|
|
583
|
+
() => limitCase(o, dir, "limit-cpu", "cpu", "cpu", { memoryBytes: 512 * MB, maxProcesses: 16, cpuTimeMs: 1_500 }),
|
|
584
|
+
() => stopCase(o, dir),
|
|
585
|
+
() => killCase(o, dir),
|
|
586
|
+
];
|
|
587
|
+
const failed = [];
|
|
588
|
+
for (const run of cases) {
|
|
589
|
+
let r;
|
|
590
|
+
try {
|
|
591
|
+
r = await run();
|
|
592
|
+
}
|
|
593
|
+
catch (err) {
|
|
594
|
+
r = { name: "case", pass: false, detail: err instanceof Error ? err.message : String(err) };
|
|
595
|
+
}
|
|
596
|
+
o.out(`N2 ${r.name} ${r.pass ? "PASS" : "FAIL"}: ${r.detail}`);
|
|
597
|
+
if (!r.pass)
|
|
598
|
+
failed.push(r.name);
|
|
599
|
+
}
|
|
600
|
+
const stop = o.host.run(tools(o.systemRoot).sc, ["stop", o.service]);
|
|
601
|
+
o.out(` sc.exe stop ${o.service} (leave the service stopped): exit ${stop.status}`);
|
|
602
|
+
if (!(await waitStopped(o))) {
|
|
603
|
+
failed.push("final-stop");
|
|
604
|
+
o.out("N2 final-stop FAIL: the service did not reach STOPPED within 30 s");
|
|
605
|
+
}
|
|
606
|
+
const account = o.host.run(tools(o.systemRoot).tasklist, ["/V", "/FO", "CSV", "/NH", "/FI", `USERNAME eq NT SERVICE\\${o.service}`]);
|
|
607
|
+
const rows = account.stdout.split(/\r?\n/).filter((l) => l.startsWith('"'));
|
|
608
|
+
if (account.status !== 0 || rows.length > 0) {
|
|
609
|
+
failed.push("account-processes");
|
|
610
|
+
o.out(`N2 account-processes FAIL: ${account.status !== 0 ? `tasklist exit ${account.status}` : `${rows.length} process(es) still run as NT SERVICE\\${o.service} with the service stopped: ${rows.join(" | ")}`}`);
|
|
611
|
+
}
|
|
612
|
+
else
|
|
613
|
+
o.out(`N2 account-processes PASS: no process runs as NT SERVICE\\${o.service} with the service stopped`);
|
|
614
|
+
o.out(failed.length === 0 ? "N2 PASS" : `N2 FAIL: ${failed.join(", ")}`);
|
|
615
|
+
return failed.length === 0;
|
|
616
|
+
}
|
|
617
|
+
/** After rollback: every place the pilot could have left something. Read-only. */
|
|
618
|
+
/** True only for N3 PASS. */
|
|
619
|
+
export function n3(o) {
|
|
620
|
+
return n3Status(o) === "pass";
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* After rollback: every place the pilot could have left something. Read-only. "pending" (exit 3) only when the
|
|
624
|
+
* service profile held by Windows (its folder, ProfileList key and loaded hives) is all that is left and at least
|
|
625
|
+
* one hive is loaded: the two-phase uninstall's state before restart. It is not a pass.
|
|
626
|
+
*/
|
|
627
|
+
export function n3Status(o) {
|
|
628
|
+
const t = tools(o.systemRoot);
|
|
629
|
+
const systemRoot = o.systemRoot ?? "C:\\Windows";
|
|
630
|
+
const sid = serviceSidFor(o.service);
|
|
631
|
+
const found = [];
|
|
632
|
+
const check = (label, clean, detail = "", kind = "other") => {
|
|
633
|
+
o.out(` ${clean ? "clean" : "FOUND"} ${label}${detail ? `: ${detail}` : ""}`);
|
|
634
|
+
if (!clean)
|
|
635
|
+
found.push({ label, kind });
|
|
636
|
+
};
|
|
637
|
+
const profileKey = `HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}`;
|
|
638
|
+
const sep = systemRoot.includes("/") ? "/" : "\\";
|
|
639
|
+
const profileFolder = [systemRoot, "ServiceProfiles", o.service].join(sep);
|
|
640
|
+
const sc = o.host.run(t.sc, ["query", o.service]);
|
|
641
|
+
check(`service ${o.service} (sc.exe query, expect exit 1060)`, sc.status === 1060, `exit ${sc.status}`);
|
|
642
|
+
for (const key of [
|
|
643
|
+
`HKLM\\SYSTEM\\CurrentControlSet\\Services\\${o.service}`,
|
|
644
|
+
`HKLM\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\${o.service}`,
|
|
645
|
+
`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}`,
|
|
646
|
+
]) {
|
|
647
|
+
const r = o.host.run(t.reg, ["query", key]);
|
|
648
|
+
check(`registry key ${key} (reg.exe query, expect exit 1)`, r.status === 1, `exit ${r.status}`, key === profileKey && r.status === 0 ? "profile" : "other");
|
|
649
|
+
}
|
|
650
|
+
for (const hive of [`HKU\\${sid}`, `HKU\\${sid}_Classes`]) {
|
|
651
|
+
const r = o.host.run(t.reg, ["query", hive]);
|
|
652
|
+
check(`registry hive ${hive} loaded (reg.exe query, expect exit 1)`, r.status === 1, `exit ${r.status}`, r.status === 0 ? "hive" : "other");
|
|
653
|
+
}
|
|
654
|
+
for (const path of [o.root, profileFolder, `${systemRoot.slice(0, 2)}\\Users\\${o.service}`])
|
|
655
|
+
check(`folder ${path}`, !existsSync(path), "", path === profileFolder ? "profile" : "other");
|
|
656
|
+
const tasks = o.host.run(t.schtasks, ["/Query", "/FO", "CSV", "/NH"]);
|
|
657
|
+
const hits = tasks.stdout.split(/\r?\n/).filter((l) => /hqnd|hqnativedelivery/i.test(l));
|
|
658
|
+
check("scheduled task naming HQND or HQNativeDelivery (schtasks.exe /Query)", tasks.status === 0 && hits.length === 0, tasks.status === 0 ? hits.join(" | ") : `exit ${tasks.status}`);
|
|
659
|
+
const procs = o.host.run(t.tasklist, ["/V", "/FO", "CSV", "/NH", "/FI", `USERNAME eq NT SERVICE\\${o.service}`]);
|
|
660
|
+
const rows = procs.stdout.split(/\r?\n/).filter((l) => l.startsWith('"'));
|
|
661
|
+
check(`process running as NT SERVICE\\${o.service}`, procs.status === 0 && rows.length === 0, procs.status === 0 ? rows.join(" | ") : `exit ${procs.status}`);
|
|
662
|
+
const helper = o.host.run(t.tasklist, ["/FO", "CSV", "/NH", "/FI", "IMAGENAME eq hqjob.exe"]);
|
|
663
|
+
const helperRows = helper.stdout.split(/\r?\n/).filter((l) => l.startsWith('"'));
|
|
664
|
+
check("process hqjob.exe", helper.status === 0 && helperRows.length === 0, helper.status === 0 ? helperRows.join(" | ") : `exit ${helper.status}`);
|
|
665
|
+
const labels = found.map((f) => f.label).join("; ");
|
|
666
|
+
if (found.length === 0) {
|
|
667
|
+
o.out("N3 PASS");
|
|
668
|
+
return "pass";
|
|
669
|
+
}
|
|
670
|
+
// Only the profile Windows holds until restart (folder, key, loaded hives), with at least one hive loaded.
|
|
671
|
+
if (found.every((f) => f.kind !== "other") && found.some((f) => f.kind === "hive")) {
|
|
672
|
+
o.out(`N3 PENDING REBOOT: ${labels}`);
|
|
673
|
+
return "pending";
|
|
674
|
+
}
|
|
675
|
+
o.out(`N3 FAIL: left behind: ${labels}`);
|
|
676
|
+
return "fail";
|
|
677
|
+
}
|
|
678
|
+
export async function liveMain(argv, host = realLiveHost, platform = process.platform, out = (s) => process.stdout.write(s + "\n"),
|
|
679
|
+
/** The only names the checks may act on. Tests pass a scratch root; the command line cannot. */
|
|
680
|
+
allowed = PILOT040) {
|
|
681
|
+
const [cmd] = argv;
|
|
682
|
+
const arg = (name) => (argv.indexOf(name) >= 0 ? argv[argv.indexOf(name) + 1] : undefined);
|
|
683
|
+
// The checks start and stop a service and end a process, so they act on the pilot only.
|
|
684
|
+
const asked = { service: arg("--service"), root: arg("--root") };
|
|
685
|
+
if (asked.service !== undefined || asked.root !== undefined) {
|
|
686
|
+
const bad = validateNames({ service: asked.service ?? PILOT040.service, root: asked.root ?? PILOT040.root });
|
|
687
|
+
if (bad)
|
|
688
|
+
return (out(`refused: ${bad}`), 2);
|
|
689
|
+
if ((asked.service ?? allowed.service) !== allowed.service || (asked.root ?? allowed.root) !== allowed.root)
|
|
690
|
+
return (out(`refused: the live checks act only on service ${allowed.service} at ${allowed.root}`), 2);
|
|
691
|
+
}
|
|
692
|
+
const o = { root: allowed.root, service: allowed.service, host, out, ...(allowed.serviceProfilesDir ? { serviceProfilesDir: allowed.serviceProfilesDir } : {}) };
|
|
693
|
+
if (cmd !== "n1" && cmd !== "n2" && cmd !== "n3")
|
|
694
|
+
return (out("usage: n1|n2|n3 [--service <name>] [--root <dir>]"), 2);
|
|
695
|
+
if (platform !== "win32")
|
|
696
|
+
return (out("refused: the live checks run only on Windows"), 2);
|
|
697
|
+
if (cmd === "n3") {
|
|
698
|
+
const status = n3Status(o);
|
|
699
|
+
return status === "pass" ? 0 : status === "pending" ? 3 : 1;
|
|
700
|
+
}
|
|
701
|
+
if (!existsSync(spoolPaths(o.root).state) || !existsSync(join(o.root, "config", "manifest.json")))
|
|
702
|
+
return (out(`${cmd.toUpperCase()} FAIL: ${o.root} is not an installed pilot root`), 1);
|
|
703
|
+
try {
|
|
704
|
+
return (await (cmd === "n1" ? n1(o) : n2(o))) ? 0 : 1;
|
|
705
|
+
}
|
|
706
|
+
catch (err) {
|
|
707
|
+
out(`${cmd.toUpperCase()} FAIL: ${err instanceof Error ? err.message : String(err)}`);
|
|
708
|
+
return 1;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
//# sourceMappingURL=windows-service-live.js.map
|