@radheim/plugin-browser 0.0.0-stage → 2.4.3

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.
@@ -0,0 +1,446 @@
1
+ export * as EgressPolicy from "./egress-policy.js";
2
+ import { isIP } from "node:net";
3
+ export class EgressDeniedError extends Error {
4
+ code = "POLICY_DENIED";
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "EgressDeniedError";
8
+ }
9
+ }
10
+ /**
11
+ * Non-HTTP infrastructure and management ports refused on loopback and private targets so a loaded
12
+ * page cannot reach local SSH, mail, SMB, Docker, or Kubernetes control planes.
13
+ */
14
+ export const BLOCKED_MANAGEMENT_PORTS = new Set([
15
+ 22,
16
+ 23,
17
+ 25,
18
+ 111,
19
+ 135,
20
+ 137,
21
+ 138,
22
+ 139,
23
+ 445,
24
+ 2375,
25
+ 2376,
26
+ 6443,
27
+ 10250,
28
+ ]);
29
+ const METADATA_HOSTS = new Set([
30
+ "metadata",
31
+ "metadata.google.internal",
32
+ "metadata.goog",
33
+ "instance-data",
34
+ "instance-data.ec2.internal",
35
+ "metadata.azure.internal",
36
+ "metadata.packet.net",
37
+ "metadata.platformequinix.com",
38
+ ]);
39
+ export function readAllowPrivateLanEnv(env = process.env) {
40
+ const value = env.OPENCODE_BROWSER_ALLOW_PRIVATE_LAN?.trim().toLowerCase();
41
+ return value === "1" || value === "true" || value === "yes";
42
+ }
43
+ export function makePolicy(options = {}) {
44
+ const granted = new Map();
45
+ const allowPrivateLan = options.allowPrivateLan ?? readAllowPrivateLanEnv();
46
+ const reservedLocalPorts = options.reservedLocalPorts ?? (() => new Set());
47
+ const isReservedPort = (port) => BLOCKED_MANAGEMENT_PORTS.has(port) || reservedLocalPorts().has(port);
48
+ const isGranted = (host, port) => granted.get(normalizeHost(host))?.has(port) ?? false;
49
+ return {
50
+ /**
51
+ * Grants one attachment access to an explicit private preview host/port (and optional HMR ports).
52
+ * Refuses reserved metadata hostnames/IPs and management or server-owned ports.
53
+ */
54
+ grant(host, port, extraPorts = []) {
55
+ const normalized = normalizeHost(host);
56
+ if (!normalized || isMetadataHost(normalized)) {
57
+ throw new EgressDeniedError(`Cannot grant reserved metadata host: ${host}`);
58
+ }
59
+ const literal = parseIpLiteral(normalized);
60
+ if (literal) {
61
+ const cls = classifyIp(literal.address);
62
+ if (cls === "metadata" || cls === "reserved") {
63
+ throw new EgressDeniedError(`Cannot grant reserved address: ${host}`);
64
+ }
65
+ }
66
+ const ports = [port, ...extraPorts];
67
+ for (const candidate of ports) {
68
+ if (!Number.isInteger(candidate) || candidate < 1 || candidate > 65_535) {
69
+ throw new EgressDeniedError(`Invalid port in grant: ${candidate}`);
70
+ }
71
+ if (isReservedPort(candidate)) {
72
+ throw new EgressDeniedError(`Cannot grant protected management port ${candidate}.`);
73
+ }
74
+ }
75
+ const existing = granted.get(normalized) ?? new Set();
76
+ ports.forEach((candidate) => existing.add(candidate));
77
+ granted.set(normalized, existing);
78
+ },
79
+ evaluateAddress(host, port, address) {
80
+ const normalized = normalizeHost(host);
81
+ if (!normalized || isMetadataHost(normalized)) {
82
+ return { allowed: false, addressClass: "metadata", reason: "Access to cloud metadata endpoints is blocked." };
83
+ }
84
+ const cls = classifyIp(address);
85
+ if (cls === "metadata" || cls === "reserved") {
86
+ return {
87
+ allowed: false,
88
+ addressClass: cls,
89
+ reason: `Access to ${cls} address ${address} is blocked by egress policy.`,
90
+ };
91
+ }
92
+ if (cls === "loopback") {
93
+ if (isReservedPort(port)) {
94
+ return {
95
+ allowed: false,
96
+ addressClass: cls,
97
+ reason: `Access to protected local management port ${port} is blocked by egress policy.`,
98
+ };
99
+ }
100
+ if (isLoopbackHostName(normalized) || isGranted(normalized, port)) {
101
+ return { allowed: true, addressClass: cls };
102
+ }
103
+ return {
104
+ allowed: false,
105
+ addressClass: cls,
106
+ reason: `Blocked DNS rebinding: non-loopback host "${normalized}" resolved to loopback address ${address}.`,
107
+ };
108
+ }
109
+ if (cls === "private") {
110
+ if (isReservedPort(port)) {
111
+ return {
112
+ allowed: false,
113
+ addressClass: cls,
114
+ reason: `Access to protected private management port ${port} is blocked by egress policy.`,
115
+ };
116
+ }
117
+ if (allowPrivateLan || isGranted(normalized, port)) {
118
+ return { allowed: true, addressClass: cls };
119
+ }
120
+ return {
121
+ allowed: false,
122
+ addressClass: cls,
123
+ reason: `Access to private network target ${normalized}:${port} (${address}) is blocked by egress policy.`,
124
+ };
125
+ }
126
+ return { allowed: true, addressClass: "public" };
127
+ },
128
+ /**
129
+ * Resolves `target.host` once on the server, validates EVERY resolved address against policy,
130
+ * and returns the complete verified list so the socket can try another address without resolving again.
131
+ */
132
+ async resolveTarget(target) {
133
+ const normalized = normalizeHost(target.host);
134
+ if (!normalized)
135
+ throw new EgressDeniedError("Target host is empty.");
136
+ if (isMetadataHost(normalized)) {
137
+ throw new EgressDeniedError(`Access to metadata host "${normalized}" is blocked by egress policy.`);
138
+ }
139
+ const literal = parseIpLiteral(normalized);
140
+ const resolved = literal ? [literal] : await (options.resolve ?? defaultResolve)(normalized);
141
+ if (resolved.length === 0) {
142
+ throw new Error(`Could not resolve target host: ${normalized}`);
143
+ }
144
+ // Every resolved address must pass policy so dual-record DNS responses cannot smuggle
145
+ // loopback, private, or metadata addresses behind a public record.
146
+ for (const candidate of resolved) {
147
+ const decision = this.evaluateAddress(normalized, target.port, candidate.address);
148
+ if (!decision.allowed)
149
+ throw new EgressDeniedError(decision.reason);
150
+ }
151
+ return resolved;
152
+ },
153
+ };
154
+ }
155
+ /**
156
+ * Connects only to verified IPs. The socket selects a reachable address when a host has several.
157
+ */
158
+ export async function resolveAndConnect(target, policy, options = {}) {
159
+ if (options.signal?.aborted)
160
+ throw new Error("Browser tunnel connection was cancelled.");
161
+ const verified = await policy.resolveTarget(target);
162
+ if (options.signal?.aborted)
163
+ throw new Error("Browser tunnel connection was cancelled.");
164
+ const { createConnection } = await import("node:net");
165
+ const socket = createConnection({
166
+ host: verified.length === 1 ? verified[0].address : target.host,
167
+ autoSelectFamily: true,
168
+ lookup: (_host, options, callback) => {
169
+ if (options.all)
170
+ return callback(null, [...verified]);
171
+ callback(null, verified[0].address, verified[0].family);
172
+ },
173
+ port: target.port,
174
+ allowHalfOpen: true,
175
+ });
176
+ const timeoutMs = options.timeoutMs ?? 10_000;
177
+ return await new Promise((resolve, reject) => {
178
+ const timer = setTimeout(() => {
179
+ cleanup();
180
+ socket.destroy();
181
+ reject(new Error("Browser tunnel target connection timed out."));
182
+ }, timeoutMs);
183
+ const onAbort = () => {
184
+ cleanup();
185
+ socket.destroy();
186
+ reject(new Error("Browser tunnel connection was cancelled."));
187
+ };
188
+ const onConnect = () => {
189
+ cleanup();
190
+ socket.setNoDelay(true);
191
+ resolve(socket);
192
+ };
193
+ const onError = (error) => {
194
+ cleanup();
195
+ socket.destroy();
196
+ reject(error);
197
+ };
198
+ const onClose = () => {
199
+ cleanup();
200
+ reject(new Error("Browser tunnel closed while connecting."));
201
+ };
202
+ const cleanup = () => {
203
+ clearTimeout(timer);
204
+ options.signal?.removeEventListener("abort", onAbort);
205
+ socket.off("connect", onConnect);
206
+ socket.off("error", onError);
207
+ socket.off("close", onClose);
208
+ };
209
+ options.signal?.addEventListener("abort", onAbort, { once: true });
210
+ socket.once("connect", onConnect);
211
+ socket.once("error", onError);
212
+ socket.once("close", onClose);
213
+ if (options.signal?.aborted)
214
+ onAbort();
215
+ });
216
+ }
217
+ async function defaultResolve(host) {
218
+ const { lookup } = await import("node:dns/promises");
219
+ const results = await lookup(host, { all: true, verbatim: true });
220
+ return results
221
+ .filter((entry) => entry.family === 4 || entry.family === 6)
222
+ .map((entry) => ({ address: entry.address, family: entry.family }));
223
+ }
224
+ export function normalizeHost(host) {
225
+ return host.trim().replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase();
226
+ }
227
+ export function isMetadataHost(host) {
228
+ const normalized = normalizeHost(host);
229
+ return METADATA_HOSTS.has(normalized) || normalized.endsWith(".metadata.google.internal");
230
+ }
231
+ export function isLoopbackHostName(host) {
232
+ const normalized = normalizeHost(host);
233
+ if (normalized === "localhost" || normalized.endsWith(".localhost"))
234
+ return true;
235
+ const literal = parseIpLiteral(normalized);
236
+ return literal !== undefined && classifyIp(literal.address) === "loopback";
237
+ }
238
+ /**
239
+ * Parses IPv4 (including decimal, octal, hex, and shorthand forms via WHATWG URL canonicalization)
240
+ * and IPv6 literals (with optional zone IDs stripped for classification).
241
+ */
242
+ export function parseIpLiteral(host) {
243
+ const normalized = normalizeHost(host);
244
+ if (!normalized)
245
+ return undefined;
246
+ // Strip IPv6 zone identifier if present (e.g. fe80::1%eth0)
247
+ const zoneIndex = normalized.indexOf("%");
248
+ const bare = zoneIndex >= 0 ? normalized.slice(0, zoneIndex) : normalized;
249
+ const kind = isIP(bare);
250
+ if (kind === 4)
251
+ return { address: bare, family: 4 };
252
+ if (kind === 6)
253
+ return { address: bare, family: 6 };
254
+ // Catch non-standard IPv4 forms like 2130706433, 0x7f000001, 0177.0.0.1, 127.1
255
+ if (!bare.includes(":") && /^[0-9a-fx.]+$/i.test(bare)) {
256
+ const parsed = URL.parse(`http://${bare}/`);
257
+ if (parsed && isIP(parsed.hostname) === 4)
258
+ return { address: parsed.hostname, family: 4 };
259
+ }
260
+ return undefined;
261
+ }
262
+ export function classifyIp(input) {
263
+ const zoneIndex = input.indexOf("%");
264
+ const address = (zoneIndex >= 0 ? input.slice(0, zoneIndex) : input).trim().toLowerCase();
265
+ const kind = isIP(address);
266
+ if (kind === 4)
267
+ return classifyIpv4(parseIpv4(address));
268
+ if (kind === 6)
269
+ return classifyIpv6(parseIpv6(address));
270
+ return "reserved";
271
+ }
272
+ function parseIpv4(address) {
273
+ const parts = address.split(".");
274
+ return ((((Number(parts[0]) << 24) >>> 0) |
275
+ ((Number(parts[1]) << 16) >>> 0) |
276
+ ((Number(parts[2]) << 8) >>> 0) |
277
+ (Number(parts[3]) >>> 0)) >>>
278
+ 0);
279
+ }
280
+ function classifyIpv4(ip) {
281
+ const a = (ip >>> 24) & 0xff;
282
+ const b = (ip >>> 16) & 0xff;
283
+ const c = (ip >>> 8) & 0xff;
284
+ const d = ip & 0xff;
285
+ // 169.254.0.0/16 (link-local & AWS/GCP/Azure IMDS) and 100.100.100.200 (Alibaba IMDS)
286
+ if (a === 169 && b === 254)
287
+ return "metadata";
288
+ if (a === 100 && b === 100 && c === 100 && d === 200)
289
+ return "metadata";
290
+ // 0.0.0.0/8 (unspecified), 224.0.0.0/4 (multicast), 240.0.0.0/4 (reserved + broadcast)
291
+ if (a === 0 || a >= 224)
292
+ return "reserved";
293
+ // 127.0.0.0/8 (loopback)
294
+ if (a === 127)
295
+ return "loopback";
296
+ // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 (CGNAT)
297
+ if (a === 10)
298
+ return "private";
299
+ if (a === 172 && b >= 16 && b <= 31)
300
+ return "private";
301
+ if (a === 192 && b === 168)
302
+ return "private";
303
+ if (a === 100 && b >= 64 && b <= 127)
304
+ return "private";
305
+ return "public";
306
+ }
307
+ function parseIpv6(address) {
308
+ const bytes = new Uint8Array(16);
309
+ // Handle embedded IPv4 tail like ::ffff:127.0.0.1
310
+ let working = address;
311
+ const lastColon = working.lastIndexOf(":");
312
+ const tail = lastColon >= 0 ? working.slice(lastColon + 1) : "";
313
+ if (tail.includes(".")) {
314
+ const v4 = parseIpv4(tail);
315
+ const hi = ((v4 >>> 16) & 0xffff).toString(16);
316
+ const lo = (v4 & 0xffff).toString(16);
317
+ working = `${working.slice(0, lastColon)}:${hi}:${lo}`;
318
+ }
319
+ const halves = working.split("::");
320
+ const left = halves[0] ? halves[0].split(":").filter(Boolean) : [];
321
+ const right = halves.length === 2 && halves[1] ? halves[1].split(":").filter(Boolean) : [];
322
+ const groups = new Uint16Array(8);
323
+ left.forEach((part, index) => {
324
+ groups[index] = parseInt(part, 16);
325
+ });
326
+ const rightStart = 8 - right.length;
327
+ right.forEach((part, index) => {
328
+ groups[rightStart + index] = parseInt(part, 16);
329
+ });
330
+ for (let i = 0; i < 8; i++) {
331
+ bytes[i * 2] = (groups[i] >>> 8) & 0xff;
332
+ bytes[i * 2 + 1] = groups[i] & 0xff;
333
+ }
334
+ return bytes;
335
+ }
336
+ function classifyIpv6(bytes) {
337
+ const allZero = bytes.every((value) => value === 0);
338
+ if (allZero)
339
+ return "reserved";
340
+ // ::1 loopback
341
+ let isLoopback = bytes[15] === 1;
342
+ for (let i = 0; i < 15 && isLoopback; i++) {
343
+ if (bytes[i] !== 0)
344
+ isLoopback = false;
345
+ }
346
+ if (isLoopback)
347
+ return "loopback";
348
+ // ::ffff:0:0/96 (IPv4-mapped)
349
+ const isV4Mapped = bytes[0] === 0 &&
350
+ bytes[1] === 0 &&
351
+ bytes[2] === 0 &&
352
+ bytes[3] === 0 &&
353
+ bytes[4] === 0 &&
354
+ bytes[5] === 0 &&
355
+ bytes[6] === 0 &&
356
+ bytes[7] === 0 &&
357
+ bytes[8] === 0 &&
358
+ bytes[9] === 0 &&
359
+ bytes[10] === 0xff &&
360
+ bytes[11] === 0xff;
361
+ if (isV4Mapped)
362
+ return classifyIpv4(readUint32(bytes, 12));
363
+ // ::ffff:0:0:0/96 (IPv4-translated)
364
+ const isV4Translated = bytes[0] === 0 &&
365
+ bytes[1] === 0 &&
366
+ bytes[2] === 0 &&
367
+ bytes[3] === 0 &&
368
+ bytes[4] === 0 &&
369
+ bytes[5] === 0 &&
370
+ bytes[6] === 0 &&
371
+ bytes[7] === 0 &&
372
+ bytes[8] === 0xff &&
373
+ bytes[9] === 0xff &&
374
+ bytes[10] === 0 &&
375
+ bytes[11] === 0;
376
+ if (isV4Translated)
377
+ return classifyIpv4(readUint32(bytes, 12));
378
+ // 64:ff9b::/96 (RFC 6052 NAT64) and 64:ff9b:1::/48 (RFC 8215 local NAT64)
379
+ const isNat64WellKnown = bytes[0] === 0x00 &&
380
+ bytes[1] === 0x64 &&
381
+ bytes[2] === 0xff &&
382
+ bytes[3] === 0x9b &&
383
+ bytes[4] === 0 &&
384
+ bytes[5] === 0 &&
385
+ bytes[6] === 0 &&
386
+ bytes[7] === 0 &&
387
+ bytes[8] === 0 &&
388
+ bytes[9] === 0 &&
389
+ bytes[10] === 0 &&
390
+ bytes[11] === 0;
391
+ if (isNat64WellKnown)
392
+ return classifyIpv4(readUint32(bytes, 12));
393
+ if (bytes[0] === 0x00 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b && bytes[4] === 0 && bytes[5] === 1) {
394
+ return classifyIpv4(readUint32(bytes, 12));
395
+ }
396
+ // 2002::/16 (6to4 embedding IPv4 in bytes 2..5)
397
+ if (bytes[0] === 0x20 && bytes[1] === 0x02)
398
+ return classifyIpv4(readUint32(bytes, 2));
399
+ // fe80::/10 (link-local)
400
+ if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80)
401
+ return "metadata";
402
+ // fd00:ec2::254 (AWS IPv6 IMDS)
403
+ const isAwsV6Imds = bytes[0] === 0xfd &&
404
+ bytes[1] === 0x00 &&
405
+ bytes[2] === 0x0e &&
406
+ bytes[3] === 0xc2 &&
407
+ bytes[4] === 0 &&
408
+ bytes[5] === 0 &&
409
+ bytes[6] === 0 &&
410
+ bytes[7] === 0 &&
411
+ bytes[8] === 0 &&
412
+ bytes[9] === 0 &&
413
+ bytes[10] === 0 &&
414
+ bytes[11] === 0 &&
415
+ bytes[12] === 0 &&
416
+ bytes[13] === 0 &&
417
+ bytes[14] === 0x02 &&
418
+ bytes[15] === 0x54;
419
+ if (isAwsV6Imds)
420
+ return "metadata";
421
+ // ff00::/8 (multicast)
422
+ if (bytes[0] === 0xff)
423
+ return "reserved";
424
+ // 100::/64 (RFC 6666 discard-only)
425
+ if (bytes[0] === 0x01 &&
426
+ bytes[1] === 0x00 &&
427
+ bytes[2] === 0 &&
428
+ bytes[3] === 0 &&
429
+ bytes[4] === 0 &&
430
+ bytes[5] === 0 &&
431
+ bytes[6] === 0 &&
432
+ bytes[7] === 0) {
433
+ return "reserved";
434
+ }
435
+ // fc00::/7 (Unique Local Address)
436
+ if ((bytes[0] & 0xfe) === 0xfc)
437
+ return "private";
438
+ return "public";
439
+ }
440
+ function readUint32(bytes, offset) {
441
+ return ((((bytes[offset] << 24) >>> 0) |
442
+ ((bytes[offset + 1] << 16) >>> 0) |
443
+ ((bytes[offset + 2] << 8) >>> 0) |
444
+ (bytes[offset + 3] >>> 0)) >>>
445
+ 0);
446
+ }
@@ -0,0 +1,75 @@
1
+ export * as BrowserFiles from "./files.js";
2
+ import { Browser } from "./rpc.js";
3
+ import { Tool } from "@radheim/schema/tool";
4
+ import { Effect } from "effect";
5
+ import type { Context } from "@radheim/plugin/effect/plugin";
6
+ export declare const authorize: (ctx: Pick<Context, "location" | "permission">, tool: Tool.Context, action: "edit" | "read", paths: readonly string[]) => Effect.Effect<undefined, Tool.Error, never>;
7
+ export declare function uploadPath(directory: string, input: string): string;
8
+ export declare const physical: (paths: readonly string[]) => Effect.Effect<string[], Tool.Error, never>;
9
+ export declare const read: (paths: readonly string[], names: readonly string[]) => Effect.Effect<Browser.File[], Tool.Error, never>;
10
+ /**
11
+ * The workspace entry a path or `file:` address names, decided from its text alone, with no look at the disk: the
12
+ * address and its percent-encoding decoded, a line suffix dropped, `.` and `..` resolved. `entry` is the result
13
+ * relative to the workspace, with forward slashes. Undefined for an address that is no file. `unresolved` for text
14
+ * that is no path, `outside` for one that leaves the workspace, `invalid` for a name the desktop cannot open.
15
+ */
16
+ export declare function entry(path: string, directory: string): {
17
+ unresolved: true;
18
+ outside?: undefined;
19
+ invalid?: undefined;
20
+ absolute?: undefined;
21
+ entry?: undefined;
22
+ } | {
23
+ unresolved?: undefined;
24
+ absolute: string;
25
+ outside: true;
26
+ invalid?: undefined;
27
+ entry?: undefined;
28
+ } | {
29
+ unresolved?: undefined;
30
+ outside?: undefined;
31
+ absolute: string;
32
+ invalid: true;
33
+ entry?: undefined;
34
+ } | {
35
+ unresolved?: undefined;
36
+ outside?: undefined;
37
+ invalid?: undefined;
38
+ absolute: string;
39
+ entry: string;
40
+ } | undefined;
41
+ /** Resolve and authorize the exact entry. A missing agent path must not trigger a search of unapproved directories. */
42
+ export declare const locate: (path: string, directory: string, approve: (absolute: string) => Effect.Effect<void, Tool.Error>) => Effect.Effect<{
43
+ absolute: string;
44
+ found: boolean;
45
+ directory: boolean;
46
+ } | {
47
+ absolute: string;
48
+ found: boolean;
49
+ directory: boolean;
50
+ outside: boolean;
51
+ } | {
52
+ absolute: string;
53
+ found: boolean;
54
+ directory: boolean;
55
+ invalid: boolean;
56
+ } | undefined, Tool.Error, never>;
57
+ /** Whether a preview path is an address with a scheme, such as https:, skill: or file:. A drive letter is no scheme. */
58
+ export declare function address(path: string): boolean;
59
+ /** A session owns one private cache tree. Neither file names nor session IDs are interpreted as directory paths. */
60
+ export declare function exportRoot(sessionID: string): string;
61
+ export declare function exportPaths(files: readonly Browser.File[], root: string): {
62
+ directory: string;
63
+ paths: string[];
64
+ };
65
+ export declare const save: (files: readonly Browser.File[], plan: {
66
+ directory: string;
67
+ paths: string[];
68
+ }) => Effect.Effect<{
69
+ id: string & import("effect/Brand").Brand<"Browser.FileID">;
70
+ name: string;
71
+ mime: string;
72
+ bytes: number;
73
+ path: string;
74
+ }[], Tool.Error, never>;
75
+ export declare function captureName(name: string): string;