@capybara-hq/device 0.1.0-rc.2 → 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.
@@ -1,15 +1,78 @@
1
1
  import type { Command } from "../args.js";
2
+ import { type TierFacts } from "../policy.js";
3
+ import { type ProxyGuardResult } from "../proxy-guard.js";
4
+ import { type Policy } from "../state.js";
2
5
  export interface PolicyDeps {
3
6
  stateDir: string;
4
7
  out: (line: string) => void;
5
8
  err: (line: string) => void;
9
+ /**
10
+ * The person already read the risk text and answered `y` at the prompt ({@link confirmRisk});
11
+ * otherwise `set tier open` and `set isolation none` need `--yes`.
12
+ */
13
+ confirmed?: boolean;
14
+ /** The localhost proxy guard `show` runs (default: {@link detectLocalProxy}). */
15
+ detectProxy?: () => Promise<ProxyGuardResult>;
16
+ platform?: NodeJS.Platform;
6
17
  }
18
+ /** Shown before `set tier open` takes effect (adapted from the network ask-to-allow spec §7). */
19
+ export declare const OPEN_TIER_RISK: string;
20
+ /** Printed when a local tier change turned the sandbox back on. */
21
+ export declare const TIER_CHANGE_SANDBOX_ON: string;
22
+ /** Shown before `set isolation none` takes effect (spec §5.4). */
23
+ export declare const UNSANDBOXED_RISK_TEXT: string;
24
+ /** A change that asks first: its risk text, the prompt, and the refusal without a confirmation. */
25
+ export interface PolicyRisk {
26
+ risk: string;
27
+ prompt: string;
28
+ needsYes: string;
29
+ }
30
+ /** The risk of a `policy` command line, when it is one of the changes that ask first. */
31
+ export declare function policyRisk(cmd: Extract<Command, {
32
+ command: "policy";
33
+ }>): PolicyRisk | undefined;
34
+ /** `set tier open` or `set isolation none` without `--yes`: the changes that ask first. */
35
+ export declare function needsConfirmation(cmd: Extract<Command, {
36
+ command: "policy";
37
+ }>): boolean;
38
+ /**
39
+ * Asks on a terminal before a change that needs it: prints its risk text and the prompt; true
40
+ * only for an answer of `y` or `yes`.
41
+ */
42
+ export declare function confirmRisk(cmd: Extract<Command, {
43
+ command: "policy";
44
+ }>, deps: {
45
+ out: (line: string) => void;
46
+ ask: (question: string) => Promise<string>;
47
+ }): Promise<boolean>;
7
48
  /** What the OS mode does not enforce yet, shown with every `show` and `set`. */
8
49
  export declare const NOT_ENFORCED_NOTE: string;
50
+ /** Shown when a docker-mode device is given an allowed domain. */
51
+ export declare const DOCKER_NETWORK_NOTE: string;
52
+ /** Shown when a Docker-mode device is told to run commands without a sandbox. */
53
+ export declare const DOCKER_ISOLATION_REFUSED: string;
54
+ /** Refusal of `set isolation none` while the local tier is not explicitly `open`. */
55
+ export declare const ISOLATION_NEEDS_OPEN: string;
56
+ /**
57
+ * Why `set isolation none` cannot apply on this machine now (Docker mode, or the local tier is
58
+ * not explicitly `open`), checked before any risk text or question; undefined for every other
59
+ * command line. The tier is checked again under the policy lock when the change is written.
60
+ */
61
+ export declare function isolationRefusal(cmd: Extract<Command, {
62
+ command: "policy";
63
+ }>, stateDir: string): string | undefined;
64
+ /** What `policy show` says the tier gives on this machine (English, one line each). */
65
+ export declare function describeTier(policy: Policy, facts: TierFacts, proxy: ProxyGuardResult): string[];
9
66
  /**
10
- * `policy show` prints the local policy; `policy set <key> <value>` changes one field. Only the
11
- * machine's user edits this file: the cloud never writes it. Changes apply at the next start.
67
+ * `policy show` prints the local policy and what its tier gives on this machine;
68
+ * `policy set <key> <value>` replaces one field (`set tier open` and `set isolation none` print
69
+ * their risk and need `--yes` or a confirmation at the prompt); `policy add|remove <key> <value>`
70
+ * adds or removes entries of a list field. `tier default` removes the key (follow the org's
71
+ * default). The machine's user edits this file; the deployment changes it only through the
72
+ * `policy` op, on the device owner's decision and only while `remoteGrants` is `owner`
73
+ * (narrowing always; never `isolation none`). Writes take policy.json.lock, and a running program
74
+ * applies the change at its next command.
12
75
  */
13
76
  export declare function policyCommand(cmd: Extract<Command, {
14
77
  command: "policy";
15
- }>, deps: PolicyDeps): number;
78
+ }>, deps: PolicyDeps): Promise<number>;
@@ -1,6 +1,71 @@
1
- import { validateAllowHost } from "@capybara-hq/plugin-sdk";
2
- import { policyPath, readPolicy, writePolicy } from "../state.js";
3
- const KEYS = ["allowedDomains", "allowCredentials", "cpu", "memoryMb"];
1
+ import { isSandboxTier, validateAllowHost } from "@capybara-hq/plugin-sdk";
2
+ import { tierFacts } from "../policy.js";
3
+ import { PolicyStore } from "../policy-store.js";
4
+ import { detectLocalProxy } from "../proxy-guard.js";
5
+ import { policyPath, readCredential } from "../state.js";
6
+ const KEYS = [
7
+ "allowedDomains",
8
+ "allowCredentials",
9
+ "cpu",
10
+ "memoryMb",
11
+ "tier",
12
+ "isolation",
13
+ "localhost",
14
+ "remoteGrants",
15
+ ];
16
+ /** Shown before `set tier open` takes effect (adapted from the network ask-to-allow spec §7). */
17
+ export const OPEN_TIER_RISK = "At tier open, agent commands on this device can reach any address the organization allows " +
18
+ "(any public address if the organization has no limit), including uploading files to " +
19
+ "outside sites. Prompt injection can make an agent do that. Turn it on only on your own " +
20
+ "development machine, with agents and material you trust.";
21
+ /** Printed when a local tier change turned the sandbox back on. */
22
+ export const TIER_CHANGE_SANDBOX_ON = "The tier changed, so the sandbox is back on. To run commands without a sandbox again, set " +
23
+ "tier open and run: capybara-device policy set isolation none";
24
+ /** Shown before `set isolation none` takes effect (spec §5.4). */
25
+ export const UNSANDBOXED_RISK_TEXT = "Without a sandbox, agent commands run on this computer as you: they can read and write all " +
26
+ "your files, use your credentials (SSH keys, cloud accounts, keychain), Docker and any " +
27
+ "network. Prompt injection can make an agent delete files or send your credentials away. " +
28
+ "Turn it on only on your own development machine, with agents and material you fully trust. " +
29
+ "Such commands can also read this program's own credential: if you suspect misuse, run " +
30
+ "capybara-device logout and log in again.";
31
+ const OPEN_TIER = {
32
+ risk: OPEN_TIER_RISK,
33
+ prompt: "Let commands on this device reach any address the organization allows? [y/N] ",
34
+ needsYes: "Nothing changed. To set tier open, run: capybara-device policy set tier open --yes",
35
+ };
36
+ const UNSANDBOXED = {
37
+ risk: UNSANDBOXED_RISK_TEXT,
38
+ prompt: "Run agent commands on this computer without a sandbox? [y/N] ",
39
+ needsYes: "Nothing changed. To run commands without a sandbox, run: " +
40
+ "capybara-device policy set isolation none --yes",
41
+ };
42
+ /** The risk of a `policy` command line, when it is one of the changes that ask first. */
43
+ export function policyRisk(cmd) {
44
+ if (cmd.action !== "set")
45
+ return undefined;
46
+ const value = cmd.value.trim().toLowerCase();
47
+ if (cmd.key === "tier" && value === "open")
48
+ return OPEN_TIER;
49
+ if (cmd.key === "isolation" && value === "none")
50
+ return UNSANDBOXED;
51
+ return undefined;
52
+ }
53
+ /** `set tier open` or `set isolation none` without `--yes`: the changes that ask first. */
54
+ export function needsConfirmation(cmd) {
55
+ return cmd.action === "set" && policyRisk(cmd) !== undefined && cmd.yes !== true;
56
+ }
57
+ /**
58
+ * Asks on a terminal before a change that needs it: prints its risk text and the prompt; true
59
+ * only for an answer of `y` or `yes`.
60
+ */
61
+ export async function confirmRisk(cmd, deps) {
62
+ const r = policyRisk(cmd);
63
+ if (r === undefined)
64
+ return true;
65
+ deps.out(r.risk);
66
+ const answer = (await deps.ask(r.prompt)).trim().toLowerCase();
67
+ return answer === "y" || answer === "yes";
68
+ }
4
69
  /** What the OS mode does not enforce yet, shown with every `show` and `set`. */
5
70
  export const NOT_ENFORCED_NOTE = "Note: in OS mode cpu and memoryMb are not enforced yet, and allowCredentials is not used: " +
6
71
  "commands get no local credentials.";
@@ -19,56 +84,307 @@ function ceiling(key, value) {
19
84
  }
20
85
  return n;
21
86
  }
87
+ /** Shown when a docker-mode device is given an allowed domain. */
88
+ export const DOCKER_NETWORK_NOTE = "Note: this device runs commands in Docker mode, which cannot limit network access per " +
89
+ "domain: while any domain is allowed or the tier is open (and the organization allows " +
90
+ "network), commands reach the whole internet. Use OS mode to allow single domains.";
91
+ /** Shown when a Docker-mode device is told to run commands without a sandbox. */
92
+ export const DOCKER_ISOLATION_REFUSED = "This device runs commands in Docker mode, where they always run in a container; " +
93
+ "isolation none works in OS mode only.";
94
+ /** Refusal of `set isolation none` while the local tier is not explicitly `open`. */
95
+ export const ISOLATION_NEEDS_OPEN = "Nothing changed. Running without a sandbox needs tier open set on this device first: " +
96
+ "capybara-device policy set tier open --yes";
97
+ /** A refusal found under the policy lock, reported as a usage refusal (exit 2). */
98
+ class LockedRefusal extends Error {
99
+ }
22
100
  /**
23
- * `policy show` prints the local policy; `policy set <key> <value>` changes one field. Only the
24
- * machine's user edits this file: the cloud never writes it. Changes apply at the next start.
101
+ * Why `set isolation none` cannot apply on this machine now (Docker mode, or the local tier is
102
+ * not explicitly `open`), checked before any risk text or question; undefined for every other
103
+ * command line. The tier is checked again under the policy lock when the change is written.
25
104
  */
26
- export function policyCommand(cmd, deps) {
105
+ export function isolationRefusal(cmd, stateDir) {
106
+ if (cmd.action !== "set" || cmd.key !== "isolation")
107
+ return undefined;
108
+ if (cmd.value.trim().toLowerCase() !== "none")
109
+ return undefined;
110
+ if (dockerMode(stateDir))
111
+ return DOCKER_ISOLATION_REFUSED;
112
+ try {
113
+ if (new PolicyStore(stateDir).current().tier !== "open")
114
+ return ISOLATION_NEEDS_OPEN;
115
+ }
116
+ catch {
117
+ // An unreadable policy file is reported by the command itself.
118
+ }
119
+ return undefined;
120
+ }
121
+ /** Whether this machine is logged in in Docker mode (false when unknown). */
122
+ function dockerMode(stateDir) {
123
+ try {
124
+ return readCredential(stateDir)?.mode === "docker";
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ }
130
+ /** The keys `add` and `remove` work on: the list fields. */
131
+ const LIST_KEYS = ["allowedDomains", "allowCredentials"];
132
+ /** Lowercased, validated hosts; throws naming the first bad one. */
133
+ function domains(value) {
134
+ const out = list(value).map((d) => d.toLowerCase());
135
+ for (const d of out) {
136
+ const errors = validateAllowHost(d);
137
+ if (errors.length > 0)
138
+ throw new Error(`"${d}": ${errors.join("; ")}`);
139
+ }
140
+ return out;
141
+ }
142
+ /** The new value of a list field after `add` / `remove`; unchanged entries are reported. */
143
+ function edit(current, action, key, values, out) {
144
+ // Domains compare ignoring case (a hand-edited file may hold any spelling).
145
+ const norm = key === "allowedDomains" ? (v) => v.toLowerCase() : (v) => v;
146
+ const has = (list, v) => list.some((x) => norm(x) === norm(v));
147
+ if (action === "add") {
148
+ const next = [...current];
149
+ for (const v of values) {
150
+ if (has(next, v))
151
+ out(`${v} is already in ${key}.`);
152
+ else {
153
+ next.push(v);
154
+ out(`Added ${v} to ${key}.`);
155
+ }
156
+ }
157
+ return next;
158
+ }
159
+ for (const v of values)
160
+ out(has(current, v) ? `Removed ${v} from ${key}.` : `${v} is not in ${key}.`);
161
+ return current.filter((x) => !has(values, x));
162
+ }
163
+ function tierValue(value) {
164
+ const v = value.trim().toLowerCase();
165
+ if (v === "default")
166
+ return undefined;
167
+ if (!isSandboxTier(v))
168
+ throw new Error(`tier must be strict, dev, open or default, got "${value}"`);
169
+ return v;
170
+ }
171
+ /** What `policy show` says the tier gives on this machine (English, one line each). */
172
+ export function describeTier(policy, facts, proxy) {
173
+ const chosen = policy.tier !== undefined
174
+ ? `${policy.tier} (set on this device; the organization's ceiling may lower it)`
175
+ : "the organization's default (dev unless the organization changed it)";
176
+ const lines = [`Tier: ${chosen}.`];
177
+ const localhost = facts.localhost === "on"
178
+ ? "commands can listen on local ports and reach this machine's localhost"
179
+ : facts.localhost === "off-proxy-detected"
180
+ ? `off: a local proxy was detected (${proxy.reasons.join("; ")}). Commands could ` +
181
+ "reach past the network allowlist through it. To allow localhost anyway, run: " +
182
+ "capybara-device policy set localhost allow"
183
+ : "off";
184
+ lines.push(`At tier ${facts.effectiveTier} on this machine: localhost ${localhost}.`);
185
+ const sockets = facts.unixSockets === "roots"
186
+ ? "allowed under the device's workspace, tmp and socket directories only"
187
+ : facts.unixSockets === "all-masked"
188
+ ? "the container's own"
189
+ : "blocked";
190
+ lines.push(`Unix sockets: ${sockets}.`);
191
+ if (facts.effectiveTier !== "strict") {
192
+ lines.push("Package caches are kept in the device directory's cache folder.");
193
+ }
194
+ if (policy.isolation === "none") {
195
+ lines.push("Isolation: none. While the tier is open, commands run directly on this computer as you, " +
196
+ "without a sandbox. To turn the sandbox back on, run: " +
197
+ "capybara-device policy set isolation sandbox");
198
+ }
199
+ return lines;
200
+ }
201
+ /**
202
+ * `policy show` prints the local policy and what its tier gives on this machine;
203
+ * `policy set <key> <value>` replaces one field (`set tier open` and `set isolation none` print
204
+ * their risk and need `--yes` or a confirmation at the prompt); `policy add|remove <key> <value>`
205
+ * adds or removes entries of a list field. `tier default` removes the key (follow the org's
206
+ * default). The machine's user edits this file; the deployment changes it only through the
207
+ * `policy` op, on the device owner's decision and only while `remoteGrants` is `owner`
208
+ * (narrowing always; never `isolation none`). Writes take policy.json.lock, and a running program
209
+ * applies the change at its next command.
210
+ */
211
+ export async function policyCommand(cmd, deps) {
27
212
  const { stateDir, out, err } = deps;
28
- let policy;
213
+ let store;
29
214
  try {
30
- policy = readPolicy(stateDir);
215
+ store = new PolicyStore(stateDir);
31
216
  }
32
217
  catch (e) {
33
218
  err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
34
219
  return 1;
35
220
  }
36
221
  if (cmd.action === "show") {
222
+ const policy = store.current();
37
223
  out(JSON.stringify(policy, null, 2));
224
+ const proxy = await (deps.detectProxy ?? (() => detectLocalProxy()))();
225
+ const facts = tierFacts(policy, undefined, {
226
+ ...(deps.platform !== undefined && { platform: deps.platform }),
227
+ proxyDetected: proxy.detected,
228
+ mode: dockerMode(stateDir) ? "docker" : "os",
229
+ });
230
+ for (const l of describeTier(policy, facts, proxy))
231
+ out(l);
38
232
  out(NOT_ENFORCED_NOTE);
39
233
  return 0;
40
234
  }
41
- const { key, value } = cmd;
42
- const next = { ...policy };
235
+ const { action, key, value } = cmd;
236
+ // Parse and validate before taking the lock; apply inside it, against the file as it is then.
237
+ let change;
43
238
  try {
44
- switch (key) {
45
- case "allowedDomains": {
46
- const domains = list(value).map((d) => d.toLowerCase());
47
- for (const d of domains) {
48
- const errors = validateAllowHost(d);
49
- if (errors.length > 0)
50
- throw new Error(`"${d}": ${errors.join("; ")}`);
239
+ if (action === "set") {
240
+ switch (key) {
241
+ case "allowedDomains": {
242
+ const next = [...new Set(domains(value))];
243
+ change = (p) => ({ ...p, allowedDomains: next });
244
+ break;
245
+ }
246
+ case "allowCredentials": {
247
+ const next = [...new Set(list(value))];
248
+ change = (p) => ({ ...p, allowCredentials: next });
249
+ break;
250
+ }
251
+ case "cpu":
252
+ case "memoryMb": {
253
+ const next = ceiling(key, value);
254
+ change = (p) => ({ ...p, [key]: next });
255
+ break;
256
+ }
257
+ case "tier": {
258
+ const next = tierValue(value);
259
+ change = (p, say) => {
260
+ const { tier: old, ...rest } = p;
261
+ // Any tier change turns the sandbox back on (spec §5.4: running without one starts
262
+ // only with a confirmed set isolation none, never by a later tier change).
263
+ const isolation = p.isolation === "none" && next !== old ? "sandbox" : p.isolation;
264
+ if (isolation !== p.isolation)
265
+ say(TIER_CHANGE_SANDBOX_ON);
266
+ return next === undefined ? { ...rest, isolation } : { ...rest, tier: next, isolation };
267
+ };
268
+ break;
269
+ }
270
+ case "isolation": {
271
+ const v = value.trim().toLowerCase();
272
+ if (v !== "sandbox" && v !== "none") {
273
+ throw new Error(`isolation must be sandbox or none, got "${value}"`);
274
+ }
275
+ if (v === "none" && dockerMode(stateDir)) {
276
+ err(DOCKER_ISOLATION_REFUSED);
277
+ return 2;
278
+ }
279
+ // Only an explicit local tier open: the org's default can change under the device.
280
+ if (v === "none" && store.current().tier !== "open") {
281
+ err(ISOLATION_NEEDS_OPEN);
282
+ return 2;
283
+ }
284
+ change = (p) => {
285
+ // Judged again on the file as it is under the lock (the tier may have changed).
286
+ if (v === "none" && p.tier !== "open")
287
+ throw new LockedRefusal(ISOLATION_NEEDS_OPEN);
288
+ return { ...p, isolation: v };
289
+ };
290
+ break;
291
+ }
292
+ case "localhost": {
293
+ const v = value.trim().toLowerCase();
294
+ if (v !== "auto" && v !== "allow") {
295
+ throw new Error(`localhost must be auto or allow, got "${value}"`);
296
+ }
297
+ change = (p) => ({ ...p, localhost: v });
298
+ break;
299
+ }
300
+ case "remoteGrants": {
301
+ if (value !== "owner" && value !== "off") {
302
+ throw new Error(`remoteGrants must be owner or off, got "${value}"`);
303
+ }
304
+ change = (p) => ({ ...p, remoteGrants: value });
305
+ break;
306
+ }
307
+ case "network":
308
+ throw new Error("network is replaced by tier: use capybara-device policy set tier strict|dev|open");
309
+ default:
310
+ throw new Error(`unknown policy key "${key}"; one of ${KEYS.join(", ")}`);
311
+ }
312
+ // Widening to tier open or isolation none needs a confirmation; narrowing never does.
313
+ const risk = policyRisk(cmd);
314
+ if (risk !== undefined && deps.confirmed !== true) {
315
+ out(risk.risk);
316
+ if (cmd.yes !== true) {
317
+ err(risk.needsYes);
318
+ return 2;
51
319
  }
52
- next.allowedDomains = [...new Set(domains)];
53
- break;
54
320
  }
55
- case "allowCredentials":
56
- next.allowCredentials = [...new Set(list(value))];
57
- break;
58
- case "cpu":
59
- case "memoryMb":
60
- next[key] = ceiling(key, value);
61
- break;
62
- default:
63
- throw new Error(`unknown policy key "${key}"; one of ${KEYS.join(", ")}`);
321
+ }
322
+ else {
323
+ if (!LIST_KEYS.includes(key)) {
324
+ throw new Error(`${action} works on ${LIST_KEYS.join(" and ")} only; use set for ${key}`);
325
+ }
326
+ const listKey = key;
327
+ // Only additions are validated: any entry already in the file can be removed.
328
+ const values = listKey !== "allowedDomains"
329
+ ? list(value)
330
+ : action === "add"
331
+ ? domains(value)
332
+ : list(value).map((d) => d.toLowerCase());
333
+ if (values.length === 0)
334
+ throw new Error(`${action} needs at least one value`);
335
+ change = (p, say) => ({ ...p, [listKey]: edit(p[listKey], action, listKey, values, say) });
64
336
  }
65
337
  }
66
338
  catch (e) {
67
339
  err(e.message);
68
340
  return 2;
69
341
  }
70
- writePolicy(stateDir, next);
71
- out(`Saved ${policyPath(stateDir)}. Restart capybara-device for it to take effect.`);
72
- out(NOT_ENFORCED_NOTE);
342
+ const lines = [];
343
+ let next;
344
+ try {
345
+ next = store.update((p) => change(p, (l) => lines.push(l)));
346
+ }
347
+ catch (e) {
348
+ if (e instanceof LockedRefusal) {
349
+ err(e.message);
350
+ return 2;
351
+ }
352
+ err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
353
+ return 1;
354
+ }
355
+ for (const l of lines)
356
+ out(l);
357
+ out(`Saved ${policyPath(stateDir)}. A running capybara-device applies it at the next command.`);
358
+ const docker = dockerMode(stateDir);
359
+ if (key === "allowedDomains" && action !== "remove" && docker) {
360
+ if (next.allowedDomains.length > 0)
361
+ out(DOCKER_NETWORK_NOTE);
362
+ }
363
+ if (key === "tier") {
364
+ out(next.tier === undefined
365
+ ? "This device now follows the organization's default tier."
366
+ : `This device now asks for tier ${next.tier}; the organization's ceiling may lower it.`);
367
+ if (next.tier === "open" && docker)
368
+ out(DOCKER_NETWORK_NOTE);
369
+ }
370
+ if (key === "isolation") {
371
+ out(next.isolation === "none"
372
+ ? "While the tier is open, commands run on this computer without a sandbox."
373
+ : "Commands run in the sandbox.");
374
+ }
375
+ if (key === "localhost") {
376
+ out(next.localhost === "allow"
377
+ ? "At tier dev or open, commands can reach this machine's localhost even when a local " +
378
+ "proxy runs (it may forward past the network allowlist)."
379
+ : "At tier dev or open, commands reach localhost unless a local proxy is detected.");
380
+ }
381
+ if (key === "remoteGrants") {
382
+ out(value === "owner"
383
+ ? "The device owner can now widen this device's network from the web or a chat card."
384
+ : "The deployment can no longer widen this device's network; it can still narrow it.");
385
+ }
386
+ if (!["allowedDomains", "tier", "isolation", "localhost", "remoteGrants"].includes(key)) {
387
+ out(NOT_ENFORCED_NOTE);
388
+ }
73
389
  return 0;
74
390
  }
@@ -1,10 +1,14 @@
1
1
  import { connect } from "../client.js";
2
2
  import type { Executor } from "../exec/types.js";
3
- import { type Credential, type Policy } from "../state.js";
3
+ import { PolicyStore } from "../policy-store.js";
4
+ import { type Credential } from "../state.js";
4
5
  export interface StartDeps {
5
6
  stateDir: string;
6
- /** Builds the executor for the credential's mode (the OS and Docker executors). */
7
- createExecutor?: (cred: Credential, policy: Policy) => Promise<Executor> | Executor;
7
+ /**
8
+ * Builds the executor for the credential's mode (the OS and Docker executors). The store
9
+ * follows policy.json, so executors read the policy at each command.
10
+ */
11
+ createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
8
12
  out: (line: string) => void;
9
13
  err: (line: string) => void;
10
14
  /** The process whose signals stop and drain the program. */
@@ -12,5 +16,7 @@ export interface StartDeps {
12
16
  kill?: typeof process.kill;
13
17
  connect?: typeof connect;
14
18
  }
19
+ /** Printed at start while policy.json still has the legacy `network: "open"` (spec §12). */
20
+ export declare const LEGACY_NETWORK_NOTICE: string;
15
21
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
16
22
  export declare function start(deps: StartDeps): Promise<number>;
@@ -1,8 +1,13 @@
1
1
  import { connect } from "../client.js";
2
2
  import { CommandLog } from "../command-log.js";
3
3
  import { readRunningPid, removePid, writePid } from "../pid.js";
4
+ import { PolicyStore } from "../policy-store.js";
4
5
  import { rotateServiceLog } from "../service/launchd.js";
5
- import { readCredential, readPolicy } from "../state.js";
6
+ import { readCredential } from "../state.js";
7
+ /** Printed at start while policy.json still has the legacy `network: "open"` (spec §12). */
8
+ export const LEGACY_NETWORK_NOTICE = "policy.json: `network` is replaced by `tier`; run `capybara-device policy set tier open` " +
9
+ "to keep an unlimited network. Any `capybara-device policy set` removes the old key and this " +
10
+ "notice.";
6
11
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
7
12
  export async function start(deps) {
8
13
  const { stateDir, out, err } = deps;
@@ -49,8 +54,13 @@ export async function start(deps) {
49
54
  writePid(stateDir, proc.pid);
50
55
  try {
51
56
  let executor;
57
+ let policy;
52
58
  try {
53
- executor = await deps.createExecutor(cred, readPolicy(stateDir));
59
+ // An invalid policy.json stops the start; later, a broken edit keeps the last good policy.
60
+ policy = new PolicyStore(stateDir, { err });
61
+ if (policy.legacyNetworkOpen)
62
+ out(LEGACY_NETWORK_NOTICE);
63
+ executor = await deps.createExecutor(cred, policy);
54
64
  }
55
65
  catch (e) {
56
66
  err(`Cannot start: ${e.message}`);
@@ -58,7 +68,12 @@ export async function start(deps) {
58
68
  }
59
69
  if (stopRequested)
60
70
  return 0;
61
- conn = (deps.connect ?? connect)(cred, executor, { log: new CommandLog(stateDir), err });
71
+ // One store: the executor's commands, the hello summary and the policy op see the same policy.
72
+ conn = (deps.connect ?? connect)(cred, executor, {
73
+ log: new CommandLog(stateDir),
74
+ err,
75
+ policy,
76
+ });
62
77
  if (drainRequested)
63
78
  conn.drain();
64
79
  out(`capybara-device: serving device ${cred.deviceId} (${cred.mode} mode)`);
@@ -1,4 +1,5 @@
1
- import { type DeviceExecArgs, type ExecResult, type SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceExecArgs, type ExecResult, type SandboxRoots, type SandboxTier } from "@capybara-hq/plugin-sdk";
2
+ import { type EgressLimits, type TierFacts } from "../policy.js";
2
3
  import type { Policy } from "../state.js";
3
4
  import { type Executor } from "./types.js";
4
5
  /** The version of the published sandbox images this program runs commands in. */
@@ -10,6 +11,20 @@ export declare const SANDBOX_IMAGE = "ghcr.io/capybara-hq/capybara-sandbox:0.1.0
10
11
  * Docker Desktop (macOS) maps file ownership itself, so the image's user is used there.
11
12
  */
12
13
  export declare function containerUser(platform?: NodeJS.Platform, uid?: number | undefined, gid?: number | undefined): string;
14
+ /**
15
+ * The container's `--shm-size` for a tier (spec §5.2): `strict` keeps Docker's default (64 MiB);
16
+ * `dev` and `open` get a quarter of the memory ceiling up to 1 GiB (at least the default), or
17
+ * 1 GiB without a ceiling, so browsers have room.
18
+ */
19
+ export declare function shmSize(tier: SandboxTier, memoryMb: number | null): string | undefined;
20
+ /**
21
+ * Whether a command gets the default bridge (spec §5.2 table). Docker mode has no domain filter,
22
+ * and the bridge reaches the host and the intranet, so only an explicit choice opens it: the
23
+ * device's own allowed domains within the ceiling (as `strict` computes them; the dev hosts do
24
+ * not count), or tier `open` with a ceiling that allows any host (an allowlist ceiling at `open`
25
+ * counts only its explicit local domains, like the lower tiers).
26
+ */
27
+ export declare function bridgeNetwork(policy: Policy, limits: EgressLimits): boolean;
13
28
  /** Container name of a device. */
14
29
  export declare function containerName(deviceId: string): string;
15
30
  /** Whether the docker CLI can reach a daemon, and why not. */
@@ -23,7 +38,12 @@ export interface DockerExecutorOptions {
23
38
  /** The device directory (from login). */
24
39
  dir: string;
25
40
  deviceId: string;
26
- policy: Policy;
41
+ /**
42
+ * The local policy now. The network decision reads it at each command; cpu, memory and the
43
+ * tier's shm size apply when the container is next created (at the next command that finds it
44
+ * idle).
45
+ */
46
+ policy: () => Policy;
27
47
  }
28
48
  /**
29
49
  * Runs every command with `docker exec` in one long-lived container of the published sandbox
@@ -31,8 +51,10 @@ export interface DockerExecutorOptions {
31
51
  * /workspace, /skills and /tmp. Workspace and tmp files are read and written inside the container
32
52
  * (as the `sandbox` user, so a link a command plants resolves in the container and never on the
33
53
  * host); the skills directory, which commands cannot write, is accessed from the host with the
34
- * same real-path checks as the OS executor. Network: none unless the effective egress is
35
- * non-empty, then the default bridge (Docker mode has no domain allowlist).
54
+ * same real-path checks as the OS executor. Network: none unless {@link bridgeNetwork} says
55
+ * otherwise, then the default bridge (Docker mode has no domain allowlist). Tiers `dev` and
56
+ * `open` get a larger `/dev/shm` ({@link shmSize}); a change of the container's flags recreates it
57
+ * at the next command that finds it idle.
36
58
  */
37
59
  export declare class DockerExecutor implements Executor {
38
60
  private readonly opts;
@@ -54,19 +76,33 @@ export declare class DockerExecutor implements Executor {
54
76
  private readonly queue;
55
77
  private pumping;
56
78
  private dirty;
79
+ /** The limits of the latest command: they decide the tier the container is made for. */
80
+ private lastLimits;
81
+ /** The spec hash of the container in use (set when it is created or reused). */
82
+ private spec;
57
83
  constructor(opts: DockerExecutorOptions);
58
84
  ensureRoot(): Promise<"ok" | "gone">;
59
85
  markerOf(tag: string): string;
60
86
  private serial;
61
87
  private inspect;
62
88
  private wanted;
89
+ /** The tier commands run at now (the owner's choice, else `dev`, before any command). */
90
+ tier(policy?: Policy): SandboxTier;
91
+ /** What the tier gives in this mode (for the policy summary). */
92
+ tierFacts(policy?: Policy): TierFacts;
63
93
  /** Every `docker run` flag of the container except its name and spec label. */
64
94
  private runArgs;
65
95
  /** A hash of the run flags: a container made with other flags is recreated. */
66
96
  private specHash;
97
+ private hashOf;
67
98
  private matches;
68
99
  private mustDocker;
69
- /** Creates the container, or reuses the existing one when it matches; call inside `serial`. */
100
+ /**
101
+ * Creates the container, or reuses the existing one when it matches; call inside `serial`.
102
+ * A file operation (`anySpec`) reuses any container that sees the directory: it needs no
103
+ * particular flags, and before the first command the tier is not known yet. The next command
104
+ * that finds it idle recreates it if its flags differ.
105
+ */
70
106
  private ensureContainer;
71
107
  /**
72
108
  * Whether a reused container's mounts still show this directory's roots: after the directory was