|
1 | | -// Resolves the Windows taskkill binary without trusting PATH. |
2 | | -import path from "node:path"; |
| 1 | +// Resolves Windows system binaries without trusting PATH. |
| 2 | +import { |
| 3 | + resolveWindowsPowerShellPath, |
| 4 | + resolveWindowsSystem32Path, |
| 5 | +} from "../windows-cmd-helpers.mjs"; |
3 | 6 |
|
4 | | -const DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows"; |
5 | | - |
6 | | -function getEnvValueCaseInsensitive(env, expectedKey) { |
7 | | - const direct = env[expectedKey]; |
8 | | - if (direct !== undefined) { |
9 | | - return direct; |
10 | | - } |
11 | | - const expected = expectedKey.toUpperCase(); |
12 | | - const actualKey = Object.keys(env).find((key) => key.toUpperCase() === expected); |
13 | | - return actualKey ? env[actualKey] : undefined; |
14 | | -} |
15 | | - |
16 | | -function normalizeWindowsSystemRoot(raw) { |
17 | | - const trimmed = raw?.trim(); |
18 | | - if ( |
19 | | - !trimmed || |
20 | | - trimmed.includes("\0") || |
21 | | - trimmed.includes("\r") || |
22 | | - trimmed.includes("\n") || |
23 | | - trimmed.includes(";") |
24 | | - ) { |
25 | | - return null; |
26 | | - } |
27 | | - const normalized = path.win32.normalize(trimmed); |
28 | | - if (!path.win32.isAbsolute(normalized) || normalized.startsWith("\\\\")) { |
29 | | - return null; |
30 | | - } |
31 | | - const parsed = path.win32.parse(normalized); |
32 | | - if (!/^[A-Za-z]:\\$/.test(parsed.root) || normalized.length <= parsed.root.length) { |
33 | | - return null; |
34 | | - } |
35 | | - return normalized.replace(/[\\/]+$/, ""); |
36 | | -} |
| 7 | +export { resolveWindowsPowerShellPath, resolveWindowsSystem32Path }; |
37 | 8 |
|
38 | 9 | export function resolveWindowsTaskkillPath(env = process.env) { |
39 | 10 | return resolveWindowsSystem32Path("taskkill.exe", env); |
40 | 11 | } |
41 | | - |
42 | | -function resolveWindowsSystemRoot(env) { |
43 | | - return ( |
44 | | - normalizeWindowsSystemRoot(getEnvValueCaseInsensitive(env, "SystemRoot")) ?? |
45 | | - normalizeWindowsSystemRoot(getEnvValueCaseInsensitive(env, "WINDIR")) ?? |
46 | | - DEFAULT_WINDOWS_SYSTEM_ROOT |
47 | | - ); |
48 | | -} |
49 | | - |
50 | | -export function resolveWindowsSystem32Path(executableName, env = process.env) { |
51 | | - if ( |
52 | | - path.win32.basename(executableName) !== executableName || |
53 | | - !/^[A-Za-z0-9_.-]+\.exe$/u.test(executableName) |
54 | | - ) { |
55 | | - throw new Error(`Invalid Windows System32 executable name: ${executableName}`); |
56 | | - } |
57 | | - const systemRoot = resolveWindowsSystemRoot(env); |
58 | | - return path.win32.join(systemRoot, "System32", executableName); |
59 | | -} |
60 | | - |
61 | | -export function resolveWindowsPowerShellPath(env = process.env) { |
62 | | - const systemRoot = resolveWindowsSystemRoot(env); |
63 | | - return path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"); |
64 | | -} |
0 commit comments