@deepseek-ai/dsh-sandbox-windows-acl 0.2.2-alpha.3 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/acl.ts ADDED
@@ -0,0 +1,448 @@
1
+ /**
2
+ * ACL editing helpers: grant/revoke a capability SID on a directory via
3
+ * SetEntriesInAclW + SetNamedSecurityInfoW (the same calls the POC uses, with
4
+ * the failure handling the POC lacks). Every API call is checked and every
5
+ * failure is reported with the API name, the exact Win32 code, the formatted
6
+ * system text, and the affected path.
7
+ *
8
+ * Each grant applies three edits in ONE SetNamedSecurityInfoW call: the
9
+ * capability-SID allow ACE, a Deny ACE that removes the ambient
10
+ * `FILE_DELETE_CHILD` right from the world SID, and a Low no-write-up
11
+ * mandatory label ({@link buildLowLabelAcl}). The deny is what keeps one
12
+ * granted root out of another's reach: Windows also authorizes a delete from
13
+ * the parent directory's `FILE_DELETE_CHILD` right, which the token's
14
+ * write-restricted intersection does not reach, and every granted root carries
15
+ * the Low label that clears the integrity check.
16
+ *
17
+ * Concurrency: grants are read-merge-write against the directory's CURRENT
18
+ * DACL, and the whole get-merge-set sequence runs under a per-path exclusive
19
+ * LockFileEx lock (see {@link withPathLock}) so concurrent sandbox instances
20
+ * cannot clobber each other's ACEs.
21
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/acl
22
+ */
23
+
24
+ import { createHash } from 'node:crypto'
25
+ import { mkdirSync } from 'node:fs'
26
+ import { dirname, join } from 'node:path'
27
+
28
+ import { allocOverlapped, allocPtrSlot, decodePtr, decodeUint8At, decodeUint16At, decodeUint32At, getTempPath, isInvalidHandle, isNullPtr, ptrAddress, sameSidAt, throwLastError, throwWin32 } from './ffi.ts'
29
+ import type { NativePtr, Win32Bindings } from './ffi.ts'
30
+ import * as abi from './win32-abi.ts'
31
+
32
+ /**
33
+ * Pack one EXPLICIT_ACCESS_W (48 bytes, layout verified by abi-probe.cpp):
34
+ * perms@0, mode@4, inheritance@8, Trustee@16 { pMultipleTrustee@16,
35
+ * MultipleTrusteeOperation@24, TrusteeForm@28, TrusteeType@32, ptstrName@40 }.
36
+ * `permissions` is the access mask; the POC passes 0 for REVOKE_ACCESS, which
37
+ * removes every ACE for the trustee. `inheritance` defaults to children of
38
+ * both kinds; the ambient-delete deny narrows it to containers because
39
+ * FILE_DELETE_CHILD is meaningless on a file and its bit would otherwise
40
+ * spread through the file's inherited mask.
41
+ * @param sidPtr - the trustee SID the entry names.
42
+ * @param mode - the access mode (GRANT_ACCESS, DENY_ACCESS, or REVOKE_ACCESS).
43
+ * @param permissions - the access mask to grant or deny (0 for REVOKE_ACCESS).
44
+ * @param inheritance - the ACE inheritance flags.
45
+ * @returns the packed entry buffer.
46
+ */
47
+ export function buildExplicitAccess(
48
+ sidPtr: NativePtr,
49
+ mode: number,
50
+ permissions: number,
51
+ inheritance: number = abi.SUB_CONTAINERS_AND_OBJECTS_INHERIT,
52
+ ): Buffer {
53
+ const entry = Buffer.alloc(abi.EXPLICIT_ACCESS_W_SIZE)
54
+ entry.writeUInt32LE(permissions, 0) // grfAccessPermissions
55
+ entry.writeUInt32LE(mode, 4) // grfAccessMode
56
+ entry.writeUInt32LE(inheritance, 8) // grfInheritance
57
+ entry.writeUInt32LE(abi.NO_MULTIPLE_TRUSTEE, 24) // Trustee.MultipleTrusteeOperation
58
+ entry.writeUInt32LE(abi.TRUSTEE_IS_SID, 28) // Trustee.TrusteeForm
59
+ entry.writeUInt32LE(abi.TRUSTEE_IS_UNKNOWN, 32) // Trustee.TrusteeType
60
+ entry.writeBigUInt64LE(ptrAddress(sidPtr), 40) // Trustee.ptstrName = the capability SID
61
+ return entry
62
+ }
63
+
64
+ /**
65
+ * One lock file per protected path: `<GetTempPathW()>\dsh-acl-locks\<first 16
66
+ * hex of sha256(lowercased path)>.lock`. The lock root derives from
67
+ * GetTempPathW (never from runner argv or DSH_HOME), and the lowercasing
68
+ * maps Windows's case-insensitive path spellings onto one lock.
69
+ * @param api - the binding table.
70
+ * @param path - the protected directory (absolute).
71
+ * @returns the lock file path for that directory.
72
+ */
73
+ export function lockFilePath(api: Win32Bindings, path: string): string {
74
+ const digest = createHash('sha256').update(path.toLowerCase()).digest('hex').slice(0, 16)
75
+ return join(getTempPath(api), 'dsh-acl-locks', `${digest}.lock`)
76
+ }
77
+
78
+ /**
79
+ * Run `action` holding the per-path exclusive lock: CreateFileW
80
+ * (OPEN_ALWAYS, shared read/write but NOT delete — a deletable lock file
81
+ * could be removed and recreated under the holder, letting two processes
82
+ * hold "the same" lock), then a one-byte LockFileEx
83
+ * (LOCKFILE_EXCLUSIVE_LOCK, zeroed OVERLAPPED = lock from offset 0 on the
84
+ * synchronous handle — see allocOverlapped for why not NULL), then
85
+ * UnlockFileEx + CloseHandle. Fail-closed: open/lock/unlock/close failures
86
+ * throw like every other Win32 call in this package; an `action` failure
87
+ * still unlocks (best-effort) and rethrows the original error.
88
+ * @param api - the binding table.
89
+ * @param path - the protected directory (absolute).
90
+ * @param action - the get-merge-set sequence to serialize.
91
+ * @returns the action's result.
92
+ */
93
+ export function withPathLock<T>(api: Win32Bindings, path: string, action: () => T): T {
94
+ const lockPath = lockFilePath(api, path)
95
+ mkdirSync(dirname(lockPath), { recursive: true })
96
+ const handle = api.createFileW(
97
+ lockPath,
98
+ abi.GENERIC_READ | abi.GENERIC_WRITE,
99
+ abi.FILE_SHARE_READ | abi.FILE_SHARE_WRITE,
100
+ null, abi.OPEN_ALWAYS, 0, null,
101
+ )
102
+ if (isInvalidHandle(handle)) throwLastError(api, 'CreateFileW', lockPath)
103
+ const overlapped = allocOverlapped() // stays zeroed: offset 0, hEvent NULL
104
+ if (api.lockFileEx(handle, abi.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, overlapped) === 0) {
105
+ const win32Code = api.getLastError()
106
+ api.closeHandle(handle) // best-effort on the lock-failure path
107
+ throwWin32(api, 'LockFileEx', win32Code, lockPath)
108
+ }
109
+
110
+ let result: T
111
+ try {
112
+ result = action()
113
+ } catch (error) {
114
+ // Best-effort release on the action-failure path: cleanup failures must
115
+ // not mask the action's error.
116
+ api.unlockFileEx(handle, 0, 1, 0, overlapped)
117
+ api.closeHandle(handle)
118
+ throw error
119
+ }
120
+ if (api.unlockFileEx(handle, 0, 1, 0, overlapped) === 0) {
121
+ const win32Code = api.getLastError()
122
+ api.closeHandle(handle) // best-effort on the unlock-failure path
123
+ throwWin32(api, 'UnlockFileEx', win32Code, lockPath)
124
+ }
125
+ if (api.closeHandle(handle) === 0) throwLastError(api, 'CloseHandle', `lock file ${lockPath}`)
126
+ return result
127
+ }
128
+
129
+ /**
130
+ * Read the directory's current explicit DACL and mandatory label via
131
+ * GetNamedSecurityInfoW.
132
+ * Allocation contract (the POC's RevokeAccess, minus its missing checks): the
133
+ * returned ACL pointer sits INSIDE the security descriptor allocation — only
134
+ * the descriptor may be LocalFree'd, and it must not be freed before
135
+ * SetEntriesInAclW has consumed the ACL. Freeing the ACL pointer itself
136
+ * corrupts the heap (verified the hard way).
137
+ * @param api - the binding table.
138
+ * @param path - the directory whose DACL and label are read.
139
+ * @returns the current explicit DACL and label ACL (null when the directory carries none) plus their owning descriptor.
140
+ */
141
+ function readCurrentSecurity(
142
+ api: Win32Bindings,
143
+ path: string,
144
+ ): { oldAcl: NativePtr | null; labelAcl: NativePtr | null; descriptor: NativePtr | null } {
145
+ const ownerSlot = allocPtrSlot()
146
+ const groupSlot = allocPtrSlot()
147
+ const daclSlot = allocPtrSlot()
148
+ const saclSlot = allocPtrSlot()
149
+ const descriptorSlot = allocPtrSlot()
150
+ const readResult = api.getNamedSecurityInfoW(
151
+ path, abi.SE_FILE_OBJECT, abi.DACL_SECURITY_INFORMATION | abi.LABEL_SECURITY_INFORMATION,
152
+ ownerSlot, groupSlot, daclSlot, saclSlot, descriptorSlot,
153
+ )
154
+ if (readResult !== abi.ERROR_SUCCESS) throwWin32(api, 'GetNamedSecurityInfoW', readResult, path)
155
+ return { oldAcl: decodePtr(daclSlot), labelAcl: decodePtr(saclSlot), descriptor: decodePtr(descriptorSlot) }
156
+ }
157
+
158
+ /**
159
+ * Build the Low mandatory label applied with every write grant: one
160
+ * SYSTEM_MANDATORY_LABEL_ACE naming `lowLabelSidPtr` with the no-write-up
161
+ * policy, inheriting to subcontainers and objects so later children carry the
162
+ * same label. The caller frees the returned ACL with LocalFree
163
+ * (SetNamedSecurityInfoW copies it); every Win32 call is checked and a
164
+ * half-built ACL is released before the error is thrown.
165
+ * @param api - the binding table.
166
+ * @param lowLabelSidPtr - the Low integrity SID (S-1-16-4096) the label names.
167
+ * @returns the ACL carrying the single inheritable label ACE.
168
+ */
169
+ export function buildLowLabelAcl(api: Win32Bindings, lowLabelSidPtr: NativePtr): NativePtr {
170
+ const sidLength = api.getLengthSid(lowLabelSidPtr)
171
+ if (sidLength === 0) throwLastError(api, 'GetLengthSid', 'Low mandatory label SID')
172
+ const aclLength = abi.ACL_HEADER_SIZE + abi.MANDATORY_ACE_OVERHEAD + sidLength
173
+ const acl = api.localAlloc(abi.LPTR, aclLength)
174
+ if (isNullPtr(acl)) throwLastError(api, 'LocalAlloc', 'Low mandatory label ACL')
175
+ if (api.initializeAcl(acl, aclLength, abi.ACL_REVISION) === 0) {
176
+ const win32Code = api.getLastError()
177
+ api.localFree(acl) // best-effort on the error path
178
+ throwWin32(api, 'InitializeAcl', win32Code, 'Low mandatory label ACL')
179
+ }
180
+ if (api.addMandatoryAce(
181
+ acl, abi.ACL_REVISION, abi.SUB_CONTAINERS_AND_OBJECTS_INHERIT, abi.SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, lowLabelSidPtr,
182
+ ) === 0) {
183
+ const win32Code = api.getLastError()
184
+ api.localFree(acl) // best-effort on the error path
185
+ throwWin32(api, 'AddMandatoryAce', win32Code, 'Low mandatory label ACL')
186
+ }
187
+ return acl
188
+ }
189
+
190
+ /**
191
+ * True when the label ACL already carries the EXACT label this module would
192
+ * add (mandatory-label ACE, OI|CI inheritance, no-write-up policy, the Low
193
+ * SID), so a re-grant can skip the eager full-tree propagation.
194
+ * @param labelAcl - the current label ACL pointer (from {@link readCurrentSecurity}).
195
+ * @param lowLabelSidPtr - the Low integrity SID to match.
196
+ * @returns whether the exact label ACE is already present.
197
+ */
198
+ function hasExactLabel(labelAcl: NativePtr, lowLabelSidPtr: NativePtr): boolean {
199
+ return hasExactEntry(
200
+ labelAcl, abi.SYSTEM_MANDATORY_LABEL_ACE_TYPE, abi.SUB_CONTAINERS_AND_OBJECTS_INHERIT,
201
+ abi.SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, lowLabelSidPtr,
202
+ )
203
+ }
204
+
205
+ /**
206
+ * The mandatory-label half of an apply: set the given label ACL, clear the
207
+ * label, or leave it untouched. `clear` is what a revoke does when the
208
+ * directory carries no other capability grant; `keep` is what it does while
209
+ * another grant still relies on the shared Low level.
210
+ */
211
+ type LabelEdit = { kind: 'apply'; acl: NativePtr } | { kind: 'clear' } | { kind: 'keep' }
212
+
213
+ /**
214
+ * Shared tail of grantWrite and revokeWrite: merge `entries` into `oldAcl`
215
+ * (null = no explicit DACL yet; SetEntriesInAclW builds one from scratch),
216
+ * free the descriptor before applying the merged ACL, apply the merged DACL
217
+ * together with the label edit in one SetNamedSecurityInfoW call, then free
218
+ * every ACL this call owns — checking each call and reporting with the
219
+ * caller's label. The entry count derives from the buffer, so a grant can
220
+ * carry its capability ACE and its ambient-delete deny in one merge.
221
+ * @param api - the binding table.
222
+ * @param path - the directory the DACL and label edits apply to.
223
+ * @param entries - packed EXPLICIT_ACCESS_W records to merge (grant, deny, or revoke).
224
+ * @param oldAcl - the current explicit DACL (from {@link readCurrentSecurity}).
225
+ * @param labelEdit - the label change to apply alongside the DACL.
226
+ * @param descriptor - the descriptor allocation owning `oldAcl`.
227
+ * @param label - the caller's name for error details.
228
+ */
229
+ function mergeAndApply(
230
+ api: Win32Bindings,
231
+ path: string,
232
+ entries: Buffer,
233
+ oldAcl: NativePtr | null,
234
+ labelEdit: LabelEdit,
235
+ descriptor: NativePtr | null,
236
+ label: string,
237
+ ): void {
238
+ const newAclSlot = allocPtrSlot()
239
+ const mergeResult = api.setEntriesInAclW(entries.length / abi.EXPLICIT_ACCESS_W_SIZE, entries, oldAcl, newAclSlot)
240
+ if (mergeResult !== abi.ERROR_SUCCESS) {
241
+ if (descriptor !== null) api.localFree(descriptor) // frees the ACL block too
242
+ if (labelEdit.kind === 'apply') api.localFree(labelEdit.acl)
243
+ throwWin32(api, 'SetEntriesInAclW', mergeResult, `${label}(${path})`)
244
+ }
245
+ const newAcl = decodePtr(newAclSlot)
246
+ if (newAcl === null) {
247
+ if (descriptor !== null) api.localFree(descriptor)
248
+ if (labelEdit.kind === 'apply') api.localFree(labelEdit.acl)
249
+ throwWin32(api, 'SetEntriesInAclW', api.getLastError(), `${label}(${path}): null new ACL`)
250
+ }
251
+
252
+ // The descriptor block (oldAcl included) is dead after the merge — free it
253
+ // before applying, exactly like the POC.
254
+ const freedDescriptor = descriptor !== null ? api.localFree(descriptor) : null
255
+ const applyResult = api.setNamedSecurityInfoW(
256
+ path, abi.SE_FILE_OBJECT,
257
+ labelEdit.kind === 'keep' ? abi.DACL_SECURITY_INFORMATION : abi.DACL_SECURITY_INFORMATION | abi.LABEL_SECURITY_INFORMATION,
258
+ null, null, newAcl, labelEdit.kind === 'apply' ? labelEdit.acl : null,
259
+ )
260
+ const freedNew = api.localFree(newAcl)
261
+ const freedLabel = labelEdit.kind === 'apply' ? api.localFree(labelEdit.acl) : null
262
+ if (applyResult !== abi.ERROR_SUCCESS) throwWin32(api, 'SetNamedSecurityInfoW', applyResult, `${label}(${path})`)
263
+ if (freedDescriptor !== null && !isNullPtr(freedDescriptor)) throwLastError(api, 'LocalFree', `${label}(${path}) descriptor`)
264
+ if (!isNullPtr(freedNew)) throwLastError(api, 'LocalFree', `${label}(${path}) new ACL`)
265
+ if (freedLabel !== null && !isNullPtr(freedLabel)) throwLastError(api, 'LocalFree', `${label}(${path}) label ACL`)
266
+ }
267
+
268
+ /**
269
+ * True when the explicit DACL already carries the EXACT entry
270
+ * `(aceType, inheritance, mask, trustee SID)`. Every field is read through
271
+ * koffi.decode at pointer offsets — no memcpy, no pointer arithmetic. The
272
+ * ACE's SID is INLINE (embedded in the ACE after the 4-byte mask — there is
273
+ * no pointer to read; reading one yields garbage addresses and crashed
274
+ * EqualSid, verified by gdb), so it is compared field-by-field against the
275
+ * trustee SID through bounded offset reads ({@link sameSidAt}). Allowed and
276
+ * denied ACEs share the Mask@4/SID@8 layout. A malformed header reads as "no
277
+ * exact entry" so the caller falls back to the merge-apply path, which owns
278
+ * the robust failure handling.
279
+ * @param acl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
280
+ * @param aceType - the ACE type to match.
281
+ * @param inheritance - the ACE inheritance flags to match.
282
+ * @param mask - the access mask to match.
283
+ * @param sidPtr - the trustee SID to match.
284
+ * @returns whether the exact entry is already present.
285
+ */
286
+ function hasExactEntry(acl: NativePtr, aceType: number, inheritance: number, mask: number, sidPtr: NativePtr): boolean {
287
+ const aclSize = decodeUint16At(acl, 2)
288
+ const aceCount = decodeUint16At(acl, 4)
289
+ if (aclSize < 8 || aclSize > 1_048_576) return false // implausible: fall back to the merge path
290
+ let offset = 8 // the first ACE follows the 8-byte ACL header
291
+ for (let index = 0; index < aceCount; index++) {
292
+ // ACE_HEADER: AceType@0, AceFlags@1, AceSize@2 (WORD); Mask@4, inline SID@8.
293
+ const aceSize = decodeUint16At(acl, offset + 2)
294
+ if (aceSize < 8 || offset + aceSize > aclSize) return false // implausible: fall back to the merge path
295
+ const exact = decodeUint8At(acl, offset) === aceType
296
+ && decodeUint8At(acl, offset + 1) === inheritance
297
+ && decodeUint32At(acl, offset + 4) === mask
298
+ if (exact && sameSidAt(acl, offset + 8, sidPtr, 0)) return true
299
+ offset += aceSize
300
+ }
301
+ return false
302
+ }
303
+
304
+ /**
305
+ * True when the explicit DACL already carries the EXACT write grant this
306
+ * module would add: the Allow ACE for {@link abi.GRANT_MASK} naming the
307
+ * capability SID.
308
+ * @param oldAcl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
309
+ * @param sidPtr - the capability SID to match.
310
+ * @returns whether the exact grant ACE is already present.
311
+ */
312
+ function hasExactGrant(oldAcl: NativePtr, sidPtr: NativePtr): boolean {
313
+ return hasExactEntry(oldAcl, abi.ACCESS_ALLOWED_ACE_TYPE, abi.SUB_CONTAINERS_AND_OBJECTS_INHERIT, abi.GRANT_MASK, sidPtr)
314
+ }
315
+
316
+ /**
317
+ * True when the explicit DACL already carries the EXACT ambient-delete deny:
318
+ * the container-inherited Deny ACE for {@link abi.FILE_DELETE_CHILD} naming
319
+ * the world SID. It is part of the idempotent skip, so a root granted by an
320
+ * earlier build receives the deny on its next provision.
321
+ * @param oldAcl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
322
+ * @param worldSidPtr - the Everyone SID the deny names.
323
+ * @returns whether the exact deny ACE is already present.
324
+ */
325
+ function hasExactDeny(oldAcl: NativePtr, worldSidPtr: NativePtr): boolean {
326
+ return hasExactEntry(oldAcl, abi.ACCESS_DENIED_ACE_TYPE, abi.CONTAINER_INHERIT_ACE, abi.FILE_DELETE_CHILD, worldSidPtr)
327
+ }
328
+
329
+ /**
330
+ * True when a capability grant for a SID OTHER than `sidPtr` stands on this
331
+ * DACL — the condition under which a revoke must leave the shared Low label in
332
+ * place, or the remaining grant's child would lose its write authority.
333
+ * @param oldAcl - the current explicit DACL pointer (from {@link readCurrentSecurity}).
334
+ * @param sidPtr - the capability SID being revoked.
335
+ * @returns whether another capability grant remains.
336
+ */
337
+ function hasForeignGrant(oldAcl: NativePtr, sidPtr: NativePtr): boolean {
338
+ const aclSize = decodeUint16At(oldAcl, 2)
339
+ const aceCount = decodeUint16At(oldAcl, 4)
340
+ if (aclSize < 8 || aclSize > 1_048_576) return false // implausible: leave the label alone
341
+ let offset = 8
342
+ for (let index = 0; index < aceCount; index++) {
343
+ const aceSize = decodeUint16At(oldAcl, offset + 2)
344
+ if (aceSize < 8 || offset + aceSize > aclSize) return false // implausible: leave the label alone
345
+ const isGrant = decodeUint8At(oldAcl, offset) === abi.ACCESS_ALLOWED_ACE_TYPE
346
+ && decodeUint32At(oldAcl, offset + 4) === abi.GRANT_MASK
347
+ if (isGrant && !sameSidAt(oldAcl, offset + 8, sidPtr, 0)) return true
348
+ offset += aceSize
349
+ }
350
+ return false
351
+ }
352
+
353
+ /**
354
+ * Grant `GRANT_MASK` (Write+Delete, displays as "Modify") to the capability SID
355
+ * on `path`, deny the world SID the ambient `FILE_DELETE_CHILD` right, and
356
+ * apply the Low mandatory label — one merge. The deny inherits to containers
357
+ * only: the right is evaluated on directories, and inheriting its bit onto
358
+ * files would deny every `FILE_ALL_ACCESS`/`GENERIC_ALL` open inside the root
359
+ * (0x40 is a member of that mask). The capability ACE's DELETE bit is then the
360
+ * only delete authority inside the root, so a file whose own DACL grants no
361
+ * DELETE is no longer deletable through its parent's rights.
362
+ *
363
+ * Idempotent: the exact ACE, deny, and label together SKIP the
364
+ * SetNamedSecurityInfoW apply, which would otherwise re-propagate the
365
+ * identical descriptor across the whole tree (eager inheritance; minutes on
366
+ * large workspaces). Otherwise read-merge-write, so pre-existing explicit ACEs
367
+ * survive (same shape as {@link revokeWrite}). Runs under the per-path lock.
368
+ * The directory must be owned by the caller AND grant WRITE_OWNER (the label
369
+ * lives in the SACL; owner-implicit rights cover only READ_CONTROL and
370
+ * WRITE_DAC) — a Full-control workspace satisfies both.
371
+ * @param api - the binding table.
372
+ * @param path - the directory whose DACL and label gain the grant (the workspace or temp root).
373
+ * @param sidPtr - the capability SID the ACE names.
374
+ * @param lowLabelSidPtr - the Low integrity SID the mandatory label names.
375
+ * @param worldSidPtr - the Everyone SID the ambient-delete deny names.
376
+ */
377
+ export function grantWrite(
378
+ api: Win32Bindings,
379
+ path: string,
380
+ sidPtr: NativePtr,
381
+ lowLabelSidPtr: NativePtr,
382
+ worldSidPtr: NativePtr,
383
+ ): void {
384
+ withPathLock(api, path, () => {
385
+ const { oldAcl, labelAcl, descriptor } = readCurrentSecurity(api, path)
386
+ if (oldAcl !== null && labelAcl !== null
387
+ && hasExactGrant(oldAcl, sidPtr) && hasExactDeny(oldAcl, worldSidPtr)
388
+ && hasExactLabel(labelAcl, lowLabelSidPtr)) {
389
+ // The exact ACE, deny, and label stand: releasing the descriptor is the whole operation.
390
+ if (descriptor !== null) {
391
+ const freed = api.localFree(descriptor)
392
+ if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', `grantWrite(${path}) descriptor`)
393
+ }
394
+ return
395
+ }
396
+ let label: NativePtr
397
+ try {
398
+ label = buildLowLabelAcl(api, lowLabelSidPtr)
399
+ } catch (error) {
400
+ // The read already owns a descriptor allocation; release it before the
401
+ // label failure propagates.
402
+ if (descriptor !== null) api.localFree(descriptor)
403
+ throw error
404
+ }
405
+ mergeAndApply(
406
+ api, path,
407
+ Buffer.concat([
408
+ buildExplicitAccess(worldSidPtr, abi.DENY_ACCESS, abi.FILE_DELETE_CHILD, abi.CONTAINER_INHERIT_ACE),
409
+ buildExplicitAccess(sidPtr, abi.GRANT_ACCESS, abi.GRANT_MASK),
410
+ ]),
411
+ oldAcl, { kind: 'apply', acl: label }, descriptor, 'grantWrite',
412
+ )
413
+ })
414
+ }
415
+
416
+ /**
417
+ * Remove every ACE for the capability SID from the directory DACL (REVOKE_ACCESS
418
+ * merge — other entries are preserved). The shared Low label is cleared only
419
+ * when no other capability grant remains on the directory: two grants may
420
+ * target one directory, and the surviving one still needs the label for its
421
+ * child's writes. Returns whether an ACE removal was attempted (false when the
422
+ * directory carries no DACL at all).
423
+ *
424
+ * Runs under the per-path lock (the whole get-merge-set sequence); the
425
+ * descriptor/ACL allocation contract lives on {@link readCurrentSecurity}.
426
+ * @param api - the binding table.
427
+ * @param path - the directory whose DACL loses the capability-SID ACEs.
428
+ * @param sidPtr - the capability SID whose ACEs are removed.
429
+ * @returns whether an ACE removal was attempted (false when the directory carries no DACL at all).
430
+ */
431
+ export function revokeWrite(api: Win32Bindings, path: string, sidPtr: NativePtr): boolean {
432
+ return withPathLock(api, path, () => {
433
+ const { oldAcl, descriptor } = readCurrentSecurity(api, path)
434
+ if (oldAcl === null) {
435
+ if (descriptor !== null) {
436
+ const freed = api.localFree(descriptor)
437
+ if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', `revokeWrite(${path}) descriptor`)
438
+ }
439
+ return false
440
+ }
441
+ mergeAndApply(
442
+ api, path, buildExplicitAccess(sidPtr, abi.REVOKE_ACCESS, 0), oldAcl,
443
+ hasForeignGrant(oldAcl, sidPtr) ? { kind: 'keep' } : { kind: 'clear' },
444
+ descriptor, 'revokeWrite',
445
+ )
446
+ return true
447
+ })
448
+ }