diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 7796a1c9070..712e07af994 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -2434,6 +2434,9 @@ export type ExperimentalPersistentPtyConnectTokenOperation = ( input: ExperimentalPersistentPtyConnectTokenInput, ) => Effect.Effect +export type ExperimentalBrowserTunnelOutput = boolean +export type ExperimentalBrowserTunnelOperation = () => Effect.Effect + export type ExperimentalAutomationCreateInput = { readonly sessionID?: Session.ID | undefined readonly directory?: string | undefined @@ -2688,6 +2691,7 @@ export interface ExperimentalApi { readonly remove: ExperimentalPersistentPtyRemoveOperation readonly connectToken: ExperimentalPersistentPtyConnectTokenOperation } + readonly browser: { readonly tunnel: ExperimentalBrowserTunnelOperation } readonly automation: { readonly create: ExperimentalAutomationCreateOperation readonly list: ExperimentalAutomationListOperation diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index c9423f87141..fc7feab1761 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -247,6 +247,7 @@ import type { ExperimentalPersistentPtyRemoveOutput, ExperimentalPersistentPtyConnectTokenInput, ExperimentalPersistentPtyConnectTokenOutput, + ExperimentalBrowserTunnelOutput, ExperimentalAutomationCreateInput, ExperimentalAutomationCreateOutput, ExperimentalAutomationListInput, @@ -1641,6 +1642,9 @@ const EndpointExperimentalPersistentPtyConnectToken = ), ) +const EndpointExperimentalBrowserTunnel = (raw: RawClient["server.experimental"]) => () => + preserveEffect()(raw["browser.tunnel"]({}).pipe(Effect.mapError(mapClientError))) + const EndpointExperimentalAutomationCreate = (raw: RawClient["server.experimental"]) => (input: ExperimentalAutomationCreateInput) => preserveEffect()( @@ -1908,6 +1912,7 @@ const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({ remove: EndpointExperimentalPersistentPtyRemove(raw), connectToken: EndpointExperimentalPersistentPtyConnectToken(raw), }, + browser: { tunnel: EndpointExperimentalBrowserTunnel(raw) }, automation: { create: EndpointExperimentalAutomationCreate(raw), list: EndpointExperimentalAutomationList(raw), diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 508cf62b336..40dfc7b889a 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -251,6 +251,7 @@ import type { ExperimentalMediaGetOutput, ExperimentalBlobGetInput, ExperimentalBlobGetOutput, + ExperimentalBrowserTunnelOutput, ExperimentalAutomationCreateInput, ExperimentalAutomationCreateOutput, ExperimentalAutomationListInput, @@ -1601,6 +1602,19 @@ export function make(options: ClientOptions) { requestOptions, ), }, + browser: { + tunnel: (requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/experimental/browser/tunnel`, + successStatus: 200, + declaredStatuses: [400, 401, 403], + empty: false, + }, + requestOptions, + ), + }, automation: { create: (input: ExperimentalAutomationCreateInput, requestOptions?: RequestOptions) => request<{ readonly data: ExperimentalAutomationCreateOutput }>( diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 2dff4964f1e..aa898d31beb 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2713,6 +2713,7 @@ export type ConfigEntry = mcp_skills?: boolean compaction_jobs?: boolean sqlite_fts?: boolean + browser_stream_tunnel?: boolean video_generate?: boolean | { model?: string | { providerID: string; model: string; variant?: string } } part_rows?: boolean image_generate?: boolean | { model?: string | { providerID: string; model: string; variant?: string } } @@ -4802,6 +4803,8 @@ export type ExperimentalBlobGetInput = { readonly id: string } export type ExperimentalBlobGetOutput = globalThis.Uint8Array +export type ExperimentalBrowserTunnelOutput = boolean + export type ExperimentalAutomationCreateInput = { readonly sessionID?: string | undefined readonly directory?: string | undefined diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 14ec51af860..2f85ce8111f 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -63,6 +63,7 @@ test("exposes every standard HTTP API group", () => { "persistentPty", "media", "blob", + "browser", "automation", "artifacts", "job", @@ -89,6 +90,7 @@ test("exposes every standard HTTP API group", () => { expect(Object.keys(client.experimental.integration.wellknown)).toEqual(["add"]) expect(Object.keys(client.experimental.file)).toEqual(["write", "watch", "unwatch"]) expect(Object.keys(client.experimental.media)).toEqual(["get"]) + expect(Object.keys(client.experimental.browser)).toEqual(["tunnel"]) expect(Object.keys(client.experimental.automation)).toEqual(["create", "list", "get", "pause", "resume", "delete"]) expect(client.experimental.persistentPty.read).toBeFunction() }) diff --git a/packages/core/src/experimental/browser-tunnel.ts b/packages/core/src/experimental/browser-tunnel.ts new file mode 100644 index 00000000000..450b697835e --- /dev/null +++ b/packages/core/src/experimental/browser-tunnel.ts @@ -0,0 +1,160 @@ +export * as BrowserTunnelGateway from "./browser-tunnel.js" + +import { randomBytes } from "node:crypto" +import { StreamWire } from "@opencode/plugin-browser/experimental/stream" +import { BrowserTunnelHost } from "@opencode/plugin-browser/experimental/tunnel-host" + +export type BinarySocket = BrowserTunnelHost.BinarySocket +export const MAX_WS_FRAME_BYTES = StreamWire.MAX_WS_FRAME_BYTES +import type { Location } from "@opencode/schema/location" +import type { Session } from "@opencode/schema/session" +import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { Clock, Context, Duration, Effect, Layer } from "effect" + +const DEFAULT_TTL = Duration.seconds(30) +const MAX_PENDING_TICKETS = 2_048 + +type TicketEntry = { + readonly binding: BrowserTunnelHost.TicketBinding + readonly attachmentKey: string + readonly expiresAt: number +} + +export interface ConsumeInput { + readonly ticket: string + readonly location: Location.Ref + readonly sessionID: Session.ID + readonly connectionID: string + readonly protocol: number +} + +export interface Interface { + readonly issueTicket: ( + binding: BrowserTunnelHost.TicketBinding, + ) => Effect.Effect + readonly consumeTicket: (input: ConsumeInput) => Effect.Effect + readonly revokeAttachment: (sessionID: Session.ID, connectionID: string, generation: number) => Effect.Effect + readonly addReservedLocalPort: (port: number) => Effect.Effect + readonly removeReservedLocalPort: (port: number) => Effect.Effect + readonly reservedLocalPorts: () => ReadonlySet + readonly hostForLocation: (enabled: Effect.Effect) => BrowserTunnelHost.Interface +} + +export class Service extends Context.Service()("@opencode/BrowserTunnelGateway") {} + +function attachmentKey(sessionID: Session.ID, connectionID: string, generation: number) { + return `${sessionID}\0${connectionID}\0${generation}` +} + +function sameLocation(a: Location.Ref, b: Location.Ref) { + return a.directory === b.directory && a.workspaceID === b.workspaceID +} + +export const make = (ttl: Duration.Input = DEFAULT_TTL) => + Effect.gen(function* () { + const ttlMs = Math.max(1_000, Duration.toMillis(Duration.fromInputUnsafe(ttl))) + const expiresIn = Math.max(1, Math.round(ttlMs / 1_000)) + const tickets = new Map() + const byAttachment = new Map>() + const reservedPorts = new Set() + + const removeTicket = (ticket: string) => { + const entry = tickets.get(ticket) + if (!entry) return undefined + tickets.delete(ticket) + const set = byAttachment.get(entry.attachmentKey) + if (set) { + set.delete(ticket) + if (set.size === 0) byAttachment.delete(entry.attachmentKey) + } + return entry + } + + const sweep = (now: number) => { + for (const [ticket, entry] of tickets) { + if (entry.expiresAt <= now) removeTicket(ticket) + } + } + + const issueTicket = Effect.fn("BrowserTunnelGateway.issueTicket")(function* ( + binding: BrowserTunnelHost.TicketBinding, + ) { + const now = yield* Clock.currentTimeMillis + sweep(now) + if (tickets.size >= MAX_PENDING_TICKETS) { + return yield* Effect.fail(new Error("Too many pending browser tunnel upgrade tickets.")) + } + const ticket = randomBytes(32).toString("base64url") + const key = attachmentKey(binding.sessionID, binding.connectionID, binding.generation) + tickets.set(ticket, { binding, attachmentKey: key, expiresAt: now + ttlMs }) + const set = byAttachment.get(key) ?? new Set() + set.add(ticket) + byAttachment.set(key, set) + return { + ticket, + expiresIn, + protocol: binding.protocol, + path: BrowserTunnelHost.BROWSER_TUNNEL_PATH, + } + }) + + const consumeTicket = Effect.fn("BrowserTunnelGateway.consumeTicket")(function* (input: ConsumeInput) { + const now = yield* Clock.currentTimeMillis + const entry = tickets.get(input.ticket) + if (!entry) return undefined + if (entry.expiresAt <= now) { + removeTicket(input.ticket) + return undefined + } + const binding = entry.binding + if ( + binding.sessionID !== input.sessionID || + binding.connectionID !== input.connectionID || + binding.protocol !== input.protocol || + !sameLocation(binding.location, input.location) + ) { + return undefined + } + // Atomic single-use removal: a ticket can never be replayed. + removeTicket(input.ticket) + return binding + }) + + const revokeAttachment = Effect.fn("BrowserTunnelGateway.revokeAttachment")(function* ( + sessionID: Session.ID, + connectionID: string, + generation: number, + ) { + const key = attachmentKey(sessionID, connectionID, generation) + const set = byAttachment.get(key) + if (!set) return + for (const ticket of Array.from(set)) removeTicket(ticket) + }) + + const gateway: Interface = { + issueTicket, + consumeTicket, + revokeAttachment, + addReservedLocalPort: (port) => + Effect.sync(() => { + if (Number.isInteger(port) && port >= 1 && port <= 65_535) reservedPorts.add(port) + }), + removeReservedLocalPort: (port) => + Effect.sync(() => { + reservedPorts.delete(port) + }), + reservedLocalPorts: () => reservedPorts, + hostForLocation: (enabled) => ({ + enabled, + reservedLocalPorts: () => reservedPorts, + issueTicket: (binding) => issueTicket(binding).pipe(Effect.orDie), + revokeAttachment, + }), + } + + return Service.of(gateway) + }) + +const layer = Layer.effect(Service, make()) + +export const node = makeGlobalNode({ service: Service, layer, deps: [] }) diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index e2dace082b7..901ed2e95b4 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -112,6 +112,8 @@ import { WellKnown } from "../wellknown.js" import { WriteTool } from "../tool/plugin/write.js" import { AgentPlugin } from "./agent.js" import BrowserPlugin from "@opencode/plugin-browser" +import { BrowserTunnelHost } from "@opencode/plugin-browser/experimental/tunnel-host" +import { BrowserTunnelGateway } from "../experimental/browser-tunnel.js" import { CommandPlugin } from "./command.js" import { IdentityPlugin } from "./identity.js" import { ForkNoticePlugin } from "./fork-notice.js" @@ -141,6 +143,7 @@ const services = [ FetchHttpClient.Fetch, Artifact.Service, AppProcess.Service, + BrowserTunnelGateway.Service, BlobStore.Service, CodeModeAgents.Service, Provider.Service, @@ -206,6 +209,7 @@ export const requirements = LayerNode.group([ App.node, Artifact.node, AppProcess.node, + BrowserTunnelGateway.node, BlobStore.node, CodeModeAgents.node, Provider.node, @@ -348,12 +352,20 @@ export const guarded: ReadonlySet = new Set([OpencodePlugin.id, ConfigPo export const list = Effect.fn("PluginInternal.list")(function* () { // Capture only services; activation supplies the child Scope and batching context. const context = Context.pick(...services)(yield* Effect.context()) + const gateway = Context.get(context, BrowserTunnelGateway.Service) + const flags = Context.get(context, Flag.Service) + const browserContext = Context.add( + context, + BrowserTunnelHost.Reference, + gateway.hostForLocation(flags.enabled("browser_stream_tunnel")), + ) const resolve = (plugins: readonly InternalPlugin[]) => plugins.map( (plugin) => ({ id: plugin.id, - effect: (host) => plugin.effect(host).pipe(Effect.provide(context)), + effect: (host) => + plugin.effect(host).pipe(Effect.provide(plugin.id === BrowserPlugin.id ? browserContext : context)), revision: "internal", source: { type: "builtin" }, }) satisfies Generation, diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index f577028ba22..5432ab3c88b 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -13,7 +13,7 @@ import { Schema } from "effect" import type { Embeds } from "@opencode/plugin/gui/main" import { captureCoordinator, captureScale, cropPixels, FULL_PAGE_DEADLINE_MS, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" import { createCdp, abortError, waitFor } from "./cdp" -import { navigationDeadline } from "./navigation-deadline" +import { navigationDeadline, navigationProgressDeadline, type NavigationOutcome } from "./navigation-deadline" import { attachChildren, releaseWorker } from "./child-targets" import { CodedError, missingArtifact, pageReports } from "./errors" import { createBrowserFiles } from "./files" @@ -1306,13 +1306,17 @@ export function createBrowserPage( const begin = (signal = options.signal, keepAddress = false) => navigation.begin(AbortSignal.any([pageLifetime.signal, signal, options.signal]), keepAddress) - const load = async (url: string, retry = false, commandSignal = options.signal, keepAddress = true, deadlineMs?: number) => { + const load = async (url: string, retry = false, commandSignal = options.signal, keepAddress = true, deadlineMs?: number): Promise => { const visit = begin(commandSignal, keepAddress) const destination = url.startsWith("artifact:") ? options.artifacts?.load(url) : localFileURL(url) || url.startsWith("workspace:") ? await options.workspace?.load(url, () => notices.show({ reason: "browser.preview.restricted" }), retry ? contents.getURL() : undefined) : url if (!destination) return Promise.reject(new Error("Workspace preview is unavailable.")) + let outcome: NavigationOutcome = "completed" + await visit(destination, async () => { + outcome = await loadDestination(destination, url, deadlineMs) + }) - return visit(destination, () => loadDestination(destination, url, deadlineMs)) + return outcome } const loadDestination = (destination: string, url: string, deadlineMs?: number) => { @@ -1333,17 +1337,21 @@ export function createBrowserPage( if (!options.artifacts?.display(destination)) artifactHost = undefined } - contents.once("did-navigate", commit) + const stillLoading = () => !closed() && !contents.isDestroyed() && contents.isLoading() + const onStop = () => next.stop(stillLoading()) + const onDestroyed = () => next.stop(false) + + contents.on("did-navigate", commit) const next = replacementNavigation() contents.on("did-start-navigation", next.start) contents.on("did-navigate", next.commit) - contents.on("did-stop-loading", next.stop) - contents.once("destroyed", next.stop) + contents.on("did-stop-loading", onStop) + contents.once("destroyed", onDestroyed) - return navigationDeadline(contents.loadURL(destination).catch(async (error: Error) => { + return navigationProgressDeadline(contents.loadURL(destination).catch(async (error: Error) => { if (committedLoad(error, committed)) return - if (destinationOrigin(destination) && await next.after(error)) return + if (destinationOrigin(destination) && await next.after(error, stillLoading())) return if (options.previewFailure?.(destination)) throw new FileVerificationError() @@ -1353,10 +1361,10 @@ export function createBrowserPage( if (!committed && "errno" in error && (error.errno === -2 || error.errno === -3)) throw new CodedError("navigation_failed", "No page committed. The navigation was cancelled, failed, or became a download. Check the tab and its downloads before navigating again.") throw error - }), deadlineMs).finally(() => { - next.stop() - contents.off("destroyed", next.stop) - contents.off("did-stop-loading", next.stop) + }), () => committed, deadlineMs).finally(() => { + next.stop(false) + contents.off("destroyed", onDestroyed) + contents.off("did-stop-loading", onStop) contents.off("did-navigate", next.commit) contents.off("did-start-navigation", next.start) contents.off("did-navigate", commit) @@ -1708,15 +1716,19 @@ export function createBrowserPage( const cancel = () => contents.stop() signal.addEventListener("abort", cancel, { once: true }) + let outcome: NavigationOutcome = "completed" + try { - await load(url, false, signal, origin === "user", options.navigationDeadlineMs) + outcome = await load(url, false, signal, origin === "user", options.navigationDeadlineMs) } finally { signal.removeEventListener("abort", cancel) } - // The load event comes just before Chromium says the tab stopped loading; report the tab after that. A frame that - // still loads after a moment is reported as loading, which it is. - await waitFor(() => !contents.isLoading(), signal, 2_000).catch(() => abortError(signal)) + // The load event comes just before Chromium says the tab stopped loading; report the tab after that. When the + // document already committed and subresources are still loading at the deadline, return the committed tab with + // `loading: true` immediately so callers can use explicit `browser.wait` readiness checks. + if (outcome === "completed") + await waitFor(() => !contents.isLoading(), signal, 2_000).catch(() => abortError(signal)) return result(state()) } diff --git a/packages/gui-plugins/src/browser/electron-open.fixture.ts b/packages/gui-plugins/src/browser/electron-open.fixture.ts index 4b021f3bf05..758a86e08c5 100644 --- a/packages/gui-plugins/src/browser/electron-open.fixture.ts +++ b/packages/gui-plugins/src/browser/electron-open.fixture.ts @@ -25,7 +25,7 @@ const loading = `Still loading

shown

{ - if (request.url === "/never") return + if (request.url === "/never" || request.url?.startsWith("/hung")) return // The server drops the connection, so Chromium fails the load at once. if (request.url?.startsWith("/dropped")) return void request.socket.destroy() @@ -173,9 +173,12 @@ void electron.app.whenReady().then(async () => { const { createSitePermissions } = await import("./site-permissions") const { createSystemMedia } = await import("./system-media") const pages = createPages() + // Dedicated loopback origin for the uncommitted /hung stall so it never shares Chromium's per-origin socket pool with /loading tabs. + const hungPages = createServer((_request, _response) => undefined) // The session's workspace, which holds `report.html`: a page that shows and takes over a second to finish loading. const api = createApi(process.env.ELECTRON_OPEN_ROOT ?? "") const origin = await listen(pages) + const hungOrigin = await listen(hungPages) const server = await listen(api.server) const win = new electron.BrowserWindow({ show: false, width: 800, height: 600 }) const values = new Map() @@ -302,12 +305,19 @@ void electron.app.whenReady().then(async () => { } // The agent: its command, what the pane answered, and what the pane asked the window to show meanwhile. - const asked = async (action: Browser.Action, address: string) => { + const asked = async (action: Browser.Action, address: string, commits = true) => { const from = shown.length + const beforeIDs = new Set(last().map((item) => item.id)) const outcome = await api.agent(action) - // The tab is at its address: a web page still loading there, as the test compares. - await until(() => !!tab(address) && (action.type === "preview" || !!tab(address)?.loading), 3_000) - const listed = tab(address) + // A committed page reaches its address; an uncommitted stall stays on its initial tab. + await until( + () => + commits + ? !!tab(address) && (action.type === "preview" || !!tab(address)?.loading) + : last().some((item) => !beforeIDs.has(item.id)), + 3_000, + ) + const listed = commits ? tab(address) : last().find((item) => !beforeIDs.has(item.id)) return { answer: outcome.type === "failure" ? outcome.message : outcome.type, @@ -321,6 +331,7 @@ void electron.app.whenReady().then(async () => { front: await asked({ type: "tabs.open", url: `${origin}/loading?agent` }, "/loading?agent"), behind: await asked({ type: "tabs.open", url: `${origin}/loading?behind`, focus: false }, "/loading?behind"), preview: await asked({ type: "preview", path: "report.html" }, "/report.html"), + hung: await asked({ type: "tabs.open", url: `${hungOrigin}/hung?agent` }, "/hung?agent", false), } // The window registers again with the inventory it last took in, as when its session moves or its server signs in @@ -345,6 +356,8 @@ void electron.app.whenReady().then(async () => { await pane.dispose() lifetime.abort() api.close() + hungPages.closeAllConnections() + hungPages.close() pages.closeAllConnections() pages.close() electron.app.quit() diff --git a/packages/gui-plugins/src/browser/electron-open.test.ts b/packages/gui-plugins/src/browser/electron-open.test.ts index b8353238d08..1e4c32ba112 100644 --- a/packages/gui-plugins/src/browser/electron-open.test.ts +++ b/packages/gui-plugins/src/browser/electron-open.test.ts @@ -36,7 +36,7 @@ test( person: { commands: Record; before: string[]; after: View[] } committed: boolean plugin: { loading: Handed; dropped: Handed; nothing: Handed } - agent: { front: Asked; behind: Asked; preview: Asked } + agent: { front: Asked; behind: Asked; preview: Asked; hung: Asked } registered: { held: string[]; again: string[] } logged: string[] } = JSON.parse(await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-open.fixture.ts"), schemes, env: { ELECTRON_OPEN_ROOT: root } })) @@ -66,16 +66,18 @@ test( expect(result.plugin.dropped).toEqual({ opened: "handle", listed: { url: `${origin}/dropped?plugin`, loading: false, failed: true }, closed: true, left: false }) expect(result.plugin.nothing).toEqual({ opened: expect.stringContaining("No page committed"), left: false }) - // The agent's tab that stays was shown as one that loaded: in front, behind with `focus: false`, and a workspace - // file takes the pane. The agent hears that the page did not finish, with the tab to go on with. + // Committed documents still loading subresources at the deadline succeed with `loading: true` instead of + // failing as false navigation timeouts. True no-progress stalls (no document committed, `/hung`) still fail + // with the deadline error and keep the tab open so the agent can inspect, wait, reload, or close it. const told = (asked: Asked, operation: string) => `browser.${operation} failed. The browser page did not finish starting or navigating. Reload the tab and inspect it before retrying. The tab stays open as ${asked.tabID}: use that tabID with browser.wait, browser.reload or browser.tabs.close, and do not open the address again.` - expect(result.agent.front).toEqual({ answer: told(result.agent.front, "tabs.open"), tabID: expect.stringMatching(/^tab_/), listed: { url: `${origin}/loading?agent`, loading: true, failed: false }, shown: ["tab"] }) - expect(result.agent.behind).toEqual({ answer: told(result.agent.behind, "tabs.open"), tabID: expect.stringMatching(/^tab_/), listed: { url: `${origin}/loading?behind`, loading: true, failed: false }, shown: ["none"] }) - expect(result.agent.preview.answer).toBe(told(result.agent.preview, "preview")) + expect(result.agent.front).toEqual({ answer: "success", tabID: expect.stringMatching(/^tab_/), listed: { url: `${origin}/loading?agent`, loading: true, failed: false }, shown: ["tab"] }) + expect(result.agent.behind).toEqual({ answer: "success", tabID: expect.stringMatching(/^tab_/), listed: { url: `${origin}/loading?behind`, loading: true, failed: false }, shown: ["none"] }) + expect(result.agent.preview.answer).toBe("success") expect(result.agent.preview.tabID).toMatch(/^tab_/) expect(result.agent.preview.shown).toEqual(["tab"]) + expect(result.agent.hung).toEqual({ answer: told(result.agent.hung, "tabs.open"), tabID: expect.stringMatching(/^tab_/), listed: { url: expect.any(String), loading: true, failed: false }, shown: ["tab"] }) // A registration is no close either. The window registers again with an inventory that has only its first two // tabs; the new binding lists every tab the pane held, in its order. It used to start from that inventory alone. expect(result.registered.held.slice(0, 2)).toEqual(result.person.before) diff --git a/packages/gui-plugins/src/browser/electron-tunnel.fixture.ts b/packages/gui-plugins/src/browser/electron-tunnel.fixture.ts new file mode 100644 index 00000000000..bbfe1b1def9 --- /dev/null +++ b/packages/gui-plugins/src/browser/electron-tunnel.fixture.ts @@ -0,0 +1,208 @@ +import { createServer } from "node:http" +import { WebSocketServer } from "@effect/platform-node/NodeWS" +import electron from "electron" +import { Effect, Predicate } from "effect" +import type { RpcClient } from "@opencode/client/effect/api" +import type { Browser } from "@opencode/plugin-browser/rpc" +import { BrowserTunnelHost, EgressPolicy, StreamMux, StreamWire } from "@opencode/plugin-browser/experimental/stream" +import { SessionID } from "@opencode/schema/session-id" +import { createBrowserNetwork, type BrowserNetwork } from "./network" + +type ServerWs = InstanceType["clients"] extends Set ? W : never + +const sessionID = SessionID.make("ses_00000000000000000000000001") + +function adaptWs(ws: ServerWs): BrowserTunnelHost.BinarySocket { + return { + get readyState() { return ws.readyState }, + get bufferedAmount() { return ws.bufferedAmount }, + send: (data, cb) => ws.send(data, { binary: true, compress: false }, (err) => cb?.(err ?? undefined)), + close: (code, reason) => { if (ws.readyState <= ws.OPEN) ws.close(code, reason) }, + terminate: () => ws.terminate(), + onMessage(listener) { + const handler = (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => + listener(!isBinary ? String(raw) : raw instanceof Uint8Array ? raw : raw instanceof ArrayBuffer ? new Uint8Array(raw) : Buffer.concat(raw)) + + ws.on("message", handler) + + return () => void ws.off("message", handler) + }, + onClose(listener) { + const handler = (code: number, reason: Buffer) => listener(code, reason.toString("utf8")) + ws.on("close", handler) + + return () => void ws.off("close", handler) + }, + onError(listener) { + ws.on("error", listener) + + return () => void ws.off("error", listener) + }, + } +} + +const listen = (server: ReturnType) => + new Promise((resolve) => + server.listen(0, "127.0.0.1", () => { + const addr = server.address() + + resolve(`http://127.0.0.1:${addr && !Predicate.isString(addr) ? addr.port : 0}`) + }), + ) + +electron.app.on("window-all-closed", () => undefined) + +void electron.app.whenReady().then(async () => { + let targetHits = 0 + const html = `` + + const target = createServer((req, res) => { + targetHits += 1 + + if (req.url === "/big") { + const body = Buffer.alloc(128 * 1024, 0x33) + res.writeHead(200, { "content-length": String(body.length) }).end(body) + + return + } + + const body = req.url === "/asset" ? "ok:/asset" : html + const type = req.url === "/asset" ? "text/plain" : "text/html" + res.writeHead(200, { "content-type": type, "content-length": String(Buffer.byteLength(body)) }).end(body) + }) + + const targetWss = new WebSocketServer({ noServer: true }) + targetWss.on("connection", (ws) => ws.on("message", (msg) => ws.send(`hmr:${msg.toString()}`))) + target.on("upgrade", (req, sock, head) => targetWss.handleUpgrade(req, sock, head, (ws) => targetWss.emit("connection", ws, req))) + + const tickets = new Set() + const muxes = new Set() + const tunnelWss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: StreamWire.MAX_WS_FRAME_BYTES }) + let rejectUpgrade = false + const stats = { upgrades: 0, rejected: 0, ticketHeader: false, ticketCalls: 0, grantCalls: 0, legacyCalls: 0 } + + const tunnelServer = createServer((_req, res) => res.writeHead(404).end()) + + tunnelServer.on("upgrade", (req, sock, head) => { + const url = new URL(req.url ?? "/", "http://fixture") + const ticket = req.headers["x-opencode-browser-ticket"] + + if (Predicate.isString(ticket) && ticket.length > 0 && !url.searchParams.has("ticket")) stats.ticketHeader = true + + if (rejectUpgrade || !Predicate.isString(ticket) || !tickets.delete(ticket)) { + stats.rejected += 1 + sock.end("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + + return + } + + stats.upgrades += 1 + tunnelWss.handleUpgrade(req, sock, head, (ws) => { + const mux = StreamMux.createServerMux(adaptWs(ws), { policy: EgressPolicy.makePolicy(), heartbeatIntervalMs: 0 }) + muxes.add(mux) + void mux.closed.finally(() => muxes.delete(mux)) + }) + }) + + const [targetOrigin, tunnelOrigin] = await Promise.all([listen(target), listen(tunnelServer)]) + + const makeRpc = () => { + const legacyFail = () => { + stats.legacyCalls += 1 + + return Effect.fail(new Error("legacy disabled")) + } + + // SAFETY: `createBrowserNetwork` calls only the tunnel.* RPC methods exercised here. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- minimal fixture stub for Browser.Definition + return { + "tunnel.ticket": () => + Effect.sync(() => { + stats.ticketCalls += 1 + const ticket = `tkt_${crypto.randomUUID()}` + tickets.add(ticket) + + return { ticket, expiresIn: 30, protocol: 1 as const, path: BrowserTunnelHost.BROWSER_TUNNEL_PATH } + }), + "tunnel.grant": () => + Effect.sync(() => { + stats.grantCalls += 1 + }), + "tunnel.open": legacyFail, + "tunnel.read": legacyFail, + "tunnel.write": legacyFail, + "tunnel.close": () => Effect.void, + } as unknown as RpcClient + } + + const runPartition = (partition: string, caps: readonly string[], body: (win: electron.BrowserWindow, net: BrowserNetwork) => Promise) => + Effect.runPromise( + Effect.gen(function* () { + const net = yield* createBrowserNetwork({ + server: { id: "remote", url: tunnelOrigin, headers: { authorization: "Basic dGVzdDp0ZXN0" }, sameMachine: false }, + rpc: makeRpc(), + attachment: { sessionID, connectionID: partition }, + location: { directory: "/remote" }, + partition, + }) + + net.activate?.(caps) + const win = new electron.BrowserWindow({ show: false, webPreferences: { partition } }) + const detach = net.attach(win.webContents) + + try { + return yield* Effect.promise(() => body(win, net)) + } finally { + detach() + win.destroy() + } + }).pipe(Effect.scoped), + ) + + // 1. Advertised binary WS stream: HTTP asset + 128 KiB body + live HMR WS kept open across clean teardown. + const streamed = await runPartition("tunnel-ok", [BrowserTunnelHost.STREAM_CAPABILITY], async (win, net) => { + await net.grantPrivateTarget?.(targetOrigin) + await win.loadURL(targetOrigin) + + return await win.webContents.executeJavaScript("window.__run()") + }) + + const okStats = { ...stats } + const hitsAfterOk = targetHits + + // 2. Rejected upgrade (403): must fail with proxy 502 and never downgrade to legacy RPC or direct network. + rejectUpgrade = true + + const blockedStatus = await runPartition("tunnel-403", [BrowserTunnelHost.STREAM_CAPABILITY], async (win) => { + let status = 0 + win.webContents.once("did-navigate", (_event, _url, code) => { status = code }) + await win.loadURL(targetOrigin).catch(() => undefined) + + return status + }) + + const blockedHits = targetHits - hitsAfterOk + const after403 = { ...stats } + + // 3. Unadvertised/disabled server: must never send tunnel.ticket or tunnel.grant RPCs. + await runPartition("tunnel-off", [], async (_win, net) => { + await net.grantPrivateTarget?.(targetOrigin) + }) + + const legacyDelta = { + ticketCalls: stats.ticketCalls - after403.ticketCalls, + grantCalls: stats.grantCalls - after403.grantCalls, + upgrades: stats.upgrades - after403.upgrades, + } + + muxes.forEach((m) => m.close()) + tunnelWss.close() + targetWss.close() + tunnelServer.closeAllConnections() + target.closeAllConnections() + tunnelServer.close() + target.close() + + process.stdout.write(`${JSON.stringify({ streamed, okStats, blockedStatus, blockedHits, after403, legacyDelta })}\n`) + electron.app.exit(0) +}) diff --git a/packages/gui-plugins/src/browser/electron-tunnel.test.ts b/packages/gui-plugins/src/browser/electron-tunnel.test.ts new file mode 100644 index 00000000000..1d3458fd297 --- /dev/null +++ b/packages/gui-plugins/src/browser/electron-tunnel.test.ts @@ -0,0 +1,40 @@ +import { expect, test } from "bun:test" +import path from "node:path" +import { schemes } from "../schemes" +import { runElectronFixture } from "./electron-run" + +test( + "Electron remote partition relays HTTP, 128 KiB body and HMR WS over one binary WS, never downgrades on 403, and skips grants when unadvertised", + async () => { + const result: { + streamed: { a: string; b: number; ws: string } + okStats: { upgrades: number; rejected: number; ticketHeader: boolean; ticketCalls: number; grantCalls: number; legacyCalls: number } + blockedStatus: number + blockedHits: number + after403: { upgrades: number; rejected: number; legacyCalls: number } + legacyDelta: { ticketCalls: number; grantCalls: number; upgrades: number } + } = JSON.parse( + await runElectronFixture({ + fixture: path.join(import.meta.dir, "electron-tunnel.fixture.ts"), + schemes, + }), + ) + + expect(result.streamed).toEqual({ a: "ok:/asset", b: 128 * 1024, ws: "hmr:ping" }) + expect(result.okStats).toEqual({ + upgrades: 1, + rejected: 0, + ticketHeader: true, + ticketCalls: 1, + grantCalls: 1, + legacyCalls: 0, + }) + expect(result.blockedStatus).toBe(502) + expect(result.blockedHits).toBe(0) + expect(result.after403.upgrades).toBe(1) + expect(result.after403.rejected).toBeGreaterThanOrEqual(1) + expect(result.after403.legacyCalls).toBe(0) + expect(result.legacyDelta).toEqual({ ticketCalls: 0, grantCalls: 0, upgrades: 0 }) + }, + 60_000, +) diff --git a/packages/gui-plugins/src/browser/navigation-deadline.test.ts b/packages/gui-plugins/src/browser/navigation-deadline.test.ts index 43db44012ab..a53696b5282 100644 --- a/packages/gui-plugins/src/browser/navigation-deadline.test.ts +++ b/packages/gui-plugins/src/browser/navigation-deadline.test.ts @@ -1,5 +1,5 @@ import { expect, jest, test } from "bun:test" -import { NAVIGATION_DEADLINE_MS, navigationDeadline } from "./navigation-deadline" +import { NAVIGATION_DEADLINE_MS, navigationDeadline, navigationProgressDeadline } from "./navigation-deadline" test("a page with no first document fails its waiter before the browser RPC deadline", async () => { jest.useFakeTimers() @@ -24,3 +24,26 @@ test("a page with no first document fails its waiter before the browser RPC dead jest.useRealTimers() } }) + +test("navigationProgressDeadline distinguishes committed-but-still-loading from uncommitted no-progress", async () => { + jest.useFakeTimers() + + try { + // 1. Committed document still loading subresources settles cleanly as still_loading instead of failing. + const committedWork = Promise.withResolvers() + const stillLoading = navigationProgressDeadline(committedWork.promise, () => true, 300) + jest.advanceTimersByTime(300) + expect(await stillLoading).toBe("still_loading") + + // 2. Uncommitted navigation (true no-progress) still rejects with NavigationDeadlineError. + const hungWork = Promise.withResolvers() + const failed = navigationProgressDeadline(hungWork.promise, () => false, 300).catch((error: Error) => error.message) + jest.advanceTimersByTime(300) + expect(await failed).toContain("Reload the tab") + + // 3. Completed load before deadline resolves as completed. + expect(await navigationProgressDeadline(Promise.resolve(), () => true, 300)).toBe("completed") + } finally { + jest.useRealTimers() + } +}) diff --git a/packages/gui-plugins/src/browser/navigation-deadline.ts b/packages/gui-plugins/src/browser/navigation-deadline.ts index 04bc278b4c1..632823e35ea 100644 --- a/packages/gui-plugins/src/browser/navigation-deadline.ts +++ b/packages/gui-plugins/src/browser/navigation-deadline.ts @@ -18,3 +18,32 @@ export function navigationDeadline(work: Promise, ms = NAVIGATION_DEADLINE return Promise.race([work, deadline]).finally(() => clearTimeout(timer)) } + +export type NavigationOutcome = "completed" | "still_loading" + +/** + * Guards a navigation against true no-progress stalls while distinguishing a document that has + * already committed and is still streaming subresources (`still_loading`) from one that never + * committed before `ms` (`NavigationDeadlineError`). + */ +export function navigationProgressDeadline( + work: Promise, + isCommitted: () => boolean, + ms = NAVIGATION_DEADLINE_MS, +): Promise { + let timer: ReturnType + + const deadline = new Promise((resolve, reject) => { + timer = setTimeout(() => { + if (isCommitted()) { + resolve("still_loading") + + return + } + + reject(new NavigationDeadlineError()) + }, ms) + }) + + return Promise.race([work.then((): NavigationOutcome => "completed"), deadline]).finally(() => clearTimeout(timer)) +} diff --git a/packages/gui-plugins/src/browser/navigation-turn.test.ts b/packages/gui-plugins/src/browser/navigation-turn.test.ts index eec45ffbb0c..55f368bad15 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.test.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.test.ts @@ -30,6 +30,35 @@ test.each([true, false])("an abort waits for the replacement document, not the o expect(next.after(new Error("network error"))).toBeUndefined() }) +test("a client redirect that rejects with -3 while loading commits cleanly, while a no-commit stop still fails", async () => { + const start = { isMainFrame: true, isSameDocument: false } + const aborted = Object.assign(new Error("ERR_ABORTED"), { errno: -3 }) + + // 1. Late-starting client redirect: loadURL rejects with -3 while stillLoading is true, then commits. + const redirect = replacementNavigation() + redirect.start(start) + const waiting = redirect.after(aborted, true) + expect(waiting).toBeDefined() + // Intermediate stop while Chromium is still loading the replacement hop does not fail it. + redirect.stop(true) + redirect.start(start) + redirect.commit() + expect(await waiting).toBe(true) + + // 2. Actual no-commit abort (e.g. download, 204, or user Stop): loading stops without a commit -> false. + const noCommit = replacementNavigation() + noCommit.start(start) + const abortedWait = noCommit.after(aborted, true) + expect(abortedWait).toBeDefined() + noCommit.stop(false) + expect(await abortedWait).toBe(false) + + // 3. Abort after loading already stopped returns undefined immediately (never unconditional success). + const idleAbort = replacementNavigation() + idleAbort.start(start) + expect(idleAbort.after(aborted, false)).toBeUndefined() +}) + test.each(["stop", "oc-preview://private/report", "https://next.test"])('a later %s wins over a deferred web navigation', async next => { const gate = Promise.withResolvers() const issued: string[] = [] diff --git a/packages/gui-plugins/src/browser/navigation-turn.ts b/packages/gui-plugins/src/browser/navigation-turn.ts index a7a570d03ed..7deed8c0489 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.ts @@ -1,18 +1,51 @@ import type { Browser } from "@opencode/plugin-browser/rpc" -/** Electron rejects loadURL as soon as a second main-frame navigation starts, before its document commits. */ +/** + * Electron rejects `loadURL` with `ERR_ABORTED` (-3) when a client redirect or second main-frame + * navigation supersedes the initial load before it commits. Tracks whether a replacement navigation + * actually commits a document while preserving genuine no-commit aborts (stops, downloads, 204s). + */ export function replacementNavigation() { let starts = 0 + let awaitingLateStart = false let replacement: ReturnType> | undefined + const ensure = () => (replacement ??= Promise.withResolvers()) + return { start(event: { isMainFrame: boolean; isSameDocument: boolean }) { - if (event.isMainFrame && !event.isSameDocument && ++starts === 2) replacement = Promise.withResolvers() + if (!event.isMainFrame || event.isSameDocument) return + + starts += 1 + + if (starts >= 2) { + awaitingLateStart = false + ensure() + } }, - commit: () => replacement?.resolve(true), - stop: () => replacement?.resolve(false), - after(error: Error) { - return "errno" in error && error.errno === -3 ? replacement?.promise : undefined + commit: () => { + if (starts >= 2 || awaitingLateStart) replacement?.resolve(true) + }, + stop: (stillLoading = false) => { + // A redirect chain can emit did-stop-loading for the aborted hop while Chromium is still loading the replacement. + if (stillLoading) return + + replacement?.resolve(false) + }, + after(error: Error, stillLoading = false) { + if (!("errno" in error && error.errno === -3)) return undefined + + if (replacement) return replacement.promise + + // A client redirect can reject the first loadURL with -3 just before its did-start-navigation fires; + // wait for either an actual commit or loading stopping without a commit (never unconditional success). + if (stillLoading) { + awaitingLateStart = true + + return ensure().promise + } + + return undefined }, } } diff --git a/packages/gui-plugins/src/browser/network.ts b/packages/gui-plugins/src/browser/network.ts index bde9e36747a..d1b752901fe 100644 --- a/packages/gui-plugins/src/browser/network.ts +++ b/packages/gui-plugins/src/browser/network.ts @@ -1,40 +1,113 @@ +import { Duplex } from "node:stream" import { net, session, type WebContents } from "electron" import type { RpcClient } from "@opencode/client/effect/api" +import type { ServerEndpoint } from "@opencode/plugin/gui/main" import type { Session } from "@opencode/schema/session" import { Browser } from "@opencode/plugin-browser/rpc" import { BrowserProxy } from "@opencode/plugin-browser/proxy" -import { Effect } from "effect" +import { BrowserTunnelHost, StreamMux } from "@opencode/plugin-browser/experimental/stream" +import { Effect, Predicate } from "effect" import { Base64 } from "effect/encoding" +import { + openAuthenticatedWebSocket, + PREWARM_WAIT_TIMEOUT_MS, + TUNNEL_PROTOCOL_VERSION, + TunnelUpgradeError, +} from "./tunnel-client" -export type BrowserNetwork = Effect.Success> +export { resolveBrowserTunnelUrl, TunnelUpgradeError, type TunnelUpgradeFailureKind } from "./tunnel-client" + +export type BrowserNetwork = { + attach(contents: WebContents): () => void + icon(url: string): Promise<{ mime: string; data: Buffer } | undefined> + /** Activates negotiated tunnel mode once the server emits `attached`. */ + activate?(capabilities: readonly string[]): void + /** Explicitly grants a private preview target for this attachment via trusted desktop RPC. */ + grantPrivateTarget?(url: string, extraPorts?: readonly number[]): Promise + /** Whether a prewarmed binary WebSocket stream currently owns this attachment's liveness. */ + streamActive?(): boolean + /** Resolves once the liveness-owning binary WebSocket stream ends. */ + readonly streamEnded?: Promise<"closed" | "replaced"> +} export const createBrowserNetwork = Effect.fn("BrowserNetwork.create")(function* (input: { + server: ServerEndpoint rpc: RpcClient attachment: { sessionID: Session.ID; connectionID: string } location: { directory: string; workspace?: string } partition: string }) { const options = { location: input.location } + const resetListeners = new Set<() => void>() + const streamEnded = Promise.withResolvers<"closed" | "replaced">() + let disposed = false + let serverAdvertisedStream = false + const initialReady = Promise.withResolvers() + // Prewarm can settle before any page opens a stream; consume the rejection here while `openStream` throws `mode.error`. + void initialReady.promise.catch(() => undefined) + + let mode: + | { readonly kind: "pending"; readonly ready: ReturnType> } + | { readonly kind: "stream"; readonly mux: StreamMux.ClientMux } + | { readonly kind: "failed"; readonly error: TunnelUpgradeError } + | { readonly kind: "legacy" } = { kind: "pending", ready: initialReady } + + const notifyReset = () => { + resetListeners.forEach((listener) => listener()) + } + + const legacyTransport: BrowserProxy.Transport = { + open: (target, signal) => + Effect.runPromise(input.rpc["tunnel.open"]({ ...input.attachment, target }, options), { signal }), + read: (tunnelID, signal) => + Effect.runPromise(input.rpc["tunnel.read"]({ ...input.attachment, tunnelID }, options), { signal }), + write: (tunnelID, data, end, signal) => { + const payload = { ...input.attachment, tunnelID, data: Base64.encode(data), end } + + return Effect.runPromise(input.rpc["tunnel.write"](payload, options), { signal }) + }, + close: (tunnelID) => + Effect.runPromise( + input.rpc["tunnel.close"]({ ...input.attachment, tunnelID }, options).pipe(Effect.timeout("5 seconds")), + ), + } + + const streamTransport: BrowserProxy.StreamTransport = { + async openStream(target, signal) { + if (disposed) throw new Error("Browser attachment is closed.") + + if (mode.kind === "pending") await waitWithAbort(mode.ready.promise, signal, PREWARM_WAIT_TIMEOUT_MS) + + if (disposed) throw new Error("Browser attachment is closed.") + + if (mode.kind === "stream") return mode.mux.openStream(target, signal) + + if (mode.kind === "failed") throw mode.error + + if (mode.kind === "legacy") return openLegacyDuplex(legacyTransport, target, signal) + + throw new Error("Browser tunnel did not become ready.") + }, + onReset(listener) { + resetListeners.add(listener) + + return () => { + resetListeners.delete(listener) + } + }, + } const proxy = yield* Effect.acquireRelease( - Effect.tryPromise(() => - BrowserProxy.make({ - open: (target, signal) => - Effect.runPromise(input.rpc["tunnel.open"]({ ...input.attachment, target }, options), { signal }), - read: (tunnelID, signal) => - Effect.runPromise(input.rpc["tunnel.read"]({ ...input.attachment, tunnelID }, options), { signal }), - write: (tunnelID, data, end, signal) => - Effect.runPromise( - input.rpc["tunnel.write"]({ ...input.attachment, tunnelID, data: Base64.encode(data), ...(end !== undefined && { end }) }, options), - { signal }, - ), - close: (tunnelID) => - Effect.runPromise( - input.rpc["tunnel.close"]({ ...input.attachment, tunnelID }, options).pipe(Effect.timeout("5 seconds")), - ), - }), - ), - (proxy) => Effect.promise(() => proxy.close()), + Effect.tryPromise(() => BrowserProxy.make(streamTransport)), + (value) => + Effect.sync(() => { + disposed = true + + if (mode.kind === "stream") mode.mux.close(1000, "desktop detached") + + if (mode.kind === "pending") mode.ready.reject(new Error("Browser attachment closed.")) + streamEnded.resolve("closed") + }).pipe(Effect.andThen(Effect.promise(() => value.close()))), ) const partition = session.fromPartition(input.partition) @@ -46,7 +119,104 @@ export const createBrowserNetwork = Effect.fn("BrowserNetwork.create")(function* ) yield* Effect.tryPromise(() => partition.closeAllConnections()) - return { + const prewarmStream = async () => { + const pending = mode.kind === "pending" ? mode.ready : undefined + + try { + const issued = await Effect.runPromise( + input.rpc["tunnel.ticket"]({ ...input.attachment, protocol: TUNNEL_PROTOCOL_VERSION }, options), + ).catch((cause: Error) => { + throw classifyTicketError(cause) + }) + + if (disposed) return + + const socket = await openAuthenticatedWebSocket({ + server: input.server, + location: input.location, + attachment: input.attachment, + ticket: issued.ticket, + path: issued.path, + protocol: issued.protocol, + }) + + if (disposed) { + socket.close(1000, "desktop detached") + + return + } + + const mux = StreamMux.createClientMux(socket) + mode = { kind: "stream", mux } + pending?.resolve() + void mux.closed.then((info) => { + notifyReset() + + if (disposed) return + + mode = { + kind: "failed", + error: new TunnelUpgradeError( + "transport", + info.replaced ? "Browser attachment was replaced." : info.reason || "Browser stream tunnel disconnected.", + ), + } + streamEnded.resolve(info.replaced ? "replaced" : "closed") + }) + } catch (cause) { + const error = + cause instanceof TunnelUpgradeError + ? cause + : new TunnelUpgradeError("transport", cause instanceof Error ? cause.message : String(cause)) + + // Never silently downgrade to legacy RPC or desktop direct network on auth, TLS, policy, or blocked upgrade errors. + mode = { kind: "failed", error } + pending?.reject(error) + } + } + + const network: BrowserNetwork = { + activate(capabilities) { + if (disposed || mode.kind !== "pending") return + + serverAdvertisedStream = capabilities.includes(BrowserTunnelHost.STREAM_CAPABILITY) + const forcedLegacy = process.env.OPENCODE_BROWSER_TUNNEL_TRANSPORT?.trim().toLowerCase() === "legacy" + + if (!forcedLegacy && serverAdvertisedStream) { + void prewarmStream() + + return + } + + const ready = mode.ready + mode = { kind: "legacy" } + ready.resolve() + }, + async grantPrivateTarget(url, extraPorts) { + // Only send experimental private-target grants when this attachment advertised the stream tunnel experiment. + if (disposed || !serverAdvertisedStream) return + + const parsed = URL.parse(url) + + if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) return + + const host = parsed.hostname.replace(/^\[|\]$/g, "") + + if (!host) return + + const port = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80 + + if (!Number.isInteger(port) || port < 1 || port > 65_535) return + + const requestInput = + extraPorts && extraPorts.length > 0 + ? { ...input.attachment, target: { host, port }, ports: [...extraPorts] } + : { ...input.attachment, target: { host, port } } + + await Effect.runPromise(input.rpc["tunnel.grant"](requestInput, options).pipe(Effect.ignore)) + }, + streamActive: () => !disposed && mode.kind === "stream" && !mode.mux.isClosed(), + streamEnded: streamEnded.promise, attach(contents: WebContents) { const login = ( event: Electron.Event, @@ -79,8 +249,174 @@ export const createBrowserNetwork = Effect.fn("BrowserNetwork.create")(function* callback() }), } + + return network }) +function classifyTicketError(cause: Error): TunnelUpgradeError { + const message = cause.message + + if (/401|403|unauthor|forbid/i.test(message)) { + return new TunnelUpgradeError("auth", `Browser stream ticket request failed authentication: ${message}`) + } + + if (/cert|ssl|tls|self.signed|unable to verify/i.test(message)) { + return new TunnelUpgradeError("tls", `Browser stream ticket request failed TLS verification: ${message}`) + } + + return new TunnelUpgradeError("ticket", `Could not obtain browser stream upgrade ticket: ${message}`) +} + +async function waitWithAbort(promise: Promise, signal: AbortSignal, timeoutMs: number) { + if (signal.aborted) throw new Error("Browser tunnel open was cancelled.") + + let timer: ReturnType | undefined + + const gate = new Promise((_resolve, reject) => { + const onAbort = () => reject(new Error("Browser tunnel open was cancelled.")) + signal.addEventListener("abort", onAbort, { once: true }) + timer = setTimeout(() => { + signal.removeEventListener("abort", onAbort) + reject(new Error("Browser stream tunnel timed out while connecting.")) + }, timeoutMs) + }) + + try { + await Promise.race([promise, gate]) + } finally { + if (timer) clearTimeout(timer) + } +} + +async function openLegacyDuplex( + transport: BrowserProxy.Transport, + target: Browser.TunnelTarget, + signal: AbortSignal, +): Promise { + const id = await transport.open(target, signal) + + return new LegacyRpcDuplex(transport, id) +} + +class LegacyRpcDuplex extends Duplex { + readonly connecting = false + private readonly abort = new AbortController() + private reading = false + private ended = false + private idleTimer?: ReturnType + + constructor( + private readonly transport: BrowserProxy.Transport, + private readonly id: string, + ) { + super({ highWaterMark: Browser.TUNNEL_CHUNK_BYTES, allowHalfOpen: true }) + this.on("error", () => this.destroy()) + } + + override _read() { + if (this.reading || this.ended || this.destroyed) return + + this.reading = true + void this.transport.read(this.id, this.abort.signal).then( + (result) => { + this.reading = false + + if (this.destroyed) return + + if (result.eof) { + this.ended = true + this.push(null) + + return + } + + if (this.push(result.data)) this._read() + }, + (error: Error) => { + this.reading = false + this.destroy(error) + }, + ) + } + + override _write(chunk: Buffer | string, encoding: BufferEncoding, callback: (error?: Error | null) => void) { + const data = Predicate.isString(chunk) ? Buffer.from(chunk, encoding) : chunk + void (async () => { + for (let offset = 0; offset < data.byteLength; offset += Browser.TUNNEL_CHUNK_BYTES) { + await this.transport.write( + this.id, + data.subarray(offset, offset + Browser.TUNNEL_CHUNK_BYTES), + false, + this.abort.signal, + ) + } + })().then( + () => callback(), + (error: Error) => callback(error), + ) + } + + override _final(callback: (error?: Error | null) => void) { + void this.transport.write(this.id, new Uint8Array(), true, this.abort.signal).then( + () => callback(), + (error: Error) => callback(error), + ) + } + + override _destroy(error: Error | null, callback: (error?: Error | null) => void) { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = undefined + } + + this.ended = true + this.abort.abort() + void this.transport + .close(this.id) + .catch(() => undefined) + .then(() => callback(error)) + } + + setKeepAlive() { + return this + } + + setNoDelay() { + return this + } + + setTimeout(timeout: number, callback?: () => void) { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = undefined + } + + if (timeout === 0) { + if (callback) this.off("timeout", callback) + + return this + } + + if (callback) this.once("timeout", callback) + + this.idleTimer = setTimeout(() => { + this.idleTimer = undefined + this.emit("timeout") + }, timeout) + this.idleTimer.unref?.() + + return this + } + + ref() { + return this + } + + unref() { + return this + } +} + /** * The network of a server on this machine: the same one this desktop has, so pages load directly in the partition, * with the system's proxy settings, rather than through the server's tunnel. @@ -103,7 +439,14 @@ function fetchIcon( ) { return new Promise<{ mime: string; data: Buffer } | undefined>((resolve) => { // The page supplies this URL. The browser chrome must not turn an icon into a credentialed navigation. - const request = net.request({ url, session: partition, useSessionCookies: false, credentials: "omit", redirect: "follow" }) + const request = net.request({ + url, + session: partition, + useSessionCookies: false, + credentials: "omit", + redirect: "follow", + }) + const chunks: Buffer[] = [] const finish = (value?: { mime: string; data: Buffer }) => { @@ -117,12 +460,14 @@ function fetchIcon( } const timeout = setTimeout(fail, 5_000) + request.on("login", login) request.on("response", (response) => { const header = response.headers["content-type"] const mime = (Array.isArray(header) ? header[0] : header)?.split(";")[0]?.trim().toLowerCase() ?? "" if (response.statusCode !== 200 || !mime.startsWith("image/")) return fail() + response.on("data", (chunk) => { chunks.push(chunk) diff --git a/packages/gui-plugins/src/browser/pane-machine.test.ts b/packages/gui-plugins/src/browser/pane-machine.test.ts index 1bd58c25390..ef21a209457 100644 --- a/packages/gui-plugins/src/browser/pane-machine.test.ts +++ b/packages/gui-plugins/src/browser/pane-machine.test.ts @@ -68,6 +68,7 @@ function frame(data: { readonly type: string readonly connectionID: string readonly version?: number + readonly capabilities?: readonly string[] readonly requestID?: string }) { return resolveControlFrame(connectionID, decodeControlHeader(data), decodeControl(data)) @@ -255,7 +256,11 @@ describe("control events", () => { test("decodes this connection's handshake and requests and ignores other connections", () => { expect(frame({ type: "attached", connectionID: "other", version: 5 })).toEqual({ kind: "foreign" }) - expect(frame({ type: "attached", connectionID, version: 4 })).toEqual({ kind: "attached" }) + expect(frame({ type: "attached", connectionID, version: 4 })).toEqual({ kind: "attached", capabilities: [] }) + expect(frame({ type: "attached", connectionID, version: 4, capabilities: ["tunnel.ws.v1"] })).toEqual({ + kind: "attached", + capabilities: ["tunnel.ws.v1"], + }) expect(frame({ type: "command", connectionID, requestID: "r1" })).toEqual({ kind: "command", requestID: "r1" }) expect(frame({ type: "cancel", connectionID, requestID: "r1" })).toEqual({ kind: "cancel", requestID: "r1" }) }) diff --git a/packages/gui-plugins/src/browser/pane-machine.ts b/packages/gui-plugins/src/browser/pane-machine.ts index 40e273d3e81..97cdfd5ee8a 100644 --- a/packages/gui-plugins/src/browser/pane-machine.ts +++ b/packages/gui-plugins/src/browser/pane-machine.ts @@ -76,7 +76,7 @@ export type AttachmentOutcome = "closed" | "replaced" | "missing" | "unavailable /** A browser control event from the server's stream, as this binding reads it. */ export type ControlFrame = | { readonly kind: "foreign" } - | { readonly kind: "attached" } + | { readonly kind: "attached"; readonly capabilities: readonly string[] } | { readonly kind: "command"; readonly requestID: string } | { readonly kind: "cancel"; readonly requestID: string } /** An `attached` handshake this desktop cannot decode: the server speaks another protocol version. */ @@ -209,7 +209,7 @@ export function resolveControlFrame( ? { kind: "incompatible" } : { kind: "unrecognized", controlType: header.value.type } - if (control.value.type === "attached") return { kind: "attached" } + if (control.value.type === "attached") return { kind: "attached", capabilities: control.value.capabilities ?? [] } return { kind: control.value.type, requestID: control.value.requestID } } diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 0bfa4b4ff13..114cc5b26ef 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -305,7 +305,7 @@ export function createBrowserPane(input: { if (shared) handle.network = createDirectNetwork(input.profile.session) if (!shared) { - handle.network = yield* createBrowserNetwork({ rpc, attachment, location: options.location, partition }) + handle.network = yield* createBrowserNetwork({ server, rpc, attachment, location: options.location, partition }) // Only when the user chose to share sign-ins with remote servers do they carry over, both ways, so a page // of a remote server is signed in where the profile is; otherwise `link` leaves the partition apart. @@ -413,7 +413,11 @@ export function createBrowserPane(input: { if (frame.kind === "foreign") return - if (frame.kind === "attached") return dispatchBinding(binding, { type: "server.attached", fileRoots }) + if (frame.kind === "attached") { + handle.network?.activate?.(frame.capabilities) + + return dispatchBinding(binding, { type: "server.attached", fileRoots }) + } if (frame.kind === "incompatible") return dispatchBinding(binding, { type: "handshake.unsupported" }) @@ -443,19 +447,29 @@ export function createBrowserPane(input: { Effect.ignore, ) + const attachWithRetry = Deferred.await(connected).pipe( + Effect.andThen(attach), + // A Location still loading its plugins has no browser RPC to call yet, so only one that lists its + // plugins and still refuses has no browser. An attachment the server accepted and then dropped stays + // dropped: the server evicted its idle Location, which another call would start again. + Effect.catchIf( + (error) => attachmentFailure(error) === "unavailable" && selectBinding(machine.state, binding)?.status === "connecting", + () => loaded.pipe(Effect.andThen(attach)), + ), + // Once a prewarmed binary WebSocket owns attachment liveness, a reverse-proxy idle timeout on the + // silent attach HTTP request does not end the live attachment: the WebSocket's outcome governs it. + Effect.catchCause((cause) => + handle.network?.streamActive?.() && handle.network.streamEnded + ? Effect.promise(() => handle.network!.streamEnded!) + : Effect.failCause(cause), + ), + ) + return yield* Effect.raceAllFirst([ receive, Stream.fromQueue(outbound).pipe(Stream.runForEach((send) => send)), - Deferred.await(connected).pipe( - Effect.andThen(attach), - // A Location still loading its plugins has no browser RPC to call yet, so only one that lists its - // plugins and still refuses has no browser. An attachment the server accepted and then dropped stays - // dropped: the server evicted its idle Location, which another call would start again. - Effect.catchIf( - (error) => attachmentFailure(error) === "unavailable" && selectBinding(machine.state, binding)?.status === "connecting", - () => loaded.pipe(Effect.andThen(attach)), - ), - ), + attachWithRetry, + ...(handle.network?.streamEnded ? [Effect.promise(() => handle.network!.streamEnded!)] : []), ]) }).pipe( Effect.matchCause({ @@ -592,6 +606,12 @@ export function createBrowserPane(input: { if (reason) throw new Error(reason) + if (url !== undefined) { + const remote = handles.get(binding) + + if (remote && !remote.shared) await remote.network?.grantPrivateTarget?.(normalizeURL(url, pagePolicy(binding))) + } + if (command.type === "navigate") dispatchBinding(binding, { type: "tab.addressed", tabID: command.tabID }) if ("tabID" in command && command.type !== "tabs.focus") page(binding, command.tabID)?.personCommand() @@ -620,7 +640,11 @@ export function createBrowserPane(input: { const handle = handles.get(binding) if (!handle) throw new Error("browser.pane.unavailable") + + if (!handle.shared) await handle.network?.grantPrivateTarget?.(normalizeURL(url, pagePolicy(binding))) + const grant = handle.pluginTabs.reserve(owner) + // Never adopt an existing file tab, even when this plugin opens the same URL as the user. await execute(binding, { action: { type: "tabs.open", url }, files: [] }, handle.abort.signal, "user", "new", undefined, grant.created) grant.settled() diff --git a/packages/gui-plugins/src/browser/tunnel-client.test.ts b/packages/gui-plugins/src/browser/tunnel-client.test.ts new file mode 100644 index 00000000000..a1dfcfb48fb --- /dev/null +++ b/packages/gui-plugins/src/browser/tunnel-client.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, test } from "bun:test" +import { once } from "node:events" +import { createServer } from "node:http" +import { WebSocketServer } from "@effect/platform-node/NodeWS" +import { BrowserTunnelHost } from "@opencode/plugin-browser/experimental/stream" +import { SessionID } from "@opencode/schema/session-id" +import { Predicate } from "effect" +import { + openAuthenticatedWebSocket, + resolveBrowserTunnelUrl, + TUNNEL_TICKET_HEADER, + TunnelUpgradeError, +} from "./tunnel-client" + +const sessionID = SessionID.make("ses_00000000000000000000000001") + +describe("resolveBrowserTunnelUrl and openAuthenticatedWebSocket credential boundary", () => { + test("derives fixed route from configured endpoint and preserves reverse-proxy base path prefix", () => { + const cases = [ + ["https://proxy.example", "wss://proxy.example/api/experimental/browser/tunnel"], + ["https://proxy.example/", "wss://proxy.example/api/experimental/browser/tunnel"], + ["https://proxy.example/opencode", "wss://proxy.example/opencode/api/experimental/browser/tunnel"], + ["https://proxy.example/opencode/", "wss://proxy.example/opencode/api/experimental/browser/tunnel"], + ["http://127.0.0.1:4096/sub/path/", "ws://127.0.0.1:4096/sub/path/api/experimental/browser/tunnel"], + ] as const + + for (const [serverUrl, expectedBase] of cases) { + const resolved = resolveBrowserTunnelUrl({ + serverUrl, + location: { directory: "/work/app" }, + replyPath: BrowserTunnelHost.BROWSER_TUNNEL_PATH, + }) + + expect(`${resolved.origin}${resolved.pathname}`).toBe(expectedBase) + expect(resolved.searchParams.get("location[directory]")).toBe("/work/app") + expect(resolved.searchParams.has("ticket")).toBe(false) + } + }) + + test("refuses malformed or mismatched reply paths before opening a socket or sending credentials", async () => { + let trapHits = 0 + + const trapServer = createServer((_req, res) => { + trapHits += 1 + res.writeHead(200).end() + }) + + trapServer.on("upgrade", (_req, socket) => { + trapHits += 1 + socket.destroy() + }) + + await once(trapServer.listen(0, "127.0.0.1"), "listening") + const trapAddr = trapServer.address() + + if (!trapAddr || Predicate.isString(trapAddr)) throw new Error("No trap server address") + + const hostilePaths = [ + `http://127.0.0.1:${trapAddr.port}/api/experimental/browser/tunnel`, + `ws://127.0.0.1:${trapAddr.port}/api/experimental/browser/tunnel`, + `//127.0.0.1:${trapAddr.port}/api/experimental/browser/tunnel`, + `https://127.0.0.1:${trapAddr.port}/steal`, + "/api/other", + "/api/experimental/browser/tunnel?extra=1", + "/api/experimental/browser/tunnel#frag", + "/api/experimental/../other", + "\\127.0.0.1\\steal", + "", + ] + + try { + for (const path of hostilePaths) { + let caught: Error | undefined + + try { + await openAuthenticatedWebSocket({ + server: { + id: "remote", + url: "http://127.0.0.1:1/opencode", + headers: { authorization: "Basic c2VjcmV0OnRva2Vu" }, + sameMachine: false, + }, + location: { directory: "/work" }, + attachment: { sessionID, connectionID: "conn_1" }, + ticket: "tkt_sensitive_test_value", + path, + protocol: 1, + }) + } catch (error) { + caught = error instanceof Error ? error : new Error(String(error)) + } + + expect(caught).toBeInstanceOf(TunnelUpgradeError) + expect(caught instanceof TunnelUpgradeError ? caught.kind : undefined).toBe("protocol") + } + + // Give the event loop a turn to prove no outbound socket dial ever started. + await new Promise((resolve) => setTimeout(resolve, 25)) + expect(trapHits).toBe(0) + } finally { + trapServer.closeAllConnections() + await new Promise((resolve) => trapServer.close(() => resolve())) + } + }) + + test("upgrades against a prefixed reverse-proxy base URL with ticket in header and no cookie forwarding", async () => { + interface SeenUpgrade { + url?: string + ticket?: string + auth?: string + cookie?: string + } + + const seen: SeenUpgrade = {} + const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false }) + const server = createServer((_req, res) => res.writeHead(404).end()) + + server.on("upgrade", (req, socket, head) => { + seen.url = req.url + seen.ticket = Predicate.isString(req.headers[TUNNEL_TICKET_HEADER]) ? req.headers[TUNNEL_TICKET_HEADER] : undefined + seen.auth = Predicate.isString(req.headers.authorization) ? req.headers.authorization : undefined + seen.cookie = Predicate.isString(req.headers.cookie) ? req.headers.cookie : undefined + wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req)) + }) + + await once(server.listen(0, "127.0.0.1"), "listening") + const addr = server.address() + + if (!addr || Predicate.isString(addr)) throw new Error("No prefixed server address") + + try { + const ws = await openAuthenticatedWebSocket({ + server: { + id: "remote", + url: `http://127.0.0.1:${addr.port}/opencode/proxy/`, + headers: { authorization: "Basic dGVzdDp0ZXN0", cookie: "session=must-not-send" }, + sameMachine: false, + }, + location: { directory: "/work/repo" }, + attachment: { sessionID, connectionID: "conn_prefixed" }, + ticket: "tkt_prefixed_ok", + path: BrowserTunnelHost.BROWSER_TUNNEL_PATH, + protocol: 1, + }) + + expect(seen.url).toBe("/opencode/proxy/api/experimental/browser/tunnel?location%5Bdirectory%5D=%2Fwork%2Frepo") + expect(seen.ticket).toBe("tkt_prefixed_ok") + expect(seen.auth).toBe("Basic dGVzdDp0ZXN0") + expect(seen.cookie).toBeUndefined() + ws.close(1000, "done") + } finally { + wss.close() + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + } + }) +}) diff --git a/packages/gui-plugins/src/browser/tunnel-client.ts b/packages/gui-plugins/src/browser/tunnel-client.ts new file mode 100644 index 00000000000..6f5263c7bee --- /dev/null +++ b/packages/gui-plugins/src/browser/tunnel-client.ts @@ -0,0 +1,289 @@ +import { WebSocket as NodeWebSocket } from "@effect/platform-node/NodeWS" +import type { ServerEndpoint } from "@opencode/plugin/gui/main" +import type { Session } from "@opencode/schema/session" +import { BrowserTunnelHost, StreamWire } from "@opencode/plugin-browser/experimental/stream" +import { Predicate } from "effect" + +export const TUNNEL_TICKET_HEADER = "x-opencode-browser-ticket" + +export const TUNNEL_SESSION_HEADER = "x-opencode-browser-session" + +export const TUNNEL_CONNECTION_HEADER = "x-opencode-browser-connection" + +export const TUNNEL_PROTOCOL_HEADER = "x-opencode-browser-protocol" + +export const TUNNEL_PROTOCOL_VERSION = 1 as const + +export const PREWARM_WAIT_TIMEOUT_MS = 15_000 + +export type TunnelUpgradeFailureKind = "auth" | "tls" | "blocked" | "protocol" | "ticket" | "transport" + +/** + * Explicit non-downgrading failure raised when a server advertises binary stream tunneling + * (`tunnel.ws.v1`) and the WebSocket upgrade is rejected, blocked, or fails TLS/auth/route checks. + */ +export class TunnelUpgradeError extends Error { + constructor( + readonly kind: TunnelUpgradeFailureKind, + message: string, + readonly statusCode?: number, + ) { + super(message) + this.name = "TunnelUpgradeError" + } +} + +/** + * Derives the binary WebSocket upgrade URL solely from the configured server endpoint using the + * same base-path prefix joining rules as the authenticated HTTP SDK (`HttpClientRequest.prependUrl`). + * Validates any reply `path` strictly against the fixed experimental route so a malformed or + * mismatched plugin reply can never steer endpoint credentials to another authority or path. + */ +export function resolveBrowserTunnelUrl(input: { + readonly serverUrl: string + readonly location: { readonly directory: string; readonly workspace?: string } + readonly replyPath?: string +}): URL { + if (input.replyPath !== undefined && input.replyPath !== BrowserTunnelHost.BROWSER_TUNNEL_PATH) { + throw new TunnelUpgradeError( + "protocol", + `Refused unexpected browser tunnel upgrade path: ${input.replyPath.slice(0, 128)}`, + ) + } + + const base = URL.parse(input.serverUrl) + + if (!base || (base.protocol !== "http:" && base.protocol !== "https:")) { + throw new TunnelUpgradeError( + "protocol", + `Unsupported server URL protocol for browser tunnel: ${base?.protocol ?? "invalid"}`, + ) + } + + if (base.username || base.password) { + throw new TunnelUpgradeError("protocol", "Configured browser tunnel server URL must not contain credentials.") + } + + const prefix = base.pathname.replace(/\/+$/, "") + const expectedPathname = `${prefix}${BrowserTunnelHost.BROWSER_TUNNEL_PATH}` + const wsUrl = new URL(expectedPathname, base.origin) + const expectedProtocol = base.protocol === "https:" ? "wss:" : "ws:" + wsUrl.protocol = expectedProtocol + + if ( + wsUrl.protocol !== expectedProtocol || + wsUrl.host !== base.host || + wsUrl.pathname !== expectedPathname || + wsUrl.username !== "" || + wsUrl.password !== "" + ) { + throw new TunnelUpgradeError("protocol", "Derived browser tunnel upgrade URL did not match configured server authority.") + } + + wsUrl.searchParams.set("location[directory]", input.location.directory) + + if (input.location.workspace) wsUrl.searchParams.set("location[workspace]", input.location.workspace) + + return wsUrl +} + +/** + * Opens one authenticated binary WebSocket in Electron main using a short-lived single-use ticket + * in the `x-opencode-browser-ticket` header. Verified TLS is strictly enforced and redirects are rejected. + */ +export async function openAuthenticatedWebSocket(input: { + readonly server: ServerEndpoint + readonly location: { readonly directory: string; readonly workspace?: string } + readonly attachment: { readonly sessionID: Session.ID; readonly connectionID: string } + readonly ticket: string + readonly path?: string + readonly protocol: number +}): Promise { + // Validate reply path and derive URL strictly from the configured endpoint BEFORE touching credentials or sockets. + const wsUrl = resolveBrowserTunnelUrl({ + serverUrl: input.server.url, + location: input.location, + replyPath: input.path, + }) + + // Forward only non-cookie configured endpoint headers (for authenticating reverse proxies if present); + // never put the ticket in URLs, and never send browser cookies. + const headers: Record = {} + + for (const [key, value] of Object.entries(input.server.headers)) { + if (key.toLowerCase() === "cookie") continue + headers[key] = value + } + + headers[TUNNEL_TICKET_HEADER] = input.ticket + headers[TUNNEL_SESSION_HEADER] = input.attachment.sessionID + headers[TUNNEL_CONNECTION_HEADER] = input.attachment.connectionID + headers[TUNNEL_PROTOCOL_HEADER] = String(input.protocol) + + return await new Promise((resolve, reject) => { + const ws = new NodeWebSocket(wsUrl.toString(), { + headers, + perMessageDeflate: false, + followRedirects: false, + maxPayload: StreamWire.MAX_WS_FRAME_BYTES, + handshakeTimeout: PREWARM_WAIT_TIMEOUT_MS, + }) + + let settled = false + + const finish = (fn: () => void) => { + if (settled) return + + settled = true + ws.off("open", onOpen) + ws.off("unexpected-response", onUnexpectedResponse) + ws.off("error", onError) + ws.off("close", onClose) + fn() + } + + const onOpen = () => { + finish(() => resolve(adaptNodeWebSocket(ws))) + } + + const onUnexpectedResponse = (_request: { readonly path?: string }, response: { readonly statusCode?: number }) => { + const status = response.statusCode ?? 0 + finish(() => { + // Keep a silent error sink because `ws.terminate()` during CONNECTING emits an asynchronous error event. + ws.on("error", () => undefined) + ws.terminate() + + if (status === 401 || status === 403) { + reject( + new TunnelUpgradeError( + "auth", + `Browser stream tunnel upgrade was rejected (HTTP ${status}). Check server credentials and attachment state.`, + status, + ), + ) + + return + } + + reject( + new TunnelUpgradeError( + "blocked", + `Browser stream tunnel WebSocket upgrade was blocked (HTTP ${status}). Ensure the server or reverse proxy permits WebSocket upgrades.`, + status, + ), + ) + }) + } + + const onError = (error: Error) => { + finish(() => { + ws.on("error", () => undefined) + ws.terminate() + reject(classifySocketError(error)) + }) + } + + const onClose = (code: number, reason: Buffer) => { + finish(() => + reject( + new TunnelUpgradeError( + code === 1002 || code === 1008 || code === 1009 ? "protocol" : "transport", + reason.toString("utf8") || `Browser stream tunnel closed during handshake (code ${code}).`, + ), + ), + ) + } + + ws.once("open", onOpen) + ws.once("unexpected-response", onUnexpectedResponse) + ws.once("error", onError) + ws.once("close", onClose) + }) +} + +function adaptNodeWebSocket(ws: NodeWebSocket): BrowserTunnelHost.BinarySocket { + return { + get readyState() { + return ws.readyState + }, + get bufferedAmount() { + return ws.bufferedAmount + }, + send(data, onWritten) { + ws.send(data, { binary: true, compress: false }, (error) => onWritten?.(error ?? undefined)) + }, + ping() { + if (ws.readyState === ws.OPEN) ws.ping() + }, + close(code, reason) { + if (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING) ws.close(code, reason) + }, + terminate() { + ws.terminate() + }, + onMessage(listener) { + const handler = (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => { + if (!isBinary) { + listener(String(raw)) + + return + } + + if (raw instanceof Uint8Array) { + listener(raw) + + return + } + + if (raw instanceof ArrayBuffer) { + listener(new Uint8Array(raw)) + + return + } + + listener(Buffer.concat(raw)) + } + + ws.on("message", handler) + + return () => { + ws.off("message", handler) + } + }, + onClose(listener) { + const handler = (code: number, reason: Buffer) => listener(code, reason.toString("utf8")) + ws.on("close", handler) + + return () => { + ws.off("close", handler) + } + }, + onError(listener) { + ws.on("error", listener) + + return () => { + ws.off("error", listener) + } + }, + onPong(listener) { + ws.on("pong", listener) + + return () => { + ws.off("pong", listener) + } + }, + } +} + +function classifySocketError(error: Error): TunnelUpgradeError { + const code = Predicate.hasProperty(error, "code") && Predicate.isString(error.code) ? error.code : "" + + if (/CERT|TLS|SSL|HOSTNAME_MISMATCH|UNABLE_TO_VERIFY|SELF_SIGNED/i.test(`${code} ${error.message}`)) { + return new TunnelUpgradeError( + "tls", + `Browser stream tunnel TLS verification failed (${code || error.message}). Check the server certificate.`, + ) + } + + return new TunnelUpgradeError("transport", `Browser stream tunnel connection failed: ${error.message}`) +} diff --git a/packages/plugin-browser/package.json b/packages/plugin-browser/package.json index 6e41f02c3e0..47ab3ec97e2 100644 --- a/packages/plugin-browser/package.json +++ b/packages/plugin-browser/package.json @@ -21,7 +21,9 @@ "./rpc": "./src/rpc.ts", "./workspace": "./src/workspace.ts", "./preview-path": "./src/preview-path.ts", - "./proxy": "./src/proxy.ts" + "./proxy": "./src/proxy.ts", + "./experimental/stream": "./src/stream.ts", + "./experimental/tunnel-host": "./src/tunnel-host.ts" }, "scripts": { "build": "tsc -p tsconfig.build.json", diff --git a/packages/plugin-browser/src/connection.ts b/packages/plugin-browser/src/connection.ts index 959a2f40eb7..0b9293e31f3 100644 --- a/packages/plugin-browser/src/connection.ts +++ b/packages/plugin-browser/src/connection.ts @@ -10,13 +10,26 @@ import type { Permission } from "@opencode/schema/permission" import { Session } from "@opencode/schema/session" import { Tool } from "@opencode/schema/tool" import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect" +import { EgressPolicy } from "./egress-policy.js" import { BrowserMachine } from "./machine.js" import { Browser } from "./rpc.js" +import { StreamMux } from "./stream-mux.js" import { BrowserTunnel } from "./tunnel.js" +import { BrowserTunnelHost } from "./tunnel-host.js" type Attachment = { + readonly sessionID: Session.ID + readonly connectionID: string + readonly attempt: number readonly closed: Deferred.Deferred<"closed" | "replaced", "unavailable"> + /** Snapped once at attachment start so capabilities, tickets, grants, and egress stay coherent. */ + readonly streamEnabled: boolean + /** Defined strictly when `streamEnabled` is true; enforced across both WS streams and legacy RPC. */ + readonly policy: EgressPolicy.AttachmentPolicy | undefined readonly tunnels: BrowserTunnel.Tunnels + stream?: StreamMux.ServerMux + streamAttached: boolean + disposed: boolean } export type Connection = Effect.Success> @@ -66,6 +79,12 @@ export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleG export const make = Effect.fn("BrowserConnection.make")(function* ( ctx: Pick, ) { + const tunnelHost = yield* BrowserTunnelHost.Reference + const locationRef = Location.Ref.make({ + directory: ctx.location.directory, + ...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }), + }) + // Each agent's rules from config and its definition, which an attachment's grant must not override. const configured = new Map() // Appended after config, so every agent hides the browser tools and their skill until an attachment allows them. @@ -134,17 +153,42 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( const perform = (effect: BrowserMachine.ConnectionEffect): Effect.Effect => { if (effect.type === "sync-permissions") return Effect.asVoid(Effect.forkIn(syncPermissions(effect), work)) if (effect.type === "close-attachment") - return Effect.suspend(() => { + return Effect.gen(function* () { const attachment = attachments.get(effect.attempt) - if (!attachment) return Effect.void + if (!attachment) return + attachment.disposed = true attachments.delete(effect.attempt) + if (tunnelHost && attachment.streamEnabled) { + yield* tunnelHost + .revokeAttachment(attachment.sessionID, attachment.connectionID, attachment.attempt) + .pipe(Effect.ignore) + } + const closeCode = + effect.outcome === "replaced" + ? BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED + : BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED + const closeReason = effect.outcome === "replaced" ? "replaced" : "closed" + attachment.stream?.close(closeCode, closeReason) + attachment.stream = undefined attachment.tunnels.dispose() - return Deferred.done( + yield* Deferred.done( attachment.closed, effect.outcome === "unavailable" ? Exit.fail(effect.outcome) : Exit.succeed(effect.outcome), ).pipe(Effect.asVoid) }) - if (effect.type === "emit-control") return rpc.events.emit("control", effect.control) + if (effect.type === "emit-control") { + const control = effect.control + if (control.type === "attached") { + const live = Array.from(attachments.values()).find( + (candidate) => !candidate.disposed && candidate.connectionID === control.connectionID, + ) + return rpc.events.emit( + "control", + live?.streamEnabled ? { ...control, capabilities: [BrowserTunnelHost.STREAM_CAPABILITY] } : control, + ) + } + return rpc.events.emit("control", control) + } if (effect.type === "dispatch-command") return ( rpc.events @@ -200,16 +244,22 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( }), }), ) + const liveAttachment = (input: { + sessionID: Session.ID + connectionID: string + }): Effect.Effect => { + const attempt = BrowserMachine.selectAttachment(machine.state, input.sessionID, input.connectionID) + const attachment = attempt === undefined ? undefined : attachments.get(attempt) + return attachment && !attachment.disposed + ? Effect.succeed(attachment) + : Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed.")) + } const tunnels = (input: { sessionID: Session.ID connectionID: string - }): Effect.Effect => { - const attempt = BrowserMachine.selectAttachment(machine.state, input.sessionID, input.connectionID) - const attachment = attempt === undefined ? undefined : attachments.get(attempt) - return attachment - ? Effect.succeed(attachment.tunnels) - : Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed.")) - } + }): Effect.Effect => + liveAttachment(input).pipe(Effect.map((attachment) => attachment.tunnels)) + yield* reconcileStaleGrants(ctx) const rpc: RpcRegistration = yield* ctx.rpc .register(Browser.Definition, { @@ -220,13 +270,32 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( .pipe(Effect.mapError(() => call.error("unavailable", "Session not found.", {}))) if (session.location.directory !== ctx.location.directory) return yield* Effect.fail(call.error("unavailable", "Session belongs to another location.", {})) + // Select experimental streaming + egress policy once at attachment start so disabled releases + // preserve pre-PR legacy tunnel behavior and active attachments stay coherent across RPCs. + const streamEnabled = tunnelHost + ? yield* tunnelHost.enabled.pipe(Effect.orElseSucceed(() => false)) + : false return yield* Effect.acquireUseRelease( lock.withPermit( Effect.suspend(() => { if (BrowserMachine.isConnectionDisposed(machine.state)) return Effect.fail(call.error("unavailable", "Browser is unavailable.", {})) const attempt = BrowserMachine.selectNextAttempt(machine.state) - const attachment: Attachment = { closed: Deferred.makeUnsafe(), tunnels: BrowserTunnel.make() } + const policy = + streamEnabled && tunnelHost + ? EgressPolicy.makePolicy({ reservedLocalPorts: tunnelHost.reservedLocalPorts }) + : undefined + const attachment: Attachment = { + sessionID: input.sessionID, + connectionID: input.connectionID, + attempt, + closed: Deferred.makeUnsafe(), + streamEnabled, + policy, + tunnels: BrowserTunnel.make(policy), + streamAttached: false, + disposed: false, + } attachments.set(attempt, attachment) return step({ type: "attach.started", @@ -240,7 +309,15 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( Deferred.await(attached.attachment.closed).pipe( Effect.mapError(() => call.error("unavailable", "Browser permissions could not be granted.", {})), ), - (attached) => dispatch({ type: "attach.closed", sessionID: input.sessionID, attempt: attached.attempt }), + (attached) => + Effect.suspend(() => { + // Once an upgraded binary WebSocket owns this attachment's liveness, a reverse-proxy idle + // timeout on the silent HTTP attach request must not tear down the live attachment. + if (attached.attachment.streamAttached && !attached.attachment.disposed && attached.attachment.stream) { + return Effect.void + } + return dispatch({ type: "attach.closed", sessionID: input.sessionID, attempt: attached.attempt }) + }), ) }), state: (input, call) => @@ -272,6 +349,74 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( ? dispatch({ type: "request.settled", ...input }) : Effect.fail(call.error("unavailable", "Browser is unavailable.", {})), ), + "tunnel.ticket": (input, call) => + Effect.gen(function* () { + const attachment = yield* liveAttachment(input).pipe( + Effect.mapError((error) => call.error("unavailable", error.message, {})), + ) + const policy = attachment.policy + if (!tunnelHost || !attachment.streamEnabled || !policy) { + return yield* Effect.fail(call.error("unavailable", "Browser stream tunnel is disabled.", {})) + } + const issued = yield* tunnelHost + .issueTicket({ + location: locationRef, + sessionID: input.sessionID, + connectionID: input.connectionID, + generation: attachment.attempt, + protocol: input.protocol, + onUpgrade: (socket) => + Effect.gen(function* () { + if (attachment.disposed || attachments.get(attachment.attempt) !== attachment) { + socket.close(BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED, "attachment closed") + return + } + const previous = attachment.stream + const mux = StreamMux.createServerMux(socket, { policy }) + attachment.stream = mux + attachment.streamAttached = true + if (previous) previous.close(BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED, "superseded") + yield* Effect.promise(() => mux.closed).pipe( + Effect.ensuring( + Effect.suspend(() => { + if (attachment.stream === mux) attachment.stream = undefined + // If no replacement stream took over and the attachment wasn't already closed/replaced, + // closing the liveness-owning WebSocket detaches the attachment and revokes its sockets. + if (!attachment.disposed && attachment.stream === undefined) { + return dispatch({ + type: "attach.closed", + sessionID: attachment.sessionID, + attempt: attachment.attempt, + }) + } + return Effect.void + }), + ), + ) + }), + }) + .pipe(Effect.mapError((error) => call.error("unavailable", String(error), {}))) + return { + ticket: issued.ticket, + expiresIn: issued.expiresIn, + protocol: 1 as const, + path: BrowserTunnelHost.BROWSER_TUNNEL_PATH, + } + }), + "tunnel.grant": (input, call) => + liveAttachment(input).pipe( + Effect.flatMap((attachment) => { + const policy = attachment.policy + if (!attachment.streamEnabled || !policy) { + return Effect.fail(new Error("Browser stream tunnel is disabled.")) + } + return Effect.try({ + try: () => policy.grant(input.target.host, input.target.port, input.ports ?? []), + catch: (error) => (error instanceof Error ? error : new Error(String(error))), + }) + }), + Effect.mapError((error) => call.error("unavailable", error.message, {})), + ), "tunnel.open": (input, call) => tunnels(input).pipe( Effect.flatMap((network) => network.open(input.target)), @@ -302,12 +447,17 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( }).pipe( // A deleted session's grant went with it, and no revoke will forget its owner record. Effect.andThen( - event.type === "session.deleted" - ? Effect.all([ - ctx.storage.remove(GRANT_PREFIX + event.data.sessionID), - 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))), - ]).pipe(Effect.ignore) + event.type === "session.deleted" + ? Effect.all([ + ctx.storage.remove(GRANT_PREFIX + event.data.sessionID), + 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), + ), + ), + ]).pipe(Effect.ignore) : Effect.void, ), ), @@ -395,7 +545,11 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( * The permission check for one call, with the operation as its resource. Its `permission.evaluate` hooks decide it: * this plugin's (configured denies win over the grant) and others such as `tool.use` policies. */ - authorize: Effect.fn("BrowserConnection.authorize")(function* (tool: Tool.Context, action: Browser.Action | Extract, operations?: readonly string[]) { + authorize: Effect.fn("BrowserConnection.authorize")(function* ( + tool: Tool.Context, + action: Browser.Action | Extract, + operations?: readonly string[], + ) { const connection = BrowserMachine.selectConnection(machine.state, tool.sessionID) if (!connection.ok) return { connected: false as const, message: connection.error.message } yield* ctx.permission.assert({ diff --git a/packages/plugin-browser/src/egress-policy.ts b/packages/plugin-browser/src/egress-policy.ts new file mode 100644 index 00000000000..d3d3b984394 --- /dev/null +++ b/packages/plugin-browser/src/egress-policy.ts @@ -0,0 +1,483 @@ +export * as EgressPolicy from "./egress-policy.js" + +import { isIP, type Socket } from "node:net" +import type { Browser } from "./rpc.js" + +export type AddressClass = "public" | "loopback" | "private" | "metadata" | "reserved" + +export type ResolvedAddress = { + readonly address: string + readonly family: 4 | 6 +} + +export type Resolver = (host: string) => Promise + +export type PolicyDecision = + | { readonly allowed: true; readonly addressClass: AddressClass } + | { readonly allowed: false; readonly reason: string; readonly addressClass: AddressClass } + +export class EgressDeniedError extends Error { + readonly code = "POLICY_DENIED" as const + constructor(message: string) { + super(message) + this.name = "EgressDeniedError" + } +} + +/** + * Non-HTTP infrastructure and management ports refused on loopback and private targets so a loaded + * page cannot reach local SSH, mail, SMB, Docker, or Kubernetes control planes. + */ +export const BLOCKED_MANAGEMENT_PORTS: ReadonlySet = new Set([ + 22, + 23, + 25, + 111, + 135, + 137, + 138, + 139, + 445, + 2375, + 2376, + 6443, + 10250, +]) + +const METADATA_HOSTS: ReadonlySet = new Set([ + "metadata", + "metadata.google.internal", + "metadata.goog", + "instance-data", + "instance-data.ec2.internal", + "metadata.azure.internal", + "metadata.packet.net", + "metadata.platformequinix.com", +]) + +export interface AttachmentPolicyOptions { + /** Server-owned local ports (such as the OpenCode HTTP API itself) that page traffic must never reach. */ + readonly reservedLocalPorts?: () => ReadonlySet + /** Explicit server policy permitting non-management private/RFC1918/ULA LAN targets. Default false. */ + readonly allowPrivateLan?: boolean + /** Custom DNS resolver (tests). Defaults to Node's `dns.lookup(host, { all: true, verbatim: true })`. */ + readonly resolve?: Resolver +} + +export type AttachmentPolicy = ReturnType + +export function readAllowPrivateLanEnv(env: Readonly> = process.env) { + const value = env.OPENCODE_BROWSER_ALLOW_PRIVATE_LAN?.trim().toLowerCase() + return value === "1" || value === "true" || value === "yes" +} + +export function makePolicy(options: AttachmentPolicyOptions = {}) { + const granted = new Map>() + const allowPrivateLan = options.allowPrivateLan ?? readAllowPrivateLanEnv() + const reservedLocalPorts = options.reservedLocalPorts ?? (() => new Set()) + + const isReservedPort = (port: number) => BLOCKED_MANAGEMENT_PORTS.has(port) || reservedLocalPorts().has(port) + + const isGranted = (host: string, port: number) => granted.get(normalizeHost(host))?.has(port) ?? false + + return { + /** + * Grants one attachment access to an explicit private preview host/port (and optional HMR ports). + * Refuses reserved metadata hostnames/IPs and management or server-owned ports. + */ + grant(host: string, port: number, extraPorts: readonly number[] = []) { + const normalized = normalizeHost(host) + if (!normalized || isMetadataHost(normalized)) { + throw new EgressDeniedError(`Cannot grant reserved metadata host: ${host}`) + } + const literal = parseIpLiteral(normalized) + if (literal) { + const cls = classifyIp(literal.address) + if (cls === "metadata" || cls === "reserved") { + throw new EgressDeniedError(`Cannot grant reserved address: ${host}`) + } + } + const ports = [port, ...extraPorts] + for (const candidate of ports) { + if (!Number.isInteger(candidate) || candidate < 1 || candidate > 65_535) { + throw new EgressDeniedError(`Invalid port in grant: ${candidate}`) + } + if (isReservedPort(candidate)) { + throw new EgressDeniedError(`Cannot grant protected management port ${candidate}.`) + } + } + const existing = granted.get(normalized) ?? new Set() + ports.forEach((candidate) => existing.add(candidate)) + granted.set(normalized, existing) + }, + + evaluateAddress(host: string, port: number, address: string): PolicyDecision { + const normalized = normalizeHost(host) + if (!normalized || isMetadataHost(normalized)) { + return { allowed: false, addressClass: "metadata", reason: "Access to cloud metadata endpoints is blocked." } + } + const cls = classifyIp(address) + if (cls === "metadata" || cls === "reserved") { + return { + allowed: false, + addressClass: cls, + reason: `Access to ${cls} address ${address} is blocked by egress policy.`, + } + } + if (cls === "loopback") { + if (isReservedPort(port)) { + return { + allowed: false, + addressClass: cls, + reason: `Access to protected local management port ${port} is blocked by egress policy.`, + } + } + if (isLoopbackHostName(normalized) || isGranted(normalized, port)) { + return { allowed: true, addressClass: cls } + } + return { + allowed: false, + addressClass: cls, + reason: `Blocked DNS rebinding: non-loopback host "${normalized}" resolved to loopback address ${address}.`, + } + } + if (cls === "private") { + if (isReservedPort(port)) { + return { + allowed: false, + addressClass: cls, + reason: `Access to protected private management port ${port} is blocked by egress policy.`, + } + } + if (allowPrivateLan || isGranted(normalized, port)) { + return { allowed: true, addressClass: cls } + } + return { + allowed: false, + addressClass: cls, + reason: `Access to private network target ${normalized}:${port} (${address}) is blocked by egress policy.`, + } + } + return { allowed: true, addressClass: "public" } + }, + + /** + * Resolves `target.host` once on the server, validates EVERY resolved address against policy, + * and returns the complete verified list so the socket can try another address without resolving again. + */ + async resolveTarget(target: Browser.TunnelTarget): Promise { + const normalized = normalizeHost(target.host) + if (!normalized) throw new EgressDeniedError("Target host is empty.") + if (isMetadataHost(normalized)) { + throw new EgressDeniedError(`Access to metadata host "${normalized}" is blocked by egress policy.`) + } + const literal = parseIpLiteral(normalized) + const resolved = literal ? [literal] : await (options.resolve ?? defaultResolve)(normalized) + if (resolved.length === 0) { + throw new Error(`Could not resolve target host: ${normalized}`) + } + // Every resolved address must pass policy so dual-record DNS responses cannot smuggle + // loopback, private, or metadata addresses behind a public record. + for (const candidate of resolved) { + const decision = this.evaluateAddress(normalized, target.port, candidate.address) + if (!decision.allowed) throw new EgressDeniedError(decision.reason) + } + return resolved + }, + } +} + +/** + * Connects only to verified IPs. The socket selects a reachable address when a host has several. + */ +export async function resolveAndConnect( + target: Browser.TunnelTarget, + policy: AttachmentPolicy, + options: { readonly signal?: AbortSignal; readonly timeoutMs?: number } = {}, +): Promise { + if (options.signal?.aborted) throw new Error("Browser tunnel connection was cancelled.") + const verified = await policy.resolveTarget(target) + if (options.signal?.aborted) throw new Error("Browser tunnel connection was cancelled.") + const { createConnection } = await import("node:net") + const socket = createConnection({ + host: verified.length === 1 ? verified[0].address : target.host, + autoSelectFamily: true, + lookup: (_host, options, callback) => { + if (options.all) return callback(null, [...verified]) + callback(null, verified[0].address, verified[0].family) + }, + port: target.port, + allowHalfOpen: true, + }) + const timeoutMs = options.timeoutMs ?? 10_000 + return await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + cleanup() + socket.destroy() + reject(new Error("Browser tunnel target connection timed out.")) + }, timeoutMs) + const onAbort = () => { + cleanup() + socket.destroy() + reject(new Error("Browser tunnel connection was cancelled.")) + } + const onConnect = () => { + cleanup() + socket.setNoDelay(true) + resolve(socket) + } + const onError = (error: Error) => { + cleanup() + socket.destroy() + reject(error) + } + const onClose = () => { + cleanup() + reject(new Error("Browser tunnel closed while connecting.")) + } + const cleanup = () => { + clearTimeout(timer) + options.signal?.removeEventListener("abort", onAbort) + socket.off("connect", onConnect) + socket.off("error", onError) + socket.off("close", onClose) + } + options.signal?.addEventListener("abort", onAbort, { once: true }) + socket.once("connect", onConnect) + socket.once("error", onError) + socket.once("close", onClose) + if (options.signal?.aborted) onAbort() + }) +} + +async function defaultResolve(host: string): Promise { + const { lookup } = await import("node:dns/promises") + const results = await lookup(host, { all: true, verbatim: true }) + return results + .filter((entry): entry is { address: string; family: 4 | 6 } => entry.family === 4 || entry.family === 6) + .map((entry) => ({ address: entry.address, family: entry.family })) +} + +export function normalizeHost(host: string) { + return host.trim().replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase() +} + +export function isMetadataHost(host: string) { + const normalized = normalizeHost(host) + return METADATA_HOSTS.has(normalized) || normalized.endsWith(".metadata.google.internal") +} + +export function isLoopbackHostName(host: string) { + const normalized = normalizeHost(host) + if (normalized === "localhost" || normalized.endsWith(".localhost")) return true + const literal = parseIpLiteral(normalized) + return literal !== undefined && classifyIp(literal.address) === "loopback" +} + +/** + * Parses IPv4 (including decimal, octal, hex, and shorthand forms via WHATWG URL canonicalization) + * and IPv6 literals (with optional zone IDs stripped for classification). + */ +export function parseIpLiteral(host: string): ResolvedAddress | undefined { + const normalized = normalizeHost(host) + if (!normalized) return undefined + // Strip IPv6 zone identifier if present (e.g. fe80::1%eth0) + const zoneIndex = normalized.indexOf("%") + const bare = zoneIndex >= 0 ? normalized.slice(0, zoneIndex) : normalized + const kind = isIP(bare) + if (kind === 4) return { address: bare, family: 4 } + if (kind === 6) return { address: bare, family: 6 } + // Catch non-standard IPv4 forms like 2130706433, 0x7f000001, 0177.0.0.1, 127.1 + if (!bare.includes(":") && /^[0-9a-fx.]+$/i.test(bare)) { + const parsed = URL.parse(`http://${bare}/`) + if (parsed && isIP(parsed.hostname) === 4) return { address: parsed.hostname, family: 4 } + } + return undefined +} + +export function classifyIp(input: string): AddressClass { + const zoneIndex = input.indexOf("%") + const address = (zoneIndex >= 0 ? input.slice(0, zoneIndex) : input).trim().toLowerCase() + const kind = isIP(address) + if (kind === 4) return classifyIpv4(parseIpv4(address)) + if (kind === 6) return classifyIpv6(parseIpv6(address)) + return "reserved" +} + +function parseIpv4(address: string): number { + const parts = address.split(".") + return ( + (((Number(parts[0]) << 24) >>> 0) | + ((Number(parts[1]) << 16) >>> 0) | + ((Number(parts[2]) << 8) >>> 0) | + (Number(parts[3]) >>> 0)) >>> + 0 + ) +} + +function classifyIpv4(ip: number): AddressClass { + const a = (ip >>> 24) & 0xff + const b = (ip >>> 16) & 0xff + const c = (ip >>> 8) & 0xff + const d = ip & 0xff + + // 169.254.0.0/16 (link-local & AWS/GCP/Azure IMDS) and 100.100.100.200 (Alibaba IMDS) + if (a === 169 && b === 254) return "metadata" + if (a === 100 && b === 100 && c === 100 && d === 200) return "metadata" + // 0.0.0.0/8 (unspecified), 224.0.0.0/4 (multicast), 240.0.0.0/4 (reserved + broadcast) + if (a === 0 || a >= 224) return "reserved" + // 127.0.0.0/8 (loopback) + if (a === 127) return "loopback" + // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 (CGNAT) + if (a === 10) return "private" + if (a === 172 && b >= 16 && b <= 31) return "private" + if (a === 192 && b === 168) return "private" + if (a === 100 && b >= 64 && b <= 127) return "private" + return "public" +} + +function parseIpv6(address: string): Uint8Array { + const bytes = new Uint8Array(16) + // Handle embedded IPv4 tail like ::ffff:127.0.0.1 + let working = address + const lastColon = working.lastIndexOf(":") + const tail = lastColon >= 0 ? working.slice(lastColon + 1) : "" + if (tail.includes(".")) { + const v4 = parseIpv4(tail) + const hi = ((v4 >>> 16) & 0xffff).toString(16) + const lo = (v4 & 0xffff).toString(16) + working = `${working.slice(0, lastColon)}:${hi}:${lo}` + } + const halves = working.split("::") + const left = halves[0] ? halves[0].split(":").filter(Boolean) : [] + const right = halves.length === 2 && halves[1] ? halves[1].split(":").filter(Boolean) : [] + const groups = new Uint16Array(8) + left.forEach((part, index) => { + groups[index] = parseInt(part, 16) + }) + const rightStart = 8 - right.length + right.forEach((part, index) => { + groups[rightStart + index] = parseInt(part, 16) + }) + for (let i = 0; i < 8; i++) { + bytes[i * 2] = (groups[i] >>> 8) & 0xff + bytes[i * 2 + 1] = groups[i] & 0xff + } + return bytes +} + +function classifyIpv6(bytes: Uint8Array): AddressClass { + const allZero = bytes.every((value) => value === 0) + if (allZero) return "reserved" + + // ::1 loopback + let isLoopback = bytes[15] === 1 + for (let i = 0; i < 15 && isLoopback; i++) { + if (bytes[i] !== 0) isLoopback = false + } + if (isLoopback) return "loopback" + + // ::ffff:0:0/96 (IPv4-mapped) + const isV4Mapped = + bytes[0] === 0 && + bytes[1] === 0 && + bytes[2] === 0 && + bytes[3] === 0 && + bytes[4] === 0 && + bytes[5] === 0 && + bytes[6] === 0 && + bytes[7] === 0 && + bytes[8] === 0 && + bytes[9] === 0 && + bytes[10] === 0xff && + bytes[11] === 0xff + if (isV4Mapped) return classifyIpv4(readUint32(bytes, 12)) + + // ::ffff:0:0:0/96 (IPv4-translated) + const isV4Translated = + bytes[0] === 0 && + bytes[1] === 0 && + bytes[2] === 0 && + bytes[3] === 0 && + bytes[4] === 0 && + bytes[5] === 0 && + bytes[6] === 0 && + bytes[7] === 0 && + bytes[8] === 0xff && + bytes[9] === 0xff && + bytes[10] === 0 && + bytes[11] === 0 + if (isV4Translated) return classifyIpv4(readUint32(bytes, 12)) + + // 64:ff9b::/96 (RFC 6052 NAT64) and 64:ff9b:1::/48 (RFC 8215 local NAT64) + const isNat64WellKnown = + bytes[0] === 0x00 && + bytes[1] === 0x64 && + bytes[2] === 0xff && + bytes[3] === 0x9b && + bytes[4] === 0 && + bytes[5] === 0 && + bytes[6] === 0 && + bytes[7] === 0 && + bytes[8] === 0 && + bytes[9] === 0 && + bytes[10] === 0 && + bytes[11] === 0 + if (isNat64WellKnown) return classifyIpv4(readUint32(bytes, 12)) + if (bytes[0] === 0x00 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b && bytes[4] === 0 && bytes[5] === 1) { + return classifyIpv4(readUint32(bytes, 12)) + } + + // 2002::/16 (6to4 embedding IPv4 in bytes 2..5) + if (bytes[0] === 0x20 && bytes[1] === 0x02) return classifyIpv4(readUint32(bytes, 2)) + + // fe80::/10 (link-local) + if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80) return "metadata" + // fd00:ec2::254 (AWS IPv6 IMDS) + const isAwsV6Imds = + bytes[0] === 0xfd && + bytes[1] === 0x00 && + bytes[2] === 0x0e && + bytes[3] === 0xc2 && + bytes[4] === 0 && + bytes[5] === 0 && + bytes[6] === 0 && + bytes[7] === 0 && + bytes[8] === 0 && + bytes[9] === 0 && + bytes[10] === 0 && + bytes[11] === 0 && + bytes[12] === 0 && + bytes[13] === 0 && + bytes[14] === 0x02 && + bytes[15] === 0x54 + if (isAwsV6Imds) return "metadata" + // ff00::/8 (multicast) + if (bytes[0] === 0xff) return "reserved" + // 100::/64 (RFC 6666 discard-only) + if ( + bytes[0] === 0x01 && + bytes[1] === 0x00 && + bytes[2] === 0 && + bytes[3] === 0 && + bytes[4] === 0 && + bytes[5] === 0 && + bytes[6] === 0 && + bytes[7] === 0 + ) { + return "reserved" + } + // fc00::/7 (Unique Local Address) + if ((bytes[0] & 0xfe) === 0xfc) return "private" + return "public" +} + +function readUint32(bytes: Uint8Array, offset: number) { + return ( + (((bytes[offset] << 24) >>> 0) | + ((bytes[offset + 1] << 16) >>> 0) | + ((bytes[offset + 2] << 8) >>> 0) | + (bytes[offset + 3] >>> 0)) >>> + 0 + ) +} diff --git a/packages/plugin-browser/src/proxy.ts b/packages/plugin-browser/src/proxy.ts index 1b4f2419d06..be6df46fd9b 100644 --- a/packages/plugin-browser/src/proxy.ts +++ b/packages/plugin-browser/src/proxy.ts @@ -14,30 +14,52 @@ import { Schema } from "effect" import { BrowserProxyMachine } from "./proxy-machine.js" import { Browser } from "./rpc.js" +/** Legacy chunked RPC transport. */ export type Transport = { open(target: Browser.TunnelTarget, signal: AbortSignal): Promise read(id: string, signal: AbortSignal): Promise write(id: string, data: Uint8Array, end: boolean, signal: AbortSignal): Promise close(id: string): Promise } + +/** Streaming duplex transport backed by the prewarmed binary WebSocket multiplexer. */ +export type StreamTransport = { + openStream(target: Browser.TunnelTarget, signal: AbortSignal): Promise + /** Optional hook invoked when the underlying tunnel disconnects so idle pooled sockets are evicted immediately. */ + onReset?(listener: () => void): () => void +} + +export type ProxyTransport = Transport | StreamTransport export type Proxy = Awaited> +const MAX_POOLED_ORIGINS = 64 +const MAX_SOCKETS_PER_ORIGIN = 8 +const MAX_FREE_SOCKETS_PER_ORIGIN = 6 +const IDLE_POOL_SOCKET_TIMEOUT_MS = 30_000 + +function isStreamTransport(transport: ProxyTransport): transport is StreamTransport { + return "openStream" in transport +} + // Desktop-only leaf. This listener is never loaded by the server plugin. -export async function make(transport: Transport) { +export async function make(transport: ProxyTransport) { const username = randomBytes(16).toString("hex") const password = randomBytes(32).toString("hex") const expected = Buffer.from(`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`) const clients = new Set() const tunnels = new Set() const pending = new Set() + const originPools = new Map() const closed = Promise.withResolvers() let state = BrowserProxyMachine.initial + const authorized = (value: string | undefined) => { if (!value) return false const actual = Buffer.from(value) return actual.length === expected.length && timingSafeEqual(actual, expected) } - const connect = async (target: Browser.TunnelTarget, signal: AbortSignal) => { + + const connect = async (destination: Browser.TunnelTarget, signal: AbortSignal) => { if (!BrowserProxyMachine.admits(state)) throw new Error("Browser proxy is closed") const abort = new AbortController() const cancel = () => abort.abort() @@ -45,8 +67,9 @@ export async function make(transport: Transport) { if (signal.aborted) cancel() pending.add(abort) try { - const id = await transport.open(target, abort.signal) - const socket = new TunnelSocket(transport, id) + const socket = isStreamTransport(transport) + ? await transport.openStream(destination, abort.signal) + : new TunnelSocket(transport, await transport.open(destination, abort.signal)) if (!BrowserProxyMachine.admits(state) || abort.signal.aborted) { socket.destroy() throw new Error("Browser proxy connection was cancelled") @@ -59,11 +82,84 @@ export async function make(transport: Transport) { signal.removeEventListener("abort", cancel) } } + + const clearPools = () => { + for (const agent of originPools.values()) agent.destroy() + originPools.clear() + } + + const offReset = isStreamTransport(transport) ? transport.onReset?.(clearPools) : undefined + + /** + * Returns a per-origin HTTP/1.1 keep-alive Agent scoped strictly to this attachment's proxy. + * Each origin key is canonicalized `host:port`; sockets are never shared across origins or attachments. + */ + const agentForOrigin = (destination: Browser.TunnelTarget) => { + const key = `${destination.host.toLowerCase()}:${destination.port}` + const existing = originPools.get(key) + if (existing) { + // Refresh LRU order. + originPools.delete(key) + originPools.set(key, existing) + return existing + } + if (originPools.size >= MAX_POOLED_ORIGINS) { + const oldest = originPools.keys().next().value + if (oldest !== undefined) { + originPools.get(oldest)?.destroy() + originPools.delete(oldest) + } + } + const agent = new Agent({ + keepAlive: true, + keepAliveMsecs: 15_000, + maxSockets: MAX_SOCKETS_PER_ORIGIN, + maxFreeSockets: MAX_FREE_SOCKETS_PER_ORIGIN, + timeout: IDLE_POOL_SOCKET_TIMEOUT_MS, + scheduling: "lifo", + }) + // Intercept async socket creation so each pooled socket dials through the attachment's tunnel. + const createConnection = ( + _options: unknown, + callback?: (error: Error | null, socket?: Duplex) => void, + ) => { + const abort = new AbortController() + if (!callback) throw new Error("Browser proxy pool requires async createConnection callback") + void connect(destination, abort.signal).then( + (socket) => { + // Keep an error sink on pooled sockets so an async nextTick error after `agent.destroy()` + // removes http.Agent's own listener cannot surface as an uncaught exception; active + // ClientRequests still receive the same error via their own socket error listener. + socket.on("error", () => { + if (!socket.destroyed) socket.destroy() + }) + // Half-open sockets whose upstream server closes them while idle must leave the pool immediately. + socket.once("end", () => { + if (!socket.destroyed) socket.destroy() + }) + callback(null, socket) + }, + (error: unknown) => callback(asError(error)), + ) + return undefined as unknown as Duplex + } + // SAFETY: Node's http.Agent invokes `createConnection(options, callback)` when a callback is accepted. + // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion + agent.createConnection = createConnection as unknown as typeof agent.createConnection + originPools.set(key, agent) + return agent + } + const server = createServer({ maxHeaderSize: 64 * 1024 }, (incoming, response) => { - void forward(incoming, response, connect, authorized).catch(() => { + void forward(incoming, response, agentForOrigin, authorized).catch((error: unknown) => { if (!response.headersSent) { - response.writeHead(502) - response.end() + const body = error instanceof Error ? error.message.slice(0, 256) : "Bad Gateway" + response.writeHead(502, { + connection: "close", + "content-type": "text/plain; charset=utf-8", + "content-length": String(Buffer.byteLength(body)), + }) + response.end(body) return } response.destroy() @@ -71,6 +167,7 @@ export async function make(transport: Transport) { }) server.requestTimeout = 30_000 server.headersTimeout = 10_000 + server.keepAliveTimeout = 30_000 server.on("connection", (socket) => { // A backlog connection can surface while the server drains after `close()`. if (!BrowserProxyMachine.admits(state)) { @@ -78,6 +175,7 @@ export async function make(transport: Transport) { return } clients.add(socket) + socket.setNoDelay(true) socket.on("error", () => socket.destroy()) socket.once("close", () => clients.delete(socket)) }) @@ -124,6 +222,9 @@ export async function make(transport: Transport) { ) } if (head.byteLength) tunnel.write(head) + // Attach explicit error handlers before `pipe()` so Node's pipe error handler never rethrows on teardown. + socket.on("error", () => tunnel.destroy()) + tunnel.on("error", () => socket.destroy()) socket.once("close", () => tunnel.destroy()) tunnel.once("close", () => socket.destroy()) socket.pipe(tunnel) @@ -156,10 +257,13 @@ export async function make(transport: Transport) { host: "127.0.0.1", port: address.port, credentials: { username, password }, + resetPools: clearPools, close() { const next = BrowserProxyMachine.transition(state, { type: "close" }) state = next.state next.effects.forEach(() => { + offReset?.() + clearPools() pending.forEach((abort) => abort.abort()) tunnels.forEach((socket) => socket.destroy()) clients.forEach((socket) => socket.destroy()) @@ -173,52 +277,75 @@ export async function make(transport: Transport) { async function forward( incoming: IncomingMessage, response: ServerResponse, - connect: (target: Browser.TunnelTarget, signal: AbortSignal) => Promise, + agentForOrigin: (target: Browser.TunnelTarget) => Agent, authorized: (value: string | undefined) => boolean, ) { if (!authorized(incoming.headers["proxy-authorization"])) { - response.writeHead(407, { "Proxy-Authenticate": 'Basic realm="OpenCode Browser Proxy"' }) + response.writeHead(407, { + "Proxy-Authenticate": 'Basic realm="OpenCode Browser Proxy"', + "Content-Length": "0", + Connection: "close", + }) response.end() return } const url = parseURL(incoming.url) if (!url || url.protocol !== "http:") { - response.writeHead(400) + response.writeHead(400, { "Content-Length": "0", Connection: "close" }) response.end() return } + const destination = target(url) + const agent = agentForOrigin(destination) const abort = new AbortController() - const cancel = () => abort.abort() + let finished = false + const cancel = () => { + if (!finished) abort.abort() + } incoming.once("aborted", cancel) response.once("close", cancel) - const agent = new Agent({ keepAlive: false, maxSockets: 1 }) - // An abort before the request adopts the tunnel leaves it out of `agent.destroy()`. - let opened: Duplex | undefined + const headers = forwardedHeaders(incoming.headers) + headers.host = url.host + // Keep upstream HTTP/1.1 connections warm per origin/attachment; Node's Agent honours upstream `Connection: close`. + headers.connection = "keep-alive" + const clientWantsClose = + incoming.httpVersion === "1.0" || + /\bclose\b/i.test(incoming.headers.connection ?? "") || + /\bclose\b/i.test(String(incoming.headers["proxy-connection"] ?? "")) + try { - const tunnel = await connect(target(url), abort.signal) - opened = tunnel - agent.createConnection = () => tunnel - const headers = forwardedHeaders(incoming.headers) - headers.host = url.host - headers.connection = "close" await new Promise((resolve, reject) => { const upstream = request( { agent, hostname: url.hostname, - port: url.port || 80, + port: destination.port, path: `${url.pathname}${url.search}`, method: incoming.method, headers, signal: abort.signal, }, (result) => { - response.writeHead(result.statusCode ?? 502, result.statusMessage, { - ...forwardedHeaders(result.headers), - connection: "close", + const status = result.statusCode ?? 502 + const bodyless = status === 204 || status === 304 || incoming.method === "HEAD" + const explicitLength = + result.headers["content-length"] !== undefined || result.headers["transfer-encoding"] !== undefined + const responseHeaders = forwardedHeaders(result.headers) + // Keep the local Chromium <-> proxy connection alive whenever framing is explicit and client allows it. + if (clientWantsClose || (!bodyless && !explicitLength)) { + responseHeaders.connection = "close" + } else { + responseHeaders.connection = "keep-alive" + } + response.writeHead(status, result.statusMessage, responseHeaders) + result.once("error", (error) => { + upstream.destroy() + reject(error) + }) + response.once("finish", () => { + finished = true + resolve() }) - result.once("error", reject) - response.once("finish", resolve) result.pipe(response) }, ) @@ -228,8 +355,6 @@ async function forward( } finally { incoming.off("aborted", cancel) response.off("close", cancel) - agent.destroy() - opened?.destroy() } } @@ -268,6 +393,7 @@ class TunnelSocket extends Duplex { readonly connecting = false private readonly abort = new AbortController() private reads: BrowserProxyMachine.ReadState = "idle" + private idleTimer?: ReturnType constructor( private readonly transport: Transport, @@ -318,6 +444,10 @@ class TunnelSocket extends Duplex { ) } override _destroy(error: Error | null, callback: (error?: Error | null) => void) { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = undefined + } this.advance("destroyed") this.abort.abort() void this.transport @@ -331,8 +461,21 @@ class TunnelSocket extends Duplex { setNoDelay() { return this } - setTimeout(_timeout: number, callback?: () => void) { + setTimeout(timeout: number, callback?: () => void) { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = undefined + } + if (timeout === 0) { + if (callback) this.off("timeout", callback) + return this + } if (callback) this.once("timeout", callback) + this.idleTimer = setTimeout(() => { + this.idleTimer = undefined + this.emit("timeout") + }, timeout) + this.idleTimer.unref?.() return this } ref() { diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 1d0c710bfcc..b3e213070e9 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -721,9 +721,22 @@ const tunnel = { ...attachment, tunnelID: short } const bytes = Schema.Uint8ArrayFromBase64.check(Schema.isMaxLength(TUNNEL_CHUNK_BYTES)) export const TunnelRead = Schema.Struct({ data: bytes, eof: Schema.Boolean }) export type TunnelRead = typeof TunnelRead.Type +export const TunnelTicket = Schema.Struct({ + ticket: short, + expiresIn: count, + protocol: Schema.Literal(1), + path: Schema.Literal("/api/experimental/browser/tunnel"), +}) +export type TunnelTicket = typeof TunnelTicket.Type +const portNumber = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_535 })) const errors = { unavailable: Schema.Struct({}) } export const Control = Schema.Union([ - Schema.Struct({ type: Schema.Literal("attached"), connectionID: Schema.String, version: Schema.Literal(4) }), + Schema.Struct({ + type: Schema.Literal("attached"), + connectionID: Schema.String, + version: Schema.Literal(4), + capabilities: optional(Schema.Array(short)), + }), Schema.Struct({ type: Schema.Literal("command"), connectionID: Schema.String, @@ -745,6 +758,16 @@ export const Definition = Rpc.define({ state: { input: Schema.Struct({ ...attachment, state: State }), output: Schema.Void, errors }, command: { input: Schema.Struct(request), output: Command, errors }, result: { input: Schema.Struct({ ...request, outcome: Outcome }), output: Schema.Void, errors }, + "tunnel.ticket": { + input: Schema.Struct({ ...attachment, protocol: Schema.Literal(1) }), + output: TunnelTicket, + errors, + }, + "tunnel.grant": { + input: Schema.Struct({ ...attachment, target: TunnelTarget, ports: optional(Schema.Array(portNumber)) }), + output: Schema.Void, + errors, + }, "tunnel.open": { input: Schema.Struct({ ...attachment, target: TunnelTarget }), output: short, errors }, "tunnel.read": { input: Schema.Struct(tunnel), output: TunnelRead, errors }, "tunnel.write": { diff --git a/packages/plugin-browser/src/stream-mux.ts b/packages/plugin-browser/src/stream-mux.ts new file mode 100644 index 00000000000..dd9214d6fd6 --- /dev/null +++ b/packages/plugin-browser/src/stream-mux.ts @@ -0,0 +1,1275 @@ +export * as StreamMux from "./stream-mux.js" + +import { randomBytes } from "node:crypto" +import type { Socket } from "node:net" +import { Duplex } from "node:stream" +import { EgressPolicy } from "./egress-policy.js" +import type { Browser } from "./rpc.js" +import { StreamWire } from "./stream-wire.js" +import { BrowserTunnelHost } from "./tunnel-host.js" + +export interface MuxOptions { + /** Per-stream receive window advertised to peer. Default 1.5 MiB. */ + readonly streamWindowBytes?: number + /** Batch threshold for sending WINDOW_UPDATE credits. Default min(256 KiB, window / 4). */ + readonly creditBatchBytes?: number + /** Maximum DATA payload bytes per frame. Default 16 KiB. */ + readonly frameChunkBytes?: number + /** Maximum bytes allowed in WebSocket library bufferedAmount for DATA frames. Default 256 KiB. */ + readonly maxWsBufferedBytes?: number + /** Maximum concurrent streams for this attachment. Default 128. */ + readonly maxStreams?: number + /** Maximum concurrent in-flight TCP connects for this attachment. Default 32. */ + readonly maxPendingConnects?: number + /** Maximum total buffered bytes across all streams of this attachment. Default 8 MiB. */ + readonly maxAttachmentBufferedBytes?: number + /** Per-stream outbound pause high-water mark. Default 256 KiB. */ + readonly streamOutboundHighWaterBytes?: number + /** Heartbeat interval in milliseconds (0 disables heartbeat timer). Default 25000. */ + readonly heartbeatIntervalMs?: number + /** Disconnect if peer is silent for longer than this (ms). Default 60000. */ + readonly heartbeatTimeoutMs?: number + /** Cross-attachment global resource limits. */ + readonly globalLimits?: BrowserTunnelHost.GlobalLimits +} + +export interface ServerMuxOptions extends MuxOptions { + readonly policy: EgressPolicy.AttachmentPolicy + /** TCP connect timeout per stream in milliseconds. Default 10000. */ + readonly connectTimeoutMs?: number + /** Optional custom connector (for deterministic tests). */ + readonly connect?: ( + target: Browser.TunnelTarget, + policy: EgressPolicy.AttachmentPolicy, + options: { readonly signal?: AbortSignal; readonly timeoutMs?: number }, + ) => Promise +} + +export interface MuxCloseInfo { + readonly code: number + readonly reason: string + readonly replaced: boolean +} + +export interface ServerMux { + readonly closed: Promise + readonly activeStreams: () => number + readonly bufferedBytes: () => number + close(code?: number, reason?: string): void +} + +export interface ClientMux { + readonly closed: Promise + readonly activeStreams: () => number + readonly bufferedBytes: () => number + readonly isClosed: () => boolean + openStream(target: Browser.TunnelTarget, signal?: AbortSignal): Promise + ping(): void + close(code?: number, reason?: string): void +} + +interface WritableStream { + inRoundRobin: boolean + hasWritableOutput(): boolean + nextOutboundFrame(): Uint8Array | undefined +} + +const WS_OPEN = 1 +const MAX_INFLIGHT_WS_SENDS = 16 +const DRAIN_RETRY_MS = 4 + +function resolveConfig(options: MuxOptions) { + const streamWindowBytes = clamp( + options.streamWindowBytes ?? StreamWire.DEFAULT_STREAM_WINDOW_BYTES, + 4096, + StreamWire.MAX_STREAM_WINDOW_BYTES, + ) + const creditBatchBytes = Math.max( + 1, + Math.min(options.creditBatchBytes ?? Math.min(256 * 1024, Math.floor(streamWindowBytes / 4)), streamWindowBytes), + ) + const frameChunkBytes = clamp( + options.frameChunkBytes ?? StreamWire.FRAME_DATA_CHUNK_BYTES, + 1024, + StreamWire.MAX_FRAME_PAYLOAD_BYTES, + ) + const maxWsBufferedBytes = Math.max(frameChunkBytes, options.maxWsBufferedBytes ?? StreamWire.MAX_WS_BUFFERED_BYTES) + const maxStreams = Math.max(1, options.maxStreams ?? StreamWire.MAX_STREAMS_PER_ATTACHMENT) + const maxPendingConnects = Math.max(1, options.maxPendingConnects ?? StreamWire.MAX_PENDING_CONNECTS_PER_ATTACHMENT) + const maxAttachmentBufferedBytes = Math.max( + streamWindowBytes, + options.maxAttachmentBufferedBytes ?? StreamWire.MAX_ATTACHMENT_BUFFERED_BYTES, + ) + const streamOutboundHighWaterBytes = Math.max( + frameChunkBytes, + options.streamOutboundHighWaterBytes ?? Math.min(256 * 1024, streamWindowBytes), + ) + const streamOutboundLowWaterBytes = Math.max(frameChunkBytes, Math.floor(streamOutboundHighWaterBytes / 2)) + const heartbeatIntervalMs = options.heartbeatIntervalMs ?? 25_000 + const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 60_000 + const globalLimits = options.globalLimits ?? BrowserTunnelHost.defaultGlobalLimits + + return { + streamWindowBytes, + creditBatchBytes, + frameChunkBytes, + maxWsBufferedBytes, + maxStreams, + maxPendingConnects, + maxAttachmentBufferedBytes, + streamOutboundHighWaterBytes, + streamOutboundLowWaterBytes, + heartbeatIntervalMs, + heartbeatTimeoutMs, + globalLimits, + } +} + +/** + * Single-writer frame scheduler: + * - Always drains priority control frames first (OPEN, OPENED, WINDOW_UPDATE, RESET, PING, PONG, GOAWAY). + * - Serves writable streams strictly round-robin, one bounded DATA frame per turn. + * - Never pushes DATA frames once `socket.bufferedAmount >= maxWsBufferedBytes`, preventing a bulk + * download from burying interactive HMR/control traffic inside the WebSocket library or TCP send buffer. + */ +function createFrameWriter( + socket: BrowserTunnelHost.BinarySocket, + maxWsBufferedBytes: number, + onWriteError: (error: Error) => void, +) { + const controlQueue: Uint8Array[] = [] + const roundRobin: WritableStream[] = [] + let closed = false + let inFlightSends = 0 + let pumping = false + let drainTimer: ReturnType | undefined + + const scheduleDrainCheck = () => { + if (closed || drainTimer) return + drainTimer = setTimeout(() => { + drainTimer = undefined + pump() + }, DRAIN_RETRY_MS) + drainTimer.unref?.() + } + + const pump = () => { + if (closed || pumping || socket.readyState !== WS_OPEN) return + pumping = true + try { + while (!closed && socket.readyState === WS_OPEN && inFlightSends < MAX_INFLIGHT_WS_SENDS) { + const buffered = socket.bufferedAmount + // Priority control frames (WINDOW_UPDATE, RESET, PING/PONG) may still transmit up to 2x cap + // so neither side can deadlock waiting for credits while DATA is paused. + if (controlQueue.length > 0 && (inFlightSends === 0 || buffered < maxWsBufferedBytes * 2)) { + const frame = controlQueue.shift()! + sendOne(frame) + continue + } + if (buffered >= maxWsBufferedBytes) { + scheduleDrainCheck() + break + } + if (roundRobin.length === 0) break + const stream = roundRobin.shift()! + stream.inRoundRobin = false + const frame = stream.nextOutboundFrame() + if (stream.hasWritableOutput() && !stream.inRoundRobin) { + stream.inRoundRobin = true + roundRobin.push(stream) + } + if (frame) sendOne(frame) + } + } finally { + pumping = false + } + } + + const sendOne = (frame: Uint8Array) => { + inFlightSends += 1 + try { + socket.send(frame, (error) => { + inFlightSends = Math.max(0, inFlightSends - 1) + if (error && !closed) { + onWriteError(error) + return + } + pump() + }) + } catch (error) { + inFlightSends = Math.max(0, inFlightSends - 1) + onWriteError(asError(error)) + } + } + + return { + enqueueControl(frame: StreamWire.Frame) { + if (closed) return + controlQueue.push(StreamWire.encodeFrame(frame)) + pump() + }, + markWritable(stream: WritableStream) { + if (closed || stream.inRoundRobin || !stream.hasWritableOutput()) return + stream.inRoundRobin = true + roundRobin.push(stream) + pump() + }, + kick() { + pump() + }, + close() { + closed = true + controlQueue.length = 0 + roundRobin.length = 0 + if (drainTimer) { + clearTimeout(drainTimer) + drainTimer = undefined + } + }, + } +} + +function startHeartbeat( + socket: BrowserTunnelHost.BinarySocket, + writer: ReturnType, + intervalMs: number, + timeoutMs: number, + onTimeout: () => void, +) { + let lastHeard = Date.now() + const heard = () => { + lastHeard = Date.now() + } + const offPong = socket.onPong?.(heard) + let timer: ReturnType | undefined + if (intervalMs > 0) { + timer = setInterval(() => { + if (Date.now() - lastHeard > timeoutMs) { + onTimeout() + return + } + if (socket.readyState !== WS_OPEN) return + socket.ping?.() + writer.enqueueControl({ type: StreamWire.FrameType.PING, token: randomBytes(8) }) + }, intervalMs) + timer.unref?.() + } + return { + heard, + stop() { + if (timer) { + clearInterval(timer) + timer = undefined + } + offPong?.() + }, + } +} + +/** + * Server-side multiplexed stream owner bound to one live desktop browser attachment. + * Enforces egress policy, per-attachment and cross-attachment caps, credit-based flow control, + * half-close, RESET cancellation, and clean teardown of every owned target TCP socket on close. + */ +export function createServerMux(socket: BrowserTunnelHost.BinarySocket, options: ServerMuxOptions): ServerMux { + const cfg = resolveConfig(options) + const connectTarget = options.connect ?? EgressPolicy.resolveAndConnect + const closedDeferred = Promise.withResolvers() + let closed = false + let attachmentBytes = 0 + let pendingConnects = 0 + + type ServerStream = WritableStream & { + readonly id: number + status: "connecting" | "open" | "closed" + readonly connectAbort: AbortController + target?: Socket + sendWindow: number + recvWindow: number + consumedSinceCredit: number + inboundPendingBytes: number + readonly outboundChunks: Uint8Array[] + outboundOffset: number + outboundBytes: number + outboundFinPending: boolean + outboundFinSent: boolean + inboundFinReceived: boolean + paused: boolean + } + + const streams = new Map() + + const reserveBytes = (bytes: number) => { + if (bytes <= 0) return true + if (attachmentBytes + bytes > cfg.maxAttachmentBufferedBytes) return false + if (!cfg.globalLimits.tryReserveBytes(bytes)) return false + attachmentBytes += bytes + return true + } + + const releaseBytes = (bytes: number) => { + if (bytes <= 0) return + attachmentBytes = Math.max(0, attachmentBytes - bytes) + cfg.globalLimits.releaseBytes(bytes) + } + + const writer = createFrameWriter(socket, cfg.maxWsBufferedBytes, () => { + shutdown(1006, "write failed", false) + }) + + const heartbeat = startHeartbeat(socket, writer, cfg.heartbeatIntervalMs, cfg.heartbeatTimeoutMs, () => { + shutdown(1001, "heartbeat timeout", true) + }) + + const cleanupStream = (stream: ServerStream, sendReset?: { readonly code: StreamWire.ResetCodeValue; readonly reason: string }) => { + if (stream.status === "closed") return + const wasConnecting = stream.status === "connecting" + stream.status = "closed" + streams.delete(stream.id) + cfg.globalLimits.releaseStream() + if (wasConnecting) { + pendingConnects = Math.max(0, pendingConnects - 1) + cfg.globalLimits.releasePendingConnect() + stream.connectAbort.abort() + } + if (stream.inboundPendingBytes > 0) { + releaseBytes(stream.inboundPendingBytes) + stream.inboundPendingBytes = 0 + } + if (stream.outboundBytes > 0) { + releaseBytes(stream.outboundBytes) + stream.outboundBytes = 0 + } + stream.outboundChunks.length = 0 + stream.outboundOffset = 0 + stream.target?.destroy() + stream.target = undefined + if (sendReset && !closed) { + writer.enqueueControl({ + type: StreamWire.FrameType.RESET, + streamID: stream.id, + code: sendReset.code, + reason: sendReset.reason, + }) + } + } + + const maybeFinishStream = (stream: ServerStream) => { + if (stream.status === "open" && stream.inboundFinReceived && stream.outboundFinSent) { + cleanupStream(stream) + } + } + + const protocolFail = (reason: string) => { + if (closed) return + writer.enqueueControl({ type: StreamWire.FrameType.GOAWAY, code: StreamWire.ResetCode.PROTOCOL_ERROR, reason }) + shutdown(1002, reason, false) + } + + const handleOpen = (frame: Extract) => { + if (streams.has(frame.streamID)) { + protocolFail(`Duplicate streamID ${frame.streamID}.`) + return + } + if (streams.size >= cfg.maxStreams || pendingConnects >= cfg.maxPendingConnects) { + writer.enqueueControl({ + type: StreamWire.FrameType.RESET, + streamID: frame.streamID, + code: StreamWire.ResetCode.LIMIT_EXCEEDED, + reason: "Browser attachment stream limit exceeded.", + }) + return + } + if (!cfg.globalLimits.tryAcquireStream()) { + writer.enqueueControl({ + type: StreamWire.FrameType.RESET, + streamID: frame.streamID, + code: StreamWire.ResetCode.LIMIT_EXCEEDED, + reason: "Server browser stream capacity reached.", + }) + return + } + if (!cfg.globalLimits.tryAcquirePendingConnect()) { + cfg.globalLimits.releaseStream() + writer.enqueueControl({ + type: StreamWire.FrameType.RESET, + streamID: frame.streamID, + code: StreamWire.ResetCode.LIMIT_EXCEEDED, + reason: "Server pending connect capacity reached.", + }) + return + } + pendingConnects += 1 + + const stream: ServerStream = { + id: frame.streamID, + status: "connecting", + connectAbort: new AbortController(), + sendWindow: frame.initialWindow, + recvWindow: cfg.streamWindowBytes, + consumedSinceCredit: 0, + inboundPendingBytes: 0, + outboundChunks: [], + outboundOffset: 0, + outboundBytes: 0, + outboundFinPending: false, + outboundFinSent: false, + inboundFinReceived: false, + paused: false, + inRoundRobin: false, + hasWritableOutput() { + if (stream.status !== "open") return false + if (stream.outboundBytes > 0 && stream.sendWindow > 0) return true + return stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent + }, + nextOutboundFrame() { + if (stream.status !== "open") return undefined + if (stream.outboundBytes > 0 && stream.sendWindow > 0) { + const maxTake = Math.min(cfg.frameChunkBytes, stream.sendWindow) + const slice = takeChunk(stream.outboundChunks, stream.outboundOffset, maxTake) + stream.outboundOffset = slice.nextOffset + stream.outboundBytes -= slice.bytes.byteLength + stream.sendWindow -= slice.bytes.byteLength + releaseBytes(slice.bytes.byteLength) + if (stream.paused && stream.outboundBytes <= cfg.streamOutboundLowWaterBytes && stream.sendWindow > 0) { + stream.paused = false + stream.target?.resume() + } + return StreamWire.encodeFrame({ + type: StreamWire.FrameType.DATA, + streamID: stream.id, + data: slice.bytes, + }) + } + if (stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent) { + stream.outboundFinSent = true + const encoded = StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: stream.id }) + maybeFinishStream(stream) + return encoded + } + return undefined + }, + } + streams.set(stream.id, stream) + + void connectTarget( + { host: frame.host, port: frame.port }, + options.policy, + { signal: stream.connectAbort.signal, timeoutMs: options.connectTimeoutMs ?? 10_000 }, + ).then( + (targetSocket) => { + if (closed || stream.status !== "connecting") { + targetSocket.destroy() + return + } + pendingConnects = Math.max(0, pendingConnects - 1) + cfg.globalLimits.releasePendingConnect() + stream.status = "open" + stream.target = targetSocket + + writer.enqueueControl({ + type: StreamWire.FrameType.OPENED, + streamID: stream.id, + initialWindow: stream.recvWindow, + }) + + targetSocket.on("data", (chunk: Buffer) => { + if (closed || stream.status !== "open") return + const copy = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength).slice() + if (!reserveBytes(copy.byteLength)) { + cleanupStream(stream, { + code: StreamWire.ResetCode.LIMIT_EXCEEDED, + reason: "Attachment buffer limit exceeded.", + }) + return + } + stream.outboundChunks.push(copy) + stream.outboundBytes += copy.byteLength + if (stream.outboundBytes >= cfg.streamOutboundHighWaterBytes || stream.sendWindow === 0) { + stream.paused = true + targetSocket.pause() + } + writer.markWritable(stream) + }) + + targetSocket.once("end", () => { + if (closed || stream.status !== "open") return + stream.outboundFinPending = true + writer.markWritable(stream) + }) + + targetSocket.on("error", (error: Error) => { + if (closed || stream.status !== "open") return + cleanupStream(stream, { code: StreamWire.ResetCode.INTERNAL_ERROR, reason: error.message.slice(0, 200) }) + }) + + targetSocket.once("close", (hadError: boolean) => { + if (closed || stream.status !== "open") return + if (hadError) { + cleanupStream(stream, { code: StreamWire.ResetCode.INTERNAL_ERROR, reason: "Target socket closed with error." }) + return + } + if (!stream.outboundFinPending && !stream.outboundFinSent) { + stream.outboundFinPending = true + writer.markWritable(stream) + } + }) + }, + (cause: unknown) => { + if (closed || stream.status !== "connecting") return + const error = asError(cause) + const code = + error instanceof EgressPolicy.EgressDeniedError + ? StreamWire.ResetCode.POLICY_DENIED + : StreamWire.ResetCode.CONNECT_FAILED + cleanupStream(stream, { code, reason: error.message.slice(0, 200) }) + }, + ) + } + + const handleData = (frame: Extract) => { + const stream = streams.get(frame.streamID) + if (!stream) return + if (stream.status !== "open" || !stream.target || stream.inboundFinReceived) { + cleanupStream(stream, { code: StreamWire.ResetCode.PROTOCOL_ERROR, reason: "DATA on non-writable stream." }) + return + } + const len = frame.data.byteLength + if (len > stream.recvWindow) { + cleanupStream(stream, { code: StreamWire.ResetCode.PROTOCOL_ERROR, reason: "Stream receive window exceeded." }) + return + } + if (!reserveBytes(len)) { + cleanupStream(stream, { code: StreamWire.ResetCode.LIMIT_EXCEEDED, reason: "Attachment inbound buffer limit exceeded." }) + return + } + stream.recvWindow -= len + stream.inboundPendingBytes += len + let drained = false + // Never block the shared WS reader: hand bytes to target TCP socket and replenish credits + // in batches once the target socket drains them. + stream.target.write(frame.data, (error) => { + if (drained) return + drained = true + if (stream.inboundPendingBytes >= len) { + stream.inboundPendingBytes -= len + releaseBytes(len) + } + if (closed || stream.status !== "open") return + if (error) { + cleanupStream(stream, { code: StreamWire.ResetCode.INTERNAL_ERROR, reason: error.message.slice(0, 200) }) + return + } + stream.consumedSinceCredit += len + if (!stream.inboundFinReceived && stream.consumedSinceCredit >= cfg.creditBatchBytes) { + const delta = stream.consumedSinceCredit + stream.consumedSinceCredit = 0 + stream.recvWindow += delta + writer.enqueueControl({ type: StreamWire.FrameType.WINDOW_UPDATE, streamID: stream.id, delta }) + } + }) + } + + const handleWindowUpdate = ( + frame: Extract, + ) => { + const stream = streams.get(frame.streamID) + if (!stream || stream.status === "closed") return + if (stream.sendWindow + frame.delta > StreamWire.MAX_STREAM_WINDOW_BYTES) { + cleanupStream(stream, { code: StreamWire.ResetCode.PROTOCOL_ERROR, reason: "Send window overflow." }) + return + } + stream.sendWindow += frame.delta + if (stream.status === "open") { + writer.markWritable(stream) + if (stream.paused && stream.outboundBytes <= cfg.streamOutboundLowWaterBytes && stream.sendWindow > 0) { + stream.paused = false + stream.target?.resume() + } + } + } + + const handleFin = (frame: Extract) => { + const stream = streams.get(frame.streamID) + if (!stream || stream.status !== "open" || !stream.target) return + if (stream.inboundFinReceived) return + stream.inboundFinReceived = true + stream.target.end() + maybeFinishStream(stream) + } + + const handleReset = (frame: Extract) => { + const stream = streams.get(frame.streamID) + if (!stream) return + cleanupStream(stream) + } + + const offMessage = socket.onMessage((raw) => { + if (closed) return + heartbeat.heard() + if (typeof raw === "string") { + protocolFail("Text WebSocket frames are not permitted on browser stream tunnel.") + return + } + let frame: StreamWire.Frame + try { + frame = StreamWire.decodeFrame(raw) + } catch (error) { + protocolFail(asError(error).message) + return + } + switch (frame.type) { + case StreamWire.FrameType.OPEN: + handleOpen(frame) + return + case StreamWire.FrameType.DATA: + handleData(frame) + return + case StreamWire.FrameType.WINDOW_UPDATE: + handleWindowUpdate(frame) + return + case StreamWire.FrameType.FIN: + handleFin(frame) + return + case StreamWire.FrameType.RESET: + handleReset(frame) + return + case StreamWire.FrameType.PING: + writer.enqueueControl({ type: StreamWire.FrameType.PONG, token: frame.token }) + return + case StreamWire.FrameType.PONG: + return + case StreamWire.FrameType.GOAWAY: + shutdown(1000, frame.reason || "peer goaway", false) + return + case StreamWire.FrameType.OPENED: + protocolFail("Client may not send OPENED frames.") + return + } + }) + + const offClose = socket.onClose((code, reason) => { + shutdown(code, reason, false) + }) + + const offError = socket.onError((error) => { + shutdown(1006, error.message, true) + }) + + function shutdown(code: number, reason: string, terminate: boolean) { + if (closed) return + closed = true + heartbeat.stop() + offMessage() + offClose() + offError() + for (const stream of Array.from(streams.values())) { + cleanupStream(stream) + } + writer.close() + try { + if (terminate) socket.terminate() + else if (socket.readyState === WS_OPEN) socket.close(code, reason.slice(0, 120)) + } catch { + // Socket may already be closing or destroyed. + } + closedDeferred.resolve({ + code, + reason, + replaced: code === BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED, + }) + } + + return { + closed: closedDeferred.promise, + activeStreams: () => streams.size, + bufferedBytes: () => attachmentBytes, + close(code = BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED, reason = "attachment closed") { + if (closed) return + if (socket.readyState === WS_OPEN) { + try { + socket.send( + StreamWire.encodeFrame({ + type: StreamWire.FrameType.GOAWAY, + code: StreamWire.ResetCode.ATTACHMENT_CLOSED, + reason, + }), + ) + } catch { + // Best-effort GOAWAY before closing. + } + } + shutdown(code, reason, false) + }, + } +} + +/** + * Desktop-side multiplexed stream client bound to one prewarmed binary WebSocket. + * Returns standard Node `Duplex` sockets per target TCP connection with end-to-end + * credit backpressure, half-close, RESET cancellation, and zero automatic replay of writes. + */ +export function createClientMux(socket: BrowserTunnelHost.BinarySocket, options: MuxOptions = {}): ClientMux { + const cfg = resolveConfig({ + streamWindowBytes: StreamWire.DEFAULT_CLIENT_STREAM_WINDOW_BYTES, + ...options, + }) + const closedDeferred = Promise.withResolvers() + let closed = false + let closeReason = "Browser tunnel disconnected." + let nextStreamID = 1 + let attachmentBytes = 0 + let pendingConnects = 0 + + type ClientStream = WritableStream & { + readonly id: number + status: "opening" | "open" | "closed" + readonly opened: ReturnType> + duplex?: StreamDuplex + sendWindow: number + recvWindow: number + consumedSinceCredit: number + readonly inboundChunks: Uint8Array[] + inboundBytes: number + inboundFinReceived: boolean + readonly outboundChunks: Uint8Array[] + outboundOffset: number + outboundBytes: number + outboundFinPending: boolean + outboundFinSent: boolean + writeResume?: (error?: Error | null) => void + finalCallback?: (error?: Error | null) => void + } + + const streams = new Map() + + const reserveBytes = (bytes: number) => { + if (bytes <= 0) return true + if (attachmentBytes + bytes > cfg.maxAttachmentBufferedBytes) return false + attachmentBytes += bytes + return true + } + + const releaseBytes = (bytes: number) => { + if (bytes <= 0) return + attachmentBytes = Math.max(0, attachmentBytes - bytes) + } + + const writer = createFrameWriter(socket, cfg.maxWsBufferedBytes, (error) => { + shutdown(1006, error.message, true) + }) + + const heartbeat = startHeartbeat(socket, writer, cfg.heartbeatIntervalMs, cfg.heartbeatTimeoutMs, () => { + shutdown(1001, "Browser tunnel heartbeat timed out.", true) + }) + + const cleanupStream = ( + stream: ClientStream, + input: { + readonly error?: Error + readonly normalClose?: boolean + readonly sendReset?: StreamWire.ResetCodeValue + readonly resetReason?: string + } = {}, + ) => { + if (stream.status === "closed") return + const wasOpening = stream.status === "opening" + stream.status = "closed" + streams.delete(stream.id) + if (wasOpening) pendingConnects = Math.max(0, pendingConnects - 1) + if (stream.outboundBytes > 0) { + releaseBytes(stream.outboundBytes) + stream.outboundBytes = 0 + } + if (stream.inboundBytes > 0) { + releaseBytes(stream.inboundBytes) + stream.inboundBytes = 0 + } + stream.outboundChunks.length = 0 + stream.outboundOffset = 0 + stream.inboundChunks.length = 0 + + const writeResume = stream.writeResume + stream.writeResume = undefined + const finalCallback = stream.finalCallback + stream.finalCallback = undefined + + if (input.sendReset !== undefined && !closed) { + writer.enqueueControl({ + type: StreamWire.FrameType.RESET, + streamID: stream.id, + code: input.sendReset, + reason: input.resetReason ?? "", + }) + } + if (wasOpening) { + stream.opened.reject(input.error ?? new Error("Browser tunnel stream closed while opening.")) + } + const duplex = stream.duplex + stream.duplex = undefined + + const streamError = input.error ?? new Error("Browser tunnel stream closed.") + if (input.normalClose) { + // Destroy first so Node/Bun never emit an uncaught async 'error' event on idle or unpiped sockets, + // then settle any outstanding write/FIN callbacks with the cancellation error so discarded bytes + // are never reported as delivered. + if (duplex && !duplex.destroyed) duplex.destroy() + if (writeResume) writeResume(streamError) + if (finalCallback) finalCallback(streamError) + return + } + + if (duplex && !duplex.destroyed) { + // Settle pending write/final callbacks with the genuine error before destroying, or destroy with error. + if (writeResume) writeResume(streamError) + if (finalCallback) finalCallback(streamError) + if (!duplex.destroyed) { + if (input.error && duplex.listenerCount("error") > 0) duplex.destroy(input.error) + else duplex.destroy() + } + return + } + if (writeResume) writeResume(streamError) + if (finalCallback) finalCallback(streamError) + } + + const maybeFinishStream = (stream: ClientStream) => { + if (stream.status === "open" && stream.inboundFinReceived && stream.inboundBytes === 0 && stream.outboundFinSent) { + stream.status = "closed" + streams.delete(stream.id) + } + } + + class StreamDuplex extends Duplex { + readonly connecting = false + private reading = false + private idleTimer?: ReturnType + + constructor(private readonly stream: ClientStream) { + super({ highWaterMark: cfg.frameChunkBytes * 4, allowHalfOpen: true }) + } + + drainInbound() { + if (!this.reading || this.destroyed) return + while (this.stream.inboundChunks.length > 0) { + const chunk = this.stream.inboundChunks.shift()! + this.stream.inboundBytes -= chunk.byteLength + releaseBytes(chunk.byteLength) + this.stream.consumedSinceCredit += chunk.byteLength + if (!this.stream.inboundFinReceived && this.stream.consumedSinceCredit >= cfg.creditBatchBytes) { + const delta = this.stream.consumedSinceCredit + this.stream.consumedSinceCredit = 0 + this.stream.recvWindow += delta + writer.enqueueControl({ + type: StreamWire.FrameType.WINDOW_UPDATE, + streamID: this.stream.id, + delta, + }) + } + const more = this.push(chunk) + if (!more) { + this.reading = false + return + } + } + if (this.stream.inboundFinReceived) { + this.reading = false + this.push(null) + maybeFinishStream(this.stream) + } + } + + override _read() { + this.reading = true + this.drainInbound() + } + + override _write(chunk: Buffer | string, encoding: BufferEncoding, callback: (error?: Error | null) => void) { + if (closed || this.stream.status !== "open") { + callback(new Error(closeReason)) + return + } + const data = typeof chunk === "string" ? Buffer.from(chunk, encoding) : chunk + if (data.byteLength === 0) { + callback() + return + } + if (!reserveBytes(data.byteLength)) { + const error = new Error("Browser tunnel attachment buffer limit exceeded.") + cleanupStream(this.stream, { error, sendReset: StreamWire.ResetCode.LIMIT_EXCEEDED }) + callback(error) + return + } + const copy = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice() + this.stream.outboundChunks.push(copy) + this.stream.outboundBytes += copy.byteLength + writer.markWritable(this.stream) + if (this.stream.outboundBytes >= cfg.streamOutboundHighWaterBytes) { + this.stream.writeResume = callback + return + } + callback() + } + + override _final(callback: (error?: Error | null) => void) { + if (closed || this.stream.status !== "open") { + callback(new Error(closeReason)) + return + } + this.stream.outboundFinPending = true + this.stream.finalCallback = callback + writer.markWritable(this.stream) + } + + override _destroy(error: Error | null, callback: (error?: Error | null) => void) { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = undefined + } + if (this.stream.status !== "closed") { + const clean = this.stream.inboundFinReceived && this.stream.inboundBytes === 0 && this.stream.outboundFinSent + cleanupStream(this.stream, { + error: error ?? undefined, + sendReset: clean ? undefined : StreamWire.ResetCode.CANCELLED, + }) + } + callback(error) + } + + setKeepAlive() { + return this + } + setNoDelay() { + return this + } + setTimeout(timeout: number, callback?: () => void) { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = undefined + } + if (timeout === 0) { + if (callback) this.off("timeout", callback) + return this + } + if (callback) this.once("timeout", callback) + this.idleTimer = setTimeout(() => { + this.idleTimer = undefined + this.emit("timeout") + }, timeout) + this.idleTimer.unref?.() + return this + } + ref() { + return this + } + unref() { + return this + } + } + + const protocolFail = (reason: string) => { + if (closed) return + writer.enqueueControl({ type: StreamWire.FrameType.GOAWAY, code: StreamWire.ResetCode.PROTOCOL_ERROR, reason }) + shutdown(1002, reason, true) + } + + const offMessage = socket.onMessage((raw) => { + if (closed) return + heartbeat.heard() + if (typeof raw === "string") { + protocolFail("Server sent text frame on binary browser stream tunnel.") + return + } + let frame: StreamWire.Frame + try { + frame = StreamWire.decodeFrame(raw) + } catch (error) { + protocolFail(asError(error).message) + return + } + switch (frame.type) { + case StreamWire.FrameType.OPENED: { + const stream = streams.get(frame.streamID) + if (!stream || stream.status !== "opening") return + pendingConnects = Math.max(0, pendingConnects - 1) + stream.status = "open" + stream.sendWindow = frame.initialWindow + const duplex = new StreamDuplex(stream) + stream.duplex = duplex + stream.opened.resolve(duplex) + return + } + case StreamWire.FrameType.DATA: { + const stream = streams.get(frame.streamID) + if (!stream || stream.status !== "open" || !stream.duplex) return + if (stream.inboundFinReceived) { + cleanupStream(stream, { + error: new Error("Server sent DATA after FIN."), + sendReset: StreamWire.ResetCode.PROTOCOL_ERROR, + }) + return + } + const len = frame.data.byteLength + if (len > stream.recvWindow) { + cleanupStream(stream, { + error: new Error("Server exceeded stream receive window."), + sendReset: StreamWire.ResetCode.PROTOCOL_ERROR, + }) + return + } + if (!reserveBytes(len)) { + cleanupStream(stream, { + error: new Error("Attachment receive buffer exceeded."), + sendReset: StreamWire.ResetCode.LIMIT_EXCEEDED, + }) + return + } + stream.recvWindow -= len + stream.inboundChunks.push(frame.data) + stream.inboundBytes += len + stream.duplex.drainInbound() + return + } + case StreamWire.FrameType.WINDOW_UPDATE: { + const stream = streams.get(frame.streamID) + if (!stream || stream.status !== "open") return + if (stream.sendWindow + frame.delta > StreamWire.MAX_STREAM_WINDOW_BYTES) { + cleanupStream(stream, { + error: new Error("Server sent overflowing WINDOW_UPDATE."), + sendReset: StreamWire.ResetCode.PROTOCOL_ERROR, + }) + return + } + stream.sendWindow += frame.delta + writer.markWritable(stream) + return + } + case StreamWire.FrameType.FIN: { + const stream = streams.get(frame.streamID) + if (!stream || stream.status !== "open" || !stream.duplex) return + stream.inboundFinReceived = true + stream.duplex.drainInbound() + return + } + case StreamWire.FrameType.RESET: { + const stream = streams.get(frame.streamID) + if (!stream) return + const message = frame.reason || resetCodeMessage(frame.code) + cleanupStream(stream, { error: new Error(message) }) + return + } + case StreamWire.FrameType.PING: + writer.enqueueControl({ type: StreamWire.FrameType.PONG, token: frame.token }) + return + case StreamWire.FrameType.PONG: + return + case StreamWire.FrameType.GOAWAY: { + const code = + frame.reason === "replaced" + ? BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED + : BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED + shutdown(code, frame.reason || "Browser tunnel closed by server.", false) + return + } + case StreamWire.FrameType.OPEN: + protocolFail("Server may not send OPEN frames.") + return + } + }) + + const offClose = socket.onClose((code, reason) => { + shutdown(code, reason || "Browser tunnel closed.", false) + }) + + const offError = socket.onError((error) => { + shutdown(1006, error.message || "Browser tunnel socket error.", true) + }) + + function shutdown(code: number, reason: string, terminate: boolean, normalClose = false) { + if (closed) return + closed = true + closeReason = reason || "Browser tunnel disconnected." + heartbeat.stop() + offMessage() + offClose() + offError() + const err = new Error(closeReason) + for (const stream of Array.from(streams.values())) { + cleanupStream(stream, { error: err, normalClose }) + } + writer.close() + try { + if (terminate) socket.terminate() + else if (socket.readyState === WS_OPEN) socket.close(code, reason.slice(0, 120)) + } catch { + // Socket may already be closed. + } + closedDeferred.resolve({ + code, + reason: closeReason, + replaced: code === BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED || reason === "replaced", + }) + } + + return { + closed: closedDeferred.promise, + activeStreams: () => streams.size, + bufferedBytes: () => attachmentBytes, + isClosed: () => closed, + ping() { + if (closed) return + writer.enqueueControl({ type: StreamWire.FrameType.PING, token: randomBytes(8) }) + }, + async openStream(target: Browser.TunnelTarget, signal?: AbortSignal): Promise { + if (closed) throw new Error(closeReason) + if (signal?.aborted) throw new Error("Browser tunnel open was cancelled.") + if (streams.size >= cfg.maxStreams || pendingConnects >= cfg.maxPendingConnects) { + throw new Error(`Browser attachment has reached its ${cfg.maxStreams}-stream limit.`) + } + const id = nextStreamID + nextStreamID = nextStreamID >= 0xfffffffe ? 1 : nextStreamID + 1 + if (streams.has(id)) throw new Error("Browser stream ID space exhausted.") + + const opened = Promise.withResolvers() + pendingConnects += 1 + + const stream: ClientStream = { + id, + status: "opening", + opened, + sendWindow: 0, + recvWindow: cfg.streamWindowBytes, + consumedSinceCredit: 0, + inboundChunks: [], + inboundBytes: 0, + inboundFinReceived: false, + outboundChunks: [], + outboundOffset: 0, + outboundBytes: 0, + outboundFinPending: false, + outboundFinSent: false, + inRoundRobin: false, + hasWritableOutput() { + if (stream.status !== "open") return false + if (stream.outboundBytes > 0 && stream.sendWindow > 0) return true + return stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent + }, + nextOutboundFrame() { + if (stream.status !== "open") return undefined + if (stream.outboundBytes > 0 && stream.sendWindow > 0) { + const maxTake = Math.min(cfg.frameChunkBytes, stream.sendWindow) + const slice = takeChunk(stream.outboundChunks, stream.outboundOffset, maxTake) + stream.outboundOffset = slice.nextOffset + stream.outboundBytes -= slice.bytes.byteLength + stream.sendWindow -= slice.bytes.byteLength + releaseBytes(slice.bytes.byteLength) + if (stream.writeResume && stream.outboundBytes <= cfg.streamOutboundLowWaterBytes) { + const resume = stream.writeResume + stream.writeResume = undefined + resume() + } + return StreamWire.encodeFrame({ + type: StreamWire.FrameType.DATA, + streamID: stream.id, + data: slice.bytes, + }) + } + if (stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent) { + stream.outboundFinSent = true + const cb = stream.finalCallback + stream.finalCallback = undefined + const encoded = StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: stream.id }) + if (cb) cb() + maybeFinishStream(stream) + return encoded + } + return undefined + }, + } + streams.set(id, stream) + + const onAbort = () => { + if (stream.status !== "opening") return + cleanupStream(stream, { + error: new Error("Browser tunnel open was cancelled."), + sendReset: StreamWire.ResetCode.CANCELLED, + }) + } + signal?.addEventListener("abort", onAbort, { once: true }) + + writer.enqueueControl({ + type: StreamWire.FrameType.OPEN, + streamID: id, + host: target.host, + port: target.port, + initialWindow: cfg.streamWindowBytes, + }) + + try { + return await opened.promise + } finally { + signal?.removeEventListener("abort", onAbort) + } + }, + close(code = 1000, reason = "client closed") { + if (closed) return + if (socket.readyState === WS_OPEN) { + try { + socket.send( + StreamWire.encodeFrame({ + type: StreamWire.FrameType.GOAWAY, + code: StreamWire.ResetCode.CANCELLED, + reason, + }), + ) + } catch { + // Best-effort GOAWAY. + } + } + shutdown(code, reason, false, true) + }, + } +} + +function takeChunk(chunks: Uint8Array[], offset: number, maxBytes: number) { + const head = chunks[0] + const available = head.byteLength - offset + if (available <= maxBytes) { + chunks.shift() + return { + bytes: offset === 0 ? head : head.subarray(offset), + nextOffset: 0, + } + } + return { + bytes: head.subarray(offset, offset + maxBytes), + nextOffset: offset + maxBytes, + } +} + +function clamp(value: number, min: number, max: number) { + return Math.max(min, Math.min(max, value)) +} + +function asError(error: unknown) { + return error instanceof Error ? error : new Error(String(error)) +} + +function resetCodeMessage(code: StreamWire.ResetCodeValue) { + switch (code) { + case StreamWire.ResetCode.CANCELLED: + return "Browser tunnel stream was cancelled." + case StreamWire.ResetCode.CONNECT_FAILED: + return "Browser tunnel could not connect to the target." + case StreamWire.ResetCode.POLICY_DENIED: + return "Target address is blocked by browser egress policy." + case StreamWire.ResetCode.LIMIT_EXCEEDED: + return "Browser tunnel resource limit exceeded." + case StreamWire.ResetCode.PROTOCOL_ERROR: + return "Browser tunnel protocol error." + case StreamWire.ResetCode.ATTACHMENT_CLOSED: + return "Browser attachment was closed." + case StreamWire.ResetCode.INTERNAL_ERROR: + return "Browser tunnel target socket error." + } +} diff --git a/packages/plugin-browser/src/stream-wire.ts b/packages/plugin-browser/src/stream-wire.ts new file mode 100644 index 00000000000..5f34489e57c --- /dev/null +++ b/packages/plugin-browser/src/stream-wire.ts @@ -0,0 +1,328 @@ +export * as StreamWire from "./stream-wire.js" + +export const STREAM_PROTOCOL_VERSION = 1 as const +export const FRAME_HEADER_BYTES = 10 +/** Target payload size for outbound DATA frames: small enough for fair interleaving with HMR/control. */ +export const FRAME_DATA_CHUNK_BYTES = 16 * 1024 +/** Maximum payload accepted in any single frame. */ +export const MAX_FRAME_PAYLOAD_BYTES = 64 * 1024 +/** Hard WebSocket maxPayload cap including header overhead. */ +export const MAX_WS_FRAME_BYTES = MAX_FRAME_PAYLOAD_BYTES + FRAME_HEADER_BYTES + 1024 +/** Default server-side per-stream receive window for uploads (1.5 MiB). */ +export const DEFAULT_STREAM_WINDOW_BYTES = 1536 * 1024 +/** + * Default desktop-side per-stream receive window for downloads (512 KiB; derives a 128 KiB credit batch). + * Asymmetric against the 1.5 MiB server receive window to bound downstream queueing ahead of concurrent + * interactive streams such as WebSocket echoes and HMR updates. + */ +export const DEFAULT_CLIENT_STREAM_WINDOW_BYTES = 512 * 1024 +/** Hard upper bound on any stream window to prevent credit overflow attacks. */ +export const MAX_STREAM_WINDOW_BYTES = 4 * 1024 * 1024 +/** Bound WebSocket library write buffer so control/HMR frames are never buried behind a bulk download. */ +export const MAX_WS_BUFFERED_BYTES = 256 * 1024 +/** Hard cap on total buffered bytes across all streams of one attachment. */ +export const MAX_ATTACHMENT_BUFFERED_BYTES = 8 * 1024 * 1024 +/** Hard cap on concurrent streams per attachment. */ +export const MAX_STREAMS_PER_ATTACHMENT = 128 +/** Hard cap on concurrent in-flight TCP connects per attachment. */ +export const MAX_PENDING_CONNECTS_PER_ATTACHMENT = 32 + +export const MAX_HOST_BYTES = 253 +export const MAX_REASON_BYTES = 256 + +const HOST_PATTERN = /^[a-zA-Z0-9._:%-]+$/u +const encoder = new TextEncoder() +const decoder = new TextDecoder("utf-8", { fatal: true }) + +export const FrameType = { + OPEN: 0x01, + OPENED: 0x02, + DATA: 0x03, + WINDOW_UPDATE: 0x04, + FIN: 0x05, + RESET: 0x06, + PING: 0x07, + PONG: 0x08, + GOAWAY: 0x09, +} as const + +export const ResetCode = { + CANCELLED: 0x0000, + CONNECT_FAILED: 0x0001, + POLICY_DENIED: 0x0002, + LIMIT_EXCEEDED: 0x0003, + PROTOCOL_ERROR: 0x0004, + ATTACHMENT_CLOSED: 0x0005, + INTERNAL_ERROR: 0x0006, +} as const + +export type ResetCodeValue = (typeof ResetCode)[keyof typeof ResetCode] + +export type Frame = + | { + readonly type: typeof FrameType.OPEN + readonly streamID: number + readonly host: string + readonly port: number + readonly initialWindow: number + } + | { + readonly type: typeof FrameType.OPENED + readonly streamID: number + readonly initialWindow: number + } + | { + readonly type: typeof FrameType.DATA + readonly streamID: number + readonly data: Uint8Array + } + | { + readonly type: typeof FrameType.WINDOW_UPDATE + readonly streamID: number + readonly delta: number + } + | { + readonly type: typeof FrameType.FIN + readonly streamID: number + } + | { + readonly type: typeof FrameType.RESET + readonly streamID: number + readonly code: ResetCodeValue + readonly reason: string + } + | { + readonly type: typeof FrameType.PING + readonly token: Uint8Array + } + | { + readonly type: typeof FrameType.PONG + readonly token: Uint8Array + } + | { + readonly type: typeof FrameType.GOAWAY + readonly code: ResetCodeValue + readonly reason: string + } + +export class WireProtocolError extends Error { + constructor(message: string) { + super(message) + this.name = "WireProtocolError" + } +} + +export function encodeFrame(frame: Frame): Uint8Array { + switch (frame.type) { + case FrameType.OPEN: { + assertStreamID(frame.streamID) + assertPort(frame.port) + assertWindow(frame.initialWindow) + const hostBytes = encoder.encode(frame.host) + if (hostBytes.byteLength < 1 || hostBytes.byteLength > MAX_HOST_BYTES || !HOST_PATTERN.test(frame.host)) { + throw new WireProtocolError(`Invalid OPEN host: ${frame.host}`) + } + const payloadLength = 6 + hostBytes.byteLength + const out = allocHeader(FrameType.OPEN, frame.streamID, payloadLength) + const view = new DataView(out.buffer, out.byteOffset, out.byteLength) + view.setUint16(FRAME_HEADER_BYTES, frame.port, false) + view.setUint32(FRAME_HEADER_BYTES + 2, frame.initialWindow, false) + out.set(hostBytes, FRAME_HEADER_BYTES + 6) + return out + } + case FrameType.OPENED: { + assertStreamID(frame.streamID) + assertWindow(frame.initialWindow) + const out = allocHeader(FrameType.OPENED, frame.streamID, 4) + const view = new DataView(out.buffer, out.byteOffset, out.byteLength) + view.setUint32(FRAME_HEADER_BYTES, frame.initialWindow, false) + return out + } + case FrameType.DATA: { + assertStreamID(frame.streamID) + if (frame.data.byteLength < 1 || frame.data.byteLength > MAX_FRAME_PAYLOAD_BYTES) { + throw new WireProtocolError(`Invalid DATA length: ${frame.data.byteLength}`) + } + const out = allocHeader(FrameType.DATA, frame.streamID, frame.data.byteLength) + out.set(frame.data, FRAME_HEADER_BYTES) + return out + } + case FrameType.WINDOW_UPDATE: { + assertStreamID(frame.streamID) + assertWindow(frame.delta) + const out = allocHeader(FrameType.WINDOW_UPDATE, frame.streamID, 4) + const view = new DataView(out.buffer, out.byteOffset, out.byteLength) + view.setUint32(FRAME_HEADER_BYTES, frame.delta, false) + return out + } + case FrameType.FIN: { + assertStreamID(frame.streamID) + return allocHeader(FrameType.FIN, frame.streamID, 0) + } + case FrameType.RESET: { + assertStreamID(frame.streamID) + const reasonBytes = encoder.encode(frame.reason.slice(0, MAX_REASON_BYTES)).subarray(0, MAX_REASON_BYTES) + const out = allocHeader(FrameType.RESET, frame.streamID, 2 + reasonBytes.byteLength) + const view = new DataView(out.buffer, out.byteOffset, out.byteLength) + view.setUint16(FRAME_HEADER_BYTES, frame.code, false) + out.set(reasonBytes, FRAME_HEADER_BYTES + 2) + return out + } + case FrameType.PING: + case FrameType.PONG: { + if (frame.token.byteLength !== 8) throw new WireProtocolError("PING/PONG token must be 8 bytes.") + const out = allocHeader(frame.type, 0, 8) + out.set(frame.token, FRAME_HEADER_BYTES) + return out + } + case FrameType.GOAWAY: { + const reasonBytes = encoder.encode(frame.reason.slice(0, MAX_REASON_BYTES)).subarray(0, MAX_REASON_BYTES) + const out = allocHeader(FrameType.GOAWAY, 0, 2 + reasonBytes.byteLength) + const view = new DataView(out.buffer, out.byteOffset, out.byteLength) + view.setUint16(FRAME_HEADER_BYTES, frame.code, false) + out.set(reasonBytes, FRAME_HEADER_BYTES + 2) + return out + } + } +} + +export function decodeFrame(raw: Uint8Array): Frame { + if (raw.byteLength < FRAME_HEADER_BYTES) { + throw new WireProtocolError(`Frame too short: ${raw.byteLength} bytes.`) + } + const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength) + const version = view.getUint8(0) + if (version !== STREAM_PROTOCOL_VERSION) { + throw new WireProtocolError(`Unsupported stream protocol version: ${version}.`) + } + const type = view.getUint8(1) + const streamID = view.getUint32(2, false) + const length = view.getUint32(6, false) + if (length > MAX_FRAME_PAYLOAD_BYTES) { + throw new WireProtocolError(`Frame payload exceeds limit: ${length} bytes.`) + } + if (raw.byteLength !== FRAME_HEADER_BYTES + length) { + throw new WireProtocolError(`Frame length mismatch: header declares ${length}, actual ${raw.byteLength - FRAME_HEADER_BYTES}.`) + } + const payload = raw.subarray(FRAME_HEADER_BYTES) + + switch (type) { + case FrameType.OPEN: { + assertStreamID(streamID) + if (length < 7 || length > 6 + MAX_HOST_BYTES) { + throw new WireProtocolError(`Invalid OPEN payload length: ${length}.`) + } + const port = view.getUint16(FRAME_HEADER_BYTES, false) + assertPort(port) + const initialWindow = view.getUint32(FRAME_HEADER_BYTES + 2, false) + assertWindow(initialWindow) + const host = decodeUtf8(payload.subarray(6)) + if (host.length < 1 || host.length > MAX_HOST_BYTES || !HOST_PATTERN.test(host)) { + throw new WireProtocolError("Invalid OPEN target host.") + } + return { type: FrameType.OPEN, streamID, host, port, initialWindow } + } + case FrameType.OPENED: { + assertStreamID(streamID) + if (length !== 4) throw new WireProtocolError(`Invalid OPENED payload length: ${length}.`) + const initialWindow = view.getUint32(FRAME_HEADER_BYTES, false) + assertWindow(initialWindow) + return { type: FrameType.OPENED, streamID, initialWindow } + } + case FrameType.DATA: { + assertStreamID(streamID) + if (length < 1) throw new WireProtocolError("DATA frame must carry at least 1 byte.") + // Copy slice so retaining the buffer does not pin a larger WebSocket slab. + return { type: FrameType.DATA, streamID, data: new Uint8Array(payload) } + } + case FrameType.WINDOW_UPDATE: { + assertStreamID(streamID) + if (length !== 4) throw new WireProtocolError(`Invalid WINDOW_UPDATE payload length: ${length}.`) + const delta = view.getUint32(FRAME_HEADER_BYTES, false) + assertWindow(delta) + return { type: FrameType.WINDOW_UPDATE, streamID, delta } + } + case FrameType.FIN: { + assertStreamID(streamID) + if (length !== 0) throw new WireProtocolError(`Invalid FIN payload length: ${length}.`) + return { type: FrameType.FIN, streamID } + } + case FrameType.RESET: { + assertStreamID(streamID) + if (length < 2 || length > 2 + MAX_REASON_BYTES) { + throw new WireProtocolError(`Invalid RESET payload length: ${length}.`) + } + const code = normalizeResetCode(view.getUint16(FRAME_HEADER_BYTES, false)) + const reason = length > 2 ? decodeUtf8(payload.subarray(2)) : "" + return { type: FrameType.RESET, streamID, code, reason } + } + case FrameType.PING: + case FrameType.PONG: { + if (streamID !== 0) throw new WireProtocolError("PING/PONG must use streamID 0.") + if (length !== 8) throw new WireProtocolError(`Invalid PING/PONG payload length: ${length}.`) + return { type, token: new Uint8Array(payload) } + } + case FrameType.GOAWAY: { + if (streamID !== 0) throw new WireProtocolError("GOAWAY must use streamID 0.") + if (length < 2 || length > 2 + MAX_REASON_BYTES) { + throw new WireProtocolError(`Invalid GOAWAY payload length: ${length}.`) + } + const code = normalizeResetCode(view.getUint16(FRAME_HEADER_BYTES, false)) + const reason = length > 2 ? decodeUtf8(payload.subarray(2)) : "" + return { type: FrameType.GOAWAY, code, reason } + } + default: + throw new WireProtocolError(`Unknown stream frame type: ${type}.`) + } +} + +function allocHeader(type: number, streamID: number, payloadLength: number) { + const out = new Uint8Array(FRAME_HEADER_BYTES + payloadLength) + const view = new DataView(out.buffer, out.byteOffset, out.byteLength) + view.setUint8(0, STREAM_PROTOCOL_VERSION) + view.setUint8(1, type) + view.setUint32(2, streamID, false) + view.setUint32(6, payloadLength, false) + return out +} + +function assertStreamID(streamID: number) { + if (!Number.isInteger(streamID) || streamID < 1 || streamID > 0xffffffff) { + throw new WireProtocolError(`Invalid streamID: ${streamID}.`) + } +} + +function assertPort(port: number) { + if (!Number.isInteger(port) || port < 1 || port > 65_535) { + throw new WireProtocolError(`Invalid port: ${port}.`) + } +} + +function assertWindow(bytes: number) { + if (!Number.isInteger(bytes) || bytes < 1 || bytes > MAX_STREAM_WINDOW_BYTES) { + throw new WireProtocolError(`Invalid window/credit size: ${bytes}.`) + } +} + +function normalizeResetCode(code: number): ResetCodeValue { + switch (code) { + case ResetCode.CANCELLED: + case ResetCode.CONNECT_FAILED: + case ResetCode.POLICY_DENIED: + case ResetCode.LIMIT_EXCEEDED: + case ResetCode.PROTOCOL_ERROR: + case ResetCode.ATTACHMENT_CLOSED: + case ResetCode.INTERNAL_ERROR: + return code + default: + return ResetCode.INTERNAL_ERROR + } +} + +function decodeUtf8(bytes: Uint8Array) { + try { + return decoder.decode(bytes) + } catch { + throw new WireProtocolError("Frame contains invalid UTF-8.") + } +} diff --git a/packages/plugin-browser/src/stream.ts b/packages/plugin-browser/src/stream.ts new file mode 100644 index 00000000000..9186e518c34 --- /dev/null +++ b/packages/plugin-browser/src/stream.ts @@ -0,0 +1,4 @@ +export { EgressPolicy } from "./egress-policy.js" +export { StreamWire } from "./stream-wire.js" +export { StreamMux } from "./stream-mux.js" +export { BrowserTunnelHost } from "./tunnel-host.js" diff --git a/packages/plugin-browser/src/tunnel-host.ts b/packages/plugin-browser/src/tunnel-host.ts new file mode 100644 index 00000000000..8c098b0340e --- /dev/null +++ b/packages/plugin-browser/src/tunnel-host.ts @@ -0,0 +1,118 @@ +export * as BrowserTunnelHost from "./tunnel-host.js" + +import type { Location } from "@opencode/schema/location" +import type { Session } from "@opencode/schema/session" +import { Context, type Effect } from "effect" + +export const STREAM_CAPABILITY = "tunnel.ws.v1" as const +export const BROWSER_TUNNEL_PATH = "/api/experimental/browser/tunnel" as const +export const CLOSE_ATTACHMENT_CLOSED = 4001 +export const CLOSE_ATTACHMENT_REPLACED = 4002 + +/** Minimal binary WebSocket transport handed from the server upgrade handler to the browser attachment. */ +export interface BinarySocket { + readonly readyState: number + readonly bufferedAmount: number + send(data: Uint8Array, onWritten?: (error?: Error) => void): void + ping?(): void + close(code?: number, reason?: string): void + terminate(): void + onMessage(listener: (data: Uint8Array | string) => void): () => void + onClose(listener: (code: number, reason: string) => void): () => void + onError(listener: (error: Error) => void): () => void + onPong?(listener: () => void): () => void +} + +export interface TicketBinding { + readonly location: Location.Ref + readonly sessionID: Session.ID + readonly connectionID: string + readonly generation: number + readonly protocol: number + readonly onUpgrade: (socket: BinarySocket) => Effect.Effect +} + +export interface IssuedTicket { + readonly ticket: string + readonly expiresIn: number + readonly protocol: number + readonly path: string +} + +/** + * Narrow handoff interface between the server's ticket-authenticated WebSocket upgrade route + * and the browser plugin's attachment owner. The server never opens target TCP sockets itself; + * it only validates the single-use ticket and hands the upgraded binary socket to the attachment. + */ +export interface Interface { + readonly enabled: Effect.Effect + readonly reservedLocalPorts: () => ReadonlySet + readonly issueTicket: (binding: TicketBinding) => Effect.Effect + readonly revokeAttachment: (sessionID: Session.ID, connectionID: string, generation: number) => Effect.Effect +} + +/** Optional host service; undefined in standalone unit tests without a WebSocket upgrade server. */ +export const Reference = Context.Reference("@opencode/BrowserTunnelHost", { + defaultValue: () => undefined, +}) + +export interface GlobalLimits { + readonly maxStreams: number + readonly maxPendingConnects: number + readonly maxBufferedBytes: number + tryAcquireStream(): boolean + releaseStream(): void + tryAcquirePendingConnect(): boolean + releasePendingConnect(): void + tryReserveBytes(bytes: number): boolean + releaseBytes(bytes: number): void +} + +export function createGlobalLimits( + input: { + readonly maxStreams?: number + readonly maxPendingConnects?: number + readonly maxBufferedBytes?: number + } = {}, +): GlobalLimits { + const maxStreams = input.maxStreams ?? 512 + const maxPendingConnects = input.maxPendingConnects ?? 128 + const maxBufferedBytes = input.maxBufferedBytes ?? 64 * 1024 * 1024 + let streams = 0 + let pendingConnects = 0 + let bufferedBytes = 0 + + return { + maxStreams, + maxPendingConnects, + maxBufferedBytes, + tryAcquireStream() { + if (streams >= maxStreams) return false + streams += 1 + return true + }, + releaseStream() { + streams = Math.max(0, streams - 1) + }, + tryAcquirePendingConnect() { + if (pendingConnects >= maxPendingConnects) return false + pendingConnects += 1 + return true + }, + releasePendingConnect() { + pendingConnects = Math.max(0, pendingConnects - 1) + }, + tryReserveBytes(bytes) { + if (bytes <= 0) return true + if (bufferedBytes + bytes > maxBufferedBytes) return false + bufferedBytes += bytes + return true + }, + releaseBytes(bytes) { + if (bytes <= 0) return + bufferedBytes = Math.max(0, bufferedBytes - bytes) + }, + } +} + +export const defaultGlobalLimits = createGlobalLimits() diff --git a/packages/plugin-browser/src/tunnel.ts b/packages/plugin-browser/src/tunnel.ts index 2cc88d56be0..ab19d57b534 100644 --- a/packages/plugin-browser/src/tunnel.ts +++ b/packages/plugin-browser/src/tunnel.ts @@ -2,6 +2,7 @@ export * as BrowserTunnel from "./tunnel.js" import type { Socket } from "node:net" import { Effect, Exit } from "effect" +import { EgressPolicy } from "./egress-policy.js" import { Browser } from "./rpc.js" import { BrowserTunnelMachine } from "./tunnel-machine.js" @@ -9,13 +10,18 @@ export type Tunnels = ReturnType // One instance belongs to one desktop attachment. Socket buffers provide // backpressure; reads never collect an unbounded stream in application memory. -export function make() { +// When `policy` is omitted (experiment disabled or no tunnel host), preserves the +// exact pre-PR legacy `net.createConnection` DNS, socket, connect, and timeout behavior. +export function make(policy?: EgressPolicy.AttachmentPolicy) { let state = BrowserTunnelMachine.initial() const sockets = new Map() + const connecting = new Map() const dispatch = (event: BrowserTunnelMachine.Event) => { const next = BrowserTunnelMachine.transition(state, event) state = next.state next.effects.forEach((effect) => { + connecting.get(effect.id)?.abort() + connecting.delete(effect.id) sockets.get(effect.id)?.destroy() sockets.delete(effect.id) }) @@ -27,48 +33,83 @@ export function make() { if (rejected) return yield* Effect.fail(rejected) const id = crypto.randomUUID() dispatch({ type: "open.started", id }) + if (!policy) { + return yield* Effect.gen(function* () { + const { createConnection } = yield* Effect.promise(() => import("node:net")) + const socket = yield* Effect.try({ + try: () => createConnection({ ...target, allowHalfOpen: true }), + catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))), + }) + sockets.set(id, socket) + socket.on("error", (error) => dispatch({ type: "socket.errored", id, error })) + socket.once("close", () => dispatch({ type: "socket.closed", id })) + yield* Effect.callback((resume) => { + const connected = () => { + cleanup() + socket.setNoDelay(true) + resume(Effect.void) + } + const failed = (error: Error) => { + cleanup() + resume(Effect.fail(error)) + } + const closed = () => failed(new Error("Browser tunnel closed while connecting.")) + const cleanup = () => { + socket.off("connect", connected) + socket.off("error", failed) + socket.off("close", closed) + } + socket.once("connect", connected) + socket.once("error", failed) + socket.once("close", closed) + if (socket.destroyed) closed() + if (!socket.destroyed && !socket.connecting) connected() + return Effect.sync(cleanup) + }).pipe( + Effect.timeoutOrElse({ + duration: "10 seconds", + orElse: () => Effect.fail(new Error("Browser tunnel target connection timed out.")), + }), + ) + dispatch({ type: "open.connected", id }) + // Disposal or `close(id)` can win the race with the connect. + if (!BrowserTunnelMachine.isOpen(state, id)) return yield* Effect.fail(new Error("Browser attachment is closed.")) + return id + }).pipe(Effect.onError(() => Effect.sync(() => dispatch({ type: "open.failed", id })))) + } + + const abort = new AbortController() + connecting.set(id, abort) return yield* Effect.gen(function* () { - const { createConnection } = yield* Effect.promise(() => import("node:net")) - const socket = yield* Effect.try({ - try: () => createConnection({ ...target, allowHalfOpen: true }), + // Resolve DNS once, enforce egress policy on every final IP, and connect directly to the checked IP. + const socket = yield* Effect.tryPromise({ + try: (signal) => + EgressPolicy.resolveAndConnect(target, policy, { + signal: AbortSignal.any([abort.signal, signal]), + timeoutMs: 10_000, + }), catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))), }) + connecting.delete(id) sockets.set(id, socket) socket.on("error", (error) => dispatch({ type: "socket.errored", id, error })) socket.once("close", () => dispatch({ type: "socket.closed", id })) - yield* Effect.callback((resume) => { - const connected = () => { - cleanup() - socket.setNoDelay(true) - resume(Effect.void) - } - const failed = (error: Error) => { - cleanup() - resume(Effect.fail(error)) - } - const closed = () => failed(new Error("Browser tunnel closed while connecting.")) - const cleanup = () => { - socket.off("connect", connected) - socket.off("error", failed) - socket.off("close", closed) - } - socket.once("connect", connected) - socket.once("error", failed) - socket.once("close", closed) - if (socket.destroyed) closed() - if (!socket.destroyed && !socket.connecting) connected() - return Effect.sync(cleanup) - }).pipe( - Effect.timeoutOrElse({ - duration: "10 seconds", - orElse: () => Effect.fail(new Error("Browser tunnel target connection timed out.")), - }), - ) dispatch({ type: "open.connected", id }) // Disposal or `close(id)` can win the race with the connect. - if (!BrowserTunnelMachine.isOpen(state, id)) return yield* Effect.fail(new Error("Browser attachment is closed.")) + if (!BrowserTunnelMachine.isOpen(state, id)) { + socket.destroy() + sockets.delete(id) + return yield* Effect.fail(new Error("Browser attachment is closed.")) + } return id - }).pipe(Effect.onError(() => Effect.sync(() => dispatch({ type: "open.failed", id })))) + }).pipe( + Effect.onError(() => + Effect.sync(() => { + connecting.delete(id) + dispatch({ type: "open.failed", id }) + }), + ), + ) }), read: Effect.fn("BrowserTunnel.read")(function* (id: string) { const socket = sockets.get(id) diff --git a/packages/plugin-browser/test/connection.test.ts b/packages/plugin-browser/test/connection.test.ts index 2b90e9f4936..b68c1f003df 100644 --- a/packages/plugin-browser/test/connection.test.ts +++ b/packages/plugin-browser/test/connection.test.ts @@ -9,6 +9,7 @@ import { Effect, Fiber, Schedule, Stream } from "effect" import { BrowserConnection } from "../src/connection.js" import { Browser } from "../src/rpc.js" import { BrowserTools } from "../src/tools.js" +import { BrowserTunnelHost } from "../src/tunnel-host.js" type Rule = Permission.Rule type SessionRow = { id: string; agent: string; parentID?: string; permissions?: Rule[]; location: { directory: string } } @@ -121,13 +122,13 @@ function plugin(input: { sessions, storage, asserts, + invoke: (name: string, input: object) => rpc.handlers![name](input, call), commands: () => controls.filter((control) => control.type === "command").length, evaluate: (event: PermissionEvaluation) => Effect.forEach(hooks, (hook) => hook(event), { discard: true }).pipe(Effect.as(event)), prompt: (sessionID: string) => Effect.forEach(prompts, (hook) => hook({ sessionID }), { discard: true }), /** Attaches a desktop to `sessionID` and reports one open tab; interrupting the fiber detaches it. */ - attach: (sessionID: string) => + attach: (sessionID: string, connectionID: string = crypto.randomUUID()) => Effect.gen(function* () { - const connectionID = crypto.randomUUID() const attached = yield* Effect.forkChild(rpc.handlers!.attach({ sessionID, connectionID, version: 4 }, call), { startImmediately: true }) yield* Effect.suspend(() => (controls.some((control) => control.type === "attached" && control.connectionID === connectionID) ? Effect.void : Effect.fail("not attached"))).pipe( Effect.retry(Schedule.spaced("5 millis")), @@ -157,6 +158,37 @@ const session = (id: string, directory: string, extra: Partial = {}) const until = (check: () => boolean) => Effect.suspend(() => (check() ? Effect.void : Effect.fail("not yet"))).pipe(Effect.retry(Schedule.spaced("5 millis")), Effect.timeout("5 seconds")) +test("changing the experiment only changes new attachments, including legacy RPC traffic", () => + Effect.runPromise(Effect.gen(function* () { + const fake = plugin({ directory: "/work", sessions: [session("ses_fixture", "/work")] }) + const listener = yield* Effect.acquireRelease( + Effect.sync(() => Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } })), + (server) => Effect.sync(() => server.stop(true)), + ) + let enabled = true + yield* BrowserConnection.make(fake.context).pipe(Effect.provideService(BrowserTunnelHost.Reference, { + enabled: Effect.sync(() => enabled), + reservedLocalPorts: () => new Set([listener.port]), + issueTicket: () => Effect.die("Disabled attachment must not mint a ticket"), + revokeAttachment: () => Effect.void, + })) + + const on = { sessionID: "ses_fixture", connectionID: "on" } + const off = { ...on, connectionID: "off" } + const target = { host: "127.0.0.1", port: listener.port } + const first = yield* fake.attach(on.sessionID, on.connectionID) + enabled = false + expect(yield* fake.invoke("tunnel.open", { ...on, target }).pipe(Effect.flip)).toMatchObject({ message: expect.stringContaining("blocked") }) + const second = yield* fake.attach(off.sessionID, off.connectionID) + expect(yield* Fiber.join(first)).toBe("replaced") + expect(yield* fake.invoke("tunnel.ticket", { ...off, protocol: 1 }).pipe(Effect.flip)).toMatchObject({ message: expect.stringContaining("disabled") }) + expect(yield* fake.invoke("tunnel.grant", { ...off, target }).pipe(Effect.flip)).toMatchObject({ message: expect.stringContaining("disabled") }) + const tunnelID = yield* fake.invoke("tunnel.open", { ...off, target }) + yield* fake.invoke("tunnel.close", { ...off, tunnelID }) + yield* Fiber.interrupt(second) + }).pipe(Effect.scoped)), +) + // An attached session's grant makes core resolve every browser call to allow, so the plugin's `evaluate` hook is what // applies the agent's own rules. When it cannot read them, the grant must not decide alone. test("a browser call is refused when the session's rules cannot be read", async () => { diff --git a/packages/plugin-browser/test/egress-connect.test.ts b/packages/plugin-browser/test/egress-connect.test.ts new file mode 100644 index 00000000000..2fd21196671 --- /dev/null +++ b/packages/plugin-browser/test/egress-connect.test.ts @@ -0,0 +1,29 @@ +import { expect, test } from "bun:test" +import { EgressPolicy } from "../src/egress-policy.js" + +test("falls back to the reachable verified address without a second DNS lookup", async () => { + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("preview") }) + const lookups: string[] = [] + const policy = EgressPolicy.makePolicy({ + resolve: async (host) => { + lookups.push(host) + return [ + { address: "::1", family: 6 }, + { address: "127.0.0.1", family: 4 }, + ] + }, + }) + try { + const target = { host: "preview.example.invalid", port: Number(server.url.port) } + policy.grant(target.host, target.port) + const socket = await EgressPolicy.resolveAndConnect(target, policy) + try { + expect(socket.remoteAddress).toBe("127.0.0.1") + expect(lookups).toEqual([target.host]) + } finally { + socket.destroy() + } + } finally { + await server.stop(true) + } +}) diff --git a/packages/plugin-browser/test/egress-policy.test.ts b/packages/plugin-browser/test/egress-policy.test.ts new file mode 100644 index 00000000000..e3aa6dc8542 --- /dev/null +++ b/packages/plugin-browser/test/egress-policy.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, test } from "bun:test" +import { EgressPolicy } from "../src/egress-policy.js" + +describe("EgressPolicy protection and dev loopback support", () => { + test("blocks cloud metadata, link-local, unspecified, multicast, and IPv4-mapped/NAT64/6to4 bypasses", () => { + const policy = EgressPolicy.makePolicy({ allowPrivateLan: true }) + const blocked = [ + ["169.254.169.254", 80, "169.254.169.254"], + ["169.254.170.2", 80, "169.254.170.2"], + ["100.100.100.200", 80, "100.100.100.200"], + ["metadata.google.internal", 80, "169.254.169.254"], + ["metadata.goog", 80, "1.1.1.1"], + ["fd00:ec2::254", 80, "fd00:ec2::254"], + ["fe80::1", 80, "fe80::1"], + ["::ffff:169.254.169.254", 80, "::ffff:169.254.169.254"], + ["64:ff9b::169.254.169.254", 80, "64:ff9b::169.254.169.254"], + ["2002:a9fe:a9fe::1", 80, "2002:a9fe:a9fe::1"], + ["0.0.0.0", 80, "0.0.0.0"], + ["::", 80, "::"], + ["224.0.0.1", 80, "224.0.0.1"], + ["255.255.255.255", 80, "255.255.255.255"], + ] as const + for (const [host, port, ip] of blocked) { + expect(policy.evaluateAddress(host, port, ip).allowed).toBe(false) + } + // Non-standard decimal/hex IPv4 literals resolve and classify as metadata too + expect(EgressPolicy.parseIpLiteral("2852039166")).toEqual({ address: "169.254.169.254", family: 4 }) + expect(EgressPolicy.parseIpLiteral("0xa9fea9fe")).toEqual({ address: "169.254.169.254", family: 4 }) + }) + + test("distinguishes public, loopback and explicitly granted private destinations", () => { + const policy = EgressPolicy.makePolicy({ reservedLocalPorts: () => new Set([4096]), allowPrivateLan: false }) + const allowed = (name: string, port: number, ip: string) => policy.evaluateAddress(name, port, ip).allowed + expect(allowed("example.com", 443, "93.184.216.34")).toBe(true) + expect(allowed("localhost", 5173, "::1")).toBe(true) + expect(allowed("app.localhost", 24678, "127.0.0.1")).toBe(true) + expect(allowed("localhost", 4096, "::1")).toBe(false) + expect(allowed("localhost", 22, "127.0.0.1")).toBe(false) + expect(allowed("preview.example", 5173, "127.0.0.1")).toBe(false) + expect(allowed("dev.internal", 5173, "192.168.1.50")).toBe(false) + policy.grant("dev.internal", 5173, [24678]) + expect(allowed("dev.internal", 5173, "192.168.1.50")).toBe(true) + expect(allowed("dev.internal", 24678, "192.168.1.50")).toBe(true) + expect(allowed("dev.internal", 9999, "192.168.1.50")).toBe(false) + expect(() => policy.grant("169.254.169.254", 80)).toThrow(EgressPolicy.EgressDeniedError) + expect(() => policy.grant("localhost", 4096)).toThrow(EgressPolicy.EgressDeniedError) + expect(() => policy.grant("dev.internal", 22)).toThrow(EgressPolicy.EgressDeniedError) + }) + + test("rejects a mixed DNS answer even when the first address is allowed", async () => { + const policy = EgressPolicy.makePolicy({ + resolve: async () => [ + { address: "93.184.216.34", family: 4 }, + { address: "::1", family: 6 }, + ], + }) + await expect(policy.resolveTarget({ host: "preview.example", port: 5173 })).rejects.toThrow( + EgressPolicy.EgressDeniedError, + ) + }) +}) diff --git a/packages/plugin-browser/test/stream-tunnel.test.ts b/packages/plugin-browser/test/stream-tunnel.test.ts new file mode 100644 index 00000000000..72eab449b7b --- /dev/null +++ b/packages/plugin-browser/test/stream-tunnel.test.ts @@ -0,0 +1,693 @@ +import { describe, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { once } from "node:events" +import { request as httpRequest } from "node:http" +import { createServer as createNetServer, type Socket } from "node:net" +import { PassThrough } from "node:stream" +import { Schema } from "effect" +import { EgressPolicy } from "../src/egress-policy.js" +import { Browser } from "../src/rpc.js" +import { BrowserProxy } from "../src/proxy.js" +import { StreamMux } from "../src/stream-mux.js" +import { StreamWire } from "../src/stream-wire.js" +import { BrowserTunnelHost } from "../src/tunnel-host.js" + +/** + * In-memory paired BinarySockets with optional deterministic manual flush and backpressure + * simulation for multiplexer tests without timers or wall-clock races. + */ +function createSocketPair(options: { readonly simulateBuffered?: boolean; readonly gateServerSends?: boolean } = {}) { + type Listener = (value: T) => void + type Side = { + readyState: number + bufferedAmount: number + maxBufferedAmount: number + readonly pendingSends: Array<() => void> + readonly sentFrames: StreamWire.Frame[] + readonly messageListeners: Set> + readonly closeListeners: Set<(code: number, reason: string) => void> + readonly errorListeners: Set> + readonly pongListeners: Set<() => void> + peer: Side + deliver(data: Uint8Array | string): void + finishClose(code: number, reason: string): void + toSocket(): BrowserTunnelHost.BinarySocket + } + const makeSide = (gated: boolean): Side => { + const messageListeners = new Set>() + const closeListeners = new Set<(code: number, reason: string) => void>() + const errorListeners = new Set>() + const pongListeners = new Set<() => void>() + const side: Side = { + readyState: 1, + bufferedAmount: 0, + maxBufferedAmount: 0, + pendingSends: [], + sentFrames: [], + messageListeners, + closeListeners, + errorListeners, + pongListeners, + peer: undefined as unknown as Side, + deliver(data: Uint8Array | string) { + if (this.readyState !== 1) return + for (const listener of Array.from(this.messageListeners)) listener(data) + }, + finishClose(code: number, reason: string) { + if (this.readyState === 3) return + this.readyState = 3 + for (const listener of Array.from(this.closeListeners)) listener(code, reason) + }, + toSocket(): BrowserTunnelHost.BinarySocket { + const self = side + return { + get readyState() { + return self.readyState + }, + get bufferedAmount() { + return self.bufferedAmount + }, + send(data, onWritten) { + if (self.readyState !== 1) { + onWritten?.(new Error("socket closed")) + return + } + const copy = new Uint8Array(data) + if (gated) self.sentFrames.push(StreamWire.decodeFrame(copy)) + if (options.simulateBuffered || gated) { + self.bufferedAmount += copy.byteLength + if (self.bufferedAmount > self.maxBufferedAmount) self.maxBufferedAmount = self.bufferedAmount + } + const dispatch = () => { + if (options.simulateBuffered || gated) { + self.bufferedAmount = Math.max(0, self.bufferedAmount - copy.byteLength) + } + onWritten?.() + if (self.peer.readyState === 1) self.peer.deliver(copy) + } + if (gated) { + self.pendingSends.push(dispatch) + } else { + queueMicrotask(dispatch) + } + }, + ping() { + if (self.readyState === 1 && self.peer.readyState === 1) { + queueMicrotask(() => { + for (const listener of Array.from(self.pongListeners)) listener() + }) + } + }, + close(code = 1000, reason = "") { + self.finishClose(code, reason) + queueMicrotask(() => self.peer.finishClose(code, reason)) + }, + terminate() { + self.finishClose(1006, "terminated") + queueMicrotask(() => self.peer.finishClose(1006, "terminated")) + }, + onMessage(listener) { + self.messageListeners.add(listener) + return () => void self.messageListeners.delete(listener) + }, + onClose(listener) { + self.closeListeners.add(listener) + return () => void self.closeListeners.delete(listener) + }, + onError(listener) { + self.errorListeners.add(listener) + return () => void self.errorListeners.delete(listener) + }, + onPong(listener) { + self.pongListeners.add(listener) + return () => void self.pongListeners.delete(listener) + }, + } + }, + } + return side + } + const a = makeSide(false) + const b = makeSide(options.gateServerSends === true) + a.peer = b + b.peer = a + return { + clientRaw: a, + serverRaw: b, + client: a.toSocket(), + server: b.toSocket(), + flushOneServerFrame() { + const next = b.pendingSends.shift() + if (!next) return false + next() + return true + }, + } +} + +describe("StreamWire codec and adversarial validation", () => { + test("round-trips every frame type cleanly", () => { + const frames: StreamWire.Frame[] = [ + { type: StreamWire.FrameType.OPEN, streamID: 1, host: "localhost", port: 5173, initialWindow: 65_536 }, + { type: StreamWire.FrameType.OPENED, streamID: 1, initialWindow: 131_072 }, + { type: StreamWire.FrameType.DATA, streamID: 1, data: new Uint8Array([1, 2, 3, 255]) }, + { type: StreamWire.FrameType.WINDOW_UPDATE, streamID: 1, delta: 32_768 }, + { type: StreamWire.FrameType.FIN, streamID: 1 }, + { type: StreamWire.FrameType.RESET, streamID: 1, code: StreamWire.ResetCode.POLICY_DENIED, reason: "blocked" }, + { type: StreamWire.FrameType.PING, token: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]) }, + { type: StreamWire.FrameType.PONG, token: new Uint8Array([8, 7, 6, 5, 4, 3, 2, 1]) }, + { type: StreamWire.FrameType.GOAWAY, code: StreamWire.ResetCode.ATTACHMENT_CLOSED, reason: "replaced" }, + ] + for (const frame of frames) { + expect(StreamWire.decodeFrame(StreamWire.encodeFrame(frame))).toEqual(frame) + } + }) + + test("rejects malformed, truncated, oversized, and protocol-violating frames", () => { + // Truncated header + expect(() => StreamWire.decodeFrame(new Uint8Array(9))).toThrow(StreamWire.WireProtocolError) + // Unsupported version + const badVersion = StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: 1 }) + badVersion[0] = 2 + expect(() => StreamWire.decodeFrame(badVersion)).toThrow(StreamWire.WireProtocolError) + // Trailing garbage + const withGarbage = new Uint8Array( + StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: 1 }).length + 1, + ) + withGarbage.set(StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: 1 })) + expect(() => StreamWire.decodeFrame(withGarbage)).toThrow(StreamWire.WireProtocolError) + // Zero streamID on DATA + const zeroStream = StreamWire.encodeFrame({ + type: StreamWire.FrameType.DATA, + streamID: 1, + data: new Uint8Array([1]), + }) + zeroStream[5] = 0 + expect(() => StreamWire.decodeFrame(zeroStream)).toThrow(StreamWire.WireProtocolError) + // Non-zero streamID on PING + const badPing = StreamWire.encodeFrame({ + type: StreamWire.FrameType.PING, + token: new Uint8Array(8), + }) + badPing[5] = 1 + expect(() => StreamWire.decodeFrame(badPing)).toThrow(StreamWire.WireProtocolError) + // Zero-delta WINDOW_UPDATE + const zeroWindow = StreamWire.encodeFrame({ type: StreamWire.FrameType.WINDOW_UPDATE, streamID: 1, delta: 1 }) + zeroWindow[13] = 0 + expect(() => StreamWire.decodeFrame(zeroWindow)).toThrow(StreamWire.WireProtocolError) + // Oversized frame length header (> MAX_FRAME_PAYLOAD_BYTES) + const oversized = new Uint8Array(10) + const view = new DataView(oversized.buffer) + view.setUint8(0, 1) + view.setUint8(1, StreamWire.FrameType.DATA) + view.setUint32(2, 1, false) + view.setUint32(6, StreamWire.MAX_FRAME_PAYLOAD_BYTES + 1, false) + expect(() => StreamWire.decodeFrame(oversized)).toThrow(StreamWire.WireProtocolError) + // Invalid host characters in OPEN + expect(() => + StreamWire.encodeFrame({ + type: StreamWire.FrameType.OPEN, + streamID: 1, + host: "evil.com/path", + port: 80, + initialWindow: 4096, + }), + ).toThrow(StreamWire.WireProtocolError) + }) +}) + +describe("StreamMux flow control, fairness, half-close, and RESET cancellation", () => { + test("transfers 1 MiB over a bounded 128 KiB window with batched credits and clean half-close", async () => { + const payload = Buffer.alloc(1024 * 1024) + for (let i = 0; i < payload.length; i++) payload[i] = (i * 31) & 0xff + const expectedHash = createHash("sha256").update(payload).digest("hex") + + const echo = createNetServer((socket) => socket.pipe(socket)) + await once(echo.listen(0, "127.0.0.1"), "listening") + const addr = echo.address() + if (!addr || typeof addr === "string") throw new Error("No TCP address") + + const pair = createSocketPair({ simulateBuffered: true }) + let windowUpdates = 0 + const offSpy = pair.server.onMessage((raw) => { + if (raw instanceof Uint8Array && raw.byteLength >= 10 && raw[1] === StreamWire.FrameType.WINDOW_UPDATE) { + windowUpdates += 1 + } + }) + const serverMux = StreamMux.createServerMux(pair.server, { + policy: EgressPolicy.makePolicy(), + streamWindowBytes: 128 * 1024, + creditBatchBytes: 32 * 1024, + heartbeatIntervalMs: 0, + }) + const clientMux = StreamMux.createClientMux(pair.client, { + streamWindowBytes: 128 * 1024, + creditBatchBytes: 32 * 1024, + heartbeatIntervalMs: 0, + }) + + try { + const stream = await clientMux.openStream({ host: "127.0.0.1", port: addr.port }) + const received = new Promise((resolve, reject) => { + const chunks: Buffer[] = [] + stream.on("data", (chunk: Buffer) => chunks.push(chunk)) + stream.once("end", () => resolve(Buffer.concat(chunks))) + stream.once("error", reject) + }) + // Write 1 MiB then half-close (FIN) + stream.end(payload) + const got = await received + expect(got.byteLength).toBe(payload.byteLength) + expect(createHash("sha256").update(got).digest("hex")).toBe(expectedHash) + // Credits returned in batches (not per 16 KiB frame) + expect(windowUpdates).toBeGreaterThanOrEqual(8) + expect(windowUpdates).toBeLessThan(64) + expect(clientMux.activeStreams()).toBe(0) + } finally { + offSpy() + clientMux.close() + serverMux.close() + await new Promise((resolve) => echo.close(() => resolve())) + } + }, 15_000) + + test("fair bounded writer interleaves small interactive echo ahead of remaining bulk download deterministically", async () => { + const chunkSize = 16 * 1024 + const bulkChunks = 8 + const bulkSize = chunkSize * bulkChunks + const maxWsBufferedBytes = 32 * 1024 + + // Deterministic in-process target sockets so scheduling order depends solely on StreamMux's + // bounded writer and credit/priority rules—never wall-clock timers or OS TCP buffers. + // A plain PassThrough natively echoes written bytes and half-closes on end(). + const bulkTarget = new PassThrough({ highWaterMark: bulkSize }) + const echoTarget = new PassThrough() + + const flushTurns = async () => { + for (let i = 0; i < 4; i++) await new Promise((resolve) => setImmediate(resolve)) + } + + const pair = createSocketPair({ gateServerSends: true }) + const serverMux = StreamMux.createServerMux(pair.server, { + policy: EgressPolicy.makePolicy(), + streamWindowBytes: 128 * 1024, + creditBatchBytes: 32 * 1024, + frameChunkBytes: chunkSize, + maxWsBufferedBytes, + heartbeatIntervalMs: 0, + connect: async (target) => (target.port === 10001 ? bulkTarget : echoTarget) as unknown as Socket, + }) + const clientMux = StreamMux.createClientMux(pair.client, { + streamWindowBytes: 128 * 1024, + creditBatchBytes: 32 * 1024, + frameChunkBytes: chunkSize, + maxWsBufferedBytes, + heartbeatIntervalMs: 0, + }) + + try { + // 1. Open bulk stream (stream 1) and deliver its OPENED control frame. + const bulkOpen = clientMux.openStream({ host: "127.0.0.1", port: 10001 }) + await flushTurns() + expect(pair.flushOneServerFrame()).toBe(true) + const bulkStream = await bulkOpen + + let bulkReceived = 0 + let bulkBytesWhenEchoDone = -1 + const bulkDone = Promise.withResolvers() + bulkStream.on("data", (chunk: Buffer) => { + bulkReceived += chunk.byteLength + }) + bulkStream.once("end", () => bulkDone.resolve()) + + // 2. Push the entire 128 KiB bulk payload on the server target socket while server sends are gated. + // FrameWriter must stop at maxWsBufferedBytes (2 × 16 KiB frames) instead of dumping all 128 KiB. + for (let i = 0; i < bulkChunks; i++) bulkTarget.write(Buffer.alloc(chunkSize, i + 1)) + bulkTarget.end() + await flushTurns() + + const bulkQueuedBeforeEcho = pair.serverRaw.sentFrames.filter( + (frame) => frame.type === StreamWire.FrameType.DATA && frame.streamID === 1, + ).length + expect(bulkQueuedBeforeEcho).toBe(2) + expect(pair.serverRaw.bufferedAmount).toBeGreaterThanOrEqual(maxWsBufferedBytes) + expect(pair.serverRaw.bufferedAmount).toBeLessThan(bulkSize) + + // 3. Open interactive echo stream (stream 2) while bulk is saturated at maxWsBufferedBytes. + // Priority control (OPENED) still enqueues immediately ahead of the remaining 6 bulk chunks. + let echoReady = false + const echoOpen = clientMux.openStream({ host: "127.0.0.1", port: 10002 }).then((stream) => { + echoReady = true + return stream + }) + await flushTurns() + // Verify OPENED(2) was queued immediately ahead of the remaining bulk DATA frames while bulk was paused. + const openedEchoIndex = pair.serverRaw.sentFrames.findIndex( + (frame) => frame.type === StreamWire.FrameType.OPENED && frame.streamID === 2, + ) + expect(openedEchoIndex).toBe(3) // [OPENED(1), DATA(1), DATA(1), OPENED(2)] + // Flush only until OPENED(2) is delivered to the client so echoStream opens while bulk still has chunks queued. + while (!echoReady && pair.flushOneServerFrame()) { + await flushTurns() + } + const echoStream = await echoOpen + + const echoDone = Promise.withResolvers() + const echoParts: Buffer[] = [] + echoStream.on("data", (chunk: Buffer) => echoParts.push(chunk)) + echoStream.once("end", () => { + bulkBytesWhenEchoDone = bulkReceived + echoDone.resolve(Buffer.concat(echoParts).toString()) + }) + echoStream.end("hmr-ping") + await flushTurns() + + // 4. Deterministically pump one server frame at a time until both echo and bulk complete. + for (let steps = 0; steps < 200; steps++) { + const flushed = pair.flushOneServerFrame() + await flushTurns() + if (!flushed) { + if (bulkReceived === bulkSize && bulkBytesWhenEchoDone >= 0) break + await flushTurns() + if (!pair.flushOneServerFrame()) break + } + } + + expect(await echoDone.promise).toBe("hmr-ping") + await bulkDone.promise + expect(bulkReceived).toBe(bulkSize) + + // Verify wire scheduling order and bounded bufferedAmount directly: + // echo DATA was transmitted ahead of the remaining bulk DATA frames, and ws.bufferedAmount stayed bounded. + const echoDataIndex = pair.serverRaw.sentFrames.findIndex( + (frame) => frame.type === StreamWire.FrameType.DATA && frame.streamID === 2, + ) + const lastBulkDataIndex = pair.serverRaw.sentFrames.findLastIndex( + (frame) => frame.type === StreamWire.FrameType.DATA && frame.streamID === 1, + ) + expect(echoDataIndex).toBeGreaterThan(0) + expect(lastBulkDataIndex).toBeGreaterThan(echoDataIndex) + expect(bulkBytesWhenEchoDone).toBeGreaterThan(0) + expect(bulkBytesWhenEchoDone).toBeLessThan(bulkSize) + expect(pair.serverRaw.maxBufferedAmount).toBeLessThan(bulkSize) + } finally { + clientMux.close() + serverMux.close() + bulkTarget.destroy() + echoTarget.destroy() + } + }) + + test("destroying a client stream mid-transfer sends RESET and destroys the server target socket", async () => { + const peerClosed = Promise.withResolvers() + const server = createNetServer((socket) => { + socket.once("close", () => peerClosed.resolve()) + socket.write(Buffer.alloc(16 * 1024)) + }) + await once(server.listen(0, "127.0.0.1"), "listening") + const addr = server.address() + if (!addr || typeof addr === "string") throw new Error("No TCP address") + + const pair = createSocketPair() + const serverMux = StreamMux.createServerMux(pair.server, { + policy: EgressPolicy.makePolicy(), + streamWindowBytes: 64 * 1024, + heartbeatIntervalMs: 0, + }) + const clientMux = StreamMux.createClientMux(pair.client, { + streamWindowBytes: 64 * 1024, + heartbeatIntervalMs: 0, + }) + + try { + const stream = await clientMux.openStream({ host: "127.0.0.1", port: addr.port }) + await new Promise((resolve) => stream.once("data", () => resolve())) + // Abort mid-stream (video seek / tab close) + stream.destroy() + await peerClosed.promise + expect(serverMux.activeStreams()).toBe(0) + expect(serverMux.bufferedBytes()).toBe(0) + } finally { + clientMux.close() + serverMux.close() + await new Promise((resolve) => server.close(() => resolve())) + } + }, 15_000) + + test("a stalled slow reader on stream 1 does not block stream 2 and respects window cap", async () => { + const slowServer = createNetServer((socket) => { + socket.write(Buffer.alloc(256 * 1024, 0x11)) + }) + const fastServer = createNetServer((socket) => { + socket.end("fast-ok") + }) + await Promise.all([ + once(slowServer.listen(0, "127.0.0.1"), "listening"), + once(fastServer.listen(0, "127.0.0.1"), "listening"), + ]) + const slowAddr = slowServer.address() + const fastAddr = fastServer.address() + if (!slowAddr || typeof slowAddr === "string" || !fastAddr || typeof fastAddr === "string") { + throw new Error("No TCP address") + } + + const pair = createSocketPair() + const serverMux = StreamMux.createServerMux(pair.server, { + policy: EgressPolicy.makePolicy(), + streamWindowBytes: 32 * 1024, + creditBatchBytes: 8 * 1024, + heartbeatIntervalMs: 0, + }) + const clientMux = StreamMux.createClientMux(pair.client, { + streamWindowBytes: 32 * 1024, + creditBatchBytes: 8 * 1024, + heartbeatIntervalMs: 0, + }) + + try { + // Open stream 1 and intentionally NEVER attach a data listener (stalled reader) + const full = Promise.withResolvers() + let bytes = 0 + const off = pair.client.onMessage((raw) => { + if (typeof raw === "string") return + const frame = StreamWire.decodeFrame(raw) + if (frame.type !== StreamWire.FrameType.DATA) return + bytes += frame.data.byteLength + if (bytes >= 32 * 1024) full.resolve() + }) + const slow = await clientMux.openStream({ host: "127.0.0.1", port: slowAddr.port }) + await full.promise + off() + // Client buffered bytes stay strictly bounded by the 32 KiB window + expect(clientMux.bufferedBytes()).toBeLessThanOrEqual(32 * 1024) + + // Stream 2 still opens and finishes immediately without blocking on stream 1! + const fast = await clientMux.openStream({ host: "127.0.0.1", port: fastAddr.port }) + const fastData = await new Promise((resolve) => { + const parts: Buffer[] = [] + fast.on("data", (d: Buffer) => parts.push(d)) + fast.once("end", () => resolve(Buffer.concat(parts).toString())) + }) + expect(fastData).toBe("fast-ok") + slow.destroy() + } finally { + clientMux.close() + serverMux.close() + await Promise.all([ + new Promise((resolve) => slowServer.close(() => resolve())), + new Promise((resolve) => fastServer.close(() => resolve())), + ]) + } + }, 15_000) + + test("detach cancels credit-starved write and FIN callbacks; an idle stream closes normally", async () => { + const pair = createSocketPair() + const client = StreamMux.createClientMux(pair.client, { + streamOutboundHighWaterBytes: 4096, + frameChunkBytes: 4096, + heartbeatIntervalMs: 0, + }) + const windowsSpent = Promise.withResolvers() + let sent = 0 + // The peer admits each stream but never returns credit, so only its initial 4 KiB can leave the client. + pair.server.onMessage((raw) => { + if (typeof raw === "string") return + const frame = StreamWire.decodeFrame(raw) + if (frame.type === StreamWire.FrameType.OPEN) { + pair.server.send( + StreamWire.encodeFrame({ type: StreamWire.FrameType.OPENED, streamID: frame.streamID, initialWindow: 4096 }), + ) + } + if (frame.type === StreamWire.FrameType.DATA) { + sent += frame.data.byteLength + if (sent >= 8192) windowsSpent.resolve() + } + }) + + try { + const target = { host: "localhost", port: 5173 } + const writing = await client.openStream(target) + const first = Promise.withResolvers() + const queued = Promise.withResolvers() + writing.write(Buffer.alloc(16 * 1024), first.resolve) + writing.write(Buffer.alloc(8 * 1024), queued.resolve) + + const ending = await client.openStream(target) + const ended = Promise.withResolvers() + let finished = false + ending.once("finish", () => { + finished = true + }) + ending.write(Buffer.alloc(6 * 1024)) + ending.end(ended.resolve) + + const idle = await client.openStream(target) + const idleClosed = once(idle, "close") + await windowsSpent.promise + client.close(1000, "desktop detached") + const errors = await Promise.all([first.promise, queued.promise, ended.promise]) + await idleClosed + for (const error of errors) expect(error).toBeInstanceOf(Error) + expect(errors[0]?.message).toContain("desktop detached") + expect(finished).toBe(false) + expect(sent).toBe(8192) + } finally { + client.close() + } + }) + + test("rejects text WebSocket frames as a protocol error and closes cleanly", async () => { + const pair = createSocketPair() + const serverMux = StreamMux.createServerMux(pair.server, { + policy: EgressPolicy.makePolicy(), + heartbeatIntervalMs: 0, + }) + pair.serverRaw.deliver("not-binary-frame") + const closed = await serverMux.closed + expect(closed.code).toBe(1002) + }) +}) + +describe("BrowserProxy attachment lifetime", () => { + test("TunnelTicket schema accepts only the fixed experimental browser tunnel path", () => { + expect( + Schema.decodeUnknownSync(Browser.TunnelTicket)({ + ticket: "tkt_1", + expiresIn: 30, + protocol: 1, + path: BrowserTunnelHost.BROWSER_TUNNEL_PATH, + }).path, + ).toBe("/api/experimental/browser/tunnel") + for (const bad of ["https://evil.example/api/experimental/browser/tunnel", "//evil.example/x", "/api/other"]) { + expect(() => + Schema.decodeUnknownSync(Browser.TunnelTicket)({ + ticket: "tkt_1", + expiresIn: 30, + protocol: 1, + path: bad, + }), + ).toThrow() + } + }) + + test.each(["detach", "disconnect"] as const)("%s closes upgraded and pooled sockets", async (ending) => { + const stalled = Promise.withResolvers() + const release = Promise.withResolvers() + const target = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(req, server) { + const path = new URL(req.url).pathname + if (path === "/ws" && server.upgrade(req)) return + if (path === "/stall") { + stalled.resolve() + return release.promise + } + return new Response("ok") + }, + websocket: { + message(ws, message) { + ws.send(message) + }, + }, + }) + const pair = createSocketPair({ simulateBuffered: true }) + const server = StreamMux.createServerMux(pair.server, { policy: EgressPolicy.makePolicy(), heartbeatIntervalMs: 0 }) + const client = StreamMux.createClientMux(pair.client, { heartbeatIntervalMs: 0 }) + let opens = 0 + const listeners = new Set<() => void>() + const proxy = await BrowserProxy.make({ + openStream(destination, signal) { + opens++ + return client.openStream(destination, signal) + }, + onReset(listener) { + listeners.add(listener) + return () => listeners.delete(listener) + }, + }) + void client.closed.then(() => listeners.forEach((reset) => reset())) + const headers = { + "proxy-authorization": `Basic ${Buffer.from(`${proxy.credentials.username}:${proxy.credentials.password}`).toString("base64")}`, + } + const options = { hostname: proxy.host, port: proxy.port } + const get = (path: string, host = "127.0.0.1") => + new Promise((resolve, reject) => { + const req = httpRequest({ ...options, headers, path: `http://${host}:${target.port}${path}` }, (res) => { + res.resume() + res.once("end", () => resolve(res.statusCode)) + res.once("error", reject) + }) + req.once("error", reject).end() + }) + + try { + expect(await get("/a")).toBe(200) + expect(await get("/b")).toBe(200) + expect(opens).toBe(1) + + // Keep the upgraded connection open alongside the idle HTTP pool until the attachment ends. + const method = ending === "detach" ? "GET" : "CONNECT" + const upgraded = httpRequest({ + ...options, + method, + path: method === "GET" ? new URL("/ws", target.url).href : target.url.host, + headers: + method === "CONNECT" + ? headers + : { + ...headers, + connection: "upgrade", + upgrade: "websocket", + "sec-websocket-version": "13", + "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==", + }, + }) + const established = once(upgraded, method === "GET" ? "upgrade" : "connect") + upgraded.end() + const [response, socket] = await established + expect(response.statusCode).toBe(method === "GET" ? 101 : 200) + const closed = once(socket, "close") + + if (ending === "detach") { + client.close(1000, "desktop detached") + await proxy.close() + } else { + // Use a second origin so the previously warmed socket is still idle when the tunnel drops. + const pending = get("/stall", "localhost").catch(() => "closed") + await stalled.promise + pair.server.terminate() + expect([502, "closed"]).toContain((await pending) ?? 0) + } + await closed + await server.closed + expect(server.activeStreams()).toBe(0) + } finally { + release.resolve(new Response(null, { status: 503 })) + await proxy.close() + client.close() + server.close() + await target.stop(true) + } + }) +}) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 7b7a3653924..fa8e1c48ab4 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -12587,6 +12587,59 @@ "summary": "Read a blob" } }, + "/api/experimental/browser/tunnel": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.browser.tunnel", + "parameters": [], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + } + }, + "description": "Upgrade to a binary WebSocket carrying multiplexed TCP streams for one live desktop browser attachment. Requires a short-lived, single-use attachment-bound ticket in the x-opencode-browser-ticket header minted through authenticated browser RPC. Never accepts a session ID or browser cookie alone. Experimental: may change without compatibility guarantees.", + "summary": "Open a browser attachment binary stream tunnel", + "x-websocket": true + } + }, "/api/experimental/automation": { "post": { "tags": ["experimental"], @@ -18576,6 +18629,9 @@ "sqlite_fts": { "type": "boolean" }, + "browser_stream_tunnel": { + "type": "boolean" + }, "video_generate": { "anyOf": [ { diff --git a/packages/protocol/src/groups/experimental.ts b/packages/protocol/src/groups/experimental.ts index 701a9bb0b9d..8e9bcf43d19 100644 --- a/packages/protocol/src/groups/experimental.ts +++ b/packages/protocol/src/groups/experimental.ts @@ -1,5 +1,6 @@ import { ArtifactEndpoints } from "./artifact.js" import { BlobGetEndpoint } from "./blob.js" +import { BrowserTunnelEndpoint } from "./experimental/browser-tunnel.js" import { AutomationEndpoints } from "./automation.js" import { JobEndpoints } from "./job.js" import { MachineEndpoints } from "./machine.js" @@ -11,6 +12,7 @@ import { PushEndpoints } from "./push.js" export const ExperimentalGroup = PersistentPtyGroup.add( MediaGetEndpoint, BlobGetEndpoint, + BrowserTunnelEndpoint, ...AutomationEndpoints, ...ArtifactEndpoints, ...JobEndpoints, diff --git a/packages/protocol/src/groups/experimental/browser-tunnel.ts b/packages/protocol/src/groups/experimental/browser-tunnel.ts new file mode 100644 index 00000000000..aebb72166d9 --- /dev/null +++ b/packages/protocol/src/groups/experimental/browser-tunnel.ts @@ -0,0 +1,41 @@ +import { Schema } from "effect" +import { HttpApiEndpoint, OpenApi } from "effect/http-api" +import { ForbiddenError } from "../../errors.js" +import { isWebSocketUpgrade } from "../machine.js" + +export const BROWSER_TUNNEL_PATH = "/api/experimental/browser/tunnel" +export const BROWSER_TUNNEL_TICKET_HEADER = "x-opencode-browser-ticket" +export const BROWSER_TUNNEL_SESSION_HEADER = "x-opencode-browser-session" +export const BROWSER_TUNNEL_CONNECTION_HEADER = "x-opencode-browser-connection" +export const BROWSER_TUNNEL_PROTOCOL_HEADER = "x-opencode-browser-protocol" +export const BROWSER_TUNNEL_PROTOCOL_VERSION = 1 + +/** + * Whether a request targets the browser stream tunnel upgrade with a non-empty ticket header. + * Compares the raw request path before any query string so URL normalization cannot alias another route. + */ +export function hasBrowserTunnelUpgrade(request: { + readonly method: string + readonly url: string + readonly headers: Readonly> +}) { + return ( + request.url.split("?", 1)[0] === BROWSER_TUNNEL_PATH && + isWebSocketUpgrade(request) && + !!request.headers[BROWSER_TUNNEL_TICKET_HEADER]?.trim() + ) +} + +/** Lives in the `server.experimental` group (see `groups/experimental.ts`). */ +export const BrowserTunnelEndpoint = HttpApiEndpoint.get("browser.tunnel", BROWSER_TUNNEL_PATH, { + success: Schema.Boolean, + error: [ForbiddenError], +}).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.browser.tunnel", + summary: "Open a browser attachment binary stream tunnel", + description: + "Upgrade to a binary WebSocket carrying multiplexed TCP streams for one live desktop browser attachment. Requires a short-lived, single-use attachment-bound ticket in the x-opencode-browser-ticket header minted through authenticated browser RPC. Never accepts a session ID or browser cookie alone. Experimental: may change without compatibility guarantees.", + transform: (operation) => ({ ...operation, "x-websocket": true, tags: ["experimental"] }), + }), +) diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index 350220e2a75..2a4ae6eac9d 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -32,6 +32,8 @@ export const registry = { "List a session's subagents, with their session IDs, and its running background jobs in its compaction checkpoints, so the agent can still continue or account for them after compacting.", sqlite_fts: "Build an SQLite full-text index of session titles and message text in the background, and enable the opencode.session.search and opencode.session.read tools. The index covers every session in the database and starts while any loaded location enables it; SQLite keeps it current from then on, also after this is turned off.", + browser_stream_tunnel: + "Stream remote desktop browser TCP traffic over one prewarmed, ticket-authenticated binary WebSocket per live browser attachment instead of per-chunk RPC.", } as const satisfies Record export type Key = keyof typeof registry diff --git a/packages/server/src/handlers/experimental/browser-tunnel.ts b/packages/server/src/handlers/experimental/browser-tunnel.ts new file mode 100644 index 00000000000..25ca718c8f2 --- /dev/null +++ b/packages/server/src/handlers/experimental/browser-tunnel.ts @@ -0,0 +1,218 @@ +import { NodeHttpServerRequest } from "@effect/platform-node" +import { type WebSocket, WebSocketServer } from "@effect/platform-node-shared/NodeWS" +import { BrowserTunnelGateway } from "@opencode/core/experimental/browser-tunnel" +import { LocationLifecycle } from "@opencode/core/location-lifecycle" +import { LocationServiceMap } from "@opencode/core/location-service-map" +import { + BROWSER_TUNNEL_CONNECTION_HEADER, + BROWSER_TUNNEL_PROTOCOL_HEADER, + BROWSER_TUNNEL_PROTOCOL_VERSION, + BROWSER_TUNNEL_SESSION_HEADER, + BROWSER_TUNNEL_TICKET_HEADER, +} from "@opencode/protocol/groups/experimental/browser-tunnel" +import { isWebSocketUpgrade } from "@opencode/protocol/groups/machine" +import { Session } from "@opencode/schema/session" +import { Effect, Option, Schema, Scope } from "effect" +import { HttpMiddleware, type HttpServerRequest, HttpServerResponse } from "effect/http" +import { IncomingMessage } from "node:http" +import { CorsConfig, isAllowedRequestOrigin } from "../../cors" +import { locationErrors, requestRef } from "../../location" + +const STOPPING = "1 second" +const CLOSING = "5 seconds" + +function toUint8Array(data: unknown): Uint8Array { + if (data instanceof Uint8Array) return data + if (data instanceof ArrayBuffer) return new Uint8Array(data) + if (Array.isArray(data)) { + const buffers = data.map((part) => (part instanceof Uint8Array ? part : new Uint8Array(part))) + return Buffer.concat(buffers) + } + return new Uint8Array() +} + +function adaptWebSocket(ws: WebSocket): BrowserTunnelGateway.BinarySocket { + return { + get readyState() { + return ws.readyState + }, + get bufferedAmount() { + return ws.bufferedAmount + }, + send(data, onWritten) { + ws.send(data, { binary: true, compress: false }, (error) => onWritten?.(error ?? undefined)) + }, + ping() { + if (ws.readyState === ws.OPEN) ws.ping() + }, + close(code, reason) { + if (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING) { + ws.close(code, reason) + } + }, + terminate() { + ws.terminate() + }, + onMessage(listener) { + const handler = (raw: unknown, isBinary: boolean) => { + if (!isBinary) { + listener(String(raw)) + return + } + listener(toUint8Array(raw)) + } + ws.on("message", handler) + // Resume after the mux listener is attached so frames sent immediately after 101 are never lost. + ws.resume() + return () => { + ws.off("message", handler) + } + }, + onClose(listener) { + const handler = (code: number, reason: Buffer) => listener(code, reason.toString("utf8")) + ws.on("close", handler) + return () => { + ws.off("close", handler) + } + }, + onError(listener) { + ws.on("error", listener) + return () => { + ws.off("error", listener) + } + }, + onPong(listener) { + ws.on("pong", listener) + return () => { + ws.off("pong", listener) + } + }, + } +} + +const upgradeSocket = (sockets: WebSocketServer, incoming: IncomingMessage) => + Effect.acquireRelease( + Effect.callback((resume) => { + const refused = () => resume(Effect.fail(new Error("WebSocket upgrade closed before completion."))) + if (incoming.socket.destroyed) return refused() + incoming.socket.once("close", refused) + sockets.handleUpgrade(incoming, incoming.socket, Buffer.alloc(0), (ws) => { + incoming.socket.off("close", refused) + incoming.socket.setNoDelay(true) + // Pause until the attachment's mux installs its message listener. + ws.pause() + resume(Effect.succeed(ws)) + }) + }), + (ws) => + Effect.gen(function* () { + if (ws.readyState === ws.CLOSED) return + const gone = Effect.callback((resume) => { + if (ws.readyState === ws.CLOSED) return resume(Effect.void) + ws.once("close", () => resume(Effect.void)) + }) + ws.close(1001, "server closing") + if (Option.isNone(yield* Effect.timeoutOption(gone, CLOSING))) ws.terminate() + }), + ) + +/** + * Narrow experimental upgrade route for remote desktop browser streaming. + * Authenticates a single-use, attachment-bound ticket from `x-opencode-browser-ticket`, + * checks origin, upgrades to a raw binary WebSocket, and hands ownership directly to the + * live browser attachment. Never exposes a general TCP proxy API. + */ +export const makeBrowserTunnel = Effect.gen(function* () { + const gateway = yield* BrowserTunnelGateway.Service + const locations = yield* LocationServiceMap.Service + const cors = yield* CorsConfig + const scope = yield* Effect.scope + + const server = yield* Effect.cached( + Effect.acquireRelease( + Effect.sync( + () => + new WebSocketServer({ + noServer: true, + perMessageDeflate: false, + maxPayload: BrowserTunnelGateway.MAX_WS_FRAME_BYTES, + }), + ), + (sockets) => + Effect.gen(function* () { + sockets.clients.forEach((ws) => ws.close(1012, "server stopping")) + const empty = Effect.callback((resume) => sockets.close(() => resume(Effect.void))) + if (Option.isNone(yield* Effect.timeoutOption(empty, STOPPING))) { + sockets.clients.forEach((ws) => ws.terminate()) + } + }), + ).pipe(Scope.provide(scope)), + ) + + return Effect.fn("BrowserTunnelHandler.connect")(function* (request: HttpServerRequest.HttpServerRequest) { + if (!isAllowedRequestOrigin(request.headers.origin, request.headers.host, cors)) { + return HttpServerResponse.empty({ status: 403 }) + } + const incoming = NodeHttpServerRequest.toIncomingMessage(request) + if (!(incoming instanceof IncomingMessage) || !isWebSocketUpgrade(request)) { + return HttpServerResponse.empty({ status: 400 }) + } + + const url = new URL(request.url, "http://localhost") + // Ticket must travel exclusively in the upgrade header, never in URLs or query strings. + if (url.searchParams.has("ticket")) { + return HttpServerResponse.empty({ status: 403 }) + } + const ticket = request.headers[BROWSER_TUNNEL_TICKET_HEADER]?.trim() + if (!ticket) { + return HttpServerResponse.empty({ status: 403 }) + } + + const rawSession = request.headers[BROWSER_TUNNEL_SESSION_HEADER]?.trim() ?? url.searchParams.get("sessionID")?.trim() + const connectionID = + request.headers[BROWSER_TUNNEL_CONNECTION_HEADER]?.trim() ?? url.searchParams.get("connectionID")?.trim() + const rawProtocol = + request.headers[BROWSER_TUNNEL_PROTOCOL_HEADER]?.trim() ?? url.searchParams.get("protocol")?.trim() + const protocol = rawProtocol ? Number(rawProtocol) : NaN + const sessionID = rawSession ? Option.getOrUndefined(Schema.decodeUnknownOption(Session.ID)(rawSession)) : undefined + + if (!sessionID || !connectionID || protocol !== BROWSER_TUNNEL_PROTOCOL_VERSION) { + return HttpServerResponse.empty({ status: 403 }) + } + + const ref = LocationServiceMap.canonical(requestRef(request)) + const binding = yield* gateway.consumeTicket({ + ticket, + location: ref, + sessionID, + connectionID, + protocol, + }) + if (!binding) { + return HttpServerResponse.empty({ status: 403 }) + } + + if (Option.isNone(yield* Effect.option(request.upgrade))) { + return HttpServerResponse.empty({ status: 400 }) + } + + return yield* Effect.gen(function* () { + const sockets = yield* server + const ws = yield* upgradeSocket(sockets, incoming) + yield* HttpMiddleware.withLoggerDisabled(Effect.void) + const lifecycle = yield* LocationLifecycle.Service + yield* lifecycle.retain + yield* lifecycle.awaitShutdown.pipe( + Effect.andThen(Effect.sync(() => ws.close(1012, "location shut down"))), + Effect.forkChild, + ) + yield* binding.onUpgrade(adaptWebSocket(ws)) + return HttpServerResponse.empty() + }).pipe( + Effect.scoped, + Effect.provide(locations.get(ref)), + locationErrors, + Effect.orElseSucceed(() => HttpServerResponse.empty()), + ) + }) +}) diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index 1fa83009413..d5966ddf7a5 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -19,6 +19,7 @@ import { Api } from "../api" import { CorsConfig, isAllowedRequestOrigin } from "../cors" import { makeArtifact } from "./artifact" import { makeBlobGet } from "./blob" +import { makeBrowserTunnel } from "./experimental/browser-tunnel" import { makeAutomation } from "./automation" import { makeJob } from "./job" import { makeMachine, makeMachineLink } from "./machine" @@ -38,11 +39,13 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment const automation = yield* makeAutomation const machine = yield* makeMachine const machineLink = yield* makeMachineLink + const browserTunnel = yield* makeBrowserTunnel const push = yield* makePush return handlers .handleRaw("media.get", (ctx) => mediaGet(ctx.params.hash, ctx.request)) .handleRaw("blob.get", (ctx) => blobGet(ctx.params.id, ctx.request)) + .handleRaw("browser.tunnel", (ctx) => browserTunnel(ctx.request)) .handle("job.list", (ctx) => job.list(ctx.query)) .handle("job.cancel", (ctx) => job.cancel(ctx.params.id)) .handleRaw("machine.link", (ctx) => machineLink(ctx.request)) diff --git a/packages/server/src/middleware/authorization.ts b/packages/server/src/middleware/authorization.ts index 257ecd6a040..b79b1d55340 100644 --- a/packages/server/src/middleware/authorization.ts +++ b/packages/server/src/middleware/authorization.ts @@ -5,6 +5,7 @@ export { Authorization } from "@opencode/protocol/middleware/authorization" import { PTY_CONNECT_PATH, PTY_CONNECT_TICKET_QUERY } from "@opencode/protocol/groups/pty" import { PERSISTENT_PTY_CONNECT_PATH } from "@opencode/protocol/groups/persistent-pty" import { MCP_CLIENT_PATH } from "@opencode/protocol/groups/mcp" +import { BROWSER_TUNNEL_PATH, hasBrowserTunnelUpgrade } from "@opencode/protocol/groups/experimental/browser-tunnel" import { isWebSocketUpgrade, MACHINE_LINK_PATH } from "@opencode/protocol/groups/machine" import { PAIRING_CONNECT_PATH } from "@opencode/protocol/groups/server" import { Effect, Layer, Redacted } from "effect" @@ -99,6 +100,9 @@ export const authorizationLayer = Layer.effect( // request to the route is checked like the rest, and with machines off the handler answers the upgrade as an // unknown route. if (route.route.path === MACHINE_LINK_PATH && isWebSocketUpgrade(request)) return yield* effect + // Browser stream tunnel upgrades authenticate with a short-lived, single-use attachment-bound ticket + // in the x-opencode-browser-ticket header, consumed atomically by the handler. + if (route.route.path === BROWSER_TUNNEL_PATH && hasBrowserTunnelUpgrade(request)) return yield* effect if (yield* authorizedRequest(request, config)) return yield* effect if (challengeRequest(request)) yield* HttpEffect.appendPreResponseHandler((_request, response) => diff --git a/packages/server/src/process.ts b/packages/server/src/process.ts index 44a60660616..43b5197f41b 100644 --- a/packages/server/src/process.ts +++ b/packages/server/src/process.ts @@ -1,6 +1,7 @@ export * as ServerProcess from "./process" import { NodeHttpServer } from "@effect/platform-node" +import { BrowserTunnelGateway } from "@opencode/core/experimental/browser-tunnel" import { Bus } from "@opencode/core/bus" import { SessionRestart } from "@opencode/core/session/execution/restart" import { Automation } from "@opencode/core/automation" @@ -8,6 +9,7 @@ import { SessionSearchBuild } from "@opencode/core/session/search-build" import { InstallationEvent } from "@opencode/schema/installation-event" import { hasPtyConnectTicketURL } from "@opencode/protocol/groups/pty" import { hasPersistentPtyConnectTicketURL } from "@opencode/protocol/groups/persistent-pty" +import { hasBrowserTunnelUpgrade } from "@opencode/protocol/groups/experimental/browser-tunnel" import { hasMcpClientTicketURL } from "@opencode/protocol/groups/mcp" import { isMachineLinkUpgrade } from "@opencode/protocol/groups/machine" import { isPairingConnectURL } from "@opencode/protocol/groups/server" @@ -132,6 +134,12 @@ export const start = Effect.fn("ServerProcess.start")(function* ( yield* Effect.forkIn(Context.get(context, Automation.Service).run, applicationScope) // Likewise the one-time session search build, once a location has sqlite_fts on. yield* Effect.forkIn(Context.get(context, SessionSearchBuild.Service).run, applicationScope) + const boundAddress = bound.server.address() + if (boundAddress && typeof boundAddress !== "string") { + const gateway = Context.get(context, BrowserTunnelGateway.Service) + yield* gateway.addReservedLocalPort(boundAddress.port) + yield* Scope.addFinalizer(applicationScope, gateway.removeReservedLocalPort(boundAddress.port)) + } yield* Ref.set(machinesFlag, yield* machinesEnabled.pipe(Effect.provide(context))) yield* Ref.set(application, Option.some(Context.get(context, HttpRouter.HttpRouter).asHttpEffect())) yield* status.ready @@ -222,6 +230,7 @@ function dispatch( (!hasPtyConnectTicketURL(url) && !hasPersistentPtyConnectTicketURL(url) && !hasMcpClientTicketURL(url) && + !hasBrowserTunnelUpgrade(request) && // With machines off the link's path is an unknown route, and gets this 401 like one. !(isMachineLinkUpgrade(request) && (yield* machines)))) && !(yield* authorizedRequest(request, auth)) diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 223a958307d..06705abde3a 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -12,6 +12,7 @@ import { FileSystemSearch } from "@opencode/core/filesystem/search" import { Credential } from "@opencode/core/credential" import { Config } from "@opencode/core/config" import { PermissionSaved } from "@opencode/core/permission/saved" +import { BrowserTunnelGateway } from "@opencode/core/experimental/browser-tunnel" import { PtyTicket } from "@opencode/core/pty/ticket" import { PersistentPty } from "@opencode/core/persistent-pty" import { Project } from "@opencode/core/project" @@ -93,6 +94,7 @@ const applicationServiceNodes = [ PluginUpdate.node, PermissionSaved.node, PtyTicket.node, + BrowserTunnelGateway.node, Credential.node, WellKnown.node, ServerPairing.node, diff --git a/packages/server/test/browser-tunnel.test.ts b/packages/server/test/browser-tunnel.test.ts new file mode 100644 index 00000000000..6fdf86da3b7 --- /dev/null +++ b/packages/server/test/browser-tunnel.test.ts @@ -0,0 +1,250 @@ +import { expect } from "bun:test" +import { NodeHttpClient } from "@effect/platform-node" +import { WebSocket } from "@effect/platform-node-shared/NodeWS" +import { + BROWSER_TUNNEL_CONNECTION_HEADER, + BROWSER_TUNNEL_PATH, + BROWSER_TUNNEL_PROTOCOL_HEADER, + BROWSER_TUNNEL_SESSION_HEADER, + BROWSER_TUNNEL_TICKET_HEADER, +} from "@opencode/protocol/groups/experimental/browser-tunnel" +import { AbsolutePath } from "@opencode/schema/schema" +import { Deferred, Effect, Fiber, Schedule, Stream } from "effect" +import { HttpClient, HttpClientRequest, HttpServer } from "effect/http" +import { once } from "node:events" +import { connect } from "node:net" +import { OpenCode } from "../../client/src/effect/index" +import { tmpdirScoped } from "../../core/test/fixture/tmpdir" +import { it } from "../../core/test/lib/effect" +import { Browser } from "../../plugin-browser/src/rpc" +import { BrowserTunnelHost, StreamWire } from "../../plugin-browser/src/stream" +import { ServerProcess } from "../src/process" + +const authHeader = `Basic ${btoa("opencode:secret")}` + +// Refusals are HTTP responses. Reading them before any WebSocket exists avoids runtime-specific WS error events. +const upgradeStatus = (url: URL, headers: Record) => + Effect.promise(async () => { + const socket = connect(Number(url.port), url.hostname) + try { + socket.write( + [ + `GET ${url.pathname}${url.search} HTTP/1.1`, + `Host: ${url.host}`, + "Connection: Upgrade", + "Upgrade: websocket", + "Sec-WebSocket-Version: 13", + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==", + ...Object.entries(headers).map(([key, value]) => `${key}: ${value}`), + "", + "", + ].join("\r\n"), + ) + let response = "" + for await (const chunk of socket) { + response += chunk.toString("latin1") + if (response.includes("\r\n")) return Number(response.split(" ", 2)[1]) + } + throw new Error("Upgrade ended without an HTTP response") + } finally { + socket.destroy() + } + }) + +const echoServer = Effect.acquireRelease( + Effect.sync(() => + Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + data(socket, chunk) { + socket.end(chunk) + }, + }, + }), + ), + (listener) => Effect.sync(() => listener.stop(true)), +) + +const bootServer = (enabled = true) => + Effect.gen(function* () { + const directory = (yield* tmpdirScoped("opencode-browser-tunnel-")).path + const server = yield* ServerProcess.start({ + hostname: "127.0.0.1", + port: 0, + password: "secret", + app: { version: "test-version" }, + database: { path: ":memory:" }, + models: { fetch: false }, + fs: { filewatcher: false }, + config: { + directory, + project: false, + content: JSON.stringify({ experimental: { browser_stream_tunnel: enabled } }), + }, + }) + const base = HttpServer.formatAddress(server.address) + const http = yield* HttpClient.HttpClient + const client = yield* OpenCode.make({ baseUrl: base }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.mapRequest(http, HttpClientRequest.setHeader("authorization", authHeader)), + ), + ) + const location = { directory: AbsolutePath.make(directory) } + yield* client.plugin.list({ location }).pipe( + Effect.repeat({ + until: (res) => res.data.some((p) => p.id === "opencode.browser"), + schedule: Schedule.spaced("50 millis").pipe(Schedule.upTo({ duration: "10 seconds" })), + }), + ) + const session = yield* client.session.create({ location }) + return { base, directory, client, location, rpc: client.rpc(Browser.Definition), sessionID: session.id } + }).pipe(Effect.provide(NodeHttpClient.layerNodeHttp)) + +const attachBrowser = (env: Effect.Success>, connectionID: string) => + Effect.gen(function* () { + const connected = yield* Deferred.make() + const attached = yield* Deferred.make() + yield* env.client.event.subscribe().pipe( + Stream.runForEach((event) => + Effect.gen(function* () { + if (event.type === "server.connected") yield* Deferred.succeed(connected, undefined) + if (event.type !== "rpc.experimental.browser.control") return + const data = event.data as { type?: string; connectionID?: string; capabilities?: readonly string[] } + if (data.type === "attached" && data.connectionID === connectionID) + yield* Deferred.succeed(attached, data.capabilities ?? []) + }), + ), + Effect.forkScoped({ startImmediately: true }), + ) + yield* Deferred.await(connected).pipe(Effect.timeout("5 seconds")) + const attachFiber = yield* env.rpc + .attach({ sessionID: env.sessionID, connectionID, version: 4 }, { location: env.location }) + .pipe(Effect.forkScoped({ startImmediately: true })) + const capabilities = yield* Deferred.await(attached).pipe(Effect.timeout("10 seconds")) + return { capabilities, attachFiber } + }) + +it.live( + "only a matching single-use ticket upgrades; attachment replacement revokes the socket and outstanding tickets", + () => + Effect.gen(function* () { + const env = yield* bootServer() + const attachment = { sessionID: env.sessionID, connectionID: "first" } + const options = { location: env.location } + const first = yield* attachBrowser(env, attachment.connectionID) + expect(first.capabilities).toContain(BrowserTunnelHost.STREAM_CAPABILITY) + + const issue = () => env.rpc["tunnel.ticket"]({ ...attachment, protocol: 1 }, options) + const issued = yield* issue() + expect(issued.path).toBe(BROWSER_TUNNEL_PATH) + const url = new URL(issued.path, env.base) + url.searchParams.set("location[directory]", env.directory) + const headers = { + [BROWSER_TUNNEL_SESSION_HEADER]: env.sessionID, + [BROWSER_TUNNEL_CONNECTION_HEADER]: attachment.connectionID, + [BROWSER_TUNNEL_PROTOCOL_HEADER]: "1", + [BROWSER_TUNNEL_TICKET_HEADER]: issued.ticket, + } + const wrongLocation = new URL(url) + wrongLocation.searchParams.set("location[directory]", env.directory + "/other") + expect(yield* upgradeStatus(wrongLocation, headers)).toBe(403) + const queryTicket = new URL(url) + queryTicket.searchParams.set("ticket", issued.ticket) + expect(yield* upgradeStatus(queryTicket, headers)).toBe(403) + expect( + yield* upgradeStatus(url, { ...headers, [BROWSER_TUNNEL_TICKET_HEADER]: "", authorization: authHeader }), + ).toBe(403) + expect(yield* upgradeStatus(url, { ...headers, [BROWSER_TUNNEL_CONNECTION_HEADER]: "other" })).toBe(403) + expect( + yield* upgradeStatus(url, { ...headers, [BROWSER_TUNNEL_SESSION_HEADER]: "ses_00000000000000000000000001" }), + ).toBe(403) + expect(yield* upgradeStatus(url, { ...headers, origin: "https://untrusted.example" })).toBe(403) + const info = yield* Effect.promise(() => fetch(new URL("/api/info", env.base), { headers })) + expect(info.status).toBe(401) + yield* Effect.promise(() => info.text()) + + // Native WS only on the successful path. After the HTTP attach request ends, this socket still owns the attachment. + const socket = yield* Effect.acquireRelease( + Effect.sync(() => { + const ws = new URL(url) + ws.protocol = "ws:" + return new WebSocket(ws, { headers }) + }), + (ws) => Effect.sync(() => ws.terminate()), + ) + yield* Effect.promise(() => once(socket, "open")) + expect(yield* upgradeStatus(url, headers)).toBe(403) + yield* Fiber.interrupt(first.attachFiber) + const echo = yield* echoServer + const exchange = (frame: StreamWire.Frame) => + Effect.promise(async () => { + const replied = once(socket, "message") + socket.send(StreamWire.encodeFrame(frame)) + const [raw] = await replied + return StreamWire.decodeFrame(raw) + }) + const streamID = 1 + expect( + yield* exchange({ + type: StreamWire.FrameType.OPEN, + streamID, + host: "127.0.0.1", + port: echo.port, + initialWindow: 4096, + }), + ).toMatchObject({ type: StreamWire.FrameType.OPENED, streamID }) + const ping = { type: StreamWire.FrameType.DATA, streamID, data: Uint8Array.of(120) } as const + expect(yield* exchange(ping)).toEqual(ping) + // Even a client using legacy RPC on this enabled attachment must respect the real server's reserved port. + expect( + yield* env.rpc["tunnel.open"]( + { + ...attachment, + target: { host: "127.0.0.1", port: Number(url.port) }, + }, + options, + ).pipe(Effect.flip), + ).toMatchObject({ type: "unavailable", message: expect.stringContaining("blocked") }) + + const unused = yield* issue() + const closed = once(socket, "close") + const next = yield* attachBrowser(env, "replacement") + const [code] = yield* Effect.promise(() => closed) + expect(code).toBe(BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED) + expect(yield* upgradeStatus(url, { ...headers, [BROWSER_TUNNEL_TICKET_HEADER]: unused.ticket })).toBe(403) + yield* Fiber.interrupt(next.attachFiber) + }), + 20_000, +) + +it.live( + "with browser_stream_tunnel off, a v4 attachment can relay bytes but cannot issue a ticket or grant", + () => + Effect.gen(function* () { + const env = yield* bootServer(false) + const attachment = { sessionID: env.sessionID, connectionID: "conn_legacy_1" } + const options = { location: env.location } + const att = yield* attachBrowser(env, attachment.connectionID) + expect(att.capabilities).not.toContain(BrowserTunnelHost.STREAM_CAPABILITY) + + const echo = yield* echoServer + const target = { host: "127.0.0.1", port: echo.port } + expect(yield* env.rpc["tunnel.ticket"]({ ...attachment, protocol: 1 }, options).pipe(Effect.flip)).toMatchObject({ + type: "unavailable", + }) + expect(yield* env.rpc["tunnel.grant"]({ ...attachment, target }, options).pipe(Effect.flip)).toMatchObject({ + type: "unavailable", + }) + + const tunnelID = yield* env.rpc["tunnel.open"]({ ...attachment, target }, options) + const tunnel = { ...attachment, tunnelID } + yield* env.rpc["tunnel.write"]({ ...tunnel, data: "eA==" }, options) + const response = yield* env.rpc["tunnel.read"](tunnel, options) + expect(Buffer.from(response.data).toString()).toBe("x") + yield* env.rpc["tunnel.close"](tunnel, options) + yield* Fiber.interrupt(att.attachFiber) + }), + 20_000, +)