operon-os-sandbox 0.1.0-alpha.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 +55 -0
- package/README.md +79 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/machine.d.ts +41 -0
- package/dist/machine.js +90 -0
- package/dist/os-sandbox.d.ts +37 -0
- package/dist/os-sandbox.js +133 -0
- package/dist/srt-command.d.ts +25 -0
- package/dist/srt-command.js +34 -0
- package/dist/types.d.ts +77 -0
- package/dist/types.js +2 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yingjie Qiao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
-------------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
THIRD-PARTY LICENSES
|
|
27
|
+
|
|
28
|
+
Portions of this software were adapted from kimi-code, which is distributed
|
|
29
|
+
under the MIT License. Its copyright and permission notice is reproduced below.
|
|
30
|
+
|
|
31
|
+
-------------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
kimi-code
|
|
34
|
+
|
|
35
|
+
MIT License
|
|
36
|
+
|
|
37
|
+
Copyright (c) 2026 Moonshot AI
|
|
38
|
+
|
|
39
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
40
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
41
|
+
in the Software without restriction, including without limitation the rights
|
|
42
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
43
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
44
|
+
furnished to do so, subject to the following conditions:
|
|
45
|
+
|
|
46
|
+
The above copyright notice and this permission notice shall be included in all
|
|
47
|
+
copies or substantial portions of the Software.
|
|
48
|
+
|
|
49
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
50
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
51
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
52
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
53
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
54
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
55
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# operon-os-sandbox
|
|
2
|
+
|
|
3
|
+
OS-level command sandboxing for the local Machine. Every `Machine.run` — the
|
|
4
|
+
bash tool, search binaries, user hooks, everything — is wrapped in the
|
|
5
|
+
platform sandbox before it spawns: **Seatbelt** (`sandbox-exec`) on macOS,
|
|
6
|
+
**bubblewrap** on Linux, via
|
|
7
|
+
[`@anthropic-ai/sandbox-runtime`](https://github.com/anthropic-experimental/sandbox-runtime) (srt).
|
|
8
|
+
|
|
9
|
+
- **Filesystem**: writes are allowed only under each machine's cwd +
|
|
10
|
+
`additionalDirs` + tmp + the framework's task-log dir; reads are open except
|
|
11
|
+
srt's built-in credential protections plus your `denyRead`.
|
|
12
|
+
- **Network**: deny-all by default. Traffic is forced through a local
|
|
13
|
+
filtering proxy with a domain allowlist; out-of-list hosts can be routed to
|
|
14
|
+
an ask callback (wire it to your approval UI).
|
|
15
|
+
- **Visibility**: OS-level denials observed during a run are annotated onto
|
|
16
|
+
that command's stderr as a `<sandbox_violations>` block, so the model sees
|
|
17
|
+
*why* a command failed instead of a bare exit code. Known-benign startup
|
|
18
|
+
noise is filtered.
|
|
19
|
+
- **Degrade, don't break**: unsupported platform (Windows) or missing
|
|
20
|
+
dependencies (no `bwrap`) → `machine()` returns a plain `LocalMachine` and
|
|
21
|
+
`status.reason` says why. Same API either way.
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { OsSandbox } from "operon-os-sandbox";
|
|
27
|
+
|
|
28
|
+
// Once per process (starts the network filter proxy).
|
|
29
|
+
const sandbox = await OsSandbox.start({
|
|
30
|
+
network: {
|
|
31
|
+
allowedDomains: ["registry.npmjs.org", "*.github.com"],
|
|
32
|
+
onAskHost: async ({ host, port }) => askUserSomehow(host, port),
|
|
33
|
+
},
|
|
34
|
+
filesystem: {
|
|
35
|
+
denyRead: ["~/secrets"],
|
|
36
|
+
denyWrite: [], // e.g. [`${work}/.env`]
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
if (!sandbox.status.enabled) console.warn(`os-sandbox off: ${sandbox.status.reason}`);
|
|
40
|
+
|
|
41
|
+
// Wherever you previously built the machine:
|
|
42
|
+
// machine: new LocalMachine(WORK)
|
|
43
|
+
// becomes:
|
|
44
|
+
const machine = sandbox.machine(WORK);
|
|
45
|
+
|
|
46
|
+
// ... hand it to createAgent / the session as usual. withCwd() siblings
|
|
47
|
+
// (subagent worktrees) stay sandboxed automatically.
|
|
48
|
+
|
|
49
|
+
await sandbox.dispose(); // on shutdown
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Only local machines are wrapped — SSH and vendor-sandbox machines run their
|
|
53
|
+
commands elsewhere, so this layer deliberately does not touch them. Direct
|
|
54
|
+
file I/O (`readBytes`/`writeText`/…) is also untouched: those are the
|
|
55
|
+
framework's own code paths, gated by its path-access policy; the OS sandbox
|
|
56
|
+
exists for arbitrary *commands*, which have no such gate.
|
|
57
|
+
|
|
58
|
+
## Platform requirements
|
|
59
|
+
|
|
60
|
+
- **macOS**: none (uses `/usr/bin/sandbox-exec`).
|
|
61
|
+
- **Linux**: `bubblewrap`, `socat`, `ripgrep` installed. Ubuntu 24.04+ needs
|
|
62
|
+
`kernel.apparmor_restrict_unprivileged_userns=0` (or an AppArmor userns
|
|
63
|
+
profile). Missing pieces are reported in `status.reason` and the sandbox
|
|
64
|
+
degrades to plain `LocalMachine`.
|
|
65
|
+
- **Windows**: not supported by this package (srt's Windows backend is alpha
|
|
66
|
+
and needs an elevated install); always degrades.
|
|
67
|
+
|
|
68
|
+
## Caveats
|
|
69
|
+
|
|
70
|
+
- One `OsSandbox` per process — srt's `SandboxManager` is a process-wide
|
|
71
|
+
singleton. Different machines (different cwds) are fine; a second `start()`
|
|
72
|
+
with a different config is not.
|
|
73
|
+
- The network allowlist only serves proxy-aware clients (HTTP/HTTPS via env
|
|
74
|
+
vars, TCP via SOCKS). Raw-TCP clients that ignore proxies — plain `ssh`, DB
|
|
75
|
+
drivers — stay blocked even with `["*"]`; grant a unix socket, or run those
|
|
76
|
+
outside the sandbox.
|
|
77
|
+
- Violation annotation is best-effort: the macOS monitor tails `log stream`,
|
|
78
|
+
which lags slightly (failed commands get one 250 ms re-check).
|
|
79
|
+
- `@anthropic-ai/sandbox-runtime` is pinned exactly (0.0.x — API still moves).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { OsSandbox } from "./os-sandbox.ts";
|
|
2
|
+
export { SandboxedLocalMachine, type SandboxPolicyContext } from "./machine.ts";
|
|
3
|
+
export { toSrtInvocation, shellQuoteArg, type SrtInvocation } from "./srt-command.ts";
|
|
4
|
+
export type { OsSandboxOptions, OsSandboxNetworkOptions, OsSandboxFilesystemOptions, OsSandboxStatus, NetworkAskRequest, } from "./types.ts";
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { LocalMachine, type Machine, type RunCommandOptions, type RunCommandResult } from "operon-agents-core";
|
|
2
|
+
/**
|
|
3
|
+
* The resolved write/read policy every sandboxed machine of one OsSandbox
|
|
4
|
+
* shares. Immutable — a machine contributes only its own cwd/additionalDirs
|
|
5
|
+
* on top, per call.
|
|
6
|
+
*/
|
|
7
|
+
export interface SandboxPolicyContext {
|
|
8
|
+
readonly denyRead: readonly string[];
|
|
9
|
+
readonly denyWrite: readonly string[];
|
|
10
|
+
/** Session-level extra write roots (user config + tmp + task-log dirs). */
|
|
11
|
+
readonly allowWrite: readonly string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A LocalMachine whose `run` goes through the OS sandbox: the argv is wrapped
|
|
15
|
+
* by @anthropic-ai/sandbox-runtime (Seatbelt on macOS, bubblewrap on Linux)
|
|
16
|
+
* before it is spawned, and sandbox denials observed during the run are
|
|
17
|
+
* annotated onto the result's stderr so callers see WHY a command failed.
|
|
18
|
+
*
|
|
19
|
+
* Only `run` changes. Direct file I/O (readBytes/writeText/…) is the
|
|
20
|
+
* framework's own code path, gated by its path-access policy — the sandbox
|
|
21
|
+
* exists for arbitrary COMMANDS, which have no such gate.
|
|
22
|
+
*/
|
|
23
|
+
export declare class SandboxedLocalMachine extends LocalMachine {
|
|
24
|
+
private readonly policy;
|
|
25
|
+
constructor(policy: SandboxPolicyContext, cwdOrOptions?: string | {
|
|
26
|
+
cwd?: string;
|
|
27
|
+
additionalDirs?: readonly string[];
|
|
28
|
+
});
|
|
29
|
+
/** Re-rooted siblings (subagent worktrees) stay sandboxed — same policy, new cwd. */
|
|
30
|
+
withCwd(cwd: string): Machine;
|
|
31
|
+
run(argv: readonly string[], options?: RunCommandOptions): Promise<RunCommandResult>;
|
|
32
|
+
/**
|
|
33
|
+
* Every machine states the full filesystem policy per call: srt falls back
|
|
34
|
+
* per-FIELD (`?? config`), and an empty array is not undefined — restating
|
|
35
|
+
* the session lists plus this machine's own roots is the only spelling that
|
|
36
|
+
* cannot accidentally drop either half.
|
|
37
|
+
*/
|
|
38
|
+
private perCallConfig;
|
|
39
|
+
private annotateViolations;
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=machine.d.ts.map
|
package/dist/machine.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { isAbsolute, resolve } from "node:path";
|
|
2
|
+
import { LocalMachine } from "operon-agents-core";
|
|
3
|
+
import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
|
|
4
|
+
import { toSrtInvocation } from "./srt-command.js";
|
|
5
|
+
/** The macOS violation monitor tails `log stream`, which reports denials with a
|
|
6
|
+
* small delay — a failed command gets one re-check after this long. */
|
|
7
|
+
const VIOLATION_SETTLE_MS = 250;
|
|
8
|
+
let commandCounter = 0;
|
|
9
|
+
/**
|
|
10
|
+
* A LocalMachine whose `run` goes through the OS sandbox: the argv is wrapped
|
|
11
|
+
* by @anthropic-ai/sandbox-runtime (Seatbelt on macOS, bubblewrap on Linux)
|
|
12
|
+
* before it is spawned, and sandbox denials observed during the run are
|
|
13
|
+
* annotated onto the result's stderr so callers see WHY a command failed.
|
|
14
|
+
*
|
|
15
|
+
* Only `run` changes. Direct file I/O (readBytes/writeText/…) is the
|
|
16
|
+
* framework's own code path, gated by its path-access policy — the sandbox
|
|
17
|
+
* exists for arbitrary COMMANDS, which have no such gate.
|
|
18
|
+
*/
|
|
19
|
+
export class SandboxedLocalMachine extends LocalMachine {
|
|
20
|
+
policy;
|
|
21
|
+
constructor(policy, cwdOrOptions = process.cwd()) {
|
|
22
|
+
super(cwdOrOptions);
|
|
23
|
+
this.policy = policy;
|
|
24
|
+
}
|
|
25
|
+
/** Re-rooted siblings (subagent worktrees) stay sandboxed — same policy, new cwd. */
|
|
26
|
+
withCwd(cwd) {
|
|
27
|
+
const absolute = isAbsolute(cwd) ? cwd : resolve(this.getcwd(), cwd);
|
|
28
|
+
return new SandboxedLocalMachine(this.policy, { cwd: absolute, additionalDirs: this.additionalDirs() });
|
|
29
|
+
}
|
|
30
|
+
async run(argv, options = {}) {
|
|
31
|
+
// The sandbox session died or was never initialized — refuse rather than
|
|
32
|
+
// silently running unsandboxed. Hosts that want no sandbox build a plain
|
|
33
|
+
// LocalMachine (OsSandbox.machine already does this when disabled).
|
|
34
|
+
if (!SandboxManager.isSandboxingEnabled()) {
|
|
35
|
+
throw new Error("os-sandbox: SandboxManager is not initialized; use OsSandbox.start() and build machines through it.");
|
|
36
|
+
}
|
|
37
|
+
// Fold a per-run cwd override into the argv exactly as BaseMachine.run
|
|
38
|
+
// would — the sandbox must wrap the FINAL command, subshell and all.
|
|
39
|
+
const { cwd, ...rest } = options;
|
|
40
|
+
const effective = cwd === undefined ? argv : this.withCwdArgv(argv, cwd);
|
|
41
|
+
const { command, binShell } = toSrtInvocation(effective, this.osEnv.shellPath);
|
|
42
|
+
// A unique id, not the command text: srt compares attribution keys on
|
|
43
|
+
// their first 100 chars, so long commands sharing a prefix would
|
|
44
|
+
// cross-attribute violations.
|
|
45
|
+
const commandId = `operon-os-sandbox-${String(++commandCounter)}`;
|
|
46
|
+
let wrappedArgv;
|
|
47
|
+
try {
|
|
48
|
+
const wrapped = await SandboxManager.wrapWithSandboxArgv(command, binShell, this.perCallConfig(), options.signal, this.getcwd(), { commandId, commandText: command });
|
|
49
|
+
wrappedArgv = wrapped.argv;
|
|
50
|
+
// wrapped.env is process.env verbatim on macOS/Linux (proxy vars are baked
|
|
51
|
+
// into the wrapped script) and LocalMachine already layers the caller's
|
|
52
|
+
// overrides over the ambient env — so it is deliberately not forwarded.
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
throw new Error(`os-sandbox: failed to wrap command for the sandbox: ${error instanceof Error ? error.message : String(error)}`);
|
|
56
|
+
}
|
|
57
|
+
const result = await super.run(wrappedArgv, rest);
|
|
58
|
+
const stderr = await this.annotateViolations(commandId, result);
|
|
59
|
+
SandboxManager.cleanupAfterCommand();
|
|
60
|
+
return stderr === result.stderr ? result : { ...result, stderr };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Every machine states the full filesystem policy per call: srt falls back
|
|
64
|
+
* per-FIELD (`?? config`), and an empty array is not undefined — restating
|
|
65
|
+
* the session lists plus this machine's own roots is the only spelling that
|
|
66
|
+
* cannot accidentally drop either half.
|
|
67
|
+
*/
|
|
68
|
+
perCallConfig() {
|
|
69
|
+
const allowWrite = new Set([...this.policy.allowWrite, this.getcwd(), ...this.additionalDirs()]);
|
|
70
|
+
return {
|
|
71
|
+
filesystem: {
|
|
72
|
+
denyRead: [...this.policy.denyRead],
|
|
73
|
+
denyWrite: [...this.policy.denyWrite],
|
|
74
|
+
allowWrite: [...allowWrite],
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async annotateViolations(commandId, result) {
|
|
79
|
+
let stderr = SandboxManager.annotateStderrWithSandboxFailures(commandId, result.stderr);
|
|
80
|
+
// Only a FAILED command earns the settle-and-recheck: a denial the command
|
|
81
|
+
// itself absorbed (fallback logic, `|| true`) is not worth 250ms.
|
|
82
|
+
const failed = result.exitCode !== undefined && result.exitCode !== 0;
|
|
83
|
+
if (stderr === result.stderr && failed) {
|
|
84
|
+
await new Promise((resolveSleep) => setTimeout(resolveSleep, VIOLATION_SETTLE_MS));
|
|
85
|
+
stderr = SandboxManager.annotateStderrWithSandboxFailures(commandId, result.stderr);
|
|
86
|
+
}
|
|
87
|
+
return stderr;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=machine.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type Machine } from "operon-agents-core";
|
|
2
|
+
import type { OsSandboxOptions, OsSandboxStatus } from "./types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Process-wide OS sandbox session for LOCAL machines.
|
|
5
|
+
*
|
|
6
|
+
* `start()` never throws: on macOS/Linux with dependencies present it
|
|
7
|
+
* initializes @anthropic-ai/sandbox-runtime (which starts the network filter
|
|
8
|
+
* proxy) and `machine()` mints {@link SandboxedLocalMachine}s; anywhere else
|
|
9
|
+
* `status.enabled` is false and `machine()` mints plain {@link LocalMachine}s
|
|
10
|
+
* — same API, today's behavior, and `status.reason` says why.
|
|
11
|
+
*
|
|
12
|
+
* One OsSandbox per process: the underlying SandboxManager is a module-level
|
|
13
|
+
* singleton, so a second concurrent `start()` with a different config would
|
|
14
|
+
* silently share the first one's session. Remote machines (SSH, vendor
|
|
15
|
+
* sandboxes) are out of scope by design — their commands do not run on this
|
|
16
|
+
* host.
|
|
17
|
+
*/
|
|
18
|
+
export declare class OsSandbox {
|
|
19
|
+
readonly status: OsSandboxStatus;
|
|
20
|
+
private readonly policy;
|
|
21
|
+
private constructor();
|
|
22
|
+
static start(options?: OsSandboxOptions): Promise<OsSandbox>;
|
|
23
|
+
/** An explicitly-off OsSandbox: same `machine()` API, plain LocalMachines. */
|
|
24
|
+
static disabled(reason?: string): OsSandbox;
|
|
25
|
+
/**
|
|
26
|
+
* Build the machine a session should get — sandboxed when this OsSandbox is
|
|
27
|
+
* enabled, a plain LocalMachine otherwise. Accepts exactly what LocalMachine's
|
|
28
|
+
* constructor does.
|
|
29
|
+
*/
|
|
30
|
+
machine(cwdOrOptions?: string | {
|
|
31
|
+
cwd?: string;
|
|
32
|
+
additionalDirs?: readonly string[];
|
|
33
|
+
}): Machine;
|
|
34
|
+
/** Tear down the srt session (filter proxies, monitors). Idempotent. */
|
|
35
|
+
dispose(): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
//# sourceMappingURL=os-sandbox.d.ts.map
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { LocalMachine } from "operon-agents-core";
|
|
4
|
+
import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
|
|
5
|
+
import { SandboxedLocalMachine } from "./machine.js";
|
|
6
|
+
/**
|
|
7
|
+
* Write roots every sandboxed machine needs regardless of its cwd:
|
|
8
|
+
* the temp trees (both the symlink and its real path — srt matches paths
|
|
9
|
+
* literally), and the framework's background-task log directory — the bash
|
|
10
|
+
* tool redirects background/attached command output to
|
|
11
|
+
* `<home>/.operon/tasks/…` (or `/tmp/.operon/tasks` when home contains the
|
|
12
|
+
* workspace), and that redirect happens INSIDE the sandboxed command.
|
|
13
|
+
*/
|
|
14
|
+
function sharedWriteRoots() {
|
|
15
|
+
const roots = new Set();
|
|
16
|
+
for (const dir of [tmpdir(), "/tmp"]) {
|
|
17
|
+
roots.add(dir);
|
|
18
|
+
try {
|
|
19
|
+
roots.add(realpathSync(dir));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
/* missing on this platform — nothing to grant */
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const home = homedir().replace(/\/+$/, "");
|
|
26
|
+
if (home.length > 0)
|
|
27
|
+
roots.add(`${home}/.operon/tasks`);
|
|
28
|
+
return [...roots];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Denials every process trips on shell startup — pure noise that would stamp
|
|
32
|
+
* `<sandbox_violations>` onto EVERY successful command's stderr. Observed on
|
|
33
|
+
* macOS 15/26: sh/bash/zsh probe this sysctl and carry on.
|
|
34
|
+
*/
|
|
35
|
+
const BENIGN_VIOLATIONS = {
|
|
36
|
+
"*": ["sysctl-read kern.iossupportversion"],
|
|
37
|
+
};
|
|
38
|
+
function mergeIgnoreViolations(user) {
|
|
39
|
+
const merged = new Map();
|
|
40
|
+
for (const source of [BENIGN_VIOLATIONS, user ?? {}]) {
|
|
41
|
+
for (const [pattern, lines] of Object.entries(source)) {
|
|
42
|
+
merged.set(pattern, [...(merged.get(pattern) ?? []), ...lines]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return Object.fromEntries(merged);
|
|
46
|
+
}
|
|
47
|
+
function buildRuntimeConfig(options) {
|
|
48
|
+
const network = options.network;
|
|
49
|
+
return {
|
|
50
|
+
ignoreViolations: mergeIgnoreViolations(options.ignoreViolations),
|
|
51
|
+
network: {
|
|
52
|
+
// Required by srt; [] means "deny all", which is the safe default.
|
|
53
|
+
allowedDomains: [...(network?.allowedDomains ?? [])],
|
|
54
|
+
deniedDomains: [...(network?.deniedDomains ?? [])],
|
|
55
|
+
...(network?.allowUnixSockets !== undefined ? { allowUnixSockets: [...network.allowUnixSockets] } : {}),
|
|
56
|
+
...(network?.allowLocalBinding !== undefined ? { allowLocalBinding: network.allowLocalBinding } : {}),
|
|
57
|
+
},
|
|
58
|
+
filesystem: {
|
|
59
|
+
denyRead: [...(options.filesystem?.denyRead ?? [])],
|
|
60
|
+
// Session-level extras only; each machine adds its own cwd tree per call.
|
|
61
|
+
allowWrite: [...(options.filesystem?.allowWrite ?? [])],
|
|
62
|
+
denyWrite: [...(options.filesystem?.denyWrite ?? [])],
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Process-wide OS sandbox session for LOCAL machines.
|
|
68
|
+
*
|
|
69
|
+
* `start()` never throws: on macOS/Linux with dependencies present it
|
|
70
|
+
* initializes @anthropic-ai/sandbox-runtime (which starts the network filter
|
|
71
|
+
* proxy) and `machine()` mints {@link SandboxedLocalMachine}s; anywhere else
|
|
72
|
+
* `status.enabled` is false and `machine()` mints plain {@link LocalMachine}s
|
|
73
|
+
* — same API, today's behavior, and `status.reason` says why.
|
|
74
|
+
*
|
|
75
|
+
* One OsSandbox per process: the underlying SandboxManager is a module-level
|
|
76
|
+
* singleton, so a second concurrent `start()` with a different config would
|
|
77
|
+
* silently share the first one's session. Remote machines (SSH, vendor
|
|
78
|
+
* sandboxes) are out of scope by design — their commands do not run on this
|
|
79
|
+
* host.
|
|
80
|
+
*/
|
|
81
|
+
export class OsSandbox {
|
|
82
|
+
status;
|
|
83
|
+
policy;
|
|
84
|
+
constructor(status, policy) {
|
|
85
|
+
this.status = status;
|
|
86
|
+
this.policy = policy;
|
|
87
|
+
}
|
|
88
|
+
static async start(options = {}) {
|
|
89
|
+
const platform = process.platform;
|
|
90
|
+
if (platform !== "darwin" && platform !== "linux") {
|
|
91
|
+
return OsSandbox.disabled(`unsupported platform: ${platform} (macOS/Linux only)`);
|
|
92
|
+
}
|
|
93
|
+
const deps = await SandboxManager.checkDependenciesAsync();
|
|
94
|
+
if (deps.errors.length > 0) {
|
|
95
|
+
return OsSandbox.disabled(`missing sandbox dependencies: ${deps.errors.join(", ")}`);
|
|
96
|
+
}
|
|
97
|
+
const ask = options.network?.onAskHost;
|
|
98
|
+
try {
|
|
99
|
+
await SandboxManager.initialize(buildRuntimeConfig(options), ask === undefined
|
|
100
|
+
? undefined
|
|
101
|
+
: (pattern) => ask({ host: pattern.host, ...(pattern.port !== undefined ? { port: pattern.port } : {}) }), options.monitorViolations ?? true);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
return OsSandbox.disabled(`sandbox initialization failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
105
|
+
}
|
|
106
|
+
const policy = {
|
|
107
|
+
denyRead: [...(options.filesystem?.denyRead ?? [])],
|
|
108
|
+
denyWrite: [...(options.filesystem?.denyWrite ?? [])],
|
|
109
|
+
allowWrite: [...(options.filesystem?.allowWrite ?? []), ...sharedWriteRoots()],
|
|
110
|
+
};
|
|
111
|
+
return new OsSandbox({ enabled: true, platform, warnings: deps.warnings }, policy);
|
|
112
|
+
}
|
|
113
|
+
/** An explicitly-off OsSandbox: same `machine()` API, plain LocalMachines. */
|
|
114
|
+
static disabled(reason = "disabled by host") {
|
|
115
|
+
return new OsSandbox({ enabled: false, reason });
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Build the machine a session should get — sandboxed when this OsSandbox is
|
|
119
|
+
* enabled, a plain LocalMachine otherwise. Accepts exactly what LocalMachine's
|
|
120
|
+
* constructor does.
|
|
121
|
+
*/
|
|
122
|
+
machine(cwdOrOptions = process.cwd()) {
|
|
123
|
+
return this.policy === undefined
|
|
124
|
+
? new LocalMachine(cwdOrOptions)
|
|
125
|
+
: new SandboxedLocalMachine(this.policy, cwdOrOptions);
|
|
126
|
+
}
|
|
127
|
+
/** Tear down the srt session (filter proxies, monitors). Idempotent. */
|
|
128
|
+
async dispose() {
|
|
129
|
+
if (this.status.enabled)
|
|
130
|
+
await SandboxManager.reset();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=os-sandbox.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* srt's wrap API takes a SHELL COMMAND STRING (plus the shell to run it with),
|
|
3
|
+
* while Machine.run hands us an argv. This module converts losslessly between
|
|
4
|
+
* the two shapes so the sandbox always sees the exact command that would have
|
|
5
|
+
* run without it.
|
|
6
|
+
*/
|
|
7
|
+
/** Single-quote for a POSIX shell (same contract as BaseMachine's internal helper). */
|
|
8
|
+
export declare function shellQuoteArg(value: string): string;
|
|
9
|
+
export interface SrtInvocation {
|
|
10
|
+
/** The command string to hand srt. */
|
|
11
|
+
readonly command: string;
|
|
12
|
+
/** The shell srt should run it with. */
|
|
13
|
+
readonly binShell: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Two argv shapes reach a machine:
|
|
17
|
+
*
|
|
18
|
+
* - `[shell, "-c", script]` — the bash tool, user hooks, and BaseMachine's own
|
|
19
|
+
* cwd fallback all build this. Pass `script` through VERBATIM with its own
|
|
20
|
+
* shell, so quoting inside the script survives untouched.
|
|
21
|
+
* - anything else (a search binary and its args) — quote each argument into a
|
|
22
|
+
* command string and run it under `fallbackShell`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function toSrtInvocation(argv: readonly string[], fallbackShell: string): SrtInvocation;
|
|
25
|
+
//# sourceMappingURL=srt-command.d.ts.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* srt's wrap API takes a SHELL COMMAND STRING (plus the shell to run it with),
|
|
3
|
+
* while Machine.run hands us an argv. This module converts losslessly between
|
|
4
|
+
* the two shapes so the sandbox always sees the exact command that would have
|
|
5
|
+
* run without it.
|
|
6
|
+
*/
|
|
7
|
+
/** Single-quote for a POSIX shell (same contract as BaseMachine's internal helper). */
|
|
8
|
+
export function shellQuoteArg(value) {
|
|
9
|
+
if (/^[A-Za-z0-9_/@%+=:,.-]+$/.test(value))
|
|
10
|
+
return value;
|
|
11
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
12
|
+
}
|
|
13
|
+
const SHELL_BASENAMES = new Set(["bash", "zsh", "sh", "dash", "ksh"]);
|
|
14
|
+
function isShellPath(candidate) {
|
|
15
|
+
const base = candidate.slice(candidate.lastIndexOf("/") + 1);
|
|
16
|
+
return SHELL_BASENAMES.has(base);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Two argv shapes reach a machine:
|
|
20
|
+
*
|
|
21
|
+
* - `[shell, "-c", script]` — the bash tool, user hooks, and BaseMachine's own
|
|
22
|
+
* cwd fallback all build this. Pass `script` through VERBATIM with its own
|
|
23
|
+
* shell, so quoting inside the script survives untouched.
|
|
24
|
+
* - anything else (a search binary and its args) — quote each argument into a
|
|
25
|
+
* command string and run it under `fallbackShell`.
|
|
26
|
+
*/
|
|
27
|
+
export function toSrtInvocation(argv, fallbackShell) {
|
|
28
|
+
const [first, second, third] = argv;
|
|
29
|
+
if (argv.length === 3 && first !== undefined && second === "-c" && third !== undefined && isShellPath(first)) {
|
|
30
|
+
return { command: third, binShell: first };
|
|
31
|
+
}
|
|
32
|
+
return { command: argv.map(shellQuoteArg).join(" "), binShell: fallbackShell };
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=srt-command.js.map
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** A host a sandboxed command tried to reach, handed to {@link OsSandboxNetworkOptions.onAskHost}. */
|
|
2
|
+
export interface NetworkAskRequest {
|
|
3
|
+
readonly host: string;
|
|
4
|
+
/** Destination port when the client stated one; undefined for portless matches. */
|
|
5
|
+
readonly port?: number;
|
|
6
|
+
}
|
|
7
|
+
export interface OsSandboxNetworkOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Domain patterns commands may reach: `"api.github.com"`, `"*.npmjs.org"`,
|
|
10
|
+
* `"github.com:443"`, or `"*"` for everything. Default `[]` — all network
|
|
11
|
+
* access is DENIED.
|
|
12
|
+
*
|
|
13
|
+
* All traffic is forced through a local filtering proxy, so even `["*"]`
|
|
14
|
+
* only serves proxy-aware clients (HTTP/HTTPS via env vars, TCP via SOCKS).
|
|
15
|
+
* A client that ignores proxies entirely — plain `ssh`, a raw DB socket —
|
|
16
|
+
* stays blocked regardless of the allowlist; grant those a unix socket or
|
|
17
|
+
* run them outside the sandbox.
|
|
18
|
+
*/
|
|
19
|
+
readonly allowedDomains?: readonly string[];
|
|
20
|
+
/** Deny these even when a broader allow pattern would match. */
|
|
21
|
+
readonly deniedDomains?: readonly string[];
|
|
22
|
+
/**
|
|
23
|
+
* Consulted when a command contacts a host outside the allowlist; resolve
|
|
24
|
+
* `true` to let that request through. Wire this to the host application's
|
|
25
|
+
* approval UI (the framework's `Responder.requestApproval`, a dialog, …).
|
|
26
|
+
* Absent — out-of-list hosts are denied outright.
|
|
27
|
+
*/
|
|
28
|
+
readonly onAskHost?: (request: NetworkAskRequest) => Promise<boolean>;
|
|
29
|
+
/** Unix socket paths commands may connect to (e.g. `/var/run/docker.sock`). */
|
|
30
|
+
readonly allowUnixSockets?: readonly string[];
|
|
31
|
+
/** Let commands bind/listen on localhost ports (dev servers). */
|
|
32
|
+
readonly allowLocalBinding?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface OsSandboxFilesystemOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Paths commands must not read, on top of srt's built-in credential
|
|
37
|
+
* protections (`~/.ssh` and friends are already covered).
|
|
38
|
+
*/
|
|
39
|
+
readonly denyRead?: readonly string[];
|
|
40
|
+
/**
|
|
41
|
+
* Extra write roots granted to EVERY machine, on top of the per-machine
|
|
42
|
+
* grant (its cwd + additionalDirs) and the shared system roots (tmp, the
|
|
43
|
+
* framework's background-task log directory).
|
|
44
|
+
*/
|
|
45
|
+
readonly allowWrite?: readonly string[];
|
|
46
|
+
/** Read-only carve-outs inside allowed write roots (e.g. a `.env`, `.git`). */
|
|
47
|
+
readonly denyWrite?: readonly string[];
|
|
48
|
+
}
|
|
49
|
+
export interface OsSandboxOptions {
|
|
50
|
+
/** Omit for the default: all network access denied. */
|
|
51
|
+
readonly network?: OsSandboxNetworkOptions;
|
|
52
|
+
readonly filesystem?: OsSandboxFilesystemOptions;
|
|
53
|
+
/**
|
|
54
|
+
* Watch the OS for sandbox denials (macOS `log stream`, Linux seccomp
|
|
55
|
+
* observer) and annotate them onto failing commands' stderr, so the model
|
|
56
|
+
* sees "the sandbox blocked X" instead of a bare exit code. Default true.
|
|
57
|
+
*/
|
|
58
|
+
readonly monitorViolations?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Violations to suppress from monitoring, merged over the built-in
|
|
61
|
+
* benign-noise list: key `"*"` applies to every command, any other key is a
|
|
62
|
+
* substring match on the command; values are substring matches on the
|
|
63
|
+
* violation line.
|
|
64
|
+
*/
|
|
65
|
+
readonly ignoreViolations?: Readonly<Record<string, readonly string[]>>;
|
|
66
|
+
}
|
|
67
|
+
export type OsSandboxStatus = {
|
|
68
|
+
readonly enabled: true;
|
|
69
|
+
readonly platform: "darwin" | "linux";
|
|
70
|
+
/** Non-fatal findings from the dependency check (degraded functionality). */
|
|
71
|
+
readonly warnings: readonly string[];
|
|
72
|
+
} | {
|
|
73
|
+
readonly enabled: false;
|
|
74
|
+
/** Why sandboxing is off: unsupported platform, missing deps, init failure, or explicit. */
|
|
75
|
+
readonly reason: string;
|
|
76
|
+
};
|
|
77
|
+
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "operon-os-sandbox",
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "OS-level command sandboxing for the LocalMachine: every Machine.run is wrapped in the platform sandbox (macOS Seatbelt / Linux bubblewrap, via @anthropic-ai/sandbox-runtime) with workspace-scoped write access, domain-allowlist networking, and sandbox-denial annotation on stderr. Unsupported platforms and missing dependencies degrade to a plain LocalMachine.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/nickqiaoo/operon-agents.git",
|
|
10
|
+
"directory": "packages/os-sandbox"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/nickqiaoo/operon-agents/tree/main/packages/os-sandbox#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/nickqiaoo/operon-agents/issues"
|
|
15
|
+
},
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@anthropic-ai/sandbox-runtime": "0.0.73",
|
|
26
|
+
"operon-agents-core": "0.1.0-alpha.0"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"!dist/**/*.map",
|
|
31
|
+
"README.md"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"clean": "rm -rf dist *.tsbuildinfo",
|
|
35
|
+
"build": "pnpm --filter operon-agents-core build && tsc -p tsconfig.build.json",
|
|
36
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
37
|
+
"test": "for f in src/test/e2e*.ts; do echo \"\\n▶ $f\"; node --experimental-strip-types --no-warnings \"$f\" || exit 1; done"
|
|
38
|
+
}
|
|
39
|
+
}
|