@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.
@@ -1,4 +1,4 @@
1
- import { constants, existsSync, mkdirSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, realpathSync, statSync, 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,215 @@ 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 data directories of version managers, relative to the home: the OS sandbox sets HOME to the
124
+ * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
125
+ * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
126
+ * sets them. CARGO_HOME is a package cache ({@link cacheEnv}).
127
+ */
128
+ export const TOOL_HOME_DIRS = [
129
+ ["ASDF_DATA_DIR", ".asdf"],
130
+ ["NVM_DIR", ".nvm"],
131
+ ["PYENV_ROOT", ".pyenv"],
132
+ ["RBENV_ROOT", ".rbenv"],
133
+ ["MISE_DATA_DIR", ".local/share/mise"],
134
+ ["MISE_CONFIG_DIR", ".config/mise"],
135
+ ["VOLTA_HOME", ".volta"],
136
+ ["SDKMAN_DIR", ".sdkman"],
137
+ ["RUSTUP_HOME", ".rustup"],
138
+ ];
139
+ function isDir(path) {
140
+ try {
141
+ return statSync(path).isDirectory();
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ /**
148
+ * The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
149
+ * the device's environment `env` sets to an absolute path is passed on; an unset one points at its
150
+ * default directory under the real `home` when that is a directory. The sandbox only reads them
151
+ * (they are never made writable); the secret paths stay denied. asdf's global `.tool-versions`
152
+ * is still found: asdf walks up from the working directory, and the device directory is under the
153
+ * home.
154
+ */
155
+ export function toolHomeEnv(home, env = process.env) {
156
+ const xdg = (name, rel) => {
157
+ const v = env[name];
158
+ return v !== undefined && isAbsolute(v) ? v : join(home, rel);
159
+ };
160
+ const defaults = {
161
+ MISE_DATA_DIR: join(xdg("XDG_DATA_HOME", ".local/share"), "mise"),
162
+ MISE_CONFIG_DIR: join(xdg("XDG_CONFIG_HOME", ".config"), "mise"),
163
+ };
164
+ const out = {};
165
+ for (const [name, rel] of TOOL_HOME_DIRS) {
166
+ const set = env[name];
167
+ if (set !== undefined && set !== "") {
168
+ if (isAbsolute(set))
169
+ out[name] = set;
170
+ continue;
171
+ }
172
+ const dir = defaults[name] ?? join(home, rel);
173
+ if (isDir(dir))
174
+ out[name] = dir;
175
+ }
176
+ return out;
177
+ }
178
+ /**
179
+ * The short socket directory of a device on macOS (spec §5.2.3): `<base>/cap-<first 8 hex of the
180
+ * device's key>`, short enough for Chromium's singleton socket (unix socket paths stop at 104
181
+ * bytes). `base` is `/private/tmp` outside tests.
182
+ */
183
+ export function socketDirPath(dirKey, base = "/private/tmp") {
184
+ return join(base, `cap-${dirKey.slice(0, 8)}`);
185
+ }
186
+ /**
187
+ * Creates the socket directory (mode 0700), or checks an existing one is a real directory of this
188
+ * user and makes it 0700 again. The check and the mode change go through one descriptor opened
189
+ * without following links, so a link swapped in meanwhile (the shared /tmp is sticky, not
190
+ * private) is refused, never followed. Returns undefined when the path is taken by something else
191
+ * (another user's directory, a file or a link): commands then use the tmp root.
192
+ */
193
+ export function prepareSocketDir(path, uid = process.getuid?.()) {
194
+ try {
195
+ mkdirSync(path, { mode: 0o700 });
196
+ }
197
+ catch (e) {
198
+ if (e.code !== "EEXIST")
199
+ return undefined;
200
+ }
201
+ let fd;
202
+ try {
203
+ fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
204
+ }
205
+ catch {
206
+ return undefined;
207
+ }
208
+ try {
209
+ const st = fstatSync(fd);
210
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid))
211
+ return undefined;
212
+ if ((st.mode & 0o777) !== 0o700)
213
+ fchmodSync(fd, 0o700);
214
+ return path;
215
+ }
216
+ catch {
217
+ return undefined;
218
+ }
219
+ finally {
220
+ closeSync(fd);
221
+ }
222
+ }
14
223
  /**
15
224
  * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
16
225
  * 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
+ }
@@ -0,0 +1,214 @@
1
+ import { UNSANDBOXED_NOT_ALLOWED_MESSAGE, } from "@capybara-hq/plugin-sdk";
2
+ import { deviceTier } from "../policy.js";
3
+ import { DeviceOpError } from "./types.js";
4
+ /**
5
+ * Whether the local policy itself asks for no sandbox: `isolation: "none"` with the owner's own
6
+ * tier set to `open` on this machine. A tier the deployment supplies (the org's default) never
7
+ * counts, so the kernel can never be the last step that makes commands run unsandboxed.
8
+ */
9
+ export function policyUnsandboxed(policy) {
10
+ return policy.isolation === "none" && policy.tier === "open";
11
+ }
12
+ /**
13
+ * Decides how one command runs (spec §5.4). Without a sandbox only when the local policy says
14
+ * `isolation: "none"` with its own tier `open` ({@link policyUnsandboxed}), the device runs in OS
15
+ * mode, the kernel allows it for this command (`limits.allowUnsandboxed`: the platform and the
16
+ * org allow it and an unattended run has its grant; absent counts as not allowed), and the
17
+ * command's tier (that choice cut to the org's ceiling) is `open`. When the policy says `none`
18
+ * but any of those does not hold, the command is refused, never run in the sandbox silently: the
19
+ * owner asked for no sandbox. The device enforces the kernel's decision itself, because the
20
+ * kernel knows the local policy only from the last hello or policy op (spec §4.3); its refusal is
21
+ * {@link UNSANDBOXED_NOT_ALLOWED_MESSAGE}, which the kernel maps to its own error. Docker mode
22
+ * ignores `isolation` (its container is the isolation).
23
+ */
24
+ export function execIsolation(policy, limits, mode) {
25
+ const tier = deviceTier(policy, limits);
26
+ if (mode !== "os" || policy.isolation !== "none")
27
+ return { tier, isolation: "sandbox" };
28
+ if (policy.tier !== "open") {
29
+ return { tier, isolation: "none", refusal: unsandboxedRefusal(policy, tier) };
30
+ }
31
+ if (limits.allowUnsandboxed !== true) {
32
+ return { tier, isolation: "none", refusal: UNSANDBOXED_NOT_ALLOWED_MESSAGE };
33
+ }
34
+ if (tier === "open")
35
+ return { tier, isolation: "none" };
36
+ return { tier, isolation: "none", refusal: unsandboxedRefusal(policy, tier) };
37
+ }
38
+ /** The refusal of a command the policy asks to run without a sandbox below tier `open`. */
39
+ export function unsandboxedRefusal(policy, tier) {
40
+ if (policy.tier !== "open") {
41
+ const own = policy.tier === undefined
42
+ ? "its tier is not set on this machine (it follows the organization's default)"
43
+ : `its tier is ${policy.tier}`;
44
+ return (`This device is set to run commands without a sandbox, but ${own}; running without a ` +
45
+ "sandbox needs tier open set on this machine. Run capybara-device policy set tier open, " +
46
+ "or turn the sandbox back on with capybara-device policy set isolation sandbox.");
47
+ }
48
+ return ("This device is set to run commands without a sandbox, but the organization allows at most " +
49
+ `the ${tier} tier, and running without a sandbox needs tier open. The device's owner can ` +
50
+ "turn the sandbox back on with capybara-device policy set isolation sandbox.");
51
+ }
52
+ /**
53
+ * How long the latest command's limits decide file operations. The kernel judges the org's
54
+ * settings at each exec, and file operations carry no limits, so an unsandboxed decision older
55
+ * than this no longer counts: file operations fall back to the sandboxed helper, which reads and
56
+ * writes the same roots (only slower), until the next command decides again. A minute covers a
57
+ * turn's file operations around its commands while bounding how long an org's change (or a lower
58
+ * ceiling) takes to reach a device that runs no more commands.
59
+ */
60
+ export const FILE_OPS_DECISION_TTL_MS = 60_000;
61
+ /** How often the switching executor rereads the policy while it runs commands unsandboxed. */
62
+ const WATCH_INTERVAL_MS = 1000;
63
+ /** The refusal of an unsandboxed command whose sandbox was turned back on before it started. */
64
+ export const SANDBOX_BACK_ON = "The sandbox was turned back on on this machine while the command was starting, so it did " +
65
+ "not run. Run it again: it runs in the sandbox now.";
66
+ /**
67
+ * The OS-mode executor the program serves: each command runs in the OS sandbox or, when
68
+ * {@link execIsolation} says so, without one; the policy is read per operation, so a change
69
+ * applies at once. File operations use the host executor's direct IO (still confined to the
70
+ * roots) when the same decision, on the policy now and the latest command's limits, says no
71
+ * sandbox; otherwise (and before any command) the sandboxed helper. When the policy turns the
72
+ * sandbox back on, every command still running without one (and what it left in the background)
73
+ * is killed, and one still starting is refused right before its spawn; while unsandboxed, the
74
+ * policy is also checked every second so that happens without waiting for the next operation.
75
+ * Kills reach both executors' commands.
76
+ */
77
+ export class SwitchingExecutor {
78
+ sandboxed;
79
+ host;
80
+ policy;
81
+ onSwitch;
82
+ mode = "os";
83
+ roots;
84
+ /** The policy asked for no sandbox when last checked. */
85
+ unsandboxed = false;
86
+ watch;
87
+ /** The latest command's limits and when they came (file operations follow their decision). */
88
+ lastLimits;
89
+ lastLimitsAt = 0;
90
+ constructor(sandboxed,
91
+ /** Runs commands without a sandbox (the `HostExecutor`). */
92
+ host, policy, onSwitch) {
93
+ this.sandboxed = sandboxed;
94
+ this.host = host;
95
+ this.policy = policy;
96
+ this.onSwitch = onSwitch;
97
+ this.roots = sandboxed.roots;
98
+ }
99
+ /**
100
+ * Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills
101
+ * the unsandboxed commands. Returns whether the policy asks for no sandbox now.
102
+ */
103
+ async sync(policy = this.policy()) {
104
+ const none = policyUnsandboxed(policy);
105
+ if (none === this.unsandboxed)
106
+ return none;
107
+ if (none) {
108
+ this.unsandboxed = true;
109
+ this.watch ??= setInterval(() => void this.sync().catch(() => { }), WATCH_INTERVAL_MS);
110
+ this.watch.unref();
111
+ this.onSwitch?.("none");
112
+ return none;
113
+ }
114
+ // Back in the sandbox only once the unsandboxed commands are gone: a failed kill keeps the
115
+ // state (and the watch), so the next sync tries again. Routing follows the policy meanwhile.
116
+ try {
117
+ await this.host.killAll();
118
+ }
119
+ catch {
120
+ return none;
121
+ }
122
+ // The policy may have changed again while the kill ran: the next sync judges that.
123
+ if (!this.unsandboxed || policyUnsandboxed(this.policy()))
124
+ return none;
125
+ this.unsandboxed = false;
126
+ if (this.watch !== undefined)
127
+ clearInterval(this.watch);
128
+ this.watch = undefined;
129
+ this.onSwitch?.("sandbox");
130
+ return none;
131
+ }
132
+ /**
133
+ * Records an exec's limits, refused ones included, so file operations follow the latest
134
+ * decision (see {@link FILE_OPS_DECISION_TTL_MS}).
135
+ */
136
+ noteLimits(limits) {
137
+ const { tier, defaultTier, allowUnsandboxed } = limits;
138
+ this.lastLimits = {
139
+ tier,
140
+ ...(defaultTier !== undefined && { defaultTier }),
141
+ ...(allowUnsandboxed !== undefined && { allowUnsandboxed }),
142
+ };
143
+ this.lastLimitsAt = Date.now();
144
+ }
145
+ /**
146
+ * The executor for file operations now: the commands' decision on the policy now and the latest
147
+ * exec's limits; the sandboxed helper before any exec or once those limits are stale.
148
+ */
149
+ async files() {
150
+ const policy = this.policy();
151
+ await this.sync(policy);
152
+ if (this.lastLimits === undefined)
153
+ return this.sandboxed;
154
+ if (Date.now() - this.lastLimitsAt > FILE_OPS_DECISION_TTL_MS)
155
+ return this.sandboxed;
156
+ const how = execIsolation(policy, this.lastLimits, "os");
157
+ return how.isolation === "none" && how.refusal === undefined ? this.host : this.sandboxed;
158
+ }
159
+ async exec(args, signal) {
160
+ signal.throwIfAborted();
161
+ const policy = this.policy();
162
+ return this.execDecided(args, signal, execIsolation(policy, args.limits, "os"), policy);
163
+ }
164
+ /**
165
+ * Runs one command as `how` decided (the caller logs the same decision). The policy it was
166
+ * decided on is synced first, so a sandbox turned back on stops the unsandboxed commands. An
167
+ * unsandboxed command is decided again on the policy then, right before its spawn: one whose
168
+ * sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
169
+ */
170
+ async execDecided(args, signal, how, policy = this.policy()) {
171
+ signal.throwIfAborted();
172
+ this.noteLimits(args.limits);
173
+ await this.sync(policy);
174
+ if (how.refusal !== undefined)
175
+ throw new DeviceOpError("policy", how.refusal);
176
+ if (how.isolation !== "none")
177
+ return this.sandboxed.exec(args, signal);
178
+ const beforeSpawn = () => {
179
+ const now = execIsolation(this.policy(), args.limits, "os");
180
+ if (now.isolation !== "none" || now.refusal !== undefined) {
181
+ throw new DeviceOpError("policy", SANDBOX_BACK_ON);
182
+ }
183
+ };
184
+ return this.host.exec(args, signal, { beforeSpawn });
185
+ }
186
+ async readFile(path, maxBytes) {
187
+ return (await this.files()).readFile(path, maxBytes);
188
+ }
189
+ async writeFile(path, data) {
190
+ return (await this.files()).writeFile(path, data);
191
+ }
192
+ async stat(path) {
193
+ return (await this.files()).stat(path);
194
+ }
195
+ async killTagged(tags) {
196
+ await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
197
+ }
198
+ async killAll() {
199
+ await Promise.all([this.sandboxed.killAll(), this.host.killAll()]);
200
+ }
201
+ ensureRoot() {
202
+ return this.sandboxed.ensureRoot();
203
+ }
204
+ /** The sandboxed executor's latest localhost proxy guard result (see `Executor`). */
205
+ proxyGuard() {
206
+ return this.sandboxed.proxyGuard?.() ?? { detected: false, reasons: [] };
207
+ }
208
+ /** Stops watching the policy. */
209
+ dispose() {
210
+ if (this.watch !== undefined)
211
+ clearInterval(this.watch);
212
+ this.watch = undefined;
213
+ }
214
+ }
@@ -1,13 +1,32 @@
1
- import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots, SandboxTier } from "@capybara-hq/plugin-sdk";
2
+ import type { ProxyGuardResult } from "../proxy-guard.js";
3
+ import type { Policy } from "../state.js";
4
+ /** How one command runs: its tier and whether it runs in the sandbox (see `exec/switch.ts`). */
5
+ export interface ExecIsolation {
6
+ tier: SandboxTier;
7
+ /** `none`: without a sandbox. */
8
+ isolation: "sandbox" | "none";
9
+ /** Set when the policy asks for no sandbox but the tiers do not allow it: the command is refused. */
10
+ refusal?: string;
11
+ }
12
+ /** Hooks of one command. */
13
+ export interface ExecHooks {
14
+ /**
15
+ * Called synchronously right before the command is spawned, after everything the executor
16
+ * awaits; throwing refuses the command (nothing is spawned) with that error.
17
+ */
18
+ beforeSpawn?: () => void;
19
+ }
2
20
  /** What runs the operations on this machine: the OS sandbox (os) or a container (docker). */
3
21
  export interface Executor {
4
22
  readonly mode: "os" | "docker";
5
23
  readonly roots: SandboxRoots;
6
24
  /**
7
25
  * Runs one command; `signal` aborting kills its whole process tree. An executor must not start
8
- * work on an already-aborted signal (the kernel cancelled the request).
26
+ * work on an already-aborted signal (the kernel cancelled the request). `hooks` are honoured by
27
+ * the executor that runs commands without a sandbox; others may ignore them.
9
28
  */
10
- exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
29
+ exec(args: DeviceExecArgs, signal: AbortSignal, hooks?: ExecHooks): Promise<ExecResult>;
11
30
  /** The file's bytes (at most `maxBytes`); null when it does not exist. */
12
31
  readFile(path: string, maxBytes: number): Promise<{
13
32
  data: Uint8Array;
@@ -26,6 +45,21 @@ export interface Executor {
26
45
  * before and has vanished; it is never recreated silently.
27
46
  */
28
47
  ensureRoot(): Promise<"ok" | "gone">;
48
+ /**
49
+ * OS mode: the latest localhost proxy guard result (a local forwarding proxy turns localhost
50
+ * off for `dev` / `open`, spec §5.2.3). Absent: none found.
51
+ */
52
+ proxyGuard?(): ProxyGuardResult;
53
+ /**
54
+ * OS mode, an executor that can run without a sandbox: records an exec's limits, also of one
55
+ * refused before it reaches the executor, so file operations follow the latest decision.
56
+ */
57
+ noteLimits?(limits: DeviceExecArgs["limits"]): void;
58
+ /**
59
+ * OS mode, an executor that can run without a sandbox: runs one command as `how` (decided by
60
+ * the caller on `policy`, and logged by it) says, instead of deciding again in {@link exec}.
61
+ */
62
+ execDecided?(args: DeviceExecArgs, signal: AbortSignal, how: ExecIsolation, policy: Policy): Promise<ExecResult>;
29
63
  }
30
64
  /** An executor failure with a protocol error kind (default `error`). */
31
65
  export declare class DeviceOpError extends Error {
@@ -0,0 +1,45 @@
1
+ import { type EgressLimits } from "./policy.js";
2
+ import type { Policy } from "./state.js";
3
+ /** What refused a host (spec §3). */
4
+ export type BlockedLayer = "device" | "org" | "address" | "unknown";
5
+ export interface BlockedHost {
6
+ host: string;
7
+ port: number;
8
+ layer: BlockedLayer;
9
+ }
10
+ /** At most this many blocked hosts are reported per command. */
11
+ export declare const MAX_BLOCKED_HOSTS = 20;
12
+ type Limits = EgressLimits;
13
+ /** The local policy fields that decide network access. */
14
+ type NetworkPolicy = Pick<Policy, "allowedDomains" | "tier">;
15
+ /**
16
+ * Parses one sandbox-runtime 0.0.81 violation line `deny network-outbound <host>:<port> (<reason>)`;
17
+ * undefined for other lines. IPv6 hosts arrive bracketed and are returned without the brackets.
18
+ */
19
+ export declare function parseNetworkViolation(line: string): {
20
+ host: string;
21
+ port: number;
22
+ reason: string;
23
+ } | undefined;
24
+ /**
25
+ * Whether `host` is a public DNS name a command may reach when nothing narrows it (device and org
26
+ * both open): never an IP literal, a single-label or internal name, or a wildcard.
27
+ */
28
+ export declare function isPublicName(host: string): boolean;
29
+ /**
30
+ * The layer that refused `host`: `address` (an IP literal, a name `validateAllowHost` refuses, or
31
+ * a resolved-address reason), `org` (not in the org's effective egress, or egress none; also when
32
+ * the device lacks it too), `device` (the org allows it, the local policy does not), else `unknown`.
33
+ */
34
+ export declare function classifyHost(host: string, reason: string, limits: Limits, policy: NetworkPolicy): BlockedLayer;
35
+ /** The refused hosts in `lines`, deduped by host (first port kept), at most {@link MAX_BLOCKED_HOSTS}. */
36
+ export declare function blockedHosts(lines: readonly string[], limits: Limits, policy: NetworkPolicy): BlockedHost[];
37
+ /** The stderr trailer of spec §9.2 (English, model-visible); "" for an empty list. */
38
+ export declare function networkTrailer(blocked: readonly BlockedHost[]): string;
39
+ /**
40
+ * The reason the sandbox's ask callback answers (spec §9.1). The callback has no command id, so
41
+ * `limits` are the last ones seen (a device belongs to one org); without any, the org layer is
42
+ * not judged.
43
+ */
44
+ export declare function denyReason(host: string, limits: Limits | undefined, policy: NetworkPolicy): string;
45
+ export {};