@capybara-hq/device 0.1.0-rc.3 → 0.1.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +201 -11
- package/dist/args.d.ts +4 -2
- package/dist/args.js +21 -5
- package/dist/cli.d.ts +12 -2
- package/dist/cli.js +60 -8
- package/dist/client.d.ts +8 -0
- package/dist/client.js +37 -13
- package/dist/command-log.d.ts +10 -0
- package/dist/commands/policy.d.ts +66 -3
- package/dist/commands/policy.js +347 -31
- package/dist/commands/start.d.ts +9 -3
- package/dist/commands/start.js +18 -3
- package/dist/exec/docker.d.ts +41 -5
- package/dist/exec/docker.js +73 -19
- package/dist/exec/groups.d.ts +42 -0
- package/dist/exec/groups.js +100 -0
- package/dist/exec/host.d.ts +53 -0
- package/dist/exec/host.js +183 -0
- package/dist/exec/os.d.ts +73 -5
- package/dist/exec/os.js +186 -14
- package/dist/exec/shared.d.ts +28 -0
- package/dist/exec/shared.js +154 -1
- package/dist/exec/switch.d.ts +108 -0
- package/dist/exec/switch.js +214 -0
- package/dist/exec/types.d.ts +37 -3
- package/dist/network.d.ts +45 -0
- package/dist/network.js +161 -0
- package/dist/policy-store.d.ts +38 -0
- package/dist/policy-store.js +92 -0
- package/dist/policy.d.ts +102 -11
- package/dist/policy.js +155 -20
- package/dist/proxy-guard.d.ts +58 -0
- package/dist/proxy-guard.js +137 -0
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +65 -7
- package/dist/server-ops.js +289 -29
- package/dist/state.d.ts +44 -1
- package/dist/state.js +177 -9
- package/package.json +2 -2
package/dist/server-ops.d.ts
CHANGED
|
@@ -1,10 +1,68 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type DeviceLocalPolicySummary, type DeviceRes, type KernelReq } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { CommandLogEntry } from "./command-log.js";
|
|
3
|
-
import { type Executor } from "./exec/types.js";
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
import { type ExecIsolation, type Executor } from "./exec/types.js";
|
|
4
|
+
import { type TierLimits } from "./policy.js";
|
|
5
|
+
import type { PolicyStore } from "./policy-store.js";
|
|
6
|
+
import { type Policy } from "./state.js";
|
|
7
|
+
/** What this program has seen across requests (one per program run, kept over reconnects). */
|
|
8
|
+
export interface SeenState {
|
|
9
|
+
/** The tier limits of the latest exec: the org's ceiling and default, for the summary. */
|
|
10
|
+
limits?: TierLimits;
|
|
11
|
+
}
|
|
12
|
+
/** What a request may need beyond the executor. */
|
|
13
|
+
export interface OpContext {
|
|
14
|
+
/**
|
|
15
|
+
* The local policy this program serves (the one the executor reads). Without it the device
|
|
16
|
+
* answers the `policy` op as unsupported (and does not announce `policyOp` in its hello).
|
|
17
|
+
*/
|
|
18
|
+
policy?: PolicyStore;
|
|
19
|
+
/** Updated by every exec; read by the policy op's summary. */
|
|
20
|
+
seen?: SeenState;
|
|
21
|
+
/** The platform the summary describes (default: this process's). */
|
|
22
|
+
platform?: NodeJS.Platform;
|
|
23
|
+
}
|
|
24
|
+
/** The refusal of a `policy` op adding hosts under `remoteGrants: "off"`. */
|
|
25
|
+
export declare const REMOTE_GRANTS_OFF_MESSAGE: string;
|
|
26
|
+
/** The refusal of a `policy` op raising the tier under `remoteGrants: "off"`. */
|
|
27
|
+
export declare const REMOTE_TIER_OFF_MESSAGE: string;
|
|
6
28
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
29
|
+
* The refusal of a `policy` op that tries to turn the sandbox off: whatever `remoteGrants` says,
|
|
30
|
+
* only the person on the machine does that (spec §5.4).
|
|
9
31
|
*/
|
|
10
|
-
export declare
|
|
32
|
+
export declare const ISOLATION_REMOTE_MESSAGE: string;
|
|
33
|
+
/**
|
|
34
|
+
* The refusal of a widening `policy` op in Docker mode: the container has either no network or the
|
|
35
|
+
* whole internet, so one allowed domain would open everything.
|
|
36
|
+
*/
|
|
37
|
+
export declare const DOCKER_WIDENING_MESSAGE: string;
|
|
38
|
+
/** The local-log line for a finished request; `detail` is its audit line, `run` how an exec ran. */
|
|
39
|
+
export declare function logEntryFor(req: KernelReq, res: DeviceRes, now: Date, detail?: string, run?: Pick<ExecIsolation, "tier" | "isolation">): CommandLogEntry;
|
|
40
|
+
/** What the summary describes besides the policy file. */
|
|
41
|
+
export interface SummaryFacts {
|
|
42
|
+
mode: Executor["mode"];
|
|
43
|
+
/** The latest exec's tier limits; undefined before the first exec. */
|
|
44
|
+
limits?: TierLimits | undefined;
|
|
45
|
+
/** The localhost proxy guard found a local forwarding proxy (OS mode). */
|
|
46
|
+
proxyDetected?: boolean;
|
|
47
|
+
platform?: NodeJS.Platform;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The summary the kernel keeps of a local policy (hello, `policy` op result): the owner's tier,
|
|
51
|
+
* what it gives on this machine with the latest ceiling seen ({@link tierFacts}), and the
|
|
52
|
+
* isolation. Docker mode always reports `sandbox` (it ignores `isolation`).
|
|
53
|
+
*/
|
|
54
|
+
export declare function policySummary(p: Policy, facts: SummaryFacts): DeviceLocalPolicySummary;
|
|
55
|
+
/** The summary facts of a request context. */
|
|
56
|
+
export declare function summaryFacts(executor: Executor, ctx: OpContext): SummaryFacts;
|
|
57
|
+
/**
|
|
58
|
+
* Runs one request and returns the answer plus its local audit line and, for an exec, its tier
|
|
59
|
+
* and isolation (for the local command log). A vanished device
|
|
60
|
+
* directory answers `fs_gone` for every operation except `stop` and `policy`. Never throws.
|
|
61
|
+
*/
|
|
62
|
+
export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
|
|
63
|
+
res: DeviceRes;
|
|
64
|
+
detail?: string;
|
|
65
|
+
run?: ExecIsolation;
|
|
66
|
+
}>;
|
|
67
|
+
/** {@link serveOp} without the audit line. */
|
|
68
|
+
export declare function runOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<DeviceRes>;
|
package/dist/server-ops.js
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
|
+
import { isSandboxTier, tierAtMost, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { execIsolation } from "./exec/switch.js";
|
|
1
3
|
import { DeviceOpError } from "./exec/types.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
+
import { grantedHosts, tierFacts } from "./policy.js";
|
|
5
|
+
import { publicSuffixWildcard } from "./public-suffix.js";
|
|
6
|
+
import { DEFAULT_POLICY } from "./state.js";
|
|
7
|
+
/** The refusal of a `policy` op adding hosts under `remoteGrants: "off"`. */
|
|
8
|
+
export const REMOTE_GRANTS_OFF_MESSAGE = "This device does not accept network changes from the deployment; allow it locally: " +
|
|
9
|
+
"capybara-device policy add allowedDomains <host>";
|
|
10
|
+
/** The refusal of a `policy` op raising the tier under `remoteGrants: "off"`. */
|
|
11
|
+
export const REMOTE_TIER_OFF_MESSAGE = "This device does not accept a higher tier from the deployment; raise it locally: " +
|
|
12
|
+
"capybara-device policy set tier <tier>";
|
|
13
|
+
/**
|
|
14
|
+
* The refusal of a `policy` op that tries to turn the sandbox off: whatever `remoteGrants` says,
|
|
15
|
+
* only the person on the machine does that (spec §5.4).
|
|
16
|
+
*/
|
|
17
|
+
export const ISOLATION_REMOTE_MESSAGE = "This device turns its sandbox off only on the machine itself (capybara-device policy set " +
|
|
18
|
+
'isolation none); the deployment may only set isolation to "sandbox".';
|
|
19
|
+
/**
|
|
20
|
+
* The refusal of a widening `policy` op in Docker mode: the container has either no network or the
|
|
21
|
+
* whole internet, so one allowed domain would open everything.
|
|
22
|
+
*/
|
|
23
|
+
export const DOCKER_WIDENING_MESSAGE = "This device runs commands in Docker mode, which cannot limit network access per domain; " +
|
|
24
|
+
"switch the device to OS mode to allow single domains.";
|
|
25
|
+
/** The local-log line for a finished request; `detail` is its audit line, `run` how an exec ran. */
|
|
26
|
+
export function logEntryFor(req, res, now, detail, run) {
|
|
4
27
|
const exec = req.op === "exec" ? req.args : undefined;
|
|
5
28
|
const exitCode = res.ok && req.op === "exec"
|
|
6
29
|
? (res.result.exitCode ?? null)
|
|
@@ -11,25 +34,224 @@ export function logEntryFor(req, res, now) {
|
|
|
11
34
|
tag: exec ? exec.tag : null,
|
|
12
35
|
actor: exec ? { accountId: exec.actor.accountId } : null,
|
|
13
36
|
exitCode,
|
|
37
|
+
...(run !== undefined && { tier: run.tier, isolation: run.isolation }),
|
|
38
|
+
...(detail !== undefined && { detail }),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The summary the kernel keeps of a local policy (hello, `policy` op result): the owner's tier,
|
|
43
|
+
* what it gives on this machine with the latest ceiling seen ({@link tierFacts}), and the
|
|
44
|
+
* isolation. Docker mode always reports `sandbox` (it ignores `isolation`).
|
|
45
|
+
*/
|
|
46
|
+
export function policySummary(p, facts) {
|
|
47
|
+
const tf = tierFacts(p, facts.limits, {
|
|
48
|
+
mode: facts.mode,
|
|
49
|
+
proxyDetected: facts.proxyDetected ?? false,
|
|
50
|
+
...(facts.platform !== undefined && { platform: facts.platform }),
|
|
51
|
+
});
|
|
52
|
+
return {
|
|
53
|
+
...(p.tier !== undefined && { tier: p.tier }),
|
|
54
|
+
effectiveTier: tf.effectiveTier,
|
|
55
|
+
isolation: facts.mode === "docker" ? "sandbox" : p.isolation,
|
|
56
|
+
localhost: tf.localhost,
|
|
57
|
+
unixSockets: tf.unixSockets,
|
|
58
|
+
allowedDomains: [...p.allowedDomains],
|
|
59
|
+
remoteGrants: p.remoteGrants,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** The summary facts of a request context. */
|
|
63
|
+
export function summaryFacts(executor, ctx) {
|
|
64
|
+
return {
|
|
65
|
+
mode: executor.mode,
|
|
66
|
+
limits: ctx.seen?.limits,
|
|
67
|
+
proxyDetected: executor.proxyGuard?.().detected ?? false,
|
|
68
|
+
...(ctx.platform !== undefined && { platform: ctx.platform }),
|
|
14
69
|
};
|
|
15
70
|
}
|
|
71
|
+
/** A refused `policy` op, with the local audit line that records the attempt. */
|
|
72
|
+
class PolicyRefused extends DeviceOpError {
|
|
73
|
+
detail;
|
|
74
|
+
constructor(message, detail) {
|
|
75
|
+
super("policy", message);
|
|
76
|
+
this.detail = detail;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** A deployment-supplied string fit for the local log: no control or format characters. */
|
|
80
|
+
function clean(s, max) {
|
|
81
|
+
return String(s ?? "")
|
|
82
|
+
.replace(/[\p{Cc}\p{Cf}]/gu, "")
|
|
83
|
+
.slice(0, max);
|
|
84
|
+
}
|
|
85
|
+
/** Lowercased hosts of a `policy` op field; throws a `policy` error naming the first bad one. */
|
|
86
|
+
function opHosts(list, key, fromApproval) {
|
|
87
|
+
if (list === undefined)
|
|
88
|
+
return [];
|
|
89
|
+
if (!Array.isArray(list))
|
|
90
|
+
throw new DeviceOpError("policy", `${key} must be a list of hosts`);
|
|
91
|
+
return list.map((raw) => {
|
|
92
|
+
if (typeof raw !== "string")
|
|
93
|
+
throw new DeviceOpError("policy", `${key} must be a list of hosts`);
|
|
94
|
+
const host = raw.toLowerCase();
|
|
95
|
+
// A device-page wildcard over a whole public suffix is close to an open network, unconfirmed.
|
|
96
|
+
const tooBroad = key === "add" ? publicSuffixWildcard(host) : null;
|
|
97
|
+
if (tooBroad !== null)
|
|
98
|
+
throw new DeviceOpError("policy", tooBroad);
|
|
99
|
+
const errors = validateAllowHost(host);
|
|
100
|
+
if (errors.length > 0) {
|
|
101
|
+
throw new DeviceOpError("policy", `${JSON.stringify(raw)}: ${errors.join("; ")}`);
|
|
102
|
+
}
|
|
103
|
+
// An approval grants the exact host it asked about; wildcards come only from the device page.
|
|
104
|
+
if (key === "add" && fromApproval && host.startsWith("*.")) {
|
|
105
|
+
throw new DeviceOpError("policy", `${JSON.stringify(raw)}: an approval grants an exact host, not a wildcard`);
|
|
106
|
+
}
|
|
107
|
+
return host;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
16
110
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
111
|
+
* Applies a `policy` op to the local policy (a trust boundary: the deployment is not the owner).
|
|
112
|
+
*
|
|
113
|
+
* - `isolation`: only `"sandbox"` (narrowing) is ever applied; anything else is refused whatever
|
|
114
|
+
* `remoteGrants` says, so the deployment can never turn the sandbox off.
|
|
115
|
+
* - Widening (`add`; a `tier` above the file's; `tier: null` when the file has strict or dev,
|
|
116
|
+
* since the org's default is not known here) applies only under `remoteGrants: "owner"`, read from the
|
|
117
|
+
* file under the lock. Docker mode refuses `add` (its container cannot limit single domains).
|
|
118
|
+
* - Narrowing always applies. Any tier change turns an unsandboxed device's sandbox back on (it
|
|
119
|
+
* runs unsandboxed only on the owner's own local tier `open`).
|
|
120
|
+
*
|
|
121
|
+
* Every host is validated; the op is idempotent. Returns the result and the local audit line; a
|
|
122
|
+
* refusal carries its audit line too ({@link PolicyRefused}).
|
|
19
123
|
*/
|
|
20
|
-
|
|
124
|
+
function applyPolicyOp(store, args, facts) {
|
|
125
|
+
const source = (args.source ?? {});
|
|
126
|
+
const fromApproval = source.approvalId !== undefined;
|
|
127
|
+
const add = [...new Set(opHosts(args.add, "add", fromApproval))];
|
|
128
|
+
const remove = [...new Set(opHosts(args.remove, "remove", fromApproval))];
|
|
129
|
+
// Read as unknown: the frame parser may have been bypassed, so nothing is assumed of the shape.
|
|
130
|
+
const rawTier = args.tier;
|
|
131
|
+
const rawIsolation = args.isolation;
|
|
132
|
+
const parts = [];
|
|
133
|
+
if (add.length > 0)
|
|
134
|
+
parts.push(`add ${add.join(", ")}`);
|
|
135
|
+
if (remove.length > 0)
|
|
136
|
+
parts.push(`remove ${remove.join(", ")}`);
|
|
137
|
+
if (rawTier !== undefined) {
|
|
138
|
+
parts.push(`tier ${rawTier === null ? "org default" : clean(String(rawTier), 40)}`);
|
|
139
|
+
}
|
|
140
|
+
if (rawIsolation !== undefined)
|
|
141
|
+
parts.push(`isolation ${clean(String(rawIsolation), 40)}`);
|
|
142
|
+
const by = `by ${clean(source.accountName, 100)} (${clean(source.accountId, 100)}) ` +
|
|
143
|
+
`via ${clean(source.via, 10)}`;
|
|
144
|
+
const approval = fromApproval ? `, approval ${clean(source.approvalId, 100)}` : "";
|
|
145
|
+
const what = parts.length > 0 ? parts.join("; ") : "unchanged";
|
|
146
|
+
const refused = `policy refused ${what} ${by}${approval}`;
|
|
147
|
+
if (rawIsolation !== undefined && rawIsolation !== "sandbox") {
|
|
148
|
+
// Turning the sandbox off is decided on the machine only.
|
|
149
|
+
throw new PolicyRefused(ISOLATION_REMOTE_MESSAGE, refused);
|
|
150
|
+
}
|
|
151
|
+
if (rawTier !== undefined && rawTier !== null && !isSandboxTier(rawTier)) {
|
|
152
|
+
throw new PolicyRefused(`unknown tier ${clean(String(rawTier), 40)}`, refused);
|
|
153
|
+
}
|
|
154
|
+
const nextTier = rawTier;
|
|
155
|
+
const both = add.find((h) => remove.includes(h));
|
|
156
|
+
if (both !== undefined) {
|
|
157
|
+
throw new DeviceOpError("policy", `${both} is both added and removed`);
|
|
158
|
+
}
|
|
159
|
+
if (add.length > 0 && facts.mode === "docker") {
|
|
160
|
+
throw new PolicyRefused(DOCKER_WIDENING_MESSAGE, refused);
|
|
161
|
+
}
|
|
162
|
+
// Docker mode takes a tier change under remoteGrants owner: raising it to dev does not open the
|
|
163
|
+
// container's network bridge (the dev hosts do not count there), only open does (spec §5.2).
|
|
164
|
+
// A tier above the file's, or following the org's default (not known here) when the file has
|
|
165
|
+
// a tier, may widen.
|
|
166
|
+
const widensTier = (p) => {
|
|
167
|
+
if (nextTier === undefined || nextTier === "strict")
|
|
168
|
+
return false;
|
|
169
|
+
// The org's default is at most its ceiling, which is at most open: following it from open
|
|
170
|
+
// never widens. From strict or dev it may.
|
|
171
|
+
if (nextTier === null)
|
|
172
|
+
return p.tier !== undefined && p.tier !== "open";
|
|
173
|
+
return p.tier === undefined || !tierAtMost(nextTier, p.tier);
|
|
174
|
+
};
|
|
175
|
+
let sandboxBackOn = false;
|
|
176
|
+
const next = store.update((p) => {
|
|
177
|
+
// Judged against the file as it is now, inside the lock: a local `remoteGrants off` wins.
|
|
178
|
+
if (p.remoteGrants !== "owner") {
|
|
179
|
+
if (add.length > 0)
|
|
180
|
+
throw new PolicyRefused(REMOTE_GRANTS_OFF_MESSAGE, refused);
|
|
181
|
+
if (widensTier(p))
|
|
182
|
+
throw new PolicyRefused(REMOTE_TIER_OFF_MESSAGE, refused);
|
|
183
|
+
}
|
|
184
|
+
const kept = p.allowedDomains.filter((d) => !remove.includes(d.toLowerCase()));
|
|
185
|
+
const present = new Set(kept.map((d) => d.toLowerCase()));
|
|
186
|
+
const { tier: _old, ...rest } = p;
|
|
187
|
+
const tier = nextTier === undefined ? p.tier : (nextTier ?? undefined);
|
|
188
|
+
let isolation = rawIsolation === "sandbox" ? "sandbox" : p.isolation;
|
|
189
|
+
// A device runs unsandboxed only on the owner's local tier `open`: any tier change from the
|
|
190
|
+
// deployment turns the sandbox back on, so the deployment is never the last step that makes
|
|
191
|
+
// (or keeps) a device unsandboxed.
|
|
192
|
+
if (isolation === "none" && nextTier !== undefined && tier !== p.tier) {
|
|
193
|
+
isolation = "sandbox";
|
|
194
|
+
sandboxBackOn = true;
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
...rest,
|
|
198
|
+
...(tier !== undefined && { tier }),
|
|
199
|
+
isolation,
|
|
200
|
+
allowedDomains: [...kept, ...add.filter((h) => !present.has(h))],
|
|
201
|
+
};
|
|
202
|
+
});
|
|
203
|
+
const also = sandboxBackOn ? "; isolation sandbox (tier changed by the deployment)" : "";
|
|
204
|
+
return {
|
|
205
|
+
result: { policy: policySummary(next, facts) },
|
|
206
|
+
detail: `policy ${what}${also} ${by}${approval}`,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
/** The audit line of an exec whose grants applied (OS mode only: Docker mode ignores grants). */
|
|
210
|
+
function grantsDetail(executor, args, policy) {
|
|
211
|
+
if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
const hosts = grantedHosts(policy, args.limits, args.grants);
|
|
215
|
+
if (hosts.length === 0)
|
|
216
|
+
return undefined;
|
|
217
|
+
const s = args.grants.source;
|
|
218
|
+
return `grants ${clean(s.kind, 10)} ${clean(s.id, 100)} by ${clean(s.accountId, 100)}: ${hosts.join(", ")}`;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Runs one request and returns the answer plus its local audit line and, for an exec, its tier
|
|
222
|
+
* and isolation (for the local command log). A vanished device
|
|
223
|
+
* directory answers `fs_gone` for every operation except `stop` and `policy`. Never throws.
|
|
224
|
+
*/
|
|
225
|
+
export async function serveOp(executor, req, signal, ctx = {}) {
|
|
21
226
|
const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
|
|
22
227
|
try {
|
|
23
228
|
if (req.op === "stop")
|
|
24
|
-
return ok(null);
|
|
229
|
+
return { res: ok(null) };
|
|
230
|
+
// The policy lives in the state directory, not the device directory.
|
|
231
|
+
if (req.op === "policy") {
|
|
232
|
+
if (ctx.policy === undefined) {
|
|
233
|
+
return {
|
|
234
|
+
res: {
|
|
235
|
+
type: "res",
|
|
236
|
+
id: req.id,
|
|
237
|
+
ok: false,
|
|
238
|
+
error: { kind: "error", message: "unsupported operation" },
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
const { result, detail } = applyPolicyOp(ctx.policy, req.args, summaryFacts(executor, ctx));
|
|
243
|
+
return { res: ok(result), detail };
|
|
244
|
+
}
|
|
25
245
|
if ((await executor.ensureRoot()) === "gone") {
|
|
26
246
|
return {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
247
|
+
res: {
|
|
248
|
+
type: "res",
|
|
249
|
+
id: req.id,
|
|
250
|
+
ok: false,
|
|
251
|
+
error: {
|
|
252
|
+
kind: "fs_gone",
|
|
253
|
+
message: "The device directory on this machine existed and is gone. It is not recreated automatically.",
|
|
254
|
+
},
|
|
33
255
|
},
|
|
34
256
|
};
|
|
35
257
|
}
|
|
@@ -37,38 +259,76 @@ export async function runOp(executor, req, signal) {
|
|
|
37
259
|
signal.throwIfAborted();
|
|
38
260
|
switch (req.op) {
|
|
39
261
|
case "create":
|
|
40
|
-
return ok({ roots: executor.roots });
|
|
41
|
-
case "exec":
|
|
42
|
-
|
|
262
|
+
return { res: ok({ roots: executor.roots }) };
|
|
263
|
+
case "exec": {
|
|
264
|
+
const args = req.args;
|
|
265
|
+
if (ctx.seen !== undefined) {
|
|
266
|
+
ctx.seen.limits = {
|
|
267
|
+
tier: args.limits.tier,
|
|
268
|
+
...(args.limits.defaultTier !== undefined && { defaultTier: args.limits.defaultTier }),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
// One decision per command, on one read of the policy: the executor runs it and the
|
|
272
|
+
// local log records it. Grants are judged on the same read.
|
|
273
|
+
const policy = ctx.policy?.current();
|
|
274
|
+
const run = execIsolation(policy ?? DEFAULT_POLICY, args.limits, executor.mode);
|
|
275
|
+
// Refused or not, these limits are the latest decision file operations follow.
|
|
276
|
+
executor.noteLimits?.(args.limits);
|
|
277
|
+
if (run.refusal !== undefined) {
|
|
278
|
+
return { ...errorAnswer(req, new DeviceOpError("policy", run.refusal)), run };
|
|
279
|
+
}
|
|
280
|
+
const detail = grantsDetail(executor, args, policy);
|
|
281
|
+
try {
|
|
282
|
+
const result = policy !== undefined && executor.execDecided !== undefined
|
|
283
|
+
? await executor.execDecided(args, signal, run, policy)
|
|
284
|
+
: await executor.exec(args, signal);
|
|
285
|
+
const res = ok(result);
|
|
286
|
+
return detail === undefined ? { res, run } : { res, detail, run };
|
|
287
|
+
}
|
|
288
|
+
catch (e) {
|
|
289
|
+
return { ...errorAnswer(req, e), run };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
43
292
|
case "readFile": {
|
|
44
293
|
const a = req.args;
|
|
45
294
|
const r = await executor.readFile(a.path, a.maxBytes);
|
|
46
|
-
return
|
|
47
|
-
|
|
48
|
-
|
|
295
|
+
return {
|
|
296
|
+
res: ok(r === null
|
|
297
|
+
? null
|
|
298
|
+
: { dataB64: Buffer.from(r.data).toString("base64"), truncated: r.truncated }),
|
|
299
|
+
};
|
|
49
300
|
}
|
|
50
301
|
case "writeFile": {
|
|
51
302
|
const a = req.args;
|
|
52
303
|
await executor.writeFile(a.path, Buffer.from(a.dataB64, "base64"));
|
|
53
|
-
return ok(null);
|
|
304
|
+
return { res: ok(null) };
|
|
54
305
|
}
|
|
55
306
|
case "stat":
|
|
56
|
-
return ok(await executor.stat(req.args.path));
|
|
307
|
+
return { res: ok(await executor.stat(req.args.path)) };
|
|
57
308
|
case "killTagged":
|
|
58
309
|
await executor.killTagged(req.args.tags);
|
|
59
|
-
return ok(null);
|
|
310
|
+
return { res: ok(null) };
|
|
60
311
|
case "killAll":
|
|
61
312
|
await executor.killAll();
|
|
62
|
-
return ok(null);
|
|
313
|
+
return { res: ok(null) };
|
|
63
314
|
}
|
|
64
315
|
}
|
|
65
316
|
catch (e) {
|
|
66
|
-
|
|
67
|
-
return {
|
|
68
|
-
type: "res",
|
|
69
|
-
id: req.id,
|
|
70
|
-
ok: false,
|
|
71
|
-
error: { kind, message: e instanceof Error ? e.message : String(e) },
|
|
72
|
-
};
|
|
317
|
+
return errorAnswer(req, e);
|
|
73
318
|
}
|
|
74
319
|
}
|
|
320
|
+
/** The error answer of a failed request, with a refused policy op's audit line. */
|
|
321
|
+
function errorAnswer(req, e) {
|
|
322
|
+
const kind = e instanceof DeviceOpError ? e.kind : "error";
|
|
323
|
+
const res = {
|
|
324
|
+
type: "res",
|
|
325
|
+
id: req.id,
|
|
326
|
+
ok: false,
|
|
327
|
+
error: { kind, message: e instanceof Error ? e.message : String(e) },
|
|
328
|
+
};
|
|
329
|
+
return e instanceof PolicyRefused ? { res, detail: e.detail } : { res };
|
|
330
|
+
}
|
|
331
|
+
/** {@link serveOp} without the audit line. */
|
|
332
|
+
export async function runOp(executor, req, signal, ctx = {}) {
|
|
333
|
+
return (await serveOp(executor, req, signal, ctx)).res;
|
|
334
|
+
}
|
package/dist/state.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type DeviceRemoteGrants, type SandboxTier } from "@capybara-hq/plugin-sdk";
|
|
1
2
|
import type { DeviceMode } from "./args.js";
|
|
2
3
|
/** What `login` stores: how to reach the deployment and who this machine is there. */
|
|
3
4
|
export interface Credential {
|
|
@@ -19,6 +20,21 @@ export interface Policy {
|
|
|
19
20
|
allowCredentials: string[];
|
|
20
21
|
cpu: number | null;
|
|
21
22
|
memoryMb: number | null;
|
|
23
|
+
/**
|
|
24
|
+
* The sandbox tier the owner chose for this machine; absent = the org's default. Commands run at
|
|
25
|
+
* this tier cut to the org's ceiling.
|
|
26
|
+
*/
|
|
27
|
+
tier?: SandboxTier;
|
|
28
|
+
/** `sandbox` (default), or `none`: commands run without a sandbox (only with tier `open`). */
|
|
29
|
+
isolation: "sandbox" | "none";
|
|
30
|
+
/** `auto` (default): localhost access unless a local proxy is detected; `allow`: always. */
|
|
31
|
+
localhost: "auto" | "allow";
|
|
32
|
+
/**
|
|
33
|
+
* `owner` (default): the deployment may widen this policy (the `policy` op's `add` and a higher
|
|
34
|
+
* `tier`, an exec's run or task grants) on the device owner's decision. `off`: only narrowing
|
|
35
|
+
* changes from the deployment are accepted. Set only locally.
|
|
36
|
+
*/
|
|
37
|
+
remoteGrants: DeviceRemoteGrants;
|
|
22
38
|
}
|
|
23
39
|
export declare const DEFAULT_MAX_FRAME_BYTES: number;
|
|
24
40
|
export declare const DEFAULT_POLICY: Policy;
|
|
@@ -27,6 +43,8 @@ type Env = Record<string, string | undefined>;
|
|
|
27
43
|
export declare function stateDir(env?: Env, home?: string): string;
|
|
28
44
|
export declare function credentialPath(dir: string): string;
|
|
29
45
|
export declare function policyPath(dir: string): string;
|
|
46
|
+
/** The lock file that serializes read-modify-writes of policy.json across processes. */
|
|
47
|
+
export declare function policyLockPath(dir: string): string;
|
|
30
48
|
/** The default working directory of a device: `~/capybara-device/<deviceId>`. */
|
|
31
49
|
export declare function defaultWorkDir(deviceId: string, home?: string): string;
|
|
32
50
|
export declare function writePrivate(file: string, text: string): void;
|
|
@@ -36,5 +54,30 @@ export declare function readCredential(dir: string): Credential | undefined;
|
|
|
36
54
|
export declare function removeCredential(dir: string): boolean;
|
|
37
55
|
/** The local policy (defaults when absent). Throws, naming the file, on bad JSON or field types. */
|
|
38
56
|
export declare function readPolicy(dir: string): Policy;
|
|
39
|
-
|
|
57
|
+
/** {@link readPolicyFile}'s result. */
|
|
58
|
+
export interface PolicyFile {
|
|
59
|
+
policy: Policy;
|
|
60
|
+
/** The file's keys this version does not know (legacy keys excluded). */
|
|
61
|
+
extra: Record<string, unknown>;
|
|
62
|
+
/** The file still has the legacy `network: "open"` (now tier `open`; worth a notice at start). */
|
|
63
|
+
legacyNetworkOpen: boolean;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The local policy plus the file's keys this version does not know (kept on every write, so an
|
|
67
|
+
* older program never drops a newer one's settings). Throws like {@link readPolicy}.
|
|
68
|
+
*/
|
|
69
|
+
export declare function readPolicyFile(dir: string): PolicyFile;
|
|
70
|
+
/** Writes policy.json atomically (owner-only); `extra` are unknown keys to keep (never legacy ones). */
|
|
71
|
+
export declare function writePolicy(dir: string, policy: Policy, extra?: Record<string, unknown>): void;
|
|
72
|
+
/**
|
|
73
|
+
* Runs `fn` holding policy.json.lock (created with O_EXCL), so a read-modify-write of the policy
|
|
74
|
+
* by this program and a concurrent `capybara-device policy` never loses an update. A lock older
|
|
75
|
+
* than 10 s whose holder pid no longer runs is stale and taken over; a held one is retried for
|
|
76
|
+
* about 2 s, then this throws. The lock is removed at the end only while it is still this
|
|
77
|
+
* holder's file.
|
|
78
|
+
*/
|
|
79
|
+
export declare function withPolicyLock<T>(dir: string, fn: () => T, opts?: {
|
|
80
|
+
waitMs?: number;
|
|
81
|
+
now?: () => number;
|
|
82
|
+
}): T;
|
|
40
83
|
export {};
|