@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/ffi.ts ADDED
@@ -0,0 +1,314 @@
1
+ /** ACL/token bindings layered on the shared Win32 process owner. */
2
+
3
+ import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
4
+ import {
5
+ ERROR_INSUFFICIENT_BUFFER,
6
+ Win32Error,
7
+ extendWin32ProcessBindings,
8
+ isNullPtr,
9
+ throwLastError,
10
+ } from '@deepseek-ai/dsh-win32-process'
11
+ import type { NativePtr, Win32ProcessBindings } from '@deepseek-ai/dsh-win32-process'
12
+ import * as abi from './win32-abi.ts'
13
+
14
+ export {
15
+ allocPtrSlot,
16
+ allocUint32,
17
+ decodePtr,
18
+ decodeUint32,
19
+ isNullPtr,
20
+ throwLastError,
21
+ throwWin32,
22
+ } from '@deepseek-ai/dsh-win32-process'
23
+ export type { NativePtr } from '@deepseek-ai/dsh-win32-process'
24
+
25
+ type Koffi = typeof import('koffi')['default']
26
+ type Ptr = ReturnType<Koffi['pointer']>
27
+
28
+ const requireKoffi = createLazyRequire<Koffi>('koffi', import.meta.url)
29
+ let cachedTypes: { PVOID: Ptr; PPVOID: Ptr } | undefined
30
+
31
+ function ffiTypes(): { PVOID: Ptr; PPVOID: Ptr } {
32
+ if (cachedTypes !== undefined) return cachedTypes
33
+ const koffi = requireKoffi()
34
+ const PVOID = koffi.pointer('void')
35
+ return cachedTypes = { PVOID, PPVOID: koffi.pointer(PVOID) }
36
+ }
37
+
38
+ /** ACL/token calls composed with the generic Win32 process binding table. */
39
+ export interface Win32Bindings extends Win32ProcessBindings {
40
+ openProcess(desiredAccess: number, inheritHandle: number, pid: number): NativePtr
41
+ openProcessToken(process: NativePtr, desiredAccess: number, tokenHandle: NativePtr): number
42
+ localAlloc(flags: number, bytes: number): NativePtr
43
+ localFree(memory: NativePtr): NativePtr
44
+ convertStringSidToSidW(stringSid: string, sid: NativePtr): number
45
+ createWellKnownSid(type: number, domainSid: null, sid: NativePtr, size: NativePtr): number
46
+ isValidSid(sid: NativePtr): number
47
+ getLengthSid(sid: NativePtr): number
48
+ copySid(length: number, destination: NativePtr, source: NativePtr): number
49
+ getTokenInformation(token: NativePtr, cls: number, info: Buffer | null, length: number, needed: NativePtr): number
50
+ setTokenInformation(token: NativePtr, cls: number, info: Buffer, length: number): number
51
+ createRestrictedToken(
52
+ existing: NativePtr,
53
+ flags: number,
54
+ disableCount: number,
55
+ disableSids: null,
56
+ deletePrivilegeCount: number,
57
+ privilegesToDelete: null,
58
+ restrictCount: number,
59
+ restrictingSids: Buffer,
60
+ newToken: NativePtr,
61
+ ): number
62
+ setEntriesInAclW(count: number, entries: Buffer, oldAcl: NativePtr | null, newAcl: NativePtr): number
63
+ initializeAcl(acl: NativePtr, length: number, revision: number): number
64
+ addMandatoryAce(acl: NativePtr, revision: number, aceFlags: number, policy: number, sid: NativePtr): number
65
+ setNamedSecurityInfoW(
66
+ path: string,
67
+ objectType: number,
68
+ information: number,
69
+ owner: null,
70
+ group: null,
71
+ dacl: NativePtr | null,
72
+ sacl: NativePtr | null,
73
+ ): number
74
+ getNamedSecurityInfoW(
75
+ path: string,
76
+ objectType: number,
77
+ information: number,
78
+ owner: NativePtr,
79
+ group: NativePtr,
80
+ dacl: NativePtr,
81
+ sacl: NativePtr,
82
+ descriptor: NativePtr,
83
+ ): number
84
+ getTempPathW(length: number, buffer: Buffer): number
85
+ setEnvironmentVariableW(name: string, value: string): number
86
+ setConsoleCtrlHandler(handler: null, add: number): number
87
+ createFileW(
88
+ fileName: string,
89
+ desiredAccess: number,
90
+ shareMode: number,
91
+ attributes: null,
92
+ creationDisposition: number,
93
+ flagsAndAttributes: number,
94
+ templateFile: null,
95
+ ): NativePtr
96
+ lockFileEx(
97
+ file: NativePtr,
98
+ flags: number,
99
+ reserved: number,
100
+ bytesLow: number,
101
+ bytesHigh: number,
102
+ overlapped: NativePtr,
103
+ ): number
104
+ unlockFileEx(
105
+ file: NativePtr,
106
+ reserved: number,
107
+ bytesLow: number,
108
+ bytesHigh: number,
109
+ overlapped: NativePtr,
110
+ ): number
111
+ }
112
+
113
+ /**
114
+ * Return whether CreateFileW produced INVALID_HANDLE_VALUE.
115
+ * @param handle - handle returned by CreateFileW.
116
+ * @returns true for null, zero, or the all-bits-one sentinel.
117
+ */
118
+ export function isInvalidHandle(handle: NativePtr | null | undefined): boolean {
119
+ if (isNullPtr(handle)) return true
120
+ return (handle as bigint) === 0xFFFFFFFFFFFFFFFFn || (handle as bigint) === -1n
121
+ }
122
+
123
+ /**
124
+ * Encode a uint32 into an allocated slot.
125
+ * @param slot - slot allocated by allocUint32.
126
+ * @param value - unsigned value to store.
127
+ */
128
+ export function encodeUint32(slot: NativePtr, value: number): void {
129
+ requireKoffi().encode(slot, 'uint32', value)
130
+ }
131
+
132
+ /**
133
+ * Return a Koffi pointer's numeric address for struct packing.
134
+ * @param ptr - native pointer.
135
+ * @returns pointer address.
136
+ */
137
+ export function ptrAddress(ptr: NativePtr): bigint {
138
+ return requireKoffi().address(ptr)
139
+ }
140
+
141
+ /**
142
+ * Allocate a raw byte block.
143
+ * @param length - byte count.
144
+ * @returns allocated pointer.
145
+ */
146
+ export function allocBytes(length: number): NativePtr {
147
+ return requireKoffi().alloc('uint8', length) as NativePtr
148
+ }
149
+
150
+ /**
151
+ * Allocate one zeroed x64 OVERLAPPED record.
152
+ * @returns allocated pointer.
153
+ * @remarks Koffi 3.1.1 crashes when LockFileEx or UnlockFileEx receives NULL;
154
+ * a zeroed OVERLAPPED is equivalent for the synchronous lock-file handle.
155
+ */
156
+ export function allocOverlapped(): NativePtr {
157
+ return allocBytes(32)
158
+ }
159
+
160
+ /**
161
+ * Decode a pointer value from a Buffer field.
162
+ * @param buffer - encoded native record.
163
+ * @param offset - pointer field byte offset.
164
+ * @returns decoded pointer, or null for address zero.
165
+ */
166
+ export function decodePtrAt(buffer: Buffer, offset: number): NativePtr | null {
167
+ const value = requireKoffi().decode(buffer, offset, ffiTypes().PVOID) as NativePtr | null
168
+ return isNullPtr(value) ? null : value
169
+ }
170
+
171
+ /**
172
+ * Decode a uint8 field at a native pointer offset.
173
+ * @param ptr - native record pointer.
174
+ * @param offset - field byte offset.
175
+ * @returns decoded value.
176
+ */
177
+ export function decodeUint8At(ptr: NativePtr, offset: number): number {
178
+ return requireKoffi().decode(ptr, offset, 'uint8') as number
179
+ }
180
+
181
+ /**
182
+ * Decode a uint16 field at a native pointer offset.
183
+ * @param ptr - native record pointer.
184
+ * @param offset - field byte offset.
185
+ * @returns decoded value.
186
+ */
187
+ export function decodeUint16At(ptr: NativePtr, offset: number): number {
188
+ return requireKoffi().decode(ptr, offset, 'uint16') as number
189
+ }
190
+
191
+ /**
192
+ * Decode a uint32 field at a native pointer offset.
193
+ * @param ptr - native record pointer.
194
+ * @param offset - field byte offset.
195
+ * @returns decoded value.
196
+ */
197
+ export function decodeUint32At(ptr: NativePtr, offset: number): number {
198
+ return requireKoffi().decode(ptr, offset, 'uint32') as number
199
+ }
200
+
201
+ /**
202
+ * Compare two in-memory SID records without allocating strings.
203
+ * @param left - first native buffer.
204
+ * @param leftOffset - first SID byte offset.
205
+ * @param right - second native buffer.
206
+ * @param rightOffset - second SID byte offset.
207
+ * @returns true when revision, authority, and every sub-authority match.
208
+ */
209
+ export function sameSidAt(
210
+ left: NativePtr,
211
+ leftOffset: number,
212
+ right: NativePtr,
213
+ rightOffset: number,
214
+ ): boolean {
215
+ if (decodeUint8At(left, leftOffset) !== decodeUint8At(right, rightOffset)) return false
216
+ const leftCount = decodeUint8At(left, leftOffset + 1)
217
+ const rightCount = decodeUint8At(right, rightOffset + 1)
218
+ if (leftCount !== rightCount || leftCount > abi.SID_MAX_SUB_AUTHORITIES) return false
219
+ for (let index = 0; index < 6; index += 1) {
220
+ if (decodeUint8At(left, leftOffset + 2 + index) !== decodeUint8At(right, rightOffset + 2 + index)) {
221
+ return false
222
+ }
223
+ }
224
+ for (let index = 0; index < leftCount; index += 1) {
225
+ if (decodeUint32At(left, leftOffset + 8 + index * 4) !==
226
+ decodeUint32At(right, rightOffset + 8 + index * 4)) return false
227
+ }
228
+ return true
229
+ }
230
+
231
+ let cached: Win32Bindings | undefined
232
+
233
+ function bindings(): Win32Bindings {
234
+ if (cached !== undefined) return cached
235
+ const koffi = requireKoffi()
236
+ const { PVOID, PPVOID } = ffiTypes()
237
+ cached = extendWin32ProcessBindings(({ kernel32, advapi32, bind }) => ({
238
+ openProcess: bind(kernel32, 'OpenProcess', PVOID, ['uint32', 'int', 'uint32']),
239
+ openProcessToken: bind(advapi32, 'OpenProcessToken', 'int', [PVOID, 'uint32', PPVOID]),
240
+ localAlloc: bind(kernel32, 'LocalAlloc', PVOID, ['uint32', 'size_t']),
241
+ localFree: bind(kernel32, 'LocalFree', PVOID, [PVOID]),
242
+ convertStringSidToSidW: bind(advapi32, 'ConvertStringSidToSidW', 'int', ['str16', PPVOID]),
243
+ createWellKnownSid: bind(advapi32, 'CreateWellKnownSid', 'int', [
244
+ 'int', PVOID, PVOID, koffi.pointer('uint32'),
245
+ ]),
246
+ isValidSid: bind(advapi32, 'IsValidSid', 'int', [PVOID]),
247
+ getLengthSid: bind(advapi32, 'GetLengthSid', 'uint32', [PVOID]),
248
+ copySid: bind(advapi32, 'CopySid', 'int', ['uint32', PVOID, PVOID]),
249
+ getTokenInformation: bind(advapi32, 'GetTokenInformation', 'int', [
250
+ PVOID, 'int', PVOID, 'uint32', koffi.pointer('uint32'),
251
+ ]),
252
+ setTokenInformation: bind(advapi32, 'SetTokenInformation', 'int', [PVOID, 'int', PVOID, 'uint32']),
253
+ createRestrictedToken: bind(advapi32, 'CreateRestrictedToken', 'int', [
254
+ PVOID, 'uint32', 'uint32', PVOID, 'uint32', PVOID, 'uint32', PVOID, PPVOID,
255
+ ]),
256
+ setEntriesInAclW: bind(advapi32, 'SetEntriesInAclW', 'uint32', ['uint32', PVOID, PVOID, PPVOID]),
257
+ initializeAcl: bind(advapi32, 'InitializeAcl', 'int', [PVOID, 'uint32', 'uint32']),
258
+ addMandatoryAce: bind(advapi32, 'AddMandatoryAce', 'int', [PVOID, 'uint32', 'uint32', 'uint32', PVOID]),
259
+ setNamedSecurityInfoW: bind(advapi32, 'SetNamedSecurityInfoW', 'uint32', [
260
+ 'str16', 'int', 'uint32', PVOID, PVOID, PVOID, PVOID,
261
+ ]),
262
+ getNamedSecurityInfoW: bind(advapi32, 'GetNamedSecurityInfoW', 'uint32', [
263
+ 'str16', 'int', 'uint32', PPVOID, PPVOID, PPVOID, PPVOID, PPVOID,
264
+ ]),
265
+ getTempPathW: bind(kernel32, 'GetTempPathW', 'uint32', ['uint32', PVOID]),
266
+ setEnvironmentVariableW: bind(kernel32, 'SetEnvironmentVariableW', 'int', ['str16', 'str16']),
267
+ setConsoleCtrlHandler: bind(kernel32, 'SetConsoleCtrlHandler', 'int', [PVOID, 'int']),
268
+ createFileW: bind(kernel32, 'CreateFileW', PVOID, [
269
+ 'str16', 'uint32', 'uint32', PVOID, 'uint32', 'uint32', PVOID,
270
+ ]),
271
+ lockFileEx: bind(kernel32, 'LockFileEx', 'int', [
272
+ PVOID, 'uint32', 'uint32', 'uint32', 'uint32', PVOID,
273
+ ]),
274
+ unlockFileEx: bind(kernel32, 'UnlockFileEx', 'int', [
275
+ PVOID, 'uint32', 'uint32', 'uint32', PVOID,
276
+ ]),
277
+ })) as Win32Bindings
278
+ return cached
279
+ }
280
+
281
+ /**
282
+ * Resolve the cached ACL/token binding table asynchronously.
283
+ * @returns generic process plus ACL/token bindings.
284
+ */
285
+ export function win32(): Promise<Win32Bindings> {
286
+ return Promise.resolve(bindings())
287
+ }
288
+
289
+ /**
290
+ * Resolve the cached ACL/token binding table synchronously.
291
+ * @returns generic process plus ACL/token bindings.
292
+ */
293
+ export function win32Sync(): Win32Bindings {
294
+ return bindings()
295
+ }
296
+
297
+ /**
298
+ * Resolve the current Windows temporary directory.
299
+ * @param api - active ACL/token binding table.
300
+ * @returns UTF-16 path reported by GetTempPathW.
301
+ */
302
+ export function getTempPath(api: Win32Bindings): string {
303
+ const buffer = Buffer.alloc((abi.MAX_PATH + 1) * 2)
304
+ const length = api.getTempPathW(buffer.length / 2, buffer)
305
+ if (length === 0) throwLastError(api, 'GetTempPathW')
306
+ if (length > buffer.length / 2) {
307
+ throw new Win32Error(
308
+ 'GetTempPathW',
309
+ ERROR_INSUFFICIENT_BUFFER,
310
+ `required ${length} chars exceed the ${buffer.length / 2}-char buffer; nothing was written`,
311
+ )
312
+ }
313
+ return buffer.subarray(0, length * 2).toString('utf16le')
314
+ }
package/src/grant.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Server-side write-grant materialization. The sandbox seam holds one
3
+ * standing workspace grant per workspace and one revocable temp grant per
4
+ * live session/workspace pair. Workspace identities survive by deterministic
5
+ * derivation and their standing ACE; temp identities derive from random
6
+ * private paths and are deliberately new after a restart.
7
+ *
8
+ * Fail-closed: `add` throws on any grant failure and the caller disposes the
9
+ * instance (revoking every path granted so far); `dispose` revokes every
10
+ * revocable grant, leaves the standing workspace edits in place, and reports
11
+ * every cleanup failure.
12
+ * @module @deepseek-ai/dsh-sandbox-windows-acl/grant
13
+ */
14
+
15
+ import { grantWrite, revokeWrite } from './acl.ts'
16
+ import { allocPtrSlot, decodePtr, isNullPtr, throwLastError, win32Sync } from './ffi.ts'
17
+ import type { NativePtr, Win32Bindings } from './ffi.ts'
18
+ import { makeWellKnownSid } from './token.ts'
19
+ import * as abi from './win32-abi.ts'
20
+
21
+ /**
22
+ * One write SID's provider-lifetime grant materialization: the parsed SID
23
+ * pointer plus every directory whose DACL currently carries its ACE and whose
24
+ * label ACL carries the Low mandatory label. Workspace paths are added
25
+ * STANDING (their security descriptor edits are the cross-session reuse cache
26
+ * and outlive the grant — dispose() skips revoking them, or the next
27
+ * provision would re-propagate the whole tree); temp paths are revocable
28
+ * (dispose() revokes them — an inheritable ACE must not outlive its
29
+ * session's temp directory). Create with {@link AclWriteGrant.create};
30
+ * dispose revokes the revocable paths and frees every SID.
31
+ */
32
+ export class AclWriteGrant {
33
+ /** The write SID in SDDL string form. */
34
+ readonly writeSid: string
35
+ private readonly api: Win32Bindings
36
+ private readonly sidPtr: NativePtr
37
+ private readonly lowLabelSidPtr: NativePtr
38
+ private readonly worldSidPtr: NativePtr
39
+ private readonly revocablePaths: string[] = []
40
+ private readonly standingPaths: string[] = []
41
+
42
+ private constructor(
43
+ api: Win32Bindings,
44
+ sidPtr: NativePtr,
45
+ lowLabelSidPtr: NativePtr,
46
+ worldSidPtr: NativePtr,
47
+ writeSid: string,
48
+ ) {
49
+ this.api = api
50
+ this.sidPtr = sidPtr
51
+ this.lowLabelSidPtr = lowLabelSidPtr
52
+ this.worldSidPtr = worldSidPtr
53
+ this.writeSid = writeSid
54
+ }
55
+
56
+ /**
57
+ * Parse the SID string, create the Low integrity SID the grants label with
58
+ * and the world SID their ambient-delete deny names, and open the binding
59
+ * table (lazily, once per server). Fail-closed: any failure throws — nothing
60
+ * is granted yet.
61
+ * @param writeSid - the workspace (`S-1-4-x-y`) or temp (`S-1-4-x-y-1`) capability SID string.
62
+ * @param api - optional already-resolved bindings (tests).
63
+ * @returns the ready grant (no ACEs yet).
64
+ */
65
+ static create(writeSid: string, api?: Win32Bindings): AclWriteGrant {
66
+ const bindings = api ?? win32Sync()
67
+ const sidSlot = allocPtrSlot()
68
+ if (bindings.convertStringSidToSidW(writeSid, sidSlot) === 0) {
69
+ throwLastError(bindings, 'ConvertStringSidToSidW', writeSid)
70
+ }
71
+ const sidPtr = decodePtr(sidSlot)
72
+ if (sidPtr === null) throwLastError(bindings, 'ConvertStringSidToSidW', `null SID for ${writeSid}`)
73
+ try {
74
+ const lowLabelSidPtr = makeWellKnownSid(bindings, abi.WinLowLabelSid)
75
+ try {
76
+ const worldSidPtr = makeWellKnownSid(bindings, abi.WinWorldSid)
77
+ return new AclWriteGrant(bindings, sidPtr, lowLabelSidPtr, worldSidPtr, writeSid)
78
+ } catch (error) {
79
+ // The Low label SID is LocalAlloc'd: release it before the world-SID
80
+ // failure propagates to the sidPtr release below.
81
+ bindings.localFree(lowLabelSidPtr)
82
+ throw error
83
+ }
84
+ } catch (error) {
85
+ bindings.localFree(sidPtr)
86
+ throw error
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Grant the write ACE, the ambient-delete deny, and the Low mandatory label
92
+ * on one directory (idempotent: an already-standing exact ACE, deny, and
93
+ * label skip the eager full-tree re-propagation — see {@link grantWrite})
94
+ * and record the path for {@link dispose} unless it is standing. The path is
95
+ * recorded BEFORE the grant: a post-apply throw (a LocalFree failure after
96
+ * SetNamedSecurityInfoW succeeded) must still revoke it, and revoking an
97
+ * ungranted path is a no-op merge. Callers treat a throw as a failed
98
+ * materialization and dispose the instance to revoke the paths granted so
99
+ * far.
100
+ * @param path - the directory whose DACL and label gain the grant.
101
+ * @param standing - the edits outlive this grant (the workspace reuse
102
+ * cache; dispose() skips revoking it). Default false (revoked on
103
+ * dispose — the temp-directory lifecycle).
104
+ */
105
+ add(path: string, standing = false): void {
106
+ ;(standing ? this.standingPaths : this.revocablePaths).push(path)
107
+ grantWrite(this.api, path, this.sidPtr, this.lowLabelSidPtr, this.worldSidPtr)
108
+ }
109
+
110
+ /** Every directory currently carrying the grant, in grant order. */
111
+ get paths(): readonly string[] {
112
+ return [...this.standingPaths, ...this.revocablePaths]
113
+ }
114
+
115
+ /** Revoke every revocable grant (standing security descriptor edits stay) and free the SIDs; reports every cleanup failure. */
116
+ dispose(): void {
117
+ const failures: unknown[] = []
118
+ for (const path of this.revocablePaths) {
119
+ try {
120
+ revokeWrite(this.api, path, this.sidPtr)
121
+ } catch (error) {
122
+ failures.push(error)
123
+ }
124
+ }
125
+ for (const [label, sidPtr] of [
126
+ ['write SID', this.sidPtr],
127
+ ['Low label SID', this.lowLabelSidPtr],
128
+ ['world SID', this.worldSidPtr],
129
+ ] as const) {
130
+ try {
131
+ const freed = this.api.localFree(sidPtr)
132
+ if (!isNullPtr(freed)) throwLastError(this.api, 'LocalFree', label)
133
+ } catch (error) {
134
+ failures.push(error)
135
+ }
136
+ }
137
+ if (failures.length > 0) {
138
+ throw new AggregateError(failures, `AclWriteGrant dispose completed with ${failures.length} cleanup failure(s)`)
139
+ }
140
+ }
141
+ }