@capybara-hq/device 0.1.0-rc.5 → 0.1.0-rc.6
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 +34 -10
- package/dist/args.d.ts +5 -1
- package/dist/args.js +23 -2
- package/dist/cli.js +9 -2
- package/dist/commands/drain.d.ts +13 -0
- package/dist/commands/drain.js +28 -0
- package/dist/commands/service.d.ts +17 -3
- package/dist/commands/service.js +74 -9
- package/dist/exec/os.d.ts +18 -3
- package/dist/exec/os.js +50 -8
- package/dist/exec/reap.d.ts +41 -0
- package/dist/exec/reap.js +89 -0
- package/dist/exec/shared.js +5 -2
- package/dist/policy.d.ts +4 -0
- package/dist/policy.js +32 -7
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -21,7 +21,8 @@ the code to enter on any signed-in browser, where you pick the org and the devic
|
|
|
21
21
|
an existing connected one of yours) after reading what the program can do. Logging in again from
|
|
22
22
|
another machine into the same device replaces the first machine (its credential is revoked).
|
|
23
23
|
`stop` ends the running program, `drain` makes it accept no new commands and exit when the running
|
|
24
|
-
ones finish
|
|
24
|
+
ones finish (`drain --wait [--timeout <seconds>]` returns only once it has exited, at most 600 s by
|
|
25
|
+
default). `logout` stops a running program, then forgets the credential (the machine stays
|
|
25
26
|
connected on the platform until it is revoked there). Deleting the device in the web app
|
|
26
27
|
revokes the machine and stops the program; the files in the working directory stay on your machine.
|
|
27
28
|
|
|
@@ -43,7 +44,7 @@ the device page says so. To start afresh, run `capybara-device logout` and then
|
|
|
43
44
|
and the platform rebuilds the device on its next use.
|
|
44
45
|
|
|
45
46
|
Commands: `login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]`, `logout`,
|
|
46
|
-
`status [--json]`, `start`, `stop`, `drain`,
|
|
47
|
+
`status [--json]`, `start`, `stop`, `drain [--wait] [--timeout <seconds>]`,
|
|
47
48
|
`policy [show | set <key> <value> [--yes] | add|remove <key> <value>]` and
|
|
48
49
|
`service install|uninstall`.
|
|
49
50
|
|
|
@@ -78,6 +79,15 @@ Changes apply at the next command; a running program does not need a restart. `a
|
|
|
78
79
|
work on `allowedDomains` and `allowCredentials`; every domain must be a lowercase host name
|
|
79
80
|
(optionally `*.` for subdomains, never the apex), never an IP address or an internal name.
|
|
80
81
|
|
|
82
|
+
A command ends with everything it started: once it returns (or times out, or is stopped), the
|
|
83
|
+
program kills what it left running, such as `server &` or `nohup …`, because inside the sandbox no
|
|
84
|
+
later command may signal another command's processes. Its process group goes at once, and a process
|
|
85
|
+
that left the group (`setsid`) is found by the marker every process of the command carries. On
|
|
86
|
+
macOS only a background task launch (`Bash` with `run_in_background`, whose command starts with the
|
|
87
|
+
line `# capybara: background task launch`) keeps what it starts. On Linux the sandbox's pid
|
|
88
|
+
namespace already ends every process with its command. In Docker mode and without a sandbox, a
|
|
89
|
+
later command can stop what an earlier one left, so nothing is killed.
|
|
90
|
+
|
|
81
91
|
When a command is refused a domain, the program says why. Clients that print the proxy's answer
|
|
82
92
|
show a reason such as `capybara: files.slack.com is not in this device's allowed domains`, and
|
|
83
93
|
after the command its stderr ends with a trailer naming each refused host (at most 20) and who can
|
|
@@ -148,6 +158,16 @@ default) and loses the key at the next change; `start` says so at each start whi
|
|
|
148
158
|
|
|
149
159
|
#### Local servers, sockets and caches at `dev` and `open`
|
|
150
160
|
|
|
161
|
+
- **Git.** Commands may write `.git/config`, so `git init`, `git clone`, `git config`,
|
|
162
|
+
`git remote add` and branch tracking work. `.git/hooks` stays unwritable at every tier (a hook is
|
|
163
|
+
code that runs unsandboxed when you later run git in that folder yourself), and `GIT_TEMPLATE_DIR`
|
|
164
|
+
points at an empty, read-only `<dir>/git-template`, so init and clone copy no sample hooks. At
|
|
165
|
+
`strict`, `.git/config` stays unwritable too. Remaining risk: a `.git/config` a command wrote can
|
|
166
|
+
set `core.hooksPath`, `core.fsmonitor`, `core.sshCommand` or similar, which run when you later
|
|
167
|
+
run git in that repository on your own machine. Treat a repository a command created or
|
|
168
|
+
configured like any downloaded one (check `git config --local --list` before running git there),
|
|
169
|
+
or keep the device at `strict`.
|
|
170
|
+
|
|
151
171
|
- **Local servers (macOS).** Commands may listen on local ports (a dev server, a browser's
|
|
152
172
|
debugging port) and connect to this machine's localhost. That also reaches any local proxy that
|
|
153
173
|
forwards past the network allowlist (Clash and the like) or Docker's TCP API, so the program
|
|
@@ -179,12 +199,13 @@ default) and loses the key at the next change; `start` says so at each start whi
|
|
|
179
199
|
including the host daemons' (Docker, D-Bus, ssh-agent). Allowing them with the daemons' sockets
|
|
180
200
|
masked is planned after a spike that proves them unreachable; it has not been done yet. Use
|
|
181
201
|
Docker mode for browsers on Linux.
|
|
182
|
-
- **Package caches.** `XDG_CACHE_HOME`, `npm_config_cache`, `
|
|
183
|
-
`
|
|
184
|
-
`MAVEN_OPTS` (`-Dmaven.repo.local`), `PLAYWRIGHT_BROWSERS_PATH` and `COREPACK_HOME` point at
|
|
202
|
+
- **Package caches.** `XDG_CACHE_HOME`, `npm_config_cache`, `PIP_CACHE_DIR`, `UV_CACHE_DIR`,
|
|
203
|
+
`CARGO_HOME`, `GOMODCACHE`, `GOCACHE`, `GRADLE_USER_HOME`, `MAVEN_OPTS` (`-Dmaven.repo.local`), `PLAYWRIGHT_BROWSERS_PATH` and `COREPACK_HOME` point at
|
|
185
204
|
folders of `<dir>/cache/`, kept across commands. Your own `~/.npm`, `~/.cache` and pnpm store stay
|
|
186
205
|
read only, so a sandboxed command cannot poison your own builds. A command that sets one of
|
|
187
|
-
these variables itself keeps its value.
|
|
206
|
+
these variables itself keeps its value. pnpm's store is not redirected (pnpm reads it only from
|
|
207
|
+
`npm_config_store_dir`, which makes npm warn on every command): it stays at pnpm's default under
|
|
208
|
+
the command's HOME, the workspace.
|
|
188
209
|
|
|
189
210
|
### Running without a sandbox
|
|
190
211
|
|
|
@@ -254,10 +275,10 @@ Limits to know: the platform's `Grep` tool assumes GNU grep, so on macOS (BSD gr
|
|
|
254
275
|
Grep options behave differently or fail. Docker mode (a Linux container) does not have this issue.
|
|
255
276
|
|
|
256
277
|
Not enforced yet in OS mode: the `cpu` and `memoryMb` ceilings, and `allowCredentials` (commands
|
|
257
|
-
get no local credentials at all). Processes a command leaves running are killed
|
|
278
|
+
get no local credentials at all). Processes a command leaves running are killed when it ends;
|
|
258
279
|
on macOS a child that leaves the command's process group and runs only Apple system binaries
|
|
259
|
-
cannot be found
|
|
260
|
-
down with it).
|
|
280
|
+
cannot be found by its marker (`ps -E` hides their environment), so it survives (Linux runs each
|
|
281
|
+
command in its own pid namespace, which takes every child down with it).
|
|
261
282
|
|
|
262
283
|
## Docker mode
|
|
263
284
|
|
|
@@ -291,4 +312,7 @@ program when it exits non-zero (systemd after 5 s) and leave it stopped after a
|
|
|
291
312
|
while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
|
|
292
313
|
running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
|
|
293
314
|
starts. The service runs `node <bin> start` with the `PATH` of the shell that installed it (so
|
|
294
|
-
`docker` is found). `service uninstall` reverses it.
|
|
315
|
+
`docker` is found). `service uninstall` reverses it. On macOS, installing again first boots the old
|
|
316
|
+
agent out and waits (up to 10 s) until launchd has let it go, because `launchctl bootout` returns
|
|
317
|
+
before that; a `bootstrap` that still fails with error 5 (Input/output error) is retried a few
|
|
318
|
+
times. On Linux, installing again restarts the unit so the new file applies.
|
package/dist/args.d.ts
CHANGED
|
@@ -17,6 +17,10 @@ export type Command = {
|
|
|
17
17
|
command: "stop";
|
|
18
18
|
} | {
|
|
19
19
|
command: "drain";
|
|
20
|
+
/** `--wait`: wait until the program has exited. */
|
|
21
|
+
wait?: true;
|
|
22
|
+
/** `--timeout <seconds>` with `--wait` (default 600). */
|
|
23
|
+
timeoutSeconds?: number;
|
|
20
24
|
} | {
|
|
21
25
|
command: "policy";
|
|
22
26
|
action: "show";
|
|
@@ -33,7 +37,7 @@ export type Command = {
|
|
|
33
37
|
} | {
|
|
34
38
|
command: "help";
|
|
35
39
|
};
|
|
36
|
-
export declare const USAGE = "Usage:\n capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]\n Connect this machine: approve the code in the browser\n capybara-device logout Forget the credential on this machine\n capybara-device status [--json] Show whether this machine is logged in\n capybara-device start Connect and serve the device\n capybara-device stop Stop the running program\n capybara-device drain
|
|
40
|
+
export declare const USAGE = "Usage:\n capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]\n Connect this machine: approve the code in the browser\n capybara-device logout Forget the credential on this machine\n capybara-device status [--json] Show whether this machine is logged in\n capybara-device start Connect and serve the device\n capybara-device stop Stop the running program\n capybara-device drain [--wait] [--timeout <seconds>]\n Finish running commands, accept no new ones, then stop;\n --wait returns once it has stopped (default limit 600 s)\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n Replace one field (applies at the next command)\n capybara-device policy set tier strict|dev|open|default [--yes]\n Choose the sandbox tier (default: follow the organization)\n capybara-device policy set isolation sandbox|none [--yes]\n none: at tier open, run commands without a sandbox (OS mode)\n capybara-device policy set localhost auto|allow\n allow: reach localhost at tier dev or open despite a local proxy\n capybara-device policy set remoteGrants owner|off\n Let the device owner widen the network from the web, or not\n capybara-device policy add|remove allowedDomains <host>\n Allow or stop allowing a domain (applies at the next command)\n capybara-device service install|uninstall\n Run at login as a user service";
|
|
37
41
|
/** Thrown for a bad command line; the message is shown with the usage. */
|
|
38
42
|
export declare class UsageError extends Error {
|
|
39
43
|
}
|
package/dist/args.js
CHANGED
|
@@ -6,7 +6,9 @@ export const USAGE = `Usage:
|
|
|
6
6
|
capybara-device status [--json] Show whether this machine is logged in
|
|
7
7
|
capybara-device start Connect and serve the device
|
|
8
8
|
capybara-device stop Stop the running program
|
|
9
|
-
capybara-device drain
|
|
9
|
+
capybara-device drain [--wait] [--timeout <seconds>]
|
|
10
|
+
Finish running commands, accept no new ones, then stop;
|
|
11
|
+
--wait returns once it has stopped (default limit 600 s)
|
|
10
12
|
capybara-device policy [show] Show the local policy
|
|
11
13
|
capybara-device policy set <key> <value>
|
|
12
14
|
Replace one field (applies at the next command)
|
|
@@ -77,8 +79,27 @@ export function parseCommandLine(argv) {
|
|
|
77
79
|
case "logout":
|
|
78
80
|
case "start":
|
|
79
81
|
case "stop":
|
|
80
|
-
case "drain":
|
|
81
82
|
return noArgs(name);
|
|
83
|
+
case "drain": {
|
|
84
|
+
const { values, positionals } = parse(rest, {
|
|
85
|
+
wait: { type: "boolean" },
|
|
86
|
+
timeout: { type: "string" },
|
|
87
|
+
});
|
|
88
|
+
if (positionals.length > 0)
|
|
89
|
+
throw new UsageError("drain takes no positional arguments");
|
|
90
|
+
if (values.timeout !== undefined && values.wait !== true) {
|
|
91
|
+
throw new UsageError("--timeout needs --wait");
|
|
92
|
+
}
|
|
93
|
+
if (values.wait !== true)
|
|
94
|
+
return { command: "drain" };
|
|
95
|
+
if (values.timeout === undefined)
|
|
96
|
+
return { command: "drain", wait: true };
|
|
97
|
+
const seconds = Number(values.timeout);
|
|
98
|
+
if (!Number.isInteger(seconds) || seconds < 1) {
|
|
99
|
+
throw new UsageError("--timeout must be a whole number of seconds, at least 1");
|
|
100
|
+
}
|
|
101
|
+
return { command: "drain", wait: true, timeoutSeconds: seconds };
|
|
102
|
+
}
|
|
82
103
|
case "policy": {
|
|
83
104
|
const { values, positionals } = parse(rest, { yes: { type: "boolean", short: "y" } });
|
|
84
105
|
const yes = values.yes === true;
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
2
|
import { parseCommandLine, USAGE, UsageError } from "./args.js";
|
|
3
|
-
import { drain } from "./commands/drain.js";
|
|
3
|
+
import { drain, drainAndWait } from "./commands/drain.js";
|
|
4
4
|
import { login } from "./commands/login.js";
|
|
5
5
|
import { logout } from "./commands/logout.js";
|
|
6
6
|
import { confirmRisk, isolationRefusal, needsConfirmation, policyCommand, policyRisk, } from "./commands/policy.js";
|
|
@@ -111,7 +111,13 @@ export async function runCli(argv, io = {}) {
|
|
|
111
111
|
case "stop":
|
|
112
112
|
return stop(dir, out, err, io.kill);
|
|
113
113
|
case "drain":
|
|
114
|
-
|
|
114
|
+
if (cmd.wait !== true)
|
|
115
|
+
return drain(dir, out, err, io.kill);
|
|
116
|
+
return drainAndWait(dir, out, err, {
|
|
117
|
+
...(io.kill && { kill: io.kill }),
|
|
118
|
+
...(io.sleep && { sleep: io.sleep }),
|
|
119
|
+
...(cmd.timeoutSeconds !== undefined && { timeoutMs: cmd.timeoutSeconds * 1000 }),
|
|
120
|
+
});
|
|
115
121
|
case "policy": {
|
|
116
122
|
// `set isolation none` that cannot apply (Docker mode, no local tier open): refused before
|
|
117
123
|
// any risk text or question (policyCommand refuses it too, under the lock).
|
|
@@ -140,6 +146,7 @@ export async function runCli(argv, io = {}) {
|
|
|
140
146
|
out,
|
|
141
147
|
err,
|
|
142
148
|
...(io.runSystem && { run: io.runSystem }),
|
|
149
|
+
...(io.sleep && { sleep: io.sleep }),
|
|
143
150
|
});
|
|
144
151
|
}
|
|
145
152
|
}
|
package/dist/commands/drain.d.ts
CHANGED
|
@@ -1,2 +1,15 @@
|
|
|
1
|
+
/** How often `drain --wait` checks whether the program has exited. */
|
|
2
|
+
export declare const DRAIN_POLL_MS = 500;
|
|
3
|
+
/** How long `drain --wait` waits by default (commands may run long). */
|
|
4
|
+
export declare const DRAIN_WAIT_DEFAULT_SECONDS = 600;
|
|
1
5
|
/** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
|
|
2
6
|
export declare function drain(stateDir: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill): number;
|
|
7
|
+
/**
|
|
8
|
+
* `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
|
|
9
|
+
* finished), at most `timeoutMs`. Exit code 1 when it still runs then.
|
|
10
|
+
*/
|
|
11
|
+
export declare function drainAndWait(stateDir: string, out: (line: string) => void, err: (line: string) => void, o?: {
|
|
12
|
+
kill?: typeof process.kill;
|
|
13
|
+
sleep?: (ms: number) => Promise<void>;
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}): Promise<number>;
|
package/dist/commands/drain.js
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
|
+
import { isAlive, readRunningPid } from "../pid.js";
|
|
1
2
|
import { signalRunning } from "./signal.js";
|
|
3
|
+
/** How often `drain --wait` checks whether the program has exited. */
|
|
4
|
+
export const DRAIN_POLL_MS = 500;
|
|
5
|
+
/** How long `drain --wait` waits by default (commands may run long). */
|
|
6
|
+
export const DRAIN_WAIT_DEFAULT_SECONDS = 600;
|
|
2
7
|
/** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
|
|
3
8
|
export function drain(stateDir, out, err, kill) {
|
|
4
9
|
return signalRunning(stateDir, "SIGUSR2", "Draining capybara-device.", out, err, kill);
|
|
5
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
|
|
13
|
+
* finished), at most `timeoutMs`. Exit code 1 when it still runs then.
|
|
14
|
+
*/
|
|
15
|
+
export async function drainAndWait(stateDir, out, err, o = {}) {
|
|
16
|
+
const kill = o.kill ?? process.kill;
|
|
17
|
+
const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
18
|
+
const timeoutMs = o.timeoutMs ?? DRAIN_WAIT_DEFAULT_SECONDS * 1000;
|
|
19
|
+
const pid = readRunningPid(stateDir, kill);
|
|
20
|
+
const code = drain(stateDir, out, err, kill);
|
|
21
|
+
if (code !== 0 || pid === undefined)
|
|
22
|
+
return code;
|
|
23
|
+
for (let waited = 0; isAlive(pid, kill); waited += DRAIN_POLL_MS) {
|
|
24
|
+
if (waited >= timeoutMs) {
|
|
25
|
+
err(`capybara-device (pid ${pid}) is still draining after ${Math.round(timeoutMs / 1000)} s: ` +
|
|
26
|
+
"commands are still running. Wait longer with drain --wait, or stop it now with stop.");
|
|
27
|
+
return 1;
|
|
28
|
+
}
|
|
29
|
+
await sleep(Math.min(DRAIN_POLL_MS, timeoutMs - waited));
|
|
30
|
+
}
|
|
31
|
+
out("capybara-device has stopped.");
|
|
32
|
+
return 0;
|
|
33
|
+
}
|
|
@@ -5,13 +5,27 @@ export interface ServiceDeps {
|
|
|
5
5
|
env: Record<string, string | undefined>;
|
|
6
6
|
out: (line: string) => void;
|
|
7
7
|
err: (line: string) => void;
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* Runs a system command; throws when it fails (default: execFileSync, whose error carries the
|
|
10
|
+
* exit `status` and `stderr`).
|
|
11
|
+
*/
|
|
9
12
|
run?: (cmd: string, args: string[]) => void;
|
|
13
|
+
/** Waits between launchctl checks (default: setTimeout). */
|
|
14
|
+
sleep?: (ms: number) => Promise<void>;
|
|
10
15
|
uid?: number;
|
|
11
16
|
nodePath?: string;
|
|
12
17
|
binPath?: string;
|
|
13
18
|
}
|
|
14
19
|
/** What the service needs from the installing shell: PATH (docker lives there) and the state dir. */
|
|
15
20
|
export declare function serviceEnv(env: Record<string, string | undefined>): Record<string, string>;
|
|
16
|
-
/**
|
|
17
|
-
export declare
|
|
21
|
+
/** How often launchctl is asked whether the old service is gone. */
|
|
22
|
+
export declare const SERVICE_POLL_MS = 200;
|
|
23
|
+
/** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
|
|
24
|
+
export declare const SERVICE_GONE_TIMEOUT_MS = 10000;
|
|
25
|
+
/** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
|
|
26
|
+
export declare const BOOTSTRAP_BACKOFF_MS: readonly [500, 1000, 2000];
|
|
27
|
+
/**
|
|
28
|
+
* `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd
|
|
29
|
+
* user).
|
|
30
|
+
*/
|
|
31
|
+
export declare function serviceCommand(action: "install" | "uninstall", deps: ServiceDeps): Promise<number>;
|
package/dist/commands/service.js
CHANGED
|
@@ -21,8 +21,17 @@ export function serviceEnv(env) {
|
|
|
21
21
|
out.XDG_CONFIG_HOME = xdg;
|
|
22
22
|
return out;
|
|
23
23
|
}
|
|
24
|
-
/**
|
|
25
|
-
export
|
|
24
|
+
/** How often launchctl is asked whether the old service is gone. */
|
|
25
|
+
export const SERVICE_POLL_MS = 200;
|
|
26
|
+
/** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
|
|
27
|
+
export const SERVICE_GONE_TIMEOUT_MS = 10_000;
|
|
28
|
+
/** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
|
|
29
|
+
export const BOOTSTRAP_BACKOFF_MS = [500, 1000, 2000];
|
|
30
|
+
/**
|
|
31
|
+
* `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd
|
|
32
|
+
* user).
|
|
33
|
+
*/
|
|
34
|
+
export async function serviceCommand(action, deps) {
|
|
26
35
|
const run = deps.run ?? defaultRun;
|
|
27
36
|
const spec = {
|
|
28
37
|
nodePath: deps.nodePath ?? process.execPath,
|
|
@@ -32,7 +41,7 @@ export function serviceCommand(action, deps) {
|
|
|
32
41
|
};
|
|
33
42
|
try {
|
|
34
43
|
if (deps.platform === "darwin")
|
|
35
|
-
return launchd(action, spec, deps, run);
|
|
44
|
+
return await launchd(action, spec, deps, run);
|
|
36
45
|
if (deps.platform === "linux")
|
|
37
46
|
return systemd(action, spec, deps, run);
|
|
38
47
|
}
|
|
@@ -43,9 +52,24 @@ export function serviceCommand(action, deps) {
|
|
|
43
52
|
deps.err("capybara-device service needs macOS (launchd) or Linux (systemd).");
|
|
44
53
|
return 1;
|
|
45
54
|
}
|
|
46
|
-
|
|
55
|
+
/** The text launchctl printed for a failed call (its stderr, else the error message). */
|
|
56
|
+
function failureText(e) {
|
|
57
|
+
const stderr = e.stderr;
|
|
58
|
+
const text = stderr instanceof Uint8Array || typeof stderr === "string" ? String(stderr).trim() : "";
|
|
59
|
+
return text !== "" ? text : e instanceof Error ? e.message : String(e);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* `launchctl bootstrap` failed with error 5 (Input/output error): typically the previous instance
|
|
63
|
+
* of the service is still being booted out.
|
|
64
|
+
*/
|
|
65
|
+
function isBootstrapIoError(e) {
|
|
66
|
+
return e.status === 5 || /Bootstrap failed: 5:/.test(failureText(e));
|
|
67
|
+
}
|
|
68
|
+
async function launchd(action, spec, deps, run) {
|
|
47
69
|
const file = plistPath(deps.home);
|
|
48
70
|
const domain = `gui/${deps.uid ?? process.getuid?.() ?? 501}`;
|
|
71
|
+
const service = `${domain}/${LAUNCHD_LABEL}`;
|
|
72
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
49
73
|
const tryRun = (args) => {
|
|
50
74
|
try {
|
|
51
75
|
run("launchctl", args);
|
|
@@ -54,17 +78,55 @@ function launchd(action, spec, deps, run) {
|
|
|
54
78
|
// Not loaded yet / already gone.
|
|
55
79
|
}
|
|
56
80
|
};
|
|
81
|
+
/** Whether launchd still knows the service (`launchctl print` fails once it is gone). */
|
|
82
|
+
const loaded = () => {
|
|
83
|
+
try {
|
|
84
|
+
run("launchctl", ["print", service]);
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
/** Boots the service out and waits until launchd has let it go (bootout returns before that). */
|
|
92
|
+
const bootout = async () => {
|
|
93
|
+
tryRun(["bootout", service]);
|
|
94
|
+
for (let waited = 0; loaded(); waited += SERVICE_POLL_MS) {
|
|
95
|
+
// Gave up: bootstrap's retries cover what is left.
|
|
96
|
+
if (waited >= SERVICE_GONE_TIMEOUT_MS)
|
|
97
|
+
return;
|
|
98
|
+
await sleep(SERVICE_POLL_MS);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
57
101
|
if (action === "install") {
|
|
58
102
|
mkdirSync(dirname(file), { recursive: true });
|
|
59
103
|
mkdirSync(spec.stateDir, { recursive: true });
|
|
60
|
-
if (existsSync(file))
|
|
61
|
-
|
|
104
|
+
if (existsSync(file) || loaded())
|
|
105
|
+
await bootout();
|
|
62
106
|
writeFileSync(file, plistContent(spec));
|
|
63
|
-
|
|
107
|
+
for (let attempt = 0;; attempt++) {
|
|
108
|
+
try {
|
|
109
|
+
run("launchctl", ["bootstrap", domain, file]);
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
if (!isBootstrapIoError(e))
|
|
114
|
+
throw e;
|
|
115
|
+
const backoff = BOOTSTRAP_BACKOFF_MS[attempt];
|
|
116
|
+
if (backoff === undefined) {
|
|
117
|
+
deps.err(`capybara-device service install failed: launchctl bootstrap failed ${attempt + 1} times (${failureText(e)}). ` +
|
|
118
|
+
`The previous capybara-device service may still be stopping: wait a few seconds and run capybara-device service install again. ` +
|
|
119
|
+
`launchctl print ${service} shows what launchd knows of it.`);
|
|
120
|
+
return 1;
|
|
121
|
+
}
|
|
122
|
+
await sleep(backoff);
|
|
123
|
+
await bootout();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
64
126
|
deps.out(`Installed ${file}; capybara-device now starts at login.`);
|
|
65
127
|
return 0;
|
|
66
128
|
}
|
|
67
|
-
|
|
129
|
+
await bootout();
|
|
68
130
|
rmSync(file, { force: true });
|
|
69
131
|
deps.out("Removed the capybara-device login service.");
|
|
70
132
|
return 0;
|
|
@@ -75,7 +137,10 @@ function systemd(action, spec, deps, run) {
|
|
|
75
137
|
mkdirSync(dirname(file), { recursive: true });
|
|
76
138
|
writeFileSync(file, unitContent(spec));
|
|
77
139
|
run("systemctl", ["--user", "daemon-reload"]);
|
|
78
|
-
run("systemctl", ["--user", "enable",
|
|
140
|
+
run("systemctl", ["--user", "enable", SYSTEMD_UNIT]);
|
|
141
|
+
// restart, not start: a unit already running (an earlier install) picks up the new file.
|
|
142
|
+
// systemctl waits for the stop and start jobs, so nothing is left in flight.
|
|
143
|
+
run("systemctl", ["--user", "restart", SYSTEMD_UNIT]);
|
|
79
144
|
deps.out(`Installed ${file}; capybara-device now starts at login. A user unit runs only while you have a session unless you run: loginctl enable-linger $USER`);
|
|
80
145
|
return 0;
|
|
81
146
|
}
|
package/dist/exec/os.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { type SandboxAskCallback, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
|
|
2
|
-
import type
|
|
2
|
+
import { type DeviceExecArgs, type ExecResult, type SandboxRoots, type SandboxTier } from "@capybara-hq/plugin-sdk";
|
|
3
3
|
import { type TierFacts } from "../policy.js";
|
|
4
4
|
import { type ProxyGuardResult } from "../proxy-guard.js";
|
|
5
5
|
import type { Policy } from "../state.js";
|
|
6
|
+
import { type ReaperDeps } from "./reap.js";
|
|
6
7
|
import { type Executor } from "./types.js";
|
|
7
8
|
export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
|
|
8
9
|
/** Whether the OS sandbox can run here, and why not. */
|
|
@@ -25,6 +26,8 @@ export interface OsExecutorOptions {
|
|
|
25
26
|
detectProxy?: () => Promise<ProxyGuardResult>;
|
|
26
27
|
/** Where the macOS short socket directory is made (default `/private/tmp`). */
|
|
27
28
|
socketBase?: string;
|
|
29
|
+
/** The reaper's process operations (default: the real ones); injectable for tests. */
|
|
30
|
+
reaper?: Partial<ReaperDeps>;
|
|
28
31
|
}
|
|
29
32
|
/**
|
|
30
33
|
* Runs every command inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux bubblewrap):
|
|
@@ -38,10 +41,12 @@ export declare class OsExecutor implements Executor {
|
|
|
38
41
|
readonly mode: "os";
|
|
39
42
|
readonly roots: SandboxRoots;
|
|
40
43
|
private readonly dir;
|
|
41
|
-
/** Marks every process of this device's commands: `<dirKey>.<tag>`. */
|
|
44
|
+
/** Marks every process of this device's commands: `<dirKey>.<tag>.<exec id>`. */
|
|
42
45
|
private readonly dirKey;
|
|
43
46
|
private readonly groups;
|
|
44
47
|
private pruneTimer;
|
|
48
|
+
/** Kills what a foreground exec left running once it ends. */
|
|
49
|
+
private readonly reaper;
|
|
45
50
|
private readonly guard;
|
|
46
51
|
private readonly files;
|
|
47
52
|
/**
|
|
@@ -109,8 +114,18 @@ export declare class OsExecutor implements Executor {
|
|
|
109
114
|
readonly askCallback: SandboxAskCallback;
|
|
110
115
|
/** The classified network refusals of one command (read before it unregisters). */
|
|
111
116
|
private blockedFor;
|
|
112
|
-
/**
|
|
117
|
+
/**
|
|
118
|
+
* `<dir>/git-template`, an empty directory commands can read but not write (it is outside the
|
|
119
|
+
* roots), made on demand; undefined when it cannot be made.
|
|
120
|
+
*/
|
|
121
|
+
private gitTemplate;
|
|
122
|
+
/**
|
|
123
|
+
* The marker value of a tag's processes. An exec's processes carry `<this>.<exec id>` (see
|
|
124
|
+
* {@link execMarker}); {@link killTagged} matches both.
|
|
125
|
+
*/
|
|
113
126
|
markerOf(tag: string): string;
|
|
127
|
+
/** The marker value of one exec's processes: its tag's plus an id of its own (no dots in a tag). */
|
|
128
|
+
private execMarker;
|
|
114
129
|
/**
|
|
115
130
|
* Wraps `script` (run by bash inside the sandbox, after the request's `env` and TMPDIR are
|
|
116
131
|
* exported) and spawns it as the leader of a new process group.
|
package/dist/exec/os.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
-
import { existsSync, realpathSync } from "node:fs";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
4
4
|
import { homedir, constants as osConstants } from "node:os";
|
|
5
|
-
import { resolve } from "node:path";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
6
|
import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
|
|
7
|
+
import { isBackgroundLaunch, } from "@capybara-hq/plugin-sdk";
|
|
7
8
|
import { blockedHosts, denyReason, isPublicName, networkTrailer, } from "../network.js";
|
|
8
9
|
import { ANY_HOST, deviceTier, effectiveEgress, grantedHosts, srtConfig, tierFacts, } from "../policy.js";
|
|
9
10
|
import { detectLocalProxy, PROXY_GUARD_TTL_MS } from "../proxy-guard.js";
|
|
10
11
|
import { FS_HELPER_SCRIPT } from "./fs-helper.js";
|
|
11
12
|
import { EXEC_MARKER, killMarked } from "./procs.js";
|
|
13
|
+
import { Reaper } from "./reap.js";
|
|
12
14
|
import { cacheEnv, cacheRoot, ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, prepareSocketDir, RootGuard, shellQuote, socketDirPath, toolHomeEnv, } from "./shared.js";
|
|
13
15
|
import { DeviceOpError } from "./types.js";
|
|
14
16
|
export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
|
|
@@ -69,10 +71,12 @@ export class OsExecutor {
|
|
|
69
71
|
mode = "os";
|
|
70
72
|
roots;
|
|
71
73
|
dir;
|
|
72
|
-
/** Marks every process of this device's commands: `<dirKey>.<tag>`. */
|
|
74
|
+
/** Marks every process of this device's commands: `<dirKey>.<tag>.<exec id>`. */
|
|
73
75
|
dirKey;
|
|
74
76
|
groups = new Set();
|
|
75
77
|
pruneTimer;
|
|
78
|
+
/** Kills what a foreground exec left running once it ends. */
|
|
79
|
+
reaper;
|
|
76
80
|
guard;
|
|
77
81
|
files;
|
|
78
82
|
/**
|
|
@@ -97,6 +101,7 @@ export class OsExecutor {
|
|
|
97
101
|
openCommands = new Set();
|
|
98
102
|
constructor(opts) {
|
|
99
103
|
this.opts = opts;
|
|
104
|
+
this.reaper = new Reaper(opts.reaper);
|
|
100
105
|
const dir = resolve(opts.dir);
|
|
101
106
|
// The roots are reported as real paths, so what commands print matches what the kernel sends.
|
|
102
107
|
this.dir = existsSync(dir) ? realpathSync(dir) : dir;
|
|
@@ -214,10 +219,31 @@ export class OsExecutor {
|
|
|
214
219
|
.map((v) => v.line);
|
|
215
220
|
return blockedHosts(lines, limits, policy);
|
|
216
221
|
}
|
|
217
|
-
/**
|
|
222
|
+
/**
|
|
223
|
+
* `<dir>/git-template`, an empty directory commands can read but not write (it is outside the
|
|
224
|
+
* roots), made on demand; undefined when it cannot be made.
|
|
225
|
+
*/
|
|
226
|
+
gitTemplate() {
|
|
227
|
+
const path = join(this.dir, "git-template");
|
|
228
|
+
try {
|
|
229
|
+
mkdirSync(path, { recursive: true, mode: 0o755 });
|
|
230
|
+
return lstatSync(path).isDirectory() ? path : undefined;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* The marker value of a tag's processes. An exec's processes carry `<this>.<exec id>` (see
|
|
238
|
+
* {@link execMarker}); {@link killTagged} matches both.
|
|
239
|
+
*/
|
|
218
240
|
markerOf(tag) {
|
|
219
241
|
return `${this.dirKey}.${tag}`;
|
|
220
242
|
}
|
|
243
|
+
/** The marker value of one exec's processes: its tag's plus an id of its own (no dots in a tag). */
|
|
244
|
+
execMarker(tag) {
|
|
245
|
+
return `${this.markerOf(tag)}.${randomBytes(8).toString("hex")}`;
|
|
246
|
+
}
|
|
221
247
|
/**
|
|
222
248
|
* Wraps `script` (run by bash inside the sandbox, after the request's `env` and TMPDIR are
|
|
223
249
|
* exported) and spawns it as the leader of a new process group.
|
|
@@ -231,6 +257,7 @@ export class OsExecutor {
|
|
|
231
257
|
this.prepareSocketDir();
|
|
232
258
|
// dev / open on macOS: the short socket directory, where unix sockets are allowed.
|
|
233
259
|
const tmp = dev && this.socketDir !== undefined ? this.socketDir : this.roots.tmp;
|
|
260
|
+
const gitTemplate = dev ? this.gitTemplate() : undefined;
|
|
234
261
|
const inner = {
|
|
235
262
|
// The user's PATH applies inside the sandbox only (the wrapper runs with OUTER_ENV).
|
|
236
263
|
PATH: process.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
|
|
@@ -244,12 +271,14 @@ export class OsExecutor {
|
|
|
244
271
|
...toolHomeEnv(this.opts.home ?? homedir()),
|
|
245
272
|
// dev / open: package caches under <dir>/cache; the command's own values win.
|
|
246
273
|
...(dev && cacheEnv(this.cacheDir, { create: true })),
|
|
274
|
+
// dev / open may write .git/config but never .git/hooks: init and clone copy no sample hooks.
|
|
275
|
+
...(dev && gitTemplate !== undefined && { GIT_TEMPLATE_DIR: gitTemplate }),
|
|
247
276
|
...o.env,
|
|
248
277
|
// The runtime points TMPDIR at its own /tmp/claude (denied by the config): use ours.
|
|
249
278
|
TMPDIR: tmp,
|
|
250
279
|
// Chromium on macOS ignores TMPDIR and reads this instead (its singleton socket).
|
|
251
280
|
...(process.platform === "darwin" && { MAC_CHROMIUM_TMPDIR: tmp }),
|
|
252
|
-
[EXEC_MARKER]:
|
|
281
|
+
[EXEC_MARKER]: o.marker,
|
|
253
282
|
};
|
|
254
283
|
for (const [k, v] of Object.entries(inner)) {
|
|
255
284
|
if (!ENV_NAME_RE.test(k))
|
|
@@ -333,10 +362,13 @@ export class OsExecutor {
|
|
|
333
362
|
allowedDomains: [...policy.allowedDomains, ...grantedHosts(policy, args.limits, args.grants)],
|
|
334
363
|
};
|
|
335
364
|
const egress = effectiveEgress(policy, args.limits, args.grants);
|
|
365
|
+
const marker = this.execMarker(args.tag);
|
|
366
|
+
// A background task launch detaches the task on purpose: what it leaves running stays.
|
|
367
|
+
const reap = !isBackgroundLaunch(args.command);
|
|
336
368
|
const { child, commandId } = await this.spawnSandboxed(args.command, {
|
|
337
369
|
cwd,
|
|
338
370
|
...(args.env !== undefined && { env: args.env }),
|
|
339
|
-
|
|
371
|
+
marker,
|
|
340
372
|
egress,
|
|
341
373
|
policy,
|
|
342
374
|
tier: deviceTier(policy, args.limits),
|
|
@@ -433,6 +465,11 @@ export class OsExecutor {
|
|
|
433
465
|
exit = { code, sig };
|
|
434
466
|
if (group)
|
|
435
467
|
group.exited = true;
|
|
468
|
+
// The call is over (exit, timeout or abort): nothing it started may outlive it, because no
|
|
469
|
+
// later command can stop it (the sandbox lets no command signal another's processes).
|
|
470
|
+
// Its group goes before the result; processes that left the group soon after.
|
|
471
|
+
if (group && reap)
|
|
472
|
+
void this.reaper.reap(group.pgid, marker);
|
|
436
473
|
// A background child may hold the pipes open; do not wait for it past a short grace.
|
|
437
474
|
grace = setTimeout(finish, PIPE_GRACE_MS);
|
|
438
475
|
});
|
|
@@ -455,7 +492,7 @@ export class OsExecutor {
|
|
|
455
492
|
.join(" ");
|
|
456
493
|
const { child, commandId } = await this.spawnSandboxed(script, {
|
|
457
494
|
cwd: this.roots.workspace,
|
|
458
|
-
|
|
495
|
+
marker: this.markerOf("fs-helper"),
|
|
459
496
|
egress: [],
|
|
460
497
|
policy: this.opts.policy(),
|
|
461
498
|
tier: this.tier(),
|
|
@@ -529,7 +566,12 @@ export class OsExecutor {
|
|
|
529
566
|
if (want.has(g.tag))
|
|
530
567
|
this.killGroup(g);
|
|
531
568
|
const values = new Set(tags.map((t) => this.markerOf(t)));
|
|
532
|
-
|
|
569
|
+
// `<dirKey>.<tag>` or an exec's `<dirKey>.<tag>.<id>`: a tag has no dot, so `ab` never
|
|
570
|
+
// matches `ab-cd`'s processes.
|
|
571
|
+
await killMarked((v) => {
|
|
572
|
+
const dot = v.indexOf(".", this.dirKey.length + 1);
|
|
573
|
+
return values.has(dot < 0 ? v : v.slice(0, dot));
|
|
574
|
+
});
|
|
533
575
|
}
|
|
534
576
|
async killAll() {
|
|
535
577
|
for (const g of [...this.groups])
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The most scans one batch of reaps makes while it still finds processes. */
|
|
2
|
+
export declare const REAP_ROUNDS = 3;
|
|
3
|
+
export interface ReaperDeps {
|
|
4
|
+
/** SIGKILLs a process group; false when it no longer exists. */
|
|
5
|
+
killGroup: (pgid: number) => boolean;
|
|
6
|
+
/** The pids of this user's processes whose marker value `match` accepts (see `procs.ts`). */
|
|
7
|
+
findMarked: (match: (value: string) => boolean) => Promise<number[]>;
|
|
8
|
+
/** SIGKILLs one process and the process group it leads, if any. */
|
|
9
|
+
killPid: (pid: number) => void;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Kills what a foreground exec left running once it ended (normal exit, timeout or abort). Inside
|
|
13
|
+
* the OS sandbox a command can neither list nor signal the processes another command started, so
|
|
14
|
+
* a `sleep 300 &` or `nohup server &` left behind could otherwise be stopped by nobody.
|
|
15
|
+
*
|
|
16
|
+
* The exec's process group goes at once (a `&` or `nohup` child stays in it). A process that left
|
|
17
|
+
* the group (`setsid`, a detached spawn) is found by the exec's own marker value, which every
|
|
18
|
+
* process it starts inherits; listing processes is slow on macOS (`ps -E`), so that part runs
|
|
19
|
+
* after the result and reaps that arrive meanwhile share one scan. On macOS `ps -E` hides the
|
|
20
|
+
* environment of Apple platform binaries, so it is best effort there (the group covers the rest).
|
|
21
|
+
* Background task launches are not reaped at all (`isBackgroundLaunch`): they detach on purpose.
|
|
22
|
+
*/
|
|
23
|
+
export declare class Reaper {
|
|
24
|
+
private readonly deps;
|
|
25
|
+
/** Markers whose processes the next scan kills. */
|
|
26
|
+
private readonly pending;
|
|
27
|
+
/** The queued scan (not started yet), which every new reap joins. */
|
|
28
|
+
private next;
|
|
29
|
+
/** The scan in progress. */
|
|
30
|
+
private running;
|
|
31
|
+
constructor(deps?: Partial<ReaperDeps>);
|
|
32
|
+
/**
|
|
33
|
+
* SIGKILLs the process group `pgid` now and, soon after, every process carrying the marker
|
|
34
|
+
* value `marker` exactly (none when empty). Resolves once that scan is done; never rejects.
|
|
35
|
+
*/
|
|
36
|
+
reap(pgid: number, marker: string): Promise<void>;
|
|
37
|
+
private schedule;
|
|
38
|
+
/** Waits for the scan in progress, then scans every marker pending by then. */
|
|
39
|
+
private runQueued;
|
|
40
|
+
private scan;
|
|
41
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { killGroupId } from "./groups.js";
|
|
2
|
+
import { findMarked } from "./procs.js";
|
|
3
|
+
/** The most scans one batch of reaps makes while it still finds processes. */
|
|
4
|
+
export const REAP_ROUNDS = 3;
|
|
5
|
+
function killPid(pid) {
|
|
6
|
+
// A live process's pid is a group id only when it leads that group: then the group goes too.
|
|
7
|
+
killGroupId(pid);
|
|
8
|
+
try {
|
|
9
|
+
process.kill(pid, "SIGKILL");
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// Already gone.
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const DEFAULT_DEPS = { killGroup: (pgid) => killGroupId(pgid), findMarked, killPid };
|
|
16
|
+
/**
|
|
17
|
+
* Kills what a foreground exec left running once it ended (normal exit, timeout or abort). Inside
|
|
18
|
+
* the OS sandbox a command can neither list nor signal the processes another command started, so
|
|
19
|
+
* a `sleep 300 &` or `nohup server &` left behind could otherwise be stopped by nobody.
|
|
20
|
+
*
|
|
21
|
+
* The exec's process group goes at once (a `&` or `nohup` child stays in it). A process that left
|
|
22
|
+
* the group (`setsid`, a detached spawn) is found by the exec's own marker value, which every
|
|
23
|
+
* process it starts inherits; listing processes is slow on macOS (`ps -E`), so that part runs
|
|
24
|
+
* after the result and reaps that arrive meanwhile share one scan. On macOS `ps -E` hides the
|
|
25
|
+
* environment of Apple platform binaries, so it is best effort there (the group covers the rest).
|
|
26
|
+
* Background task launches are not reaped at all (`isBackgroundLaunch`): they detach on purpose.
|
|
27
|
+
*/
|
|
28
|
+
export class Reaper {
|
|
29
|
+
deps;
|
|
30
|
+
/** Markers whose processes the next scan kills. */
|
|
31
|
+
pending = new Set();
|
|
32
|
+
/** The queued scan (not started yet), which every new reap joins. */
|
|
33
|
+
next;
|
|
34
|
+
/** The scan in progress. */
|
|
35
|
+
running;
|
|
36
|
+
constructor(deps = {}) {
|
|
37
|
+
this.deps = { ...DEFAULT_DEPS, ...deps };
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* SIGKILLs the process group `pgid` now and, soon after, every process carrying the marker
|
|
41
|
+
* value `marker` exactly (none when empty). Resolves once that scan is done; never rejects.
|
|
42
|
+
*/
|
|
43
|
+
reap(pgid, marker) {
|
|
44
|
+
this.deps.killGroup(pgid);
|
|
45
|
+
if (marker === "")
|
|
46
|
+
return Promise.resolve();
|
|
47
|
+
this.pending.add(marker);
|
|
48
|
+
return this.schedule();
|
|
49
|
+
}
|
|
50
|
+
schedule() {
|
|
51
|
+
if (this.next !== undefined)
|
|
52
|
+
return this.next;
|
|
53
|
+
const queued = this.runQueued();
|
|
54
|
+
this.next = queued;
|
|
55
|
+
return queued;
|
|
56
|
+
}
|
|
57
|
+
/** Waits for the scan in progress, then scans every marker pending by then. */
|
|
58
|
+
async runQueued() {
|
|
59
|
+
// Always yields first, so `schedule` has set `this.next` before it is cleared here.
|
|
60
|
+
await (this.running ?? Promise.resolve()).catch(() => { });
|
|
61
|
+
this.next = undefined;
|
|
62
|
+
const markers = new Set(this.pending);
|
|
63
|
+
this.pending.clear();
|
|
64
|
+
const scan = this.scan(markers);
|
|
65
|
+
this.running = scan;
|
|
66
|
+
try {
|
|
67
|
+
await scan;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
if (this.running === scan)
|
|
71
|
+
this.running = undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async scan(markers) {
|
|
75
|
+
for (let round = 0; round < REAP_ROUNDS; round++) {
|
|
76
|
+
let pids;
|
|
77
|
+
try {
|
|
78
|
+
pids = await this.deps.findMarked((v) => markers.has(v));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (pids.length === 0)
|
|
84
|
+
return;
|
|
85
|
+
for (const pid of pids)
|
|
86
|
+
this.deps.killPid(pid);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
package/dist/exec/shared.js
CHANGED
|
@@ -15,11 +15,14 @@ export function osRoots(dir) {
|
|
|
15
15
|
export function cacheRoot(dir) {
|
|
16
16
|
return join(dir, "cache");
|
|
17
17
|
}
|
|
18
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* Each cache variable of `dev` / `open` and its folder under the cache root. No pnpm store entry:
|
|
20
|
+
* pnpm 10 takes it only from `npm_config_store_dir`, and npm prints a warning about that unknown
|
|
21
|
+
* key on every command; pnpm keeps its store at its default under HOME (the workspace).
|
|
22
|
+
*/
|
|
19
23
|
const CACHE_DIRS = [
|
|
20
24
|
["XDG_CACHE_HOME", "xdg"],
|
|
21
25
|
["npm_config_cache", "npm"],
|
|
22
|
-
["npm_config_store_dir", "pnpm-store"],
|
|
23
26
|
["PIP_CACHE_DIR", "pip"],
|
|
24
27
|
["UV_CACHE_DIR", "uv"],
|
|
25
28
|
["CARGO_HOME", "cargo"],
|
package/dist/policy.d.ts
CHANGED
|
@@ -90,6 +90,8 @@ export interface SrtConfig {
|
|
|
90
90
|
denyRead: string[];
|
|
91
91
|
allowWrite: string[];
|
|
92
92
|
denyWrite: string[];
|
|
93
|
+
/** Whether commands may write `.git/config` (`dev` / `open`); `.git/hooks` never. */
|
|
94
|
+
allowGitConfig: boolean;
|
|
93
95
|
};
|
|
94
96
|
network: {
|
|
95
97
|
allowedDomains: string[];
|
|
@@ -128,6 +130,8 @@ export interface SrtConfigOptions {
|
|
|
128
130
|
* and use unix sockets under the tmp root, the workspace and the socket directory. On Linux unix
|
|
129
131
|
* sockets stay blocked (srt can only allow all of them there, the host daemons' included) and the
|
|
130
132
|
* sandbox's own network namespace gives it a loopback anyway. `allowAllUnixSockets` is never set.
|
|
133
|
+
* `dev` and `open` may write `.git/config` (so git can init, clone, set remotes and config);
|
|
134
|
+
* `.git/hooks` stays unwritable at every tier ({@link gitWriteDenies}).
|
|
131
135
|
*/
|
|
132
136
|
export declare function srtConfig(policy: Policy, roots: SandboxRoots, egress: string[], opts?: SrtConfigOptions): SrtConfig;
|
|
133
137
|
export {};
|
package/dist/policy.js
CHANGED
|
@@ -185,6 +185,27 @@ export function effectiveEgress(policy, limits, grants) {
|
|
|
185
185
|
out.add(h);
|
|
186
186
|
return [...out];
|
|
187
187
|
}
|
|
188
|
+
/** Characters the sandbox runtime reads as a glob in a path entry. */
|
|
189
|
+
const GLOB_CHARS = /[*?[\]{}]/;
|
|
190
|
+
/**
|
|
191
|
+
* Write denies for git under each writable root (spec §5.2.1): `.git/hooks` at every tier (a hook
|
|
192
|
+
* is code that runs unsandboxed when the owner later runs git there), `.git/config` at `strict`.
|
|
193
|
+
* The runtime has the same mandatory denies, but anchored at this program's own working directory,
|
|
194
|
+
* which may not contain the roots. A root whose path reads as a glob gets none (it cannot be
|
|
195
|
+
* anchored literally); the runtime's own denies still apply when it lies under the working
|
|
196
|
+
* directory.
|
|
197
|
+
*/
|
|
198
|
+
function gitWriteDenies(writable, gitConfig) {
|
|
199
|
+
const out = [];
|
|
200
|
+
for (const root of writable) {
|
|
201
|
+
if (GLOB_CHARS.test(root))
|
|
202
|
+
continue;
|
|
203
|
+
out.push(`${root}/.git/hooks/**`, `${root}/**/.git/hooks/**`);
|
|
204
|
+
if (!gitConfig)
|
|
205
|
+
out.push(`${root}/.git/config`, `${root}/**/.git/config`);
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
188
209
|
/**
|
|
189
210
|
* The sandbox-runtime configuration (spec §5.1, §5.2.3): writes only under the workspace and tmp
|
|
190
211
|
* roots (the runtime's implicit write paths denied), skills read only, the secret paths (plus
|
|
@@ -197,6 +218,8 @@ export function effectiveEgress(policy, limits, grants) {
|
|
|
197
218
|
* and use unix sockets under the tmp root, the workspace and the socket directory. On Linux unix
|
|
198
219
|
* sockets stay blocked (srt can only allow all of them there, the host daemons' included) and the
|
|
199
220
|
* sandbox's own network namespace gives it a loopback anyway. `allowAllUnixSockets` is never set.
|
|
221
|
+
* `dev` and `open` may write `.git/config` (so git can init, clone, set remotes and config);
|
|
222
|
+
* `.git/hooks` stays unwritable at every tier ({@link gitWriteDenies}).
|
|
200
223
|
*/
|
|
201
224
|
export function srtConfig(policy, roots, egress, opts = {}) {
|
|
202
225
|
const platform = opts.platform ?? process.platform;
|
|
@@ -204,16 +227,18 @@ export function srtConfig(policy, roots, egress, opts = {}) {
|
|
|
204
227
|
const darwin = platform === "darwin";
|
|
205
228
|
const dev = tier !== "strict";
|
|
206
229
|
const socketDir = darwin && dev ? opts.socketDir : undefined;
|
|
230
|
+
const allowWrite = [
|
|
231
|
+
roots.workspace,
|
|
232
|
+
roots.tmp,
|
|
233
|
+
...(socketDir !== undefined ? [socketDir] : []),
|
|
234
|
+
...(dev && opts.cacheDir !== undefined ? [opts.cacheDir] : []),
|
|
235
|
+
];
|
|
207
236
|
return {
|
|
208
237
|
filesystem: {
|
|
209
238
|
denyRead: [...deniedSecretPaths(opts.home), ...(opts.denyRead ?? [])],
|
|
210
|
-
allowWrite
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
...(socketDir !== undefined ? [socketDir] : []),
|
|
214
|
-
...(dev && opts.cacheDir !== undefined ? [opts.cacheDir] : []),
|
|
215
|
-
],
|
|
216
|
-
denyWrite: [roots.skills, ...implicitWritePaths()],
|
|
239
|
+
allowWrite,
|
|
240
|
+
denyWrite: [roots.skills, ...implicitWritePaths(), ...gitWriteDenies(allowWrite, dev)],
|
|
241
|
+
allowGitConfig: dev,
|
|
217
242
|
},
|
|
218
243
|
network: {
|
|
219
244
|
allowedDomains: [...egress],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capybara-hq/device",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.6",
|
|
4
4
|
"description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@anthropic-ai/sandbox-runtime": "0.0.81",
|
|
36
36
|
"ws": "^8.18.0",
|
|
37
|
-
"@capybara-hq/plugin-sdk": "^0.1.0-rc.
|
|
37
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.18"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@types/ws": "^8.5.13"
|