@capybara-hq/device 0.1.0-rc.8 → 0.1.0-rc.9
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 +90 -179
- package/dist/api.d.ts +5 -0
- package/dist/args.d.ts +7 -2
- package/dist/args.js +33 -16
- package/dist/cli.d.ts +7 -5
- package/dist/cli.js +20 -31
- package/dist/client.d.ts +0 -2
- package/dist/client.js +9 -10
- package/dist/command-log.d.ts +3 -5
- package/dist/commands/login.js +55 -1
- package/dist/commands/mode.d.ts +52 -0
- package/dist/commands/mode.js +108 -0
- package/dist/commands/policy.d.ts +11 -65
- package/dist/commands/policy.js +62 -249
- package/dist/commands/start.d.ts +2 -2
- package/dist/commands/start.js +14 -6
- package/dist/commands/status.js +11 -3
- package/dist/exec/docker.d.ts +22 -30
- package/dist/exec/docker.js +81 -69
- package/dist/exec/fs-helper.d.ts +13 -8
- package/dist/exec/fs-helper.js +30 -12
- package/dist/exec/host.d.ts +8 -8
- package/dist/exec/host.js +9 -9
- package/dist/exec/os.d.ts +36 -69
- package/dist/exec/os.js +65 -159
- package/dist/exec/sandbox-messages.d.ts +14 -0
- package/dist/exec/sandbox-messages.js +21 -0
- package/dist/exec/shared.d.ts +21 -36
- package/dist/exec/shared.js +30 -164
- package/dist/exec/switch.d.ts +38 -55
- package/dist/exec/switch.js +58 -108
- package/dist/exec/types.d.ts +8 -18
- package/dist/index.d.ts +1 -1
- package/dist/network.d.ts +7 -7
- package/dist/network.js +11 -18
- package/dist/policy-store.d.ts +7 -8
- package/dist/policy-store.js +11 -15
- package/dist/policy.d.ts +25 -100
- package/dist/policy.js +44 -146
- package/dist/server-ops.d.ts +15 -35
- package/dist/server-ops.js +36 -117
- package/dist/state.d.ts +15 -16
- package/dist/state.js +38 -36
- package/package.json +2 -2
- package/dist/proxy-guard.d.ts +0 -58
- package/dist/proxy-guard.js +0 -137
package/dist/server-ops.js
CHANGED
|
@@ -1,27 +1,10 @@
|
|
|
1
|
-
import { isPolicyOpId,
|
|
2
|
-
import { execIsolation } from "./exec/switch.js";
|
|
1
|
+
import { isPolicyOpId, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
3
2
|
import { DeviceOpError } from "./exec/types.js";
|
|
4
|
-
import {
|
|
3
|
+
import { effectiveMode, grantedHosts } from "./policy.js";
|
|
5
4
|
import { publicSuffixWildcard } from "./public-suffix.js";
|
|
6
5
|
import { DEFAULT_POLICY } from "./state.js";
|
|
7
|
-
/** The refusal of a `policy` op
|
|
8
|
-
export const
|
|
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.";
|
|
6
|
+
/** The refusal of a `policy` op that tries to turn auto mode on from the deployment. */
|
|
7
|
+
export const MODE_ON_DEVICE_MESSAGE = "The device's mode can only be changed on the machine: run `capybara-device mode auto`.";
|
|
25
8
|
/** The local-log line for a finished request; `detail` is its audit line, `run` how an exec ran. */
|
|
26
9
|
export function logEntryFor(req, res, now, detail, run) {
|
|
27
10
|
const exec = req.op === "exec" ? req.args : undefined;
|
|
@@ -34,29 +17,18 @@ export function logEntryFor(req, res, now, detail, run) {
|
|
|
34
17
|
tag: exec ? exec.tag : null,
|
|
35
18
|
actor: exec ? { accountId: exec.actor.accountId } : null,
|
|
36
19
|
exitCode,
|
|
37
|
-
...(run !== undefined && {
|
|
20
|
+
...(run !== undefined && { mode: run.mode }),
|
|
38
21
|
...(detail !== undefined && { detail }),
|
|
39
22
|
};
|
|
40
23
|
}
|
|
41
24
|
/**
|
|
42
|
-
* The summary the kernel keeps of a local policy (hello, `policy` op result): the
|
|
43
|
-
*
|
|
44
|
-
* isolation. Docker mode always reports `sandbox` (it ignores `isolation`).
|
|
25
|
+
* The summary the kernel keeps of a local policy (hello, `policy` op result): the effective mode
|
|
26
|
+
* (the owner's choice cut to the latest ceiling seen) and the device's sandbox-mode allowlist.
|
|
45
27
|
*/
|
|
46
28
|
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
29
|
return {
|
|
53
|
-
|
|
54
|
-
effectiveTier: tf.effectiveTier,
|
|
55
|
-
isolation: facts.mode === "docker" ? "sandbox" : p.isolation,
|
|
56
|
-
localhost: tf.localhost,
|
|
57
|
-
unixSockets: tf.unixSockets,
|
|
30
|
+
mode: facts.limits === undefined ? p.mode : effectiveMode(p, facts.limits),
|
|
58
31
|
allowedDomains: [...p.allowedDomains],
|
|
59
|
-
remoteGrants: p.remoteGrants,
|
|
60
32
|
};
|
|
61
33
|
}
|
|
62
34
|
/** The summary facts of a request context. */
|
|
@@ -64,8 +36,6 @@ export function summaryFacts(executor, ctx) {
|
|
|
64
36
|
return {
|
|
65
37
|
mode: executor.mode,
|
|
66
38
|
limits: ctx.seen?.limits,
|
|
67
|
-
proxyDetected: executor.proxyGuard?.().detected ?? false,
|
|
68
|
-
...(ctx.platform !== undefined && { platform: ctx.platform }),
|
|
69
39
|
};
|
|
70
40
|
}
|
|
71
41
|
/** A refused `policy` op, with the local audit line that records the attempt. */
|
|
@@ -110,16 +80,13 @@ function opHosts(list, key, fromApproval) {
|
|
|
110
80
|
/**
|
|
111
81
|
* Applies a `policy` op to the local policy (a trust boundary: the deployment is not the owner).
|
|
112
82
|
*
|
|
113
|
-
* - `
|
|
114
|
-
*
|
|
115
|
-
* -
|
|
116
|
-
*
|
|
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`).
|
|
83
|
+
* - `mode`: only `"sandbox"` (narrowing) is ever applied; `"auto"` is refused, so the deployment
|
|
84
|
+
* can never turn auto mode on. Only `capybara-device mode auto` on the machine does.
|
|
85
|
+
* - `add` / `remove` change the sandbox-mode allowlist; every host is validated (an approval adds
|
|
86
|
+
* an exact host, never a wildcard).
|
|
120
87
|
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
88
|
+
* The op is idempotent. Returns the result and the local audit line; a refusal carries its audit
|
|
89
|
+
* line too ({@link PolicyRefused}).
|
|
123
90
|
*/
|
|
124
91
|
function applyPolicyOp(store, args, facts, written) {
|
|
125
92
|
const source = (args.source ?? {});
|
|
@@ -127,84 +94,40 @@ function applyPolicyOp(store, args, facts, written) {
|
|
|
127
94
|
const add = [...new Set(opHosts(args.add, "add", fromApproval))];
|
|
128
95
|
const remove = [...new Set(opHosts(args.remove, "remove", fromApproval))];
|
|
129
96
|
// Read as unknown: the frame parser may have been bypassed, so nothing is assumed of the shape.
|
|
130
|
-
const
|
|
131
|
-
const rawIsolation = args.isolation;
|
|
97
|
+
const rawMode = args.mode;
|
|
132
98
|
const parts = [];
|
|
133
99
|
if (add.length > 0)
|
|
134
100
|
parts.push(`add ${add.join(", ")}`);
|
|
135
101
|
if (remove.length > 0)
|
|
136
102
|
parts.push(`remove ${remove.join(", ")}`);
|
|
137
|
-
if (
|
|
138
|
-
parts.push(`
|
|
139
|
-
}
|
|
140
|
-
if (rawIsolation !== undefined)
|
|
141
|
-
parts.push(`isolation ${clean(String(rawIsolation), 40)}`);
|
|
103
|
+
if (rawMode !== undefined)
|
|
104
|
+
parts.push(`mode ${clean(String(rawMode), 40)}`);
|
|
142
105
|
const by = `by ${clean(source.accountName, 100)} (${clean(source.accountId, 100)}) ` +
|
|
143
106
|
`via ${clean(source.via, 10)}`;
|
|
144
107
|
const approval = fromApproval ? `, approval ${clean(source.approvalId, 100)}` : "";
|
|
145
108
|
const what = parts.length > 0 ? parts.join("; ") : "unchanged";
|
|
146
109
|
const refused = `policy refused ${what} ${by}${approval}`;
|
|
147
|
-
if (
|
|
148
|
-
// Turning
|
|
149
|
-
throw new PolicyRefused(
|
|
110
|
+
if (rawMode !== undefined && rawMode !== "sandbox") {
|
|
111
|
+
// Turning auto mode on is decided on the machine only (spec §4.1).
|
|
112
|
+
throw new PolicyRefused(MODE_ON_DEVICE_MESSAGE, refused);
|
|
150
113
|
}
|
|
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
114
|
const both = add.find((h) => remove.includes(h));
|
|
156
115
|
if (both !== undefined) {
|
|
157
116
|
throw new DeviceOpError("policy", `${both} is both added and removed`);
|
|
158
117
|
}
|
|
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
118
|
const change = (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
119
|
const kept = p.allowedDomains.filter((d) => !remove.includes(d.toLowerCase()));
|
|
185
120
|
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
121
|
return {
|
|
197
|
-
...
|
|
198
|
-
|
|
199
|
-
isolation,
|
|
122
|
+
...p,
|
|
123
|
+
mode: rawMode === "sandbox" ? "sandbox" : p.mode,
|
|
200
124
|
allowedDomains: [...kept, ...add.filter((h) => !present.has(h))],
|
|
201
125
|
};
|
|
202
126
|
};
|
|
203
127
|
const next = store.update(change, { written });
|
|
204
|
-
const also = sandboxBackOn ? "; isolation sandbox (tier changed by the deployment)" : "";
|
|
205
128
|
return {
|
|
206
129
|
result: { policy: policySummary(next, facts) },
|
|
207
|
-
detail: `policy ${what}
|
|
130
|
+
detail: `policy ${what} ${by}${approval}`,
|
|
208
131
|
};
|
|
209
132
|
}
|
|
210
133
|
/** The answer to a `policy` op whose outcome is logged already: the change is not made again. */
|
|
@@ -280,22 +203,23 @@ function policyStatus(store, args, facts) {
|
|
|
280
203
|
...(known?.outcome === "refused" && known.message !== undefined && { message: known.message }),
|
|
281
204
|
};
|
|
282
205
|
}
|
|
283
|
-
/** The audit line of an exec whose grants applied (
|
|
206
|
+
/** The audit line of an exec whose grants applied (sandbox mode only: auto mode ignores grants). */
|
|
284
207
|
function grantsDetail(executor, args, policy) {
|
|
285
208
|
if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
|
|
286
209
|
return undefined;
|
|
287
210
|
}
|
|
288
|
-
|
|
211
|
+
if (effectiveMode(policy, args.limits) !== "sandbox")
|
|
212
|
+
return undefined;
|
|
213
|
+
const hosts = grantedHosts(args.limits, args.grants);
|
|
289
214
|
if (hosts.length === 0)
|
|
290
215
|
return undefined;
|
|
291
216
|
const s = args.grants.source;
|
|
292
217
|
return `grants ${clean(s.kind, 10)} ${clean(s.id, 100)} by ${clean(s.accountId, 100)}: ${hosts.join(", ")}`;
|
|
293
218
|
}
|
|
294
219
|
/**
|
|
295
|
-
* Runs one request and returns the answer plus its local audit line and, for an exec, its
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
* Never throws.
|
|
220
|
+
* Runs one request and returns the answer plus its local audit line and, for an exec, its mode
|
|
221
|
+
* (for the local command log). A vanished device directory answers `fs_gone` for every operation
|
|
222
|
+
* except `stop`, `policy` and `policyStatus`. Never throws.
|
|
299
223
|
*/
|
|
300
224
|
export async function serveOp(executor, req, signal, ctx = {}) {
|
|
301
225
|
const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
|
|
@@ -339,21 +263,16 @@ export async function serveOp(executor, req, signal, ctx = {}) {
|
|
|
339
263
|
return { res: ok({ roots: executor.roots }) };
|
|
340
264
|
case "exec": {
|
|
341
265
|
const args = req.args;
|
|
342
|
-
if (ctx.seen !== undefined)
|
|
343
|
-
ctx.seen.limits = {
|
|
344
|
-
tier: args.limits.tier,
|
|
345
|
-
...(args.limits.defaultTier !== undefined && { defaultTier: args.limits.defaultTier }),
|
|
346
|
-
};
|
|
347
|
-
}
|
|
266
|
+
if (ctx.seen !== undefined)
|
|
267
|
+
ctx.seen.limits = { mode: args.limits.mode };
|
|
348
268
|
// One decision per command, on one read of the policy: the executor runs it and the
|
|
349
269
|
// local log records it. Grants are judged on the same read.
|
|
350
270
|
const policy = ctx.policy?.current();
|
|
351
|
-
const run =
|
|
352
|
-
|
|
271
|
+
const run = {
|
|
272
|
+
mode: effectiveMode(policy ?? DEFAULT_POLICY, args.limits),
|
|
273
|
+
};
|
|
274
|
+
// These limits are the latest decision file operations follow.
|
|
353
275
|
executor.noteLimits?.(args.limits);
|
|
354
|
-
if (run.refusal !== undefined) {
|
|
355
|
-
return { ...errorAnswer(req, new DeviceOpError("policy", run.refusal)), run };
|
|
356
|
-
}
|
|
357
276
|
const detail = grantsDetail(executor, args, policy);
|
|
358
277
|
try {
|
|
359
278
|
const result = policy !== undefined && executor.execDecided !== undefined
|
package/dist/state.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { type DeviceRemoteGrants, type SandboxTier } from "@capybara-hq/plugin-sdk";
|
|
2
1
|
import type { DeviceMode } from "./args.js";
|
|
3
2
|
/** What `login` stores: how to reach the deployment and who this machine is there. */
|
|
4
3
|
export interface Credential {
|
|
@@ -14,6 +13,12 @@ export interface Credential {
|
|
|
14
13
|
/** The deployment's `devices.local.maxFrameBytes`: no frame this program sends is larger. */
|
|
15
14
|
maxFrameBytes: number;
|
|
16
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* How commands run on this machine: `auto` (no OS sandbox; the owner's files, credentials and
|
|
18
|
+
* network, with every command reviewed by the deployment) or `sandbox` (today's strict
|
|
19
|
+
* `sandbox-runtime` profile). Not `DeviceMode`, which is the run mode (`os | docker`).
|
|
20
|
+
*/
|
|
21
|
+
export type SandboxMode = "auto" | "sandbox";
|
|
17
22
|
/** Local limits the person sets for this machine. */
|
|
18
23
|
export interface Policy {
|
|
19
24
|
allowedDomains: string[];
|
|
@@ -21,20 +26,10 @@ export interface Policy {
|
|
|
21
26
|
cpu: number | null;
|
|
22
27
|
memoryMb: number | null;
|
|
23
28
|
/**
|
|
24
|
-
* The
|
|
25
|
-
*
|
|
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.
|
|
29
|
+
* The mode the owner chose for this machine. The kernel's `limits.mode` can only narrow it: a
|
|
30
|
+
* sandbox-mode machine never runs auto because the organization allows it.
|
|
36
31
|
*/
|
|
37
|
-
|
|
32
|
+
mode: SandboxMode;
|
|
38
33
|
}
|
|
39
34
|
export declare const DEFAULT_MAX_FRAME_BYTES: number;
|
|
40
35
|
export declare const DEFAULT_POLICY: Policy;
|
|
@@ -61,8 +56,12 @@ export interface PolicyFile {
|
|
|
61
56
|
policy: Policy;
|
|
62
57
|
/** The file's keys this version does not know (legacy keys excluded). */
|
|
63
58
|
extra: Record<string, unknown>;
|
|
64
|
-
/**
|
|
65
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The file was written before auto mode (it has no `mode`): the mode was derived from its legacy
|
|
61
|
+
* keys and the file is rewritten in the new vocabulary at the next change (worth a notice at
|
|
62
|
+
* start).
|
|
63
|
+
*/
|
|
64
|
+
legacy: boolean;
|
|
66
65
|
}
|
|
67
66
|
/**
|
|
68
67
|
* The local policy plus the file's keys this version does not know (kept on every write, so an
|
package/dist/state.js
CHANGED
|
@@ -2,7 +2,6 @@ import { randomBytes } from "node:crypto";
|
|
|
2
2
|
import { chmodSync, closeSync, existsSync, fstatSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync, } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { isSandboxTier } from "@capybara-hq/plugin-sdk";
|
|
6
5
|
const DEFAULT_RECONNECT_GRACE_SECONDS = 120;
|
|
7
6
|
export const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
8
7
|
export const DEFAULT_POLICY = {
|
|
@@ -10,9 +9,7 @@ export const DEFAULT_POLICY = {
|
|
|
10
9
|
allowCredentials: [],
|
|
11
10
|
cpu: null,
|
|
12
11
|
memoryMb: null,
|
|
13
|
-
|
|
14
|
-
localhost: "auto",
|
|
15
|
-
remoteGrants: "owner",
|
|
12
|
+
mode: "auto",
|
|
16
13
|
};
|
|
17
14
|
/** `$XDG_CONFIG_HOME/capybara-device`, or `~/.config/capybara-device`. */
|
|
18
15
|
export function stateDir(env = process.env, home = homedir()) {
|
|
@@ -93,9 +90,22 @@ export function removeCredential(dir) {
|
|
|
93
90
|
}
|
|
94
91
|
const isStringList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
95
92
|
const isCeiling = (v) => v === null || (typeof v === "number" && Number.isFinite(v) && v > 0);
|
|
96
|
-
const POLICY_KEYS =
|
|
97
|
-
/**
|
|
98
|
-
|
|
93
|
+
const POLICY_KEYS = Object.keys(DEFAULT_POLICY);
|
|
94
|
+
/**
|
|
95
|
+
* Keys of older policy files: ignored on read and dropped on the next write. `tier` / `isolation` /
|
|
96
|
+
* `localhost` / `remoteGrants` are the auto-mode migration (spec §4.4): a file without `mode` runs
|
|
97
|
+
* in auto when it asked for no sandbox, else in sandbox.
|
|
98
|
+
*/
|
|
99
|
+
const LEGACY_POLICY_KEYS = [
|
|
100
|
+
"network",
|
|
101
|
+
"allowLocalBinding",
|
|
102
|
+
"allowUnixSockets",
|
|
103
|
+
"tier",
|
|
104
|
+
"isolation",
|
|
105
|
+
"localhost",
|
|
106
|
+
"remoteGrants",
|
|
107
|
+
];
|
|
108
|
+
const isMode = (v) => v === "auto" || v === "sandbox";
|
|
99
109
|
/** The local policy (defaults when absent). Throws, naming the file, on bad JSON or field types. */
|
|
100
110
|
export function readPolicy(dir) {
|
|
101
111
|
return readPolicyFile(dir).policy;
|
|
@@ -107,7 +117,7 @@ export function readPolicy(dir) {
|
|
|
107
117
|
export function readPolicyFile(dir) {
|
|
108
118
|
const file = policyPath(dir);
|
|
109
119
|
if (!existsSync(file)) {
|
|
110
|
-
return { policy: { ...DEFAULT_POLICY }, extra: {},
|
|
120
|
+
return { policy: { ...DEFAULT_POLICY }, extra: {}, legacy: false };
|
|
111
121
|
}
|
|
112
122
|
let raw;
|
|
113
123
|
try {
|
|
@@ -119,8 +129,25 @@ export function readPolicyFile(dir) {
|
|
|
119
129
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
120
130
|
throw new Error(`${file} is invalid: expected a JSON object`);
|
|
121
131
|
}
|
|
122
|
-
const
|
|
132
|
+
const o = raw;
|
|
123
133
|
const bad = (key, want) => new Error(`${file} is invalid: ${key} must be ${want} (fix or delete the file)`);
|
|
134
|
+
// Lenient read (spec §4.4): no `mode` means an older file; `isolation: none` or `tier: open`
|
|
135
|
+
// asked for no sandbox, so it becomes auto, anything else sandbox.
|
|
136
|
+
const legacy = o.mode === undefined;
|
|
137
|
+
const rawMode = legacy
|
|
138
|
+
? o.isolation === "none" || o.tier === "open"
|
|
139
|
+
? "auto"
|
|
140
|
+
: "sandbox"
|
|
141
|
+
: o.mode;
|
|
142
|
+
if (!isMode(rawMode))
|
|
143
|
+
throw bad("mode", '"auto" or "sandbox"');
|
|
144
|
+
const policy = {
|
|
145
|
+
allowedDomains: o.allowedDomains === undefined ? [] : o.allowedDomains,
|
|
146
|
+
allowCredentials: o.allowCredentials === undefined ? [] : o.allowCredentials,
|
|
147
|
+
cpu: o.cpu === undefined ? null : o.cpu,
|
|
148
|
+
memoryMb: o.memoryMb === undefined ? null : o.memoryMb,
|
|
149
|
+
mode: rawMode,
|
|
150
|
+
};
|
|
124
151
|
if (!isStringList(policy.allowedDomains))
|
|
125
152
|
throw bad("allowedDomains", "a list of strings");
|
|
126
153
|
if (!isStringList(policy.allowCredentials))
|
|
@@ -129,37 +156,12 @@ export function readPolicyFile(dir) {
|
|
|
129
156
|
throw bad("cpu", "a positive number or null");
|
|
130
157
|
if (!isCeiling(policy.memoryMb))
|
|
131
158
|
throw bad("memoryMb", "a positive number or null");
|
|
132
|
-
if (policy.tier !== undefined && !isSandboxTier(policy.tier)) {
|
|
133
|
-
throw bad("tier", '"strict", "dev" or "open"');
|
|
134
|
-
}
|
|
135
|
-
if (policy.isolation !== "sandbox" && policy.isolation !== "none") {
|
|
136
|
-
throw bad("isolation", '"sandbox" or "none"');
|
|
137
|
-
}
|
|
138
|
-
if (policy.localhost !== "auto" && policy.localhost !== "allow") {
|
|
139
|
-
throw bad("localhost", '"auto" or "allow"');
|
|
140
|
-
}
|
|
141
|
-
if (policy.remoteGrants !== "owner" && policy.remoteGrants !== "off") {
|
|
142
|
-
throw bad("remoteGrants", '"owner" or "off"');
|
|
143
|
-
}
|
|
144
159
|
const extra = {};
|
|
145
|
-
for (const [k, v] of Object.entries(
|
|
160
|
+
for (const [k, v] of Object.entries(o)) {
|
|
146
161
|
if (!POLICY_KEYS.includes(k) && !LEGACY_POLICY_KEYS.includes(k))
|
|
147
162
|
extra[k] = v;
|
|
148
163
|
}
|
|
149
|
-
return {
|
|
150
|
-
policy: {
|
|
151
|
-
allowedDomains: policy.allowedDomains,
|
|
152
|
-
allowCredentials: policy.allowCredentials,
|
|
153
|
-
cpu: policy.cpu,
|
|
154
|
-
memoryMb: policy.memoryMb,
|
|
155
|
-
...(policy.tier !== undefined && { tier: policy.tier }),
|
|
156
|
-
isolation: policy.isolation,
|
|
157
|
-
localhost: policy.localhost,
|
|
158
|
-
remoteGrants: policy.remoteGrants,
|
|
159
|
-
},
|
|
160
|
-
extra,
|
|
161
|
-
legacyNetworkOpen: raw.network === "open",
|
|
162
|
-
};
|
|
164
|
+
return { policy, extra, legacy };
|
|
163
165
|
}
|
|
164
166
|
/** Writes policy.json atomically (owner-only); `extra` are unknown keys to keep (never legacy ones). */
|
|
165
167
|
export function writePolicy(dir, policy, extra = {}) {
|
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.9",
|
|
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.22"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@types/ws": "^8.5.13"
|
package/dist/proxy-guard.d.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The macOS localhost proxy guard (spec §5.2.3). `dev` lets sandboxed commands reach any port on
|
|
3
|
-
* this machine's localhost, which includes a local proxy that forwards past the network allowlist
|
|
4
|
-
* (Clash and the like) or Docker's TCP API. The device looks for one at start, whenever the
|
|
5
|
-
* policy is reloaded and again before a command once the last result is older than
|
|
6
|
-
* {@link PROXY_GUARD_TTL_MS}; when it finds one, `dev` / `open` run without local binding unless the
|
|
7
|
-
* owner set `localhost: allow`. A check that cannot run on macOS counts as a finding (fail safe).
|
|
8
|
-
*/
|
|
9
|
-
/** How long a proxy guard result is used before the next command runs the guard again. */
|
|
10
|
-
export declare const PROXY_GUARD_TTL_MS = 30000;
|
|
11
|
-
/** Common local proxy ports (Clash, V2Ray, Surge, Privoxy, Tor) and Docker's TCP API ports. */
|
|
12
|
-
export declare const PROXY_PORTS: readonly number[];
|
|
13
|
-
export interface ProxyGuardResult {
|
|
14
|
-
detected: boolean;
|
|
15
|
-
/** What was found, in English (for `policy show` and the log). */
|
|
16
|
-
reasons: string[];
|
|
17
|
-
}
|
|
18
|
-
export interface ProxyGuardDeps {
|
|
19
|
-
platform?: NodeJS.Platform;
|
|
20
|
-
/** The program's environment (default: `process.env`). */
|
|
21
|
-
env?: Record<string, string | undefined>;
|
|
22
|
-
/** `scutil --proxy`'s output, or undefined when it cannot run (default: runs it on macOS). */
|
|
23
|
-
scutil?: () => Promise<string | undefined>;
|
|
24
|
-
/** Whether something accepts TCP connections on `host`:`port` (default: a short connect). */
|
|
25
|
-
probe?: (port: number, host: string) => Promise<boolean>;
|
|
26
|
-
ports?: readonly number[];
|
|
27
|
-
}
|
|
28
|
-
/** Whether `host` names this machine's loopback. */
|
|
29
|
-
export declare function isLoopbackHost(host: string): boolean;
|
|
30
|
-
/**
|
|
31
|
-
* The loopback proxies `scutil --proxy` reports as enabled: `HTTPEnable`, `HTTPSEnable`,
|
|
32
|
-
* `SOCKSEnable` set to 1 with their `*Proxy` host on loopback. Returns `"HTTP 127.0.0.1:7890"`
|
|
33
|
-
* style entries.
|
|
34
|
-
*/
|
|
35
|
-
export declare function parseScutilProxy(text: string): string[];
|
|
36
|
-
/**
|
|
37
|
-
* `value` with the user and password of a proxy URL (`user:pass@`) replaced by `***@`. The
|
|
38
|
-
* userinfo ends at the last `@` before the host, so a password with an unencoded `@`, `/` or `:`
|
|
39
|
-
* is hidden whole.
|
|
40
|
-
*/
|
|
41
|
-
export declare function redactProxyUserinfo(value: string): string;
|
|
42
|
-
/**
|
|
43
|
-
* The proxy variables of `env` (any case) whose host is loopback, as `NAME=value` (credentials in
|
|
44
|
-
* the value redacted: the result is printed and logged).
|
|
45
|
-
*/
|
|
46
|
-
export declare function loopbackProxyEnv(env: Record<string, string | undefined>): string[];
|
|
47
|
-
/** The loopback addresses probed: a proxy may listen on either. */
|
|
48
|
-
export declare const PROBE_HOSTS: readonly string[];
|
|
49
|
-
/** Whether something accepts a TCP connection on `host`:`port` within a short time. */
|
|
50
|
-
export declare function probeLoopbackPort(port: number, host?: string, timeoutMs?: number): Promise<boolean>;
|
|
51
|
-
/**
|
|
52
|
-
* Looks for a local forwarding proxy: the system proxy (macOS `scutil --proxy`), loopback proxy
|
|
53
|
-
* variables in the program's environment, and a listener on {@link PROXY_PORTS} of 127.0.0.1 or
|
|
54
|
-
* ::1. A proxy configured only through a PAC file (automatic proxy configuration) is not read.
|
|
55
|
-
* Never throws. On macOS a system proxy setting that cannot be read counts as found (fail safe);
|
|
56
|
-
* a port probe that cannot run finds nothing.
|
|
57
|
-
*/
|
|
58
|
-
export declare function detectLocalProxy(deps?: ProxyGuardDeps): Promise<ProxyGuardResult>;
|
package/dist/proxy-guard.js
DELETED
|
@@ -1,137 +0,0 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
|
-
import { connect } from "node:net";
|
|
3
|
-
/**
|
|
4
|
-
* The macOS localhost proxy guard (spec §5.2.3). `dev` lets sandboxed commands reach any port on
|
|
5
|
-
* this machine's localhost, which includes a local proxy that forwards past the network allowlist
|
|
6
|
-
* (Clash and the like) or Docker's TCP API. The device looks for one at start, whenever the
|
|
7
|
-
* policy is reloaded and again before a command once the last result is older than
|
|
8
|
-
* {@link PROXY_GUARD_TTL_MS}; when it finds one, `dev` / `open` run without local binding unless the
|
|
9
|
-
* owner set `localhost: allow`. A check that cannot run on macOS counts as a finding (fail safe).
|
|
10
|
-
*/
|
|
11
|
-
/** How long a proxy guard result is used before the next command runs the guard again. */
|
|
12
|
-
export const PROXY_GUARD_TTL_MS = 30_000;
|
|
13
|
-
/** Common local proxy ports (Clash, V2Ray, Surge, Privoxy, Tor) and Docker's TCP API ports. */
|
|
14
|
-
export const PROXY_PORTS = Object.freeze([
|
|
15
|
-
7890, 7891, 7897, 1080, 1087, 8118, 9050, 9150, 2375, 2376,
|
|
16
|
-
]);
|
|
17
|
-
/** How long one port probe waits for a connection. */
|
|
18
|
-
const PROBE_TIMEOUT_MS = 150;
|
|
19
|
-
/** The proxy variables of a program's environment, checked in any case. */
|
|
20
|
-
const PROXY_ENV = ["http_proxy", "https_proxy", "all_proxy"];
|
|
21
|
-
/** Whether `host` names this machine's loopback. */
|
|
22
|
-
export function isLoopbackHost(host) {
|
|
23
|
-
const h = host
|
|
24
|
-
.trim()
|
|
25
|
-
.toLowerCase()
|
|
26
|
-
.replace(/^\[|\]$/g, "");
|
|
27
|
-
return h === "localhost" || h === "::1" || h.startsWith("127.") || h === "0.0.0.0";
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* The loopback proxies `scutil --proxy` reports as enabled: `HTTPEnable`, `HTTPSEnable`,
|
|
31
|
-
* `SOCKSEnable` set to 1 with their `*Proxy` host on loopback. Returns `"HTTP 127.0.0.1:7890"`
|
|
32
|
-
* style entries.
|
|
33
|
-
*/
|
|
34
|
-
export function parseScutilProxy(text) {
|
|
35
|
-
const fields = new Map();
|
|
36
|
-
for (const line of text.split("\n")) {
|
|
37
|
-
const m = /^\s*([A-Za-z]+)\s*:\s*(.*?)\s*$/.exec(line);
|
|
38
|
-
if (m !== null)
|
|
39
|
-
fields.set(m[1], m[2]);
|
|
40
|
-
}
|
|
41
|
-
const out = [];
|
|
42
|
-
for (const kind of ["HTTP", "HTTPS", "SOCKS"]) {
|
|
43
|
-
if (fields.get(`${kind}Enable`) !== "1")
|
|
44
|
-
continue;
|
|
45
|
-
const host = fields.get(`${kind}Proxy`);
|
|
46
|
-
if (host === undefined || !isLoopbackHost(host))
|
|
47
|
-
continue;
|
|
48
|
-
const port = fields.get(`${kind}Port`);
|
|
49
|
-
out.push(`${kind} ${host}${port !== undefined ? `:${port}` : ""}`);
|
|
50
|
-
}
|
|
51
|
-
return out;
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* `value` with the user and password of a proxy URL (`user:pass@`) replaced by `***@`. The
|
|
55
|
-
* userinfo ends at the last `@` before the host, so a password with an unencoded `@`, `/` or `:`
|
|
56
|
-
* is hidden whole.
|
|
57
|
-
*/
|
|
58
|
-
export function redactProxyUserinfo(value) {
|
|
59
|
-
const scheme = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.exec(value)?.[0] ?? "";
|
|
60
|
-
const rest = value.slice(scheme.length);
|
|
61
|
-
// the host part never holds an `@`: everything before the last one is userinfo
|
|
62
|
-
const at = rest.lastIndexOf("@");
|
|
63
|
-
return at === -1 ? value : `${scheme}***@${rest.slice(at + 1)}`;
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* The proxy variables of `env` (any case) whose host is loopback, as `NAME=value` (credentials in
|
|
67
|
-
* the value redacted: the result is printed and logged).
|
|
68
|
-
*/
|
|
69
|
-
export function loopbackProxyEnv(env) {
|
|
70
|
-
const out = [];
|
|
71
|
-
for (const [name, value] of Object.entries(env)) {
|
|
72
|
-
if (!PROXY_ENV.includes(name.toLowerCase()) || value === undefined || value === "")
|
|
73
|
-
continue;
|
|
74
|
-
let host;
|
|
75
|
-
try {
|
|
76
|
-
// `127.0.0.1:7890` without a scheme is common too.
|
|
77
|
-
host = new URL(value.includes("://") ? value : `http://${value}`).hostname;
|
|
78
|
-
}
|
|
79
|
-
catch {
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
if (isLoopbackHost(host))
|
|
83
|
-
out.push(`${name}=${redactProxyUserinfo(value)}`);
|
|
84
|
-
}
|
|
85
|
-
return out;
|
|
86
|
-
}
|
|
87
|
-
function runScutil() {
|
|
88
|
-
return new Promise((resolve) => {
|
|
89
|
-
execFile("/usr/sbin/scutil", ["--proxy"], { timeout: 2_000 }, (e, stdout) => resolve(e === null ? stdout : undefined));
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
/** The loopback addresses probed: a proxy may listen on either. */
|
|
93
|
-
export const PROBE_HOSTS = Object.freeze(["127.0.0.1", "::1"]);
|
|
94
|
-
/** Whether something accepts a TCP connection on `host`:`port` within a short time. */
|
|
95
|
-
export function probeLoopbackPort(port, host = "127.0.0.1", timeoutMs = PROBE_TIMEOUT_MS) {
|
|
96
|
-
return new Promise((resolve) => {
|
|
97
|
-
const socket = connect({ host, port });
|
|
98
|
-
const done = (open) => {
|
|
99
|
-
socket.destroy();
|
|
100
|
-
resolve(open);
|
|
101
|
-
};
|
|
102
|
-
socket.setTimeout(timeoutMs, () => done(false));
|
|
103
|
-
socket.once("connect", () => done(true));
|
|
104
|
-
socket.once("error", () => done(false));
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Looks for a local forwarding proxy: the system proxy (macOS `scutil --proxy`), loopback proxy
|
|
109
|
-
* variables in the program's environment, and a listener on {@link PROXY_PORTS} of 127.0.0.1 or
|
|
110
|
-
* ::1. A proxy configured only through a PAC file (automatic proxy configuration) is not read.
|
|
111
|
-
* Never throws. On macOS a system proxy setting that cannot be read counts as found (fail safe);
|
|
112
|
-
* a port probe that cannot run finds nothing.
|
|
113
|
-
*/
|
|
114
|
-
export async function detectLocalProxy(deps = {}) {
|
|
115
|
-
const platform = deps.platform ?? process.platform;
|
|
116
|
-
const reasons = [];
|
|
117
|
-
if (platform === "darwin") {
|
|
118
|
-
const text = await (deps.scutil ?? runScutil)().catch(() => undefined);
|
|
119
|
-
if (text === undefined)
|
|
120
|
-
reasons.push("the system proxy settings could not be read");
|
|
121
|
-
else
|
|
122
|
-
for (const p of parseScutilProxy(text))
|
|
123
|
-
reasons.push(`system proxy ${p}`);
|
|
124
|
-
}
|
|
125
|
-
for (const v of loopbackProxyEnv(deps.env ?? process.env))
|
|
126
|
-
reasons.push(`environment ${v}`);
|
|
127
|
-
const probe = deps.probe ?? ((port, host) => probeLoopbackPort(port, host));
|
|
128
|
-
const ports = deps.ports ?? PROXY_PORTS;
|
|
129
|
-
const targets = PROBE_HOSTS.flatMap((host) => ports.map((port) => ({ host, port })));
|
|
130
|
-
const open = await Promise.all(targets.map((t) => probe(t.port, t.host).catch(() => false)));
|
|
131
|
-
targets.forEach((t, i) => {
|
|
132
|
-
const where = t.host.includes(":") ? `[${t.host}]` : t.host;
|
|
133
|
-
if (open[i])
|
|
134
|
-
reasons.push(`a listener on ${where}:${t.port}`);
|
|
135
|
-
});
|
|
136
|
-
return { detected: reasons.length > 0, reasons };
|
|
137
|
-
}
|