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

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 (45) hide show
  1. package/README.md +51 -27
  2. package/dist/cli.d.ts +13 -2
  3. package/dist/cli.js +25 -4
  4. package/dist/client.d.ts +11 -3
  5. package/dist/client.js +18 -8
  6. package/dist/commands/drain.d.ts +3 -3
  7. package/dist/commands/drain.js +5 -4
  8. package/dist/commands/login.d.ts +3 -0
  9. package/dist/commands/login.js +33 -5
  10. package/dist/commands/logout.d.ts +2 -0
  11. package/dist/commands/logout.js +1 -1
  12. package/dist/commands/mode.d.ts +23 -6
  13. package/dist/commands/mode.js +24 -3
  14. package/dist/commands/service.d.ts +11 -4
  15. package/dist/commands/service.js +122 -65
  16. package/dist/commands/signal.d.ts +6 -2
  17. package/dist/commands/signal.js +7 -4
  18. package/dist/commands/start.d.ts +4 -0
  19. package/dist/commands/start.js +12 -5
  20. package/dist/commands/stop.d.ts +18 -7
  21. package/dist/commands/stop.js +20 -8
  22. package/dist/exec/docker.d.ts +24 -2
  23. package/dist/exec/docker.js +176 -2
  24. package/dist/exec/fs-helper.d.ts +7 -3
  25. package/dist/exec/fs-helper.js +70 -2
  26. package/dist/exec/host.d.ts +9 -1
  27. package/dist/exec/host.js +20 -0
  28. package/dist/exec/listing.d.ts +35 -0
  29. package/dist/exec/listing.js +157 -0
  30. package/dist/exec/os.d.ts +14 -2
  31. package/dist/exec/os.js +59 -13
  32. package/dist/exec/switch.d.ts +20 -4
  33. package/dist/exec/switch.js +39 -4
  34. package/dist/exec/types.d.ts +13 -1
  35. package/dist/pid.d.ts +33 -4
  36. package/dist/pid.js +91 -35
  37. package/dist/server-ops.d.ts +6 -4
  38. package/dist/server-ops.js +90 -17
  39. package/dist/service/launchd.d.ts +9 -6
  40. package/dist/service/launchd.js +22 -7
  41. package/dist/service/manager.d.ts +41 -0
  42. package/dist/service/manager.js +91 -0
  43. package/dist/service/systemd.d.ts +2 -0
  44. package/dist/service/systemd.js +8 -0
  45. package/package.json +2 -2
package/dist/exec/os.js CHANGED
@@ -2,12 +2,13 @@ import { spawn } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, realpathSync } from "node:fs";
4
4
  import { homedir, constants as osConstants } from "node:os";
5
- import { resolve } from "node:path";
5
+ import { isAbsolute, resolve } from "node:path";
6
6
  import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
7
7
  import { isBackgroundLaunch, } from "@capybara-hq/plugin-sdk";
8
8
  import { blockedHosts, denyReason, networkTrailer } from "../network.js";
9
9
  import { effectiveEgress, grantedHosts, srtConfig } from "../policy.js";
10
10
  import { FS_HELPER_SCRIPT } from "./fs-helper.js";
11
+ import { finishScan } from "./listing.js";
11
12
  import { EXEC_MARKER, killMarked } from "./procs.js";
12
13
  import { Reaper } from "./reap.js";
13
14
  import { sandboxUnavailableMessage } from "./sandbox-messages.js";
@@ -415,18 +416,10 @@ export class OsExecutor {
415
416
  });
416
417
  }
417
418
  /** Runs one file operation in the sandboxed helper; returns its `r`, throws its `e`. */
418
- async helper(op, path, maxBytes, data) {
419
- const script = [
420
- process.execPath,
421
- "-e",
422
- FS_HELPER_SCRIPT,
423
- "sandbox",
424
- op,
425
- path,
426
- String(maxBytes),
427
- this.roots.workspace,
428
- this.roots.tmp,
429
- ]
419
+ async helper(op, path, maxBytes, data, roots = [this.roots.workspace, this.roots.tmp], signal) {
420
+ signal?.throwIfAborted();
421
+ const script = [process.execPath, "-e", FS_HELPER_SCRIPT, "sandbox", op, path, String(maxBytes)]
422
+ .concat(roots)
430
423
  .map(shellQuote)
431
424
  .join(" ");
432
425
  const { child, commandId } = await this.spawnSandboxed(script, {
@@ -449,6 +442,15 @@ export class OsExecutor {
449
442
  if (child.pid !== undefined)
450
443
  killGroupId(child.pid);
451
444
  }, HELPER_TIMEOUT_MS);
445
+ // the kernel cancelled: the helper's whole process group goes at once
446
+ const onAbort = () => {
447
+ if (child.pid !== undefined)
448
+ killGroupId(child.pid);
449
+ };
450
+ signal?.addEventListener("abort", onAbort, { once: true });
451
+ // a listener added to an already-aborted signal never fires: an abort during the spawn lands here
452
+ if (signal?.aborted)
453
+ onAbort();
452
454
  try {
453
455
  await new Promise((res, rej) => {
454
456
  child.once("error", rej);
@@ -457,11 +459,13 @@ export class OsExecutor {
457
459
  }
458
460
  finally {
459
461
  clearTimeout(timer);
462
+ signal?.removeEventListener("abort", onAbort);
460
463
  if (child.pid !== undefined)
461
464
  killGroupId(child.pid);
462
465
  SandboxManager.unregisterCommandNetworkLists(commandId);
463
466
  SandboxManager.cleanupAfterCommand();
464
467
  }
468
+ signal?.throwIfAborted();
465
469
  if (timedOut)
466
470
  throw new DeviceOpError("error", `${op} ${path} timed out`);
467
471
  const text = Buffer.concat(chunks).toString("utf8");
@@ -500,6 +504,48 @@ export class OsExecutor {
500
504
  }
501
505
  return (await this.helper("stat", p, 0));
502
506
  }
507
+ /**
508
+ * The workspace path `path` names, refused unless it lies lexically under the workspace: sandbox
509
+ * mode offers the workspace only (spec §4.2), not the tmp or skills roots.
510
+ */
511
+ workspacePath(path) {
512
+ if (!isAbsolute(path))
513
+ throw policyError(`${path} is not an absolute path`);
514
+ const p = resolve(path);
515
+ if (!isUnder(p, this.roots.workspace)) {
516
+ throw policyError(`${path} is outside the device's workspace; in sandbox mode the device reads only that`);
517
+ }
518
+ return p;
519
+ }
520
+ /**
521
+ * Lists a workspace directory in the sandboxed helper (sandbox mode whatever `_mode` says: this
522
+ * executor has no other). A path outside the workspace is refused, also after resolving links.
523
+ */
524
+ async list(_mode, path, limit, signal) {
525
+ this.requireSandbox();
526
+ const p = this.workspacePath(path);
527
+ // the device directory is gone: nothing under the workspace exists (and no helper can start
528
+ // there, its working directory being the workspace)
529
+ if (!existsSync(this.roots.workspace))
530
+ return null;
531
+ const r = await this.helper("list", p, limit, undefined, [this.roots.workspace], signal);
532
+ if (r !== null && !Array.isArray(r.entries)) {
533
+ throw new DeviceOpError("error", `list ${path} answered an invalid result`);
534
+ }
535
+ return r;
536
+ }
537
+ /** Scans a workspace directory in the sandboxed helper ({@link list}'s rules). */
538
+ async scan(_mode, base, signal) {
539
+ this.requireSandbox();
540
+ const p = this.workspacePath(base);
541
+ if (!existsSync(this.roots.workspace))
542
+ return [];
543
+ const r = await this.helper("scan", p, 0, undefined, [this.roots.workspace], signal);
544
+ if (!Array.isArray(r) || !r.every((x) => typeof x === "string")) {
545
+ throw new DeviceOpError("error", `scan ${base} answered an invalid result`);
546
+ }
547
+ return finishScan(r);
548
+ }
503
549
  async killTagged(tags) {
504
550
  const want = new Set(tags);
505
551
  for (const g of [...this.groups])
@@ -1,5 +1,5 @@
1
1
  import type { DeviceExecArgs, ExecResult, SandboxLimits, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import type { Policy } from "../state.js";
2
+ import type { Policy, SandboxMode } from "../state.js";
3
3
  import { type ExecMode, type Executor } from "./types.js";
4
4
  export type { ExecMode } from "./types.js";
5
5
  /**
@@ -13,6 +13,12 @@ export type { ExecMode } from "./types.js";
13
13
  export declare const FILE_OPS_DECISION_TTL_MS = 60000;
14
14
  /** The refusal of an auto-mode command whose sandbox was turned back on before it started. */
15
15
  export declare const SANDBOX_BACK_ON: string;
16
+ /**
17
+ * The refusal of a file operation on a machine without the OS sandbox when no recent command
18
+ * decided the mode: file operations never pass command review, so they cannot exceed a ceiling
19
+ * the deployment has not confirmed.
20
+ */
21
+ export declare const NO_FRESH_DECISION: string;
16
22
  /**
17
23
  * The OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
18
24
  * directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
@@ -61,9 +67,10 @@ export declare class SwitchingExecutor implements Executor {
61
67
  * The executor for file operations now. File operations carry no limits and never pass command
62
68
  * review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
63
69
  * any exec and once those limits are stale (the safe default for an organization whose ceiling
64
- * is sandbox), else `effectiveMode(policy, limits)`. On a machine without the OS sandbox, auto
65
- * mode still works: without a fresh sandbox decision the host runs them (a sandbox decision is
66
- * refused by the sandboxed executor with the reason).
70
+ * is sandbox), else `effectiveMode(policy, limits)`. On a machine without the OS sandbox there is
71
+ * no safe default: without a fresh decision they are refused ({@link NO_FRESH_DECISION}), never
72
+ * run on the host; a fresh auto decision runs them on the host, a sandbox one is refused by the
73
+ * sandboxed executor with the reason.
67
74
  */
68
75
  private files;
69
76
  exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
@@ -83,6 +90,15 @@ export declare class SwitchingExecutor implements Executor {
83
90
  size: number;
84
91
  isDir: boolean;
85
92
  } | null>;
93
+ /**
94
+ * The executor that reads as a device in `mode` (the request's own effective mode), without the
95
+ * file-operation window: the host with the owner's rights in auto mode, else the sandboxed
96
+ * helper. The policy is reread and wins: a sandbox turned on on the machine reads through the
97
+ * sandboxed helper whatever `mode` says.
98
+ */
99
+ private readerFor;
100
+ list(mode: SandboxMode, path: string, limit: number, signal: AbortSignal): Promise<import("@capybara-hq/plugin-sdk").DeviceListResult>;
101
+ scan(mode: SandboxMode, base: string, signal: AbortSignal): Promise<import("@capybara-hq/plugin-sdk").DeviceScanResult>;
86
102
  killTagged(tags: string[]): Promise<void>;
87
103
  killAll(): Promise<void>;
88
104
  ensureRoot(): Promise<"ok" | "gone">;
@@ -14,6 +14,14 @@ const WATCH_INTERVAL_MS = 1000;
14
14
  /** The refusal of an auto-mode command whose sandbox was turned back on before it started. */
15
15
  export const SANDBOX_BACK_ON = "The sandbox was turned back on on this machine while the command was starting, so it did " +
16
16
  "not run. Run it again: it runs in the sandbox now.";
17
+ /**
18
+ * The refusal of a file operation on a machine without the OS sandbox when no recent command
19
+ * decided the mode: file operations never pass command review, so they cannot exceed a ceiling
20
+ * the deployment has not confirmed.
21
+ */
22
+ export const NO_FRESH_DECISION = "The OS sandbox is unavailable on this machine and no recent command decided this device's " +
23
+ "mode, so file operations are refused until the next command runs (the deployment decides the " +
24
+ "mode at each command).";
17
25
  /**
18
26
  * The OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
19
27
  * directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
@@ -99,9 +107,10 @@ export class SwitchingExecutor {
99
107
  * The executor for file operations now. File operations carry no limits and never pass command
100
108
  * review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
101
109
  * any exec and once those limits are stale (the safe default for an organization whose ceiling
102
- * is sandbox), else `effectiveMode(policy, limits)`. On a machine without the OS sandbox, auto
103
- * mode still works: without a fresh sandbox decision the host runs them (a sandbox decision is
104
- * refused by the sandboxed executor with the reason).
110
+ * is sandbox), else `effectiveMode(policy, limits)`. On a machine without the OS sandbox there is
111
+ * no safe default: without a fresh decision they are refused ({@link NO_FRESH_DECISION}), never
112
+ * run on the host; a fresh auto decision runs them on the host, a sandbox one is refused by the
113
+ * sandboxed executor with the reason.
105
114
  */
106
115
  async files() {
107
116
  const policy = this.policy();
@@ -110,7 +119,9 @@ export class SwitchingExecutor {
110
119
  return this.sandboxed;
111
120
  if (this.lastLimits === undefined ||
112
121
  Date.now() - this.lastLimitsAt > FILE_OPS_DECISION_TTL_MS) {
113
- return this.sandboxReady ? this.sandboxed : this.host;
122
+ if (!this.sandboxReady)
123
+ throw new DeviceOpError("policy", NO_FRESH_DECISION);
124
+ return this.sandboxed;
114
125
  }
115
126
  return this.lastLimits.mode === "sandbox" ? this.sandboxed : this.host;
116
127
  }
@@ -146,6 +157,30 @@ export class SwitchingExecutor {
146
157
  async stat(path) {
147
158
  return (await this.files()).stat(path);
148
159
  }
160
+ /**
161
+ * The executor that reads as a device in `mode` (the request's own effective mode), without the
162
+ * file-operation window: the host with the owner's rights in auto mode, else the sandboxed
163
+ * helper. The policy is reread and wins: a sandbox turned on on the machine reads through the
164
+ * sandboxed helper whatever `mode` says.
165
+ */
166
+ async readerFor(mode) {
167
+ const policy = this.policy();
168
+ await this.sync(policy);
169
+ const auto = mode === "auto" && policy.mode === "auto";
170
+ return auto ? { ex: this.host, mode: "auto" } : { ex: this.sandboxed, mode: "sandbox" };
171
+ }
172
+ async list(mode, path, limit, signal) {
173
+ const r = await this.readerFor(mode);
174
+ if (r.ex.list === undefined)
175
+ throw new DeviceOpError("error", "unsupported operation");
176
+ return r.ex.list(r.mode, path, limit, signal);
177
+ }
178
+ async scan(mode, base, signal) {
179
+ const r = await this.readerFor(mode);
180
+ if (r.ex.scan === undefined)
181
+ throw new DeviceOpError("error", "unsupported operation");
182
+ return r.ex.scan(r.mode, base, signal);
183
+ }
149
184
  async killTagged(tags) {
150
185
  await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
151
186
  }
@@ -1,4 +1,4 @@
1
- import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import type { DeviceErrorKind, DeviceExecArgs, DeviceListResult, DeviceScanResult, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
2
  import type { Policy, SandboxMode } from "../state.js";
3
3
  /** How one command runs: in auto mode (no OS sandbox) or in the sandbox. */
4
4
  export interface ExecMode {
@@ -33,6 +33,18 @@ export interface Executor {
33
33
  size: number;
34
34
  isDir: boolean;
35
35
  } | null>;
36
+ /**
37
+ * Lists one directory as a device in `mode` reads (`SandboxProvider.list`'s semantics): `mode`
38
+ * is the request's own, `effectiveMode(policy, limits)` on the ceiling that came with it, never
39
+ * the latest command's decision. Auto mode reads with the owner's rights; sandbox mode through
40
+ * the sandboxed helper, the workspace only; a container device its workspace only, in either
41
+ * mode. A path the mode cannot reach throws a `policy` refusal. Works without the device
42
+ * directory (it is not called through `ensureRoot`). Optional: without it (and {@link scan})
43
+ * the device answers `list` and `scan` as unsupported.
44
+ */
45
+ list?(mode: SandboxMode, path: string, limit: number, signal: AbortSignal): Promise<DeviceListResult>;
46
+ /** Looks for projects under `base` as a device in `mode` reads ({@link list}'s rules). */
47
+ scan?(mode: SandboxMode, base: string, signal: AbortSignal): Promise<DeviceScanResult>;
36
48
  killTagged(tags: string[]): Promise<void>;
37
49
  killAll(): Promise<void>;
38
50
  /**
package/dist/pid.d.ts CHANGED
@@ -9,10 +9,39 @@ export type RunningProgram = {
9
9
  version?: string;
10
10
  startedAt?: string;
11
11
  };
12
+ /** What `ps` tells of a process: its command line and, when known, when it started. */
13
+ export interface ProcessInfo {
14
+ command: string;
15
+ started?: Date;
16
+ }
17
+ /** Looks a process up by pid (default: `ps`); undefined when there is no such process. */
18
+ export type ProcessLookup = (pid: number) => ProcessInfo | undefined;
19
+ /** How a pid is checked: `kill(pid, 0)` for liveness, `ps` for what the process is. */
20
+ export interface ProcessChecks {
21
+ kill?: typeof process.kill;
22
+ ps?: ProcessLookup;
23
+ }
24
+ /** The name every command line of this program contains (`…/bin/capybara-device.mjs start`). */
25
+ export declare const PROGRAM_BIN = "capybara-device";
26
+ /**
27
+ * Parses `ps -o lstart= -o command=` output (C locale): `Sat Nov 14 02:11:37 2026 <command>`, the
28
+ * start in local time. A line without a readable start keeps only the command.
29
+ */
30
+ export declare function parsePsOutput(output: string): ProcessInfo | undefined;
31
+ /** The default {@link ProcessLookup}: one `ps` call in the C locale. */
32
+ export declare function psLookup(pid: number): ProcessInfo | undefined;
12
33
  export declare function isAlive(pid: number, kill?: typeof process.kill): boolean;
13
- /** The running program, or undefined (no file, a stale one, or a file that is not a pid). */
14
- export declare function readRunning(dir: string, kill?: typeof process.kill): RunningProgram | undefined;
15
- /** The pid of the running program, or undefined (no file, or a stale one). */
16
- export declare function readRunningPid(dir: string, kill?: typeof process.kill): number | undefined;
34
+ /**
35
+ * The entry a pid file holds: JSON `{pid, version, startedAt}`, or a bare pid from a program older
36
+ * than the version field. Undefined when it is neither.
37
+ */
38
+ export declare function parsePidFile(raw: string): RunningProgram | undefined;
39
+ /**
40
+ * The running program, or undefined: no file, a file that is not a pid, a dead pid, or a pid that
41
+ * is not this program any more (see {@link namesThisProgram}). Nothing signals an unverified pid.
42
+ */
43
+ export declare function readRunning(dir: string, checks?: ProcessChecks): RunningProgram | undefined;
44
+ /** The pid of the running program, or undefined (see {@link readRunning}). */
45
+ export declare function readRunningPid(dir: string, checks?: ProcessChecks): number | undefined;
17
46
  export declare function writePid(dir: string, pid: number, version?: string): void;
18
47
  export declare function removePid(dir: string, pid: number): void;
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,16 +29,18 @@ 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
  /**
39
41
  * Runs one request and returns the answer plus its local audit line and, for an exec, its mode
40
42
  * (for the local command log). A vanished device directory answers `fs_gone` for every operation
41
- * except `stop`, `policy` and `policyStatus`. Never throws.
43
+ * except `stop`, `policy`, `policyStatus`, `list` and `scan`. Never throws.
42
44
  */
43
45
  export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
44
46
  res: DeviceRes;
@@ -1,4 +1,4 @@
1
- import { isPolicyOpId, validateAllowHost, } from "@capybara-hq/plugin-sdk";
1
+ import { isPolicyOpId, MAX_DEVICE_LIST_ENTRIES, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
2
  import { DeviceOpError } from "./exec/types.js";
3
3
  import { effectiveMode, grantedHosts } from "./policy.js";
4
4
  import { publicSuffixWildcard } from "./public-suffix.js";
@@ -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
  }
@@ -190,6 +192,22 @@ function servePolicyOp(req, store, facts) {
190
192
  throw e;
191
193
  }
192
194
  }
195
+ /**
196
+ * Whether `op` is answered from the local policy file: it lives in the state directory, so these
197
+ * work while the device directory is gone, like the `policy` ops.
198
+ */
199
+ function isLocalPolicyOp(op) {
200
+ return op === "policy" || op === "policyStatus";
201
+ }
202
+ /** The answer to an operation this program does not serve (no policy store, or no reader). */
203
+ function unsupported(req) {
204
+ return {
205
+ type: "res",
206
+ id: req.id,
207
+ ok: false,
208
+ error: { kind: "error", message: "unsupported operation" },
209
+ };
210
+ }
193
211
  /** What the log says of an op id, with the summary now. Read-only. */
194
212
  function policyStatus(store, args, facts) {
195
213
  const opId = args?.opId;
@@ -203,6 +221,52 @@ function policyStatus(store, args, facts) {
203
221
  ...(known?.outcome === "refused" && known.message !== undefined && { message: known.message }),
204
222
  };
205
223
  }
224
+ /** A `list` / `scan` field that must be a clean absolute path, checked again here. */
225
+ function requestPath(v, key) {
226
+ const errors = typeof v === "string" ? validateSandboxPathShape(v) : ["path must be a string"];
227
+ if (errors.length > 0) {
228
+ throw new DeviceOpError("error", `invalid request: field "${key}": ${errors.join("; ")}`);
229
+ }
230
+ return v;
231
+ }
232
+ /** A `list` / `scan` request's ceiling (`limits.mode`), checked again here. */
233
+ function requestCeiling(args) {
234
+ const mode = args?.limits?.mode;
235
+ if (mode !== "auto" && mode !== "sandbox") {
236
+ throw new DeviceOpError("error", 'invalid request: field "limits.mode" must be "auto" or "sandbox"');
237
+ }
238
+ return { mode };
239
+ }
240
+ /**
241
+ * A `list` or `scan` request (a trust boundary: the device decides what a web session sees of its
242
+ * machine). Each is read in the mode it would run in now, `effectiveMode` of the owner's policy and
243
+ * the ceiling the request carries, never one an earlier command saw nor the file operations'
244
+ * window. Answered without the device directory: it reads the owner's machine, not that
245
+ * directory. Throws like the executor (a path its mode cannot reach is a `policy` refusal).
246
+ */
247
+ async function serveRead(executor, req, signal, store) {
248
+ const args = req.args;
249
+ const limits = requestCeiling(args);
250
+ if (req.op === "list") {
251
+ const path = requestPath(args?.path, "path");
252
+ const limit = args?.limit;
253
+ if (typeof limit !== "number" ||
254
+ !Number.isInteger(limit) ||
255
+ limit < 1 ||
256
+ limit > MAX_DEVICE_LIST_ENTRIES) {
257
+ throw new DeviceOpError("error", `invalid request: field "limit" must be an integer from 1 to ${MAX_DEVICE_LIST_ENTRIES}`);
258
+ }
259
+ const mode = effectiveMode(store.current(), limits);
260
+ signal.throwIfAborted();
261
+ const result = await executor.list(mode, path, limit, signal);
262
+ return { result, detail: `list ${clean(path, 300)} in ${mode} mode` };
263
+ }
264
+ const base = requestPath(args?.base, "base");
265
+ const mode = effectiveMode(store.current(), limits);
266
+ signal.throwIfAborted();
267
+ const result = await executor.scan(mode, base, signal);
268
+ return { result, detail: `scan ${clean(base, 300)} in ${mode} mode` };
269
+ }
206
270
  /** The audit line of an exec whose grants applied (sandbox mode only: auto mode ignores grants). */
207
271
  function grantsDetail(executor, args, policy) {
208
272
  if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
@@ -219,7 +283,7 @@ function grantsDetail(executor, args, policy) {
219
283
  /**
220
284
  * Runs one request and returns the answer plus its local audit line and, for an exec, its mode
221
285
  * (for the local command log). A vanished device directory answers `fs_gone` for every operation
222
- * except `stop`, `policy` and `policyStatus`. Never throws.
286
+ * except `stop`, `policy`, `policyStatus`, `list` and `scan`. Never throws.
223
287
  */
224
288
  export async function serveOp(executor, req, signal, ctx = {}) {
225
289
  const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
@@ -227,22 +291,31 @@ export async function serveOp(executor, req, signal, ctx = {}) {
227
291
  if (req.op === "stop")
228
292
  return { res: ok(null) };
229
293
  // The policy lives in the state directory, not the device directory.
230
- if (req.op === "policy" || req.op === "policyStatus") {
231
- if (ctx.policy === undefined) {
232
- return {
233
- res: {
234
- type: "res",
235
- id: req.id,
236
- ok: false,
237
- error: { kind: "error", message: "unsupported operation" },
238
- },
239
- };
240
- }
294
+ if (isLocalPolicyOp(req.op)) {
295
+ if (ctx.policy === undefined)
296
+ return { res: unsupported(req) };
241
297
  const facts = summaryFacts(executor, ctx);
242
298
  if (req.op === "policyStatus")
243
299
  return { res: ok(policyStatus(ctx.policy, req.args, facts)) };
244
300
  return servePolicyOp(req, ctx.policy, facts);
245
301
  }
302
+ // They read the owner's machine in the request's own mode, not the device directory, so they
303
+ // work while that directory is gone. Served only with a policy store (the mode needs the
304
+ // owner's choice) and by an executor that can read in a given mode.
305
+ if (req.op === "list" || req.op === "scan") {
306
+ const can = req.op === "list" ? executor.list : executor.scan;
307
+ if (ctx.policy === undefined || can === undefined)
308
+ return { res: unsupported(req) };
309
+ try {
310
+ const { result, detail } = await serveRead(executor, req, signal, ctx.policy);
311
+ return { res: ok(result), detail };
312
+ }
313
+ catch (e) {
314
+ const { res } = errorAnswer(req, e);
315
+ const message = res.ok ? "" : clean(res.error.message, 300);
316
+ return { res, detail: `${req.op} refused: ${message}` };
317
+ }
318
+ }
246
319
  if ((await executor.ensureRoot()) === "gone") {
247
320
  return {
248
321
  res: {