@capybara-hq/device 0.1.0-rc.1 → 0.1.0-rc.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +205 -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 +27 -4
- package/dist/cli.js +81 -11
- package/dist/client.d.ts +19 -6
- package/dist/client.js +93 -19
- package/dist/command-log.d.ts +8 -0
- package/dist/commands/drain.d.ts +14 -1
- package/dist/commands/drain.js +31 -2
- package/dist/commands/login.d.ts +3 -0
- package/dist/commands/login.js +96 -11
- package/dist/commands/logout.d.ts +2 -0
- package/dist/commands/logout.js +1 -1
- package/dist/commands/mode.d.ts +69 -0
- package/dist/commands/mode.js +129 -0
- package/dist/commands/policy.d.ts +13 -4
- package/dist/commands/policy.js +162 -33
- package/dist/commands/service.d.ts +26 -4
- package/dist/commands/service.js +242 -19
- package/dist/commands/signal.d.ts +6 -2
- package/dist/commands/signal.js +7 -4
- package/dist/commands/start.d.ts +18 -3
- package/dist/commands/start.js +46 -7
- package/dist/commands/status.js +12 -4
- package/dist/commands/stop.d.ts +20 -2
- package/dist/commands/stop.js +26 -3
- 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 +98 -0
- package/dist/exec/switch.js +175 -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 +44 -3
- package/dist/pid.js +110 -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 +48 -7
- package/dist/server-ops.js +287 -29
- package/dist/service/installed.d.ts +5 -0
- package/dist/service/installed.js +14 -0
- package/dist/service/launchd.d.ts +14 -1
- package/dist/service/launchd.js +25 -1
- package/dist/service/manager.d.ts +41 -0
- package/dist/service/manager.js +91 -0
- package/dist/service/systemd.d.ts +2 -0
- package/dist/service/systemd.js +8 -0
- 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,47 @@
|
|
|
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
|
+
};
|
|
12
|
+
/** What `ps` tells of a process: its command line and, when known, when it started. */
|
|
13
|
+
export interface ProcessInfo {
|
|
14
|
+
command: string;
|
|
15
|
+
started?: Date;
|
|
16
|
+
}
|
|
17
|
+
/** Looks a process up by pid (default: `ps`); undefined when there is no such process. */
|
|
18
|
+
export type ProcessLookup = (pid: number) => ProcessInfo | undefined;
|
|
19
|
+
/** How a pid is checked: `kill(pid, 0)` for liveness, `ps` for what the process is. */
|
|
20
|
+
export interface ProcessChecks {
|
|
21
|
+
kill?: typeof process.kill;
|
|
22
|
+
ps?: ProcessLookup;
|
|
23
|
+
}
|
|
24
|
+
/** The name every command line of this program contains (`…/bin/capybara-device.mjs start`). */
|
|
25
|
+
export declare const PROGRAM_BIN = "capybara-device";
|
|
26
|
+
/**
|
|
27
|
+
* Parses `ps -o lstart= -o command=` output (C locale): `Sat Nov 14 02:11:37 2026 <command>`, the
|
|
28
|
+
* start in local time. A line without a readable start keeps only the command.
|
|
29
|
+
*/
|
|
30
|
+
export declare function parsePsOutput(output: string): ProcessInfo | undefined;
|
|
31
|
+
/** The default {@link ProcessLookup}: one `ps` call in the C locale. */
|
|
32
|
+
export declare function psLookup(pid: number): ProcessInfo | undefined;
|
|
2
33
|
export declare function isAlive(pid: number, kill?: typeof process.kill): boolean;
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
|
|
34
|
+
/**
|
|
35
|
+
* The entry a pid file holds: JSON `{pid, version, startedAt}`, or a bare pid from a program older
|
|
36
|
+
* than the version field. Undefined when it is neither.
|
|
37
|
+
*/
|
|
38
|
+
export declare function parsePidFile(raw: string): RunningProgram | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* The running program, or undefined: no file, a file that is not a pid, a dead pid, or a pid that
|
|
41
|
+
* is not this program any more (see {@link namesThisProgram}). Nothing signals an unverified pid.
|
|
42
|
+
*/
|
|
43
|
+
export declare function readRunning(dir: string, checks?: ProcessChecks): RunningProgram | undefined;
|
|
44
|
+
/** The pid of the running program, or undefined (see {@link readRunning}). */
|
|
45
|
+
export declare function readRunningPid(dir: string, checks?: ProcessChecks): number | undefined;
|
|
46
|
+
export declare function writePid(dir: string, pid: number, version?: string): void;
|
|
6
47
|
export declare function removePid(dir: string, pid: number): void;
|
package/dist/pid.js
CHANGED
|
@@ -1,9 +1,51 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
1
2
|
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { writePrivate } from "./state.js";
|
|
4
5
|
export function pidPath(dir) {
|
|
5
6
|
return join(dir, "capybara-device.pid");
|
|
6
7
|
}
|
|
8
|
+
/** The name every command line of this program contains (`…/bin/capybara-device.mjs start`). */
|
|
9
|
+
export const PROGRAM_BIN = "capybara-device";
|
|
10
|
+
/**
|
|
11
|
+
* How much later than the pid file's `startedAt` the process may seem to have started: `ps`
|
|
12
|
+
* reports whole seconds, and Linux derives the time from a boot time rounded to the second.
|
|
13
|
+
*/
|
|
14
|
+
const START_SLACK_MS = 2000;
|
|
15
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
16
|
+
/**
|
|
17
|
+
* Parses `ps -o lstart= -o command=` output (C locale): `Sat Nov 14 02:11:37 2026 <command>`, the
|
|
18
|
+
* start in local time. A line without a readable start keeps only the command.
|
|
19
|
+
*/
|
|
20
|
+
export function parsePsOutput(output) {
|
|
21
|
+
const line = output.split("\n").find((l) => l.trim() !== "");
|
|
22
|
+
if (line === undefined)
|
|
23
|
+
return undefined;
|
|
24
|
+
const m = /^\s*\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})\s+(\d{4})\s+(.*)$/.exec(line);
|
|
25
|
+
const month = m === null ? -1 : MONTHS.indexOf(m[1] ?? "");
|
|
26
|
+
if (m === null || month < 0)
|
|
27
|
+
return { command: line.trim() };
|
|
28
|
+
const [, , day, h, min, s, year, command] = m;
|
|
29
|
+
return {
|
|
30
|
+
command: (command ?? "").trim(),
|
|
31
|
+
started: new Date(Number(year), month, Number(day), Number(h), Number(min), Number(s)),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** The default {@link ProcessLookup}: one `ps` call in the C locale. */
|
|
35
|
+
export function psLookup(pid) {
|
|
36
|
+
try {
|
|
37
|
+
const output = execFileSync("ps", ["-o", "lstart=", "-o", "command=", "-p", String(pid)], {
|
|
38
|
+
encoding: "utf8",
|
|
39
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
40
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
41
|
+
});
|
|
42
|
+
return parsePsOutput(output);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// ps exits 1 when no such process exists.
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
7
49
|
export function isAlive(pid, kill = process.kill) {
|
|
8
50
|
try {
|
|
9
51
|
kill(pid, 0);
|
|
@@ -13,21 +55,82 @@ export function isAlive(pid, kill = process.kill) {
|
|
|
13
55
|
return e.code === "EPERM";
|
|
14
56
|
}
|
|
15
57
|
}
|
|
16
|
-
/**
|
|
17
|
-
|
|
58
|
+
/**
|
|
59
|
+
* The entry a pid file holds: JSON `{pid, version, startedAt}`, or a bare pid from a program older
|
|
60
|
+
* than the version field. Undefined when it is neither.
|
|
61
|
+
*/
|
|
62
|
+
export function parsePidFile(raw) {
|
|
63
|
+
const text = raw.trim();
|
|
64
|
+
let pid;
|
|
65
|
+
let version;
|
|
66
|
+
let startedAt;
|
|
67
|
+
if (text.startsWith("{")) {
|
|
68
|
+
try {
|
|
69
|
+
const parsed = JSON.parse(text);
|
|
70
|
+
pid = Number(parsed.pid);
|
|
71
|
+
version = typeof parsed.version === "string" ? parsed.version : undefined;
|
|
72
|
+
startedAt = typeof parsed.startedAt === "string" ? parsed.startedAt : undefined;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
pid = Number.parseInt(text, 10);
|
|
80
|
+
}
|
|
81
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
82
|
+
return undefined;
|
|
83
|
+
return {
|
|
84
|
+
pid,
|
|
85
|
+
...(version !== undefined && { version }),
|
|
86
|
+
...(startedAt !== undefined && { startedAt }),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Whether the process `entry` names is this program: its command line contains the
|
|
91
|
+
* `capybara-device` bin, and it did not start after the pid file was written (a reused pid did).
|
|
92
|
+
* A file without `startedAt` (an older program) is checked by the command line alone.
|
|
93
|
+
*/
|
|
94
|
+
function namesThisProgram(entry, ps) {
|
|
95
|
+
const info = ps(entry.pid);
|
|
96
|
+
if (info === undefined || !info.command.includes(PROGRAM_BIN))
|
|
97
|
+
return false;
|
|
98
|
+
if (entry.startedAt === undefined)
|
|
99
|
+
return true;
|
|
100
|
+
const written = Date.parse(entry.startedAt);
|
|
101
|
+
if (Number.isNaN(written) || info.started === undefined)
|
|
102
|
+
return false;
|
|
103
|
+
return info.started.getTime() <= written + START_SLACK_MS;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The running program, or undefined: no file, a file that is not a pid, a dead pid, or a pid that
|
|
107
|
+
* is not this program any more (see {@link namesThisProgram}). Nothing signals an unverified pid.
|
|
108
|
+
*/
|
|
109
|
+
export function readRunning(dir, checks = {}) {
|
|
18
110
|
const file = pidPath(dir);
|
|
19
111
|
if (!existsSync(file))
|
|
20
112
|
return undefined;
|
|
21
|
-
const
|
|
22
|
-
|
|
113
|
+
const entry = parsePidFile(readFileSync(file, "utf8"));
|
|
114
|
+
if (entry === undefined || !isAlive(entry.pid, checks.kill))
|
|
115
|
+
return undefined;
|
|
116
|
+
return namesThisProgram(entry, checks.ps ?? psLookup) ? entry : undefined;
|
|
117
|
+
}
|
|
118
|
+
/** The pid of the running program, or undefined (see {@link readRunning}). */
|
|
119
|
+
export function readRunningPid(dir, checks = {}) {
|
|
120
|
+
return readRunning(dir, checks)?.pid;
|
|
23
121
|
}
|
|
24
|
-
export function writePid(dir, pid) {
|
|
25
|
-
|
|
122
|
+
export function writePid(dir, pid, version) {
|
|
123
|
+
const entry = {
|
|
124
|
+
pid,
|
|
125
|
+
...(version !== undefined && { version }),
|
|
126
|
+
startedAt: new Date().toISOString(),
|
|
127
|
+
};
|
|
128
|
+
writePrivate(pidPath(dir), `${JSON.stringify(entry)}\n`);
|
|
26
129
|
}
|
|
27
130
|
export function removePid(dir, pid) {
|
|
28
131
|
const file = pidPath(dir);
|
|
29
132
|
try {
|
|
30
|
-
if (
|
|
133
|
+
if (parsePidFile(readFileSync(file, "utf8"))?.pid === pid)
|
|
31
134
|
rmSync(file, { force: true });
|
|
32
135
|
}
|
|
33
136
|
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
|
+
}
|