opencode-fs-plugin 3.4.0 → 3.6.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 +268 -132
- package/SPEC.md +171 -56
- package/package.json +2 -2
- package/skills/filesystem/SKILL.md +172 -67
- package/src/core/format.ts +3 -9
- package/src/core/fsutil.ts +84 -23
- package/src/core/jobs.ts +210 -34
- package/src/core/permissions.ts +32 -14
- package/src/core/relay-control.ts +343 -0
- package/src/core/relay-protocol.ts +274 -0
- package/src/core/safe-output.ts +290 -0
- package/src/core/sandbox.ts +43 -0
- package/src/core/types.ts +0 -5
- package/src/index.ts +78 -72
- package/src/tools/ar.ts +62 -29
- package/src/tools/cat.ts +31 -46
- package/src/tools/chmod.ts +30 -19
- package/src/tools/chown.ts +24 -16
- package/src/tools/command.ts +536 -0
- package/src/tools/cp.ts +84 -20
- package/src/tools/cpio.ts +204 -65
- package/src/tools/{http_request.ts → curl.ts} +127 -10
- package/src/tools/dd.ts +15 -9
- package/src/tools/diff.ts +46 -15
- package/src/tools/grep.ts +5 -2
- package/src/tools/gzip.ts +13 -15
- package/src/tools/mktemp.ts +41 -26
- package/src/tools/mv.ts +69 -28
- package/src/tools/pipe.ts +24 -16
- package/src/tools/split.ts +26 -12
- package/src/tools/tar.ts +132 -57
- package/src/tools/tee.ts +7 -4
- package/src/tools/touch.ts +12 -4
- package/src/tools/truncate.ts +17 -7
- package/src/tools/zip.ts +119 -54
- package/src/core/spill.ts +0 -145
- package/src/tools/exec.ts +0 -483
package/src/tools/exec.ts
DELETED
|
@@ -1,483 +0,0 @@
|
|
|
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 * as path from "node:path";
|
|
9
|
-
import { Type, type Static } from "@sinclair/typebox";
|
|
10
|
-
import type { Relaxation, Violation } from "procage";
|
|
11
|
-
import { FsError } from "../core/errors.js";
|
|
12
|
-
import { collect } from "../core/stream.js";
|
|
13
|
-
import { textResult, type RunContext, type ToolSpec } from "../core/types.js";
|
|
14
|
-
|
|
15
|
-
export const DEFAULT_EXEC_ALLOWLIST = ["npm", "npx", "uv", "uvx", "pip", "pip3"] as const;
|
|
16
|
-
|
|
17
|
-
const EXEC_NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
18
|
-
|
|
19
|
-
export function isSafeExecName(value: string): boolean {
|
|
20
|
-
return EXEC_NAME.test(value);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function normalizeExecAllowlist(value: unknown): readonly string[] {
|
|
24
|
-
if (value === undefined) return DEFAULT_EXEC_ALLOWLIST;
|
|
25
|
-
if (!Array.isArray(value)) throw new FsError("execAllowlist must be an array of executable names.", "invalid");
|
|
26
|
-
const names: string[] = [];
|
|
27
|
-
for (const entry of value) {
|
|
28
|
-
if (typeof entry !== "string") throw new FsError("execAllowlist entries must be strings.", "invalid");
|
|
29
|
-
const name = entry.trim();
|
|
30
|
-
if (!isSafeExecName(name)) throw new FsError(`Invalid exec allowlist entry: ${entry}`, "invalid");
|
|
31
|
-
names.push(name);
|
|
32
|
-
}
|
|
33
|
-
return [...new Set(names)];
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const Schema = Type.Object(
|
|
37
|
-
{
|
|
38
|
-
command: Type.String({ minLength: 1, description: "Allowlisted executable name, without a path or shell syntax." }),
|
|
39
|
-
args: Type.Optional(Type.Array(Type.String(), { description: "Arguments passed verbatim to the executable." })),
|
|
40
|
-
cwd: Type.Optional(Type.String({ minLength: 1, description: "Working directory inside the project. Default: project root." })),
|
|
41
|
-
stdin: Type.Optional(Type.String({ description: "Text for stdin when the tool is not used in a pipe." })),
|
|
42
|
-
timeoutMs: Type.Optional(
|
|
43
|
-
Type.Integer({ minimum: 100, maximum: 600_000, description: "Timeout in milliseconds. Default: 120000." }),
|
|
44
|
-
),
|
|
45
|
-
},
|
|
46
|
-
{ additionalProperties: false },
|
|
47
|
-
);
|
|
48
|
-
|
|
49
|
-
type Input = Static<typeof Schema>;
|
|
50
|
-
|
|
51
|
-
export interface PolicyDocument {
|
|
52
|
-
fs: Array<{ access: string; target: { subpath: string } }>;
|
|
53
|
-
net: string;
|
|
54
|
-
ipc: { unix_sockets: string[] };
|
|
55
|
-
[key: string]: unknown;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Sockets used by the name-service resolvers on common Linux systems:
|
|
60
|
-
* systemd-resolved, nscd, and SSSD. Plain glibc/musl DNS over UDP needs none.
|
|
61
|
-
* Landlock ignores paths that do not exist on the host.
|
|
62
|
-
*/
|
|
63
|
-
export const RESOLVER_SOCKETS = ["/run/systemd/resolve", "/run/nscd", "/var/lib/sss/pipes"] as const;
|
|
64
|
-
|
|
65
|
-
/** The proxy allowlist must not be empty; this name never resolves. */
|
|
66
|
-
export const PROXY_SENTINEL = "procage.invalid";
|
|
67
|
-
|
|
68
|
-
export type ExecNetworkMode = "proxy" | "ip";
|
|
69
|
-
|
|
70
|
-
export function normalizeExecNetworkMode(value: unknown): ExecNetworkMode {
|
|
71
|
-
if (value === undefined) return "proxy";
|
|
72
|
-
if (value === "proxy" || value === "ip") return value;
|
|
73
|
-
throw new FsError('execNetworkMode must be "proxy" or "ip".', "invalid");
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** `ip` adds all-IP networking; both modes get the local resolver sockets. */
|
|
77
|
-
export function applyNetworkPolicy(doc: PolicyDocument, mode: ExecNetworkMode): void {
|
|
78
|
-
doc.ipc.unix_sockets = [...RESOLVER_SOCKETS];
|
|
79
|
-
if (mode === "ip") doc.net = "ip";
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** A host the run's proxy refused. */
|
|
83
|
-
export interface ProxyHost {
|
|
84
|
-
/** Host without a port, for the permission resource. */
|
|
85
|
-
host: string;
|
|
86
|
-
/** `host:port`, for the allowlist entry. */
|
|
87
|
-
entry: string;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** The refused host in a proxy violation, if this violation is one. */
|
|
91
|
-
export function proxyHostOf(violation: Violation): ProxyHost | undefined {
|
|
92
|
-
if (violation.operation !== "network-outbound") return undefined;
|
|
93
|
-
const match = /^(\[[^\]]+\]|[^\s:]+)(?::(\d+))? \(not on the allowlist\)$/.exec(violation.target ?? "");
|
|
94
|
-
if (match === null) return undefined;
|
|
95
|
-
const host = match[1]!;
|
|
96
|
-
return { host, entry: match[2] === undefined ? host : `${host}:${match[2]}` };
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Ask `fs_exec_network` for every host the run's proxy refused, and add the
|
|
101
|
-
* approved ones to `hosts`. Returns whether the list grew.
|
|
102
|
-
*/
|
|
103
|
-
export async function approveProxyHosts(
|
|
104
|
-
ctx: Pick<RunContext, "permissionFor">,
|
|
105
|
-
outcome: ExecOutcome,
|
|
106
|
-
hosts: string[],
|
|
107
|
-
): Promise<boolean> {
|
|
108
|
-
if (outcome.networkMode !== "proxy") return false;
|
|
109
|
-
let added = false;
|
|
110
|
-
for (const violation of outcome.violations) {
|
|
111
|
-
const host = proxyHostOf(violation);
|
|
112
|
-
if (host === undefined || hosts.includes(host.entry)) continue;
|
|
113
|
-
await ctx.permissionFor("fs_exec_network").assertTrusted([host.host]);
|
|
114
|
-
hosts.push(host.entry);
|
|
115
|
-
added = true;
|
|
116
|
-
}
|
|
117
|
-
return added;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** Whether the host cannot keep a run to a proxy-only route (Linux T2). */
|
|
121
|
-
export function isProxyGap(error: unknown, api: typeof import("procage")): boolean {
|
|
122
|
-
return error instanceof api.CapabilityGapError && error.gaps.some((gap) => gap.construct === "net-proxy");
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/** Why a blocked run failed, and what to do about it. */
|
|
126
|
-
export function blockedHint(mode: ExecNetworkMode): string {
|
|
127
|
-
return mode === "proxy"
|
|
128
|
-
? 'The run\'s network is proxy-only and a program tried to bypass it. Use a proxy-aware client, or set execNetworkMode to "ip".'
|
|
129
|
-
: "The sandbox denied an external path or network access. Approve the path or network in the permission prompt and retry.";
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export interface ExecOutcome {
|
|
133
|
-
stdout: Buffer;
|
|
134
|
-
stderr: Buffer;
|
|
135
|
-
exitCode: number;
|
|
136
|
-
signal: string | null;
|
|
137
|
-
timedOut: boolean;
|
|
138
|
-
aborted: boolean;
|
|
139
|
-
/** The mode the sandbox actually ran: proxy may fall back to ip. */
|
|
140
|
-
networkMode: ExecNetworkMode;
|
|
141
|
-
violations: Violation[];
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
let procage: Promise<typeof import("procage")> | undefined;
|
|
145
|
-
|
|
146
|
-
function loadProcage(): Promise<typeof import("procage")> {
|
|
147
|
-
procage ??= import("procage");
|
|
148
|
-
return procage;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export const execTool: ToolSpec<Input> = {
|
|
152
|
-
name: "exec",
|
|
153
|
-
description:
|
|
154
|
-
"Run an allowlisted executable in a procage sandbox without a shell. Direct calls return JSON; " +
|
|
155
|
-
"pipe stages pass raw stdout. Default allowlist: npm, npx, uv, uvx, pip, pip3. Network is forced " +
|
|
156
|
-
"through the run's allowlist proxy by default; a refused host asks fs_exec_network.",
|
|
157
|
-
schema: Schema,
|
|
158
|
-
pipeable: "filter",
|
|
159
|
-
mutates: true,
|
|
160
|
-
async run(ctx, input, io) {
|
|
161
|
-
const command = input.command.trim();
|
|
162
|
-
if (!isSafeExecName(command)) {
|
|
163
|
-
throw new FsError(`exec command must be a bare executable name: "${input.command}"`, "invalid");
|
|
164
|
-
}
|
|
165
|
-
if (!ctx.execAllowlist.includes(command)) {
|
|
166
|
-
throw new FsError(`exec command is not allowlisted: "${command}"`, "unsupported");
|
|
167
|
-
}
|
|
168
|
-
const args = input.args ?? [];
|
|
169
|
-
if (args.some((arg) => arg.includes("\0"))) {
|
|
170
|
-
throw new FsError("exec arguments must not contain NUL bytes.", "invalid");
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const requested = input.cwd ?? ".";
|
|
174
|
-
const cwdTarget = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
|
|
175
|
-
const cwdStats = await ctx.sandbox.stat(cwdTarget.full, requested);
|
|
176
|
-
if (!cwdStats.isDirectory()) throw new FsError(`exec cwd is not a directory: "${requested}"`, "not-directory");
|
|
177
|
-
await ctx.permission.assert([{ target: cwdTarget, boundary: cwdTarget.full }]);
|
|
178
|
-
if (ctx.signal.aborted) throw new FsError("exec interrupted.", "interrupted");
|
|
179
|
-
|
|
180
|
-
const executable = await resolveExecutable(command);
|
|
181
|
-
const tempDir = await fs.mkdtemp(path.join(ctx.tmpdir, "fs-exec-"));
|
|
182
|
-
try {
|
|
183
|
-
const inputData = io.stdin === undefined
|
|
184
|
-
? input.stdin === undefined ? undefined : Buffer.from(input.stdin)
|
|
185
|
-
: await collect(io.stdin);
|
|
186
|
-
let networkMode = ctx.execNetworkMode;
|
|
187
|
-
const proxyHosts: string[] = [];
|
|
188
|
-
let ipNetwork = false;
|
|
189
|
-
const approved: Array<{ full: string }> = [];
|
|
190
|
-
let outcome: ExecOutcome | undefined;
|
|
191
|
-
|
|
192
|
-
for (let attempt = 0; attempt < 12; attempt++) {
|
|
193
|
-
outcome = await runCaged(ctx, {
|
|
194
|
-
command,
|
|
195
|
-
executable,
|
|
196
|
-
args,
|
|
197
|
-
cwd: cwdTarget.full,
|
|
198
|
-
timeoutMs: input.timeoutMs ?? 120_000,
|
|
199
|
-
networkMode,
|
|
200
|
-
proxyHosts,
|
|
201
|
-
ipNetwork,
|
|
202
|
-
allowed: approved,
|
|
203
|
-
tempDir,
|
|
204
|
-
input: inputData,
|
|
205
|
-
});
|
|
206
|
-
networkMode = outcome.networkMode;
|
|
207
|
-
|
|
208
|
-
if (networkMode === "ip" && !ipNetwork && detectsNetworkDenial(outcome)) {
|
|
209
|
-
await ctx.permissionFor("fs_exec_network").assert([]);
|
|
210
|
-
ipNetwork = true;
|
|
211
|
-
continue;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
let added = await approveProxyHosts(ctx, outcome, proxyHosts);
|
|
215
|
-
const deniedPaths = discoverExternalPaths(ctx, outcome)
|
|
216
|
-
.filter((candidate) => !approved.some((entry) => entry.full === candidate));
|
|
217
|
-
for (const candidate of deniedPaths) {
|
|
218
|
-
const target = await existingBoundary(ctx, candidate);
|
|
219
|
-
if (target === undefined) continue;
|
|
220
|
-
/* v8 ignore next */
|
|
221
|
-
const stats = await ctx.sandbox.stat(target.full, candidate).catch(() => undefined);
|
|
222
|
-
/* v8 ignore next */
|
|
223
|
-
if (stats === undefined) continue;
|
|
224
|
-
const boundary = stats.isDirectory() ? target.full : path.dirname(target.full);
|
|
225
|
-
const dirTarget = await ctx.sandbox.resolveExisting(boundary, { allowRoot: true });
|
|
226
|
-
if (approved.some((entry) => entry.full === dirTarget.full)) continue;
|
|
227
|
-
await ctx.permission.assert([{ target: dirTarget, boundary: dirTarget.full }]);
|
|
228
|
-
approved.push({ full: dirTarget.full });
|
|
229
|
-
added = true;
|
|
230
|
-
}
|
|
231
|
-
if (!added) break;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/* v8 ignore next */
|
|
235
|
-
if (outcome === undefined) throw new FsError("exec produced no result.", "io");
|
|
236
|
-
const metadata = {
|
|
237
|
-
command,
|
|
238
|
-
args,
|
|
239
|
-
exitCode: outcome.exitCode,
|
|
240
|
-
signal: outcome.signal,
|
|
241
|
-
timedOut: outcome.timedOut,
|
|
242
|
-
aborted: outcome.aborted,
|
|
243
|
-
sandboxBlocked: isSandboxBlocked(outcome),
|
|
244
|
-
violations: outcome.violations.length,
|
|
245
|
-
network: networkMode === "proxy" || ipNetwork,
|
|
246
|
-
networkMode,
|
|
247
|
-
networkHosts: proxyHosts,
|
|
248
|
-
externalPaths: approved.map((entry) => entry.full),
|
|
249
|
-
};
|
|
250
|
-
if (io.piped === true) {
|
|
251
|
-
return {
|
|
252
|
-
stdout: outcome.stdout,
|
|
253
|
-
stderr: outcome.stderr.toString("utf8"),
|
|
254
|
-
exitCode: outcome.exitCode === 0 ? 0 : 1,
|
|
255
|
-
metadata,
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
const sandboxBlocked = isSandboxBlocked(outcome);
|
|
259
|
-
const body = {
|
|
260
|
-
...metadata,
|
|
261
|
-
stdout: outcome.stdout.toString("utf8"),
|
|
262
|
-
stderr: outcome.stderr.toString("utf8"),
|
|
263
|
-
violations: outcome.violations,
|
|
264
|
-
...(sandboxBlocked ? { hint: blockedHint(networkMode) } : {}),
|
|
265
|
-
};
|
|
266
|
-
return textResult(JSON.stringify(body, null, 2), metadata, outcome.exitCode === 0 ? 0 : 1);
|
|
267
|
-
} finally {
|
|
268
|
-
/* v8 ignore next 5 */
|
|
269
|
-
try {
|
|
270
|
-
await fs.rm(tempDir, { recursive: true, force: true });
|
|
271
|
-
} catch {
|
|
272
|
-
/* already gone */
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
},
|
|
276
|
-
};
|
|
277
|
-
|
|
278
|
-
interface CagedInput {
|
|
279
|
-
command: string;
|
|
280
|
-
executable: { path: string; real: string };
|
|
281
|
-
args: string[];
|
|
282
|
-
cwd: string;
|
|
283
|
-
timeoutMs: number;
|
|
284
|
-
networkMode: ExecNetworkMode;
|
|
285
|
-
proxyHosts: readonly string[];
|
|
286
|
-
ipNetwork: boolean;
|
|
287
|
-
allowed: Array<{ full: string }>;
|
|
288
|
-
tempDir: string;
|
|
289
|
-
input: Buffer | undefined;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
async function runCaged(ctx: RunContext, input: CagedInput): Promise<ExecOutcome> {
|
|
293
|
-
let api: typeof import("procage");
|
|
294
|
-
try {
|
|
295
|
-
api = await loadProcage();
|
|
296
|
-
} catch (error) {
|
|
297
|
-
/* v8 ignore next */
|
|
298
|
-
throw new FsError(`exec sandbox is unavailable: ${String(error)}`, "unsupported");
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
const doc = api.Policy.preset("agent_workspace", 3, { workspace: ctx.sandbox.root }).toJSON() as PolicyDocument;
|
|
302
|
-
applyNetworkPolicy(doc, input.networkMode === "ip" && !input.ipNetwork ? "proxy" : input.networkMode);
|
|
303
|
-
addRule(doc, "exec", path.dirname(input.executable.path));
|
|
304
|
-
addRule(doc, "exec", path.dirname(input.executable.real));
|
|
305
|
-
addRule(doc, "exec", path.dirname(process.execPath));
|
|
306
|
-
addRule(doc, "exec", path.resolve(path.dirname(process.execPath), ".."));
|
|
307
|
-
addRule(doc, "exec", path.dirname(input.executable.real));
|
|
308
|
-
addRule(doc, "exec", path.resolve(path.dirname(input.executable.real), ".."));
|
|
309
|
-
for (const root of ["/home/linuxbrew", "/var/home/linuxbrew"]) {
|
|
310
|
-
try {
|
|
311
|
-
await fs.access(root);
|
|
312
|
-
addRule(doc, "read", root);
|
|
313
|
-
addRule(doc, "exec", root);
|
|
314
|
-
} catch {
|
|
315
|
-
// Homebrew is optional.
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
addRule(doc, "write", input.tempDir);
|
|
319
|
-
addRule(doc, "write", input.cwd);
|
|
320
|
-
for (const allowed of input.allowed) addRule(doc, "write", allowed.full);
|
|
321
|
-
|
|
322
|
-
const cageOptions = {
|
|
323
|
-
violations: true,
|
|
324
|
-
acceptSpawnSnapshot: true,
|
|
325
|
-
relax: ["waive:trust-handoff", "signals-same-user", "no-unix-sockets"] as Relaxation[],
|
|
326
|
-
...(input.networkMode === "proxy"
|
|
327
|
-
? { proxy: { allowlist: [...input.proxyHosts, PROXY_SENTINEL] } }
|
|
328
|
-
: {}),
|
|
329
|
-
};
|
|
330
|
-
|
|
331
|
-
let cage: InstanceType<typeof api.Cage>;
|
|
332
|
-
let policy: ReturnType<typeof api.Policy.fromJSON>;
|
|
333
|
-
try {
|
|
334
|
-
policy = api.Policy.fromJSON(doc);
|
|
335
|
-
cage = new api.Cage(policy, cageOptions);
|
|
336
|
-
} catch (error) {
|
|
337
|
-
/* v8 ignore next 3 */
|
|
338
|
-
if (input.networkMode === "proxy" && isProxyGap(error, api)) {
|
|
339
|
-
return runCaged(ctx, { ...input, networkMode: "ip" });
|
|
340
|
-
}
|
|
341
|
-
/* v8 ignore next */
|
|
342
|
-
throw new FsError(`exec policy rejected: ${String(error)}`, "unsupported");
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
const env = Object.fromEntries(
|
|
346
|
-
Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined),
|
|
347
|
-
);
|
|
348
|
-
env.TMPDIR = input.tempDir;
|
|
349
|
-
|
|
350
|
-
let child;
|
|
351
|
-
try {
|
|
352
|
-
child = await cage.spawn([input.executable.path, ...input.args], {
|
|
353
|
-
cwd: input.cwd,
|
|
354
|
-
env,
|
|
355
|
-
stdin: input.input !== undefined,
|
|
356
|
-
});
|
|
357
|
-
} catch (error) {
|
|
358
|
-
/* v8 ignore next */
|
|
359
|
-
throw new FsError(`exec spawn failed: ${String(error)}`, "unsupported");
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
let aborted = false;
|
|
363
|
-
const onAbort = () => {
|
|
364
|
-
aborted = true;
|
|
365
|
-
child?.kill();
|
|
366
|
-
};
|
|
367
|
-
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
368
|
-
try {
|
|
369
|
-
const out = await child.output({ timeout: input.timeoutMs, ...(input.input === undefined ? {} : { input: input.input }) });
|
|
370
|
-
const violations = filterViolations(await child.violations());
|
|
371
|
-
return {
|
|
372
|
-
stdout: out.stdout,
|
|
373
|
-
stderr: out.stderr,
|
|
374
|
-
exitCode: out.timedOut ? 124 : aborted ? 130 : (out.exitCode ?? 1),
|
|
375
|
-
signal: out.signal,
|
|
376
|
-
timedOut: out.timedOut,
|
|
377
|
-
aborted,
|
|
378
|
-
networkMode: input.networkMode,
|
|
379
|
-
violations,
|
|
380
|
-
};
|
|
381
|
-
} catch (error) {
|
|
382
|
-
/* v8 ignore next 15 */
|
|
383
|
-
if (aborted || ctx.signal.aborted) {
|
|
384
|
-
return {
|
|
385
|
-
stdout: Buffer.alloc(0),
|
|
386
|
-
stderr: Buffer.alloc(0),
|
|
387
|
-
exitCode: 130,
|
|
388
|
-
signal: null,
|
|
389
|
-
timedOut: false,
|
|
390
|
-
aborted: true,
|
|
391
|
-
networkMode: input.networkMode,
|
|
392
|
-
violations: [],
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
/* v8 ignore next */
|
|
396
|
-
throw new FsError(`exec failed: ${String(error)}`, "unsupported");
|
|
397
|
-
} finally {
|
|
398
|
-
ctx.signal.removeEventListener("abort", onAbort);
|
|
399
|
-
child.close();
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
/**
|
|
404
|
-
* Resolve a denied path to the nearest existing ancestor, so a missing
|
|
405
|
-
* directory or a redacted temp name still yields an approvable boundary.
|
|
406
|
-
* The filesystem root is never exposed.
|
|
407
|
-
*/
|
|
408
|
-
async function existingBoundary(ctx: RunContext, candidate: string) {
|
|
409
|
-
let current = candidate;
|
|
410
|
-
for (;;) {
|
|
411
|
-
/* v8 ignore next */
|
|
412
|
-
const target = await ctx.sandbox.resolveExisting(current, { allowRoot: true }).catch(() => undefined);
|
|
413
|
-
if (target !== undefined) {
|
|
414
|
-
return target.full === path.parse(target.full).root ? undefined : target;
|
|
415
|
-
}
|
|
416
|
-
current = path.dirname(current);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
function addRule(doc: PolicyDocument, access: string, target: string): void {
|
|
421
|
-
const subpath = path.resolve(target);
|
|
422
|
-
if (doc.fs.some((rule) => rule.access === access && rule.target.subpath === subpath)) return;
|
|
423
|
-
doc.fs.push({ access, target: { subpath } });
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
export function filterViolations(violations: readonly Violation[]): Violation[] {
|
|
427
|
-
return violations.filter((violation) => {
|
|
428
|
-
if (proxyHostOf(violation) !== undefined) return true;
|
|
429
|
-
if (violation.target?.startsWith("/")) return true;
|
|
430
|
-
return /AF_INET|AF_INET6/.test(violation.target ?? "");
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
export function isSandboxBlocked(outcome: ExecOutcome): boolean {
|
|
435
|
-
if (outcome.violations.length > 0) return true;
|
|
436
|
-
if (outcome.exitCode === 0) return false;
|
|
437
|
-
return /EACCES|EPERM|EROFS|Permission denied|Read-only file system/i.test(outcome.stderr.toString("utf8"));
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
export function detectsNetworkDenial(outcome: ExecOutcome): boolean {
|
|
441
|
-
if (outcome.violations.some((violation) => /AF_INET|AF_INET6/.test(violation.target ?? ""))) return true;
|
|
442
|
-
return /EAI_AGAIN|getaddrinfo|ENETUNREACH|ECONNREFUSED/i.test(outcome.stderr.toString("utf8"));
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
export function discoverExternalPaths(ctx: RunContext, outcome: ExecOutcome): string[] {
|
|
446
|
-
const found = new Set<string>();
|
|
447
|
-
for (const violation of outcome.violations) {
|
|
448
|
-
if (violation.target?.startsWith("/")) found.add(violation.target);
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const stderr = outcome.stderr.toString("utf8");
|
|
452
|
-
if (/EACCES|EPERM|EROFS|Permission denied|Read-only file system|error writing|not written|cannot open|failed to open/i.test(stderr)) {
|
|
453
|
-
for (const line of stderr.split("\n")) {
|
|
454
|
-
for (const match of line.matchAll(/(?:^|[\s'"`(])(\/[^\s'"`),]+)/g)) {
|
|
455
|
-
found.add(match[1]!);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
for (const match of stderr.matchAll(/path:\s*['"]([^'"]+)['"]/g)) {
|
|
460
|
-
found.add(match[1]!);
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
const root = ctx.sandbox.root;
|
|
464
|
-
return [...found]
|
|
465
|
-
.map((candidate) => path.resolve(candidate))
|
|
466
|
-
.map((candidate) => candidate.replace(/\/\*+$/, ""))
|
|
467
|
-
.filter((candidate) => candidate !== root && !candidate.startsWith(`${root}${path.sep}`))
|
|
468
|
-
.filter((candidate, index, all) => all.indexOf(candidate) === index);
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
async function resolveExecutable(command: string): Promise<{ path: string; real: string }> {
|
|
472
|
-
const directories = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
|
|
473
|
-
for (const directory of directories) {
|
|
474
|
-
const candidate = path.join(directory, command);
|
|
475
|
-
try {
|
|
476
|
-
await fs.access(candidate, fsConstants.X_OK);
|
|
477
|
-
return { path: candidate, real: await fs.realpath(candidate) };
|
|
478
|
-
} catch {
|
|
479
|
-
// keep searching PATH
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
throw new FsError(`exec command not found: "${command}"`, "not-found");
|
|
483
|
-
}
|