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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,29 +43,213 @@ the device page says so. To start afresh, run `capybara-device logout` and then
43
43
  and the platform rebuilds the device on its next use.
44
44
 
45
45
  Commands: `login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]`, `logout`,
46
- `status [--json]`, `start`, `stop`, `drain`, `policy [show|set <key> <value>]` and
46
+ `status [--json]`, `start`, `stop`, `drain`,
47
+ `policy [show | set <key> <value> [--yes] | add|remove <key> <value>]` and
47
48
  `service install|uninstall`.
48
49
 
49
50
  State lives in `$XDG_CONFIG_HOME/capybara-device` (default `~/.config/capybara-device`):
50
51
  `credential.json` (mode 0600; the program refuses a file other users can read; it also holds the
51
52
  deployment's reconnect grace and frame limit: a result larger than the frame limit is answered
52
53
  with an error instead) and `policy.json` (a file with wrong field types stops `start` with an
53
- error naming it).
54
+ error naming it; once running, the program re-reads the file when it changes, and a broken edit
55
+ keeps the last valid policy and logs one error). Changes made with `capybara-device policy` take
56
+ `policy.json.lock`, so two writers never lose an update; keys this version does not know are kept.
54
57
  The working directory (default `~/capybara-device/<deviceId>`) holds `workspace/`, `skills/`
55
58
  and `tmp/`.
56
59
 
57
60
  In OS mode every command runs inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux
58
61
  bubblewrap; Linux needs `bwrap` and `socat`): writes only under `workspace/` and `tmp/`,
59
62
  `skills/` read only, `~/.ssh`, cloud CLI credentials, `~/.netrc`, `~/.gnupg`, browser profiles and
60
- this program's state directory unreadable. Network is limited to the domains of the local policy
61
- that the device's egress also allows; with an empty policy (the default) commands reach no
62
- network at all. Only you edit the policy, the platform can never widen it:
63
+ this program's state directory unreadable. What else a command may do depends on the device's
64
+ [sandbox tier](#sandbox-tiers): at `strict`, network only to the domains of the local policy that
65
+ the device's egress also allows (with an empty list, no network at all); at `dev` (the default of
66
+ every organization unless changed) also the common package registries and local servers; at
67
+ `open` anything the organization allows. You edit the policy locally; the deployment can change it
68
+ only as described in [Changes from the deployment](#changes-from-the-deployment):
63
69
 
64
70
  ```bash
65
71
  capybara-device policy set allowedDomains registry.npmjs.org,*.github.com
66
- capybara-device policy show # changes apply at the next start
72
+ capybara-device policy add allowedDomains files.slack.com
73
+ capybara-device policy remove allowedDomains files.slack.com
74
+ capybara-device policy show
67
75
  ```
68
76
 
77
+ Changes apply at the next command; a running program does not need a restart. `add` and `remove`
78
+ work on `allowedDomains` and `allowCredentials`; every domain must be a lowercase host name
79
+ (optionally `*.` for subdomains, never the apex), never an IP address or an internal name.
80
+
81
+ When a command is refused a domain, the program says why. Clients that print the proxy's answer
82
+ show a reason such as `capybara: files.slack.com is not in this device's allowed domains`, and
83
+ after the command its stderr ends with a trailer naming each refused host (at most 20) and who can
84
+ lift it:
85
+
86
+ ```text
87
+ [capybara-device] Network access was blocked:
88
+ - files.slack.com:443: not in this device's allowed domains. Only the device owner can allow it (capybara-device policy add allowedDomains files.slack.com, or the device page).
89
+ - api.foo.com:443: not in the organization's network allowlist. Only an organization admin can add it.
90
+ - 10.0.0.5:22: a private or local address; commands can never reach it.
91
+ ```
92
+
93
+ The trailer is part of the command's output, so the agent reads it too. It comes after the
94
+ output the deployment asked for (`maxOutputBytes`), so stderr can exceed that cap by the trailer's
95
+ lines (at most 21).
96
+
97
+ In OS mode each command's result also carries the refused hosts and their layers, so the
98
+ deployment can ask the device owner on the spot (the device announces this in its hello, together
99
+ with a summary of its local policy: the chosen and effective `tier`, `isolation`, what `localhost`
100
+ and `unixSockets` give on this machine, `allowedDomains` and `remoteGrants`).
101
+
102
+ ### Sandbox tiers
103
+
104
+ `tier` in `policy.json` is `strict`, `dev` or `open`; without it (the default) the device follows
105
+ the organization's default tier, which is `dev` unless an admin changed it. The deployment sends
106
+ the organization's ceiling with every command, and the device runs the command at its own tier cut
107
+ to that ceiling: a device set to `open` in an organization that allows at most `dev` runs at
108
+ `dev`.
109
+
110
+ | | `strict` | `dev` | `open` |
111
+ |---|---|---|---|
112
+ | Network | `allowedDomains` within the organization's list | also the dev hosts (npm, PyPI, GitHub, crates.io, Go, Maven / Gradle, Docker Hub, Playwright) | anything the organization allows |
113
+ | Local servers (macOS) | no | yes, unless a local proxy is detected | same as `dev` |
114
+ | Unix sockets (macOS) | no | under `workspace/`, `tmp/` and the socket directory | same as `dev` |
115
+ | Package caches | none | `<dir>/cache/` | same as `dev` |
116
+
117
+ In every tier commands keep `HOME` = `workspace/`, writes stay inside the device directory (plus
118
+ the socket directory), the secret paths stay unreadable, and the network proxy refuses loopback,
119
+ private addresses and internal names as destinations. Local servers are a separate permission:
120
+ at `dev` and `open` on macOS a command may listen on and connect to this machine's localhost
121
+ directly (below), never through the proxy.
122
+
123
+ The tier sets what the device adds to its own list; the organization's ceiling only cuts. So a
124
+ device at `strict` under a `dev` ceiling still reaches a dev host (say `registry.npmjs.org`) when
125
+ its owner listed it in `allowedDomains`: `strict` means "only what I listed", not "less than the
126
+ organization's strict list".
127
+
128
+ ```bash
129
+ capybara-device policy set tier dev # or strict
130
+ capybara-device policy set tier open --yes # anything the organization allows
131
+ capybara-device policy set tier default # follow the organization's default again
132
+ capybara-device policy show # what the tier gives on this machine
133
+ ```
134
+
135
+ `set tier open` prints the risk and changes nothing without a confirmation: `--yes`, or, on a
136
+ terminal, an answer of `y` at the prompt (without a terminal and without `--yes` it exits with
137
+ status 2): at `open` a command can upload files to any outside site the organization allows, and
138
+ prompt injection can make an agent do that. Turn it on only on your own development machine, with
139
+ agents and material you trust. Lower tiers are always accepted. When the organization allows any
140
+ host too, the program lets a command reach any public host only while a command started that way
141
+ is running (the sandbox runtime cannot list "any host" per command, so it is allowed process-wide
142
+ meanwhile; a lower tier takes effect at once). The device's owner can also raise the tier on the
143
+ device page, behind the same risk text, while `remoteGrants` is `owner`.
144
+
145
+ An older `policy.json` with `network` is read without it (the device follows the organization's
146
+ default) and loses the key at the next change; `start` says so at each start while it held
147
+ `network: open`. Any `capybara-device policy set` writes the file again and so clears the notice.
148
+
149
+ #### Local servers, sockets and caches at `dev` and `open`
150
+
151
+ - **Local servers (macOS).** Commands may listen on local ports (a dev server, a browser's
152
+ debugging port) and connect to this machine's localhost. That also reaches any local proxy that
153
+ forwards past the network allowlist (Clash and the like) or Docker's TCP API, so the program
154
+ looks for one when it starts and whenever `policy.json` changes: the system proxy
155
+ (`scutil --proxy`), `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` pointing at loopback in its own
156
+ environment, and a listener on 127.0.0.1 or ::1 ports 7890, 7891, 7897, 1080, 1087, 8118, 9050,
157
+ 9150, 2375 or 2376. When it finds one, commands get no localhost and `policy show` says why. A
158
+ proxy set up only through a PAC file (automatic proxy configuration) or on another port is not
159
+ found: if you run one, keep `localhost auto` and consider tier `strict`. To allow localhost
160
+ despite a detected proxy: `capybara-device policy set localhost allow` (back with
161
+ `localhost auto`).
162
+ - **Local servers (Linux).** The sandbox has its own network namespace: a server listens and
163
+ answers inside the command (and its children), never reachable from the host's browser.
164
+ - **Unix sockets (macOS).** Allowed under `workspace/`, `tmp/` and a short socket directory
165
+ `/private/tmp/cap-<8 hex>` (mode 0700, made at start), never anywhere else (Docker's socket stays
166
+ out of reach). `TMPDIR` and `MAC_CHROMIUM_TMPDIR` point at the socket directory, so a headless
167
+ Chromium's socket path stays under the 104-byte limit (`chromium-headless-shell` with
168
+ `--single-process`; full Chrome needs the patched sandbox runtime, see below).
169
+ - **The sandbox runtime patch is not in published installs yet.** This repository patches
170
+ `@anthropic-ai/sandbox-runtime` (`patches/@anthropic-ai__sandbox-runtime@*.patch`, applied by pnpm
171
+ in the workspace) so the macOS profile lets full Chrome read the `hw.product` and
172
+ `kern.hv_vmm_present` sysctls it needs to start headless. The package is built with plain `tsc`
173
+ and depends on the runtime from npm, so `npm i -g @capybara-hq/device` installs the unpatched
174
+ runtime: there, full Chrome (and Puppeteer's or Playwright's default `chrome` / `chromium`
175
+ headless mode) fails to start in the macOS sandbox. Everything else works the same:
176
+ `chromium-headless-shell` with `--single-process`, local servers, unix sockets, package caches,
177
+ the network rules, Linux (the patch is macOS only), Docker mode and running without a sandbox.
178
+ - **Unix sockets (Linux).** Blocked: the sandbox runtime can only allow every socket there,
179
+ including the host daemons' (Docker, D-Bus, ssh-agent). Allowing them with the daemons' sockets
180
+ masked is planned after a spike that proves them unreachable; it has not been done yet. Use
181
+ Docker mode for browsers on Linux.
182
+ - **Package caches.** `XDG_CACHE_HOME`, `npm_config_cache`, `npm_config_store_dir` (pnpm),
183
+ `PIP_CACHE_DIR`, `UV_CACHE_DIR`, `CARGO_HOME`, `GOMODCACHE`, `GOCACHE`, `GRADLE_USER_HOME`,
184
+ `MAVEN_OPTS` (`-Dmaven.repo.local`), `PLAYWRIGHT_BROWSERS_PATH` and `COREPACK_HOME` point at
185
+ folders of `<dir>/cache/`, kept across commands. Your own `~/.npm`, `~/.cache` and pnpm store stay
186
+ read only, so a sandboxed command cannot poison your own builds. A command that sets one of
187
+ these variables itself keeps its value.
188
+
189
+ ### Running without a sandbox
190
+
191
+ `isolation` in `policy.json` is `sandbox` (default) or `none`. With `none` and tier `open`, in OS
192
+ mode, commands run directly on this computer as you: your real `HOME`, `PATH`, environment,
193
+ caches, credentials (SSH keys, cloud accounts, keychain), Docker and any network, like a coding
194
+ agent with its sandbox off. They still start in `workspace/`, and the platform's file tools still
195
+ stay inside the device's directories. Such commands can also read this program's own credential
196
+ (`credential.json`): if you suspect misuse, run `capybara-device logout` and log in again, which
197
+ revokes it. Prompt injection can make an agent delete files or send your credentials away: turn it
198
+ on only on your own development machine, with agents and material you fully trust.
199
+
200
+ ```bash
201
+ capybara-device policy set tier open --yes # first: an explicit local tier open
202
+ capybara-device policy set isolation none --yes
203
+ capybara-device policy set isolation sandbox # back to the sandbox
204
+ ```
205
+
206
+ It is set only on this machine: `set isolation none` is refused unless `tier` is set to `open` in
207
+ `policy.json` (following the organization's default is not enough), prints the risk and needs
208
+ `--yes` or a `y` at the prompt, and the device refuses it from the deployment whatever `remoteGrants` says (turning it
209
+ back to `sandbox` from the deployment is accepted). A Docker-mode device refuses it. The platform
210
+ or the organization may refuse to use a device that runs without a sandbox; its owner then turns
211
+ the sandbox back on.
212
+
213
+ ### Changes from the deployment
214
+
215
+ `remoteGrants` in `policy.json` decides whether the deployment may widen this device's network
216
+ policy on the device owner's decision (an approval answered in a signed-in web or IM session, or
217
+ the device page):
218
+
219
+ - `owner` (default): the device accepts the `policy` operation's additions to `allowedDomains`
220
+ (an approval adds an exact host; the device page may add a `*.` wildcard) and a higher `tier`,
221
+ and adds a run's or a scheduled task's granted hosts to a command's list. Grants are exact hosts
222
+ and never go beyond the organization's egress.
223
+ - `off`: the device refuses every widening from the deployment (additions, a higher `tier`, run and
224
+ task grants) with "This device does not accept network changes from the deployment; allow it
225
+ locally: capybara-device policy add allowedDomains <host>".
226
+
227
+ `isolation: none` is never accepted from the deployment. Narrowing (removing hosts, a lower
228
+ `tier`, `isolation: sandbox`) is always accepted. Every host is validated like
229
+ a local one, the change is written under `policy.json.lock`, and it applies at the next command.
230
+ `remoteGrants` itself is set only locally: `capybara-device policy set remoteGrants owner|off`
231
+ (or in `policy.json`). Each change from the deployment is
232
+ recorded in the local command log (`commands.log`, next to `policy.json`) with who decided it,
233
+ and so is a refused attempt and the grants a command was given:
234
+
235
+ ```text
236
+ {"op":"policy","detail":"policy add files.slack.com by Ada Lovelace (acc_123) via web, approval apr_456",...}
237
+ {"op":"policy","detail":"policy refused tier open by Ada Lovelace (acc_123) via web",...}
238
+ {"op":"exec","detail":"grants run run_789 by acc_123: files.slack.com",...}
239
+ ```
240
+
241
+ Docker mode has no per-domain allowlist (a container has either no network or the whole
242
+ internet), so a Docker-mode device refuses every widening from the deployment ("This device runs
243
+ commands in Docker mode, which cannot limit network access per domain; switch the device to OS mode
244
+ to allow single domains."), reports no refused hosts and ignores grants; narrowing still applies.
245
+ `capybara-device policy add allowedDomains` on a Docker-mode device warns that any allowed domain
246
+ opens the whole internet.
247
+
248
+ Limit to know: commands of one device run as the same user, and the sandbox runtime ties a
249
+ command's list (including its run grants) to the proxy credentials it hands that command. Another
250
+ command running at the same time on the same device could reuse them, so a run's grants may be
251
+ usable by a concurrent command of another run on that device: same owner, same device.
252
+
69
253
  Limits to know: the platform's `Grep` tool assumes GNU grep, so on macOS (BSD grep) in OS mode some
70
254
  Grep options behave differently or fail. Docker mode (a Linux container) does not have this issue.
71
255
 
@@ -84,12 +268,18 @@ run as your own uid:gid, so they can write the mounted directories you own (a ro
84
268
  the image's `sandbox` user, uid 1000); on macOS as the image's `sandbox` user. `<dir>/workspace`, `<dir>/skills` (read only) and `<dir>/tmp` are mounted
85
269
  at `/workspace`, `/skills` and `/tmp`; the container has a read-only root file system, a pids limit of 1024, `--memory-swap` equal to
86
270
  `memoryMb`, `--cap-drop ALL` and `no-new-privileges`. The policy's `cpu` and
87
- `memoryMb` become `--cpus` and `--memory`. The container is reused while its mounts and limits
88
- match and recreated when they change; it stays running (idle) between starts.
271
+ `memoryMb` become `--cpus` and `--memory`; at tier `dev` and `open` `/dev/shm` grows to a quarter
272
+ of `memoryMb` (at most 1 GiB; 1 GiB without a ceiling) for browsers. The container is reused while
273
+ its mounts and flags match and recreated when they change (at the next command that finds it
274
+ idle); it stays running (idle) between starts. Commands always have the container's own localhost
275
+ and unix sockets; `isolation none` is refused.
89
276
 
90
- Docker mode has no domain allowlist: a command has either no network (`--network none`, when the
91
- local policy or the device's egress allows no domain) or the default bridge, with the whole
92
- internet. Use OS mode to limit commands to the domains of the local policy.
277
+ Docker mode has no domain allowlist: a command has either no network (`--network none`) or the
278
+ default bridge, with the whole internet and this machine's network. It gets the bridge only when
279
+ the local `allowedDomains` holds a domain the device's egress allows, or the tier is `open` and the
280
+ organization allows any host (under an organization allowlist, `open` counts only the explicit
281
+ local domains, like the lower tiers); the dev hosts of tier `dev` do not open it. Use OS mode to limit
282
+ commands to single domains.
93
283
 
94
284
  ## Running at login
95
285
 
package/dist/args.d.ts CHANGED
@@ -22,16 +22,18 @@ export type Command = {
22
22
  action: "show";
23
23
  } | {
24
24
  command: "policy";
25
- action: "set";
25
+ action: "set" | "add" | "remove";
26
26
  key: string;
27
27
  value: string;
28
+ /** `--yes`: confirms `set tier open` or `set isolation none` without asking. */
29
+ yes?: true;
28
30
  } | {
29
31
  command: "service";
30
32
  action: "install" | "uninstall";
31
33
  } | {
32
34
  command: "help";
33
35
  };
34
- 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 Finish running commands, accept no new ones, then stop\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n capybara-device service install|uninstall\n Run at login as a user service";
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 Finish running commands, accept no new ones, then stop\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";
35
37
  /** Thrown for a bad command line; the message is shown with the usage. */
36
38
  export declare class UsageError extends Error {
37
39
  }
package/dist/args.js CHANGED
@@ -9,6 +9,17 @@ export const USAGE = `Usage:
9
9
  capybara-device drain Finish running commands, accept no new ones, then stop
10
10
  capybara-device policy [show] Show the local policy
11
11
  capybara-device policy set <key> <value>
12
+ Replace one field (applies at the next command)
13
+ capybara-device policy set tier strict|dev|open|default [--yes]
14
+ Choose the sandbox tier (default: follow the organization)
15
+ capybara-device policy set isolation sandbox|none [--yes]
16
+ none: at tier open, run commands without a sandbox (OS mode)
17
+ capybara-device policy set localhost auto|allow
18
+ allow: reach localhost at tier dev or open despite a local proxy
19
+ capybara-device policy set remoteGrants owner|off
20
+ Let the device owner widen the network from the web, or not
21
+ capybara-device policy add|remove allowedDomains <host>
22
+ Allow or stop allowing a domain (applies at the next command)
12
23
  capybara-device service install|uninstall
13
24
  Run at login as a user service`;
14
25
  /** Thrown for a bad command line; the message is shown with the usage. */
@@ -69,15 +80,20 @@ export function parseCommandLine(argv) {
69
80
  case "drain":
70
81
  return noArgs(name);
71
82
  case "policy": {
72
- const { positionals } = parse(rest, {});
83
+ const { values, positionals } = parse(rest, { yes: { type: "boolean", short: "y" } });
84
+ const yes = values.yes === true;
73
85
  const [action, key, value, ...extra] = positionals;
74
- if (action === undefined || (action === "show" && key === undefined && extra.length === 0)) {
86
+ if (!yes &&
87
+ (action === undefined || (action === "show" && key === undefined && extra.length === 0))) {
75
88
  return { command: "policy", action: "show" };
76
89
  }
77
- if (action === "set" && key !== undefined && value !== undefined && extra.length === 0) {
78
- return { command: "policy", action: "set", key, value };
90
+ if ((action === "set" || action === "add" || action === "remove") &&
91
+ key !== undefined &&
92
+ value !== undefined &&
93
+ extra.length === 0) {
94
+ return { command: "policy", action, key, value, ...(yes && { yes: true }) };
79
95
  }
80
- throw new UsageError("usage: policy [show | set <key> <value>]");
96
+ throw new UsageError("usage: policy [show | set <key> <value> [--yes] | add|remove <key> <value>]");
81
97
  }
82
98
  case "service": {
83
99
  const { positionals } = parse(rest, {});
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Executor } from "./exec/types.js";
2
- import { type Credential, type Policy } from "./state.js";
2
+ import type { PolicyStore } from "./policy-store.js";
3
+ import { type Credential } from "./state.js";
3
4
  export interface CliEnv {
4
5
  env?: Record<string, string | undefined>;
5
6
  home?: string;
@@ -9,10 +10,19 @@ export interface CliEnv {
9
10
  openBrowser?: (url: string) => void;
10
11
  out?: (line: string) => void;
11
12
  err?: (line: string) => void;
12
- createExecutor?: (cred: Credential, policy: Policy) => Promise<Executor> | Executor;
13
+ createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
13
14
  kill?: typeof process.kill;
14
15
  /** Runs a system command for `service` (default: execFileSync). */
15
16
  runSystem?: (cmd: string, args: string[]) => void;
17
+ /** Standard input is a terminal (default: `process.stdin.isTTY`): a confirmation may be asked. */
18
+ stdinIsTTY?: boolean;
19
+ /** Asks one question on the terminal and resolves the answer (default: node:readline). */
20
+ ask?: (question: string) => Promise<string>;
16
21
  }
22
+ /** Shown once when a Docker-mode device's policy says `isolation: none` (it is ignored there). */
23
+ export declare const DOCKER_ISOLATION_IGNORED: string;
24
+ /** Logged when commands start or stop running without a sandbox. */
25
+ export declare const UNSANDBOXED_ON = "Commands on this device now run without a sandbox (isolation none).";
26
+ export declare const UNSANDBOXED_OFF: string;
17
27
  /** Runs one command line and returns the exit code. */
18
28
  export declare function runCli(argv: string[], io?: CliEnv): Promise<number>;
package/dist/cli.js CHANGED
@@ -3,16 +3,41 @@ import { parseCommandLine, USAGE, UsageError } from "./args.js";
3
3
  import { drain } from "./commands/drain.js";
4
4
  import { login } from "./commands/login.js";
5
5
  import { logout } from "./commands/logout.js";
6
- import { policyCommand } from "./commands/policy.js";
6
+ import { confirmRisk, isolationRefusal, needsConfirmation, policyCommand, policyRisk, } from "./commands/policy.js";
7
7
  import { serviceCommand } from "./commands/service.js";
8
8
  import { start } from "./commands/start.js";
9
9
  import { status } from "./commands/status.js";
10
10
  import { stop } from "./commands/stop.js";
11
11
  import { stateDir } from "./state.js";
12
- /** The executor for the credential's mode; the program's state directory is unreadable to commands. */
13
- function defaultCreateExecutor(stateDir, home) {
14
- return async (cred, policy) => {
12
+ /** Asks one question on the process's terminal. */
13
+ async function askOnTerminal(question) {
14
+ const { createInterface } = await import("node:readline/promises");
15
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
16
+ try {
17
+ return await rl.question(question);
18
+ }
19
+ finally {
20
+ rl.close();
21
+ }
22
+ }
23
+ /** Shown once when a Docker-mode device's policy says `isolation: none` (it is ignored there). */
24
+ export const DOCKER_ISOLATION_IGNORED = "policy.json says isolation none, which works in OS mode only: this device runs commands in " +
25
+ "Docker mode, always in a container.";
26
+ /** Logged when commands start or stop running without a sandbox. */
27
+ export const UNSANDBOXED_ON = "Commands on this device now run without a sandbox (isolation none).";
28
+ export const UNSANDBOXED_OFF = "Commands on this device run in the sandbox again; commands still running without one were " +
29
+ "stopped.";
30
+ /**
31
+ * The executor for the credential's mode; the program's state directory is unreadable to
32
+ * sandboxed commands. OS mode serves a {@link SwitchingExecutor}: the OS sandbox, or no sandbox
33
+ * when the owner set `isolation none` locally and the command's tier is `open` (spec §5.4).
34
+ */
35
+ function defaultCreateExecutor(stateDir, home, err) {
36
+ return async (cred, store) => {
37
+ const policy = () => store.current();
15
38
  if (cred.mode === "docker") {
39
+ if (policy().isolation === "none")
40
+ err(DOCKER_ISOLATION_IGNORED);
16
41
  const { createDockerExecutor } = await import("./exec/docker.js");
17
42
  return createDockerExecutor({
18
43
  dir: cred.dir,
@@ -21,8 +46,18 @@ function defaultCreateExecutor(stateDir, home) {
21
46
  });
22
47
  }
23
48
  // Loaded on demand: the sandbox runtime is only needed by start.
24
- const { createOsExecutor } = await import("./exec/os.js");
25
- return createOsExecutor({ dir: cred.dir, policy, home, denyRead: [stateDir] });
49
+ const [{ createOsExecutor }, { HostExecutor }, { SwitchingExecutor }] = await Promise.all([
50
+ import("./exec/os.js"),
51
+ import("./exec/host.js"),
52
+ import("./exec/switch.js"),
53
+ ]);
54
+ const sandboxed = await createOsExecutor({
55
+ dir: cred.dir,
56
+ policy,
57
+ home,
58
+ denyRead: [stateDir],
59
+ });
60
+ return new SwitchingExecutor(sandboxed, new HostExecutor({ dir: cred.dir }), policy, (i) => err(i === "none" ? UNSANDBOXED_ON : UNSANDBOXED_OFF));
26
61
  };
27
62
  }
28
63
  /** Runs one command line and returns the exit code. */
@@ -70,15 +105,32 @@ export async function runCli(argv, io = {}) {
70
105
  stateDir: dir,
71
106
  out,
72
107
  err,
73
- createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home),
108
+ createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home, err),
74
109
  ...(io.kill && { kill: io.kill }),
75
110
  });
76
111
  case "stop":
77
112
  return stop(dir, out, err, io.kill);
78
113
  case "drain":
79
114
  return drain(dir, out, err, io.kill);
80
- case "policy":
115
+ case "policy": {
116
+ // `set isolation none` that cannot apply (Docker mode, no local tier open): refused before
117
+ // any risk text or question (policyCommand refuses it too, under the lock).
118
+ const refusal = isolationRefusal(cmd, dir);
119
+ if (refusal !== undefined) {
120
+ err(refusal);
121
+ return 2;
122
+ }
123
+ // `set tier open` / `set isolation none` without --yes: ask on a terminal (after printing
124
+ // the risk text); elsewhere policyCommand refuses them.
125
+ if (needsConfirmation(cmd) && (io.stdinIsTTY ?? process.stdin.isTTY === true)) {
126
+ if (!(await confirmRisk(cmd, { out, ask: io.ask ?? askOnTerminal }))) {
127
+ err(policyRisk(cmd)?.needsYes ?? "Nothing changed.");
128
+ return 1;
129
+ }
130
+ return policyCommand(cmd, { stateDir: dir, out, err, confirmed: true });
131
+ }
81
132
  return policyCommand(cmd, { stateDir: dir, out, err });
133
+ }
82
134
  case "service":
83
135
  return serviceCommand(cmd.action, {
84
136
  stateDir: dir,
package/dist/client.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { CommandLog } from "./command-log.js";
2
2
  import type { Executor } from "./exec/types.js";
3
+ import type { PolicyStore } from "./policy-store.js";
3
4
  import type { Credential } from "./state.js";
4
5
  export declare const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device@next";
5
6
  export declare const DISCONNECTED_MESSAGE = "This machine was disconnected from the deployment. Run capybara-device logout, then capybara-device login.";
@@ -9,17 +10,29 @@ export declare const DELETED_MESSAGE = "The device was deleted on the deployment
9
10
  export declare const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
10
11
  export interface ConnectOptions {
11
12
  log?: CommandLog;
13
+ /**
14
+ * The local policy the executor reads: its summary goes in each hello, and the `policy` op
15
+ * edits it. Without it the device does not offer the `policy` op.
16
+ */
17
+ policy?: PolicyStore;
12
18
  err?: (line: string) => void;
13
19
  sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
14
20
  random?: () => number;
15
21
  now?: () => number;
16
22
  programVersion?: string;
23
+ /** The platform the policy summary describes (default: this process's; for tests). */
24
+ platform?: NodeJS.Platform;
17
25
  /** A connection must stay up this long before the backoff resets (default 10 s). */
18
26
  stableMs?: number;
19
27
  /** Terminate a socket that heard nothing from the server for this long (default 60 s). */
20
28
  livenessMs?: number;
21
29
  /** Terminate a socket still closing this long after we asked it to close (default 2 s). */
22
30
  closeTimeoutMs?: number;
31
+ /**
32
+ * How often a connected program checks its policy summary for a change made on the machine
33
+ * (default 2 s); a change is pushed to the deployment as a `policy` frame.
34
+ */
35
+ policyCheckMs?: number;
23
36
  }
24
37
  /**
25
38
  * A running connection. `done` resolves with the exit code once the program should end: 0 for the
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
2
2
  import WebSocket from "ws";
3
- import { logEntryFor, runOp } from "./server-ops.js";
3
+ import { logEntryFor, policySummary, serveOp, summaryFacts, } from "./server-ops.js";
4
4
  import { PROGRAM_VERSION } from "./version.js";
5
5
  export const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device@next";
6
6
  export const DISCONNECTED_MESSAGE = "This machine was disconnected from the deployment. Run capybara-device logout, then capybara-device login.";
@@ -38,6 +38,7 @@ export function connect(cred, executor, opts = {}) {
38
38
  const stableMs = opts.stableMs ?? 10_000;
39
39
  const livenessMs = opts.livenessMs ?? 60_000;
40
40
  const closeTimeoutMs = opts.closeTimeoutMs ?? 2000;
41
+ const policyCheckMs = opts.policyCheckMs ?? 2000;
41
42
  const lifetime = new AbortController();
42
43
  let ws;
43
44
  let draining = false;
@@ -45,6 +46,13 @@ export function connect(cred, executor, opts = {}) {
45
46
  let exitAfterStop;
46
47
  let session;
47
48
  let drainTimer;
49
+ /** What the requests of this run have seen (the latest exec's tier limits), over reconnects. */
50
+ const seen = {};
51
+ const ctx = {
52
+ seen,
53
+ ...(opts.policy !== undefined && { policy: opts.policy }),
54
+ ...(opts.platform !== undefined && { platform: opts.platform }),
55
+ };
48
56
  const running = new Map();
49
57
  /** Requests the kernel gave up on: never started, or their result is dropped. */
50
58
  const cancelled = new Map();
@@ -63,6 +71,30 @@ export function connect(cred, executor, opts = {}) {
63
71
  pending.delete(k);
64
72
  };
65
73
  const isOpen = () => ws !== undefined && ws.readyState === WebSocket.OPEN;
74
+ /** The policy summary now: the store's policy (re-read when its file changed) and the facts. */
75
+ const summaryNow = () => opts.policy === undefined
76
+ ? undefined
77
+ : policySummary(opts.policy.current(), summaryFacts(executor, ctx));
78
+ /** The summary the deployment last got on this connection (hello, `policy` op, `policy` frame). */
79
+ let sentPolicy;
80
+ /**
81
+ * Pushes the policy summary when it differs from the one the deployment last got: the owner
82
+ * changed the policy on the machine (`capybara-device policy ...`), the localhost proxy guard
83
+ * flipped, or an exec brought a new tier ceiling. Without it the deployment would learn the
84
+ * change only at the next connect.
85
+ */
86
+ const pushPolicy = () => {
87
+ if (!isOpen())
88
+ return;
89
+ const summary = summaryNow();
90
+ if (summary === undefined)
91
+ return;
92
+ const json = JSON.stringify(summary);
93
+ if (json === sentPolicy)
94
+ return;
95
+ sentPolicy = json;
96
+ ws?.send(JSON.stringify({ type: "policy", policy: summary }));
97
+ };
66
98
  /** `res`, or an error answer when its frame would exceed the deployment's frame limit. */
67
99
  const fit = (res) => Buffer.byteLength(JSON.stringify(res)) <= cred.maxFrameBytes
68
100
  ? res
@@ -138,9 +170,9 @@ export function connect(cred, executor, opts = {}) {
138
170
  }
139
171
  const ctl = new AbortController();
140
172
  running.set(req.id, ctl);
141
- void runOp(executor, req, ctl.signal).then((res) => {
173
+ void serveOp(executor, req, ctl.signal, ctx).then(({ res, detail, run }) => {
142
174
  running.delete(req.id);
143
- opts.log?.append(logEntryFor(req, res, new Date(now())));
175
+ opts.log?.append(logEntryFor(req, res, new Date(now()), detail, run));
144
176
  if (cancelled.has(req.id)) {
145
177
  // The kernel is no longer waiting for this one.
146
178
  }
@@ -161,7 +193,13 @@ export function connect(cred, executor, opts = {}) {
161
193
  return;
162
194
  }
163
195
  else {
196
+ // a policy op's answer carries the summary the deployment stores
197
+ if (req.op === "policy" && res.ok) {
198
+ sentPolicy = JSON.stringify(res.result.policy);
199
+ }
164
200
  deliver(res);
201
+ // an exec may have changed the facts (the proxy guard, the tier ceiling)
202
+ pushPolicy();
165
203
  }
166
204
  maybeFinishDrain();
167
205
  });
@@ -200,16 +238,33 @@ export function connect(cred, executor, opts = {}) {
200
238
  else if (frame.type === "cancel")
201
239
  handleCancel(frame.id);
202
240
  };
203
- const hello = () => ({
204
- type: "hello",
205
- protocol: DEVICE_PROTOCOL_VERSION,
206
- programVersion: opts.programVersion ?? PROGRAM_VERSION,
207
- os: process.platform === "darwin" ? "darwin" : "linux",
208
- arch: process.arch,
209
- mode: executor.mode,
210
- roots: executor.roots,
211
- sessionIsolation: false,
212
- });
241
+ /**
242
+ * The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
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.
245
+ */
246
+ const hello = () => {
247
+ const summary = summaryNow();
248
+ sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
249
+ const features = [];
250
+ if (executor.mode === "os")
251
+ features.push("networkReport");
252
+ if (opts.policy !== undefined)
253
+ features.push("policyOp");
254
+ features.push("tiers");
255
+ return {
256
+ type: "hello",
257
+ protocol: DEVICE_PROTOCOL_VERSION,
258
+ programVersion: opts.programVersion ?? PROGRAM_VERSION,
259
+ os: process.platform === "darwin" ? "darwin" : "linux",
260
+ arch: process.arch,
261
+ mode: executor.mode,
262
+ roots: executor.roots,
263
+ sessionIsolation: false,
264
+ features,
265
+ ...(summary !== undefined && { policy: summary }),
266
+ };
267
+ };
213
268
  let attempt = 0;
214
269
  /** When a failing connection was last reported; reset once a connection stays up. */
215
270
  let lastReport;
@@ -232,6 +287,7 @@ export function connect(cred, executor, opts = {}) {
232
287
  ws = sock;
233
288
  let liveness;
234
289
  let stable;
290
+ let policyCheck;
235
291
  let opened = false;
236
292
  /** The deployment answered the upgrade with an HTTP status (already handled). */
237
293
  let answered = false;
@@ -248,6 +304,8 @@ export function connect(cred, executor, opts = {}) {
248
304
  lastReport = undefined;
249
305
  }, stableMs);
250
306
  sock.send(JSON.stringify(hello()));
307
+ if (opts.policy !== undefined)
308
+ policyCheck = setInterval(pushPolicy, policyCheckMs);
251
309
  prune();
252
310
  for (const [id, p] of pending) {
253
311
  pending.delete(id);
@@ -286,6 +344,7 @@ export function connect(cred, executor, opts = {}) {
286
344
  sock.on("close", (code, reason) => {
287
345
  clearTimeout(liveness);
288
346
  clearTimeout(stable);
347
+ clearInterval(policyCheck);
289
348
  if (ws === sock)
290
349
  ws = undefined;
291
350
  if (exitAfterStop)