@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/index.ts ADDED
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Windows ACL write-restriction sandbox backend for the DeepSeek Harness
3
+ * sandbox seam. Mirrors the mechanism of github.com/huoyaoyuan/
4
+ * windows-acl-restrict-poc @ 10e4dfb (the fixed revision): a WRITE_RESTRICTED
5
+ * token whose restricting SIDs include distinct workspace and temp write
6
+ * SIDs that this sandbox adds to their owning directories' DACLs — the
7
+ * intersection check then allows writes exactly where either capability has
8
+ * a Write ACE, and nowhere else those SIDs are concerned (the check ALSO
9
+ * inherits the ambient write ACEs of the other restricting SIDs — the
10
+ * keep-alive group logon SID + Everyone; Authenticated Users, INTERACTIVE,
11
+ * and LOCAL are absent from both lists — see the seam's dual-list contract
12
+ * in `packages/sandbox/sandbox-local` and the package README's Modes section
13
+ * for the complete boundary). The intersection covers only the object's own
14
+ * access check, so the token is also lowered to Low integrity and every
15
+ * granted directory carries a Low no-write-up label and the ambient-delete
16
+ * deny the `acl` module documents. The write SID is the per-WORKSPACE identity
17
+ * ({@link workspaceWriteSid}): deterministic from the canonical workspace
18
+ * path, so the workspace-root ACE materializes once per workspace per
19
+ * machine and every later provision hits the exact-ACE skip — the
20
+ * grant-reuse story the per-session random SID paid a full tree propagation
21
+ * per session for. Each private temp directory instead receives its own SID,
22
+ * so sibling sessions sharing a workspace cannot enter one another's temp
23
+ * trees. Unlike the POC, every API failure throws with the API
24
+ * name and exact Win32 code; a child is NEVER spawned unrestricted.
25
+ *
26
+ * Known boundaries (inherent to restricted tokens, not this port):
27
+ * - writes are restricted; reads, network, and process visibility are NOT
28
+ * (WRITE_RESTRICTED intersects only write accesses);
29
+ * - console isolation is unavailable — children share the host console
30
+ * (CREATE_NO_WINDOW / CREATE_NEW_CONSOLE children die with
31
+ * STATUS_DLL_INIT_FAILED under the restriction);
32
+ * - the private temp directory and every writable directory must be owned by the
33
+ * caller (owner-implicit WRITE_DAC);
34
+ * - grants are standing ACE mutations on real directories. WORKSPACE grants
35
+ * are deliberately never revoked — the ACE is the cross-session reuse
36
+ * cache (revoking would force the next session to re-propagate the whole
37
+ * tree). TEMP grants are revocable: dispose() removes them so a standing
38
+ * inheritable ACE never outlives its session's temp directory. The
39
+ * ambient temp root is never granted implicitly. With `manageDacls: false`
40
+ * the CALLER owns the DACLs (the sandbox seam's grant reuse):
41
+ * init()/dispose() skip grant/revoke entirely and the caller must not
42
+ * revoke under live children.
43
+ * @module @deepseek-ai/dsh-sandbox-windows-acl
44
+ */
45
+
46
+ import { existsSync, statSync } from 'node:fs'
47
+ import { resolve } from 'node:path'
48
+ import { Win32Error } from '@deepseek-ai/dsh-win32-process'
49
+
50
+ import { grantWrite, revokeWrite } from './acl.ts'
51
+ import { allocPtrSlot, decodePtr, isNullPtr, throwLastError, win32 } from './ffi.ts'
52
+ import type { NativePtr, Win32Bindings } from './ffi.ts'
53
+ import { assertPrivateTempDisjoint } from './path-boundary.ts'
54
+ import { drainPipe, spawnSandboxed, spawnSandboxedInherited, waitForExit } from './spawn.ts'
55
+ import { createRestrictedToken, findLogonSid, makeWellKnownSid, openCurrentProcessToken, restrictTokenIntegrity, setTokenDefaultDaclGrant } from './token.ts'
56
+ import * as abi from './win32-abi.ts'
57
+
58
+ export { AclWriteGrant } from './grant.ts'
59
+ export { assertTempRootOutsideWorkspace, isTempRootInsideWorkspace } from './path-boundary.ts'
60
+ export { tempWriteSid, workspaceWriteSid } from './workspace-sid.ts'
61
+ export { ACL_DIAGNOSIS_SKILL, registerAclDiagnosisSkill } from './acl-skill.ts'
62
+ /** Construction options: the workspace/temp allowlists and their distinct SID identities. */
63
+ export interface AclSandboxOptions {
64
+ /** Directories the confined child may write into (must exist and be caller-owned). */
65
+ writableDirs: readonly string[]
66
+ /**
67
+ * Existing private temp directory to grant. Workspace-write callers must
68
+ * pass it explicitly or pass null to disable temp writes; the ambient temp
69
+ * root is never an implicit grant. Read-only accepts only null/undefined.
70
+ */
71
+ tempDir?: string | null
72
+ /**
73
+ * The write SID forming the workspace-write allowlist: REQUIRED under
74
+ * workspace-write, ignored (and must be absent) under read-only. Callers
75
+ * derive it from the workspace via {@link workspaceWriteSid} — the identity
76
+ * is per workspace, not per sandbox instance, so the workspace-root ACE
77
+ * outlives every instance and later provisions hit the exact-ACE skip.
78
+ */
79
+ writeSid?: string
80
+ /**
81
+ * The private temp directory's write SID. Required whenever
82
+ * workspace-write grants a temp directory, absent otherwise. It must be
83
+ * distinct from {@link writeSid}, so sibling sessions sharing a workspace
84
+ * cannot use the standing workspace capability in one another's temp tree.
85
+ */
86
+ tempWriteSid?: string
87
+ /**
88
+ * The file-effect mode this instance confines under — selects the
89
+ * restricted token's restricting-SID list (I for read-only, J for
90
+ * workspace-write) and MUST match the grant shape: read-only pairs with
91
+ * zero grants. The runner validates the argv-borne mode string at its
92
+ * boundary; this typed seam trusts the union.
93
+ */
94
+ mode: 'read-only' | 'workspace-write'
95
+ /**
96
+ * Whether this instance owns its DACL grants (default true). False means
97
+ * the CALLER has already materialized the ACEs (the sandbox seam's
98
+ * workspace/temp capability lifecycle): init()/dispose() skip grant/revoke entirely —
99
+ * the caller holds the grants for its own lifetime and revokes them.
100
+ */
101
+ manageDacls?: boolean
102
+ }
103
+
104
+ /** Per-spawn options: the program, its argv/cwd, and the stdio shape. */
105
+ export interface AclSandboxSpawnOptions {
106
+ /** Program to run (resolved via PATH search when unqualified, like CreateProcess). */
107
+ command: string
108
+ /** Arguments, quoted per CommandLineToArgvW rules. */
109
+ args?: readonly string[]
110
+ /** Working directory; defaults to the caller's cwd. */
111
+ cwd?: string
112
+ /**
113
+ * 'pipe' (default): capture stdout/stderr via anonymous pipes.
114
+ * 'inherit': the child inherits the caller's stdio directly (runner usage —
115
+ * bytes flow straight through), always wrapped in a kill-on-close job so the
116
+ * child dies with the caller; stdout/stderr in the result are empty.
117
+ */
118
+ stdio?: 'pipe' | 'inherit'
119
+ /** Control pipe forwarded to the same payload descriptor in inherited-stdio mode. */
120
+ controlFileDescriptor?: 7
121
+ }
122
+
123
+ /** A settled confined child: captured stdio and the exit code. */
124
+ export interface AclSandboxChildResult {
125
+ stdout: Buffer
126
+ stderr: Buffer
127
+ exitCode: number
128
+ }
129
+
130
+ /** A running confined child: its pid and a settlement promise. */
131
+ export interface AclSandboxChild {
132
+ /** Child process id. */
133
+ pid: number
134
+ /** Resolve stdout/stderr and the exit code once the child exits. */
135
+ wait(): Promise<AclSandboxChildResult>
136
+ }
137
+
138
+ /** Free one optional SID while retaining a failure for best-effort sibling cleanup. */
139
+ function freeSidBestEffort(
140
+ api: Win32Bindings,
141
+ sidPtr: NativePtr | undefined,
142
+ label: string,
143
+ failures: unknown[],
144
+ ): void {
145
+ if (sidPtr === undefined) return
146
+ try {
147
+ const freed = api.localFree(sidPtr)
148
+ if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', label)
149
+ } catch (error) {
150
+ failures.push(error)
151
+ }
152
+ }
153
+
154
+ /**
155
+ * One write-restricted sandbox instance: token + write-SID grants + spawn.
156
+ * `init()` is fail-closed — any Win32 failure revokes the revocable (temp)
157
+ * grants and throws; `dispose()` revokes the temp grants, leaves the
158
+ * standing workspace ACEs in place (the cross-instance reuse cache), frees
159
+ * every allocation, and reports every cleanup failure. With
160
+ * `manageDacls: false` the caller owns the grants (the sandbox seam's grant
161
+ * reuse): init() applies none and dispose() revokes none.
162
+ */
163
+ export class AclSandbox {
164
+ /** Absolute writable directories (constructor-validated). */
165
+ readonly writableDirs: string[]
166
+ /** The workspace SID string whose ACEs form the workspace allowlist. */
167
+ readonly writeSid: string | undefined
168
+ /** The private temp directory's write SID (workspace-write with temp only). */
169
+ readonly tempWriteSid: string | undefined
170
+ /** The file-effect mode — the restricted token's restricting-SID list selection. */
171
+ readonly mode: 'read-only' | 'workspace-write'
172
+ private readonly tempDirOption: string | null | undefined
173
+ private readonly manageDacls: boolean
174
+ private tempDirResolved: string | null | undefined
175
+ private api: Win32Bindings | undefined
176
+ private token: NativePtr | undefined
177
+ private writeSidPtr: NativePtr | undefined
178
+ private tempWriteSidPtr: NativePtr | undefined
179
+ /** The well-known/logon SID allocations init() makes; freed by dispose() alongside the write SIDs. */
180
+ private sidAllocations: NativePtr[] = []
181
+ private grantedPaths: Array<{ path: string; sidPtr: NativePtr }> = []
182
+
183
+ constructor(options: AclSandboxOptions) {
184
+ this.mode = options.mode
185
+ this.manageDacls = options.manageDacls ?? true
186
+ this.writableDirs = options.writableDirs.map((directory) => {
187
+ const absolute = resolve(directory)
188
+ if (!existsSync(absolute) || !statSync(absolute).isDirectory()) {
189
+ throw new Error(`AclSandbox writable dir does not exist or is not a directory: ${absolute}`)
190
+ }
191
+ return absolute
192
+ })
193
+ this.tempDirOption = options.tempDir
194
+ this.writeSid = options.writeSid
195
+ this.tempWriteSid = options.tempWriteSid
196
+ if (this.mode === 'workspace-write' && this.writeSid === undefined) {
197
+ throw new Error('AclSandbox workspace-write requires a write SID — derive it from the workspace via workspaceWriteSid()')
198
+ }
199
+ if (this.mode === 'workspace-write' && this.tempDirOption === undefined) {
200
+ throw new Error('AclSandbox workspace-write requires an explicit private temp directory or null')
201
+ }
202
+ if (this.mode === 'read-only' && this.tempDirOption !== undefined && this.tempDirOption !== null) {
203
+ throw new Error('AclSandbox read-only does not accept a temp directory')
204
+ }
205
+ if (this.mode === 'read-only' && (this.writeSid !== undefined || this.tempWriteSid !== undefined)) {
206
+ throw new Error('AclSandbox read-only does not accept write SIDs')
207
+ }
208
+ if (this.mode === 'workspace-write' && this.tempDirOption !== null && this.tempWriteSid === undefined) {
209
+ throw new Error('AclSandbox workspace-write with temp requires a temp write SID — derive it via tempWriteSid()')
210
+ }
211
+ if (this.tempDirOption === null && this.tempWriteSid !== undefined) {
212
+ throw new Error('AclSandbox temp write SID requires a temp directory')
213
+ }
214
+ if (this.writeSid !== undefined && this.tempWriteSid === this.writeSid) {
215
+ throw new Error('AclSandbox workspace and temp write SIDs must be distinct')
216
+ }
217
+ }
218
+
219
+ /** Resolved temp directory (available after init; null when temp grants are disabled). */
220
+ get tempDir(): string | null | undefined {
221
+ return this.tempDirResolved
222
+ }
223
+
224
+ /** Create the restricted token and apply the capability-SID grants. Idempotent-unsafe: once per instance. */
225
+ async init(): Promise<void> {
226
+ if (this.api !== undefined) throw new Error('AclSandbox is already initialized')
227
+ const api = await win32()
228
+ const currentToken = openCurrentProcessToken(api)
229
+ let currentTokenOpen = true
230
+ let restrictedToken: NativePtr | undefined
231
+ try {
232
+ const parseSid = (sid: string): NativePtr => {
233
+ const sidSlot = allocPtrSlot()
234
+ if (api.convertStringSidToSidW(sid, sidSlot) === 0) {
235
+ throwLastError(api, 'ConvertStringSidToSidW', sid)
236
+ }
237
+ const parsedSid = decodePtr(sidSlot)
238
+ if (parsedSid === null) throw new Win32Error('ConvertStringSidToSidW', api.getLastError(), sid)
239
+ return parsedSid
240
+ }
241
+ this.writeSidPtr = this.writeSid === undefined ? undefined : parseSid(this.writeSid)
242
+ this.tempWriteSidPtr = this.tempWriteSid === undefined ? undefined : parseSid(this.tempWriteSid)
243
+
244
+ const tempDir = this.mode === 'read-only' || this.tempDirOption === null ? null : this.tempDirOption
245
+ /* v8 ignore next -- constructor validation requires workspace-write to supply
246
+ an explicit temp directory or null; the other branches normalize to null. */
247
+ if (tempDir === undefined) throw new Error('AclSandbox workspace-write temp directory was not resolved')
248
+ if (tempDir !== null) {
249
+ if (!existsSync(tempDir) || !statSync(tempDir).isDirectory()) {
250
+ throw new Error(`AclSandbox temp dir does not exist or is not a directory: ${tempDir}`)
251
+ }
252
+ assertPrivateTempDisjoint(this.writableDirs, tempDir)
253
+ }
254
+ this.tempDirResolved = tempDir
255
+
256
+ // manageDacls: false — the caller (the sandbox seam's grant) already
257
+ // materialized the ACEs; this instance must neither add nor remove any.
258
+ // When this instance owns the DACLs, writableDir ACEs are STANDING (the
259
+ // per-workspace reuse cache — dispose() never revokes them, or the next
260
+ // provision would re-propagate the whole tree) and the temp ACE is
261
+ // REVOCABLE (dispose() removes it before the private directory is
262
+ // deleted; the ambient temp root is never granted).
263
+ // The Low label SID and the world SID the grants deny and label with.
264
+ const lowLabelSid = makeWellKnownSid(api, abi.WinLowLabelSid)
265
+ const worldSid = makeWellKnownSid(api, abi.WinWorldSid)
266
+ this.sidAllocations.push(lowLabelSid, worldSid)
267
+
268
+ if (this.manageDacls) {
269
+ if (this.writeSidPtr !== undefined) {
270
+ for (const path of this.writableDirs) {
271
+ grantWrite(api, path, this.writeSidPtr, lowLabelSid, worldSid)
272
+ }
273
+ if (tempDir !== null && this.tempWriteSidPtr !== undefined) {
274
+ // Record BEFORE granting: grantWrite can throw after a successful
275
+ // apply (a LocalFree failure), and the fail-closed catch must still
276
+ // revoke that path (revoking an ungranted path is a no-op merge).
277
+ this.grantedPaths.push({ path: tempDir, sidPtr: this.tempWriteSidPtr })
278
+ grantWrite(api, tempDir, this.tempWriteSidPtr, lowLabelSid, worldSid)
279
+ }
280
+ }
281
+ }
282
+ const logonSid = findLogonSid(api, currentToken)
283
+ this.sidAllocations.push(logonSid)
284
+ const writeSids = [this.writeSidPtr, this.tempWriteSidPtr].filter((sid): sid is NativePtr => sid !== undefined)
285
+ restrictedToken = createRestrictedToken(
286
+ api, currentToken, logonSid, writeSids,
287
+ { world: worldSid },
288
+ this.mode,
289
+ )
290
+ restrictTokenIntegrity(api, restrictedToken, lowLabelSid)
291
+ this.token = restrictedToken
292
+ // The restricted token's default DACL still names only the user's
293
+ // ambient SIDs — none of the restricting SIDs. Every NEW object the
294
+ // confined process creates (anonymous stdio pipes, sync objects) takes
295
+ // its DACL from that default, so the write pass-2 check would deny
296
+ // pipe creation (ERROR_ACCESS_DENIED; Node EPERM) and break every
297
+ // piped-stdio grandchild spawn. Merge a full-access ACE for a
298
+ // restricting SID (the PRIVATE temp SID when present, otherwise the
299
+ // workspace SID, or Everyone under read-only): new-object creation
300
+ // stays gated by the parent object's DACL, while the new object's own
301
+ // DACL passes pass-2. Choosing the temp SID prevents default-DACL
302
+ // objects in one session's temp tree from acquiring the shared
303
+ // workspace capability.
304
+ setTokenDefaultDaclGrant(api, restrictedToken, this.tempWriteSidPtr ?? this.writeSidPtr ?? worldSid)
305
+ if (api.closeHandle(currentToken) === 0) throwLastError(api, 'CloseHandle', 'current process token')
306
+ currentTokenOpen = false
307
+ this.api = api
308
+ } catch (error) {
309
+ // Fail-closed cleanup: never leave a revocable (temp) grant or SID
310
+ // allocation behind a failed init. Standing workspace ACEs are NOT
311
+ // revoked — they are the intended end state (the reuse cache), not an
312
+ // error artifact.
313
+ const cleanupFailures: unknown[] = []
314
+ if (currentTokenOpen && api.closeHandle(currentToken) === 0) {
315
+ cleanupFailures.push(new Win32Error('CloseHandle', api.getLastError(), 'current process token after init failure'))
316
+ }
317
+ if (restrictedToken !== undefined && api.closeHandle(restrictedToken) === 0) {
318
+ cleanupFailures.push(new Win32Error('CloseHandle', api.getLastError(), 'restricted token after init failure'))
319
+ }
320
+ for (const grant of this.grantedPaths) {
321
+ try {
322
+ revokeWrite(api, grant.path, grant.sidPtr)
323
+ } catch (cleanupError) {
324
+ cleanupFailures.push(cleanupError)
325
+ }
326
+ }
327
+ for (const [label, sidPtr] of [['workspace write SID', this.writeSidPtr], ['temp write SID', this.tempWriteSidPtr]] as const) {
328
+ freeSidBestEffort(api, sidPtr, label, cleanupFailures)
329
+ }
330
+ for (const sidPtr of this.sidAllocations.splice(0)) {
331
+ freeSidBestEffort(api, sidPtr, 'init SID allocation', cleanupFailures)
332
+ }
333
+ this.token = undefined
334
+ this.writeSidPtr = undefined
335
+ this.tempWriteSidPtr = undefined
336
+ this.tempDirResolved = undefined
337
+ this.grantedPaths = []
338
+ if (cleanupFailures.length > 0) {
339
+ throw new AggregateError(
340
+ [error, ...cleanupFailures],
341
+ `AclSandbox init failed and ${cleanupFailures.length} cleanup operation(s) also failed`,
342
+ )
343
+ }
344
+ throw error
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Spawn a process under the restricted token. Fails closed: throws on every
350
+ * Win32 failure; the child is never created unrestricted. With
351
+ * `stdio: 'inherit'` the child shares the caller's stdio directly and is
352
+ * placed in a kill-on-close job (dies with the caller). Call dispose() only
353
+ * after all children have exited — revoking grants under a live child
354
+ * removes its remaining write allowance.
355
+ * @param options - the program, argv/cwd, and stdio shape.
356
+ * @returns the running child.
357
+ */
358
+ spawn(options: AclSandboxSpawnOptions): AclSandboxChild {
359
+ const api = this.api
360
+ const token = this.token
361
+ if (api === undefined || token === undefined) throw new Error('AclSandbox is not initialized: call init() first')
362
+ if (options.controlFileDescriptor !== undefined && options.stdio !== 'inherit') {
363
+ throw new Error('control pipe requires inherited stdio')
364
+ }
365
+ const args = options.args ?? []
366
+ const cwd = options.cwd ?? process.cwd()
367
+
368
+ if (options.stdio === 'inherit') {
369
+ const native = spawnSandboxedInherited(api, token, {
370
+ command: options.command, args, cwd,
371
+ ...options.controlFileDescriptor === undefined ? {} : { controlFileDescriptor: options.controlFileDescriptor },
372
+ })
373
+ let exitCodePromise: Promise<number> | undefined
374
+ return {
375
+ pid: native.pid,
376
+ wait: async () => {
377
+ exitCodePromise ??= Promise.resolve(waitForExit(api, native.process))
378
+ const exitCode = await exitCodePromise
379
+ if (api.closeHandle(native.job) === 0) throwLastError(api, 'CloseHandle', 'kill-on-close job')
380
+ return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), exitCode }
381
+ },
382
+ }
383
+ }
384
+
385
+ const native = spawnSandboxed(api, token, { command: options.command, args, cwd })
386
+ const stdout = drainPipe(api, native.stdoutRead)
387
+ const stderr = drainPipe(api, native.stderrRead)
388
+ // waitForExit is deliberately NOT started here: WaitForSingleObject blocks
389
+ // the thread and would starve the drains while the child is still running
390
+ // (pipe-buffer deadlock). The drains resolve only after the child closed
391
+ // its pipe ends — by then the wait returns immediately.
392
+ let exitCodePromise: Promise<number> | undefined
393
+ return {
394
+ pid: native.pid,
395
+ wait: async () => {
396
+ const stdoutBuffer = await stdout
397
+ const stderrBuffer = await stderr
398
+ exitCodePromise ??= Promise.resolve(waitForExit(api, native.process))
399
+ return { stdout: stdoutBuffer, stderr: stderrBuffer, exitCode: await exitCodePromise }
400
+ },
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Revoke the revocable (temp) grants, free the SID, close the token; the
406
+ * standing workspace ACEs stay (the reuse cache). Reports every cleanup
407
+ * failure.
408
+ */
409
+ dispose(): void {
410
+ const api = this.api
411
+ if (api === undefined) return
412
+ const failures: unknown[] = []
413
+ if (this.manageDacls) {
414
+ for (const grant of this.grantedPaths) {
415
+ try {
416
+ revokeWrite(api, grant.path, grant.sidPtr)
417
+ } catch (error) {
418
+ failures.push(error)
419
+ }
420
+ }
421
+ }
422
+ for (const [label, sidPtr] of [['workspace write SID', this.writeSidPtr], ['temp write SID', this.tempWriteSidPtr]] as const) {
423
+ freeSidBestEffort(api, sidPtr, label, failures)
424
+ }
425
+ const token = this.token
426
+ /* v8 ignore next -- init assigns this.api only after this.token, so an initialized instance always
427
+ has its token; the guard mirrors the write-SID guard. */
428
+ if (token !== undefined) {
429
+ try {
430
+ if (api.closeHandle(token) === 0) throwLastError(api, 'CloseHandle', 'restricted token')
431
+ } catch (error) {
432
+ failures.push(error)
433
+ }
434
+ }
435
+ for (const sidPtr of this.sidAllocations.splice(0)) {
436
+ freeSidBestEffort(api, sidPtr, 'init SID allocation', failures)
437
+ }
438
+ this.api = undefined
439
+ this.token = undefined
440
+ this.writeSidPtr = undefined
441
+ this.tempWriteSidPtr = undefined
442
+ this.grantedPaths = []
443
+ if (failures.length > 0) {
444
+ throw new AggregateError(failures, `AclSandbox dispose completed with ${failures.length} cleanup failure(s)`)
445
+ }
446
+ }
447
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Canonical directory-boundary checks for the Windows ACL workspace and
3
+ * private-temp capabilities.
4
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/path-boundary
5
+ */
6
+
7
+ import { realpathSync } from 'node:fs'
8
+ import { isAbsolute, relative, sep } from 'node:path'
9
+
10
+ /** Whether `root` is the same canonical directory as `candidate` or contains it. */
11
+ function containsDirectory(root: string, candidate: string): boolean {
12
+ const relation = relative(realpathSync.native(root), realpathSync.native(candidate))
13
+ return relation === '' || (!isAbsolute(relation) && relation !== '..' && !relation.startsWith(`..${sep}`))
14
+ }
15
+
16
+ /**
17
+ * Whether a temp parent is inside the workspace, where every child created
18
+ * below it would inherit the standing workspace capability.
19
+ * @param workspaceRoot - the canonical workspace root that receives the standing ACE.
20
+ * @param tempRoot - the existing parent beneath which a private temp child would be created.
21
+ * @returns whether the canonical workspace contains the canonical temp root.
22
+ * @throws the filesystem error when either directory cannot be resolved.
23
+ */
24
+ export function isTempRootInsideWorkspace(workspaceRoot: string, tempRoot: string): boolean {
25
+ return containsDirectory(workspaceRoot, tempRoot)
26
+ }
27
+
28
+ /**
29
+ * Reject a temp parent that is inside the workspace (see {@link isTempRootInsideWorkspace}).
30
+ * @param workspaceRoot - the canonical workspace root that receives the standing ACE.
31
+ * @param tempRoot - the existing parent beneath which a private temp child would be created.
32
+ */
33
+ export function assertTempRootOutsideWorkspace(workspaceRoot: string, tempRoot: string): void {
34
+ if (isTempRootInsideWorkspace(workspaceRoot, tempRoot)) {
35
+ throw new Error(`Windows ACL temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tempRoot}`)
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Reject overlap between an actual private temp directory and any writable
41
+ * directory: either inheritance direction would merge the two capabilities.
42
+ * @param writableDirs - directories carrying the standing workspace capability.
43
+ * @param tempDir - the existing directory carrying the revocable temp capability.
44
+ */
45
+ export function assertPrivateTempDisjoint(writableDirs: readonly string[], tempDir: string): void {
46
+ for (const writableDir of writableDirs) {
47
+ if (containsDirectory(writableDir, tempDir) || containsDirectory(tempDir, writableDir)) {
48
+ throw new Error(`AclSandbox private temp directory must be disjoint from writable directories: writable=${writableDir}; temp=${tempDir}`)
49
+ }
50
+ }
51
+ }