@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/network.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
import { validateAllowHost } from "@capybara-hq/plugin-sdk";
|
|
3
|
+
import { covers } 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
|
+
// `open-public` is for cloud instances; a local sandbox-mode device gets an allowlist.
|
|
65
|
+
if (limits.network.kind === "open-public")
|
|
66
|
+
return true;
|
|
67
|
+
return admittedBy(limits.network.hosts, host);
|
|
68
|
+
}
|
|
69
|
+
/** Whether the device's own allowlist admits `host` (sandbox mode). */
|
|
70
|
+
function deviceAllows(host, policy) {
|
|
71
|
+
return admittedBy(policy.allowedDomains, host);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The layer that refused `host`: `address` (an IP literal, a name `validateAllowHost` refuses, or
|
|
75
|
+
* a resolved-address reason), `org` (not in the kernel's allowlist; also when the device lacks it
|
|
76
|
+
* too), `device` (the kernel allows it, the local policy does not), else `unknown`.
|
|
77
|
+
*/
|
|
78
|
+
export function classifyHost(host, reason, limits, policy) {
|
|
79
|
+
const h = normalizeHost(host);
|
|
80
|
+
if (isAddress(h, reason))
|
|
81
|
+
return "address";
|
|
82
|
+
if (!orgAllows(h, limits))
|
|
83
|
+
return "org";
|
|
84
|
+
if (!deviceAllows(h, policy))
|
|
85
|
+
return "device";
|
|
86
|
+
return "unknown";
|
|
87
|
+
}
|
|
88
|
+
/** The refused hosts in `lines`, deduped by host (first port kept), at most {@link MAX_BLOCKED_HOSTS}. */
|
|
89
|
+
export function blockedHosts(lines, limits, policy) {
|
|
90
|
+
const out = new Map();
|
|
91
|
+
for (const line of lines) {
|
|
92
|
+
if (out.size >= MAX_BLOCKED_HOSTS)
|
|
93
|
+
break;
|
|
94
|
+
const v = parseNetworkViolation(line);
|
|
95
|
+
if (v === undefined || out.has(v.host))
|
|
96
|
+
continue;
|
|
97
|
+
out.set(v.host, {
|
|
98
|
+
host: v.host,
|
|
99
|
+
port: v.port,
|
|
100
|
+
layer: classifyHost(v.host, v.reason, limits, policy),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return [...out.values()];
|
|
104
|
+
}
|
|
105
|
+
function target(b) {
|
|
106
|
+
return b.host.includes(":") ? `[${b.host}]:${b.port}` : `${b.host}:${b.port}`;
|
|
107
|
+
}
|
|
108
|
+
function explain(b) {
|
|
109
|
+
switch (b.layer) {
|
|
110
|
+
case "device":
|
|
111
|
+
return ("not in this device's allowed domains. Only the device owner can allow it " +
|
|
112
|
+
`(capybara-device policy add allowedDomains ${b.host}, or the device page).`);
|
|
113
|
+
case "org":
|
|
114
|
+
return "not in the organization's network allowlist. Only an organization admin can add it.";
|
|
115
|
+
case "address":
|
|
116
|
+
return "a private or local address; commands can never reach it.";
|
|
117
|
+
case "unknown":
|
|
118
|
+
return "refused by the sandbox's network proxy.";
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** The stderr trailer of spec §9.2 (English, model-visible); "" for an empty list. */
|
|
122
|
+
export function networkTrailer(blocked) {
|
|
123
|
+
if (blocked.length === 0)
|
|
124
|
+
return "";
|
|
125
|
+
return [
|
|
126
|
+
"[capybara-device] Network access was blocked:",
|
|
127
|
+
...blocked.slice(0, MAX_BLOCKED_HOSTS).map((b) => `- ${target(b)}: ${explain(b)}`),
|
|
128
|
+
].join("\n");
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The reason the sandbox's ask callback answers (spec §9.1). The callback has no command id, so
|
|
132
|
+
* `limits` are the last ones seen (a device belongs to one org); without any, the org layer is
|
|
133
|
+
* not judged.
|
|
134
|
+
*/
|
|
135
|
+
export function denyReason(host, limits, policy) {
|
|
136
|
+
const h = normalizeHost(host);
|
|
137
|
+
let layer;
|
|
138
|
+
if (limits !== undefined)
|
|
139
|
+
layer = classifyHost(h, "", limits, policy);
|
|
140
|
+
else if (isAddress(h, ""))
|
|
141
|
+
layer = "address";
|
|
142
|
+
else
|
|
143
|
+
layer = deviceAllows(h, policy) ? "unknown" : "device";
|
|
144
|
+
switch (layer) {
|
|
145
|
+
case "device":
|
|
146
|
+
return `capybara: ${host} is not in this device's allowed domains`;
|
|
147
|
+
case "org":
|
|
148
|
+
return `capybara: ${host} is not in the organization's network allowlist`;
|
|
149
|
+
case "address":
|
|
150
|
+
return `capybara: ${host} is a private or local address`;
|
|
151
|
+
case "unknown":
|
|
152
|
+
return `capybara: ${host} is not allowed by the network policy`;
|
|
153
|
+
}
|
|
154
|
+
}
|
package/dist/pid.d.ts
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
export declare function pidPath(dir: string): string;
|
|
2
|
+
/**
|
|
3
|
+
* The program a pid file names: its pid, and — for a program that wrote the file since this
|
|
4
|
+
* change — the version it runs and when it started (`service status` compares the version with the
|
|
5
|
+
* installed package, so a stale daemon after an upgrade says so instead of looking healthy).
|
|
6
|
+
*/
|
|
7
|
+
export type RunningProgram = {
|
|
8
|
+
pid: number;
|
|
9
|
+
version?: string;
|
|
10
|
+
startedAt?: string;
|
|
11
|
+
};
|
|
2
12
|
export declare function isAlive(pid: number, kill?: typeof process.kill): boolean;
|
|
13
|
+
/** The running program, or undefined (no file, a stale one, or a file that is not a pid). */
|
|
14
|
+
export declare function readRunning(dir: string, kill?: typeof process.kill): RunningProgram | undefined;
|
|
3
15
|
/** The pid of the running program, or undefined (no file, or a stale one). */
|
|
4
16
|
export declare function readRunningPid(dir: string, kill?: typeof process.kill): number | undefined;
|
|
5
|
-
export declare function writePid(dir: string, pid: number): void;
|
|
17
|
+
export declare function writePid(dir: string, pid: number, version?: string): void;
|
|
6
18
|
export declare function removePid(dir: string, pid: number): void;
|
package/dist/pid.js
CHANGED
|
@@ -13,21 +13,68 @@ export function isAlive(pid, kill = process.kill) {
|
|
|
13
13
|
return e.code === "EPERM";
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
/** The
|
|
17
|
-
export function
|
|
16
|
+
/** The running program, or undefined (no file, a stale one, or a file that is not a pid). */
|
|
17
|
+
export function readRunning(dir, kill = process.kill) {
|
|
18
18
|
const file = pidPath(dir);
|
|
19
19
|
if (!existsSync(file))
|
|
20
20
|
return undefined;
|
|
21
|
-
const
|
|
22
|
-
|
|
21
|
+
const raw = readFileSync(file, "utf8").trim();
|
|
22
|
+
let pid;
|
|
23
|
+
let version;
|
|
24
|
+
let startedAt;
|
|
25
|
+
if (raw.startsWith("{")) {
|
|
26
|
+
try {
|
|
27
|
+
const parsed = JSON.parse(raw);
|
|
28
|
+
pid = Number(parsed.pid);
|
|
29
|
+
version = typeof parsed.version === "string" ? parsed.version : undefined;
|
|
30
|
+
startedAt = typeof parsed.startedAt === "string" ? parsed.startedAt : undefined;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
// A program older than the version field wrote a bare pid: its version is unknown.
|
|
38
|
+
pid = Number.parseInt(raw, 10);
|
|
39
|
+
}
|
|
40
|
+
return Number.isInteger(pid) && pid > 0 && isAlive(pid, kill)
|
|
41
|
+
? {
|
|
42
|
+
pid,
|
|
43
|
+
...(version !== undefined && { version }),
|
|
44
|
+
...(startedAt !== undefined && { startedAt }),
|
|
45
|
+
}
|
|
46
|
+
: undefined;
|
|
23
47
|
}
|
|
24
|
-
|
|
25
|
-
|
|
48
|
+
/** The pid of the running program, or undefined (no file, or a stale one). */
|
|
49
|
+
export function readRunningPid(dir, kill = process.kill) {
|
|
50
|
+
return readRunning(dir, kill)?.pid;
|
|
51
|
+
}
|
|
52
|
+
export function writePid(dir, pid, version) {
|
|
53
|
+
const entry = {
|
|
54
|
+
pid,
|
|
55
|
+
...(version !== undefined && { version }),
|
|
56
|
+
startedAt: new Date().toISOString(),
|
|
57
|
+
};
|
|
58
|
+
writePrivate(pidPath(dir), `${JSON.stringify(entry)}\n`);
|
|
59
|
+
}
|
|
60
|
+
/** The pid a pid file names, without asking whether it is alive. */
|
|
61
|
+
function pidInFile(file) {
|
|
62
|
+
const raw = readFileSync(file, "utf8").trim();
|
|
63
|
+
if (raw.startsWith("{")) {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(raw);
|
|
66
|
+
return Number(parsed.pid);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return Number.parseInt(raw, 10);
|
|
26
73
|
}
|
|
27
74
|
export function removePid(dir, pid) {
|
|
28
75
|
const file = pidPath(dir);
|
|
29
76
|
try {
|
|
30
|
-
if (
|
|
77
|
+
if (pidInFile(file) === pid)
|
|
31
78
|
rmSync(file, { force: true });
|
|
32
79
|
}
|
|
33
80
|
catch {
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type DeviceErrorKind, type DevicePolicyOpOutcome, type DevicePolicyOpReport } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
/** The most `policy` op outcomes the log keeps; the oldest is dropped first. */
|
|
3
|
+
export declare const MAX_LOGGED_POLICY_OPS = 100;
|
|
4
|
+
/** The longest refusal message the log keeps (characters); a longer one is cut. */
|
|
5
|
+
export declare const MAX_LOGGED_MESSAGE_LENGTH = 500;
|
|
6
|
+
/**
|
|
7
|
+
* One logged `policy` op: its id from the deployment, the outcome, and a refusal's message and
|
|
8
|
+
* error kind (a repeated op is answered with them).
|
|
9
|
+
*/
|
|
10
|
+
export interface PolicyOpRecord {
|
|
11
|
+
opId: string;
|
|
12
|
+
outcome: DevicePolicyOpOutcome;
|
|
13
|
+
message?: string;
|
|
14
|
+
kind?: DeviceErrorKind;
|
|
15
|
+
time: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The outcomes of the latest `policy` ops, by the deployment's op id, in
|
|
19
|
+
* `<stateDir>/policy-ops.json` (oldest first, at most {@link MAX_LOGGED_POLICY_OPS}). An op is
|
|
20
|
+
* logged `started` before the policy is written, then `applied` or `refused`; one the program was
|
|
21
|
+
* stopped in the middle of stays `started`. The deployment reads it with `policyStatus` and in
|
|
22
|
+
* each hello (`recentOps`). Writes hold policy.json.lock, so they never interleave with a policy
|
|
23
|
+
* change.
|
|
24
|
+
*/
|
|
25
|
+
export declare class PolicyOpLog {
|
|
26
|
+
private readonly dir;
|
|
27
|
+
private readonly file;
|
|
28
|
+
constructor(dir: string);
|
|
29
|
+
/** The logged ops, oldest first; a missing or unreadable file (or entry) reads as none. */
|
|
30
|
+
entries(): PolicyOpRecord[];
|
|
31
|
+
get(opId: string): PolicyOpRecord | undefined;
|
|
32
|
+
/** The outcomes a hello reports, oldest first. */
|
|
33
|
+
recent(): DevicePolicyOpReport[];
|
|
34
|
+
/** Logs an outcome under the policy lock. */
|
|
35
|
+
record(entry: Omit<PolicyOpRecord, "time">): void;
|
|
36
|
+
/**
|
|
37
|
+
* Logs an outcome; the caller holds policy.json.lock. A later outcome of the same op replaces
|
|
38
|
+
* its entry and moves it last.
|
|
39
|
+
*/
|
|
40
|
+
recordHeld(entry: Omit<PolicyOpRecord, "time">): void;
|
|
41
|
+
/**
|
|
42
|
+
* Under the policy lock: the op's final outcome when it was applied or refused before (the
|
|
43
|
+
* caller answers from it), else logs it `started` and returns undefined (an op left `started`
|
|
44
|
+
* by an interrupted run is taken again: its content is idempotent).
|
|
45
|
+
*/
|
|
46
|
+
claim(opId: string): PolicyOpRecord | undefined;
|
|
47
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { isPolicyOpId, } from "@capybara-hq/plugin-sdk";
|
|
3
|
+
import { policyOpsPath, withPolicyLock, writePrivate } from "./state.js";
|
|
4
|
+
/** The most `policy` op outcomes the log keeps; the oldest is dropped first. */
|
|
5
|
+
export const MAX_LOGGED_POLICY_OPS = 100;
|
|
6
|
+
/** The longest refusal message the log keeps (characters); a longer one is cut. */
|
|
7
|
+
export const MAX_LOGGED_MESSAGE_LENGTH = 500;
|
|
8
|
+
const KINDS = ["gone", "fs_gone", "policy", "error"];
|
|
9
|
+
const OUTCOMES = ["applied", "refused", "started"];
|
|
10
|
+
function isRecord(v) {
|
|
11
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
12
|
+
return false;
|
|
13
|
+
const o = v;
|
|
14
|
+
return (isPolicyOpId(o.opId) &&
|
|
15
|
+
OUTCOMES.includes(o.outcome) &&
|
|
16
|
+
(o.message === undefined || typeof o.message === "string") &&
|
|
17
|
+
(o.kind === undefined || KINDS.includes(o.kind)) &&
|
|
18
|
+
typeof o.time === "string");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The outcomes of the latest `policy` ops, by the deployment's op id, in
|
|
22
|
+
* `<stateDir>/policy-ops.json` (oldest first, at most {@link MAX_LOGGED_POLICY_OPS}). An op is
|
|
23
|
+
* logged `started` before the policy is written, then `applied` or `refused`; one the program was
|
|
24
|
+
* stopped in the middle of stays `started`. The deployment reads it with `policyStatus` and in
|
|
25
|
+
* each hello (`recentOps`). Writes hold policy.json.lock, so they never interleave with a policy
|
|
26
|
+
* change.
|
|
27
|
+
*/
|
|
28
|
+
export class PolicyOpLog {
|
|
29
|
+
dir;
|
|
30
|
+
file;
|
|
31
|
+
constructor(dir) {
|
|
32
|
+
this.dir = dir;
|
|
33
|
+
this.file = policyOpsPath(dir);
|
|
34
|
+
}
|
|
35
|
+
/** The logged ops, oldest first; a missing or unreadable file (or entry) reads as none. */
|
|
36
|
+
entries() {
|
|
37
|
+
if (!existsSync(this.file))
|
|
38
|
+
return [];
|
|
39
|
+
let raw;
|
|
40
|
+
try {
|
|
41
|
+
raw = JSON.parse(readFileSync(this.file, "utf8"));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// a broken log is replaced at the next write: the deployment then learns less, never more
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
return Array.isArray(raw) ? raw.filter(isRecord).slice(-MAX_LOGGED_POLICY_OPS) : [];
|
|
48
|
+
}
|
|
49
|
+
get(opId) {
|
|
50
|
+
return this.entries().find((e) => e.opId === opId);
|
|
51
|
+
}
|
|
52
|
+
/** The outcomes a hello reports, oldest first. */
|
|
53
|
+
recent() {
|
|
54
|
+
return this.entries().map((e) => ({ opId: e.opId, outcome: e.outcome }));
|
|
55
|
+
}
|
|
56
|
+
/** Logs an outcome under the policy lock. */
|
|
57
|
+
record(entry) {
|
|
58
|
+
withPolicyLock(this.dir, () => this.recordHeld(entry));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Logs an outcome; the caller holds policy.json.lock. A later outcome of the same op replaces
|
|
62
|
+
* its entry and moves it last.
|
|
63
|
+
*/
|
|
64
|
+
recordHeld(entry) {
|
|
65
|
+
const next = {
|
|
66
|
+
...entry,
|
|
67
|
+
...(entry.message !== undefined && {
|
|
68
|
+
message: entry.message.slice(0, MAX_LOGGED_MESSAGE_LENGTH),
|
|
69
|
+
}),
|
|
70
|
+
time: new Date().toISOString(),
|
|
71
|
+
};
|
|
72
|
+
const kept = this.entries().filter((e) => e.opId !== entry.opId);
|
|
73
|
+
kept.push(next);
|
|
74
|
+
writePrivate(this.file, `${JSON.stringify(kept.slice(-MAX_LOGGED_POLICY_OPS), null, 2)}\n`);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Under the policy lock: the op's final outcome when it was applied or refused before (the
|
|
78
|
+
* caller answers from it), else logs it `started` and returns undefined (an op left `started`
|
|
79
|
+
* by an interrupted run is taken again: its content is idempotent).
|
|
80
|
+
*/
|
|
81
|
+
claim(opId) {
|
|
82
|
+
return withPolicyLock(this.dir, () => {
|
|
83
|
+
const known = this.get(opId);
|
|
84
|
+
if (known !== undefined && known.outcome !== "started")
|
|
85
|
+
return known;
|
|
86
|
+
this.recordHeld({ opId, outcome: "started" });
|
|
87
|
+
return undefined;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { PolicyOpLog } from "./policy-ops.js";
|
|
2
|
+
import { type Policy } from "./state.js";
|
|
3
|
+
/**
|
|
4
|
+
* The device's local policy as the running program sees it. Commands read {@link current} at
|
|
5
|
+
* each exec, so a change applies at the next command without a restart, whether this program
|
|
6
|
+
* wrote it ({@link update}) or someone ran `capybara-device mode` / `capybara-device policy`
|
|
7
|
+
* meanwhile. Each new version is a new object, so a reader can tell a reload by identity (the
|
|
8
|
+
* switching executor kills auto-mode commands when the policy turns the sandbox back on).
|
|
9
|
+
*/
|
|
10
|
+
export declare class PolicyStore {
|
|
11
|
+
private readonly dir;
|
|
12
|
+
private policy;
|
|
13
|
+
private version;
|
|
14
|
+
/** The broken version last reported, so each one is reported once. */
|
|
15
|
+
private reportedBad;
|
|
16
|
+
private readonly file;
|
|
17
|
+
private readonly err;
|
|
18
|
+
/**
|
|
19
|
+
* policy.json was written before auto mode (no `mode`) when the store was made: `start` prints
|
|
20
|
+
* one notice, and the key is dropped at the next write.
|
|
21
|
+
*/
|
|
22
|
+
readonly legacy: boolean;
|
|
23
|
+
/** The outcomes of the `policy` ops this machine served, by op id (next to policy.json). */
|
|
24
|
+
readonly ops: PolicyOpLog;
|
|
25
|
+
constructor(dir: string, opts?: {
|
|
26
|
+
err?: (line: string) => void;
|
|
27
|
+
initial?: Policy;
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* The policy now: re-reads policy.json when it changed (or appeared, or vanished: defaults).
|
|
31
|
+
* An invalid file keeps the last good policy and is reported once per version.
|
|
32
|
+
*/
|
|
33
|
+
current(): Policy;
|
|
34
|
+
/**
|
|
35
|
+
* Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
|
|
36
|
+
* than overwrite it), writes the change atomically keeping unknown keys, and swaps the
|
|
37
|
+
* in-memory policy. `written` runs after that, still holding the lock (the `policy` op logs its
|
|
38
|
+
* outcome there, next to the change). Returns the new policy.
|
|
39
|
+
*/
|
|
40
|
+
update(change: (p: Policy) => Policy, opts?: {
|
|
41
|
+
written?: (p: Policy) => void;
|
|
42
|
+
}): Policy;
|
|
43
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import { PolicyOpLog } from "./policy-ops.js";
|
|
3
|
+
import { policyPath, readPolicyFile, withPolicyLock, writePolicy } from "./state.js";
|
|
4
|
+
/** What identifies one version of policy.json: absent, or its inode, size and mtime. */
|
|
5
|
+
function versionOf(file) {
|
|
6
|
+
try {
|
|
7
|
+
const st = statSync(file);
|
|
8
|
+
// An atomic write (rename) changes the inode; an in-place edit changes size or mtime.
|
|
9
|
+
return `${st.ino}:${st.size}:${st.mtimeMs}`;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return "absent";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The device's local policy as the running program sees it. Commands read {@link current} at
|
|
17
|
+
* each exec, so a change applies at the next command without a restart, whether this program
|
|
18
|
+
* wrote it ({@link update}) or someone ran `capybara-device mode` / `capybara-device policy`
|
|
19
|
+
* meanwhile. Each new version is a new object, so a reader can tell a reload by identity (the
|
|
20
|
+
* switching executor kills auto-mode commands when the policy turns the sandbox back on).
|
|
21
|
+
*/
|
|
22
|
+
export class PolicyStore {
|
|
23
|
+
dir;
|
|
24
|
+
policy;
|
|
25
|
+
version;
|
|
26
|
+
/** The broken version last reported, so each one is reported once. */
|
|
27
|
+
reportedBad;
|
|
28
|
+
file;
|
|
29
|
+
err;
|
|
30
|
+
/**
|
|
31
|
+
* policy.json was written before auto mode (no `mode`) when the store was made: `start` prints
|
|
32
|
+
* one notice, and the key is dropped at the next write.
|
|
33
|
+
*/
|
|
34
|
+
legacy;
|
|
35
|
+
/** The outcomes of the `policy` ops this machine served, by op id (next to policy.json). */
|
|
36
|
+
ops;
|
|
37
|
+
constructor(dir, opts = {}) {
|
|
38
|
+
this.dir = dir;
|
|
39
|
+
this.file = policyPath(dir);
|
|
40
|
+
this.err = opts.err ?? (() => { });
|
|
41
|
+
this.ops = new PolicyOpLog(dir);
|
|
42
|
+
this.version = versionOf(this.file);
|
|
43
|
+
// Without an initial policy, an unreadable file throws here: the program does not start.
|
|
44
|
+
if (opts.initial !== undefined) {
|
|
45
|
+
this.policy = opts.initial;
|
|
46
|
+
this.legacy = false;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
const read = readPolicyFile(dir);
|
|
50
|
+
this.policy = read.policy;
|
|
51
|
+
this.legacy = read.legacy;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The policy now: re-reads policy.json when it changed (or appeared, or vanished: defaults).
|
|
56
|
+
* An invalid file keeps the last good policy and is reported once per version.
|
|
57
|
+
*/
|
|
58
|
+
current() {
|
|
59
|
+
const version = versionOf(this.file);
|
|
60
|
+
if (version === this.version)
|
|
61
|
+
return this.policy;
|
|
62
|
+
try {
|
|
63
|
+
this.policy = readPolicyFile(this.dir).policy;
|
|
64
|
+
// Advanced only on a good read: a broken version is retried until it is fixed.
|
|
65
|
+
this.version = version;
|
|
66
|
+
this.reportedBad = undefined;
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
// A broken file never changes the mode: the last good policy stands.
|
|
70
|
+
if (this.reportedBad !== version) {
|
|
71
|
+
this.reportedBad = version;
|
|
72
|
+
this.err(`${e.message}; keeping the last valid policy until the 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. `written` runs after that, still holding the lock (the `policy` op logs its
|
|
81
|
+
* outcome there, next to the change). Returns the new policy.
|
|
82
|
+
*/
|
|
83
|
+
update(change, opts = {}) {
|
|
84
|
+
return withPolicyLock(this.dir, () => {
|
|
85
|
+
const { policy, extra } = readPolicyFile(this.dir);
|
|
86
|
+
const next = change(policy);
|
|
87
|
+
writePolicy(this.dir, next, extra);
|
|
88
|
+
this.policy = next;
|
|
89
|
+
this.version = versionOf(this.file);
|
|
90
|
+
opts.written?.(next);
|
|
91
|
+
return next;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
package/dist/policy.d.ts
CHANGED
|
@@ -1,25 +1,40 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import type { Policy } from "./state.js";
|
|
1
|
+
import { type DeviceExecGrants, type SandboxLimits, type SandboxRoots } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { Policy, SandboxMode } from "./state.js";
|
|
3
3
|
/**
|
|
4
|
-
* Paths no command may read (spec §13.6, extended by ruling R19): SSH keys, cloud CLI
|
|
4
|
+
* Paths no sandboxed command may read (spec §13.6, extended by ruling R19): SSH keys, cloud CLI
|
|
5
5
|
* credentials, container and Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the
|
|
6
6
|
* macOS keychains, and the browser profile directories (Chrome, Firefox, Chromium, Safari, Brave,
|
|
7
|
-
* Edge, Arc). Relative to `~`.
|
|
7
|
+
* Edge, Arc). Relative to `~`. Auto mode runs as the owner and does not apply them: command review
|
|
8
|
+
* in the kernel does (spec §5.2).
|
|
8
9
|
*/
|
|
9
10
|
export declare const DENIED_SECRET_PATHS: readonly string[];
|
|
10
11
|
/** {@link DENIED_SECRET_PATHS} with `~` expanded to `home`. */
|
|
11
12
|
export declare function deniedSecretPaths(home?: string): string[];
|
|
12
13
|
/**
|
|
13
14
|
* Paths sandbox-runtime makes writable without being asked (its own temp directory and two home
|
|
14
|
-
* convenience directories). They lie outside the
|
|
15
|
+
* convenience directories). They lie outside the device directory, so they are denied.
|
|
15
16
|
*/
|
|
16
17
|
export declare function implicitWritePaths(home?: string): string[];
|
|
18
|
+
/** True when the allowlist entry `pattern` admits every host `host` names (`host` may be a wildcard). */
|
|
19
|
+
export declare function covers(pattern: string, host: string): boolean;
|
|
20
|
+
/** The limits fields that decide the mode and the sandbox-mode network. */
|
|
21
|
+
export type ModeLimits = Pick<SandboxLimits, "mode" | "network">;
|
|
17
22
|
/**
|
|
18
|
-
* The
|
|
19
|
-
*
|
|
23
|
+
* The mode a command runs in (spec §4.1): the device's own choice cut to the kernel's ceiling. A
|
|
24
|
+
* sandbox-mode machine never runs auto because the organization allows it; an auto-mode machine in
|
|
25
|
+
* an organization that forbids auto runs in the sandbox (and its summary says so).
|
|
20
26
|
*/
|
|
21
|
-
export declare function
|
|
22
|
-
/** The
|
|
27
|
+
export declare function effectiveMode(policy: Pick<Policy, "mode">, limits: Pick<SandboxLimits, "mode">): SandboxMode;
|
|
28
|
+
/** The granted hosts that apply to one command, within the kernel's network limits. */
|
|
29
|
+
export declare function grantedHosts(limits: Pick<SandboxLimits, "network">, grants: Pick<DeviceExecGrants, "hosts"> | undefined): string[];
|
|
30
|
+
/**
|
|
31
|
+
* The domains one sandbox-mode command may reach (spec §4.1, §4.4): the intersection of the
|
|
32
|
+
* device's own `allowedDomains` and the kernel's allowlist (`limits.network`), plus the command's
|
|
33
|
+
* grants. An empty list allows nothing. Auto mode ignores both lists: the command has the machine's
|
|
34
|
+
* own network, so this returns no list there (the OS sandbox is not running).
|
|
35
|
+
*/
|
|
36
|
+
export declare function effectiveEgress(policy: Pick<Policy, "allowedDomains" | "mode">, limits: ModeLimits, grants?: Pick<DeviceExecGrants, "hosts">): string[];
|
|
37
|
+
/** The sandbox-runtime configuration of a sandbox-mode device. */
|
|
23
38
|
export interface SrtConfig {
|
|
24
39
|
filesystem: {
|
|
25
40
|
denyRead: string[];
|
|
@@ -31,12 +46,17 @@ export interface SrtConfig {
|
|
|
31
46
|
deniedDomains: string[];
|
|
32
47
|
};
|
|
33
48
|
}
|
|
34
|
-
/**
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
* unreadable, and network limited to `egress`.
|
|
38
|
-
*/
|
|
39
|
-
export declare function srtConfig(_policy: Policy, roots: SandboxRoots, egress: string[], opts?: {
|
|
49
|
+
/** What {@link srtConfig} needs besides the egress list. */
|
|
50
|
+
export interface SrtConfigOptions {
|
|
51
|
+
/** The home whose secret paths are denied (default: the user's home). */
|
|
40
52
|
home?: string;
|
|
53
|
+
/** More paths commands may not read (this program's state directory). */
|
|
41
54
|
denyRead?: string[];
|
|
42
|
-
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The sandbox-runtime configuration of sandbox mode (spec §4.1, §4.4): today's strict profile
|
|
58
|
+
* only. Writes only under the workspace and tmp roots (the runtime's implicit write paths
|
|
59
|
+
* denied), skills read only, the secret paths (plus `opts.denyRead`, such as this program's own
|
|
60
|
+
* state directory) unreadable, and network limited to `egress`. No local binding, no unix sockets.
|
|
61
|
+
*/
|
|
62
|
+
export declare function srtConfig(roots: SandboxRoots, egress: string[], opts?: SrtConfigOptions): SrtConfig;
|