@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,432 @@
1
+ export * as BrowserConnection from "./connection.js";
2
+ import { hostname } from "node:os";
3
+ import { rm } from "node:fs/promises";
4
+ import { BrowserFiles } from "./files.js";
5
+ import { Location } from "@radheim/schema/location";
6
+ import { Session } from "@radheim/schema/session";
7
+ import { Tool } from "@radheim/schema/tool";
8
+ import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect";
9
+ import { EgressPolicy } from "./egress-policy.js";
10
+ import { BrowserMachine } from "./machine.js";
11
+ import { Browser } from "./rpc.js";
12
+ import { StreamMux } from "./stream-mux.js";
13
+ import { BrowserTunnel } from "./tunnel.js";
14
+ import { BrowserTunnelHost } from "./tunnel-host.js";
15
+ /** The server process that wrote a session's grant, stored as `grant:<sessionID>` until its revoke succeeds. */
16
+ const GrantOwner = Schema.Struct({ host: Schema.String, pid: Schema.Number, location: Location.Ref });
17
+ const GRANT_PREFIX = "grant:";
18
+ /**
19
+ * A crash or SIGKILL skips the revokes, so a session keeps its grant with no attachment behind it. Revokes the grants
20
+ * this location's servers recorded, except those of a process that still runs: several servers can share one
21
+ * database, and another one's attachment may be live. Runs before the RPC registers, so no attach here can race it.
22
+ */
23
+ export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleGrants")(function* (ctx) {
24
+ const revoke = (entry) => {
25
+ const owner = Schema.decodeUnknownOption(GrantOwner)(entry.value);
26
+ if (Option.isNone(owner) ||
27
+ owner.value.location.directory !== ctx.location.directory ||
28
+ owner.value.location.workspaceID !== ctx.location.workspaceID ||
29
+ running(owner.value))
30
+ return Effect.void;
31
+ return writePermissions(ctx, Session.ID.make(entry.key.slice(GRANT_PREFIX.length)), false).pipe(Effect.ignore, Effect.andThen(ctx.storage.remove(entry.key)));
32
+ };
33
+ const page = (after) => ctx.storage
34
+ .scan({ prefix: GRANT_PREFIX, after })
35
+ .pipe(Effect.flatMap((result) => Effect.forEach(result.entries, revoke, { discard: true }).pipe(Effect.andThen(result.next === undefined ? Effect.void : page(result.next)))));
36
+ yield* page();
37
+ });
38
+ export const make = Effect.fn("BrowserConnection.make")(function* (ctx) {
39
+ const tunnelHost = yield* BrowserTunnelHost.Reference;
40
+ const locationRef = Location.Ref.make({
41
+ directory: ctx.location.directory,
42
+ ...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }),
43
+ });
44
+ // Each agent's rules from config and its definition, which an attachment's grant must not override.
45
+ const configured = new Map();
46
+ // Appended after config, so every agent hides the browser tools and their skill until an attachment allows them.
47
+ yield* ctx.agent.transform((editor) => {
48
+ configured.clear();
49
+ editor.list().forEach((agent) => {
50
+ configured.set(agent.id, [...agent.permissions]);
51
+ agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" })));
52
+ });
53
+ });
54
+ const rulesFor = (session, agent) => [
55
+ // Core denies everything to an agent it cannot resolve, such as a disabled or removed one; so does this.
56
+ ...(configured.get(agent ?? session.agent ?? "") ?? [{ action: "*", resource: "*", effect: "deny" }]),
57
+ ...(session.permissions ?? []).filter((rule) => !BrowserMachine.isGrant(rule)),
58
+ ];
59
+ // The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call to
60
+ // allow, and lists the browser tools and their skill to every agent of an attached session, one whose own rules
61
+ // deny the browser included. This hook alone refuses such an agent's calls, by the rules from config, the agent's
62
+ // definition and the session itself: a deny refuses the call. An ask rule is not applied in an attached session, as
63
+ // on dev, and no matching rule leaves the call allowed.
64
+ yield* ctx.permission.hook("evaluate", (event) => {
65
+ if (event.action !== "browser" || event.effect === "deny")
66
+ return Effect.void;
67
+ return ctx.session.get({ sessionID: event.sessionID }).pipe(Effect.map((session) => {
68
+ const denied = denial(rulesFor(session, event.agent), event.resources);
69
+ if (denied) {
70
+ event.effect = "deny";
71
+ event.message = denied;
72
+ }
73
+ }),
74
+ // Without the rules, the grant must not decide alone.
75
+ Effect.catchCause((cause) => Effect.logWarning("Browser permission evaluation failed", cause).pipe(Effect.andThen(Effect.sync(() => {
76
+ event.effect = "deny";
77
+ event.message = "Browser permissions could not be read; no action ran.";
78
+ })))));
79
+ });
80
+ // Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes.
81
+ const work = yield* Scope.make();
82
+ yield* Effect.addFinalizer((exit) => Scope.close(work, exit));
83
+ const machine = { state: BrowserMachine.createConnectionState() };
84
+ const attachments = new Map();
85
+ const requests = new Map();
86
+ const drained = Deferred.makeUnsafe();
87
+ // One event at a time, effects included, so controls reach the bus in transition order: `attached` before any
88
+ // `command` of that attachment.
89
+ const lock = Semaphore.makeUnsafe(1);
90
+ const step = (event) => Effect.suspend(() => {
91
+ const next = BrowserMachine.transitionConnection(machine.state, event);
92
+ machine.state = next.state;
93
+ return Effect.forEach(next.effects, (effect) => perform(effect).pipe(Effect.catchCause((cause) => Effect.logWarning("Browser effect failed", cause))), { discard: true });
94
+ });
95
+ const dispatch = (event) => lock.withPermit(step(event));
96
+ const perform = (effect) => {
97
+ if (effect.type === "sync-permissions")
98
+ return Effect.asVoid(Effect.forkIn(syncPermissions(effect), work));
99
+ if (effect.type === "close-attachment")
100
+ return Effect.gen(function* () {
101
+ const attachment = attachments.get(effect.attempt);
102
+ if (!attachment)
103
+ return;
104
+ attachment.disposed = true;
105
+ attachments.delete(effect.attempt);
106
+ if (tunnelHost && attachment.streamEnabled) {
107
+ yield* tunnelHost
108
+ .revokeAttachment(attachment.sessionID, attachment.connectionID, attachment.attempt)
109
+ .pipe(Effect.ignore);
110
+ }
111
+ const closeCode = effect.outcome === "replaced"
112
+ ? BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED
113
+ : BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED;
114
+ const closeReason = effect.outcome === "replaced" ? "replaced" : "closed";
115
+ attachment.stream?.close(closeCode, closeReason);
116
+ attachment.stream = undefined;
117
+ attachment.tunnels.dispose();
118
+ yield* Deferred.done(attachment.closed, effect.outcome === "unavailable" ? Exit.fail(effect.outcome) : Exit.succeed(effect.outcome)).pipe(Effect.asVoid);
119
+ });
120
+ if (effect.type === "emit-control") {
121
+ const control = effect.control;
122
+ if (control.type === "attached") {
123
+ const live = Array.from(attachments.values()).find((candidate) => !candidate.disposed && candidate.connectionID === control.connectionID);
124
+ return rpc.events.emit("control", live?.streamEnabled ? { ...control, capabilities: [BrowserTunnelHost.STREAM_CAPABILITY] } : control);
125
+ }
126
+ return rpc.events.emit("control", control);
127
+ }
128
+ if (effect.type === "dispatch-command")
129
+ return (rpc.events
130
+ .emit("control", { type: "command", connectionID: effect.connectionID, requestID: effect.requestID })
131
+ // Already inside the lock, so the failure steps directly.
132
+ .pipe(Effect.catch((error) => step({ ...effect, type: "request.dispatch-failed", error }))));
133
+ if (effect.type === "settle-request")
134
+ return Effect.suspend(() => {
135
+ const result = requests.get(effect.requestID);
136
+ if (!result)
137
+ return Effect.void;
138
+ requests.delete(effect.requestID);
139
+ return Deferred.done(result, effect.settlement.ok ? Exit.succeed(effect.settlement.result) : Exit.fail(effect.settlement.error)).pipe(Effect.asVoid);
140
+ });
141
+ if (effect.type === "warn")
142
+ return Effect.logWarning(effect.message, effect.error);
143
+ return Deferred.done(drained, Exit.void).pipe(Effect.asVoid);
144
+ };
145
+ const owner = {
146
+ host: hostname(),
147
+ pid: process.pid,
148
+ location: {
149
+ directory: ctx.location.directory,
150
+ ...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }),
151
+ },
152
+ };
153
+ const syncPermissions = (effect) =>
154
+ // The owner is recorded before the grant and forgotten after the revoke, so a stored grant always has one.
155
+ (effect.allow
156
+ ? ctx.storage
157
+ .set(GRANT_PREFIX + effect.sessionID, owner)
158
+ .pipe(Effect.andThen(writePermissions(ctx, effect.sessionID, true)))
159
+ : writePermissions(ctx, effect.sessionID, false).pipe(Effect.andThen(ctx.storage.remove(GRANT_PREFIX + effect.sessionID)))).pipe(Effect.timeoutOption(Duration.millis(BrowserMachine.PERMISSION_SYNC_TIMEOUT_MS)), Effect.matchCauseEffect({
160
+ onSuccess: (done) => dispatch({
161
+ type: Option.isSome(done) ? "permissions.synced" : "permissions.timed-out",
162
+ sessionID: effect.sessionID,
163
+ attempt: effect.attempt,
164
+ }),
165
+ onFailure: (cause) => dispatch({
166
+ type: "permissions.failed",
167
+ sessionID: effect.sessionID,
168
+ attempt: effect.attempt,
169
+ error: Cause.squash(cause),
170
+ }),
171
+ }));
172
+ const liveAttachment = (input) => {
173
+ const attempt = BrowserMachine.selectAttachment(machine.state, input.sessionID, input.connectionID);
174
+ const attachment = attempt === undefined ? undefined : attachments.get(attempt);
175
+ return attachment && !attachment.disposed
176
+ ? Effect.succeed(attachment)
177
+ : Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed."));
178
+ };
179
+ const tunnels = (input) => liveAttachment(input).pipe(Effect.map((attachment) => attachment.tunnels));
180
+ yield* reconcileStaleGrants(ctx);
181
+ const rpc = yield* ctx.rpc
182
+ .register(Browser.Definition, {
183
+ attach: (input, call) => Effect.gen(function* () {
184
+ const session = yield* ctx.session
185
+ .get({ sessionID: input.sessionID })
186
+ .pipe(Effect.mapError(() => call.error("unavailable", "Session not found.", {})));
187
+ if (session.location.directory !== ctx.location.directory)
188
+ return yield* Effect.fail(call.error("unavailable", "Session belongs to another location.", {}));
189
+ // Select experimental streaming + egress policy once at attachment start so disabled releases
190
+ // preserve pre-PR legacy tunnel behavior and active attachments stay coherent across RPCs.
191
+ const streamEnabled = tunnelHost
192
+ ? yield* tunnelHost.enabled.pipe(Effect.orElseSucceed(() => false))
193
+ : false;
194
+ return yield* Effect.acquireUseRelease(lock.withPermit(Effect.suspend(() => {
195
+ if (BrowserMachine.isConnectionDisposed(machine.state))
196
+ return Effect.fail(call.error("unavailable", "Browser is unavailable.", {}));
197
+ const attempt = BrowserMachine.selectNextAttempt(machine.state);
198
+ const policy = streamEnabled && tunnelHost
199
+ ? EgressPolicy.makePolicy({ reservedLocalPorts: tunnelHost.reservedLocalPorts })
200
+ : undefined;
201
+ const attachment = {
202
+ sessionID: input.sessionID,
203
+ connectionID: input.connectionID,
204
+ attempt,
205
+ closed: Deferred.makeUnsafe(),
206
+ streamEnabled,
207
+ policy,
208
+ tunnels: BrowserTunnel.make(policy),
209
+ streamAttached: false,
210
+ disposed: false,
211
+ };
212
+ attachments.set(attempt, attachment);
213
+ return step({
214
+ type: "attach.started",
215
+ sessionID: input.sessionID,
216
+ attempt,
217
+ connectionID: input.connectionID,
218
+ }).pipe(Effect.as({ attempt, attachment }));
219
+ })), (attached) => Deferred.await(attached.attachment.closed).pipe(Effect.mapError(() => call.error("unavailable", "Browser permissions could not be granted.", {}))), (attached) => Effect.suspend(() => {
220
+ // Once an upgraded binary WebSocket owns this attachment's liveness, a reverse-proxy idle
221
+ // timeout on the silent HTTP attach request must not tear down the live attachment.
222
+ if (attached.attachment.streamAttached && !attached.attachment.disposed && attached.attachment.stream) {
223
+ return Effect.void;
224
+ }
225
+ return dispatch({ type: "attach.closed", sessionID: input.sessionID, attempt: attached.attempt });
226
+ }));
227
+ }),
228
+ state: (input, call) => Effect.suspend(() => BrowserMachine.isAttachedConnection(machine.state, input.sessionID, input.connectionID)
229
+ ? dispatch({
230
+ type: "state.updated",
231
+ sessionID: input.sessionID,
232
+ connectionID: input.connectionID,
233
+ browserState: input.state,
234
+ })
235
+ : Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))),
236
+ command: (input, call) => Effect.suspend(() => {
237
+ const command = BrowserMachine.selectPendingCommand(machine.state, input.sessionID, input.connectionID, input.requestID);
238
+ return command
239
+ ? Effect.succeed(command)
240
+ : Effect.fail(call.error("unavailable", "Browser request is no longer available.", {}));
241
+ }),
242
+ result: (input, call) => Effect.suspend(() => BrowserMachine.isAttachedConnection(machine.state, input.sessionID, input.connectionID)
243
+ ? dispatch({ type: "request.settled", ...input })
244
+ : Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))),
245
+ "tunnel.ticket": (input, call) => Effect.gen(function* () {
246
+ const attachment = yield* liveAttachment(input).pipe(Effect.mapError((error) => call.error("unavailable", error.message, {})));
247
+ const policy = attachment.policy;
248
+ if (!tunnelHost || !attachment.streamEnabled || !policy) {
249
+ return yield* Effect.fail(call.error("unavailable", "Browser stream tunnel is disabled.", {}));
250
+ }
251
+ const issued = yield* tunnelHost
252
+ .issueTicket({
253
+ location: locationRef,
254
+ sessionID: input.sessionID,
255
+ connectionID: input.connectionID,
256
+ generation: attachment.attempt,
257
+ protocol: input.protocol,
258
+ onUpgrade: (socket) => Effect.gen(function* () {
259
+ if (attachment.disposed || attachments.get(attachment.attempt) !== attachment) {
260
+ socket.close(BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED, "attachment closed");
261
+ return;
262
+ }
263
+ const previous = attachment.stream;
264
+ const mux = StreamMux.createServerMux(socket, { policy });
265
+ attachment.stream = mux;
266
+ attachment.streamAttached = true;
267
+ if (previous)
268
+ previous.close(BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED, "superseded");
269
+ yield* Effect.promise(() => mux.closed).pipe(Effect.ensuring(Effect.suspend(() => {
270
+ if (attachment.stream === mux)
271
+ attachment.stream = undefined;
272
+ // If no replacement stream took over and the attachment wasn't already closed/replaced,
273
+ // closing the liveness-owning WebSocket detaches the attachment and revokes its sockets.
274
+ if (!attachment.disposed && attachment.stream === undefined) {
275
+ return dispatch({
276
+ type: "attach.closed",
277
+ sessionID: attachment.sessionID,
278
+ attempt: attachment.attempt,
279
+ });
280
+ }
281
+ return Effect.void;
282
+ })));
283
+ }),
284
+ })
285
+ .pipe(Effect.mapError((error) => call.error("unavailable", String(error), {})));
286
+ return {
287
+ ticket: issued.ticket,
288
+ expiresIn: issued.expiresIn,
289
+ protocol: 1,
290
+ path: BrowserTunnelHost.BROWSER_TUNNEL_PATH,
291
+ };
292
+ }),
293
+ "tunnel.grant": (input, call) => liveAttachment(input).pipe(Effect.flatMap((attachment) => {
294
+ const policy = attachment.policy;
295
+ if (!attachment.streamEnabled || !policy) {
296
+ return Effect.fail(new Error("Browser stream tunnel is disabled."));
297
+ }
298
+ return Effect.try({
299
+ try: () => policy.grant(input.target.host, input.target.port, input.ports ?? []),
300
+ catch: (error) => (error instanceof Error ? error : new Error(String(error))),
301
+ });
302
+ }), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
303
+ "tunnel.open": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.open(input.target)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
304
+ "tunnel.read": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.read(input.tunnelID)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
305
+ "tunnel.write": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.write(input.tunnelID, input.data, input.end)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
306
+ "tunnel.close": (input, call) => tunnels(input).pipe(Effect.flatMap((network) => network.close(input.tunnelID)), Effect.mapError((error) => call.error("unavailable", error.message, {}))),
307
+ })
308
+ .pipe(Effect.orDie);
309
+ yield* ctx.event.subscribe({ types: ["session.deleted", "session.moved"] }).pipe(Stream.runForEach((event) => dispatch({
310
+ type: event.type === "session.deleted" ? "session.deleted" : "session.moved",
311
+ sessionID: event.data.sessionID,
312
+ }).pipe(
313
+ // A deleted session's grant went with it, and no revoke will forget its owner record.
314
+ Effect.andThen(event.type === "session.deleted"
315
+ ? Effect.all([
316
+ ctx.storage.remove(GRANT_PREFIX + event.data.sessionID),
317
+ Effect.tryPromise(() => rm(BrowserFiles.exportRoot(event.data.sessionID), { recursive: true, force: true })).pipe(Effect.tapError((error) => Effect.logWarning("Could not remove deleted session's browser exports", error))),
318
+ ]).pipe(Effect.ignore)
319
+ : Effect.void))), Effect.forkScoped({ startImmediately: true }));
320
+ // A child copies its parent's permissions, browser grant included, but not the attachment. The grant is revoked while
321
+ // the child's prompt is admitted, so no step of the child lists browser tools. The lock keeps an attachment of the
322
+ // child's own from starting meanwhile; one that already exists keeps its grant.
323
+ yield* ctx.session.hook("prompt", (event) => ctx.session.get({ sessionID: event.sessionID }).pipe(Effect.flatMap((session) => session.parentID === undefined || !session.permissions?.some(BrowserMachine.isGrant)
324
+ ? Effect.void
325
+ : lock.withPermit(Effect.suspend(() => BrowserMachine.hasSession(machine.state, session.id)
326
+ ? Effect.void
327
+ : writePermissions(ctx, session.id, false)))), Effect.catchCause((cause) => Effect.logWarning("Browser permission revoke failed", cause))));
328
+ // Registered last, so it runs first: attachments close and revokes drain while the RPC and `work` are still open.
329
+ yield* Effect.addFinalizer(() => dispatch({ type: "disposed" }).pipe(Effect.andThen(Deferred.await(drained))));
330
+ const request = Effect.fn("BrowserConnection.request")(function* (sessionID, connectionID, action, tab, files, inspection) {
331
+ const requestID = crypto.randomUUID();
332
+ const target = { sessionID, connectionID, requestID };
333
+ const result = yield* Deferred.make();
334
+ const command = {
335
+ action: (action.type === "files.upload" || action.type === "files.drop") && !inspection.inspect
336
+ ? { ...action, paths: files.map((file) => file.name) }
337
+ : action,
338
+ ...(tab ? { generation: tab.generation } : {}),
339
+ files,
340
+ ...inspection,
341
+ };
342
+ // Once started, the request always reaches the machine's exit: a settlement, a timeout or a cancel.
343
+ return yield* Effect.uninterruptibleMask((restore) => Effect.sync(() => requests.set(requestID, result)).pipe(Effect.andThen(dispatch({ type: "request.started", ...target, command })), Effect.andThen(restore(Deferred.await(result).pipe(Effect.timeoutOrElse({
344
+ duration: Duration.millis(BrowserMachine.REQUEST_TIMEOUT_MS),
345
+ orElse: () => dispatch({ type: "request.timed-out", ...target }).pipe(Effect.andThen(Deferred.await(result))),
346
+ })))), Effect.onInterrupt(() => dispatch({ type: "request.cancelled", ...target })), Effect.ensuring(Effect.sync(() => requests.delete(requestID)))));
347
+ });
348
+ return {
349
+ /**
350
+ * Refuses a call that config, the agent's definition or the session's own rules deny. It reads rules only and never
351
+ * prompts, so it runs before the tool reads a file, looks up a tab or says whether a desktop is attached: a denied
352
+ * call reveals nothing but the denial. Without a desktop the session has no grant, and core would deny the call
353
+ * with its own message before any hook ran.
354
+ */
355
+ refuse: Effect.fn("BrowserConnection.refuse")(function* (tool, operations) {
356
+ const session = yield* ctx.session
357
+ .get({ sessionID: tool.sessionID })
358
+ .pipe(Effect.mapError((error) => new Tool.Error({ message: `Session not found: ${tool.sessionID}`, error })));
359
+ const denied = denial(rulesFor(session, tool.agent), operations);
360
+ if (denied)
361
+ return yield* new Tool.Error({ message: denied });
362
+ }),
363
+ /**
364
+ * The permission check for one call, with the operation as its resource. Its `permission.evaluate` hooks decide it:
365
+ * this plugin's (configured denies win over the grant) and others such as `tool.use` policies.
366
+ */
367
+ authorize: Effect.fn("BrowserConnection.authorize")(function* (tool, action, operations) {
368
+ const connection = BrowserMachine.selectConnection(machine.state, tool.sessionID);
369
+ if (!connection.ok)
370
+ return { connected: false, message: connection.error.message };
371
+ yield* ctx.permission.assert({
372
+ sessionID: tool.sessionID,
373
+ agent: tool.agent,
374
+ action: "browser",
375
+ // Keep exact operation resources for existing permission rules and tool.use policies. A call that stands for
376
+ // more than one operation names each, and a deny of any of them refuses it.
377
+ resources: operations ?? [action.type],
378
+ source: { type: "tool", messageID: tool.messageID, id: tool.id },
379
+ });
380
+ return { connected: true };
381
+ }),
382
+ target: Effect.fn("BrowserConnection.target")(function* (sessionID, action) {
383
+ const selected = BrowserMachine.selectTarget(machine.state, sessionID, action);
384
+ if (!selected.ok)
385
+ return yield* selected.error;
386
+ // Requests go to the attachment selected here. One that closes first, even while file IO waits, runs nothing.
387
+ return {
388
+ tab: selected.tab,
389
+ inspect: () => request(sessionID, selected.connectionID, action, selected.tab, [], { inspect: true }).pipe(Effect.flatMap((result) => Schema.decodeUnknownEffect(Browser.Target)(result.value)), Effect.mapError((error) => new Tool.Error({
390
+ message: error instanceof Tool.Error
391
+ ? error.message
392
+ : "Browser returned invalid target metadata. Check desktop/plugin versions; no action was authorized.",
393
+ error,
394
+ }))),
395
+ request: (files, target) => request(sessionID, selected.connectionID, action, selected.tab, files, { target }),
396
+ };
397
+ }),
398
+ };
399
+ });
400
+ /** The refusal for the first operation the rules deny, or undefined when they deny none. */
401
+ function denial(rules, operations) {
402
+ const denied = operations
403
+ .map((operation) => ({ operation, rule: BrowserMachine.selectBrowserRule(rules, operation) }))
404
+ .find((item) => item.rule?.effect === "deny");
405
+ if (!denied)
406
+ return undefined;
407
+ return denied.rule?.resource === "*"
408
+ ? "[browser.denied] Browser tools are denied for this agent by configuration; no action ran. Do not retry browser tools."
409
+ : denied.operation === "preview"
410
+ ? // No tool has this name any more: it is the permission that covers showing a workspace file.
411
+ "[browser.denied] Showing a workspace file in the browser (permission browser.preview) is denied for this agent by configuration; no action ran. Do not retry it."
412
+ : `[browser.denied] browser.${denied.operation} is denied for this agent by configuration; no action ran. Do not retry it.`;
413
+ }
414
+ function writePermissions(ctx, sessionID, allow) {
415
+ return ctx.session.get({ sessionID }).pipe(Effect.flatMap((session) => {
416
+ const permissions = BrowserMachine.reconcileBrowserPermissions(session.permissions, allow);
417
+ return permissions ? ctx.session.update({ sessionID, permissions }) : Effect.void;
418
+ }));
419
+ }
420
+ // A process on another host, such as another container on a shared volume, cannot be checked; its grants count as live.
421
+ // A reused process ID also counts as live, which only leaves a stale grant in place.
422
+ function running(owner) {
423
+ if (owner.host !== hostname())
424
+ return true;
425
+ try {
426
+ process.kill(owner.pid, 0);
427
+ return true;
428
+ }
429
+ catch (error) {
430
+ return error instanceof Error && "code" in error && error.code === "EPERM";
431
+ }
432
+ }
@@ -0,0 +1,65 @@
1
+ export * as EgressPolicy from "./egress-policy.js";
2
+ import { type Socket } from "node:net";
3
+ import type { Browser } from "./rpc.js";
4
+ export type AddressClass = "public" | "loopback" | "private" | "metadata" | "reserved";
5
+ export type ResolvedAddress = {
6
+ readonly address: string;
7
+ readonly family: 4 | 6;
8
+ };
9
+ export type Resolver = (host: string) => Promise<readonly ResolvedAddress[]>;
10
+ export type PolicyDecision = {
11
+ readonly allowed: true;
12
+ readonly addressClass: AddressClass;
13
+ } | {
14
+ readonly allowed: false;
15
+ readonly reason: string;
16
+ readonly addressClass: AddressClass;
17
+ };
18
+ export declare class EgressDeniedError extends Error {
19
+ readonly code: "POLICY_DENIED";
20
+ constructor(message: string);
21
+ }
22
+ /**
23
+ * Non-HTTP infrastructure and management ports refused on loopback and private targets so a loaded
24
+ * page cannot reach local SSH, mail, SMB, Docker, or Kubernetes control planes.
25
+ */
26
+ export declare const BLOCKED_MANAGEMENT_PORTS: ReadonlySet<number>;
27
+ export interface AttachmentPolicyOptions {
28
+ /** Server-owned local ports (such as the OpenCode HTTP API itself) that page traffic must never reach. */
29
+ readonly reservedLocalPorts?: () => ReadonlySet<number>;
30
+ /** Explicit server policy permitting non-management private/RFC1918/ULA LAN targets. Default false. */
31
+ readonly allowPrivateLan?: boolean;
32
+ /** Custom DNS resolver (tests). Defaults to Node's `dns.lookup(host, { all: true, verbatim: true })`. */
33
+ readonly resolve?: Resolver;
34
+ }
35
+ export type AttachmentPolicy = ReturnType<typeof makePolicy>;
36
+ export declare function readAllowPrivateLanEnv(env?: Readonly<Record<string, string | undefined>>): boolean;
37
+ export declare function makePolicy(options?: AttachmentPolicyOptions): {
38
+ /**
39
+ * Grants one attachment access to an explicit private preview host/port (and optional HMR ports).
40
+ * Refuses reserved metadata hostnames/IPs and management or server-owned ports.
41
+ */
42
+ grant(host: string, port: number, extraPorts?: readonly number[]): void;
43
+ evaluateAddress(host: string, port: number, address: string): PolicyDecision;
44
+ /**
45
+ * Resolves `target.host` once on the server, validates EVERY resolved address against policy,
46
+ * and returns the complete verified list so the socket can try another address without resolving again.
47
+ */
48
+ resolveTarget(target: Browser.TunnelTarget): Promise<readonly ResolvedAddress[]>;
49
+ };
50
+ /**
51
+ * Connects only to verified IPs. The socket selects a reachable address when a host has several.
52
+ */
53
+ export declare function resolveAndConnect(target: Browser.TunnelTarget, policy: AttachmentPolicy, options?: {
54
+ readonly signal?: AbortSignal;
55
+ readonly timeoutMs?: number;
56
+ }): Promise<Socket>;
57
+ export declare function normalizeHost(host: string): string;
58
+ export declare function isMetadataHost(host: string): boolean;
59
+ export declare function isLoopbackHostName(host: string): boolean;
60
+ /**
61
+ * Parses IPv4 (including decimal, octal, hex, and shorthand forms via WHATWG URL canonicalization)
62
+ * and IPv6 literals (with optional zone IDs stripped for classification).
63
+ */
64
+ export declare function parseIpLiteral(host: string): ResolvedAddress | undefined;
65
+ export declare function classifyIp(input: string): AddressClass;