@capybara-hq/device 0.1.0-rc.1 → 0.1.0-rc.11

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.
Files changed (73) hide show
  1. package/README.md +205 -44
  2. package/dist/api.d.ts +6 -1
  3. package/dist/args.d.ts +14 -3
  4. package/dist/args.js +74 -10
  5. package/dist/cli.d.ts +27 -4
  6. package/dist/cli.js +81 -11
  7. package/dist/client.d.ts +19 -6
  8. package/dist/client.js +93 -19
  9. package/dist/command-log.d.ts +8 -0
  10. package/dist/commands/drain.d.ts +14 -1
  11. package/dist/commands/drain.js +31 -2
  12. package/dist/commands/login.d.ts +3 -0
  13. package/dist/commands/login.js +96 -11
  14. package/dist/commands/logout.d.ts +2 -0
  15. package/dist/commands/logout.js +1 -1
  16. package/dist/commands/mode.d.ts +69 -0
  17. package/dist/commands/mode.js +129 -0
  18. package/dist/commands/policy.d.ts +13 -4
  19. package/dist/commands/policy.js +162 -33
  20. package/dist/commands/service.d.ts +26 -4
  21. package/dist/commands/service.js +242 -19
  22. package/dist/commands/signal.d.ts +6 -2
  23. package/dist/commands/signal.js +7 -4
  24. package/dist/commands/start.d.ts +18 -3
  25. package/dist/commands/start.js +46 -7
  26. package/dist/commands/status.js +12 -4
  27. package/dist/commands/stop.d.ts +20 -2
  28. package/dist/commands/stop.js +26 -3
  29. package/dist/exec/docker.d.ts +41 -13
  30. package/dist/exec/docker.js +123 -57
  31. package/dist/exec/fs-helper.d.ts +13 -8
  32. package/dist/exec/fs-helper.js +31 -13
  33. package/dist/exec/groups.d.ts +42 -0
  34. package/dist/exec/groups.js +100 -0
  35. package/dist/exec/host.d.ts +53 -0
  36. package/dist/exec/host.js +183 -0
  37. package/dist/exec/os.d.ts +85 -15
  38. package/dist/exec/os.js +208 -36
  39. package/dist/exec/reap.d.ts +41 -0
  40. package/dist/exec/reap.js +89 -0
  41. package/dist/exec/sandbox-messages.d.ts +14 -0
  42. package/dist/exec/sandbox-messages.js +21 -0
  43. package/dist/exec/shared.d.ts +42 -13
  44. package/dist/exec/shared.js +94 -16
  45. package/dist/exec/switch.d.ts +98 -0
  46. package/dist/exec/switch.js +175 -0
  47. package/dist/exec/types.d.ts +28 -4
  48. package/dist/index.d.ts +1 -1
  49. package/dist/network.d.ts +45 -0
  50. package/dist/network.js +154 -0
  51. package/dist/pid.d.ts +44 -3
  52. package/dist/pid.js +110 -7
  53. package/dist/policy-ops.d.ts +47 -0
  54. package/dist/policy-ops.js +90 -0
  55. package/dist/policy-store.d.ts +43 -0
  56. package/dist/policy-store.js +94 -0
  57. package/dist/policy.d.ts +36 -16
  58. package/dist/policy.js +77 -19
  59. package/dist/public-suffix.d.ts +6 -0
  60. package/dist/public-suffix.js +79 -0
  61. package/dist/server-ops.d.ts +48 -7
  62. package/dist/server-ops.js +287 -29
  63. package/dist/service/installed.d.ts +5 -0
  64. package/dist/service/installed.js +14 -0
  65. package/dist/service/launchd.d.ts +14 -1
  66. package/dist/service/launchd.js +25 -1
  67. package/dist/service/manager.d.ts +41 -0
  68. package/dist/service/manager.js +91 -0
  69. package/dist/service/systemd.d.ts +2 -0
  70. package/dist/service/systemd.js +8 -0
  71. package/dist/state.d.ts +50 -6
  72. package/dist/state.js +195 -16
  73. package/package.json +3 -3
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @capybara-hq/device
2
2
 
3
3
  `capybara-device` connects a laptop or server to a [Capybara](https://github.com/capybara-hq/core)
4
- deployment as an environment: the platform's agents run commands and read and write files on this
5
- machine, inside a sandbox, while the program is online.
4
+ deployment as a device: the platform's agents run commands and read and write files on this
5
+ machine, in auto mode (as you, with every command reviewed by the deployment) or inside an OS
6
+ sandbox, while the program is online.
6
7
 
7
8
  Runs on macOS and Linux. Native Windows is refused: use WSL (then it is a Linux machine) or Docker
8
9
  mode inside WSL. Node 22.12 or newer.
@@ -16,89 +17,249 @@ capybara-device status [--json]
16
17
  capybara-device logout
17
18
  ```
18
19
 
19
- `login` shows a code like `BCDF-GHJK`; with `--no-browser` it prints the address (`<url>/device`) and
20
- the code to enter on any signed-in browser, where you pick the org and the environment (a new one or
20
+ `login` shows a code like `BCDF-GHJK`; with `--no-browser` it prints the address (`<url>/devices/link`) and
21
+ the code to enter on any signed-in browser, where you pick the org and the device (a new one or
21
22
  an existing connected one of yours) after reading what the program can do. Logging in again from
22
- another machine into the same environment replaces the first machine (its credential is revoked).
23
+ another machine into the same device replaces the first machine (its credential is revoked).
23
24
  `stop` ends the running program, `drain` makes it accept no new commands and exit when the running
24
- ones finish. `logout` stops a running program, then forgets the credential (the machine stays
25
- connected on the platform until it is revoked there). Deleting the environment in the web app
25
+ ones finish (`drain --wait [--timeout <seconds>]` returns only once it has exited, at most 600 s by
26
+ default). Both signal only a pid the pid file names **and** `ps` shows to be `capybara-device`,
27
+ started before the file was written; a stale file (a reused pid) is never signalled. When the login
28
+ service runs the program, `stop` refuses and points at `service stop`; `drain` exits 0, which the
29
+ service leaves stopped until `service start`. `logout` stops a
30
+ running program, then forgets the credential (the machine stays
31
+ connected on the platform until it is revoked there). Deleting the device in the web app
26
32
  revokes the machine and stops the program; the files in the working directory stay on your machine.
27
33
 
28
34
  The deployment must route `/device/connect` on its public URL to the gateway role (see
29
35
  [Connected devices](https://github.com/capybara-hq/core/blob/main/docs/deploy/README.md#connected-devices)).
30
- While connecting keeps failing, `start` retries and prints why at most once a minute: the HTTP
31
- status (a 404 usually means that route is missing), the close reason, or the network error.
36
+ While connecting keeps failing, `start` retries with exponential backoff (capped at 60 s, with
37
+ jitter) and never gives up: a failure different from the last one is printed at once, the same one
38
+ at most once a minute. The message is the HTTP status (a 404 usually means that route is missing),
39
+ the close reason, or the network error.
32
40
 
33
- `start` exits 0, after printing why, when retrying cannot help: the machine was revoked or the
34
- environment deleted, the program is too old for the deployment (426), another login replaced this
35
- connection, or the machine is not logged in. Other failures exit non-zero, so a service (below)
36
- restarts the program after those and leaves it stopped after the terminal ones; fix the cause
37
- (log in again, upgrade), then run `start` or `service install` again.
41
+ `start` exits 0 only for a deliberate stop: the machine was revoked or the device deleted, another
42
+ connection of this device replaced this one, `stop` / `drain` / `logout`, or the machine is not
43
+ logged in. The login service (below) leaves such an exit stopped. Every exit it must recover from is
44
+ non-zero, and the service restarts it: a crash, an invalid start (`Cannot start: …`), or a
45
+ deployment that needs a newer program (426: upgrade the package in place and the next restart runs
46
+ the new one). A failing connection never ends the program: it reconnects with backoff, so a kernel
47
+ restart needs no service restart. After logging in again, start the installed service with
48
+ `capybara-device service restart`; `capybara-device service status` shows what is true now.
38
49
 
39
50
  If the working directory (or its marker `.capybara-device`, or one of `workspace/`, `skills/`,
40
51
  `tmp/`) is removed, the program never recreates it: operations answer that the files are lost and
41
- the environment page says so. To start afresh, run `capybara-device logout` and then
42
- `capybara-device login` into the same environment: login recreates the directory and the marker,
43
- and the platform rebuilds the environment on its next use.
52
+ the device page says so. To start afresh, run `capybara-device logout` and then
53
+ `capybara-device login` into the same device: login recreates the directory and the marker,
54
+ and the platform rebuilds the device on its next use.
44
55
 
45
56
  Commands: `login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]`, `logout`,
46
- `status [--json]`, `start`, `stop`, `drain`, `policy [show|set <key> <value>]` and
47
- `service install|uninstall`.
57
+ `status [--json]` (it prints the command mode too), `start`, `stop`,
58
+ `drain [--wait] [--timeout <seconds>]`, `mode [auto|sandbox] [--yes]`,
59
+ `policy [show | set <key> <value> [--yes] | add|remove <key> <value>]` and
60
+ `service install|uninstall|start|stop|restart|status`.
61
+ `mode` is the only way to switch the command mode (`policy set mode` points there); `mode auto`
62
+ prints the risk text and asks for confirmation unless `--yes` is given.
48
63
 
49
64
  State lives in `$XDG_CONFIG_HOME/capybara-device` (default `~/.config/capybara-device`):
50
65
  `credential.json` (mode 0600; the program refuses a file other users can read; it also holds the
51
66
  deployment's reconnect grace and frame limit: a result larger than the frame limit is answered
52
67
  with an error instead) and `policy.json` (a file with wrong field types stops `start` with an
53
- error naming it).
54
- The working directory (default `~/capybara-device/<environmentId>`) holds `workspace/`, `skills/`
68
+ error naming it; once running, the program re-reads the file when it changes, and a broken edit
69
+ keeps the last valid policy and logs one error). Changes made with `capybara-device policy` take
70
+ `policy.json.lock`, so two writers never lose an update; keys this version does not know are kept.
71
+ The working directory (default `~/capybara-device/<deviceId>`) holds `workspace/`, `skills/`
55
72
  and `tmp/`.
56
73
 
57
- In OS mode every command runs inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux
58
- bubblewrap; Linux needs `bwrap` and `socat`): writes only under `workspace/` and `tmp/`,
59
- `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 environment'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:
74
+ In OS mode a device runs every command in one of two modes (`mode` in `policy.json`; switch it
75
+ with `capybara-device mode`):
76
+
77
+ - **auto** (the default of a new login): commands run directly on this computer as you — your real
78
+ `HOME`, `PATH`, environment, caches, credentials (SSH keys, `gh`, cloud CLIs), Docker and any
79
+ network. It is what a coding agent without an OS sandbox has, and what Claude Code calls auto
80
+ mode. The deployment reviews every command before it runs and blocks, or asks about, the
81
+ dangerous ones (deleting outside the workspace, sending a secret away, force-pushing a protected
82
+ branch). The platform's file tools reach any absolute path on the machine.
83
+ - **sandbox**: today's strict `@anthropic-ai/sandbox-runtime` profile (macOS Seatbelt, Linux
84
+ bubblewrap; Linux needs `bwrap` and `socat`). Writes only under `workspace/` and `tmp/`,
85
+ `skills/` read only, `HOME` = the workspace, `~/.ssh`, cloud CLI credentials, `~/.netrc`,
86
+ `~/.gnupg`, browser profiles and this program's state directory unreadable, no local binding or
87
+ unix sockets, and network only to the domains of the local policy that the organization's
88
+ allowlist also admits (with an empty list, no network at all). Commands keep their package
89
+ caches in the workspace like any other file.
90
+
91
+ If the OS sandbox is unavailable on the machine (an unsupported platform or missing dependencies,
92
+ such as `bwrap` / `socat` on Linux), the device still starts and serves: auto mode works, and every
93
+ sandbox-mode command is refused with the reason and how to fix it (`capybara-device mode auto`, or
94
+ install the dependencies and restart). `capybara-device mode sandbox` is refused on such a machine
95
+ and the policy stays in auto; nothing ever runs unsandboxed by falling back. File operations
96
+ (read, write, stat) there follow only a fresh command decision (the latest command, within a
97
+ minute): without one they are refused, never served on the host. `login` into an organization that
98
+ forbids auto mode checks the OS sandbox first: when it is unavailable, no sandbox policy is written
99
+ and the login line says what to install (or to log in with `--mode docker`).
63
100
 
64
101
  ```bash
65
- capybara-device policy set allowedDomains registry.npmjs.org,*.github.com
66
- capybara-device policy show # changes apply at the next start
102
+ capybara-device mode # print the current mode
103
+ capybara-device mode sandbox # switch to the sandbox
104
+ capybara-device mode auto # prints the risk text and asks; or add --yes
105
+ capybara-device policy add allowedDomains files.slack.com # sandbox mode
106
+ capybara-device policy remove allowedDomains files.slack.com
107
+ capybara-device policy show
108
+ ```
109
+
110
+ A change applies at the next command; a running program does not need a restart. Turning the
111
+ sandbox back on stops the commands still running in auto mode. Auto mode is set only on the
112
+ machine: the deployment may narrow a device to `sandbox` but never turn auto mode on. An
113
+ organization can allow or forbid auto mode; when it forbids it, this device runs in the sandbox
114
+ and its summary says so, and the device's own `mode sandbox` always wins. `add` and `remove` work
115
+ on `allowedDomains` and `allowCredentials`; every domain must be a lowercase host name (optionally
116
+ `*.` for subdomains, never the apex), never an IP address or an internal name. They apply in
117
+ sandbox mode only.
118
+
119
+ A command ends with everything it started: once it returns (or times out, or is stopped), the
120
+ program kills what it left running, such as `server &` or `nohup …`, because inside the sandbox no
121
+ later command may signal another command's processes. Its process group goes at once, and a process
122
+ that left the group (`setsid`) is found by the marker every process of the command carries. On
123
+ macOS only a background task launch (`Bash` with `run_in_background`, whose command starts with the
124
+ line `# capybara: background task launch`) keeps what it starts. On Linux the sandbox's pid
125
+ namespace already ends every process with its command. In Docker mode and without a sandbox, a
126
+ later command can stop what an earlier one left, so nothing is killed.
127
+
128
+ When a command is refused a domain, the program says why. Clients that print the proxy's answer
129
+ show a reason such as `capybara: files.slack.com is not in this device's allowed domains`, and
130
+ after the command its stderr ends with a trailer naming each refused host (at most 20) and who can
131
+ lift it:
132
+
133
+ ```text
134
+ [capybara-device] Network access was blocked:
135
+ - 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).
136
+ - api.foo.com:443: not in the organization's network allowlist. Only an organization admin can add it.
137
+ - 10.0.0.5:22: a private or local address; commands can never reach it.
138
+ ```
139
+
140
+ The trailer is part of the command's output, so the agent reads it too. It comes after the
141
+ output the deployment asked for (`maxOutputBytes`), so stderr can exceed that cap by the trailer's
142
+ lines (at most 21).
143
+
144
+ In OS mode each command's result also carries the refused hosts and their layers, so the
145
+ deployment can ask the device owner on the spot (the device announces this in its hello, together
146
+ with a summary of its local policy: the owner's `mode`, never cut by an exec's ceiling (the
147
+ deployment applies its own), and the sandbox-mode `allowedDomains`).
148
+
149
+ ### Sandbox mode details
150
+
151
+ In sandbox mode commands keep `HOME` = `workspace/`, writes stay inside the device directory, the
152
+ secret paths stay unreadable, and the network proxy refuses loopback, private addresses and
153
+ internal names as destinations. The device's `allowedDomains` are intersected with the
154
+ organization's allowlist; a host either list refuses is reported as described above.
155
+
156
+ Version managers (asdf, nvm, pyenv, mise, …) find their data under the real home, read only, so
157
+ their shims work with `HOME` = the workspace. Git can read a repository, but `.git/config` and
158
+ `.git/hooks` stay unwritable: a hook or `core.sshCommand` a command wrote would run when you later
159
+ run git there. When you want git to write (init, clone, remotes) or commands to use your
160
+ credentials, use auto mode.
161
+
162
+ ### The auto mode risk
163
+
164
+ In auto mode agent commands have your full capability. The deployment reviews every command and
165
+ blocks or asks about the dangerous ones, but that review is the boundary, not an OS sandbox: prompt
166
+ injection can still make an agent attempt to delete files or send your credentials away. Commands
167
+ can also read this program's own credential (`credential.json`): if you suspect misuse, run
168
+ `capybara-device logout` and log in again, which revokes it. Keep auto mode to your own development
169
+ machine, with agents and material you trust; `capybara-device mode sandbox` turns the sandbox back
170
+ on.
171
+
172
+ ### Changes from the deployment
173
+
174
+ The deployment changes the local policy only by narrowing it: it may add or remove
175
+ `allowedDomains` (an approval adds an exact host; the device page may add a `*.` wildcard) and set
176
+ `mode: "sandbox"`. It can never set `mode: "auto"` — that is `capybara-device mode auto` on the
177
+ machine, with its risk text and confirmation. Every host is validated like a local one, the change
178
+ is written under `policy.json.lock`, and it applies at the next command. Each change from the
179
+ deployment is recorded in the local command log (`commands.log`, next to `policy.json`) with who
180
+ decided it, and so is a refused attempt and the grants a command was given:
181
+
182
+ ```text
183
+ {"op":"policy","detail":"policy add files.slack.com by Ada Lovelace (acc_123) via web, approval apr_456",...}
184
+ {"op":"policy","detail":"policy refused mode auto by Ada Lovelace (acc_123) via web",...}
185
+ {"op":"exec","detail":"grants run run_789 by acc_123: files.slack.com",...}
67
186
  ```
68
187
 
188
+ A run's or a scheduled task's network grants apply in sandbox mode only, within the organization's
189
+ allowlist; auto mode has the machine's own network, so grants do nothing there.
190
+
191
+ Limit to know: commands of one device run as the same user, and the sandbox runtime ties a
192
+ command's list (including its run grants) to the proxy credentials it hands that command. Another
193
+ command running at the same time on the same device could reuse them, so a run's grants may be
194
+ usable by a concurrent command of another run on that device: same owner, same device.
195
+
69
196
  Limits to know: the platform's `Grep` tool assumes GNU grep, so on macOS (BSD grep) in OS mode some
70
197
  Grep options behave differently or fail. Docker mode (a Linux container) does not have this issue.
71
198
 
72
- Not enforced yet in OS mode: the `cpu` and `memoryMb` ceilings, and `allowCredentials` (commands
73
- get no local credentials at all). Processes a command leaves running are killed with it by tag;
74
- on macOS a child that leaves the command's process group and runs only Apple system binaries
75
- cannot be found again (Linux runs each command in its own pid namespace, which takes every child
76
- down with it).
199
+ Not enforced yet in OS mode: the `cpu` and `memoryMb` ceilings. In auto mode commands already see
200
+ the owner's credentials, so `allowCredentials` has nothing to add; in sandbox mode they get none.
201
+ Processes a command leaves running are killed when it ends; on macOS a child that leaves the
202
+ command's process group and runs only Apple system binaries cannot be found by its marker
203
+ (`ps -E` hides their environment), so it survives (Linux runs each command in its own pid
204
+ namespace, which takes every child down with it).
77
205
 
78
206
  ## Docker mode
79
207
 
80
- `login --mode docker` runs every command with `docker exec` in one container per environment
81
- (`capybara-device-<environmentId>`, started on first use from
208
+ `login --mode docker` runs every command with `docker exec` in one container per device
209
+ (`capybara-device-<deviceId>`, started on first use from
82
210
  `ghcr.io/capybara-hq/capybara-sandbox:<tag>`, the sandbox image of this release). On Linux commands
83
211
  run as your own uid:gid, so they can write the mounted directories you own (a root user falls back to
84
212
  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
213
  at `/workspace`, `/skills` and `/tmp`; the container has a read-only root file system, a pids limit of 1024, `--memory-swap` equal to
86
214
  `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.
215
+ `memoryMb` become `--cpus` and `--memory`. The container is reused while its mounts and flags
216
+ match and recreated when they change (at the next command that finds it idle); it stays running
217
+ (idle) between starts. Commands always have the container's own localhost and unix sockets.
218
+
219
+ Docker mode has no per-domain network filter, so the mode alone decides:
89
220
 
90
- Docker mode has no domain allowlist: a command has either no network (`--network none`, when the
91
- local policy or the environment'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.
221
+ - **auto**: the container runs on Docker's default bridge (the whole internet and this machine's
222
+ network), and the platform's file tools reach any absolute path in the container.
223
+ - **sandbox**: the container has no network at all, and file operations stay in the mounted roots.
224
+
225
+ The network is switched between the two without recreating the container (a container disconnected
226
+ from every network has no network, the same as `--network none`). Use OS mode's sandbox when you
227
+ need to allow single domains.
93
228
 
94
229
  ## Running at login
95
230
 
96
231
  `capybara-device service install` makes the program start at login: on macOS a launchd agent
97
232
  (`~/Library/LaunchAgents/top.capybara.device.plist`, log `service.log` in the state directory), on
98
233
  Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). Both restart the
99
- program when it exits non-zero (systemd after 5 s) and leave it stopped after a terminal exit (code
100
- 0, see above); once the cause is fixed, `service install` again starts it. A user unit runs only
234
+ program only when it exits non-zero: the macOS agent uses `KeepAlive { SuccessfulExit: false }`, at
235
+ most every 30 s (`ThrottleInterval`); systemd `Restart=on-failure`, after 5 s. Exit 0 is a deliberate
236
+ stop and stays stopped.
237
+
238
+ `service start|stop|restart` control it without knowing launchctl or systemctl. `stop` unloads the
239
+ service (the plist or unit stays) rather than signalling the program; running commands end with
240
+ it, and it reports a failure when the service is still loaded afterwards. `start` and `restart`
241
+ wait (up to 10 s) until the service manager runs the program and report a failure, pointing at
242
+ `service.log`, when it does not come back; `service start` refuses while a program started in a
243
+ terminal runs ("stop it first"). On macOS a loaded agent whose program exited is started again with
244
+ `launchctl kickstart`. `restart` reloads the program from the installed `bin`, so it is **the way to
245
+ apply a package upgrade**: `npm i -g @capybara-hq/device@latest && capybara-device service restart`.
246
+ The top-level `stop` refuses only when the service manager runs the program it would signal (launchd
247
+ has the agent loaded, or systemd the unit active, and its pid is the pid file's) and points at
248
+ `service stop`; a program started in a terminal is signalled as before. `start` in a terminal says
249
+ how to restart the installed service; started by the service manager (launchd sets
250
+ `XPC_SERVICE_NAME`, systemd `INVOCATION_ID`) it prints no such hint.
251
+
252
+ `capybara-device service status` says one of four things: not installed; installed but not loaded
253
+ (`service start`); loaded but the program is not running, i.e. it exited (the reason is at the end of
254
+ `service.log`; fix it, then `service restart`); or running, with the service manager's pid and the
255
+ program's **version**. When the package at the service file's `bin` path (its `package.json`) is a
256
+ different version from the running program, it adds the restart command: an upgrade the service has
257
+ not picked up yet. The pid file records the version (`{pid, version, startedAt}`); one written by an
258
+ older program reads as "version unknown". A user unit runs only
101
259
  while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
102
260
  running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
103
261
  starts. The service runs `node <bin> start` with the `PATH` of the shell that installed it (so
104
- `docker` is found). `service uninstall` reverses it.
262
+ `docker` is found). `service uninstall` reverses it. On macOS, installing again first boots the old
263
+ agent out and waits (up to 10 s) until launchd has let it go, because `launchctl bootout` returns
264
+ before that; a `bootstrap` that still fails with error 5 (Input/output error) is retried a few
265
+ times. On Linux, installing again restarts the unit so the new file applies.
package/dist/api.d.ts CHANGED
@@ -9,11 +9,16 @@ export interface AuthorizeResponse {
9
9
  export interface TokenResponse {
10
10
  credential: string;
11
11
  orgId: string;
12
- environmentId: string;
12
+ deviceId: string;
13
13
  connectUrl: string;
14
14
  reconnectGraceSeconds: number;
15
15
  /** The program uses 16 MiB when it is absent. */
16
16
  maxFrameBytes?: number;
17
+ /**
18
+ * Whether the organization allows auto mode (`allowed`, the default) or forbids it (`off`):
19
+ * `login` prints the matching line. Absent counts as allowed.
20
+ */
21
+ autoMode?: "allowed" | "off";
17
22
  }
18
23
  /** An error response of the kernel: `{ error: { code, message } }`. */
19
24
  export declare class ApiError extends Error {
package/dist/args.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SandboxMode } from "./state.js";
1
2
  export type DeviceMode = "os" | "docker";
2
3
  /** A parsed command line. */
3
4
  export type Command = {
@@ -17,21 +18,31 @@ export type Command = {
17
18
  command: "stop";
18
19
  } | {
19
20
  command: "drain";
21
+ /** `--wait`: wait until the program has exited. */
22
+ wait?: true;
23
+ /** `--timeout <seconds>` with `--wait` (default 600). */
24
+ timeoutSeconds?: number;
20
25
  } | {
21
26
  command: "policy";
22
27
  action: "show";
23
28
  } | {
24
29
  command: "policy";
25
- action: "set";
30
+ action: "set" | "add" | "remove";
26
31
  key: string;
27
32
  value: string;
33
+ } | {
34
+ command: "mode";
35
+ /** Absent: print the current mode. */
36
+ mode?: SandboxMode;
37
+ /** `--yes`: confirms `mode auto` without asking. */
38
+ yes?: true;
28
39
  } | {
29
40
  command: "service";
30
- action: "install" | "uninstall";
41
+ action: "install" | "uninstall" | "start" | "stop" | "restart" | "status";
31
42
  } | {
32
43
  command: "help";
33
44
  };
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 environment\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";
45
+ 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 mode [auto|sandbox] [--yes]\n Show or choose how commands run: auto (as you on this\n machine, every command reviewed) or sandbox (applies at\n the next command; auto needs --yes or a y at the prompt)\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n Replace one field (cpu, memoryMb, allowCredentials)\n capybara-device policy add|remove allowedDomains <host>\n Allow or stop allowing a domain in sandbox mode\n capybara-device policy add|remove allowCredentials <name>\n Allow or stop allowing a credential in sandbox mode\n capybara-device service install|uninstall\n Run at login as a user service, or remove it\n capybara-device service start|stop|restart\n Start, stop or restart the login service\n capybara-device service status Report whether the login service is loaded, what is running,\n and whether it is older than the installed program";
35
46
  /** Thrown for a bad command line; the message is shown with the usage. */
36
47
  export declare class UsageError extends Error {
37
48
  }
package/dist/args.js CHANGED
@@ -4,13 +4,28 @@ export const USAGE = `Usage:
4
4
  Connect this machine: approve the code in the browser
5
5
  capybara-device logout Forget the credential on this machine
6
6
  capybara-device status [--json] Show whether this machine is logged in
7
- capybara-device start Connect and serve the environment
7
+ capybara-device start Connect and serve the device
8
8
  capybara-device stop Stop the running program
9
- capybara-device drain Finish running commands, accept no new ones, then stop
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)
12
+ capybara-device mode [auto|sandbox] [--yes]
13
+ Show or choose how commands run: auto (as you on this
14
+ machine, every command reviewed) or sandbox (applies at
15
+ the next command; auto needs --yes or a y at the prompt)
10
16
  capybara-device policy [show] Show the local policy
11
17
  capybara-device policy set <key> <value>
18
+ Replace one field (cpu, memoryMb, allowCredentials)
19
+ capybara-device policy add|remove allowedDomains <host>
20
+ Allow or stop allowing a domain in sandbox mode
21
+ capybara-device policy add|remove allowCredentials <name>
22
+ Allow or stop allowing a credential in sandbox mode
12
23
  capybara-device service install|uninstall
13
- Run at login as a user service`;
24
+ Run at login as a user service, or remove it
25
+ capybara-device service start|stop|restart
26
+ Start, stop or restart the login service
27
+ capybara-device service status Report whether the login service is loaded, what is running,
28
+ and whether it is older than the installed program`;
14
29
  /** Thrown for a bad command line; the message is shown with the usage. */
15
30
  export class UsageError extends Error {
16
31
  }
@@ -66,26 +81,75 @@ export function parseCommandLine(argv) {
66
81
  case "logout":
67
82
  case "start":
68
83
  case "stop":
69
- case "drain":
70
84
  return noArgs(name);
85
+ case "drain": {
86
+ const { values, positionals } = parse(rest, {
87
+ wait: { type: "boolean" },
88
+ timeout: { type: "string" },
89
+ });
90
+ if (positionals.length > 0)
91
+ throw new UsageError("drain takes no positional arguments");
92
+ if (values.timeout !== undefined && values.wait !== true) {
93
+ throw new UsageError("--timeout needs --wait");
94
+ }
95
+ if (values.wait !== true)
96
+ return { command: "drain" };
97
+ if (values.timeout === undefined)
98
+ return { command: "drain", wait: true };
99
+ const seconds = Number(values.timeout);
100
+ if (!Number.isInteger(seconds) || seconds < 1) {
101
+ throw new UsageError("--timeout must be a whole number of seconds, at least 1");
102
+ }
103
+ return { command: "drain", wait: true, timeoutSeconds: seconds };
104
+ }
71
105
  case "policy": {
72
106
  const { positionals } = parse(rest, {});
73
107
  const [action, key, value, ...extra] = positionals;
74
- if (action === undefined || (action === "show" && key === undefined && extra.length === 0)) {
108
+ if (action === undefined)
109
+ return { command: "policy", action: "show" };
110
+ if (action === "show" && key === undefined && extra.length === 0) {
75
111
  return { command: "policy", action: "show" };
76
112
  }
77
- if (action === "set" && key !== undefined && value !== undefined && extra.length === 0) {
78
- return { command: "policy", action: "set", key, value };
113
+ if ((action === "set" || action === "add" || action === "remove") &&
114
+ key !== undefined &&
115
+ value !== undefined &&
116
+ extra.length === 0) {
117
+ return { command: "policy", action, key, value };
79
118
  }
80
- throw new UsageError("usage: policy [show | set <key> <value>]");
119
+ throw new UsageError("usage: policy [show | set <key> <value> | add|remove <key> <value>]");
120
+ }
121
+ case "mode": {
122
+ const { values, positionals } = parse(rest, { yes: { type: "boolean", short: "y" } });
123
+ const [which, ...extra] = positionals;
124
+ if (extra.length > 0) {
125
+ throw new UsageError("usage: mode [auto|sandbox] [--yes]");
126
+ }
127
+ if (which !== undefined && which !== "auto" && which !== "sandbox") {
128
+ throw new UsageError("mode must be auto or sandbox");
129
+ }
130
+ const yes = values.yes === true;
131
+ if (yes && which === undefined) {
132
+ throw new UsageError("--yes needs a mode: mode auto|sandbox");
133
+ }
134
+ return {
135
+ command: "mode",
136
+ ...(which !== undefined && { mode: which }),
137
+ ...(yes && which !== undefined && { yes: true }),
138
+ };
81
139
  }
82
140
  case "service": {
83
141
  const { positionals } = parse(rest, {});
84
142
  const [action, ...extra] = positionals;
85
- if ((action === "install" || action === "uninstall") && extra.length === 0) {
143
+ if ((action === "install" ||
144
+ action === "uninstall" ||
145
+ action === "start" ||
146
+ action === "stop" ||
147
+ action === "restart" ||
148
+ action === "status") &&
149
+ extra.length === 0) {
86
150
  return { command: "service", action };
87
151
  }
88
- throw new UsageError("usage: service install|uninstall");
152
+ throw new UsageError("usage: service install|uninstall|start|stop|restart|status");
89
153
  }
90
154
  default:
91
155
  throw new UsageError(`unknown command ${name}`);
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import type { Executor } from "./exec/types.js";
2
- import { type Credential, type Policy } from "./state.js";
2
+ import type { ProcessLookup } from "./pid.js";
3
+ import type { PolicyStore } from "./policy-store.js";
4
+ import type { RunSystem } from "./service/manager.js";
5
+ import { type Credential } from "./state.js";
3
6
  export interface CliEnv {
4
7
  env?: Record<string, string | undefined>;
5
8
  home?: string;
@@ -9,10 +12,30 @@ export interface CliEnv {
9
12
  openBrowser?: (url: string) => void;
10
13
  out?: (line: string) => void;
11
14
  err?: (line: string) => void;
12
- createExecutor?: (cred: Credential, policy: Policy) => Promise<Executor> | Executor;
15
+ createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
13
16
  kill?: typeof process.kill;
14
- /** Runs a system command for `service` (default: execFileSync). */
15
- runSystem?: (cmd: string, args: string[]) => void;
17
+ /** Runs a system command for `service` and `stop` and returns its output (default: execFileSync). */
18
+ runSystem?: RunSystem;
19
+ /** Looks a process up by pid, to check a pid file names this program (default: `ps`). */
20
+ ps?: ProcessLookup;
21
+ /** Standard input is a terminal (default: `process.stdin.isTTY`): a confirmation may be asked. */
22
+ stdinIsTTY?: boolean;
23
+ /** Whether the OS sandbox can run here, for `login` and `mode` (default: the runtime's check). */
24
+ sandboxAvailable?: () => {
25
+ ok: true;
26
+ } | {
27
+ ok: false;
28
+ reason: string;
29
+ };
30
+ /** Asks one question on the terminal and resolves the answer (default: node:readline). */
31
+ ask?: (question: string) => Promise<string>;
16
32
  }
33
+ /**
34
+ * Logged when the local policy switches between auto and sandbox. It names the local choice, not
35
+ * the effective mode: the organization's ceiling still cuts it (a device whose org forbids auto
36
+ * runs in the sandbox even with this policy).
37
+ */
38
+ export declare const AUTO_MODE_ON = "This machine's local policy is auto mode; the deployment's ceiling applies.";
39
+ export declare const AUTO_MODE_OFF = "This machine's local policy is sandbox mode; commands still running in auto mode were stopped.";
17
40
  /** Runs one command line and returns the exit code. */
18
41
  export declare function runCli(argv: string[], io?: CliEnv): Promise<number>;