@capybara-hq/device 0.1.0-rc.3 → 0.1.0-rc.5

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