-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Resolve resident browser proxy CDP #2463
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
miguelg719
wants to merge
15
commits into
v4-spike
Choose a base branch
from
feat/resident-transport
base: v4-spike
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
59c3589
Make stagehand.init the first runtime RPC
miguelg719 30a7788
Cover init handoff contracts
miguelg719 80de813
Merge remote-tracking branch 'stagehand/v4-spike' into feat/stagehand…
miguelg719 82b8765
Remove public browser connection status RPC
miguelg719 b13a8c2
Resolve resident browser proxy CDP
miguelg719 f70bdfd
Support default resident proxy ports
miguelg719 1d037f1
Format resident browser initialization
miguelg719 355f022
Merge branch 'feat/stagehand-init-first-rpc' into feat/resident-trans…
miguelg719 1451d8c
Sort generated protocol imports
miguelg719 a4b1b17
Merge branch 'feat/stagehand-init-first-rpc' into feat/resident-trans…
miguelg719 f732df4
Harden Stagehand initialization boundaries
miguelg719 d59ecef
Merge branch 'feat/stagehand-init-first-rpc' into feat/resident-trans…
miguelg719 d39f0ac
Make stagehand.init the first runtime RPC
miguelg719 03c7b9a
Merge branch 'feat/stagehand-init-first-rpc' into feat/resident-trans…
miguelg719 91cbcf2
Merge commit 'd77c902371c1d0462e812e0650b4dadaa4573be7' into feat/res…
miguelg719 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
86 changes: 86 additions & 0 deletions
86
packages/server/service-worker-lifecycle/resident-browser-proxy.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import { z } from "zod/v4"; | ||
|
|
||
| const BrowserVersionSchema = z.object({ | ||
| webSocketDebuggerUrl: z.string().min(1), | ||
| }); | ||
|
|
||
| const DEFAULT_RESOLVE_TIMEOUT_MS = 1_000; | ||
|
|
||
| export type ResidentBrowserProxyResolverOptions = { | ||
| fetch?: typeof globalThis.fetch; | ||
| timeoutMs?: number; | ||
| }; | ||
|
|
||
| export async function resolveResidentBrowserWebSocketUrl( | ||
| browserProxyUrl: string, | ||
| options: ResidentBrowserProxyResolverOptions = {}, | ||
| ): Promise<string> { | ||
| const proxyUrl = parseBrowserProxyUrl(browserProxyUrl); | ||
| const abortController = new AbortController(); | ||
| const timeout = setTimeout( | ||
| () => abortController.abort(), | ||
| options.timeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS, | ||
| ); | ||
|
|
||
| try { | ||
| const versionUrl = new URL("/json/version", proxyUrl); | ||
| const response = await (options.fetch ?? globalThis.fetch)(versionUrl, { | ||
| signal: abortController.signal, | ||
| }); | ||
| if (!response.ok) { | ||
| throw new Error(`Browser proxy version request failed with HTTP ${response.status}`); | ||
| } | ||
|
|
||
| const { webSocketDebuggerUrl } = BrowserVersionSchema.parse(await response.json()); | ||
| return rewriteDebuggerUrl(webSocketDebuggerUrl, proxyUrl); | ||
| } finally { | ||
| clearTimeout(timeout); | ||
| } | ||
| } | ||
|
|
||
| function parseBrowserProxyUrl(rawUrl: string): URL { | ||
| const url = new URL(rawUrl); | ||
| if (url.protocol !== "http:" && url.protocol !== "https:") { | ||
| throw new Error("Resident browser proxy URL must use http: or https:"); | ||
| } | ||
| if (!isLoopbackHostname(url.hostname)) { | ||
| throw new Error("Resident browser proxy URL must point to loopback"); | ||
| } | ||
| if (url.username || url.password || url.search || url.hash) { | ||
| throw new Error("Resident browser proxy URL must not include credentials, query, or fragment"); | ||
| } | ||
| if (url.pathname !== "/") { | ||
| throw new Error("Resident browser proxy URL must contain only an origin"); | ||
| } | ||
| return url; | ||
| } | ||
|
|
||
| function rewriteDebuggerUrl(rawUrl: string, proxyUrl: URL): string { | ||
| const debuggerUrl = new URL(rawUrl); | ||
| if (debuggerUrl.protocol !== "ws:") { | ||
| throw new Error("Chromium webSocketDebuggerUrl must use ws:"); | ||
| } | ||
| if (!isLoopbackHostname(debuggerUrl.hostname)) { | ||
| throw new Error("Chromium webSocketDebuggerUrl must point to loopback"); | ||
| } | ||
| if (debuggerUrl.username || debuggerUrl.password || debuggerUrl.hash) { | ||
| throw new Error("Chromium webSocketDebuggerUrl must not include credentials or a fragment"); | ||
| } | ||
| if ( | ||
| !debuggerUrl.pathname.startsWith("/devtools/browser/") || | ||
| debuggerUrl.pathname.endsWith("/") | ||
| ) { | ||
| throw new Error("Chromium webSocketDebuggerUrl must identify a browser target"); | ||
| } | ||
|
|
||
| const authorityEnd = rawUrl.indexOf("/", "ws://".length); | ||
| if (authorityEnd < 0) { | ||
| throw new Error("Chromium webSocketDebuggerUrl must include a browser target path"); | ||
| } | ||
| const websocketProtocol = proxyUrl.protocol === "https:" ? "wss:" : "ws:"; | ||
| return `${websocketProtocol}//${proxyUrl.host}${rawUrl.slice(authorityEnd)}`; | ||
| } | ||
|
|
||
| function isLoopbackHostname(hostname: string): boolean { | ||
| return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]"; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| import { resolveResidentBrowserWebSocketUrl } from "../service-worker-lifecycle/resident-browser-proxy.js"; | ||
|
|
||
| function response(body: unknown, init: { ok?: boolean; status?: number } = {}): Response { | ||
| return { | ||
| ok: init.ok ?? true, | ||
| status: init.status ?? 200, | ||
| json: async () => body, | ||
| } as Response; | ||
| } | ||
|
|
||
| describe("resident browser proxy resolver", () => { | ||
| it("resolves Chromium and preserves the exact browser target path and query", async () => { | ||
| const fetch = vi.fn(async () => | ||
| response({ | ||
| webSocketDebuggerUrl: | ||
| "ws://127.0.0.1:9222/devtools/browser/a%2Fb?token=one%2Ftwo&token=three", | ||
| }), | ||
| ); | ||
|
|
||
| await expect( | ||
| resolveResidentBrowserWebSocketUrl("http://127.0.0.1:9333", { fetch }), | ||
| ).resolves.toBe("ws://127.0.0.1:9333/devtools/browser/a%2Fb?token=one%2Ftwo&token=three"); | ||
| expect(fetch).toHaveBeenCalledWith( | ||
| new URL("http://127.0.0.1:9333/json/version"), | ||
| expect.objectContaining({ signal: expect.any(AbortSignal) }), | ||
| ); | ||
| }); | ||
|
|
||
| it("uses secure WebSockets for an HTTPS proxy and supports default ports", async () => { | ||
| await expect( | ||
| resolveResidentBrowserWebSocketUrl("https://127.0.0.1", { | ||
| fetch: async () => | ||
| response({ | ||
| webSocketDebuggerUrl: "ws://localhost/devtools/browser/browser-id?token=one", | ||
| }), | ||
| }), | ||
| ).resolves.toBe("wss://127.0.0.1/devtools/browser/browser-id?token=one"); | ||
| }); | ||
|
|
||
| it("rejects malformed JSON", async () => { | ||
| const fetch = vi.fn(async () => ({ | ||
| ok: true, | ||
| status: 200, | ||
| json: async () => { | ||
| throw new SyntaxError("Unexpected token"); | ||
| }, | ||
| })) as unknown as typeof globalThis.fetch; | ||
|
|
||
| await expect( | ||
| resolveResidentBrowserWebSocketUrl("http://127.0.0.1:9333", { fetch }), | ||
| ).rejects.toThrow("Unexpected token"); | ||
| }); | ||
|
|
||
| it.each([ | ||
| [{}, "webSocketDebuggerUrl"], | ||
| [{ webSocketDebuggerUrl: "http://127.0.0.1:9222/devtools/browser/id" }, "must use ws:"], | ||
| [{ webSocketDebuggerUrl: "ws://browser.example:9222/devtools/browser/id" }, "loopback"], | ||
| [{ webSocketDebuggerUrl: "ws://127.0.0.1:9222/devtools/page/id" }, "browser target"], | ||
| ])("rejects invalid version metadata %#", async (body, message) => { | ||
| await expect( | ||
| resolveResidentBrowserWebSocketUrl("http://127.0.0.1:9333", { | ||
| fetch: async () => response(body), | ||
| }), | ||
| ).rejects.toThrow(message); | ||
| }); | ||
|
|
||
| it("rejects HTTP failures", async () => { | ||
| await expect( | ||
| resolveResidentBrowserWebSocketUrl("http://127.0.0.1:9333", { | ||
| fetch: async () => response({}, { ok: false, status: 503 }), | ||
| }), | ||
| ).rejects.toThrow("HTTP 503"); | ||
| }); | ||
|
|
||
| it("aborts a request after the bounded timeout", async () => { | ||
| const fetch = vi.fn( | ||
| async (_input: URL | RequestInfo, init?: RequestInit): Promise<Response> => | ||
| await new Promise((_, reject) => { | ||
| init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), { | ||
| once: true, | ||
| }); | ||
| }), | ||
| ); | ||
|
|
||
| await expect( | ||
| resolveResidentBrowserWebSocketUrl("http://127.0.0.1:9333", { fetch, timeoutMs: 1 }), | ||
| ).rejects.toThrow("aborted"); | ||
| }); | ||
|
|
||
| it.each([ | ||
| "ws://127.0.0.1:9333", | ||
| "http://browser.example:9333", | ||
| "http://127.0.0.1:9333/path", | ||
| "http://user:secret@127.0.0.1:9333", | ||
| ])("rejects invalid proxy configuration %s", async (browserProxyUrl) => { | ||
| await expect(resolveResidentBrowserWebSocketUrl(browserProxyUrl)).rejects.toThrow(); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.