@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
package/dist/index.d.ts
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
* access a built-in checker uses. Everything not exported here is internal; a built-in that
|
|
5
5
|
* needs something absent from this file is a missing capability, not a private exception.
|
|
6
6
|
*/
|
|
7
|
-
export type { Checker, CheckerContext, CheckerDefinition, CheckResult, CheckSandbox, CheckSandboxOutcome, CheckStatus, ImplementationContext, MockRecord, MockWiring, PreparedRunner, Runner, RunnerContext, RunnerDefinition, RunnerOutcome, RunnerTokens, RunnerUsage, TraceEntry, } from "./engine/registry.js";
|
|
7
|
+
export type { Checker, CheckerContext, CheckerDefinition, CheckResult, CheckSandbox, CheckSandboxOutcome, CheckStatus, HomeProtection, ImplementationContext, MockRecord, MockWiring, PreparedRunner, Runner, RunnerContext, RunnerDefinition, RunnerOutcome, RunnerTokens, RunnerUsage, TraceEntry, } from "./engine/registry.js";
|
|
8
8
|
export type { EnvSource } from "./engine/env-source.js";
|
|
9
9
|
export type { RunVariables, ValueSource } from "./engine/values.js";
|
|
10
|
-
export { ConfigError, expectMockArgs, expectMockTarget, mockTargetIdentity, type MockArgs, type MockArgument, type MockPattern, type PatternSyntax, } from "./engine/config.js";
|
|
10
|
+
export { ConfigError, expectMockArgs, expectMockTarget, mockTargetIdentity, type ImplementationRecord, type MockArgs, type MockArgument, type MockPattern, type PatternSyntax, } from "./engine/config.js";
|
|
11
11
|
export { compileMockArgs } from "./engine/mock-match.js";
|
|
12
|
-
export { patternListSchema, patternSyntaxSchema, runRelativePathSchema } from "./engine/params.js";
|
|
12
|
+
export { patternListSchema, patternSyntaxSchema, runFilePathSchema, runRelativePathSchema } from "./engine/params.js";
|
|
13
13
|
export { searches } from "./engine/regex.js";
|
|
14
|
-
export { MAX_CHECK_BYTES, WorkspacePathError, isMissing, readRunFile, readRunTree, runPathExists, type RunEntryKind, type RunRoot, type RunTree, type RunTreeEntry, } from "./engine/workspace.js";
|
|
14
|
+
export { MAX_CHECK_BYTES, WorkspacePathError, assertRunRoot, fileIdentity, isMissing, isProtectedHomePath, readRunFile, readRunTree, resolveWorkspacePath, runPathExists, type RunEntryKind, type RunRoot, type RunTree, type RunTreeEntry, } from "./engine/workspace.js";
|
|
15
15
|
export { messageText } from "./engine/messages.js";
|
|
16
16
|
export { shellSkillAccess, skillConsultations, type ShellSkillAccess, type SkillConsultation, type SkillSources, } from "./engine/skills.js";
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { ConfigError, expectMockArgs, expectMockTarget, mockTargetIdentity, } from "./engine/config.js";
|
|
2
2
|
export { compileMockArgs } from "./engine/mock-match.js";
|
|
3
|
-
export { patternListSchema, patternSyntaxSchema, runRelativePathSchema } from "./engine/params.js";
|
|
3
|
+
export { patternListSchema, patternSyntaxSchema, runFilePathSchema, runRelativePathSchema } from "./engine/params.js";
|
|
4
4
|
export { searches } from "./engine/regex.js";
|
|
5
|
-
export { MAX_CHECK_BYTES, WorkspacePathError, isMissing, readRunFile, readRunTree, runPathExists, } from "./engine/workspace.js";
|
|
5
|
+
export { MAX_CHECK_BYTES, WorkspacePathError, assertRunRoot, fileIdentity, isMissing, isProtectedHomePath, readRunFile, readRunTree, resolveWorkspacePath, runPathExists, } from "./engine/workspace.js";
|
|
6
6
|
export { messageText } from "./engine/messages.js";
|
|
7
7
|
export { shellSkillAccess, skillConsultations, } from "./engine/skills.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
+
import type { FileHandle } from "node:fs/promises";
|
|
3
|
+
import type { Server } from "node:net";
|
|
4
|
+
import type { CreateSandboxPolicyOptions, DirectoryIdentity, MockEndpoint, MockForwarderSpec, MockForwarderTemplate, PlatformBackend, SandboxPolicy, ShellLookupHandle, SpawnSandboxedOptions, SpawnSupervisedOptions, SupervisedProcess } from "./types.js";
|
|
5
|
+
export type { CreateSandboxPolicyOptions, DirectoryIdentity, MockEndpoint, MockForwarderSpec, MockForwarderTemplate, PlatformBackend, SandboxPolicy, ShellLookupHandle, SpawnSandboxedOptions, SpawnSupervisedOptions, SupervisedProcess, };
|
|
6
|
+
export declare const isSandboxPlatformSupported: boolean;
|
|
7
|
+
export declare const SYSTEM_PATH: readonly string[];
|
|
8
|
+
export declare const caseInsensitivePaths: boolean;
|
|
9
|
+
export declare const executableExtensions: readonly string[];
|
|
10
|
+
export declare const usesPiShellWrapper: boolean;
|
|
11
|
+
export declare function defaultTempParent(): string;
|
|
12
|
+
export declare function dirEnv(dirs: {
|
|
13
|
+
readonly home: string;
|
|
14
|
+
readonly tmp: string;
|
|
15
|
+
}): Record<string, string>;
|
|
16
|
+
export declare function checkChildEnv(sourceEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
17
|
+
export declare function openDirectoryIdentity(canonicalPath: string): Promise<DirectoryIdentity>;
|
|
18
|
+
export declare function openRegularFileNoFollow(absolutePath: string): Promise<FileHandle>;
|
|
19
|
+
export declare function isExecutableAccessible(path: string): Promise<boolean>;
|
|
20
|
+
export declare function wrapExecutableCommand(executable: string, args: readonly string[]): readonly [string, ...string[]];
|
|
21
|
+
export declare function spawnShellLookup(command: string, cwd: string): ShellLookupHandle;
|
|
22
|
+
export declare function mockForwarderSpec(): MockForwarderSpec;
|
|
23
|
+
export declare function listenMockServer(server: Server, runRootDir: string): Promise<MockEndpoint>;
|
|
24
|
+
export declare function assertSandboxAvailable(): void;
|
|
25
|
+
export declare function setupSandbox(options: {
|
|
26
|
+
readonly teardown: boolean;
|
|
27
|
+
}): Promise<string>;
|
|
28
|
+
export declare function createSandboxPolicy(options: CreateSandboxPolicyOptions): SandboxPolicy;
|
|
29
|
+
export declare function resolveDeniedExecutables(targets: readonly string[], pathEntries: readonly string[]): Promise<readonly string[]>;
|
|
30
|
+
export declare function spawnSupervised(options: SpawnSupervisedOptions): Promise<SupervisedProcess>;
|
|
31
|
+
export declare function spawnSandboxed(options: SpawnSandboxedOptions): Promise<ChildProcessWithoutNullStreams>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { tmpdir } from "node:os";
|
|
2
|
+
import { linuxBackend } from "./linux/index.js";
|
|
3
|
+
import { macosBackend } from "./macos/index.js";
|
|
4
|
+
import { windowsBackend } from "./windows/index.js";
|
|
5
|
+
function unsupportedPlatform() {
|
|
6
|
+
throw new Error(`unsupported host platform: ${process.platform}; supported platforms are darwin, linux, and win32`);
|
|
7
|
+
}
|
|
8
|
+
const unsupportedBackend = {
|
|
9
|
+
systemPath: [],
|
|
10
|
+
caseInsensitivePaths: false,
|
|
11
|
+
executableExtensions: [""],
|
|
12
|
+
usesPiShellWrapper: false,
|
|
13
|
+
dirEnv: (dirs) => ({ HOME: dirs.home, TMPDIR: dirs.tmp }),
|
|
14
|
+
checkChildEnv: (env) => ({ PATH: env.PATH, HOME: env.HOME, TMPDIR: env.TMPDIR }),
|
|
15
|
+
openDirectoryIdentity: async () => unsupportedPlatform(),
|
|
16
|
+
openRegularFileNoFollow: async () => unsupportedPlatform(),
|
|
17
|
+
isExecutableAccessible: async () => false,
|
|
18
|
+
wrapExecutableCommand: (executable, args) => [executable, ...args],
|
|
19
|
+
spawnShellLookup: () => unsupportedPlatform(),
|
|
20
|
+
mockForwarderSpec: () => unsupportedPlatform(),
|
|
21
|
+
listenMockServer: async () => unsupportedPlatform(),
|
|
22
|
+
assertSandboxAvailable: unsupportedPlatform,
|
|
23
|
+
setupSandbox: async () => unsupportedPlatform(),
|
|
24
|
+
createSandboxPolicy: unsupportedPlatform,
|
|
25
|
+
resolveDeniedExecutables: async () => unsupportedPlatform(),
|
|
26
|
+
spawnSupervised: async () => unsupportedPlatform(),
|
|
27
|
+
spawnSandboxed: async () => unsupportedPlatform(),
|
|
28
|
+
};
|
|
29
|
+
const backend = process.platform === "darwin"
|
|
30
|
+
? macosBackend
|
|
31
|
+
: process.platform === "linux"
|
|
32
|
+
? linuxBackend
|
|
33
|
+
: process.platform === "win32"
|
|
34
|
+
? windowsBackend
|
|
35
|
+
: unsupportedBackend;
|
|
36
|
+
export const isSandboxPlatformSupported = process.platform === "darwin" || process.platform === "linux" || process.platform === "win32";
|
|
37
|
+
export const SYSTEM_PATH = backend.systemPath;
|
|
38
|
+
export const caseInsensitivePaths = backend.caseInsensitivePaths;
|
|
39
|
+
export const executableExtensions = backend.executableExtensions;
|
|
40
|
+
export const usesPiShellWrapper = backend.usesPiShellWrapper;
|
|
41
|
+
export function defaultTempParent() {
|
|
42
|
+
return backend.defaultTempParent?.() ?? tmpdir();
|
|
43
|
+
}
|
|
44
|
+
export function dirEnv(dirs) {
|
|
45
|
+
return backend.dirEnv(dirs);
|
|
46
|
+
}
|
|
47
|
+
export function checkChildEnv(sourceEnv) {
|
|
48
|
+
return backend.checkChildEnv(sourceEnv);
|
|
49
|
+
}
|
|
50
|
+
export function openDirectoryIdentity(canonicalPath) {
|
|
51
|
+
return backend.openDirectoryIdentity(canonicalPath);
|
|
52
|
+
}
|
|
53
|
+
export function openRegularFileNoFollow(absolutePath) {
|
|
54
|
+
return backend.openRegularFileNoFollow(absolutePath);
|
|
55
|
+
}
|
|
56
|
+
export function isExecutableAccessible(path) {
|
|
57
|
+
return backend.isExecutableAccessible(path);
|
|
58
|
+
}
|
|
59
|
+
export function wrapExecutableCommand(executable, args) {
|
|
60
|
+
return backend.wrapExecutableCommand(executable, args);
|
|
61
|
+
}
|
|
62
|
+
export function spawnShellLookup(command, cwd) {
|
|
63
|
+
return backend.spawnShellLookup(command, cwd);
|
|
64
|
+
}
|
|
65
|
+
export function mockForwarderSpec() {
|
|
66
|
+
return backend.mockForwarderSpec();
|
|
67
|
+
}
|
|
68
|
+
export function listenMockServer(server, runRootDir) {
|
|
69
|
+
return backend.listenMockServer(server, runRootDir);
|
|
70
|
+
}
|
|
71
|
+
export function assertSandboxAvailable() {
|
|
72
|
+
backend.assertSandboxAvailable();
|
|
73
|
+
}
|
|
74
|
+
export function setupSandbox(options) {
|
|
75
|
+
return backend.setupSandbox(options);
|
|
76
|
+
}
|
|
77
|
+
export function createSandboxPolicy(options) {
|
|
78
|
+
return backend.createSandboxPolicy(options);
|
|
79
|
+
}
|
|
80
|
+
export function resolveDeniedExecutables(targets, pathEntries) {
|
|
81
|
+
return backend.resolveDeniedExecutables(targets, pathEntries);
|
|
82
|
+
}
|
|
83
|
+
export function spawnSupervised(options) {
|
|
84
|
+
return backend.spawnSupervised(options);
|
|
85
|
+
}
|
|
86
|
+
export function spawnSandboxed(options) {
|
|
87
|
+
return backend.spawnSandboxed(options);
|
|
88
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { posixPlatformHelpers } from "../posix-helpers.js";
|
|
4
|
+
import { spawnSandboxed } from "./launch.js";
|
|
5
|
+
import { assertBwrapAvailable, createSandboxPolicy, SYSTEM_PATH } from "./policy.js";
|
|
6
|
+
import { spawnSupervised } from "./supervise.js";
|
|
7
|
+
async function resolveDeniedExecutables(targets, pathEntries) {
|
|
8
|
+
if (targets.length === 0)
|
|
9
|
+
return [];
|
|
10
|
+
const denied = [];
|
|
11
|
+
for (const target of targets) {
|
|
12
|
+
for (const dir of pathEntries) {
|
|
13
|
+
const candidate = join(dir, target);
|
|
14
|
+
try {
|
|
15
|
+
if ((await stat(candidate)).isFile())
|
|
16
|
+
denied.push(candidate, await realpath(candidate));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// Not installed here.
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return denied;
|
|
24
|
+
}
|
|
25
|
+
export const linuxBackend = {
|
|
26
|
+
...posixPlatformHelpers,
|
|
27
|
+
systemPath: SYSTEM_PATH,
|
|
28
|
+
caseInsensitivePaths: false,
|
|
29
|
+
assertSandboxAvailable: assertBwrapAvailable,
|
|
30
|
+
async setupSandbox({ teardown }) {
|
|
31
|
+
if (teardown)
|
|
32
|
+
return "Linux bubblewrap requires no host teardown.\n";
|
|
33
|
+
assertBwrapAvailable();
|
|
34
|
+
return "Linux bubblewrap sandbox is ready.\n";
|
|
35
|
+
},
|
|
36
|
+
createSandboxPolicy,
|
|
37
|
+
resolveDeniedExecutables,
|
|
38
|
+
spawnSupervised,
|
|
39
|
+
spawnSandboxed,
|
|
40
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
+
import type { SpawnSandboxedOptions } from "../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Launch a command inside a bubblewrap sandbox as its own process group.
|
|
5
|
+
* `--unshare-pid --die-with-parent` ensures the kernel reaps every descendant on exit,
|
|
6
|
+
* while `--args` passes the workload environment via FD 3 instead of host env/argv.
|
|
7
|
+
*/
|
|
8
|
+
export declare function spawnSandboxed(options: SpawnSandboxedOptions): Promise<ChildProcessWithoutNullStreams>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { bwrapExecutablePath, prepareBwrapLaunch, trustedHostEnv } from "./policy.js";
|
|
3
|
+
/**
|
|
4
|
+
* Launch a command inside a bubblewrap sandbox as its own process group.
|
|
5
|
+
* `--unshare-pid --die-with-parent` ensures the kernel reaps every descendant on exit,
|
|
6
|
+
* while `--args` passes the workload environment via FD 3 instead of host env/argv.
|
|
7
|
+
*/
|
|
8
|
+
export async function spawnSandboxed(options) {
|
|
9
|
+
const executable = bwrapExecutablePath();
|
|
10
|
+
const launch = await prepareBwrapLaunch(options.policyDirectory, options.policy, options.env);
|
|
11
|
+
try {
|
|
12
|
+
const stdio = ["pipe", "pipe", "pipe", launch.argsFd];
|
|
13
|
+
if (launch.seccompFd !== undefined)
|
|
14
|
+
stdio.push(launch.seccompFd);
|
|
15
|
+
return spawn(executable, ["--args", "3", "--", options.command, ...options.args], {
|
|
16
|
+
cwd: options.cwd,
|
|
17
|
+
env: trustedHostEnv(),
|
|
18
|
+
stdio,
|
|
19
|
+
detached: true,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
launch.closeFds();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { CreateSandboxPolicyOptions, SandboxPolicy } from "../types.js";
|
|
2
|
+
export type { SandboxPolicy };
|
|
3
|
+
export declare const SYSTEM_PATH: readonly ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
|
|
4
|
+
/** Minimal trusted environment for host-side launcher processes (`bwrap`, `script`). */
|
|
5
|
+
export declare function trustedHostEnv(includeTerm?: boolean): NodeJS.ProcessEnv;
|
|
6
|
+
export declare function createSandboxPolicy(options: CreateSandboxPolicyOptions): SandboxPolicy;
|
|
7
|
+
/** Verify `bwrap` is installed and unprivileged user namespaces work; fail closed otherwise. */
|
|
8
|
+
export declare function assertBwrapAvailable(): void;
|
|
9
|
+
export declare function bwrapExecutablePath(): string;
|
|
10
|
+
/**
|
|
11
|
+
* Build a minimal cBPF seccomp filter for network-disabled sandboxes. Denies `socket(2)`,
|
|
12
|
+
* `connect(2)`, `io_uring_setup(2)`, and (on x86_64) x32 ABI syscalls with `EPERM`, blocking
|
|
13
|
+
* stream and connectionless `AF_UNIX` sockets across the entire filesystem while keeping
|
|
14
|
+
* `pipe2`/`socketpair` and ordinary read-only files working.
|
|
15
|
+
*/
|
|
16
|
+
export declare function buildNoNetworkSeccomp(arch?: string): Buffer;
|
|
17
|
+
/** Build the `bwrap` option list (everything before `-- <command>`) implementing `policy`. */
|
|
18
|
+
export declare function buildBwrapOptions(policy: SandboxPolicy, options?: {
|
|
19
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
20
|
+
readonly newSession?: boolean;
|
|
21
|
+
readonly seccompFd?: number;
|
|
22
|
+
}): string[];
|
|
23
|
+
/** Build the full `bwrap` argument list implementing `policy` around `command` and `args`. */
|
|
24
|
+
export declare function buildBwrapArgs(policy: SandboxPolicy, command: string, args: readonly string[]): string[];
|
|
25
|
+
export interface PreparedBwrapLaunch {
|
|
26
|
+
readonly argsFd: number;
|
|
27
|
+
readonly seccompFd?: number;
|
|
28
|
+
readonly closeFds: () => void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Create unlinked read-only FDs for `bwrap --args` (including `--clearenv`/`--setenv` workload
|
|
32
|
+
* env) and optional `--seccomp` BPF program. Each backing file is created exclusively with mode
|
|
33
|
+
* 0600, opened, and unlinked immediately before spawning so no credentials ever remain on disk.
|
|
34
|
+
*/
|
|
35
|
+
export declare function prepareBwrapLaunch(policyDirectory: string, policy: SandboxPolicy, env: NodeJS.ProcessEnv, options?: {
|
|
36
|
+
readonly newSession?: boolean;
|
|
37
|
+
}): Promise<PreparedBwrapLaunch>;
|
|
38
|
+
/**
|
|
39
|
+
* Walk a symlink chain starting inside `/etc` until the first hop outside `/etc` and `/usr`.
|
|
40
|
+
* Mounting the final resolved target at that first unmounted hop keeps multi-hop resolver
|
|
41
|
+
* chains working inside the read-only `/etc` bind.
|
|
42
|
+
*/
|
|
43
|
+
export declare function resolveExternalSymlinkTarget(file: string, isMounted?: (path: string) => boolean): {
|
|
44
|
+
readonly source: string;
|
|
45
|
+
readonly dest: string;
|
|
46
|
+
} | undefined;
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { accessSync, closeSync, constants, lstatSync, openSync, readlinkSync, realpathSync, statSync, unlinkSync, } from "node:fs";
|
|
4
|
+
import { writeFile } from "node:fs/promises";
|
|
5
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
6
|
+
export const SYSTEM_PATH = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
|
|
7
|
+
const DISTRO_TOP_DIRS = ["/bin", "/sbin", "/lib", "/lib64"];
|
|
8
|
+
const NETWORK_ETC_FILES = ["/etc/resolv.conf", "/etc/hosts"];
|
|
9
|
+
const PROBE_TRUE_PATHS = ["/usr/bin/true", "/bin/true"];
|
|
10
|
+
/** Minimal trusted environment for host-side launcher processes (`bwrap`, `script`). */
|
|
11
|
+
export function trustedHostEnv(includeTerm = false) {
|
|
12
|
+
return {
|
|
13
|
+
PATH: "/usr/bin:/bin",
|
|
14
|
+
SHELL: "/bin/sh",
|
|
15
|
+
...(includeTerm && process.env.TERM !== undefined ? { TERM: process.env.TERM } : {}),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
let cachedBwrapPath;
|
|
19
|
+
export function createSandboxPolicy(options) {
|
|
20
|
+
return {
|
|
21
|
+
writableRoots: options.writableRoots,
|
|
22
|
+
readableRoots: options.readableRoots,
|
|
23
|
+
...(options.readableFiles === undefined ? {} : { readableFiles: options.readableFiles }),
|
|
24
|
+
...(options.writableFiles === undefined ? {} : { writableFiles: options.writableFiles }),
|
|
25
|
+
...(options.denyExecutables === undefined ? {} : { denyExecutables: options.denyExecutables }),
|
|
26
|
+
allowNetwork: options.allowNetwork,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** Verify `bwrap` is installed and unprivileged user namespaces work; fail closed otherwise. */
|
|
30
|
+
export function assertBwrapAvailable() {
|
|
31
|
+
if (process.platform !== "linux") {
|
|
32
|
+
throw new Error("the Linux bubblewrap backend requires linux");
|
|
33
|
+
}
|
|
34
|
+
if (cachedBwrapPath !== undefined)
|
|
35
|
+
return;
|
|
36
|
+
const bwrap = findBwrap();
|
|
37
|
+
if (bwrap === undefined) {
|
|
38
|
+
throw new Error("the Linux sandbox requires bubblewrap (bwrap), which was not found on PATH; install bubblewrap (e.g. apt-get install bubblewrap)");
|
|
39
|
+
}
|
|
40
|
+
const probeTrue = PROBE_TRUE_PATHS.find((candidate) => safeStat(candidate)?.isFile() === true);
|
|
41
|
+
if (probeTrue === undefined) {
|
|
42
|
+
throw new Error("the Linux sandbox could not find /usr/bin/true or /bin/true for preflight verification");
|
|
43
|
+
}
|
|
44
|
+
const probe = spawnSync(bwrap, ["--ro-bind", "/", "/", "--unshare-pid", "--die-with-parent", "--new-session", "--", probeTrue], { env: trustedHostEnv(), encoding: "utf8", timeout: 5_000 });
|
|
45
|
+
if (probe.error !== undefined || probe.status !== 0) {
|
|
46
|
+
const detail = (probe.stderr || probe.error?.message || `exit status ${String(probe.status)}`).trim();
|
|
47
|
+
throw new Error(`bubblewrap (bwrap) cannot create a sandbox on this host (${detail}); ensure unprivileged user namespaces are permitted`);
|
|
48
|
+
}
|
|
49
|
+
cachedBwrapPath = bwrap;
|
|
50
|
+
}
|
|
51
|
+
export function bwrapExecutablePath() {
|
|
52
|
+
assertBwrapAvailable();
|
|
53
|
+
return cachedBwrapPath;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Build a minimal cBPF seccomp filter for network-disabled sandboxes. Denies `socket(2)`,
|
|
57
|
+
* `connect(2)`, `io_uring_setup(2)`, and (on x86_64) x32 ABI syscalls with `EPERM`, blocking
|
|
58
|
+
* stream and connectionless `AF_UNIX` sockets across the entire filesystem while keeping
|
|
59
|
+
* `pipe2`/`socketpair` and ordinary read-only files working.
|
|
60
|
+
*/
|
|
61
|
+
export function buildNoNetworkSeccomp(arch = process.arch) {
|
|
62
|
+
let auditArch;
|
|
63
|
+
let deniedSyscalls;
|
|
64
|
+
if (arch === "arm64") {
|
|
65
|
+
auditArch = 0xc00000b7; // AUDIT_ARCH_AARCH64
|
|
66
|
+
deniedSyscalls = [198, 203, 425]; // socket, connect, io_uring_setup
|
|
67
|
+
}
|
|
68
|
+
else if (arch === "x64") {
|
|
69
|
+
auditArch = 0xc000003e; // AUDIT_ARCH_X86_64
|
|
70
|
+
deniedSyscalls = [41, 42, 425]; // socket, connect, io_uring_setup
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
throw new Error(`unsupported Linux architecture for seccomp network isolation: ${arch}`);
|
|
74
|
+
}
|
|
75
|
+
const SECCOMP_RET_ERRNO_EPERM = 0x00050001;
|
|
76
|
+
const SECCOMP_RET_ALLOW = 0x7fff0000;
|
|
77
|
+
const insn = (code, jt, jf, k) => {
|
|
78
|
+
const buf = Buffer.alloc(8);
|
|
79
|
+
buf.writeUInt16LE(code, 0);
|
|
80
|
+
buf.writeUInt8(jt, 2);
|
|
81
|
+
buf.writeUInt8(jf, 3);
|
|
82
|
+
buf.writeUInt32LE(k >>> 0, 4);
|
|
83
|
+
return buf;
|
|
84
|
+
};
|
|
85
|
+
const ops = [
|
|
86
|
+
insn(0x20, 0, 0, 4), // LD seccomp_data.arch
|
|
87
|
+
insn(0x15, 1, 0, auditArch), // JEQ auditArch -> +1
|
|
88
|
+
insn(0x06, 0, 0, SECCOMP_RET_ERRNO_EPERM), // unknown arch: fail closed
|
|
89
|
+
insn(0x20, 0, 0, 0), // LD seccomp_data.nr
|
|
90
|
+
];
|
|
91
|
+
if (arch === "x64") {
|
|
92
|
+
// Reject x32 ABI syscalls (nr >= 0x40000000) sharing AUDIT_ARCH_X86_64.
|
|
93
|
+
ops.push(insn(0x35, 0, 1, 0x40000000)); // JGE 0x40000000 -> next else +1
|
|
94
|
+
ops.push(insn(0x06, 0, 0, SECCOMP_RET_ERRNO_EPERM));
|
|
95
|
+
}
|
|
96
|
+
for (const nr of deniedSyscalls) {
|
|
97
|
+
ops.push(insn(0x15, 0, 1, nr)); // JEQ nr -> next else +1
|
|
98
|
+
ops.push(insn(0x06, 0, 0, SECCOMP_RET_ERRNO_EPERM));
|
|
99
|
+
}
|
|
100
|
+
ops.push(insn(0x06, 0, 0, SECCOMP_RET_ALLOW));
|
|
101
|
+
return Buffer.concat(ops);
|
|
102
|
+
}
|
|
103
|
+
/** Build the `bwrap` option list (everything before `-- <command>`) implementing `policy`. */
|
|
104
|
+
export function buildBwrapOptions(policy, options = {}) {
|
|
105
|
+
const flags = ["--unshare-pid", "--die-with-parent"];
|
|
106
|
+
if (options.newSession !== false) {
|
|
107
|
+
flags.push("--new-session");
|
|
108
|
+
}
|
|
109
|
+
if (!policy.allowNetwork) {
|
|
110
|
+
flags.push("--unshare-net");
|
|
111
|
+
}
|
|
112
|
+
const roMounted = new Set();
|
|
113
|
+
const addRoBind = (source, dest = source) => {
|
|
114
|
+
const key = `${source}\0${dest}`;
|
|
115
|
+
if (roMounted.has(key))
|
|
116
|
+
return;
|
|
117
|
+
roMounted.add(key);
|
|
118
|
+
flags.push("--ro-bind", source, dest);
|
|
119
|
+
};
|
|
120
|
+
const addSymlink = (target, dest) => {
|
|
121
|
+
const key = `sym\0${target}\0${dest}`;
|
|
122
|
+
if (roMounted.has(key))
|
|
123
|
+
return;
|
|
124
|
+
roMounted.add(key);
|
|
125
|
+
flags.push("--symlink", target, dest);
|
|
126
|
+
};
|
|
127
|
+
if (policy.readAll === true) {
|
|
128
|
+
flags.push("--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc");
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
addRoBind("/usr");
|
|
132
|
+
for (const dir of DISTRO_TOP_DIRS) {
|
|
133
|
+
const info = safeLstat(dir);
|
|
134
|
+
if (info === undefined)
|
|
135
|
+
continue;
|
|
136
|
+
if (info.isSymbolicLink()) {
|
|
137
|
+
addSymlink(readlinkSync(dir), dir);
|
|
138
|
+
}
|
|
139
|
+
else if (info.isDirectory()) {
|
|
140
|
+
addRoBind(dir);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (safeLstat("/etc") !== undefined) {
|
|
144
|
+
addRoBind("/etc");
|
|
145
|
+
}
|
|
146
|
+
if (policy.allowNetwork) {
|
|
147
|
+
for (const file of NETWORK_ETC_FILES) {
|
|
148
|
+
const mount = resolveExternalSymlinkTarget(file);
|
|
149
|
+
if (mount !== undefined) {
|
|
150
|
+
addRoBind(mount.source, mount.dest);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
flags.push("--dev", "/dev", "--proc", "/proc");
|
|
155
|
+
for (const root of policy.readableRoots) {
|
|
156
|
+
mountReadablePath(root, addRoBind, addSymlink);
|
|
157
|
+
}
|
|
158
|
+
for (const file of policy.readableFiles ?? []) {
|
|
159
|
+
mountReadablePath(file, addRoBind, addSymlink);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Writable mounts come after read-only mounts so they overlay cleanly.
|
|
163
|
+
const rwMounted = new Set();
|
|
164
|
+
const addRwBind = (path) => {
|
|
165
|
+
if (rwMounted.has(path))
|
|
166
|
+
return;
|
|
167
|
+
rwMounted.add(path);
|
|
168
|
+
flags.push("--bind", path, path);
|
|
169
|
+
};
|
|
170
|
+
const mountWritablePath = (rawPath) => {
|
|
171
|
+
const resolved = resolve(rawPath);
|
|
172
|
+
const info = safeLstat(resolved);
|
|
173
|
+
if (info === undefined)
|
|
174
|
+
return;
|
|
175
|
+
if (info.isSymbolicLink()) {
|
|
176
|
+
const real = safeRealpath(resolved);
|
|
177
|
+
if (real === undefined)
|
|
178
|
+
return;
|
|
179
|
+
addRwBind(real);
|
|
180
|
+
addSymlink(real, resolved);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
addRwBind(resolved);
|
|
184
|
+
const real = safeRealpath(resolved);
|
|
185
|
+
if (real !== undefined && real !== resolved)
|
|
186
|
+
addRwBind(real);
|
|
187
|
+
};
|
|
188
|
+
for (const root of policy.writableRoots) {
|
|
189
|
+
mountWritablePath(root);
|
|
190
|
+
}
|
|
191
|
+
for (const file of policy.writableFiles ?? []) {
|
|
192
|
+
mountWritablePath(file);
|
|
193
|
+
}
|
|
194
|
+
// Denied executables come last, masking each real binary with non-executable /dev/null.
|
|
195
|
+
const masked = new Set();
|
|
196
|
+
for (const executable of policy.denyExecutables ?? []) {
|
|
197
|
+
const resolved = resolve(executable);
|
|
198
|
+
const target = safeRealpath(resolved);
|
|
199
|
+
if (target === undefined || masked.has(target))
|
|
200
|
+
continue;
|
|
201
|
+
const info = safeStat(target);
|
|
202
|
+
if (info === undefined || !info.isFile())
|
|
203
|
+
continue;
|
|
204
|
+
masked.add(target);
|
|
205
|
+
flags.push("--ro-bind", "/dev/null", target);
|
|
206
|
+
}
|
|
207
|
+
if (options.env !== undefined) {
|
|
208
|
+
flags.push("--clearenv");
|
|
209
|
+
for (const [key, value] of Object.entries(options.env)) {
|
|
210
|
+
if (value === undefined)
|
|
211
|
+
continue;
|
|
212
|
+
if (key.includes("\0") || value.includes("\0")) {
|
|
213
|
+
throw new Error(`sandbox environment variable "${key.replaceAll("\0", "")}" contains a NUL byte`);
|
|
214
|
+
}
|
|
215
|
+
flags.push("--setenv", key, value);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (options.seccompFd !== undefined) {
|
|
219
|
+
flags.push("--seccomp", String(options.seccompFd));
|
|
220
|
+
}
|
|
221
|
+
for (const token of flags) {
|
|
222
|
+
if (token.includes("\0")) {
|
|
223
|
+
throw new Error("sandbox argument list contains an embedded NUL byte");
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return flags;
|
|
227
|
+
}
|
|
228
|
+
/** Build the full `bwrap` argument list implementing `policy` around `command` and `args`. */
|
|
229
|
+
export function buildBwrapArgs(policy, command, args) {
|
|
230
|
+
return [...buildBwrapOptions(policy), "--", command, ...args];
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Create unlinked read-only FDs for `bwrap --args` (including `--clearenv`/`--setenv` workload
|
|
234
|
+
* env) and optional `--seccomp` BPF program. Each backing file is created exclusively with mode
|
|
235
|
+
* 0600, opened, and unlinked immediately before spawning so no credentials ever remain on disk.
|
|
236
|
+
*/
|
|
237
|
+
export async function prepareBwrapLaunch(policyDirectory, policy, env, options = {}) {
|
|
238
|
+
const needsSeccomp = !policy.allowNetwork;
|
|
239
|
+
const seccompFd = needsSeccomp ? 4 : undefined;
|
|
240
|
+
const bwrapOptions = buildBwrapOptions(policy, {
|
|
241
|
+
env,
|
|
242
|
+
...(options.newSession === undefined ? {} : { newSession: options.newSession }),
|
|
243
|
+
...(seccompFd === undefined ? {} : { seccompFd }),
|
|
244
|
+
});
|
|
245
|
+
const openArgsFd = await openUnlinkedTempFd(join(policyDirectory, `.bwrap-args-${randomUUID()}`), bwrapOptions.join("\0") + "\0");
|
|
246
|
+
let openSeccompFd;
|
|
247
|
+
if (needsSeccomp) {
|
|
248
|
+
try {
|
|
249
|
+
openSeccompFd = await openUnlinkedTempFd(join(policyDirectory, `.bwrap-seccomp-${randomUUID()}`), buildNoNetworkSeccomp());
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
closeSync(openArgsFd);
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
let closed = false;
|
|
257
|
+
const closeFds = () => {
|
|
258
|
+
if (closed)
|
|
259
|
+
return;
|
|
260
|
+
closed = true;
|
|
261
|
+
try {
|
|
262
|
+
closeSync(openArgsFd);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
// Already closed.
|
|
266
|
+
}
|
|
267
|
+
if (openSeccompFd !== undefined) {
|
|
268
|
+
try {
|
|
269
|
+
closeSync(openSeccompFd);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// Already closed.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
return {
|
|
277
|
+
argsFd: openArgsFd,
|
|
278
|
+
...(openSeccompFd === undefined ? {} : { seccompFd: openSeccompFd }),
|
|
279
|
+
closeFds,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
async function openUnlinkedTempFd(path, content) {
|
|
283
|
+
await writeFile(path, content, { mode: 0o600, flag: "wx" });
|
|
284
|
+
try {
|
|
285
|
+
return openSync(path, constants.O_RDONLY);
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
try {
|
|
289
|
+
unlinkSync(path);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// Best-effort cleanup if already removed.
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Walk a symlink chain starting inside `/etc` until the first hop outside `/etc` and `/usr`.
|
|
298
|
+
* Mounting the final resolved target at that first unmounted hop keeps multi-hop resolver
|
|
299
|
+
* chains working inside the read-only `/etc` bind.
|
|
300
|
+
*/
|
|
301
|
+
export function resolveExternalSymlinkTarget(file, isMounted = (path) => path.startsWith("/etc/") || path.startsWith("/usr/")) {
|
|
302
|
+
let current = file;
|
|
303
|
+
let firstUnmounted;
|
|
304
|
+
for (let depth = 0; depth < 16; depth++) {
|
|
305
|
+
const info = safeLstat(current);
|
|
306
|
+
if (info === undefined || !info.isSymbolicLink())
|
|
307
|
+
break;
|
|
308
|
+
const next = resolve(dirname(current), readlinkSync(current));
|
|
309
|
+
if (firstUnmounted === undefined && !isMounted(next)) {
|
|
310
|
+
firstUnmounted = next;
|
|
311
|
+
}
|
|
312
|
+
current = next;
|
|
313
|
+
}
|
|
314
|
+
if (firstUnmounted === undefined)
|
|
315
|
+
return undefined;
|
|
316
|
+
const finalReal = safeRealpath(file);
|
|
317
|
+
if (finalReal === undefined)
|
|
318
|
+
return undefined;
|
|
319
|
+
return { source: finalReal, dest: firstUnmounted };
|
|
320
|
+
}
|
|
321
|
+
function mountReadablePath(rawPath, addRoBind, addSymlink) {
|
|
322
|
+
const resolved = resolve(rawPath);
|
|
323
|
+
const info = safeLstat(resolved);
|
|
324
|
+
if (info === undefined)
|
|
325
|
+
return;
|
|
326
|
+
if (info.isSymbolicLink()) {
|
|
327
|
+
const real = safeRealpath(resolved);
|
|
328
|
+
if (real === undefined)
|
|
329
|
+
return;
|
|
330
|
+
addRoBind(real);
|
|
331
|
+
addSymlink(real, resolved);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
addRoBind(resolved);
|
|
335
|
+
const real = safeRealpath(resolved);
|
|
336
|
+
if (real !== undefined && real !== resolved)
|
|
337
|
+
addRoBind(real);
|
|
338
|
+
}
|
|
339
|
+
function findBwrap() {
|
|
340
|
+
const candidates = [
|
|
341
|
+
"/usr/bin/bwrap",
|
|
342
|
+
"/bin/bwrap",
|
|
343
|
+
...(process.env.PATH ?? "")
|
|
344
|
+
.split(":")
|
|
345
|
+
.filter((entry) => entry.length > 0 && isAbsolute(entry))
|
|
346
|
+
.map((entry) => join(entry, "bwrap")),
|
|
347
|
+
];
|
|
348
|
+
for (const candidate of candidates) {
|
|
349
|
+
const real = safeRealpath(candidate);
|
|
350
|
+
if (real === undefined)
|
|
351
|
+
continue;
|
|
352
|
+
const info = safeStat(real);
|
|
353
|
+
if (info === undefined || !info.isFile())
|
|
354
|
+
continue;
|
|
355
|
+
try {
|
|
356
|
+
accessSync(real, constants.X_OK);
|
|
357
|
+
return real;
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
// Keep searching.
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
function safeLstat(path) {
|
|
366
|
+
try {
|
|
367
|
+
return lstatSync(path);
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return undefined;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
function safeStat(path) {
|
|
374
|
+
try {
|
|
375
|
+
return statSync(path);
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
function safeRealpath(path) {
|
|
382
|
+
try {
|
|
383
|
+
return realpathSync(path);
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
return undefined;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SpawnSupervisedOptions, SupervisedProcess } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Start a command inside a bubblewrap PID namespace (`--unshare-pid --die-with-parent`).
|
|
4
|
+
* Workload environment is installed via `--args` on FD 3 so host launchers (`bwrap`, `script`)
|
|
5
|
+
* run with a minimal trusted environment. When interactive on a real TTY, `util-linux` `script`
|
|
6
|
+
* allocates a sandbox-owned PTY so `/dev/tty` works without exposing the operator's terminal.
|
|
7
|
+
*/
|
|
8
|
+
export declare function spawnSupervised(options: SpawnSupervisedOptions): Promise<SupervisedProcess>;
|