@palladin/cli 0.0.0-bootstrap → 0.0.9
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/README.md +500 -0
- package/SBOM.cdx.json +8990 -0
- package/SECURITY.md +32 -0
- package/dist/bin/palladin.d.ts +3 -0
- package/dist/bin/palladin.d.ts.map +1 -0
- package/dist/bin/palladin.js +6 -0
- package/dist/bin/palladin.js.map +1 -0
- package/dist/form-map.d.ts +35 -0
- package/dist/form-map.js +66 -0
- package/dist/inject-contract.d.ts +112 -0
- package/dist/inject-contract.js +133 -0
- package/dist/runtime/native-dispatch.d.ts +29 -0
- package/dist/runtime/native-dispatch.d.ts.map +1 -0
- package/dist/runtime/native-dispatch.js +425 -0
- package/dist/runtime/native-dispatch.js.map +1 -0
- package/dist/runtime/version-policy-build.d.ts +4 -0
- package/dist/runtime/version-policy-build.d.ts.map +1 -0
- package/dist/runtime/version-policy-build.js +5 -0
- package/dist/runtime/version-policy-build.js.map +1 -0
- package/dist/runtime/version-policy.d.ts +41 -0
- package/dist/runtime/version-policy.d.ts.map +1 -0
- package/dist/runtime/version-policy.js +230 -0
- package/dist/runtime/version-policy.js.map +1 -0
- package/dist/runtime/windows-runtime-cache.d.ts +32 -0
- package/dist/runtime/windows-runtime-cache.d.ts.map +1 -0
- package/dist/runtime/windows-runtime-cache.js +687 -0
- package/dist/runtime/windows-runtime-cache.js.map +1 -0
- package/package.json +41 -3
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
import { execFileSync, spawn, } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { constants as fsConstants, closeSync, copyFileSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
4
|
+
import { dirname, join, relative, win32 as windowsPath } from 'node:path';
|
|
5
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
6
|
+
const EXACT_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
|
7
|
+
const WINDOWS_PACKAGE = /^@palladin\/runtime-win32-(arm64|x64)$/;
|
|
8
|
+
const THUMBPRINT = /^(?:[0-9A-F]{40}|[0-9A-F]{64})$/;
|
|
9
|
+
const CACHE_SCHEMA = 'v1';
|
|
10
|
+
const CLIENT_FILENAME = 'palladin-client.exe';
|
|
11
|
+
const LEASE = /^(?:launcher|child)-(\d+)-[0-9a-f-]{36}\.lease$/;
|
|
12
|
+
const MAX_EXECUTABLE_BYTES = 256 * 1024 * 1024;
|
|
13
|
+
const SYSTEM_ROOT = '\\\\?\\GLOBALROOT\\SystemRoot';
|
|
14
|
+
const SYSTEM_POWERSHELL = '\\\\?\\GLOBALROOT\\SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
|
|
15
|
+
/**
|
|
16
|
+
* Copy the signed Windows launcher into a version/hash-specific public cache.
|
|
17
|
+
*
|
|
18
|
+
* npm may replace a platform package while an MCP process is still running.
|
|
19
|
+
* Windows locks loaded executables, so the runtime must never execute directly
|
|
20
|
+
* from node_modules. Cache entries contain no Agent state or credentials.
|
|
21
|
+
*/
|
|
22
|
+
export function prepareWindowsRuntimeCache(source, binding, options = {}) {
|
|
23
|
+
validateBinding(source, binding);
|
|
24
|
+
const verifyAuthenticode = options.verifyAuthenticode ?? verifySystemAuthenticode;
|
|
25
|
+
const expectedHash = binding.executableSha256;
|
|
26
|
+
verifyHash(source.executable, expectedHash);
|
|
27
|
+
const cacheRoot = canonicalCacheRoot(options.cacheRoot ?? systemCacheRoot(), options.cacheRoot === undefined);
|
|
28
|
+
const packageDirectory = join(cacheRoot, CACHE_SCHEMA, packageSegment(source.packageName));
|
|
29
|
+
const versionDirectory = join(packageDirectory, source.version);
|
|
30
|
+
ensurePlainDirectory(join(cacheRoot, CACHE_SCHEMA));
|
|
31
|
+
ensurePlainDirectory(packageDirectory);
|
|
32
|
+
ensurePlainDirectory(versionDirectory);
|
|
33
|
+
const entryDirectory = join(versionDirectory, expectedHash);
|
|
34
|
+
const cachedExecutable = join(entryDirectory, CLIENT_FILENAME);
|
|
35
|
+
if (existsSync(entryDirectory)) {
|
|
36
|
+
assertPlainDirectory(entryDirectory);
|
|
37
|
+
verifyHash(cachedExecutable, expectedHash);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
installCacheEntry(source.executable, entryDirectory, cachedExecutable, expectedHash, options.randomId ?? randomUUID);
|
|
41
|
+
}
|
|
42
|
+
// Re-check the source after policy lookup/copy. A concurrent npm update must
|
|
43
|
+
// fail this launch rather than mix files from two package versions.
|
|
44
|
+
verifyHash(source.executable, expectedHash);
|
|
45
|
+
const processId = options.processId ?? process.pid;
|
|
46
|
+
const randomId = options.randomId ?? randomUUID;
|
|
47
|
+
const leaseDirectory = join(cacheRoot, CACHE_SCHEMA, 'leases', entryIdentity(source, binding));
|
|
48
|
+
ensurePlainDirectory(join(cacheRoot, CACHE_SCHEMA, 'leases'));
|
|
49
|
+
ensurePlainDirectory(leaseDirectory);
|
|
50
|
+
let leasePath = createLease(leaseDirectory, 'launcher', processId, randomId());
|
|
51
|
+
let released = false;
|
|
52
|
+
collectInactiveEntries(cacheRoot, entryDirectory, options.processIsAlive ?? systemProcessIsAlive);
|
|
53
|
+
return {
|
|
54
|
+
executable: cachedExecutable,
|
|
55
|
+
verifyBeforeSpawn() {
|
|
56
|
+
if (released)
|
|
57
|
+
throw new Error('Palladin Windows runtime lease is closed');
|
|
58
|
+
verifyFile(cachedExecutable, expectedHash, binding, verifyAuthenticode);
|
|
59
|
+
},
|
|
60
|
+
spawnLocked(args, spawnOptions) {
|
|
61
|
+
if (released)
|
|
62
|
+
throw new Error('Palladin Windows runtime lease is closed');
|
|
63
|
+
return spawnLockedSystemRuntime(cachedExecutable, expectedHash, binding, args, spawnOptions);
|
|
64
|
+
},
|
|
65
|
+
bindToChild(childProcessId) {
|
|
66
|
+
if (released || childProcessId === undefined || !Number.isSafeInteger(childProcessId)
|
|
67
|
+
|| childProcessId <= 0)
|
|
68
|
+
return;
|
|
69
|
+
try {
|
|
70
|
+
const childLease = createLease(leaseDirectory, 'child', childProcessId, randomId());
|
|
71
|
+
removeLease(leasePath);
|
|
72
|
+
leasePath = childLease;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// The launcher lease remains valid while it waits for the child. A
|
|
76
|
+
// locked executable is retained even if the lease conversion fails.
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
release() {
|
|
80
|
+
if (released)
|
|
81
|
+
return;
|
|
82
|
+
released = true;
|
|
83
|
+
removeLease(leasePath);
|
|
84
|
+
removeEmptyDirectory(leaseDirectory);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export function sha256File(path) {
|
|
89
|
+
const descriptor = openSync(path, fsConstants.O_RDONLY);
|
|
90
|
+
try {
|
|
91
|
+
const size = fstatSync(descriptor).size;
|
|
92
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_EXECUTABLE_BYTES) {
|
|
93
|
+
throw new Error('Palladin Windows runtime size is invalid');
|
|
94
|
+
}
|
|
95
|
+
const hash = createHash('sha256');
|
|
96
|
+
const buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
97
|
+
let position = 0;
|
|
98
|
+
while (position < size) {
|
|
99
|
+
const length = readSync(descriptor, buffer, 0, Math.min(buffer.length, size - position), position);
|
|
100
|
+
if (length <= 0)
|
|
101
|
+
throw new Error('Palladin Windows runtime could not be read');
|
|
102
|
+
hash.update(buffer.subarray(0, length));
|
|
103
|
+
position += length;
|
|
104
|
+
}
|
|
105
|
+
return hash.digest('hex');
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
closeSync(descriptor);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function validateBinding(source, binding) {
|
|
112
|
+
if (!WINDOWS_PACKAGE.test(source.packageName) || !EXACT_VERSION.test(source.version)
|
|
113
|
+
|| binding.packageName !== source.packageName || binding.version !== source.version
|
|
114
|
+
|| !SHA256.test(binding.executableSha256)
|
|
115
|
+
|| typeof binding.authenticodePublisher !== 'string'
|
|
116
|
+
|| binding.authenticodePublisher.trim() === ''
|
|
117
|
+
|| binding.authenticodePublisher.length > 256
|
|
118
|
+
|| [...binding.authenticodePublisher].some((character) => character < ' ' || character > '~')
|
|
119
|
+
|| typeof binding.authenticodeThumbprint !== 'string'
|
|
120
|
+
|| !THUMBPRINT.test(binding.authenticodeThumbprint)) {
|
|
121
|
+
throw new Error('Palladin Windows runtime binding is invalid');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function verifyFile(path, expectedHash, binding, verifyAuthenticode) {
|
|
125
|
+
verifyHash(path, expectedHash);
|
|
126
|
+
const canonical = realpathSync(path);
|
|
127
|
+
verifyAuthenticode(canonical, binding);
|
|
128
|
+
verifyHash(canonical, expectedHash);
|
|
129
|
+
}
|
|
130
|
+
function verifyHash(path, expectedHash) {
|
|
131
|
+
const metadata = lstatSync(path);
|
|
132
|
+
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
133
|
+
throw new Error('Palladin Windows runtime is not a regular file');
|
|
134
|
+
}
|
|
135
|
+
const canonical = realpathSync(path);
|
|
136
|
+
if (sha256File(canonical) !== expectedHash) {
|
|
137
|
+
throw new Error('Palladin Windows runtime hash verification failed');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function installCacheEntry(sourceExecutable, entryDirectory, cachedExecutable, expectedHash, randomId) {
|
|
141
|
+
const versionDirectory = dirname(entryDirectory);
|
|
142
|
+
const temporary = join(versionDirectory, `.${expectedHash}.${randomId()}.tmp`);
|
|
143
|
+
const temporaryExecutable = join(temporary, CLIENT_FILENAME);
|
|
144
|
+
try {
|
|
145
|
+
mkdirSync(temporary, { recursive: false, mode: 0o700 });
|
|
146
|
+
copyFileSync(sourceExecutable, temporaryExecutable, fsConstants.COPYFILE_EXCL);
|
|
147
|
+
syncFile(temporaryExecutable);
|
|
148
|
+
verifyHash(temporaryExecutable, expectedHash);
|
|
149
|
+
try {
|
|
150
|
+
renameSync(temporary, entryDirectory);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (!existsSync(entryDirectory))
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
assertPlainDirectory(entryDirectory);
|
|
157
|
+
verifyHash(cachedExecutable, expectedHash);
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function verifySystemAuthenticode(path, binding) {
|
|
164
|
+
const publisher = binding.authenticodePublisher;
|
|
165
|
+
const thumbprint = binding.authenticodeThumbprint;
|
|
166
|
+
if (publisher === undefined || thumbprint === undefined) {
|
|
167
|
+
throw new Error('Palladin Windows runtime Authenticode binding is missing');
|
|
168
|
+
}
|
|
169
|
+
const { powershell, root: canonicalRoot, modulePath } = trustedPowerShell();
|
|
170
|
+
const script = [
|
|
171
|
+
"$ErrorActionPreference = 'Stop'",
|
|
172
|
+
'$env:PSModulePath = $env:PALLADIN_TRUSTED_MODULE_PATH',
|
|
173
|
+
'$env:WinPSModulePath = $env:PALLADIN_TRUSTED_MODULE_PATH',
|
|
174
|
+
'$signature = Get-AuthenticodeSignature -LiteralPath $env:PALLADIN_RUNTIME_PATH',
|
|
175
|
+
"$actualThumbprint = $signature.SignerCertificate.Thumbprint.Replace(' ', '').ToUpperInvariant()",
|
|
176
|
+
"if ($signature.Status -ne 'Valid') { exit 41 }",
|
|
177
|
+
'if ($actualThumbprint -cne $env:PALLADIN_EXPECTED_THUMBPRINT) { exit 42 }',
|
|
178
|
+
'if ($signature.SignerCertificate.Subject -cne $env:PALLADIN_EXPECTED_PUBLISHER) { exit 43 }',
|
|
179
|
+
'if ($null -eq $signature.TimeStamperCertificate) { exit 44 }',
|
|
180
|
+
].join('; ');
|
|
181
|
+
try {
|
|
182
|
+
execFileSync(powershell, [
|
|
183
|
+
'-NoLogo',
|
|
184
|
+
'-NoProfile',
|
|
185
|
+
'-NonInteractive',
|
|
186
|
+
'-Command',
|
|
187
|
+
script,
|
|
188
|
+
], {
|
|
189
|
+
encoding: 'utf8',
|
|
190
|
+
shell: false,
|
|
191
|
+
stdio: 'ignore',
|
|
192
|
+
timeout: 10_000,
|
|
193
|
+
windowsHide: true,
|
|
194
|
+
env: {
|
|
195
|
+
SystemRoot: canonicalRoot,
|
|
196
|
+
PSModulePath: '',
|
|
197
|
+
WinPSModulePath: '',
|
|
198
|
+
PALLADIN_TRUSTED_MODULE_PATH: modulePath,
|
|
199
|
+
PALLADIN_RUNTIME_PATH: path,
|
|
200
|
+
PALLADIN_EXPECTED_PUBLISHER: publisher,
|
|
201
|
+
PALLADIN_EXPECTED_THUMBPRINT: thumbprint,
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
throw new Error('Palladin Windows runtime Authenticode verification failed');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function spawnLockedSystemRuntime(path, expectedHash, binding, args, spawnOptions) {
|
|
210
|
+
const publisher = binding.authenticodePublisher;
|
|
211
|
+
const thumbprint = binding.authenticodeThumbprint;
|
|
212
|
+
if (publisher === undefined || thumbprint === undefined) {
|
|
213
|
+
throw new Error('Palladin Windows runtime Authenticode binding is missing');
|
|
214
|
+
}
|
|
215
|
+
const { powershell, root, modulePath } = trustedPowerShell();
|
|
216
|
+
const childEnvironment = spawnOptions.env ?? process.env;
|
|
217
|
+
const childPsModulePath = environmentValue(childEnvironment, 'PSModulePath');
|
|
218
|
+
const childWinPsModulePath = environmentValue(childEnvironment, 'WinPSModulePath');
|
|
219
|
+
const wrapperEnvironment = withoutEnvironmentKeys(childEnvironment, new Set(['psmodulepath', 'winpsmodulepath']));
|
|
220
|
+
const commandLine = [path, ...args].map(quoteWindowsArgument).join(' ');
|
|
221
|
+
const lockedProcessSource = String.raw `
|
|
222
|
+
using System;
|
|
223
|
+
using System.ComponentModel;
|
|
224
|
+
using System.Runtime.InteropServices;
|
|
225
|
+
using System.Text;
|
|
226
|
+
|
|
227
|
+
public static class PalladinLockedProcess {
|
|
228
|
+
private const uint CREATE_SUSPENDED = 0x00000004;
|
|
229
|
+
private const uint STARTF_USESTDHANDLES = 0x00000100;
|
|
230
|
+
private const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
|
|
231
|
+
private const int JobObjectExtendedLimitInformation = 9;
|
|
232
|
+
private const uint INFINITE = 0xFFFFFFFF;
|
|
233
|
+
|
|
234
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
235
|
+
private struct STARTUPINFO {
|
|
236
|
+
public uint cb;
|
|
237
|
+
public string lpReserved;
|
|
238
|
+
public string lpDesktop;
|
|
239
|
+
public string lpTitle;
|
|
240
|
+
public uint dwX;
|
|
241
|
+
public uint dwY;
|
|
242
|
+
public uint dwXSize;
|
|
243
|
+
public uint dwYSize;
|
|
244
|
+
public uint dwXCountChars;
|
|
245
|
+
public uint dwYCountChars;
|
|
246
|
+
public uint dwFillAttribute;
|
|
247
|
+
public uint dwFlags;
|
|
248
|
+
public ushort wShowWindow;
|
|
249
|
+
public ushort cbReserved2;
|
|
250
|
+
public IntPtr lpReserved2;
|
|
251
|
+
public IntPtr hStdInput;
|
|
252
|
+
public IntPtr hStdOutput;
|
|
253
|
+
public IntPtr hStdError;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
257
|
+
private struct PROCESS_INFORMATION {
|
|
258
|
+
public IntPtr hProcess;
|
|
259
|
+
public IntPtr hThread;
|
|
260
|
+
public uint dwProcessId;
|
|
261
|
+
public uint dwThreadId;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
265
|
+
private struct JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
|
266
|
+
public long PerProcessUserTimeLimit;
|
|
267
|
+
public long PerJobUserTimeLimit;
|
|
268
|
+
public uint LimitFlags;
|
|
269
|
+
public UIntPtr MinimumWorkingSetSize;
|
|
270
|
+
public UIntPtr MaximumWorkingSetSize;
|
|
271
|
+
public uint ActiveProcessLimit;
|
|
272
|
+
public UIntPtr Affinity;
|
|
273
|
+
public uint PriorityClass;
|
|
274
|
+
public uint SchedulingClass;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
278
|
+
private struct IO_COUNTERS {
|
|
279
|
+
public ulong ReadOperationCount;
|
|
280
|
+
public ulong WriteOperationCount;
|
|
281
|
+
public ulong OtherOperationCount;
|
|
282
|
+
public ulong ReadTransferCount;
|
|
283
|
+
public ulong WriteTransferCount;
|
|
284
|
+
public ulong OtherTransferCount;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
288
|
+
private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
|
289
|
+
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
|
|
290
|
+
public IO_COUNTERS IoInfo;
|
|
291
|
+
public UIntPtr ProcessMemoryLimit;
|
|
292
|
+
public UIntPtr JobMemoryLimit;
|
|
293
|
+
public UIntPtr PeakProcessMemoryUsed;
|
|
294
|
+
public UIntPtr PeakJobMemoryUsed;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
298
|
+
private static extern IntPtr CreateJobObject(IntPtr attributes, string name);
|
|
299
|
+
|
|
300
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
301
|
+
private static extern bool SetInformationJobObject(IntPtr job, int informationClass, IntPtr information, uint length);
|
|
302
|
+
|
|
303
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
304
|
+
private static extern bool CreateProcess(
|
|
305
|
+
string applicationName,
|
|
306
|
+
StringBuilder commandLine,
|
|
307
|
+
IntPtr processAttributes,
|
|
308
|
+
IntPtr threadAttributes,
|
|
309
|
+
bool inheritHandles,
|
|
310
|
+
uint creationFlags,
|
|
311
|
+
IntPtr environment,
|
|
312
|
+
string currentDirectory,
|
|
313
|
+
ref STARTUPINFO startupInfo,
|
|
314
|
+
out PROCESS_INFORMATION processInformation);
|
|
315
|
+
|
|
316
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
317
|
+
private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
318
|
+
|
|
319
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
320
|
+
private static extern uint ResumeThread(IntPtr thread);
|
|
321
|
+
|
|
322
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
323
|
+
private static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
|
|
324
|
+
|
|
325
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
326
|
+
private static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
|
|
327
|
+
|
|
328
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
329
|
+
private static extern bool TerminateProcess(IntPtr process, uint exitCode);
|
|
330
|
+
|
|
331
|
+
[DllImport("kernel32.dll")]
|
|
332
|
+
private static extern IntPtr GetStdHandle(int standardHandle);
|
|
333
|
+
|
|
334
|
+
[DllImport("kernel32.dll")]
|
|
335
|
+
private static extern bool CloseHandle(IntPtr handle);
|
|
336
|
+
|
|
337
|
+
public static int Run(string path, string commandLine) {
|
|
338
|
+
IntPtr job = IntPtr.Zero;
|
|
339
|
+
IntPtr information = IntPtr.Zero;
|
|
340
|
+
PROCESS_INFORMATION process = new PROCESS_INFORMATION();
|
|
341
|
+
bool assigned = false;
|
|
342
|
+
try {
|
|
343
|
+
job = CreateJobObject(IntPtr.Zero, null);
|
|
344
|
+
if (job == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
345
|
+
var limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
|
|
346
|
+
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
|
347
|
+
int size = Marshal.SizeOf(limits);
|
|
348
|
+
information = Marshal.AllocHGlobal(size);
|
|
349
|
+
Marshal.StructureToPtr(limits, information, false);
|
|
350
|
+
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, information, (uint)size)) {
|
|
351
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
352
|
+
}
|
|
353
|
+
var startup = new STARTUPINFO();
|
|
354
|
+
startup.cb = (uint)Marshal.SizeOf(startup);
|
|
355
|
+
startup.dwFlags = STARTF_USESTDHANDLES;
|
|
356
|
+
startup.hStdInput = GetStdHandle(-10);
|
|
357
|
+
startup.hStdOutput = GetStdHandle(-11);
|
|
358
|
+
startup.hStdError = GetStdHandle(-12);
|
|
359
|
+
if (!CreateProcess(path, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero, true,
|
|
360
|
+
CREATE_SUSPENDED, IntPtr.Zero, null, ref startup, out process)) {
|
|
361
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
362
|
+
}
|
|
363
|
+
if (!AssignProcessToJobObject(job, process.hProcess)) {
|
|
364
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
365
|
+
}
|
|
366
|
+
assigned = true;
|
|
367
|
+
if (ResumeThread(process.hThread) == 0xFFFFFFFF) {
|
|
368
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
369
|
+
}
|
|
370
|
+
if (WaitForSingleObject(process.hProcess, INFINITE) != 0) {
|
|
371
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
372
|
+
}
|
|
373
|
+
uint exitCode;
|
|
374
|
+
if (!GetExitCodeProcess(process.hProcess, out exitCode)) {
|
|
375
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
376
|
+
}
|
|
377
|
+
return unchecked((int)exitCode);
|
|
378
|
+
} finally {
|
|
379
|
+
if (!assigned && process.hProcess != IntPtr.Zero) TerminateProcess(process.hProcess, 1);
|
|
380
|
+
if (process.hThread != IntPtr.Zero) CloseHandle(process.hThread);
|
|
381
|
+
if (process.hProcess != IntPtr.Zero) CloseHandle(process.hProcess);
|
|
382
|
+
if (information != IntPtr.Zero) Marshal.FreeHGlobal(information);
|
|
383
|
+
if (job != IntPtr.Zero) CloseHandle(job);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}`;
|
|
387
|
+
const script = [
|
|
388
|
+
"$ErrorActionPreference = 'Stop'",
|
|
389
|
+
'$env:PSModulePath = $env:PALLADIN_TRUSTED_MODULE_PATH',
|
|
390
|
+
'$env:WinPSModulePath = $env:PALLADIN_TRUSTED_MODULE_PATH',
|
|
391
|
+
'$path = $env:PALLADIN_RUNTIME_PATH',
|
|
392
|
+
'$stream = [IO.FileStream]::new($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)',
|
|
393
|
+
'try {',
|
|
394
|
+
' $sha = [Security.Cryptography.SHA256]::Create()',
|
|
395
|
+
' try { $actualHash = ([BitConverter]::ToString($sha.ComputeHash($stream))).Replace("-", "").ToLowerInvariant() } finally { $sha.Dispose() }',
|
|
396
|
+
' if ($actualHash -cne $env:PALLADIN_EXPECTED_SHA256) { exit 51 }',
|
|
397
|
+
' $signature = Get-AuthenticodeSignature -LiteralPath $path',
|
|
398
|
+
" if ($signature.Status -ne 'Valid') { exit 52 }",
|
|
399
|
+
" $actualThumbprint = $signature.SignerCertificate.Thumbprint.Replace(' ', '').ToUpperInvariant()",
|
|
400
|
+
' if ($actualThumbprint -cne $env:PALLADIN_EXPECTED_THUMBPRINT) { exit 53 }',
|
|
401
|
+
' if ($signature.SignerCertificate.Subject -cne $env:PALLADIN_EXPECTED_PUBLISHER) { exit 54 }',
|
|
402
|
+
' if ($null -eq $signature.TimeStamperCertificate) { exit 55 }',
|
|
403
|
+
` $source = @'\n${lockedProcessSource}\n'@`,
|
|
404
|
+
' Add-Type -TypeDefinition $source -Language CSharp',
|
|
405
|
+
' $commandLine = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:PALLADIN_RUNTIME_COMMAND_LINE))',
|
|
406
|
+
" if ($env:PALLADIN_CHILD_PSMODULEPATH_PRESENT -ceq '1') { $env:PSModulePath = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:PALLADIN_CHILD_PSMODULEPATH)) } else { Remove-Item -LiteralPath 'Env:PSModulePath' -ErrorAction SilentlyContinue }",
|
|
407
|
+
" if ($env:PALLADIN_CHILD_WINPSMODULEPATH_PRESENT -ceq '1') { $env:WinPSModulePath = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:PALLADIN_CHILD_WINPSMODULEPATH)) } else { Remove-Item -LiteralPath 'Env:WinPSModulePath' -ErrorAction SilentlyContinue }",
|
|
408
|
+
" foreach ($name in @('PALLADIN_TRUSTED_MODULE_PATH', 'PALLADIN_CHILD_PSMODULEPATH', 'PALLADIN_CHILD_PSMODULEPATH_PRESENT', 'PALLADIN_CHILD_WINPSMODULEPATH', 'PALLADIN_CHILD_WINPSMODULEPATH_PRESENT', 'PALLADIN_RUNTIME_PATH', 'PALLADIN_RUNTIME_COMMAND_LINE', 'PALLADIN_EXPECTED_SHA256', 'PALLADIN_EXPECTED_PUBLISHER', 'PALLADIN_EXPECTED_THUMBPRINT')) { Remove-Item -LiteralPath \"Env:$name\" -ErrorAction SilentlyContinue }",
|
|
409
|
+
' exit [PalladinLockedProcess]::Run($path, $commandLine)',
|
|
410
|
+
'} finally { $stream.Dispose() }',
|
|
411
|
+
].join('\n');
|
|
412
|
+
const encodedScript = Buffer.from(script, 'utf16le').toString('base64');
|
|
413
|
+
return spawn(powershell, [
|
|
414
|
+
'-NoLogo',
|
|
415
|
+
'-NoProfile',
|
|
416
|
+
'-NonInteractive',
|
|
417
|
+
'-EncodedCommand',
|
|
418
|
+
encodedScript,
|
|
419
|
+
], {
|
|
420
|
+
...spawnOptions,
|
|
421
|
+
shell: false,
|
|
422
|
+
windowsHide: true,
|
|
423
|
+
env: {
|
|
424
|
+
...wrapperEnvironment,
|
|
425
|
+
SystemRoot: root,
|
|
426
|
+
PSModulePath: '',
|
|
427
|
+
WinPSModulePath: '',
|
|
428
|
+
PALLADIN_TRUSTED_MODULE_PATH: modulePath,
|
|
429
|
+
PALLADIN_CHILD_PSMODULEPATH: encodeEnvironmentValue(childPsModulePath),
|
|
430
|
+
PALLADIN_CHILD_PSMODULEPATH_PRESENT: childPsModulePath === undefined ? '0' : '1',
|
|
431
|
+
PALLADIN_CHILD_WINPSMODULEPATH: encodeEnvironmentValue(childWinPsModulePath),
|
|
432
|
+
PALLADIN_CHILD_WINPSMODULEPATH_PRESENT: childWinPsModulePath === undefined ? '0' : '1',
|
|
433
|
+
PALLADIN_RUNTIME_PATH: path,
|
|
434
|
+
PALLADIN_RUNTIME_COMMAND_LINE: Buffer.from(commandLine, 'utf8').toString('base64'),
|
|
435
|
+
PALLADIN_EXPECTED_SHA256: expectedHash,
|
|
436
|
+
PALLADIN_EXPECTED_PUBLISHER: publisher,
|
|
437
|
+
PALLADIN_EXPECTED_THUMBPRINT: thumbprint,
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
function environmentValue(environment, name) {
|
|
442
|
+
const normalized = name.toLowerCase();
|
|
443
|
+
for (const [key, value] of Object.entries(environment)) {
|
|
444
|
+
if (key.toLowerCase() === normalized)
|
|
445
|
+
return value;
|
|
446
|
+
}
|
|
447
|
+
return undefined;
|
|
448
|
+
}
|
|
449
|
+
function withoutEnvironmentKeys(environment, names) {
|
|
450
|
+
return Object.fromEntries(Object.entries(environment).filter(([key]) => !names.has(key.toLowerCase())));
|
|
451
|
+
}
|
|
452
|
+
function encodeEnvironmentValue(value) {
|
|
453
|
+
return Buffer.from(value ?? '', 'utf8').toString('base64');
|
|
454
|
+
}
|
|
455
|
+
export function quoteWindowsArgument(value) {
|
|
456
|
+
if (value.includes('\0'))
|
|
457
|
+
throw new Error('Palladin Windows runtime argument is invalid');
|
|
458
|
+
if (value !== '' && !/[\s"]/u.test(value))
|
|
459
|
+
return value;
|
|
460
|
+
let quoted = '"';
|
|
461
|
+
let backslashes = 0;
|
|
462
|
+
for (const character of value) {
|
|
463
|
+
if (character === '\\') {
|
|
464
|
+
backslashes += 1;
|
|
465
|
+
}
|
|
466
|
+
else if (character === '"') {
|
|
467
|
+
quoted += '\\'.repeat(backslashes * 2 + 1);
|
|
468
|
+
quoted += '"';
|
|
469
|
+
backslashes = 0;
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
quoted += '\\'.repeat(backslashes);
|
|
473
|
+
quoted += character;
|
|
474
|
+
backslashes = 0;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
quoted += '\\'.repeat(backslashes * 2);
|
|
478
|
+
return `${quoted}"`;
|
|
479
|
+
}
|
|
480
|
+
function trustedPowerShell() {
|
|
481
|
+
const rootHint = process.env.SystemRoot;
|
|
482
|
+
if (rootHint === undefined || !windowsPath.isAbsolute(rootHint)) {
|
|
483
|
+
throw new Error('Palladin Windows system root is unavailable');
|
|
484
|
+
}
|
|
485
|
+
const root = realpathSync(rootHint);
|
|
486
|
+
if (!sameFileIdentity(root, SYSTEM_ROOT, 'directory')) {
|
|
487
|
+
throw new Error('Palladin Windows system root is invalid');
|
|
488
|
+
}
|
|
489
|
+
const powershell = realpathSync(windowsPath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'));
|
|
490
|
+
if (!sameFileIdentity(powershell, SYSTEM_POWERSHELL, 'file')) {
|
|
491
|
+
throw new Error('Palladin Windows signature verifier is invalid');
|
|
492
|
+
}
|
|
493
|
+
const pathFromRoot = windowsPath.relative(root, powershell);
|
|
494
|
+
if (pathFromRoot.toLowerCase()
|
|
495
|
+
!== 'system32\\windowspowershell\\v1.0\\powershell.exe') {
|
|
496
|
+
throw new Error('Palladin Windows signature verifier is invalid');
|
|
497
|
+
}
|
|
498
|
+
const modulePath = windowsPath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'Modules');
|
|
499
|
+
if (!sameFileIdentity(modulePath, `${SYSTEM_ROOT}\\System32\\WindowsPowerShell\\v1.0\\Modules`, 'directory')) {
|
|
500
|
+
throw new Error('Palladin Windows PowerShell module path is invalid');
|
|
501
|
+
}
|
|
502
|
+
return { powershell, root, modulePath };
|
|
503
|
+
}
|
|
504
|
+
function sameFileIdentity(candidate, kernelPath, kind) {
|
|
505
|
+
const candidateDescriptor = openSync(candidate, fsConstants.O_RDONLY);
|
|
506
|
+
try {
|
|
507
|
+
const kernelDescriptor = openSync(kernelPath, fsConstants.O_RDONLY);
|
|
508
|
+
try {
|
|
509
|
+
const candidateMetadata = fstatSync(candidateDescriptor, { bigint: true });
|
|
510
|
+
const kernelMetadata = fstatSync(kernelDescriptor, { bigint: true });
|
|
511
|
+
const expectedKind = kind === 'directory'
|
|
512
|
+
? candidateMetadata.isDirectory() && kernelMetadata.isDirectory()
|
|
513
|
+
: candidateMetadata.isFile() && kernelMetadata.isFile();
|
|
514
|
+
return expectedKind
|
|
515
|
+
&& candidateMetadata.ino !== 0n
|
|
516
|
+
&& candidateMetadata.dev === kernelMetadata.dev
|
|
517
|
+
&& candidateMetadata.ino === kernelMetadata.ino;
|
|
518
|
+
}
|
|
519
|
+
finally {
|
|
520
|
+
closeSync(kernelDescriptor);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
finally {
|
|
524
|
+
closeSync(candidateDescriptor);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
function canonicalCacheRoot(root, requireWindowsAbsolute) {
|
|
528
|
+
if (requireWindowsAbsolute && !windowsPath.isAbsolute(root)) {
|
|
529
|
+
throw new Error('Palladin Windows runtime cache path is invalid');
|
|
530
|
+
}
|
|
531
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
532
|
+
assertPlainDirectory(root);
|
|
533
|
+
return realpathSync(root);
|
|
534
|
+
}
|
|
535
|
+
function systemCacheRoot() {
|
|
536
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
537
|
+
if (localAppData === undefined || !windowsPath.isAbsolute(localAppData)) {
|
|
538
|
+
throw new Error('Palladin Windows runtime cache is unavailable');
|
|
539
|
+
}
|
|
540
|
+
return windowsPath.join(localAppData, 'Palladin', 'RuntimeCache');
|
|
541
|
+
}
|
|
542
|
+
function packageSegment(packageName) {
|
|
543
|
+
const match = WINDOWS_PACKAGE.exec(packageName);
|
|
544
|
+
if (match?.[1] === undefined)
|
|
545
|
+
throw new Error('Palladin Windows runtime package is invalid');
|
|
546
|
+
return `win32-${match[1]}`;
|
|
547
|
+
}
|
|
548
|
+
function entryIdentity(source, binding) {
|
|
549
|
+
return createHash('sha256')
|
|
550
|
+
.update(`${source.packageName}\0${source.version}\0${binding.executableSha256}`, 'utf8')
|
|
551
|
+
.digest('hex');
|
|
552
|
+
}
|
|
553
|
+
function ensurePlainDirectory(path) {
|
|
554
|
+
try {
|
|
555
|
+
mkdirSync(path, { recursive: false, mode: 0o700 });
|
|
556
|
+
}
|
|
557
|
+
catch (error) {
|
|
558
|
+
if (!existsSync(path))
|
|
559
|
+
throw error;
|
|
560
|
+
}
|
|
561
|
+
assertPlainDirectory(path);
|
|
562
|
+
}
|
|
563
|
+
function assertPlainDirectory(path) {
|
|
564
|
+
const metadata = lstatSync(path);
|
|
565
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
566
|
+
throw new Error('Palladin Windows runtime cache contains an invalid path');
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
function syncFile(path) {
|
|
570
|
+
// Windows requires a write-capable handle for FlushFileBuffers (fsync).
|
|
571
|
+
// This path is the private temporary copy and is closed before hashing and
|
|
572
|
+
// the atomic rename, so granting this handle write access does not weaken
|
|
573
|
+
// the verified executable binding.
|
|
574
|
+
const descriptor = openSync(path, fsConstants.O_RDWR);
|
|
575
|
+
try {
|
|
576
|
+
fsyncSync(descriptor);
|
|
577
|
+
}
|
|
578
|
+
finally {
|
|
579
|
+
closeSync(descriptor);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
function createLease(leaseDirectory, kind, processId, randomId) {
|
|
583
|
+
if (!Number.isSafeInteger(processId) || processId <= 0
|
|
584
|
+
|| !/^[0-9a-f-]{36}$/.test(randomId)) {
|
|
585
|
+
throw new Error('Palladin Windows runtime lease is invalid');
|
|
586
|
+
}
|
|
587
|
+
const path = join(leaseDirectory, `${kind}-${processId}-${randomId}.lease`);
|
|
588
|
+
writeFileSync(path, '', { flag: 'wx', mode: 0o600 });
|
|
589
|
+
return path;
|
|
590
|
+
}
|
|
591
|
+
function removeLease(path) {
|
|
592
|
+
try {
|
|
593
|
+
unlinkSync(path);
|
|
594
|
+
return true;
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
// Unknown or undeletable leases force retention during collection.
|
|
598
|
+
return !existsSync(path);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function collectInactiveEntries(cacheRoot, currentEntry, processIsAlive) {
|
|
602
|
+
const schemaRoot = join(cacheRoot, CACHE_SCHEMA);
|
|
603
|
+
for (const packageEntry of safeDirectories(schemaRoot)) {
|
|
604
|
+
if (packageEntry !== 'win32-arm64' && packageEntry !== 'win32-x64')
|
|
605
|
+
continue;
|
|
606
|
+
const packageDirectory = join(schemaRoot, packageEntry);
|
|
607
|
+
for (const version of safeDirectories(packageDirectory)) {
|
|
608
|
+
if (!EXACT_VERSION.test(version))
|
|
609
|
+
continue;
|
|
610
|
+
const versionDirectory = join(packageDirectory, version);
|
|
611
|
+
for (const hash of safeDirectories(versionDirectory)) {
|
|
612
|
+
if (!SHA256.test(hash))
|
|
613
|
+
continue;
|
|
614
|
+
const entryDirectory = join(versionDirectory, hash);
|
|
615
|
+
if (samePath(entryDirectory, currentEntry))
|
|
616
|
+
continue;
|
|
617
|
+
const identity = createHash('sha256')
|
|
618
|
+
.update(`@palladin/runtime-${packageEntry}\0${version}\0${hash}`, 'utf8')
|
|
619
|
+
.digest('hex');
|
|
620
|
+
const leaseDirectory = join(schemaRoot, 'leases', identity);
|
|
621
|
+
if (hasActiveLease(leaseDirectory, processIsAlive))
|
|
622
|
+
continue;
|
|
623
|
+
try {
|
|
624
|
+
rmSync(entryDirectory, { recursive: true, force: false });
|
|
625
|
+
removeEmptyDirectory(versionDirectory);
|
|
626
|
+
removeEmptyDirectory(packageDirectory);
|
|
627
|
+
removeEmptyDirectory(leaseDirectory);
|
|
628
|
+
}
|
|
629
|
+
catch {
|
|
630
|
+
// A loaded Windows image remains locked. Leaving it in place is the
|
|
631
|
+
// safe outcome; a later launch retries collection.
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
function hasActiveLease(leaseDirectory, processIsAlive) {
|
|
638
|
+
if (!existsSync(leaseDirectory))
|
|
639
|
+
return false;
|
|
640
|
+
assertPlainDirectory(leaseDirectory);
|
|
641
|
+
let active = false;
|
|
642
|
+
for (const file of readdirSync(leaseDirectory)) {
|
|
643
|
+
const match = LEASE.exec(file);
|
|
644
|
+
if (match?.[1] === undefined) {
|
|
645
|
+
active = true;
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
const processId = Number(match[1]);
|
|
649
|
+
if (processIsAlive(processId)) {
|
|
650
|
+
active = true;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
if (!removeLease(join(leaseDirectory, file)))
|
|
654
|
+
active = true;
|
|
655
|
+
}
|
|
656
|
+
return active;
|
|
657
|
+
}
|
|
658
|
+
function systemProcessIsAlive(processId) {
|
|
659
|
+
try {
|
|
660
|
+
process.kill(processId, 0);
|
|
661
|
+
return true;
|
|
662
|
+
}
|
|
663
|
+
catch (error) {
|
|
664
|
+
return error.code === 'EPERM';
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
function safeDirectories(path) {
|
|
668
|
+
if (!existsSync(path))
|
|
669
|
+
return [];
|
|
670
|
+
assertPlainDirectory(path);
|
|
671
|
+
return readdirSync(path, { withFileTypes: true })
|
|
672
|
+
.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
|
|
673
|
+
.map((entry) => entry.name);
|
|
674
|
+
}
|
|
675
|
+
function removeEmptyDirectory(path) {
|
|
676
|
+
try {
|
|
677
|
+
if (existsSync(path) && readdirSync(path).length === 0)
|
|
678
|
+
rmSync(path, { recursive: false });
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
// Concurrent launch or collector owns this directory now.
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function samePath(left, right) {
|
|
685
|
+
return relative(left, right) === '' && relative(right, left) === '';
|
|
686
|
+
}
|
|
687
|
+
//# sourceMappingURL=windows-runtime-cache.js.map
|