fix(browser): explain refused page and popup destinations

This commit is contained in:
Luke Parker 2026-11-16 12:01:21 +10:00
parent b3fac71e3c
commit 0f2b79fd96
9 changed files with 126 additions and 38 deletions

View file

@ -54,10 +54,10 @@ import {
extensionURL,
localFileURL,
normalizeURL,
refusal,
type Policy,
} from "./policy"
import type { PaneElement } from "./ipc"
import type { PaneElement, RefusalNotice } from "./ipc"
import { navigationNotice } from "./refusal-notice"
import { previewAddress, previewFile, reloadAddress } from "./preview"
import { previewScheme } from "./scheme"
import { workspaceFile } from "./workspace-file"
@ -200,6 +200,7 @@ export function createBrowserPage(
partition: string
network: BrowserNetwork | null
publish: (error?: string) => void
refused: (notice: RefusalNotice) => void
/** Reports the element picker starting, stopping, or picking an element. */
inspect?: (event: { active: boolean; element?: PaneElement }) => void
/** Reports the page's icon or zoom changing. */
@ -517,35 +518,38 @@ export function createBrowserPage(
if (!local && (!event.isMainFrame || allowedDestination(event.url, policy))) return
event.preventDefault()
// The same reason a typed address gets, so a blocked link and a blocked address read alike.
publish(refusal(event.url, policy) ?? "ERR_BLOCKED_BY_CLIENT")
options.refused(navigationNotice(event.url, policy))
}
contents.on("will-frame-navigate", guard)
contents.on("will-redirect", guard)
// Links opened with Cmd or Ctrl arrive as background tabs, and stay behind the current one as in the system browser.
contents.setWindowOpenHandler(({ url, disposition }) =>
url === "about:blank" || destinationOrigin(url) || extensionURL(url, policy.extensions ?? []) ||
preview(url)
? {
action: "allow",
outlivesOpener: true,
overrideBrowserWindowOptions: {
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
webviewTag: false,
devTools: false,
// Electron applies these preferences before the popup is adopted by our view.
focusOnNavigation: false,
partition: options.partition,
},
},
createWindow: (popupOptions) => options.popup(popupOptions, disposition === "background-tab"),
}
: { action: "deny" },
)
contents.setWindowOpenHandler(({ url, disposition }) => {
if (url !== "about:blank" && !destinationOrigin(url) && !extensionURL(url, policy.extensions ?? []) && !preview(url)) {
options.refused(navigationNotice(url, policy))
return { action: "deny" }
}
return {
action: "allow",
outlivesOpener: true,
overrideBrowserWindowOptions: {
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
webviewTag: false,
devTools: false,
// Electron applies these preferences before the popup is adopted by our view.
focusOnNavigation: false,
partition: options.partition,
},
},
createWindow: (popupOptions) => options.popup(popupOptions, disposition === "background-tab"),
}
})
// Called from the session's one download listener (`guardSession`) for a download this page started. One the user
// started is left to the system's save flow, so it goes where they save it and the agent never reads it.

View file

@ -7,6 +7,7 @@ test("late matches cannot replace the new query's count or reopen a dismissed se
const first = transitionFind(edited, { type: "issued", id: 8 })
const next = transitionFind(first, { type: "query", query: "other" })
const search = transitionFind(next, { type: "issued", id: 9 })
const result = {
requestId: 8,
finalUpdate: true,
@ -14,6 +15,7 @@ test("late matches cannot replace the new query's count or reopen a dismissed se
activeMatchOrdinal: 2,
selectionArea: { x: 0, y: 0, width: 1, height: 1 },
}
expect(transitionFind(next, { type: "found", result })).toBe(next)
expect(transitionFind(search, { type: "found", result })).toBe(search)
expect(transitionFind(search, { type: "found", result: { ...result, requestId: 9, finalUpdate: false } })).toBe(

View file

@ -19,6 +19,8 @@ export default {
"address.search": "Search or enter a URL",
"address.suggestions": "Suggestions",
"refused.web": "Only web pages can open here.",
"refused.external": "This link opens another app.",
"refused.dismiss": "Dismiss notice",
"refused.workspace": "Only web pages and files inside this session's workspace can open here.",
"refused.credentials": "Addresses with a user name or password can't open here.",
inspect: "Select an element to comment on",

View file

@ -39,8 +39,16 @@ const FindView = Schema.Struct({
export type FindView = typeof FindView.Type
const RefusalNotice = Schema.Union([
Schema.Struct({ reason: Schema.Literals(["browser.address.credentials", "browser.address.workspace", "browser.address.web"]) }),
Schema.Struct({ reason: Schema.Literal("external"), target: text(2048) }),
])
export type RefusalNotice = typeof RefusalNotice.Type
export const PaneEvent = Schema.Union([
Schema.Struct({ type: Schema.Literal("find"), tabID: Browser.TabID, view: Schema.NullOr(FindView) }),
Schema.Struct({ type: Schema.Literal("refusal"), tabID: Browser.TabID, notice: RefusalNotice }),
Schema.Struct({ type: Schema.Literal("focus"), tabID: Browser.TabID }),
Schema.Struct({ type: Schema.Literal("preview"), path: text(2_048) }),
Schema.Struct({

View file

@ -16,7 +16,7 @@ import {
import { recordable, remember, withIcon } from "./history"
import type definition from "./index"
import { workspaceFileURL } from "./link"
import { BrowserPane, type FindAction, type FindView, type PaneEvent } from "./ipc"
import { BrowserPane, type FindAction, type FindView, type PaneEvent, type RefusalNotice } from "./ipc"
import {
addressFocusTab,
createInitialState,
@ -51,7 +51,7 @@ type ModelState = {
machine: State
/** Each session's page icons and zoom by tab, as this desktop reports them. */
pages: Record<string, Record<string, PageDetail | undefined> | undefined>
searches: Record<string, Record<string, FindView | undefined> | undefined>
chrome: Record<string, Record<string, { find?: FindView; notice?: RefusalNotice } | undefined> | undefined>
}
/** A page's icon as a data URL, and its zoom factor, 1 at 100%. */
@ -104,7 +104,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
const owner = getOwner()
const history = ctx.stores.history
const [state, setState] = createStore<ModelState>({ machine: createInitialState(untrack(ipc)), pages: {}, searches: {} })
const [state, setState] = createStore<ModelState>({ machine: createInitialState(untrack(ipc)), pages: {}, chrome: {} })
const machine = () => state.machine
const [panes, setPanes] = createSignal<readonly PaneHandle[]>([])
// The I/O handles the machine's effects drive. They are never read as state.
@ -153,7 +153,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
if (current?.attempt !== effect.attempt) return
registrations.delete(effect.sessionKey)
setState("searches", effect.sessionKey, undefined)
setState("chrome", effect.sessionKey, undefined)
current.registration.close()
return
@ -267,16 +267,22 @@ export function createModel(ctx: SetupContext<typeof definition>) {
const receive = (drive: Drive, attempt: number, event: PaneEvent) => {
const sessionKey = drive.ref.key
if (event.type === "find") {
setState("searches", sessionKey, (old) => ({ ...old, [event.tabID]: event.view ?? undefined }))
if (event.type === "find" || event.type === "refusal") {
setState("chrome", sessionKey, (old) => ({ ...old, [event.tabID]: {
...old?.[event.tabID], ...(event.type === "find" ? { find: event.view ?? undefined } : { notice: event.notice }),
} }))
return
}
if (event.type === "state") {
const open = event.state?.tabs
Object.keys(state.searches[sessionKey] ?? {}).forEach((id) => {
if (!open?.some((tab) => tab.id === id)) setState("searches", sessionKey, id, undefined)
Object.keys(state.chrome[sessionKey] ?? {}).forEach((id) => {
const tab = open?.find((item) => item.id === id)
if (!tab) return setState("chrome", sessionKey, id, undefined)
if (tab.generation !== sessionTab(machine(), sessionKey, id)?.generation) setState("chrome", sessionKey, id, "notice", undefined)
})
return dispatch({ type: "pane.state", sessionKey, attempt, state: event.state, error: event.error })
@ -392,7 +398,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
.filter((item) => item.startsWith(`${sessionKey}\n`))
.forEach((item) => recorded.delete(item))
setState("pages", sessionKey, undefined)
setState("searches", sessionKey, undefined)
setState("chrome", sessionKey, undefined)
}
// A server whose plugin lacked the browser RPC may have it once its plugins finish loading, its event stream
@ -617,7 +623,15 @@ export function createModel(ctx: SetupContext<typeof definition>) {
},
/** A page's icon and zoom, once this desktop reported them. */
page: (session: Session, tabID: string) => state.pages[session.key]?.[tabID],
search: (session: Session, tabID: string) => state.searches[session.key]?.[tabID],
search: (session: Session, tabID: string) => state.chrome[session.key]?.[tabID]?.find,
notice(session: Session, tabID: string) {
const notice = state.chrome[session.key]?.[tabID]?.notice
if (!notice) return
return notice.reason === "external" ? { text: ctx.t("refused.external"), target: notice.target } : { text: describe(notice.reason) }
},
dismissNotice: (session: Session, tabID: string) => setState("chrome", session.key, tabID, "notice", undefined),
find(session: Session, tabID: Browser.TabID, action: FindAction) {
return registration(session)?.find(tabID, action) ?? Promise.reject(new Error("browser.pane.unavailable"))
},

View file

@ -584,6 +584,9 @@ export function createBrowserPane(input: {
shared,
embeds: input.embeds,
fail,
refused: (notice) => {
if (current()) emit(binding, { type: "refusal", tabID: id, notice })
},
publish: (error) => {
if (current()) dispatchBinding(binding, { type: "tab.published", tabID: id, attempt, tab: page.state(), error })
},

View file

@ -848,9 +848,19 @@ export default function SessionBrowserPane(props: {
</div>
</Show>
<Show when={state()?.id} keyed>
{(id) => <Show when={!suspended() && props.model.search(props.session, id)}>{(view) => (
{(id) => <><Show when={props.model.notice(props.session, id)}>{(notice) => (
<section class="flex shrink-0 items-center gap-3 border-b-[0.5px] border-v2-border-border-muted bg-v2-background-bg-layer-01 px-3 py-2">
<div role="status" class="min-w-0 flex-1 text-13-regular text-v2-text-text-base">
{notice().text}
<Show when={notice().target}>{(target) => (
<bdi dir="ltr" class="block truncate text-12-regular text-v2-text-text-muted" title={target()}>{target()}</bdi>
)}</Show>
</div>
<IconButton variant="ghost-muted" size="small" aria-label={plugin.t("refused.dismiss")} icon={<Icon name="close" />} onClick={() => props.model.dismissNotice(props.session, id)} />
</section>
)}</Show><Show when={!suspended() && props.model.search(props.session, id)}>{(view) => (
<FindBar view={view()} input={(el) => { findInput = el }} run={find} />
)}</Show>}
)}</Show></>}
</Show>
{/* Above a page, where a signed-out site is the reason to import; the new tab page shows the offer as a card. */}
<Show when={offering() && !empty() && !suspended()}>

View file

@ -0,0 +1,23 @@
import { expect, test } from "bun:test"
import { navigationNotice } from "./refusal-notice"
test("refusals describe the actual destination without displaying private, misleading or unbounded targets", () => {
expect(navigationNotice("mailto:fixture@example.invalid", {})).toEqual({
reason: "external",
target: "mailto:fixture@example.invalid",
})
expect(navigationNotice("https://name:secret@example.invalid", {})).toEqual({ reason: "browser.address.credentials" })
for (const url of [
"file:///etc/passwd",
"oc-preview://private/secret",
"javascript:noop()",
"slack://user:password@host",
"slack://abc\n",
"tel:12\u202e34",
`sms:${"x".repeat(2048)}`,
]) {
expect(navigationNotice(url, { fileRoots: ["/workspace"] })).toEqual({ reason: "browser.address.workspace" })
expect(navigationNotice(url, {})).toEqual({ reason: "browser.address.web" })
}
})

View file

@ -0,0 +1,22 @@
import { destinationOrigin, type Policy } from "./policy"
/** A refused Chromium navigation is an absolute destination, never text to turn into a web search or host name. */
export function navigationNotice(url: string, policy: Policy) {
if (URL.canParse(url) && /^https?:$/i.test(new URL(url).protocol) && !destinationOrigin(url))
return { reason: "browser.address.credentials" } as const
// An address supplied by a document may contain credentials, misleading direction controls or a whole data URL.
// Only display a bounded, plain target for the named external protocols. Never use this display value to open it.
if (
url.length <= 2048 &&
!/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u.test(url) &&
URL.canParse(url)
) {
const target = new URL(url)
if (!target.username && !target.password && /^(?:mailto|tel|sms|vscode|slack|zoommtg):$/.test(target.protocol))
return { reason: "external", target: url } as const
}
return { reason: policy.fileRoots?.length ? "browser.address.workspace" : "browser.address.web" } as const
}