@capybara-hq/device 0.1.0-rc.10 → 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.
package/dist/pid.js CHANGED
@@ -1,9 +1,51 @@
1
+ import { execFileSync } from "node:child_process";
1
2
  import { existsSync, readFileSync, rmSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { writePrivate } from "./state.js";
4
5
  export function pidPath(dir) {
5
6
  return join(dir, "capybara-device.pid");
6
7
  }
8
+ /** The name every command line of this program contains (`…/bin/capybara-device.mjs start`). */
9
+ export const PROGRAM_BIN = "capybara-device";
10
+ /**
11
+ * How much later than the pid file's `startedAt` the process may seem to have started: `ps`
12
+ * reports whole seconds, and Linux derives the time from a boot time rounded to the second.
13
+ */
14
+ const START_SLACK_MS = 2000;
15
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
16
+ /**
17
+ * Parses `ps -o lstart= -o command=` output (C locale): `Sat Nov 14 02:11:37 2026 <command>`, the
18
+ * start in local time. A line without a readable start keeps only the command.
19
+ */
20
+ export function parsePsOutput(output) {
21
+ const line = output.split("\n").find((l) => l.trim() !== "");
22
+ if (line === undefined)
23
+ return undefined;
24
+ const m = /^\s*\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})\s+(\d{4})\s+(.*)$/.exec(line);
25
+ const month = m === null ? -1 : MONTHS.indexOf(m[1] ?? "");
26
+ if (m === null || month < 0)
27
+ return { command: line.trim() };
28
+ const [, , day, h, min, s, year, command] = m;
29
+ return {
30
+ command: (command ?? "").trim(),
31
+ started: new Date(Number(year), month, Number(day), Number(h), Number(min), Number(s)),
32
+ };
33
+ }
34
+ /** The default {@link ProcessLookup}: one `ps` call in the C locale. */
35
+ export function psLookup(pid) {
36
+ try {
37
+ const output = execFileSync("ps", ["-o", "lstart=", "-o", "command=", "-p", String(pid)], {
38
+ encoding: "utf8",
39
+ stdio: ["ignore", "pipe", "ignore"],
40
+ env: { ...process.env, LC_ALL: "C" },
41
+ });
42
+ return parsePsOutput(output);
43
+ }
44
+ catch {
45
+ // ps exits 1 when no such process exists.
46
+ return undefined;
47
+ }
48
+ }
7
49
  export function isAlive(pid, kill = process.kill) {
8
50
  try {
9
51
  kill(pid, 0);
@@ -13,18 +55,18 @@ export function isAlive(pid, kill = process.kill) {
13
55
  return e.code === "EPERM";
14
56
  }
15
57
  }
16
- /** The running program, or undefined (no file, a stale one, or a file that is not a pid). */
17
- export function readRunning(dir, kill = process.kill) {
18
- const file = pidPath(dir);
19
- if (!existsSync(file))
20
- return undefined;
21
- const raw = readFileSync(file, "utf8").trim();
58
+ /**
59
+ * The entry a pid file holds: JSON `{pid, version, startedAt}`, or a bare pid from a program older
60
+ * than the version field. Undefined when it is neither.
61
+ */
62
+ export function parsePidFile(raw) {
63
+ const text = raw.trim();
22
64
  let pid;
23
65
  let version;
24
66
  let startedAt;
25
- if (raw.startsWith("{")) {
67
+ if (text.startsWith("{")) {
26
68
  try {
27
- const parsed = JSON.parse(raw);
69
+ const parsed = JSON.parse(text);
28
70
  pid = Number(parsed.pid);
29
71
  version = typeof parsed.version === "string" ? parsed.version : undefined;
30
72
  startedAt = typeof parsed.startedAt === "string" ? parsed.startedAt : undefined;
@@ -34,20 +76,48 @@ export function readRunning(dir, kill = process.kill) {
34
76
  }
35
77
  }
36
78
  else {
37
- // A program older than the version field wrote a bare pid: its version is unknown.
38
- pid = Number.parseInt(raw, 10);
79
+ pid = Number.parseInt(text, 10);
39
80
  }
40
- return Number.isInteger(pid) && pid > 0 && isAlive(pid, kill)
41
- ? {
42
- pid,
43
- ...(version !== undefined && { version }),
44
- ...(startedAt !== undefined && { startedAt }),
45
- }
46
- : undefined;
81
+ if (!Number.isInteger(pid) || pid <= 0)
82
+ return undefined;
83
+ return {
84
+ pid,
85
+ ...(version !== undefined && { version }),
86
+ ...(startedAt !== undefined && { startedAt }),
87
+ };
88
+ }
89
+ /**
90
+ * Whether the process `entry` names is this program: its command line contains the
91
+ * `capybara-device` bin, and it did not start after the pid file was written (a reused pid did).
92
+ * A file without `startedAt` (an older program) is checked by the command line alone.
93
+ */
94
+ function namesThisProgram(entry, ps) {
95
+ const info = ps(entry.pid);
96
+ if (info === undefined || !info.command.includes(PROGRAM_BIN))
97
+ return false;
98
+ if (entry.startedAt === undefined)
99
+ return true;
100
+ const written = Date.parse(entry.startedAt);
101
+ if (Number.isNaN(written) || info.started === undefined)
102
+ return false;
103
+ return info.started.getTime() <= written + START_SLACK_MS;
104
+ }
105
+ /**
106
+ * The running program, or undefined: no file, a file that is not a pid, a dead pid, or a pid that
107
+ * is not this program any more (see {@link namesThisProgram}). Nothing signals an unverified pid.
108
+ */
109
+ export function readRunning(dir, checks = {}) {
110
+ const file = pidPath(dir);
111
+ if (!existsSync(file))
112
+ return undefined;
113
+ const entry = parsePidFile(readFileSync(file, "utf8"));
114
+ if (entry === undefined || !isAlive(entry.pid, checks.kill))
115
+ return undefined;
116
+ return namesThisProgram(entry, checks.ps ?? psLookup) ? entry : undefined;
47
117
  }
48
- /** The pid of the running program, or undefined (no file, or a stale one). */
49
- export function readRunningPid(dir, kill = process.kill) {
50
- return readRunning(dir, kill)?.pid;
118
+ /** The pid of the running program, or undefined (see {@link readRunning}). */
119
+ export function readRunningPid(dir, checks = {}) {
120
+ return readRunning(dir, checks)?.pid;
51
121
  }
52
122
  export function writePid(dir, pid, version) {
53
123
  const entry = {
@@ -57,24 +127,10 @@ export function writePid(dir, pid, version) {
57
127
  };
58
128
  writePrivate(pidPath(dir), `${JSON.stringify(entry)}\n`);
59
129
  }
60
- /** The pid a pid file names, without asking whether it is alive. */
61
- function pidInFile(file) {
62
- const raw = readFileSync(file, "utf8").trim();
63
- if (raw.startsWith("{")) {
64
- try {
65
- const parsed = JSON.parse(raw);
66
- return Number(parsed.pid);
67
- }
68
- catch {
69
- return undefined;
70
- }
71
- }
72
- return Number.parseInt(raw, 10);
73
- }
74
130
  export function removePid(dir, pid) {
75
131
  const file = pidPath(dir);
76
132
  try {
77
- if (pidInFile(file) === pid)
133
+ if (parsePidFile(readFileSync(file, "utf8"))?.pid === pid)
78
134
  rmSync(file, { force: true });
79
135
  }
80
136
  catch {
@@ -29,10 +29,12 @@ export interface SummaryFacts {
29
29
  limits?: Pick<SandboxLimits, "mode"> | undefined;
30
30
  }
31
31
  /**
32
- * The summary the kernel keeps of a local policy (hello, `policy` op result): the effective mode
33
- * (the owner's choice cut to the latest ceiling seen) and the device's sandbox-mode allowlist.
32
+ * The summary the kernel keeps of a local policy (hello, `policy` op result): the owner's mode and
33
+ * the device's sandbox-mode allowlist. The mode is never cut by the latest exec's ceiling: the
34
+ * kernel takes min(allowed, reported) itself, so an organization that later allows auto mode is
35
+ * followed at once instead of at the next command (the exec path still applies its ceiling).
34
36
  */
35
- export declare function policySummary(p: Policy, facts: SummaryFacts): DeviceLocalPolicySummary;
37
+ export declare function policySummary(p: Policy, _facts: SummaryFacts): DeviceLocalPolicySummary;
36
38
  /** The summary facts of a request context. */
37
39
  export declare function summaryFacts(executor: Executor, ctx: OpContext): SummaryFacts;
38
40
  /**
@@ -22,12 +22,14 @@ export function logEntryFor(req, res, now, detail, run) {
22
22
  };
23
23
  }
24
24
  /**
25
- * The summary the kernel keeps of a local policy (hello, `policy` op result): the effective mode
26
- * (the owner's choice cut to the latest ceiling seen) and the device's sandbox-mode allowlist.
25
+ * The summary the kernel keeps of a local policy (hello, `policy` op result): the owner's mode and
26
+ * the device's sandbox-mode allowlist. The mode is never cut by the latest exec's ceiling: the
27
+ * kernel takes min(allowed, reported) itself, so an organization that later allows auto mode is
28
+ * followed at once instead of at the next command (the exec path still applies its ceiling).
27
29
  */
28
- export function policySummary(p, facts) {
30
+ export function policySummary(p, _facts) {
29
31
  return {
30
- mode: facts.limits === undefined ? p.mode : effectiveMode(p, facts.limits),
32
+ mode: p.mode,
31
33
  allowedDomains: [...p.allowedDomains],
32
34
  };
33
35
  }
@@ -1,7 +1,7 @@
1
1
  export declare const LAUNCHD_LABEL = "top.capybara.device";
2
2
  /**
3
- * Minimum seconds between launchd restarts of the agent. Together with unconditional KeepAlive
4
- * this restarts the program after any exit, without spinning when it crashes during startup.
3
+ * Minimum seconds between launchd restarts of the agent: a program that keeps failing (exit code
4
+ * not 0) is started again at most this often, so a fast crash loop cannot spin.
5
5
  */
6
6
  export declare const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
7
7
  export interface ServiceSpec {
@@ -16,12 +16,15 @@ export interface ServiceSpec {
16
16
  }
17
17
  export declare function plistPath(home: string): string;
18
18
  /**
19
- * The launchd agent: `node <bin> start`, at login and after every exit. `KeepAlive` is
20
- * unconditional on purpose: the program only exits for a shutdown or a terminal condition, and a
21
- * clean exit must not leave the machine offline until someone bootstraps the agent again.
22
- * `ThrottleInterval` keeps a fast crash loop from spinning.
19
+ * The launchd agent: `node <bin> start` at login, and again after every failing exit. The program
20
+ * exits 0 only for a deliberate stop (logout, a revoked credential, `drain`, not logged in, a
21
+ * newer connection of this device), which must stay stopped; every exit it must recover from (a
22
+ * crash, a deployment that needs a newer program) is non-zero, so `KeepAlive { SuccessfulExit:
23
+ * false }` restarts exactly those. `ThrottleInterval` keeps a fast crash loop from spinning.
23
24
  */
24
25
  export declare function plistContent(spec: ServiceSpec): string;
26
+ /** The bin script a plist runs (the second `ProgramArguments` string), or undefined. */
27
+ export declare function plistBinPath(content: string): string | undefined;
25
28
  export declare const SERVICE_LOG_MAX_BYTES: number;
26
29
  /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
27
30
  export declare function rotateServiceLog(stateDir: string, maxBytes?: number): void;
@@ -2,8 +2,8 @@ import { copyFileSync, statSync, truncateSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  export const LAUNCHD_LABEL = "top.capybara.device";
4
4
  /**
5
- * Minimum seconds between launchd restarts of the agent. Together with unconditional KeepAlive
6
- * this restarts the program after any exit, without spinning when it crashes during startup.
5
+ * Minimum seconds between launchd restarts of the agent: a program that keeps failing (exit code
6
+ * not 0) is started again at most this often, so a fast crash loop cannot spin.
7
7
  */
8
8
  export const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
9
9
  export function plistPath(home) {
@@ -13,10 +13,11 @@ function xml(s) {
13
13
  return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
14
14
  }
15
15
  /**
16
- * The launchd agent: `node <bin> start`, at login and after every exit. `KeepAlive` is
17
- * unconditional on purpose: the program only exits for a shutdown or a terminal condition, and a
18
- * clean exit must not leave the machine offline until someone bootstraps the agent again.
19
- * `ThrottleInterval` keeps a fast crash loop from spinning.
16
+ * The launchd agent: `node <bin> start` at login, and again after every failing exit. The program
17
+ * exits 0 only for a deliberate stop (logout, a revoked credential, `drain`, not logged in, a
18
+ * newer connection of this device), which must stay stopped; every exit it must recover from (a
19
+ * crash, a deployment that needs a newer program) is non-zero, so `KeepAlive { SuccessfulExit:
20
+ * false }` restarts exactly those. `ThrottleInterval` keeps a fast crash loop from spinning.
20
21
  */
21
22
  export function plistContent(spec) {
22
23
  const env = Object.entries(spec.env)
@@ -37,7 +38,10 @@ export function plistContent(spec) {
37
38
  <key>RunAtLoad</key>
38
39
  <true/>
39
40
  <key>KeepAlive</key>
40
- <true/>
41
+ <dict>
42
+ <key>SuccessfulExit</key>
43
+ <false/>
44
+ </dict>
41
45
  <key>ThrottleInterval</key>
42
46
  <integer>${LAUNCHD_THROTTLE_INTERVAL_SECONDS}</integer>
43
47
  <key>EnvironmentVariables</key>
@@ -52,6 +56,17 @@ ${env}
52
56
  </plist>
53
57
  `;
54
58
  }
59
+ function unxml(s) {
60
+ return s.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
61
+ }
62
+ /** The bin script a plist runs (the second `ProgramArguments` string), or undefined. */
63
+ export function plistBinPath(content) {
64
+ const args = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(content)?.[1];
65
+ if (args === undefined)
66
+ return undefined;
67
+ const strings = [...args.matchAll(/<string>([\s\S]*?)<\/string>/g)].map((m) => unxml(m[1] ?? ""));
68
+ return strings[1];
69
+ }
55
70
  export const SERVICE_LOG_MAX_BYTES = 10 * 1024 * 1024;
56
71
  /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
57
72
  export function rotateServiceLog(stateDir, maxBytes = SERVICE_LOG_MAX_BYTES) {
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Runs a system command and returns its standard output; throws when it fails (the default,
3
+ * execFileSync, throws an error carrying the exit `status` and `stderr`).
4
+ */
5
+ export type RunSystem = (cmd: string, args: string[]) => string;
6
+ export declare function defaultRunSystem(cmd: string, args: string[]): string;
7
+ /** Where the login service lives: the user's home, the platform, and (macOS) the GUI domain's uid. */
8
+ export interface ServiceWhere {
9
+ home: string;
10
+ platform: NodeJS.Platform;
11
+ uid?: number;
12
+ }
13
+ /** The launchd domain and service target of the agent. */
14
+ export declare function launchdTarget(uid: number | undefined): {
15
+ domain: string;
16
+ service: string;
17
+ };
18
+ /**
19
+ * What the service manager says of the login service: whether launchd has it loaded (systemd:
20
+ * whether the unit is active), and the pid of the program it runs now, if any.
21
+ */
22
+ export interface ManagerState {
23
+ loaded: boolean;
24
+ pid?: number;
25
+ }
26
+ /** Asks launchd or systemd about the login service; a manager that cannot be asked says "not loaded". */
27
+ export declare function managerState(where: ServiceWhere, run: RunSystem): ManagerState;
28
+ /** The bin script the installed service file runs, or undefined (no file, or unreadable). */
29
+ export declare function serviceBinPath(where: ServiceWhere): string | undefined;
30
+ /**
31
+ * The version of the package at `binPath` (`<package>/bin/capybara-device.mjs`), read from its
32
+ * `package.json`: what a restart of the service would run. Undefined when it cannot be read.
33
+ */
34
+ export declare function packageVersionAt(binPath: string): string | undefined;
35
+ /**
36
+ * Whether this process was started by the service manager: launchd sets `XPC_SERVICE_NAME` to the
37
+ * agent's label (a terminal on macOS sets it to `0` or the terminal app's), systemd sets
38
+ * `INVOCATION_ID`. A shell inside a systemd-run terminal inherits `INVOCATION_ID` too; systemd 248+
39
+ * also sets `SYSTEMD_EXEC_PID`, which names this process only when systemd started it.
40
+ */
41
+ export declare function startedByServiceManager(env: Record<string, string | undefined>, pid?: number): boolean;
@@ -0,0 +1,91 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { hasLoginService } from "./installed.js";
5
+ import { LAUNCHD_LABEL, plistBinPath, plistPath } from "./launchd.js";
6
+ import { SYSTEMD_UNIT, unitBinPath, unitPath } from "./systemd.js";
7
+ export function defaultRunSystem(cmd, args) {
8
+ return execFileSync(cmd, args, { stdio: "pipe", encoding: "utf8" });
9
+ }
10
+ /** The launchd domain and service target of the agent. */
11
+ export function launchdTarget(uid) {
12
+ const domain = `gui/${uid ?? process.getuid?.() ?? 501}`;
13
+ return { domain, service: `${domain}/${LAUNCHD_LABEL}` };
14
+ }
15
+ /** The job's own `pid = N` line in `launchctl print` output (absent while it is not running). */
16
+ function launchdPid(printed) {
17
+ const m = /^\s*pid = (\d+)\s*$/m.exec(printed);
18
+ const pid = m === null ? Number.NaN : Number(m[1]);
19
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined;
20
+ }
21
+ /** Asks launchd or systemd about the login service; a manager that cannot be asked says "not loaded". */
22
+ export function managerState(where, run) {
23
+ if (where.platform === "darwin") {
24
+ try {
25
+ const printed = run("launchctl", ["print", launchdTarget(where.uid).service]);
26
+ const pid = launchdPid(String(printed ?? ""));
27
+ return { loaded: true, ...(pid !== undefined && { pid }) };
28
+ }
29
+ catch {
30
+ return { loaded: false };
31
+ }
32
+ }
33
+ if (where.platform === "linux") {
34
+ try {
35
+ run("systemctl", ["--user", "is-active", "--quiet", SYSTEMD_UNIT]);
36
+ }
37
+ catch {
38
+ return { loaded: false };
39
+ }
40
+ try {
41
+ const out = run("systemctl", ["--user", "show", "-p", "MainPID", "--value", SYSTEMD_UNIT]);
42
+ const pid = Number(String(out ?? "").trim());
43
+ return { loaded: true, ...(Number.isInteger(pid) && pid > 0 && { pid }) };
44
+ }
45
+ catch {
46
+ return { loaded: true };
47
+ }
48
+ }
49
+ return { loaded: false };
50
+ }
51
+ /** The bin script the installed service file runs, or undefined (no file, or unreadable). */
52
+ export function serviceBinPath(where) {
53
+ if (!hasLoginService(where.home, where.platform))
54
+ return undefined;
55
+ try {
56
+ if (where.platform === "darwin") {
57
+ return plistBinPath(readFileSync(plistPath(where.home), "utf8"));
58
+ }
59
+ return unitBinPath(readFileSync(unitPath(where.home), "utf8"));
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
65
+ /**
66
+ * The version of the package at `binPath` (`<package>/bin/capybara-device.mjs`), read from its
67
+ * `package.json`: what a restart of the service would run. Undefined when it cannot be read.
68
+ */
69
+ export function packageVersionAt(binPath) {
70
+ try {
71
+ const raw = readFileSync(join(dirname(dirname(binPath)), "package.json"), "utf8");
72
+ const version = JSON.parse(raw).version;
73
+ return typeof version === "string" ? version : undefined;
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /**
80
+ * Whether this process was started by the service manager: launchd sets `XPC_SERVICE_NAME` to the
81
+ * agent's label (a terminal on macOS sets it to `0` or the terminal app's), systemd sets
82
+ * `INVOCATION_ID`. A shell inside a systemd-run terminal inherits `INVOCATION_ID` too; systemd 248+
83
+ * also sets `SYSTEMD_EXEC_PID`, which names this process only when systemd started it.
84
+ */
85
+ export function startedByServiceManager(env, pid = process.pid) {
86
+ if (env.XPC_SERVICE_NAME === LAUNCHD_LABEL)
87
+ return true;
88
+ if ((env.INVOCATION_ID ?? "") === "")
89
+ return false;
90
+ return env.SYSTEMD_EXEC_PID === undefined || env.SYSTEMD_EXEC_PID === String(pid);
91
+ }
@@ -3,3 +3,5 @@ export declare const SYSTEMD_UNIT = "capybara-device.service";
3
3
  export declare function unitPath(home: string): string;
4
4
  /** The systemd user unit: `node <bin> start`, restarted on failure, wanted by the default target. */
5
5
  export declare function unitContent(spec: ServiceSpec): string;
6
+ /** The bin script a unit runs (the second word of `ExecStart`), or undefined. */
7
+ export declare function unitBinPath(content: string): string | undefined;
@@ -26,3 +26,11 @@ ${env}
26
26
  WantedBy=default.target
27
27
  `;
28
28
  }
29
+ /** The bin script a unit runs (the second word of `ExecStart`), or undefined. */
30
+ export function unitBinPath(content) {
31
+ const line = /^ExecStart=(.*)$/m.exec(content)?.[1];
32
+ if (line === undefined)
33
+ return undefined;
34
+ const words = [...line.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => (m[1] ?? "").replace(/\\(.)/g, "$1").replaceAll("%%", "%"));
35
+ return words[1];
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.1.0-rc.10",
3
+ "version": "0.1.0-rc.11",
4
4
  "description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {