@lelouchhe/agent-evals 0.1.1 → 0.3.0
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 +27 -18
- package/dist/checkers/file/index.js +181 -13
- package/dist/checkers/judge/index.d.ts +1 -1
- package/dist/checkers/judge/index.js +243 -31
- package/dist/checkers/judge/prompt.d.ts +4 -3
- package/dist/checkers/judge/prompt.js +22 -3
- package/dist/cli.js +171 -35
- package/dist/engine/authoring.js +108 -13
- package/dist/engine/check-runner.js +18 -3
- package/dist/engine/check-sandbox.js +9 -6
- package/dist/engine/config.d.ts +31 -2
- package/dist/engine/config.js +16 -10
- package/dist/engine/env-source.js +82 -14
- package/dist/engine/files.d.ts +2 -5
- package/dist/engine/files.js +4 -6
- package/dist/engine/mocks.js +72 -46
- package/dist/engine/params.d.ts +2 -0
- package/dist/engine/params.js +10 -0
- package/dist/engine/registry.d.ts +11 -0
- package/dist/engine/report.js +43 -8
- package/dist/engine/results.d.ts +7 -0
- package/dist/engine/results.js +9 -6
- package/dist/engine/run.d.ts +4 -1
- package/dist/engine/run.js +171 -28
- package/dist/engine/skills.js +12 -5
- package/dist/engine/view.d.ts +1 -1
- package/dist/engine/view.js +125 -10
- package/dist/engine/workspace.d.ts +7 -0
- package/dist/engine/workspace.js +37 -27
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/platform/index.d.ts +31 -0
- package/dist/platform/index.js +88 -0
- package/dist/platform/linux/index.d.ts +2 -0
- package/dist/platform/linux/index.js +40 -0
- package/dist/platform/linux/launch.d.ts +8 -0
- package/dist/platform/linux/launch.js +25 -0
- package/dist/platform/linux/policy.d.ts +46 -0
- package/dist/platform/linux/policy.js +388 -0
- package/dist/platform/linux/supervise.d.ts +8 -0
- package/dist/platform/linux/supervise.js +124 -0
- package/dist/platform/macos/index.d.ts +2 -0
- package/dist/platform/macos/index.js +59 -0
- package/dist/platform/macos/launch.d.ts +2 -8
- package/dist/platform/macos/launch.js +5 -3
- package/dist/platform/macos/policy.d.ts +3 -21
- package/dist/platform/macos/policy.js +5 -2
- package/dist/platform/macos/supervise.d.ts +3 -25
- package/dist/platform/posix-forwarder-client.mjs +129 -0
- package/dist/platform/posix-forwarder.sh +9 -0
- package/dist/platform/posix-helpers.d.ts +22 -0
- package/dist/platform/posix-helpers.js +97 -0
- package/dist/platform/types.d.ts +118 -0
- package/dist/platform/types.js +1 -0
- package/dist/platform/windows/forwarder-client.mjs +165 -0
- package/dist/platform/windows/forwarder.cmd +3 -0
- package/dist/platform/windows/forwarder.ps1 +2 -0
- package/dist/platform/windows/forwarder.sh +2 -0
- package/dist/platform/windows/index.d.ts +2 -0
- package/dist/platform/windows/index.js +225 -0
- package/dist/platform/windows/launch.d.ts +3 -0
- package/dist/platform/windows/launch.js +30 -0
- package/dist/platform/windows/policy.d.ts +17 -0
- package/dist/platform/windows/policy.js +155 -0
- package/dist/platform/windows/setup.ps1 +112 -0
- package/dist/platform/windows/supervise.d.ts +2 -0
- package/dist/platform/windows/supervise.js +142 -0
- package/dist/platform/windows/win-sandbox.exe +0 -0
- package/dist/runners/acp/commands.js +2 -3
- package/dist/runners/acp/environment.d.ts +1 -7
- package/dist/runners/acp/environment.js +18 -48
- package/dist/runners/acp/index.js +5 -1
- package/dist/runners/acp/session.d.ts +1 -1
- package/dist/runners/pi/index.js +2 -2
- package/dist/runners/pi/session.d.ts +1 -1
- package/dist/runners/pi/session.js +27 -44
- package/dist/runners/pi/supervisor.js +1 -0
- package/package.json +5 -3
- package/dist/engine/forwarder.sh +0 -61
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { ChildProcess, ChildProcessByStdio, ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
+
import type { FileHandle } from "node:fs/promises";
|
|
3
|
+
import type { Server } from "node:net";
|
|
4
|
+
import type { Readable } from "node:stream";
|
|
5
|
+
export interface DirectoryIdentity {
|
|
6
|
+
readonly dev: bigint;
|
|
7
|
+
readonly ino: bigint;
|
|
8
|
+
}
|
|
9
|
+
export interface ShellLookupHandle {
|
|
10
|
+
readonly child: ChildProcessByStdio<null, Readable, Readable>;
|
|
11
|
+
readonly terminate: () => void;
|
|
12
|
+
}
|
|
13
|
+
export interface MockForwarderTemplate {
|
|
14
|
+
readonly assetPath: string;
|
|
15
|
+
readonly quote: (value: string) => string;
|
|
16
|
+
}
|
|
17
|
+
export interface MockPathForwarderTemplate extends MockForwarderTemplate {
|
|
18
|
+
readonly templateName: string;
|
|
19
|
+
readonly targetFileName: (target: string) => string;
|
|
20
|
+
}
|
|
21
|
+
export interface MockForwarderSpec extends MockPathForwarderTemplate {
|
|
22
|
+
readonly clientPath: string;
|
|
23
|
+
/** Additional PATH shims placed beside the primary one (e.g. extensionless `sh` shims for Git Bash on Windows). */
|
|
24
|
+
readonly extraPathForwarders?: readonly MockPathForwarderTemplate[];
|
|
25
|
+
readonly workspaceForwarder?: (target: string) => MockForwarderTemplate;
|
|
26
|
+
readonly resolvePathTargetName: (selfPath: string, forwarderRoot: string) => string | undefined;
|
|
27
|
+
}
|
|
28
|
+
export interface MockEndpoint {
|
|
29
|
+
readonly socketPath: string;
|
|
30
|
+
readonly expectedNonce?: string;
|
|
31
|
+
readonly cleanup: () => Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
export interface SandboxPolicy {
|
|
34
|
+
/** Read and write access. */
|
|
35
|
+
readonly writableRoots: readonly string[];
|
|
36
|
+
/** Read-only access. */
|
|
37
|
+
readonly readableRoots: readonly string[];
|
|
38
|
+
/**
|
|
39
|
+
* Read everything the host user can read, as the check sandbox does after the evaluated agent
|
|
40
|
+
* stopped. It replaces `readableRoots` for the read clauses.
|
|
41
|
+
*/
|
|
42
|
+
readonly readAll?: boolean;
|
|
43
|
+
/** Read-only single files, such as a launcher script. */
|
|
44
|
+
readonly readableFiles?: readonly string[];
|
|
45
|
+
/** Writable single files or Unix sockets outside `writableRoots`, such as a mock host socket. */
|
|
46
|
+
readonly writableFiles?: readonly string[];
|
|
47
|
+
/** Executables the sandbox may not start, such as the real binary behind a mocked command. */
|
|
48
|
+
readonly denyExecutables?: readonly string[];
|
|
49
|
+
/** Interactive terminal device; allow termios mode changes, not arbitrary ioctl operations. */
|
|
50
|
+
readonly terminal?: string;
|
|
51
|
+
readonly allowNetwork: boolean;
|
|
52
|
+
}
|
|
53
|
+
export interface CreateSandboxPolicyOptions {
|
|
54
|
+
readonly writableRoots: readonly string[];
|
|
55
|
+
readonly readableRoots: readonly string[];
|
|
56
|
+
readonly readableFiles?: readonly string[];
|
|
57
|
+
readonly writableFiles?: readonly string[];
|
|
58
|
+
readonly denyExecutables?: readonly string[];
|
|
59
|
+
readonly allowNetwork: boolean;
|
|
60
|
+
readonly interactive: boolean;
|
|
61
|
+
}
|
|
62
|
+
export interface SupervisedProcess {
|
|
63
|
+
readonly child: ChildProcess;
|
|
64
|
+
/** Native workload exit code, not the supervisor's teardown exit. */
|
|
65
|
+
readonly completion: Promise<number>;
|
|
66
|
+
readonly stop: () => Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* The workload's private report pipe at FD 5, present only when requested. FD 5 is not a
|
|
69
|
+
* standard stream, so it stays out of the workload's own output; `spawn` closes it for the
|
|
70
|
+
* workload's children, so untrusted descendants cannot write it.
|
|
71
|
+
*/
|
|
72
|
+
readonly report?: Readable;
|
|
73
|
+
}
|
|
74
|
+
export interface SpawnSupervisedOptions {
|
|
75
|
+
readonly policy: SandboxPolicy;
|
|
76
|
+
readonly policyDirectory: string;
|
|
77
|
+
readonly command: readonly [string, ...string[]];
|
|
78
|
+
readonly cwd: string;
|
|
79
|
+
readonly env: NodeJS.ProcessEnv;
|
|
80
|
+
readonly interactive: boolean;
|
|
81
|
+
/** Add a private report pipe at FD 5 for the workload, exposed as `report`. */
|
|
82
|
+
readonly report?: boolean;
|
|
83
|
+
}
|
|
84
|
+
export interface SpawnSandboxedOptions {
|
|
85
|
+
readonly policy: SandboxPolicy;
|
|
86
|
+
readonly policyDirectory: string;
|
|
87
|
+
readonly command: string;
|
|
88
|
+
readonly args: readonly string[];
|
|
89
|
+
readonly cwd: string;
|
|
90
|
+
readonly env: NodeJS.ProcessEnv;
|
|
91
|
+
}
|
|
92
|
+
export interface PlatformBackend {
|
|
93
|
+
readonly systemPath: readonly string[];
|
|
94
|
+
readonly caseInsensitivePaths: boolean;
|
|
95
|
+
readonly executableExtensions: readonly string[];
|
|
96
|
+
readonly usesPiShellWrapper: boolean;
|
|
97
|
+
defaultTempParent?(): string;
|
|
98
|
+
dirEnv(dirs: {
|
|
99
|
+
readonly home: string;
|
|
100
|
+
readonly tmp: string;
|
|
101
|
+
}): Record<string, string>;
|
|
102
|
+
checkChildEnv(sourceEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
103
|
+
openDirectoryIdentity(canonicalPath: string): Promise<DirectoryIdentity>;
|
|
104
|
+
openRegularFileNoFollow(absolutePath: string): Promise<FileHandle>;
|
|
105
|
+
isExecutableAccessible(path: string): Promise<boolean>;
|
|
106
|
+
wrapExecutableCommand(executable: string, args: readonly string[]): readonly [string, ...string[]];
|
|
107
|
+
spawnShellLookup(command: string, cwd: string): ShellLookupHandle;
|
|
108
|
+
mockForwarderSpec(): MockForwarderSpec;
|
|
109
|
+
listenMockServer(server: Server, runRootDir: string): Promise<MockEndpoint>;
|
|
110
|
+
assertSandboxAvailable(): void;
|
|
111
|
+
setupSandbox(options: {
|
|
112
|
+
readonly teardown: boolean;
|
|
113
|
+
}): Promise<string>;
|
|
114
|
+
createSandboxPolicy(options: CreateSandboxPolicyOptions): SandboxPolicy;
|
|
115
|
+
resolveDeniedExecutables(targets: readonly string[], pathEntries: readonly string[]): Promise<readonly string[]>;
|
|
116
|
+
spawnSupervised(options: SpawnSupervisedOptions): Promise<SupervisedProcess>;
|
|
117
|
+
spawnSandboxed(options: SpawnSandboxedOptions): Promise<ChildProcessWithoutNullStreams>;
|
|
118
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { appendFileSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { createConnection } from "node:net";
|
|
4
|
+
import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Windows mock forwarder client.
|
|
8
|
+
*
|
|
9
|
+
* Invoked by `forwarder.cmd` as:
|
|
10
|
+
* node forwarder-client.mjs <bindir> <endpoint> <fault> <self> [...args]
|
|
11
|
+
*
|
|
12
|
+
* Reports the canonicalised invocation path and arguments over the host's authenticated
|
|
13
|
+
* loopback TCP endpoint. For mocked results, replays stdout/stderr directly and exits with
|
|
14
|
+
* the mocked code. For `pass`, runs the resolved real executable with inherited stdio.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const [bindir, endpoint, faultPath, rawSelf, ...args] = process.argv.slice(2);
|
|
18
|
+
if (bindir === undefined || endpoint === undefined || faultPath === undefined || rawSelf === undefined) {
|
|
19
|
+
process.exit(126);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const self = canonicalSelf(rawSelf);
|
|
23
|
+
const inBinDir = self.toLowerCase().startsWith(`${bindir.toLowerCase()}${sep}`);
|
|
24
|
+
const name = inBinDir && self.toLowerCase().endsWith(".cmd") ? basename(self).slice(0, -4) : basename(self);
|
|
25
|
+
|
|
26
|
+
function canonicalSelf(path) {
|
|
27
|
+
try {
|
|
28
|
+
return join(realpathSync(dirname(path)), basename(path));
|
|
29
|
+
} catch {
|
|
30
|
+
return path;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function encode(value) {
|
|
35
|
+
return Buffer.from(value, "utf8").toString("base64");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function failUnavailable() {
|
|
39
|
+
process.stderr.write(`${name}: Service unavailable\n`);
|
|
40
|
+
try {
|
|
41
|
+
appendFileSync(faultPath, `${name}\n`);
|
|
42
|
+
} catch {
|
|
43
|
+
// Fault log is best-effort when the temporary directory is inaccessible.
|
|
44
|
+
}
|
|
45
|
+
process.exitCode = 126;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isRegularFile(path) {
|
|
49
|
+
try {
|
|
50
|
+
return statSync(path).isFile();
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function findPassTarget() {
|
|
57
|
+
if (inBinDir) {
|
|
58
|
+
const extensions = ["", ".exe", ".cmd", ".bat", ".com"];
|
|
59
|
+
for (const folder of (process.env.PATH ?? "").split(delimiter)) {
|
|
60
|
+
if (folder.length === 0) continue;
|
|
61
|
+
for (const ext of extensions) {
|
|
62
|
+
const candidate = resolve(folder, `${name}${ext}`);
|
|
63
|
+
if (!isRegularFile(candidate)) continue;
|
|
64
|
+
const canonical = canonicalSelf(candidate).toLowerCase();
|
|
65
|
+
if (canonical === self.toLowerCase() || canonical.startsWith(`${bindir.toLowerCase()}${sep}`)) continue;
|
|
66
|
+
return candidate;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const real = resolve(dirname(self), `.${basename(self)}`);
|
|
72
|
+
return isRegularFile(real) ? real : undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function runPass() {
|
|
76
|
+
const target = findPassTarget();
|
|
77
|
+
if (target === undefined) {
|
|
78
|
+
process.stderr.write(`${name}: Operation not permitted\n`);
|
|
79
|
+
process.exitCode = 126;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const isPs1 = target.toLowerCase().endsWith(".ps1");
|
|
83
|
+
const res = isPs1
|
|
84
|
+
? spawnSync(
|
|
85
|
+
"powershell.exe",
|
|
86
|
+
["-NoLogo", "-NoProfile", "-NonInteractive", "-InputFormat", "None", "-File", target, ...args],
|
|
87
|
+
{ stdio: "inherit", windowsHide: true },
|
|
88
|
+
)
|
|
89
|
+
: spawnSync(target, args, {
|
|
90
|
+
stdio: "inherit",
|
|
91
|
+
shell: /\.(?:cmd|bat)$/iu.test(target),
|
|
92
|
+
windowsHide: true,
|
|
93
|
+
});
|
|
94
|
+
if (res.error !== undefined) {
|
|
95
|
+
process.stderr.write(`${name}: ${res.error.message}\n`);
|
|
96
|
+
process.exitCode = 126;
|
|
97
|
+
} else {
|
|
98
|
+
process.exitCode = res.status ?? 1;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function parseEndpoint(value) {
|
|
103
|
+
if (!value.startsWith("tcp://127.0.0.1:")) return undefined;
|
|
104
|
+
const rest = value.slice("tcp://127.0.0.1:".length);
|
|
105
|
+
const slash = rest.indexOf("/");
|
|
106
|
+
if (slash === -1) return undefined;
|
|
107
|
+
const port = Number(rest.slice(0, slash));
|
|
108
|
+
const nonce = rest.slice(slash + 1);
|
|
109
|
+
if (!Number.isInteger(port) || port <= 0 || nonce.length === 0) return undefined;
|
|
110
|
+
return { port, nonce };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const parsed = parseEndpoint(endpoint);
|
|
114
|
+
if (parsed === undefined) {
|
|
115
|
+
failUnavailable();
|
|
116
|
+
process.exit(126);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const socket = createConnection({ host: "127.0.0.1", port: parsed.port });
|
|
120
|
+
const chunks = [];
|
|
121
|
+
let settled = false;
|
|
122
|
+
|
|
123
|
+
socket.on("error", () => {
|
|
124
|
+
if (settled) return;
|
|
125
|
+
settled = true;
|
|
126
|
+
socket.destroy();
|
|
127
|
+
failUnavailable();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
socket.on("data", (chunk) => {
|
|
131
|
+
chunks.push(chunk);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
socket.on("end", () => {
|
|
135
|
+
if (settled) return;
|
|
136
|
+
settled = true;
|
|
137
|
+
socket.destroy();
|
|
138
|
+
const reply = Buffer.concat(chunks)
|
|
139
|
+
.toString("utf8")
|
|
140
|
+
.replace(/\r?\n$/, "");
|
|
141
|
+
if (reply.length === 0) {
|
|
142
|
+
failUnavailable();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const [kind, codeText, outText, errText] = reply.split(" ");
|
|
146
|
+
if (kind === "pass") {
|
|
147
|
+
runPass();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const code = Number(codeText);
|
|
151
|
+
if (!Number.isInteger(code)) {
|
|
152
|
+
failUnavailable();
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (outText !== undefined && outText !== "" && outText !== "-") {
|
|
156
|
+
process.stdout.write(Buffer.from(outText, "base64"));
|
|
157
|
+
}
|
|
158
|
+
if (errText !== undefined && errText !== "" && errText !== "-") {
|
|
159
|
+
process.stderr.write(Buffer.from(errText, "base64"));
|
|
160
|
+
}
|
|
161
|
+
process.exitCode = code;
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const payload = [`nonce:${parsed.nonce}`, self, ...args].map(encode).join("\n") + "\n";
|
|
165
|
+
socket.end(payload);
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { access, constants, lstat, open, realpath, stat } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { spawnSandboxed } from "./launch.js";
|
|
7
|
+
import { assertWinSandboxAvailable, createSandboxPolicy, defaultTempParent, SYSTEM_PATH } from "./policy.js";
|
|
8
|
+
import { spawnSupervised } from "./supervise.js";
|
|
9
|
+
const WINDOWS_CHECK_CHILD_ENV_KEYS = [
|
|
10
|
+
"SystemRoot",
|
|
11
|
+
"WINDIR",
|
|
12
|
+
"SystemDrive",
|
|
13
|
+
"ComSpec",
|
|
14
|
+
"PATHEXT",
|
|
15
|
+
"TEMP",
|
|
16
|
+
"TMP",
|
|
17
|
+
"USERPROFILE",
|
|
18
|
+
"LOCALAPPDATA",
|
|
19
|
+
"APPDATA",
|
|
20
|
+
];
|
|
21
|
+
async function resolveDeniedExecutables(targets, pathEntries) {
|
|
22
|
+
if (targets.length === 0)
|
|
23
|
+
return [];
|
|
24
|
+
const denied = [];
|
|
25
|
+
for (const target of targets) {
|
|
26
|
+
for (const dir of pathEntries) {
|
|
27
|
+
for (const ext of ["", ".exe", ".cmd", ".bat"]) {
|
|
28
|
+
const candidate = join(dir, `${target}${ext}`);
|
|
29
|
+
try {
|
|
30
|
+
if ((await stat(candidate)).isFile())
|
|
31
|
+
denied.push(candidate, await realpath(candidate));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// Not installed here.
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return denied;
|
|
40
|
+
}
|
|
41
|
+
export const windowsBackend = {
|
|
42
|
+
systemPath: SYSTEM_PATH,
|
|
43
|
+
caseInsensitivePaths: true,
|
|
44
|
+
executableExtensions: ["", ".exe", ".cmd", ".bat"],
|
|
45
|
+
usesPiShellWrapper: false,
|
|
46
|
+
defaultTempParent,
|
|
47
|
+
dirEnv(dirs) {
|
|
48
|
+
return {
|
|
49
|
+
HOME: dirs.home,
|
|
50
|
+
USERPROFILE: dirs.home,
|
|
51
|
+
TMPDIR: dirs.tmp,
|
|
52
|
+
TMP: dirs.tmp,
|
|
53
|
+
TEMP: dirs.tmp,
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
checkChildEnv(sourceEnv) {
|
|
57
|
+
const env = {
|
|
58
|
+
PATH: sourceEnv.PATH,
|
|
59
|
+
HOME: sourceEnv.HOME,
|
|
60
|
+
TMPDIR: sourceEnv.TMPDIR,
|
|
61
|
+
};
|
|
62
|
+
for (const key of WINDOWS_CHECK_CHILD_ENV_KEYS) {
|
|
63
|
+
if (sourceEnv[key] !== undefined)
|
|
64
|
+
env[key] = sourceEnv[key];
|
|
65
|
+
}
|
|
66
|
+
return env;
|
|
67
|
+
},
|
|
68
|
+
async openDirectoryIdentity(canonicalPath) {
|
|
69
|
+
const stats = await lstat(canonicalPath, { bigint: true });
|
|
70
|
+
if (stats.isSymbolicLink() || !stats.isDirectory()) {
|
|
71
|
+
throw Object.assign(new Error(`not a directory: ${canonicalPath}`), { code: "ENOTDIR" });
|
|
72
|
+
}
|
|
73
|
+
return { dev: stats.dev, ino: stats.ino };
|
|
74
|
+
},
|
|
75
|
+
async openRegularFileNoFollow(absolutePath) {
|
|
76
|
+
const info = await lstat(absolutePath);
|
|
77
|
+
if (info.isSymbolicLink() || !info.isFile()) {
|
|
78
|
+
throw Object.assign(new Error(`not a regular file: ${absolutePath}`), { code: "ELOOP" });
|
|
79
|
+
}
|
|
80
|
+
return open(absolutePath, constants.O_RDONLY);
|
|
81
|
+
},
|
|
82
|
+
async isExecutableAccessible(path) {
|
|
83
|
+
try {
|
|
84
|
+
await access(path, constants.F_OK);
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
wrapExecutableCommand(executable, args) {
|
|
92
|
+
if (/\.(?:[cm]?js|[cm]?ts)$/iu.test(executable)) {
|
|
93
|
+
return [process.execPath, executable, ...args];
|
|
94
|
+
}
|
|
95
|
+
if (/\.(?:cmd|bat)$/iu.test(executable)) {
|
|
96
|
+
return [process.env.ComSpec ?? "cmd.exe", "/d", "/c", executable, ...args];
|
|
97
|
+
}
|
|
98
|
+
return [executable, ...args];
|
|
99
|
+
},
|
|
100
|
+
spawnShellLookup(command, cwd) {
|
|
101
|
+
const child = spawn(process.env.ComSpec ?? "cmd.exe", ["/d", "/c", `"${command}"`], {
|
|
102
|
+
cwd,
|
|
103
|
+
env: process.env,
|
|
104
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
105
|
+
windowsHide: true,
|
|
106
|
+
windowsVerbatimArguments: true,
|
|
107
|
+
});
|
|
108
|
+
return {
|
|
109
|
+
child,
|
|
110
|
+
terminate() {
|
|
111
|
+
if (child.pid !== undefined) {
|
|
112
|
+
try {
|
|
113
|
+
// Run taskkill /T /F synchronously while the shell parent still exists so
|
|
114
|
+
// grandchildren (e.g. node.exe under cmd.exe) are terminated before cmd.exe exits.
|
|
115
|
+
execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
116
|
+
stdio: "ignore",
|
|
117
|
+
windowsHide: true,
|
|
118
|
+
timeout: 2_000,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// Already exited or taskkill unavailable; fall back to direct kill below.
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
child.kill();
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// Already exited.
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
mockForwarderSpec() {
|
|
135
|
+
const cmdAsset = fileURLToPath(new URL("./forwarder.cmd", import.meta.url));
|
|
136
|
+
const ps1Asset = fileURLToPath(new URL("./forwarder.ps1", import.meta.url));
|
|
137
|
+
const shAsset = fileURLToPath(new URL("./forwarder.sh", import.meta.url));
|
|
138
|
+
const quoteCmd = (value) => `"${value.replaceAll('"', '""').replaceAll("%", "%%")}"`;
|
|
139
|
+
const quotePs1 = (value) => `'${value.replaceAll("'", "''")}'`;
|
|
140
|
+
const quoteSh = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
141
|
+
return {
|
|
142
|
+
assetPath: cmdAsset,
|
|
143
|
+
clientPath: fileURLToPath(new URL("./forwarder-client.mjs", import.meta.url)),
|
|
144
|
+
templateName: "forward.cmd",
|
|
145
|
+
quote: quoteCmd,
|
|
146
|
+
targetFileName: (target) => `${target}.cmd`,
|
|
147
|
+
extraPathForwarders: [
|
|
148
|
+
{
|
|
149
|
+
assetPath: shAsset,
|
|
150
|
+
quote: quoteSh,
|
|
151
|
+
templateName: "forward.sh",
|
|
152
|
+
targetFileName: (target) => target,
|
|
153
|
+
},
|
|
154
|
+
],
|
|
155
|
+
workspaceForwarder: (target) => target.toLowerCase().endsWith(".ps1")
|
|
156
|
+
? { assetPath: ps1Asset, quote: quotePs1 }
|
|
157
|
+
: { assetPath: cmdAsset, quote: quoteCmd },
|
|
158
|
+
resolvePathTargetName: (selfPath, forwarderRoot) => {
|
|
159
|
+
if (dirname(selfPath).toLowerCase() !== forwarderRoot.toLowerCase())
|
|
160
|
+
return undefined;
|
|
161
|
+
const raw = basename(selfPath);
|
|
162
|
+
return raw.toLowerCase().endsWith(".cmd") ? raw.slice(0, -4) : raw;
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
async listenMockServer(server) {
|
|
167
|
+
const expectedNonce = randomBytes(16).toString("hex");
|
|
168
|
+
const port = await new Promise((resolve, reject) => {
|
|
169
|
+
server.once("error", reject);
|
|
170
|
+
server.listen(0, "127.0.0.1", () => {
|
|
171
|
+
server.off("error", reject);
|
|
172
|
+
const address = server.address();
|
|
173
|
+
if (address === null) {
|
|
174
|
+
reject(new Error("mock loopback server did not bind a port"));
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
resolve(address.port);
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
return {
|
|
182
|
+
socketPath: `tcp://127.0.0.1:${port}/${expectedNonce}`,
|
|
183
|
+
expectedNonce,
|
|
184
|
+
cleanup: async () => { },
|
|
185
|
+
};
|
|
186
|
+
},
|
|
187
|
+
assertSandboxAvailable: assertWinSandboxAvailable,
|
|
188
|
+
async setupSandbox({ teardown }) {
|
|
189
|
+
const setupScript = fileURLToPath(new URL("./setup.ps1", import.meta.url));
|
|
190
|
+
const scriptArgs = [
|
|
191
|
+
"-NoLogo",
|
|
192
|
+
"-NoProfile",
|
|
193
|
+
"-ExecutionPolicy",
|
|
194
|
+
"Bypass",
|
|
195
|
+
"-File",
|
|
196
|
+
setupScript,
|
|
197
|
+
...(teardown ? ["-Teardown"] : []),
|
|
198
|
+
];
|
|
199
|
+
const runShell = (shell) => new Promise((resolveCode, reject) => {
|
|
200
|
+
const child = spawn(shell, scriptArgs, { stdio: "inherit", windowsHide: false });
|
|
201
|
+
child.once("error", reject);
|
|
202
|
+
child.once("close", (code) => resolveCode(code ?? 1));
|
|
203
|
+
});
|
|
204
|
+
let code;
|
|
205
|
+
try {
|
|
206
|
+
code = await runShell("pwsh.exe");
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (error.code === "ENOENT") {
|
|
210
|
+
code = await runShell("powershell.exe");
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (code !== 0) {
|
|
217
|
+
throw new Error(`Windows sandbox ${teardown ? "teardown" : "setup"} failed with exit code ${code} (run from an Administrator prompt)`);
|
|
218
|
+
}
|
|
219
|
+
return "";
|
|
220
|
+
},
|
|
221
|
+
createSandboxPolicy,
|
|
222
|
+
resolveDeniedExecutables,
|
|
223
|
+
spawnSupervised,
|
|
224
|
+
spawnSandboxed,
|
|
225
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { buildWindowsWorkloadEnv, resolveWindowsCommand, winSandboxCredentialsPath, winSandboxExecutablePath, } from "./policy.js";
|
|
6
|
+
export async function spawnSandboxed(options) {
|
|
7
|
+
const helper = winSandboxExecutablePath();
|
|
8
|
+
await mkdir(options.policyDirectory, { recursive: true });
|
|
9
|
+
const workloadEnv = buildWindowsWorkloadEnv(options.env);
|
|
10
|
+
const resolvedCmd = resolveWindowsCommand(options.command, options.args, workloadEnv);
|
|
11
|
+
const configPath = join(options.policyDirectory, `win-sandbox-${randomUUID()}.json`);
|
|
12
|
+
const config = {
|
|
13
|
+
command: resolvedCmd.command,
|
|
14
|
+
args: [...resolvedCmd.args],
|
|
15
|
+
cwd: resolve(options.cwd),
|
|
16
|
+
env: workloadEnv,
|
|
17
|
+
writableRoots: options.policy.writableRoots,
|
|
18
|
+
readableRoots: options.policy.readableRoots,
|
|
19
|
+
writableFiles: options.policy.writableFiles ?? [],
|
|
20
|
+
readableFiles: options.policy.readableFiles ?? [],
|
|
21
|
+
allowNetwork: options.policy.allowNetwork,
|
|
22
|
+
credentialsPath: winSandboxCredentialsPath(),
|
|
23
|
+
};
|
|
24
|
+
await writeFile(configPath, JSON.stringify(config), "utf8");
|
|
25
|
+
return spawn(helper, ["--config", configPath, "--delete-config"], {
|
|
26
|
+
cwd: options.cwd,
|
|
27
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
28
|
+
windowsHide: true,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CreateSandboxPolicyOptions, SandboxPolicy } from "../types.js";
|
|
2
|
+
export declare const SYSTEM_PATH: readonly string[];
|
|
3
|
+
export declare function winSandboxExecutablePath(): string;
|
|
4
|
+
export declare function defaultTempParent(): string;
|
|
5
|
+
export declare function winSandboxCredentialsPath(): string;
|
|
6
|
+
export declare function assertWinSandboxAvailable(): void;
|
|
7
|
+
export declare function createSandboxPolicy(options: CreateSandboxPolicyOptions): SandboxPolicy;
|
|
8
|
+
export declare function buildWindowsWorkloadEnv(env: NodeJS.ProcessEnv): Record<string, string>;
|
|
9
|
+
/**
|
|
10
|
+
* Resolve a bare program name against the workload's PATH (including `.exe`/`.cmd`/`.bat`)
|
|
11
|
+
* and wrap `.cmd`/`.bat` shims with `cmd.exe /d /c` because Win32 `CreateProcessAsUserW`
|
|
12
|
+
* cannot execute batch files directly.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveWindowsCommand(program: string, args: readonly string[], env: Readonly<Record<string, string>>): {
|
|
15
|
+
readonly command: string;
|
|
16
|
+
readonly args: readonly string[];
|
|
17
|
+
};
|