@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
@@ -0,0 +1,53 @@
1
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ /** `path` in on-disk form when it exists (case and Unicode normalization as stored). */
4
+ export function onDisk(path) {
5
+ try {
6
+ return realpathSync.native(path);
7
+ }
8
+ catch {
9
+ return path;
10
+ }
11
+ }
12
+ /**
13
+ * How `path` resolves, one component at a time with `lstat` and `readlink`: every symbolic link
14
+ * met on the way (each link's own location, wherever in the chain it sits) and the final target
15
+ * (its existing part in on-disk form, the missing names appended). A dangling link is followed to
16
+ * the location it names. A link loop stops the walk; the links met so far are still returned.
17
+ *
18
+ * Shared by the device workers (macOS and Linux): each link and the target become anchored denies
19
+ * (the SDK `sandbox-write-denies.ts` constraint on consumers), so no hop of a dotfile manager's
20
+ * chain can be swapped for a real directory.
21
+ */
22
+ export function protectedChain(path) {
23
+ const links = [];
24
+ let pending = path.split("/").filter((part) => part !== "");
25
+ let current = "/";
26
+ for (let hops = 0; pending.length > 0;) {
27
+ const name = pending.shift();
28
+ if (name === ".")
29
+ continue;
30
+ // `current` is always a real directory here, so `..` is its physical parent
31
+ const next = name === ".." ? dirname(current) : join(current, name);
32
+ let link = false;
33
+ try {
34
+ link = lstatSync(next).isSymbolicLink();
35
+ }
36
+ catch {
37
+ // missing from here on: the rest would be created below the existing part
38
+ return { links, target: join(onDisk(current), name, ...pending) };
39
+ }
40
+ if (!link) {
41
+ current = next;
42
+ continue;
43
+ }
44
+ links.push(next);
45
+ if (++hops > 40)
46
+ return { links, target: path };
47
+ const to = readlinkSync(next);
48
+ pending = [...to.split("/").filter((part) => part !== ""), ...pending];
49
+ if (to.startsWith("/"))
50
+ current = "/";
51
+ }
52
+ return { links, target: onDisk(current) };
53
+ }
@@ -5,15 +5,19 @@ export declare function osRoots(dir: string): SandboxRoots;
5
5
  /**
6
6
  * The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
7
7
  * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
8
- * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
9
- * sets them.
8
+ * have to reshim?"). mise's follows XDG_DATA_HOME when the device's environment sets it. mise's
9
+ * configuration directory (`~/.config/mise`) is never granted: its `config.toml` may hold tokens
10
+ * (an `[env]` section). A mise-managed tool still runs from the data directory with a project pin
11
+ * or the global `.tool-versions` ({@link TOOL_HOME_FILES}); a global pin kept only in
12
+ * `config.toml` is not seen inside the sandbox.
10
13
  */
11
14
  export declare const TOOL_HOME_DIRS: readonly (readonly [string, string])[];
12
15
  /**
13
16
  * Single files in the home that hold a version manager's global pins, granted read only next to
14
17
  * {@link TOOL_HOME_DIRS}: asdf's global `.tool-versions` (mise reads it too). The other managers
15
18
  * keep their global version inside their data directory (pyenv and rbenv `version`, nvm
16
- * `alias/default`, rustup `settings.toml`, mise `config.toml`); a per-project file such as
19
+ * `alias/default`, rustup `settings.toml`; mise's `config.toml` is never granted, see
20
+ * {@link TOOL_HOME_DIRS}); a per-project file such as
17
21
  * `.nvmrc` is not global. Never a dotfile that could hold a secret.
18
22
  */
19
23
  export declare const TOOL_HOME_FILES: readonly string[];
@@ -10,8 +10,11 @@ export function osRoots(dir) {
10
10
  /**
11
11
  * The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
12
12
  * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
13
- * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
14
- * sets them.
13
+ * have to reshim?"). mise's follows XDG_DATA_HOME when the device's environment sets it. mise's
14
+ * configuration directory (`~/.config/mise`) is never granted: its `config.toml` may hold tokens
15
+ * (an `[env]` section). A mise-managed tool still runs from the data directory with a project pin
16
+ * or the global `.tool-versions` ({@link TOOL_HOME_FILES}); a global pin kept only in
17
+ * `config.toml` is not seen inside the sandbox.
15
18
  */
16
19
  export const TOOL_HOME_DIRS = [
17
20
  ["ASDF_DATA_DIR", ".asdf"],
@@ -19,7 +22,6 @@ export const TOOL_HOME_DIRS = [
19
22
  ["PYENV_ROOT", ".pyenv"],
20
23
  ["RBENV_ROOT", ".rbenv"],
21
24
  ["MISE_DATA_DIR", ".local/share/mise"],
22
- ["MISE_CONFIG_DIR", ".config/mise"],
23
25
  ["VOLTA_HOME", ".volta"],
24
26
  ["SDKMAN_DIR", ".sdkman"],
25
27
  ["RUSTUP_HOME", ".rustup"],
@@ -28,7 +30,8 @@ export const TOOL_HOME_DIRS = [
28
30
  * Single files in the home that hold a version manager's global pins, granted read only next to
29
31
  * {@link TOOL_HOME_DIRS}: asdf's global `.tool-versions` (mise reads it too). The other managers
30
32
  * keep their global version inside their data directory (pyenv and rbenv `version`, nvm
31
- * `alias/default`, rustup `settings.toml`, mise `config.toml`); a per-project file such as
33
+ * `alias/default`, rustup `settings.toml`; mise's `config.toml` is never granted, see
34
+ * {@link TOOL_HOME_DIRS}); a per-project file such as
32
35
  * `.nvmrc` is not global. Never a dotfile that could hold a secret.
33
36
  */
34
37
  export const TOOL_HOME_FILES = [".tool-versions"];
@@ -55,7 +58,6 @@ export function toolHomeEnv(home, env = process.env) {
55
58
  };
56
59
  const defaults = {
57
60
  MISE_DATA_DIR: join(xdg("XDG_DATA_HOME", ".local/share"), "mise"),
58
- MISE_CONFIG_DIR: join(xdg("XDG_CONFIG_HOME", ".config"), "mise"),
59
61
  };
60
62
  const out = {};
61
63
  for (const [name, rel] of TOOL_HOME_DIRS) {
@@ -60,11 +60,322 @@ index 0e598b612d84d24b09ec2ab0d7ccc9b009c9457b..10c4bd0b6518f6b968a105b0ed70838b
60
60
  ' (sysctl-name "hw.memsize")',
61
61
  ' (sysctl-name "hw.ncpu")',
62
62
  ' (sysctl-name "hw.nperflevels")',
63
+ diff --git a/dist/sandbox/resolved-address-guard.js b/dist/sandbox/resolved-address-guard.js
64
+ index 54970f754e71188fb6ab98971b39560b0b8f8724..e222d21be8df9d5bd77f6b1a33601737965fa5f1 100644
65
+ --- a/dist/sandbox/resolved-address-guard.js
66
+ +++ b/dist/sandbox/resolved-address-guard.js
67
+ @@ -25,6 +25,8 @@
68
+ import { lookup as dnsLookup } from 'node:dns';
69
+ import { BlockList, isIP } from 'node:net';
70
+ import { networkInterfaces } from 'node:os';
71
+ +// capybara patch: DNS-over-HTTPS behind a fake-IP resolver
72
+ +import { get as httpsGet } from 'node:https';
73
+ import { logForDebugging } from '../utils/debug.js';
74
+ import { ipLiteralRules } from './domain-pattern.js';
75
+ import { addRange, addressInSet, embeddedIPv4, isLoopbackAddress, isLoopbackName, LOOPBACK_RANGES, } from './address.js';
76
+ @@ -86,6 +88,192 @@ export function localInterfaceAddresses() {
77
+ .flat()
78
+ .flatMap(i => (i ? [i.address] : []));
79
+ }
80
+ +/**
81
+ + * capybara patch: DNS-over-HTTPS for names a fake-IP resolver answered. A router or local proxy in
82
+ + * fake-IP mode (OpenClash and the like) intercepts every DNS query, port 53 to any server
83
+ + * included, and answers each name with an address in a fake-IP range (`fakeIpDoh.fakeIpCidr`,
84
+ + * 198.18.0.0/15), which it maps back on connect. The guard cannot judge such an answer, so with
85
+ + * `fakeIpDoh` it re-resolves the name through DNS-over-HTTPS (RFC 8484: GET, wire format, A and
86
+ + * AAAA) to IP-literal endpoints (TLS verified against the endpoint's IP certificate; no DNS is
87
+ + * needed to reach them) and judges and dials the real answer like any resolved address. A failed
88
+ + * lookup refuses the connection: the fake address is never dialed. Only the IPv4 range is a
89
+ + * signal: a fake-IP resolver handing out IPv6 addresses (from ULA space, say) is not detected and
90
+ + * its answers are judged as they are (ULA is closed, so they fail closed).
91
+ + */
92
+ +const DOH_DEFAULTS = { timeoutMs: 5000, cacheTtlCapSeconds: 300, cacheMaxNames: 256 };
93
+ +const DOH_ANSWER_MAX_BYTES = 65536;
94
+ +function dohEndpoint(entry) {
95
+ + let url;
96
+ + try {
97
+ + url = new URL(entry);
98
+ + }
99
+ + catch { }
100
+ + const host = url?.hostname.replace(/^\[(.*)\]$/, '$1');
101
+ + if (!url || url.protocol !== 'https:' || !isIP(host ?? '') || url.username || url.password || url.search || url.hash)
102
+ + throw new Error(`A DNS-over-HTTPS endpoint must be an https URL with an IP-literal host and no query: ${JSON.stringify(entry)}`);
103
+ + return url;
104
+ +}
105
+ +/**
106
+ + * One RFC 8484 GET (`application/dns-message`). `tls` is a test seam only (a trusted CA for a
107
+ + * local fixture); production verifies against the system's roots.
108
+ + */
109
+ +export function defaultDohRequest(url, timeoutMs, tls = {}) {
110
+ + return new Promise((resolve, reject) => {
111
+ + const req = httpsGet(url, { headers: { accept: 'application/dns-message' }, agent: false, timeout: timeoutMs, ...(tls.ca ? { ca: tls.ca } : {}) }, res => {
112
+ + if (res.statusCode !== 200) {
113
+ + res.resume();
114
+ + reject(new Error(`HTTP ${res.statusCode}`));
115
+ + return;
116
+ + }
117
+ + const chunks = [];
118
+ + let size = 0;
119
+ + res.on('data', chunk => {
120
+ + size += chunk.length;
121
+ + if (size > DOH_ANSWER_MAX_BYTES)
122
+ + req.destroy(new Error('answer too large'));
123
+ + else
124
+ + chunks.push(chunk);
125
+ + });
126
+ + res.on('end', () => resolve(Buffer.concat(chunks)));
127
+ + res.on('error', reject);
128
+ + });
129
+ + req.on('timeout', () => req.destroy(new Error('timed out')));
130
+ + req.on('error', reject);
131
+ + });
132
+ +}
133
+ +function withDeadline(promise, ms) {
134
+ + let timer;
135
+ + return Promise.race([
136
+ + promise,
137
+ + new Promise((_, reject) => {
138
+ + timer = setTimeout(() => reject(new Error('timed out')), ms);
139
+ + }),
140
+ + ]).finally(() => clearTimeout(timer));
141
+ +}
142
+ +/** A wire-format query (RFC 1035) for `name` and `qtype`, id 0 as RFC 8484 recommends. */
143
+ +function dnsQuery(name, qtype) {
144
+ + const labels = name.split('.');
145
+ + if (name.length > 253 || labels.some(l => !l.length || l.length > 63 || /[^\x21-\x7e]/.test(l)))
146
+ + throw new Error('name not expressible in DNS');
147
+ + const header = Buffer.from([0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0]);
148
+ + const parts = labels.map(l => Buffer.concat([Buffer.from([l.length]), Buffer.from(l, 'ascii')]));
149
+ + const tail = Buffer.from([0, qtype >> 8, qtype & 0xff, 0, 1]);
150
+ + return Buffer.concat([header, ...parts, tail]);
151
+ +}
152
+ +/** The offset after the (possibly compressed) name at `at`. */
153
+ +function skipName(message, at) {
154
+ + for (let hops = 0; hops < 128; hops++) {
155
+ + const length = message[at];
156
+ + if (length === undefined)
157
+ + throw new Error('truncated');
158
+ + if (length === 0)
159
+ + return at + 1;
160
+ + if ((length & 0xc0) === 0xc0)
161
+ + return at + 2;
162
+ + at += length + 1;
163
+ + }
164
+ + throw new Error('malformed name');
165
+ +}
166
+ +/** The addresses of one wire-format answer for `qtype`, the fake-IP range dropped, and their TTL. */
167
+ +function dnsAnswer(message, qtype, fakeIp, ttlCap) {
168
+ + if (message.length < 12)
169
+ + throw new Error('truncated answer');
170
+ + const flags = message.readUInt16BE(2);
171
+ + if (!(flags & 0x8000) || flags & 0x0200)
172
+ + throw new Error('not a complete answer');
173
+ + const rcode = flags & 0x000f;
174
+ + // NXDOMAIN is an answer: the name does not exist
175
+ + if (rcode === 3)
176
+ + return { addresses: [], ttl: 0 };
177
+ + if (rcode !== 0)
178
+ + throw new Error(`DNS rcode ${rcode}`);
179
+ + const questions = message.readUInt16BE(4);
180
+ + const answers = message.readUInt16BE(6);
181
+ + let at = 12;
182
+ + for (let i = 0; i < questions; i++)
183
+ + at = skipName(message, at) + 4;
184
+ + const size = qtype === 1 ? 4 : 16;
185
+ + const addresses = [];
186
+ + let ttl = ttlCap;
187
+ + for (let i = 0; i < answers; i++) {
188
+ + at = skipName(message, at);
189
+ + if (at + 10 > message.length)
190
+ + throw new Error('truncated answer');
191
+ + const type = message.readUInt16BE(at);
192
+ + const rclass = message.readUInt16BE(at + 2);
193
+ + const recordTtl = message.readUInt32BE(at + 4);
194
+ + const length = message.readUInt16BE(at + 8);
195
+ + at += 10;
196
+ + if (at + length > message.length)
197
+ + throw new Error('truncated answer');
198
+ + if (type === qtype && rclass === 1 && length === size) {
199
+ + const bytes = message.subarray(at, at + length);
200
+ + const address = size === 4
201
+ + ? [...bytes].join('.')
202
+ + : Array.from({ length: 8 }, (_, g) => bytes.readUInt16BE(g * 2).toString(16)).join(':');
203
+ + if (!addressInSet(fakeIp, address)) {
204
+ + addresses.push({ address, family: size === 4 ? 4 : 6 });
205
+ + ttl = Math.min(ttl, recordTtl);
206
+ + }
207
+ + }
208
+ + at += length;
209
+ + }
210
+ + return { addresses, ttl };
211
+ +}
212
+ +function createDohResolver(config, request) {
213
+ + const endpoints = (config.endpoints ?? []).map(dohEndpoint);
214
+ + if (!endpoints.length)
215
+ + throw new Error('A DNS-over-HTTPS endpoint list must not be empty');
216
+ + const deadlineMs = config.timeoutMs ?? DOH_DEFAULTS.timeoutMs;
217
+ + const ttlCap = config.cacheTtlCapSeconds ?? DOH_DEFAULTS.cacheTtlCapSeconds;
218
+ + const cacheMax = config.cacheMaxNames ?? DOH_DEFAULTS.cacheMaxNames;
219
+ + const fakeIp = new BlockList();
220
+ + if (!addRange(fakeIp, config.fakeIpCidr ?? '198.18.0.0/15'))
221
+ + throw new Error(`Invalid fake-IP range: ${JSON.stringify(config.fakeIpCidr)}`);
222
+ + const cache = new Map();
223
+ + const ask = (endpoint, name, qtype, ms) => {
224
+ + const url = new URL(endpoint.href);
225
+ + url.searchParams.set('dns', dnsQuery(name, qtype).toString('base64url'));
226
+ + return withDeadline(Promise.resolve().then(() => request(url.href, ms)), ms).then(body => dnsAnswer(Buffer.from(body), qtype, fakeIp, ttlCap));
227
+ + };
228
+ + const lookup = async (hostname) => {
229
+ + const name = hostname.toLowerCase().replace(/\.$/, '');
230
+ + const hit = cache.get(name);
231
+ + if (hit && hit.expires > Date.now())
232
+ + return hit.addresses;
233
+ + cache.delete(name);
234
+ + const deadline = Date.now() + deadlineMs;
235
+ + let partial;
236
+ + let last;
237
+ + for (let i = 0; i < endpoints.length; i++) {
238
+ + const remaining = deadline - Date.now();
239
+ + if (remaining <= 0)
240
+ + break;
241
+ + // each endpoint gets its share of what is left, so a stalled one cannot starve the rest
242
+ + const share = Math.max(1, Math.floor(remaining / (endpoints.length - i)));
243
+ + const [a, aaaa] = await Promise.allSettled([1, 28].map(qtype => ask(endpoints[i], name, qtype, share)));
244
+ + if (a.status === 'fulfilled' && aaaa.status === 'fulfilled') {
245
+ + const addresses = [...a.value.addresses, ...aaaa.value.addresses];
246
+ + const ttl = Math.min(a.value.ttl, aaaa.value.ttl);
247
+ + // cached only when both queries answered
248
+ + if (ttl > 0 && cacheMax > 0) {
249
+ + if (cache.size >= cacheMax)
250
+ + cache.delete(cache.keys().next().value);
251
+ + cache.set(name, { addresses, expires: Date.now() + ttl * 1000 });
252
+ + }
253
+ + return addresses;
254
+ + }
255
+ + const ok = [a, aaaa].find(r => r.status === 'fulfilled');
256
+ + partial ??= ok?.value.addresses;
257
+ + last = [a, aaaa].find(r => r.status === 'rejected')?.reason ?? last;
258
+ + }
259
+ + // one family answered somewhere: use it, uncached
260
+ + if (partial)
261
+ + return partial;
262
+ + throw last ?? new Error('timed out');
263
+ + };
264
+ + return { lookup, fakeIp };
265
+ +}
266
+ export class ResolvedAddressDeniedError extends Error {
267
+ /**
268
+ * @param reason parenthetical for the violation line and the client, e.g.
269
+ @@ -131,6 +319,14 @@ export function createResolvedAddressGuard(opts = {}) {
270
+ ['a listed address', buildRuleSet(opts.deniedResolvedAddresses ?? [])],
271
+ ];
272
+ const resolve = opts.resolve ?? dnsLookup;
273
+ + // capybara patch: `resolvedAddressStrict` judges every destination by its address: an IP
274
+ + // literal by the same rules as a resolved name (see `literalDenial`), and the reserved
275
+ + // loopback names without their loopback carve-out
276
+ + const strict = opts.resolvedAddressStrict === true;
277
+ + // capybara patch: the DNS-over-HTTPS resolver for fake-IP answers (`fakeIpDoh`)
278
+ + const doh = opts.fakeIpDoh
279
+ + ? createDohResolver(opts.fakeIpDoh, opts.dohRequest ?? defaultDohRequest)
280
+ + : undefined;
281
+ /** This host's addresses right now; a malformed entry from the seam is skipped. */
282
+ const localSet = () => {
283
+ const list = new BlockList();
284
+ @@ -140,8 +336,8 @@ export function createResolvedAddressGuard(opts = {}) {
285
+ return list;
286
+ };
287
+ /** Why `hostname:port` may not use resolved `address`, or undefined if it may. */
288
+ - const denial = (hostname, address, port, local) => {
289
+ - if (isIP(hostname))
290
+ + const denial = (hostname, address, port, local, literal = false) => {
291
+ + if (isIP(hostname) && !literal)
292
+ return undefined;
293
+ if (!isIP(address))
294
+ return 'an unparsable address';
295
+ @@ -157,9 +353,11 @@ export function createResolvedAddressGuard(opts = {}) {
296
+ (v4 !== undefined && inRuleSet(set, v4, port));
297
+ if (denies(refused))
298
+ return 'a deny-listed address';
299
+ - if (inRuleSet(allowed, address, port))
300
+ + // capybara patch: in strict mode an allow-listed literal gets no carve-out over the
301
+ + // closed classes (private destinations need the escalation)
302
+ + if (!strict && inRuleSet(allowed, address, port))
303
+ return undefined;
304
+ - if (isLoopbackName(hostname)) {
305
+ + if (!strict && isLoopbackName(hostname)) {
306
+ return isLoopbackAddress(address) ? undefined : 'a non-loopback address';
307
+ }
308
+ const why = denied.find(([, set]) => denies(set))?.[0];
309
+ @@ -171,11 +369,24 @@ export function createResolvedAddressGuard(opts = {}) {
310
+ return undefined;
311
+ };
312
+ const lookupFor = (port) => (hostname, options, callback) => {
313
+ - resolve(hostname, { ...options, all: true }, (err, addresses) => {
314
+ + resolve(hostname, { ...options, all: true }, (err, answer) => {
315
+ if (err) {
316
+ callback(err, []);
317
+ return;
318
+ }
319
+ + // capybara patch: a fake-IP answer is re-resolved through DNS-over-HTTPS, and only
320
+ + // the real answer is judged; when that fails, the connection is refused
321
+ + if (doh && answer.some(a => isIP(a.address) && addressInSet(doh.fakeIp, a.address))) {
322
+ + doh.lookup(hostname).then(judge, error => {
323
+ + const fake = answer.map(a => a.address);
324
+ + logForDebugging(`DNS-over-HTTPS failed for ${hostname}:${port} behind a fake-IP resolver: ${error?.message ?? error}`);
325
+ + callback(new ResolvedAddressDeniedError(hostname, `resolved by a fake-IP resolver and the DNS-over-HTTPS lookup failed (${error?.message ?? 'unknown error'})`, fake), []);
326
+ + });
327
+ + return;
328
+ + }
329
+ + judge(answer);
330
+ + });
331
+ + function judge(addresses) {
332
+ const local = localSet();
333
+ const kept = [];
334
+ const dropped = [];
335
+ @@ -211,10 +422,13 @@ export function createResolvedAddressGuard(opts = {}) {
336
+ callback(null, kept);
337
+ else
338
+ callback(null, first.address, first.family);
339
+ - });
340
+ + }
341
+ };
342
+ return {
343
+ permits: (hostname, address, port) => denial(hostname, address, port, localSet()) === undefined,
344
+ + // capybara patch: why an IP-literal destination is refused in strict mode, or undefined
345
+ + // when it may be dialed (always undefined without `resolvedAddressStrict`)
346
+ + literalDenial: (address, port) => strict ? denial(address, address, port, localSet(), true) : undefined,
347
+ lookupFor,
348
+ };
349
+ }
63
350
  diff --git a/dist/sandbox/sandbox-config.js b/dist/sandbox/sandbox-config.js
64
- index 76b00b1dc82a2d42a451a9f58068cbbd5e68da75..25ea77fe4259ddeb8578262fffd2021c7c06aa0d 100644
351
+ index 76b00b1dc82a2d42a451a9f58068cbbd5e68da75..e00370349136adcd79465395efd3ffb051116c71 100644
65
352
  --- a/dist/sandbox/sandbox-config.js
66
353
  +++ b/dist/sandbox/sandbox-config.js
67
- @@ -832,6 +832,22 @@ export const FilesystemConfigSchema = z.object({
354
+ @@ -608,6 +608,23 @@ export const NetworkConfigSchema = z.object({
355
+ 'deniedDomains. A permitted name that resolves only into these is refused instead of dialed. A name may ' +
356
+ 'resolve to a denied address only if that IP literal (and port) is itself in allowedDomains. Not evaluated ' +
357
+ 'for connections routed through parentProxy (including one taken from HTTP_PROXY/HTTPS_PROXY) or mitmProxy (that hop resolves the name).'),
358
+ + // capybara patch: judge IP literals and the loopback names by their address too
359
+ + resolvedAddressStrict: z
360
+ + .boolean()
361
+ + .optional()
362
+ + .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.'),
363
+ + // capybara patch: DNS-over-HTTPS for names a fake-IP resolver answered (198.18.0.0/15)
364
+ + fakeIpDoh: z
365
+ + .object({
366
+ + fakeIpCidr: z.string().optional(),
367
+ + endpoints: z.array(z.string()).min(1),
368
+ + timeoutMs: z.number().int().min(1).max(30000).optional(),
369
+ + cacheTtlCapSeconds: z.number().int().min(0).max(86400).optional(),
370
+ + cacheMaxNames: z.number().int().min(0).max(65536).optional(),
371
+ + })
372
+ + .strict()
373
+ + .optional()
374
+ + .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.'),
375
+ allowUnixSockets: z
376
+ .array(z.string())
377
+ .optional()
378
+ @@ -832,6 +849,22 @@ export const FilesystemConfigSchema = z.object({
68
379
  .boolean()
69
380
  .optional()
70
381
  .describe('Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.'),
@@ -88,10 +399,35 @@ index 76b00b1dc82a2d42a451a9f58068cbbd5e68da75..25ea77fe4259ddeb8578262fffd2021c
88
399
  /**
89
400
  * Configuration schema for ignoring specific sandbox violations
90
401
  diff --git a/dist/sandbox/sandbox-manager.js b/dist/sandbox/sandbox-manager.js
91
- index d475e55977bf54a2fe00a0c6aba38313761d55aa..d60dab574bca5a1071e55dae7c597c6a2c86a4a6 100644
402
+ index d475e55977bf54a2fe00a0c6aba38313761d55aa..b9a0f9920dbb3fab60c6f48e40956304295478c4 100644
92
403
  --- a/dist/sandbox/sandbox-manager.js
93
404
  +++ b/dist/sandbox/sandbox-manager.js
94
- @@ -1493,6 +1493,8 @@ function getFsReadConfig() {
405
+ @@ -26,6 +26,8 @@ import { canonicalizeHost, isValidHost, redactUrl, resolveParentProxy, } from '.
406
+ import { ALLOWED_DOMAIN_ENTRY_MESSAGE, isValidAllowedDomainEntry, matchesDomainPattern, matchesDomainPatternWithPort, stripDomainPatternPort, } from './domain-pattern.js';
407
+ import { createResolvedAddressGuard, isResolvedAddressDenied, } from './resolved-address-guard.js';
408
+ import { EOL } from 'node:os';
409
+ +// capybara patch: the strict literal check
410
+ +import { isIP } from 'node:net';
411
+ import { dirname } from 'node:path';
412
+ import { getJavaProxyAgentJarPathAsync } from './java-proxy-agent.js';
413
+ import { getApplySeccompBinaryPathAsync } from './generate-seccomp-filter.js';
414
+ @@ -522,6 +524,15 @@ async function filterNetworkRequest(port, host, sandboxAskCallback, encodedComma
415
+ return denied(deniedDomainReason(deniedDomain));
416
+ }
417
+ }
418
+ + // capybara patch: in strict mode an IP-literal destination is judged by the resolved-address
419
+ + // rules (upstream judges only names there), so a literal reaches nothing a name could not
420
+ + const literalWhy = isIP(canonicalHost)
421
+ + ? resolvedAddressGuard.literalDenial(canonicalHost, port)
422
+ + : undefined;
423
+ + if (literalWhy) {
424
+ + logForDebugging(`Denied address literal: ${host}:${port} (${literalWhy})`);
425
+ + return denied(`address is ${literalWhy}`);
426
+ + }
427
+ // Check allowed domains
428
+ for (const allowedDomain of config.network.allowedDomains) {
429
+ if (matchesDomainPatternWithPort(canonicalHost, port, allowedDomain)) {
430
+ @@ -1493,6 +1504,8 @@ function getFsReadConfig() {
95
431
  allowWithinDeny: allowPaths,
96
432
  unlistableDenyDirs: [...unlistableDenyDirs],
97
433
  ...literalReadLists(config.filesystem.denyRead, config.filesystem.allowRead),
@@ -100,7 +436,7 @@ index d475e55977bf54a2fe00a0c6aba38313761d55aa..d60dab574bca5a1071e55dae7c597c6a
100
436
  };
101
437
  }
102
438
  function getFsWriteConfig() {
103
- @@ -1516,6 +1518,8 @@ function getFsWriteConfig() {
439
+ @@ -1516,6 +1529,8 @@ function getFsWriteConfig() {
104
440
  allowOnly,
105
441
  denyWithinAllow: denyPaths,
106
442
  ...literalWriteLists(config.filesystem.allowWrite, config.filesystem.denyWrite),
@@ -109,7 +445,7 @@ index d475e55977bf54a2fe00a0c6aba38313761d55aa..d60dab574bca5a1071e55dae7c597c6a
109
445
  };
110
446
  }
111
447
  /**
112
- @@ -1866,6 +1870,8 @@ async function wrapWithSandboxOnce(walkEnded, restarts, command, binShell, custo
448
+ @@ -1866,6 +1881,8 @@ async function wrapWithSandboxOnce(walkEnded, restarts, command, binShell, custo
113
449
  config?.filesystem.denyWrite ??
114
450
  []),
115
451
  ...literalWriteLists(customConfig?.filesystem?.allowWrite ?? config?.filesystem.allowWrite, customConfig?.filesystem?.denyWrite ?? config?.filesystem.denyWrite),
@@ -118,7 +454,7 @@ index d475e55977bf54a2fe00a0c6aba38313761d55aa..d60dab574bca5a1071e55dae7c597c6a
118
454
  };
119
455
  // For a caller that never reads checkDependencies(), the CLI among them.
120
456
  if (!ownInstallLogged) {
121
- @@ -1917,6 +1923,8 @@ async function wrapWithSandboxOnce(walkEnded, restarts, command, binShell, custo
457
+ @@ -1917,6 +1934,8 @@ async function wrapWithSandboxOnce(walkEnded, restarts, command, binShell, custo
122
458
  ...(ownAllowWithinDeny.length > 0 && { ownAllowWithinDeny }),
123
459
  unlistableDenyDirs: [...unlistableDenyDirs],
124
460
  ...literalReadLists(customConfig?.filesystem?.denyRead ?? config?.filesystem.denyRead, customConfig?.filesystem?.allowRead ?? config?.filesystem.allowRead),