@capybara-hq/device 0.1.0-rc.0 → 0.1.0-rc.10

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 (64) hide show
  1. package/README.md +187 -44
  2. package/dist/api.d.ts +6 -1
  3. package/dist/args.d.ts +14 -3
  4. package/dist/args.js +74 -10
  5. package/dist/cli.d.ts +14 -2
  6. package/dist/cli.js +59 -10
  7. package/dist/client.d.ts +14 -3
  8. package/dist/client.js +92 -18
  9. package/dist/command-log.d.ts +8 -0
  10. package/dist/commands/drain.d.ts +13 -0
  11. package/dist/commands/drain.js +28 -0
  12. package/dist/commands/login.js +68 -11
  13. package/dist/commands/mode.d.ts +52 -0
  14. package/dist/commands/mode.js +108 -0
  15. package/dist/commands/policy.d.ts +13 -4
  16. package/dist/commands/policy.js +162 -33
  17. package/dist/commands/service.d.ts +18 -3
  18. package/dist/commands/service.js +175 -9
  19. package/dist/commands/start.d.ts +14 -3
  20. package/dist/commands/start.js +37 -5
  21. package/dist/commands/status.js +12 -4
  22. package/dist/commands/stop.d.ts +9 -2
  23. package/dist/commands/stop.js +13 -2
  24. package/dist/exec/docker.d.ts +41 -13
  25. package/dist/exec/docker.js +123 -57
  26. package/dist/exec/fs-helper.d.ts +13 -8
  27. package/dist/exec/fs-helper.js +31 -13
  28. package/dist/exec/groups.d.ts +42 -0
  29. package/dist/exec/groups.js +100 -0
  30. package/dist/exec/host.d.ts +53 -0
  31. package/dist/exec/host.js +183 -0
  32. package/dist/exec/os.d.ts +85 -15
  33. package/dist/exec/os.js +208 -36
  34. package/dist/exec/reap.d.ts +41 -0
  35. package/dist/exec/reap.js +89 -0
  36. package/dist/exec/sandbox-messages.d.ts +14 -0
  37. package/dist/exec/sandbox-messages.js +21 -0
  38. package/dist/exec/shared.d.ts +42 -13
  39. package/dist/exec/shared.js +94 -16
  40. package/dist/exec/switch.d.ts +91 -0
  41. package/dist/exec/switch.js +164 -0
  42. package/dist/exec/types.d.ts +28 -4
  43. package/dist/index.d.ts +1 -1
  44. package/dist/network.d.ts +45 -0
  45. package/dist/network.js +154 -0
  46. package/dist/pid.d.ts +13 -1
  47. package/dist/pid.js +54 -7
  48. package/dist/policy-ops.d.ts +47 -0
  49. package/dist/policy-ops.js +90 -0
  50. package/dist/policy-store.d.ts +43 -0
  51. package/dist/policy-store.js +94 -0
  52. package/dist/policy.d.ts +36 -16
  53. package/dist/policy.js +77 -19
  54. package/dist/public-suffix.d.ts +6 -0
  55. package/dist/public-suffix.js +79 -0
  56. package/dist/server-ops.d.ts +46 -7
  57. package/dist/server-ops.js +285 -29
  58. package/dist/service/installed.d.ts +5 -0
  59. package/dist/service/installed.js +14 -0
  60. package/dist/service/launchd.d.ts +11 -1
  61. package/dist/service/launchd.js +14 -5
  62. package/dist/state.d.ts +50 -6
  63. package/dist/state.js +195 -16
  64. package/package.json +3 -3
package/dist/policy.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
+ import { validateAllowHost, } from "@capybara-hq/plugin-sdk";
3
4
  /**
4
- * Paths no command may read (spec §13.6, extended by ruling R19): SSH keys, cloud CLI
5
+ * Paths no sandboxed command may read (spec §13.6, extended by ruling R19): SSH keys, cloud CLI
5
6
  * credentials, container and Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the
6
7
  * macOS keychains, and the browser profile directories (Chrome, Firefox, Chromium, Safari, Brave,
7
- * Edge, Arc). Relative to `~`.
8
+ * Edge, Arc). Relative to `~`. Auto mode runs as the owner and does not apply them: command review
9
+ * in the kernel does (spec §5.2).
8
10
  */
9
11
  export const DENIED_SECRET_PATHS = Object.freeze([
10
12
  "~/.ssh",
@@ -40,7 +42,7 @@ export function deniedSecretPaths(home = homedir()) {
40
42
  }
41
43
  /**
42
44
  * Paths sandbox-runtime makes writable without being asked (its own temp directory and two home
43
- * convenience directories). They lie outside the environment directory, so they are denied.
45
+ * convenience directories). They lie outside the device directory, so they are denied.
44
46
  */
45
47
  export function implicitWritePaths(home = homedir()) {
46
48
  return [
@@ -51,25 +53,54 @@ export function implicitWritePaths(home = homedir()) {
51
53
  ];
52
54
  }
53
55
  /** True when the allowlist entry `pattern` admits every host `host` names (`host` may be a wildcard). */
54
- function covers(pattern, host) {
56
+ export function covers(pattern, host) {
55
57
  if (pattern === host)
56
58
  return true;
57
59
  // `*.x.com` admits `a.x.com` and `*.a.x.com`, never the apex `x.com`.
58
60
  return pattern.startsWith("*.") && host.endsWith(pattern.slice(1));
59
61
  }
60
62
  /**
61
- * The domains one command may reach: what the environment's egress allows, cut to the local
62
- * policy. The cloud can only narrow it: an empty policy allows nothing, whatever the egress.
63
+ * The mode a command runs in (spec §4.1): the device's own choice cut to the kernel's ceiling. A
64
+ * sandbox-mode machine never runs auto because the organization allows it; an auto-mode machine in
65
+ * an organization that forbids auto runs in the sandbox (and its summary says so).
63
66
  */
64
- export function effectiveEgress(policy, limits) {
65
- const local = policy.allowedDomains.map((d) => d.toLowerCase());
66
- if (limits.egress === "none")
67
+ export function effectiveMode(policy, limits) {
68
+ return policy.mode === "sandbox" || limits.mode === "sandbox" ? "sandbox" : "auto";
69
+ }
70
+ /** The granted hosts that apply to one command, within the kernel's network limits. */
71
+ export function grantedHosts(limits, grants) {
72
+ if (grants === undefined)
67
73
  return [];
68
- if (limits.egress === "open")
69
- return [...new Set(local)];
70
74
  const out = new Set();
71
- for (const raw of limits.allowHosts) {
75
+ for (const raw of grants.hosts) {
76
+ if (typeof raw !== "string")
77
+ continue;
72
78
  const host = raw.toLowerCase();
79
+ // Only valid exact public hosts (no wildcards, addresses or internal names).
80
+ if (validateAllowHost(host).length > 0)
81
+ continue;
82
+ if (limits.network.kind === "open-public" ||
83
+ limits.network.hosts.some((p) => covers(p.toLowerCase(), host))) {
84
+ out.add(host);
85
+ }
86
+ }
87
+ return [...out];
88
+ }
89
+ /**
90
+ * The domains one sandbox-mode command may reach (spec §4.1, §4.4): the intersection of the
91
+ * device's own `allowedDomains` and the kernel's allowlist (`limits.network`), plus the command's
92
+ * grants. An empty list allows nothing. Auto mode ignores both lists: the command has the machine's
93
+ * own network, so this returns no list there (the OS sandbox is not running).
94
+ */
95
+ export function effectiveEgress(policy, limits, grants) {
96
+ if (effectiveMode(policy, limits) === "auto")
97
+ return [];
98
+ const out = new Set();
99
+ const local = policy.allowedDomains.map((d) => d.toLowerCase());
100
+ // `open-public` is for cloud instances only; a local sandbox-mode device is stricter and keeps
101
+ // its own allowlist.
102
+ const orgHosts = limits.network.kind === "allowlist" ? limits.network.hosts.map((h) => h.toLowerCase()) : local;
103
+ for (const host of orgHosts) {
73
104
  for (const p of local) {
74
105
  // The intersection of two entries is the narrower one, if either contains the other.
75
106
  if (covers(p, host))
@@ -78,20 +109,47 @@ export function effectiveEgress(policy, limits) {
78
109
  out.add(p);
79
110
  }
80
111
  }
112
+ for (const h of grantedHosts(limits, grants))
113
+ out.add(h);
81
114
  return [...out];
82
115
  }
116
+ /** Characters the sandbox runtime reads as a glob in a path entry. */
117
+ const GLOB_CHARS = /[*?[\]{}]/;
118
+ /**
119
+ * Write denies for git under each writable root (spec §5.2.1): `.git/hooks` and `.git/config`
120
+ * (a hook or `core.sshCommand` set by a command would run when the owner later runs git there).
121
+ * The runtime has the same mandatory denies, but anchored at this program's own working directory,
122
+ * which may not contain the roots. A root whose path reads as a glob gets none (it cannot be
123
+ * anchored literally); the runtime's own denies still apply when it lies under the working
124
+ * directory.
125
+ */
126
+ function gitWriteDenies(writable) {
127
+ const out = [];
128
+ for (const root of writable) {
129
+ if (GLOB_CHARS.test(root))
130
+ continue;
131
+ out.push(`${root}/.git/hooks/**`, `${root}/**/.git/hooks/**`);
132
+ out.push(`${root}/.git/config`, `${root}/**/.git/config`);
133
+ }
134
+ return out;
135
+ }
83
136
  /**
84
- * The sandbox-runtime configuration: writes only under the workspace and tmp roots (the runtime's
85
- * implicit write paths denied), skills read only, the secret paths (plus `opts.denyRead`, such as this program's own state directory)
86
- * unreadable, and network limited to `egress`.
137
+ * The sandbox-runtime configuration of sandbox mode (spec §4.1, §4.4): today's strict profile
138
+ * only. Writes only under the workspace and tmp roots (the runtime's implicit write paths
139
+ * denied), skills read only, the secret paths (plus `opts.denyRead`, such as this program's own
140
+ * state directory) unreadable, and network limited to `egress`. No local binding, no unix sockets.
87
141
  */
88
- export function srtConfig(_policy, roots, egress, opts = {}) {
142
+ export function srtConfig(roots, egress, opts = {}) {
143
+ const allowWrite = [roots.workspace, roots.tmp];
89
144
  return {
90
145
  filesystem: {
91
146
  denyRead: [...deniedSecretPaths(opts.home), ...(opts.denyRead ?? [])],
92
- allowWrite: [roots.workspace, roots.tmp],
93
- denyWrite: [roots.skills, ...implicitWritePaths()],
147
+ allowWrite,
148
+ denyWrite: [roots.skills, ...implicitWritePaths(opts.home), ...gitWriteDenies(allowWrite)],
149
+ },
150
+ network: {
151
+ allowedDomains: [...egress],
152
+ deniedDomains: [],
94
153
  },
95
- network: { allowedDomains: [...egress], deniedDomains: [] },
96
154
  };
97
155
  }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Why a `*.` wildcard is too broad to add from the device page: its remainder is a whole public
3
+ * suffix (one label such as `com`, or a known multi-label one such as `co.uk`, `github.io`);
4
+ * null for an exact host or a narrower wildcard.
5
+ */
6
+ export declare function publicSuffixWildcard(pattern: string): string | null;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Public suffixes of more than one label that a device-page wildcard may not cover (a small
3
+ * built-in list, not the public suffix list; the kernel keeps the same list in
4
+ * packages/kernel/src/devices/public-suffix.ts). Includes the shared hosting suffixes where each
5
+ * subdomain belongs to someone else.
6
+ */
7
+ const MULTI_LABEL_SUFFIXES = new Set([
8
+ "ac.uk",
9
+ "co.uk",
10
+ "gov.uk",
11
+ "ltd.uk",
12
+ "me.uk",
13
+ "net.uk",
14
+ "org.uk",
15
+ "plc.uk",
16
+ "com.cn",
17
+ "edu.cn",
18
+ "gov.cn",
19
+ "net.cn",
20
+ "org.cn",
21
+ "com.hk",
22
+ "org.hk",
23
+ "com.tw",
24
+ "org.tw",
25
+ "co.jp",
26
+ "ne.jp",
27
+ "or.jp",
28
+ "ac.jp",
29
+ "co.kr",
30
+ "or.kr",
31
+ "com.au",
32
+ "net.au",
33
+ "org.au",
34
+ "edu.au",
35
+ "co.nz",
36
+ "org.nz",
37
+ "com.br",
38
+ "com.mx",
39
+ "com.sg",
40
+ "com.my",
41
+ "co.in",
42
+ "co.za",
43
+ "com.tr",
44
+ "com.ar",
45
+ "github.io",
46
+ "gitlab.io",
47
+ "pages.dev",
48
+ "workers.dev",
49
+ "vercel.app",
50
+ "netlify.app",
51
+ "herokuapp.com",
52
+ "appspot.com",
53
+ "web.app",
54
+ "firebaseapp.com",
55
+ "azurewebsites.net",
56
+ "cloudfront.net",
57
+ "amazonaws.com",
58
+ "blogspot.com",
59
+ "ngrok.io",
60
+ "ngrok-free.app",
61
+ "trycloudflare.com",
62
+ "onrender.com",
63
+ "fly.dev",
64
+ "glitch.me",
65
+ ]);
66
+ /**
67
+ * Why a `*.` wildcard is too broad to add from the device page: its remainder is a whole public
68
+ * suffix (one label such as `com`, or a known multi-label one such as `co.uk`, `github.io`);
69
+ * null for an exact host or a narrower wildcard.
70
+ */
71
+ export function publicSuffixWildcard(pattern) {
72
+ if (!pattern.startsWith("*."))
73
+ return null;
74
+ const rest = pattern.slice(2).toLowerCase();
75
+ if (!rest.includes(".") || MULTI_LABEL_SUFFIXES.has(rest)) {
76
+ return `Use a narrower domain; ${pattern.toLowerCase()} covers a whole public suffix.`;
77
+ }
78
+ return null;
79
+ }
@@ -1,10 +1,49 @@
1
- import type { DeviceRes, KernelReq } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceLocalPolicySummary, type DeviceRes, type KernelReq, type SandboxLimits } from "@capybara-hq/plugin-sdk";
2
2
  import type { CommandLogEntry } from "./command-log.js";
3
- import { type Executor } from "./exec/types.js";
4
- /** The local-log line for a finished request. */
5
- export declare function logEntryFor(req: KernelReq, res: DeviceRes, now: Date): CommandLogEntry;
3
+ import { type ExecMode, type Executor } from "./exec/types.js";
4
+ import type { PolicyStore } from "./policy-store.js";
5
+ import { type Policy } from "./state.js";
6
+ /** What this program has seen across requests (one per program run, kept over reconnects). */
7
+ export interface SeenState {
8
+ /** The mode of the latest exec's limits (the kernel's ceiling), for the summary. */
9
+ limits?: Pick<SandboxLimits, "mode">;
10
+ }
11
+ /** What a request may need beyond the executor. */
12
+ export interface OpContext {
13
+ /**
14
+ * The local policy this program serves (the one the executor reads). Without it the device
15
+ * answers the `policy` op as unsupported (and does not announce `policyOp` in its hello).
16
+ */
17
+ policy?: PolicyStore;
18
+ /** Updated by every exec; read by the policy op's summary. */
19
+ seen?: SeenState;
20
+ }
21
+ /** The refusal of a `policy` op that tries to turn auto mode on from the deployment. */
22
+ export declare const MODE_ON_DEVICE_MESSAGE = "The device's mode can only be changed on the machine: run `capybara-device mode auto`.";
23
+ /** The local-log line for a finished request; `detail` is its audit line, `run` how an exec ran. */
24
+ export declare function logEntryFor(req: KernelReq, res: DeviceRes, now: Date, detail?: string, run?: ExecMode): CommandLogEntry;
25
+ /** What the summary describes besides the policy file. */
26
+ export interface SummaryFacts {
27
+ mode: Executor["mode"];
28
+ /** The latest exec's mode ceiling; undefined before the first exec. */
29
+ limits?: Pick<SandboxLimits, "mode"> | undefined;
30
+ }
6
31
  /**
7
- * Runs one request on the executor and returns the answer. A vanished environment directory
8
- * answers `fs_gone` for every operation except `stop`. Never throws.
32
+ * The summary the kernel keeps of a local policy (hello, `policy` op result): the effective mode
33
+ * (the owner's choice cut to the latest ceiling seen) and the device's sandbox-mode allowlist.
9
34
  */
10
- export declare function runOp(executor: Executor, req: KernelReq, signal: AbortSignal): Promise<DeviceRes>;
35
+ export declare function policySummary(p: Policy, facts: SummaryFacts): DeviceLocalPolicySummary;
36
+ /** The summary facts of a request context. */
37
+ export declare function summaryFacts(executor: Executor, ctx: OpContext): SummaryFacts;
38
+ /**
39
+ * Runs one request and returns the answer plus its local audit line and, for an exec, its mode
40
+ * (for the local command log). A vanished device directory answers `fs_gone` for every operation
41
+ * except `stop`, `policy` and `policyStatus`. Never throws.
42
+ */
43
+ export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
44
+ res: DeviceRes;
45
+ detail?: string;
46
+ run?: ExecMode;
47
+ }>;
48
+ /** {@link serveOp} without the audit line. */
49
+ export declare function runOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<DeviceRes>;
@@ -1,6 +1,12 @@
1
+ import { isPolicyOpId, validateAllowHost, } from "@capybara-hq/plugin-sdk";
1
2
  import { DeviceOpError } from "./exec/types.js";
2
- /** The local-log line for a finished request. */
3
- export function logEntryFor(req, res, now) {
3
+ import { effectiveMode, grantedHosts } from "./policy.js";
4
+ import { publicSuffixWildcard } from "./public-suffix.js";
5
+ import { DEFAULT_POLICY } from "./state.js";
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`.";
8
+ /** The local-log line for a finished request; `detail` is its audit line, `run` how an exec ran. */
9
+ export function logEntryFor(req, res, now, detail, run) {
4
10
  const exec = req.op === "exec" ? req.args : undefined;
5
11
  const exitCode = res.ok && req.op === "exec"
6
12
  ? (res.result.exitCode ?? null)
@@ -11,25 +17,242 @@ export function logEntryFor(req, res, now) {
11
17
  tag: exec ? exec.tag : null,
12
18
  actor: exec ? { accountId: exec.actor.accountId } : null,
13
19
  exitCode,
20
+ ...(run !== undefined && { mode: run.mode }),
21
+ ...(detail !== undefined && { detail }),
14
22
  };
15
23
  }
16
24
  /**
17
- * Runs one request on the executor and returns the answer. A vanished environment directory
18
- * answers `fs_gone` for every operation except `stop`. Never throws.
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.
19
27
  */
20
- export async function runOp(executor, req, signal) {
28
+ export function policySummary(p, facts) {
29
+ return {
30
+ mode: facts.limits === undefined ? p.mode : effectiveMode(p, facts.limits),
31
+ allowedDomains: [...p.allowedDomains],
32
+ };
33
+ }
34
+ /** The summary facts of a request context. */
35
+ export function summaryFacts(executor, ctx) {
36
+ return {
37
+ mode: executor.mode,
38
+ limits: ctx.seen?.limits,
39
+ };
40
+ }
41
+ /** A refused `policy` op, with the local audit line that records the attempt. */
42
+ class PolicyRefused extends DeviceOpError {
43
+ detail;
44
+ constructor(message, detail) {
45
+ super("policy", message);
46
+ this.detail = detail;
47
+ }
48
+ }
49
+ /** A deployment-supplied string fit for the local log: no control or format characters. */
50
+ function clean(s, max) {
51
+ return String(s ?? "")
52
+ .replace(/[\p{Cc}\p{Cf}]/gu, "")
53
+ .slice(0, max);
54
+ }
55
+ /** Lowercased hosts of a `policy` op field; throws a `policy` error naming the first bad one. */
56
+ function opHosts(list, key, fromApproval) {
57
+ if (list === undefined)
58
+ return [];
59
+ if (!Array.isArray(list))
60
+ throw new DeviceOpError("policy", `${key} must be a list of hosts`);
61
+ return list.map((raw) => {
62
+ if (typeof raw !== "string")
63
+ throw new DeviceOpError("policy", `${key} must be a list of hosts`);
64
+ const host = raw.toLowerCase();
65
+ // A device-page wildcard over a whole public suffix is close to an open network, unconfirmed.
66
+ const tooBroad = key === "add" ? publicSuffixWildcard(host) : null;
67
+ if (tooBroad !== null)
68
+ throw new DeviceOpError("policy", tooBroad);
69
+ const errors = validateAllowHost(host);
70
+ if (errors.length > 0) {
71
+ throw new DeviceOpError("policy", `${JSON.stringify(raw)}: ${errors.join("; ")}`);
72
+ }
73
+ // An approval grants the exact host it asked about; wildcards come only from the device page.
74
+ if (key === "add" && fromApproval && host.startsWith("*.")) {
75
+ throw new DeviceOpError("policy", `${JSON.stringify(raw)}: an approval grants an exact host, not a wildcard`);
76
+ }
77
+ return host;
78
+ });
79
+ }
80
+ /**
81
+ * Applies a `policy` op to the local policy (a trust boundary: the deployment is not the owner).
82
+ *
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).
87
+ *
88
+ * The op is idempotent. Returns the result and the local audit line; a refusal carries its audit
89
+ * line too ({@link PolicyRefused}).
90
+ */
91
+ function applyPolicyOp(store, args, facts, written) {
92
+ const source = (args.source ?? {});
93
+ const fromApproval = source.approvalId !== undefined;
94
+ const add = [...new Set(opHosts(args.add, "add", fromApproval))];
95
+ const remove = [...new Set(opHosts(args.remove, "remove", fromApproval))];
96
+ // Read as unknown: the frame parser may have been bypassed, so nothing is assumed of the shape.
97
+ const rawMode = args.mode;
98
+ const parts = [];
99
+ if (add.length > 0)
100
+ parts.push(`add ${add.join(", ")}`);
101
+ if (remove.length > 0)
102
+ parts.push(`remove ${remove.join(", ")}`);
103
+ if (rawMode !== undefined)
104
+ parts.push(`mode ${clean(String(rawMode), 40)}`);
105
+ const by = `by ${clean(source.accountName, 100)} (${clean(source.accountId, 100)}) ` +
106
+ `via ${clean(source.via, 10)}`;
107
+ const approval = fromApproval ? `, approval ${clean(source.approvalId, 100)}` : "";
108
+ const what = parts.length > 0 ? parts.join("; ") : "unchanged";
109
+ const refused = `policy refused ${what} ${by}${approval}`;
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);
113
+ }
114
+ const both = add.find((h) => remove.includes(h));
115
+ if (both !== undefined) {
116
+ throw new DeviceOpError("policy", `${both} is both added and removed`);
117
+ }
118
+ const change = (p) => {
119
+ const kept = p.allowedDomains.filter((d) => !remove.includes(d.toLowerCase()));
120
+ const present = new Set(kept.map((d) => d.toLowerCase()));
121
+ return {
122
+ ...p,
123
+ mode: rawMode === "sandbox" ? "sandbox" : p.mode,
124
+ allowedDomains: [...kept, ...add.filter((h) => !present.has(h))],
125
+ };
126
+ };
127
+ const next = store.update(change, { written });
128
+ return {
129
+ result: { policy: policySummary(next, facts) },
130
+ detail: `policy ${what} ${by}${approval}`,
131
+ };
132
+ }
133
+ /** The answer to a `policy` op whose outcome is logged already: the change is not made again. */
134
+ function answerFromLog(req, known, store, facts) {
135
+ if (known.outcome === "applied") {
136
+ return {
137
+ type: "res",
138
+ id: req.id,
139
+ ok: true,
140
+ result: { policy: policySummary(store.current(), facts) },
141
+ };
142
+ }
143
+ return {
144
+ type: "res",
145
+ id: req.id,
146
+ ok: false,
147
+ error: { kind: known.kind ?? "policy", message: known.message ?? "refused" },
148
+ };
149
+ }
150
+ /**
151
+ * A `policy` op by its op id: logged `started` before anything is checked or written, then
152
+ * `applied` (inside the policy lock, right after the write) or `refused` with the message. An op
153
+ * id applied or refused before is answered from the log without applying it again. Throws like
154
+ * {@link applyPolicyOp}.
155
+ */
156
+ function servePolicyOp(req, store, facts) {
157
+ const opId = req.args.opId;
158
+ if (!isPolicyOpId(opId)) {
159
+ throw new DeviceOpError("error", 'invalid request: field "opId" must be a valid op id');
160
+ }
161
+ const known = store.ops.claim(opId);
162
+ if (known !== undefined)
163
+ return { res: answerFromLog(req, known, store, facts) };
164
+ try {
165
+ const { result, detail } = applyPolicyOp(store, req.args, facts, () => {
166
+ try {
167
+ store.ops.recordHeld({ opId, outcome: "applied" });
168
+ }
169
+ catch {
170
+ // the change stands; the log keeps `started` and the deployment learns it from the hello
171
+ }
172
+ });
173
+ return { res: { type: "res", id: req.id, ok: true, result }, detail };
174
+ }
175
+ catch (e) {
176
+ // an op the log already says was applied stays applied (the log reports what the file holds)
177
+ if (store.ops.get(opId)?.outcome !== "applied") {
178
+ try {
179
+ store.ops.record({
180
+ opId,
181
+ outcome: "refused",
182
+ message: e instanceof Error ? e.message : String(e),
183
+ kind: e instanceof DeviceOpError ? e.kind : "error",
184
+ });
185
+ }
186
+ catch {
187
+ // nothing was applied; the log keeps `started`
188
+ }
189
+ }
190
+ throw e;
191
+ }
192
+ }
193
+ /** What the log says of an op id, with the summary now. Read-only. */
194
+ function policyStatus(store, args, facts) {
195
+ const opId = args?.opId;
196
+ if (!isPolicyOpId(opId)) {
197
+ throw new DeviceOpError("error", 'invalid request: field "opId" must be a valid op id');
198
+ }
199
+ const known = store.ops.get(opId);
200
+ return {
201
+ outcome: known?.outcome ?? "unknown",
202
+ policy: policySummary(store.current(), facts),
203
+ ...(known?.outcome === "refused" && known.message !== undefined && { message: known.message }),
204
+ };
205
+ }
206
+ /** The audit line of an exec whose grants applied (sandbox mode only: auto mode ignores grants). */
207
+ function grantsDetail(executor, args, policy) {
208
+ if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
209
+ return undefined;
210
+ }
211
+ if (effectiveMode(policy, args.limits) !== "sandbox")
212
+ return undefined;
213
+ const hosts = grantedHosts(args.limits, args.grants);
214
+ if (hosts.length === 0)
215
+ return undefined;
216
+ const s = args.grants.source;
217
+ return `grants ${clean(s.kind, 10)} ${clean(s.id, 100)} by ${clean(s.accountId, 100)}: ${hosts.join(", ")}`;
218
+ }
219
+ /**
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.
223
+ */
224
+ export async function serveOp(executor, req, signal, ctx = {}) {
21
225
  const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
22
226
  try {
23
227
  if (req.op === "stop")
24
- return ok(null);
228
+ return { res: ok(null) };
229
+ // The policy lives in the state directory, not the device directory.
230
+ if (req.op === "policy" || req.op === "policyStatus") {
231
+ if (ctx.policy === undefined) {
232
+ return {
233
+ res: {
234
+ type: "res",
235
+ id: req.id,
236
+ ok: false,
237
+ error: { kind: "error", message: "unsupported operation" },
238
+ },
239
+ };
240
+ }
241
+ const facts = summaryFacts(executor, ctx);
242
+ if (req.op === "policyStatus")
243
+ return { res: ok(policyStatus(ctx.policy, req.args, facts)) };
244
+ return servePolicyOp(req, ctx.policy, facts);
245
+ }
25
246
  if ((await executor.ensureRoot()) === "gone") {
26
247
  return {
27
- type: "res",
28
- id: req.id,
29
- ok: false,
30
- error: {
31
- kind: "fs_gone",
32
- message: "The environment directory on this machine existed and is gone. It is not recreated automatically.",
248
+ res: {
249
+ type: "res",
250
+ id: req.id,
251
+ ok: false,
252
+ error: {
253
+ kind: "fs_gone",
254
+ message: "The device directory on this machine existed and is gone. It is not recreated automatically.",
255
+ },
33
256
  },
34
257
  };
35
258
  }
@@ -37,38 +260,71 @@ export async function runOp(executor, req, signal) {
37
260
  signal.throwIfAborted();
38
261
  switch (req.op) {
39
262
  case "create":
40
- return ok({ roots: executor.roots });
41
- case "exec":
42
- return ok(await executor.exec(req.args, signal));
263
+ return { res: ok({ roots: executor.roots }) };
264
+ case "exec": {
265
+ const args = req.args;
266
+ if (ctx.seen !== undefined)
267
+ ctx.seen.limits = { mode: args.limits.mode };
268
+ // One decision per command, on one read of the policy: the executor runs it and the
269
+ // local log records it. Grants are judged on the same read.
270
+ const policy = ctx.policy?.current();
271
+ const run = {
272
+ mode: effectiveMode(policy ?? DEFAULT_POLICY, args.limits),
273
+ };
274
+ // These limits are the latest decision file operations follow.
275
+ executor.noteLimits?.(args.limits);
276
+ const detail = grantsDetail(executor, args, policy);
277
+ try {
278
+ const result = policy !== undefined && executor.execDecided !== undefined
279
+ ? await executor.execDecided(args, signal, run, policy)
280
+ : await executor.exec(args, signal);
281
+ const res = ok(result);
282
+ return detail === undefined ? { res, run } : { res, detail, run };
283
+ }
284
+ catch (e) {
285
+ return { ...errorAnswer(req, e), run };
286
+ }
287
+ }
43
288
  case "readFile": {
44
289
  const a = req.args;
45
290
  const r = await executor.readFile(a.path, a.maxBytes);
46
- return ok(r === null
47
- ? null
48
- : { dataB64: Buffer.from(r.data).toString("base64"), truncated: r.truncated });
291
+ return {
292
+ res: ok(r === null
293
+ ? null
294
+ : { dataB64: Buffer.from(r.data).toString("base64"), truncated: r.truncated }),
295
+ };
49
296
  }
50
297
  case "writeFile": {
51
298
  const a = req.args;
52
299
  await executor.writeFile(a.path, Buffer.from(a.dataB64, "base64"));
53
- return ok(null);
300
+ return { res: ok(null) };
54
301
  }
55
302
  case "stat":
56
- return ok(await executor.stat(req.args.path));
303
+ return { res: ok(await executor.stat(req.args.path)) };
57
304
  case "killTagged":
58
305
  await executor.killTagged(req.args.tags);
59
- return ok(null);
306
+ return { res: ok(null) };
60
307
  case "killAll":
61
308
  await executor.killAll();
62
- return ok(null);
309
+ return { res: ok(null) };
63
310
  }
64
311
  }
65
312
  catch (e) {
66
- const kind = e instanceof DeviceOpError ? e.kind : "error";
67
- return {
68
- type: "res",
69
- id: req.id,
70
- ok: false,
71
- error: { kind, message: e instanceof Error ? e.message : String(e) },
72
- };
313
+ return errorAnswer(req, e);
73
314
  }
74
315
  }
316
+ /** The error answer of a failed request, with a refused policy op's audit line. */
317
+ function errorAnswer(req, e) {
318
+ const kind = e instanceof DeviceOpError ? e.kind : "error";
319
+ const res = {
320
+ type: "res",
321
+ id: req.id,
322
+ ok: false,
323
+ error: { kind, message: e instanceof Error ? e.message : String(e) },
324
+ };
325
+ return e instanceof PolicyRefused ? { res, detail: e.detail } : { res };
326
+ }
327
+ /** {@link serveOp} without the audit line. */
328
+ export async function runOp(executor, req, signal, ctx = {}) {
329
+ return (await serveOp(executor, req, signal, ctx)).res;
330
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Whether a login service is installed here, by its file (the platform decides which one): the
3
+ * file exists as soon as `service install` wrote it, with or without the service running.
4
+ */
5
+ export declare function hasLoginService(home: string, platform: NodeJS.Platform): boolean;
@@ -0,0 +1,14 @@
1
+ import { existsSync } from "node:fs";
2
+ import { plistPath } from "./launchd.js";
3
+ import { unitPath } from "./systemd.js";
4
+ /**
5
+ * Whether a login service is installed here, by its file (the platform decides which one): the
6
+ * file exists as soon as `service install` wrote it, with or without the service running.
7
+ */
8
+ export function hasLoginService(home, platform) {
9
+ if (platform === "darwin")
10
+ return existsSync(plistPath(home));
11
+ if (platform === "linux")
12
+ return existsSync(unitPath(home));
13
+ return false;
14
+ }