From baec1df883dba4fcf41bc2606c2d8f81982d3cf5 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:00:48 +1000 Subject: [PATCH] fix(browser): resolve session preview addresses and bound remote header waits --- packages/gui-plugins/src/browser/pane.ts | 6 +- packages/gui-plugins/src/browser/policy.ts | 4 +- .../gui-plugins/src/browser/preview.test.ts | 18 +++++ .../gui-plugins/src/browser/refusal-notice.ts | 2 +- .../src/browser/remote-preview.test.ts | 66 +++++++++++++++++++ .../gui-plugins/src/browser/remote-preview.ts | 14 ++-- packages/gui-plugins/src/browser/renderer.tsx | 13 ++++ 7 files changed, 114 insertions(+), 9 deletions(-) create mode 100644 packages/gui-plugins/src/browser/remote-preview.test.ts diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index a11c843e3b5..c1f34404c36 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -762,7 +762,7 @@ export function createBrowserPane(input: { if (!url || !(remote ? await remote.stat(action.path, signal) !== null : await workspaceFile(url, roots))) throw new CodedError(Browser.FailureCode.previewUnavailable, "The workspace file no longer exists or cannot be read by this session.") signal.throwIfAborted() - const existing = inventory(binding).tabs.find((tab) => tab.url === url) + const existing = inventory(binding).tabs.find((tab) => tab.url.split(/[?#]/, 1)[0] === url) const tab = existing ? load(binding, existing.id) : create(binding) if (!tab) throw new Error("Workspace preview tab is unavailable.") @@ -792,7 +792,7 @@ export function createBrowserPane(input: { const existing = inventory(binding).tabs.find((tab) => { const live = page(binding, tab.id) - return tab.url === file || (!!live && openingFiles.get(live) === file) + return tab.url.split(/[?#]/, 1)[0] === file || (!!live && openingFiles.get(live) === file) }) if (existing) { @@ -801,12 +801,14 @@ export function createBrowserPane(input: { return { value: existing, files: [] } } } + const opened = create(binding) const tabID = opened.state().id if (file) openingFiles.set(opened, file) if (action.focus !== false) dispatchBinding(binding, { type: "tab.focused", tabID }) + try { await opened.ready diff --git a/packages/gui-plugins/src/browser/policy.ts b/packages/gui-plugins/src/browser/policy.ts index 1f11ff6248a..c721cc8bbf8 100644 --- a/packages/gui-plugins/src/browser/policy.ts +++ b/packages/gui-plugins/src/browser/policy.ts @@ -301,7 +301,7 @@ export function normalizeURL(input: string, policy?: Policy) { if (reason) throw new Error( - policy?.fileRoots?.length + policy?.fileRoots?.length || policy?.remote ? "Only HTTP, HTTPS, about:blank, and file URLs inside the workspace are supported." : "Only HTTP, HTTPS, and about:blank URLs are supported.", ) @@ -323,7 +323,7 @@ export function refusal(input: string, policy?: Policy) { // A web page is refused only for its credentials. if (URL.canParse(url) && /^https?:$/.test(new URL(url).protocol)) return "browser.address.credentials" - return policy?.fileRoots?.length ? "browser.address.workspace" : "browser.address.web" + return policy?.fileRoots?.length || policy?.remote ? "browser.address.workspace" : "browser.address.web" } // The URL an address opens: a blank page for none, else the address with a scheme, `http` for this machine's names. diff --git a/packages/gui-plugins/src/browser/preview.test.ts b/packages/gui-plugins/src/browser/preview.test.ts index e63232dad6d..8a4c55f4b36 100644 --- a/packages/gui-plugins/src/browser/preview.test.ts +++ b/packages/gui-plugins/src/browser/preview.test.ts @@ -1,5 +1,7 @@ import { expect, test } from "bun:test" import { previewAddress, previewFile, previewResource, reloadAddress } from "./preview" +import { refusal } from "./policy" +import { navigationNotice } from "./refusal-notice" const roots = ["/work/repo #1"] @@ -7,6 +9,22 @@ const file = "file:///work/repo%20%231/index.html?q=1#anchor" const view = "oc-preview://first/work/repo%20%231/index.html?q=1#anchor" +test("a remote policy opens only its own session's workspace and explains a refusal as a workspace restriction", () => { + const remote = "workspace://ses_x/" + const address = `${remote}dir/page.html?q=1#h` + const actual = "oc-preview://host/dir/page.html?q=1#h" + expect(previewAddress(address, "host", [], remote)).toBe(actual) + expect(previewFile(actual, "host", [], remote)).toBe(address) + expect(refusal(address, {remote})).toBeUndefined() + expect(refusal(address, {})).toBe("browser.address.web") + + for (const other of [file, "workspace://ses_other/dir/page.html"]) { + expect(previewAddress(other, "host", roots, remote)).toBeUndefined() + expect(refusal(other, {remote})).toBe("browser.address.workspace") + expect(navigationNotice(other, {remote}).reason).toBe("browser.address.workspace") + } +}) + test("reload chooses the shown preview file for a virtual route, otherwise lets Chromium reload", () => { expect(reloadAddress(view.replace("index.html", "virtual"), file, "first", roots)).toBe(file) expect(reloadAddress(view, file, "first", roots)).toBeUndefined() diff --git a/packages/gui-plugins/src/browser/refusal-notice.ts b/packages/gui-plugins/src/browser/refusal-notice.ts index e18f1592a59..3492bacd0a7 100644 --- a/packages/gui-plugins/src/browser/refusal-notice.ts +++ b/packages/gui-plugins/src/browser/refusal-notice.ts @@ -36,5 +36,5 @@ export function navigationNotice(url: string, policy: Policy, owner: "agent" | " if (action) return { reason: "external", target: url, action: owner === "agent" ? "copy" : action } as const - return { reason: policy.fileRoots?.length ? "browser.address.workspace" : "browser.address.web" } as const + return { reason: policy.fileRoots?.length || policy.remote ? "browser.address.workspace" : "browser.address.web" } as const } diff --git a/packages/gui-plugins/src/browser/remote-preview.test.ts b/packages/gui-plugins/src/browser/remote-preview.test.ts new file mode 100644 index 00000000000..b2f350ceb21 --- /dev/null +++ b/packages/gui-plugins/src/browser/remote-preview.test.ts @@ -0,0 +1,66 @@ +import { afterAll, beforeAll, expect, test } from "bun:test" +import { GlobalRegistrator } from "@happy-dom/global-registrator" +import { remotePreview } from "./remote-preview" +import { workspaceFileURL } from "./link" +import { previewAddress } from "./preview" +import { resolvePreviewRequest, type PreviewSource } from "./workspace-file" + +// Main uses the host HTTP stack, not the DOM's CORS preflight implementation. +beforeAll(() => GlobalRegistrator.unregister()) + +afterAll(() => GlobalRegistrator.register()) + +test("the authenticated read under a server base path names exactly the file validated by stat", async () => { + const checked: string[] = [] + const reads: string[] = [] + + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(req) { + const url = new URL(req.url) + expect(url.searchParams.get("location[directory]")).toBe("/work") + expect(req.headers.get("authorization")).toBe("fixture") + expect(req.headers.get("accept-encoding")).toBe("identity") + expect(url.pathname.startsWith("/sub/api/fs/read/")).toBe(true) + reads.push(decodeURIComponent(url.pathname.slice("/sub/api/fs/read/".length))) + + return new Response("x") + }, + }) + + const controller = new AbortController() + + const source = remotePreview( + { id: "test", url: `${server.url}sub`, sameMachine: false, headers: { authorization: "fixture" } }, + "ses_x", + { directory: "/work" }, + controller.signal, + async (path) => { + checked.push(path) + + return 1 + }, + ) + + const grants = new Map([["grant", source]]) + const names = ["dir/50% off.html", "#?.txt", "a%2fb", "%252e%252e/[slug]", "日本語.txt"] + + try { + for (const path of names) { + const url = previewAddress(workspaceFileURL("/work", path, "ses_x"), "grant", [], source.prefix) + + const file = + url && (await resolvePreviewRequest(`${url}?ignored=yes`, "GET", undefined, grants, controller.signal)) + + if (!file || file.type !== "remote") throw new Error("expected remote file") + expect(await (await file.read(file.path, undefined, controller.signal)).text()).toBe("x") + } + + expect(checked).toEqual(names) + expect(reads).toEqual(names) + } finally { + controller.abort() + await server.stop(true) + } +}) diff --git a/packages/gui-plugins/src/browser/remote-preview.ts b/packages/gui-plugins/src/browser/remote-preview.ts index 48b7f719158..4a1a8151714 100644 --- a/packages/gui-plugins/src/browser/remote-preview.ts +++ b/packages/gui-plugins/src/browser/remote-preview.ts @@ -14,7 +14,7 @@ export function remotePreview( type: "remote", prefix: workspacePrefix(session), stat: (path, signal) => stat(path, AbortSignal.any([lifetime, signal, AbortSignal.timeout(15_000)])).catch(() => null), - read(path, range, signal) { + async read(path, range, signal) { const encoded = path.split("/").map(encodeURIComponent).join("/") const url = new URL(`api/fs/read/${encoded}`, `${server.url.replace(/\/+$/, "")}/`) url.searchParams.set("location[directory]", location.directory) @@ -25,9 +25,15 @@ export function remotePreview( if (range) headers.set("range", range) - // Never send the page's headers or follow a redirect supplied by the server. Node streams the response with - // backpressure and a body inactivity timeout; revoking the attachment also interrupts active readers. - return fetch(url, { headers, redirect: "error", signal: AbortSignal.any([signal, lifetime]) }) + // Bound the wait for headers, not the duration of a large response. Detach still aborts its body. + const timeout = new AbortController() + const timer = setTimeout(() => timeout.abort(), 15_000) + + try { + return await fetch(url, { headers, redirect: "error", signal: AbortSignal.any([signal, lifetime, timeout.signal]) }) + } finally { + clearTimeout(timer) + } }, } } diff --git a/packages/gui-plugins/src/browser/renderer.tsx b/packages/gui-plugins/src/browser/renderer.tsx index 259158d84c7..fd4e18a22cd 100644 --- a/packages/gui-plugins/src/browser/renderer.tsx +++ b/packages/gui-plugins/src/browser/renderer.tsx @@ -29,6 +29,7 @@ import { } from "./model-machine" import { PageIcon } from "./page-icon" import { artifactLink, artifactWebURL } from "./artifact-link" +import { remotePath, workspacePrefix } from "./remote-address" import barStyles from "./bar.css?inline" import commentStyles from "./comment.css?inline" import tabStyles from "./tabs.css?inline" @@ -83,6 +84,18 @@ const setup: Plugin.Setup = (ctx) => { // The native pane is a desktop feature. if (ctx.app.platform !== "desktop") return + ctx.add(LinkHandler, { + priority: 6, + match: (link) => link.origin === undefined && link.href.startsWith("workspace://"), + open(link) { + const session = link.session + const pane = model() + + if (session?.id && !session.server.builtin && remotePath(link.href, workspacePrefix(session.id)) && pane?.available(session)) + return pane.openURL(session, link.href) + ctx.toast.show({ variant: "error", title: ctx.t("refused.workspace") }) + }, + }) // Tab trigger styles render with the strip, before the pane chunk loads. ctx.add(Style, tabStyles) ctx.add(Style, commentStyles)