opencode-any-sandbox 0.0.0-stage → 0.1.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 +201 -0
- package/README.md +111 -2
- package/dist/config.d.ts +53 -0
- package/dist/config.js +128 -0
- package/dist/engines.d.ts +35 -0
- package/dist/engines.js +161 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +354 -0
- package/dist/rpc.d.ts +43 -0
- package/dist/rpc.js +17 -0
- package/package.json +67 -4
- package/tui.jsx +165 -0
package/dist/engines.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { access, constants, realpath, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { PROTECTED_NAMES, configDirectory } from "./config.js";
|
|
5
|
+
const contains = (root, target) => {
|
|
6
|
+
const relative = path.relative(root, target);
|
|
7
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
8
|
+
};
|
|
9
|
+
async function canonical(value) {
|
|
10
|
+
try {
|
|
11
|
+
return await realpath(value);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return path.resolve(value);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export async function policy(config, project, scratch) {
|
|
18
|
+
const root = await canonical(project);
|
|
19
|
+
if (root === path.parse(root).root)
|
|
20
|
+
throw new Error("the filesystem root cannot be the sandbox's project");
|
|
21
|
+
const temp = await canonical(scratch);
|
|
22
|
+
const writable = [...new Set([root, temp, ...(await Promise.all(config.write.map(canonical)))])];
|
|
23
|
+
// The temp directory holds throwaway work (a scratch git repo, a build), so its names are not protected.
|
|
24
|
+
const protectedPaths = writable
|
|
25
|
+
.filter((item) => item !== temp)
|
|
26
|
+
.flatMap((item) => PROTECTED_NAMES.map((name) => path.join(item, name)));
|
|
27
|
+
return {
|
|
28
|
+
project: root,
|
|
29
|
+
scratch: temp,
|
|
30
|
+
writable,
|
|
31
|
+
denyWrite: [...new Set([...protectedPaths, ...config.denyWrite])],
|
|
32
|
+
denyRead: [...new Set(config.denyRead)],
|
|
33
|
+
allowDomains: config.allowDomains,
|
|
34
|
+
network: config.network,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
async function which(name, env) {
|
|
38
|
+
for (const dir of (env.PATH ?? "").split(path.delimiter)) {
|
|
39
|
+
if (!dir)
|
|
40
|
+
continue;
|
|
41
|
+
const candidate = path.join(dir, name);
|
|
42
|
+
try {
|
|
43
|
+
await access(candidate, constants.X_OK);
|
|
44
|
+
return candidate;
|
|
45
|
+
}
|
|
46
|
+
catch { }
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
export async function resolveExecutable(config, env = process.env) {
|
|
51
|
+
const found = config.bin ?? (await which(config.engine, env));
|
|
52
|
+
if (!found)
|
|
53
|
+
throw new Error(`${config.engine} was not found on PATH; install it or set "bin" in the config`);
|
|
54
|
+
await access(found, constants.X_OK);
|
|
55
|
+
return realpath(found);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Builds the engine's argv for a policy. Every protection is written as an explicit rule, so it does not depend on
|
|
59
|
+
* what the engine happens to protect by default.
|
|
60
|
+
*/
|
|
61
|
+
export async function build(config, executable, policy, privateDir) {
|
|
62
|
+
// The engine, the launcher and the config live outside the sandbox. A writable root that holds any of them would
|
|
63
|
+
// let one confined command rewrite the sandbox for every later one.
|
|
64
|
+
const configDir = await canonical(configDirectory());
|
|
65
|
+
const configFile = await canonical(path.join(configDirectory(), "config.json"));
|
|
66
|
+
for (const item of [executable, privateDir, configDir, configFile]) {
|
|
67
|
+
const holder = policy.writable.find((root) => contains(root, item));
|
|
68
|
+
if (holder)
|
|
69
|
+
throw new Error(`writable directory ${holder} contains ${item}, which must stay out of the sandbox's reach`);
|
|
70
|
+
}
|
|
71
|
+
// Nor can a writable root sit inside the plugin's config directory.
|
|
72
|
+
const nested = policy.writable.find((root) => contains(configDir, root));
|
|
73
|
+
if (nested)
|
|
74
|
+
throw new Error(`writable directory ${nested} is inside ${configDir}, which must stay out of the sandbox's reach`);
|
|
75
|
+
if (config.engine === "tartaros") {
|
|
76
|
+
const prefix = [executable, "run"];
|
|
77
|
+
for (const item of policy.writable)
|
|
78
|
+
prefix.push("--write", item);
|
|
79
|
+
for (const item of policy.denyWrite)
|
|
80
|
+
prefix.push("--write-deny", item);
|
|
81
|
+
for (const item of policy.denyRead)
|
|
82
|
+
prefix.push("--read-deny", item);
|
|
83
|
+
for (const item of policy.allowDomains)
|
|
84
|
+
prefix.push("--allow-domain", item);
|
|
85
|
+
if (policy.network === "all")
|
|
86
|
+
prefix.push("--net");
|
|
87
|
+
prefix.push("--env", "OPENCODE_SESSION_ID", "--env", "TMPDIR=" + policy.scratch, ...config.engineArgs, "--");
|
|
88
|
+
return { name: "tartaros", executable, prefix, env: {} };
|
|
89
|
+
}
|
|
90
|
+
if (policy.network === "all")
|
|
91
|
+
throw new Error('srt has no "allow all network" setting; list the domains in "allowDomains" instead');
|
|
92
|
+
const settings = path.join(privateDir, "srt-settings.json");
|
|
93
|
+
await writeFile(settings, JSON.stringify({
|
|
94
|
+
filesystem: { denyRead: policy.denyRead, allowWrite: policy.writable, denyWrite: policy.denyWrite },
|
|
95
|
+
network: { allowedDomains: policy.allowDomains, deniedDomains: [] },
|
|
96
|
+
}, null, 2), { mode: 0o600 });
|
|
97
|
+
// srt hands the command TMPDIR=$CLAUDE_CODE_TMPDIR (default /tmp/claude, which may not exist): use the scratch dir.
|
|
98
|
+
return {
|
|
99
|
+
name: "srt",
|
|
100
|
+
executable,
|
|
101
|
+
prefix: [executable, "--settings", settings, ...config.engineArgs, "--"],
|
|
102
|
+
env: { CLAUDE_CODE_TMPDIR: policy.scratch },
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Runs `exit 0` through the engine. A sandbox that cannot start a trivial command will not start the agent's. The probe
|
|
107
|
+
* runs in its own process group, killed on timeout and after it exits, so no helper the engine started outlives it.
|
|
108
|
+
*/
|
|
109
|
+
export async function probe(engine, cwd) {
|
|
110
|
+
const [file, ...args] = engine.prefix;
|
|
111
|
+
await new Promise((resolve, reject) => {
|
|
112
|
+
const child = spawn(file, [...args, "/bin/sh", "-c", "exit 0"], {
|
|
113
|
+
cwd,
|
|
114
|
+
env: { ...process.env, ...engine.env },
|
|
115
|
+
detached: true,
|
|
116
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
117
|
+
});
|
|
118
|
+
let stderr = "";
|
|
119
|
+
child.stderr?.on("data", (chunk) => {
|
|
120
|
+
if (stderr.length < 4000)
|
|
121
|
+
stderr += chunk.toString();
|
|
122
|
+
});
|
|
123
|
+
const killGroup = () => {
|
|
124
|
+
try {
|
|
125
|
+
if (child.pid)
|
|
126
|
+
process.kill(-child.pid, "SIGKILL");
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
};
|
|
130
|
+
const timer = setTimeout(() => {
|
|
131
|
+
killGroup();
|
|
132
|
+
reject(new Error(`${engine.name} did not finish "exit 0" within 15 s`));
|
|
133
|
+
}, 15_000);
|
|
134
|
+
child.on("error", (error) => {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
reject(error);
|
|
137
|
+
});
|
|
138
|
+
// "exit", not "close": a helper holding the pipes open must not keep the plugin waiting.
|
|
139
|
+
child.on("exit", (code, signal) => {
|
|
140
|
+
clearTimeout(timer);
|
|
141
|
+
killGroup();
|
|
142
|
+
if (code === 0)
|
|
143
|
+
return resolve();
|
|
144
|
+
reject(Object.assign(new Error(`${engine.name} exited with ${code ?? signal}`), { stderr }));
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
149
|
+
/** The launcher OpenCode runs as the shell. It runs outside the sandbox and starts the real shell inside it. */
|
|
150
|
+
export function launcher(engine) {
|
|
151
|
+
return [
|
|
152
|
+
"#!/bin/sh",
|
|
153
|
+
"# opencode-any-sandbox: runs the real shell inside the configured sandbox.",
|
|
154
|
+
'real=$OPENCODE_ANY_SANDBOX_SHELL',
|
|
155
|
+
"unset OPENCODE_ANY_SANDBOX_SHELL",
|
|
156
|
+
'if [ -z "$real" ]; then echo "opencode-any-sandbox: no shell to run" >&2; exit 126; fi',
|
|
157
|
+
...Object.entries(engine.env).map(([key, value]) => `export ${key}=${quote(value)}`),
|
|
158
|
+
`exec ${engine.prefix.map(quote).join(" ")} "$real" "$@"`,
|
|
159
|
+
"",
|
|
160
|
+
].join("\n");
|
|
161
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { STATUS, type Blocked, type Status } from "./rpc.js";
|
|
2
|
+
export { STATUS } from "./rpc.js";
|
|
3
|
+
export type { Status, Blocked } from "./rpc.js";
|
|
4
|
+
export { DEFAULT_DENY_READ, PROTECTED_NAMES, parse as parseConfig } from "./config.js";
|
|
5
|
+
export type { Config, UserConfig } from "./config.js";
|
|
6
|
+
interface ShellCreateBefore {
|
|
7
|
+
command: string;
|
|
8
|
+
cwd: string;
|
|
9
|
+
timeout: number;
|
|
10
|
+
shell: string;
|
|
11
|
+
env: Record<string, string | undefined>;
|
|
12
|
+
}
|
|
13
|
+
interface PermissionEvaluation {
|
|
14
|
+
readonly sessionID?: string;
|
|
15
|
+
readonly action: string;
|
|
16
|
+
readonly resources: ReadonlyArray<string>;
|
|
17
|
+
effect: string;
|
|
18
|
+
message?: string;
|
|
19
|
+
}
|
|
20
|
+
type ToolExecute = (input: unknown, context: {
|
|
21
|
+
id: string;
|
|
22
|
+
} & Record<string, unknown>) => Promise<unknown>;
|
|
23
|
+
interface ToolValue {
|
|
24
|
+
description?: string;
|
|
25
|
+
execute: ToolExecute;
|
|
26
|
+
}
|
|
27
|
+
export interface Context {
|
|
28
|
+
readonly location: {
|
|
29
|
+
readonly directory: string;
|
|
30
|
+
};
|
|
31
|
+
readonly shell: {
|
|
32
|
+
hook(name: "create.before", cb: (event: ShellCreateBefore) => Promise<void> | void): Promise<unknown>;
|
|
33
|
+
};
|
|
34
|
+
readonly permission: {
|
|
35
|
+
hook(name: "evaluate", cb: (event: PermissionEvaluation) => Promise<void> | void): Promise<unknown>;
|
|
36
|
+
};
|
|
37
|
+
readonly tool: {
|
|
38
|
+
transform(cb: (editor: {
|
|
39
|
+
update(name: string, fn: (tool: ToolValue) => void): void;
|
|
40
|
+
}) => void): Promise<unknown>;
|
|
41
|
+
reload?(): Promise<void>;
|
|
42
|
+
};
|
|
43
|
+
/** Absent in hosts without RPC: the TUI part then has nothing to show, and the sandbox works the same. */
|
|
44
|
+
readonly rpc?: {
|
|
45
|
+
register(definition: typeof STATUS, handlers: {
|
|
46
|
+
status: () => Promise<Status>;
|
|
47
|
+
}): Promise<{
|
|
48
|
+
events: {
|
|
49
|
+
emit(name: "blocked", data: Blocked): Promise<void>;
|
|
50
|
+
};
|
|
51
|
+
}>;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** OpenCode names a file as `<environment>:<absolute path>`, a glob like `/dir/*`, or a path relative to the project. */
|
|
55
|
+
export declare function resourcePath(resource: string, project: string): string | undefined;
|
|
56
|
+
export declare const plugin: {
|
|
57
|
+
id: string;
|
|
58
|
+
setup(ctx: Context): Promise<() => Promise<void>>;
|
|
59
|
+
};
|
|
60
|
+
export default plugin;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { access, mkdtemp, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { PROTECTED_NAMES, configDirectory, load } from "./config.js";
|
|
6
|
+
import { STATUS } from "./rpc.js";
|
|
7
|
+
import { build, launcher, policy as buildPolicy, probe, resolveExecutable } from "./engines.js";
|
|
8
|
+
export { STATUS } from "./rpc.js";
|
|
9
|
+
export { DEFAULT_DENY_READ, PROTECTED_NAMES, parse as parseConfig } from "./config.js";
|
|
10
|
+
const ID = "opencode-any-sandbox";
|
|
11
|
+
const SHELL_ENV = "OPENCODE_ANY_SANDBOX_SHELL";
|
|
12
|
+
const log = (message) => console.warn(`[${ID}] ${message}`);
|
|
13
|
+
// macOS and Windows volumes ignore case by default: `.OPENCODE` is `.opencode` there.
|
|
14
|
+
const fold = process.platform === "darwin" || process.platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
|
|
15
|
+
const contains = (root, target) => {
|
|
16
|
+
const relative = path.relative(fold(root), fold(target));
|
|
17
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
18
|
+
};
|
|
19
|
+
/** The real path of a file that may not exist yet: its deepest existing ancestor resolved, the rest appended. */
|
|
20
|
+
async function realTarget(value) {
|
|
21
|
+
let current = value;
|
|
22
|
+
const rest = [];
|
|
23
|
+
for (;;) {
|
|
24
|
+
try {
|
|
25
|
+
return path.join(await realpath(current), ...rest);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
const parent = path.dirname(current);
|
|
29
|
+
if (parent === current)
|
|
30
|
+
return value;
|
|
31
|
+
rest.unshift(path.basename(current));
|
|
32
|
+
current = parent;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const isRelative = (resource) => !/^[A-Za-z0-9_-]+:(?=\/)/.test(resource) && !path.isAbsolute(resource);
|
|
37
|
+
/** OpenCode names a file as `<environment>:<absolute path>`, a glob like `/dir/*`, or a path relative to the project. */
|
|
38
|
+
export function resourcePath(resource, project) {
|
|
39
|
+
let value = resource.replace(/^[A-Za-z0-9_-]+:(?=\/)/, "");
|
|
40
|
+
value = value.replace(/\/\*+$/, "").replace(/\*+$/, "");
|
|
41
|
+
if (!value)
|
|
42
|
+
return undefined;
|
|
43
|
+
return path.resolve(project, value);
|
|
44
|
+
}
|
|
45
|
+
async function prepare(directory) {
|
|
46
|
+
let config;
|
|
47
|
+
try {
|
|
48
|
+
config = await load();
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
// A config that cannot be read cannot say "permissive": fail closed.
|
|
52
|
+
return { ok: false, mode: "enforce", engine: "none", reason: `invalid config: ${error.message}`, denyWrite: [] };
|
|
53
|
+
}
|
|
54
|
+
// README promise: on Windows commands are blocked, whatever the mode.
|
|
55
|
+
if (process.platform === "win32")
|
|
56
|
+
return { ok: false, mode: "enforce", engine: config.engine, reason: "Windows is not supported yet", denyWrite: config.denyWrite };
|
|
57
|
+
const made = [];
|
|
58
|
+
let stage = "creating its temp directories";
|
|
59
|
+
try {
|
|
60
|
+
// Canonical (/private/var/... on macOS), so the check that keeps them out of every writable root compares like with like.
|
|
61
|
+
const privateDir = await realpath(await mkdtemp(path.join(os.tmpdir(), `${ID}-`)));
|
|
62
|
+
made.push(privateDir);
|
|
63
|
+
const scratch = await realpath(await mkdtemp(path.join(os.tmpdir(), `${ID}-tmp-`)));
|
|
64
|
+
made.push(scratch);
|
|
65
|
+
stage = "finding the engine";
|
|
66
|
+
const executable = await resolveExecutable(config);
|
|
67
|
+
stage = "building the policy";
|
|
68
|
+
const policy = await buildPolicy(config, directory, scratch);
|
|
69
|
+
const engine = await build(config, executable, policy, privateDir);
|
|
70
|
+
stage = "running a test command";
|
|
71
|
+
await probe(engine, policy.project);
|
|
72
|
+
return { ok: true, config, policy, engine, privateDir };
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
await removeAll(made);
|
|
76
|
+
const detail = error.stderr?.trim() || error.message;
|
|
77
|
+
return {
|
|
78
|
+
ok: false,
|
|
79
|
+
mode: config.mode,
|
|
80
|
+
engine: config.engine,
|
|
81
|
+
reason: `${config.engine} failed while ${stage}: ${detail}`,
|
|
82
|
+
denyWrite: config.denyWrite,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Removes each directory on its own, so one failure does not leave the others behind. */
|
|
87
|
+
async function removeAll(dirs) {
|
|
88
|
+
await Promise.allSettled(dirs.map((dir) => rm(dir, { recursive: true, force: true })));
|
|
89
|
+
}
|
|
90
|
+
/** Normalized path segments of a resource relative to some directory OpenCode chose (the session's cwd). */
|
|
91
|
+
function touchesProtectedName(relative) {
|
|
92
|
+
// A backslash is a separator only on Windows; elsewhere it is part of a file name.
|
|
93
|
+
const separators = process.platform === "win32" ? /[\\/]+/ : /\/+/;
|
|
94
|
+
const segments = path.normalize(relative).split(separators).filter((item) => item && item !== "." && item !== "..").map(fold);
|
|
95
|
+
return PROTECTED_NAMES.some((name) => {
|
|
96
|
+
const parts = name.split("/").map(fold);
|
|
97
|
+
for (let i = 0; i + parts.length <= segments.length; i++)
|
|
98
|
+
if (parts.every((part, j) => segments[i + j] === part))
|
|
99
|
+
return true;
|
|
100
|
+
return false;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
function describe(state) {
|
|
104
|
+
const { policy, engine } = state;
|
|
105
|
+
const network = policy.network === "all" ? "Network is open." : policy.allowDomains.length ? `Network is limited to: ${policy.allowDomains.join(", ")}.` : "There is no network access.";
|
|
106
|
+
return (` Shell commands run inside the ${engine.name} sandbox. Writes are limited to the project, $TMPDIR` +
|
|
107
|
+
(policy.writable.length > 2 ? " and configured directories" : "") +
|
|
108
|
+
`; OpenCode config, skills, agents and git hooks in the project are read-only. ${network}` +
|
|
109
|
+
" Credential stores such as ~/.ssh and ~/.aws are unreadable.");
|
|
110
|
+
}
|
|
111
|
+
export const plugin = {
|
|
112
|
+
id: ID,
|
|
113
|
+
async setup(ctx) {
|
|
114
|
+
const announce = (current) => {
|
|
115
|
+
if (current.ok)
|
|
116
|
+
log(`shell commands run inside ${current.engine.name} (${current.engine.executable})`);
|
|
117
|
+
else
|
|
118
|
+
log(current.mode === "enforce" ? `${current.reason}; shell commands are blocked` : `${current.reason}; shell commands run unconfined`);
|
|
119
|
+
};
|
|
120
|
+
let state = await prepare(ctx.location.directory);
|
|
121
|
+
announce(state);
|
|
122
|
+
// A failed start is tried again, at most every 30 s, when a command or the TUI needs the sandbox: installing the
|
|
123
|
+
// engine or fixing the config then works without restarting OpenCode.
|
|
124
|
+
const current = () => state;
|
|
125
|
+
let lastTry = Date.now();
|
|
126
|
+
let retrying;
|
|
127
|
+
const recover = async () => {
|
|
128
|
+
if (state.ok || process.platform === "win32" || Date.now() - lastTry < 30_000)
|
|
129
|
+
return;
|
|
130
|
+
retrying ??= (async () => {
|
|
131
|
+
lastTry = Date.now();
|
|
132
|
+
const next = await prepare(ctx.location.directory);
|
|
133
|
+
if (next.ok || next.reason !== (state.ok ? "" : state.reason))
|
|
134
|
+
announce(next);
|
|
135
|
+
state = next;
|
|
136
|
+
// The shell tool's description tells the model whether it is sandboxed: rebuild it.
|
|
137
|
+
if (next.ok)
|
|
138
|
+
await ctx.tool.reload?.().catch(() => { });
|
|
139
|
+
})().finally(() => (retrying = undefined));
|
|
140
|
+
await retrying;
|
|
141
|
+
};
|
|
142
|
+
let blockedCount = 0;
|
|
143
|
+
const status = () => {
|
|
144
|
+
const state = current();
|
|
145
|
+
if (!state.ok)
|
|
146
|
+
return { state: state.mode === "enforce" ? "blocked" : "off", engine: state.engine, reason: state.reason, blocked: blockedCount };
|
|
147
|
+
const { policy, engine } = state;
|
|
148
|
+
return {
|
|
149
|
+
state: "on",
|
|
150
|
+
engine: engine.name,
|
|
151
|
+
network: policy.network === "all" ? "open" : policy.allowDomains.length ? policy.allowDomains.join(", ") : "none",
|
|
152
|
+
project: policy.project,
|
|
153
|
+
scratch: policy.scratch,
|
|
154
|
+
writable: policy.writable,
|
|
155
|
+
protected: policy.denyWrite,
|
|
156
|
+
denyRead: policy.denyRead,
|
|
157
|
+
blocked: blockedCount,
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
const rpc = await ctx.rpc?.register(STATUS, {
|
|
161
|
+
status: async () => {
|
|
162
|
+
await recover();
|
|
163
|
+
return status();
|
|
164
|
+
},
|
|
165
|
+
}).catch((error) => {
|
|
166
|
+
log(`the status for the TUI is not available: ${error.message}`);
|
|
167
|
+
return undefined;
|
|
168
|
+
});
|
|
169
|
+
const report = (event) => {
|
|
170
|
+
blockedCount++;
|
|
171
|
+
void rpc?.events.emit("blocked", event).catch(() => { });
|
|
172
|
+
};
|
|
173
|
+
const calls = new AsyncLocalStorage();
|
|
174
|
+
// The commands of the agent's shell calls in progress, to recognize one whose async context got lost on the way.
|
|
175
|
+
const running = new Map();
|
|
176
|
+
const launchers = new Map();
|
|
177
|
+
const writeLauncher = async (name) => {
|
|
178
|
+
const state = current();
|
|
179
|
+
if (!state.ok)
|
|
180
|
+
throw new Error("no sandbox");
|
|
181
|
+
const file = path.join(state.privateDir, name);
|
|
182
|
+
const partial = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}`;
|
|
183
|
+
try {
|
|
184
|
+
await writeFile(partial, launcher(state.engine), { mode: 0o700, flag: "wx" });
|
|
185
|
+
await rename(partial, file);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
await rm(partial, { force: true });
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
return file;
|
|
192
|
+
};
|
|
193
|
+
// One launcher per shell name: concurrent first calls share one write, a failed write is retried by the next call,
|
|
194
|
+
// and a launcher that something removed is written again, once.
|
|
195
|
+
const launcherFor = async (name) => {
|
|
196
|
+
for (let attempt = 0;; attempt++) {
|
|
197
|
+
let pending = launchers.get(name);
|
|
198
|
+
if (!pending) {
|
|
199
|
+
const created = writeLauncher(name);
|
|
200
|
+
pending = created;
|
|
201
|
+
launchers.set(name, created);
|
|
202
|
+
created.catch(() => launchers.get(name) === created && launchers.delete(name));
|
|
203
|
+
}
|
|
204
|
+
const file = await pending;
|
|
205
|
+
try {
|
|
206
|
+
await access(file);
|
|
207
|
+
return file;
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
if (launchers.get(name) === pending)
|
|
211
|
+
launchers.delete(name);
|
|
212
|
+
if (attempt > 0)
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
await ctx.tool.transform((editor) => {
|
|
218
|
+
editor.update("shell", (tool) => {
|
|
219
|
+
const state = current();
|
|
220
|
+
if (state.ok)
|
|
221
|
+
tool.description = (tool.description ?? "") + describe(state);
|
|
222
|
+
else if (state.mode === "permissive")
|
|
223
|
+
tool.description = (tool.description ?? "") + ` Shell commands run WITHOUT a sandbox (${ID}: ${state.reason}).`;
|
|
224
|
+
else
|
|
225
|
+
tool.description = (tool.description ?? "") + ` Shell commands are blocked (${ID}: ${state.reason}).`;
|
|
226
|
+
const execute = tool.execute;
|
|
227
|
+
tool.execute = async (input, context) => {
|
|
228
|
+
const key = Symbol();
|
|
229
|
+
const command = input?.command;
|
|
230
|
+
if (typeof command === "string")
|
|
231
|
+
running.set(key, command);
|
|
232
|
+
try {
|
|
233
|
+
const sessionID = typeof context.sessionID === "string" ? context.sessionID : undefined;
|
|
234
|
+
return await calls.run({ sessionID }, () => execute(input, context));
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
running.delete(key);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
await ctx.shell.hook("create.before", async (event) => {
|
|
243
|
+
// Only the agent's shell tool is confined: the server's own commands and the user's terminals are not.
|
|
244
|
+
const call = calls.getStore();
|
|
245
|
+
// Outside the tool's async context, a shell is the agent's only if it runs a command the agent is running now. A
|
|
246
|
+
// user's `!` command or the server's own shells are left alone; the agent's command is never let through.
|
|
247
|
+
if (!call && ![...running.values()].includes(event.command))
|
|
248
|
+
return;
|
|
249
|
+
const sessionID = call?.sessionID;
|
|
250
|
+
await recover();
|
|
251
|
+
const state = current();
|
|
252
|
+
if (!state.ok) {
|
|
253
|
+
if (state.mode === "enforce") {
|
|
254
|
+
const message = `${ID}: ${state.reason}. Command blocked.`;
|
|
255
|
+
report({ kind: "shell", message, sessionID });
|
|
256
|
+
throw new Error(message);
|
|
257
|
+
}
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const name = path.basename(event.shell);
|
|
261
|
+
const file = await launcherFor(name);
|
|
262
|
+
event.env[SHELL_ENV] = event.shell;
|
|
263
|
+
// TMPDIR is not changed here: the engine itself runs with this environment, and srt puts its sockets under
|
|
264
|
+
// TMPDIR. tartaros hands the command the scratch directory with --env, srt through CLAUDE_CODE_TMPDIR.
|
|
265
|
+
event.shell = file;
|
|
266
|
+
});
|
|
267
|
+
// The file tools run inside OpenCode, outside the sandbox. Without this, one `write` to a protected path would undo
|
|
268
|
+
// what the sandbox protects: plant a skill or a git hook, or rewrite this plugin's config.
|
|
269
|
+
const project = state.ok ? state.policy.project : await realTarget(path.resolve(ctx.location.directory));
|
|
270
|
+
const guardedFor = new WeakMap();
|
|
271
|
+
const guardedNow = () => {
|
|
272
|
+
const state = current();
|
|
273
|
+
let list = guardedFor.get(state);
|
|
274
|
+
if (!list) {
|
|
275
|
+
list = Promise.all((state.ok
|
|
276
|
+
? [...state.policy.denyWrite, configDirectory(), state.privateDir, state.engine.executable]
|
|
277
|
+
: [configDirectory(), ...state.denyWrite, ...PROTECTED_NAMES.map((name) => path.join(project, name))]).map(realTarget));
|
|
278
|
+
guardedFor.set(state, list);
|
|
279
|
+
}
|
|
280
|
+
return list;
|
|
281
|
+
};
|
|
282
|
+
// Both the path as written and where it really lands (a symlink inside the project can point at a protected place).
|
|
283
|
+
const isGuarded = async (value) => {
|
|
284
|
+
const guarded = await guardedNow();
|
|
285
|
+
if (guarded.some((root) => contains(root, value)))
|
|
286
|
+
return true;
|
|
287
|
+
const real = await realTarget(value);
|
|
288
|
+
return guarded.some((root) => contains(root, real));
|
|
289
|
+
};
|
|
290
|
+
// OpenCode resolves relative paths against the session's working directory, which the `cd` tool can move. Track it,
|
|
291
|
+
// and refuse to move it into a protected place.
|
|
292
|
+
const cwds = new Map();
|
|
293
|
+
await ctx.tool.transform((editor) => {
|
|
294
|
+
try {
|
|
295
|
+
editor.update("cd", (tool) => {
|
|
296
|
+
const execute = tool.execute;
|
|
297
|
+
tool.execute = async (input, context) => {
|
|
298
|
+
const sessionID = typeof context.sessionID === "string" ? context.sessionID : undefined;
|
|
299
|
+
const base = (sessionID && cwds.get(sessionID)) || project;
|
|
300
|
+
const raw = input?.path;
|
|
301
|
+
const target = typeof raw === "string" && raw.trim() ? resourcePath(raw.trim(), base) : undefined;
|
|
302
|
+
if (target && (await isGuarded(target))) {
|
|
303
|
+
const message = `${ID}: ${raw} is protected while the shell is sandboxed; the working directory stays where it is.`;
|
|
304
|
+
report({ kind: "edit", message, sessionID });
|
|
305
|
+
throw new Error(message);
|
|
306
|
+
}
|
|
307
|
+
const result = await execute(input, context);
|
|
308
|
+
if (sessionID) {
|
|
309
|
+
const cwd = result?.output?.cwd;
|
|
310
|
+
if (raw === null || cwd === null)
|
|
311
|
+
cwds.delete(sessionID);
|
|
312
|
+
else if (typeof cwd === "string")
|
|
313
|
+
cwds.set(sessionID, resourcePath(cwd, base) ?? base);
|
|
314
|
+
else if (target)
|
|
315
|
+
cwds.set(sessionID, target);
|
|
316
|
+
}
|
|
317
|
+
return result;
|
|
318
|
+
};
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
// No `cd` tool in this OpenCode: the working directory is always the project.
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
await ctx.permission.hook("evaluate", async (event) => {
|
|
326
|
+
if (event.action !== "edit")
|
|
327
|
+
return;
|
|
328
|
+
const base = (event.sessionID && cwds.get(event.sessionID)) || project;
|
|
329
|
+
let hit;
|
|
330
|
+
for (const item of event.resources) {
|
|
331
|
+
const value = resourcePath(item, isRelative(item) ? base : project);
|
|
332
|
+
if (value === undefined)
|
|
333
|
+
continue;
|
|
334
|
+
// A relative resource is also judged by the names it touches, in case the cwd moved in a way not seen here.
|
|
335
|
+
if ((isRelative(item) && touchesProtectedName(item)) || (await isGuarded(value))) {
|
|
336
|
+
hit = item;
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (!hit)
|
|
341
|
+
return;
|
|
342
|
+
event.effect = "deny";
|
|
343
|
+
event.message = `${ID}: ${hit} is protected while the shell is sandboxed (config, skills, agents, git hooks).`;
|
|
344
|
+
report({ kind: "edit", message: event.message, sessionID: event.sessionID });
|
|
345
|
+
});
|
|
346
|
+
return async () => {
|
|
347
|
+
const state = current();
|
|
348
|
+
if (!state.ok)
|
|
349
|
+
return;
|
|
350
|
+
await removeAll([state.privateDir, state.policy.scratch]);
|
|
351
|
+
};
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
export default plugin;
|
package/dist/rpc.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The contract between the server part and the TUI part. JSON Schemas keep it portable: the TUI imports this file as
|
|
3
|
+
* plain JavaScript, with no schema library.
|
|
4
|
+
*/
|
|
5
|
+
export declare const STATUS: {
|
|
6
|
+
readonly id: "opencode-any-sandbox";
|
|
7
|
+
readonly methods: {
|
|
8
|
+
readonly status: {
|
|
9
|
+
readonly input: {
|
|
10
|
+
readonly type: "object";
|
|
11
|
+
};
|
|
12
|
+
readonly output: {
|
|
13
|
+
readonly type: "object";
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
readonly events: {
|
|
18
|
+
/** A shell command or a file edit the plugin stopped. */
|
|
19
|
+
readonly blocked: {
|
|
20
|
+
readonly schema: {
|
|
21
|
+
readonly type: "object";
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
export interface Status {
|
|
27
|
+
/** on: commands run sandboxed. blocked: the engine failed and commands are refused. off: permissive, unconfined. */
|
|
28
|
+
readonly state: "on" | "blocked" | "off";
|
|
29
|
+
readonly engine: string;
|
|
30
|
+
readonly network?: string;
|
|
31
|
+
readonly reason?: string;
|
|
32
|
+
readonly project?: string;
|
|
33
|
+
readonly scratch?: string;
|
|
34
|
+
readonly writable?: readonly string[];
|
|
35
|
+
readonly protected?: readonly string[];
|
|
36
|
+
readonly denyRead?: readonly string[];
|
|
37
|
+
readonly blocked: number;
|
|
38
|
+
}
|
|
39
|
+
export interface Blocked {
|
|
40
|
+
readonly kind: "shell" | "edit";
|
|
41
|
+
readonly message: string;
|
|
42
|
+
readonly sessionID?: string;
|
|
43
|
+
}
|
package/dist/rpc.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The contract between the server part and the TUI part. JSON Schemas keep it portable: the TUI imports this file as
|
|
3
|
+
* plain JavaScript, with no schema library.
|
|
4
|
+
*/
|
|
5
|
+
export const STATUS = {
|
|
6
|
+
id: "opencode-any-sandbox",
|
|
7
|
+
methods: {
|
|
8
|
+
status: {
|
|
9
|
+
input: { type: "object" },
|
|
10
|
+
output: { type: "object" },
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
events: {
|
|
14
|
+
/** A shell command or a file edit the plugin stopped. */
|
|
15
|
+
blocked: { schema: { type: "object" } },
|
|
16
|
+
},
|
|
17
|
+
};
|