@capybara-hq/device 0.1.0-rc.3 → 0.1.0-rc.5
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 +201 -11
- package/dist/args.d.ts +4 -2
- package/dist/args.js +21 -5
- package/dist/cli.d.ts +12 -2
- package/dist/cli.js +60 -8
- package/dist/client.d.ts +13 -0
- package/dist/client.js +72 -13
- package/dist/command-log.d.ts +10 -0
- package/dist/commands/policy.d.ts +66 -3
- package/dist/commands/policy.js +347 -31
- package/dist/commands/start.d.ts +9 -3
- package/dist/commands/start.js +18 -3
- package/dist/exec/docker.d.ts +41 -5
- package/dist/exec/docker.js +73 -19
- package/dist/exec/groups.d.ts +42 -0
- package/dist/exec/groups.js +100 -0
- package/dist/exec/host.d.ts +53 -0
- package/dist/exec/host.js +183 -0
- package/dist/exec/os.d.ts +73 -5
- package/dist/exec/os.js +190 -15
- package/dist/exec/shared.d.ts +44 -0
- package/dist/exec/shared.js +210 -1
- package/dist/exec/switch.d.ts +108 -0
- package/dist/exec/switch.js +214 -0
- package/dist/exec/types.d.ts +37 -3
- package/dist/network.d.ts +45 -0
- package/dist/network.js +161 -0
- package/dist/policy-store.d.ts +38 -0
- package/dist/policy-store.js +92 -0
- package/dist/policy.d.ts +102 -11
- package/dist/policy.js +155 -20
- package/dist/proxy-guard.d.ts +58 -0
- package/dist/proxy-guard.js +137 -0
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +65 -7
- package/dist/server-ops.js +289 -29
- package/dist/state.d.ts +44 -1
- package/dist/state.js +177 -9
- package/package.json +2 -2
package/dist/exec/os.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
|
|
2
|
-
import type { DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { type SandboxAskCallback, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
|
|
2
|
+
import type { DeviceExecArgs, ExecResult, SandboxRoots, SandboxTier } from "@capybara-hq/plugin-sdk";
|
|
3
|
+
import { type TierFacts } from "../policy.js";
|
|
4
|
+
import { type ProxyGuardResult } from "../proxy-guard.js";
|
|
3
5
|
import type { Policy } from "../state.js";
|
|
4
6
|
import { type Executor } from "./types.js";
|
|
5
7
|
export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
|
|
@@ -13,11 +15,16 @@ export declare function sandboxAvailability(): {
|
|
|
13
15
|
export interface OsExecutorOptions {
|
|
14
16
|
/** The device directory (from login). */
|
|
15
17
|
dir: string;
|
|
16
|
-
policy
|
|
18
|
+
/** The local policy now (read at each command, so a change applies without a restart). */
|
|
19
|
+
policy: () => Policy;
|
|
17
20
|
/** The home whose secret paths are denied (default: the user's home). */
|
|
18
21
|
home?: string;
|
|
19
22
|
/** More paths commands may not read (this program's state directory). */
|
|
20
23
|
denyRead?: string[];
|
|
24
|
+
/** The localhost proxy guard (default: {@link detectLocalProxy}); injectable for tests. */
|
|
25
|
+
detectProxy?: () => Promise<ProxyGuardResult>;
|
|
26
|
+
/** Where the macOS short socket directory is made (default `/private/tmp`). */
|
|
27
|
+
socketBase?: string;
|
|
21
28
|
}
|
|
22
29
|
/**
|
|
23
30
|
* Runs every command inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux bubblewrap):
|
|
@@ -37,10 +44,71 @@ export declare class OsExecutor implements Executor {
|
|
|
37
44
|
private pruneTimer;
|
|
38
45
|
private readonly guard;
|
|
39
46
|
private readonly files;
|
|
47
|
+
/**
|
|
48
|
+
* The limits of the latest command. The ask callback has no command id; a device belongs to one
|
|
49
|
+
* org, so these stand for the org's egress when it explains a refusal.
|
|
50
|
+
*/
|
|
51
|
+
private lastLimits;
|
|
52
|
+
/** macOS: the short socket directory (TMPDIR in `dev` / `open`); undefined elsewhere. */
|
|
53
|
+
private socketDir;
|
|
54
|
+
/** The device's package caches (`<dir>/cache`). */
|
|
55
|
+
private readonly cacheDir;
|
|
56
|
+
/** The latest proxy guard result, and the policy object it was taken for. */
|
|
57
|
+
private proxy;
|
|
58
|
+
private guardedPolicy;
|
|
59
|
+
private guardedAt;
|
|
60
|
+
/** The configuration the sandbox runs with now, as JSON (see {@link applyConfig}). */
|
|
61
|
+
private installed;
|
|
62
|
+
/**
|
|
63
|
+
* Commands spawned while nothing narrowed them (policy `open`, their limits `open`) and still
|
|
64
|
+
* running. The ask callback allows any public name only while one runs.
|
|
65
|
+
*/
|
|
66
|
+
private readonly openCommands;
|
|
40
67
|
constructor(opts: OsExecutorOptions);
|
|
41
|
-
/**
|
|
42
|
-
|
|
68
|
+
/**
|
|
69
|
+
* The tier of work that has no limits of its own (the file helper): the device's choice cut to
|
|
70
|
+
* the latest exec's ceiling, `strict` before any exec (no ceiling known yet).
|
|
71
|
+
*/
|
|
72
|
+
tier(policy?: Policy): SandboxTier;
|
|
73
|
+
/** What the tier gives on this machine now (for the policy summary). */
|
|
74
|
+
tierFacts(policy?: Policy): TierFacts;
|
|
75
|
+
/** The latest proxy guard result. */
|
|
76
|
+
proxyGuard(): ProxyGuardResult;
|
|
77
|
+
/** The sandbox configuration for the policy at `tier` (no domains: those are per command). */
|
|
78
|
+
config(policy?: Policy, tier?: SandboxTier): SandboxRuntimeConfig;
|
|
79
|
+
/**
|
|
80
|
+
* Installs {@link config} when the policy or the tier changed it, so the change applies at the
|
|
81
|
+
* next command without a restart. The runtime reads its global configuration at each wrap.
|
|
82
|
+
*/
|
|
83
|
+
private applyConfig;
|
|
84
|
+
/** Records the configuration the sandbox was initialized with. */
|
|
85
|
+
markInstalled(config: SandboxRuntimeConfig): void;
|
|
86
|
+
/**
|
|
87
|
+
* macOS: makes the short socket directory (0700) at creation, and again before a `dev` / `open`
|
|
88
|
+
* command when it is gone (macOS prunes /tmp). A path taken by something else leaves the
|
|
89
|
+
* device without one: commands then use the tmp root.
|
|
90
|
+
*/
|
|
91
|
+
prepareSocketDir(): void;
|
|
92
|
+
/**
|
|
93
|
+
* Runs the localhost proxy guard at creation, when the policy was reloaded since the last run
|
|
94
|
+
* (the store returns a new object for each new version of policy.json), and when the last result
|
|
95
|
+
* is older than {@link PROXY_GUARD_TTL_MS} (a proxy started after this program). A guard that
|
|
96
|
+
* fails counts as a proxy found (fail safe; `localhost: allow` still overrides).
|
|
97
|
+
*/
|
|
98
|
+
refreshProxyGuard(policy: Policy): Promise<void>;
|
|
43
99
|
ensureRoot(): Promise<"ok" | "gone">;
|
|
100
|
+
/**
|
|
101
|
+
* The sandbox's ask callback, reached only for a host no list allows. sandbox-runtime refuses `*`
|
|
102
|
+
* in a per-command list, so a command that may reach any host (device policy `open`, its limits
|
|
103
|
+
* `open`) is allowed here: a public name is allowed while such a command runs and the policy
|
|
104
|
+
* and latest limits still say so (narrowing takes effect at once). The callback has no command
|
|
105
|
+
* id, so a concurrent command of the same device may ride along meanwhile; the file helper never
|
|
106
|
+
* opens it. Otherwise it refuses, with a reason clients that print the proxy's status phrase
|
|
107
|
+
* show (spec §9.1).
|
|
108
|
+
*/
|
|
109
|
+
readonly askCallback: SandboxAskCallback;
|
|
110
|
+
/** The classified network refusals of one command (read before it unregisters). */
|
|
111
|
+
private blockedFor;
|
|
44
112
|
/** The marker value of a tag's processes. */
|
|
45
113
|
markerOf(tag: string): string;
|
|
46
114
|
/**
|
package/dist/exec/os.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
import { existsSync, realpathSync } from "node:fs";
|
|
4
|
-
import { constants as osConstants } from "node:os";
|
|
4
|
+
import { homedir, constants as osConstants } from "node:os";
|
|
5
5
|
import { resolve } from "node:path";
|
|
6
|
-
import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
|
|
7
|
-
import {
|
|
6
|
+
import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
|
|
7
|
+
import { blockedHosts, denyReason, isPublicName, networkTrailer, } from "../network.js";
|
|
8
|
+
import { ANY_HOST, deviceTier, effectiveEgress, grantedHosts, srtConfig, tierFacts, } from "../policy.js";
|
|
9
|
+
import { detectLocalProxy, PROXY_GUARD_TTL_MS } from "../proxy-guard.js";
|
|
8
10
|
import { FS_HELPER_SCRIPT } from "./fs-helper.js";
|
|
9
11
|
import { EXEC_MARKER, killMarked } from "./procs.js";
|
|
10
|
-
import { ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, RootGuard, shellQuote, } from "./shared.js";
|
|
12
|
+
import { cacheEnv, cacheRoot, ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, prepareSocketDir, RootGuard, shellQuote, socketDirPath, toolHomeEnv, } from "./shared.js";
|
|
11
13
|
import { DeviceOpError } from "./types.js";
|
|
12
14
|
export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
|
|
13
15
|
/** A file operation in the sandboxed helper that takes longer than this is killed. */
|
|
@@ -73,6 +75,26 @@ export class OsExecutor {
|
|
|
73
75
|
pruneTimer;
|
|
74
76
|
guard;
|
|
75
77
|
files;
|
|
78
|
+
/**
|
|
79
|
+
* The limits of the latest command. The ask callback has no command id; a device belongs to one
|
|
80
|
+
* org, so these stand for the org's egress when it explains a refusal.
|
|
81
|
+
*/
|
|
82
|
+
lastLimits;
|
|
83
|
+
/** macOS: the short socket directory (TMPDIR in `dev` / `open`); undefined elsewhere. */
|
|
84
|
+
socketDir;
|
|
85
|
+
/** The device's package caches (`<dir>/cache`). */
|
|
86
|
+
cacheDir;
|
|
87
|
+
/** The latest proxy guard result, and the policy object it was taken for. */
|
|
88
|
+
proxy = { detected: false, reasons: [] };
|
|
89
|
+
guardedPolicy;
|
|
90
|
+
guardedAt = 0;
|
|
91
|
+
/** The configuration the sandbox runs with now, as JSON (see {@link applyConfig}). */
|
|
92
|
+
installed;
|
|
93
|
+
/**
|
|
94
|
+
* Commands spawned while nothing narrowed them (policy `open`, their limits `open`) and still
|
|
95
|
+
* running. The ask callback allows any public name only while one runs.
|
|
96
|
+
*/
|
|
97
|
+
openCommands = new Set();
|
|
76
98
|
constructor(opts) {
|
|
77
99
|
this.opts = opts;
|
|
78
100
|
const dir = resolve(opts.dir);
|
|
@@ -82,17 +104,116 @@ export class OsExecutor {
|
|
|
82
104
|
this.guard = new RootGuard(this.dir, this.roots);
|
|
83
105
|
this.files = new HostFiles(this.roots);
|
|
84
106
|
this.dirKey = createHash("sha256").update(this.dir).digest("hex").slice(0, 16);
|
|
107
|
+
this.cacheDir = cacheRoot(this.dir);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The tier of work that has no limits of its own (the file helper): the device's choice cut to
|
|
111
|
+
* the latest exec's ceiling, `strict` before any exec (no ceiling known yet).
|
|
112
|
+
*/
|
|
113
|
+
tier(policy = this.opts.policy()) {
|
|
114
|
+
return this.lastLimits === undefined ? "strict" : deviceTier(policy, this.lastLimits);
|
|
115
|
+
}
|
|
116
|
+
/** What the tier gives on this machine now (for the policy summary). */
|
|
117
|
+
tierFacts(policy = this.opts.policy()) {
|
|
118
|
+
return tierFacts(policy, this.lastLimits, {
|
|
119
|
+
proxyDetected: this.proxy.detected,
|
|
120
|
+
mode: "os",
|
|
121
|
+
});
|
|
85
122
|
}
|
|
86
|
-
/** The
|
|
87
|
-
|
|
88
|
-
return
|
|
123
|
+
/** The latest proxy guard result. */
|
|
124
|
+
proxyGuard() {
|
|
125
|
+
return this.proxy;
|
|
126
|
+
}
|
|
127
|
+
/** The sandbox configuration for the policy at `tier` (no domains: those are per command). */
|
|
128
|
+
config(policy = this.opts.policy(), tier = this.tier(policy)) {
|
|
129
|
+
return srtConfig(policy, this.roots, [], {
|
|
130
|
+
tier,
|
|
89
131
|
...(this.opts.home !== undefined && { home: this.opts.home }),
|
|
90
132
|
...(this.opts.denyRead !== undefined && { denyRead: this.opts.denyRead }),
|
|
133
|
+
proxyDetected: this.proxy.detected,
|
|
134
|
+
...(this.socketDir !== undefined && { socketDir: this.socketDir }),
|
|
135
|
+
cacheDir: this.cacheDir,
|
|
91
136
|
});
|
|
92
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Installs {@link config} when the policy or the tier changed it, so the change applies at the
|
|
140
|
+
* next command without a restart. The runtime reads its global configuration at each wrap.
|
|
141
|
+
*/
|
|
142
|
+
applyConfig(policy, tier) {
|
|
143
|
+
const config = this.config(policy, tier);
|
|
144
|
+
const json = JSON.stringify(config);
|
|
145
|
+
if (json === this.installed)
|
|
146
|
+
return;
|
|
147
|
+
if (this.installed !== undefined)
|
|
148
|
+
SandboxManager.updateConfig(config);
|
|
149
|
+
this.installed = json;
|
|
150
|
+
}
|
|
151
|
+
/** Records the configuration the sandbox was initialized with. */
|
|
152
|
+
markInstalled(config) {
|
|
153
|
+
this.installed = JSON.stringify(config);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* macOS: makes the short socket directory (0700) at creation, and again before a `dev` / `open`
|
|
157
|
+
* command when it is gone (macOS prunes /tmp). A path taken by something else leaves the
|
|
158
|
+
* device without one: commands then use the tmp root.
|
|
159
|
+
*/
|
|
160
|
+
prepareSocketDir() {
|
|
161
|
+
if (process.platform !== "darwin")
|
|
162
|
+
return;
|
|
163
|
+
this.socketDir = prepareSocketDir(socketDirPath(this.dirKey, this.opts.socketBase));
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Runs the localhost proxy guard at creation, when the policy was reloaded since the last run
|
|
167
|
+
* (the store returns a new object for each new version of policy.json), and when the last result
|
|
168
|
+
* is older than {@link PROXY_GUARD_TTL_MS} (a proxy started after this program). A guard that
|
|
169
|
+
* fails counts as a proxy found (fail safe; `localhost: allow` still overrides).
|
|
170
|
+
*/
|
|
171
|
+
async refreshProxyGuard(policy) {
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
if (policy === this.guardedPolicy && now - this.guardedAt < PROXY_GUARD_TTL_MS)
|
|
174
|
+
return;
|
|
175
|
+
this.guardedPolicy = policy;
|
|
176
|
+
this.guardedAt = now;
|
|
177
|
+
try {
|
|
178
|
+
this.proxy = await (this.opts.detectProxy ?? (() => detectLocalProxy()))();
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
this.proxy = {
|
|
182
|
+
detected: true,
|
|
183
|
+
reasons: [`the localhost proxy guard failed: ${e.message}`],
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
93
187
|
async ensureRoot() {
|
|
94
188
|
return this.guard.ensure();
|
|
95
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* The sandbox's ask callback, reached only for a host no list allows. sandbox-runtime refuses `*`
|
|
192
|
+
* in a per-command list, so a command that may reach any host (device policy `open`, its limits
|
|
193
|
+
* `open`) is allowed here: a public name is allowed while such a command runs and the policy
|
|
194
|
+
* and latest limits still say so (narrowing takes effect at once). The callback has no command
|
|
195
|
+
* id, so a concurrent command of the same device may ride along meanwhile; the file helper never
|
|
196
|
+
* opens it. Otherwise it refuses, with a reason clients that print the proxy's status phrase
|
|
197
|
+
* show (spec §9.1).
|
|
198
|
+
*/
|
|
199
|
+
askCallback = async ({ host }) => {
|
|
200
|
+
const policy = this.opts.policy();
|
|
201
|
+
const limits = this.lastLimits;
|
|
202
|
+
if (this.openCommands.size > 0 &&
|
|
203
|
+
limits !== undefined &&
|
|
204
|
+
effectiveEgress(policy, limits).includes(ANY_HOST) &&
|
|
205
|
+
isPublicName(host)) {
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
return { allow: false, reason: denyReason(host, limits, policy) };
|
|
209
|
+
};
|
|
210
|
+
/** The classified network refusals of one command (read before it unregisters). */
|
|
211
|
+
blockedFor(commandId, limits, policy) {
|
|
212
|
+
const lines = SandboxManager.getSandboxViolationStore()
|
|
213
|
+
.getViolationsForCommand(commandId)
|
|
214
|
+
.map((v) => v.line);
|
|
215
|
+
return blockedHosts(lines, limits, policy);
|
|
216
|
+
}
|
|
96
217
|
/** The marker value of a tag's processes. */
|
|
97
218
|
markerOf(tag) {
|
|
98
219
|
return `${this.dirKey}.${tag}`;
|
|
@@ -103,6 +224,13 @@ export class OsExecutor {
|
|
|
103
224
|
*/
|
|
104
225
|
async spawnSandboxed(script, o) {
|
|
105
226
|
const exports = [];
|
|
227
|
+
const dev = o.tier !== "strict";
|
|
228
|
+
// Re-checked before every dev / open command (macOS prunes /tmp, and a path swapped for a
|
|
229
|
+
// link or another user's directory must not be used): prepareSocketDir never follows links.
|
|
230
|
+
if (dev && process.platform === "darwin")
|
|
231
|
+
this.prepareSocketDir();
|
|
232
|
+
// dev / open on macOS: the short socket directory, where unix sockets are allowed.
|
|
233
|
+
const tmp = dev && this.socketDir !== undefined ? this.socketDir : this.roots.tmp;
|
|
106
234
|
const inner = {
|
|
107
235
|
// The user's PATH applies inside the sandbox only (the wrapper runs with OUTER_ENV).
|
|
108
236
|
PATH: process.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
|
|
@@ -111,9 +239,16 @@ export class OsExecutor {
|
|
|
111
239
|
TERM: "dumb",
|
|
112
240
|
HOME: this.roots.workspace,
|
|
113
241
|
...(process.env.USER !== undefined && { USER: process.env.USER }),
|
|
242
|
+
// Version managers (asdf, nvm, pyenv, ...) read their data under the real home, at every
|
|
243
|
+
// tier: HOME is the workspace here. Read only; the request's values win.
|
|
244
|
+
...toolHomeEnv(this.opts.home ?? homedir()),
|
|
245
|
+
// dev / open: package caches under <dir>/cache; the command's own values win.
|
|
246
|
+
...(dev && cacheEnv(this.cacheDir, { create: true })),
|
|
114
247
|
...o.env,
|
|
115
|
-
// The runtime points TMPDIR at its own /tmp/claude (denied by the config): use
|
|
116
|
-
TMPDIR:
|
|
248
|
+
// The runtime points TMPDIR at its own /tmp/claude (denied by the config): use ours.
|
|
249
|
+
TMPDIR: tmp,
|
|
250
|
+
// Chromium on macOS ignores TMPDIR and reads this instead (its singleton socket).
|
|
251
|
+
...(process.platform === "darwin" && { MAC_CHROMIUM_TMPDIR: tmp }),
|
|
117
252
|
[EXEC_MARKER]: this.markerOf(o.tag),
|
|
118
253
|
};
|
|
119
254
|
for (const [k, v] of Object.entries(inner)) {
|
|
@@ -121,12 +256,15 @@ export class OsExecutor {
|
|
|
121
256
|
throw policyError(`invalid environment variable name ${JSON.stringify(k)}`);
|
|
122
257
|
exports.push(`export ${k}=${shellQuote(v)}`);
|
|
123
258
|
}
|
|
259
|
+
this.applyConfig(o.policy, o.tier);
|
|
124
260
|
const commandId = randomBytes(16).toString("base64url");
|
|
125
261
|
const wrapped = await SandboxManager.wrapWithSandbox(`${exports.join("\n")}\n${script}`, "/bin/bash", undefined, o.signal, { commandId, commandText: script });
|
|
126
262
|
// The kernel may have cancelled while the wrap was prepared.
|
|
127
263
|
o.signal?.throwIfAborted();
|
|
128
|
-
|
|
129
|
-
|
|
264
|
+
// "*" (any host) is refused in a per-command list: the ask callback allows those hosts.
|
|
265
|
+
const listed = o.egress.filter((d) => d !== ANY_HOST);
|
|
266
|
+
if (listed.length > 0) {
|
|
267
|
+
SandboxManager.registerCommandNetworkLists(commandId, { allowedDomains: listed });
|
|
130
268
|
}
|
|
131
269
|
let child;
|
|
132
270
|
try {
|
|
@@ -185,13 +323,27 @@ export class OsExecutor {
|
|
|
185
323
|
async exec(args, signal) {
|
|
186
324
|
signal.throwIfAborted();
|
|
187
325
|
const cwd = await this.files.inside(args.cwd ?? this.roots.workspace, "cwd");
|
|
326
|
+
// Read once: the command's lists and the explanation of its refusals use the same policy.
|
|
327
|
+
const policy = this.opts.policy();
|
|
328
|
+
this.lastLimits = args.limits;
|
|
329
|
+
await this.refreshProxyGuard(policy);
|
|
330
|
+
// A granted host the command still could not reach is not the device's doing.
|
|
331
|
+
const judged = {
|
|
332
|
+
...policy,
|
|
333
|
+
allowedDomains: [...policy.allowedDomains, ...grantedHosts(policy, args.limits, args.grants)],
|
|
334
|
+
};
|
|
335
|
+
const egress = effectiveEgress(policy, args.limits, args.grants);
|
|
188
336
|
const { child, commandId } = await this.spawnSandboxed(args.command, {
|
|
189
337
|
cwd,
|
|
190
338
|
...(args.env !== undefined && { env: args.env }),
|
|
191
339
|
tag: args.tag,
|
|
192
|
-
egress
|
|
340
|
+
egress,
|
|
341
|
+
policy,
|
|
342
|
+
tier: deviceTier(policy, args.limits),
|
|
193
343
|
signal,
|
|
194
344
|
});
|
|
345
|
+
if (egress.includes(ANY_HOST))
|
|
346
|
+
this.openCommands.add(commandId);
|
|
195
347
|
return new Promise((resolvePromise, reject) => {
|
|
196
348
|
const cap = new OutputCap(args.maxOutputBytes);
|
|
197
349
|
let timedOut = false;
|
|
@@ -227,6 +379,7 @@ export class OsExecutor {
|
|
|
227
379
|
group.exited = true;
|
|
228
380
|
group.onKill = undefined;
|
|
229
381
|
}
|
|
382
|
+
this.openCommands.delete(commandId);
|
|
230
383
|
SandboxManager.unregisterCommandNetworkLists(commandId);
|
|
231
384
|
SandboxManager.cleanupAfterCommand();
|
|
232
385
|
};
|
|
@@ -234,6 +387,15 @@ export class OsExecutor {
|
|
|
234
387
|
if (settled || exit === undefined)
|
|
235
388
|
return;
|
|
236
389
|
settled = true;
|
|
390
|
+
// Before cleanup: the violations are looked up by the command's id.
|
|
391
|
+
let blocked = [];
|
|
392
|
+
try {
|
|
393
|
+
blocked = this.blockedFor(commandId, args.limits, judged);
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
// The explanation is best effort: the command's result always comes back.
|
|
397
|
+
}
|
|
398
|
+
const trailer = networkTrailer(blocked);
|
|
237
399
|
cleanup();
|
|
238
400
|
child.stdout?.destroy();
|
|
239
401
|
child.stderr?.destroy();
|
|
@@ -243,12 +405,17 @@ export class OsExecutor {
|
|
|
243
405
|
else if (exitCode === null && exit.sig !== null) {
|
|
244
406
|
exitCode = 128 + (osConstants.signals[exit.sig] ?? 0);
|
|
245
407
|
}
|
|
408
|
+
let stderr = cap.text("stderr");
|
|
409
|
+
if (trailer !== "") {
|
|
410
|
+
stderr += `${stderr === "" || stderr.endsWith("\n") ? "" : "\n"}${trailer}`;
|
|
411
|
+
}
|
|
246
412
|
resolvePromise({
|
|
247
413
|
exitCode,
|
|
248
414
|
stdout: cap.text("stdout"),
|
|
249
|
-
stderr
|
|
415
|
+
stderr,
|
|
250
416
|
truncated: cap.truncated,
|
|
251
417
|
timedOut,
|
|
418
|
+
...(blocked.length > 0 && { network: { blocked } }),
|
|
252
419
|
});
|
|
253
420
|
};
|
|
254
421
|
child.stdout?.on("data", (b) => cap.push("stdout", b));
|
|
@@ -290,6 +457,8 @@ export class OsExecutor {
|
|
|
290
457
|
cwd: this.roots.workspace,
|
|
291
458
|
tag: "fs-helper",
|
|
292
459
|
egress: [],
|
|
460
|
+
policy: this.opts.policy(),
|
|
461
|
+
tier: this.tier(),
|
|
293
462
|
stdin: data !== undefined,
|
|
294
463
|
});
|
|
295
464
|
const chunks = [];
|
|
@@ -391,8 +560,14 @@ export async function createOsExecutor(opts) {
|
|
|
391
560
|
if (!available.ok)
|
|
392
561
|
throw new Error(available.reason);
|
|
393
562
|
const executor = new OsExecutor(opts);
|
|
394
|
-
|
|
395
|
-
|
|
563
|
+
executor.prepareSocketDir();
|
|
564
|
+
const policy = opts.policy();
|
|
565
|
+
await executor.refreshProxyGuard(policy);
|
|
566
|
+
// The ask callback never allows: a destination outside the lists is refused, with a reason
|
|
567
|
+
// when this runtime carries one (an older runtime would read any answer object as an allow).
|
|
568
|
+
const config = executor.config(policy);
|
|
569
|
+
await SandboxManager.initialize(config, SandboxManager.askCallbackDenyReason === true ? executor.askCallback : undefined);
|
|
570
|
+
executor.markInstalled(config);
|
|
396
571
|
await executor.killLeftovers();
|
|
397
572
|
return executor;
|
|
398
573
|
}
|
package/dist/exec/shared.d.ts
CHANGED
|
@@ -7,6 +7,50 @@ export declare const PIPE_GRACE_MS = 200;
|
|
|
7
7
|
export declare const ENV_NAME_RE: RegExp;
|
|
8
8
|
/** The roots of a device directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
|
|
9
9
|
export declare function osRoots(dir: string): SandboxRoots;
|
|
10
|
+
/** The device's package caches: `<dir>/cache`, outside the workspace (spec §5.2.1). */
|
|
11
|
+
export declare function cacheRoot(dir: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* The cache variables of `dev` / `open` (spec §5.2.1), each pointing at a folder of `root`
|
|
14
|
+
* (`MAVEN_OPTS` as `-Dmaven.repo.local=<folder>`). With `create` (on the host, before a
|
|
15
|
+
* sandboxed command), the root is made a real directory first ({@link ensureCacheRoot}) and the
|
|
16
|
+
* folders are made on demand; a folder that cannot be made leaves its variable out, and a root
|
|
17
|
+
* that cannot be made, or that was swapped while the folders were made, leaves every variable
|
|
18
|
+
* out, so a broken cache never stops the next command. A command's
|
|
19
|
+
* own value wins: callers apply the request's environment after these.
|
|
20
|
+
*/
|
|
21
|
+
export declare function cacheEnv(root: string, opts?: {
|
|
22
|
+
create?: boolean;
|
|
23
|
+
}): Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
|
|
26
|
+
* workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
|
|
27
|
+
* have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
|
|
28
|
+
* sets them. CARGO_HOME is a package cache ({@link cacheEnv}).
|
|
29
|
+
*/
|
|
30
|
+
export declare const TOOL_HOME_DIRS: readonly (readonly [string, string])[];
|
|
31
|
+
/**
|
|
32
|
+
* The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
|
|
33
|
+
* the device's environment `env` sets to an absolute path is passed on; an unset one points at its
|
|
34
|
+
* default directory under the real `home` when that is a directory. The sandbox only reads them
|
|
35
|
+
* (they are never made writable); the secret paths stay denied. asdf's global `.tool-versions`
|
|
36
|
+
* is still found: asdf walks up from the working directory, and the device directory is under the
|
|
37
|
+
* home.
|
|
38
|
+
*/
|
|
39
|
+
export declare function toolHomeEnv(home: string, env?: Record<string, string | undefined>): Record<string, string>;
|
|
40
|
+
/**
|
|
41
|
+
* The short socket directory of a device on macOS (spec §5.2.3): `<base>/cap-<first 8 hex of the
|
|
42
|
+
* device's key>`, short enough for Chromium's singleton socket (unix socket paths stop at 104
|
|
43
|
+
* bytes). `base` is `/private/tmp` outside tests.
|
|
44
|
+
*/
|
|
45
|
+
export declare function socketDirPath(dirKey: string, base?: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Creates the socket directory (mode 0700), or checks an existing one is a real directory of this
|
|
48
|
+
* user and makes it 0700 again. The check and the mode change go through one descriptor opened
|
|
49
|
+
* without following links, so a link swapped in meanwhile (the shared /tmp is sticky, not
|
|
50
|
+
* private) is refused, never followed. Returns undefined when the path is taken by something else
|
|
51
|
+
* (another user's directory, a file or a link): commands then use the tmp root.
|
|
52
|
+
*/
|
|
53
|
+
export declare function prepareSocketDir(path: string, uid?: number | undefined): string | undefined;
|
|
10
54
|
/**
|
|
11
55
|
* The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
|
|
12
56
|
* dropped instead of decoding to U+FFFD).
|