opencode-fs-plugin 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +173 -121
- package/SPEC.md +61 -40
- package/package.json +2 -2
- package/skills/filesystem/SKILL.md +93 -53
- package/src/core/format.ts +3 -9
- package/src/core/permissions.ts +32 -14
- package/src/core/relay-control.ts +343 -0
- package/src/core/relay-protocol.ts +229 -0
- package/src/core/types.ts +0 -5
- package/src/index.ts +55 -66
- package/src/tools/cat.ts +31 -46
- package/src/tools/command.ts +533 -0
- package/src/tools/{http_request.ts → curl.ts} +4 -4
- package/src/tools/pipe.ts +7 -7
- package/src/core/spill.ts +0 -145
- package/src/tools/exec.ts +0 -483
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import { constants as fsConstants } from "node:fs";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
11
|
+
import type { CageOptions, Relaxation, Violation } from "procage";
|
|
12
|
+
import { FsError, errorMessage } from "../core/errors.js";
|
|
13
|
+
import { RelayControlServer } from "../core/relay-control.js";
|
|
14
|
+
import { collect } from "../core/stream.js";
|
|
15
|
+
import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Proxy settings the child may inherit in addition to the preset's own
|
|
19
|
+
* environment allowlist. They are passed explicitly because the policy's
|
|
20
|
+
* allowlist does not name them. No other caller environment variable is
|
|
21
|
+
* forwarded explicitly, but the preset's allowlist still applies, and a proxy
|
|
22
|
+
* variable may itself carry proxy credentials.
|
|
23
|
+
*/
|
|
24
|
+
export const EXEC_PROXY_ENV = [
|
|
25
|
+
"HTTP_PROXY",
|
|
26
|
+
"HTTPS_PROXY",
|
|
27
|
+
"ALL_PROXY",
|
|
28
|
+
"NO_PROXY",
|
|
29
|
+
"http_proxy",
|
|
30
|
+
"https_proxy",
|
|
31
|
+
"all_proxy",
|
|
32
|
+
"no_proxy",
|
|
33
|
+
"npm_config_proxy",
|
|
34
|
+
"npm_config_https_proxy",
|
|
35
|
+
"npm_config_http_proxy",
|
|
36
|
+
"npm_config_noproxy",
|
|
37
|
+
"NPM_CONFIG_PROXY",
|
|
38
|
+
"NPM_CONFIG_HTTPS_PROXY",
|
|
39
|
+
"NPM_CONFIG_HTTP_PROXY",
|
|
40
|
+
"NPM_CONFIG_NOPROXY",
|
|
41
|
+
] as const;
|
|
42
|
+
|
|
43
|
+
const EXEC_NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
44
|
+
|
|
45
|
+
export function isSafeExecName(value: string): boolean {
|
|
46
|
+
return EXEC_NAME.test(value);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const Schema = Type.Object(
|
|
50
|
+
{
|
|
51
|
+
command: Type.String({ minLength: 1, description: "Allowlisted executable name, without a path or shell syntax." }),
|
|
52
|
+
args: Type.Optional(Type.Array(Type.String(), { description: "Arguments passed verbatim to the executable." })),
|
|
53
|
+
cwd: Type.Optional(Type.String({ minLength: 1, description: "Working directory inside the project. Default: project root." })),
|
|
54
|
+
stdin: Type.Optional(Type.String({ description: "Text for stdin when the tool is not used in a pipe." })),
|
|
55
|
+
timeoutMs: Type.Optional(
|
|
56
|
+
Type.Integer({ minimum: 100, maximum: 600_000, description: "Timeout in milliseconds. Default: 120000." }),
|
|
57
|
+
),
|
|
58
|
+
},
|
|
59
|
+
{ additionalProperties: false },
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
type Input = Static<typeof Schema>;
|
|
63
|
+
|
|
64
|
+
export interface PolicyDocument {
|
|
65
|
+
fs: Array<{ access: string; target: { subpath: string } }>;
|
|
66
|
+
net: string;
|
|
67
|
+
ipc: { unix_sockets: string[] };
|
|
68
|
+
[key: string]: unknown;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* How a run reaches the network: procage's transparent relay on Linux T1, or
|
|
73
|
+
* no networking at all. There is no proxy or all-IP fallback.
|
|
74
|
+
*/
|
|
75
|
+
export type NetworkMode = "relay" | "disabled";
|
|
76
|
+
|
|
77
|
+
/** A relay control endpoint handed to procage's cage options. */
|
|
78
|
+
export interface RelaySettings {
|
|
79
|
+
readonly socketPath: string;
|
|
80
|
+
/** Unsigned 64-bit run id, as a decimal string on the wire. */
|
|
81
|
+
readonly runId: bigint;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The `net-relay` gap an unsupported backend reports, if this error is one. */
|
|
85
|
+
export function relayGapReason(error: unknown, api: typeof import("procage")): string | undefined {
|
|
86
|
+
if (!(error instanceof api.CapabilityGapError)) return undefined;
|
|
87
|
+
const unsupported = error.gaps.some((gap) => gap.construct === "net-relay" && gap.kind === "unsupported");
|
|
88
|
+
if (!unsupported) return undefined;
|
|
89
|
+
const message = error.message.trim();
|
|
90
|
+
return message.length > 0 ? message : "the transparent relay is unavailable on this host";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A recognized unsupported relay backend; the run retries with networking off. */
|
|
94
|
+
class RelayUnsupportedError extends Error {
|
|
95
|
+
constructor(reason: string) {
|
|
96
|
+
super(reason);
|
|
97
|
+
this.name = "RelayUnsupportedError";
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Why a blocked run failed, and what to do about it. */
|
|
102
|
+
export function blockedHint(mode: NetworkMode): string {
|
|
103
|
+
return mode === "relay"
|
|
104
|
+
? "The sandbox denied a path or refused a network flow. Approve the denied path, or the refused resource in fs_exec_network, and retry."
|
|
105
|
+
: "Networking is disabled in this sandbox. Approve the denied external path in the permission prompt and retry; relayed networking needs Linux tier T1.";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface ExecOutcome {
|
|
109
|
+
stdout: Buffer;
|
|
110
|
+
stderr: Buffer;
|
|
111
|
+
exitCode: number;
|
|
112
|
+
signal: string | null;
|
|
113
|
+
timedOut: boolean;
|
|
114
|
+
aborted: boolean;
|
|
115
|
+
/** The mode the sandbox actually ran. */
|
|
116
|
+
networkMode: NetworkMode;
|
|
117
|
+
violations: Violation[];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let procage: Promise<typeof import("procage")> | undefined;
|
|
121
|
+
|
|
122
|
+
function loadProcage(): Promise<typeof import("procage")> {
|
|
123
|
+
procage ??= import("procage");
|
|
124
|
+
return procage;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export const commandTool: ToolSpec<Input> = {
|
|
128
|
+
name: "command",
|
|
129
|
+
description:
|
|
130
|
+
"Run an executable allowed by fs_command in a procage sandbox without a shell. Direct calls return JSON; " +
|
|
131
|
+
"pipe stages pass raw stdout. On Linux tier T1 every network flow is named to the transparent relay, " +
|
|
132
|
+
"which asks fs_exec_network for its exact resource; elsewhere networking is disabled.",
|
|
133
|
+
schema: Schema,
|
|
134
|
+
pipeable: "filter",
|
|
135
|
+
mutates: true,
|
|
136
|
+
async run(ctx, input, io) {
|
|
137
|
+
const command = input.command.trim();
|
|
138
|
+
if (!isSafeExecName(command)) {
|
|
139
|
+
throw new FsError(`command must be a bare executable name: "${input.command}"`, "invalid");
|
|
140
|
+
}
|
|
141
|
+
const args = input.args ?? [];
|
|
142
|
+
if (args.some((arg) => arg.includes("\0"))) {
|
|
143
|
+
throw new FsError("arguments must not contain NUL bytes.", "invalid");
|
|
144
|
+
}
|
|
145
|
+
await ctx.permission.assertTrusted([command]);
|
|
146
|
+
|
|
147
|
+
const requested = input.cwd ?? ".";
|
|
148
|
+
const cwdTarget = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
149
|
+
const cwdStats = await ctx.sandbox.stat(cwdTarget.full, requested);
|
|
150
|
+
if (!cwdStats.isDirectory()) throw new FsError(`cwd is not a directory: "${requested}"`, "not-directory");
|
|
151
|
+
await ctx.permission.assertExternal([{ target: cwdTarget, boundary: cwdTarget.full }]);
|
|
152
|
+
if (ctx.signal.aborted) throw new FsError("command interrupted.", "interrupted");
|
|
153
|
+
|
|
154
|
+
const executable = await resolveExecutable(command);
|
|
155
|
+
const tempDir = await fs.mkdtemp(path.join(ctx.tmpdir, "fs-exec-"));
|
|
156
|
+
try {
|
|
157
|
+
const inputData = io.stdin === undefined
|
|
158
|
+
? input.stdin === undefined ? undefined : Buffer.from(input.stdin)
|
|
159
|
+
: await collect(io.stdin);
|
|
160
|
+
const approvedResources: string[] = [];
|
|
161
|
+
const approved: Array<{ full: string }> = [];
|
|
162
|
+
const assertNetwork = async (resource: string) => {
|
|
163
|
+
await ctx.permissionFor("fs_exec_network").assertTrusted([resource]);
|
|
164
|
+
if (!approvedResources.includes(resource)) approvedResources.push(resource);
|
|
165
|
+
};
|
|
166
|
+
const base = {
|
|
167
|
+
command,
|
|
168
|
+
executable,
|
|
169
|
+
args,
|
|
170
|
+
cwd: cwdTarget.full,
|
|
171
|
+
timeoutMs: input.timeoutMs ?? 120_000,
|
|
172
|
+
allowed: approved,
|
|
173
|
+
tempDir,
|
|
174
|
+
input: inputData,
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
let attempt: RelayAttempt | undefined;
|
|
178
|
+
for (let round = 0; round < 12; round++) {
|
|
179
|
+
attempt = await runAttempt(ctx, base, assertNetwork);
|
|
180
|
+
const deniedPaths = discoverExternalPaths(ctx, attempt.outcome)
|
|
181
|
+
.filter((candidate) => !approved.some((entry) => entry.full === candidate));
|
|
182
|
+
let added = false;
|
|
183
|
+
for (const candidate of deniedPaths) {
|
|
184
|
+
const target = await existingBoundary(ctx, candidate);
|
|
185
|
+
if (target === undefined) continue;
|
|
186
|
+
/* v8 ignore next */
|
|
187
|
+
const stats = await ctx.sandbox.stat(target.full, candidate).catch(() => undefined);
|
|
188
|
+
/* v8 ignore next */
|
|
189
|
+
if (stats === undefined) continue;
|
|
190
|
+
const boundary = stats.isDirectory() ? target.full : path.dirname(target.full);
|
|
191
|
+
const dirTarget = await ctx.sandbox.resolveExisting(boundary, { allowRoot: true });
|
|
192
|
+
if (approved.some((entry) => entry.full === dirTarget.full)) continue;
|
|
193
|
+
await ctx.permission.assertExternal([{ target: dirTarget, boundary: dirTarget.full }]);
|
|
194
|
+
approved.push({ full: dirTarget.full });
|
|
195
|
+
added = true;
|
|
196
|
+
}
|
|
197
|
+
if (!added) break;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/* v8 ignore next */
|
|
201
|
+
if (attempt === undefined) throw new FsError("command produced no result.", "io");
|
|
202
|
+
const outcome = attempt.outcome;
|
|
203
|
+
const networkMode = attempt.mode;
|
|
204
|
+
const networkReason = attempt.reason;
|
|
205
|
+
|
|
206
|
+
const metadata = {
|
|
207
|
+
command,
|
|
208
|
+
args,
|
|
209
|
+
exitCode: outcome.exitCode,
|
|
210
|
+
signal: outcome.signal,
|
|
211
|
+
timedOut: outcome.timedOut,
|
|
212
|
+
aborted: outcome.aborted,
|
|
213
|
+
sandboxBlocked: isSandboxBlocked(outcome),
|
|
214
|
+
violations: outcome.violations.length,
|
|
215
|
+
network: networkMode === "relay",
|
|
216
|
+
networkMode,
|
|
217
|
+
networkHosts: approvedResources,
|
|
218
|
+
...(networkReason === undefined ? {} : { networkReason }),
|
|
219
|
+
externalPaths: approved.map((entry) => entry.full),
|
|
220
|
+
};
|
|
221
|
+
if (io.piped === true) {
|
|
222
|
+
return {
|
|
223
|
+
stdout: outcome.stdout,
|
|
224
|
+
stderr: outcome.stderr.toString("utf8"),
|
|
225
|
+
exitCode: outcome.exitCode === 0 ? 0 : 1,
|
|
226
|
+
metadata,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
const sandboxBlocked = isSandboxBlocked(outcome);
|
|
230
|
+
const body = {
|
|
231
|
+
...metadata,
|
|
232
|
+
stdout: outcome.stdout.toString("utf8"),
|
|
233
|
+
stderr: outcome.stderr.toString("utf8"),
|
|
234
|
+
violations: outcome.violations,
|
|
235
|
+
...(sandboxBlocked ? { hint: blockedHint(networkMode) } : {}),
|
|
236
|
+
};
|
|
237
|
+
return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
|
|
238
|
+
} finally {
|
|
239
|
+
/* v8 ignore next 5 */
|
|
240
|
+
try {
|
|
241
|
+
await fs.rm(tempDir, { recursive: true, force: true });
|
|
242
|
+
} catch {
|
|
243
|
+
/* already gone */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
interface CagedInput {
|
|
250
|
+
command: string;
|
|
251
|
+
executable: { path: string; real: string };
|
|
252
|
+
args: string[];
|
|
253
|
+
cwd: string;
|
|
254
|
+
timeoutMs: number;
|
|
255
|
+
allowed: Array<{ full: string }>;
|
|
256
|
+
tempDir: string;
|
|
257
|
+
input: Buffer | undefined;
|
|
258
|
+
relay?: RelaySettings;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
interface RelayAttempt {
|
|
262
|
+
outcome: ExecOutcome;
|
|
263
|
+
mode: NetworkMode;
|
|
264
|
+
reason?: string;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* One spawn attempt. The relay control server starts before the cage is built
|
|
269
|
+
* and stays open until the run ends; a recognized unsupported relay backend
|
|
270
|
+
* closes it and retries the same attempt with networking off. A control server
|
|
271
|
+
* that cannot start is treated the same way: without it every flow is refused,
|
|
272
|
+
* so the run keeps networking off instead of failing outright.
|
|
273
|
+
*/
|
|
274
|
+
async function runAttempt(
|
|
275
|
+
ctx: RunContext,
|
|
276
|
+
base: Omit<CagedInput, "relay">,
|
|
277
|
+
assertNetwork: (resource: string) => Promise<void>,
|
|
278
|
+
): Promise<RelayAttempt> {
|
|
279
|
+
if (ctx.signal.aborted) throw interruptedError();
|
|
280
|
+
const runId = randomBytes(8).readBigUInt64BE(0);
|
|
281
|
+
const control = new RelayControlServer({ runId, assertNetwork });
|
|
282
|
+
let socketPath: string;
|
|
283
|
+
try {
|
|
284
|
+
socketPath = await control.start();
|
|
285
|
+
} catch (error) {
|
|
286
|
+
// An abort during relay setup must not fall through to an offline child.
|
|
287
|
+
if (ctx.signal.aborted) throw interruptedError();
|
|
288
|
+
// Nothing is granted without the relay, so this fallback cannot mask a
|
|
289
|
+
// denial; it only reports why networking is disabled.
|
|
290
|
+
return {
|
|
291
|
+
outcome: await runCaged(ctx, base),
|
|
292
|
+
mode: "disabled",
|
|
293
|
+
reason: errorMessage(error),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
if (ctx.signal.aborted) throw interruptedError();
|
|
298
|
+
try {
|
|
299
|
+
return { outcome: await runCaged(ctx, { ...base, relay: { runId, socketPath } }), mode: "relay" };
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (!(error instanceof RelayUnsupportedError)) throw error;
|
|
302
|
+
return { outcome: await runCaged(ctx, base), mode: "disabled", reason: error.message };
|
|
303
|
+
}
|
|
304
|
+
} finally {
|
|
305
|
+
await control.close();
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function interruptedError(): FsError {
|
|
310
|
+
return new FsError("exec interrupted.", "interrupted");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome> {
|
|
314
|
+
let api: typeof import("procage");
|
|
315
|
+
try {
|
|
316
|
+
api = await loadProcage();
|
|
317
|
+
} catch (error) {
|
|
318
|
+
/* v8 ignore next */
|
|
319
|
+
throw new FsError(`exec sandbox is unavailable: ${String(error)}`, "unsupported");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const doc = api.Policy.preset("agent_workspace", 3, { workspace: ctx.sandbox.root }).toJSON() as PolicyDocument;
|
|
323
|
+
// Networking is off unless procage's relay replaces this policy value with
|
|
324
|
+
// `Network::Relay`; the plugin never grants IP networking or resolver sockets.
|
|
325
|
+
doc.net = "none";
|
|
326
|
+
addRule(doc, "exec", path.dirname(input.executable.path));
|
|
327
|
+
addRule(doc, "exec", path.dirname(input.executable.real));
|
|
328
|
+
addRule(doc, "exec", path.dirname(process.execPath));
|
|
329
|
+
addRule(doc, "exec", path.resolve(path.dirname(process.execPath), ".."));
|
|
330
|
+
addRule(doc, "exec", path.dirname(input.executable.real));
|
|
331
|
+
addRule(doc, "exec", path.resolve(path.dirname(input.executable.real), ".."));
|
|
332
|
+
await addOptionalRoots(doc, ["/home/linuxbrew", "/var/home/linuxbrew"], (root) => fs.access(root));
|
|
333
|
+
addRule(doc, "write", input.tempDir);
|
|
334
|
+
addRule(doc, "write", input.cwd);
|
|
335
|
+
for (const allowed of input.allowed) addRule(doc, "write", allowed.full);
|
|
336
|
+
|
|
337
|
+
const cageOptions: CageOptions = {
|
|
338
|
+
violations: true,
|
|
339
|
+
acceptSpawnSnapshot: true,
|
|
340
|
+
relax: ["waive:trust-handoff", "signals-same-user", "no-unix-sockets"] as Relaxation[],
|
|
341
|
+
...(input.relay === undefined
|
|
342
|
+
? {}
|
|
343
|
+
: {
|
|
344
|
+
relay_control_socket: input.relay.socketPath,
|
|
345
|
+
relay_run_id: input.relay.runId.toString(),
|
|
346
|
+
}),
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
let cage: InstanceType<typeof api.Cage>;
|
|
350
|
+
let policy: ReturnType<typeof api.Policy.fromJSON>;
|
|
351
|
+
try {
|
|
352
|
+
policy = api.Policy.fromJSON(doc);
|
|
353
|
+
cage = new api.Cage(policy, cageOptions);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (input.relay !== undefined) {
|
|
356
|
+
const reason = relayGapReason(error, api);
|
|
357
|
+
if (reason !== undefined) throw new RelayUnsupportedError(reason);
|
|
358
|
+
}
|
|
359
|
+
throw new FsError(`exec policy rejected: ${errorMessage(error)}`, "unsupported");
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// The policy's allowlist supplies HOME, LANG, LC_ALL, PATH, TERM, TMPDIR and
|
|
363
|
+
// USER. Explicit values win over that allowlist, so pass only the tool's own
|
|
364
|
+
// TMPDIR and proxy settings: forwarding process.env would defeat the
|
|
365
|
+
// preset's secret filtering. The transparent relay treats a connection to the
|
|
366
|
+
// proxy as the proxy's own destination (never its CONNECT target), so the
|
|
367
|
+
// proxy's address, or its cached DNS name, is authorized through
|
|
368
|
+
// fs_exec_network; the target URL behind the proxy is never treated as
|
|
369
|
+
// approved.
|
|
370
|
+
const env: Record<string, string> = { TMPDIR: input.tempDir };
|
|
371
|
+
for (const name of EXEC_PROXY_ENV) {
|
|
372
|
+
const value = process.env[name];
|
|
373
|
+
if (value !== undefined) env[name] = value;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Attach the listener before the spawn: an abort during the spawn await must
|
|
377
|
+
// still reach the child once it exists. The flag also captures an abort that
|
|
378
|
+
// already arrived during relay setup or cage construction, which a listener
|
|
379
|
+
// attached afterwards would never see.
|
|
380
|
+
let child!: Awaited<ReturnType<typeof cage.spawn>>;
|
|
381
|
+
let aborted = ctx.signal.aborted;
|
|
382
|
+
const onAbort = () => {
|
|
383
|
+
aborted = true;
|
|
384
|
+
child?.kill();
|
|
385
|
+
};
|
|
386
|
+
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
387
|
+
try {
|
|
388
|
+
// An abort that arrived during relay setup or cage construction must not
|
|
389
|
+
// start a child at all.
|
|
390
|
+
if (aborted) throw interruptedError();
|
|
391
|
+
try {
|
|
392
|
+
child = await cage.spawn([input.executable.path, ...input.args], {
|
|
393
|
+
cwd: input.cwd,
|
|
394
|
+
env,
|
|
395
|
+
stdin: input.input !== undefined,
|
|
396
|
+
});
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (aborted || ctx.signal.aborted) throw interruptedError();
|
|
399
|
+
throw new FsError(`exec spawn failed: ${String(error)}`, "unsupported");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// The abort listener could not kill a child that did not exist yet.
|
|
403
|
+
if (aborted) child.kill();
|
|
404
|
+
|
|
405
|
+
try {
|
|
406
|
+
const out = await child.output({ timeout: input.timeoutMs, ...(input.input === undefined ? {} : { input: input.input }) });
|
|
407
|
+
const violations = filterViolations(await child.violations());
|
|
408
|
+
return {
|
|
409
|
+
stdout: out.stdout,
|
|
410
|
+
stderr: out.stderr,
|
|
411
|
+
exitCode: out.timedOut ? 124 : aborted ? 130 : (out.exitCode ?? 1),
|
|
412
|
+
signal: out.signal,
|
|
413
|
+
timedOut: out.timedOut,
|
|
414
|
+
aborted,
|
|
415
|
+
networkMode: input.relay === undefined ? "disabled" : "relay",
|
|
416
|
+
violations,
|
|
417
|
+
};
|
|
418
|
+
} catch (error) {
|
|
419
|
+
/* v8 ignore next 15 */
|
|
420
|
+
if (aborted || ctx.signal.aborted) {
|
|
421
|
+
return {
|
|
422
|
+
stdout: Buffer.alloc(0),
|
|
423
|
+
stderr: Buffer.alloc(0),
|
|
424
|
+
exitCode: 130,
|
|
425
|
+
signal: null,
|
|
426
|
+
timedOut: false,
|
|
427
|
+
aborted: true,
|
|
428
|
+
networkMode: input.relay === undefined ? "disabled" : "relay",
|
|
429
|
+
violations: [],
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/* v8 ignore next */
|
|
433
|
+
throw new FsError(`exec failed: ${String(error)}`, "unsupported");
|
|
434
|
+
} finally {
|
|
435
|
+
child.close();
|
|
436
|
+
}
|
|
437
|
+
} finally {
|
|
438
|
+
ctx.signal.removeEventListener("abort", onAbort);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Resolve a denied path to the nearest existing ancestor, so a missing
|
|
444
|
+
* directory or a redacted temp name still yields an approvable boundary.
|
|
445
|
+
* The filesystem root is never exposed.
|
|
446
|
+
*/
|
|
447
|
+
async function existingBoundary(ctx: RunContext, candidate: string) {
|
|
448
|
+
let current = candidate;
|
|
449
|
+
for (;;) {
|
|
450
|
+
/* v8 ignore next */
|
|
451
|
+
const target = await ctx.sandbox.resolveExisting(current, { allowRoot: true }).catch(() => undefined);
|
|
452
|
+
if (target !== undefined) {
|
|
453
|
+
return target.full === path.parse(target.full).root ? undefined : target;
|
|
454
|
+
}
|
|
455
|
+
current = path.dirname(current);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function addRule(doc: PolicyDocument, access: string, target: string): void {
|
|
460
|
+
const subpath = path.resolve(target);
|
|
461
|
+
if (doc.fs.some((rule) => rule.access === access && rule.target.subpath === subpath)) return;
|
|
462
|
+
doc.fs.push({ access, target: { subpath } });
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Grant read and exec on each optional root that exists on this host. The
|
|
467
|
+
* predicate is injected so tests can simulate present and absent roots without
|
|
468
|
+
* touching the real filesystem layout.
|
|
469
|
+
*/
|
|
470
|
+
export async function addOptionalRoots(
|
|
471
|
+
doc: PolicyDocument,
|
|
472
|
+
roots: readonly string[],
|
|
473
|
+
access: (root: string) => Promise<void>,
|
|
474
|
+
): Promise<void> {
|
|
475
|
+
for (const root of roots) {
|
|
476
|
+
try {
|
|
477
|
+
await access(root);
|
|
478
|
+
addRule(doc, "read", root);
|
|
479
|
+
addRule(doc, "exec", root);
|
|
480
|
+
} catch {
|
|
481
|
+
// Optional root: the preset stays portable without it.
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export function filterViolations(violations: readonly Violation[]): Violation[] {
|
|
487
|
+
return violations.filter((violation) => {
|
|
488
|
+
if (violation.operation === "network-outbound") return true;
|
|
489
|
+
if (violation.target?.startsWith("/")) return true;
|
|
490
|
+
return /AF_INET|AF_INET6/.test(violation.target ?? "");
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export function isSandboxBlocked(outcome: ExecOutcome): boolean {
|
|
495
|
+
if (outcome.violations.length > 0) return true;
|
|
496
|
+
if (outcome.exitCode === 0) return false;
|
|
497
|
+
return /EACCES|EPERM|EROFS|Permission denied|Read-only file system/i.test(outcome.stderr.toString("utf8"));
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export function discoverExternalPaths(ctx: RunContext, outcome: ExecOutcome): string[] {
|
|
501
|
+
const found = new Set<string>();
|
|
502
|
+
for (const violation of outcome.violations) {
|
|
503
|
+
// Only a structured write denial may become a write grant. Seatbelt names
|
|
504
|
+
// that family `file-write-*`; a read, exec, network, or unknown operation
|
|
505
|
+
// must never widen the boundary, even when its target is an absolute path.
|
|
506
|
+
if (!violation.operation.startsWith("file-write-")) continue;
|
|
507
|
+
if (violation.target?.startsWith("/")) found.add(violation.target);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// Only structured violation targets are grant candidates. The child controls
|
|
511
|
+
// stdout and stderr, so a path printed there (even next to an EACCES string)
|
|
512
|
+
// must never widen the permission boundary.
|
|
513
|
+
const root = ctx.sandbox.root;
|
|
514
|
+
return [...found]
|
|
515
|
+
.map((candidate) => path.resolve(candidate))
|
|
516
|
+
.map((candidate) => candidate.replace(/\/\*+$/, ""))
|
|
517
|
+
.filter((candidate) => candidate !== root && !candidate.startsWith(`${root}${path.sep}`))
|
|
518
|
+
.filter((candidate, index, all) => all.indexOf(candidate) === index);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function resolveExecutable(command: string): Promise<{ path: string; real: string }> {
|
|
522
|
+
const directories = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
|
|
523
|
+
for (const directory of directories) {
|
|
524
|
+
const candidate = path.join(directory, command);
|
|
525
|
+
try {
|
|
526
|
+
await fs.access(candidate, fsConstants.X_OK);
|
|
527
|
+
return { path: candidate, real: await fs.realpath(candidate) };
|
|
528
|
+
} catch {
|
|
529
|
+
// keep searching PATH
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
throw new FsError(`exec command not found: "${command}"`, "not-found");
|
|
533
|
+
}
|
|
@@ -65,12 +65,12 @@ interface Checksum {
|
|
|
65
65
|
digest: string;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
export const
|
|
69
|
-
name: "
|
|
68
|
+
export const curlTool: ToolSpec<Input> = {
|
|
69
|
+
name: "curl",
|
|
70
70
|
description:
|
|
71
71
|
"Make an HTTP(S) request and either return the body or stream it to a file (`output`). " +
|
|
72
|
-
"Supports methods, headers, a text or JSON
|
|
73
|
-
"`checksum` verification. Usable as a `pipe` source.",
|
|
72
|
+
"Uses structured options, not curl CLI flags. Supports methods, headers, a text or JSON " +
|
|
73
|
+
"body, redirects, timeouts, `maxBytes`, and `checksum` verification. Usable as a `pipe` source.",
|
|
74
74
|
schema: Schema,
|
|
75
75
|
pipeable: "source",
|
|
76
76
|
mutates: true,
|
package/src/tools/pipe.ts
CHANGED
|
@@ -10,16 +10,16 @@ import { writeAll } from "../core/stream.js";
|
|
|
10
10
|
import { textResult, type ToolSpec, type ToolResult } from "../core/types.js";
|
|
11
11
|
import { base64Tool } from "./base64.js";
|
|
12
12
|
import { catTool } from "./cat.js";
|
|
13
|
+
import { commandTool } from "./command.js";
|
|
13
14
|
import { cpioTool } from "./cpio.js";
|
|
15
|
+
import { curlTool } from "./curl.js";
|
|
14
16
|
import { cutTool } from "./cut.js";
|
|
15
17
|
import { ddTool } from "./dd.js";
|
|
16
|
-
import { execTool } from "./exec.js";
|
|
17
18
|
import { foldTool } from "./fold.js";
|
|
18
19
|
import { grepTool } from "./grep.js";
|
|
19
20
|
import { gunzipTool, gzipTool } from "./gzip.js";
|
|
20
21
|
import { hashTool } from "./hash.js";
|
|
21
22
|
import { headTool } from "./head.js";
|
|
22
|
-
import { httpRequestTool } from "./http_request.js";
|
|
23
23
|
import { nlTool } from "./nl.js";
|
|
24
24
|
import { odTool } from "./od.js";
|
|
25
25
|
import { pasteTool } from "./paste.js";
|
|
@@ -60,10 +60,11 @@ type AnyTool = ToolSpec<any>;
|
|
|
60
60
|
|
|
61
61
|
const REGISTRY: ReadonlyMap<string, AnyTool> = new Map(
|
|
62
62
|
[
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
63
|
+
base64Tool, catTool, commandTool, cpioTool, curlTool, cutTool,
|
|
64
|
+
ddTool, foldTool, grepTool, gunzipTool, gzipTool, hashTool,
|
|
65
|
+
headTool, nlTool, odTool, pasteTool, revTool, sedTool,
|
|
66
|
+
shufTool, sortTool, stringsTool, tacTool, tailTool, tarTool,
|
|
67
|
+
teeTool, trTool, uniqTool, wcTool, zipTool,
|
|
67
68
|
].map((tool) => [tool.name, tool]),
|
|
68
69
|
);
|
|
69
70
|
|
|
@@ -91,7 +92,6 @@ export const pipeTool: ToolSpec<Input> = {
|
|
|
91
92
|
}
|
|
92
93
|
const parsed = parseSchema(tool.schema, stage.args ?? {}, `${stage.tool} arguments`);
|
|
93
94
|
const gate = ctx.permissionFor(`fs_${tool.name}`);
|
|
94
|
-
await gate.assertTrusted([]);
|
|
95
95
|
const result = await tool.run(
|
|
96
96
|
{ ...ctx, permission: gate },
|
|
97
97
|
parsed,
|