@capybara-hq/device 0.1.0-rc.7 → 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.
Files changed (50) hide show
  1. package/README.md +106 -189
  2. package/dist/api.d.ts +5 -0
  3. package/dist/args.d.ts +8 -3
  4. package/dist/args.js +38 -19
  5. package/dist/cli.d.ts +7 -5
  6. package/dist/cli.js +20 -31
  7. package/dist/client.d.ts +0 -2
  8. package/dist/client.js +23 -12
  9. package/dist/command-log.d.ts +3 -5
  10. package/dist/commands/login.js +55 -1
  11. package/dist/commands/mode.d.ts +52 -0
  12. package/dist/commands/mode.js +108 -0
  13. package/dist/commands/policy.d.ts +11 -65
  14. package/dist/commands/policy.js +62 -249
  15. package/dist/commands/service.d.ts +4 -3
  16. package/dist/commands/service.js +30 -2
  17. package/dist/commands/start.d.ts +2 -2
  18. package/dist/commands/start.js +14 -6
  19. package/dist/commands/status.js +11 -3
  20. package/dist/exec/docker.d.ts +22 -30
  21. package/dist/exec/docker.js +81 -69
  22. package/dist/exec/fs-helper.d.ts +13 -8
  23. package/dist/exec/fs-helper.js +30 -12
  24. package/dist/exec/host.d.ts +8 -8
  25. package/dist/exec/host.js +9 -9
  26. package/dist/exec/os.d.ts +36 -69
  27. package/dist/exec/os.js +65 -159
  28. package/dist/exec/sandbox-messages.d.ts +14 -0
  29. package/dist/exec/sandbox-messages.js +21 -0
  30. package/dist/exec/shared.d.ts +21 -36
  31. package/dist/exec/shared.js +30 -164
  32. package/dist/exec/switch.d.ts +38 -55
  33. package/dist/exec/switch.js +58 -108
  34. package/dist/exec/types.d.ts +8 -18
  35. package/dist/index.d.ts +1 -1
  36. package/dist/network.d.ts +7 -7
  37. package/dist/network.js +11 -18
  38. package/dist/policy-store.d.ts +7 -8
  39. package/dist/policy-store.js +11 -15
  40. package/dist/policy.d.ts +25 -100
  41. package/dist/policy.js +44 -146
  42. package/dist/server-ops.d.ts +15 -35
  43. package/dist/server-ops.js +36 -117
  44. package/dist/service/launchd.d.ts +11 -1
  45. package/dist/service/launchd.js +14 -5
  46. package/dist/state.d.ts +15 -16
  47. package/dist/state.js +38 -36
  48. package/package.json +2 -2
  49. package/dist/proxy-guard.d.ts +0 -58
  50. package/dist/proxy-guard.js +0 -137
package/dist/cli.js CHANGED
@@ -3,7 +3,8 @@ import { parseCommandLine, USAGE, UsageError } from "./args.js";
3
3
  import { drain, drainAndWait } from "./commands/drain.js";
4
4
  import { login } from "./commands/login.js";
5
5
  import { logout } from "./commands/logout.js";
6
- import { confirmRisk, isolationRefusal, needsConfirmation, policyCommand, policyRisk, } from "./commands/policy.js";
6
+ import { modeCommand } from "./commands/mode.js";
7
+ import { policyCommand } from "./commands/policy.js";
7
8
  import { serviceCommand } from "./commands/service.js";
8
9
  import { start } from "./commands/start.js";
9
10
  import { status } from "./commands/status.js";
@@ -20,24 +21,22 @@ async function askOnTerminal(question) {
20
21
  rl.close();
21
22
  }
22
23
  }
23
- /** Shown once when a Docker-mode device's policy says `isolation: none` (it is ignored there). */
24
- export const DOCKER_ISOLATION_IGNORED = "policy.json says isolation none, which works in OS mode only: this device runs commands in " +
25
- "Docker mode, always in a container.";
26
- /** Logged when commands start or stop running without a sandbox. */
27
- export const UNSANDBOXED_ON = "Commands on this device now run without a sandbox (isolation none).";
28
- export const UNSANDBOXED_OFF = "Commands on this device run in the sandbox again; commands still running without one were " +
29
- "stopped.";
24
+ /**
25
+ * Logged when the local policy switches between auto and sandbox. It names the local choice, not
26
+ * the effective mode: the organization's ceiling still cuts it (a device whose org forbids auto
27
+ * runs in the sandbox even with this policy).
28
+ */
29
+ export const AUTO_MODE_ON = "This machine's local policy is auto mode; the deployment's ceiling applies.";
30
+ export const AUTO_MODE_OFF = "This machine's local policy is sandbox mode; commands still running in auto mode were stopped.";
30
31
  /**
31
32
  * The executor for the credential's mode; the program's state directory is unreadable to
32
- * sandboxed commands. OS mode serves a {@link SwitchingExecutor}: the OS sandbox, or no sandbox
33
- * when the owner set `isolation none` locally and the command's tier is `open` (spec §5.4).
33
+ * sandboxed commands. OS mode serves a {@link SwitchingExecutor}: the host (auto mode) or the OS
34
+ * sandbox (sandbox mode), chosen per command from the policy and the kernel's ceiling (spec §4.1).
34
35
  */
35
36
  function defaultCreateExecutor(stateDir, home, err) {
36
37
  return async (cred, store) => {
37
38
  const policy = () => store.current();
38
39
  if (cred.mode === "docker") {
39
- if (policy().isolation === "none")
40
- err(DOCKER_ISOLATION_IGNORED);
41
40
  const { createDockerExecutor } = await import("./exec/docker.js");
42
41
  return createDockerExecutor({
43
42
  dir: cred.dir,
@@ -57,7 +56,7 @@ function defaultCreateExecutor(stateDir, home, err) {
57
56
  home,
58
57
  denyRead: [stateDir],
59
58
  });
60
- return new SwitchingExecutor(sandboxed, new HostExecutor({ dir: cred.dir }), policy, (i) => err(i === "none" ? UNSANDBOXED_ON : UNSANDBOXED_OFF));
59
+ return new SwitchingExecutor(sandboxed, new HostExecutor({ dir: cred.dir }), policy, (mode) => err(mode === "auto" ? AUTO_MODE_ON : AUTO_MODE_OFF));
61
60
  };
62
61
  }
63
62
  /** Runs one command line and returns the exit code. */
@@ -118,25 +117,15 @@ export async function runCli(argv, io = {}) {
118
117
  ...(io.sleep && { sleep: io.sleep }),
119
118
  ...(cmd.timeoutSeconds !== undefined && { timeoutMs: cmd.timeoutSeconds * 1000 }),
120
119
  });
121
- case "policy": {
122
- // `set isolation none` that cannot apply (Docker mode, no local tier open): refused before
123
- // any risk text or question (policyCommand refuses it too, under the lock).
124
- const refusal = isolationRefusal(cmd, dir);
125
- if (refusal !== undefined) {
126
- err(refusal);
127
- return 2;
128
- }
129
- // `set tier open` / `set isolation none` without --yes: ask on a terminal (after printing
130
- // the risk text); elsewhere policyCommand refuses them.
131
- if (needsConfirmation(cmd) && (io.stdinIsTTY ?? process.stdin.isTTY === true)) {
132
- if (!(await confirmRisk(cmd, { out, ask: io.ask ?? askOnTerminal }))) {
133
- err(policyRisk(cmd)?.needsYes ?? "Nothing changed.");
134
- return 1;
135
- }
136
- return policyCommand(cmd, { stateDir: dir, out, err, confirmed: true });
137
- }
120
+ case "policy":
138
121
  return policyCommand(cmd, { stateDir: dir, out, err });
139
- }
122
+ case "mode":
123
+ return modeCommand(cmd, {
124
+ stateDir: dir,
125
+ out,
126
+ err,
127
+ ...((io.stdinIsTTY ?? process.stdin.isTTY === true) && { ask: io.ask ?? askOnTerminal }),
128
+ });
140
129
  case "service":
141
130
  return serviceCommand(cmd.action, {
142
131
  stateDir: dir,
package/dist/client.d.ts CHANGED
@@ -20,8 +20,6 @@ export interface ConnectOptions {
20
20
  random?: () => number;
21
21
  now?: () => number;
22
22
  programVersion?: string;
23
- /** The platform the policy summary describes (default: this process's; for tests). */
24
- platform?: NodeJS.Platform;
25
23
  /** A connection must stay up this long before the backoff resets (default 10 s). */
26
24
  stableMs?: number;
27
25
  /** Terminate a socket that heard nothing from the server for this long (default 60 s). */
package/dist/client.js CHANGED
@@ -46,12 +46,11 @@ export function connect(cred, executor, opts = {}) {
46
46
  let exitAfterStop;
47
47
  let session;
48
48
  let drainTimer;
49
- /** What the requests of this run have seen (the latest exec's tier limits), over reconnects. */
49
+ /** What the requests of this run have seen (the latest exec's mode), over reconnects. */
50
50
  const seen = {};
51
51
  const ctx = {
52
52
  seen,
53
53
  ...(opts.policy !== undefined && { policy: opts.policy }),
54
- ...(opts.platform !== undefined && { platform: opts.platform }),
55
54
  };
56
55
  const running = new Map();
57
56
  /** Requests the kernel gave up on: never started, or their result is dropped. */
@@ -79,9 +78,9 @@ export function connect(cred, executor, opts = {}) {
79
78
  let sentPolicy;
80
79
  /**
81
80
  * Pushes the policy summary when it differs from the one the deployment last got: the owner
82
- * changed the policy on the machine (`capybara-device policy ...`), the localhost proxy guard
83
- * flipped, or an exec brought a new tier ceiling. Without it the deployment would learn the
84
- * change only at the next connect.
81
+ * changed the mode or the policy on the machine (`capybara-device mode` / `policy ...`), or an
82
+ * exec brought a new mode ceiling. Without it the deployment would learn the change only at the
83
+ * next connect.
85
84
  */
86
85
  const pushPolicy = () => {
87
86
  if (!isOpen())
@@ -198,7 +197,7 @@ export function connect(cred, executor, opts = {}) {
198
197
  sentPolicy = JSON.stringify(res.result.policy);
199
198
  }
200
199
  deliver(res);
201
- // an exec may have changed the facts (the proxy guard, the tier ceiling)
200
+ // an exec may have changed the ceiling (the effective mode)
202
201
  pushPolicy();
203
202
  }
204
203
  maybeFinishDrain();
@@ -240,9 +239,9 @@ export function connect(cred, executor, opts = {}) {
240
239
  };
241
240
  /**
242
241
  * The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
243
- * mode has no per-host view); the device applies tiers (`limits.tier` / `defaultTier` /
244
- * `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen; then the
245
- * outcomes of the latest policy ops by op id.
242
+ * mode has no per-host view); the device applies `limits.mode` / `limits.network` (`mode`); the
243
+ * policy summary is the store's policy now, with the effective mode and the latest ceiling seen;
244
+ * then the outcomes of the latest policy ops by op id.
246
245
  */
247
246
  const hello = () => {
248
247
  const summary = summaryNow();
@@ -253,7 +252,7 @@ export function connect(cred, executor, opts = {}) {
253
252
  // the policy op, logged by its op id (policy-ops.json next to the policy)
254
253
  if (opts.policy !== undefined)
255
254
  features.push("policyOp", "policyOpId");
256
- features.push("tiers");
255
+ features.push("mode");
257
256
  return {
258
257
  type: "hello",
259
258
  protocol: DEVICE_PROTOCOL_VERSION,
@@ -272,12 +271,21 @@ export function connect(cred, executor, opts = {}) {
272
271
  let attempt = 0;
273
272
  /** When a failing connection was last reported; reset once a connection stays up. */
274
273
  let lastReport;
275
- /** Reports why connecting keeps failing, at most once a minute. */
274
+ /** The failure last reported: a different failure is reported at once, not after the interval. */
275
+ let lastReportText;
276
+ /**
277
+ * Reports why connecting keeps failing: a failure different from the last one is reported at
278
+ * once, the same one at most once a minute. A long outage therefore does not flood the log.
279
+ */
276
280
  const reportFailure = (why) => {
277
281
  const t = now();
278
- if (lastReport !== undefined && t - lastReport < FAILURE_REPORT_INTERVAL_MS)
282
+ if (why === lastReportText &&
283
+ lastReport !== undefined &&
284
+ t - lastReport < FAILURE_REPORT_INTERVAL_MS) {
279
285
  return;
286
+ }
280
287
  lastReport = t;
288
+ lastReportText = why;
281
289
  err(`${why} Retrying.`);
282
290
  };
283
291
  const runSession = () => new Promise((resolve) => {
@@ -304,8 +312,11 @@ export function connect(cred, executor, opts = {}) {
304
312
  opened = true;
305
313
  heard();
306
314
  stable = setTimeout(() => {
315
+ // A connection that stayed up enough is a success: the next failure starts at the
316
+ // base delay, and is reported again even if it is the same message as before.
307
317
  attempt = 0;
308
318
  lastReport = undefined;
319
+ lastReportText = undefined;
309
320
  }, stableMs);
310
321
  sock.send(JSON.stringify(hello()));
311
322
  if (opts.policy !== undefined)
@@ -1,4 +1,4 @@
1
- import type { SandboxTier } from "@capybara-hq/plugin-sdk";
1
+ import type { SandboxMode } from "./state.js";
2
2
  export declare const COMMAND_LOG_MAX_BYTES: number;
3
3
  export interface CommandLogEntry {
4
4
  time: string;
@@ -8,10 +8,8 @@ export interface CommandLogEntry {
8
8
  accountId: string;
9
9
  } | null;
10
10
  exitCode: number | null;
11
- /** An exec's tier (the owner's choice cut to the org's ceiling). */
12
- tier?: SandboxTier;
13
- /** An exec's isolation: `none` = it ran (or was refused for running) without a sandbox. */
14
- isolation?: "sandbox" | "none";
11
+ /** An exec's mode: auto (no OS sandbox) or sandbox. */
12
+ mode?: SandboxMode;
15
13
  /**
16
14
  * An audit line: a policy change from the deployment (`policy add a.com by <name> (<id>) via
17
15
  * web, approval <id>`) or the grants an exec was given (`grants run <id> by <id>: a.com`).
@@ -1,9 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
2
3
  import { hostname } from "node:os";
3
4
  import { isAbsolute, resolve } from "node:path";
4
5
  import { ApiError, authorize, programVersion, token } from "../api.js";
5
6
  import { prepareDeviceDir } from "../exec/shared.js";
6
- import { DEFAULT_MAX_FRAME_BYTES, defaultWorkDir, readCredential, writeCredential, } from "../state.js";
7
+ import { DEFAULT_MAX_FRAME_BYTES, DEFAULT_POLICY, defaultWorkDir, policyPath, readCredential, readPolicy, withPolicyLock, writeCredential, writePolicy, } from "../state.js";
8
+ import { AUTO_MODE_LOGIN_LINE, AUTO_MODE_RISK_TEXT, AUTO_POLICY_REFUSED_LOGIN_LINE, SANDBOX_MODE_LOGIN_LINE, SANDBOX_POLICY_LOGIN_LINE, } from "./mode.js";
7
9
  const SLOW_DOWN_STEP_SECONDS = 5;
8
10
  function defaultOpen(platform) {
9
11
  return (url) => {
@@ -18,6 +20,24 @@ function defaultOpen(platform) {
18
20
  }
19
21
  };
20
22
  }
23
+ /**
24
+ * A fresh device in an organization that forbids auto mode starts in sandbox mode (auto mode
25
+ * spec §4.1): the default policy is auto, which the kernel refuses at every exec, so the login
26
+ * line would otherwise describe a mode the machine does not run. Written under the policy lock,
27
+ * and only while no policy file exists: an existing policy is the owner's choice and is never
28
+ * changed here. Returns whether this call created the file.
29
+ */
30
+ function persistSandboxPolicy(stateDir) {
31
+ const file = policyPath(stateDir);
32
+ if (existsSync(file))
33
+ return false;
34
+ return withPolicyLock(stateDir, () => {
35
+ if (existsSync(file))
36
+ return false;
37
+ writePolicy(stateDir, { ...DEFAULT_POLICY, mode: "sandbox" });
38
+ return true;
39
+ });
40
+ }
21
41
  /** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
22
42
  export function normalizeUrl(raw) {
23
43
  let u;
@@ -86,6 +106,29 @@ export async function login(cmd, deps) {
86
106
  : resolve(cmd.dir);
87
107
  // Recreates a lost directory, marker or root: the device starts afresh.
88
108
  prepareDeviceDir(dir);
109
+ // The printed line follows this machine's persisted policy in both branches, not the
110
+ // organization's allowance: sandbox mode is also the state an earlier login in an
111
+ // auto-forbidden organization left behind. The default mode is auto; an organization that
112
+ // forbids it gets sandbox mode written as this device's policy before the credential makes
113
+ // the login final. An existing policy is the owner's choice: the kernel refuses auto mode
114
+ // at every command if the organization forbids it and the owner keeps auto.
115
+ let mode = "auto";
116
+ if (granted.autoMode === "off") {
117
+ try {
118
+ mode = persistSandboxPolicy(deps.stateDir) ? "sandbox" : readPolicy(deps.stateDir).mode;
119
+ }
120
+ catch (e) {
121
+ err(`Cannot set the local policy in ${deps.stateDir}: ${e.message}`);
122
+ }
123
+ }
124
+ else {
125
+ try {
126
+ mode = readPolicy(deps.stateDir).mode;
127
+ }
128
+ catch (e) {
129
+ err(`Cannot read the local policy in ${deps.stateDir}: ${e.message}`);
130
+ }
131
+ }
89
132
  writeCredential(deps.stateDir, {
90
133
  url: baseUrl,
91
134
  connectUrl: granted.connectUrl,
@@ -98,6 +141,17 @@ export async function login(cmd, deps) {
98
141
  maxFrameBytes: granted.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES,
99
142
  });
100
143
  out(`Logged in. Device ${granted.deviceId}, working directory ${dir}`);
144
+ // The risk text is shown once at login (spec §8), and only when this machine runs auto.
145
+ if (granted.autoMode === "off") {
146
+ out(mode === "sandbox" ? SANDBOX_MODE_LOGIN_LINE : AUTO_POLICY_REFUSED_LOGIN_LINE);
147
+ }
148
+ else if (mode === "sandbox") {
149
+ out(SANDBOX_POLICY_LOGIN_LINE);
150
+ }
151
+ else {
152
+ out(AUTO_MODE_LOGIN_LINE);
153
+ out(AUTO_MODE_RISK_TEXT);
154
+ }
101
155
  out("Run `capybara-device start` to bring it online (or `capybara-device service install` to connect at login).");
102
156
  return 0;
103
157
  }
@@ -0,0 +1,52 @@
1
+ import type { Command } from "../args.js";
2
+ /**
3
+ * Shown once before auto mode is turned on, and once at login in an organization that allows it
4
+ * (spec §8): the trust model is command review, not the OS sandbox.
5
+ */
6
+ export declare const AUTO_MODE_RISK_TEXT: string;
7
+ /** The refusal of `capybara-device mode auto` without `--yes` or a `y` at the prompt. */
8
+ export declare const MODE_AUTO_NEEDS_YES = "Nothing changed. To run commands in auto mode, run: capybara-device mode auto --yes";
9
+ /** Printed before the question `capybara-device mode auto` asks on a terminal. */
10
+ export declare const MODE_AUTO_PROMPT = "Run agent commands on this computer as you, in auto mode? [y/N] ";
11
+ /**
12
+ * The line `login` prints when the organization allows auto mode and this machine's policy is
13
+ * auto (the default).
14
+ */
15
+ export declare const AUTO_MODE_LOGIN_LINE: string;
16
+ /**
17
+ * The line `login` prints when the organization allows auto mode but this machine's persisted
18
+ * policy is sandbox mode (an earlier login in an auto-forbidden organization, or the owner's
19
+ * switch): the line follows the machine, not the allowance.
20
+ */
21
+ export declare const SANDBOX_POLICY_LOGIN_LINE: string;
22
+ /** The line `login` prints when the organization forbids auto mode and the policy now says so. */
23
+ export declare const SANDBOX_MODE_LOGIN_LINE: string;
24
+ /**
25
+ * The line `login` prints when the organization forbids auto mode but the machine keeps its own
26
+ * auto policy: the kernel refuses every command until the owner switches the machine.
27
+ */
28
+ export declare const AUTO_POLICY_REFUSED_LOGIN_LINE: string;
29
+ export interface ModeDeps {
30
+ stateDir: string;
31
+ out: (line: string) => void;
32
+ err: (line: string) => void;
33
+ /**
34
+ * Asks the question on a terminal (only when standard input is one). Without it and without
35
+ * `--yes`, `mode auto` changes nothing.
36
+ */
37
+ ask?: (question: string) => Promise<string>;
38
+ /**
39
+ * Whether the OS sandbox can run here (default: the runtime's check). `mode sandbox` is refused
40
+ * when it cannot; injectable for tests.
41
+ */
42
+ sandboxAvailable?: () => {
43
+ ok: true;
44
+ } | {
45
+ ok: false;
46
+ reason: string;
47
+ };
48
+ }
49
+ /** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
50
+ export declare function modeCommand(cmd: Extract<Command, {
51
+ command: "mode";
52
+ }>, deps: ModeDeps): Promise<number>;
@@ -0,0 +1,108 @@
1
+ import { sandboxUnavailableSwitchRefusal } from "../exec/sandbox-messages.js";
2
+ import { PolicyStore } from "../policy-store.js";
3
+ import { policyPath, readCredential } from "../state.js";
4
+ /**
5
+ * Shown once before auto mode is turned on, and once at login in an organization that allows it
6
+ * (spec §8): the trust model is command review, not the OS sandbox.
7
+ */
8
+ export const AUTO_MODE_RISK_TEXT = "In auto mode, agent commands run on this computer as you: they can read and write all your " +
9
+ "files, use your credentials (SSH keys, cloud accounts, keychain), Docker and any network, and " +
10
+ "the deployment reviews every command before it runs. Prompt injection can make an agent try " +
11
+ "to delete files or send your credentials away; the review blocks or asks about the dangerous " +
12
+ "ones. Such commands can also read this program's own credential: if you suspect misuse, run " +
13
+ "capybara-device logout and log in again.";
14
+ /** The refusal of `capybara-device mode auto` without `--yes` or a `y` at the prompt. */
15
+ export const MODE_AUTO_NEEDS_YES = "Nothing changed. To run commands in auto mode, run: capybara-device mode auto --yes";
16
+ /** Printed before the question `capybara-device mode auto` asks on a terminal. */
17
+ export const MODE_AUTO_PROMPT = "Run agent commands on this computer as you, in auto mode? [y/N] ";
18
+ /**
19
+ * The line `login` prints when the organization allows auto mode and this machine's policy is
20
+ * auto (the default).
21
+ */
22
+ export const AUTO_MODE_LOGIN_LINE = "New logins start in auto mode: agent commands run as you on this machine, and the deployment " +
23
+ "reviews every command. Switch with `capybara-device mode sandbox`.";
24
+ /**
25
+ * The line `login` prints when the organization allows auto mode but this machine's persisted
26
+ * policy is sandbox mode (an earlier login in an auto-forbidden organization, or the owner's
27
+ * switch): the line follows the machine, not the allowance.
28
+ */
29
+ export const SANDBOX_POLICY_LOGIN_LINE = "This organization allows auto mode, but this machine's local policy is sandbox mode: agent " +
30
+ "commands run inside the OS sandbox here. Switch with `capybara-device mode auto`.";
31
+ /** The line `login` prints when the organization forbids auto mode and the policy now says so. */
32
+ export const SANDBOX_MODE_LOGIN_LINE = "This organization does not allow auto mode, so this device runs in sandbox mode: agent " +
33
+ "commands run inside the OS sandbox on this machine.";
34
+ /**
35
+ * The line `login` prints when the organization forbids auto mode but the machine keeps its own
36
+ * auto policy: the kernel refuses every command until the owner switches the machine.
37
+ */
38
+ export const AUTO_POLICY_REFUSED_LOGIN_LINE = "This organization does not allow auto mode, but this machine's local policy is auto mode: the " +
39
+ "deployment refuses every command until you run `capybara-device mode sandbox`.";
40
+ /** Whether this machine is logged in in Docker mode (false when unknown). */
41
+ function dockerRunMode(stateDir) {
42
+ try {
43
+ return readCredential(stateDir)?.mode === "docker";
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ /** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
50
+ export async function modeCommand(cmd, deps) {
51
+ const { stateDir, out, err } = deps;
52
+ let store;
53
+ try {
54
+ store = new PolicyStore(stateDir);
55
+ }
56
+ catch (e) {
57
+ err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
58
+ return 1;
59
+ }
60
+ const mode = cmd.mode;
61
+ if (mode === undefined) {
62
+ const now = store.current().mode;
63
+ out(`Mode: ${now}.`);
64
+ out(now === "auto"
65
+ ? "Commands run as you on this machine; the deployment reviews every command."
66
+ : "Commands run in the OS sandbox; only the workspace, skills and temporary files are " +
67
+ "writable and the network reaches the allowed hosts.");
68
+ return 0;
69
+ }
70
+ if (mode === "auto") {
71
+ // The risk text is printed once, whether --yes was given or the question is asked.
72
+ out(AUTO_MODE_RISK_TEXT);
73
+ if (cmd.yes !== true) {
74
+ if (deps.ask === undefined) {
75
+ err(MODE_AUTO_NEEDS_YES);
76
+ return 2;
77
+ }
78
+ const answer = (await deps.ask(MODE_AUTO_PROMPT)).trim().toLowerCase();
79
+ if (answer !== "y" && answer !== "yes") {
80
+ err("Nothing changed.");
81
+ return 1;
82
+ }
83
+ }
84
+ }
85
+ let next;
86
+ if (mode === "sandbox" && !dockerRunMode(stateDir)) {
87
+ // Sandbox mode cannot run a command without the OS sandbox; refuse the switch on such a
88
+ // machine and leave the policy as it is (auto mode keeps working).
89
+ const os = await import("../exec/os.js");
90
+ const available = deps.sandboxAvailable?.() ?? os.sandboxAvailability();
91
+ if (!available.ok) {
92
+ err(sandboxUnavailableSwitchRefusal(available.reason));
93
+ return 1;
94
+ }
95
+ }
96
+ try {
97
+ next = store.update((p) => ({ ...p, mode })).mode;
98
+ }
99
+ catch (e) {
100
+ err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
101
+ return 1;
102
+ }
103
+ out(next === "auto"
104
+ ? "This machine's local policy is now auto mode (from the next command); the deployment's " +
105
+ "ceiling still applies."
106
+ : "This machine's local policy is now sandbox mode (from the next command).");
107
+ return 0;
108
+ }
@@ -1,77 +1,23 @@
1
1
  import type { Command } from "../args.js";
2
- import { type TierFacts } from "../policy.js";
3
- import { type ProxyGuardResult } from "../proxy-guard.js";
4
2
  import { type Policy } from "../state.js";
5
3
  export interface PolicyDeps {
6
4
  stateDir: string;
7
5
  out: (line: string) => void;
8
6
  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;
17
7
  }
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>;
48
- /** What the OS mode does not enforce yet, shown with every `show` and `set`. */
8
+ /** What OS mode does not enforce yet, shown with `show` and with a limits change. */
49
9
  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[];
10
+ /** Shown when a Docker-mode device's policy is shown or given allowed domains. */
11
+ export declare const DOCKER_DOMAIN_NOTE: string;
12
+ /** What `policy show` says the mode gives on this machine (English, one line each). */
13
+ export declare function describeMode(policy: Policy, runMode?: "os" | "docker"): string[];
66
14
  /**
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.
15
+ * `policy show` prints the local policy and what its mode gives on this machine;
16
+ * `policy set <key> <value>` replaces one field; `policy add|remove <key> <value>` adds or removes
17
+ * entries of a list field. The mode is set with `capybara-device mode`. The machine's user edits
18
+ * this file; the deployment changes it only through the `policy` op (narrowing only: hosts and
19
+ * `mode: "sandbox"`, never auto). Writes take policy.json.lock, and a running program applies the
20
+ * change at its next command.
75
21
  */
76
22
  export declare function policyCommand(cmd: Extract<Command, {
77
23
  command: "policy";