@niwa-labs/sandbox 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +21 -2
- package/package.json +15 -4
- package/src/access.ts +642 -0
- package/src/index.ts +68 -0
- package/src/launch.ts +403 -0
- package/src/nono.ts +349 -0
- package/src/paths.ts +31 -0
- package/src/profile.ts +140 -0
- package/src/profiles.ts +62 -0
- package/src/sandbox.ts +124 -0
- package/src/spawn.ts +147 -0
- package/src/spec.ts +60 -0
- package/src/srt.ts +187 -0
- package/test/access.test.ts +367 -0
- package/test/box-process.test.ts +327 -0
- package/test/launcher-env.test.ts +144 -0
- package/test/live.test.ts +259 -0
- package/test/manifest.test.ts +231 -0
- package/tsconfig.json +6 -0
package/src/sandbox.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sandbox interface.
|
|
3
|
+
*
|
|
4
|
+
* One interface over two classes: the process class (srt, nono) is built; the microVM class
|
|
5
|
+
* (Gondolin, BoxLite) is not, and nothing here assumes a process: a launched box is only
|
|
6
|
+
* what a caller needs to talk to it and wait for it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { BoxSpec } from "./spec.ts";
|
|
10
|
+
|
|
11
|
+
export type SandboxName = "srt" | "nono" | "gondolin" | "boxlite";
|
|
12
|
+
export type SandboxClass = "process" | "vm";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What a box lets its process reach once the sandbox has applied a spec: the places the spec lists
|
|
16
|
+
* and what the sandbox adds of its own. A path is absolute, with `~` expanded.
|
|
17
|
+
*/
|
|
18
|
+
export interface BoxPolicy {
|
|
19
|
+
/** Every place the process may write, besides the devices. */
|
|
20
|
+
readonly write: readonly string[];
|
|
21
|
+
/** The devices the process may write to run: the null device, the terminal, its descriptors. */
|
|
22
|
+
readonly devices: readonly string[];
|
|
23
|
+
/** Reads: only the places listed, or every place but those listed. */
|
|
24
|
+
readonly read: { readonly only: readonly string[] } | { readonly except: readonly string[] };
|
|
25
|
+
/** The only hosts the process may reach. */
|
|
26
|
+
readonly net: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The full configuration a sandbox will be given for one spec. A pure value of the spec. */
|
|
30
|
+
export interface SandboxManifest {
|
|
31
|
+
readonly sandbox: SandboxName;
|
|
32
|
+
readonly cwd: string;
|
|
33
|
+
/** The whole environment of the process. */
|
|
34
|
+
readonly env: Readonly<Record<string, string>>;
|
|
35
|
+
/** What the box will let the process reach. Absent: the sandbox does not say, and nothing is promised beyond the spec. */
|
|
36
|
+
readonly policy?: BoxPolicy;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A launched box: its streams and its end. */
|
|
40
|
+
export interface LaunchedBox {
|
|
41
|
+
readonly pid: number;
|
|
42
|
+
readonly stdin: { write(data: string | Uint8Array): unknown; end(): unknown };
|
|
43
|
+
readonly stdout: ReadableStream<Uint8Array>;
|
|
44
|
+
readonly stderr: ReadableStream<Uint8Array>;
|
|
45
|
+
/**
|
|
46
|
+
* The exit code; resolves once the process is gone and the sandbox has cleaned up after it. Rejects
|
|
47
|
+
* when the clean-up fails: the process is gone all the same, and the caller must not take it for running.
|
|
48
|
+
*/
|
|
49
|
+
readonly exited: Promise<number>;
|
|
50
|
+
/**
|
|
51
|
+
* The exit code as soon as the process is gone, before the sandbox has cleaned up after it. Absent
|
|
52
|
+
* where the sandbox has no step of its own after the process: `exited` is then the same moment.
|
|
53
|
+
*/
|
|
54
|
+
readonly ended?: Promise<number>;
|
|
55
|
+
/**
|
|
56
|
+
* The signal that ended the wrapper, `null` when it exited by itself; settled no later than
|
|
57
|
+
* `exited`. A process killed by a signal also has a conventional exit code (143 for SIGTERM): this
|
|
58
|
+
* tells the two apart, as a child process's `signalCode` does. A box that cannot tell may leave it out.
|
|
59
|
+
*/
|
|
60
|
+
readonly signaled?: Promise<NodeJS.Signals | null>;
|
|
61
|
+
/** Signals the wrapper's process (SIGTERM by default), as a child process's `kill` does. */
|
|
62
|
+
kill(signal?: NodeJS.Signals | number): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** How a box's process is started, besides what the spec says. */
|
|
66
|
+
export interface LaunchOptions {
|
|
67
|
+
/** The process leads its own process group, so a signal to the group reaches everything it started. */
|
|
68
|
+
readonly detached?: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface Sandbox<M extends SandboxManifest = SandboxManifest> {
|
|
72
|
+
readonly name: SandboxName;
|
|
73
|
+
readonly class: SandboxClass;
|
|
74
|
+
/** Probes the machine: the binary is there and can really wrap a process. */
|
|
75
|
+
available(): Promise<boolean>;
|
|
76
|
+
/** Pure and deterministic: the same spec gives the same manifest. Recorded in the journal before launch. */
|
|
77
|
+
manifest(spec: BoxSpec): M;
|
|
78
|
+
/** Starts `argv` inside the box. Throws SandboxUnavailable when the sandbox cannot run here. */
|
|
79
|
+
launch(spec: BoxSpec, argv: readonly string[], options?: LaunchOptions): Promise<LaunchedBox>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A session that needs a sandbox and has none available must not start. */
|
|
83
|
+
export class SandboxUnavailable extends Error {
|
|
84
|
+
readonly sandbox: SandboxName;
|
|
85
|
+
constructor(sandbox: SandboxName, reason: string) {
|
|
86
|
+
super(`sandbox ${sandbox} is not available: ${reason}`);
|
|
87
|
+
this.name = "SandboxUnavailable";
|
|
88
|
+
this.sandbox = sandbox;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Why a box was refused: one reason, with what it is about. */
|
|
93
|
+
export interface BoxRefusal {
|
|
94
|
+
/**
|
|
95
|
+
* `unknown-profile`: a name no profile has. `closed`: a place another box's profile or the closed
|
|
96
|
+
* list keeps. `not-granted`: wider than the host's default, and no rule of the grant covers it.
|
|
97
|
+
* `no-network`: a host asked of a box that reaches none. `adapter`: the sandbox cannot say it.
|
|
98
|
+
*/
|
|
99
|
+
readonly code: "unknown-profile" | "closed" | "not-granted" | "no-network" | "adapter";
|
|
100
|
+
readonly message: string;
|
|
101
|
+
/** The rule of a grant that would cover what was refused. */
|
|
102
|
+
readonly rule?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* A box that cannot be had as it was asked for, with every reason at once. Silently widening or
|
|
107
|
+
* narrowing it would be worse than refusing: nothing was started.
|
|
108
|
+
*/
|
|
109
|
+
export class BoxRefused extends Error {
|
|
110
|
+
readonly reasons: readonly BoxRefusal[];
|
|
111
|
+
readonly sandbox: SandboxName | undefined;
|
|
112
|
+
constructor(reasons: readonly BoxRefusal[], sandbox?: SandboxName) {
|
|
113
|
+
super(`${sandbox === undefined ? "the box" : `sandbox ${sandbox}`} was refused: ${reasons.map((reason) => reason.message).join("; ")}`);
|
|
114
|
+
this.name = "BoxRefused";
|
|
115
|
+
this.reasons = reasons;
|
|
116
|
+
this.sandbox = sandbox;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The caller's gate: returns the sandbox when it can run, throws SandboxUnavailable when it cannot. */
|
|
121
|
+
export async function requireSandbox<S extends Sandbox>(sandbox: S): Promise<S> {
|
|
122
|
+
if (!(await sandbox.available())) throw new SandboxUnavailable(sandbox.name, "the probe failed");
|
|
123
|
+
return sandbox;
|
|
124
|
+
}
|
package/src/spawn.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Shared by the process-class sandboxes: start the wrapper, and the command inside it with exactly the listed environment. */
|
|
2
|
+
|
|
3
|
+
import { existsSync, statSync } from "node:fs";
|
|
4
|
+
import { constants } from "node:os";
|
|
5
|
+
|
|
6
|
+
import { BoxRefused, SandboxUnavailable } from "./sandbox.ts";
|
|
7
|
+
import type { LaunchOptions, LaunchedBox, SandboxName } from "./sandbox.ts";
|
|
8
|
+
|
|
9
|
+
/** Where a wrapper finds the system's tools: the host's choice, never the spec's. */
|
|
10
|
+
export const SYSTEM_PATH = "/usr/bin:/bin";
|
|
11
|
+
|
|
12
|
+
/** What a spec's variable is called in the wrapper's environment, on its way in. */
|
|
13
|
+
const CARRIED = "NIWA_BOX__";
|
|
14
|
+
|
|
15
|
+
/** Names a shell adds to what it starts, besides the ones it was given. */
|
|
16
|
+
const SHELL_ADDED = ["PWD", "OLDPWD", "SHLVL", "_"];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The command a wrapper runs, and the variables it has to be started with for that command.
|
|
20
|
+
*
|
|
21
|
+
* The wrapper is the host's own process: it locates system tools and loads libraries before any
|
|
22
|
+
* restriction exists, so the spec's environment must not reach it as its own, and it starts from a
|
|
23
|
+
* directory of the host's, not the spec's, where files the command writes cannot be read as
|
|
24
|
+
* configuration. A shell inside the box enters `cwd`, gives each variable its name and runs `env`,
|
|
25
|
+
* which removes a launcher variable the spec leaves out and what the shell adds, so the command has
|
|
26
|
+
* the variables the spec lists and what the wrapper adds itself.
|
|
27
|
+
*
|
|
28
|
+
* The values travel in the wrapper's environment under a prefix of their own. As arguments they
|
|
29
|
+
* would be readable by every user of the machine for as long as the wrapper lives.
|
|
30
|
+
*/
|
|
31
|
+
export function insideBox(
|
|
32
|
+
sandbox: SandboxName,
|
|
33
|
+
launcher: Readonly<Record<string, string>>,
|
|
34
|
+
guest: { readonly cwd: string; readonly env: Readonly<Record<string, string>> },
|
|
35
|
+
argv: readonly string[],
|
|
36
|
+
): { readonly command: string[]; readonly carried: Record<string, string> } {
|
|
37
|
+
const program = argv[0];
|
|
38
|
+
if (program === undefined) throw new BoxRefused([{ code: "adapter", message: "there is no program to run" }], sandbox);
|
|
39
|
+
if (program.includes("=")) {
|
|
40
|
+
throw new BoxRefused([{ code: "adapter", message: `the program ${JSON.stringify(program)} would be read by env as a variable` }], sandbox);
|
|
41
|
+
}
|
|
42
|
+
const names = Object.keys(guest.env);
|
|
43
|
+
const unset = [...Object.keys(launcher), ...SHELL_ADDED].filter((name) => !(name in guest.env)).flatMap((name) => ["-u", name]);
|
|
44
|
+
// The names are checked by the spec: letters, digits and `_` only.
|
|
45
|
+
const script = [
|
|
46
|
+
'cd -- "$1" || exit 126',
|
|
47
|
+
"shift",
|
|
48
|
+
...names.map((name) => `export ${name}="$${CARRIED}${name}" || exit 126; unset ${CARRIED}${name}`),
|
|
49
|
+
`exec /usr/bin/env ${unset.join(" ")} -- "$@"`,
|
|
50
|
+
].join("\n");
|
|
51
|
+
return {
|
|
52
|
+
command: ["/bin/sh", "-c", script, "niwa-box", guest.cwd, ...argv],
|
|
53
|
+
carried: Object.fromEntries(names.map((name) => [`${CARRIED}${name}`, guest.env[name] ?? ""])),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The name of the signal that ended a process, however the runtime reports it. */
|
|
58
|
+
function signalName(signal: NodeJS.Signals | number | null): NodeJS.Signals | null {
|
|
59
|
+
if (typeof signal !== "number") return signal;
|
|
60
|
+
const named = Object.entries(constants.signals).find(([, number]) => number === signal);
|
|
61
|
+
return named === undefined ? null : (named[0] as NodeJS.Signals);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Is the program not to be found, where the spawn looks for it? */
|
|
65
|
+
function missing(program: string | undefined, env: Readonly<Record<string, string>>): boolean {
|
|
66
|
+
if (program === undefined) return true;
|
|
67
|
+
return program.includes("/") ? !existsSync(program) : Bun.which(program, { PATH: env["PATH"] ?? "" }) === null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A working directory the command is to start in has to be there: the wrapper cannot tell the spec's fault from its own. */
|
|
71
|
+
function requireDirectory(cwd: string): void {
|
|
72
|
+
let directory = false;
|
|
73
|
+
try {
|
|
74
|
+
directory = statSync(cwd).isDirectory();
|
|
75
|
+
} catch {
|
|
76
|
+
// Not there: reported below, as a spawn reports it.
|
|
77
|
+
}
|
|
78
|
+
if (!directory) throw Object.assign(new Error(`ENOENT: the working directory ${cwd} is not a directory`), { code: "ENOENT" });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Starts the wrapper from `home` with the launcher's environment, and the command inside it. A
|
|
83
|
+
* wrapper that is not there is `SandboxUnavailable` and no process exists, as it is when the probe
|
|
84
|
+
* finds it missing; any other failure to start is the caller's to see as it is.
|
|
85
|
+
*/
|
|
86
|
+
export function spawnBox(
|
|
87
|
+
sandbox: SandboxName,
|
|
88
|
+
wrapper: readonly string[],
|
|
89
|
+
guest: { readonly cwd: string; readonly env: Readonly<Record<string, string>>; readonly argv: readonly string[] },
|
|
90
|
+
launcher: Readonly<Record<string, string>>,
|
|
91
|
+
home: string,
|
|
92
|
+
cleanup: () => Promise<void>,
|
|
93
|
+
options: LaunchOptions = {},
|
|
94
|
+
): LaunchedBox {
|
|
95
|
+
if (missing(wrapper[0], launcher)) throw new SandboxUnavailable(sandbox, `${wrapper[0] ?? "the wrapper"} is not there`);
|
|
96
|
+
requireDirectory(guest.cwd);
|
|
97
|
+
const stage = insideBox(sandbox, launcher, guest, guest.argv);
|
|
98
|
+
const argv = [...wrapper, ...stage.command];
|
|
99
|
+
let child: ReturnType<typeof Bun.spawn<"pipe", "pipe", "pipe">>;
|
|
100
|
+
try {
|
|
101
|
+
child = Bun.spawn(argv, {
|
|
102
|
+
cwd: home,
|
|
103
|
+
env: { ...launcher, ...stage.carried },
|
|
104
|
+
stdin: "pipe",
|
|
105
|
+
stdout: "pipe",
|
|
106
|
+
stderr: "pipe",
|
|
107
|
+
detached: options.detached ?? false,
|
|
108
|
+
});
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT" && missing(argv[0], launcher)) {
|
|
111
|
+
throw new SandboxUnavailable(sandbox, `${argv[0] ?? "the wrapper"} cannot be started: ${(error as Error).message}`);
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
const ended = child.exited;
|
|
116
|
+
const exited = ended.then(async (code) => {
|
|
117
|
+
await cleanup();
|
|
118
|
+
return code;
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
pid: child.pid,
|
|
122
|
+
stdin: child.stdin,
|
|
123
|
+
stdout: child.stdout,
|
|
124
|
+
stderr: child.stderr,
|
|
125
|
+
exited,
|
|
126
|
+
ended,
|
|
127
|
+
signaled: exited.then(() => signalName(child.signalCode), () => null),
|
|
128
|
+
kill: (signal) => child.kill(signal),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Runs the wrapper once, from `home`, to see whether it can start a command in `cwd` on this machine. */
|
|
133
|
+
export async function probe(
|
|
134
|
+
sandbox: SandboxName,
|
|
135
|
+
wrapper: readonly string[],
|
|
136
|
+
cwd: string,
|
|
137
|
+
launcher: Readonly<Record<string, string>>,
|
|
138
|
+
home: string,
|
|
139
|
+
): Promise<boolean> {
|
|
140
|
+
try {
|
|
141
|
+
const stage = insideBox(sandbox, launcher, { cwd, env: {} }, ["/usr/bin/true"]);
|
|
142
|
+
const child = Bun.spawn([...wrapper, ...stage.command], { cwd: home, env: { ...launcher }, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
|
143
|
+
return (await child.exited) === 0;
|
|
144
|
+
} catch {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
}
|
package/src/spec.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The BoxSpec: what a sandboxed process may reach.
|
|
3
|
+
*
|
|
4
|
+
* Writing and the network are allow-lists. The spec itself has no default prohibitions: `closed` is
|
|
5
|
+
* empty unless the caller sets it (a box resolved from profiles closes the places of the profiles it
|
|
6
|
+
* did not take). The environment is only what is listed; `process.env` is never inherited.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
/** A path as the grant wrote it. A leading `~` is expanded by the sandbox, not here, so the spec is a pure value; the working directory's is expanded once when paths are anchored to it. */
|
|
12
|
+
export const BoxPathSchema = z.string().min(1).brand<"BoxPath">();
|
|
13
|
+
export type BoxPath = z.output<typeof BoxPathSchema>;
|
|
14
|
+
|
|
15
|
+
/** A host the process may reach, as the sandbox's network filter spells it: "registry.npmjs.org", "*.example.com". */
|
|
16
|
+
export const NetHostSchema = z
|
|
17
|
+
.string()
|
|
18
|
+
.regex(/^\S+$/, "a net host must be non-empty and contain no whitespace")
|
|
19
|
+
.brand<"NetHost">();
|
|
20
|
+
export type NetHost = z.output<typeof NetHostSchema>;
|
|
21
|
+
|
|
22
|
+
/** The name of an environment variable the process receives. */
|
|
23
|
+
export const EnvNameSchema = z
|
|
24
|
+
.string()
|
|
25
|
+
.regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "not a valid environment variable name")
|
|
26
|
+
.brand<"EnvName">();
|
|
27
|
+
export type EnvName = z.output<typeof EnvNameSchema>;
|
|
28
|
+
|
|
29
|
+
export const BoxSpecSchema = z.object({
|
|
30
|
+
/** The working directory of the process. It is not made writable by being the cwd: list it in `write`. */
|
|
31
|
+
cwd: BoxPathSchema,
|
|
32
|
+
/**
|
|
33
|
+
* Places the process may read besides its `cwd`. Only a sandbox whose reading is an allow-list
|
|
34
|
+
* (nono) holds it to them; where reads are open unless denied (srt) it changes nothing.
|
|
35
|
+
*/
|
|
36
|
+
read: z.array(BoxPathSchema).default([]),
|
|
37
|
+
/** The only places the process may write. */
|
|
38
|
+
write: z.array(BoxPathSchema).default([]),
|
|
39
|
+
/**
|
|
40
|
+
* Places the process may neither read nor write, whatever else the spec lists: the sandbox keeps
|
|
41
|
+
* them closed or refuses the spec. Empty unless the caller sets it.
|
|
42
|
+
*/
|
|
43
|
+
closed: z.array(BoxPathSchema).default([]),
|
|
44
|
+
/** The only hosts the process may reach. Empty: no network. */
|
|
45
|
+
net: z.array(NetHostSchema).default([]),
|
|
46
|
+
/** The whole environment of the process. */
|
|
47
|
+
env: z.record(EnvNameSchema, z.string()).default({}),
|
|
48
|
+
/** Unix sockets the process may connect to (niwa's own socket must be reachable inside). */
|
|
49
|
+
sockets: z.array(BoxPathSchema).default([]),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** What the caller writes. */
|
|
53
|
+
export type BoxSpecInput = z.input<typeof BoxSpecSchema>;
|
|
54
|
+
/** A checked spec. */
|
|
55
|
+
export type BoxSpec = z.output<typeof BoxSpecSchema>;
|
|
56
|
+
|
|
57
|
+
/** Check a spec; a malformed one throws a ZodError naming the field. */
|
|
58
|
+
export function boxSpec(input: BoxSpecInput): BoxSpec {
|
|
59
|
+
return BoxSpecSchema.parse(input);
|
|
60
|
+
}
|
package/src/srt.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* srt, Anthropic's sandbox-runtime: the process class, first.
|
|
3
|
+
*
|
|
4
|
+
* The adapter writes srt's settings and runs the srt CLI as its own process for each session.
|
|
5
|
+
* It never calls the SandboxManager in-process: that keeps module-global state, and two sessions
|
|
6
|
+
* with different specs would share it.
|
|
7
|
+
*
|
|
8
|
+
* srt adds places of its own to what a spec lists, and the manifest's policy says so: the temp
|
|
9
|
+
* directory it hands the process and a few places under the home are always writable, and reads
|
|
10
|
+
* are open but for the spec's `closed` places, which are denied to reading and writing alike. A
|
|
11
|
+
* denied place wins over anything granted inside it, so a place the spec grants inside a closed one
|
|
12
|
+
* is refused rather than left unreachable.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
16
|
+
import { homedir, tmpdir } from "node:os";
|
|
17
|
+
import { join, resolve, sep } from "node:path";
|
|
18
|
+
|
|
19
|
+
import type { BoxPolicy, Sandbox, SandboxManifest } from "./sandbox.ts";
|
|
20
|
+
import { BoxRefused, SandboxUnavailable } from "./sandbox.ts";
|
|
21
|
+
import type { BoxRefusal } from "./sandbox.ts";
|
|
22
|
+
import type { BoxSpec } from "./spec.ts";
|
|
23
|
+
import { boxSpec } from "./spec.ts";
|
|
24
|
+
import { anchoredSpec } from "./paths.ts";
|
|
25
|
+
import { SYSTEM_PATH, probe, spawnBox } from "./spawn.ts";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A path as srt is to read it: the name and nothing else. A plain string is also a pattern wherever
|
|
29
|
+
* it has `*`, `?` or `[`, so an entry that does not exist yet would grant its neighbours as well.
|
|
30
|
+
*/
|
|
31
|
+
export interface SrtPath {
|
|
32
|
+
readonly path: string;
|
|
33
|
+
readonly literal: true;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The part of srt's settings file this adapter writes. */
|
|
37
|
+
export interface SrtSettings {
|
|
38
|
+
readonly network: {
|
|
39
|
+
readonly allowedDomains: readonly string[];
|
|
40
|
+
readonly deniedDomains: readonly string[];
|
|
41
|
+
readonly allowUnixSockets: readonly string[];
|
|
42
|
+
};
|
|
43
|
+
readonly filesystem: {
|
|
44
|
+
readonly denyRead: readonly SrtPath[];
|
|
45
|
+
readonly allowWrite: readonly SrtPath[];
|
|
46
|
+
readonly denyWrite: readonly SrtPath[];
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface SrtManifest extends SandboxManifest {
|
|
51
|
+
readonly sandbox: "srt";
|
|
52
|
+
readonly policy: BoxPolicy;
|
|
53
|
+
readonly settings: SrtSettings;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* What the srt process runs with: the host's, fixed. srt finds its shell and the system's tools
|
|
58
|
+
* through PATH before it confines anything, so the spec's environment is not given to it.
|
|
59
|
+
*/
|
|
60
|
+
const LAUNCHER_ENV: Readonly<Record<string, string>> = { PATH: SYSTEM_PATH };
|
|
61
|
+
|
|
62
|
+
/** The command's environment: its PATH is the system's unless the spec lists its own. */
|
|
63
|
+
function withPath(env: Readonly<Record<string, string>>): Readonly<Record<string, string>> {
|
|
64
|
+
return "PATH" in env ? env : { PATH: SYSTEM_PATH, ...env };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The srt CLI as a command: the package's own entry run by the current runtime, not found through PATH. */
|
|
68
|
+
function packagedCommand(): string[] | undefined {
|
|
69
|
+
try {
|
|
70
|
+
return [process.execPath, Bun.fileURLToPath(import.meta.resolve("@anthropic-ai/sandbox-runtime/dist/cli.js"))];
|
|
71
|
+
} catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface SrtOptions {
|
|
77
|
+
/** The srt command. Default: the installed `@anthropic-ai/sandbox-runtime`. */
|
|
78
|
+
readonly command?: readonly string[];
|
|
79
|
+
/** The platform srt runs on. Default: this one. */
|
|
80
|
+
readonly platform?: NodeJS.Platform;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const literally = (paths: readonly string[]): SrtPath[] => paths.map((path) => ({ path, literal: true }));
|
|
84
|
+
|
|
85
|
+
/** The devices srt always lets a process write. */
|
|
86
|
+
const SRT_DEVICES = ["/dev/stdout", "/dev/stderr", "/dev/null", "/dev/tty", "/dev/dtracehelper", "/dev/autofs_nowait"];
|
|
87
|
+
|
|
88
|
+
/** The temp directory srt gives every process, writable whatever the settings say. */
|
|
89
|
+
const SRT_TEMP = ["/tmp/claude", "/private/tmp/claude"];
|
|
90
|
+
|
|
91
|
+
/** Places under the home srt makes writable unless a closed place covers them. */
|
|
92
|
+
const SRT_HOME_WRITES = [".npm/_logs", ".claude/debug"];
|
|
93
|
+
|
|
94
|
+
function homeExpanded(path: string): string {
|
|
95
|
+
return resolve(path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What srt will let a process reach: the spec's places, and the ones srt adds of its own. */
|
|
99
|
+
/** Is `path` the place `root` names, or under it? */
|
|
100
|
+
function covers(root: string, path: string): boolean {
|
|
101
|
+
return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function srtPolicy(spec: BoxSpec): BoxPolicy {
|
|
105
|
+
const denied = spec.closed.map(homeExpanded);
|
|
106
|
+
const covered = (path: string) => denied.some((root) => covers(root, path));
|
|
107
|
+
const home = SRT_HOME_WRITES.map((place) => join(homedir(), place)).filter((path) => !covered(path));
|
|
108
|
+
return {
|
|
109
|
+
write: [...new Set([...spec.write.map(homeExpanded), ...SRT_TEMP, ...home])],
|
|
110
|
+
devices: SRT_DEVICES,
|
|
111
|
+
read: { except: denied },
|
|
112
|
+
net: spec.net,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function srt(options: SrtOptions = {}): Sandbox<SrtManifest> {
|
|
117
|
+
const command = options.command ?? packagedCommand();
|
|
118
|
+
const platform = options.platform ?? process.platform;
|
|
119
|
+
let probed: Promise<boolean> | undefined;
|
|
120
|
+
|
|
121
|
+
// Relative paths are read from the box's working directory, where srt is run, not from the host's.
|
|
122
|
+
const manifest = (given: BoxSpec): SrtManifest => {
|
|
123
|
+
const spec = anchoredSpec(given);
|
|
124
|
+
const reasons: BoxRefusal[] = [];
|
|
125
|
+
// On Linux srt cannot filter a socket by its path: the list is ignored, and the box would run
|
|
126
|
+
// with the socket the spec promises it closed to the process.
|
|
127
|
+
if (platform === "linux" && spec.sockets.length > 0) {
|
|
128
|
+
reasons.push({ code: "adapter", message: "srt on Linux cannot allow a unix socket by its path" });
|
|
129
|
+
}
|
|
130
|
+
const closed = spec.closed.map((path) => ({ path, place: homeExpanded(path) }));
|
|
131
|
+
for (const place of [spec.cwd, ...spec.read, ...spec.write, ...spec.sockets]) {
|
|
132
|
+
const within = closed.find((one) => covers(one.place, homeExpanded(place)));
|
|
133
|
+
if (within !== undefined) reasons.push({ code: "adapter", message: `srt cannot open ${place} inside ${within.path}, which is closed: a denied place wins over what lies in it` });
|
|
134
|
+
}
|
|
135
|
+
if (reasons.length > 0) throw new BoxRefused(reasons, "srt");
|
|
136
|
+
return {
|
|
137
|
+
sandbox: "srt",
|
|
138
|
+
cwd: spec.cwd,
|
|
139
|
+
env: withPath(spec.env),
|
|
140
|
+
policy: srtPolicy(spec),
|
|
141
|
+
settings: {
|
|
142
|
+
network: { allowedDomains: spec.net, deniedDomains: [], allowUnixSockets: spec.sockets },
|
|
143
|
+
filesystem: { denyRead: literally(spec.closed), allowWrite: literally(spec.write), denyWrite: literally(spec.closed) },
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** The wrapper's own command, up to the one it runs. */
|
|
149
|
+
const wrapped = (settingsPath: string) => {
|
|
150
|
+
if (!command) throw new SandboxUnavailable("srt", "@anthropic-ai/sandbox-runtime is not installed");
|
|
151
|
+
return [...command, "--settings", settingsPath, "--"];
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
name: "srt",
|
|
156
|
+
class: "process",
|
|
157
|
+
manifest,
|
|
158
|
+
available() {
|
|
159
|
+
probed ??= (async () => {
|
|
160
|
+
if (!command) return false;
|
|
161
|
+
const dir = await mkdtemp(join(tmpdir(), "niwa-srt-probe-"));
|
|
162
|
+
try {
|
|
163
|
+
const path = join(dir, "settings.json");
|
|
164
|
+
await writeFile(path, JSON.stringify(manifest(boxSpec({ cwd: dir })).settings));
|
|
165
|
+
return await probe("srt", wrapped(path), dir, LAUNCHER_ENV, dir);
|
|
166
|
+
} finally {
|
|
167
|
+
await rm(dir, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
})();
|
|
170
|
+
return probed;
|
|
171
|
+
},
|
|
172
|
+
async launch(spec, argv, options) {
|
|
173
|
+
const config = manifest(spec);
|
|
174
|
+
const dir = await mkdtemp(join(tmpdir(), "niwa-srt-"));
|
|
175
|
+
const cleanup = () => rm(dir, { recursive: true, force: true });
|
|
176
|
+
try {
|
|
177
|
+
const path = join(dir, "settings.json");
|
|
178
|
+
await writeFile(path, JSON.stringify(config.settings), { mode: 0o600 });
|
|
179
|
+
// srt runs from the directory that holds its settings: no one but this process has written there.
|
|
180
|
+
return spawnBox("srt", wrapped(path), { cwd: config.cwd, env: config.env, argv }, LAUNCHER_ENV, dir, cleanup, options);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
await cleanup();
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|