@capybara-hq/device 0.1.0-rc.2 → 0.1.0-rc.4
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 +201 -11
- package/dist/args.d.ts +4 -2
- package/dist/args.js +21 -5
- package/dist/cli.d.ts +12 -2
- package/dist/cli.js +60 -8
- package/dist/client.d.ts +9 -1
- package/dist/client.js +38 -14
- package/dist/command-log.d.ts +10 -0
- package/dist/commands/login.js +1 -0
- package/dist/commands/policy.d.ts +66 -3
- package/dist/commands/policy.js +347 -31
- package/dist/commands/start.d.ts +9 -3
- package/dist/commands/start.js +18 -3
- package/dist/exec/docker.d.ts +41 -5
- package/dist/exec/docker.js +73 -19
- 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 +73 -5
- package/dist/exec/os.js +186 -14
- package/dist/exec/shared.d.ts +28 -0
- package/dist/exec/shared.js +154 -1
- package/dist/exec/switch.d.ts +108 -0
- package/dist/exec/switch.js +214 -0
- package/dist/exec/types.d.ts +37 -3
- package/dist/network.d.ts +45 -0
- package/dist/network.js +161 -0
- package/dist/policy-store.d.ts +38 -0
- package/dist/policy-store.js +92 -0
- package/dist/policy.d.ts +102 -11
- package/dist/policy.js +155 -20
- package/dist/proxy-guard.d.ts +58 -0
- package/dist/proxy-guard.js +137 -0
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +65 -7
- package/dist/server-ops.js +289 -29
- package/dist/state.d.ts +44 -1
- package/dist/state.js +177 -9
- package/package.json +2 -2
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { UNSANDBOXED_NOT_ALLOWED_MESSAGE, } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { deviceTier } from "../policy.js";
|
|
3
|
+
import { DeviceOpError } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Whether the local policy itself asks for no sandbox: `isolation: "none"` with the owner's own
|
|
6
|
+
* tier set to `open` on this machine. A tier the deployment supplies (the org's default) never
|
|
7
|
+
* counts, so the kernel can never be the last step that makes commands run unsandboxed.
|
|
8
|
+
*/
|
|
9
|
+
export function policyUnsandboxed(policy) {
|
|
10
|
+
return policy.isolation === "none" && policy.tier === "open";
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Decides how one command runs (spec §5.4). Without a sandbox only when the local policy says
|
|
14
|
+
* `isolation: "none"` with its own tier `open` ({@link policyUnsandboxed}), the device runs in OS
|
|
15
|
+
* mode, the kernel allows it for this command (`limits.allowUnsandboxed`: the platform and the
|
|
16
|
+
* org allow it and an unattended run has its grant; absent counts as not allowed), and the
|
|
17
|
+
* command's tier (that choice cut to the org's ceiling) is `open`. When the policy says `none`
|
|
18
|
+
* but any of those does not hold, the command is refused, never run in the sandbox silently: the
|
|
19
|
+
* owner asked for no sandbox. The device enforces the kernel's decision itself, because the
|
|
20
|
+
* kernel knows the local policy only from the last hello or policy op (spec §4.3); its refusal is
|
|
21
|
+
* {@link UNSANDBOXED_NOT_ALLOWED_MESSAGE}, which the kernel maps to its own error. Docker mode
|
|
22
|
+
* ignores `isolation` (its container is the isolation).
|
|
23
|
+
*/
|
|
24
|
+
export function execIsolation(policy, limits, mode) {
|
|
25
|
+
const tier = deviceTier(policy, limits);
|
|
26
|
+
if (mode !== "os" || policy.isolation !== "none")
|
|
27
|
+
return { tier, isolation: "sandbox" };
|
|
28
|
+
if (policy.tier !== "open") {
|
|
29
|
+
return { tier, isolation: "none", refusal: unsandboxedRefusal(policy, tier) };
|
|
30
|
+
}
|
|
31
|
+
if (limits.allowUnsandboxed !== true) {
|
|
32
|
+
return { tier, isolation: "none", refusal: UNSANDBOXED_NOT_ALLOWED_MESSAGE };
|
|
33
|
+
}
|
|
34
|
+
if (tier === "open")
|
|
35
|
+
return { tier, isolation: "none" };
|
|
36
|
+
return { tier, isolation: "none", refusal: unsandboxedRefusal(policy, tier) };
|
|
37
|
+
}
|
|
38
|
+
/** The refusal of a command the policy asks to run without a sandbox below tier `open`. */
|
|
39
|
+
export function unsandboxedRefusal(policy, tier) {
|
|
40
|
+
if (policy.tier !== "open") {
|
|
41
|
+
const own = policy.tier === undefined
|
|
42
|
+
? "its tier is not set on this machine (it follows the organization's default)"
|
|
43
|
+
: `its tier is ${policy.tier}`;
|
|
44
|
+
return (`This device is set to run commands without a sandbox, but ${own}; running without a ` +
|
|
45
|
+
"sandbox needs tier open set on this machine. Run capybara-device policy set tier open, " +
|
|
46
|
+
"or turn the sandbox back on with capybara-device policy set isolation sandbox.");
|
|
47
|
+
}
|
|
48
|
+
return ("This device is set to run commands without a sandbox, but the organization allows at most " +
|
|
49
|
+
`the ${tier} tier, and running without a sandbox needs tier open. The device's owner can ` +
|
|
50
|
+
"turn the sandbox back on with capybara-device policy set isolation sandbox.");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* How long the latest command's limits decide file operations. The kernel judges the org's
|
|
54
|
+
* settings at each exec, and file operations carry no limits, so an unsandboxed decision older
|
|
55
|
+
* than this no longer counts: file operations fall back to the sandboxed helper, which reads and
|
|
56
|
+
* writes the same roots (only slower), until the next command decides again. A minute covers a
|
|
57
|
+
* turn's file operations around its commands while bounding how long an org's change (or a lower
|
|
58
|
+
* ceiling) takes to reach a device that runs no more commands.
|
|
59
|
+
*/
|
|
60
|
+
export const FILE_OPS_DECISION_TTL_MS = 60_000;
|
|
61
|
+
/** How often the switching executor rereads the policy while it runs commands unsandboxed. */
|
|
62
|
+
const WATCH_INTERVAL_MS = 1000;
|
|
63
|
+
/** The refusal of an unsandboxed command whose sandbox was turned back on before it started. */
|
|
64
|
+
export const SANDBOX_BACK_ON = "The sandbox was turned back on on this machine while the command was starting, so it did " +
|
|
65
|
+
"not run. Run it again: it runs in the sandbox now.";
|
|
66
|
+
/**
|
|
67
|
+
* The OS-mode executor the program serves: each command runs in the OS sandbox or, when
|
|
68
|
+
* {@link execIsolation} says so, without one; the policy is read per operation, so a change
|
|
69
|
+
* applies at once. File operations use the host executor's direct IO (still confined to the
|
|
70
|
+
* roots) when the same decision, on the policy now and the latest command's limits, says no
|
|
71
|
+
* sandbox; otherwise (and before any command) the sandboxed helper. When the policy turns the
|
|
72
|
+
* sandbox back on, every command still running without one (and what it left in the background)
|
|
73
|
+
* is killed, and one still starting is refused right before its spawn; while unsandboxed, the
|
|
74
|
+
* policy is also checked every second so that happens without waiting for the next operation.
|
|
75
|
+
* Kills reach both executors' commands.
|
|
76
|
+
*/
|
|
77
|
+
export class SwitchingExecutor {
|
|
78
|
+
sandboxed;
|
|
79
|
+
host;
|
|
80
|
+
policy;
|
|
81
|
+
onSwitch;
|
|
82
|
+
mode = "os";
|
|
83
|
+
roots;
|
|
84
|
+
/** The policy asked for no sandbox when last checked. */
|
|
85
|
+
unsandboxed = false;
|
|
86
|
+
watch;
|
|
87
|
+
/** The latest command's limits and when they came (file operations follow their decision). */
|
|
88
|
+
lastLimits;
|
|
89
|
+
lastLimitsAt = 0;
|
|
90
|
+
constructor(sandboxed,
|
|
91
|
+
/** Runs commands without a sandbox (the `HostExecutor`). */
|
|
92
|
+
host, policy, onSwitch) {
|
|
93
|
+
this.sandboxed = sandboxed;
|
|
94
|
+
this.host = host;
|
|
95
|
+
this.policy = policy;
|
|
96
|
+
this.onSwitch = onSwitch;
|
|
97
|
+
this.roots = sandboxed.roots;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Rereads the policy; on a change fires `onSwitch` and, when the sandbox came back on, kills
|
|
101
|
+
* the unsandboxed commands. Returns whether the policy asks for no sandbox now.
|
|
102
|
+
*/
|
|
103
|
+
async sync(policy = this.policy()) {
|
|
104
|
+
const none = policyUnsandboxed(policy);
|
|
105
|
+
if (none === this.unsandboxed)
|
|
106
|
+
return none;
|
|
107
|
+
if (none) {
|
|
108
|
+
this.unsandboxed = true;
|
|
109
|
+
this.watch ??= setInterval(() => void this.sync().catch(() => { }), WATCH_INTERVAL_MS);
|
|
110
|
+
this.watch.unref();
|
|
111
|
+
this.onSwitch?.("none");
|
|
112
|
+
return none;
|
|
113
|
+
}
|
|
114
|
+
// Back in the sandbox only once the unsandboxed commands are gone: a failed kill keeps the
|
|
115
|
+
// state (and the watch), so the next sync tries again. Routing follows the policy meanwhile.
|
|
116
|
+
try {
|
|
117
|
+
await this.host.killAll();
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return none;
|
|
121
|
+
}
|
|
122
|
+
// The policy may have changed again while the kill ran: the next sync judges that.
|
|
123
|
+
if (!this.unsandboxed || policyUnsandboxed(this.policy()))
|
|
124
|
+
return none;
|
|
125
|
+
this.unsandboxed = false;
|
|
126
|
+
if (this.watch !== undefined)
|
|
127
|
+
clearInterval(this.watch);
|
|
128
|
+
this.watch = undefined;
|
|
129
|
+
this.onSwitch?.("sandbox");
|
|
130
|
+
return none;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Records an exec's limits, refused ones included, so file operations follow the latest
|
|
134
|
+
* decision (see {@link FILE_OPS_DECISION_TTL_MS}).
|
|
135
|
+
*/
|
|
136
|
+
noteLimits(limits) {
|
|
137
|
+
const { tier, defaultTier, allowUnsandboxed } = limits;
|
|
138
|
+
this.lastLimits = {
|
|
139
|
+
tier,
|
|
140
|
+
...(defaultTier !== undefined && { defaultTier }),
|
|
141
|
+
...(allowUnsandboxed !== undefined && { allowUnsandboxed }),
|
|
142
|
+
};
|
|
143
|
+
this.lastLimitsAt = Date.now();
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The executor for file operations now: the commands' decision on the policy now and the latest
|
|
147
|
+
* exec's limits; the sandboxed helper before any exec or once those limits are stale.
|
|
148
|
+
*/
|
|
149
|
+
async files() {
|
|
150
|
+
const policy = this.policy();
|
|
151
|
+
await this.sync(policy);
|
|
152
|
+
if (this.lastLimits === undefined)
|
|
153
|
+
return this.sandboxed;
|
|
154
|
+
if (Date.now() - this.lastLimitsAt > FILE_OPS_DECISION_TTL_MS)
|
|
155
|
+
return this.sandboxed;
|
|
156
|
+
const how = execIsolation(policy, this.lastLimits, "os");
|
|
157
|
+
return how.isolation === "none" && how.refusal === undefined ? this.host : this.sandboxed;
|
|
158
|
+
}
|
|
159
|
+
async exec(args, signal) {
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
const policy = this.policy();
|
|
162
|
+
return this.execDecided(args, signal, execIsolation(policy, args.limits, "os"), policy);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Runs one command as `how` decided (the caller logs the same decision). The policy it was
|
|
166
|
+
* decided on is synced first, so a sandbox turned back on stops the unsandboxed commands. An
|
|
167
|
+
* unsandboxed command is decided again on the policy then, right before its spawn: one whose
|
|
168
|
+
* sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
|
|
169
|
+
*/
|
|
170
|
+
async execDecided(args, signal, how, policy = this.policy()) {
|
|
171
|
+
signal.throwIfAborted();
|
|
172
|
+
this.noteLimits(args.limits);
|
|
173
|
+
await this.sync(policy);
|
|
174
|
+
if (how.refusal !== undefined)
|
|
175
|
+
throw new DeviceOpError("policy", how.refusal);
|
|
176
|
+
if (how.isolation !== "none")
|
|
177
|
+
return this.sandboxed.exec(args, signal);
|
|
178
|
+
const beforeSpawn = () => {
|
|
179
|
+
const now = execIsolation(this.policy(), args.limits, "os");
|
|
180
|
+
if (now.isolation !== "none" || now.refusal !== undefined) {
|
|
181
|
+
throw new DeviceOpError("policy", SANDBOX_BACK_ON);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
return this.host.exec(args, signal, { beforeSpawn });
|
|
185
|
+
}
|
|
186
|
+
async readFile(path, maxBytes) {
|
|
187
|
+
return (await this.files()).readFile(path, maxBytes);
|
|
188
|
+
}
|
|
189
|
+
async writeFile(path, data) {
|
|
190
|
+
return (await this.files()).writeFile(path, data);
|
|
191
|
+
}
|
|
192
|
+
async stat(path) {
|
|
193
|
+
return (await this.files()).stat(path);
|
|
194
|
+
}
|
|
195
|
+
async killTagged(tags) {
|
|
196
|
+
await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
|
|
197
|
+
}
|
|
198
|
+
async killAll() {
|
|
199
|
+
await Promise.all([this.sandboxed.killAll(), this.host.killAll()]);
|
|
200
|
+
}
|
|
201
|
+
ensureRoot() {
|
|
202
|
+
return this.sandboxed.ensureRoot();
|
|
203
|
+
}
|
|
204
|
+
/** The sandboxed executor's latest localhost proxy guard result (see `Executor`). */
|
|
205
|
+
proxyGuard() {
|
|
206
|
+
return this.sandboxed.proxyGuard?.() ?? { detected: false, reasons: [] };
|
|
207
|
+
}
|
|
208
|
+
/** Stops watching the policy. */
|
|
209
|
+
dispose() {
|
|
210
|
+
if (this.watch !== undefined)
|
|
211
|
+
clearInterval(this.watch);
|
|
212
|
+
this.watch = undefined;
|
|
213
|
+
}
|
|
214
|
+
}
|
package/dist/exec/types.d.ts
CHANGED
|
@@ -1,13 +1,32 @@
|
|
|
1
|
-
import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots, SandboxTier } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { ProxyGuardResult } from "../proxy-guard.js";
|
|
3
|
+
import type { Policy } from "../state.js";
|
|
4
|
+
/** How one command runs: its tier and whether it runs in the sandbox (see `exec/switch.ts`). */
|
|
5
|
+
export interface ExecIsolation {
|
|
6
|
+
tier: SandboxTier;
|
|
7
|
+
/** `none`: without a sandbox. */
|
|
8
|
+
isolation: "sandbox" | "none";
|
|
9
|
+
/** Set when the policy asks for no sandbox but the tiers do not allow it: the command is refused. */
|
|
10
|
+
refusal?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Hooks of one command. */
|
|
13
|
+
export interface ExecHooks {
|
|
14
|
+
/**
|
|
15
|
+
* Called synchronously right before the command is spawned, after everything the executor
|
|
16
|
+
* awaits; throwing refuses the command (nothing is spawned) with that error.
|
|
17
|
+
*/
|
|
18
|
+
beforeSpawn?: () => void;
|
|
19
|
+
}
|
|
2
20
|
/** What runs the operations on this machine: the OS sandbox (os) or a container (docker). */
|
|
3
21
|
export interface Executor {
|
|
4
22
|
readonly mode: "os" | "docker";
|
|
5
23
|
readonly roots: SandboxRoots;
|
|
6
24
|
/**
|
|
7
25
|
* 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).
|
|
26
|
+
* work on an already-aborted signal (the kernel cancelled the request). `hooks` are honoured by
|
|
27
|
+
* the executor that runs commands without a sandbox; others may ignore them.
|
|
9
28
|
*/
|
|
10
|
-
exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
|
|
29
|
+
exec(args: DeviceExecArgs, signal: AbortSignal, hooks?: ExecHooks): Promise<ExecResult>;
|
|
11
30
|
/** The file's bytes (at most `maxBytes`); null when it does not exist. */
|
|
12
31
|
readFile(path: string, maxBytes: number): Promise<{
|
|
13
32
|
data: Uint8Array;
|
|
@@ -26,6 +45,21 @@ export interface Executor {
|
|
|
26
45
|
* before and has vanished; it is never recreated silently.
|
|
27
46
|
*/
|
|
28
47
|
ensureRoot(): Promise<"ok" | "gone">;
|
|
48
|
+
/**
|
|
49
|
+
* OS mode: the latest localhost proxy guard result (a local forwarding proxy turns localhost
|
|
50
|
+
* off for `dev` / `open`, spec §5.2.3). Absent: none found.
|
|
51
|
+
*/
|
|
52
|
+
proxyGuard?(): ProxyGuardResult;
|
|
53
|
+
/**
|
|
54
|
+
* OS mode, an executor that can run without a sandbox: records an exec's limits, also of one
|
|
55
|
+
* refused before it reaches the executor, so file operations follow the latest decision.
|
|
56
|
+
*/
|
|
57
|
+
noteLimits?(limits: DeviceExecArgs["limits"]): void;
|
|
58
|
+
/**
|
|
59
|
+
* OS mode, an executor that can run without a sandbox: runs one command as `how` (decided by
|
|
60
|
+
* the caller on `policy`, and logged by it) says, instead of deciding again in {@link exec}.
|
|
61
|
+
*/
|
|
62
|
+
execDecided?(args: DeviceExecArgs, signal: AbortSignal, how: ExecIsolation, policy: Policy): Promise<ExecResult>;
|
|
29
63
|
}
|
|
30
64
|
/** An executor failure with a protocol error kind (default `error`). */
|
|
31
65
|
export declare class DeviceOpError extends Error {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type EgressLimits } from "./policy.js";
|
|
2
|
+
import type { Policy } from "./state.js";
|
|
3
|
+
/** What refused a host (spec §3). */
|
|
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 = EgressLimits;
|
|
13
|
+
/** The local policy fields that decide network access. */
|
|
14
|
+
type NetworkPolicy = Pick<Policy, "allowedDomains" | "tier">;
|
|
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 org's effective egress, or egress none; also when
|
|
32
|
+
* the device lacks it too), `device` (the org 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 {};
|
package/dist/network.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
import { validateAllowHost } from "@capybara-hq/plugin-sdk";
|
|
3
|
+
import { covers, deviceHosts, deviceTier, provisionalTier } from "./policy.js";
|
|
4
|
+
/** At most this many blocked hosts are reported per command. */
|
|
5
|
+
export const MAX_BLOCKED_HOSTS = 20;
|
|
6
|
+
// The proxy's line in @anthropic-ai/sandbox-runtime 0.0.81 (`recordOutboundDeny`):
|
|
7
|
+
// `deny network-outbound <host>:<port> (<reason>)`. Pinned by test/network.test.ts.
|
|
8
|
+
const OUTBOUND_DENY = /^deny network-outbound (\S+) \((.*)\)$/;
|
|
9
|
+
/**
|
|
10
|
+
* Parses one sandbox-runtime 0.0.81 violation line `deny network-outbound <host>:<port> (<reason>)`;
|
|
11
|
+
* undefined for other lines. IPv6 hosts arrive bracketed and are returned without the brackets.
|
|
12
|
+
*/
|
|
13
|
+
export function parseNetworkViolation(line) {
|
|
14
|
+
const m = OUTBOUND_DENY.exec(line.trim());
|
|
15
|
+
if (m === null)
|
|
16
|
+
return undefined;
|
|
17
|
+
const target = m[1];
|
|
18
|
+
const reason = m[2];
|
|
19
|
+
let host;
|
|
20
|
+
let portText;
|
|
21
|
+
const bracketed = /^\[([^\]]+)\]:(\d+)$/.exec(target);
|
|
22
|
+
if (bracketed !== null) {
|
|
23
|
+
host = bracketed[1];
|
|
24
|
+
portText = bracketed[2];
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
// The SOCKS path writes IPv6 unbracketed: the port follows the last colon.
|
|
28
|
+
const at = target.lastIndexOf(":");
|
|
29
|
+
if (at <= 0)
|
|
30
|
+
return undefined;
|
|
31
|
+
host = target.slice(0, at);
|
|
32
|
+
portText = target.slice(at + 1);
|
|
33
|
+
if (host.includes(":") && isIP(host) !== 6)
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
if (!/^\d+$/.test(portText))
|
|
37
|
+
return undefined;
|
|
38
|
+
const port = Number(portText);
|
|
39
|
+
if (port > 65535)
|
|
40
|
+
return undefined;
|
|
41
|
+
return { host: normalizeHost(host), port, reason };
|
|
42
|
+
}
|
|
43
|
+
/** Lowercase, without the trailing dot of a fully qualified name. */
|
|
44
|
+
function normalizeHost(host) {
|
|
45
|
+
const h = host.toLowerCase();
|
|
46
|
+
return h.endsWith(".") ? h.slice(0, -1) : h;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Whether `host` is a public DNS name a command may reach when nothing narrows it (device and org
|
|
50
|
+
* both open): never an IP literal, a single-label or internal name, or a wildcard.
|
|
51
|
+
*/
|
|
52
|
+
export function isPublicName(host) {
|
|
53
|
+
const h = normalizeHost(host);
|
|
54
|
+
return !h.startsWith("*") && validateAllowHost(h).length === 0;
|
|
55
|
+
}
|
|
56
|
+
function admittedBy(list, host) {
|
|
57
|
+
return list.some((p) => covers(p.toLowerCase(), host));
|
|
58
|
+
}
|
|
59
|
+
/** IP literals, single-label and internal names: the runtime's guard refuses them for good. */
|
|
60
|
+
function isAddress(host, reason) {
|
|
61
|
+
return reason.startsWith("resolved to ") || validateAllowHost(host).length > 0;
|
|
62
|
+
}
|
|
63
|
+
function orgAllows(host, limits) {
|
|
64
|
+
if (limits.egress === "none")
|
|
65
|
+
return false;
|
|
66
|
+
if (limits.egress === "open")
|
|
67
|
+
return true;
|
|
68
|
+
return admittedBy(limits.allowHosts, host);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Whether the device's own tier admits `host` (spec §4.2): `open` admits every host, `dev` its
|
|
72
|
+
* `allowedDomains` and the dev hosts, `strict` its `allowedDomains`. Without limits (nothing run
|
|
73
|
+
* yet) the owner's choice, else `dev`, stands with no dev hosts known.
|
|
74
|
+
*/
|
|
75
|
+
function deviceAllows(host, policy, limits) {
|
|
76
|
+
const tier = limits === undefined ? provisionalTier(policy) : deviceTier(policy, limits);
|
|
77
|
+
const list = deviceHosts(policy, tier, limits?.devHosts ?? []);
|
|
78
|
+
return list === undefined || admittedBy(list, host);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The layer that refused `host`: `address` (an IP literal, a name `validateAllowHost` refuses, or
|
|
82
|
+
* a resolved-address reason), `org` (not in the org's effective egress, or egress none; also when
|
|
83
|
+
* the device lacks it too), `device` (the org allows it, the local policy does not), else `unknown`.
|
|
84
|
+
*/
|
|
85
|
+
export function classifyHost(host, reason, limits, policy) {
|
|
86
|
+
const h = normalizeHost(host);
|
|
87
|
+
if (isAddress(h, reason))
|
|
88
|
+
return "address";
|
|
89
|
+
if (!orgAllows(h, limits))
|
|
90
|
+
return "org";
|
|
91
|
+
if (!deviceAllows(h, policy, limits))
|
|
92
|
+
return "device";
|
|
93
|
+
return "unknown";
|
|
94
|
+
}
|
|
95
|
+
/** The refused hosts in `lines`, deduped by host (first port kept), at most {@link MAX_BLOCKED_HOSTS}. */
|
|
96
|
+
export function blockedHosts(lines, limits, policy) {
|
|
97
|
+
const out = new Map();
|
|
98
|
+
for (const line of lines) {
|
|
99
|
+
if (out.size >= MAX_BLOCKED_HOSTS)
|
|
100
|
+
break;
|
|
101
|
+
const v = parseNetworkViolation(line);
|
|
102
|
+
if (v === undefined || out.has(v.host))
|
|
103
|
+
continue;
|
|
104
|
+
out.set(v.host, {
|
|
105
|
+
host: v.host,
|
|
106
|
+
port: v.port,
|
|
107
|
+
layer: classifyHost(v.host, v.reason, limits, policy),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
return [...out.values()];
|
|
111
|
+
}
|
|
112
|
+
function target(b) {
|
|
113
|
+
return b.host.includes(":") ? `[${b.host}]:${b.port}` : `${b.host}:${b.port}`;
|
|
114
|
+
}
|
|
115
|
+
function explain(b) {
|
|
116
|
+
switch (b.layer) {
|
|
117
|
+
case "device":
|
|
118
|
+
return ("not in this device's allowed domains. Only the device owner can allow it " +
|
|
119
|
+
`(capybara-device policy add allowedDomains ${b.host}, or the device page).`);
|
|
120
|
+
case "org":
|
|
121
|
+
return "not in the organization's network allowlist. Only an organization admin can add it.";
|
|
122
|
+
case "address":
|
|
123
|
+
return "a private or local address; commands can never reach it.";
|
|
124
|
+
case "unknown":
|
|
125
|
+
return "refused by the sandbox's network proxy.";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** The stderr trailer of spec §9.2 (English, model-visible); "" for an empty list. */
|
|
129
|
+
export function networkTrailer(blocked) {
|
|
130
|
+
if (blocked.length === 0)
|
|
131
|
+
return "";
|
|
132
|
+
return [
|
|
133
|
+
"[capybara-device] Network access was blocked:",
|
|
134
|
+
...blocked.slice(0, MAX_BLOCKED_HOSTS).map((b) => `- ${target(b)}: ${explain(b)}`),
|
|
135
|
+
].join("\n");
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The reason the sandbox's ask callback answers (spec §9.1). The callback has no command id, so
|
|
139
|
+
* `limits` are the last ones seen (a device belongs to one org); without any, the org layer is
|
|
140
|
+
* not judged.
|
|
141
|
+
*/
|
|
142
|
+
export function denyReason(host, limits, policy) {
|
|
143
|
+
const h = normalizeHost(host);
|
|
144
|
+
let layer;
|
|
145
|
+
if (limits !== undefined)
|
|
146
|
+
layer = classifyHost(h, "", limits, policy);
|
|
147
|
+
else if (isAddress(h, ""))
|
|
148
|
+
layer = "address";
|
|
149
|
+
else
|
|
150
|
+
layer = deviceAllows(h, policy, undefined) ? "unknown" : "device";
|
|
151
|
+
switch (layer) {
|
|
152
|
+
case "device":
|
|
153
|
+
return `capybara: ${host} is not in this device's allowed domains`;
|
|
154
|
+
case "org":
|
|
155
|
+
return `capybara: ${host} is not in the organization's network allowlist`;
|
|
156
|
+
case "address":
|
|
157
|
+
return `capybara: ${host} is a private or local address`;
|
|
158
|
+
case "unknown":
|
|
159
|
+
return `capybara: ${host} is not allowed by the network policy`;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type Policy } from "./state.js";
|
|
2
|
+
/**
|
|
3
|
+
* The device's local policy as the running program sees it. Commands read {@link current} at
|
|
4
|
+
* each exec, so a change applies at the next command without a restart, whether this program
|
|
5
|
+
* wrote it ({@link update}) or someone ran `capybara-device policy` meanwhile. Each new version
|
|
6
|
+
* is a new object, so a reader can tell a reload by identity (the OS executor reruns its
|
|
7
|
+
* localhost proxy guard then).
|
|
8
|
+
*/
|
|
9
|
+
export declare class PolicyStore {
|
|
10
|
+
private readonly dir;
|
|
11
|
+
private policy;
|
|
12
|
+
private version;
|
|
13
|
+
/** The broken version last reported, so each one is reported once. */
|
|
14
|
+
private reportedBad;
|
|
15
|
+
private readonly file;
|
|
16
|
+
private readonly err;
|
|
17
|
+
/**
|
|
18
|
+
* policy.json had the legacy `network: "open"` when the store was made (start prints a notice;
|
|
19
|
+
* the key is dropped at the next write).
|
|
20
|
+
*/
|
|
21
|
+
readonly legacyNetworkOpen: boolean;
|
|
22
|
+
constructor(dir: string, opts?: {
|
|
23
|
+
err?: (line: string) => void;
|
|
24
|
+
initial?: Policy;
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* The policy now: re-reads policy.json when it changed (or appeared, or vanished: defaults).
|
|
28
|
+
* An invalid file keeps the last good policy, never a looser one, with the sandbox turned back
|
|
29
|
+
* on (a broken file never keeps commands running unsandboxed), and is reported once per version.
|
|
30
|
+
*/
|
|
31
|
+
current(): Policy;
|
|
32
|
+
/**
|
|
33
|
+
* Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
|
|
34
|
+
* than overwrite it), writes the change atomically keeping unknown keys, and swaps the
|
|
35
|
+
* in-memory policy. Returns the new policy.
|
|
36
|
+
*/
|
|
37
|
+
update(change: (p: Policy) => Policy): Policy;
|
|
38
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import { policyPath, readPolicyFile, withPolicyLock, writePolicy } from "./state.js";
|
|
3
|
+
/** What identifies one version of policy.json: absent, or its inode, size and mtime. */
|
|
4
|
+
function versionOf(file) {
|
|
5
|
+
try {
|
|
6
|
+
const st = statSync(file);
|
|
7
|
+
// An atomic write (rename) changes the inode; an in-place edit changes size or mtime.
|
|
8
|
+
return `${st.ino}:${st.size}:${st.mtimeMs}`;
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return "absent";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The device's local policy as the running program sees it. Commands read {@link current} at
|
|
16
|
+
* each exec, so a change applies at the next command without a restart, whether this program
|
|
17
|
+
* wrote it ({@link update}) or someone ran `capybara-device policy` meanwhile. Each new version
|
|
18
|
+
* is a new object, so a reader can tell a reload by identity (the OS executor reruns its
|
|
19
|
+
* localhost proxy guard then).
|
|
20
|
+
*/
|
|
21
|
+
export class PolicyStore {
|
|
22
|
+
dir;
|
|
23
|
+
policy;
|
|
24
|
+
version;
|
|
25
|
+
/** The broken version last reported, so each one is reported once. */
|
|
26
|
+
reportedBad;
|
|
27
|
+
file;
|
|
28
|
+
err;
|
|
29
|
+
/**
|
|
30
|
+
* policy.json had the legacy `network: "open"` when the store was made (start prints a notice;
|
|
31
|
+
* the key is dropped at the next write).
|
|
32
|
+
*/
|
|
33
|
+
legacyNetworkOpen;
|
|
34
|
+
constructor(dir, opts = {}) {
|
|
35
|
+
this.dir = dir;
|
|
36
|
+
this.file = policyPath(dir);
|
|
37
|
+
this.err = opts.err ?? (() => { });
|
|
38
|
+
this.version = versionOf(this.file);
|
|
39
|
+
// Without an initial policy, an unreadable file throws here: the program does not start.
|
|
40
|
+
if (opts.initial !== undefined) {
|
|
41
|
+
this.policy = opts.initial;
|
|
42
|
+
this.legacyNetworkOpen = false;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
const read = readPolicyFile(dir);
|
|
46
|
+
this.policy = read.policy;
|
|
47
|
+
this.legacyNetworkOpen = read.legacyNetworkOpen;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The policy now: re-reads policy.json when it changed (or appeared, or vanished: defaults).
|
|
52
|
+
* An invalid file keeps the last good policy, never a looser one, with the sandbox turned back
|
|
53
|
+
* on (a broken file never keeps commands running unsandboxed), and is reported once per version.
|
|
54
|
+
*/
|
|
55
|
+
current() {
|
|
56
|
+
const version = versionOf(this.file);
|
|
57
|
+
if (version === this.version)
|
|
58
|
+
return this.policy;
|
|
59
|
+
try {
|
|
60
|
+
this.policy = readPolicyFile(this.dir).policy;
|
|
61
|
+
// Advanced only on a good read: a broken version is retried until it is fixed.
|
|
62
|
+
this.version = version;
|
|
63
|
+
this.reportedBad = undefined;
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
// A new object only when it narrows: readers tell a reload by identity.
|
|
67
|
+
if (this.policy.isolation === "none")
|
|
68
|
+
this.policy = { ...this.policy, isolation: "sandbox" };
|
|
69
|
+
if (this.reportedBad !== version) {
|
|
70
|
+
this.reportedBad = version;
|
|
71
|
+
this.err(`${e.message}; keeping the last valid policy with the sandbox on until the ` +
|
|
72
|
+
"file is fixed");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return this.policy;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
|
|
79
|
+
* than overwrite it), writes the change atomically keeping unknown keys, and swaps the
|
|
80
|
+
* in-memory policy. Returns the new policy.
|
|
81
|
+
*/
|
|
82
|
+
update(change) {
|
|
83
|
+
return withPolicyLock(this.dir, () => {
|
|
84
|
+
const { policy, extra } = readPolicyFile(this.dir);
|
|
85
|
+
const next = change(policy);
|
|
86
|
+
writePolicy(this.dir, next, extra);
|
|
87
|
+
this.policy = next;
|
|
88
|
+
this.version = versionOf(this.file);
|
|
89
|
+
return next;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|