@deepseek-ai/dsh-win32-process 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,383 @@
1
+ /** Lazy Koffi bindings for generic Win32 process, stdio, and Job operations. */
2
+
3
+ import * as abi from './abi.ts'
4
+ import { Win32Error } from './errors.ts'
5
+ import { requireKoffi, type Koffi } from './koffi.ts'
6
+
7
+ declare const nativePtr: unique symbol
8
+ /** Koffi native pointer branded against accidental numeric use. */
9
+ export type NativePtr = bigint & { readonly [nativePtr]: true }
10
+
11
+ type Ptr = ReturnType<Koffi['pointer']>
12
+
13
+ /** Loaded Win32 libraries and the shared stdcall binder used by process extensions. */
14
+ export interface Win32BindingContext {
15
+ /** Kernel process, handle, pipe, and Job APIs. */
16
+ readonly kernel32: ReturnType<Koffi['load']>
17
+ /** Token and security APIs. */
18
+ readonly advapi32: ReturnType<Koffi['load']>
19
+ /** Bind one stdcall function from a loaded Win32 library. */
20
+ readonly bind: (
21
+ library: ReturnType<Koffi['load']>,
22
+ name: string,
23
+ result: Ptr | string,
24
+ args: Array<Ptr | string>,
25
+ ) => unknown
26
+ }
27
+
28
+ /**
29
+ * Return whether a Koffi pointer represents NULL.
30
+ * @param value - pointer value returned by Koffi or a Win32 call.
31
+ * @returns true for null, undefined, or address zero.
32
+ */
33
+ export function isNullPtr(value: NativePtr | null | undefined): value is null | undefined {
34
+ return value === null || value === undefined || (value as bigint) === 0n
35
+ }
36
+
37
+ /** STARTUPINFOW fields used by inherited or piped stdio launches. */
38
+ export interface StartupInfoInput {
39
+ cb: number
40
+ dwFlags: number
41
+ wShowWindow: number
42
+ hStdInput: NativePtr
43
+ hStdOutput: NativePtr
44
+ hStdError: NativePtr
45
+ cbReserved2?: number
46
+ lpReserved2?: NativePtr
47
+ }
48
+
49
+ /** Decoded PROCESS_INFORMATION result. */
50
+ export interface ProcessInfoOutput {
51
+ hProcess: NativePtr | null
52
+ hThread: NativePtr | null
53
+ dwProcessId: number
54
+ dwThreadId: number
55
+ }
56
+
57
+ /** Generic Win32 calls consumed by restricted-token sandbox process operations. */
58
+ export interface Win32ProcessBindings {
59
+ closeHandle(handle: NativePtr): number
60
+ getLastError(): number
61
+ getFileType(handle: NativePtr): number
62
+ uvGetOsfhandle(fileDescriptor: number): NativePtr | null
63
+ formatMessageW(
64
+ flags: number,
65
+ source: null,
66
+ messageId: number,
67
+ languageId: number,
68
+ buffer: Buffer,
69
+ size: number,
70
+ args: null,
71
+ ): number
72
+ createPipe(readHandle: NativePtr, writeHandle: NativePtr, attributes: null, size: number): number
73
+ setHandleInformation(handle: NativePtr, mask: number, flags: number): number
74
+ createProcessAsUserW(
75
+ token: NativePtr,
76
+ applicationName: string | null,
77
+ commandLine: string,
78
+ processAttributes: null,
79
+ threadAttributes: null,
80
+ inheritHandles: number,
81
+ creationFlags: number,
82
+ environment: null,
83
+ currentDirectory: string | null,
84
+ startupInfo: NativePtr,
85
+ processInfo: NativePtr,
86
+ ): number
87
+ createProcessW(
88
+ applicationName: string | null,
89
+ commandLine: string,
90
+ processAttributes: null,
91
+ threadAttributes: null,
92
+ inheritHandles: number,
93
+ creationFlags: number,
94
+ environment: Buffer | null,
95
+ currentDirectory: string | null,
96
+ startupInfo: NativePtr,
97
+ processInfo: NativePtr,
98
+ ): number
99
+ readFile(file: NativePtr, buffer: Buffer, count: number, bytesRead: NativePtr, overlapped: null): number
100
+ peekNamedPipe(
101
+ pipe: NativePtr,
102
+ buffer: null,
103
+ size: number,
104
+ bytesRead: NativePtr | null,
105
+ totalAvail: NativePtr,
106
+ leftThisMessage: NativePtr | null,
107
+ ): number
108
+ waitForSingleObject(handle: NativePtr, milliseconds: number): number
109
+ getExitCodeProcess(process: NativePtr, exitCode: NativePtr): number
110
+ createJobObjectW(attributes: null, name: null): NativePtr
111
+ setInformationJobObject(job: NativePtr, cls: number, information: Buffer, length: number): number
112
+ queryInformationJobObject(
113
+ job: NativePtr,
114
+ cls: number,
115
+ information: Buffer,
116
+ length: number,
117
+ returnLength: null,
118
+ ): number
119
+ assignProcessToJobObject(job: NativePtr, process: NativePtr): number
120
+ resumeThread(thread: NativePtr): number
121
+ terminateProcess(process: NativePtr, exitCode: number): number
122
+ terminateJobObject(job: NativePtr, exitCode: number): number
123
+ getStdHandle(stdHandle: number): NativePtr
124
+ }
125
+
126
+ /** Generic Win32 calls plus Node's libuv descriptor-to-handle bridge. */
127
+ export interface CurrentTokenProcessBindings extends Win32ProcessBindings {
128
+ uvGetOsfhandle(fileDescriptor: number): NativePtr | null
129
+ }
130
+
131
+ interface Win32Types {
132
+ PVOID: Ptr
133
+ PPVOID: Ptr
134
+ STARTUPINFOW: ReturnType<Koffi['struct']>
135
+ PROCESS_INFORMATION: ReturnType<Koffi['struct']>
136
+ }
137
+
138
+ let cachedTypes: Win32Types | undefined
139
+
140
+ /** Resolve Koffi pointer and process layouts on the first native operation. */
141
+ function win32Types(): Win32Types {
142
+ if (cachedTypes !== undefined) return cachedTypes
143
+ const koffi = requireKoffi()
144
+ const PVOID = koffi.pointer('void')
145
+ const PPVOID = koffi.pointer(PVOID)
146
+ const STARTUPINFOW = koffi.struct('DSH_STARTUPINFOW', {
147
+ cb: 'uint32', lpReserved: 'str16', lpDesktop: 'str16', lpTitle: 'str16',
148
+ dwX: 'uint32', dwY: 'uint32', dwXSize: 'uint32', dwYSize: 'uint32',
149
+ dwXCountChars: 'uint32', dwYCountChars: 'uint32', dwFillAttribute: 'uint32',
150
+ dwFlags: 'uint32', wShowWindow: 'uint16', cbReserved2: 'uint16',
151
+ lpReserved2: koffi.pointer('uint8'), hStdInput: PVOID, hStdOutput: PVOID, hStdError: PVOID,
152
+ })
153
+ const PROCESS_INFORMATION = koffi.struct('DSH_PROCESS_INFORMATION', {
154
+ hProcess: PVOID, hThread: PVOID, dwProcessId: 'uint32', dwThreadId: 'uint32',
155
+ })
156
+ /* v8 ignore start -- ABI guards are pinned by native header probes. */
157
+ if (STARTUPINFOW.size !== abi.STARTUPINFOW_SIZE) {
158
+ throw new Error(`STARTUPINFOW layout mismatch: koffi computed ${STARTUPINFOW.size}, expected ${abi.STARTUPINFOW_SIZE}`)
159
+ }
160
+ if (PROCESS_INFORMATION.size !== abi.PROCESS_INFORMATION_SIZE) {
161
+ throw new Error(`PROCESS_INFORMATION layout mismatch: koffi computed ${PROCESS_INFORMATION.size}, expected ${abi.PROCESS_INFORMATION_SIZE}`)
162
+ }
163
+ /* v8 ignore stop */
164
+ return cachedTypes = { PVOID, PPVOID, STARTUPINFOW, PROCESS_INFORMATION }
165
+ }
166
+
167
+ /**
168
+ * Materialize the Koffi STARTUPINFOW layout on first native use.
169
+ * @returns the cached native struct type.
170
+ */
171
+ export function startupInfoType(): ReturnType<Koffi['struct']> {
172
+ return win32Types().STARTUPINFOW
173
+ }
174
+
175
+ /**
176
+ * Materialize the Koffi PROCESS_INFORMATION layout on first native use.
177
+ * @returns the cached native struct type.
178
+ */
179
+ export function processInformationType(): ReturnType<Koffi['struct']> {
180
+ return win32Types().PROCESS_INFORMATION
181
+ }
182
+
183
+ /**
184
+ * Allocate a pointer-sized out-parameter slot.
185
+ * @returns allocated native slot.
186
+ */
187
+ export function allocPtrSlot(): NativePtr {
188
+ const { PVOID } = win32Types()
189
+ return requireKoffi().alloc(PVOID, 1) as NativePtr
190
+ }
191
+
192
+ /**
193
+ * Allocate a uint32 out-parameter slot.
194
+ * @returns allocated native slot.
195
+ */
196
+ export function allocUint32(): NativePtr {
197
+ return requireKoffi().alloc('uint32', 1) as NativePtr
198
+ }
199
+
200
+ /**
201
+ * Decode a pointer out-parameter.
202
+ * @param slot - pointer-sized slot filled by Win32.
203
+ * @returns decoded pointer, or null for address zero.
204
+ */
205
+ export function decodePtr(slot: NativePtr): NativePtr | null {
206
+ const value = requireKoffi().decode(slot, win32Types().PVOID) as NativePtr | null
207
+ return isNullPtr(value) ? null : value
208
+ }
209
+
210
+ /**
211
+ * Decode a uint32 out-parameter.
212
+ * @param slot - uint32 slot filled by Win32.
213
+ * @returns decoded unsigned value.
214
+ */
215
+ export function decodeUint32(slot: NativePtr): number {
216
+ return requireKoffi().decode(slot, 'uint32') as number
217
+ }
218
+
219
+ /**
220
+ * Allocate a zeroed STARTUPINFOW.
221
+ * @returns allocated struct pointer.
222
+ */
223
+ export function allocStartupInfo(): NativePtr {
224
+ return requireKoffi().alloc(win32Types().STARTUPINFOW, 1) as NativePtr
225
+ }
226
+
227
+ /**
228
+ * Encode the stdio-bearing STARTUPINFOW fields.
229
+ * @param startupInfo - allocated STARTUPINFOW pointer.
230
+ * @param fields - fields required for inherited stdio.
231
+ */
232
+ export function encodeStartupInfo(startupInfo: NativePtr, fields: StartupInfoInput): void {
233
+ requireKoffi().encode(startupInfo, win32Types().STARTUPINFOW, fields)
234
+ }
235
+
236
+ /**
237
+ * Allocate a zeroed PROCESS_INFORMATION.
238
+ * @returns allocated struct pointer.
239
+ */
240
+ export function allocProcessInfo(): NativePtr {
241
+ return requireKoffi().alloc(win32Types().PROCESS_INFORMATION, 1) as NativePtr
242
+ }
243
+
244
+ /**
245
+ * Decode PROCESS_INFORMATION.
246
+ * @param processInfo - struct pointer filled by CreateProcess.
247
+ * @returns process/thread handles and ids.
248
+ */
249
+ export function decodeProcessInfo(processInfo: NativePtr): ProcessInfoOutput {
250
+ return requireKoffi().decode(processInfo, win32Types().PROCESS_INFORMATION) as ProcessInfoOutput
251
+ }
252
+
253
+ let cachedContext: Win32BindingContext | undefined
254
+ let cached: CurrentTokenProcessBindings | undefined
255
+
256
+ /* v8 ignore start -- exercised by native Windows ABI and sandbox jobs. */
257
+ function bindingContext(): Win32BindingContext {
258
+ if (cachedContext !== undefined) return cachedContext
259
+ const koffi = requireKoffi()
260
+ const kernel32 = koffi.load('kernel32.dll')
261
+ const advapi32 = koffi.load('advapi32.dll')
262
+ const bind = (
263
+ lib: ReturnType<typeof koffi.load>,
264
+ name: string,
265
+ result: Ptr | string,
266
+ args: Array<Ptr | string>,
267
+ ): unknown => lib.func('__stdcall', name, result, args)
268
+ cachedContext = { kernel32, advapi32, bind }
269
+ return cachedContext
270
+ }
271
+
272
+ function bindings(): CurrentTokenProcessBindings {
273
+ if (cached !== undefined) return cached
274
+ const koffi = requireKoffi()
275
+ const { PVOID, PPVOID, STARTUPINFOW, PROCESS_INFORMATION } = win32Types()
276
+ const { kernel32, advapi32, bind } = bindingContext()
277
+ const node = koffi.load(null)
278
+ cached = {
279
+ closeHandle: bind(kernel32, 'CloseHandle', 'int', [PVOID]),
280
+ getLastError: bind(kernel32, 'GetLastError', 'uint32', []),
281
+ getFileType: bind(kernel32, 'GetFileType', 'uint32', [PVOID]),
282
+ formatMessageW: bind(kernel32, 'FormatMessageW', 'uint32', [
283
+ 'uint32', PVOID, 'uint32', 'uint32', PVOID, 'uint32', PVOID,
284
+ ]),
285
+ createPipe: bind(kernel32, 'CreatePipe', 'int', [PPVOID, PPVOID, PVOID, 'uint32']),
286
+ setHandleInformation: bind(kernel32, 'SetHandleInformation', 'int', [PVOID, 'uint32', 'uint32']),
287
+ createProcessAsUserW: bind(advapi32, 'CreateProcessAsUserW', 'int', [
288
+ PVOID, 'str16', 'str16', PVOID, PVOID, 'int', 'uint32', PVOID, 'str16',
289
+ koffi.pointer(STARTUPINFOW), koffi.pointer(PROCESS_INFORMATION),
290
+ ]),
291
+ createProcessW: bind(kernel32, 'CreateProcessW', 'int', [
292
+ 'str16', 'str16', PVOID, PVOID, 'int', 'uint32', PVOID, 'str16',
293
+ koffi.pointer(STARTUPINFOW), koffi.pointer(PROCESS_INFORMATION),
294
+ ]),
295
+ readFile: bind(kernel32, 'ReadFile', 'int', [PVOID, PVOID, 'uint32', koffi.pointer('uint32'), PVOID]),
296
+ peekNamedPipe: bind(kernel32, 'PeekNamedPipe', 'int', [
297
+ PVOID, PVOID, 'uint32', koffi.pointer('uint32'), koffi.pointer('uint32'), koffi.pointer('uint32'),
298
+ ]),
299
+ waitForSingleObject: bind(kernel32, 'WaitForSingleObject', 'uint32', [PVOID, 'uint32']),
300
+ getExitCodeProcess: bind(kernel32, 'GetExitCodeProcess', 'int', [PVOID, koffi.pointer('uint32')]),
301
+ createJobObjectW: bind(kernel32, 'CreateJobObjectW', PVOID, [PVOID, 'str16']),
302
+ setInformationJobObject: bind(kernel32, 'SetInformationJobObject', 'int', [PVOID, 'int', PVOID, 'uint32']),
303
+ queryInformationJobObject: bind(kernel32, 'QueryInformationJobObject', 'int', [
304
+ PVOID, 'int', PVOID, 'uint32', PVOID,
305
+ ]),
306
+ assignProcessToJobObject: bind(kernel32, 'AssignProcessToJobObject', 'int', [PVOID, PVOID]),
307
+ resumeThread: bind(kernel32, 'ResumeThread', 'uint32', [PVOID]),
308
+ terminateProcess: bind(kernel32, 'TerminateProcess', 'int', [PVOID, 'uint32']),
309
+ terminateJobObject: bind(kernel32, 'TerminateJobObject', 'int', [PVOID, 'uint32']),
310
+ getStdHandle: bind(kernel32, 'GetStdHandle', PVOID, ['int']),
311
+ uvGetOsfhandle: node.func('uv_get_osfhandle', PVOID, ['int']),
312
+ } as unknown as CurrentTokenProcessBindings
313
+ return cached
314
+ }
315
+
316
+ /**
317
+ * Extend the shared process table with caller-owned Win32 API families.
318
+ * @param create - binds only the caller-specific operations from the shared libraries.
319
+ * @returns generic process bindings combined with the caller-specific operations.
320
+ */
321
+ export function extendWin32ProcessBindings<Extension extends object>(
322
+ create: (context: Win32BindingContext) => Extension,
323
+ ): CurrentTokenProcessBindings & Extension {
324
+ return { ...bindings(), ...create(bindingContext()) }
325
+ }
326
+
327
+ /**
328
+ * Load the generic process binding table without policy-specific extensions.
329
+ * @returns shared Win32 process, stdio, and Job operations.
330
+ */
331
+ export function loadWin32ProcessBindings(): CurrentTokenProcessBindings {
332
+ return bindings()
333
+ }
334
+ /* v8 ignore stop */
335
+
336
+ /**
337
+ * Format a Win32 error code through FormatMessageW.
338
+ * @param api - active binding table.
339
+ * @param win32Code - captured GetLastError value.
340
+ * @returns trimmed system message, or an empty string when unavailable.
341
+ */
342
+ export function errorText(api: Win32ProcessBindings, win32Code: number): string {
343
+ const buffer = Buffer.alloc(1024)
344
+ const length = api.formatMessageW(
345
+ abi.FORMAT_MESSAGE_FROM_SYSTEM | abi.FORMAT_MESSAGE_IGNORE_INSERTS,
346
+ null,
347
+ win32Code,
348
+ 0,
349
+ buffer,
350
+ buffer.length / 2,
351
+ null,
352
+ )
353
+ return length === 0 ? '' : buffer.subarray(0, length * 2).toString('utf16le').trim()
354
+ }
355
+
356
+ /**
357
+ * Throw the current GetLastError value.
358
+ * @param api - active binding table.
359
+ * @param name - failing Win32 operation.
360
+ * @param detail - optional operation context.
361
+ * @returns never; always throws Win32Error.
362
+ */
363
+ export function throwLastError(api: Win32ProcessBindings, name: string, detail?: string): never {
364
+ const win32Code = api.getLastError()
365
+ throw new Win32Error(name, win32Code, detail ?? errorText(api, win32Code))
366
+ }
367
+
368
+ /**
369
+ * Throw an explicitly captured Win32 error code.
370
+ * @param api - active binding table.
371
+ * @param name - failing Win32 operation.
372
+ * @param win32Code - error captured before cleanup.
373
+ * @param detail - optional operation context.
374
+ * @returns never; always throws Win32Error.
375
+ */
376
+ export function throwWin32(
377
+ api: Win32ProcessBindings,
378
+ name: string,
379
+ win32Code: number,
380
+ detail?: string,
381
+ ): never {
382
+ throw new Win32Error(name, win32Code, detail ?? errorText(api, win32Code))
383
+ }
package/src/index.ts ADDED
@@ -0,0 +1,38 @@
1
+ /** Shared low-level Win32 process, stdio, and Job Object primitives. */
2
+
3
+ export { ERROR_INSUFFICIENT_BUFFER } from './abi.ts'
4
+ export * from './errors.ts'
5
+ export {
6
+ allocPtrSlot,
7
+ allocUint32,
8
+ decodePtr,
9
+ decodeUint32,
10
+ extendWin32ProcessBindings,
11
+ isNullPtr,
12
+ loadWin32ProcessBindings,
13
+ throwLastError,
14
+ throwWin32,
15
+ } from './ffi.ts'
16
+ export type {
17
+ CurrentTokenProcessBindings,
18
+ NativePtr,
19
+ Win32ProcessBindings,
20
+ } from './ffi.ts'
21
+ export {
22
+ closeHandleChecked,
23
+ drainPipe,
24
+ isJobEmpty,
25
+ pollProcessExit,
26
+ probeCurrentTokenJobSupport,
27
+ spawnInheritedJobProcess,
28
+ spawnCurrentTokenJobProcess,
29
+ spawnPipedProcess,
30
+ terminateJob,
31
+ waitForProcessExit,
32
+ } from './process.ts'
33
+ export type {
34
+ CurrentTokenStdioFileDescriptors,
35
+ CurrentTokenProcessSpawnOptions,
36
+ SpawnedJobProcess,
37
+ SpawnedPipedProcess,
38
+ } from './process.ts'
package/src/koffi.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** Process-realm lazy access to Koffi's CommonJS entry. */
2
+
3
+ import type koffi from 'koffi'
4
+ import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
5
+
6
+ /** Koffi runtime export type. */
7
+ export type Koffi = typeof koffi
8
+
9
+ /** Load Koffi on the first Win32 native operation. */
10
+ export const requireKoffi = createLazyRequire<Koffi>('koffi', import.meta.url)