@indigoai-us/hq-cli 5.345.212 → 5.345.215-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +442 -50
  4. package/dist/command-catalog.generated.js +541 -50
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/agents.d.ts +51 -1
  9. package/dist/commands/agents.js +154 -2
  10. package/dist/commands/bot-jobs.d.ts +2 -15
  11. package/dist/commands/bot-jobs.js +2 -94
  12. package/dist/commands/bot-runtime.d.ts +46 -5
  13. package/dist/commands/bot-runtime.js +228 -18
  14. package/dist/commands/bot.d.ts +16 -9
  15. package/dist/commands/bot.js +169 -51
  16. package/dist/commands/cloud.d.ts +66 -13
  17. package/dist/commands/cloud.js +120 -39
  18. package/dist/commands/company-restore.d.ts +23 -0
  19. package/dist/commands/company-restore.js +128 -0
  20. package/dist/commands/company.js +2 -0
  21. package/dist/commands/core-handoff.js +1 -0
  22. package/dist/commands/core-hq-session-native.js +2 -2
  23. package/dist/commands/core-pin-native.js +1 -1
  24. package/dist/commands/core-policy.js +1 -1
  25. package/dist/commands/core-resolve-company-native.js +1 -1
  26. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  27. package/dist/commands/core-sentry-report-fast.js +3 -1
  28. package/dist/commands/daemon.js +11 -1
  29. package/dist/commands/integrations-connect.d.ts +17 -4
  30. package/dist/commands/integrations-connect.js +224 -26
  31. package/dist/commands/lanes-link.js +10 -5
  32. package/dist/commands/lanes.js +26 -9
  33. package/dist/commands/rescue.js +13 -0
  34. package/dist/commands/secrets.d.ts +11 -0
  35. package/dist/commands/secrets.js +41 -7
  36. package/dist/commands/sources.js +6 -0
  37. package/dist/commands/storage-offload.d.ts +12 -0
  38. package/dist/commands/storage-offload.js +41 -3
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/index.js +2 -0
  42. package/dist/lazy-commands.js +2 -0
  43. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  44. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  45. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  46. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  47. package/dist/lib/agent-kit/inbox-state.js +261 -4
  48. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  49. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  50. package/dist/lib/agent-kit/run/inbox.js +4 -2
  51. package/dist/lib/agent-kit/skills.js +4 -1
  52. package/dist/lib/agent-kit/wake.d.ts +9 -1
  53. package/dist/lib/agent-kit/wake.js +10 -3
  54. package/dist/lib/bot/config.d.ts +1 -0
  55. package/dist/lib/bot/config.js +10 -0
  56. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  57. package/dist/lib/bot/eventbridge-cron.js +104 -0
  58. package/dist/lib/bot/fleet-cron.js +193 -14
  59. package/dist/lib/bot/fleet-download.d.ts +2 -0
  60. package/dist/lib/bot/fleet-download.js +23 -0
  61. package/dist/lib/bot/fleet-local.d.ts +34 -1
  62. package/dist/lib/bot/fleet-local.js +254 -37
  63. package/dist/lib/bot/fleet-python.d.ts +3 -0
  64. package/dist/lib/bot/fleet-python.js +34 -4
  65. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  66. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  67. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  68. package/dist/lib/bot/legacy-provider-login.js +19 -2
  69. package/dist/lib/bot/prompt.js +1 -1
  70. package/dist/lib/bot/readiness.d.ts +8 -0
  71. package/dist/lib/bot/readiness.js +17 -3
  72. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  73. package/dist/lib/bot/runtime-auth.js +94 -3
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  76. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  77. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  78. package/dist/lib/capacity/collectors/grok.js +56 -5
  79. package/dist/lib/core-utils/session-id.d.ts +1 -1
  80. package/dist/lib/core-utils/session-id.js +4 -0
  81. package/dist/lib/daemon/catalog.js +11 -1
  82. package/dist/lib/daemon/run.js +9 -1
  83. package/dist/lib/daemon/updater.d.ts +34 -2
  84. package/dist/lib/daemon/updater.js +51 -2
  85. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  86. package/dist/lib/db/sqlite-binding.js +1 -1
  87. package/dist/lib/delivery/artifacts.d.ts +99 -0
  88. package/dist/lib/delivery/artifacts.js +548 -0
  89. package/dist/lib/delivery/backup.d.ts +78 -0
  90. package/dist/lib/delivery/backup.js +343 -0
  91. package/dist/lib/delivery/cache.d.ts +29 -0
  92. package/dist/lib/delivery/cache.js +33 -0
  93. package/dist/lib/delivery/contracts.d.ts +142 -0
  94. package/dist/lib/delivery/contracts.js +289 -0
  95. package/dist/lib/delivery/credentials.d.ts +54 -0
  96. package/dist/lib/delivery/credentials.js +119 -0
  97. package/dist/lib/delivery/enrollment.d.ts +142 -0
  98. package/dist/lib/delivery/enrollment.js +382 -0
  99. package/dist/lib/delivery/identity.d.ts +25 -0
  100. package/dist/lib/delivery/identity.js +82 -0
  101. package/dist/lib/delivery/inbox.d.ts +116 -0
  102. package/dist/lib/delivery/inbox.js +260 -0
  103. package/dist/lib/delivery/migrations.d.ts +139 -0
  104. package/dist/lib/delivery/migrations.js +623 -0
  105. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  106. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  107. package/dist/lib/delivery/mqtt.d.ts +61 -0
  108. package/dist/lib/delivery/mqtt.js +112 -0
  109. package/dist/lib/delivery/outbox.d.ts +95 -0
  110. package/dist/lib/delivery/outbox.js +187 -0
  111. package/dist/lib/delivery/provenance.d.ts +129 -0
  112. package/dist/lib/delivery/provenance.js +93 -0
  113. package/dist/lib/delivery/reconciler.d.ts +151 -0
  114. package/dist/lib/delivery/reconciler.js +492 -0
  115. package/dist/lib/delivery/restore.d.ts +35 -0
  116. package/dist/lib/delivery/restore.js +134 -0
  117. package/dist/lib/delivery/store.d.ts +161 -0
  118. package/dist/lib/delivery/store.js +940 -0
  119. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  120. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  121. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  122. package/dist/lib/delivery/workers/macos.js +901 -0
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  124. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  125. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  126. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  127. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  128. package/dist/lib/delivery/workers/windows.js +608 -0
  129. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  130. package/dist/lib/doctor/checks/release-links.js +260 -24
  131. package/dist/lib/doctor/fix/apply.js +24 -8
  132. package/dist/lib/doctor/fix/remediation.js +15 -5
  133. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  134. package/dist/lib/install/provider-wrappers.js +68 -3
  135. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  136. package/dist/lib/lanes/autopilot-registry.js +59 -7
  137. package/dist/lib/lanes/links.d.ts +14 -0
  138. package/dist/lib/lanes/links.js +320 -25
  139. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  140. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  141. package/dist/main.js +3 -1
  142. package/dist/sentry-init.d.ts +2 -0
  143. package/dist/sentry-init.js +13 -2
  144. package/dist/sentry.d.ts +2 -0
  145. package/dist/sentry.js +5 -1
  146. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  147. package/dist/utils/cli-network-lifecycle.js +52 -0
  148. package/dist/utils/cognito-callback-port.d.ts +14 -0
  149. package/dist/utils/cognito-callback-port.js +24 -0
  150. package/dist/utils/cognito-session.js +3 -3
  151. package/dist/utils/deleted-company-notice.d.ts +59 -0
  152. package/dist/utils/deleted-company-notice.js +156 -0
  153. package/dist/utils/login-browser.d.ts +1 -1
  154. package/dist/utils/login-browser.js +7 -5
  155. package/dist/utils/resident-package-preload.js +30 -15
  156. package/dist/utils/safe-link.d.ts +63 -0
  157. package/dist/utils/safe-link.js +246 -0
  158. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  159. package/dist/utils/sentry-keepalive-transport.js +70 -0
  160. package/dist/utils/vault-api.js +7 -0
  161. package/package.json +7 -7
@@ -0,0 +1,693 @@
1
+ /**
2
+ * Boundary logic for the US-006 Windows service pilot (proposal 039, 03d).
3
+ *
4
+ * The pilot runs jobs through a manual-start Windows service whose virtual
5
+ * account owns a native supervisor; the supervisor starts each job as a
6
+ * separate batch-logon account inside a Job Object. This module holds the
7
+ * parts of that design that can be built and tested without a Windows host:
8
+ * - the pilot names, the virtual service SID and literal SDDL for the
9
+ * pipes and the install directories,
10
+ * - the seven ordered boundary predicates the launcher checks before any
11
+ * claim or spawn,
12
+ * - reply attestation and its invalidation on restart or config change,
13
+ * - pipe server authentication behind an injectable API, with no
14
+ * credential resend after a failure,
15
+ * - launch parameter builders and the suspended create, assign, resume
16
+ * sequence,
17
+ * - outcomes from supervisor handles only,
18
+ * - a handle-based safe cleaner over an injectable filesystem API,
19
+ * - the boundary manifest, its digest and the supervisor load check,
20
+ * - the offline dry-run generator, the rollback plan, the expected job
21
+ * account state per phase, and the gate 1 preflight commands.
22
+ * Nothing here touches the host. Every Windows call sits behind an interface
23
+ * that root's installer and the native supervisor implement. Only node
24
+ * built-ins are imported at runtime.
25
+ */
26
+ import { createHash } from "node:crypto";
27
+ // ---------------------------------------------------------------------------
28
+ // Pilot names
29
+ const PILOT_ROOT = "C:\\ProgramData\\HQNativeDelivery-US006-038";
30
+ export const PILOT = {
31
+ service: "HQNDUS006038",
32
+ serviceIdentity: "NT SERVICE\\HQNDUS006038",
33
+ jobAccount: "BEAKER\\hqnd_job038",
34
+ jobUser: "hqnd_job038",
35
+ root: PILOT_ROOT,
36
+ supervisor: "bin\\hqnd-supervisor.exe",
37
+ supervisorPath: `${PILOT_ROOT}\\bin\\hqnd-supervisor.exe`,
38
+ pipes: {
39
+ bootstrap: "\\\\.\\pipe\\HQNDUS006038.bootstrap",
40
+ submit: "\\\\.\\pipe\\HQNDUS006038.submit",
41
+ control: "\\\\.\\pipe\\HQNDUS006038.control",
42
+ },
43
+ secretName: "HQ_NATIVE_DELIVERY_BEAKER_US006_JOB038_PASSWORD",
44
+ lsaRights: ["SeAssignPrimaryTokenPrivilege", "SeIncreaseQuotaPrivilege"],
45
+ };
46
+ // ---------------------------------------------------------------------------
47
+ // SIDs and SDDL
48
+ const SID_RE = /^S-1-\d+(-\d+)+$/;
49
+ export function isSid(value) {
50
+ return typeof value === "string" && SID_RE.test(value);
51
+ }
52
+ /**
53
+ * The virtual account SID Windows derives for a service name:
54
+ * S-1-5-80- followed by the SHA-1 of the upper-cased UTF-16LE name, read as
55
+ * five little-endian 32-bit values.
56
+ */
57
+ export function serviceSidFor(name) {
58
+ const digest = createHash("sha1").update(Buffer.from(name.toUpperCase(), "utf16le")).digest();
59
+ const parts = [];
60
+ for (let i = 0; i < 20; i += 4)
61
+ parts.push(digest.readUInt32LE(i));
62
+ return `S-1-5-80-${parts.join("-")}`;
63
+ }
64
+ /** The service SID is computed; a resolver answer for it must agree. The job SID comes only from the resolver. */
65
+ export function resolveSids(resolver) {
66
+ const serviceSid = serviceSidFor(PILOT.service);
67
+ let resolvedService;
68
+ let jobSid;
69
+ try {
70
+ resolvedService = resolver.lookup(PILOT.serviceIdentity);
71
+ jobSid = resolver.lookup(PILOT.jobAccount);
72
+ }
73
+ catch (err) {
74
+ return { ok: false, detail: "SID_UNRESOLVED", reason: `lookup failed: ${err.message}` };
75
+ }
76
+ if (resolvedService !== null && resolvedService !== serviceSid)
77
+ return { ok: false, detail: "SID_MISMATCH", reason: `${PILOT.serviceIdentity} resolved to ${resolvedService}, expected ${serviceSid}` };
78
+ if (jobSid === null)
79
+ return { ok: false, detail: "SID_UNRESOLVED", reason: `${PILOT.jobAccount} did not resolve` };
80
+ if (!isSid(jobSid))
81
+ return { ok: false, detail: "SID_INVALID", reason: `${PILOT.jobAccount} resolved to a value that is not a SID` };
82
+ if (jobSid === serviceSid)
83
+ return { ok: false, detail: "SID_MISMATCH", reason: "the job account and the service share a SID" };
84
+ return { ok: true, serviceSid, jobSid };
85
+ }
86
+ function requireSid(sid) {
87
+ if (!isSid(sid))
88
+ throw new Error(`not a SID: ${sid}`);
89
+ return sid;
90
+ }
91
+ /** Access masks used in the directory SDDL. */
92
+ export const RIGHTS = {
93
+ /** FILE_GENERIC_READ | FILE_GENERIC_EXECUTE. */
94
+ RX: "0x1200a9",
95
+ /** Read, write, execute and delete, without WRITE_DAC or WRITE_OWNER. */
96
+ MODIFY: "0x1301bf",
97
+ /** FILE_TRAVERSE | SYNCHRONIZE: no list, create, delete-child or rename. */
98
+ TRAVERSE: "0x100020",
99
+ };
100
+ /** The same DACL on each of the three pipes: SYSTEM, Administrators and the service SID only. */
101
+ export function pipeSddl(serviceSid) {
102
+ return `O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;${requireSid(serviceSid)})`;
103
+ }
104
+ /** The proposal 039 ACL table, one row per object. */
105
+ export const DIRECTORY_RULES = [
106
+ { path: "", service: "RX", job: "TRAVERSE", jobScope: "this_only" },
107
+ { path: "bin", service: "RX", job: null, jobScope: "contents" },
108
+ { path: "config", service: "RX", job: null, jobScope: "contents" },
109
+ { path: "runtime", service: "RX", job: "RX", jobScope: "contents" },
110
+ { path: "state", service: "MODIFY", job: null, jobScope: "contents" },
111
+ { path: "logs", service: "MODIFY", job: null, jobScope: "contents" },
112
+ { path: "control", service: "MODIFY", job: null, jobScope: "contents" },
113
+ { path: "runs", service: "MODIFY", job: "TRAVERSE", jobScope: "this_only" },
114
+ { path: "runs\\{run-id}", service: "MODIFY", job: "TRAVERSE", jobScope: "this_only" },
115
+ { path: "runs\\{run-id}\\input", service: "RX", job: "RX", jobScope: "contents" },
116
+ { path: "runs\\{run-id}\\work", service: "MODIFY", job: "MODIFY", jobScope: "contents" },
117
+ { path: "runs\\{run-id}\\output", service: "MODIFY", job: "MODIFY", jobScope: "contents" },
118
+ { path: "runs\\{run-id}\\tmp", service: "MODIFY", job: "MODIFY", jobScope: "contents" },
119
+ ];
120
+ /**
121
+ * Literal SDDL for one directory. Every directory gets an explicit protected
122
+ * DACL owned by Administrators, with full control for SYSTEM and
123
+ * Administrators, so nothing above the pilot root is inherited.
124
+ */
125
+ export function directorySddl(rule, serviceSid, jobSid) {
126
+ let sddl = `O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;${RIGHTS[rule.service]};;;${requireSid(serviceSid)})`;
127
+ if (rule.job)
128
+ sddl += `(A;${rule.jobScope === "contents" ? "OICI" : ""};${RIGHTS[rule.job]};;;${requireSid(jobSid)})`;
129
+ return sddl;
130
+ }
131
+ // ---------------------------------------------------------------------------
132
+ // Boundary predicates
133
+ /** Checked in this order; the first that does not pass names the refusal. */
134
+ export const BOUNDARY_PREDICATES = [
135
+ "BOUNDARY_SERVICE_UNAVAILABLE",
136
+ "BOUNDARY_SERVICE_IDENTITY",
137
+ "BOUNDARY_CHANNEL_IDENTITY",
138
+ "BOUNDARY_JOB_IDENTITY",
139
+ "BOUNDARY_PERMISSIONS",
140
+ "BOUNDARY_MANIFEST",
141
+ "BOUNDARY_RUN_SETUP",
142
+ ];
143
+ /** Missing, unknown, stale or failed results refuse; nothing defaults to pass. */
144
+ export function evaluateBoundary(results, ctx) {
145
+ if (!Array.isArray(results))
146
+ return { ok: false, detail: BOUNDARY_PREDICATES[0], reason: "missing: the probe returned no result list" };
147
+ const now = ctx.now().getTime();
148
+ for (const detail of BOUNDARY_PREDICATES) {
149
+ const matches = results.filter((r) => isObject(r) && r.detail === detail);
150
+ if (matches.length === 0)
151
+ return { ok: false, detail, reason: "missing: no result" };
152
+ if (matches.length > 1)
153
+ return { ok: false, detail, reason: "unknown: more than one result" };
154
+ const r = matches[0];
155
+ if (r.status !== "pass" && r.status !== "fail")
156
+ return { ok: false, detail, reason: `unknown: status ${JSON.stringify(r.status)}` };
157
+ const at = typeof r.observedAt === "string" ? Date.parse(r.observedAt) : Number.NaN;
158
+ if (Number.isNaN(at))
159
+ return { ok: false, detail, reason: "unknown: no observation time" };
160
+ if (at > now)
161
+ return { ok: false, detail, reason: "stale: observed in the future" };
162
+ if (now - at > ctx.maxAgeMs)
163
+ return { ok: false, detail, reason: `stale: observed ${now - at} ms ago` };
164
+ if (r.installationId !== ctx.installationId)
165
+ return { ok: false, detail, reason: "stale: another installation" };
166
+ if (r.configDigest !== ctx.configDigest)
167
+ return { ok: false, detail, reason: "stale: another configuration" };
168
+ if (r.status === "fail")
169
+ return { ok: false, detail, reason: `failed: ${typeof r.reason === "string" ? r.reason : "no reason given"}` };
170
+ }
171
+ const extra = results.find((r) => !isObject(r) || !BOUNDARY_PREDICATES.includes(r.detail));
172
+ if (extra !== undefined)
173
+ return { ok: false, detail: BOUNDARY_PREDICATES[0], reason: "unknown: unrecognised result" };
174
+ return { ok: true };
175
+ }
176
+ function isObject(v) {
177
+ return typeof v === "object" && v !== null && !Array.isArray(v);
178
+ }
179
+ export const ATTESTATION_FIELDS = [
180
+ ["connectionId", "ATTESTATION_CONNECTION"],
181
+ ["installationId", "ATTESTATION_INSTALLATION"],
182
+ ["runId", "ATTESTATION_RUN"],
183
+ ["sourceDigest", "ATTESTATION_SOURCE"],
184
+ ["serviceStartId", "ATTESTATION_RESTARTED"],
185
+ ["configDigest", "ATTESTATION_CONFIG_CHANGED"],
186
+ ];
187
+ /** A reply counts only when it is bound to this connection, installation, run, source, service start and config. */
188
+ export function checkAttestation(reply, expected) {
189
+ if (!isObject(reply))
190
+ return { ok: false, detail: "ATTESTATION_MISSING" };
191
+ for (const [field] of ATTESTATION_FIELDS)
192
+ if (typeof reply[field] !== "string")
193
+ return { ok: false, detail: "ATTESTATION_MISSING" };
194
+ for (const [field, detail] of ATTESTATION_FIELDS)
195
+ if (reply[field] !== expected[field])
196
+ return { ok: false, detail };
197
+ return { ok: true };
198
+ }
199
+ /** Holds one attestation; a service restart or config change drops it for good. */
200
+ export class AttestationCache {
201
+ entry = null;
202
+ remember(a) {
203
+ this.entry = { ...a };
204
+ }
205
+ current(observed) {
206
+ if (!this.entry)
207
+ return null;
208
+ if (this.entry.serviceStartId !== observed.serviceStartId || this.entry.configDigest !== observed.configDigest) {
209
+ this.entry = null;
210
+ return null;
211
+ }
212
+ return { ...this.entry };
213
+ }
214
+ }
215
+ /** Checked in this order before any byte is written. */
216
+ export const PIPE_AUTH_CHECKS = ["PIPE_SERVER_SID", "PIPE_SCM_PROCESS", "PIPE_IMAGE_PATH", "PIPE_SESSION"];
217
+ export function authenticatePipeServer(api, handle, expected) {
218
+ let step = "PIPE_SERVER_SID";
219
+ try {
220
+ const sid = api.serverSid(handle);
221
+ if (sid !== expected.serviceSid)
222
+ return { ok: false, detail: step, reason: "the pipe server is not the service SID" };
223
+ step = "PIPE_SCM_PROCESS";
224
+ const pid = api.serverProcessId(handle);
225
+ const scmPid = api.scmServicePid(expected.service);
226
+ if (pid === null || scmPid === null || pid <= 0 || pid !== scmPid)
227
+ return { ok: false, detail: step, reason: "the pipe server is not the SCM's service process" };
228
+ step = "PIPE_IMAGE_PATH";
229
+ const configured = api.serviceImagePath(expected.service);
230
+ const running = api.processImagePath(pid);
231
+ if ((configured !== expected.imagePath && configured !== `"${expected.imagePath}"`) || running !== expected.imagePath) {
232
+ return { ok: false, detail: step, reason: "the service image path is not the pilot supervisor" };
233
+ }
234
+ step = "PIPE_SESSION";
235
+ if (api.serverSessionId(handle) !== expected.sessionId)
236
+ return { ok: false, detail: step, reason: "the pipe server runs in another session" };
237
+ if (api.scmServicePid(expected.service) !== pid)
238
+ return { ok: false, detail: step, reason: "the service process changed during the checks" };
239
+ return { ok: true };
240
+ }
241
+ catch (err) {
242
+ return { ok: false, detail: step, reason: `query failed: ${err.message}` };
243
+ }
244
+ }
245
+ /**
246
+ * Sends the job credential once over an authenticated pipe. After any
247
+ * failure, or after one send, the client refuses further sends; there is no
248
+ * automatic resend.
249
+ */
250
+ export class PipeClient {
251
+ connector;
252
+ api;
253
+ expected;
254
+ pipeName;
255
+ latched = null;
256
+ constructor(connector, api, expected, pipeName) {
257
+ this.connector = connector;
258
+ this.api = api;
259
+ this.expected = expected;
260
+ this.pipeName = pipeName;
261
+ }
262
+ sendCredential(payload) {
263
+ if (this.latched)
264
+ return { ok: false, detail: this.latched, reason: "this client has already sent or failed; no resend" };
265
+ let conn;
266
+ try {
267
+ conn = this.connector.connect(this.pipeName);
268
+ }
269
+ catch (err) {
270
+ this.latched = "PIPE_CLIENT_POISONED";
271
+ return { ok: false, detail: "PIPE_CONNECT_FAILED", reason: err.message };
272
+ }
273
+ try {
274
+ const auth = authenticatePipeServer(this.api, conn.handle, this.expected);
275
+ if (!auth.ok) {
276
+ this.latched = "PIPE_CLIENT_POISONED";
277
+ return auth;
278
+ }
279
+ try {
280
+ this.latched = "PIPE_CREDENTIAL_SENT";
281
+ conn.write(payload);
282
+ }
283
+ catch (err) {
284
+ this.latched = "PIPE_CLIENT_POISONED";
285
+ return { ok: false, detail: "PIPE_WRITE_FAILED", reason: err.message };
286
+ }
287
+ return { ok: true };
288
+ }
289
+ finally {
290
+ try {
291
+ conn.close();
292
+ }
293
+ catch {
294
+ // The result above already stands; closing cannot change it.
295
+ }
296
+ }
297
+ }
298
+ }
299
+ // ---------------------------------------------------------------------------
300
+ // Launch parameters and sequence
301
+ /** Keys the supervisor sets itself; a job may not declare them. Compared case-insensitively. */
302
+ export const ENV_RESERVED = ["USERPROFILE", "APPDATA", "LOCALAPPDATA", "TEMP", "TMP", "SYSTEMROOT", "WINDIR", "PATH", "HOME", "CODEX_HOME"];
303
+ export const PROCESS_DACL_MASKS = {
304
+ PROCESS_QUERY_LIMITED_INFORMATION: 0x1000,
305
+ SYNCHRONIZE: 0x00100000,
306
+ PROCESS_TERMINATE: 0x0001,
307
+ };
308
+ export const CREATION_FLAGS = {
309
+ CREATE_SUSPENDED: 0x00000004,
310
+ CREATE_UNICODE_ENVIRONMENT: 0x00000400,
311
+ EXTENDED_STARTUPINFO_PRESENT: 0x00080000,
312
+ CREATE_NO_WINDOW: 0x08000000,
313
+ };
314
+ const RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
315
+ const WIN_ABS_RE = /^[A-Za-z]:\\[^<>"|?*]*$/;
316
+ function verifiedDir(p) {
317
+ return WIN_ABS_RE.test(p) && !p.split("\\").some((s) => s === ".." || s === ".");
318
+ }
319
+ export function buildLaunchParameters(input, serviceSid) {
320
+ if (!isSid(serviceSid))
321
+ return { ok: false, detail: "SID_INVALID", reason: "no service SID" };
322
+ if (!RUN_ID_RE.test(input.runId))
323
+ return { ok: false, detail: "RUN_DIR_OUTSIDE_ROOT", reason: "the run ID is not a single safe path segment" };
324
+ for (const [name, dir] of [["root", input.root], ["windowsDir", input.windowsDir], ["runtimeDir", input.runtimeDir]]) {
325
+ if (!verifiedDir(dir))
326
+ return { ok: false, detail: "PATH_UNVERIFIED", reason: `${name} is not an absolute verified path` };
327
+ }
328
+ if (!input.runtimeDir.toLowerCase().startsWith(`${input.root.toLowerCase()}\\`))
329
+ return { ok: false, detail: "PATH_UNVERIFIED", reason: "the runtime directory is outside the pilot root" };
330
+ const runDir = `${input.root}\\runs\\${input.runId}`;
331
+ const work = `${runDir}\\work`;
332
+ const tmp = `${runDir}\\tmp`;
333
+ const env = new Map();
334
+ for (const [k, v] of Object.entries(input.declaredEnv)) {
335
+ if (k === "" || k.includes("=") || k.includes("\0") || v.includes("\0"))
336
+ return { ok: false, detail: "ENV_INVALID", reason: "an environment entry is malformed" };
337
+ if (ENV_RESERVED.includes(k.toUpperCase()))
338
+ return { ok: false, detail: "ENV_RESERVED", reason: `${k} is set by the supervisor` };
339
+ if (env.has(k.toUpperCase()))
340
+ return { ok: false, detail: "ENV_INVALID", reason: `${k} is declared twice` };
341
+ env.set(k.toUpperCase(), [k, v]);
342
+ }
343
+ const fixed = [
344
+ ["USERPROFILE", work],
345
+ ["APPDATA", `${work}\\AppData\\Roaming`],
346
+ ["LOCALAPPDATA", `${work}\\AppData\\Local`],
347
+ ["TEMP", tmp],
348
+ ["TMP", tmp],
349
+ ["SystemRoot", input.windowsDir],
350
+ ["windir", input.windowsDir],
351
+ ["PATH", `${input.runtimeDir};${input.windowsDir}\\System32;${input.windowsDir}`],
352
+ ];
353
+ for (const [k, v] of fixed)
354
+ env.set(k.toUpperCase(), [k, v]);
355
+ const environment = [...env.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, kv]) => kv);
356
+ const handles = [input.stdio.stdin, input.stdio.stdout, input.stdio.stderr];
357
+ if (!handles.every((h) => Number.isInteger(h) && h > 0) || new Set(handles).size !== handles.length) {
358
+ return { ok: false, detail: "HANDLES_INVALID", reason: "stdio handles must be three distinct handles" };
359
+ }
360
+ const mask = PROCESS_DACL_MASKS.PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_DACL_MASKS.SYNCHRONIZE | PROCESS_DACL_MASKS.PROCESS_TERMINATE;
361
+ const creationFlags = CREATION_FLAGS.CREATE_SUSPENDED | CREATION_FLAGS.CREATE_UNICODE_ENVIRONMENT | CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT | CREATION_FLAGS.CREATE_NO_WINDOW;
362
+ return { ok: true, params: { lpDesktop: "", cwd: work, environment, inheritedHandles: handles, defaultDacl: { sid: serviceSid, mask }, creationFlags } };
363
+ }
364
+ /** Create suspended, then the Job Object with limits, then assign, then resume. Any failure after create terminates the process. */
365
+ export function launchSequence(api, params, limits) {
366
+ const steps = [];
367
+ if ((params.creationFlags & CREATION_FLAGS.CREATE_SUSPENDED) === 0)
368
+ return { ok: false, failedStep: "refused", reason: "the process would not start suspended", steps };
369
+ if (![limits.memoryBytes, limits.maxProcesses, limits.cpuTimeMs].every((n) => Number.isInteger(n) && n > 0))
370
+ return { ok: false, failedStep: "refused", reason: "job limits must be positive integers", steps };
371
+ let created;
372
+ try {
373
+ steps.push("create_suspended");
374
+ created = api.createSuspended(params);
375
+ }
376
+ catch (err) {
377
+ return { ok: false, failedStep: "create_suspended", reason: err.message, steps };
378
+ }
379
+ let step = "create_job";
380
+ try {
381
+ steps.push("create_job");
382
+ const job = api.createJob({ ...limits, killOnJobClose: true, breakawayAllowed: false });
383
+ step = "assign_job";
384
+ steps.push("assign_job");
385
+ api.assign(job, created.process);
386
+ step = "resume";
387
+ steps.push("resume");
388
+ api.resume(created.thread);
389
+ return { ok: true, process: created.process, job, steps };
390
+ }
391
+ catch (err) {
392
+ steps.push("terminate");
393
+ try {
394
+ api.terminate(created.process, 1);
395
+ }
396
+ catch {
397
+ // Job close with kill-on-close is the second line; the failure is reported either way.
398
+ }
399
+ return { ok: false, failedStep: step, reason: err.message, steps };
400
+ }
401
+ }
402
+ /** The outcome comes from handles only. Job stdio is passed in to show it is never read. */
403
+ export function outcomeFromHandles(input) {
404
+ const h = input.handles;
405
+ if (h.supervisorLost !== null)
406
+ return { reason: "supervisor_lost", detail: h.supervisorLost };
407
+ const exitCode = h.exitCode ?? undefined;
408
+ if (h.cancelled)
409
+ return { reason: "cancelled", exitCode };
410
+ if (h.jobLimit)
411
+ return { reason: "limit", limit: h.jobLimit, exitCode };
412
+ if (h.exitCode !== null)
413
+ return { reason: "exited", exitCode: h.exitCode };
414
+ return { reason: "supervisor_lost", detail: "no exit was observed on the process handle" };
415
+ }
416
+ /** Remove everything under the retained root handle. Anything in doubt is left in place and reported for quarantine. */
417
+ export function safeClean(fs, rootPath, expectedRoot) {
418
+ const report = { removed: [], quarantined: [] };
419
+ const root = fs.openRoot(rootPath);
420
+ try {
421
+ const id = fs.identity(root);
422
+ if (id.reparse || !id.directory || id.volume !== expectedRoot.volume || id.fileId !== expectedRoot.fileId) {
423
+ report.quarantined.push({ path: "", reason: "ROOT_IDENTITY" });
424
+ return report;
425
+ }
426
+ walk(fs, root, "", id.volume, report);
427
+ return report;
428
+ }
429
+ finally {
430
+ fs.close(root);
431
+ }
432
+ }
433
+ /** Returns true when everything under dir was removed. */
434
+ function walk(fs, dir, rel, volume, report) {
435
+ let clean = true;
436
+ for (const name of fs.list(dir)) {
437
+ const path = rel ? `${rel}\\${name}` : name;
438
+ if (name === "" || name === "." || name === ".." || /[\\/:\0]/.test(name)) {
439
+ report.quarantined.push({ path, reason: "NAME" });
440
+ clean = false;
441
+ continue;
442
+ }
443
+ let child;
444
+ try {
445
+ child = fs.openChild(dir, name);
446
+ }
447
+ catch {
448
+ report.quarantined.push({ path, reason: "OPEN_FAILED" });
449
+ clean = false;
450
+ continue;
451
+ }
452
+ let reason = null;
453
+ try {
454
+ const first = fs.identity(child);
455
+ if (first.reparse)
456
+ reason = "LINK";
457
+ else if (first.volume !== volume)
458
+ reason = "VOLUME";
459
+ else if (!first.directory && first.links > 1)
460
+ reason = "HARDLINK";
461
+ else if (first.directory && !walk(fs, child, path, volume, report)) {
462
+ clean = false;
463
+ continue;
464
+ }
465
+ else if (fs.identity(child).fileId !== first.fileId)
466
+ reason = "IDENTITY_CHANGED";
467
+ }
468
+ finally {
469
+ fs.close(child);
470
+ }
471
+ if (reason) {
472
+ report.quarantined.push({ path, reason });
473
+ clean = false;
474
+ continue;
475
+ }
476
+ try {
477
+ fs.remove(dir, name);
478
+ report.removed.push(path);
479
+ }
480
+ catch {
481
+ report.quarantined.push({ path, reason: "REMOVE_FAILED" });
482
+ clean = false;
483
+ }
484
+ }
485
+ return clean;
486
+ }
487
+ // ---------------------------------------------------------------------------
488
+ // Manifest
489
+ export const MANIFEST_VERSION = "hqnd.boundary-manifest.v1";
490
+ /** JSON with object keys sorted at every level. */
491
+ export function canonicalJson(value) {
492
+ if (Array.isArray(value))
493
+ return `[${value.map(canonicalJson).join(",")}]`;
494
+ if (isObject(value))
495
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(",")}}`;
496
+ return JSON.stringify(value);
497
+ }
498
+ export function manifestDigest(m) {
499
+ return createHash("sha256").update(canonicalJson(m)).digest("hex");
500
+ }
501
+ const HEX64 = /^[0-9a-f]{64}$/;
502
+ export function safeRelativePath(p) {
503
+ if (typeof p !== "string" || p === "" || p.includes("/") || p.includes("\0") || p.startsWith("\\") || /^[A-Za-z]:/.test(p))
504
+ return false;
505
+ return p.split("\\").every((s) => s !== "" && s !== "." && s !== "..");
506
+ }
507
+ export function parseManifest(raw) {
508
+ let v;
509
+ try {
510
+ v = JSON.parse(raw);
511
+ }
512
+ catch {
513
+ return { ok: false, detail: "MANIFEST_PARSE", reason: "not JSON" };
514
+ }
515
+ if (!isObject(v))
516
+ return { ok: false, detail: "MANIFEST_SHAPE", reason: "not an object" };
517
+ if (v.schemaVersion !== MANIFEST_VERSION)
518
+ return { ok: false, detail: "MANIFEST_VERSION", reason: `schemaVersion ${JSON.stringify(v.schemaVersion)}` };
519
+ for (const k of ["installationId", "service", "serviceIdentity", "jobAccount", "root", "supervisor"]) {
520
+ if (typeof v[k] !== "string" || v[k] === "")
521
+ return { ok: false, detail: "MANIFEST_SHAPE", reason: `${k} is missing` };
522
+ }
523
+ if (!isSid(v.serviceSid) || !isSid(v.jobSid))
524
+ return { ok: false, detail: "MANIFEST_SHAPE", reason: "a SID is missing or malformed" };
525
+ for (const k of ["pipes", "directories", "lsa", "files"])
526
+ if (!Array.isArray(v[k]))
527
+ return { ok: false, detail: "MANIFEST_SHAPE", reason: `${k} is not a list` };
528
+ if (!safeRelativePath(v.supervisor))
529
+ return { ok: false, detail: "MANIFEST_PATH", reason: "supervisor path is not a safe relative path" };
530
+ for (const f of v.files) {
531
+ if (!isObject(f) || typeof f.sha256 !== "string" || !HEX64.test(f.sha256))
532
+ return { ok: false, detail: "MANIFEST_SHAPE", reason: "a file entry has no sha256" };
533
+ if (!safeRelativePath(f.path))
534
+ return { ok: false, detail: "MANIFEST_PATH", reason: `${JSON.stringify(f.path)} is not a safe relative path` };
535
+ }
536
+ return { ok: true, manifest: v };
537
+ }
538
+ /** The manifest must match the independently approved digest, and every listed file must match its hash. */
539
+ export function verifyManifest(m, approvedDigest, readFile) {
540
+ if (manifestDigest(m) !== approvedDigest)
541
+ return { ok: false, detail: "MANIFEST_DIGEST", reason: "the manifest is not the approved one" };
542
+ for (const f of m.files) {
543
+ const bytes = readFile(f.path);
544
+ if (bytes === null)
545
+ return { ok: false, detail: "MANIFEST_FILE_MISSING", reason: f.path };
546
+ if (createHash("sha256").update(bytes).digest("hex") !== f.sha256)
547
+ return { ok: false, detail: "MANIFEST_FILE_DIGEST", reason: f.path };
548
+ }
549
+ return { ok: true };
550
+ }
551
+ /** What the supervisor runs at start: parse, then verify. Any failure means it does not open its pipes. */
552
+ export function supervisorLoadCheck(raw, approvedDigest, readFile) {
553
+ const parsed = parseManifest(raw);
554
+ if (!parsed.ok)
555
+ return parsed;
556
+ return verifyManifest(parsed.manifest, approvedDigest, readFile);
557
+ }
558
+ export const ROLLBACK_STEPS = [
559
+ { id: "refuse_admissions", description: "Set the worker to refuse new admissions and record the time.", commands: [] },
560
+ { id: "cancel_runs", description: "Cancel every admitted run through the control pipe and wait for each terminal result.", commands: [] },
561
+ { id: "stop_and_disable_service", description: "Stop the service and set it to disabled so nothing restarts it.", commands: ["sc.exe stop HQNDUS006038", "sc.exe config HQNDUS006038 start= disabled"] },
562
+ { id: "disable_job_account", description: "Disable the job account so no new logon can start.", commands: ["net.exe user hqnd_job038 /active:no"] },
563
+ { id: "zero_process_check", description: "Enumerate processes whose token user is the service SID or the job SID; the count must be 0. A non-zero count stops rollback for root.", commands: [] },
564
+ { id: "snapshot", description: "Record the service config, account state, LSA rights by SID, ACLs and the file inventory under the pilot root.", commands: ["sc.exe qc HQNDUS006038", "sc.exe sdshow HQNDUS006038", "net.exe user hqnd_job038"] },
565
+ { id: "zero_process_check_repeat", description: "Repeat the zero-process check by SID immediately before any deletion; the count must still be 0.", commands: [] },
566
+ { id: "remove_lsa_rights_by_sid", description: "Remove only the rights the installer recorded as added, by SID, with LsaRemoveAccountRights.", commands: [] },
567
+ { id: "remove_account_and_service", description: "Delete the job account, then the service.", commands: ["net.exe user hqnd_job038 /delete", "sc.exe delete HQNDUS006038"] },
568
+ { id: "remove_new_sid_matched_profiles", description: "Remove only profiles created during the pilot whose SID matches the job SID.", commands: [] },
569
+ { id: "revoke_secret_via_hq", description: "Revoke the job credential through the HQ secret workflow by name only.", commands: [] },
570
+ { id: "safe_inventory_cleanup", description: "Remove pilot files with the handle-based safe cleaner against the recorded root identity.", commands: [] },
571
+ { id: "quarantine_unproven", description: "Leave anything the cleaner could not prove safe in place and list it for root.", commands: [] },
572
+ { id: "final_checks_by_sid", description: "Confirm by SID that no process, right, account, service or ACE for the pilot remains.", commands: ["sc.exe query HQNDUS006038"] },
573
+ ];
574
+ const DELETION_STEPS = ["remove_lsa_rights_by_sid", "remove_account_and_service", "remove_new_sid_matched_profiles", "safe_inventory_cleanup"];
575
+ /** The NF03d-2 order: stop and disable before the zero check, and a repeated zero check before any deletion. */
576
+ export function checkRollbackOrder(steps) {
577
+ const ids = steps.map((s) => s.id);
578
+ for (const s of ROLLBACK_STEPS) {
579
+ const n = ids.filter((id) => id === s.id).length;
580
+ if (n === 0)
581
+ return { ok: false, detail: "ROLLBACK_STEP_MISSING", reason: s.id };
582
+ if (n > 1)
583
+ return { ok: false, detail: "ROLLBACK_STEP_DUPLICATE", reason: s.id };
584
+ }
585
+ const at = (id) => ids.indexOf(id);
586
+ if (at("refuse_admissions") !== 0)
587
+ return { ok: false, detail: "ROLLBACK_REFUSE_NOT_FIRST", reason: "admissions must stop first" };
588
+ if (at("stop_and_disable_service") > at("zero_process_check"))
589
+ return { ok: false, detail: "ROLLBACK_ZERO_BEFORE_STOP", reason: "the service must be stopped and disabled before the zero-process check" };
590
+ if (at("disable_job_account") > at("zero_process_check"))
591
+ return { ok: false, detail: "ROLLBACK_ZERO_BEFORE_DISABLE", reason: "the job account must be disabled before the zero-process check" };
592
+ if (!(at("zero_process_check") < at("snapshot") && at("snapshot") < at("zero_process_check_repeat")))
593
+ return { ok: false, detail: "ROLLBACK_SNAPSHOT_ORDER", reason: "zero check, snapshot, then the repeated zero check" };
594
+ for (const d of DELETION_STEPS) {
595
+ if (at(d) < at("zero_process_check_repeat"))
596
+ return { ok: false, detail: "ROLLBACK_DELETE_BEFORE_REPEAT_ZERO", reason: `${d} runs before the repeated zero-process check` };
597
+ }
598
+ if (at("final_checks_by_sid") !== ids.length - 1)
599
+ return { ok: false, detail: "ROLLBACK_FINAL_NOT_LAST", reason: "the final checks must be last" };
600
+ return { ok: true };
601
+ }
602
+ // ---------------------------------------------------------------------------
603
+ // Job account state per phase (NF03d-4)
604
+ export const ACCOUNT_PHASES = ["installed", "idle", "admitted_session", "after_session", "rollback"];
605
+ /** Disabled with no session outside an admitted session; enabled with exactly one session inside one. */
606
+ export const EXPECTED_ACCOUNT_STATE = {
607
+ installed: { enabled: false, sessions: 0 },
608
+ idle: { enabled: false, sessions: 0 },
609
+ admitted_session: { enabled: true, sessions: 1 },
610
+ after_session: { enabled: false, sessions: 0 },
611
+ rollback: { enabled: false, sessions: 0 },
612
+ };
613
+ export function checkAccountState(phase, observed) {
614
+ if (!ACCOUNT_PHASES.includes(phase))
615
+ return { ok: false, detail: "ACCOUNT_PHASE_UNKNOWN" };
616
+ const expected = EXPECTED_ACCOUNT_STATE[phase];
617
+ const tag = phase.toUpperCase();
618
+ if (typeof observed.enabled !== "boolean" || typeof observed.sessions !== "number" || !Number.isInteger(observed.sessions) || observed.sessions < 0) {
619
+ return { ok: false, detail: "ACCOUNT_STATE_UNKNOWN" };
620
+ }
621
+ if (observed.enabled !== expected.enabled)
622
+ return { ok: false, detail: `ACCOUNT_STATE_${tag}_EXPECTED_${expected.enabled ? "ENABLED" : "DISABLED"}` };
623
+ if (observed.sessions !== expected.sessions) {
624
+ if (expected.sessions === 1)
625
+ return { ok: false, detail: observed.sessions === 0 ? "ACCOUNT_SESSION_MISSING" : "ACCOUNT_MULTIPLE_SESSIONS" };
626
+ return { ok: false, detail: `ACCOUNT_SESSIONS_${tag}_EXPECTED_0` };
627
+ }
628
+ return { ok: true };
629
+ }
630
+ export const GATE1_PREFLIGHT = [
631
+ { id: "os_build", command: "cmd.exe /d /c ver", purpose: "Windows build", expectStdoutIncludes: "Version 10.0." },
632
+ { id: "edition_id", command: 'reg.exe query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v EditionID', purpose: "Windows edition ID", expectStdoutIncludes: "EditionID" },
633
+ {
634
+ id: "edition_caption",
635
+ command: 'powershell.exe -NoProfile -NonInteractive -Command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"',
636
+ purpose: "Windows edition name",
637
+ expectStdoutIncludes: "Windows",
638
+ },
639
+ { id: "virtual_account_support", command: "sc.exe showsid HQNDUS006038", purpose: "virtual service account SID support", expectStdoutIncludes: serviceSidFor("HQNDUS006038") },
640
+ ];
641
+ /** Each command is judged on its own capture and exit code. */
642
+ export function evaluatePreflight(captures) {
643
+ for (const c of GATE1_PREFLIGHT) {
644
+ const tag = c.id.toUpperCase();
645
+ const cap = captures[c.id];
646
+ if (!isObject(cap) || typeof cap.stdout !== "string" || typeof cap.stderr !== "string")
647
+ return { ok: false, detail: `PREFLIGHT_${tag}_MISSING` };
648
+ if (typeof cap.exitCode !== "number")
649
+ return { ok: false, detail: `PREFLIGHT_${tag}_NO_EXIT_CODE` };
650
+ if (cap.exitCode !== 0)
651
+ return { ok: false, detail: `PREFLIGHT_${tag}_EXIT` };
652
+ if (!cap.stdout.includes(c.expectStdoutIncludes))
653
+ return { ok: false, detail: `PREFLIGHT_${tag}_UNEXPECTED` };
654
+ }
655
+ return { ok: true };
656
+ }
657
+ export function generateDryRun(input) {
658
+ const sids = resolveSids(input.resolver);
659
+ if (!sids.ok)
660
+ return sids;
661
+ const { serviceSid, jobSid } = sids;
662
+ const pipes = Object.values(PILOT.pipes).map((name) => ({ name, sddl: pipeSddl(serviceSid) }));
663
+ const directories = DIRECTORY_RULES.map((rule) => ({ path: rule.path, sddl: directorySddl(rule, serviceSid, jobSid) }));
664
+ const manifest = {
665
+ schemaVersion: MANIFEST_VERSION,
666
+ installationId: input.installationId,
667
+ service: PILOT.service,
668
+ serviceIdentity: PILOT.serviceIdentity,
669
+ serviceSid,
670
+ jobAccount: PILOT.jobAccount,
671
+ jobSid,
672
+ root: PILOT.root,
673
+ supervisor: PILOT.supervisor,
674
+ pipes,
675
+ directories,
676
+ lsa: PILOT.lsaRights.map((right) => ({ sid: serviceSid, right, action: "add_if_absent_record_prior" })),
677
+ files: input.files.map((f) => ({ ...f })),
678
+ };
679
+ const parsed = parseManifest(JSON.stringify(manifest));
680
+ if (!parsed.ok)
681
+ return parsed;
682
+ if (checkRollbackOrder(ROLLBACK_STEPS).ok !== true)
683
+ return { ok: false, detail: "ROLLBACK_ORDER", reason: "the rollback plan is out of order" };
684
+ const sddlText = [
685
+ ...pipes.map((p) => `pipe\t${p.name}\t${p.sddl}`),
686
+ ...directories.map((d) => `directory\t${d.path === "" ? PILOT.root : `${PILOT.root}\\${d.path}`}\t${d.sddl}`),
687
+ ].join("\n");
688
+ return {
689
+ ok: true,
690
+ output: { manifest, manifestDigest: manifestDigest(manifest), sddlText: `${sddlText}\n`, rollback: ROLLBACK_STEPS, preflight: GATE1_PREFLIGHT, accountStates: EXPECTED_ACCOUNT_STATE },
691
+ };
692
+ }
693
+ //# sourceMappingURL=windows-boundary.js.map