@capybara-hq/device 0.1.0-rc.1 → 0.1.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +187 -44
- package/dist/api.d.ts +6 -1
- package/dist/args.d.ts +14 -3
- package/dist/args.js +74 -10
- package/dist/cli.d.ts +14 -2
- package/dist/cli.js +59 -10
- package/dist/client.d.ts +14 -3
- package/dist/client.js +92 -18
- package/dist/command-log.d.ts +8 -0
- package/dist/commands/drain.d.ts +13 -0
- package/dist/commands/drain.js +28 -0
- package/dist/commands/login.js +68 -11
- package/dist/commands/mode.d.ts +52 -0
- package/dist/commands/mode.js +108 -0
- package/dist/commands/policy.d.ts +13 -4
- package/dist/commands/policy.js +162 -33
- package/dist/commands/service.d.ts +18 -3
- package/dist/commands/service.js +175 -9
- package/dist/commands/start.d.ts +14 -3
- package/dist/commands/start.js +37 -5
- package/dist/commands/status.js +12 -4
- package/dist/commands/stop.d.ts +9 -2
- package/dist/commands/stop.js +13 -2
- package/dist/exec/docker.d.ts +41 -13
- package/dist/exec/docker.js +123 -57
- package/dist/exec/fs-helper.d.ts +13 -8
- package/dist/exec/fs-helper.js +31 -13
- package/dist/exec/groups.d.ts +42 -0
- package/dist/exec/groups.js +100 -0
- package/dist/exec/host.d.ts +53 -0
- package/dist/exec/host.js +183 -0
- package/dist/exec/os.d.ts +85 -15
- package/dist/exec/os.js +208 -36
- package/dist/exec/reap.d.ts +41 -0
- package/dist/exec/reap.js +89 -0
- package/dist/exec/sandbox-messages.d.ts +14 -0
- package/dist/exec/sandbox-messages.js +21 -0
- package/dist/exec/shared.d.ts +42 -13
- package/dist/exec/shared.js +94 -16
- package/dist/exec/switch.d.ts +91 -0
- package/dist/exec/switch.js +164 -0
- package/dist/exec/types.d.ts +28 -4
- package/dist/index.d.ts +1 -1
- package/dist/network.d.ts +45 -0
- package/dist/network.js +154 -0
- package/dist/pid.d.ts +13 -1
- package/dist/pid.js +54 -7
- package/dist/policy-ops.d.ts +47 -0
- package/dist/policy-ops.js +90 -0
- package/dist/policy-store.d.ts +43 -0
- package/dist/policy-store.js +94 -0
- package/dist/policy.d.ts +36 -16
- package/dist/policy.js +77 -19
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +46 -7
- package/dist/server-ops.js +285 -29
- package/dist/service/installed.d.ts +5 -0
- package/dist/service/installed.js +14 -0
- package/dist/service/launchd.d.ts +11 -1
- package/dist/service/launchd.js +14 -5
- package/dist/state.d.ts +50 -6
- package/dist/state.js +195 -16
- package/package.json +3 -3
package/dist/exec/shared.d.ts
CHANGED
|
@@ -1,12 +1,29 @@
|
|
|
1
|
-
import type
|
|
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
|
|
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
|
|
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)
|
|
32
|
-
* calls it, so logging in again after the files were lost starts the
|
|
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
|
|
51
|
+
export declare function prepareDeviceDir(dir: string): void;
|
|
35
52
|
/**
|
|
36
|
-
* The
|
|
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
|
|
49
|
-
*
|
|
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
|
-
|
|
54
|
-
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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;
|
package/dist/exec/shared.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
129
|
+
const MARKER_TEXT = "This directory is a capybara-device directory.\n";
|
|
73
130
|
/**
|
|
74
|
-
* Creates (or completes)
|
|
75
|
-
* calls it, so logging in again after the files were lost starts the
|
|
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
|
|
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
|
|
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
|
|
117
|
-
*
|
|
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
|
-
|
|
180
|
+
mode;
|
|
181
|
+
constructor(roots, mode) {
|
|
122
182
|
this.roots = roots;
|
|
183
|
+
this.mode = mode;
|
|
123
184
|
}
|
|
124
|
-
/**
|
|
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
|
|
200
|
+
throw policyError(`${path} is outside the device's roots (${this.rootList().join(", ")})`);
|
|
131
201
|
}
|
|
132
202
|
return p;
|
|
133
203
|
}
|
|
134
|
-
/**
|
|
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
|
-
/**
|
|
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
|
|
243
|
+
throw policyError(`${path} resolves to ${real}, outside the device's roots`);
|
|
166
244
|
}
|
|
167
245
|
return real;
|
|
168
246
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
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 OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
|
|
18
|
+
* directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
|
|
19
|
+
* applies at the next command. File operations use the host executor's direct IO (any absolute
|
|
20
|
+
* path in auto mode, the roots in the sandbox) only while the latest command's decision is fresh;
|
|
21
|
+
* before any command, or once its limits are stale, the sandboxed helper runs (file operations
|
|
22
|
+
* never pass command review, so the org's ceiling may not be exceeded). When the policy turns the
|
|
23
|
+
* sandbox back on, every auto-mode command still running (and what it left in the background) is
|
|
24
|
+
* killed, and one still starting is refused right before its spawn; while auto mode is on, the
|
|
25
|
+
* policy is also checked every second so that happens without waiting for the next operation.
|
|
26
|
+
* Kills reach both executors' commands.
|
|
27
|
+
*/
|
|
28
|
+
export declare class SwitchingExecutor implements Executor {
|
|
29
|
+
private readonly sandboxed;
|
|
30
|
+
/** Runs commands without a sandbox (the `HostExecutor`). */
|
|
31
|
+
private readonly host;
|
|
32
|
+
private readonly policy;
|
|
33
|
+
private readonly onSwitch?;
|
|
34
|
+
readonly mode: "os";
|
|
35
|
+
readonly roots: SandboxRoots;
|
|
36
|
+
/** The policy said auto mode when last checked. */
|
|
37
|
+
private auto;
|
|
38
|
+
/**
|
|
39
|
+
* Whether the OS sandbox can run here. When it cannot, sandbox-mode operations go to the
|
|
40
|
+
* sandboxed executor and are refused there with the reason; auto mode keeps working.
|
|
41
|
+
*/
|
|
42
|
+
private readonly sandboxReady;
|
|
43
|
+
private watch;
|
|
44
|
+
/** The latest command's limits and when they came (file operations follow their decision). */
|
|
45
|
+
private lastLimits;
|
|
46
|
+
private lastLimitsAt;
|
|
47
|
+
constructor(sandboxed: Executor,
|
|
48
|
+
/** Runs commands without a sandbox (the `HostExecutor`). */
|
|
49
|
+
host: Executor, policy: () => Policy, onSwitch?: ((mode: "auto" | "sandbox") => void) | undefined);
|
|
50
|
+
/**
|
|
51
|
+
* Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills the
|
|
52
|
+
* auto-mode commands. Returns whether the policy says auto mode now.
|
|
53
|
+
*/
|
|
54
|
+
sync(policy?: Policy): Promise<boolean>;
|
|
55
|
+
/**
|
|
56
|
+
* Records an exec's limits, refused ones included, so file operations follow the latest
|
|
57
|
+
* decision (see {@link FILE_OPS_DECISION_TTL_MS}).
|
|
58
|
+
*/
|
|
59
|
+
noteLimits(limits: Pick<SandboxLimits, "mode">): void;
|
|
60
|
+
/**
|
|
61
|
+
* The executor for file operations now. File operations carry no limits and never pass command
|
|
62
|
+
* review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
|
|
63
|
+
* 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).
|
|
67
|
+
*/
|
|
68
|
+
private files;
|
|
69
|
+
exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
|
|
70
|
+
/**
|
|
71
|
+
* Runs one command as `how` decided (the caller logs the same decision). The policy it was
|
|
72
|
+
* decided on is synced first, so a sandbox turned back on stops the auto-mode commands. An
|
|
73
|
+
* auto-mode command is decided again on the policy then, right before its spawn: one whose
|
|
74
|
+
* sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
|
|
75
|
+
*/
|
|
76
|
+
execDecided(args: DeviceExecArgs, signal: AbortSignal, how: ExecMode, policy?: Policy): Promise<ExecResult>;
|
|
77
|
+
readFile(path: string, maxBytes: number): Promise<{
|
|
78
|
+
data: Uint8Array;
|
|
79
|
+
truncated: boolean;
|
|
80
|
+
} | null>;
|
|
81
|
+
writeFile(path: string, data: Uint8Array): Promise<void>;
|
|
82
|
+
stat(path: string): Promise<{
|
|
83
|
+
size: number;
|
|
84
|
+
isDir: boolean;
|
|
85
|
+
} | null>;
|
|
86
|
+
killTagged(tags: string[]): Promise<void>;
|
|
87
|
+
killAll(): Promise<void>;
|
|
88
|
+
ensureRoot(): Promise<"ok" | "gone">;
|
|
89
|
+
/** Stops watching the policy. */
|
|
90
|
+
dispose(): void;
|
|
91
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
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 OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
|
|
19
|
+
* directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
|
|
20
|
+
* applies at the next command. File operations use the host executor's direct IO (any absolute
|
|
21
|
+
* path in auto mode, the roots in the sandbox) only while the latest command's decision is fresh;
|
|
22
|
+
* before any command, or once its limits are stale, the sandboxed helper runs (file operations
|
|
23
|
+
* never pass command review, so the org's ceiling may not be exceeded). When the policy turns the
|
|
24
|
+
* sandbox back on, every auto-mode command still running (and what it left in the background) is
|
|
25
|
+
* killed, and one still starting is refused right before its spawn; while auto mode is on, the
|
|
26
|
+
* policy is also checked every second so that happens without waiting for the next operation.
|
|
27
|
+
* Kills reach both executors' commands.
|
|
28
|
+
*/
|
|
29
|
+
export class SwitchingExecutor {
|
|
30
|
+
sandboxed;
|
|
31
|
+
host;
|
|
32
|
+
policy;
|
|
33
|
+
onSwitch;
|
|
34
|
+
mode = "os";
|
|
35
|
+
roots;
|
|
36
|
+
/** The policy said auto mode when last checked. */
|
|
37
|
+
auto = false;
|
|
38
|
+
/**
|
|
39
|
+
* Whether the OS sandbox can run here. When it cannot, sandbox-mode operations go to the
|
|
40
|
+
* sandboxed executor and are refused there with the reason; auto mode keeps working.
|
|
41
|
+
*/
|
|
42
|
+
sandboxReady;
|
|
43
|
+
watch;
|
|
44
|
+
/** The latest command's limits and when they came (file operations follow their decision). */
|
|
45
|
+
lastLimits;
|
|
46
|
+
lastLimitsAt = 0;
|
|
47
|
+
constructor(sandboxed,
|
|
48
|
+
/** Runs commands without a sandbox (the `HostExecutor`). */
|
|
49
|
+
host, policy, onSwitch) {
|
|
50
|
+
this.sandboxed = sandboxed;
|
|
51
|
+
this.host = host;
|
|
52
|
+
this.policy = policy;
|
|
53
|
+
this.onSwitch = onSwitch;
|
|
54
|
+
this.roots = sandboxed.roots;
|
|
55
|
+
this.sandboxReady = sandboxed.available !== false;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills the
|
|
59
|
+
* auto-mode commands. Returns whether the policy says auto mode now.
|
|
60
|
+
*/
|
|
61
|
+
async sync(policy = this.policy()) {
|
|
62
|
+
const auto = policy.mode === "auto";
|
|
63
|
+
if (auto === this.auto)
|
|
64
|
+
return auto;
|
|
65
|
+
if (auto) {
|
|
66
|
+
this.auto = true;
|
|
67
|
+
this.watch ??= setInterval(() => void this.sync().catch(() => { }), WATCH_INTERVAL_MS);
|
|
68
|
+
this.watch.unref();
|
|
69
|
+
this.onSwitch?.("auto");
|
|
70
|
+
return auto;
|
|
71
|
+
}
|
|
72
|
+
// The sandbox is back on only once the auto-mode commands are gone: a failed kill keeps the
|
|
73
|
+
// state (and the watch), so the next sync tries again. Routing follows the policy meanwhile.
|
|
74
|
+
try {
|
|
75
|
+
await this.host.killAll();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return auto;
|
|
79
|
+
}
|
|
80
|
+
// The policy may have changed again while the kill ran: the next sync judges that.
|
|
81
|
+
if (!this.auto || this.policy().mode === "auto")
|
|
82
|
+
return auto;
|
|
83
|
+
this.auto = false;
|
|
84
|
+
if (this.watch !== undefined)
|
|
85
|
+
clearInterval(this.watch);
|
|
86
|
+
this.watch = undefined;
|
|
87
|
+
this.onSwitch?.("sandbox");
|
|
88
|
+
return auto;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Records an exec's limits, refused ones included, so file operations follow the latest
|
|
92
|
+
* decision (see {@link FILE_OPS_DECISION_TTL_MS}).
|
|
93
|
+
*/
|
|
94
|
+
noteLimits(limits) {
|
|
95
|
+
this.lastLimits = { mode: limits.mode };
|
|
96
|
+
this.lastLimitsAt = Date.now();
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The executor for file operations now. File operations carry no limits and never pass command
|
|
100
|
+
* review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
|
|
101
|
+
* 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).
|
|
105
|
+
*/
|
|
106
|
+
async files() {
|
|
107
|
+
const policy = this.policy();
|
|
108
|
+
await this.sync(policy);
|
|
109
|
+
if (policy.mode === "sandbox")
|
|
110
|
+
return this.sandboxed;
|
|
111
|
+
if (this.lastLimits === undefined ||
|
|
112
|
+
Date.now() - this.lastLimitsAt > FILE_OPS_DECISION_TTL_MS) {
|
|
113
|
+
return this.sandboxReady ? this.sandboxed : this.host;
|
|
114
|
+
}
|
|
115
|
+
return this.lastLimits.mode === "sandbox" ? this.sandboxed : this.host;
|
|
116
|
+
}
|
|
117
|
+
async exec(args, signal) {
|
|
118
|
+
signal.throwIfAborted();
|
|
119
|
+
const policy = this.policy();
|
|
120
|
+
return this.execDecided(args, signal, { mode: effectiveMode(policy, args.limits) }, policy);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Runs one command as `how` decided (the caller logs the same decision). The policy it was
|
|
124
|
+
* decided on is synced first, so a sandbox turned back on stops the auto-mode commands. An
|
|
125
|
+
* auto-mode command is decided again on the policy then, right before its spawn: one whose
|
|
126
|
+
* sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
|
|
127
|
+
*/
|
|
128
|
+
async execDecided(args, signal, how, policy = this.policy()) {
|
|
129
|
+
signal.throwIfAborted();
|
|
130
|
+
this.noteLimits(args.limits);
|
|
131
|
+
await this.sync(policy);
|
|
132
|
+
if (how.mode !== "auto")
|
|
133
|
+
return this.sandboxed.exec(args, signal);
|
|
134
|
+
const beforeSpawn = () => {
|
|
135
|
+
if (this.policy().mode === "sandbox")
|
|
136
|
+
throw new DeviceOpError("policy", SANDBOX_BACK_ON);
|
|
137
|
+
};
|
|
138
|
+
return this.host.exec(args, signal, { beforeSpawn });
|
|
139
|
+
}
|
|
140
|
+
async readFile(path, maxBytes) {
|
|
141
|
+
return (await this.files()).readFile(path, maxBytes);
|
|
142
|
+
}
|
|
143
|
+
async writeFile(path, data) {
|
|
144
|
+
return (await this.files()).writeFile(path, data);
|
|
145
|
+
}
|
|
146
|
+
async stat(path) {
|
|
147
|
+
return (await this.files()).stat(path);
|
|
148
|
+
}
|
|
149
|
+
async killTagged(tags) {
|
|
150
|
+
await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
|
|
151
|
+
}
|
|
152
|
+
async killAll() {
|
|
153
|
+
await Promise.all([this.sandboxed.killAll(), this.host.killAll()]);
|
|
154
|
+
}
|
|
155
|
+
ensureRoot() {
|
|
156
|
+
return this.sandboxed.ensureRoot();
|
|
157
|
+
}
|
|
158
|
+
/** Stops watching the policy. */
|
|
159
|
+
dispose() {
|
|
160
|
+
if (this.watch !== undefined)
|
|
161
|
+
clearInterval(this.watch);
|
|
162
|
+
this.watch = undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
package/dist/exec/types.d.ts
CHANGED
|
@@ -1,13 +1,27 @@
|
|
|
1
1
|
import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
|
|
2
|
-
|
|
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
|
|
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
|
@@ -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 {};
|