@capybara-hq/device 0.1.0-rc.0 → 0.1.0-rc.10

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 (64) hide show
  1. package/README.md +187 -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 +14 -2
  6. package/dist/cli.js +59 -10
  7. package/dist/client.d.ts +14 -3
  8. package/dist/client.js +92 -18
  9. package/dist/command-log.d.ts +8 -0
  10. package/dist/commands/drain.d.ts +13 -0
  11. package/dist/commands/drain.js +28 -0
  12. package/dist/commands/login.js +68 -11
  13. package/dist/commands/mode.d.ts +52 -0
  14. package/dist/commands/mode.js +108 -0
  15. package/dist/commands/policy.d.ts +13 -4
  16. package/dist/commands/policy.js +162 -33
  17. package/dist/commands/service.d.ts +18 -3
  18. package/dist/commands/service.js +175 -9
  19. package/dist/commands/start.d.ts +14 -3
  20. package/dist/commands/start.js +37 -5
  21. package/dist/commands/status.js +12 -4
  22. package/dist/commands/stop.d.ts +9 -2
  23. package/dist/commands/stop.js +13 -2
  24. package/dist/exec/docker.d.ts +41 -13
  25. package/dist/exec/docker.js +123 -57
  26. package/dist/exec/fs-helper.d.ts +13 -8
  27. package/dist/exec/fs-helper.js +31 -13
  28. package/dist/exec/groups.d.ts +42 -0
  29. package/dist/exec/groups.js +100 -0
  30. package/dist/exec/host.d.ts +53 -0
  31. package/dist/exec/host.js +183 -0
  32. package/dist/exec/os.d.ts +85 -15
  33. package/dist/exec/os.js +208 -36
  34. package/dist/exec/reap.d.ts +41 -0
  35. package/dist/exec/reap.js +89 -0
  36. package/dist/exec/sandbox-messages.d.ts +14 -0
  37. package/dist/exec/sandbox-messages.js +21 -0
  38. package/dist/exec/shared.d.ts +42 -13
  39. package/dist/exec/shared.js +94 -16
  40. package/dist/exec/switch.d.ts +91 -0
  41. package/dist/exec/switch.js +164 -0
  42. package/dist/exec/types.d.ts +28 -4
  43. package/dist/index.d.ts +1 -1
  44. package/dist/network.d.ts +45 -0
  45. package/dist/network.js +154 -0
  46. package/dist/pid.d.ts +13 -1
  47. package/dist/pid.js +54 -7
  48. package/dist/policy-ops.d.ts +47 -0
  49. package/dist/policy-ops.js +90 -0
  50. package/dist/policy-store.d.ts +43 -0
  51. package/dist/policy-store.js +94 -0
  52. package/dist/policy.d.ts +36 -16
  53. package/dist/policy.js +77 -19
  54. package/dist/public-suffix.d.ts +6 -0
  55. package/dist/public-suffix.js +79 -0
  56. package/dist/server-ops.d.ts +46 -7
  57. package/dist/server-ops.js +285 -29
  58. package/dist/service/installed.d.ts +5 -0
  59. package/dist/service/installed.js +14 -0
  60. package/dist/service/launchd.d.ts +11 -1
  61. package/dist/service/launchd.js +14 -5
  62. package/dist/state.d.ts +50 -6
  63. package/dist/state.js +195 -16
  64. package/package.json +3 -3
@@ -1,9 +1,15 @@
1
1
  import { validateAllowHost } from "@capybara-hq/plugin-sdk";
2
- import { policyPath, readPolicy, writePolicy } from "../state.js";
3
- const KEYS = ["allowedDomains", "allowCredentials", "cpu", "memoryMb"];
4
- /** What the OS mode does not enforce yet, shown with every `show` and `set`. */
5
- export const NOT_ENFORCED_NOTE = "Note: in OS mode cpu and memoryMb are not enforced yet, and allowCredentials is not used: " +
6
- "commands get no local credentials.";
2
+ import { PolicyStore } from "../policy-store.js";
3
+ import { policyPath, readCredential } from "../state.js";
4
+ /** The fields `show` prints and `set` may replace. */
5
+ const KEYS = ["allowedDomains", "allowCredentials", "cpu", "memoryMb", "mode"];
6
+ /** What OS mode does not enforce yet, shown with `show` and with a limits change. */
7
+ export const NOT_ENFORCED_NOTE = "Note: in OS mode cpu and memoryMb are not enforced yet; allowCredentials is ignored (auto " +
8
+ "mode already has the owner's credentials, sandbox mode gets none).";
9
+ /** Shown when a Docker-mode device's policy is shown or given allowed domains. */
10
+ export const DOCKER_DOMAIN_NOTE = "Note: this device runs commands in Docker mode, where the mode alone decides network " +
11
+ "access (auto: the default bridge; sandbox: no network). Allowed domains apply in OS mode's " +
12
+ "sandbox only.";
7
13
  function list(value) {
8
14
  return value
9
15
  .split(",")
@@ -19,56 +25,179 @@ function ceiling(key, value) {
19
25
  }
20
26
  return n;
21
27
  }
28
+ /** Whether this machine is logged in in Docker mode (false when unknown). */
29
+ function dockerMode(stateDir) {
30
+ try {
31
+ return readCredential(stateDir)?.mode === "docker";
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ /** The keys `add` and `remove` work on: the list fields. */
38
+ const LIST_KEYS = ["allowedDomains", "allowCredentials"];
39
+ /** Lowercased, validated hosts; throws naming the first bad one. */
40
+ function domains(value) {
41
+ const out = list(value).map((d) => d.toLowerCase());
42
+ for (const d of out) {
43
+ const errors = validateAllowHost(d);
44
+ if (errors.length > 0)
45
+ throw new Error(`"${d}": ${errors.join("; ")}`);
46
+ }
47
+ return out;
48
+ }
49
+ /** The new value of a list field after `add` / `remove`; unchanged entries are reported. */
50
+ function edit(current, action, key, values, out) {
51
+ // Domains compare ignoring case (a hand-edited file may hold any spelling).
52
+ const norm = key === "allowedDomains" ? (v) => v.toLowerCase() : (v) => v;
53
+ const has = (list, v) => list.some((x) => norm(x) === norm(v));
54
+ if (action === "add") {
55
+ const next = [...current];
56
+ for (const v of values) {
57
+ if (has(next, v))
58
+ out(`${v} is already in ${key}.`);
59
+ else {
60
+ next.push(v);
61
+ out(`Added ${v} to ${key}.`);
62
+ }
63
+ }
64
+ return next;
65
+ }
66
+ for (const v of values)
67
+ out(has(current, v) ? `Removed ${v} from ${key}.` : `${v} is not in ${key}.`);
68
+ return current.filter((x) => !has(values, x));
69
+ }
70
+ /** What `policy show` says the mode gives on this machine (English, one line each). */
71
+ export function describeMode(policy, runMode = "os") {
72
+ if (policy.mode === "auto") {
73
+ if (runMode === "docker") {
74
+ return [
75
+ "Mode: auto. Commands run in the device's container on its default bridge, and the " +
76
+ "platform's file tools reach any path in the container; the deployment reviews every " +
77
+ "command and blocks or asks about dangerous ones.",
78
+ ];
79
+ }
80
+ return [
81
+ "Mode: auto. Commands run as you on this machine, with their files, credentials and " +
82
+ "network; the deployment reviews every command and blocks or asks about dangerous ones.",
83
+ "Allowed domains apply in sandbox mode only (capybara-device mode sandbox).",
84
+ ];
85
+ }
86
+ if (runMode === "docker") {
87
+ return [
88
+ "Mode: sandbox. Commands run in the device's container with no network; only the " +
89
+ "workspace, skills and temporary files are writable.",
90
+ ];
91
+ }
92
+ return [
93
+ "Mode: sandbox. Only the workspace, skills and temporary files are writable; the network " +
94
+ "reaches the allowed hosts.",
95
+ ];
96
+ }
22
97
  /**
23
- * `policy show` prints the local policy; `policy set <key> <value>` changes one field. Only the
24
- * machine's user edits this file: the cloud never writes it. Changes apply at the next start.
98
+ * `policy show` prints the local policy and what its mode gives on this machine;
99
+ * `policy set <key> <value>` replaces one field; `policy add|remove <key> <value>` adds or removes
100
+ * entries of a list field. The mode is set with `capybara-device mode`. The machine's user edits
101
+ * this file; the deployment changes it only through the `policy` op (narrowing only: hosts and
102
+ * `mode: "sandbox"`, never auto). Writes take policy.json.lock, and a running program applies the
103
+ * change at its next command.
25
104
  */
26
- export function policyCommand(cmd, deps) {
105
+ export async function policyCommand(cmd, deps) {
27
106
  const { stateDir, out, err } = deps;
28
- let policy;
107
+ let store;
29
108
  try {
30
- policy = readPolicy(stateDir);
109
+ store = new PolicyStore(stateDir);
31
110
  }
32
111
  catch (e) {
33
112
  err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
34
113
  return 1;
35
114
  }
115
+ const docker = dockerMode(stateDir);
36
116
  if (cmd.action === "show") {
117
+ const policy = store.current();
37
118
  out(JSON.stringify(policy, null, 2));
119
+ for (const l of describeMode(policy, docker ? "docker" : "os"))
120
+ out(l);
121
+ if (docker)
122
+ out(DOCKER_DOMAIN_NOTE);
38
123
  out(NOT_ENFORCED_NOTE);
39
124
  return 0;
40
125
  }
41
- const { key, value } = cmd;
42
- const next = { ...policy };
126
+ const { action, key, value } = cmd;
127
+ // Parse and validate before taking the lock; apply inside it, against the file as it is then.
128
+ let change;
43
129
  try {
44
- switch (key) {
45
- case "allowedDomains": {
46
- const domains = list(value).map((d) => d.toLowerCase());
47
- for (const d of domains) {
48
- const errors = validateAllowHost(d);
49
- if (errors.length > 0)
50
- throw new Error(`"${d}": ${errors.join("; ")}`);
130
+ if (action === "set") {
131
+ switch (key) {
132
+ case "allowedDomains": {
133
+ const next = [...new Set(domains(value))];
134
+ change = (p) => ({ ...p, allowedDomains: next });
135
+ break;
136
+ }
137
+ case "allowCredentials": {
138
+ const next = [...new Set(list(value))];
139
+ change = (p) => ({ ...p, allowCredentials: next });
140
+ break;
141
+ }
142
+ case "cpu":
143
+ case "memoryMb": {
144
+ const next = ceiling(key, value);
145
+ change = (p) => ({ ...p, [key]: next });
146
+ break;
51
147
  }
52
- next.allowedDomains = [...new Set(domains)];
53
- break;
148
+ case "mode":
149
+ throw new Error("the mode is set with: capybara-device mode auto|sandbox");
150
+ case "network":
151
+ case "tier":
152
+ case "isolation":
153
+ case "localhost":
154
+ case "remoteGrants":
155
+ throw new Error(`"${key}" is gone: the mode is set with capybara-device mode auto|sandbox; ` +
156
+ `allowedDomains with capybara-device policy add allowedDomains <host>`);
157
+ default:
158
+ throw new Error(`unknown policy key "${key}"; one of ${KEYS.join(", ")}`);
54
159
  }
55
- case "allowCredentials":
56
- next.allowCredentials = [...new Set(list(value))];
57
- break;
58
- case "cpu":
59
- case "memoryMb":
60
- next[key] = ceiling(key, value);
61
- break;
62
- default:
63
- throw new Error(`unknown policy key "${key}"; one of ${KEYS.join(", ")}`);
160
+ }
161
+ else {
162
+ if (!LIST_KEYS.includes(key)) {
163
+ throw new Error(`${action} works on ${LIST_KEYS.join(" and ")} only; use set for ${key}`);
164
+ }
165
+ const listKey = key;
166
+ // Only additions are validated: any entry already in the file can be removed.
167
+ const values = listKey !== "allowedDomains"
168
+ ? list(value)
169
+ : action === "add"
170
+ ? domains(value)
171
+ : list(value).map((d) => d.toLowerCase());
172
+ if (values.length === 0)
173
+ throw new Error(`${action} needs at least one value`);
174
+ change = (p, say) => ({ ...p, [listKey]: edit(p[listKey], action, listKey, values, say) });
64
175
  }
65
176
  }
66
177
  catch (e) {
67
178
  err(e.message);
68
179
  return 2;
69
180
  }
70
- writePolicy(stateDir, next);
71
- out(`Saved ${policyPath(stateDir)}. Restart capybara-device for it to take effect.`);
72
- out(NOT_ENFORCED_NOTE);
181
+ const lines = [];
182
+ let next;
183
+ try {
184
+ next = store.update((p) => change(p, (l) => lines.push(l)));
185
+ }
186
+ catch (e) {
187
+ err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
188
+ return 1;
189
+ }
190
+ for (const l of lines)
191
+ out(l);
192
+ out(`Saved ${policyPath(stateDir)}. A running capybara-device applies it at the next command.`);
193
+ if (key === "allowedDomains") {
194
+ out(docker
195
+ ? DOCKER_DOMAIN_NOTE
196
+ : next.mode === "auto"
197
+ ? "Allowed domains apply in sandbox mode only; switch with: capybara-device mode sandbox"
198
+ : "Sandboxed commands may reach these domains when the organization allows them too.");
199
+ }
200
+ if (key === "cpu" || key === "memoryMb" || key === "allowCredentials")
201
+ out(NOT_ENFORCED_NOTE);
73
202
  return 0;
74
203
  }
@@ -1,3 +1,4 @@
1
+ export type ServiceAction = "install" | "uninstall" | "start" | "stop" | "restart" | "status";
1
2
  export interface ServiceDeps {
2
3
  stateDir: string;
3
4
  home: string;
@@ -5,13 +6,27 @@ export interface ServiceDeps {
5
6
  env: Record<string, string | undefined>;
6
7
  out: (line: string) => void;
7
8
  err: (line: string) => void;
8
- /** Runs a system command; throws when it fails (default: execFileSync). */
9
+ /**
10
+ * Runs a system command; throws when it fails (default: execFileSync, whose error carries the
11
+ * exit `status` and `stderr`).
12
+ */
9
13
  run?: (cmd: string, args: string[]) => void;
14
+ /** Waits between launchctl checks (default: setTimeout). */
15
+ sleep?: (ms: number) => Promise<void>;
10
16
  uid?: number;
11
17
  nodePath?: string;
12
18
  binPath?: string;
13
19
  }
14
20
  /** What the service needs from the installing shell: PATH (docker lives there) and the state dir. */
15
21
  export declare function serviceEnv(env: Record<string, string | undefined>): Record<string, string>;
16
- /** `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd user). */
17
- export declare function serviceCommand(action: "install" | "uninstall", deps: ServiceDeps): number;
22
+ /** How often launchctl is asked whether the old service is gone. */
23
+ export declare const SERVICE_POLL_MS = 200;
24
+ /** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
25
+ export declare const SERVICE_GONE_TIMEOUT_MS = 10000;
26
+ /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
27
+ export declare const BOOTSTRAP_BACKOFF_MS: readonly [500, 1000, 2000];
28
+ /**
29
+ * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
30
+ * (systemd user), removes it, or reports whether it is loaded and running.
31
+ */
32
+ export declare function serviceCommand(action: ServiceAction, deps: ServiceDeps): Promise<number>;
@@ -2,8 +2,10 @@ import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { readRunning } from "../pid.js";
5
6
  import { LAUNCHD_LABEL, plistContent, plistPath } from "../service/launchd.js";
6
7
  import { SYSTEMD_UNIT, unitContent, unitPath } from "../service/systemd.js";
8
+ import { PROGRAM_VERSION } from "../version.js";
7
9
  function defaultRun(cmd, args) {
8
10
  execFileSync(cmd, args, { stdio: "pipe" });
9
11
  }
@@ -21,8 +23,17 @@ export function serviceEnv(env) {
21
23
  out.XDG_CONFIG_HOME = xdg;
22
24
  return out;
23
25
  }
24
- /** `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd user). */
25
- export function serviceCommand(action, deps) {
26
+ /** How often launchctl is asked whether the old service is gone. */
27
+ export const SERVICE_POLL_MS = 200;
28
+ /** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
29
+ export const SERVICE_GONE_TIMEOUT_MS = 10_000;
30
+ /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
31
+ export const BOOTSTRAP_BACKOFF_MS = [500, 1000, 2000];
32
+ /**
33
+ * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
34
+ * (systemd user), removes it, or reports whether it is loaded and running.
35
+ */
36
+ export async function serviceCommand(action, deps) {
26
37
  const run = deps.run ?? defaultRun;
27
38
  const spec = {
28
39
  nodePath: deps.nodePath ?? process.execPath,
@@ -32,7 +43,7 @@ export function serviceCommand(action, deps) {
32
43
  };
33
44
  try {
34
45
  if (deps.platform === "darwin")
35
- return launchd(action, spec, deps, run);
46
+ return await launchd(action, spec, deps, run);
36
47
  if (deps.platform === "linux")
37
48
  return systemd(action, spec, deps, run);
38
49
  }
@@ -43,9 +54,44 @@ export function serviceCommand(action, deps) {
43
54
  deps.err("capybara-device service needs macOS (launchd) or Linux (systemd).");
44
55
  return 1;
45
56
  }
46
- function launchd(action, spec, deps, run) {
57
+ /** The text launchctl printed for a failed call (its stderr, else the error message). */
58
+ function failureText(e) {
59
+ const stderr = e.stderr;
60
+ const text = stderr instanceof Uint8Array || typeof stderr === "string" ? String(stderr).trim() : "";
61
+ return text !== "" ? text : e instanceof Error ? e.message : String(e);
62
+ }
63
+ /**
64
+ * `launchctl bootstrap` failed with error 5 (Input/output error): typically the previous instance
65
+ * of the service is still being booted out.
66
+ */
67
+ function isBootstrapIoError(e) {
68
+ return e.status === 5 || /Bootstrap failed: 5:/.test(failureText(e));
69
+ }
70
+ /**
71
+ * One status report: installed? running (and at which version)? When the running program is older
72
+ * than the installed package, a stale daemon after an upgrade — a restart makes it current.
73
+ */
74
+ function reportStatus(deps, state, installedVersion) {
75
+ if (!state.installed) {
76
+ deps.out("capybara-device service is not installed. Install it: capybara-device service install");
77
+ return 1;
78
+ }
79
+ const running = readRunning(deps.stateDir);
80
+ if (running === undefined || !state.loaded) {
81
+ deps.out("capybara-device service is installed, but nothing is running. Start it: capybara-device service start");
82
+ return 1;
83
+ }
84
+ deps.out(`capybara-device service is loaded; running (pid ${running.pid}, ${running.version ?? "version unknown"}).`);
85
+ if (running.version !== installedVersion) {
86
+ deps.out(`installed ${installedVersion} — restart it: capybara-device service restart`);
87
+ }
88
+ return 0;
89
+ }
90
+ async function launchd(action, spec, deps, run) {
47
91
  const file = plistPath(deps.home);
48
92
  const domain = `gui/${deps.uid ?? process.getuid?.() ?? 501}`;
93
+ const service = `${domain}/${LAUNCHD_LABEL}`;
94
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
49
95
  const tryRun = (args) => {
50
96
  try {
51
97
  run("launchctl", args);
@@ -54,28 +100,148 @@ function launchd(action, spec, deps, run) {
54
100
  // Not loaded yet / already gone.
55
101
  }
56
102
  };
103
+ /** Whether launchd still knows the service (`launchctl print` fails once it is gone). */
104
+ const loaded = () => {
105
+ try {
106
+ run("launchctl", ["print", service]);
107
+ return true;
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ };
113
+ /** Boots the service out and waits until launchd has let it go (bootout returns before that). */
114
+ const bootout = async () => {
115
+ tryRun(["bootout", service]);
116
+ for (let waited = 0; loaded(); waited += SERVICE_POLL_MS) {
117
+ // Gave up: bootstrap's retries cover what is left.
118
+ if (waited >= SERVICE_GONE_TIMEOUT_MS)
119
+ return;
120
+ await sleep(SERVICE_POLL_MS);
121
+ }
122
+ };
123
+ /** Boots the plist in, retrying launchd's transient "previous instance still going" error. */
124
+ const bootstrap = async () => {
125
+ for (let attempt = 0;; attempt++) {
126
+ try {
127
+ run("launchctl", ["bootstrap", domain, file]);
128
+ return true;
129
+ }
130
+ catch (e) {
131
+ if (!isBootstrapIoError(e))
132
+ throw e;
133
+ const backoff = BOOTSTRAP_BACKOFF_MS[attempt];
134
+ if (backoff === undefined) {
135
+ deps.err(`launchctl bootstrap failed ${attempt + 1} times (${failureText(e)}). ` +
136
+ `The previous capybara-device service may still be stopping: wait a few seconds and try again. ` +
137
+ `launchctl print ${service} shows what launchd knows of it.`);
138
+ return false;
139
+ }
140
+ await sleep(backoff);
141
+ await bootout();
142
+ }
143
+ }
144
+ };
145
+ const installed = () => existsSync(file);
146
+ if (action === "status") {
147
+ return reportStatus(deps, { installed: installed(), loaded: loaded() }, PROGRAM_VERSION);
148
+ }
149
+ if (action === "start" || action === "restart") {
150
+ if (!installed()) {
151
+ deps.err("capybara-device service is not installed. Install it: capybara-device service install");
152
+ return 1;
153
+ }
154
+ if (action === "start" && loaded()) {
155
+ deps.out("The capybara-device login service is already running.");
156
+ return 0;
157
+ }
158
+ if (action === "restart" && loaded()) {
159
+ // Reloads the program from the plist's bin, so a newer package takes effect.
160
+ tryRun(["kickstart", "-k", service]);
161
+ deps.out("Restarted the capybara-device login service.");
162
+ return 0;
163
+ }
164
+ if (!(await bootstrap()))
165
+ return 1;
166
+ deps.out(action === "restart"
167
+ ? "Restarted the capybara-device login service."
168
+ : "Started the capybara-device login service.");
169
+ return 0;
170
+ }
171
+ if (action === "stop") {
172
+ if (!installed()) {
173
+ deps.err("capybara-device service is not installed. Install it: capybara-device service install");
174
+ return 1;
175
+ }
176
+ if (!loaded()) {
177
+ deps.out("The capybara-device login service is not running.");
178
+ return 0;
179
+ }
180
+ // Unload, never a signal: KeepAlive would start a signalled program straight back up.
181
+ await bootout();
182
+ deps.out("Stopped the capybara-device login service; running commands ended. It starts again at the next login or with: capybara-device service start");
183
+ return 0;
184
+ }
57
185
  if (action === "install") {
58
186
  mkdirSync(dirname(file), { recursive: true });
59
187
  mkdirSync(spec.stateDir, { recursive: true });
60
- if (existsSync(file))
61
- tryRun(["bootout", `${domain}/${LAUNCHD_LABEL}`]);
188
+ if (existsSync(file) || loaded())
189
+ await bootout();
62
190
  writeFileSync(file, plistContent(spec));
63
- run("launchctl", ["bootstrap", domain, file]);
191
+ if (!(await bootstrap()))
192
+ return 1;
64
193
  deps.out(`Installed ${file}; capybara-device now starts at login.`);
65
194
  return 0;
66
195
  }
67
- tryRun(["bootout", `${domain}/${LAUNCHD_LABEL}`]);
196
+ await bootout();
68
197
  rmSync(file, { force: true });
69
198
  deps.out("Removed the capybara-device login service.");
70
199
  return 0;
71
200
  }
72
201
  function systemd(action, spec, deps, run) {
73
202
  const file = unitPath(deps.home);
203
+ const active = () => {
204
+ try {
205
+ run("systemctl", ["--user", "is-active", "--quiet", SYSTEMD_UNIT]);
206
+ return true;
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ };
212
+ const installed = () => existsSync(file);
213
+ if (action === "status") {
214
+ return reportStatus(deps, { installed: installed(), loaded: active() }, PROGRAM_VERSION);
215
+ }
216
+ if (action === "start" || action === "stop" || action === "restart") {
217
+ if (!installed()) {
218
+ deps.err("capybara-device service is not installed. Install it: capybara-device service install");
219
+ return 1;
220
+ }
221
+ if (action === "start" && active()) {
222
+ deps.out("The capybara-device login service is already running.");
223
+ return 0;
224
+ }
225
+ if (action === "stop" && !active()) {
226
+ deps.out("The capybara-device login service is not running.");
227
+ return 0;
228
+ }
229
+ run("systemctl", ["--user", action, SYSTEMD_UNIT]);
230
+ deps.out(action === "start"
231
+ ? "Started the capybara-device login service."
232
+ : action === "restart"
233
+ ? "Restarted the capybara-device login service."
234
+ : "Stopped the capybara-device login service; running commands ended. It starts again at the next login or with: capybara-device service start");
235
+ return 0;
236
+ }
74
237
  if (action === "install") {
75
238
  mkdirSync(dirname(file), { recursive: true });
76
239
  writeFileSync(file, unitContent(spec));
77
240
  run("systemctl", ["--user", "daemon-reload"]);
78
- run("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT]);
241
+ run("systemctl", ["--user", "enable", SYSTEMD_UNIT]);
242
+ // restart, not start: a unit already running (an earlier install) picks up the new file.
243
+ // systemctl waits for the stop and start jobs, so nothing is left in flight.
244
+ run("systemctl", ["--user", "restart", SYSTEMD_UNIT]);
79
245
  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
246
  return 0;
81
247
  }
@@ -1,16 +1,27 @@
1
1
  import { connect } from "../client.js";
2
2
  import type { Executor } from "../exec/types.js";
3
- import { type Credential, type Policy } from "../state.js";
3
+ import { PolicyStore } from "../policy-store.js";
4
+ import { type Credential } from "../state.js";
4
5
  export interface StartDeps {
5
6
  stateDir: string;
6
- /** Builds the executor for the credential's mode (the OS and Docker executors). */
7
- createExecutor?: (cred: Credential, policy: Policy) => Promise<Executor> | Executor;
7
+ /**
8
+ * Builds the executor for the credential's mode (the OS and Docker executors). The store
9
+ * follows policy.json, so executors read the policy at each command.
10
+ */
11
+ createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
8
12
  out: (line: string) => void;
9
13
  err: (line: string) => void;
14
+ /** Where the login service would be installed, and on which platform (default: this machine). */
15
+ service?: {
16
+ home: string;
17
+ platform: NodeJS.Platform;
18
+ };
10
19
  /** The process whose signals stop and drain the program. */
11
20
  proc?: Pick<NodeJS.Process, "on" | "off" | "pid">;
12
21
  kill?: typeof process.kill;
13
22
  connect?: typeof connect;
14
23
  }
24
+ /** Printed once when policy.json was written before auto mode (spec §4.4). */
25
+ export declare function legacyPolicyNotice(mode: "auto" | "sandbox"): string;
15
26
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
16
27
  export declare function start(deps: StartDeps): Promise<number>;
@@ -1,8 +1,18 @@
1
+ import { homedir } from "node:os";
1
2
  import { connect } from "../client.js";
2
3
  import { CommandLog } from "../command-log.js";
4
+ import { sandboxUnavailableMessage } from "../exec/sandbox-messages.js";
3
5
  import { readRunningPid, removePid, writePid } from "../pid.js";
6
+ import { PolicyStore } from "../policy-store.js";
7
+ import { hasLoginService } from "../service/installed.js";
4
8
  import { rotateServiceLog } from "../service/launchd.js";
5
- import { readCredential, readPolicy } from "../state.js";
9
+ import { readCredential } from "../state.js";
10
+ import { PROGRAM_VERSION } from "../version.js";
11
+ /** Printed once when policy.json was written before auto mode (spec §4.4). */
12
+ export function legacyPolicyNotice(mode) {
13
+ return ("policy.json now uses `mode`; this machine runs in " +
14
+ `${mode} mode; switch with \`capybara-device mode\`.`);
15
+ }
6
16
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
7
17
  export async function start(deps) {
8
18
  const { stateDir, out, err } = deps;
@@ -24,6 +34,12 @@ export async function start(deps) {
24
34
  err("capybara-device start: no execution backend is available in this build");
25
35
  return 1;
26
36
  }
37
+ const where = deps.service ?? { home: homedir(), platform: process.platform };
38
+ if (hasLoginService(where.home, where.platform)) {
39
+ // The service manager runs exactly this command, so it must keep working; say how to control
40
+ // the one that is installed.
41
+ out("capybara-device runs as a login service on this machine. Restart it with: capybara-device service restart");
42
+ }
27
43
  rotateServiceLog(stateDir);
28
44
  const running = readRunningPid(stateDir, deps.kill);
29
45
  if (running !== undefined && running !== proc.pid) {
@@ -46,11 +62,22 @@ export async function start(deps) {
46
62
  proc.on("SIGTERM", onStop);
47
63
  proc.on("SIGINT", onStop);
48
64
  proc.on("SIGUSR2", onDrain);
49
- writePid(stateDir, proc.pid);
65
+ writePid(stateDir, proc.pid, PROGRAM_VERSION);
50
66
  try {
51
67
  let executor;
68
+ let policy;
52
69
  try {
53
- executor = await deps.createExecutor(cred, readPolicy(stateDir));
70
+ // An invalid policy.json stops the start; later, a broken edit keeps the last good policy.
71
+ policy = new PolicyStore(stateDir, { err });
72
+ if (policy.legacy)
73
+ out(legacyPolicyNotice(policy.current().mode));
74
+ executor = await deps.createExecutor(cred, policy);
75
+ // Without the OS sandbox the device keeps serving: auto mode works, and sandbox mode
76
+ // refuses every command with this reason. A policy set to sandbox says so at start.
77
+ const sandbox = executor;
78
+ if (sandbox.available === false && policy.current().mode === "sandbox") {
79
+ err(sandboxUnavailableMessage(sandbox.unavailableReason ?? ""));
80
+ }
54
81
  }
55
82
  catch (e) {
56
83
  err(`Cannot start: ${e.message}`);
@@ -58,10 +85,15 @@ export async function start(deps) {
58
85
  }
59
86
  if (stopRequested)
60
87
  return 0;
61
- conn = (deps.connect ?? connect)(cred, executor, { log: new CommandLog(stateDir), err });
88
+ // One store: the executor's commands, the hello summary and the policy op see the same policy.
89
+ conn = (deps.connect ?? connect)(cred, executor, {
90
+ log: new CommandLog(stateDir),
91
+ err,
92
+ policy,
93
+ });
62
94
  if (drainRequested)
63
95
  conn.drain();
64
- out(`capybara-device: serving environment ${cred.environmentId} (${cred.mode} mode)`);
96
+ out(`capybara-device: serving device ${cred.deviceId} (${cred.mode} mode)`);
65
97
  return await conn.done;
66
98
  }
67
99
  finally {
@@ -1,4 +1,4 @@
1
- import { readCredential } from "../state.js";
1
+ import { readCredential, readPolicy } from "../state.js";
2
2
  /** `status`: exit 0 when logged in, 1 when not (or the credential file is unusable). */
3
3
  export function status(stateDir, json, out, err) {
4
4
  let cred;
@@ -13,19 +13,27 @@ export function status(stateDir, json, out, err) {
13
13
  out(json ? JSON.stringify({ loggedIn: false }) : "Not logged in.");
14
14
  return 1;
15
15
  }
16
+ // An unreadable policy file is reported by `start` and `policy show`; status still answers.
17
+ let sandboxMode;
18
+ try {
19
+ sandboxMode = readPolicy(stateDir).mode;
20
+ }
21
+ catch {
22
+ sandboxMode = undefined;
23
+ }
16
24
  // The credential itself is never printed.
17
25
  const { credential: _secret, ...shown } = cred;
18
26
  if (json) {
19
- out(JSON.stringify({ loggedIn: true, ...shown }));
27
+ out(JSON.stringify({ loggedIn: true, ...shown, ...(sandboxMode && { sandboxMode }) }));
20
28
  }
21
29
  else {
22
30
  out([
23
31
  "Logged in.",
24
32
  ` deployment: ${cred.url}`,
25
33
  ` organization: ${cred.orgId}`,
26
- ` environment: ${cred.environmentId}`,
34
+ ` device: ${cred.deviceId}`,
27
35
  ` directory: ${cred.dir}`,
28
- ` mode: ${cred.mode}`,
36
+ ` mode: ${cred.mode} | ${sandboxMode ?? "unknown"}`,
29
37
  ].join("\n"));
30
38
  }
31
39
  return 0;
@@ -1,2 +1,9 @@
1
- /** `stop`: SIGTERM to the running program. */
2
- export declare function stop(stateDir: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill): number;
1
+ /**
2
+ * `stop`: SIGTERM to the running program. A machine that runs the program as a login service is
3
+ * stopped through it instead: launchd's `KeepAlive` (and systemd's restart) would start a signalled
4
+ * program straight back up, so `service stop` (which unloads the service) is the honest path.
5
+ */
6
+ export declare function stop(stateDir: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill, service?: {
7
+ home: string;
8
+ platform: NodeJS.Platform;
9
+ }): number;