@capybara-hq/device 0.1.0-rc.5 → 0.1.0-rc.7
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/client.js +6 -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 +38 -3
- package/dist/exec/os.js +108 -17
- 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-ops.d.ts +47 -0
- package/dist/policy-ops.js +90 -0
- package/dist/policy-store.d.ts +8 -2
- package/dist/policy-store.js +8 -2
- package/dist/policy.d.ts +4 -0
- package/dist/policy.js +32 -7
- package/dist/server-ops.d.ts +2 -1
- package/dist/server-ops.js +85 -8
- package/dist/state.d.ts +2 -0
- package/dist/state.js +10 -1
- 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/client.js
CHANGED
|
@@ -241,7 +241,8 @@ export function connect(cred, executor, opts = {}) {
|
|
|
241
241
|
/**
|
|
242
242
|
* The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
|
|
243
243
|
* mode has no per-host view); the device applies tiers (`limits.tier` / `defaultTier` /
|
|
244
|
-
* `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen
|
|
244
|
+
* `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen; then the
|
|
245
|
+
* outcomes of the latest policy ops by op id.
|
|
245
246
|
*/
|
|
246
247
|
const hello = () => {
|
|
247
248
|
const summary = summaryNow();
|
|
@@ -249,8 +250,9 @@ export function connect(cred, executor, opts = {}) {
|
|
|
249
250
|
const features = [];
|
|
250
251
|
if (executor.mode === "os")
|
|
251
252
|
features.push("networkReport");
|
|
253
|
+
// the policy op, logged by its op id (policy-ops.json next to the policy)
|
|
252
254
|
if (opts.policy !== undefined)
|
|
253
|
-
features.push("policyOp");
|
|
255
|
+
features.push("policyOp", "policyOpId");
|
|
254
256
|
features.push("tiers");
|
|
255
257
|
return {
|
|
256
258
|
type: "hello",
|
|
@@ -263,6 +265,8 @@ export function connect(cred, executor, opts = {}) {
|
|
|
263
265
|
sessionIsolation: false,
|
|
264
266
|
features,
|
|
265
267
|
...(summary !== undefined && { policy: summary }),
|
|
268
|
+
// what became of the latest policy ops, so an answer lost with a connection is not lost
|
|
269
|
+
...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
|
|
266
270
|
};
|
|
267
271
|
};
|
|
268
272
|
let attempt = 0;
|
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
|
/**
|
|
@@ -64,6 +69,13 @@ export declare class OsExecutor implements Executor {
|
|
|
64
69
|
* running. The ask callback allows any public name only while one runs.
|
|
65
70
|
*/
|
|
66
71
|
private readonly openCommands;
|
|
72
|
+
/**
|
|
73
|
+
* Background tasks launched on macOS that still run, by the command id of their launch, with
|
|
74
|
+
* the task's process group id (its sid). A task keeps its launch's network permissions (the
|
|
75
|
+
* per-command list and {@link openCommands}) until its group is gone: it uses the launch's proxy
|
|
76
|
+
* credentials long after the launch returned. Checked on the prune tick.
|
|
77
|
+
*/
|
|
78
|
+
private readonly backgroundNet;
|
|
67
79
|
constructor(opts: OsExecutorOptions);
|
|
68
80
|
/**
|
|
69
81
|
* The tier of work that has no limits of its own (the file helper): the device's choice cut to
|
|
@@ -109,13 +121,30 @@ export declare class OsExecutor implements Executor {
|
|
|
109
121
|
readonly askCallback: SandboxAskCallback;
|
|
110
122
|
/** The classified network refusals of one command (read before it unregisters). */
|
|
111
123
|
private blockedFor;
|
|
112
|
-
/**
|
|
124
|
+
/**
|
|
125
|
+
* `<dir>/git-template`, an empty directory commands can read but not write (it is outside the
|
|
126
|
+
* roots), made on demand; undefined when it cannot be made.
|
|
127
|
+
*/
|
|
128
|
+
private gitTemplate;
|
|
129
|
+
/**
|
|
130
|
+
* The marker value of a tag's processes. An exec's processes carry `<this>.<exec id>` (see
|
|
131
|
+
* {@link execMarker}); {@link killTagged} matches both.
|
|
132
|
+
*/
|
|
113
133
|
markerOf(tag: string): string;
|
|
134
|
+
/** The marker value of one exec's processes: its tag's plus an id of its own (no dots in a tag). */
|
|
135
|
+
private execMarker;
|
|
114
136
|
/**
|
|
115
137
|
* Wraps `script` (run by bash inside the sandbox, after the request's `env` and TMPDIR are
|
|
116
138
|
* exported) and spawns it as the leader of a new process group.
|
|
117
139
|
*/
|
|
118
140
|
private spawnSandboxed;
|
|
141
|
+
/** Drops a command's network permissions (its per-command list and any-host membership). */
|
|
142
|
+
private releaseNet;
|
|
143
|
+
/** Keeps a launched background task's network permissions while its group `sid` lives. */
|
|
144
|
+
private keepBackgroundNet;
|
|
145
|
+
/** Releases the network permissions of background tasks whose group is gone (all: `all`). */
|
|
146
|
+
private pruneBackgroundNet;
|
|
147
|
+
private startPruning;
|
|
119
148
|
/** Tracks a spawned command's process group; returns the entry. */
|
|
120
149
|
private track;
|
|
121
150
|
/** Forgets finished groups with no members left (or whose id was taken by another process). */
|
|
@@ -140,6 +169,12 @@ export declare class OsExecutor implements Executor {
|
|
|
140
169
|
/** Kills every running command and shuts the sandbox's proxies down. */
|
|
141
170
|
dispose(): Promise<void>;
|
|
142
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* The process group id a background task launch printed as its last line (the task's sid), on
|
|
174
|
+
* macOS only: there the sandbox shares the host's process ids, so the device can watch the group.
|
|
175
|
+
* Elsewhere (Linux: bwrap's own pid namespace) undefined, and the launch's permissions end with it.
|
|
176
|
+
*/
|
|
177
|
+
export declare function launchedGroup(stdout: string, platform?: NodeJS.Platform): number | undefined;
|
|
143
178
|
/**
|
|
144
179
|
* The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
|
|
145
180
|
* once for this process, and kills what a previous run of this device left running.
|