@capybara-hq/device 0.1.0-rc.6 → 0.1.0-rc.7
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/dist/client.js +6 -2
- package/dist/exec/os.d.ts +20 -0
- package/dist/exec/os.js +58 -9
- package/dist/policy-ops.d.ts +47 -0
- package/dist/policy-ops.js +90 -0
- package/dist/policy-store.d.ts +8 -2
- package/dist/policy-store.js +8 -2
- package/dist/server-ops.d.ts +2 -1
- package/dist/server-ops.js +85 -8
- package/dist/state.d.ts +2 -0
- package/dist/state.js +10 -1
- package/package.json +2 -2
package/dist/client.js
CHANGED
|
@@ -241,7 +241,8 @@ export function connect(cred, executor, opts = {}) {
|
|
|
241
241
|
/**
|
|
242
242
|
* The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
|
|
243
243
|
* mode has no per-host view); the device applies tiers (`limits.tier` / `defaultTier` /
|
|
244
|
-
* `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen
|
|
244
|
+
* `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen; then the
|
|
245
|
+
* outcomes of the latest policy ops by op id.
|
|
245
246
|
*/
|
|
246
247
|
const hello = () => {
|
|
247
248
|
const summary = summaryNow();
|
|
@@ -249,8 +250,9 @@ export function connect(cred, executor, opts = {}) {
|
|
|
249
250
|
const features = [];
|
|
250
251
|
if (executor.mode === "os")
|
|
251
252
|
features.push("networkReport");
|
|
253
|
+
// the policy op, logged by its op id (policy-ops.json next to the policy)
|
|
252
254
|
if (opts.policy !== undefined)
|
|
253
|
-
features.push("policyOp");
|
|
255
|
+
features.push("policyOp", "policyOpId");
|
|
254
256
|
features.push("tiers");
|
|
255
257
|
return {
|
|
256
258
|
type: "hello",
|
|
@@ -263,6 +265,8 @@ export function connect(cred, executor, opts = {}) {
|
|
|
263
265
|
sessionIsolation: false,
|
|
264
266
|
features,
|
|
265
267
|
...(summary !== undefined && { policy: summary }),
|
|
268
|
+
// what became of the latest policy ops, so an answer lost with a connection is not lost
|
|
269
|
+
...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
|
|
266
270
|
};
|
|
267
271
|
};
|
|
268
272
|
let attempt = 0;
|
package/dist/exec/os.d.ts
CHANGED
|
@@ -69,6 +69,13 @@ export declare class OsExecutor implements Executor {
|
|
|
69
69
|
* running. The ask callback allows any public name only while one runs.
|
|
70
70
|
*/
|
|
71
71
|
private readonly openCommands;
|
|
72
|
+
/**
|
|
73
|
+
* Background tasks launched on macOS that still run, by the command id of their launch, with
|
|
74
|
+
* the task's process group id (its sid). A task keeps its launch's network permissions (the
|
|
75
|
+
* per-command list and {@link openCommands}) until its group is gone: it uses the launch's proxy
|
|
76
|
+
* credentials long after the launch returned. Checked on the prune tick.
|
|
77
|
+
*/
|
|
78
|
+
private readonly backgroundNet;
|
|
72
79
|
constructor(opts: OsExecutorOptions);
|
|
73
80
|
/**
|
|
74
81
|
* The tier of work that has no limits of its own (the file helper): the device's choice cut to
|
|
@@ -131,6 +138,13 @@ export declare class OsExecutor implements Executor {
|
|
|
131
138
|
* exported) and spawns it as the leader of a new process group.
|
|
132
139
|
*/
|
|
133
140
|
private spawnSandboxed;
|
|
141
|
+
/** Drops a command's network permissions (its per-command list and any-host membership). */
|
|
142
|
+
private releaseNet;
|
|
143
|
+
/** Keeps a launched background task's network permissions while its group `sid` lives. */
|
|
144
|
+
private keepBackgroundNet;
|
|
145
|
+
/** Releases the network permissions of background tasks whose group is gone (all: `all`). */
|
|
146
|
+
private pruneBackgroundNet;
|
|
147
|
+
private startPruning;
|
|
134
148
|
/** Tracks a spawned command's process group; returns the entry. */
|
|
135
149
|
private track;
|
|
136
150
|
/** Forgets finished groups with no members left (or whose id was taken by another process). */
|
|
@@ -155,6 +169,12 @@ export declare class OsExecutor implements Executor {
|
|
|
155
169
|
/** Kills every running command and shuts the sandbox's proxies down. */
|
|
156
170
|
dispose(): Promise<void>;
|
|
157
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* The process group id a background task launch printed as its last line (the task's sid), on
|
|
174
|
+
* macOS only: there the sandbox shares the host's process ids, so the device can watch the group.
|
|
175
|
+
* Elsewhere (Linux: bwrap's own pid namespace) undefined, and the launch's permissions end with it.
|
|
176
|
+
*/
|
|
177
|
+
export declare function launchedGroup(stdout: string, platform?: NodeJS.Platform): number | undefined;
|
|
158
178
|
/**
|
|
159
179
|
* The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
|
|
160
180
|
* once for this process, and kills what a previous run of this device left running.
|
package/dist/exec/os.js
CHANGED
|
@@ -99,6 +99,13 @@ export class OsExecutor {
|
|
|
99
99
|
* running. The ask callback allows any public name only while one runs.
|
|
100
100
|
*/
|
|
101
101
|
openCommands = new Set();
|
|
102
|
+
/**
|
|
103
|
+
* Background tasks launched on macOS that still run, by the command id of their launch, with
|
|
104
|
+
* the task's process group id (its sid). A task keeps its launch's network permissions (the
|
|
105
|
+
* per-command list and {@link openCommands}) until its group is gone: it uses the launch's proxy
|
|
106
|
+
* credentials long after the launch returned. Checked on the prune tick.
|
|
107
|
+
*/
|
|
108
|
+
backgroundNet = new Map();
|
|
102
109
|
constructor(opts) {
|
|
103
110
|
this.opts = opts;
|
|
104
111
|
this.reaper = new Reaper(opts.reaper);
|
|
@@ -312,16 +319,41 @@ export class OsExecutor {
|
|
|
312
319
|
}
|
|
313
320
|
return { child, commandId };
|
|
314
321
|
}
|
|
322
|
+
/** Drops a command's network permissions (its per-command list and any-host membership). */
|
|
323
|
+
releaseNet(commandId) {
|
|
324
|
+
this.backgroundNet.delete(commandId);
|
|
325
|
+
this.openCommands.delete(commandId);
|
|
326
|
+
SandboxManager.unregisterCommandNetworkLists(commandId);
|
|
327
|
+
}
|
|
328
|
+
/** Keeps a launched background task's network permissions while its group `sid` lives. */
|
|
329
|
+
keepBackgroundNet(commandId, sid) {
|
|
330
|
+
if (!killGroupId(sid, 0)) {
|
|
331
|
+
this.releaseNet(commandId);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
this.backgroundNet.set(commandId, sid);
|
|
335
|
+
this.startPruning();
|
|
336
|
+
}
|
|
337
|
+
/** Releases the network permissions of background tasks whose group is gone (all: `all`). */
|
|
338
|
+
pruneBackgroundNet(all = false) {
|
|
339
|
+
for (const [commandId, sid] of [...this.backgroundNet]) {
|
|
340
|
+
if (all || !killGroupId(sid, 0))
|
|
341
|
+
this.releaseNet(commandId);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
startPruning() {
|
|
345
|
+
if (this.pruneTimer === undefined) {
|
|
346
|
+
this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
|
|
347
|
+
this.pruneTimer.unref();
|
|
348
|
+
}
|
|
349
|
+
}
|
|
315
350
|
/** Tracks a spawned command's process group; returns the entry. */
|
|
316
351
|
track(tag, child) {
|
|
317
352
|
if (child.pid === undefined)
|
|
318
353
|
return undefined;
|
|
319
354
|
const g = { tag, pgid: child.pid, exited: false };
|
|
320
355
|
this.groups.add(g);
|
|
321
|
-
|
|
322
|
-
this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
|
|
323
|
-
this.pruneTimer.unref();
|
|
324
|
-
}
|
|
356
|
+
this.startPruning();
|
|
325
357
|
return g;
|
|
326
358
|
}
|
|
327
359
|
/** Forgets finished groups with no members left (or whose id was taken by another process). */
|
|
@@ -334,7 +366,8 @@ export class OsExecutor {
|
|
|
334
366
|
if (pidAlive(g.pgid) || !killGroupId(g.pgid, 0))
|
|
335
367
|
this.groups.delete(g);
|
|
336
368
|
}
|
|
337
|
-
|
|
369
|
+
this.pruneBackgroundNet();
|
|
370
|
+
if (this.groups.size === 0 && this.backgroundNet.size === 0 && this.pruneTimer !== undefined) {
|
|
338
371
|
clearInterval(this.pruneTimer);
|
|
339
372
|
this.pruneTimer = undefined;
|
|
340
373
|
}
|
|
@@ -402,7 +435,7 @@ export class OsExecutor {
|
|
|
402
435
|
}, args.timeoutMs);
|
|
403
436
|
const onAbort = () => kill();
|
|
404
437
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
405
|
-
const cleanup = () => {
|
|
438
|
+
const cleanup = (keepFor) => {
|
|
406
439
|
clearTimeout(timer);
|
|
407
440
|
if (grace)
|
|
408
441
|
clearTimeout(grace);
|
|
@@ -411,8 +444,10 @@ export class OsExecutor {
|
|
|
411
444
|
group.exited = true;
|
|
412
445
|
group.onKill = undefined;
|
|
413
446
|
}
|
|
414
|
-
|
|
415
|
-
|
|
447
|
+
if (keepFor !== undefined)
|
|
448
|
+
this.keepBackgroundNet(commandId, keepFor);
|
|
449
|
+
else
|
|
450
|
+
this.releaseNet(commandId);
|
|
416
451
|
SandboxManager.cleanupAfterCommand();
|
|
417
452
|
};
|
|
418
453
|
const finish = () => {
|
|
@@ -428,7 +463,9 @@ export class OsExecutor {
|
|
|
428
463
|
// The explanation is best effort: the command's result always comes back.
|
|
429
464
|
}
|
|
430
465
|
const trailer = networkTrailer(blocked);
|
|
431
|
-
cleanup(
|
|
466
|
+
cleanup(reap || killed || timedOut || exit.code !== 0
|
|
467
|
+
? undefined
|
|
468
|
+
: launchedGroup(cap.text("stdout")));
|
|
432
469
|
child.stdout?.destroy();
|
|
433
470
|
child.stderr?.destroy();
|
|
434
471
|
let exitCode = exit.code;
|
|
@@ -577,6 +614,7 @@ export class OsExecutor {
|
|
|
577
614
|
for (const g of [...this.groups])
|
|
578
615
|
this.killGroup(g);
|
|
579
616
|
await this.killLeftovers();
|
|
617
|
+
this.pruneBackgroundNet(true);
|
|
580
618
|
}
|
|
581
619
|
/** Kills every process carrying this device's marker (also a previous run's). */
|
|
582
620
|
async killLeftovers() {
|
|
@@ -592,6 +630,17 @@ export class OsExecutor {
|
|
|
592
630
|
await SandboxManager.reset();
|
|
593
631
|
}
|
|
594
632
|
}
|
|
633
|
+
/**
|
|
634
|
+
* The process group id a background task launch printed as its last line (the task's sid), on
|
|
635
|
+
* macOS only: there the sandbox shares the host's process ids, so the device can watch the group.
|
|
636
|
+
* Elsewhere (Linux: bwrap's own pid namespace) undefined, and the launch's permissions end with it.
|
|
637
|
+
*/
|
|
638
|
+
export function launchedGroup(stdout, platform = process.platform) {
|
|
639
|
+
if (platform !== "darwin")
|
|
640
|
+
return undefined;
|
|
641
|
+
const last = stdout.trimEnd().split("\n").pop()?.trim() ?? "";
|
|
642
|
+
return /^[1-9][0-9]*$/.test(last) ? Number(last) : undefined;
|
|
643
|
+
}
|
|
595
644
|
/**
|
|
596
645
|
* The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
|
|
597
646
|
* once for this process, and kills what a previous run of this device left running.
|
|
@@ -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
|
+
}
|
package/dist/policy-store.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PolicyOpLog } from "./policy-ops.js";
|
|
1
2
|
import { type Policy } from "./state.js";
|
|
2
3
|
/**
|
|
3
4
|
* The device's local policy as the running program sees it. Commands read {@link current} at
|
|
@@ -19,6 +20,8 @@ export declare class PolicyStore {
|
|
|
19
20
|
* the key is dropped at the next write).
|
|
20
21
|
*/
|
|
21
22
|
readonly legacyNetworkOpen: boolean;
|
|
23
|
+
/** The outcomes of the `policy` ops this machine served, by op id (next to policy.json). */
|
|
24
|
+
readonly ops: PolicyOpLog;
|
|
22
25
|
constructor(dir: string, opts?: {
|
|
23
26
|
err?: (line: string) => void;
|
|
24
27
|
initial?: Policy;
|
|
@@ -32,7 +35,10 @@ export declare class PolicyStore {
|
|
|
32
35
|
/**
|
|
33
36
|
* Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
|
|
34
37
|
* than overwrite it), writes the change atomically keeping unknown keys, and swaps the
|
|
35
|
-
* in-memory policy.
|
|
38
|
+
* in-memory policy. `written` runs after that, still holding the lock (the `policy` op logs its
|
|
39
|
+
* outcome there, next to the change). Returns the new policy.
|
|
36
40
|
*/
|
|
37
|
-
update(change: (p: Policy) => Policy
|
|
41
|
+
update(change: (p: Policy) => Policy, opts?: {
|
|
42
|
+
written?: (p: Policy) => void;
|
|
43
|
+
}): Policy;
|
|
38
44
|
}
|
package/dist/policy-store.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { statSync } from "node:fs";
|
|
2
|
+
import { PolicyOpLog } from "./policy-ops.js";
|
|
2
3
|
import { policyPath, readPolicyFile, withPolicyLock, writePolicy } from "./state.js";
|
|
3
4
|
/** What identifies one version of policy.json: absent, or its inode, size and mtime. */
|
|
4
5
|
function versionOf(file) {
|
|
@@ -31,10 +32,13 @@ export class PolicyStore {
|
|
|
31
32
|
* the key is dropped at the next write).
|
|
32
33
|
*/
|
|
33
34
|
legacyNetworkOpen;
|
|
35
|
+
/** The outcomes of the `policy` ops this machine served, by op id (next to policy.json). */
|
|
36
|
+
ops;
|
|
34
37
|
constructor(dir, opts = {}) {
|
|
35
38
|
this.dir = dir;
|
|
36
39
|
this.file = policyPath(dir);
|
|
37
40
|
this.err = opts.err ?? (() => { });
|
|
41
|
+
this.ops = new PolicyOpLog(dir);
|
|
38
42
|
this.version = versionOf(this.file);
|
|
39
43
|
// Without an initial policy, an unreadable file throws here: the program does not start.
|
|
40
44
|
if (opts.initial !== undefined) {
|
|
@@ -77,15 +81,17 @@ export class PolicyStore {
|
|
|
77
81
|
/**
|
|
78
82
|
* Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
|
|
79
83
|
* than overwrite it), writes the change atomically keeping unknown keys, and swaps the
|
|
80
|
-
* in-memory policy.
|
|
84
|
+
* in-memory policy. `written` runs after that, still holding the lock (the `policy` op logs its
|
|
85
|
+
* outcome there, next to the change). Returns the new policy.
|
|
81
86
|
*/
|
|
82
|
-
update(change) {
|
|
87
|
+
update(change, opts = {}) {
|
|
83
88
|
return withPolicyLock(this.dir, () => {
|
|
84
89
|
const { policy, extra } = readPolicyFile(this.dir);
|
|
85
90
|
const next = change(policy);
|
|
86
91
|
writePolicy(this.dir, next, extra);
|
|
87
92
|
this.policy = next;
|
|
88
93
|
this.version = versionOf(this.file);
|
|
94
|
+
opts.written?.(next);
|
|
89
95
|
return next;
|
|
90
96
|
});
|
|
91
97
|
}
|
package/dist/server-ops.d.ts
CHANGED
|
@@ -57,7 +57,8 @@ export declare function summaryFacts(executor: Executor, ctx: OpContext): Summar
|
|
|
57
57
|
/**
|
|
58
58
|
* Runs one request and returns the answer plus its local audit line and, for an exec, its tier
|
|
59
59
|
* and isolation (for the local command log). A vanished device
|
|
60
|
-
* directory answers `fs_gone` for every operation except `stop` and `
|
|
60
|
+
* directory answers `fs_gone` for every operation except `stop`, `policy` and `policyStatus`.
|
|
61
|
+
* Never throws.
|
|
61
62
|
*/
|
|
62
63
|
export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
|
|
63
64
|
res: DeviceRes;
|
package/dist/server-ops.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isSandboxTier, tierAtMost, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { isPolicyOpId, isSandboxTier, tierAtMost, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { execIsolation } from "./exec/switch.js";
|
|
3
3
|
import { DeviceOpError } from "./exec/types.js";
|
|
4
4
|
import { grantedHosts, tierFacts } from "./policy.js";
|
|
@@ -121,7 +121,7 @@ function opHosts(list, key, fromApproval) {
|
|
|
121
121
|
* Every host is validated; the op is idempotent. Returns the result and the local audit line; a
|
|
122
122
|
* refusal carries its audit line too ({@link PolicyRefused}).
|
|
123
123
|
*/
|
|
124
|
-
function applyPolicyOp(store, args, facts) {
|
|
124
|
+
function applyPolicyOp(store, args, facts, written) {
|
|
125
125
|
const source = (args.source ?? {});
|
|
126
126
|
const fromApproval = source.approvalId !== undefined;
|
|
127
127
|
const add = [...new Set(opHosts(args.add, "add", fromApproval))];
|
|
@@ -173,7 +173,7 @@ function applyPolicyOp(store, args, facts) {
|
|
|
173
173
|
return p.tier === undefined || !tierAtMost(nextTier, p.tier);
|
|
174
174
|
};
|
|
175
175
|
let sandboxBackOn = false;
|
|
176
|
-
const
|
|
176
|
+
const change = (p) => {
|
|
177
177
|
// Judged against the file as it is now, inside the lock: a local `remoteGrants off` wins.
|
|
178
178
|
if (p.remoteGrants !== "owner") {
|
|
179
179
|
if (add.length > 0)
|
|
@@ -199,13 +199,87 @@ function applyPolicyOp(store, args, facts) {
|
|
|
199
199
|
isolation,
|
|
200
200
|
allowedDomains: [...kept, ...add.filter((h) => !present.has(h))],
|
|
201
201
|
};
|
|
202
|
-
}
|
|
202
|
+
};
|
|
203
|
+
const next = store.update(change, { written });
|
|
203
204
|
const also = sandboxBackOn ? "; isolation sandbox (tier changed by the deployment)" : "";
|
|
204
205
|
return {
|
|
205
206
|
result: { policy: policySummary(next, facts) },
|
|
206
207
|
detail: `policy ${what}${also} ${by}${approval}`,
|
|
207
208
|
};
|
|
208
209
|
}
|
|
210
|
+
/** The answer to a `policy` op whose outcome is logged already: the change is not made again. */
|
|
211
|
+
function answerFromLog(req, known, store, facts) {
|
|
212
|
+
if (known.outcome === "applied") {
|
|
213
|
+
return {
|
|
214
|
+
type: "res",
|
|
215
|
+
id: req.id,
|
|
216
|
+
ok: true,
|
|
217
|
+
result: { policy: policySummary(store.current(), facts) },
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
type: "res",
|
|
222
|
+
id: req.id,
|
|
223
|
+
ok: false,
|
|
224
|
+
error: { kind: known.kind ?? "policy", message: known.message ?? "refused" },
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* A `policy` op by its op id: logged `started` before anything is checked or written, then
|
|
229
|
+
* `applied` (inside the policy lock, right after the write) or `refused` with the message. An op
|
|
230
|
+
* id applied or refused before is answered from the log without applying it again. Throws like
|
|
231
|
+
* {@link applyPolicyOp}.
|
|
232
|
+
*/
|
|
233
|
+
function servePolicyOp(req, store, facts) {
|
|
234
|
+
const opId = req.args.opId;
|
|
235
|
+
if (!isPolicyOpId(opId)) {
|
|
236
|
+
throw new DeviceOpError("error", 'invalid request: field "opId" must be a valid op id');
|
|
237
|
+
}
|
|
238
|
+
const known = store.ops.claim(opId);
|
|
239
|
+
if (known !== undefined)
|
|
240
|
+
return { res: answerFromLog(req, known, store, facts) };
|
|
241
|
+
try {
|
|
242
|
+
const { result, detail } = applyPolicyOp(store, req.args, facts, () => {
|
|
243
|
+
try {
|
|
244
|
+
store.ops.recordHeld({ opId, outcome: "applied" });
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// the change stands; the log keeps `started` and the deployment learns it from the hello
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
return { res: { type: "res", id: req.id, ok: true, result }, detail };
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
// an op the log already says was applied stays applied (the log reports what the file holds)
|
|
254
|
+
if (store.ops.get(opId)?.outcome !== "applied") {
|
|
255
|
+
try {
|
|
256
|
+
store.ops.record({
|
|
257
|
+
opId,
|
|
258
|
+
outcome: "refused",
|
|
259
|
+
message: e instanceof Error ? e.message : String(e),
|
|
260
|
+
kind: e instanceof DeviceOpError ? e.kind : "error",
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
// nothing was applied; the log keeps `started`
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
throw e;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/** What the log says of an op id, with the summary now. Read-only. */
|
|
271
|
+
function policyStatus(store, args, facts) {
|
|
272
|
+
const opId = args?.opId;
|
|
273
|
+
if (!isPolicyOpId(opId)) {
|
|
274
|
+
throw new DeviceOpError("error", 'invalid request: field "opId" must be a valid op id');
|
|
275
|
+
}
|
|
276
|
+
const known = store.ops.get(opId);
|
|
277
|
+
return {
|
|
278
|
+
outcome: known?.outcome ?? "unknown",
|
|
279
|
+
policy: policySummary(store.current(), facts),
|
|
280
|
+
...(known?.outcome === "refused" && known.message !== undefined && { message: known.message }),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
209
283
|
/** The audit line of an exec whose grants applied (OS mode only: Docker mode ignores grants). */
|
|
210
284
|
function grantsDetail(executor, args, policy) {
|
|
211
285
|
if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
|
|
@@ -220,7 +294,8 @@ function grantsDetail(executor, args, policy) {
|
|
|
220
294
|
/**
|
|
221
295
|
* Runs one request and returns the answer plus its local audit line and, for an exec, its tier
|
|
222
296
|
* and isolation (for the local command log). A vanished device
|
|
223
|
-
* directory answers `fs_gone` for every operation except `stop` and `
|
|
297
|
+
* directory answers `fs_gone` for every operation except `stop`, `policy` and `policyStatus`.
|
|
298
|
+
* Never throws.
|
|
224
299
|
*/
|
|
225
300
|
export async function serveOp(executor, req, signal, ctx = {}) {
|
|
226
301
|
const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
|
|
@@ -228,7 +303,7 @@ export async function serveOp(executor, req, signal, ctx = {}) {
|
|
|
228
303
|
if (req.op === "stop")
|
|
229
304
|
return { res: ok(null) };
|
|
230
305
|
// The policy lives in the state directory, not the device directory.
|
|
231
|
-
if (req.op === "policy") {
|
|
306
|
+
if (req.op === "policy" || req.op === "policyStatus") {
|
|
232
307
|
if (ctx.policy === undefined) {
|
|
233
308
|
return {
|
|
234
309
|
res: {
|
|
@@ -239,8 +314,10 @@ export async function serveOp(executor, req, signal, ctx = {}) {
|
|
|
239
314
|
},
|
|
240
315
|
};
|
|
241
316
|
}
|
|
242
|
-
const
|
|
243
|
-
|
|
317
|
+
const facts = summaryFacts(executor, ctx);
|
|
318
|
+
if (req.op === "policyStatus")
|
|
319
|
+
return { res: ok(policyStatus(ctx.policy, req.args, facts)) };
|
|
320
|
+
return servePolicyOp(req, ctx.policy, facts);
|
|
244
321
|
}
|
|
245
322
|
if ((await executor.ensureRoot()) === "gone") {
|
|
246
323
|
return {
|
package/dist/state.d.ts
CHANGED
|
@@ -43,6 +43,8 @@ type Env = Record<string, string | undefined>;
|
|
|
43
43
|
export declare function stateDir(env?: Env, home?: string): string;
|
|
44
44
|
export declare function credentialPath(dir: string): string;
|
|
45
45
|
export declare function policyPath(dir: string): string;
|
|
46
|
+
/** The outcomes of the latest `policy` ops by op id (written under the policy lock). */
|
|
47
|
+
export declare function policyOpsPath(dir: string): string;
|
|
46
48
|
/** The lock file that serializes read-modify-writes of policy.json across processes. */
|
|
47
49
|
export declare function policyLockPath(dir: string): string;
|
|
48
50
|
/** The default working directory of a device: `~/capybara-device/<deviceId>`. */
|
package/dist/state.js
CHANGED
|
@@ -26,6 +26,10 @@ export function credentialPath(dir) {
|
|
|
26
26
|
export function policyPath(dir) {
|
|
27
27
|
return join(dir, "policy.json");
|
|
28
28
|
}
|
|
29
|
+
/** The outcomes of the latest `policy` ops by op id (written under the policy lock). */
|
|
30
|
+
export function policyOpsPath(dir) {
|
|
31
|
+
return join(dir, "policy-ops.json");
|
|
32
|
+
}
|
|
29
33
|
/** The lock file that serializes read-modify-writes of policy.json across processes. */
|
|
30
34
|
export function policyLockPath(dir) {
|
|
31
35
|
return join(dir, "policy.json.lock");
|
|
@@ -279,7 +283,12 @@ export function withPolicyLock(dir, fn, opts = {}) {
|
|
|
279
283
|
catch {
|
|
280
284
|
// Already gone.
|
|
281
285
|
}
|
|
282
|
-
|
|
286
|
+
try {
|
|
287
|
+
closeSync(fd);
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
// `fn` ran (a policy write may have happened): a failed close must not turn it into an error
|
|
291
|
+
}
|
|
283
292
|
}
|
|
284
293
|
}
|
|
285
294
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capybara-hq/device",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.7",
|
|
4
4
|
"description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@anthropic-ai/sandbox-runtime": "0.0.81",
|
|
36
36
|
"ws": "^8.18.0",
|
|
37
|
-
"@capybara-hq/plugin-sdk": "^0.1.0-rc.
|
|
37
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.20"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@types/ws": "^8.5.13"
|