@songtonyli/dsh-cli 0.1.54 → 0.1.55

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 (67) hide show
  1. package/README.md +1 -1
  2. package/bin/dsh.mjs +1 -1
  3. package/node_modules/@deepseek-ai/dsh-agent-preset/skills/cordis-composition-reference/references/packages.md +1 -1
  4. package/node_modules/@deepseek-ai/dsh-client-locale/lib/client.js +7 -7
  5. package/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/lib/client.js +61 -61
  6. package/node_modules/@deepseek-ai/dsh-client-ui-approval/lib/client.js +10 -10
  7. package/node_modules/@deepseek-ai/dsh-client-ui-attachment/lib/client.js +49 -49
  8. package/node_modules/@deepseek-ai/dsh-client-ui-chat/lib/client.js +207 -207
  9. package/node_modules/@deepseek-ai/dsh-client-ui-commands/lib/client.js +16 -16
  10. package/node_modules/@deepseek-ai/dsh-client-ui-conversation/lib/client.js +153 -153
  11. package/node_modules/@deepseek-ai/dsh-client-ui-cordis/lib/client.js +74 -74
  12. package/node_modules/@deepseek-ai/dsh-client-ui-deliverables/lib/client.js +80 -80
  13. package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-browse/lib/client.js +39 -39
  14. package/node_modules/@deepseek-ai/dsh-client-ui-goal/lib/client.js +16 -16
  15. package/node_modules/@deepseek-ai/dsh-client-ui-input-trigger/lib/client.js +23 -23
  16. package/node_modules/@deepseek-ai/dsh-client-ui-jobs/lib/client.js +37 -37
  17. package/node_modules/@deepseek-ai/dsh-client-ui-layout/lib/client.js +9 -9
  18. package/node_modules/@deepseek-ai/dsh-client-ui-message-feedback/lib/client.js +12 -12
  19. package/node_modules/@deepseek-ai/dsh-client-ui-model-selection/lib/client.js +31 -31
  20. package/node_modules/@deepseek-ai/dsh-client-ui-open-in-app/lib/client.js +8 -8
  21. package/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/lib/client.js +18 -18
  22. package/node_modules/@deepseek-ai/dsh-client-ui-plan/lib/client.js +22 -22
  23. package/node_modules/@deepseek-ai/dsh-client-ui-plugin-manager/lib/client.js +139 -139
  24. package/node_modules/@deepseek-ai/dsh-client-ui-primitives/lib/OnboardingSurface.module.css +28 -0
  25. package/node_modules/@deepseek-ai/dsh-client-ui-primitives/lib/types/OnboardingSurface.d.ts +11 -0
  26. package/node_modules/@deepseek-ai/dsh-client-ui-schedule/lib/client.js +182 -182
  27. package/node_modules/@deepseek-ai/dsh-client-ui-settings-account/lib/client.js +128 -128
  28. package/node_modules/@deepseek-ai/dsh-client-ui-settings-general/lib/client.js +49 -49
  29. package/node_modules/@deepseek-ai/dsh-client-ui-settings-models/lib/client.js +87 -87
  30. package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugin-inventory/lib/client.js +41 -41
  31. package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugins/lib/client.js +13 -13
  32. package/node_modules/@deepseek-ai/dsh-client-ui-settings-session-log/lib/client.js +5 -5
  33. package/node_modules/@deepseek-ai/dsh-client-ui-settings-signin/lib/client.js +24 -24
  34. package/node_modules/@deepseek-ai/dsh-client-ui-settings-subagent/lib/client.js +27 -27
  35. package/node_modules/@deepseek-ai/dsh-client-ui-shortcuts/lib/client.js +42 -42
  36. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +44 -44
  37. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-browser/lib/client.js +25 -25
  38. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-documentpreview/lib/client.excel.js +9 -9
  39. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-documentpreview/lib/client.js +70 -70
  40. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-documentpreview/lib/client.pdf.js +9 -9
  41. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-files/lib/client.js +18 -18
  42. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-right/lib/client.js +26 -26
  43. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-terminal/lib/client.js +16 -16
  44. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar-terminal/lib/client.terminal.js +11 -11
  45. package/node_modules/@deepseek-ai/dsh-client-ui-skill/lib/client.js +19 -19
  46. package/node_modules/@deepseek-ai/dsh-client-ui-subagent/lib/client.js +37 -37
  47. package/node_modules/@deepseek-ai/dsh-client-ui-theme/lib/client.js +27 -27
  48. package/node_modules/@deepseek-ai/dsh-client-ui-tool/lib/client.js +99 -99
  49. package/node_modules/@deepseek-ai/dsh-client-ui-trajectory/lib/client.js +197 -197
  50. package/node_modules/@deepseek-ai/dsh-client-ui-user-questions/lib/client.js +73 -73
  51. package/node_modules/@deepseek-ai/dsh-client-ui-workflow-run/lib/client.js +26 -26
  52. package/node_modules/@deepseek-ai/dsh-client-ui-workspace/lib/client.js +92 -92
  53. package/node_modules/@deepseek-ai/dsh-experimental-auto-review/README.i18n.yaml +2 -2
  54. package/node_modules/@deepseek-ai/dsh-experimental-auto-review/README.md +1 -1
  55. package/node_modules/@deepseek-ai/dsh-experimental-auto-review/README.zh.md +1 -1
  56. package/node_modules/@deepseek-ai/dsh-experimental-auto-review/cordis.patch.yml +3 -0
  57. package/node_modules/@deepseek-ai/dsh-experimental-auto-review/lib/index.js +11 -5
  58. package/node_modules/@deepseek-ai/dsh-experimental-auto-review/package.json +4 -0
  59. package/node_modules/@deepseek-ai/dsh-experimental-client-ui-agent-team/lib/client.js +32 -32
  60. package/node_modules/@deepseek-ai/dsh-experimental-client-ui-voice-input/lib/client.js +24 -24
  61. package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/types-DxezulnA.js +1324 -0
  62. package/node_modules/@deepseek-ai/dsh-schedule/lib/types/persistence.js +30 -0
  63. package/node_modules/@deepseek-ai/dsh-schedule/lib/types/projection.js +68 -0
  64. package/node_modules/@deepseek-ai/dsh-schedule/lib/types/transaction.js +22 -0
  65. package/node_modules/@deepseek-ai/dsh-session-log-export/lib/client.js +3 -3
  66. package/node_modules/@deepseek-ai/dsh-subprocess-local/lib/runner-launch-DGV26RBf.js +1525 -0
  67. package/package.json +1 -1
@@ -0,0 +1,1324 @@
1
+ import { existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { ERROR_INSUFFICIENT_BUFFER, Win32Error, allocPtrSlot, allocUint32, decodePtr, decodeUint32, drainPipe, extendWin32ProcessBindings, isNullPtr, isNullPtr as isNullPtr$1, spawnInheritedJobProcess, spawnPipedProcess, throwLastError, throwLastError as throwLastError$1, throwWin32, waitForProcessExit } from "@deepseek-ai/dsh-win32-process";
4
+ import { createHash } from "node:crypto";
5
+ import { createLazyRequire } from "@deepseek-ai/dsh-lazy-require";
6
+ //#region lib/types/win32-abi.js
7
+ /** ACL/token-specific Win32 constants. */
8
+ /** OpenProcess access required to query the current process token. */
9
+ const PROCESS_QUERY_INFORMATION = 1024;
10
+ /** Group attribute identifying the token logon SID. */
11
+ const SE_GROUP_LOGON_ID = 3221225472;
12
+ /**
13
+ * Capability-SID access mask granting write, delete, and child deletion.
14
+ * WRITE_DAC and WRITE_OWNER stay excluded so a confined child cannot rewrite
15
+ * DACLs or take ownership to escape the allowlist.
16
+ */
17
+ const GRANT_MASK = 1114454;
18
+ /** Full access used in the restricted token default DACL. */
19
+ const FILE_ALL_ACCESS = 2032127;
20
+ //#endregion
21
+ //#region lib/types/ffi.js
22
+ /** ACL/token bindings layered on the shared Win32 process owner. */
23
+ const requireKoffi = createLazyRequire("koffi", import.meta.url);
24
+ let cachedTypes;
25
+ function ffiTypes() {
26
+ if (cachedTypes !== void 0) return cachedTypes;
27
+ const koffi = requireKoffi();
28
+ const PVOID = koffi.pointer("void");
29
+ return cachedTypes = {
30
+ PVOID,
31
+ PPVOID: koffi.pointer(PVOID)
32
+ };
33
+ }
34
+ /**
35
+ * Return whether CreateFileW produced INVALID_HANDLE_VALUE.
36
+ * @param handle - handle returned by CreateFileW.
37
+ * @returns true for null, zero, or the all-bits-one sentinel.
38
+ */
39
+ function isInvalidHandle(handle) {
40
+ if (isNullPtr(handle)) return true;
41
+ return handle === 18446744073709551615n || handle === -1n;
42
+ }
43
+ /**
44
+ * Encode a uint32 into an allocated slot.
45
+ * @param slot - slot allocated by allocUint32.
46
+ * @param value - unsigned value to store.
47
+ */
48
+ function encodeUint32(slot, value) {
49
+ requireKoffi().encode(slot, "uint32", value);
50
+ }
51
+ /**
52
+ * Return a Koffi pointer's numeric address for struct packing.
53
+ * @param ptr - native pointer.
54
+ * @returns pointer address.
55
+ */
56
+ function ptrAddress(ptr) {
57
+ return requireKoffi().address(ptr);
58
+ }
59
+ /**
60
+ * Allocate a raw byte block.
61
+ * @param length - byte count.
62
+ * @returns allocated pointer.
63
+ */
64
+ function allocBytes(length) {
65
+ return requireKoffi().alloc("uint8", length);
66
+ }
67
+ /**
68
+ * Allocate one zeroed x64 OVERLAPPED record.
69
+ * @returns allocated pointer.
70
+ * @remarks Koffi 3.1.1 crashes when LockFileEx or UnlockFileEx receives NULL;
71
+ * a zeroed OVERLAPPED is equivalent for the synchronous lock-file handle.
72
+ */
73
+ function allocOverlapped() {
74
+ return allocBytes(32);
75
+ }
76
+ /**
77
+ * Decode a pointer value from a Buffer field.
78
+ * @param buffer - encoded native record.
79
+ * @param offset - pointer field byte offset.
80
+ * @returns decoded pointer, or null for address zero.
81
+ */
82
+ function decodePtrAt(buffer, offset) {
83
+ const value = requireKoffi().decode(buffer, offset, ffiTypes().PVOID);
84
+ return isNullPtr(value) ? null : value;
85
+ }
86
+ /**
87
+ * Decode a uint8 field at a native pointer offset.
88
+ * @param ptr - native record pointer.
89
+ * @param offset - field byte offset.
90
+ * @returns decoded value.
91
+ */
92
+ function decodeUint8At(ptr, offset) {
93
+ return requireKoffi().decode(ptr, offset, "uint8");
94
+ }
95
+ /**
96
+ * Decode a uint16 field at a native pointer offset.
97
+ * @param ptr - native record pointer.
98
+ * @param offset - field byte offset.
99
+ * @returns decoded value.
100
+ */
101
+ function decodeUint16At(ptr, offset) {
102
+ return requireKoffi().decode(ptr, offset, "uint16");
103
+ }
104
+ /**
105
+ * Decode a uint32 field at a native pointer offset.
106
+ * @param ptr - native record pointer.
107
+ * @param offset - field byte offset.
108
+ * @returns decoded value.
109
+ */
110
+ function decodeUint32At(ptr, offset) {
111
+ return requireKoffi().decode(ptr, offset, "uint32");
112
+ }
113
+ /**
114
+ * Compare two in-memory SID records without allocating strings.
115
+ * @param left - first native buffer.
116
+ * @param leftOffset - first SID byte offset.
117
+ * @param right - second native buffer.
118
+ * @param rightOffset - second SID byte offset.
119
+ * @returns true when revision, authority, and every sub-authority match.
120
+ */
121
+ function sameSidAt(left, leftOffset, right, rightOffset) {
122
+ if (decodeUint8At(left, leftOffset) !== decodeUint8At(right, rightOffset)) return false;
123
+ const leftCount = decodeUint8At(left, leftOffset + 1);
124
+ if (leftCount !== decodeUint8At(right, rightOffset + 1) || leftCount > 15) return false;
125
+ for (let index = 0; index < 6; index += 1) if (decodeUint8At(left, leftOffset + 2 + index) !== decodeUint8At(right, rightOffset + 2 + index)) return false;
126
+ for (let index = 0; index < leftCount; index += 1) if (decodeUint32At(left, leftOffset + 8 + index * 4) !== decodeUint32At(right, rightOffset + 8 + index * 4)) return false;
127
+ return true;
128
+ }
129
+ let cached;
130
+ function bindings() {
131
+ if (cached !== void 0) return cached;
132
+ const koffi = requireKoffi();
133
+ const { PVOID, PPVOID } = ffiTypes();
134
+ cached = extendWin32ProcessBindings(({ kernel32, advapi32, bind }) => ({
135
+ openProcess: bind(kernel32, "OpenProcess", PVOID, [
136
+ "uint32",
137
+ "int",
138
+ "uint32"
139
+ ]),
140
+ openProcessToken: bind(advapi32, "OpenProcessToken", "int", [
141
+ PVOID,
142
+ "uint32",
143
+ PPVOID
144
+ ]),
145
+ localAlloc: bind(kernel32, "LocalAlloc", PVOID, ["uint32", "size_t"]),
146
+ localFree: bind(kernel32, "LocalFree", PVOID, [PVOID]),
147
+ convertStringSidToSidW: bind(advapi32, "ConvertStringSidToSidW", "int", ["str16", PPVOID]),
148
+ createWellKnownSid: bind(advapi32, "CreateWellKnownSid", "int", [
149
+ "int",
150
+ PVOID,
151
+ PVOID,
152
+ koffi.pointer("uint32")
153
+ ]),
154
+ isValidSid: bind(advapi32, "IsValidSid", "int", [PVOID]),
155
+ getLengthSid: bind(advapi32, "GetLengthSid", "uint32", [PVOID]),
156
+ copySid: bind(advapi32, "CopySid", "int", [
157
+ "uint32",
158
+ PVOID,
159
+ PVOID
160
+ ]),
161
+ getTokenInformation: bind(advapi32, "GetTokenInformation", "int", [
162
+ PVOID,
163
+ "int",
164
+ PVOID,
165
+ "uint32",
166
+ koffi.pointer("uint32")
167
+ ]),
168
+ setTokenInformation: bind(advapi32, "SetTokenInformation", "int", [
169
+ PVOID,
170
+ "int",
171
+ PVOID,
172
+ "uint32"
173
+ ]),
174
+ createRestrictedToken: bind(advapi32, "CreateRestrictedToken", "int", [
175
+ PVOID,
176
+ "uint32",
177
+ "uint32",
178
+ PVOID,
179
+ "uint32",
180
+ PVOID,
181
+ "uint32",
182
+ PVOID,
183
+ PPVOID
184
+ ]),
185
+ setEntriesInAclW: bind(advapi32, "SetEntriesInAclW", "uint32", [
186
+ "uint32",
187
+ PVOID,
188
+ PVOID,
189
+ PPVOID
190
+ ]),
191
+ initializeAcl: bind(advapi32, "InitializeAcl", "int", [
192
+ PVOID,
193
+ "uint32",
194
+ "uint32"
195
+ ]),
196
+ addMandatoryAce: bind(advapi32, "AddMandatoryAce", "int", [
197
+ PVOID,
198
+ "uint32",
199
+ "uint32",
200
+ "uint32",
201
+ PVOID
202
+ ]),
203
+ setNamedSecurityInfoW: bind(advapi32, "SetNamedSecurityInfoW", "uint32", [
204
+ "str16",
205
+ "int",
206
+ "uint32",
207
+ PVOID,
208
+ PVOID,
209
+ PVOID,
210
+ PVOID
211
+ ]),
212
+ getNamedSecurityInfoW: bind(advapi32, "GetNamedSecurityInfoW", "uint32", [
213
+ "str16",
214
+ "int",
215
+ "uint32",
216
+ PPVOID,
217
+ PPVOID,
218
+ PPVOID,
219
+ PPVOID,
220
+ PPVOID
221
+ ]),
222
+ getTempPathW: bind(kernel32, "GetTempPathW", "uint32", ["uint32", PVOID]),
223
+ setEnvironmentVariableW: bind(kernel32, "SetEnvironmentVariableW", "int", ["str16", "str16"]),
224
+ setConsoleCtrlHandler: bind(kernel32, "SetConsoleCtrlHandler", "int", [PVOID, "int"]),
225
+ createFileW: bind(kernel32, "CreateFileW", PVOID, [
226
+ "str16",
227
+ "uint32",
228
+ "uint32",
229
+ PVOID,
230
+ "uint32",
231
+ "uint32",
232
+ PVOID
233
+ ]),
234
+ lockFileEx: bind(kernel32, "LockFileEx", "int", [
235
+ PVOID,
236
+ "uint32",
237
+ "uint32",
238
+ "uint32",
239
+ "uint32",
240
+ PVOID
241
+ ]),
242
+ unlockFileEx: bind(kernel32, "UnlockFileEx", "int", [
243
+ PVOID,
244
+ "uint32",
245
+ "uint32",
246
+ "uint32",
247
+ PVOID
248
+ ])
249
+ }));
250
+ return cached;
251
+ }
252
+ /**
253
+ * Resolve the cached ACL/token binding table asynchronously.
254
+ * @returns generic process plus ACL/token bindings.
255
+ */
256
+ function win32() {
257
+ return Promise.resolve(bindings());
258
+ }
259
+ /**
260
+ * Resolve the cached ACL/token binding table synchronously.
261
+ * @returns generic process plus ACL/token bindings.
262
+ */
263
+ function win32Sync() {
264
+ return bindings();
265
+ }
266
+ /**
267
+ * Resolve the current Windows temporary directory.
268
+ * @param api - active ACL/token binding table.
269
+ * @returns UTF-16 path reported by GetTempPathW.
270
+ */
271
+ function getTempPath(api) {
272
+ const buffer = Buffer.alloc(261 * 2);
273
+ const length = api.getTempPathW(buffer.length / 2, buffer);
274
+ if (length === 0) throwLastError(api, "GetTempPathW");
275
+ if (length > buffer.length / 2) throw new Win32Error("GetTempPathW", ERROR_INSUFFICIENT_BUFFER, `required ${length} chars exceed the ${buffer.length / 2}-char buffer; nothing was written`);
276
+ return buffer.subarray(0, length * 2).toString("utf16le");
277
+ }
278
+ //#endregion
279
+ //#region lib/types/acl.js
280
+ /**
281
+ * ACL editing helpers: grant/revoke a capability SID on a directory via
282
+ * SetEntriesInAclW + SetNamedSecurityInfoW (the same calls the POC uses, with
283
+ * the failure handling the POC lacks). Every API call is checked and every
284
+ * failure is reported with the API name, the exact Win32 code, the formatted
285
+ * system text, and the affected path.
286
+ *
287
+ * Each grant applies three edits in ONE SetNamedSecurityInfoW call: the
288
+ * capability-SID allow ACE, a Deny ACE that removes the ambient
289
+ * `FILE_DELETE_CHILD` right from the world SID, and a Low no-write-up
290
+ * mandatory label ({@link buildLowLabelAcl}). The deny is what keeps one
291
+ * granted root out of another's reach: Windows also authorizes a delete from
292
+ * the parent directory's `FILE_DELETE_CHILD` right, which the token's
293
+ * write-restricted intersection does not reach, and every granted root carries
294
+ * the Low label that clears the integrity check.
295
+ *
296
+ * Concurrency: grants are read-merge-write against the directory's CURRENT
297
+ * DACL, and the whole get-merge-set sequence runs under a per-path exclusive
298
+ * LockFileEx lock (see {@link withPathLock}) so concurrent sandbox instances
299
+ * cannot clobber each other's ACEs.
300
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/acl
301
+ */
302
+ /**
303
+ * Pack one EXPLICIT_ACCESS_W (48 bytes, layout verified by abi-probe.cpp):
304
+ * perms@0, mode@4, inheritance@8, Trustee@16 { pMultipleTrustee@16,
305
+ * MultipleTrusteeOperation@24, TrusteeForm@28, TrusteeType@32, ptstrName@40 }.
306
+ * `permissions` is the access mask; the POC passes 0 for REVOKE_ACCESS, which
307
+ * removes every ACE for the trustee. `inheritance` defaults to children of
308
+ * both kinds; the ambient-delete deny narrows it to containers because
309
+ * FILE_DELETE_CHILD is meaningless on a file and its bit would otherwise
310
+ * spread through the file's inherited mask.
311
+ * @param sidPtr - the trustee SID the entry names.
312
+ * @param mode - the access mode (GRANT_ACCESS, DENY_ACCESS, or REVOKE_ACCESS).
313
+ * @param permissions - the access mask to grant or deny (0 for REVOKE_ACCESS).
314
+ * @param inheritance - the ACE inheritance flags.
315
+ * @returns the packed entry buffer.
316
+ */
317
+ function buildExplicitAccess(sidPtr, mode, permissions, inheritance = 3) {
318
+ const entry = Buffer.alloc(48);
319
+ entry.writeUInt32LE(permissions, 0);
320
+ entry.writeUInt32LE(mode, 4);
321
+ entry.writeUInt32LE(inheritance, 8);
322
+ entry.writeUInt32LE(0, 24);
323
+ entry.writeUInt32LE(0, 28);
324
+ entry.writeUInt32LE(0, 32);
325
+ entry.writeBigUInt64LE(ptrAddress(sidPtr), 40);
326
+ return entry;
327
+ }
328
+ /**
329
+ * One lock file per protected path: `<GetTempPathW()>\dsh-acl-locks\<first 16
330
+ * hex of sha256(lowercased path)>.lock`. The lock root derives from
331
+ * GetTempPathW (never from runner argv or DSH_HOME), and the lowercasing
332
+ * maps Windows's case-insensitive path spellings onto one lock.
333
+ * @param api - the binding table.
334
+ * @param path - the protected directory (absolute).
335
+ * @returns the lock file path for that directory.
336
+ */
337
+ function lockFilePath(api, path) {
338
+ const digest = createHash("sha256").update(path.toLowerCase()).digest("hex").slice(0, 16);
339
+ return join(getTempPath(api), "dsh-acl-locks", `${digest}.lock`);
340
+ }
341
+ /**
342
+ * Run `action` holding the per-path exclusive lock: CreateFileW
343
+ * (OPEN_ALWAYS, shared read/write but NOT delete — a deletable lock file
344
+ * could be removed and recreated under the holder, letting two processes
345
+ * hold "the same" lock), then a one-byte LockFileEx
346
+ * (LOCKFILE_EXCLUSIVE_LOCK, zeroed OVERLAPPED = lock from offset 0 on the
347
+ * synchronous handle — see allocOverlapped for why not NULL), then
348
+ * UnlockFileEx + CloseHandle. Fail-closed: open/lock/unlock/close failures
349
+ * throw like every other Win32 call in this package; an `action` failure
350
+ * still unlocks (best-effort) and rethrows the original error.
351
+ * @param api - the binding table.
352
+ * @param path - the protected directory (absolute).
353
+ * @param action - the get-merge-set sequence to serialize.
354
+ * @returns the action's result.
355
+ */
356
+ function withPathLock(api, path, action) {
357
+ const lockPath = lockFilePath(api, path);
358
+ mkdirSync(dirname(lockPath), { recursive: true });
359
+ const handle = api.createFileW(lockPath, -1073741824, 3, null, 4, 0, null);
360
+ if (isInvalidHandle(handle)) throwLastError$1(api, "CreateFileW", lockPath);
361
+ const overlapped = allocOverlapped();
362
+ if (api.lockFileEx(handle, 2, 0, 1, 0, overlapped) === 0) {
363
+ const win32Code = api.getLastError();
364
+ api.closeHandle(handle);
365
+ throwWin32(api, "LockFileEx", win32Code, lockPath);
366
+ }
367
+ let result;
368
+ try {
369
+ result = action();
370
+ } catch (error) {
371
+ api.unlockFileEx(handle, 0, 1, 0, overlapped);
372
+ api.closeHandle(handle);
373
+ throw error;
374
+ }
375
+ if (api.unlockFileEx(handle, 0, 1, 0, overlapped) === 0) {
376
+ const win32Code = api.getLastError();
377
+ api.closeHandle(handle);
378
+ throwWin32(api, "UnlockFileEx", win32Code, lockPath);
379
+ }
380
+ if (api.closeHandle(handle) === 0) throwLastError$1(api, "CloseHandle", `lock file ${lockPath}`);
381
+ return result;
382
+ }
383
+ /**
384
+ * Read the directory's current explicit DACL and mandatory label via
385
+ * GetNamedSecurityInfoW.
386
+ * Allocation contract (the POC's RevokeAccess, minus its missing checks): the
387
+ * returned ACL pointer sits INSIDE the security descriptor allocation — only
388
+ * the descriptor may be LocalFree'd, and it must not be freed before
389
+ * SetEntriesInAclW has consumed the ACL. Freeing the ACL pointer itself
390
+ * corrupts the heap (verified the hard way).
391
+ * @param api - the binding table.
392
+ * @param path - the directory whose DACL and label are read.
393
+ * @returns the current explicit DACL and label ACL (null when the directory carries none) plus their owning descriptor.
394
+ */
395
+ function readCurrentSecurity(api, path) {
396
+ const ownerSlot = allocPtrSlot();
397
+ const groupSlot = allocPtrSlot();
398
+ const daclSlot = allocPtrSlot();
399
+ const saclSlot = allocPtrSlot();
400
+ const descriptorSlot = allocPtrSlot();
401
+ const readResult = api.getNamedSecurityInfoW(path, 1, 20, ownerSlot, groupSlot, daclSlot, saclSlot, descriptorSlot);
402
+ if (readResult !== 0) throwWin32(api, "GetNamedSecurityInfoW", readResult, path);
403
+ return {
404
+ oldAcl: decodePtr(daclSlot),
405
+ labelAcl: decodePtr(saclSlot),
406
+ descriptor: decodePtr(descriptorSlot)
407
+ };
408
+ }
409
+ /**
410
+ * Build the Low mandatory label applied with every write grant: one
411
+ * SYSTEM_MANDATORY_LABEL_ACE naming `lowLabelSidPtr` with the no-write-up
412
+ * policy, inheriting to subcontainers and objects so later children carry the
413
+ * same label. The caller frees the returned ACL with LocalFree
414
+ * (SetNamedSecurityInfoW copies it); every Win32 call is checked and a
415
+ * half-built ACL is released before the error is thrown.
416
+ * @param api - the binding table.
417
+ * @param lowLabelSidPtr - the Low integrity SID (S-1-16-4096) the label names.
418
+ * @returns the ACL carrying the single inheritable label ACE.
419
+ */
420
+ function buildLowLabelAcl(api, lowLabelSidPtr) {
421
+ const sidLength = api.getLengthSid(lowLabelSidPtr);
422
+ if (sidLength === 0) throwLastError$1(api, "GetLengthSid", "Low mandatory label SID");
423
+ const aclLength = 16 + sidLength;
424
+ const acl = api.localAlloc(64, aclLength);
425
+ if (isNullPtr$1(acl)) throwLastError$1(api, "LocalAlloc", "Low mandatory label ACL");
426
+ if (api.initializeAcl(acl, aclLength, 2) === 0) {
427
+ const win32Code = api.getLastError();
428
+ api.localFree(acl);
429
+ throwWin32(api, "InitializeAcl", win32Code, "Low mandatory label ACL");
430
+ }
431
+ if (api.addMandatoryAce(acl, 2, 3, 1, lowLabelSidPtr) === 0) {
432
+ const win32Code = api.getLastError();
433
+ api.localFree(acl);
434
+ throwWin32(api, "AddMandatoryAce", win32Code, "Low mandatory label ACL");
435
+ }
436
+ return acl;
437
+ }
438
+ /**
439
+ * True when the label ACL already carries the EXACT label this module would
440
+ * add (mandatory-label ACE, OI|CI inheritance, no-write-up policy, the Low
441
+ * SID), so a re-grant can skip the eager full-tree propagation.
442
+ * @param labelAcl - the current label ACL pointer (from {@link readCurrentSecurity}).
443
+ * @param lowLabelSidPtr - the Low integrity SID to match.
444
+ * @returns whether the exact label ACE is already present.
445
+ */
446
+ function hasExactLabel(labelAcl, lowLabelSidPtr) {
447
+ return hasExactEntry(labelAcl, 17, 3, 1, lowLabelSidPtr);
448
+ }
449
+ /**
450
+ * Shared tail of grantWrite and revokeWrite: merge `entries` into `oldAcl`
451
+ * (null = no explicit DACL yet; SetEntriesInAclW builds one from scratch),
452
+ * free the descriptor before applying the merged ACL, apply the merged DACL
453
+ * together with the label edit in one SetNamedSecurityInfoW call, then free
454
+ * every ACL this call owns — checking each call and reporting with the
455
+ * caller's label. The entry count derives from the buffer, so a grant can
456
+ * carry its capability ACE and its ambient-delete deny in one merge.
457
+ * @param api - the binding table.
458
+ * @param path - the directory the DACL and label edits apply to.
459
+ * @param entries - packed EXPLICIT_ACCESS_W records to merge (grant, deny, or revoke).
460
+ * @param oldAcl - the current explicit DACL (from {@link readCurrentSecurity}).
461
+ * @param labelEdit - the label change to apply alongside the DACL.
462
+ * @param descriptor - the descriptor allocation owning `oldAcl`.
463
+ * @param label - the caller's name for error details.
464
+ */
465
+ function mergeAndApply(api, path, entries, oldAcl, labelEdit, descriptor, label) {
466
+ const newAclSlot = allocPtrSlot();
467
+ const mergeResult = api.setEntriesInAclW(entries.length / 48, entries, oldAcl, newAclSlot);
468
+ if (mergeResult !== 0) {
469
+ if (descriptor !== null) api.localFree(descriptor);
470
+ if (labelEdit.kind === "apply") api.localFree(labelEdit.acl);
471
+ throwWin32(api, "SetEntriesInAclW", mergeResult, `${label}(${path})`);
472
+ }
473
+ const newAcl = decodePtr(newAclSlot);
474
+ if (newAcl === null) {
475
+ if (descriptor !== null) api.localFree(descriptor);
476
+ if (labelEdit.kind === "apply") api.localFree(labelEdit.acl);
477
+ throwWin32(api, "SetEntriesInAclW", api.getLastError(), `${label}(${path}): null new ACL`);
478
+ }
479
+ const freedDescriptor = descriptor !== null ? api.localFree(descriptor) : null;
480
+ const applyResult = api.setNamedSecurityInfoW(path, 1, labelEdit.kind === "keep" ? 4 : 20, null, null, newAcl, labelEdit.kind === "apply" ? labelEdit.acl : null);
481
+ const freedNew = api.localFree(newAcl);
482
+ const freedLabel = labelEdit.kind === "apply" ? api.localFree(labelEdit.acl) : null;
483
+ if (applyResult !== 0) throwWin32(api, "SetNamedSecurityInfoW", applyResult, `${label}(${path})`);
484
+ if (freedDescriptor !== null && !isNullPtr$1(freedDescriptor)) throwLastError$1(api, "LocalFree", `${label}(${path}) descriptor`);
485
+ if (!isNullPtr$1(freedNew)) throwLastError$1(api, "LocalFree", `${label}(${path}) new ACL`);
486
+ if (freedLabel !== null && !isNullPtr$1(freedLabel)) throwLastError$1(api, "LocalFree", `${label}(${path}) label ACL`);
487
+ }
488
+ /**
489
+ * True when the explicit DACL already carries the EXACT entry
490
+ * `(aceType, inheritance, mask, trustee SID)`. Every field is read through
491
+ * koffi.decode at pointer offsets — no memcpy, no pointer arithmetic. The
492
+ * ACE's SID is INLINE (embedded in the ACE after the 4-byte mask — there is
493
+ * no pointer to read; reading one yields garbage addresses and crashed
494
+ * EqualSid, verified by gdb), so it is compared field-by-field against the
495
+ * trustee SID through bounded offset reads ({@link sameSidAt}). Allowed and
496
+ * denied ACEs share the Mask@4/SID@8 layout. A malformed header reads as "no
497
+ * exact entry" so the caller falls back to the merge-apply path, which owns
498
+ * the robust failure handling.
499
+ * @param acl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
500
+ * @param aceType - the ACE type to match.
501
+ * @param inheritance - the ACE inheritance flags to match.
502
+ * @param mask - the access mask to match.
503
+ * @param sidPtr - the trustee SID to match.
504
+ * @returns whether the exact entry is already present.
505
+ */
506
+ function hasExactEntry(acl, aceType, inheritance, mask, sidPtr) {
507
+ const aclSize = decodeUint16At(acl, 2);
508
+ const aceCount = decodeUint16At(acl, 4);
509
+ if (aclSize < 8 || aclSize > 1048576) return false;
510
+ let offset = 8;
511
+ for (let index = 0; index < aceCount; index++) {
512
+ const aceSize = decodeUint16At(acl, offset + 2);
513
+ if (aceSize < 8 || offset + aceSize > aclSize) return false;
514
+ if (decodeUint8At(acl, offset) === aceType && decodeUint8At(acl, offset + 1) === inheritance && decodeUint32At(acl, offset + 4) === mask && sameSidAt(acl, offset + 8, sidPtr, 0)) return true;
515
+ offset += aceSize;
516
+ }
517
+ return false;
518
+ }
519
+ /**
520
+ * True when the explicit DACL already carries the EXACT write grant this
521
+ * module would add: the Allow ACE for {@link abi.GRANT_MASK} naming the
522
+ * capability SID.
523
+ * @param oldAcl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
524
+ * @param sidPtr - the capability SID to match.
525
+ * @returns whether the exact grant ACE is already present.
526
+ */
527
+ function hasExactGrant(oldAcl, sidPtr) {
528
+ return hasExactEntry(oldAcl, 0, 3, GRANT_MASK, sidPtr);
529
+ }
530
+ /**
531
+ * True when the explicit DACL already carries the EXACT ambient-delete deny:
532
+ * the container-inherited Deny ACE for {@link abi.FILE_DELETE_CHILD} naming
533
+ * the world SID. It is part of the idempotent skip, so a root granted by an
534
+ * earlier build receives the deny on its next provision.
535
+ * @param oldAcl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
536
+ * @param worldSidPtr - the Everyone SID the deny names.
537
+ * @returns whether the exact deny ACE is already present.
538
+ */
539
+ function hasExactDeny(oldAcl, worldSidPtr) {
540
+ return hasExactEntry(oldAcl, 1, 2, 64, worldSidPtr);
541
+ }
542
+ /**
543
+ * True when a capability grant for a SID OTHER than `sidPtr` stands on this
544
+ * DACL — the condition under which a revoke must leave the shared Low label in
545
+ * place, or the remaining grant's child would lose its write authority.
546
+ * @param oldAcl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
547
+ * @param sidPtr - the capability SID being revoked.
548
+ * @returns whether another capability grant remains.
549
+ */
550
+ function hasForeignGrant(oldAcl, sidPtr) {
551
+ const aclSize = decodeUint16At(oldAcl, 2);
552
+ const aceCount = decodeUint16At(oldAcl, 4);
553
+ if (aclSize < 8 || aclSize > 1048576) return false;
554
+ let offset = 8;
555
+ for (let index = 0; index < aceCount; index++) {
556
+ const aceSize = decodeUint16At(oldAcl, offset + 2);
557
+ if (aceSize < 8 || offset + aceSize > aclSize) return false;
558
+ if (decodeUint8At(oldAcl, offset) === 0 && decodeUint32At(oldAcl, offset + 4) === 1114454 && !sameSidAt(oldAcl, offset + 8, sidPtr, 0)) return true;
559
+ offset += aceSize;
560
+ }
561
+ return false;
562
+ }
563
+ /**
564
+ * Grant `GRANT_MASK` (Write+Delete, displays as "Modify") to the capability SID
565
+ * on `path`, deny the world SID the ambient `FILE_DELETE_CHILD` right, and
566
+ * apply the Low mandatory label — one merge. The deny inherits to containers
567
+ * only: the right is evaluated on directories, and inheriting its bit onto
568
+ * files would deny every `FILE_ALL_ACCESS`/`GENERIC_ALL` open inside the root
569
+ * (0x40 is a member of that mask). The capability ACE's DELETE bit is then the
570
+ * only delete authority inside the root, so a file whose own DACL grants no
571
+ * DELETE is no longer deletable through its parent's rights.
572
+ *
573
+ * Idempotent: the exact ACE, deny, and label together SKIP the
574
+ * SetNamedSecurityInfoW apply, which would otherwise re-propagate the
575
+ * identical descriptor across the whole tree (eager inheritance; minutes on
576
+ * large workspaces). Otherwise read-merge-write, so pre-existing explicit ACEs
577
+ * survive (same shape as {@link revokeWrite}). Runs under the per-path lock.
578
+ * The directory must be owned by the caller AND grant WRITE_OWNER (the label
579
+ * lives in the SACL; owner-implicit rights cover only READ_CONTROL and
580
+ * WRITE_DAC) — a Full-control workspace satisfies both.
581
+ * @param api - the binding table.
582
+ * @param path - the directory whose DACL and label gain the grant (the workspace or temp root).
583
+ * @param sidPtr - the capability SID the ACE names.
584
+ * @param lowLabelSidPtr - the Low integrity SID the mandatory label names.
585
+ * @param worldSidPtr - the Everyone SID the ambient-delete deny names.
586
+ */
587
+ function grantWrite(api, path, sidPtr, lowLabelSidPtr, worldSidPtr) {
588
+ withPathLock(api, path, () => {
589
+ const { oldAcl, labelAcl, descriptor } = readCurrentSecurity(api, path);
590
+ if (oldAcl !== null && labelAcl !== null && hasExactGrant(oldAcl, sidPtr) && hasExactDeny(oldAcl, worldSidPtr) && hasExactLabel(labelAcl, lowLabelSidPtr)) {
591
+ if (descriptor !== null) {
592
+ if (!isNullPtr$1(api.localFree(descriptor))) throwLastError$1(api, "LocalFree", `grantWrite(${path}) descriptor`);
593
+ }
594
+ return;
595
+ }
596
+ let label;
597
+ try {
598
+ label = buildLowLabelAcl(api, lowLabelSidPtr);
599
+ } catch (error) {
600
+ if (descriptor !== null) api.localFree(descriptor);
601
+ throw error;
602
+ }
603
+ mergeAndApply(api, path, Buffer.concat([buildExplicitAccess(worldSidPtr, 3, 64, 2), buildExplicitAccess(sidPtr, 1, GRANT_MASK)]), oldAcl, {
604
+ kind: "apply",
605
+ acl: label
606
+ }, descriptor, "grantWrite");
607
+ });
608
+ }
609
+ /**
610
+ * Remove every ACE for the capability SID from the directory DACL (REVOKE_ACCESS
611
+ * merge — other entries are preserved). The shared Low label is cleared only
612
+ * when no other capability grant remains on the directory: two grants may
613
+ * target one directory, and the surviving one still needs the label for its
614
+ * child's writes. Returns whether an ACE removal was attempted (false when the
615
+ * directory carries no DACL at all).
616
+ *
617
+ * Runs under the per-path lock (the whole get-merge-set sequence); the
618
+ * descriptor/ACL allocation contract lives on {@link readCurrentSecurity}.
619
+ * @param api - the binding table.
620
+ * @param path - the directory whose DACL loses the capability-SID ACEs.
621
+ * @param sidPtr - the capability SID whose ACEs are removed.
622
+ * @returns whether an ACE removal was attempted (false when the directory carries no DACL at all).
623
+ */
624
+ function revokeWrite(api, path, sidPtr) {
625
+ return withPathLock(api, path, () => {
626
+ const { oldAcl, descriptor } = readCurrentSecurity(api, path);
627
+ if (oldAcl === null) {
628
+ if (descriptor !== null) {
629
+ if (!isNullPtr$1(api.localFree(descriptor))) throwLastError$1(api, "LocalFree", `revokeWrite(${path}) descriptor`);
630
+ }
631
+ return false;
632
+ }
633
+ mergeAndApply(api, path, buildExplicitAccess(sidPtr, 4, 0), oldAcl, hasForeignGrant(oldAcl, sidPtr) ? { kind: "keep" } : { kind: "clear" }, descriptor, "revokeWrite");
634
+ return true;
635
+ });
636
+ }
637
+ //#endregion
638
+ //#region lib/types/path-boundary.js
639
+ /**
640
+ * Canonical directory-boundary checks for the Windows ACL workspace and
641
+ * private-temp capabilities.
642
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/path-boundary
643
+ */
644
+ /** Whether `root` is the same canonical directory as `candidate` or contains it. */
645
+ function containsDirectory(root, candidate) {
646
+ const relation = relative(realpathSync.native(root), realpathSync.native(candidate));
647
+ return relation === "" || !isAbsolute(relation) && relation !== ".." && !relation.startsWith(`..${sep}`);
648
+ }
649
+ /**
650
+ * Reject a temp parent that is inside the workspace: every child created
651
+ * below it would inherit the standing workspace capability.
652
+ * @param workspaceRoot - the canonical workspace root that receives the standing ACE.
653
+ * @param tempRoot - the existing parent beneath which a private temp child would be created.
654
+ */
655
+ function assertTempRootOutsideWorkspace(workspaceRoot, tempRoot) {
656
+ if (containsDirectory(workspaceRoot, tempRoot)) throw new Error(`Windows ACL temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tempRoot}`);
657
+ }
658
+ /**
659
+ * Reject overlap between an actual private temp directory and any writable
660
+ * directory: either inheritance direction would merge the two capabilities.
661
+ * @param writableDirs - directories carrying the standing workspace capability.
662
+ * @param tempDir - the existing directory carrying the revocable temp capability.
663
+ */
664
+ function assertPrivateTempDisjoint(writableDirs, tempDir) {
665
+ for (const writableDir of writableDirs) if (containsDirectory(writableDir, tempDir) || containsDirectory(tempDir, writableDir)) throw new Error(`AclSandbox private temp directory must be disjoint from writable directories: writable=${writableDir}; temp=${tempDir}`);
666
+ }
667
+ //#endregion
668
+ //#region lib/types/spawn.js
669
+ /** Restricted-token adapters over the shared Win32 process owner. */
670
+ /**
671
+ * Spawn a restricted-token child with piped stdout/stderr.
672
+ * @param api - ACL/token binding table.
673
+ * @param token - restricted primary token.
674
+ * @param options - command, args, and working directory.
675
+ * @returns process and caller-owned pipe handles.
676
+ */
677
+ function spawnSandboxed(api, token, options) {
678
+ return spawnPipedProcess(api, {
679
+ ...options,
680
+ token
681
+ });
682
+ }
683
+ /**
684
+ * Spawn a restricted-token child in a kill-on-close Job with inherited stdio.
685
+ * @param api - ACL/token binding table.
686
+ * @param token - restricted primary token.
687
+ * @param options - command, args, and working directory.
688
+ * @returns process and Job handles after assignment and resume.
689
+ */
690
+ function spawnSandboxedInherited(api, token, options) {
691
+ return spawnInheritedJobProcess(api, {
692
+ ...options,
693
+ token
694
+ });
695
+ }
696
+ /**
697
+ * Wait for a restricted child and close its process handle.
698
+ * @param api - ACL/token binding table.
699
+ * @param process - caller-owned process handle.
700
+ * @returns direct process exit code.
701
+ */
702
+ function waitForExit(api, process) {
703
+ return waitForProcessExit(api, process);
704
+ }
705
+ //#endregion
706
+ //#region lib/types/token.js
707
+ /**
708
+ * Restricted-token construction: open the current process token, extract its
709
+ * logon SID, build the well-known SIDs, and call CreateRestrictedToken with
710
+ * the POC's restricting-SID allowlist. Every API call is checked; any failure
711
+ * throws with the API name and the exact Win32 code — the original POC ignored
712
+ * all of these and silently ran children with the FULL, unrestricted token.
713
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/token
714
+ */
715
+ /**
716
+ * Open the current process's access token with the rights
717
+ * CreateRestrictedToken requires (the POC's OpenProcessToken call; the token
718
+ * handle is obtained through a real OpenProcess handle because the
719
+ * GetCurrentProcess() pseudo-handle is not addressable through koffi).
720
+ * @param api - the binding table.
721
+ * @returns the opened token handle.
722
+ */
723
+ function openCurrentProcessToken(api) {
724
+ const processHandle = api.openProcess(PROCESS_QUERY_INFORMATION, 0, process.pid);
725
+ if (isNullPtr$1(processHandle)) throwLastError$1(api, "OpenProcess", `pid ${process.pid}`);
726
+ const tokenSlot = allocPtrSlot();
727
+ if (api.openProcessToken(processHandle, 139, tokenSlot) === 0) {
728
+ const win32Code = api.getLastError();
729
+ api.closeHandle(processHandle);
730
+ throwWin32(api, "OpenProcessToken", win32Code, `pid ${process.pid}`);
731
+ }
732
+ if (api.closeHandle(processHandle) === 0) throwLastError$1(api, "CloseHandle", "OpenProcess process handle");
733
+ const token = decodePtr(tokenSlot);
734
+ if (token === null) throwWin32(api, "OpenProcessToken", api.getLastError(), "null token handle");
735
+ return token;
736
+ }
737
+ /**
738
+ * Find and copy the token's logon session SID (S-1-5-5-x-y, attribute
739
+ * SE_GROUP_LOGON_ID). The restricted token needs it for WinSta0/desktop and
740
+ * other per-logon objects; the POC extracts it the same way.
741
+ * @param api - the binding table.
742
+ * @param token - the token whose groups are scanned.
743
+ * @returns a copied logon SID (thrown when the token carries none).
744
+ */
745
+ function findLogonSid(api, token) {
746
+ const neededSlot = allocUint32();
747
+ api.getTokenInformation(token, 2, null, 0, neededSlot);
748
+ const needed = decodeUint32(neededSlot);
749
+ if (needed === 0) throwLastError$1(api, "GetTokenInformation", "TokenGroups size query");
750
+ if (needed < 8) throwWin32(api, "GetTokenInformation", api.getLastError(), `implausible TokenGroups size ${needed}`);
751
+ const groups = Buffer.alloc(needed);
752
+ if (api.getTokenInformation(token, 2, groups, groups.length, neededSlot) === 0) throwLastError$1(api, "GetTokenInformation", "TokenGroups");
753
+ const groupCount = groups.readUInt32LE(0);
754
+ for (let index = 0; index < groupCount; index++) {
755
+ const sidPtr = decodePtrAt(groups, 8 + index * 16);
756
+ const isLogonId = (groups.readUInt32LE(8 + index * 16 + 8) & SE_GROUP_LOGON_ID) >>> 0 === SE_GROUP_LOGON_ID >>> 0;
757
+ if (sidPtr === null || !isLogonId) continue;
758
+ const sidLength = api.getLengthSid(sidPtr);
759
+ if (sidLength === 0) throwLastError$1(api, "GetLengthSid", `logon SID group ${index}`);
760
+ const copy = allocBytes(sidLength);
761
+ if (api.copySid(sidLength, copy, sidPtr) === 0) throwLastError$1(api, "CopySid", `logon SID group ${index}`);
762
+ return copy;
763
+ }
764
+ throw new Error(`CreateRestrictedToken prerequisite failed: no logon SID found among ${groupCount} token groups`);
765
+ }
766
+ /**
767
+ * Create one well-known SID (68-byte buffer) and assert its validity.
768
+ * @param api - the binding table.
769
+ * @param type - the WELL_KNOWN_SID_TYPE to create.
770
+ * @returns the created SID pointer.
771
+ */
772
+ function makeWellKnownSid(api, type) {
773
+ const sid = allocBytes(68);
774
+ const sizeSlot = allocUint32();
775
+ encodeUint32(sizeSlot, 68);
776
+ if (api.createWellKnownSid(type, null, sid, sizeSlot) === 0) throwLastError$1(api, "CreateWellKnownSid", `type ${type}`);
777
+ if (api.isValidSid(sid) === 0) throwLastError$1(api, "IsValidSid", `CreateWellKnownSid type ${type}`);
778
+ return sid;
779
+ }
780
+ /**
781
+ * Merge one full-access allow ACE for `sidPtr` into the token's DEFAULT DACL
782
+ * — the DACL every NEW object the token holder creates (without an explicit
783
+ * security descriptor) takes. The restricted token inherits the user's
784
+ * default DACL verbatim, which names no restricting SID: a new anonymous pipe
785
+ * (child stdio) therefore fails the write pass-2 check at creation
786
+ * (ERROR_ACCESS_DENIED; Node surfaces it as spawn EPERM), breaking every
787
+ * piped-stdio grandchild spawn. The merged ACE names a RESTRICTING SID (the
788
+ * write SID under workspace-write, Everyone under read-only), so each new
789
+ * object's own DACL passes pass-2 while object creation itself stays gated by
790
+ * the parent container's DACL (files outside the granted trees remain
791
+ * uncreatable). Fails closed: any Win32 failure throws before the spawn.
792
+ * @param api - the binding table.
793
+ * @param token - the restricted token to adjust (requires TOKEN_ADJUST_DEFAULT).
794
+ * @param sidPtr - the restricting SID whose full-access ACE joins the default DACL.
795
+ */
796
+ function setTokenDefaultDaclGrant(api, token, sidPtr) {
797
+ const neededSlot = allocUint32();
798
+ api.getTokenInformation(token, 6, null, 0, neededSlot);
799
+ const needed = decodeUint32(neededSlot);
800
+ if (needed === 0) throwLastError$1(api, "GetTokenInformation", "TokenDefaultDacl size query");
801
+ const buffer = Buffer.alloc(needed);
802
+ if (api.getTokenInformation(token, 6, buffer, buffer.length, neededSlot) === 0) throwLastError$1(api, "GetTokenInformation", "TokenDefaultDacl");
803
+ const currentDacl = decodePtrAt(buffer, 0);
804
+ if (currentDacl === null) throw new Error("setTokenDefaultDaclGrant: the token carries no default DACL to extend");
805
+ const newDaclSlot = allocPtrSlot();
806
+ const result = api.setEntriesInAclW(1, buildExplicitAccess(sidPtr, 1, FILE_ALL_ACCESS), currentDacl, newDaclSlot);
807
+ if (result !== 0) throwWin32(api, "SetEntriesInAclW", result, "default DACL merge");
808
+ const newDacl = decodePtr(newDaclSlot);
809
+ if (newDacl === null) throwWin32(api, "SetEntriesInAclW", result, "null merged default DACL");
810
+ const info = Buffer.alloc(8);
811
+ info.writeBigUInt64LE(newDacl, 0);
812
+ if (api.setTokenInformation(token, 6, info, info.length) === 0) {
813
+ const win32Code = api.getLastError();
814
+ api.localFree(newDacl);
815
+ throwWin32(api, "SetTokenInformation", win32Code, "TokenDefaultDacl");
816
+ }
817
+ api.localFree(newDacl);
818
+ }
819
+ /**
820
+ * Lower the restricted token's integrity level to Low (S-1-16-4096), the level
821
+ * the mandatory labels `grantWrite` applies are matched against; a token left
822
+ * at Medium would ignore them. Requires TOKEN_ADJUST_DEFAULT on the token;
823
+ * fails closed before any child is spawned.
824
+ * @param api - the binding table.
825
+ * @param token - the restricted token to lower.
826
+ * @param lowLabelSidPtr - the Low integrity SID (S-1-16-4096).
827
+ */
828
+ function restrictTokenIntegrity(api, token, lowLabelSidPtr) {
829
+ const sidLength = api.getLengthSid(lowLabelSidPtr);
830
+ if (sidLength === 0) throwLastError$1(api, "GetLengthSid", "Low integrity label SID");
831
+ const info = Buffer.alloc(16 + sidLength);
832
+ info.writeBigUInt64LE(ptrAddress(lowLabelSidPtr), 0);
833
+ info.writeUInt32LE(32, 8);
834
+ if (api.setTokenInformation(token, 25, info, info.length) === 0) throwLastError$1(api, "SetTokenInformation", "TokenIntegrityLevel (Low)");
835
+ }
836
+ /** Pack `SID_AND_ATTRIBUTES[count]` (16-byte stride; Attributes stay 0). */
837
+ function buildRestrictingSids(sids) {
838
+ const buffer = Buffer.alloc(16 * sids.length);
839
+ sids.forEach((sid, index) => {
840
+ buffer.writeBigUInt64LE(ptrAddress(sid), 16 * index);
841
+ });
842
+ return buffer;
843
+ }
844
+ /**
845
+ * Create the write-restricted token with the mode-selected restricting list
846
+ * (verified on Win11 26200, see the POC-worktree restrict-variant harness):
847
+ * - read-only: [logon SID, EVERYONE]
848
+ * - workspace-write: [logon SID, EVERYONE, workspace SID, optional temp SID]
849
+ *
850
+ * The logon SID + EVERYONE keep-alive group is shared by both modes: early
851
+ * DLL init dies with 0xC0000142 and CNG (`\Device\CNG` write trustee —
852
+ * pwsh crashes 0xE0434352) fails without them. The write SIDs join ONLY
853
+ * workspace-write — read-only carries no write SID, so a standing grant ACE
854
+ * from an earlier workspace-write period (a `/permission` mode downgrade, or
855
+ * a crash-resumed session) stays INERT under read-only: the WRITE_RESTRICTED
856
+ * pass-2 check grants only what the restricting list carries, keeping that
857
+ * workspace grant inert under read-only while the unrevoked ACE keeps the
858
+ * re-upgrade free (the grant's exact-ACE skip — no re-propagation).
859
+ * Everyone's own ambient grants remain the documented partial boundary.
860
+ * Authenticated Users is absent from BOTH lists: the WMI
861
+ * namespace security check fails (0x80041003), so CIM is unavailable in
862
+ * every confined mode, and the C:\-root tree-creation escape (standing
863
+ * `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACEs) is closed in both — documented in
864
+ * README. INTERACTIVE/LOCAL are absent from BOTH lists too — the host's
865
+ * Public tree grants write to INTERACTIVE, so removing it closes that
866
+ * escape. S-1-2-1 (console logon) is intentionally absent: the package
867
+ * README's "Console isolation is unavailable" entry records the verified
868
+ * failure modes. FAILS CLOSED: any failure throws — never
869
+ * spawn unrestricted.
870
+ * @param api - the binding table.
871
+ * @param currentToken - the process token to restrict.
872
+ * @param logonSid - the copied logon session SID.
873
+ * @param writeSids - the distinct write SIDs forming the workspace and
874
+ * optional temp allowlists (workspace-write only; empty under read-only).
875
+ * @param known - the well-known SIDs entering the restricting list.
876
+ * @param mode - selects the restricting list (workspace-write adds the capability SIDs).
877
+ * @returns the restricted token handle.
878
+ */
879
+ function createRestrictedToken(api, currentToken, logonSid, writeSids, known, mode) {
880
+ const restrictingSids = buildRestrictingSids(mode === "read-only" ? [logonSid, known.world] : writeSids.length === 0 ? (() => {
881
+ throw new Error("createRestrictedToken: workspace-write restricting list requires at least one write SID");
882
+ })() : [
883
+ logonSid,
884
+ known.world,
885
+ ...writeSids
886
+ ]);
887
+ const tokenSlot = allocPtrSlot();
888
+ if (api.createRestrictedToken(currentToken, 13, 0, null, 0, null, restrictingSids.length / 16, restrictingSids, tokenSlot) === 0) throwLastError$1(api, "CreateRestrictedToken", `restricting SIDs: ${restrictingSids.length / 16}`);
889
+ const token = decodePtr(tokenSlot);
890
+ if (token === null) throwWin32(api, "CreateRestrictedToken", api.getLastError(), "null token handle");
891
+ return token;
892
+ }
893
+ //#endregion
894
+ //#region lib/types/grant.js
895
+ /**
896
+ * Server-side write-grant materialization. The sandbox seam holds one
897
+ * standing workspace grant per workspace and one revocable temp grant per
898
+ * live session/workspace pair. Workspace identities survive by deterministic
899
+ * derivation and their standing ACE; temp identities derive from random
900
+ * private paths and are deliberately new after a restart.
901
+ *
902
+ * Fail-closed: `add` throws on any grant failure and the caller disposes the
903
+ * instance (revoking every path granted so far); `dispose` revokes every
904
+ * revocable grant, leaves the standing workspace edits in place, and reports
905
+ * every cleanup failure.
906
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/grant
907
+ */
908
+ /**
909
+ * One write SID's provider-lifetime grant materialization: the parsed SID
910
+ * pointer plus every directory whose DACL currently carries its ACE and whose
911
+ * label ACL carries the Low mandatory label. Workspace paths are added
912
+ * STANDING (their security descriptor edits are the cross-session reuse cache
913
+ * and outlive the grant — dispose() skips revoking them, or the next
914
+ * provision would re-propagate the whole tree); temp paths are revocable
915
+ * (dispose() revokes them — an inheritable ACE must not outlive its
916
+ * session's temp directory). Create with {@link AclWriteGrant.create};
917
+ * dispose revokes the revocable paths and frees every SID.
918
+ */
919
+ var AclWriteGrant = class AclWriteGrant {
920
+ /** The write SID in SDDL string form. */
921
+ writeSid;
922
+ api;
923
+ sidPtr;
924
+ lowLabelSidPtr;
925
+ worldSidPtr;
926
+ revocablePaths = [];
927
+ standingPaths = [];
928
+ constructor(api, sidPtr, lowLabelSidPtr, worldSidPtr, writeSid) {
929
+ this.api = api;
930
+ this.sidPtr = sidPtr;
931
+ this.lowLabelSidPtr = lowLabelSidPtr;
932
+ this.worldSidPtr = worldSidPtr;
933
+ this.writeSid = writeSid;
934
+ }
935
+ /**
936
+ * Parse the SID string, create the Low integrity SID the grants label with
937
+ * and the world SID their ambient-delete deny names, and open the binding
938
+ * table (lazily, once per server). Fail-closed: any failure throws — nothing
939
+ * is granted yet.
940
+ * @param writeSid - the workspace (`S-1-4-x-y`) or temp (`S-1-4-x-y-1`) capability SID string.
941
+ * @param api - optional already-resolved bindings (tests).
942
+ * @returns the ready grant (no ACEs yet).
943
+ */
944
+ static create(writeSid, api) {
945
+ const bindings = api ?? win32Sync();
946
+ const sidSlot = allocPtrSlot();
947
+ if (bindings.convertStringSidToSidW(writeSid, sidSlot) === 0) throwLastError$1(bindings, "ConvertStringSidToSidW", writeSid);
948
+ const sidPtr = decodePtr(sidSlot);
949
+ if (sidPtr === null) throwLastError$1(bindings, "ConvertStringSidToSidW", `null SID for ${writeSid}`);
950
+ try {
951
+ const lowLabelSidPtr = makeWellKnownSid(bindings, 66);
952
+ try {
953
+ return new AclWriteGrant(bindings, sidPtr, lowLabelSidPtr, makeWellKnownSid(bindings, 1), writeSid);
954
+ } catch (error) {
955
+ bindings.localFree(lowLabelSidPtr);
956
+ throw error;
957
+ }
958
+ } catch (error) {
959
+ bindings.localFree(sidPtr);
960
+ throw error;
961
+ }
962
+ }
963
+ /**
964
+ * Grant the write ACE, the ambient-delete deny, and the Low mandatory label
965
+ * on one directory (idempotent: an already-standing exact ACE, deny, and
966
+ * label skip the eager full-tree re-propagation — see {@link grantWrite})
967
+ * and record the path for {@link dispose} unless it is standing. The path is
968
+ * recorded BEFORE the grant: a post-apply throw (a LocalFree failure after
969
+ * SetNamedSecurityInfoW succeeded) must still revoke it, and revoking an
970
+ * ungranted path is a no-op merge. Callers treat a throw as a failed
971
+ * materialization and dispose the instance to revoke the paths granted so
972
+ * far.
973
+ * @param path - the directory whose DACL and label gain the grant.
974
+ * @param standing - the edits outlive this grant (the workspace reuse
975
+ * cache; dispose() skips revoking it). Default false (revoked on
976
+ * dispose — the temp-directory lifecycle).
977
+ */
978
+ add(path, standing = false) {
979
+ (standing ? this.standingPaths : this.revocablePaths).push(path);
980
+ grantWrite(this.api, path, this.sidPtr, this.lowLabelSidPtr, this.worldSidPtr);
981
+ }
982
+ /** Every directory currently carrying the grant, in grant order. */
983
+ get paths() {
984
+ return [...this.standingPaths, ...this.revocablePaths];
985
+ }
986
+ /** Revoke every revocable grant (standing security descriptor edits stay) and free the SIDs; reports every cleanup failure. */
987
+ dispose() {
988
+ const failures = [];
989
+ for (const path of this.revocablePaths) try {
990
+ revokeWrite(this.api, path, this.sidPtr);
991
+ } catch (error) {
992
+ failures.push(error);
993
+ }
994
+ for (const [label, sidPtr] of [
995
+ ["write SID", this.sidPtr],
996
+ ["Low label SID", this.lowLabelSidPtr],
997
+ ["world SID", this.worldSidPtr]
998
+ ]) try {
999
+ if (!isNullPtr$1(this.api.localFree(sidPtr))) throwLastError$1(this.api, "LocalFree", label);
1000
+ } catch (error) {
1001
+ failures.push(error);
1002
+ }
1003
+ if (failures.length > 0) throw new AggregateError(failures, `AclWriteGrant dispose completed with ${failures.length} cleanup failure(s)`);
1004
+ }
1005
+ };
1006
+ //#endregion
1007
+ //#region lib/types/workspace-sid.js
1008
+ /**
1009
+ * The per-workspace write identity: a deterministic `S-1-4-x-y` SID derived
1010
+ * from the canonical workspace path, whose ACEs form that workspace's write
1011
+ * allowlist. Every confined execution of the same workspace — across
1012
+ * sessions, server restarts, and calls — carries the SAME write SID, so the
1013
+ * workspace-root ACE materializes once per workspace per machine (the
1014
+ * grant's exact-ACE skip then makes every later provision O(1)) instead of
1015
+ * once per session. The SID's power is defined solely by the ACEs that name
1016
+ * it (which exist only on the workspace tree and the session's private temp
1017
+ * directory), and only tokens minted for that workspace carry it — the SID
1018
+ * string itself is not a secret. Temporary directories use a separate,
1019
+ * per-directory identity from {@link tempWriteSid}; sharing the workspace
1020
+ * identity with temp would let sibling sessions write one another's temp
1021
+ * trees.
1022
+ *
1023
+ * The input MUST be the canonical workspace path (`realpathSync.native` on
1024
+ * Windows — the sandbox-policy `resolveWorkspaceRoot` already applies it):
1025
+ * canonicalization converges case/alias spellings, so two spellings of one
1026
+ * workspace derive one SID; an as-spelled fallback path would mint a second
1027
+ * identity for the same directory (self-healing, at the cost of one extra
1028
+ * tree propagation). Renaming the workspace directory derives a new SID —
1029
+ * the old standing ACEs are inert residue, and the next session re-propagates
1030
+ * once.
1031
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/workspace-sid
1032
+ */
1033
+ /**
1034
+ * Derive the workspace's write SID (`S-1-4-x-y`; subauthorities 30-bit,
1035
+ * matching the workspace-capability shape the token and ACE layers carry).
1036
+ * @param workspaceRoot - the canonical workspace path.
1037
+ * @returns the SDDL string form.
1038
+ */
1039
+ function workspaceWriteSid(workspaceRoot) {
1040
+ const digest = createHash("sha256").update(workspaceRoot, "utf8").digest();
1041
+ return `S-1-4-${digest.readUInt32LE(0) % (2 ** 30 - 1) + 1}-${digest.readUInt32LE(4) % (2 ** 30 - 1) + 1}`;
1042
+ }
1043
+ /**
1044
+ * Derive one private temp directory's write SID. The random directory path
1045
+ * is the capability identity; a fixed third subauthority domain-separates
1046
+ * the result from every two-subauthority workspace SID.
1047
+ * @param tempDir - the private temp directory's absolute path.
1048
+ * @returns the SDDL string form.
1049
+ */
1050
+ function tempWriteSid(tempDir) {
1051
+ const digest = createHash("sha256").update("temp\0", "utf8").update(tempDir, "utf8").digest();
1052
+ return `S-1-4-${digest.readUInt32LE(0) % (2 ** 30 - 1) + 1}-${digest.readUInt32LE(4) % (2 ** 30 - 1) + 1}-1`;
1053
+ }
1054
+ //#endregion
1055
+ //#region lib/types/index.js
1056
+ /**
1057
+ * Windows ACL write-restriction sandbox backend for the DeepSeek Harness
1058
+ * sandbox seam. Mirrors the mechanism of github.com/huoyaoyuan/
1059
+ * windows-acl-restrict-poc @ 10e4dfb (the fixed revision): a WRITE_RESTRICTED
1060
+ * token whose restricting SIDs include distinct workspace and temp write
1061
+ * SIDs that this sandbox adds to their owning directories' DACLs — the
1062
+ * intersection check then allows writes exactly where either capability has
1063
+ * a Write ACE, and nowhere else those SIDs are concerned (the check ALSO
1064
+ * inherits the ambient write ACEs of the other restricting SIDs — the
1065
+ * keep-alive group logon SID + Everyone; Authenticated Users, INTERACTIVE,
1066
+ * and LOCAL are absent from both lists — see the seam's dual-list contract
1067
+ * in `packages/sandbox/sandbox-local` and the package README's Modes section
1068
+ * for the complete boundary). The intersection covers only the object's own
1069
+ * access check, so the token is also lowered to Low integrity and every
1070
+ * granted directory carries a Low no-write-up label and the ambient-delete
1071
+ * deny the `acl` module documents. The write SID is the per-WORKSPACE identity
1072
+ * ({@link workspaceWriteSid}): deterministic from the canonical workspace
1073
+ * path, so the workspace-root ACE materializes once per workspace per
1074
+ * machine and every later provision hits the exact-ACE skip — the
1075
+ * grant-reuse story the per-session random SID paid a full tree propagation
1076
+ * per session for. Each private temp directory instead receives its own SID,
1077
+ * so sibling sessions sharing a workspace cannot enter one another's temp
1078
+ * trees. Unlike the POC, every API failure throws with the API
1079
+ * name and exact Win32 code; a child is NEVER spawned unrestricted.
1080
+ *
1081
+ * Known boundaries (inherent to restricted tokens, not this port):
1082
+ * - writes are restricted; reads, network, and process visibility are NOT
1083
+ * (WRITE_RESTRICTED intersects only write accesses);
1084
+ * - console isolation is unavailable — children share the host console
1085
+ * (CREATE_NO_WINDOW / CREATE_NEW_CONSOLE children die with
1086
+ * STATUS_DLL_INIT_FAILED under the restriction);
1087
+ * - the private temp directory and every writable directory must be owned by the
1088
+ * caller (owner-implicit WRITE_DAC);
1089
+ * - grants are standing ACE mutations on real directories. WORKSPACE grants
1090
+ * are deliberately never revoked — the ACE is the cross-session reuse
1091
+ * cache (revoking would force the next session to re-propagate the whole
1092
+ * tree). TEMP grants are revocable: dispose() removes them so a standing
1093
+ * inheritable ACE never outlives its session's temp directory. The
1094
+ * ambient temp root is never granted implicitly. With `manageDacls: false`
1095
+ * the CALLER owns the DACLs (the sandbox seam's grant reuse):
1096
+ * init()/dispose() skip grant/revoke entirely and the caller must not
1097
+ * revoke under live children.
1098
+ * @module @deepseek-ai/dsh-sandbox-windows-acl
1099
+ */
1100
+ /** Free one optional SID while retaining a failure for best-effort sibling cleanup. */
1101
+ function freeSidBestEffort(api, sidPtr, label, failures) {
1102
+ if (sidPtr === void 0) return;
1103
+ try {
1104
+ if (!isNullPtr$1(api.localFree(sidPtr))) throwLastError$1(api, "LocalFree", label);
1105
+ } catch (error) {
1106
+ failures.push(error);
1107
+ }
1108
+ }
1109
+ /**
1110
+ * One write-restricted sandbox instance: token + write-SID grants + spawn.
1111
+ * `init()` is fail-closed — any Win32 failure revokes the revocable (temp)
1112
+ * grants and throws; `dispose()` revokes the temp grants, leaves the
1113
+ * standing workspace ACEs in place (the cross-instance reuse cache), frees
1114
+ * every allocation, and reports every cleanup failure. With
1115
+ * `manageDacls: false` the caller owns the grants (the sandbox seam's grant
1116
+ * reuse): init() applies none and dispose() revokes none.
1117
+ */
1118
+ var AclSandbox = class {
1119
+ /** Absolute writable directories (constructor-validated). */
1120
+ writableDirs;
1121
+ /** The workspace SID string whose ACEs form the workspace allowlist. */
1122
+ writeSid;
1123
+ /** The private temp directory's write SID (workspace-write with temp only). */
1124
+ tempWriteSid;
1125
+ /** The file-effect mode — the restricted token's restricting-SID list selection. */
1126
+ mode;
1127
+ tempDirOption;
1128
+ manageDacls;
1129
+ tempDirResolved;
1130
+ api;
1131
+ token;
1132
+ writeSidPtr;
1133
+ tempWriteSidPtr;
1134
+ /** The well-known/logon SID allocations init() makes; freed by dispose() alongside the write SIDs. */
1135
+ sidAllocations = [];
1136
+ grantedPaths = [];
1137
+ constructor(options) {
1138
+ this.mode = options.mode;
1139
+ this.manageDacls = options.manageDacls ?? true;
1140
+ this.writableDirs = options.writableDirs.map((directory) => {
1141
+ const absolute = resolve(directory);
1142
+ if (!existsSync(absolute) || !statSync(absolute).isDirectory()) throw new Error(`AclSandbox writable dir does not exist or is not a directory: ${absolute}`);
1143
+ return absolute;
1144
+ });
1145
+ this.tempDirOption = options.tempDir;
1146
+ this.writeSid = options.writeSid;
1147
+ this.tempWriteSid = options.tempWriteSid;
1148
+ if (this.mode === "workspace-write" && this.writeSid === void 0) throw new Error("AclSandbox workspace-write requires a write SID — derive it from the workspace via workspaceWriteSid()");
1149
+ if (this.mode === "workspace-write" && this.tempDirOption === void 0) throw new Error("AclSandbox workspace-write requires an explicit private temp directory or null");
1150
+ if (this.mode === "read-only" && this.tempDirOption !== void 0 && this.tempDirOption !== null) throw new Error("AclSandbox read-only does not accept a temp directory");
1151
+ if (this.mode === "read-only" && (this.writeSid !== void 0 || this.tempWriteSid !== void 0)) throw new Error("AclSandbox read-only does not accept write SIDs");
1152
+ if (this.mode === "workspace-write" && this.tempDirOption !== null && this.tempWriteSid === void 0) throw new Error("AclSandbox workspace-write with temp requires a temp write SID — derive it via tempWriteSid()");
1153
+ if (this.tempDirOption === null && this.tempWriteSid !== void 0) throw new Error("AclSandbox temp write SID requires a temp directory");
1154
+ if (this.writeSid !== void 0 && this.tempWriteSid === this.writeSid) throw new Error("AclSandbox workspace and temp write SIDs must be distinct");
1155
+ }
1156
+ /** Resolved temp directory (available after init; null when temp grants are disabled). */
1157
+ get tempDir() {
1158
+ return this.tempDirResolved;
1159
+ }
1160
+ /** Create the restricted token and apply the capability-SID grants. Idempotent-unsafe: once per instance. */
1161
+ async init() {
1162
+ if (this.api !== void 0) throw new Error("AclSandbox is already initialized");
1163
+ const api = await win32();
1164
+ const currentToken = openCurrentProcessToken(api);
1165
+ let currentTokenOpen = true;
1166
+ let restrictedToken;
1167
+ try {
1168
+ const parseSid = (sid) => {
1169
+ const sidSlot = allocPtrSlot();
1170
+ if (api.convertStringSidToSidW(sid, sidSlot) === 0) throwLastError$1(api, "ConvertStringSidToSidW", sid);
1171
+ const parsedSid = decodePtr(sidSlot);
1172
+ if (parsedSid === null) throw new Win32Error("ConvertStringSidToSidW", api.getLastError(), sid);
1173
+ return parsedSid;
1174
+ };
1175
+ this.writeSidPtr = this.writeSid === void 0 ? void 0 : parseSid(this.writeSid);
1176
+ this.tempWriteSidPtr = this.tempWriteSid === void 0 ? void 0 : parseSid(this.tempWriteSid);
1177
+ const tempDir = this.mode === "read-only" || this.tempDirOption === null ? null : this.tempDirOption;
1178
+ /* v8 ignore next -- constructor validation requires workspace-write to supply
1179
+ an explicit temp directory or null; the other branches normalize to null. */
1180
+ if (tempDir === void 0) throw new Error("AclSandbox workspace-write temp directory was not resolved");
1181
+ if (tempDir !== null) {
1182
+ if (!existsSync(tempDir) || !statSync(tempDir).isDirectory()) throw new Error(`AclSandbox temp dir does not exist or is not a directory: ${tempDir}`);
1183
+ assertPrivateTempDisjoint(this.writableDirs, tempDir);
1184
+ }
1185
+ this.tempDirResolved = tempDir;
1186
+ const lowLabelSid = makeWellKnownSid(api, 66);
1187
+ const worldSid = makeWellKnownSid(api, 1);
1188
+ this.sidAllocations.push(lowLabelSid, worldSid);
1189
+ if (this.manageDacls) {
1190
+ if (this.writeSidPtr !== void 0) {
1191
+ for (const path of this.writableDirs) grantWrite(api, path, this.writeSidPtr, lowLabelSid, worldSid);
1192
+ if (tempDir !== null && this.tempWriteSidPtr !== void 0) {
1193
+ this.grantedPaths.push({
1194
+ path: tempDir,
1195
+ sidPtr: this.tempWriteSidPtr
1196
+ });
1197
+ grantWrite(api, tempDir, this.tempWriteSidPtr, lowLabelSid, worldSid);
1198
+ }
1199
+ }
1200
+ }
1201
+ const logonSid = findLogonSid(api, currentToken);
1202
+ this.sidAllocations.push(logonSid);
1203
+ restrictedToken = createRestrictedToken(api, currentToken, logonSid, [this.writeSidPtr, this.tempWriteSidPtr].filter((sid) => sid !== void 0), { world: worldSid }, this.mode);
1204
+ restrictTokenIntegrity(api, restrictedToken, lowLabelSid);
1205
+ this.token = restrictedToken;
1206
+ setTokenDefaultDaclGrant(api, restrictedToken, this.tempWriteSidPtr ?? this.writeSidPtr ?? worldSid);
1207
+ if (api.closeHandle(currentToken) === 0) throwLastError$1(api, "CloseHandle", "current process token");
1208
+ currentTokenOpen = false;
1209
+ this.api = api;
1210
+ } catch (error) {
1211
+ const cleanupFailures = [];
1212
+ if (currentTokenOpen && api.closeHandle(currentToken) === 0) cleanupFailures.push(new Win32Error("CloseHandle", api.getLastError(), "current process token after init failure"));
1213
+ if (restrictedToken !== void 0 && api.closeHandle(restrictedToken) === 0) cleanupFailures.push(new Win32Error("CloseHandle", api.getLastError(), "restricted token after init failure"));
1214
+ for (const grant of this.grantedPaths) try {
1215
+ revokeWrite(api, grant.path, grant.sidPtr);
1216
+ } catch (cleanupError) {
1217
+ cleanupFailures.push(cleanupError);
1218
+ }
1219
+ for (const [label, sidPtr] of [["workspace write SID", this.writeSidPtr], ["temp write SID", this.tempWriteSidPtr]]) freeSidBestEffort(api, sidPtr, label, cleanupFailures);
1220
+ for (const sidPtr of this.sidAllocations.splice(0)) freeSidBestEffort(api, sidPtr, "init SID allocation", cleanupFailures);
1221
+ this.token = void 0;
1222
+ this.writeSidPtr = void 0;
1223
+ this.tempWriteSidPtr = void 0;
1224
+ this.tempDirResolved = void 0;
1225
+ this.grantedPaths = [];
1226
+ if (cleanupFailures.length > 0) throw new AggregateError([error, ...cleanupFailures], `AclSandbox init failed and ${cleanupFailures.length} cleanup operation(s) also failed`);
1227
+ throw error;
1228
+ }
1229
+ }
1230
+ /**
1231
+ * Spawn a process under the restricted token. Fails closed: throws on every
1232
+ * Win32 failure; the child is never created unrestricted. With
1233
+ * `stdio: 'inherit'` the child shares the caller's stdio directly and is
1234
+ * placed in a kill-on-close job (dies with the caller). Call dispose() only
1235
+ * after all children have exited — revoking grants under a live child
1236
+ * removes its remaining write allowance.
1237
+ * @param options - the program, argv/cwd, and stdio shape.
1238
+ * @returns the running child.
1239
+ */
1240
+ spawn(options) {
1241
+ const api = this.api;
1242
+ const token = this.token;
1243
+ if (api === void 0 || token === void 0) throw new Error("AclSandbox is not initialized: call init() first");
1244
+ if (options.controlFileDescriptor !== void 0 && options.stdio !== "inherit") throw new Error("control pipe requires inherited stdio");
1245
+ const args = options.args ?? [];
1246
+ const cwd = options.cwd ?? process.cwd();
1247
+ if (options.stdio === "inherit") {
1248
+ const native = spawnSandboxedInherited(api, token, {
1249
+ command: options.command,
1250
+ args,
1251
+ cwd,
1252
+ ...options.controlFileDescriptor === void 0 ? {} : { controlFileDescriptor: options.controlFileDescriptor }
1253
+ });
1254
+ let exitCodePromise;
1255
+ return {
1256
+ pid: native.pid,
1257
+ wait: async () => {
1258
+ exitCodePromise ??= Promise.resolve(waitForExit(api, native.process));
1259
+ const exitCode = await exitCodePromise;
1260
+ if (api.closeHandle(native.job) === 0) throwLastError$1(api, "CloseHandle", "kill-on-close job");
1261
+ return {
1262
+ stdout: Buffer.alloc(0),
1263
+ stderr: Buffer.alloc(0),
1264
+ exitCode
1265
+ };
1266
+ }
1267
+ };
1268
+ }
1269
+ const native = spawnSandboxed(api, token, {
1270
+ command: options.command,
1271
+ args,
1272
+ cwd
1273
+ });
1274
+ const stdout = drainPipe(api, native.stdoutRead);
1275
+ const stderr = drainPipe(api, native.stderrRead);
1276
+ let exitCodePromise;
1277
+ return {
1278
+ pid: native.pid,
1279
+ wait: async () => {
1280
+ const stdoutBuffer = await stdout;
1281
+ const stderrBuffer = await stderr;
1282
+ exitCodePromise ??= Promise.resolve(waitForExit(api, native.process));
1283
+ return {
1284
+ stdout: stdoutBuffer,
1285
+ stderr: stderrBuffer,
1286
+ exitCode: await exitCodePromise
1287
+ };
1288
+ }
1289
+ };
1290
+ }
1291
+ /**
1292
+ * Revoke the revocable (temp) grants, free the SID, close the token; the
1293
+ * standing workspace ACEs stay (the reuse cache). Reports every cleanup
1294
+ * failure.
1295
+ */
1296
+ dispose() {
1297
+ const api = this.api;
1298
+ if (api === void 0) return;
1299
+ const failures = [];
1300
+ if (this.manageDacls) for (const grant of this.grantedPaths) try {
1301
+ revokeWrite(api, grant.path, grant.sidPtr);
1302
+ } catch (error) {
1303
+ failures.push(error);
1304
+ }
1305
+ for (const [label, sidPtr] of [["workspace write SID", this.writeSidPtr], ["temp write SID", this.tempWriteSidPtr]]) freeSidBestEffort(api, sidPtr, label, failures);
1306
+ const token = this.token;
1307
+ /* v8 ignore next -- init assigns this.api only after this.token, so an initialized instance always
1308
+ has its token; the guard mirrors the write-SID guard. */
1309
+ if (token !== void 0) try {
1310
+ if (api.closeHandle(token) === 0) throwLastError$1(api, "CloseHandle", "restricted token");
1311
+ } catch (error) {
1312
+ failures.push(error);
1313
+ }
1314
+ for (const sidPtr of this.sidAllocations.splice(0)) freeSidBestEffort(api, sidPtr, "init SID allocation", failures);
1315
+ this.api = void 0;
1316
+ this.token = void 0;
1317
+ this.writeSidPtr = void 0;
1318
+ this.tempWriteSidPtr = void 0;
1319
+ this.grantedPaths = [];
1320
+ if (failures.length > 0) throw new AggregateError(failures, `AclSandbox dispose completed with ${failures.length} cleanup failure(s)`);
1321
+ }
1322
+ };
1323
+ //#endregion
1324
+ export { assertTempRootOutsideWorkspace as a, AclWriteGrant as i, tempWriteSid as n, win32 as o, workspaceWriteSid as r, AclSandbox as t };