@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
@@ -1,12 +1,11 @@
1
- import { execFileSync } from "node:child_process";
2
1
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
- import { dirname } from "node:path";
2
+ import { dirname, join } from "node:path";
4
3
  import { fileURLToPath } from "node:url";
5
- import { LAUNCHD_LABEL, plistContent, plistPath } from "../service/launchd.js";
4
+ import { readRunning } from "../pid.js";
5
+ import { hasLoginService } from "../service/installed.js";
6
+ import { plistContent, plistPath } from "../service/launchd.js";
7
+ import { defaultRunSystem, launchdTarget, managerState, packageVersionAt, serviceBinPath, } from "../service/manager.js";
6
8
  import { SYSTEMD_UNIT, unitContent, unitPath } from "../service/systemd.js";
7
- function defaultRun(cmd, args) {
8
- execFileSync(cmd, args, { stdio: "pipe" });
9
- }
10
9
  /** The bin script next to this package's `dist` (or `src`) directory. */
11
10
  function defaultBinPath() {
12
11
  return fileURLToPath(new URL("../../bin/capybara-device.mjs", import.meta.url));
@@ -21,9 +20,20 @@ export function serviceEnv(env) {
21
20
  out.XDG_CONFIG_HOME = xdg;
22
21
  return out;
23
22
  }
24
- /** `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd user). */
25
- export function serviceCommand(action, deps) {
26
- const run = deps.run ?? defaultRun;
23
+ /** How often launchctl is asked whether the old service is gone. */
24
+ export const SERVICE_POLL_MS = 200;
25
+ /** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
26
+ export const SERVICE_GONE_TIMEOUT_MS = 10_000;
27
+ /** How long `service start|restart` wait for the program to be running. */
28
+ export const SERVICE_UP_TIMEOUT_MS = 10_000;
29
+ /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
30
+ export const BOOTSTRAP_BACKOFF_MS = [500, 1000, 2000];
31
+ /**
32
+ * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
33
+ * (systemd user), removes it, or reports whether it is loaded and running.
34
+ */
35
+ export async function serviceCommand(action, deps) {
36
+ const run = deps.run ?? defaultRunSystem;
27
37
  const spec = {
28
38
  nodePath: deps.nodePath ?? process.execPath,
29
39
  binPath: deps.binPath ?? defaultBinPath(),
@@ -32,9 +42,9 @@ export function serviceCommand(action, deps) {
32
42
  };
33
43
  try {
34
44
  if (deps.platform === "darwin")
35
- return launchd(action, spec, deps, run);
45
+ return await launchd(action, spec, deps, run);
36
46
  if (deps.platform === "linux")
37
- return systemd(action, spec, deps, run);
47
+ return await systemd(action, spec, deps, run);
38
48
  }
39
49
  catch (e) {
40
50
  deps.err(`capybara-device service ${action} failed: ${e instanceof Error ? e.message : String(e)}`);
@@ -43,9 +53,99 @@ export function serviceCommand(action, deps) {
43
53
  deps.err("capybara-device service needs macOS (launchd) or Linux (systemd).");
44
54
  return 1;
45
55
  }
46
- function launchd(action, spec, deps, run) {
56
+ /** The text launchctl printed for a failed call (its stderr, else the error message). */
57
+ function failureText(e) {
58
+ const stderr = e.stderr;
59
+ const text = stderr instanceof Uint8Array || typeof stderr === "string" ? String(stderr).trim() : "";
60
+ return text !== "" ? text : e instanceof Error ? e.message : String(e);
61
+ }
62
+ /**
63
+ * `launchctl bootstrap` failed with error 5 (Input/output error): typically the previous instance
64
+ * of the service is still being booted out.
65
+ */
66
+ function isBootstrapIoError(e) {
67
+ return e.status === 5 || /Bootstrap failed: 5:/.test(failureText(e));
68
+ }
69
+ /** The pid file's program, checked to be this program (never trusted on the file alone). */
70
+ function running(deps) {
71
+ return readRunning(deps.stateDir, {
72
+ ...(deps.kill && { kill: deps.kill }),
73
+ ...(deps.ps && { ps: deps.ps }),
74
+ });
75
+ }
76
+ function where(deps) {
77
+ return {
78
+ home: deps.home,
79
+ platform: deps.platform,
80
+ ...(deps.uid !== undefined && { uid: deps.uid }),
81
+ };
82
+ }
83
+ const NOT_INSTALLED = "capybara-device service is not installed. Install it: capybara-device service install";
84
+ /**
85
+ * One status report, in four shapes: not installed; installed but not loaded; loaded but the
86
+ * program is not running (it exited: the reason is in service.log); running, with its pid and
87
+ * version, plus a restart line when the package the service file runs is a different version (a
88
+ * stale daemon after an upgrade). Exit code 0 only when running.
89
+ */
90
+ function reportStatus(deps, run) {
91
+ const at = where(deps);
92
+ if (!hasLoginService(at.home, at.platform)) {
93
+ deps.out(NOT_INSTALLED);
94
+ return 1;
95
+ }
96
+ const state = managerState(at, run);
97
+ if (!state.loaded) {
98
+ deps.out("capybara-device service is installed but not loaded. Start it: capybara-device service start");
99
+ return 1;
100
+ }
101
+ if (state.pid === undefined) {
102
+ deps.out("capybara-device service is loaded, but the program is not running: it exited. The reason " +
103
+ `is at the end of ${join(deps.stateDir, "service.log")}; once it is fixed: ` +
104
+ "capybara-device service restart");
105
+ return 1;
106
+ }
107
+ const program = running(deps);
108
+ const version = program?.pid === state.pid ? program.version : undefined;
109
+ deps.out(`capybara-device service is loaded; running (pid ${state.pid}, ${version ?? "version unknown"}).`);
110
+ const bin = serviceBinPath(at);
111
+ const installed = bin === undefined ? undefined : packageVersionAt(bin);
112
+ if (installed !== undefined && version !== installed) {
113
+ deps.out(`installed ${installed} — restart it: capybara-device service restart`);
114
+ }
115
+ return 0;
116
+ }
117
+ /**
118
+ * Refuses to start the service while a program started outside it runs (`capybara-device start`
119
+ * in a terminal): two programs would fight over the one connection of this device.
120
+ */
121
+ function foregroundRunning(deps, state) {
122
+ const program = running(deps);
123
+ if (program === undefined || program.pid === state.pid)
124
+ return false;
125
+ deps.err(`capybara-device is already running outside the service (pid ${program.pid}). Stop it first: capybara-device stop`);
126
+ return true;
127
+ }
128
+ /** Waits until the service manager runs the program (a pid other than `previous`). */
129
+ async function cameUp(deps, run, sleep, previous) {
130
+ for (let waited = 0;; waited += SERVICE_POLL_MS) {
131
+ const pid = managerState(where(deps), run).pid;
132
+ if (pid !== undefined && pid !== previous)
133
+ return true;
134
+ if (waited >= SERVICE_UP_TIMEOUT_MS)
135
+ return false;
136
+ await sleep(SERVICE_POLL_MS);
137
+ }
138
+ }
139
+ /** The failure of a start or restart whose program is not running afterwards. */
140
+ function didNotComeBack(deps, action) {
141
+ deps.err(`capybara-device service ${action} failed: the program is not running. The reason is at the ` +
142
+ `end of ${join(deps.stateDir, "service.log")}.`);
143
+ return 1;
144
+ }
145
+ async function launchd(action, spec, deps, run) {
47
146
  const file = plistPath(deps.home);
48
- const domain = `gui/${deps.uid ?? process.getuid?.() ?? 501}`;
147
+ const { domain, service } = launchdTarget(deps.uid);
148
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
49
149
  const tryRun = (args) => {
50
150
  try {
51
151
  run("launchctl", args);
@@ -54,28 +154,151 @@ function launchd(action, spec, deps, run) {
54
154
  // Not loaded yet / already gone.
55
155
  }
56
156
  };
157
+ /** Whether launchd still knows the service (`launchctl print` fails once it is gone). */
158
+ const loaded = () => managerState(where(deps), run).loaded;
159
+ /** Boots the service out and waits until launchd has let it go (bootout returns before that). */
160
+ const bootout = async () => {
161
+ tryRun(["bootout", service]);
162
+ for (let waited = 0; loaded(); waited += SERVICE_POLL_MS) {
163
+ // Gave up: bootstrap's retries cover what is left.
164
+ if (waited >= SERVICE_GONE_TIMEOUT_MS)
165
+ return;
166
+ await sleep(SERVICE_POLL_MS);
167
+ }
168
+ };
169
+ /** Boots the plist in, retrying launchd's transient "previous instance still going" error. */
170
+ const bootstrap = async () => {
171
+ for (let attempt = 0;; attempt++) {
172
+ try {
173
+ run("launchctl", ["bootstrap", domain, file]);
174
+ return true;
175
+ }
176
+ catch (e) {
177
+ if (!isBootstrapIoError(e))
178
+ throw e;
179
+ const backoff = BOOTSTRAP_BACKOFF_MS[attempt];
180
+ if (backoff === undefined) {
181
+ deps.err(`launchctl bootstrap failed ${attempt + 1} times (${failureText(e)}). ` +
182
+ `The previous capybara-device service may still be stopping: wait a few seconds and try again. ` +
183
+ `launchctl print ${service} shows what launchd knows of it.`);
184
+ return false;
185
+ }
186
+ await sleep(backoff);
187
+ await bootout();
188
+ }
189
+ }
190
+ };
191
+ const installed = () => hasLoginService(deps.home, "darwin");
192
+ if (action === "status")
193
+ return reportStatus(deps, run);
194
+ if (action === "start" || action === "restart") {
195
+ if (!installed()) {
196
+ deps.err(NOT_INSTALLED);
197
+ return 1;
198
+ }
199
+ const state = managerState(where(deps), run);
200
+ if (action === "start" && state.pid !== undefined) {
201
+ deps.out("The capybara-device login service is already running.");
202
+ return 0;
203
+ }
204
+ if (foregroundRunning(deps, state))
205
+ return 1;
206
+ if (state.loaded) {
207
+ // Loaded: run the program again from the plist's bin (a newer package takes effect); a
208
+ // loaded service whose program exited is started without a kill.
209
+ run("launchctl", state.pid === undefined ? ["kickstart", service] : ["kickstart", "-k", service]);
210
+ }
211
+ else if (!(await bootstrap())) {
212
+ return 1;
213
+ }
214
+ if (!(await cameUp(deps, run, sleep, state.pid)))
215
+ return didNotComeBack(deps, action);
216
+ deps.out(action === "restart"
217
+ ? "Restarted the capybara-device login service."
218
+ : "Started the capybara-device login service.");
219
+ return 0;
220
+ }
221
+ if (action === "stop") {
222
+ if (!installed()) {
223
+ deps.err(NOT_INSTALLED);
224
+ return 1;
225
+ }
226
+ if (!loaded()) {
227
+ deps.out("The capybara-device login service is not running.");
228
+ return 0;
229
+ }
230
+ // Unload, never a signal: KeepAlive would start a program that exits non-zero straight back.
231
+ await bootout();
232
+ if (loaded()) {
233
+ deps.err(`capybara-device service stop failed: launchd still has the service loaded. Check with: launchctl print ${service}`);
234
+ return 1;
235
+ }
236
+ deps.out("Stopped the capybara-device login service; running commands ended. It starts again at the next login or with: capybara-device service start");
237
+ return 0;
238
+ }
57
239
  if (action === "install") {
58
240
  mkdirSync(dirname(file), { recursive: true });
59
241
  mkdirSync(spec.stateDir, { recursive: true });
60
- if (existsSync(file))
61
- tryRun(["bootout", `${domain}/${LAUNCHD_LABEL}`]);
242
+ if (existsSync(file) || loaded())
243
+ await bootout();
62
244
  writeFileSync(file, plistContent(spec));
63
- run("launchctl", ["bootstrap", domain, file]);
245
+ if (!(await bootstrap()))
246
+ return 1;
64
247
  deps.out(`Installed ${file}; capybara-device now starts at login.`);
65
248
  return 0;
66
249
  }
67
- tryRun(["bootout", `${domain}/${LAUNCHD_LABEL}`]);
250
+ await bootout();
68
251
  rmSync(file, { force: true });
69
252
  deps.out("Removed the capybara-device login service.");
70
253
  return 0;
71
254
  }
72
- function systemd(action, spec, deps, run) {
255
+ async function systemd(action, spec, deps, run) {
73
256
  const file = unitPath(deps.home);
257
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
258
+ const active = () => managerState(where(deps), run).loaded;
259
+ const installed = () => hasLoginService(deps.home, "linux");
260
+ if (action === "status")
261
+ return reportStatus(deps, run);
262
+ if (action === "start" || action === "stop" || action === "restart") {
263
+ if (!installed()) {
264
+ deps.err(NOT_INSTALLED);
265
+ return 1;
266
+ }
267
+ const state = managerState(where(deps), run);
268
+ if (action === "start" && state.loaded) {
269
+ deps.out("The capybara-device login service is already running.");
270
+ return 0;
271
+ }
272
+ if (action === "stop" && !state.loaded) {
273
+ deps.out("The capybara-device login service is not running.");
274
+ return 0;
275
+ }
276
+ if (action !== "stop" && !state.loaded && foregroundRunning(deps, state))
277
+ return 1;
278
+ run("systemctl", ["--user", action, SYSTEMD_UNIT]);
279
+ if (action === "stop") {
280
+ if (active()) {
281
+ deps.err(`capybara-device service stop failed: the unit is still active. Check with: systemctl --user status ${SYSTEMD_UNIT}`);
282
+ return 1;
283
+ }
284
+ deps.out("Stopped the capybara-device login service; running commands ended. It starts again at the next login or with: capybara-device service start");
285
+ return 0;
286
+ }
287
+ if (!(await cameUp(deps, run, sleep, state.pid)))
288
+ return didNotComeBack(deps, action);
289
+ deps.out(action === "start"
290
+ ? "Started the capybara-device login service."
291
+ : "Restarted the capybara-device login service.");
292
+ return 0;
293
+ }
74
294
  if (action === "install") {
75
295
  mkdirSync(dirname(file), { recursive: true });
76
296
  writeFileSync(file, unitContent(spec));
77
297
  run("systemctl", ["--user", "daemon-reload"]);
78
- run("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT]);
298
+ run("systemctl", ["--user", "enable", SYSTEMD_UNIT]);
299
+ // restart, not start: a unit already running (an earlier install) picks up the new file.
300
+ // systemctl waits for the stop and start jobs, so nothing is left in flight.
301
+ run("systemctl", ["--user", "restart", SYSTEMD_UNIT]);
79
302
  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
303
  return 0;
81
304
  }
@@ -1,2 +1,6 @@
1
- /** Sends `signal` to the running program; exit code 0 when it was signalled, 1 when none runs. */
2
- export declare function signalRunning(stateDir: string, signal: NodeJS.Signals, message: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill): number;
1
+ import { type ProcessChecks } from "../pid.js";
2
+ /**
3
+ * Sends `signal` to the running program; exit code 0 when it was signalled, 1 when none runs. A
4
+ * pid the file names but that is not this program any more is never signalled.
5
+ */
6
+ export declare function signalRunning(stateDir: string, signal: NodeJS.Signals, message: string, out: (line: string) => void, err: (line: string) => void, checks?: ProcessChecks): number;
@@ -1,13 +1,16 @@
1
1
  import { readRunningPid } from "../pid.js";
2
- /** Sends `signal` to the running program; exit code 0 when it was signalled, 1 when none runs. */
3
- export function signalRunning(stateDir, signal, message, out, err, kill = process.kill) {
4
- const pid = readRunningPid(stateDir, kill);
2
+ /**
3
+ * Sends `signal` to the running program; exit code 0 when it was signalled, 1 when none runs. A
4
+ * pid the file names but that is not this program any more is never signalled.
5
+ */
6
+ export function signalRunning(stateDir, signal, message, out, err, checks = {}) {
7
+ const pid = readRunningPid(stateDir, checks);
5
8
  if (pid === undefined) {
6
9
  err("capybara-device is not running.");
7
10
  return 1;
8
11
  }
9
12
  try {
10
- kill(pid, signal);
13
+ (checks.kill ?? process.kill)(pid, signal);
11
14
  }
12
15
  catch (e) {
13
16
  err(`Could not signal pid ${pid}: ${e.message}`);
@@ -1,16 +1,31 @@
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 { type ProcessLookup } from "../pid.js";
4
+ import { PolicyStore } from "../policy-store.js";
5
+ import { type Credential } from "../state.js";
4
6
  export interface StartDeps {
5
7
  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;
8
+ /**
9
+ * Builds the executor for the credential's mode (the OS and Docker executors). The store
10
+ * follows policy.json, so executors read the policy at each command.
11
+ */
12
+ createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
8
13
  out: (line: string) => void;
9
14
  err: (line: string) => void;
15
+ /** Where the login service would be installed, and on which platform (default: this machine). */
16
+ service?: {
17
+ home: string;
18
+ platform: NodeJS.Platform;
19
+ };
10
20
  /** The process whose signals stop and drain the program. */
11
21
  proc?: Pick<NodeJS.Process, "on" | "off" | "pid">;
12
22
  kill?: typeof process.kill;
23
+ ps?: ProcessLookup;
24
+ /** The environment (default: process.env): tells whether the service manager started this. */
25
+ env?: Record<string, string | undefined>;
13
26
  connect?: typeof connect;
14
27
  }
28
+ /** Printed once when policy.json was written before auto mode (spec §4.4). */
29
+ export declare function legacyPolicyNotice(mode: "auto" | "sandbox"): string;
15
30
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
16
31
  export declare function start(deps: StartDeps): Promise<number>;
@@ -1,8 +1,19 @@
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 { startedByServiceManager } from "../service/manager.js";
10
+ import { readCredential } from "../state.js";
11
+ import { PROGRAM_VERSION } from "../version.js";
12
+ /** Printed once when policy.json was written before auto mode (spec §4.4). */
13
+ export function legacyPolicyNotice(mode) {
14
+ return ("policy.json now uses `mode`; this machine runs in " +
15
+ `${mode} mode; switch with \`capybara-device mode\`.`);
16
+ }
6
17
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
7
18
  export async function start(deps) {
8
19
  const { stateDir, out, err } = deps;
@@ -16,7 +27,9 @@ export async function start(deps) {
16
27
  return 1;
17
28
  }
18
29
  if (cred === undefined) {
19
- // Terminal: exit 0 so a service manager does not restart it until someone logs in.
30
+ // A deliberate stop: exit 0, which the service manager does not restart (launchd
31
+ // `KeepAlive { SuccessfulExit: false }`, systemd `Restart=on-failure`) until someone logs in
32
+ // and starts it.
20
33
  err("Not logged in. Run capybara-device login --url <url> first.");
21
34
  return 0;
22
35
  }
@@ -24,8 +37,18 @@ export async function start(deps) {
24
37
  err("capybara-device start: no execution backend is available in this build");
25
38
  return 1;
26
39
  }
40
+ const where = deps.service ?? { home: homedir(), platform: process.platform };
41
+ if (hasLoginService(where.home, where.platform) &&
42
+ !startedByServiceManager(deps.env ?? process.env, proc.pid)) {
43
+ // Started in a terminal while a service is installed: say how to control the installed one.
44
+ // The service manager runs exactly this command, so it must keep working, without the hint.
45
+ out("capybara-device runs as a login service on this machine. Restart it with: capybara-device service restart");
46
+ }
27
47
  rotateServiceLog(stateDir);
28
- const running = readRunningPid(stateDir, deps.kill);
48
+ const running = readRunningPid(stateDir, {
49
+ ...(deps.kill && { kill: deps.kill }),
50
+ ...(deps.ps && { ps: deps.ps }),
51
+ });
29
52
  if (running !== undefined && running !== proc.pid) {
30
53
  err(`capybara-device is already running (pid ${running}). Stop it first: capybara-device stop`);
31
54
  return 1;
@@ -46,11 +69,22 @@ export async function start(deps) {
46
69
  proc.on("SIGTERM", onStop);
47
70
  proc.on("SIGINT", onStop);
48
71
  proc.on("SIGUSR2", onDrain);
49
- writePid(stateDir, proc.pid);
72
+ writePid(stateDir, proc.pid, PROGRAM_VERSION);
50
73
  try {
51
74
  let executor;
75
+ let policy;
52
76
  try {
53
- executor = await deps.createExecutor(cred, readPolicy(stateDir));
77
+ // An invalid policy.json stops the start; later, a broken edit keeps the last good policy.
78
+ policy = new PolicyStore(stateDir, { err });
79
+ if (policy.legacy)
80
+ out(legacyPolicyNotice(policy.current().mode));
81
+ executor = await deps.createExecutor(cred, policy);
82
+ // Without the OS sandbox the device keeps serving: auto mode works, and sandbox mode
83
+ // refuses every command with this reason. A policy set to sandbox says so at start.
84
+ const sandbox = executor;
85
+ if (sandbox.available === false && policy.current().mode === "sandbox") {
86
+ err(sandboxUnavailableMessage(sandbox.unavailableReason ?? ""));
87
+ }
54
88
  }
55
89
  catch (e) {
56
90
  err(`Cannot start: ${e.message}`);
@@ -58,10 +92,15 @@ export async function start(deps) {
58
92
  }
59
93
  if (stopRequested)
60
94
  return 0;
61
- conn = (deps.connect ?? connect)(cred, executor, { log: new CommandLog(stateDir), err });
95
+ // One store: the executor's commands, the hello summary and the policy op see the same policy.
96
+ conn = (deps.connect ?? connect)(cred, executor, {
97
+ log: new CommandLog(stateDir),
98
+ err,
99
+ policy,
100
+ });
62
101
  if (drainRequested)
63
102
  conn.drain();
64
- out(`capybara-device: serving environment ${cred.environmentId} (${cred.mode} mode)`);
103
+ out(`capybara-device: serving device ${cred.deviceId} (${cred.mode} mode)`);
65
104
  return await conn.done;
66
105
  }
67
106
  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,20 @@
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
+ import { type ProcessChecks } from "../pid.js";
2
+ import { type RunSystem } from "../service/manager.js";
3
+ export interface StopOptions extends ProcessChecks {
4
+ /** Where the login service would be installed, and on which platform (default: this machine). */
5
+ service?: {
6
+ home: string;
7
+ platform: NodeJS.Platform;
8
+ uid?: number;
9
+ };
10
+ /** Asks the service manager (default: execFileSync). */
11
+ run?: RunSystem;
12
+ }
13
+ /**
14
+ * `stop`: SIGTERM to the running program. When the service manager runs that program (launchd has
15
+ * the service loaded, systemd has the unit active, and its pid is the running one), `stop` refuses
16
+ * and points at `service stop`, which unloads the service: a signalled service program would be
17
+ * started again by the restart policy, or would leave a service that looks loaded but stays down.
18
+ * A program started in a terminal is signalled as before, with or without a service installed.
19
+ */
20
+ export declare function stop(stateDir: string, out: (line: string) => void, err: (line: string) => void, opts?: StopOptions): number;
@@ -1,5 +1,28 @@
1
+ import { homedir } from "node:os";
2
+ import { readRunning } from "../pid.js";
3
+ import { hasLoginService } from "../service/installed.js";
4
+ import { defaultRunSystem, managerState } from "../service/manager.js";
1
5
  import { signalRunning } from "./signal.js";
2
- /** `stop`: SIGTERM to the running program. */
3
- export function stop(stateDir, out, err, kill) {
4
- return signalRunning(stateDir, "SIGTERM", "Stopping capybara-device.", out, err, kill);
6
+ /**
7
+ * `stop`: SIGTERM to the running program. When the service manager runs that program (launchd has
8
+ * the service loaded, systemd has the unit active, and its pid is the running one), `stop` refuses
9
+ * and points at `service stop`, which unloads the service: a signalled service program would be
10
+ * started again by the restart policy, or would leave a service that looks loaded but stays down.
11
+ * A program started in a terminal is signalled as before, with or without a service installed.
12
+ */
13
+ export function stop(stateDir, out, err, opts = {}) {
14
+ const where = opts.service ?? { home: homedir(), platform: process.platform };
15
+ const checks = {
16
+ ...(opts.kill && { kill: opts.kill }),
17
+ ...(opts.ps && { ps: opts.ps }),
18
+ };
19
+ if (hasLoginService(where.home, where.platform)) {
20
+ const state = managerState(where, opts.run ?? defaultRunSystem);
21
+ const program = readRunning(stateDir, checks);
22
+ if (state.loaded && program !== undefined && state.pid === program.pid) {
23
+ err("capybara-device runs as a login service on this machine. Stop it with: capybara-device service stop");
24
+ return 1;
25
+ }
26
+ }
27
+ return signalRunning(stateDir, "SIGTERM", "Stopping capybara-device.", out, err, checks);
5
28
  }