@capybara-hq/device 0.1.0-rc.3 → 0.1.0-rc.4

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/dist/exec/os.js CHANGED
@@ -3,11 +3,13 @@ import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, realpathSync } from "node:fs";
4
4
  import { constants as osConstants } from "node:os";
5
5
  import { resolve } from "node:path";
6
- import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
7
- import { effectiveEgress, srtConfig } from "../policy.js";
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, } 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 configuration the sandbox is initialized with (no domains: those are per command). */
87
- config() {
88
- return srtConfig(this.opts.policy, this.roots, [], {
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,13 @@ export class OsExecutor {
111
239
  TERM: "dumb",
112
240
  HOME: this.roots.workspace,
113
241
  ...(process.env.USER !== undefined && { USER: process.env.USER }),
242
+ // dev / open: package caches under <dir>/cache; the command's own values win.
243
+ ...(dev && cacheEnv(this.cacheDir, { create: true })),
114
244
  ...o.env,
115
- // The runtime points TMPDIR at its own /tmp/claude (denied by the config): use the tmp root.
116
- TMPDIR: this.roots.tmp,
245
+ // The runtime points TMPDIR at its own /tmp/claude (denied by the config): use ours.
246
+ TMPDIR: tmp,
247
+ // Chromium on macOS ignores TMPDIR and reads this instead (its singleton socket).
248
+ ...(process.platform === "darwin" && { MAC_CHROMIUM_TMPDIR: tmp }),
117
249
  [EXEC_MARKER]: this.markerOf(o.tag),
118
250
  };
119
251
  for (const [k, v] of Object.entries(inner)) {
@@ -121,12 +253,15 @@ export class OsExecutor {
121
253
  throw policyError(`invalid environment variable name ${JSON.stringify(k)}`);
122
254
  exports.push(`export ${k}=${shellQuote(v)}`);
123
255
  }
256
+ this.applyConfig(o.policy, o.tier);
124
257
  const commandId = randomBytes(16).toString("base64url");
125
258
  const wrapped = await SandboxManager.wrapWithSandbox(`${exports.join("\n")}\n${script}`, "/bin/bash", undefined, o.signal, { commandId, commandText: script });
126
259
  // The kernel may have cancelled while the wrap was prepared.
127
260
  o.signal?.throwIfAborted();
128
- if (o.egress.length > 0) {
129
- SandboxManager.registerCommandNetworkLists(commandId, { allowedDomains: o.egress });
261
+ // "*" (any host) is refused in a per-command list: the ask callback allows those hosts.
262
+ const listed = o.egress.filter((d) => d !== ANY_HOST);
263
+ if (listed.length > 0) {
264
+ SandboxManager.registerCommandNetworkLists(commandId, { allowedDomains: listed });
130
265
  }
131
266
  let child;
132
267
  try {
@@ -185,13 +320,27 @@ export class OsExecutor {
185
320
  async exec(args, signal) {
186
321
  signal.throwIfAborted();
187
322
  const cwd = await this.files.inside(args.cwd ?? this.roots.workspace, "cwd");
323
+ // Read once: the command's lists and the explanation of its refusals use the same policy.
324
+ const policy = this.opts.policy();
325
+ this.lastLimits = args.limits;
326
+ await this.refreshProxyGuard(policy);
327
+ // A granted host the command still could not reach is not the device's doing.
328
+ const judged = {
329
+ ...policy,
330
+ allowedDomains: [...policy.allowedDomains, ...grantedHosts(policy, args.limits, args.grants)],
331
+ };
332
+ const egress = effectiveEgress(policy, args.limits, args.grants);
188
333
  const { child, commandId } = await this.spawnSandboxed(args.command, {
189
334
  cwd,
190
335
  ...(args.env !== undefined && { env: args.env }),
191
336
  tag: args.tag,
192
- egress: effectiveEgress(this.opts.policy, args.limits),
337
+ egress,
338
+ policy,
339
+ tier: deviceTier(policy, args.limits),
193
340
  signal,
194
341
  });
342
+ if (egress.includes(ANY_HOST))
343
+ this.openCommands.add(commandId);
195
344
  return new Promise((resolvePromise, reject) => {
196
345
  const cap = new OutputCap(args.maxOutputBytes);
197
346
  let timedOut = false;
@@ -227,6 +376,7 @@ export class OsExecutor {
227
376
  group.exited = true;
228
377
  group.onKill = undefined;
229
378
  }
379
+ this.openCommands.delete(commandId);
230
380
  SandboxManager.unregisterCommandNetworkLists(commandId);
231
381
  SandboxManager.cleanupAfterCommand();
232
382
  };
@@ -234,6 +384,15 @@ export class OsExecutor {
234
384
  if (settled || exit === undefined)
235
385
  return;
236
386
  settled = true;
387
+ // Before cleanup: the violations are looked up by the command's id.
388
+ let blocked = [];
389
+ try {
390
+ blocked = this.blockedFor(commandId, args.limits, judged);
391
+ }
392
+ catch {
393
+ // The explanation is best effort: the command's result always comes back.
394
+ }
395
+ const trailer = networkTrailer(blocked);
237
396
  cleanup();
238
397
  child.stdout?.destroy();
239
398
  child.stderr?.destroy();
@@ -243,12 +402,17 @@ export class OsExecutor {
243
402
  else if (exitCode === null && exit.sig !== null) {
244
403
  exitCode = 128 + (osConstants.signals[exit.sig] ?? 0);
245
404
  }
405
+ let stderr = cap.text("stderr");
406
+ if (trailer !== "") {
407
+ stderr += `${stderr === "" || stderr.endsWith("\n") ? "" : "\n"}${trailer}`;
408
+ }
246
409
  resolvePromise({
247
410
  exitCode,
248
411
  stdout: cap.text("stdout"),
249
- stderr: cap.text("stderr"),
412
+ stderr,
250
413
  truncated: cap.truncated,
251
414
  timedOut,
415
+ ...(blocked.length > 0 && { network: { blocked } }),
252
416
  });
253
417
  };
254
418
  child.stdout?.on("data", (b) => cap.push("stdout", b));
@@ -290,6 +454,8 @@ export class OsExecutor {
290
454
  cwd: this.roots.workspace,
291
455
  tag: "fs-helper",
292
456
  egress: [],
457
+ policy: this.opts.policy(),
458
+ tier: this.tier(),
293
459
  stdin: data !== undefined,
294
460
  });
295
461
  const chunks = [];
@@ -391,8 +557,14 @@ export async function createOsExecutor(opts) {
391
557
  if (!available.ok)
392
558
  throw new Error(available.reason);
393
559
  const executor = new OsExecutor(opts);
394
- // No ask callback: a destination outside the lists is refused, never prompted.
395
- await SandboxManager.initialize(executor.config());
560
+ executor.prepareSocketDir();
561
+ const policy = opts.policy();
562
+ await executor.refreshProxyGuard(policy);
563
+ // The ask callback never allows: a destination outside the lists is refused, with a reason
564
+ // when this runtime carries one (an older runtime would read any answer object as an allow).
565
+ const config = executor.config(policy);
566
+ await SandboxManager.initialize(config, SandboxManager.askCallbackDenyReason === true ? executor.askCallback : undefined);
567
+ executor.markInstalled(config);
396
568
  await executor.killLeftovers();
397
569
  return executor;
398
570
  }
@@ -7,6 +7,34 @@ 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 short socket directory of a device on macOS (spec §5.2.3): `<base>/cap-<first 8 hex of the
26
+ * device's key>`, short enough for Chromium's singleton socket (unix socket paths stop at 104
27
+ * bytes). `base` is `/private/tmp` outside tests.
28
+ */
29
+ export declare function socketDirPath(dirKey: string, base?: string): string;
30
+ /**
31
+ * Creates the socket directory (mode 0700), or checks an existing one is a real directory of this
32
+ * user and makes it 0700 again. The check and the mode change go through one descriptor opened
33
+ * without following links, so a link swapped in meanwhile (the shared /tmp is sticky, not
34
+ * private) is refused, never followed. Returns undefined when the path is taken by something else
35
+ * (another user's directory, a file or a link): commands then use the tmp root.
36
+ */
37
+ export declare function prepareSocketDir(path: string, uid?: number | undefined): string | undefined;
10
38
  /**
11
39
  * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
12
40
  * dropped instead of decoding to U+FFFD).
@@ -1,4 +1,4 @@
1
- import { constants, existsSync, mkdirSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
2
2
  import { lstat, mkdir, open, realpath } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { DeviceOpError } from "./types.js";
@@ -11,6 +11,159 @@ export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
11
11
  export function osRoots(dir) {
12
12
  return { workspace: join(dir, "workspace"), skills: join(dir, "skills"), tmp: join(dir, "tmp") };
13
13
  }
14
+ /** The device's package caches: `<dir>/cache`, outside the workspace (spec §5.2.1). */
15
+ export function cacheRoot(dir) {
16
+ return join(dir, "cache");
17
+ }
18
+ /** Each cache variable of `dev` / `open` and its folder under the cache root. */
19
+ const CACHE_DIRS = [
20
+ ["XDG_CACHE_HOME", "xdg"],
21
+ ["npm_config_cache", "npm"],
22
+ ["npm_config_store_dir", "pnpm-store"],
23
+ ["PIP_CACHE_DIR", "pip"],
24
+ ["UV_CACHE_DIR", "uv"],
25
+ ["CARGO_HOME", "cargo"],
26
+ ["GOMODCACHE", "go-mod"],
27
+ ["GOCACHE", "go-build"],
28
+ ["GRADLE_USER_HOME", "gradle"],
29
+ ["MAVEN_OPTS", "maven"],
30
+ ["PLAYWRIGHT_BROWSERS_PATH", "ms-playwright"],
31
+ ["COREPACK_HOME", "corepack"],
32
+ ];
33
+ /** The device and inode of a real directory (never through a link); undefined otherwise. */
34
+ function realDirId(path) {
35
+ try {
36
+ const st = lstatSync(path);
37
+ return st.isDirectory() ? `${st.dev}:${st.ino}` : undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ /**
44
+ * Makes the cache root a real directory and returns its identity. Sandboxed commands may write
45
+ * the root (it is under `<dir>/cache`), so they can replace it with a link to a host folder: a
46
+ * link, a file or anything else in its place is unlinked (never followed) and the root made
47
+ * again, mode 0700. Its real path must then be its parent's real path plus its name (nothing in
48
+ * between resolves elsewhere). Undefined when it cannot be made a real directory.
49
+ */
50
+ function ensureCacheRoot(root) {
51
+ try {
52
+ const st = lstatSync(root);
53
+ // unlink, not rm: rm skips a link whose target is missing, and never recurse into a target.
54
+ if (!st.isDirectory())
55
+ unlinkSync(root);
56
+ }
57
+ catch (e) {
58
+ if (e.code !== "ENOENT")
59
+ return undefined;
60
+ }
61
+ try {
62
+ mkdirSync(root, { mode: 0o700 });
63
+ }
64
+ catch (e) {
65
+ if (e.code !== "EEXIST")
66
+ return undefined;
67
+ }
68
+ try {
69
+ if (realpathSync(root) !== join(realpathSync(dirname(root)), basename(root)))
70
+ return undefined;
71
+ }
72
+ catch {
73
+ return undefined;
74
+ }
75
+ return realDirId(root);
76
+ }
77
+ /**
78
+ * Makes one cache folder under a verified root: an existing real directory is used, a missing
79
+ * one is made (not recursively, so nothing is made through a link). A file or a link a command
80
+ * put in its place is left alone (never removed, never followed): its variable is left out.
81
+ */
82
+ function ensureCacheFolder(path) {
83
+ if (realDirId(path) !== undefined)
84
+ return true;
85
+ try {
86
+ mkdirSync(path, { mode: 0o700 });
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ return realDirId(path) !== undefined;
92
+ }
93
+ /**
94
+ * The cache variables of `dev` / `open` (spec §5.2.1), each pointing at a folder of `root`
95
+ * (`MAVEN_OPTS` as `-Dmaven.repo.local=<folder>`). With `create` (on the host, before a
96
+ * sandboxed command), the root is made a real directory first ({@link ensureCacheRoot}) and the
97
+ * folders are made on demand; a folder that cannot be made leaves its variable out, and a root
98
+ * that cannot be made, or that was swapped while the folders were made, leaves every variable
99
+ * out, so a broken cache never stops the next command. A command's
100
+ * own value wins: callers apply the request's environment after these.
101
+ */
102
+ export function cacheEnv(root, opts = {}) {
103
+ const create = opts.create === true;
104
+ const rootId = create ? ensureCacheRoot(root) : undefined;
105
+ if (create && rootId === undefined)
106
+ return {};
107
+ const out = {};
108
+ for (const [name, sub] of CACHE_DIRS) {
109
+ const path = join(root, sub);
110
+ if (create && !ensureCacheFolder(path))
111
+ continue;
112
+ out[name] = name === "MAVEN_OPTS" ? `-Dmaven.repo.local=${path}` : path;
113
+ }
114
+ // A concurrent command may have swapped the root meanwhile: then trust none of the folders.
115
+ // Accepted narrow race: a swap between ensureCacheRoot and a folder's mkdir makes that one
116
+ // fixed-name folder (mode 0700, empty) in the link's target. Nothing is removed or followed
117
+ // further, and this recheck of the root's device and inode drops every variable.
118
+ if (create && realDirId(root) !== rootId)
119
+ return {};
120
+ return out;
121
+ }
122
+ /**
123
+ * The short socket directory of a device on macOS (spec §5.2.3): `<base>/cap-<first 8 hex of the
124
+ * device's key>`, short enough for Chromium's singleton socket (unix socket paths stop at 104
125
+ * bytes). `base` is `/private/tmp` outside tests.
126
+ */
127
+ export function socketDirPath(dirKey, base = "/private/tmp") {
128
+ return join(base, `cap-${dirKey.slice(0, 8)}`);
129
+ }
130
+ /**
131
+ * Creates the socket directory (mode 0700), or checks an existing one is a real directory of this
132
+ * user and makes it 0700 again. The check and the mode change go through one descriptor opened
133
+ * without following links, so a link swapped in meanwhile (the shared /tmp is sticky, not
134
+ * private) is refused, never followed. Returns undefined when the path is taken by something else
135
+ * (another user's directory, a file or a link): commands then use the tmp root.
136
+ */
137
+ export function prepareSocketDir(path, uid = process.getuid?.()) {
138
+ try {
139
+ mkdirSync(path, { mode: 0o700 });
140
+ }
141
+ catch (e) {
142
+ if (e.code !== "EEXIST")
143
+ return undefined;
144
+ }
145
+ let fd;
146
+ try {
147
+ fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ try {
153
+ const st = fstatSync(fd);
154
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid))
155
+ return undefined;
156
+ if ((st.mode & 0o777) !== 0o700)
157
+ fchmodSync(fd, 0o700);
158
+ return path;
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ finally {
164
+ closeSync(fd);
165
+ }
166
+ }
14
167
  /**
15
168
  * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
16
169
  * dropped instead of decoding to U+FFFD).
@@ -0,0 +1,108 @@
1
+ import { type DeviceExecArgs, type ExecResult, type SandboxLimits, type SandboxRoots, type SandboxTier } from "@capybara-hq/plugin-sdk";
2
+ import { type TierLimits } from "../policy.js";
3
+ import type { ProxyGuardResult } from "../proxy-guard.js";
4
+ import type { Policy } from "../state.js";
5
+ import { type ExecIsolation, type Executor } from "./types.js";
6
+ export type { ExecIsolation } from "./types.js";
7
+ /**
8
+ * Whether the local policy itself asks for no sandbox: `isolation: "none"` with the owner's own
9
+ * tier set to `open` on this machine. A tier the deployment supplies (the org's default) never
10
+ * counts, so the kernel can never be the last step that makes commands run unsandboxed.
11
+ */
12
+ export declare function policyUnsandboxed(policy: Pick<Policy, "tier" | "isolation">): boolean;
13
+ /**
14
+ * Decides how one command runs (spec §5.4). Without a sandbox only when the local policy says
15
+ * `isolation: "none"` with its own tier `open` ({@link policyUnsandboxed}), the device runs in OS
16
+ * mode, the kernel allows it for this command (`limits.allowUnsandboxed`: the platform and the
17
+ * org allow it and an unattended run has its grant; absent counts as not allowed), and the
18
+ * command's tier (that choice cut to the org's ceiling) is `open`. When the policy says `none`
19
+ * but any of those does not hold, the command is refused, never run in the sandbox silently: the
20
+ * owner asked for no sandbox. The device enforces the kernel's decision itself, because the
21
+ * kernel knows the local policy only from the last hello or policy op (spec §4.3); its refusal is
22
+ * {@link UNSANDBOXED_NOT_ALLOWED_MESSAGE}, which the kernel maps to its own error. Docker mode
23
+ * ignores `isolation` (its container is the isolation).
24
+ */
25
+ export declare function execIsolation(policy: Pick<Policy, "tier" | "isolation">, limits: ExecLimits, mode: Executor["mode"]): ExecIsolation;
26
+ /** What {@link execIsolation} reads of an exec's limits. */
27
+ export type ExecLimits = TierLimits & Pick<SandboxLimits, "allowUnsandboxed">;
28
+ /** The refusal of a command the policy asks to run without a sandbox below tier `open`. */
29
+ export declare function unsandboxedRefusal(policy: Pick<Policy, "tier">, tier: SandboxTier): string;
30
+ /**
31
+ * How long the latest command's limits decide file operations. The kernel judges the org's
32
+ * settings at each exec, and file operations carry no limits, so an unsandboxed decision older
33
+ * than this no longer counts: file operations fall back to the sandboxed helper, which reads and
34
+ * writes the same roots (only slower), until the next command decides again. A minute covers a
35
+ * turn's file operations around its commands while bounding how long an org's change (or a lower
36
+ * ceiling) takes to reach a device that runs no more commands.
37
+ */
38
+ export declare const FILE_OPS_DECISION_TTL_MS = 60000;
39
+ /** The refusal of an unsandboxed command whose sandbox was turned back on before it started. */
40
+ export declare const SANDBOX_BACK_ON: string;
41
+ /**
42
+ * The OS-mode executor the program serves: each command runs in the OS sandbox or, when
43
+ * {@link execIsolation} says so, without one; the policy is read per operation, so a change
44
+ * applies at once. File operations use the host executor's direct IO (still confined to the
45
+ * roots) when the same decision, on the policy now and the latest command's limits, says no
46
+ * sandbox; otherwise (and before any command) the sandboxed helper. When the policy turns the
47
+ * sandbox back on, every command still running without one (and what it left in the background)
48
+ * is killed, and one still starting is refused right before its spawn; while unsandboxed, the
49
+ * policy is also checked every second so that happens without waiting for the next operation.
50
+ * Kills reach both executors' commands.
51
+ */
52
+ export declare class SwitchingExecutor implements Executor {
53
+ private readonly sandboxed;
54
+ /** Runs commands without a sandbox (the `HostExecutor`). */
55
+ private readonly host;
56
+ private readonly policy;
57
+ private readonly onSwitch?;
58
+ readonly mode: "os";
59
+ readonly roots: SandboxRoots;
60
+ /** The policy asked for no sandbox when last checked. */
61
+ private unsandboxed;
62
+ private watch;
63
+ /** The latest command's limits and when they came (file operations follow their decision). */
64
+ private lastLimits;
65
+ private lastLimitsAt;
66
+ constructor(sandboxed: Executor,
67
+ /** Runs commands without a sandbox (the `HostExecutor`). */
68
+ host: Executor, policy: () => Policy, onSwitch?: ((isolation: "sandbox" | "none") => void) | undefined);
69
+ /**
70
+ * Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills
71
+ * the unsandboxed commands. Returns whether the policy asks for no sandbox now.
72
+ */
73
+ sync(policy?: Policy): Promise<boolean>;
74
+ /**
75
+ * Records an exec's limits, refused ones included, so file operations follow the latest
76
+ * decision (see {@link FILE_OPS_DECISION_TTL_MS}).
77
+ */
78
+ noteLimits(limits: ExecLimits): void;
79
+ /**
80
+ * The executor for file operations now: the commands' decision on the policy now and the latest
81
+ * exec's limits; the sandboxed helper before any exec or once those limits are stale.
82
+ */
83
+ private files;
84
+ exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
85
+ /**
86
+ * Runs one command as `how` decided (the caller logs the same decision). The policy it was
87
+ * decided on is synced first, so a sandbox turned back on stops the unsandboxed commands. An
88
+ * unsandboxed command is decided again on the policy then, right before its spawn: one whose
89
+ * sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
90
+ */
91
+ execDecided(args: DeviceExecArgs, signal: AbortSignal, how: ExecIsolation, policy?: Policy): Promise<ExecResult>;
92
+ readFile(path: string, maxBytes: number): Promise<{
93
+ data: Uint8Array;
94
+ truncated: boolean;
95
+ } | null>;
96
+ writeFile(path: string, data: Uint8Array): Promise<void>;
97
+ stat(path: string): Promise<{
98
+ size: number;
99
+ isDir: boolean;
100
+ } | null>;
101
+ killTagged(tags: string[]): Promise<void>;
102
+ killAll(): Promise<void>;
103
+ ensureRoot(): Promise<"ok" | "gone">;
104
+ /** The sandboxed executor's latest localhost proxy guard result (see `Executor`). */
105
+ proxyGuard(): ProxyGuardResult;
106
+ /** Stops watching the policy. */
107
+ dispose(): void;
108
+ }