fix(browser): keep print and Windows Hello dialogs an agent sets off from taking the screen (#42209)

window.print() opens the system print dialog and, on Windows, a passkey request
opens Windows Hello. Both are modal windows that take the foreground, and an
agent click could set either off over the user's work. Main now tells each
page's frames whether an agent drove it since the desktop user last gave it
input, and the session frame preload refuses print() on such a page (reported
to the agent as effects.blockedPrint, pointing at pdf) and, on Windows, holds
its passkey requests unsent, still reported as passkeyRequest. The user's own
input releases the page and cancels held requests so the page can retry.
This commit is contained in:
Kelvin Amoaba
2026-11-14 01:15:23 +00:00
committed by GitHub
parent b8b29df2b9
commit ee49c567dc
27 changed files with 355 additions and 81 deletions
@@ -18,8 +18,8 @@ const GUEST_PRELOADS = [
{ entry: 'src/preload/browser-extension-preload.ts', fileName: 'browser-extension-preload.js' },
{ entry: 'src/preload/browser-guest.ts', fileName: 'browser-guest-preload.js' },
{
entry: 'src/preload/browser-passkey-request.ts',
fileName: 'browser-passkey-request-preload.js'
entry: 'src/preload/browser-system-dialogs.ts',
fileName: 'browser-system-dialogs-preload.js'
},
{ entry: 'src/preload/doc-preview-link.ts', fileName: 'doc-preview-link-preload.js' },
{ entry: 'src/preload/plugin-frame-guest.ts', fileName: 'plugin-frame-guest-preload.js' }
+1 -1
View File
@@ -4,7 +4,7 @@
"src/main/index.ts",
"src/preload/index.ts",
"src/preload/browser-guest.ts",
"src/preload/browser-passkey-request.ts",
"src/preload/browser-system-dialogs.ts",
"src/main/daemon/daemon-entry.ts",
"src/main/plugins/workers/plugin-host-entry.ts",
"src/main/computer/computer-sidecar.ts",
+1 -1
View File
@@ -64,7 +64,7 @@ ORCA exec --page <browserPageId> --command "get text @e3" --json
Browser rules:
- Actions (`click`, `fill`, `type`, `keypress`, `select`, `check`, `hover`, `scroll`, `goto`, `back`, `reload`, `mouse` and the rest) wait briefly for the page to settle and then report what they caused in `result.effects` (text mode prints it under the action): `url`/`title` when they changed, `newTabs` with their `browserPageId`, blocked or opened `popups`, `downloads` started, `consoleErrors`, a `passkeyRequest` still waiting, and `page`: `"unchanged"`, or the snapshot lines the action added or replaced, with their refs (`full: true` means the whole new page). `loading: true` means a navigation was still running: `wait --load load`, then `snapshot`. No `page` means the page could not be read: run `snapshot`. `settled: false` means the page was still changing when it was read. An action that opens a JavaScript dialog fails with `browser_dialog_opened` instead. One that opens a file picker fails with `browser_file_chooser_opened`: Orca closes the picker so the system dialog never covers the user's screen; use `ORCA upload` on the file input or its button instead.
- Actions (`click`, `fill`, `type`, `keypress`, `select`, `check`, `hover`, `scroll`, `goto`, `back`, `reload`, `mouse` and the rest) wait briefly for the page to settle and then report what they caused in `result.effects` (text mode prints it under the action): `url`/`title` when they changed, `newTabs` with their `browserPageId`, blocked or opened `popups`, `downloads` started, `consoleErrors`, a `passkeyRequest` still waiting, `blockedPrint` when Orca refused the page's system print dialog (run `ORCA pdf` to save the page instead), and `page`: `"unchanged"`, or the snapshot lines the action added or replaced, with their refs (`full: true` means the whole new page). `loading: true` means a navigation was still running: `wait --load load`, then `snapshot`. No `page` means the page could not be read: run `snapshot`. `settled: false` means the page was still changing when it was read. An action that opens a JavaScript dialog fails with `browser_dialog_opened` instead. One that opens a file picker fails with `browser_file_chooser_opened`: Orca closes the picker so the system dialog never covers the user's screen; use `ORCA upload` on the file input or its button instead.
- Snapshot again only when `page.truncated` is true, after `wait`, after a tab switch, on a `browser_stale_ref`, or when a result has no `effects` (older Orca, or a server-hosted page).
- Pass `--expect-url <url>` with `--page` when acting on the wrong resource would matter, such as writing or sending in one conversation of a chat app. Use the exact absolute URL from `result.tab.url` in `ORCA tab current --json`, or `url` from a `snapshot --json` or `goto`. Path, query and fragment must all match, so a page that rewrites its URL while you work refuses until you read the URL again. If the page's URL differs, or a navigation to another URL is under way, the command fails with `browser_expected_url_mismatch`, and `error.data` holds `expectedUrl`, `actualUrl`, `browserPageId` and `mayHaveStarted`. `mayHaveStarted: false` means nothing ran; `true` means a step of a longer command (a typed run, a `select-all`) may have happened, so look at the page before retrying. Success adds `browserPageId` and `checkedUrl`, the URL last checked; the action itself may have navigated since, and `effects.url` says where. The check runs right before the action and again before each later step, but it is not a lock: a route change in the instant after a check can still receive the action. It compares the top-level page only, so it says nothing about an iframe or an app that shows different content at one URL; read the page for those. `exec` refuses the flag, because one raw batch can navigate and retarget. A runtime, client or desktop that cannot check the URL refuses with `incompatible_runtime` or `browser_expect_url_unsupported` rather than acting unguarded.
- Refs like `@e1` are assigned by `snapshot`, scoped to one tab, and invalidated by navigation or tab switch.
+5
View File
@@ -204,6 +204,11 @@ export function formatBrowserActionEffects(result: unknown): string {
if (effects.passkeyRequest) {
lines.push(formatPasskeyRequest(effects.passkeyRequest))
}
if (effects.blockedPrint) {
lines.push(
`${effects.blockedPrint.origin} tried to open the system print dialog, which Orca blocked so it wouldn't take over the user's screen. To save the page as a PDF, run \`pdf\`.`
)
}
if (effects.loading) {
lines.push('Still loading; run `wait --load load`, then `snapshot`.')
} else if (effects.page === undefined) {
+1 -1
View File
@@ -737,7 +737,7 @@ const ORCA_CLI_BROWSER_REFERENCE_MARKDOWN = [
"",
"Browser rules:",
"",
"- Actions (`click`, `fill`, `type`, `keypress`, `select`, `check`, `hover`, `scroll`, `goto`, `back`, `reload`, `mouse` and the rest) wait briefly for the page to settle and then report what they caused in `result.effects` (text mode prints it under the action): `url`/`title` when they changed, `newTabs` with their `browserPageId`, blocked or opened `popups`, `downloads` started, `consoleErrors`, a `passkeyRequest` still waiting, and `page`: `\"unchanged\"`, or the snapshot lines the action added or replaced, with their refs (`full: true` means the whole new page). `loading: true` means a navigation was still running: `wait --load load`, then `snapshot`. No `page` means the page could not be read: run `snapshot`. `settled: false` means the page was still changing when it was read. An action that opens a JavaScript dialog fails with `browser_dialog_opened` instead. One that opens a file picker fails with `browser_file_chooser_opened`: Orca closes the picker so the system dialog never covers the user's screen; use `ORCA upload` on the file input or its button instead.",
"- Actions (`click`, `fill`, `type`, `keypress`, `select`, `check`, `hover`, `scroll`, `goto`, `back`, `reload`, `mouse` and the rest) wait briefly for the page to settle and then report what they caused in `result.effects` (text mode prints it under the action): `url`/`title` when they changed, `newTabs` with their `browserPageId`, blocked or opened `popups`, `downloads` started, `consoleErrors`, a `passkeyRequest` still waiting, `blockedPrint` when Orca refused the page's system print dialog (run `ORCA pdf` to save the page instead), and `page`: `\"unchanged\"`, or the snapshot lines the action added or replaced, with their refs (`full: true` means the whole new page). `loading: true` means a navigation was still running: `wait --load load`, then `snapshot`. No `page` means the page could not be read: run `snapshot`. `settled: false` means the page was still changing when it was read. An action that opens a JavaScript dialog fails with `browser_dialog_opened` instead. One that opens a file picker fails with `browser_file_chooser_opened`: Orca closes the picker so the system dialog never covers the user's screen; use `ORCA upload` on the file input or its button instead.",
"- Snapshot again only when `page.truncated` is true, after `wait`, after a tab switch, on a `browser_stale_ref`, or when a result has no `effects` (older Orca, or a server-hosted page).",
"- Pass `--expect-url <url>` with `--page` when acting on the wrong resource would matter, such as writing or sending in one conversation of a chat app. Use the exact absolute URL from `result.tab.url` in `ORCA tab current --json`, or `url` from a `snapshot --json` or `goto`. Path, query and fragment must all match, so a page that rewrites its URL while you work refuses until you read the URL again. If the page's URL differs, or a navigation to another URL is under way, the command fails with `browser_expected_url_mismatch`, and `error.data` holds `expectedUrl`, `actualUrl`, `browserPageId` and `mayHaveStarted`. `mayHaveStarted: false` means nothing ran; `true` means a step of a longer command (a typed run, a `select-all`) may have happened, so look at the page before retrying. Success adds `browserPageId` and `checkedUrl`, the URL last checked; the action itself may have navigated since, and `effects.url` says where. The check runs right before the action and again before each later step, but it is not a lock: a route change in the instant after a check can still receive the action. It compares the top-level page only, so it says nothing about an iframe or an app that shows different content at one URL; read the page for those. `exec` refuses the flag, because one raw batch can navigate and retarget. A runtime, client or desktop that cannot check the URL refuses with `incompatible_runtime` or `browser_expect_url_unsupported` rather than acting unguarded.",
"- Refs like `@e1` are assigned by `snapshot`, scoped to one tab, and invalidated by navigation or tab switch.",
@@ -190,6 +190,10 @@ async function settle(
: []
)
)
const print = events.find((event) => event.kind === 'print')
if (print) {
effects.blockedPrint = { origin: clip(print.origin) }
}
effects.consoleErrors = firstItems(watch.consoleErrors.map((error) => clip(error)))
return effects
}
@@ -60,6 +60,7 @@ export function resetBrowserManagerMocks(mocks: BrowserManagerMocks): void {
export function resetBrowserManagerState(): void {
browserManager.unregisterAll()
browserManager.setBrowserGuestStateChangedListener(null)
browserManager.setAgentLeadListener(null)
browserManager.setOffscreenTabOpener(null)
browserManager.setDictationShortcutForwardingPredicate(null)
browserManager.setSettingsResolver(() => ({}))
@@ -25,6 +25,8 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState {
worktreeForPage: (browserPageId) => this.worktreeIdByTabId.get(browserPageId) ?? null
})
private agentLeadListener: ((guestWebContentsId: number, led: boolean) => void) | null = null
protected readonly pageEvents = new BrowserPageEvents()
protected readonly pageInputCredit = new BrowserPageInputCredit()
@@ -39,28 +41,49 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState {
/** Holds the page's agent marking for one queued command, from queueing until it settles. */
beginAgentCommand(browserPageId: string): AgentCommandLease {
const lease = this.agentActivity.beginCommand(browserPageId)
const guestId =
const pageGuestId =
this.webContentsIdByTabId.get(browserPageId) ?? browserPopupPageWebContentsId(browserPageId)
// An SSH route popup has no guest policies, so its opener carries the lead.
const guestId =
pageGuestId === null
? null
: (resolveBrowserRouteGuestPopupOpener(pageGuestId) ?? pageGuestId)
// Only attached guests, whose teardown releases the lead.
if (lease.agent && guestId !== null && this.policyAttachedGuestIds.has(guestId)) {
this.agentLedGuestIds.add(guestId)
this.leadAgent(guestId)
}
return lease
}
/** Tells the page's frames when the agent takes or gives up its lead, so they can refuse system dialogs. */
setAgentLeadListener(
listener: ((guestWebContentsId: number, led: boolean) => void) | null
): void {
this.agentLeadListener = listener
}
private leadAgent(guestWebContentsId: number): void {
if (!this.agentLedGuestIds.has(guestWebContentsId)) {
this.agentLedGuestIds.add(guestWebContentsId)
this.agentLeadListener?.(guestWebContentsId, true)
}
}
/** A popup opened from a page the agent leads starts led too. */
protected inheritAgentLead(openerWebContentsId: number, popupWebContentsId: number): void {
if (
this.agentLedGuestIds.has(openerWebContentsId) &&
this.policyAttachedGuestIds.has(popupWebContentsId)
) {
this.agentLedGuestIds.add(popupWebContentsId)
this.leadAgent(popupWebContentsId)
}
}
/** The desktop user's own input takes the page back from the agent. */
protected releaseAgentLead(guestWebContentsId: number): void {
this.agentLedGuestIds.delete(guestWebContentsId)
releaseAgentLead(guestWebContentsId: number): void {
if (this.agentLedGuestIds.delete(guestWebContentsId)) {
this.agentLeadListener?.(guestWebContentsId, false)
}
}
/** Clears the agent marking from every page this SSH host was driving. */
@@ -88,17 +111,39 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState {
}
}
/** An agent drove the page this guest shows since the desktop user last gave it input. */
isAgentLedGuest(guestWebContentsId: number): boolean {
// SSH route popups skip guest policies, so they follow their opener's lead.
return this.agentLedGuestIds.has(
resolveBrowserRouteGuestPopupOpener(guestWebContentsId) ?? guestWebContentsId
)
}
/** An agent drives the page this guest shows (a tab or a popup), or drove it since the desktop user last gave it input. */
isAgentLeadingGuest(guestWebContentsId: number): boolean {
// SSH route popups skip guest policies, so they follow their opener's lead.
const leadingGuestId =
resolveBrowserRouteGuestPopupOpener(guestWebContentsId) ?? guestWebContentsId
return (
this.agentLedGuestIds.has(leadingGuestId) ||
this.isAgentLedGuest(guestWebContentsId) ||
this.isAgentUsingPage(this.pageIdForGuest(guestWebContentsId))
)
}
/** A page the agent leads refused its own print dialog, which would take the foreground; tell the agent. */
reportRefusedPrint(guestWebContentsId: number, origin: string): void {
if (!this.isAgentLedGuest(guestWebContentsId)) {
return
}
// Reach a command on the popup page itself as well as one on the tab that owns it.
const pageIds = new Set([
this.pageIdForGuest(guestWebContentsId),
this.resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId)
])
for (const pageId of pageIds) {
if (pageId) {
this.pageEvents.emit(pageId, { kind: 'print', origin })
}
}
}
private pageIdForGuest(guestWebContentsId: number): string {
return (
this.tabIdByWebContentsId.get(guestWebContentsId) ?? browserPopupPageId(guestWebContentsId)
@@ -249,6 +249,61 @@ describe('browserManager', () => {
])
})
it("tells the agent's page it leads it, so its print is refused and reported, until the user uses the page", () => {
const { guest, pressMouse } = attachGuest()
registerAsTab(guest)
const leads: [number, boolean][] = []
browserManager.setAgentLeadListener((guestId, led) => leads.push([guestId, led]))
const events: unknown[] = []
browserManager.observePageEvents('browser-1', (event) => events.push(event))
runWithActiveRpcCaller({ kind: 'local-cli' }, () =>
browserManager.beginAgentCommand('browser-1')
).end()
runWithActiveRpcCaller({ kind: 'local-cli' }, () =>
browserManager.beginAgentCommand('browser-1')
).end()
browserManager.reportRefusedPrint(guest.id, 'https://shop.example.com')
pressMouse()
browserManager.reportRefusedPrint(guest.id, 'https://shop.example.com')
expect(leads).toEqual([
[guest.id, true],
[guest.id, false]
])
expect(events).toEqual([{ kind: 'print', origin: 'https://shop.example.com' }])
})
it('reports a refused print to an agent command on the popup page that asked', () => {
const { guest } = attachGuest()
registerAsTab(guest)
const onDidCreateWindow = guestOnMock.mock.calls.find(
([event]) => event === 'did-create-window'
)?.[1]
onDidCreateWindow({ webContents: { ...guest, id: 146 } })
const events: unknown[] = []
browserManager.observePageEvents('popup-146', (event) => events.push(event))
runWithActiveRpcCaller({ kind: 'local-cli' }, () =>
browserManager.beginAgentCommand('popup-146')
).end()
browserManager.reportRefusedPrint(146, 'https://pay.example.com')
expect(events).toEqual([{ kind: 'print', origin: 'https://pay.example.com' }])
})
it('leads an SSH route popup the agent drives directly through its opener', () => {
const { guest } = attachGuest()
registerAsTab(guest)
registerBrowserRouteGuestPopup({ popupWebContentsId: 147, openerWebContentsId: guest.id })
runWithActiveRpcCaller({ kind: 'local-cli' }, () =>
browserManager.beginAgentCommand('popup-147')
).end()
const led = browserManager.isAgentLedGuest(147)
releaseBrowserRouteGuestPopup(147)
expect(led).toBe(true)
})
it("opens the system browser for a page with no tab only on the desktop user's own click", async () => {
const { guest, openLink, pressMouse } = attachGuest()
@@ -16,7 +16,7 @@ export abstract class BrowserManagerGuestCleanup extends BrowserManagerGuestNavi
this.policyCleanupByGuestId.delete(guestWebContentsId)
}
this.policyAttachedGuestIds.delete(guestWebContentsId)
this.agentLedGuestIds.delete(guestWebContentsId)
this.releaseAgentLead(guestWebContentsId)
this.offscreenGuestIds.delete(guestWebContentsId)
this.popupOwnerContextByGuestId.delete(guestWebContentsId)
this.pageInitiatedTabBudgetByRootGuestId.delete(guestWebContentsId)
@@ -1,7 +1,7 @@
import { EventEmitter } from 'node:events'
import type { BrowserPopupEvent } from '../../../../shared/browser/guest-lifecycle/browser-guest-events'
/** Facts the browser manager resolves to their owning page: a tab it asked for, a popup outcome, a download. */
/** Facts the browser manager resolves to their owning page: a tab it asked for, a popup outcome, a download, a refused print. */
export type BrowserPageEvent =
| { kind: 'tab'; url: string }
| {
@@ -10,6 +10,7 @@ export type BrowserPageEvent =
origin: string
}
| { kind: 'download'; filename: string; origin: string }
| { kind: 'print'; origin: string }
/** Keyed by browser page id. */
export class BrowserPageEvents {
@@ -0,0 +1,74 @@
import { ipcMain, webContents, type Session } from 'electron'
import {
BROWSER_AGENT_LEAD_CHANNEL,
BROWSER_AGENT_LEAD_QUERY_CHANNEL,
BROWSER_PRINT_REFUSED_CHANNEL,
BROWSER_SYSTEM_DIALOGS_PRELOAD_FILE
} from '../../../../shared/browser-system-dialogs'
import {
registerBrowserSessionFramePreload,
unregisterBrowserSessionFramePreload
} from '../../sessions/browser-session-frame-preloads'
import {
listBrowserRouteGuestPopups,
resolveBrowserRouteGuestPopupOpener
} from '../../routing/guest-authority/browser-route-guest-popup-ownership'
import { browserManager } from '../manager/browser-manager'
import { cancelBrowserPasskeyRequests } from '../../webauthn/browser-passkey-requests'
const PRELOAD_ID = 'orca-browser-system-dialogs'
/** Watches the session's pages for passkey requests and print dialogs, which Electron doesn't report. */
export function watchBrowserSystemDialogs(browserSession: Session): void {
if (
!registerBrowserSessionFramePreload(
browserSession,
PRELOAD_ID,
BROWSER_SYSTEM_DIALOGS_PRELOAD_FILE
)
) {
console.warn('[browser] System dialog preload is missing')
}
}
export function unwatchBrowserSystemDialogs(browserSession: Session): void {
unregisterBrowserSessionFramePreload(browserSession, PRELOAD_ID)
}
/** Keeps every watched page's frames told whether the agent leads it; once per app. */
export function listenForBrowserSystemDialogs(): void {
ipcMain.on(BROWSER_AGENT_LEAD_QUERY_CHANNEL, (event) => {
event.reply(BROWSER_AGENT_LEAD_CHANNEL, browserManager.isAgentLedGuest(event.sender.id))
})
ipcMain.on(BROWSER_PRINT_REFUSED_CHANNEL, (event) => {
browserManager.reportRefusedPrint(event.sender.id, event.senderFrame?.origin ?? '')
})
browserManager.setAgentLeadListener((guestWebContentsId, led) => {
// SSH route popups follow their opener's lead.
const routePopups = listBrowserRouteGuestPopups().filter(
(popupId) => resolveBrowserRouteGuestPopupOpener(popupId) === guestWebContentsId
)
for (const id of [guestWebContentsId, ...routePopups]) {
publishAgentLead(id, led)
// A passkey request held from Windows Hello for the agent can't resume; cancelling it lets
// the page offer its own retry to the user who just came back.
if (!led && process.platform === 'win32') {
cancelBrowserPasskeyRequests(id)
}
}
})
}
function publishAgentLead(guestWebContentsId: number, led: boolean): void {
try {
const guest = webContents.fromId(guestWebContentsId)
if (!guest || guest.isDestroyed()) {
return
}
for (const frame of guest.mainFrame.framesInSubtree) {
frame.send(BROWSER_AGENT_LEAD_CHANNEL, led)
}
} catch {
// Best-effort: a guest or frame torn down mid-walk has no dialog left to guard.
}
}
@@ -38,6 +38,8 @@ export type BrowserRouteGuestPopupDependencies = {
request: NewBrowserTabPopupRequest,
observed: ObservedBrowserGuestGesture | null
) => boolean
/** The desktop user's own input in a popup takes its opener's page back from the agent. */
releaseAgentLead?: (openerWebContentsId: number) => void
openPopupWindow?: (
options: PopupChildWindowOptions,
targetUrl: string,
@@ -105,7 +107,18 @@ export function createBrowserRouteGuestPopupController(input: {
if (!enforceBrowserRouteWebRtcPolicy(contents, () => {})) {
return false
}
const gesture = trackBrowserGuestInputGesture(contents)
const gesture = trackBrowserGuestInputGesture(contents, {
onActivatingInput: (byAgent) => {
if (byAgent) {
return
}
try {
input.dependencies.releaseAgentLead?.(input.opener.id)
} catch {
// A destroyed opener has no lead left to release.
}
}
})
gestures.add(gesture)
try {
contents.setWindowOpenHandler(buildWindowOpenHandler(contents, gesture))
@@ -18,5 +18,6 @@ export type BrowserRouteWebContentsRegistryDependencies = {
/** Route-guest popup denials need an explicit notice on the owning page. */
reportBlockedPopup?(input: { openerWebContentsId: number; url: string }): void
openNewTabPopup?: BrowserRouteGuestPopupDependencies['openNewTabPopup']
releaseAgentLead?: BrowserRouteGuestPopupDependencies['releaseAgentLead']
maxGuests?: number
}
@@ -76,6 +76,7 @@ export class BrowserRouteWebContentsRegistry {
this.dependencies.getPartitionForSession(routeSession),
reportBlockedPopup: (blocked) => this.dependencies.reportBlockedPopup?.(blocked),
openNewTabPopup: this.dependencies.openNewTabPopup,
releaseAgentLead: this.dependencies.releaseAgentLead,
isPopupNavigationAllowed: (url) => this.navigationAllowed(state, url, false)
})
} catch {
@@ -90,7 +90,8 @@ export const browserRouteWebContentsRegistry = new BrowserRouteWebContentsRegist
browserRouteSessionRegistry.retirePreparedPagesOwnedByRenderer(rendererWebContentsId),
reportBlockedPopup: (blocked) => browserManager.reportRouteGuestPopupBlocked(blocked),
openNewTabPopup: (source, request, observed) =>
browserManager.openNewTabPopup(source, request, observed)
browserManager.openNewTabPopup(source, request, observed),
releaseAgentLead: (openerWebContentsId) => browserManager.releaseAgentLead(openerWebContentsId)
})
routeWebContentsRegistryRef.current = browserRouteWebContentsRegistry
@@ -10,6 +10,7 @@ import { configureBrowserExtensionProfileDataDirectory } from '../extensions/pro
import { configurePairedRuntimeBrowserClientHostsForOrcaProfile } from '../client-hosts/lifecycle/paired-runtime-browser-client-host-runtime'
import { configureBrowserPasswordVaults } from '../../browser-passwords/browser-password-vaults'
import { listenForBrowserPasskeyRequests } from '../webauthn/browser-passkey-requests'
import { listenForBrowserSystemDialogs } from '../guest-lifecycle/prompts/browser-system-dialogs'
let initialized = false
@@ -22,6 +23,7 @@ export function initializeBrowserSessionsForApp(
return
}
listenForBrowserPasskeyRequests()
listenForBrowserSystemDialogs()
if (activeProfile) {
browserSessionRegistry.configureForOrcaProfile(activeProfile)
@@ -1,23 +1,15 @@
import {
ipcMain,
type IpcMainEvent,
type Session,
type WebContents,
type WebFrameMain,
webFrameMain
} from 'electron'
import {
BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL,
BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL,
BROWSER_PASSKEY_REQUEST_PRELOAD_FILE
BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL
} from '../../../shared/browser-passkey-request'
import type { BrowserPasskeyRequest } from '../../../shared/browser/runtime/runtime-browser-contracts'
import {
registerBrowserSessionFramePreload,
unregisterBrowserSessionFramePreload
} from '../sessions/browser-session-frame-preloads'
const PRELOAD_ID = 'orca-browser-passkey-request'
// Frames waiting on a passkey request, by guest WebContents id and frame tree node.
const pendingFramesByGuest = new Map<number, Map<number, WebFrameMain>>()
@@ -80,23 +72,6 @@ export function listenForBrowserPasskeyRequests(): void {
ipcMain.on(BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL, onPendingChanged)
}
/** Watches the session's pages for passkey requests, which Electron neither shows nor reports. */
export function watchBrowserPasskeyRequests(browserSession: Session): void {
if (
!registerBrowserSessionFramePreload(
browserSession,
PRELOAD_ID,
BROWSER_PASSKEY_REQUEST_PRELOAD_FILE
)
) {
console.warn('[browser-webauthn] Passkey request preload is missing')
}
}
export function unwatchBrowserPasskeyRequests(browserSession: Session): void {
unregisterBrowserSessionFramePreload(browserSession, PRELOAD_ID)
}
function livePendingFrames(webContentsId: number): WebFrameMain[] {
const frames = pendingFramesByGuest.get(webContentsId)
if (!frames) {
@@ -4,9 +4,9 @@ import {
requestBrowserWebAuthnAccount
} from './browser-webauthn-account-picker'
import {
unwatchBrowserPasskeyRequests,
watchBrowserPasskeyRequests
} from './browser-passkey-requests'
unwatchBrowserSystemDialogs,
watchBrowserSystemDialogs
} from '../guest-lifecycle/prompts/browser-system-dialogs'
const FIDO_HID_USAGE_PAGE = 0xf1d0
const LOCALHOST_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]'])
@@ -104,7 +104,7 @@ export function installBrowserWebAuthnAccessHandlers(browserSession: Session): v
handleBrowserSelectWebAuthnAccount(browserSession, event, details, callback)
selectWebAuthnAccountHandlers.set(browserSession, selectWebAuthnAccountHandler)
browserSession.on('select-webauthn-account', selectWebAuthnAccountHandler)
watchBrowserPasskeyRequests(browserSession)
watchBrowserSystemDialogs(browserSession)
}
export function clearBrowserWebAuthnAccessHandlers(browserSession: Session): void {
@@ -116,5 +116,5 @@ export function clearBrowserWebAuthnAccessHandlers(browserSession: Session): voi
}
browserSession.setDevicePermissionHandler(null)
cancelBrowserWebAuthnAccountRequestsForSession(browserSession)
unwatchBrowserPasskeyRequests(browserSession)
unwatchBrowserSystemDialogs(browserSession)
}
-23
View File
@@ -1,23 +0,0 @@
import type { ContextBridge, IpcRenderer } from 'electron'
import {
BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL,
BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL
} from '../shared/browser-passkey-request'
import { installBrowserPasskeyRequestWatch } from './browser/passkeys/browser-passkey-request-watch'
// A session preload: it runs in every frame of every browser page, popup and serve window.
const electron: {
contextBridge: ContextBridge
ipcRenderer: Pick<IpcRenderer, 'send' | 'on'>
} = require('electron')
const { contextBridge, ipcRenderer } = electron
const cancel: unknown = contextBridge.executeInMainWorld({
func: installBrowserPasskeyRequestWatch,
args: [(pending: boolean) => ipcRenderer.send(BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL, pending)]
})
ipcRenderer.on(BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL, () => {
if (typeof cancel === 'function') {
cancel()
}
})
+54
View File
@@ -0,0 +1,54 @@
import type { ContextBridge, IpcRenderer } from 'electron'
import {
BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL,
BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL
} from '../shared/browser-passkey-request'
import {
BROWSER_AGENT_LEAD_CHANNEL,
BROWSER_AGENT_LEAD_QUERY_CHANNEL,
BROWSER_PRINT_REFUSED_CHANNEL
} from '../shared/browser-system-dialogs'
import { installBrowserPasskeyRequestWatch } from './browser/passkeys/browser-passkey-request-watch'
import { installBrowserPrintGuard } from './browser/printing/browser-print-guard'
// A session preload: it runs in every frame of every browser page, popup and serve window.
const electron: {
contextBridge: ContextBridge
ipcRenderer: Pick<IpcRenderer, 'send' | 'on'>
} = require('electron')
const { contextBridge, ipcRenderer } = electron
// Pushed by main, since print() must decide synchronously. Unknown until main answers, which
// refuses: an agent-led page's script can print before the answer lands.
let agentLed: boolean | null = null
ipcRenderer.on(BROWSER_AGENT_LEAD_CHANNEL, (_event, led: unknown) => {
agentLed = led === true
})
ipcRenderer.send(BROWSER_AGENT_LEAD_QUERY_CHANNEL)
// Only Windows hands a passkey request to a system dialog (Windows Hello).
const passkeysOpenSystemDialog = process.platform === 'win32'
const cancel: unknown = contextBridge.executeInMainWorld({
func: installBrowserPasskeyRequestWatch,
args: [
(pending: boolean) => ipcRenderer.send(BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL, pending),
() => !(passkeysOpenSystemDialog && agentLed !== false)
]
})
ipcRenderer.on(BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL, () => {
if (typeof cancel === 'function') {
cancel()
}
})
contextBridge.executeInMainWorld({
func: installBrowserPrintGuard,
args: [
() => {
if (agentLed === false) {
return true
}
ipcRenderer.send(BROWSER_PRINT_REFUSED_CHANNEL)
return false
}
]
})
@@ -9,7 +9,9 @@ function waitForAbort(signal?: AbortSignal | null): Promise<Credential | null> {
}
class PendingCredentialsContainer {
static asked = 0
get(options?: CredentialRequestOptions): Promise<Credential | null> {
PendingCredentialsContainer.asked += 1
return waitForAbort(options?.signal)
}
create(options?: CredentialCreationOptions): Promise<Credential | null> {
@@ -19,7 +21,7 @@ class PendingCredentialsContainer {
const original = Object.getOwnPropertyDescriptor(globalThis, 'CredentialsContainer')
function install(): {
function install(mayAskSystem: () => boolean = () => true): {
credentials: PendingCredentialsContainer
reports: boolean[]
cancel: () => void
@@ -29,7 +31,8 @@ function install(): {
value: PendingCredentialsContainer
})
const reports: boolean[] = []
const cancel = installBrowserPasskeyRequestWatch((pending) => reports.push(pending))
PendingCredentialsContainer.asked = 0
const cancel = installBrowserPasskeyRequestWatch((pending) => reports.push(pending), mayAskSystem)
return { credentials: new PendingCredentialsContainer(), reports, cancel }
}
@@ -62,4 +65,21 @@ describe('installBrowserPasskeyRequestWatch', () => {
await expect(request).rejects.toMatchObject({ name: 'AbortError' })
expect(reports).toEqual([true, false])
})
it("holds a request main keeps from the system dialog until it is cancelled or the user's own request replaces it", async () => {
let mayAskSystem = false
const { credentials, reports, cancel } = install(() => mayAskSystem)
const cancelled = credentials.get({ publicKey })
expect(PendingCredentialsContainer.asked).toBe(0)
expect(reports).toEqual([true])
cancel()
await expect(cancelled).rejects.toMatchObject({ name: 'NotAllowedError' })
const replaced = credentials.get({ publicKey })
mayAskSystem = true
void credentials.get({ publicKey }).catch(() => {})
await expect(replaced).rejects.toMatchObject({ name: 'NotAllowedError' })
expect(PendingCredentialsContainer.asked).toBe(1)
cancel()
})
})
@@ -1,13 +1,22 @@
/**
* Runs serialized in the page's main world. Electron has no passkey UI and tells main nothing, so
* the page's calls report when the document starts and stops waiting on one. Returns the canceller.
* Runs serialized in the page's main world. Electron tells main nothing about passkey requests, so
* the page's calls report when the document starts and stops waiting on one. A request main won't
* hand to the OS (Windows Hello would take the foreground) waits unsent until cancelled. Returns the canceller.
*/
export function installBrowserPasskeyRequestWatch(report: (pending: boolean) => void): () => void {
export function installBrowserPasskeyRequestWatch(
report: (pending: boolean) => void,
mayAskSystem: () => boolean
): () => void {
// Insecure documents have no credentials API.
if (typeof CredentialsContainer === 'undefined') {
return () => {}
}
const pending = new Set<AbortController>()
// Requests main kept from the OS; the user's own later request replaces them.
const held = new Set<AbortController>()
// The page's own "user cancelled" path, so it offers another way to sign in.
const cancelled = (): DOMException =>
new DOMException('The passkey request was cancelled.', 'NotAllowedError')
type Options = { publicKey?: unknown; mediation?: string; signal?: AbortSignal }
type Request<O> = (options?: O) => Promise<Credential | null>
const watch = <O extends Options>(original: Request<O>): Request<O> =>
@@ -28,7 +37,21 @@ export function installBrowserPasskeyRequestWatch(report: (pending: boolean) =>
// oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy `get` trap: raw string|symbol pass-through; the receiver stays the page's object on purpose.
key === 'signal' ? signal : Reflect.get(target, key)
})
request = original.call(this, withSignal)
if (mayAskSystem()) {
for (const stale of held) {
stale.abort(cancelled())
}
request = original.call(this, withSignal)
} else {
held.add(controller)
request = new Promise((_resolve, reject) => {
if (signal.aborted) {
reject(signal.reason)
return
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
})
}
} catch (error) {
return Promise.reject(error)
}
@@ -37,6 +60,7 @@ export function installBrowserPasskeyRequestWatch(report: (pending: boolean) =>
report(true)
}
const settle = (): void => {
held.delete(controller)
if (pending.delete(controller) && pending.size === 0) {
report(false)
}
@@ -49,8 +73,7 @@ export function installBrowserPasskeyRequestWatch(report: (pending: boolean) =>
credentials.create = watch(credentials.create)
return () => {
for (const controller of pending) {
// The page's own "user cancelled" path, so it offers another way to sign in.
controller.abort(new DOMException('The passkey request was cancelled.', 'NotAllowedError'))
controller.abort(cancelled())
}
}
}
@@ -0,0 +1,14 @@
/**
* Runs serialized in the page's main world. Electron's `print()` opens the system print dialog,
* which takes the foreground, so main may refuse it; a refused call returns like a throttled one.
*/
export function installBrowserPrintGuard(mayOpen: () => boolean): void {
const print = window.print
try {
window.print = () => {
if (mayOpen()) {
print.call(window)
}
}
} catch {}
}
-1
View File
@@ -2,7 +2,6 @@
export const BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL = 'browser:passkeyRequestPending'
/** Main → guest frame: cancel its pending passkey requests. */
export const BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL = 'browser:passkeyRequestCancel'
export const BROWSER_PASSKEY_REQUEST_PRELOAD_FILE = 'browser-passkey-request-preload.js'
/** What an agent should do about a page's pending passkey request. */
export function formatBrowserPasskeyRequest(origin: string, dismissCommand: string): string {
+7
View File
@@ -0,0 +1,7 @@
/** Main → guest frame: whether an agent drove the page since the desktop user last gave it input. */
export const BROWSER_AGENT_LEAD_CHANNEL = 'browser:agentLead'
/** Guest frame → main: a new document asks for the current lead; main answers on the lead channel. */
export const BROWSER_AGENT_LEAD_QUERY_CHANNEL = 'browser:agentLeadQuery'
/** Guest frame → main: the page's print() was refused because the agent leads it. */
export const BROWSER_PRINT_REFUSED_CHANNEL = 'browser:printRefused'
export const BROWSER_SYSTEM_DIALOGS_PRELOAD_FILE = 'browser-system-dialogs-preload.js'
@@ -48,6 +48,8 @@ export type BrowserActionEffects = {
consoleErrors?: string[]
/** Still pending when the page settled. */
passkeyRequest?: BrowserPasskeyRequest
/** The page asked for the system print dialog, which Orca refused so it would not take the user's screen. */
blockedPrint?: { origin: string }
/** Snapshot lines changed since the last reading; `full` is the whole new tree. Absent when unread. */
page?: 'unchanged' | { lines: string[]; removedLines: number; full: boolean; truncated: boolean }
/** False when the page was still changing at the settle cap. */