@unieai/rabi-win32-process 0.2.1-rc.3 → 0.2.2-rc.5

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/lib/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { HarnessError } from "@unieai/rabi-error";
1
2
  import { createLazyRequire } from "@unieai/rabi-lazy-require";
2
3
  /** Win32 code reporting a caller-provided buffer is too small. */
3
4
  const ERROR_INSUFFICIENT_BUFFER = 122;
@@ -5,14 +6,21 @@ const ERROR_INSUFFICIENT_BUFFER = 122;
5
6
  const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 8192;
6
7
  //#endregion
7
8
  //#region lib/types/errors.js
9
+ /** Code of every {@link Win32Error}; the failing API and its numeric code stay in `api`, `win32Code`, and `message`. */
10
+ const WIN32_ERROR = "WIN32_ERROR";
8
11
  /** Win32 call failure with the exact API name and error code. */
9
- var Win32Error = class extends Error {
12
+ var Win32Error = class extends HarnessError {
10
13
  /** Win32 function whose checked result failed. */
11
14
  api;
12
15
  /** Exact GetLastError value or direct Win32 API error code. */
13
16
  win32Code;
17
+ /**
18
+ * @param api - Win32 function whose checked result failed.
19
+ * @param win32Code - exact GetLastError value or direct API error code.
20
+ * @param detail - optional subject, such as the path the call targeted.
21
+ */
14
22
  constructor(api, win32Code, detail) {
15
- super(`${api} failed (Win32 ${win32Code})${detail === void 0 ? "" : `: ${detail}`}`);
23
+ super(`${api} failed (Win32 ${win32Code})${detail === void 0 ? "" : `: ${detail}`}`, WIN32_ERROR);
16
24
  this.name = "Win32Error";
17
25
  this.api = api;
18
26
  this.win32Code = win32Code;
@@ -758,4 +766,4 @@ function closeHandleChecked(api, handle, detail) {
758
766
  if (api.closeHandle(handle) === 0) throwLastError(api, "CloseHandle", detail);
759
767
  }
760
768
  //#endregion
761
- export { ERROR_INSUFFICIENT_BUFFER, Win32Error, allocPtrSlot, allocUint32, closeHandleChecked, decodePtr, decodeUint32, drainPipe, extendWin32ProcessBindings, isJobEmpty, isNullPtr, loadWin32ProcessBindings, pollProcessExit, probeCurrentTokenJobSupport, spawnCurrentTokenJobProcess, spawnInheritedJobProcess, spawnPipedProcess, terminateJob, throwLastError, throwWin32, waitForProcessExit };
769
+ export { ERROR_INSUFFICIENT_BUFFER, WIN32_ERROR, Win32Error, allocPtrSlot, allocUint32, closeHandleChecked, decodePtr, decodeUint32, drainPipe, extendWin32ProcessBindings, isJobEmpty, isNullPtr, loadWin32ProcessBindings, pollProcessExit, probeCurrentTokenJobSupport, spawnCurrentTokenJobProcess, spawnInheritedJobProcess, spawnPipedProcess, terminateJob, throwLastError, throwWin32, waitForProcessExit };
@@ -1,9 +1,17 @@
1
+ import { HarnessError } from '@unieai/rabi-error';
2
+ /** Code of every {@link Win32Error}; the failing API and its numeric code stay in `api`, `win32Code`, and `message`. */
3
+ export declare const WIN32_ERROR = "WIN32_ERROR";
1
4
  /** Win32 call failure with the exact API name and error code. */
2
- export declare class Win32Error extends Error {
5
+ export declare class Win32Error extends HarnessError {
3
6
  /** Win32 function whose checked result failed. */
4
7
  readonly api: string;
5
8
  /** Exact GetLastError value or direct Win32 API error code. */
6
9
  readonly win32Code: number;
10
+ /**
11
+ * @param api - Win32 function whose checked result failed.
12
+ * @param win32Code - exact GetLastError value or direct API error code.
13
+ * @param detail - optional subject, such as the path the call targeted.
14
+ */
7
15
  constructor(api: string, win32Code: number, detail?: string);
8
16
  }
9
17
  //# sourceMappingURL=errors.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-win32-process",
3
3
  "description": "Shared low-level Win32 process, stdio, and Job Object primitives",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -19,14 +19,18 @@
19
19
  "files": [
20
20
  "lib/index.js",
21
21
  "lib/types/**/*.d.ts",
22
+ "lib/types/**/*.d.ts.map",
23
+ "lib/**/*.js.map",
24
+ "src",
22
25
  "README.md"
23
26
  ],
24
27
  "license": "MIT",
25
28
  "peerDependencies": {
26
- "@unieai/cordis": "4.0.5"
29
+ "@unieai/cordis": "4.1.0",
30
+ "@unieai/rabi-error": "0.2.2-rc.5"
27
31
  },
28
32
  "dependencies": {
29
- "@unieai/rabi-lazy-require": "0.2.1-rc.3",
33
+ "@unieai/rabi-lazy-require": "0.2.2-rc.5",
30
34
  "koffi": "3.1.1"
31
35
  }
32
36
  }
package/src/abi.ts ADDED
@@ -0,0 +1,52 @@
1
+ /** Generic Win32 process, stdio, and Job Object constants verified on x64. */
2
+
3
+ /** STARTUPINFOW uses the standard input, output, and error handles. */
4
+ export const STARTF_USESTDHANDLES = 0x00000100
5
+ /** STARTUPINFOW applies wShowWindow when creating a console window. */
6
+ export const STARTF_USESHOWWINDOW = 0x00000001
7
+ /** Initial window visibility that preserves the child's console attachment. */
8
+ export const SW_HIDE = 0
9
+ /** HandleInformation flag that permits child inheritance. */
10
+ export const HANDLE_FLAG_INHERIT = 0x1
11
+ /** Infinite WaitForSingleObject timeout. */
12
+ export const INFINITE = 0xFFFFFFFF
13
+ /** WaitForSingleObject returned because a zero-time probe is not signalled. */
14
+ export const WAIT_TIMEOUT = 258
15
+ /** CreateProcess flag that prevents user code from running before resume. */
16
+ export const CREATE_SUSPENDED = 0x4
17
+ /** CreateProcess flag selecting a UTF-16 environment block. */
18
+ export const CREATE_UNICODE_ENVIRONMENT = 0x400
19
+ /** GetStdHandle selector for standard input. */
20
+ export const STD_INPUT_HANDLE = -10
21
+ /** GetStdHandle selector for standard output. */
22
+ export const STD_OUTPUT_HANDLE = -11
23
+ /** GetStdHandle selector for standard error. */
24
+ export const STD_ERROR_HANDLE = -12
25
+ /** FormatMessage reads the operating system message table. */
26
+ export const FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
27
+ /** FormatMessage leaves insertion placeholders uninterpreted. */
28
+ export const FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
29
+ /** Win32 code reporting a caller-provided buffer is too small. */
30
+ export const ERROR_INSUFFICIENT_BUFFER = 122
31
+ /** Win32 code reporting that the other pipe end closed. */
32
+ export const ERROR_BROKEN_PIPE = 109
33
+ /** Win32 code reporting that a pipe has no remaining data. */
34
+ export const ERROR_NO_DATA = 232
35
+ /** Job limit that terminates every member when the final Job handle closes. */
36
+ export const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
37
+ /** QueryInformationJobObject class for basic accounting and active-process count. */
38
+ export const JobObjectBasicAccountingInformation = 1
39
+ /** SetInformationJobObject class for JOBOBJECT_EXTENDED_LIMIT_INFORMATION. */
40
+ export const JobObjectExtendedLimitInformation = 9
41
+ /** x64 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION byte size. */
42
+ export const JOBOBJECT_BASIC_ACCOUNTING_SIZE = 48
43
+ /** Byte offset of ActiveProcesses in JOBOBJECT_BASIC_ACCOUNTING_INFORMATION. */
44
+ export const JOBOBJECT_BASIC_ACCOUNTING_ACTIVE_PROCESSES_OFFSET = 40
45
+ /** x64 JOBOBJECT_EXTENDED_LIMIT_INFORMATION byte size. */
46
+ export const JOBOBJECT_EXTENDED_LIMIT_SIZE = 144
47
+ /** Byte offset of BasicLimitInformation.LimitFlags in the extended Job record. */
48
+ export const JOBOBJECT_EXTENDED_LIMIT_FLAGS_OFFSET = 16
49
+ /** x64 STARTUPINFOW byte size verified by the native probe. */
50
+ export const STARTUPINFOW_SIZE = 104
51
+ /** x64 PROCESS_INFORMATION byte size verified by the native probe. */
52
+ export const PROCESS_INFORMATION_SIZE = 24
@@ -0,0 +1,47 @@
1
+ /** Windows CRT startup descriptors for a Node payload with one inherited control pipe. */
2
+
3
+ import type { NativePtr, Win32ProcessBindings } from './ffi.ts'
4
+
5
+ /** Native stdio handles plus the single additional descriptor selected by the launcher. */
6
+ export interface InheritedControlStdio {
7
+ stdin: NativePtr
8
+ stdout: NativePtr
9
+ stderr: NativePtr
10
+ control: { fileDescriptor: 7; handle: NativePtr }
11
+ }
12
+
13
+ const HANDLE_BYTES = 8
14
+ const INVALID_HANDLE = 0xffff_ffff_ffff_ffffn
15
+ const FOPEN = 0x01
16
+ const FPIPE = 0x08
17
+ const FDEV = 0x40
18
+ const FILE_TYPE_CHAR = 2
19
+ const FILE_TYPE_PIPE = 3
20
+
21
+ /**
22
+ * Encode the CRT's descriptor table before the child runtime allocates descriptors.
23
+ * Supported Windows targets use 64-bit handles. Empty slots remain closed, and the
24
+ * backing Buffer must remain alive until CreateProcess returns.
25
+ * @param api - native file-type inspection for inherited handles.
26
+ * @param stdio - standard handles and the provider-owned fd-7 control pipe.
27
+ * @returns descriptor count, flag bytes, and handle values for STARTUPINFO's reserved CRT fields.
28
+ */
29
+ export function inheritedControlStdio(api: Pick<Win32ProcessBindings, 'getFileType'>, stdio: InheritedControlStdio): Buffer {
30
+ const count = stdio.control.fileDescriptor + 1
31
+ const handleOffset = 4 + count
32
+ const bytes = Buffer.alloc(handleOffset + count * HANDLE_BYTES)
33
+ bytes.writeUInt32LE(count, 0)
34
+ for (let index = 0; index < count; index++) {
35
+ bytes.writeBigUInt64LE(INVALID_HANDLE, handleOffset + index * HANDLE_BYTES)
36
+ }
37
+ const entries = [[0, stdio.stdin], [1, stdio.stdout], [2, stdio.stderr], [stdio.control.fileDescriptor, stdio.control.handle]] as const
38
+ for (const [fd, handle] of entries) {
39
+ const kind = api.getFileType(handle)
40
+ if (fd === stdio.control.fileDescriptor && kind !== FILE_TYPE_PIPE) {
41
+ throw new Error('subprocess control descriptor is not a Windows pipe')
42
+ }
43
+ bytes[4 + fd] = FOPEN | (kind === FILE_TYPE_PIPE ? FPIPE : kind === FILE_TYPE_CHAR ? FDEV : 0)
44
+ bytes.writeBigUInt64LE(handle, handleOffset + fd * HANDLE_BYTES)
45
+ }
46
+ return bytes
47
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { HarnessError } from '@unieai/rabi-error'
2
+
3
+ /** Code of every {@link Win32Error}; the failing API and its numeric code stay in `api`, `win32Code`, and `message`. */
4
+ export const WIN32_ERROR = 'WIN32_ERROR'
5
+
6
+ /** Win32 call failure with the exact API name and error code. */
7
+ export class Win32Error extends HarnessError {
8
+ /** Win32 function whose checked result failed. */
9
+ readonly api: string
10
+ /** Exact GetLastError value or direct Win32 API error code. */
11
+ readonly win32Code: number
12
+
13
+ /**
14
+ * @param api - Win32 function whose checked result failed.
15
+ * @param win32Code - exact GetLastError value or direct API error code.
16
+ * @param detail - optional subject, such as the path the call targeted.
17
+ */
18
+ constructor(api: string, win32Code: number, detail?: string) {
19
+ super(`${api} failed (Win32 ${win32Code})${detail === undefined ? '' : `: ${detail}`}`, WIN32_ERROR)
20
+ this.name = 'Win32Error'
21
+ this.api = api
22
+ this.win32Code = win32Code
23
+ }
24
+ }
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('RABI_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('RABI_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 '@unieai/rabi-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)
package/src/process.ts ADDED
@@ -0,0 +1,641 @@
1
+ /** Typed Win32 process operations over the shared binding table. */
2
+
3
+ import * as abi from './abi.ts'
4
+ import { inheritedControlStdio } from './control-stdio.ts'
5
+ import {
6
+ allocProcessInfo,
7
+ allocPtrSlot,
8
+ allocStartupInfo,
9
+ allocUint32,
10
+ decodeProcessInfo,
11
+ decodePtr,
12
+ decodeUint32,
13
+ encodeStartupInfo,
14
+ isNullPtr,
15
+ throwLastError,
16
+ throwWin32,
17
+ } from './ffi.ts'
18
+ import type { CurrentTokenProcessBindings, NativePtr, Win32ProcessBindings } from './ffi.ts'
19
+ import { requireKoffi } from './koffi.ts'
20
+
21
+ /**
22
+ * Quote one argument according to CommandLineToArgvW parsing.
23
+ * @param argument - one argv entry.
24
+ * @returns bare or quoted command-line segment.
25
+ */
26
+ export function quoteArg(argument: string): string {
27
+ if (argument === '') return '""'
28
+ if (!/[\s"]/u.test(argument)) return argument
29
+ let quoted = '"'
30
+ for (let index = 0; index < argument.length; index++) {
31
+ let backslashes = 0
32
+ while (index < argument.length && argument.charAt(index) === '\\') {
33
+ backslashes += 1
34
+ index += 1
35
+ }
36
+ if (index === argument.length) {
37
+ quoted += '\\'.repeat(backslashes * 2)
38
+ } else if (argument.charAt(index) === '"') {
39
+ quoted += '\\'.repeat(backslashes * 2 + 1) + '"'
40
+ } else {
41
+ quoted += '\\'.repeat(backslashes) + argument.charAt(index)
42
+ }
43
+ }
44
+ return quoted + '"'
45
+ }
46
+
47
+ /**
48
+ * Build the mutable command line accepted by CreateProcessAsUserW.
49
+ * @param program - executable argv entry.
50
+ * @param args - remaining argv entries.
51
+ * @returns joined Win32 command line.
52
+ */
53
+ export function buildCommandLine(program: string, args: readonly string[]): string {
54
+ return [program, ...args].map(quoteArg).join(' ')
55
+ }
56
+
57
+ function compareWindowsEnvironmentKeys(
58
+ [left]: readonly [string, string],
59
+ [right]: readonly [string, string],
60
+ ): number {
61
+ const foldedLeft = left.toUpperCase()
62
+ const foldedRight = right.toUpperCase()
63
+ return foldedLeft < foldedRight ? -1 : foldedLeft > foldedRight ? 1 : 0
64
+ }
65
+
66
+ function encodeWindowsEnvironment(env: Readonly<Record<string, string>>): Buffer {
67
+ const entries = Object.entries(env).sort(compareWindowsEnvironmentKeys)
68
+ const strings = entries.map(([key, value]) => `${key}=${value}`)
69
+ return Buffer.from(`${strings.join('\0')}\0\0`, 'utf16le')
70
+ }
71
+
72
+ interface ProcessSpawnOptions {
73
+ /** Executable argv entry passed through CreateProcess. */
74
+ command: string
75
+ /** Arguments excluding the executable. */
76
+ args: readonly string[]
77
+ /** Existing child working directory. */
78
+ cwd: string
79
+ }
80
+
81
+ /** Ordinary process creation inputs used by the local Win32 runner. */
82
+ export interface CurrentTokenProcessSpawnOptions extends ProcessSpawnOptions {
83
+ /** Resolved executable path passed separately from the preserved argv entry. */
84
+ applicationName: string
85
+ /** Complete target environment passed without mutating the runner. */
86
+ env: Readonly<Record<string, string>>
87
+ /** Runner CRT descriptors carrying target stdin, stdout, and stderr. */
88
+ stdio: CurrentTokenStdioFileDescriptors
89
+ }
90
+
91
+ /** Runner CRT descriptors whose OS handles become the target standard handles. */
92
+ export interface CurrentTokenStdioFileDescriptors {
93
+ stdin: number
94
+ stdout: number
95
+ stderr: number
96
+ /** Optional carrier and target descriptor for the inherited control pipe. */
97
+ control?: 7
98
+ }
99
+
100
+ /** Restricted-token process creation inputs owned by the Windows ACL sandbox. */
101
+ export interface RestrictedProcessSpawnOptions extends ProcessSpawnOptions {
102
+ /** Restricted primary token supplied by sandbox policy. */
103
+ token: NativePtr
104
+ /** Optional control pipe inherited at the same descriptor in the payload. */
105
+ controlFileDescriptor?: 7
106
+ }
107
+
108
+ /** Piped child resources whose process and read handles remain caller-owned. */
109
+ export interface SpawnedPipedProcess {
110
+ /** Direct child process id. */
111
+ pid: number
112
+ /** Process handle closed by waitForProcessExit. */
113
+ process: NativePtr
114
+ /** Stdout pipe read end closed by drainPipe. */
115
+ stdoutRead: NativePtr
116
+ /** Stderr pipe read end closed by drainPipe. */
117
+ stderrRead: NativePtr
118
+ }
119
+
120
+ /** Suspended child assigned to one caller-owned kill-on-close Job before resume. */
121
+ export interface SpawnedJobProcess {
122
+ /** Direct child process id. */
123
+ pid: number
124
+ /** Process handle closed by waitForProcessExit. */
125
+ process: NativePtr
126
+ /** Job handle closed by the lifecycle owner. */
127
+ job: NativePtr
128
+ }
129
+
130
+ interface PipePair {
131
+ read: NativePtr
132
+ write: NativePtr
133
+ }
134
+
135
+ function freeNative(pointer: NativePtr | undefined): void {
136
+ if (pointer !== undefined) requireKoffi().free(pointer)
137
+ }
138
+
139
+ function closeBestEffort(api: Win32ProcessBindings, handle: NativePtr | null | undefined): void {
140
+ if (!isNullPtr(handle)) api.closeHandle(handle)
141
+ }
142
+
143
+ function createPipe(api: Win32ProcessBindings, owned: Set<NativePtr>): PipePair {
144
+ const readSlot = allocPtrSlot()
145
+ let writeSlot: NativePtr | undefined
146
+ try {
147
+ writeSlot = allocPtrSlot()
148
+ if (api.createPipe(readSlot, writeSlot, null, 0) === 0) throwLastError(api, 'CreatePipe')
149
+ const read = decodePtr(readSlot)
150
+ const write = decodePtr(writeSlot)
151
+ if (read === null || write === null) {
152
+ closeBestEffort(api, read)
153
+ closeBestEffort(api, write)
154
+ throwLastError(api, 'CreatePipe', 'null pipe handle')
155
+ }
156
+ owned.add(read)
157
+ owned.add(write)
158
+ return { read, write }
159
+ } finally {
160
+ freeNative(writeSlot)
161
+ requireKoffi().free(readSlot)
162
+ }
163
+ }
164
+
165
+ function closeOwned(api: Win32ProcessBindings, owned: Set<NativePtr>, handle: NativePtr): void {
166
+ /* v8 ignore next -- each successfully decoded pipe end is uniquely owned. */
167
+ if (!owned.delete(handle)) return
168
+ api.closeHandle(handle)
169
+ }
170
+
171
+ function closeAllOwned(api: Win32ProcessBindings, owned: Set<NativePtr>): void {
172
+ for (const handle of owned) api.closeHandle(handle)
173
+ owned.clear()
174
+ }
175
+
176
+ function createRestrictedProcess(
177
+ api: Win32ProcessBindings,
178
+ options: RestrictedProcessSpawnOptions,
179
+ commandLine: string,
180
+ creationFlags: number,
181
+ startupInfo: NativePtr,
182
+ processInfo: NativePtr,
183
+ ): number {
184
+ // The sandbox mutates its process environment before this call. Passing an
185
+ // explicit block through Koffi makes CreateProcessAsUserW reject the request
186
+ // with ERROR_INVALID_PARAMETER, so lpEnvironment remains NULL.
187
+ return api.createProcessAsUserW(
188
+ options.token,
189
+ null,
190
+ commandLine,
191
+ null,
192
+ null,
193
+ 1,
194
+ creationFlags,
195
+ null,
196
+ options.cwd,
197
+ startupInfo,
198
+ processInfo,
199
+ )
200
+ }
201
+
202
+ /**
203
+ * Spawn a process with anonymous-pipe stdout/stderr and immediate stdin EOF.
204
+ * New console windows start hidden without changing console inheritance.
205
+ * @param api - active binding table.
206
+ * @param options - command, cwd, args, and restricted primary token.
207
+ * @returns caller-owned process and pipe read handles.
208
+ */
209
+ export function spawnPipedProcess(
210
+ api: Win32ProcessBindings,
211
+ options: RestrictedProcessSpawnOptions,
212
+ ): SpawnedPipedProcess {
213
+ const owned = new Set<NativePtr>()
214
+ let startupInfo: NativePtr | undefined
215
+ let processInfo: NativePtr | undefined
216
+ try {
217
+ const stdIn = createPipe(api, owned)
218
+ const stdOut = createPipe(api, owned)
219
+ const stdErr = createPipe(api, owned)
220
+ for (const [handle, label] of [
221
+ [stdIn.read, 'stdin read end'],
222
+ [stdOut.write, 'stdout write end'],
223
+ [stdErr.write, 'stderr write end'],
224
+ ] as const) {
225
+ if (api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, abi.HANDLE_FLAG_INHERIT) === 0) {
226
+ throwLastError(api, 'SetHandleInformation', label)
227
+ }
228
+ }
229
+ startupInfo = allocStartupInfo()
230
+ encodeStartupInfo(startupInfo, {
231
+ cb: abi.STARTUPINFOW_SIZE,
232
+ dwFlags: abi.STARTF_USESTDHANDLES | abi.STARTF_USESHOWWINDOW,
233
+ wShowWindow: abi.SW_HIDE,
234
+ hStdInput: stdIn.read,
235
+ hStdOutput: stdOut.write,
236
+ hStdError: stdErr.write,
237
+ })
238
+ processInfo = allocProcessInfo()
239
+ const created = createRestrictedProcess(
240
+ api,
241
+ options,
242
+ buildCommandLine(options.command, options.args),
243
+ 0,
244
+ startupInfo,
245
+ processInfo,
246
+ )
247
+ if (created === 0) {
248
+ const win32Code = api.getLastError()
249
+ throwWin32(api, 'CreateProcessAsUserW', win32Code, `command: ${options.command}, cwd: ${options.cwd}`)
250
+ }
251
+ const info = decodeProcessInfo(processInfo)
252
+ if (info.hProcess === null || info.hThread === null) {
253
+ if (info.hProcess !== null) api.terminateProcess(info.hProcess, 1)
254
+ closeBestEffort(api, info.hThread)
255
+ closeBestEffort(api, info.hProcess)
256
+ throw new Error(`CreateProcessAsUserW succeeded but returned null process/thread handles (pid ${info.dwProcessId})`)
257
+ }
258
+ closeOwned(api, owned, stdIn.read)
259
+ closeOwned(api, owned, stdIn.write)
260
+ closeOwned(api, owned, stdOut.write)
261
+ closeOwned(api, owned, stdErr.write)
262
+ closeBestEffort(api, info.hThread)
263
+ owned.delete(stdOut.read)
264
+ owned.delete(stdErr.read)
265
+ return {
266
+ pid: info.dwProcessId,
267
+ process: info.hProcess,
268
+ stdoutRead: stdOut.read,
269
+ stderrRead: stdErr.read,
270
+ }
271
+ } catch (error) {
272
+ closeAllOwned(api, owned)
273
+ throw error
274
+ } finally {
275
+ freeNative(processInfo)
276
+ freeNative(startupInfo)
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Drain one anonymous pipe until the writer closes it.
282
+ * @param api - active binding table.
283
+ * @param handle - caller-owned pipe read end.
284
+ * @returns complete bytes read before EOF; the handle is always closed.
285
+ * @throws when a Win32 pipe operation fails.
286
+ */
287
+ export async function drainPipe(
288
+ api: Win32ProcessBindings,
289
+ handle: NativePtr,
290
+ ): Promise<Buffer> {
291
+ const chunks: Buffer[] = []
292
+ let countSlot: NativePtr | undefined
293
+ try {
294
+ countSlot = allocUint32()
295
+ for (;;) {
296
+ const peeked = api.peekNamedPipe(handle, null, 0, null, countSlot, null)
297
+ if (peeked === 0) {
298
+ const win32Code = api.getLastError()
299
+ if (win32Code === abi.ERROR_BROKEN_PIPE || win32Code === abi.ERROR_NO_DATA) break
300
+ throwLastError(api, 'PeekNamedPipe', `drain failure after ${chunks.length} chunk(s)`)
301
+ }
302
+ const available = decodeUint32(countSlot)
303
+ if (available > 0) {
304
+ const chunk = Buffer.alloc(available)
305
+ if (api.readFile(handle, chunk, chunk.length, countSlot, null) === 0) {
306
+ throwLastError(api, 'ReadFile', `drain failure after ${chunks.length} chunk(s)`)
307
+ }
308
+ chunks.push(chunk.subarray(0, decodeUint32(countSlot)))
309
+ }
310
+ await new Promise<void>(resolve => setTimeout(resolve, 1))
311
+ }
312
+ return Buffer.concat(chunks)
313
+ } finally {
314
+ freeNative(countSlot)
315
+ api.closeHandle(handle)
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Wait for a process and always close its handle.
321
+ * @param api - active binding table.
322
+ * @param process - caller-owned process handle.
323
+ * @returns direct process exit code.
324
+ */
325
+ export function waitForProcessExit(api: Win32ProcessBindings, process: NativePtr): number {
326
+ let exitCodeSlot: NativePtr | undefined
327
+ try {
328
+ if (api.waitForSingleObject(process, abi.INFINITE) === 0xFFFFFFFF) {
329
+ throwLastError(api, 'WaitForSingleObject')
330
+ }
331
+ exitCodeSlot = allocUint32()
332
+ if (api.getExitCodeProcess(process, exitCodeSlot) === 0) throwLastError(api, 'GetExitCodeProcess')
333
+ return decodeUint32(exitCodeSlot)
334
+ } finally {
335
+ freeNative(exitCodeSlot)
336
+ api.closeHandle(process)
337
+ }
338
+ }
339
+
340
+ function createKillOnCloseJob(api: Win32ProcessBindings): NativePtr {
341
+ const job = api.createJobObjectW(null, null)
342
+ if (isNullPtr(job)) throwLastError(api, 'CreateJobObjectW')
343
+ const information = Buffer.alloc(abi.JOBOBJECT_EXTENDED_LIMIT_SIZE)
344
+ information.writeUInt32LE(
345
+ abi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
346
+ abi.JOBOBJECT_EXTENDED_LIMIT_FLAGS_OFFSET,
347
+ )
348
+ if (api.setInformationJobObject(
349
+ job,
350
+ abi.JobObjectExtendedLimitInformation,
351
+ information,
352
+ information.length,
353
+ ) === 0) {
354
+ const win32Code = api.getLastError()
355
+ api.closeHandle(job)
356
+ throwWin32(api, 'SetInformationJobObject', win32Code)
357
+ }
358
+ return job
359
+ }
360
+
361
+ interface ProcessStandardHandles {
362
+ stdin: NativePtr
363
+ stdout: NativePtr
364
+ stderr: NativePtr
365
+ control?: { fileDescriptor: 7; handle: NativePtr }
366
+ }
367
+
368
+ // Koffi exposes PVOID as an unsigned 64-bit bigint on supported Windows hosts.
369
+ const UV_INVALID_OS_FILE_HANDLE = 0xffff_ffff_ffff_ffffn
370
+ const UV_INVALID_FILE_DESCRIPTOR = 0xffff_ffff_ffff_fffen
371
+
372
+ function inheritedStandardHandles(api: Win32ProcessBindings, controlFileDescriptor?: 7): ProcessStandardHandles {
373
+ const get = (selector: number, label: string): NativePtr => {
374
+ const handle = api.getStdHandle(selector)
375
+ if (!isNullPtr(handle)) return handle
376
+ throwLastError(api, 'GetStdHandle', `null ${label} handle`)
377
+ }
378
+ return {
379
+ stdin: get(abi.STD_INPUT_HANDLE, 'stdin'),
380
+ stdout: get(abi.STD_OUTPUT_HANDLE, 'stdout'),
381
+ stderr: get(abi.STD_ERROR_HANDLE, 'stderr'),
382
+ ...controlFileDescriptor === undefined ? {} : {
383
+ control: { fileDescriptor: controlFileDescriptor, handle: descriptorHandle(api, controlFileDescriptor, 'control') },
384
+ },
385
+ }
386
+ }
387
+
388
+ function descriptorHandle(api: Win32ProcessBindings, fileDescriptor: number, label: string): NativePtr {
389
+ const handle = api.uvGetOsfhandle(fileDescriptor)
390
+ if (
391
+ isNullPtr(handle)
392
+ || handle === UV_INVALID_OS_FILE_HANDLE
393
+ || handle === UV_INVALID_FILE_DESCRIPTOR
394
+ ) {
395
+ throw new Error(`uv_get_osfhandle returned an invalid handle for target ${label} fd ${String(fileDescriptor)}`)
396
+ }
397
+ return handle
398
+ }
399
+
400
+ function targetCarrierHandles(
401
+ api: CurrentTokenProcessBindings,
402
+ descriptors: CurrentTokenStdioFileDescriptors,
403
+ ): ProcessStandardHandles {
404
+ return {
405
+ stdin: descriptorHandle(api, descriptors.stdin, 'stdin'),
406
+ stdout: descriptorHandle(api, descriptors.stdout, 'stdout'),
407
+ stderr: descriptorHandle(api, descriptors.stderr, 'stderr'),
408
+ ...descriptors.control === undefined ? {} : {
409
+ control: { fileDescriptor: descriptors.control, handle: descriptorHandle(api, descriptors.control, 'control') },
410
+ },
411
+ }
412
+ }
413
+
414
+ /** Shared suspended-create, Job-assignment, and resume lifecycle. */
415
+ function spawnJobProcess(
416
+ api: Win32ProcessBindings,
417
+ options: ProcessSpawnOptions,
418
+ resolveStdio: () => ProcessStandardHandles,
419
+ createName: 'CreateProcessAsUserW' | 'CreateProcessW',
420
+ create: (startupInfo: NativePtr, processInfo: NativePtr) => number,
421
+ ): SpawnedJobProcess {
422
+ const job = createKillOnCloseJob(api)
423
+ const enabled: NativePtr[] = []
424
+ let startupInfo: NativePtr | undefined
425
+ let processInfo: NativePtr | undefined
426
+ let controlDescriptorBlock: { pointer: NativePtr; length: number } | undefined
427
+ let created = 0
428
+ let createFailureCode = 0
429
+ try {
430
+ const stdio = resolveStdio()
431
+ const inherited: Array<readonly [NativePtr, string]> = [
432
+ [stdio.stdin, 'stdin'],
433
+ [stdio.stdout, 'stdout'],
434
+ [stdio.stderr, 'stderr'],
435
+ ]
436
+ if (stdio.control !== undefined) inherited.push([stdio.control.handle, 'control'])
437
+ for (const [handle, label] of inherited) {
438
+ if (api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, abi.HANDLE_FLAG_INHERIT) === 0) {
439
+ throwLastError(api, 'SetHandleInformation', `${label} (enable inherit)`)
440
+ }
441
+ enabled.push(handle)
442
+ }
443
+ const controlBytes = stdio.control === undefined
444
+ ? undefined
445
+ : inheritedControlStdio(api, { ...stdio, control: stdio.control })
446
+ if (controlBytes !== undefined) {
447
+ const koffi = requireKoffi()
448
+ controlDescriptorBlock = { pointer: koffi.alloc('uint8', controlBytes.length) as NativePtr, length: controlBytes.length }
449
+ koffi.encode(controlDescriptorBlock.pointer, 'uint8', controlBytes, controlBytes.length)
450
+ }
451
+ startupInfo = allocStartupInfo()
452
+ encodeStartupInfo(startupInfo, {
453
+ cb: abi.STARTUPINFOW_SIZE,
454
+ // Preserve console inheritance: CREATE_NO_WINDOW can fail restricted-token DLL initialization.
455
+ dwFlags: abi.STARTF_USESTDHANDLES | abi.STARTF_USESHOWWINDOW,
456
+ wShowWindow: abi.SW_HIDE,
457
+ hStdInput: stdio.stdin,
458
+ hStdOutput: stdio.stdout,
459
+ hStdError: stdio.stderr,
460
+ ...controlDescriptorBlock === undefined ? {} : {
461
+ cbReserved2: controlDescriptorBlock.length,
462
+ lpReserved2: controlDescriptorBlock.pointer,
463
+ },
464
+ })
465
+ processInfo = allocProcessInfo()
466
+ created = create(startupInfo, processInfo)
467
+ if (created === 0) createFailureCode = api.getLastError()
468
+ } catch (error) {
469
+ freeNative(processInfo)
470
+ api.closeHandle(job)
471
+ throw error
472
+ } finally {
473
+ freeNative(startupInfo)
474
+ freeNative(controlDescriptorBlock?.pointer)
475
+ for (const handle of enabled) {
476
+ // The runner spawns nothing else; cleanup failure must not mask the child.
477
+ api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, 0)
478
+ }
479
+ }
480
+ if (created === 0) {
481
+ freeNative(processInfo)
482
+ api.closeHandle(job)
483
+ throwWin32(
484
+ api,
485
+ createName,
486
+ createFailureCode,
487
+ `command: ${options.command}, cwd: ${options.cwd}`,
488
+ )
489
+ }
490
+ let info: ReturnType<typeof decodeProcessInfo>
491
+ try {
492
+ info = decodeProcessInfo(processInfo)
493
+ } finally {
494
+ freeNative(processInfo)
495
+ }
496
+ if (info.hProcess === null || info.hThread === null) {
497
+ if (info.hProcess !== null) api.terminateProcess(info.hProcess, 1)
498
+ api.closeHandle(job)
499
+ closeBestEffort(api, info.hThread)
500
+ closeBestEffort(api, info.hProcess)
501
+ throw new Error(`${createName} succeeded but returned null process/thread handles (pid ${info.dwProcessId})`)
502
+ }
503
+ if (api.assignProcessToJobObject(job, info.hProcess) === 0) {
504
+ const win32Code = api.getLastError()
505
+ api.terminateProcess(info.hProcess, 1)
506
+ closeBestEffort(api, info.hThread)
507
+ closeBestEffort(api, info.hProcess)
508
+ api.closeHandle(job)
509
+ throwWin32(api, 'AssignProcessToJobObject', win32Code, `pid ${info.dwProcessId}`)
510
+ }
511
+ if (api.resumeThread(info.hThread) === 0xFFFFFFFF) {
512
+ const win32Code = api.getLastError()
513
+ closeBestEffort(api, info.hThread)
514
+ closeBestEffort(api, info.hProcess)
515
+ api.closeHandle(job)
516
+ throwWin32(api, 'ResumeThread', win32Code, `pid ${info.dwProcessId}`)
517
+ }
518
+ closeBestEffort(api, info.hThread)
519
+ return { pid: info.dwProcessId, process: info.hProcess, job }
520
+ }
521
+
522
+ /**
523
+ * Spawn a restricted-token process suspended with hidden initial windows, assign its Job, then resume it.
524
+ * @param api - active binding table.
525
+ * @param options - command, cwd, args, and restricted primary token.
526
+ * @returns caller-owned process and Job handles after successful resume.
527
+ * @remarks Node clears stdio handle inheritability at startup through
528
+ * uv_disable_stdio_inheritance. This operation temporarily restores the bits
529
+ * required by STARTF_USESTDHANDLES. Restoring them afterward is best-effort:
530
+ * failure must not replace the already-created child's outcome.
531
+ */
532
+ export function spawnInheritedJobProcess(
533
+ api: Win32ProcessBindings,
534
+ options: RestrictedProcessSpawnOptions,
535
+ ): SpawnedJobProcess {
536
+ const commandLine = buildCommandLine(options.command, options.args)
537
+ return spawnJobProcess(api, options, () => inheritedStandardHandles(api, options.controlFileDescriptor), 'CreateProcessAsUserW', (startupInfo, processInfo) =>
538
+ createRestrictedProcess(
539
+ api,
540
+ options,
541
+ commandLine,
542
+ abi.CREATE_SUSPENDED,
543
+ startupInfo,
544
+ processInfo,
545
+ ))
546
+ }
547
+
548
+ /**
549
+ * Spawn an ordinary process suspended with hidden initial windows, assign its Job, then resume it.
550
+ * @param api - active binding table.
551
+ * @param options - command, cwd, argv, and target carrier descriptors.
552
+ * @returns caller-owned process and Job handles after successful resume.
553
+ */
554
+ export function spawnCurrentTokenJobProcess(
555
+ api: CurrentTokenProcessBindings,
556
+ options: CurrentTokenProcessSpawnOptions,
557
+ ): SpawnedJobProcess {
558
+ const commandLine = buildCommandLine(options.command, options.args)
559
+ const environment = encodeWindowsEnvironment(options.env)
560
+ return spawnJobProcess(api, options, () => targetCarrierHandles(api, options.stdio), 'CreateProcessW', (startupInfo, processInfo) =>
561
+ api.createProcessW(
562
+ options.applicationName,
563
+ commandLine,
564
+ null,
565
+ null,
566
+ 1,
567
+ abi.CREATE_SUSPENDED | abi.CREATE_UNICODE_ENVIRONMENT,
568
+ environment,
569
+ options.cwd,
570
+ startupInfo,
571
+ processInfo,
572
+ ))
573
+ }
574
+
575
+ /**
576
+ * Verify that an unnamed kill-on-close Job can be created and released now.
577
+ * @param api - active binding table.
578
+ */
579
+ export function probeCurrentTokenJobSupport(api: CurrentTokenProcessBindings): void {
580
+ const job = createKillOnCloseJob(api)
581
+ closeHandleChecked(api, job, 'current-token Job capability probe')
582
+ }
583
+
584
+ /**
585
+ * Poll one process handle without blocking the runner event loop.
586
+ * @param api - active binding table.
587
+ * @param process - caller-owned process handle.
588
+ * @returns the direct exit code when signalled, or undefined while running.
589
+ */
590
+ export function pollProcessExit(api: Win32ProcessBindings, process: NativePtr): number | undefined {
591
+ const waitResult = api.waitForSingleObject(process, 0)
592
+ if (waitResult === abi.WAIT_TIMEOUT) return undefined
593
+ if (waitResult === 0xFFFFFFFF) throwLastError(api, 'WaitForSingleObject')
594
+ const exitCodeSlot = allocUint32()
595
+ try {
596
+ if (api.getExitCodeProcess(process, exitCodeSlot) === 0) throwLastError(api, 'GetExitCodeProcess')
597
+ return decodeUint32(exitCodeSlot)
598
+ } finally {
599
+ requireKoffi().free(exitCodeSlot)
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Return whether a Job has no active processes.
605
+ * @param api - active binding table.
606
+ * @param job - caller-owned Job handle.
607
+ * @returns true once the Job reports zero active processes.
608
+ */
609
+ export function isJobEmpty(api: Win32ProcessBindings, job: NativePtr): boolean {
610
+ const information = Buffer.alloc(abi.JOBOBJECT_BASIC_ACCOUNTING_SIZE)
611
+ if (api.queryInformationJobObject(
612
+ job,
613
+ abi.JobObjectBasicAccountingInformation,
614
+ information,
615
+ information.length,
616
+ null,
617
+ ) === 0) {
618
+ throwLastError(api, 'QueryInformationJobObject', 'active process count')
619
+ }
620
+ return information.readUInt32LE(abi.JOBOBJECT_BASIC_ACCOUNTING_ACTIVE_PROCESSES_OFFSET) === 0
621
+ }
622
+
623
+ /**
624
+ * Terminate every process in a Job.
625
+ * @param api - active binding table.
626
+ * @param job - caller-owned Job handle.
627
+ * @param exitCode - direct Windows exit code assigned to members.
628
+ */
629
+ export function terminateJob(api: Win32ProcessBindings, job: NativePtr, exitCode: number): void {
630
+ if (api.terminateJobObject(job, exitCode) === 0) throwLastError(api, 'TerminateJobObject')
631
+ }
632
+
633
+ /**
634
+ * Close a caller-owned handle and report a labelled Win32 failure.
635
+ * @param api - active binding table.
636
+ * @param handle - handle to close.
637
+ * @param detail - lifecycle label for diagnostics.
638
+ */
639
+ export function closeHandleChecked(api: Win32ProcessBindings, handle: NativePtr, detail: string): void {
640
+ if (api.closeHandle(handle) === 0) throwLastError(api, 'CloseHandle', detail)
641
+ }