@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,29 @@
1
- import type { SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import { type SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import type { SandboxMode } from "../state.js";
2
3
  import { DeviceOpError } from "./types.js";
3
- /** The file that marks a directory as an environment directory this program has used. */
4
+ /** The file that marks a directory as a device directory this program has used. */
4
5
  export declare const ROOT_MARKER = ".capybara-device";
5
6
  /** How long a finished command's output pipes may stay open (held by a background child). */
6
7
  export declare const PIPE_GRACE_MS = 200;
7
8
  export declare const ENV_NAME_RE: RegExp;
8
- /** The roots of an environment directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
9
+ /** The roots of a device directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
9
10
  export declare function osRoots(dir: string): SandboxRoots;
11
+ /**
12
+ * The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
13
+ * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
14
+ * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
15
+ * sets them.
16
+ */
17
+ export declare const TOOL_HOME_DIRS: readonly (readonly [string, string])[];
18
+ /**
19
+ * The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
20
+ * the device's environment `env` sets to an absolute path is passed on; an unset one points at its
21
+ * default directory under the real `home` when that is a directory. The sandbox only reads them
22
+ * (they are never made writable); the secret paths stay denied. asdf's global `.tool-versions`
23
+ * is still found: asdf walks up from the working directory, and the device directory is under the
24
+ * home.
25
+ */
26
+ export declare function toolHomeEnv(home: string, env?: Record<string, string | undefined>): Record<string, string>;
10
27
  /**
11
28
  * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
12
29
  * dropped instead of decoding to U+FFFD).
@@ -28,12 +45,12 @@ export declare class OutputCap {
28
45
  text(stream: "stdout" | "stderr"): string;
29
46
  }
30
47
  /**
31
- * Creates (or completes) an environment directory: the marker and the three roots. Only `login`
32
- * calls it, so logging in again after the files were lost starts the environment afresh.
48
+ * Creates (or completes) a device directory: the marker and the three roots. Only `login`
49
+ * calls it, so logging in again after the files were lost starts the device afresh.
33
50
  */
34
- export declare function prepareEnvironmentDir(dir: string): void;
51
+ export declare function prepareDeviceDir(dir: string): void;
35
52
  /**
36
- * The environment directory's marker and roots. Once the marker exists, the directory, the marker
53
+ * The device directory's marker and roots. Once the marker exists, the directory, the marker
37
54
  * or any root vanishing is "gone": nothing is recreated silently (log in again to start afresh).
38
55
  */
39
56
  export declare class RootGuard {
@@ -45,17 +62,29 @@ export declare class RootGuard {
45
62
  ensure(): "ok" | "gone";
46
63
  }
47
64
  /**
48
- * Host-side file access under the three roots (real paths, symlinks resolved, refused when they
49
- * leave a root). Used for the skills root, which commands can only read, so nothing can race it.
65
+ * Host-side file access. In sandbox mode `path`s are confined to the three roots (real paths,
66
+ * symlinks resolved, refused when they leave a root); in auto mode any clean absolute path is
67
+ * accepted (shape checks only: absolute, no `..` segments, no control characters). Used for the
68
+ * skills root (commands can only read it, so nothing can race it) and by the host executor.
50
69
  */
51
70
  export declare class HostFiles {
52
71
  private readonly roots;
53
- constructor(roots: SandboxRoots);
54
- /** `path` made absolute and normalized; refused unless it is lexically under a root. */
72
+ private readonly mode;
73
+ constructor(roots: SandboxRoots, mode: SandboxMode);
74
+ /**
75
+ * `path` made absolute and normalized; in sandbox mode refused unless it is lexically under a
76
+ * root, in auto mode accepted when its shape is clean.
77
+ */
55
78
  lexical(path: string): string;
56
- /** The real path of an existing `path`, refused unless under a root after resolving links; null when missing. */
79
+ /**
80
+ * The real path of an existing `path` (null when missing); in sandbox mode refused unless under
81
+ * a root after resolving links.
82
+ */
57
83
  existing(path: string): Promise<string | null>;
58
- /** The real path of an existing `path` under a root (symlinks resolved); refused otherwise. */
84
+ /**
85
+ * The real path of an existing `path` (symlinks resolved); in sandbox mode refused unless under
86
+ * a root.
87
+ */
59
88
  inside(path: string, what: string): Promise<string>;
60
89
  private checkReal;
61
90
  private rootList;
@@ -1,16 +1,73 @@
1
- import { constants, existsSync, mkdirSync, writeFileSync } from "node:fs";
1
+ import { constants, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
2
  import { lstat, mkdir, open, realpath } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { validateSandboxPathShape } from "@capybara-hq/plugin-sdk";
4
5
  import { DeviceOpError } from "./types.js";
5
- /** The file that marks a directory as an environment directory this program has used. */
6
+ /** The file that marks a directory as a device directory this program has used. */
6
7
  export const ROOT_MARKER = ".capybara-device";
7
8
  /** How long a finished command's output pipes may stay open (held by a background child). */
8
9
  export const PIPE_GRACE_MS = 200;
9
10
  export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
- /** The roots of an environment directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
11
+ /** The roots of a device directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
11
12
  export function osRoots(dir) {
12
13
  return { workspace: join(dir, "workspace"), skills: join(dir, "skills"), tmp: join(dir, "tmp") };
13
14
  }
15
+ /**
16
+ * The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
17
+ * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
18
+ * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
19
+ * sets them.
20
+ */
21
+ export const TOOL_HOME_DIRS = [
22
+ ["ASDF_DATA_DIR", ".asdf"],
23
+ ["NVM_DIR", ".nvm"],
24
+ ["PYENV_ROOT", ".pyenv"],
25
+ ["RBENV_ROOT", ".rbenv"],
26
+ ["MISE_DATA_DIR", ".local/share/mise"],
27
+ ["MISE_CONFIG_DIR", ".config/mise"],
28
+ ["VOLTA_HOME", ".volta"],
29
+ ["SDKMAN_DIR", ".sdkman"],
30
+ ["RUSTUP_HOME", ".rustup"],
31
+ ];
32
+ function isDir(path) {
33
+ try {
34
+ return statSync(path).isDirectory();
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ /**
41
+ * The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
42
+ * the device's environment `env` sets to an absolute path is passed on; an unset one points at its
43
+ * default directory under the real `home` when that is a directory. The sandbox only reads them
44
+ * (they are never made writable); the secret paths stay denied. asdf's global `.tool-versions`
45
+ * is still found: asdf walks up from the working directory, and the device directory is under the
46
+ * home.
47
+ */
48
+ export function toolHomeEnv(home, env = process.env) {
49
+ const xdg = (name, rel) => {
50
+ const v = env[name];
51
+ return v !== undefined && isAbsolute(v) ? v : join(home, rel);
52
+ };
53
+ const defaults = {
54
+ MISE_DATA_DIR: join(xdg("XDG_DATA_HOME", ".local/share"), "mise"),
55
+ MISE_CONFIG_DIR: join(xdg("XDG_CONFIG_HOME", ".config"), "mise"),
56
+ };
57
+ const out = {};
58
+ for (const [name, rel] of TOOL_HOME_DIRS) {
59
+ const set = env[name];
60
+ if (set !== undefined && set !== "") {
61
+ if (isAbsolute(set))
62
+ out[name] = set;
63
+ continue;
64
+ }
65
+ const dir = defaults[name] ?? join(home, rel);
66
+ if (isDir(dir))
67
+ out[name] = dir;
68
+ }
69
+ return out;
70
+ }
14
71
  /**
15
72
  * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
16
73
  * dropped instead of decoding to U+FFFD).
@@ -69,12 +126,12 @@ export class OutputCap {
69
126
  return (this.cut[stream] ? utf8Prefix(all) : all).toString("utf8");
70
127
  }
71
128
  }
72
- const MARKER_TEXT = "This directory is a capybara-device environment.\n";
129
+ const MARKER_TEXT = "This directory is a capybara-device directory.\n";
73
130
  /**
74
- * Creates (or completes) an environment directory: the marker and the three roots. Only `login`
75
- * calls it, so logging in again after the files were lost starts the environment afresh.
131
+ * Creates (or completes) a device directory: the marker and the three roots. Only `login`
132
+ * calls it, so logging in again after the files were lost starts the device afresh.
76
133
  */
77
- export function prepareEnvironmentDir(dir) {
134
+ export function prepareDeviceDir(dir) {
78
135
  for (const r of Object.values(osRoots(dir)))
79
136
  mkdirSync(r, { recursive: true });
80
137
  const marker = join(dir, ROOT_MARKER);
@@ -82,7 +139,7 @@ export function prepareEnvironmentDir(dir) {
82
139
  writeFileSync(marker, MARKER_TEXT);
83
140
  }
84
141
  /**
85
- * The environment directory's marker and roots. Once the marker exists, the directory, the marker
142
+ * The device directory's marker and roots. Once the marker exists, the directory, the marker
86
143
  * or any root vanishing is "gone": nothing is recreated silently (log in again to start afresh).
87
144
  */
88
145
  export class RootGuard {
@@ -113,25 +170,41 @@ export class RootGuard {
113
170
  }
114
171
  }
115
172
  /**
116
- * Host-side file access under the three roots (real paths, symlinks resolved, refused when they
117
- * leave a root). Used for the skills root, which commands can only read, so nothing can race it.
173
+ * Host-side file access. In sandbox mode `path`s are confined to the three roots (real paths,
174
+ * symlinks resolved, refused when they leave a root); in auto mode any clean absolute path is
175
+ * accepted (shape checks only: absolute, no `..` segments, no control characters). Used for the
176
+ * skills root (commands can only read it, so nothing can race it) and by the host executor.
118
177
  */
119
178
  export class HostFiles {
120
179
  roots;
121
- constructor(roots) {
180
+ mode;
181
+ constructor(roots, mode) {
122
182
  this.roots = roots;
183
+ this.mode = mode;
123
184
  }
124
- /** `path` made absolute and normalized; refused unless it is lexically under a root. */
185
+ /**
186
+ * `path` made absolute and normalized; in sandbox mode refused unless it is lexically under a
187
+ * root, in auto mode accepted when its shape is clean.
188
+ */
125
189
  lexical(path) {
190
+ if (this.mode === "auto") {
191
+ const errors = validateSandboxPathShape(path);
192
+ if (errors.length > 0)
193
+ throw policyError(`${path}: ${errors.join("; ")}`);
194
+ return resolve(path);
195
+ }
126
196
  if (!isAbsolute(path))
127
197
  throw policyError(`${path} is not an absolute path`);
128
198
  const p = resolve(path);
129
199
  if (!this.rootList().some((r) => isUnder(p, r))) {
130
- throw policyError(`${path} is outside the environment's roots (${this.rootList().join(", ")})`);
200
+ throw policyError(`${path} is outside the device's roots (${this.rootList().join(", ")})`);
131
201
  }
132
202
  return p;
133
203
  }
134
- /** The real path of an existing `path`, refused unless under a root after resolving links; null when missing. */
204
+ /**
205
+ * The real path of an existing `path` (null when missing); in sandbox mode refused unless under
206
+ * a root after resolving links.
207
+ */
135
208
  async existing(path) {
136
209
  const p = this.lexical(path);
137
210
  let real;
@@ -145,7 +218,10 @@ export class HostFiles {
145
218
  }
146
219
  return this.checkReal(path, real);
147
220
  }
148
- /** The real path of an existing `path` under a root (symlinks resolved); refused otherwise. */
221
+ /**
222
+ * The real path of an existing `path` (symlinks resolved); in sandbox mode refused unless under
223
+ * a root.
224
+ */
149
225
  async inside(path, what) {
150
226
  const p = this.lexical(path);
151
227
  let real;
@@ -160,9 +236,11 @@ export class HostFiles {
160
236
  return this.checkReal(path, real);
161
237
  }
162
238
  async checkReal(path, real) {
239
+ if (this.mode === "auto")
240
+ return real;
163
241
  const roots = await Promise.all(this.rootList().map((r) => realpath(r).catch(() => r)));
164
242
  if (!roots.some((r) => isUnder(real, r))) {
165
- throw policyError(`${path} resolves to ${real}, outside the environment's roots`);
243
+ throw policyError(`${path} resolves to ${real}, outside the device's roots`);
166
244
  }
167
245
  return real;
168
246
  }
@@ -0,0 +1,98 @@
1
+ import type { DeviceExecArgs, ExecResult, SandboxLimits, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import type { Policy } from "../state.js";
3
+ import { type ExecMode, type Executor } from "./types.js";
4
+ export type { ExecMode } from "./types.js";
5
+ /**
6
+ * How long the latest command's limits decide file operations. The kernel judges the mode at each
7
+ * exec, and file operations carry no limits, so a decision older than this no longer counts: file
8
+ * operations fall back to the sandboxed helper (the safe default for an organization whose ceiling
9
+ * is sandbox), until the next command decides again. A minute covers a turn's file operations
10
+ * around its commands while bounding how long an organization's change takes to reach a device
11
+ * that runs no more commands.
12
+ */
13
+ export declare const FILE_OPS_DECISION_TTL_MS = 60000;
14
+ /** The refusal of an auto-mode command whose sandbox was turned back on before it started. */
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;
22
+ /**
23
+ * The OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
24
+ * directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
25
+ * applies at the next command. File operations use the host executor's direct IO (any absolute
26
+ * path in auto mode, the roots in the sandbox) only while the latest command's decision is fresh;
27
+ * before any command, or once its limits are stale, the sandboxed helper runs (file operations
28
+ * never pass command review, so the org's ceiling may not be exceeded). When the policy turns the
29
+ * sandbox back on, every auto-mode command still running (and what it left in the background) is
30
+ * killed, and one still starting is refused right before its spawn; while auto mode is on, the
31
+ * policy is also checked every second so that happens without waiting for the next operation.
32
+ * Kills reach both executors' commands.
33
+ */
34
+ export declare class SwitchingExecutor implements Executor {
35
+ private readonly sandboxed;
36
+ /** Runs commands without a sandbox (the `HostExecutor`). */
37
+ private readonly host;
38
+ private readonly policy;
39
+ private readonly onSwitch?;
40
+ readonly mode: "os";
41
+ readonly roots: SandboxRoots;
42
+ /** The policy said auto mode when last checked. */
43
+ private auto;
44
+ /**
45
+ * Whether the OS sandbox can run here. When it cannot, sandbox-mode operations go to the
46
+ * sandboxed executor and are refused there with the reason; auto mode keeps working.
47
+ */
48
+ private readonly sandboxReady;
49
+ private watch;
50
+ /** The latest command's limits and when they came (file operations follow their decision). */
51
+ private lastLimits;
52
+ private lastLimitsAt;
53
+ constructor(sandboxed: Executor,
54
+ /** Runs commands without a sandbox (the `HostExecutor`). */
55
+ host: Executor, policy: () => Policy, onSwitch?: ((mode: "auto" | "sandbox") => void) | undefined);
56
+ /**
57
+ * Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills the
58
+ * auto-mode commands. Returns whether the policy says auto mode now.
59
+ */
60
+ sync(policy?: Policy): Promise<boolean>;
61
+ /**
62
+ * Records an exec's limits, refused ones included, so file operations follow the latest
63
+ * decision (see {@link FILE_OPS_DECISION_TTL_MS}).
64
+ */
65
+ noteLimits(limits: Pick<SandboxLimits, "mode">): void;
66
+ /**
67
+ * The executor for file operations now. File operations carry no limits and never pass command
68
+ * review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
69
+ * any exec and once those limits are stale (the safe default for an organization whose ceiling
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.
74
+ */
75
+ private files;
76
+ exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
77
+ /**
78
+ * Runs one command as `how` decided (the caller logs the same decision). The policy it was
79
+ * decided on is synced first, so a sandbox turned back on stops the auto-mode commands. An
80
+ * auto-mode command is decided again on the policy then, right before its spawn: one whose
81
+ * sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
82
+ */
83
+ execDecided(args: DeviceExecArgs, signal: AbortSignal, how: ExecMode, policy?: Policy): Promise<ExecResult>;
84
+ readFile(path: string, maxBytes: number): Promise<{
85
+ data: Uint8Array;
86
+ truncated: boolean;
87
+ } | null>;
88
+ writeFile(path: string, data: Uint8Array): Promise<void>;
89
+ stat(path: string): Promise<{
90
+ size: number;
91
+ isDir: boolean;
92
+ } | null>;
93
+ killTagged(tags: string[]): Promise<void>;
94
+ killAll(): Promise<void>;
95
+ ensureRoot(): Promise<"ok" | "gone">;
96
+ /** Stops watching the policy. */
97
+ dispose(): void;
98
+ }
@@ -0,0 +1,175 @@
1
+ import { effectiveMode } from "../policy.js";
2
+ import { DeviceOpError } from "./types.js";
3
+ /**
4
+ * How long the latest command's limits decide file operations. The kernel judges the mode at each
5
+ * exec, and file operations carry no limits, so a decision older than this no longer counts: file
6
+ * operations fall back to the sandboxed helper (the safe default for an organization whose ceiling
7
+ * is sandbox), until the next command decides again. A minute covers a turn's file operations
8
+ * around its commands while bounding how long an organization's change takes to reach a device
9
+ * that runs no more commands.
10
+ */
11
+ export const FILE_OPS_DECISION_TTL_MS = 60_000;
12
+ /** How often the switching executor rereads the policy while auto mode is on. */
13
+ const WATCH_INTERVAL_MS = 1000;
14
+ /** The refusal of an auto-mode command whose sandbox was turned back on before it started. */
15
+ export const SANDBOX_BACK_ON = "The sandbox was turned back on on this machine while the command was starting, so it did " +
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).";
25
+ /**
26
+ * The OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
27
+ * directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
28
+ * applies at the next command. File operations use the host executor's direct IO (any absolute
29
+ * path in auto mode, the roots in the sandbox) only while the latest command's decision is fresh;
30
+ * before any command, or once its limits are stale, the sandboxed helper runs (file operations
31
+ * never pass command review, so the org's ceiling may not be exceeded). When the policy turns the
32
+ * sandbox back on, every auto-mode command still running (and what it left in the background) is
33
+ * killed, and one still starting is refused right before its spawn; while auto mode is on, the
34
+ * policy is also checked every second so that happens without waiting for the next operation.
35
+ * Kills reach both executors' commands.
36
+ */
37
+ export class SwitchingExecutor {
38
+ sandboxed;
39
+ host;
40
+ policy;
41
+ onSwitch;
42
+ mode = "os";
43
+ roots;
44
+ /** The policy said auto mode when last checked. */
45
+ auto = false;
46
+ /**
47
+ * Whether the OS sandbox can run here. When it cannot, sandbox-mode operations go to the
48
+ * sandboxed executor and are refused there with the reason; auto mode keeps working.
49
+ */
50
+ sandboxReady;
51
+ watch;
52
+ /** The latest command's limits and when they came (file operations follow their decision). */
53
+ lastLimits;
54
+ lastLimitsAt = 0;
55
+ constructor(sandboxed,
56
+ /** Runs commands without a sandbox (the `HostExecutor`). */
57
+ host, policy, onSwitch) {
58
+ this.sandboxed = sandboxed;
59
+ this.host = host;
60
+ this.policy = policy;
61
+ this.onSwitch = onSwitch;
62
+ this.roots = sandboxed.roots;
63
+ this.sandboxReady = sandboxed.available !== false;
64
+ }
65
+ /**
66
+ * Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills the
67
+ * auto-mode commands. Returns whether the policy says auto mode now.
68
+ */
69
+ async sync(policy = this.policy()) {
70
+ const auto = policy.mode === "auto";
71
+ if (auto === this.auto)
72
+ return auto;
73
+ if (auto) {
74
+ this.auto = true;
75
+ this.watch ??= setInterval(() => void this.sync().catch(() => { }), WATCH_INTERVAL_MS);
76
+ this.watch.unref();
77
+ this.onSwitch?.("auto");
78
+ return auto;
79
+ }
80
+ // The sandbox is back on only once the auto-mode commands are gone: a failed kill keeps the
81
+ // state (and the watch), so the next sync tries again. Routing follows the policy meanwhile.
82
+ try {
83
+ await this.host.killAll();
84
+ }
85
+ catch {
86
+ return auto;
87
+ }
88
+ // The policy may have changed again while the kill ran: the next sync judges that.
89
+ if (!this.auto || this.policy().mode === "auto")
90
+ return auto;
91
+ this.auto = false;
92
+ if (this.watch !== undefined)
93
+ clearInterval(this.watch);
94
+ this.watch = undefined;
95
+ this.onSwitch?.("sandbox");
96
+ return auto;
97
+ }
98
+ /**
99
+ * Records an exec's limits, refused ones included, so file operations follow the latest
100
+ * decision (see {@link FILE_OPS_DECISION_TTL_MS}).
101
+ */
102
+ noteLimits(limits) {
103
+ this.lastLimits = { mode: limits.mode };
104
+ this.lastLimitsAt = Date.now();
105
+ }
106
+ /**
107
+ * The executor for file operations now. File operations carry no limits and never pass command
108
+ * review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
109
+ * any exec and once those limits are stale (the safe default for an organization whose ceiling
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.
114
+ */
115
+ async files() {
116
+ const policy = this.policy();
117
+ await this.sync(policy);
118
+ if (policy.mode === "sandbox")
119
+ return this.sandboxed;
120
+ if (this.lastLimits === undefined ||
121
+ Date.now() - this.lastLimitsAt > FILE_OPS_DECISION_TTL_MS) {
122
+ if (!this.sandboxReady)
123
+ throw new DeviceOpError("policy", NO_FRESH_DECISION);
124
+ return this.sandboxed;
125
+ }
126
+ return this.lastLimits.mode === "sandbox" ? this.sandboxed : this.host;
127
+ }
128
+ async exec(args, signal) {
129
+ signal.throwIfAborted();
130
+ const policy = this.policy();
131
+ return this.execDecided(args, signal, { mode: effectiveMode(policy, args.limits) }, policy);
132
+ }
133
+ /**
134
+ * Runs one command as `how` decided (the caller logs the same decision). The policy it was
135
+ * decided on is synced first, so a sandbox turned back on stops the auto-mode commands. An
136
+ * auto-mode command is decided again on the policy then, right before its spawn: one whose
137
+ * sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
138
+ */
139
+ async execDecided(args, signal, how, policy = this.policy()) {
140
+ signal.throwIfAborted();
141
+ this.noteLimits(args.limits);
142
+ await this.sync(policy);
143
+ if (how.mode !== "auto")
144
+ return this.sandboxed.exec(args, signal);
145
+ const beforeSpawn = () => {
146
+ if (this.policy().mode === "sandbox")
147
+ throw new DeviceOpError("policy", SANDBOX_BACK_ON);
148
+ };
149
+ return this.host.exec(args, signal, { beforeSpawn });
150
+ }
151
+ async readFile(path, maxBytes) {
152
+ return (await this.files()).readFile(path, maxBytes);
153
+ }
154
+ async writeFile(path, data) {
155
+ return (await this.files()).writeFile(path, data);
156
+ }
157
+ async stat(path) {
158
+ return (await this.files()).stat(path);
159
+ }
160
+ async killTagged(tags) {
161
+ await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
162
+ }
163
+ async killAll() {
164
+ await Promise.all([this.sandboxed.killAll(), this.host.killAll()]);
165
+ }
166
+ ensureRoot() {
167
+ return this.sandboxed.ensureRoot();
168
+ }
169
+ /** Stops watching the policy. */
170
+ dispose() {
171
+ if (this.watch !== undefined)
172
+ clearInterval(this.watch);
173
+ this.watch = undefined;
174
+ }
175
+ }
@@ -1,13 +1,27 @@
1
1
  import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- /** What runs the operations on this machine: the OS sandbox (os) or a container (docker). */
2
+ import type { Policy, SandboxMode } from "../state.js";
3
+ /** How one command runs: in auto mode (no OS sandbox) or in the sandbox. */
4
+ export interface ExecMode {
5
+ mode: SandboxMode;
6
+ }
7
+ /** Hooks of one command. */
8
+ export interface ExecHooks {
9
+ /**
10
+ * Called synchronously right before the command is spawned, after everything the executor
11
+ * awaits; throwing refuses the command (nothing is spawned) with that error.
12
+ */
13
+ beforeSpawn?: () => void;
14
+ }
15
+ /** What runs the operations on this machine: the OS sandbox / host (os) or a container (docker). */
3
16
  export interface Executor {
4
17
  readonly mode: "os" | "docker";
5
18
  readonly roots: SandboxRoots;
6
19
  /**
7
20
  * Runs one command; `signal` aborting kills its whole process tree. An executor must not start
8
- * work on an already-aborted signal (the kernel cancelled the request).
21
+ * work on an already-aborted signal (the kernel cancelled the request). `hooks` are honoured by
22
+ * the executor that runs commands without a sandbox; others may ignore them.
9
23
  */
10
- exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
24
+ exec(args: DeviceExecArgs, signal: AbortSignal, hooks?: ExecHooks): Promise<ExecResult>;
11
25
  /** The file's bytes (at most `maxBytes`); null when it does not exist. */
12
26
  readFile(path: string, maxBytes: number): Promise<{
13
27
  data: Uint8Array;
@@ -22,10 +36,20 @@ export interface Executor {
22
36
  killTagged(tags: string[]): Promise<void>;
23
37
  killAll(): Promise<void>;
24
38
  /**
25
- * Creates the environment directory (and its marker file) on first use. "gone" when it existed
39
+ * Creates the device directory (and its marker file) on first use. "gone" when it existed
26
40
  * before and has vanished; it is never recreated silently.
27
41
  */
28
42
  ensureRoot(): Promise<"ok" | "gone">;
43
+ /**
44
+ * OS mode, an executor that can run without a sandbox: records an exec's limits, also of one
45
+ * the policy sent to the sandbox, so file operations follow the latest decision.
46
+ */
47
+ noteLimits?(limits: DeviceExecArgs["limits"]): void;
48
+ /**
49
+ * OS mode, an executor that can run without a sandbox: runs one command as `how` (decided by
50
+ * the caller on `policy`, and logged by it) says, instead of deciding again in {@link exec}.
51
+ */
52
+ execDecided?(args: DeviceExecArgs, signal: AbortSignal, how: ExecMode, policy: Policy): Promise<ExecResult>;
29
53
  }
30
54
  /** An executor failure with a protocol error kind (default `error`). */
31
55
  export declare class DeviceOpError extends Error {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { type Command, parseCommandLine } from "./args.js";
2
2
  export { runCli } from "./cli.js";
3
- export { type Credential, type Policy, stateDir } from "./state.js";
3
+ export { type Credential, type Policy, type SandboxMode, stateDir } from "./state.js";
@@ -0,0 +1,45 @@
1
+ import { type SandboxLimits } from "@capybara-hq/plugin-sdk";
2
+ import type { Policy } from "./state.js";
3
+ /** What refused a host (spec §9.2). */
4
+ export type BlockedLayer = "device" | "org" | "address" | "unknown";
5
+ export interface BlockedHost {
6
+ host: string;
7
+ port: number;
8
+ layer: BlockedLayer;
9
+ }
10
+ /** At most this many blocked hosts are reported per command. */
11
+ export declare const MAX_BLOCKED_HOSTS = 20;
12
+ type Limits = Pick<SandboxLimits, "mode" | "network">;
13
+ /** The local policy fields that decide sandbox-mode network access. */
14
+ type NetworkPolicy = Pick<Policy, "allowedDomains">;
15
+ /**
16
+ * Parses one sandbox-runtime 0.0.81 violation line `deny network-outbound <host>:<port> (<reason>)`;
17
+ * undefined for other lines. IPv6 hosts arrive bracketed and are returned without the brackets.
18
+ */
19
+ export declare function parseNetworkViolation(line: string): {
20
+ host: string;
21
+ port: number;
22
+ reason: string;
23
+ } | undefined;
24
+ /**
25
+ * Whether `host` is a public DNS name a command may reach when nothing narrows it (device and org
26
+ * both open): never an IP literal, a single-label or internal name, or a wildcard.
27
+ */
28
+ export declare function isPublicName(host: string): boolean;
29
+ /**
30
+ * The layer that refused `host`: `address` (an IP literal, a name `validateAllowHost` refuses, or
31
+ * a resolved-address reason), `org` (not in the kernel's allowlist; also when the device lacks it
32
+ * too), `device` (the kernel allows it, the local policy does not), else `unknown`.
33
+ */
34
+ export declare function classifyHost(host: string, reason: string, limits: Limits, policy: NetworkPolicy): BlockedLayer;
35
+ /** The refused hosts in `lines`, deduped by host (first port kept), at most {@link MAX_BLOCKED_HOSTS}. */
36
+ export declare function blockedHosts(lines: readonly string[], limits: Limits, policy: NetworkPolicy): BlockedHost[];
37
+ /** The stderr trailer of spec §9.2 (English, model-visible); "" for an empty list. */
38
+ export declare function networkTrailer(blocked: readonly BlockedHost[]): string;
39
+ /**
40
+ * The reason the sandbox's ask callback answers (spec §9.1). The callback has no command id, so
41
+ * `limits` are the last ones seen (a device belongs to one org); without any, the org layer is
42
+ * not judged.
43
+ */
44
+ export declare function denyReason(host: string, limits: Limits | undefined, policy: NetworkPolicy): string;
45
+ export {};