@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.
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.2",
3
+ "version": "0.1.0-rc.4",
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.9"
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.16"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/ws": "^8.5.13"