@capybara-hq/device 0.1.0-rc.18 → 0.1.0-rc.19

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 (72) hide show
  1. package/README.md +65 -33
  2. package/dist/api.d.ts +3 -3
  3. package/dist/args.d.ts +8 -3
  4. package/dist/args.js +27 -14
  5. package/dist/cli.js +1 -1
  6. package/dist/client.js +1 -1
  7. package/dist/commands/ceiling.d.ts +3 -2
  8. package/dist/commands/ceiling.js +39 -21
  9. package/dist/commands/login.d.ts +15 -11
  10. package/dist/commands/login.js +46 -33
  11. package/dist/commands/policy.js +16 -10
  12. package/dist/commands/start.d.ts +11 -3
  13. package/dist/commands/start.js +25 -9
  14. package/dist/commands/status.js +10 -6
  15. package/dist/exec/docker-operations.d.ts +14 -2
  16. package/dist/exec/docker-operations.js +32 -5
  17. package/dist/exec/linux-agent.d.ts +13 -3
  18. package/dist/exec/linux-agent.js +450 -43
  19. package/dist/exec/linux-operation-backend.d.ts +27 -6
  20. package/dist/exec/linux-operation-backend.js +30 -9
  21. package/dist/exec/linux-operation-worker.d.ts +51 -3
  22. package/dist/exec/linux-operation-worker.js +55 -3
  23. package/dist/exec/linux-runtime.d.ts +3 -2
  24. package/dist/exec/linux-runtime.js +4 -2
  25. package/dist/exec/mac-operation-backend.d.ts +7 -2
  26. package/dist/exec/mac-operation-backend.js +18 -10
  27. package/dist/exec/mac-write-policy.d.ts +2 -0
  28. package/dist/exec/mac-write-policy.js +1 -1
  29. package/dist/exec/operation-types.d.ts +35 -5
  30. package/dist/exec/operation-types.js +73 -23
  31. package/dist/exec/operation-worker.d.ts +80 -1
  32. package/dist/exec/operation-worker.js +197 -14
  33. package/dist/exec/protected-targets.d.ts +16 -0
  34. package/dist/exec/protected-targets.js +53 -0
  35. package/dist/exec/shared.d.ts +7 -3
  36. package/dist/exec/shared.js +7 -5
  37. package/dist/node_modules/@anthropic-ai/sandbox-runtime/CAPYBARA-MODIFICATIONS.patch +343 -7
  38. package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/resolved-address-guard.js +220 -6
  39. package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js +17 -0
  40. package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js +11 -0
  41. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.d.ts +77 -46
  42. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.js +206 -83
  43. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.d.ts +3 -2
  44. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.js +3 -2
  45. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/network-classes.d.ts +98 -0
  46. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/network-classes.js +291 -0
  47. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-linux-runtime-source.js +460 -28
  48. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-native-runtime-source.js +143 -3
  49. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.d.ts +36 -4
  50. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.js +21 -4
  51. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-runtime-source.js +2 -2
  52. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-write-denies.d.ts +87 -8
  53. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-write-denies.js +249 -10
  54. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox.d.ts +11 -22
  55. package/dist/node_modules/@capybara-hq/plugin-sdk/package.json +1 -1
  56. package/dist/owner-report.d.ts +1 -1
  57. package/dist/owner-report.js +5 -4
  58. package/dist/policy-store.d.ts +2 -1
  59. package/dist/policy-store.js +2 -1
  60. package/dist/policy.d.ts +23 -14
  61. package/dist/policy.js +28 -21
  62. package/dist/runtime-manifest.json +1 -1
  63. package/dist/server-ops.d.ts +30 -5
  64. package/dist/server-ops.js +105 -85
  65. package/dist/staged-connect.d.ts +1 -1
  66. package/dist/staged-connect.js +1 -1
  67. package/dist/staged-device.d.ts +1 -1
  68. package/dist/staged-device.js +7 -5
  69. package/dist/staged-session.d.ts +1 -1
  70. package/dist/state.d.ts +41 -21
  71. package/dist/state.js +102 -45
  72. package/package.json +2 -2
@@ -25,6 +25,8 @@
25
25
  import { lookup as dnsLookup } from 'node:dns';
26
26
  import { BlockList, isIP } from 'node:net';
27
27
  import { networkInterfaces } from 'node:os';
28
+ // capybara patch: DNS-over-HTTPS behind a fake-IP resolver
29
+ import { get as httpsGet } from 'node:https';
28
30
  import { logForDebugging } from '../utils/debug.js';
29
31
  import { ipLiteralRules } from './domain-pattern.js';
30
32
  import { addRange, addressInSet, embeddedIPv4, isLoopbackAddress, isLoopbackName, LOOPBACK_RANGES, } from './address.js';
@@ -86,6 +88,192 @@ export function localInterfaceAddresses() {
86
88
  .flat()
87
89
  .flatMap(i => (i ? [i.address] : []));
88
90
  }
91
+ /**
92
+ * capybara patch: DNS-over-HTTPS for names a fake-IP resolver answered. A router or local proxy in
93
+ * fake-IP mode (OpenClash and the like) intercepts every DNS query, port 53 to any server
94
+ * included, and answers each name with an address in a fake-IP range (`fakeIpDoh.fakeIpCidr`,
95
+ * 198.18.0.0/15), which it maps back on connect. The guard cannot judge such an answer, so with
96
+ * `fakeIpDoh` it re-resolves the name through DNS-over-HTTPS (RFC 8484: GET, wire format, A and
97
+ * AAAA) to IP-literal endpoints (TLS verified against the endpoint's IP certificate; no DNS is
98
+ * needed to reach them) and judges and dials the real answer like any resolved address. A failed
99
+ * lookup refuses the connection: the fake address is never dialed. Only the IPv4 range is a
100
+ * signal: a fake-IP resolver handing out IPv6 addresses (from ULA space, say) is not detected and
101
+ * its answers are judged as they are (ULA is closed, so they fail closed).
102
+ */
103
+ const DOH_DEFAULTS = { timeoutMs: 5000, cacheTtlCapSeconds: 300, cacheMaxNames: 256 };
104
+ const DOH_ANSWER_MAX_BYTES = 65536;
105
+ function dohEndpoint(entry) {
106
+ let url;
107
+ try {
108
+ url = new URL(entry);
109
+ }
110
+ catch { }
111
+ const host = url?.hostname.replace(/^\[(.*)\]$/, '$1');
112
+ if (!url || url.protocol !== 'https:' || !isIP(host ?? '') || url.username || url.password || url.search || url.hash)
113
+ throw new Error(`A DNS-over-HTTPS endpoint must be an https URL with an IP-literal host and no query: ${JSON.stringify(entry)}`);
114
+ return url;
115
+ }
116
+ /**
117
+ * One RFC 8484 GET (`application/dns-message`). `tls` is a test seam only (a trusted CA for a
118
+ * local fixture); production verifies against the system's roots.
119
+ */
120
+ export function defaultDohRequest(url, timeoutMs, tls = {}) {
121
+ return new Promise((resolve, reject) => {
122
+ const req = httpsGet(url, { headers: { accept: 'application/dns-message' }, agent: false, timeout: timeoutMs, ...(tls.ca ? { ca: tls.ca } : {}) }, res => {
123
+ if (res.statusCode !== 200) {
124
+ res.resume();
125
+ reject(new Error(`HTTP ${res.statusCode}`));
126
+ return;
127
+ }
128
+ const chunks = [];
129
+ let size = 0;
130
+ res.on('data', chunk => {
131
+ size += chunk.length;
132
+ if (size > DOH_ANSWER_MAX_BYTES)
133
+ req.destroy(new Error('answer too large'));
134
+ else
135
+ chunks.push(chunk);
136
+ });
137
+ res.on('end', () => resolve(Buffer.concat(chunks)));
138
+ res.on('error', reject);
139
+ });
140
+ req.on('timeout', () => req.destroy(new Error('timed out')));
141
+ req.on('error', reject);
142
+ });
143
+ }
144
+ function withDeadline(promise, ms) {
145
+ let timer;
146
+ return Promise.race([
147
+ promise,
148
+ new Promise((_, reject) => {
149
+ timer = setTimeout(() => reject(new Error('timed out')), ms);
150
+ }),
151
+ ]).finally(() => clearTimeout(timer));
152
+ }
153
+ /** A wire-format query (RFC 1035) for `name` and `qtype`, id 0 as RFC 8484 recommends. */
154
+ function dnsQuery(name, qtype) {
155
+ const labels = name.split('.');
156
+ if (name.length > 253 || labels.some(l => !l.length || l.length > 63 || /[^\x21-\x7e]/.test(l)))
157
+ throw new Error('name not expressible in DNS');
158
+ const header = Buffer.from([0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0]);
159
+ const parts = labels.map(l => Buffer.concat([Buffer.from([l.length]), Buffer.from(l, 'ascii')]));
160
+ const tail = Buffer.from([0, qtype >> 8, qtype & 0xff, 0, 1]);
161
+ return Buffer.concat([header, ...parts, tail]);
162
+ }
163
+ /** The offset after the (possibly compressed) name at `at`. */
164
+ function skipName(message, at) {
165
+ for (let hops = 0; hops < 128; hops++) {
166
+ const length = message[at];
167
+ if (length === undefined)
168
+ throw new Error('truncated');
169
+ if (length === 0)
170
+ return at + 1;
171
+ if ((length & 0xc0) === 0xc0)
172
+ return at + 2;
173
+ at += length + 1;
174
+ }
175
+ throw new Error('malformed name');
176
+ }
177
+ /** The addresses of one wire-format answer for `qtype`, the fake-IP range dropped, and their TTL. */
178
+ function dnsAnswer(message, qtype, fakeIp, ttlCap) {
179
+ if (message.length < 12)
180
+ throw new Error('truncated answer');
181
+ const flags = message.readUInt16BE(2);
182
+ if (!(flags & 0x8000) || flags & 0x0200)
183
+ throw new Error('not a complete answer');
184
+ const rcode = flags & 0x000f;
185
+ // NXDOMAIN is an answer: the name does not exist
186
+ if (rcode === 3)
187
+ return { addresses: [], ttl: 0 };
188
+ if (rcode !== 0)
189
+ throw new Error(`DNS rcode ${rcode}`);
190
+ const questions = message.readUInt16BE(4);
191
+ const answers = message.readUInt16BE(6);
192
+ let at = 12;
193
+ for (let i = 0; i < questions; i++)
194
+ at = skipName(message, at) + 4;
195
+ const size = qtype === 1 ? 4 : 16;
196
+ const addresses = [];
197
+ let ttl = ttlCap;
198
+ for (let i = 0; i < answers; i++) {
199
+ at = skipName(message, at);
200
+ if (at + 10 > message.length)
201
+ throw new Error('truncated answer');
202
+ const type = message.readUInt16BE(at);
203
+ const rclass = message.readUInt16BE(at + 2);
204
+ const recordTtl = message.readUInt32BE(at + 4);
205
+ const length = message.readUInt16BE(at + 8);
206
+ at += 10;
207
+ if (at + length > message.length)
208
+ throw new Error('truncated answer');
209
+ if (type === qtype && rclass === 1 && length === size) {
210
+ const bytes = message.subarray(at, at + length);
211
+ const address = size === 4
212
+ ? [...bytes].join('.')
213
+ : Array.from({ length: 8 }, (_, g) => bytes.readUInt16BE(g * 2).toString(16)).join(':');
214
+ if (!addressInSet(fakeIp, address)) {
215
+ addresses.push({ address, family: size === 4 ? 4 : 6 });
216
+ ttl = Math.min(ttl, recordTtl);
217
+ }
218
+ }
219
+ at += length;
220
+ }
221
+ return { addresses, ttl };
222
+ }
223
+ function createDohResolver(config, request) {
224
+ const endpoints = (config.endpoints ?? []).map(dohEndpoint);
225
+ if (!endpoints.length)
226
+ throw new Error('A DNS-over-HTTPS endpoint list must not be empty');
227
+ const deadlineMs = config.timeoutMs ?? DOH_DEFAULTS.timeoutMs;
228
+ const ttlCap = config.cacheTtlCapSeconds ?? DOH_DEFAULTS.cacheTtlCapSeconds;
229
+ const cacheMax = config.cacheMaxNames ?? DOH_DEFAULTS.cacheMaxNames;
230
+ const fakeIp = new BlockList();
231
+ if (!addRange(fakeIp, config.fakeIpCidr ?? '198.18.0.0/15'))
232
+ throw new Error(`Invalid fake-IP range: ${JSON.stringify(config.fakeIpCidr)}`);
233
+ const cache = new Map();
234
+ const ask = (endpoint, name, qtype, ms) => {
235
+ const url = new URL(endpoint.href);
236
+ url.searchParams.set('dns', dnsQuery(name, qtype).toString('base64url'));
237
+ return withDeadline(Promise.resolve().then(() => request(url.href, ms)), ms).then(body => dnsAnswer(Buffer.from(body), qtype, fakeIp, ttlCap));
238
+ };
239
+ const lookup = async (hostname) => {
240
+ const name = hostname.toLowerCase().replace(/\.$/, '');
241
+ const hit = cache.get(name);
242
+ if (hit && hit.expires > Date.now())
243
+ return hit.addresses;
244
+ cache.delete(name);
245
+ const deadline = Date.now() + deadlineMs;
246
+ let partial;
247
+ let last;
248
+ for (let i = 0; i < endpoints.length; i++) {
249
+ const remaining = deadline - Date.now();
250
+ if (remaining <= 0)
251
+ break;
252
+ // each endpoint gets its share of what is left, so a stalled one cannot starve the rest
253
+ const share = Math.max(1, Math.floor(remaining / (endpoints.length - i)));
254
+ const [a, aaaa] = await Promise.allSettled([1, 28].map(qtype => ask(endpoints[i], name, qtype, share)));
255
+ if (a.status === 'fulfilled' && aaaa.status === 'fulfilled') {
256
+ const addresses = [...a.value.addresses, ...aaaa.value.addresses];
257
+ const ttl = Math.min(a.value.ttl, aaaa.value.ttl);
258
+ // cached only when both queries answered
259
+ if (ttl > 0 && cacheMax > 0) {
260
+ if (cache.size >= cacheMax)
261
+ cache.delete(cache.keys().next().value);
262
+ cache.set(name, { addresses, expires: Date.now() + ttl * 1000 });
263
+ }
264
+ return addresses;
265
+ }
266
+ const ok = [a, aaaa].find(r => r.status === 'fulfilled');
267
+ partial ??= ok?.value.addresses;
268
+ last = [a, aaaa].find(r => r.status === 'rejected')?.reason ?? last;
269
+ }
270
+ // one family answered somewhere: use it, uncached
271
+ if (partial)
272
+ return partial;
273
+ throw last ?? new Error('timed out');
274
+ };
275
+ return { lookup, fakeIp };
276
+ }
89
277
  export class ResolvedAddressDeniedError extends Error {
90
278
  /**
91
279
  * @param reason parenthetical for the violation line and the client, e.g.
@@ -131,6 +319,14 @@ export function createResolvedAddressGuard(opts = {}) {
131
319
  ['a listed address', buildRuleSet(opts.deniedResolvedAddresses ?? [])],
132
320
  ];
133
321
  const resolve = opts.resolve ?? dnsLookup;
322
+ // capybara patch: `resolvedAddressStrict` judges every destination by its address: an IP
323
+ // literal by the same rules as a resolved name (see `literalDenial`), and the reserved
324
+ // loopback names without their loopback carve-out
325
+ const strict = opts.resolvedAddressStrict === true;
326
+ // capybara patch: the DNS-over-HTTPS resolver for fake-IP answers (`fakeIpDoh`)
327
+ const doh = opts.fakeIpDoh
328
+ ? createDohResolver(opts.fakeIpDoh, opts.dohRequest ?? defaultDohRequest)
329
+ : undefined;
134
330
  /** This host's addresses right now; a malformed entry from the seam is skipped. */
135
331
  const localSet = () => {
136
332
  const list = new BlockList();
@@ -140,8 +336,8 @@ export function createResolvedAddressGuard(opts = {}) {
140
336
  return list;
141
337
  };
142
338
  /** Why `hostname:port` may not use resolved `address`, or undefined if it may. */
143
- const denial = (hostname, address, port, local) => {
144
- if (isIP(hostname))
339
+ const denial = (hostname, address, port, local, literal = false) => {
340
+ if (isIP(hostname) && !literal)
145
341
  return undefined;
146
342
  if (!isIP(address))
147
343
  return 'an unparsable address';
@@ -157,9 +353,11 @@ export function createResolvedAddressGuard(opts = {}) {
157
353
  (v4 !== undefined && inRuleSet(set, v4, port));
158
354
  if (denies(refused))
159
355
  return 'a deny-listed address';
160
- if (inRuleSet(allowed, address, port))
356
+ // capybara patch: in strict mode an allow-listed literal gets no carve-out over the
357
+ // closed classes (private destinations need the escalation)
358
+ if (!strict && inRuleSet(allowed, address, port))
161
359
  return undefined;
162
- if (isLoopbackName(hostname)) {
360
+ if (!strict && isLoopbackName(hostname)) {
163
361
  return isLoopbackAddress(address) ? undefined : 'a non-loopback address';
164
362
  }
165
363
  const why = denied.find(([, set]) => denies(set))?.[0];
@@ -171,11 +369,24 @@ export function createResolvedAddressGuard(opts = {}) {
171
369
  return undefined;
172
370
  };
173
371
  const lookupFor = (port) => (hostname, options, callback) => {
174
- resolve(hostname, { ...options, all: true }, (err, addresses) => {
372
+ resolve(hostname, { ...options, all: true }, (err, answer) => {
175
373
  if (err) {
176
374
  callback(err, []);
177
375
  return;
178
376
  }
377
+ // capybara patch: a fake-IP answer is re-resolved through DNS-over-HTTPS, and only
378
+ // the real answer is judged; when that fails, the connection is refused
379
+ if (doh && answer.some(a => isIP(a.address) && addressInSet(doh.fakeIp, a.address))) {
380
+ doh.lookup(hostname).then(judge, error => {
381
+ const fake = answer.map(a => a.address);
382
+ logForDebugging(`DNS-over-HTTPS failed for ${hostname}:${port} behind a fake-IP resolver: ${error?.message ?? error}`);
383
+ callback(new ResolvedAddressDeniedError(hostname, `resolved by a fake-IP resolver and the DNS-over-HTTPS lookup failed (${error?.message ?? 'unknown error'})`, fake), []);
384
+ });
385
+ return;
386
+ }
387
+ judge(answer);
388
+ });
389
+ function judge(addresses) {
179
390
  const local = localSet();
180
391
  const kept = [];
181
392
  const dropped = [];
@@ -211,10 +422,13 @@ export function createResolvedAddressGuard(opts = {}) {
211
422
  callback(null, kept);
212
423
  else
213
424
  callback(null, first.address, first.family);
214
- });
425
+ }
215
426
  };
216
427
  return {
217
428
  permits: (hostname, address, port) => denial(hostname, address, port, localSet()) === undefined,
429
+ // capybara patch: why an IP-literal destination is refused in strict mode, or undefined
430
+ // when it may be dialed (always undefined without `resolvedAddressStrict`)
431
+ literalDenial: (address, port) => strict ? denial(address, address, port, localSet(), true) : undefined,
218
432
  lookupFor,
219
433
  };
220
434
  }
@@ -608,6 +608,23 @@ export const NetworkConfigSchema = z.object({
608
608
  'deniedDomains. A permitted name that resolves only into these is refused instead of dialed. A name may ' +
609
609
  'resolve to a denied address only if that IP literal (and port) is itself in allowedDomains. Not evaluated ' +
610
610
  'for connections routed through parentProxy (including one taken from HTTP_PROXY/HTTPS_PROXY) or mitmProxy (that hop resolves the name).'),
611
+ // capybara patch: judge IP literals and the loopback names by their address too
612
+ resolvedAddressStrict: z
613
+ .boolean()
614
+ .optional()
615
+ .describe('If true, an IP-literal destination is judged by the resolved-address rules like a resolved name (the built-in classes, deniedResolvedAddresses, deniedDomains literals, this host\'s addresses), and localhost names get no loopback carve-out.'),
616
+ // capybara patch: DNS-over-HTTPS for names a fake-IP resolver answered (198.18.0.0/15)
617
+ fakeIpDoh: z
618
+ .object({
619
+ fakeIpCidr: z.string().optional(),
620
+ endpoints: z.array(z.string()).min(1),
621
+ timeoutMs: z.number().int().min(1).max(30000).optional(),
622
+ cacheTtlCapSeconds: z.number().int().min(0).max(86400).optional(),
623
+ cacheMaxNames: z.number().int().min(0).max(65536).optional(),
624
+ })
625
+ .strict()
626
+ .optional()
627
+ .describe('When the system resolver answers a name with an address in fakeIpCidr (default 198.18.0.0/15), re-resolve it through these DNS-over-HTTPS endpoints (https URLs with IP-literal hosts, RFC 8484 wire format; timeoutMs is the whole lookup, shared among the endpoints) and judge and dial the real answer; a failed lookup refuses the connection.'),
611
628
  allowUnixSockets: z
612
629
  .array(z.string())
613
630
  .optional()
@@ -26,6 +26,8 @@ import { canonicalizeHost, isValidHost, redactUrl, resolveParentProxy, } from '.
26
26
  import { ALLOWED_DOMAIN_ENTRY_MESSAGE, isValidAllowedDomainEntry, matchesDomainPattern, matchesDomainPatternWithPort, stripDomainPatternPort, } from './domain-pattern.js';
27
27
  import { createResolvedAddressGuard, isResolvedAddressDenied, } from './resolved-address-guard.js';
28
28
  import { EOL } from 'node:os';
29
+ // capybara patch: the strict literal check
30
+ import { isIP } from 'node:net';
29
31
  import { dirname } from 'node:path';
30
32
  import { getJavaProxyAgentJarPathAsync } from './java-proxy-agent.js';
31
33
  import { getApplySeccompBinaryPathAsync } from './generate-seccomp-filter.js';
@@ -522,6 +524,15 @@ async function filterNetworkRequest(port, host, sandboxAskCallback, encodedComma
522
524
  return denied(deniedDomainReason(deniedDomain));
523
525
  }
524
526
  }
527
+ // capybara patch: in strict mode an IP-literal destination is judged by the resolved-address
528
+ // rules (upstream judges only names there), so a literal reaches nothing a name could not
529
+ const literalWhy = isIP(canonicalHost)
530
+ ? resolvedAddressGuard.literalDenial(canonicalHost, port)
531
+ : undefined;
532
+ if (literalWhy) {
533
+ logForDebugging(`Denied address literal: ${host}:${port} (${literalWhy})`);
534
+ return denied(`address is ${literalWhy}`);
535
+ }
525
536
  // Check allowed domains
526
537
  for (const allowedDomain of config.network.allowedDomains) {
527
538
  if (matchesDomainPatternWithPort(canonicalHost, port, allowedDomain)) {
@@ -2,40 +2,41 @@
2
2
  * The device protocol: the WebSocket frames between the kernel and a `capybara-device` program
3
3
  * (a connected machine that serves as a device). Pure types and hand-written guards.
4
4
  *
5
- * Protocol 3 (the scope-bearing operations, `parseDeviceFrame`) is defined in the second half of
6
- * this file. Protocol 2's frames keep a `Legacy` prefix where a protocol 3 name replaced them
7
- * (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 3 reuses their value guards, and
5
+ * Protocol 4 (the scope-bearing operations, `parseDeviceFrame`) is defined in the second half of
6
+ * this file. Protocol 2's frames keep a `Legacy` prefix where a newer name replaced them
7
+ * (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 4 reuses their value guards, and
8
8
  * they go with the legacy device surface.
9
9
  */
10
10
  import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./sandbox.js";
11
11
  import { type SandboxPermissionSupport } from "./sandbox-operation.js";
12
12
  /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
13
- export declare const DEVICE_PROTOCOL_VERSION = 3;
13
+ export declare const DEVICE_PROTOCOL_VERSION = 4;
14
14
  /**
15
- * Protocol 2's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
- * on the header, a protocol close on the hello). Kept only for the legacy device surface.
15
+ * Protocol 3's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
+ * on the header, a protocol close on the hello): its owner report and runtime support describe the
17
+ * removed Full access ceiling, so a protocol 3 program must be updated.
17
18
  */
18
- export declare const LEGACY_DEVICE_PROTOCOL_VERSION = 2;
19
+ export declare const LEGACY_DEVICE_PROTOCOL_VERSION = 3;
19
20
  /** The operations the kernel asks a device to run. */
20
21
  export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "policy" | "policyStatus" | "list" | "scan";
21
22
  /**
22
23
  * Optional capabilities a device announces in its hello. `policyOp`: the device takes the `policy`
23
24
  * op; `policyOpId`: it also logs each `policy` op's outcome by its `opId`, answers `policyStatus`
24
25
  * and reports recent outcomes in its hello (`recentOps`); `networkReport` means exec results may
25
- * carry `network`; `mode` means the device applies `limits.mode` / `limits.network` (without it
26
- * the device behaves as an allowlisted sandbox); `projects` means the device serves `list` and
26
+ * carry `network`; `projects` means the device serves `list` and
27
27
  * `scan` (the kernel keeps a device's projects itself and asks the device only what it can read).
28
28
  * The kernel gates each op on its feature, as it gates `policy` on `policyOp` / `policyOpId`: it
29
29
  * never sends `list` or `scan` to a device that did not announce `projects`.
30
30
  */
31
- export type DeviceFeature = "networkReport" | "policyOp" | "policyOpId" | "mode" | "projects";
31
+ export type DeviceFeature = "networkReport" | "policyOp" | "policyOpId" | "projects";
32
32
  /** The most entries a `list` op may ask for and its result may carry. */
33
33
  export declare const MAX_DEVICE_LIST_ENTRIES = 1000;
34
- /** What a device knows of its local policy and reports (in the hello or a `policy` op). */
34
+ /**
35
+ * What a device knows of its local policy and reports (in the hello or a `policy` op). The owner
36
+ * ceiling travels separately, in the owner report ({@link DeviceOwnerCeiling}).
37
+ */
35
38
  export interface DeviceLocalPolicySummary {
36
- /** `auto` = no OS sandbox (the owner's machine); `sandbox` = the OS sandbox. */
37
- mode: "auto" | "sandbox";
38
- /** The device's sandbox-mode allowlist; meaningful in sandbox mode only. */
39
+ /** The device's sandbox allowlist (the owner's `allowedDomains`). */
39
40
  allowedDomains: string[];
40
41
  }
41
42
  /**
@@ -47,14 +48,13 @@ export interface DeviceProjectCandidate {
47
48
  path: string;
48
49
  suggestedName: string;
49
50
  }
50
- /**
51
- * The kernel's current ceiling on a request that reads the device's file system outside a command
52
- * (`readFile`, `stat`, `list`, `scan`): the device answers in the mode it would run this request in, the owner's
53
- * choice cut to `mode`, never by a ceiling it saw on an earlier command.
54
- */
55
- export type DeviceRequestCeiling = Pick<SandboxLimits, "mode">;
56
51
  /** The most blocked hosts an exec result reports; the parser cuts longer lists. */
57
52
  export declare const MAX_NETWORK_BLOCKED_HOSTS = 20;
53
+ /**
54
+ * Why a `policy` op naming hosts to `add` is refused: the deployment may only narrow a local
55
+ * device's sandbox; its owner widens it on the machine.
56
+ */
57
+ export declare const POLICY_ADD_REFUSED = "The deployment may not add hosts to a device's sandbox allowlist: widening happens only on the machine (capybara-device policy add allowedDomains <host>)";
58
58
  /** The longest `opId` a `policy` / `policyStatus` op may carry. */
59
59
  export declare const MAX_POLICY_OP_ID_LENGTH = 128;
60
60
  /** The most entries a hello's `recentOps` carries; the parser keeps the newest. */
@@ -176,7 +176,6 @@ export interface DeviceExecGrants {
176
176
  export type DeviceExecResult = ExecResult;
177
177
  export interface DeviceReadFileArgs {
178
178
  path: string;
179
- limits: DeviceRequestCeiling;
180
179
  maxBytes: number;
181
180
  }
182
181
  export type DeviceReadFileResult = {
@@ -190,7 +189,6 @@ export interface DeviceWriteFileArgs {
190
189
  export type DeviceWriteFileResult = null;
191
190
  export interface DeviceStatArgs {
192
191
  path: string;
193
- limits: DeviceRequestCeiling;
194
192
  }
195
193
  export type DeviceStatResult = {
196
194
  size: number;
@@ -210,9 +208,10 @@ export interface DeviceStopArgs {
210
208
  reason: "revoked" | "deleted";
211
209
  }
212
210
  /**
213
- * Edits the device's local policy. The kernel may only narrow: `mode` may turn the sandbox back on
214
- * (`"sandbox"`), never off (turning auto mode on is decided on the machine), and `add` extends the
215
- * sandbox-mode allowlist only. Narrowing is always accepted.
211
+ * Edits the device's local policy. The kernel may only narrow: it removes hosts from the sandbox
212
+ * allowlist and narrows the owner ceiling ({@link DevicePolicyArgs}). Widening happens only on the
213
+ * machine (`capybara-device policy add`, `capybara-device ceiling set`): the frame parser refuses
214
+ * an `add` and the protocol 3 `mode`.
216
215
  */
217
216
  export interface LegacyDevicePolicyArgs {
218
217
  /**
@@ -221,12 +220,8 @@ export interface LegacyDevicePolicyArgs {
221
220
  * `recentOps`.
222
221
  */
223
222
  opId: string;
224
- /** Hosts to add to `allowedDomains`. */
225
- add?: string[];
226
223
  /** Hosts to remove from `allowedDomains`. */
227
224
  remove?: string[];
228
- /** Only `"sandbox"`: the kernel may narrow, never turn auto mode on. */
229
- mode?: "sandbox";
230
225
  /** Who decided, for the device's local audit line. */
231
226
  source: {
232
227
  approvalId?: string;
@@ -255,13 +250,12 @@ export interface LegacyDevicePolicyStatus {
255
250
  }
256
251
  /**
257
252
  * Lists one directory (absolute `path`, {@link validateSandboxPathShape}): at most `limit` entries
258
- * (at most {@link MAX_DEVICE_LIST_ENTRIES}), read in the mode `limits` gives. See
253
+ * (at most {@link MAX_DEVICE_LIST_ENTRIES}), read within the operation's scope. See
259
254
  * `SandboxProvider.list` for the semantics.
260
255
  */
261
256
  export interface DeviceListArgs {
262
257
  path: string;
263
258
  limit: number;
264
- limits: DeviceRequestCeiling;
265
259
  }
266
260
  /**
267
261
  * One entry of a listed directory: `name` is never empty, `.` or `..` and holds no `/`. `isDir`
@@ -284,13 +278,12 @@ export type DeviceListResult = {
284
278
  } | null;
285
279
  /**
286
280
  * Looks for project-like directories under `base` (absolute, {@link validateSandboxPathShape}),
287
- * read in the mode `limits` gives. A `base` that does not exist answers `[]`; a `base` that is a
288
- * file, unreadable, or outside the request's mode is an error. See `SandboxProvider.scan` for the
281
+ * read within the operation's scope. A `base` that does not exist answers `[]`; a `base` that is a
282
+ * file, unreadable, or outside the request's scope is an error. See `SandboxProvider.scan` for the
289
283
  * traversal.
290
284
  */
291
285
  export interface DeviceScanArgs {
292
286
  base: string;
293
- limits: DeviceRequestCeiling;
294
287
  }
295
288
  /**
296
289
  * `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH} levels below it that
@@ -332,24 +325,36 @@ export declare function parseOpResult<Op extends DeviceOp>(op: Op, result: unkno
332
325
  */
333
326
  export declare function parseLegacyDeviceFrame(raw: string, from: "device" | "kernel"): LegacyDeviceFrame;
334
327
  /**
335
- * The operations the kernel asks a protocol 3 device to run: every user operation carries its
328
+ * The operations the kernel asks a protocol 4 device to run: every user operation carries its
336
329
  * admitted scope; there is no broad kill (`killTagged` / `killAll`).
337
330
  */
338
331
  export type DeviceOperation = Exclude<DeviceOp, "killTagged" | "killAll"> | "prepareReadFile" | "prepareWriteFile" | "prepareStat" | "browseStat" | "browseList" | "browseScan" | "backgroundStart" | "backgroundStatus" | "backgroundTail" | "backgroundReadOutput" | "backgroundStop" | "revokeOperation" | "bindInstance";
332
+ /** The sandbox network of a device: the open public internet or an allowlist. */
333
+ export type DeviceNetworkMode = "open" | "allowlist";
334
+ /**
335
+ * The owner ceiling of protocol 4 (approval-only profiles design, "Settings model"): the device
336
+ * sandbox for every profile. `outsideSandbox` is whether a call may be granted escalation outside
337
+ * the sandbox; `network` and `allowedDomains` are the sandbox network.
338
+ */
339
339
  export interface DeviceOwnerCeiling {
340
- readonly version: 2;
340
+ readonly version: 3;
341
341
  readonly sequence: number;
342
- readonly restrictedProjectReach: "workspace" | "os-user";
343
342
  readonly revision: string;
344
- readonly fullAccess: boolean;
345
- readonly restrictedAllowedDomains: readonly string[];
343
+ readonly outsideSandbox: boolean;
344
+ readonly network: DeviceNetworkMode;
345
+ readonly allowedDomains: readonly string[];
346
+ readonly restrictedProjectReach: "workspace" | "os-user";
346
347
  }
347
348
  /**
348
- * The only owner-ceiling change the kernel may ask of a machine (B2): narrowing. Widening is decided
349
- * on the machine by its owner (`capybara-device ceiling set`), never over the wire.
349
+ * The narrowing of protocol 4: the kernel may switch the network to `allowlist`, remove hosts, turn
350
+ * `outsideSandbox` off or narrow the project reach. Never a widening: widening is decided on the
351
+ * machine by its owner (`capybara-device ceiling set`), never over the wire.
350
352
  */
351
353
  export interface DeviceOwnerCeilingNarrowing {
352
- readonly fullAccess?: false;
354
+ readonly outsideSandbox?: false;
355
+ readonly network?: "allowlist";
356
+ /** Hosts to remove from `allowedDomains`; a host not on the list is ignored. */
357
+ readonly removeAllowedDomains?: readonly string[];
353
358
  readonly restrictedProjectReach?: "workspace";
354
359
  }
355
360
  /** A staged `policy` op: the protocol 2 change plus an optional owner-ceiling narrowing. */
@@ -372,7 +377,7 @@ export interface DevicePolicyChanged {
372
377
  ownerCeiling: DeviceOwnerCeiling;
373
378
  }
374
379
  export interface DeviceHello extends LegacyDeviceHello {
375
- protocol: 3;
380
+ protocol: 4;
376
381
  permissionSupport: SandboxPermissionSupport;
377
382
  ownerCeiling: DeviceOwnerCeiling;
378
383
  instanceGeneration: string | null;
@@ -438,13 +443,39 @@ export type DeviceResponse = Exclude<DeviceRes, {
438
443
  id: string;
439
444
  ok: false;
440
445
  error: {
441
- kind: "gone" | "fs_gone" | "policy" | "error" | "denied" | "unsupported" | "unknown";
446
+ /**
447
+ * The typed failure: `denied`, `unsupported`, `unknown` and `invalid` carry the SDK's
448
+ * scope denial, unsupported permission, unknown outcome and scope validation errors.
449
+ * `invalid` never proves the operation had no effect (a skewed device may have parsed
450
+ * part of it): it must never join the not-run refusals (`isRefusal`, `failureKindOf`).
451
+ */
452
+ kind: "gone" | "fs_gone" | "policy" | "error" | "denied" | "unsupported" | "unknown" | "invalid";
442
453
  message: string;
443
454
  };
444
455
  };
445
456
  export type DeviceFrame = DeviceHello | KernelReady | KernelRequest | KernelCancel | DeviceResponse | DevicePolicyChanged;
446
- /** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
457
+ /**
458
+ * Strictly parses a runtime permission report, version 2 (the protocol 4 `permissionSupport`, also
459
+ * the shape a cloud provider reports), and returns a frozen copy; throws {@link DeviceProtocolError}.
460
+ * Restricted support is all four claims or `null`; per-operation hosts need the allowlist; an
461
+ * operation boundary without restricted support claims no sandbox network at all. An
462
+ * instance boundary is the whole instance: it claims no restricted per-operation scope, no
463
+ * outside-sandbox escalation and no per-operation hosts (a host joins the device's list instead).
464
+ */
465
+ export declare function parseSandboxPermissionSupport(value: unknown): SandboxPermissionSupport;
466
+ /**
467
+ * Strictly parses one authenticated owner-ceiling report of protocol 4 and returns a frozen copy;
468
+ * throws {@link DeviceProtocolError}. Unknown fields (the protocol 3 `fullAccess` and
469
+ * `restrictedAllowedDomains` among them) are refused.
470
+ */
447
471
  export declare function parseOwnerCeilingReport(value: unknown): DeviceOwnerCeiling;
448
- /** Strictly parses one protocol 3 frame; throws {@link DeviceProtocolError}. */
472
+ /**
473
+ * Strictly parses an owner-ceiling narrowing of protocol 4 and returns a frozen copy; throws
474
+ * {@link DeviceProtocolError}. Every field can only narrow: `outsideSandbox` only to `false`,
475
+ * `network` only to `allowlist`, the project reach only to `workspace`, and hosts only removed.
476
+ * There is no way to name a host to add or a list to replace.
477
+ */
478
+ export declare function parseOwnerCeilingNarrowing(value: unknown): DeviceOwnerCeilingNarrowing;
479
+ /** Strictly parses one protocol 4 frame; throws {@link DeviceProtocolError}. */
449
480
  export declare function parseDeviceFrame(raw: string, from: "device" | "kernel", maxFrameBytes?: number): DeviceFrame;
450
481
  export declare function parseOperationResult(op: DeviceOperation, result: unknown, request?: BackgroundReadOutputRequest | BindInstanceRequest): unknown;